diff --git a/.changeset/35047-formula-percent-return.md b/.changeset/35047-formula-percent-return.md new file mode 100644 index 00000000000..748813c3983 --- /dev/null +++ b/.changeset/35047-formula-percent-return.md @@ -0,0 +1,21 @@ +--- +'@objectstack/spec': minor +'@objectstack/objectql': patch +'@object-ui/fields': patch +'@object-ui/app-shell': patch +--- + +feat(spec): a formula field can return `percent` + +Clause-②: yes (widening) +Metadata-protocol: added + +A ratio formula (budget used, gross margin) can now declare `returnType: 'percent'` and read and display as a `percent` field does, instead of a bare decimal beside the stored percentages. + +- **The value.** A `percent` formula result is read exactly 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 (`percentScaleOf`). +- **Its places.** `scale` counts the decimal places of the displayed percentage, as on a `percent` field (absent: 0). The engine rounds a fraction result to `scale + 2` places and a whole percentage to `scale`, so `scale: 1` keeps 0.417 (41.7%) instead of rounding it to 0.4. +- **An existing `percent` field computed from its `expression` rounds the same way.** The engine shares one rounding step for computed values, so a stored `percent` field that computes from an `expression` now keeps `scale + 2` places for a fraction (and `scale` for a whole percentage). Before, its computed fraction was rounded to `scale` itself: at `scale: 1`, 0.417 was stored as 0.4 and read 40.0%; it is now stored 0.417 and reads 41.7%. The change applies to the next computed write; rows written earlier are not rewritten. +- **Its face.** `percentDisplay` applies to a `percent` formula too (bar or plain). The formula renderer formats the result with the percent formatter, and the field and object forms offer `percent` as a return type. Editing the expression in the Studio field inspector keeps a declared `percent` (or `currency`) unless the new expression proves text, a boolean or a date. +- **Declared, never inferred.** No CEL type proves a quotient is a percentage, so authoring keeps a declared `percent` where it would otherwise stamp `number`. Readers that switch on `returnType` (display-name eligibility, filter operator and comparand typing) treat `percent` as a number. + +The enum only gains a member: every formula that parsed before parses the same, and nothing stored needs migrating. diff --git a/content/docs/data-modeling/field-types.mdx b/content/docs/data-modeling/field-types.mdx index 6acdc1c2ee6..c4780a103b6 100644 --- a/content/docs/data-modeling/field-types.mdx +++ b/content/docs/data-modeling/field-types.mdx @@ -687,7 +687,7 @@ Calculated field using a CEL expression (see [Expressions](/docs/data-modeling/f | Property | Type | Default | Description | |:---|:---|:---|:---| | `expression` | `string \| Expression` | **required** | CEL calculation expression | -| `returnType` | `'number' \| 'text' \| 'boolean' \| 'date' \| 'currency'` | — | Declared value type of the computed result. `currency`: an amount of money, in the currency the formula's own `currencyConfig` declares (none: dynamic; over record-mode amounts, `record` with their `currencyField`) | +| `returnType` | `'number' \| 'text' \| 'boolean' \| 'date' \| 'currency' \| 'percent'` | — | Declared value type of the computed result. `currency`: an amount of money, in the currency the formula's own `currencyConfig` declares (none: dynamic; over record-mode amounts, `record` with their `currencyField`). `percent`: a ratio, read 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, never inferred | ```typescript { name: 'total', label: 'Total', type: 'formula', expression: 'record.quantity * record.unit_price', returnType: 'number' } @@ -697,7 +697,8 @@ Calculated field using a CEL expression (see [Expressions](/docs/data-modeling/f evaluates the expression. The form and the grid cell draw it by `returnType`: `number` is formatted as a number field formats it (to the field's `scale`), `boolean` as Yes / No in the UI language (a non-boolean reads empty), `date` as the date field's absolute face (not the -grid's relative one), and `text` in a monospace font. With no `returnType`, a number is drawn +grid's relative one), `percent` as a percent field draws it (its `scale`, `max` and +`percentDisplay`), and `text` in a monospace font. With no `returnType`, a number is drawn as a number and anything else as text; nothing is inferred from the expression. #### `expression` on a stored field diff --git a/content/docs/data-modeling/formulas.mdx b/content/docs/data-modeling/formulas.mdx index 174ee69a968..a6257acc868 100644 --- a/content/docs/data-modeling/formulas.mdx +++ b/content/docs/data-modeling/formulas.mdx @@ -132,7 +132,7 @@ evaluates (`objectql` computes a formula virtual field from its `expression` only). Do **not** pass `type: 'currency' | 'number' | …` to `Field.formula` — it is rejected by the typed `FieldInput` and, untyped, would override `type:'formula'` so the field silently never computes. To declare what the formula returns, set -**`returnType`** (`'number' | 'text' | 'boolean' | 'date' | 'currency'`). You declare it +**`returnType`** (`'number' | 'text' | 'boolean' | 'date' | 'currency' | 'percent'`). You declare it yourself — nothing back-fills it — but the agent-callable `validate_expression` tool reports the type it infers from the expression (`inferredType`) so an AI author can stamp the matching value. A `'currency'` result is an amount of money @@ -141,7 +141,13 @@ and carries its currency the way a currency field does: in the formula's own record-mode amounts it is `{ currencyMode: 'record', currencyField }`, naming the same code field). Copy it from the currency field the formula computes from — `inferFormulaReturn` in -`@objectstack/formula` answers both halves for a formula it can prove is money. Consumers read the declared `returnType` +`@objectstack/formula` answers both halves for a formula it can prove is money. A `'percent'` +result is a ratio, read exactly 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` counts the decimal places of the displayed percentage (absent: 0), and +`percentDisplay` picks the bar or the plain face. No CEL type proves a quotient +is a percentage, so `'percent'` is only ever declared, never inferred. Consumers read the declared `returnType` instead of re-parsing the expression (record-title eligibility, for one: a formula is title-eligible only when its `returnType` is `'text'`, which is what lets it be *derived* as the record title — an explicit `nameField` pointer is diff --git a/content/docs/references/data/field.mdx b/content/docs/references/data/field.mdx index a786416910c..f100d9f17b3 100644 --- a/content/docs/references/data/field.mdx +++ b/content/docs/references/data/field.mdx @@ -66,11 +66,11 @@ const result = CurrencyConfigSchema.parse(data); | **valueDomain** | `Enum<'iana_time_zone' \| 'iso_4217_currency' \| 'iso_3166_alpha2'>` | optional | Standard value domain the WRITTEN value must be a member of: `iana_time_zone` (an IANA/tzdb zone identifier such as `UTC`, `Asia/Kolkata`, `Europe/Kyiv` — membership is the `Intl.DateTimeFormat` probe, never the `Intl.supportedValuesOf` enumeration, which omits `UTC`), `iso_4217_currency` (an ISO 4217 alphabetic currency code, uppercase, e.g. `CHF`) or `iso_3166_alpha2` (an ISO 3166-1 alpha-2 country code, uppercase, e.g. `CH`). The same closed vocabulary and the same membership predicate as a settings specifier's `valueDomain`. Only authorable on `text` — the one type whose stored value is a single plain string naming the member. Checked on the WRITTEN value only (the `min`/`max`/`maxLength` transition-gate class): a stored value outside a domain declared later is never re-read and survives unrelated edits — only a write carrying a non-member is refused, with the field error code `value_domain`. Reach for it precisely where a pattern cannot help: `^[A-Z]{2}$` admits `ZZ`, and `Mars/Olympus` is a shape-valid zone that does not exist. | | **rows** | `integer` | optional | Height of the INLINE multiline editor, in text rows (positive integer — the HTML textarea `rows` attribute; fullscreen/dialog editor surfaces size themselves and ignore it). Only authorable on multiline editor types: textarea, markdown, html, richtext. Omit it for the widget default height. | | **precision** | `integer` | optional | Total digits (non-negative integer) — the `p` of a DECIMAL(p, s): the digits of the value, integer and fraction together, counted at the field's decimal places, so `precision: 5, scale: 2` holds up to 999.99 and refuses 1234.5 (1234.50 is 6 digits). Enforced on writes of `number`, `currency`, `percent`, `rating` and `slider` fields: a value that needs more digits is refused with field code `max_precision`, never rounded. Counted on the STORED value: at the declared `scale` when one applies, else at the value's own decimal places (leading zeros never count) — so on a `currency` field, where `scale` is refused, an amount's written decimals count toward the total; a fraction-stored `percent` is counted two places further right (`scale + 2`, or 2 with no `scale`), which makes the count that of the percentage-point value as displayed. Not decimal places (that is `scale`; a currency's are its CLDR fraction digits) and not a column size: every numeric column keeps the platform's fixed exact decimal whatever this declares. Not read on any other field type. | -| **scale** | `integer` | optional | 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. | +| **scale** | `integer` | optional | 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. | | **min** | `number` | optional | 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. | | **max** | `number` | optional | 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. | | **useGrouping** | `boolean` | optional | Digit-grouping presentation hint for `number` fields — maps to `Intl.NumberFormat`'s `useGrouping`. Absent = renderer decides (interim heuristic today, locale default eventually); `false` = author opts out of grouping (e.g. a year or other ordinal/identifier integer); `true` = author pins grouping on. | -| **percentDisplay** | `Enum<'bar' \| 'plain'>` | optional | 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. | +| **percentDisplay** | `Enum<'bar' \| 'plain'>` | optional | 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. | | **accept** | `string[]` | optional | Permitted upload types for media fields, as MIME types or extensions (e.g. ["image/*", ".pdf"]). Offered to the file picker AND enforced on write. | | **maxSize** | `integer` | optional | Maximum permitted file size in BYTES for media fields. Enforced on write against the stored file size, not just checked in the browser. | | **options** | `{ label: string; value: string; description?: string; color?: string; … }[]` | optional | Static options for the option types. A `select` / `radio` field needs a non-empty list here or a `picklist` — with neither (or `options: []`) it is refused at parse. | @@ -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'>` | optional | 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). | +| **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. | | **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 1d48b7a4988..42cd92f8f70 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -244,11 +244,11 @@ const result = ApiMethod.parse(data); | **valueDomain** | `Enum<'iana_time_zone' \| 'iso_4217_currency' \| 'iso_3166_alpha2'>` | optional | Standard value domain the WRITTEN value must be a member of: `iana_time_zone` (an IANA/tzdb zone identifier such as `UTC`, `Asia/Kolkata`, `Europe/Kyiv` — membership is the `Intl.DateTimeFormat` probe, never the `Intl.supportedValuesOf` enumeration, which omits `UTC`), `iso_4217_currency` (an ISO 4217 alphabetic currency code, uppercase, e.g. `CHF`) or `iso_3166_alpha2` (an ISO 3166-1 alpha-2 country code, uppercase, e.g. `CH`). The same closed vocabulary and the same membership predicate as a settings specifier's `valueDomain`. Only authorable on `text` — the one type whose stored value is a single plain string naming the member. Checked on the WRITTEN value only (the `min`/`max`/`maxLength` transition-gate class): a stored value outside a domain declared later is never re-read and survives unrelated edits — only a write carrying a non-member is refused, with the field error code `value_domain`. Reach for it precisely where a pattern cannot help: `^[A-Z]{2}$` admits `ZZ`, and `Mars/Olympus` is a shape-valid zone that does not exist. | | **rows** | `integer` | optional | Height of the INLINE multiline editor, in text rows (positive integer — the HTML textarea `rows` attribute; fullscreen/dialog editor surfaces size themselves and ignore it). Only authorable on multiline editor types: textarea, markdown, html, richtext. Omit it for the widget default height. | | **precision** | `integer` | optional | Total digits (non-negative integer) — the `p` of a DECIMAL(p, s): the digits of the value, integer and fraction together, counted at the field's decimal places, so `precision: 5, scale: 2` holds up to 999.99 and refuses 1234.5 (1234.50 is 6 digits). Enforced on writes of `number`, `currency`, `percent`, `rating` and `slider` fields: a value that needs more digits is refused with field code `max_precision`, never rounded. Counted on the STORED value: at the declared `scale` when one applies, else at the value's own decimal places (leading zeros never count) — so on a `currency` field, where `scale` is refused, an amount's written decimals count toward the total; a fraction-stored `percent` is counted two places further right (`scale + 2`, or 2 with no `scale`), which makes the count that of the percentage-point value as displayed. Not decimal places (that is `scale`; a currency's are its CLDR fraction digits) and not a column size: every numeric column keeps the platform's fixed exact decimal whatever this declares. Not read on any other field type. | -| **scale** | `integer` | optional | 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. | +| **scale** | `integer` | optional | 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. | | **min** | `number` | optional | 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. | | **max** | `number` | optional | 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. | | **useGrouping** | `boolean` | optional | Digit-grouping presentation hint for `number` fields — maps to `Intl.NumberFormat`'s `useGrouping`. Absent = renderer decides (interim heuristic today, locale default eventually); `false` = author opts out of grouping (e.g. a year or other ordinal/identifier integer); `true` = author pins grouping on. | -| **percentDisplay** | `Enum<'bar' \| 'plain'>` | optional | 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. | +| **percentDisplay** | `Enum<'bar' \| 'plain'>` | optional | 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. | | **accept** | `string[]` | optional | Permitted upload types for media fields, as MIME types or extensions (e.g. ["image/*", ".pdf"]). Offered to the file picker AND enforced on write. | | **maxSize** | `integer` | optional | Maximum permitted file size in BYTES for media fields. Enforced on write against the stored file size, not just checked in the browser. | | **options** | `{ label: string; value: string; description?: string; color?: string; … }[]` | optional | Static options for the option types. A `select` / `radio` field needs a non-empty list here or a `picklist` — with neither (or `options: []`) it is refused at parse. | @@ -276,7 +276,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'>` | optional | 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). | +| **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. | | **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) | @@ -624,11 +624,11 @@ const result = ApiMethod.parse(data); | **valueDomain** | `Enum<'iana_time_zone' \| 'iso_4217_currency' \| 'iso_3166_alpha2'>` | optional | Standard value domain the WRITTEN value must be a member of: `iana_time_zone` (an IANA/tzdb zone identifier such as `UTC`, `Asia/Kolkata`, `Europe/Kyiv` — membership is the `Intl.DateTimeFormat` probe, never the `Intl.supportedValuesOf` enumeration, which omits `UTC`), `iso_4217_currency` (an ISO 4217 alphabetic currency code, uppercase, e.g. `CHF`) or `iso_3166_alpha2` (an ISO 3166-1 alpha-2 country code, uppercase, e.g. `CH`). The same closed vocabulary and the same membership predicate as a settings specifier's `valueDomain`. Only authorable on `text` — the one type whose stored value is a single plain string naming the member. Checked on the WRITTEN value only (the `min`/`max`/`maxLength` transition-gate class): a stored value outside a domain declared later is never re-read and survives unrelated edits — only a write carrying a non-member is refused, with the field error code `value_domain`. Reach for it precisely where a pattern cannot help: `^[A-Z]{2}$` admits `ZZ`, and `Mars/Olympus` is a shape-valid zone that does not exist. | | **rows** | `integer` | optional | Height of the INLINE multiline editor, in text rows (positive integer — the HTML textarea `rows` attribute; fullscreen/dialog editor surfaces size themselves and ignore it). Only authorable on multiline editor types: textarea, markdown, html, richtext. Omit it for the widget default height. | | **precision** | `integer` | optional | Total digits (non-negative integer) — the `p` of a DECIMAL(p, s): the digits of the value, integer and fraction together, counted at the field's decimal places, so `precision: 5, scale: 2` holds up to 999.99 and refuses 1234.5 (1234.50 is 6 digits). Enforced on writes of `number`, `currency`, `percent`, `rating` and `slider` fields: a value that needs more digits is refused with field code `max_precision`, never rounded. Counted on the STORED value: at the declared `scale` when one applies, else at the value's own decimal places (leading zeros never count) — so on a `currency` field, where `scale` is refused, an amount's written decimals count toward the total; a fraction-stored `percent` is counted two places further right (`scale + 2`, or 2 with no `scale`), which makes the count that of the percentage-point value as displayed. Not decimal places (that is `scale`; a currency's are its CLDR fraction digits) and not a column size: every numeric column keeps the platform's fixed exact decimal whatever this declares. Not read on any other field type. | -| **scale** | `integer` | optional | 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. | +| **scale** | `integer` | optional | 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. | | **min** | `number` | optional | 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. | | **max** | `number` | optional | 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. | | **useGrouping** | `boolean` | optional | Digit-grouping presentation hint for `number` fields — maps to `Intl.NumberFormat`'s `useGrouping`. Absent = renderer decides (interim heuristic today, locale default eventually); `false` = author opts out of grouping (e.g. a year or other ordinal/identifier integer); `true` = author pins grouping on. | -| **percentDisplay** | `Enum<'bar' \| 'plain'>` | optional | 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. | +| **percentDisplay** | `Enum<'bar' \| 'plain'>` | optional | 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. | | **accept** | `string[]` | optional | Permitted upload types for media fields, as MIME types or extensions (e.g. ["image/*", ".pdf"]). Offered to the file picker AND enforced on write. | | **maxSize** | `integer` | optional | Maximum permitted file size in BYTES for media fields. Enforced on write against the stored file size, not just checked in the browser. | | **options** | `{ label: string; value: string; description?: string; color?: string; … }[]` | optional | Static options for the option types. A `select` / `radio` field needs a non-empty list here or a `picklist` — with neither (or `options: []`) it is refused at parse. | @@ -656,7 +656,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'>` | optional | 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). | +| **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. | | **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 4576a62d5da..c05dee8df8b 100644 --- a/content/docs/references/system/migration.mdx +++ b/content/docs/references/system/migration.mdx @@ -69,11 +69,11 @@ Add a new field to an existing object | **valueDomain** | `Enum<'iana_time_zone' \| 'iso_4217_currency' \| 'iso_3166_alpha2'>` | optional | Standard value domain the WRITTEN value must be a member of: `iana_time_zone` (an IANA/tzdb zone identifier such as `UTC`, `Asia/Kolkata`, `Europe/Kyiv` — membership is the `Intl.DateTimeFormat` probe, never the `Intl.supportedValuesOf` enumeration, which omits `UTC`), `iso_4217_currency` (an ISO 4217 alphabetic currency code, uppercase, e.g. `CHF`) or `iso_3166_alpha2` (an ISO 3166-1 alpha-2 country code, uppercase, e.g. `CH`). The same closed vocabulary and the same membership predicate as a settings specifier's `valueDomain`. Only authorable on `text` — the one type whose stored value is a single plain string naming the member. Checked on the WRITTEN value only (the `min`/`max`/`maxLength` transition-gate class): a stored value outside a domain declared later is never re-read and survives unrelated edits — only a write carrying a non-member is refused, with the field error code `value_domain`. Reach for it precisely where a pattern cannot help: `^[A-Z]{2}$` admits `ZZ`, and `Mars/Olympus` is a shape-valid zone that does not exist. | | **rows** | `integer` | optional | Height of the INLINE multiline editor, in text rows (positive integer — the HTML textarea `rows` attribute; fullscreen/dialog editor surfaces size themselves and ignore it). Only authorable on multiline editor types: textarea, markdown, html, richtext. Omit it for the widget default height. | | **precision** | `integer` | optional | Total digits (non-negative integer) — the `p` of a DECIMAL(p, s): the digits of the value, integer and fraction together, counted at the field's decimal places, so `precision: 5, scale: 2` holds up to 999.99 and refuses 1234.5 (1234.50 is 6 digits). Enforced on writes of `number`, `currency`, `percent`, `rating` and `slider` fields: a value that needs more digits is refused with field code `max_precision`, never rounded. Counted on the STORED value: at the declared `scale` when one applies, else at the value's own decimal places (leading zeros never count) — so on a `currency` field, where `scale` is refused, an amount's written decimals count toward the total; a fraction-stored `percent` is counted two places further right (`scale + 2`, or 2 with no `scale`), which makes the count that of the percentage-point value as displayed. Not decimal places (that is `scale`; a currency's are its CLDR fraction digits) and not a column size: every numeric column keeps the platform's fixed exact decimal whatever this declares. Not read on any other field type. | -| **scale** | `integer` | optional | 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. | +| **scale** | `integer` | optional | 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. | | **min** | `number` | optional | 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. | | **max** | `number` | optional | 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. | | **useGrouping** | `boolean` | optional | Digit-grouping presentation hint for `number` fields — maps to `Intl.NumberFormat`'s `useGrouping`. Absent = renderer decides (interim heuristic today, locale default eventually); `false` = author opts out of grouping (e.g. a year or other ordinal/identifier integer); `true` = author pins grouping on. | -| **percentDisplay** | `Enum<'bar' \| 'plain'>` | optional | 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. | +| **percentDisplay** | `Enum<'bar' \| 'plain'>` | optional | 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. | | **accept** | `string[]` | optional | Permitted upload types for media fields, as MIME types or extensions (e.g. ["image/*", ".pdf"]). Offered to the file picker AND enforced on write. | | **maxSize** | `integer` | optional | Maximum permitted file size in BYTES for media fields. Enforced on write against the stored file size, not just checked in the browser. | | **options** | `{ label: string; value: string; description?: string; color?: string; … }[]` | optional | Static options for the option types. A `select` / `radio` field needs a non-empty list here or a `picklist` — with neither (or `options: []`) it is refused at parse. | @@ -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'>` | optional | 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). | +| **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. | | **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) | @@ -505,11 +505,11 @@ Add a new field to an existing object | **valueDomain** | `Enum<'iana_time_zone' \| 'iso_4217_currency' \| 'iso_3166_alpha2'>` | optional | Standard value domain the WRITTEN value must be a member of: `iana_time_zone` (an IANA/tzdb zone identifier such as `UTC`, `Asia/Kolkata`, `Europe/Kyiv` — membership is the `Intl.DateTimeFormat` probe, never the `Intl.supportedValuesOf` enumeration, which omits `UTC`), `iso_4217_currency` (an ISO 4217 alphabetic currency code, uppercase, e.g. `CHF`) or `iso_3166_alpha2` (an ISO 3166-1 alpha-2 country code, uppercase, e.g. `CH`). The same closed vocabulary and the same membership predicate as a settings specifier's `valueDomain`. Only authorable on `text` — the one type whose stored value is a single plain string naming the member. Checked on the WRITTEN value only (the `min`/`max`/`maxLength` transition-gate class): a stored value outside a domain declared later is never re-read and survives unrelated edits — only a write carrying a non-member is refused, with the field error code `value_domain`. Reach for it precisely where a pattern cannot help: `^[A-Z]{2}$` admits `ZZ`, and `Mars/Olympus` is a shape-valid zone that does not exist. | | **rows** | `integer` | optional | Height of the INLINE multiline editor, in text rows (positive integer — the HTML textarea `rows` attribute; fullscreen/dialog editor surfaces size themselves and ignore it). Only authorable on multiline editor types: textarea, markdown, html, richtext. Omit it for the widget default height. | | **precision** | `integer` | optional | Total digits (non-negative integer) — the `p` of a DECIMAL(p, s): the digits of the value, integer and fraction together, counted at the field's decimal places, so `precision: 5, scale: 2` holds up to 999.99 and refuses 1234.5 (1234.50 is 6 digits). Enforced on writes of `number`, `currency`, `percent`, `rating` and `slider` fields: a value that needs more digits is refused with field code `max_precision`, never rounded. Counted on the STORED value: at the declared `scale` when one applies, else at the value's own decimal places (leading zeros never count) — so on a `currency` field, where `scale` is refused, an amount's written decimals count toward the total; a fraction-stored `percent` is counted two places further right (`scale + 2`, or 2 with no `scale`), which makes the count that of the percentage-point value as displayed. Not decimal places (that is `scale`; a currency's are its CLDR fraction digits) and not a column size: every numeric column keeps the platform's fixed exact decimal whatever this declares. Not read on any other field type. | -| **scale** | `integer` | optional | 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. | +| **scale** | `integer` | optional | 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. | | **min** | `number` | optional | 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. | | **max** | `number` | optional | 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. | | **useGrouping** | `boolean` | optional | Digit-grouping presentation hint for `number` fields — maps to `Intl.NumberFormat`'s `useGrouping`. Absent = renderer decides (interim heuristic today, locale default eventually); `false` = author opts out of grouping (e.g. a year or other ordinal/identifier integer); `true` = author pins grouping on. | -| **percentDisplay** | `Enum<'bar' \| 'plain'>` | optional | 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. | +| **percentDisplay** | `Enum<'bar' \| 'plain'>` | optional | 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. | | **accept** | `string[]` | optional | Permitted upload types for media fields, as MIME types or extensions (e.g. ["image/*", ".pdf"]). Offered to the file picker AND enforced on write. | | **maxSize** | `integer` | optional | Maximum permitted file size in BYTES for media fields. Enforced on write against the stored file size, not just checked in the browser. | | **options** | `{ label: string; value: string; description?: string; color?: string; … }[]` | optional | Static options for the option types. A `select` / `radio` field needs a non-empty list here or a `picklist` — with neither (or `options: []`) it is refused at parse. | @@ -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'>` | optional | 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). | +| **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. | | **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/ui/component.mdx b/content/docs/references/ui/component.mdx index 8fdc2cf0f6c..0c239db1094 100644 --- a/content/docs/references/ui/component.mdx +++ b/content/docs/references/ui/component.mdx @@ -627,7 +627,7 @@ Sort field and direction pair | **minLength** | `integer` | optional | Minimum character count — the native control's `minlength` | | **maxLength** | `integer` | optional | Maximum character count — the control's ceiling (a textarea also draws its counter) | | **pattern** | `string` | optional | Regular expression the value must match, as a string — the native control's `pattern`, enforced by the browser at submit | -| **returnType** | `Enum<'number' \| 'text' \| 'boolean' \| 'date' \| 'currency'>` | optional | The value type a formula field displays (number / text / boolean / date / currency) | +| **returnType** | `Enum<'number' \| 'text' \| 'boolean' \| 'date' \| 'currency' \| 'percent'>` | optional | The value type a formula field displays (number / text / boolean / date / currency / percent) | | **summaryOperations** | `{ object: string; field?: string; function: Enum<'count' \| 'sum' \| 'min' \| 'max' \| 'avg'>; relationshipField?: string; … }` | optional | The roll-up a summary field displays — the object field's own `{ object, field, function, … }` | | **columns** | `{ name: string; label?: string; type?: Enum<'text' \| 'number' \| 'currency' \| 'date' \| 'datetime' \| 'time' \| 'select' \| 'lookup' \| 'file'>; width?: number; … }[]` | optional | The columns of a `grid` field — the strict, name-keyed inline grid column a relationship field's `inlineColumns` takes | | **minRows** | `number` | optional | A `grid` field's minimum row count: its Remove action is disabled at this many rows (no minimum when unset). Read only by the `grid` widget | diff --git a/packages/lint/src/validate-predicate-path-refs.test.ts b/packages/lint/src/validate-predicate-path-refs.test.ts index 07fdec57e8d..8d38546b7e9 100644 --- a/packages/lint/src/validate-predicate-path-refs.test.ts +++ b/packages/lint/src/validate-predicate-path-refs.test.ts @@ -824,7 +824,10 @@ describe('#7010 corpus — shipped METADATA_FORM_REGISTRY', () => { // object form) to `user` and respelled them `data.type in ['lookup','user']`, // an `in`-list outside this rule, so two `==` literal comparisons left the // census. - expect(comparisons, 'no shipped predicate carries an `==`/`!=` literal comparison').toBe(63); + // It is 65 today: #35047's `field :: percentDisplay` gate also opens for a + // percent formula, `data.type == 'formula' && data.returnType == 'percent'`, + // two more single-quoted literal comparisons. + expect(comparisons, 'no shipped predicate carries an `==`/`!=` literal comparison').toBe(65); const rhsFindings = validatePredicatePathRefs(corrupted) .filter((f) => f.rule === PREDICATE_RHS_PATH_SHAPED); diff --git a/packages/objectql/src/engine-formula-scale.test.ts b/packages/objectql/src/engine-formula-scale.test.ts index dce71766233..a1501fc8e46 100644 --- a/packages/objectql/src/engine-formula-scale.test.ts +++ b/packages/objectql/src/engine-formula-scale.test.ts @@ -112,6 +112,24 @@ const CAMPAIGN = { * nothing on this branch may start rounding it. */ plain_rate: { name: 'plain_rate', label: 'Plain Rate', type: 'number' as const, scale: 2 }, + /** #35047 — a `percent` formula: a fraction, `scale` counting the displayed percentage's places. */ + response_ratio: { + name: 'response_ratio', label: 'Response Ratio', type: 'formula' as const, returnType: 'percent' as const, + expression: { dialect: 'cel', source: 'coalesce(record.num_sent, 0) > 0 ? (coalesce(record.num_responses, 0) * 1.0) / record.num_sent : 0.0' }, + scale: 1, + }, + /** #35047 — a `percent` formula declaring whole-percent storage (`max` above 1). */ + response_points: { + name: 'response_points', label: 'Response Points', type: 'formula' as const, returnType: 'percent' as const, + expression: { dialect: 'cel', source: 'coalesce(record.num_sent, 0) > 0 ? (coalesce(record.num_responses, 0) * 100.0) / record.num_sent : 0.0' }, + scale: 1, max: 100, + }, + /** #35047 — a STORED `percent` field computed from its expression: the same storage rule. */ + stored_ratio: { + name: 'stored_ratio', label: 'Stored Ratio', type: 'percent' as const, + expression: { dialect: 'cel', source: 'coalesce(record.num_sent, 0) > 0 ? (coalesce(record.num_responses, 0) * 1.0) / record.num_sent : 0.0' }, + scale: 1, + }, }, }; @@ -313,6 +331,34 @@ describe('#10280 CONTROL 1 (defect) — a formula applies its declared `scale`', }); }); +describe('#35047 — a percentage is rounded at the percent storage scale', () => { + let rig: Rig; + beforeEach(async () => { rig = await makeEngine(); }); + + 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 () => { + const created = await rig.protocol.createData({ object: 'fs_campaign', data: SEED }); + expect((created.record as Rec).response_ratio).toBe(0.417); + const [row] = await rig.engine.find('fs_campaign', {} as never) as Rec[]; + expect(row.response_ratio).toBe(0.417); + }); + + it('a `percent` formula declaring `max` above 1 holds percentage points, rounded to `scale`', async () => { + const created = await rig.protocol.createData({ object: 'fs_campaign', data: SEED }); + expect((created.record as Rec).response_points).toBe(41.7); + }); + + it('a stored `percent` field computed from its expression is rounded the same way', async () => { + const created = await rig.protocol.createData({ object: 'fs_campaign', data: SEED }); + expect((created.record as Rec).stored_ratio).toBe(0.417); + }); + + it('CONTROL — a `number` formula at the same `scale` still rounds to `scale`', async () => { + const created = await rig.protocol.createData({ object: 'fs_campaign', data: SEED }); + expect((created.record as Rec).response_rate_whole).toBe(42); + expect((created.record as Rec).response_rate).toBe(41.67); + }); +}); + describe('#10280 CONTROL 1 — every plan-entry call site rounds, not just `find`', () => { let rig: Rig; beforeEach(async () => { rig = await makeEngine(); }); diff --git a/packages/objectql/src/engine-top-level.ts b/packages/objectql/src/engine-top-level.ts index b82f82e362a..c98d4cadfb4 100644 --- a/packages/objectql/src/engine-top-level.ts +++ b/packages/objectql/src/engine-top-level.ts @@ -11,7 +11,7 @@ // re-exports, by name, every declaration here it exported before, so every // importer of `./engine.js` reads what it read. -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'; +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'; import type { DroppedFieldsEvent, FilterCondition, FilterLoweringOptions, HookContext, QueryAST, QueryAliasSlot, RecycleBinClearedReference, ServiceObject } from '@objectstack/spec/data'; import type { EngineFilterJudgement, ISecurityService } from '@objectstack/spec/contracts'; import { assertFilterIsMaterializable, assertListComparandShapes, collectComposableReadableIds, invalidFilterError } from './filter-comparand-shape.js'; @@ -1424,10 +1424,25 @@ const MAX_FORMULA_SCALE = 100; * carries is a no-op request either way — so the rounding is skipped and the * value is returned whole. */ -function formulaRoundingScale(def: { scale?: unknown } | undefined): number | undefined { +function formulaRoundingScale( + def: { type?: unknown; scale?: unknown; returnType?: unknown; max?: unknown } | undefined, +): number | undefined { const scale = def?.scale; if (typeof scale !== 'number' || !Number.isInteger(scale) || scale < 0) return undefined; - return scale <= MAX_FORMULA_SCALE ? scale : undefined; + // [#35047] A percentage — a formula returning `percent`, or a stored + // `percent` field computed from its `expression` — declares its `scale` as + // the decimal places of the DISPLAYED percentage. So the value is rounded at + // the storage the percent field uses (`percentScaleOf`, the rule the write + // seam's `max_scale` allowance follows): a fraction carries `scale + 2` + // places (`scale: 1` keeps 0.417, which reads 41.7%), a whole percentage + // exactly `scale`. Rounding a fraction to `scale` itself turned 41.7% into + // 40.0%. + const percentage = def?.type === 'percent' || (def?.type === 'formula' && def.returnType === 'percent'); + const places = percentage + && percentScaleOf({ type: 'percent', max: typeof def?.max === 'number' ? def.max : undefined }) === 'fraction' + ? scale + 2 + : scale; + return places <= MAX_FORMULA_SCALE ? places : undefined; } /** diff --git a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts index 328473cddb0..23f3b01e573 100644 --- a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts @@ -811,7 +811,7 @@ export const enMetadataForms: NonNullable = { }, returnType: { label: "Return Type", - 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)." + 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%." }, summaryOperations: { label: "Summary Operations", diff --git a/packages/services/service-analytics/src/__tests__/formula-return-type-measure.test.ts b/packages/services/service-analytics/src/__tests__/formula-return-type-measure.test.ts index 86f2a4514b9..a722bd0c05c 100644 --- a/packages/services/service-analytics/src/__tests__/formula-return-type-measure.test.ts +++ b/packages/services/service-analytics/src/__tests__/formula-return-type-measure.test.ts @@ -98,7 +98,7 @@ describe('A) the formula branch is retired — no declared returnType buys a res // rule does with `returnType`, not about the key going away. #22727 added // `currency` — a formula is still VIRTUAL in SQL storage whatever it // returns, so the walk below holds it to the same `undefined` as the four. - expect([...SPEC_RETURN_TYPES].sort()).toEqual(['boolean', 'currency', 'date', 'number', 'text']); + expect([...SPEC_RETURN_TYPES].sort()).toEqual(['boolean', 'currency', 'date', 'number', 'percent', 'text']); }); it('⭐ the table REFUSES `min` / `max` over `formula` — the ground the ruling stood on', () => { diff --git a/packages/spec/src/data/display-name.ts b/packages/spec/src/data/display-name.ts index 404c173ba8a..b9bdd60624f 100644 --- a/packages/spec/src/data/display-name.ts +++ b/packages/spec/src/data/display-name.ts @@ -36,7 +36,7 @@ export interface TitleEligibleFieldDef { type?: string; /** * For `formula` fields: the declared result type. The framework field schema - * carries this as `returnType` (number/text/boolean/date/currency); `valueType` is also + * carries this as `returnType` (number/text/boolean/date/currency/percent); `valueType` is also * accepted for forward/cross-repo compatibility. A formula is title-eligible * ONLY when this is `text`. */ diff --git a/packages/spec/src/data/field.form.ts b/packages/spec/src/data/field.form.ts index 77a1c1f6533..d1a84a47967 100644 --- a/packages/spec/src/data/field.form.ts +++ b/packages/spec/src/data/field.form.ts @@ -97,8 +97,9 @@ export const fieldForm = defineForm({ // host, so declared = enforced = shown. A select over the schema's two // members with no default: an untouched row writes nothing and the // field keeps the renderer's default face, the bar. Gated to `percent`, - // the one type the key describes. - { 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: [ + // the one type the key describes, and to a formula returning `percent` + // (#35047), which the console draws through the same percent face. + { 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: [ { label: 'Bar', value: 'bar' }, { label: 'Plain', value: 'plain' }, ] }, @@ -371,16 +372,18 @@ export const fieldForm = defineForm({ collapsed: true, fields: [ { 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.' }, - // The five members are what FieldSchema declares — an explicit list, not + // The six members are what FieldSchema declares — an explicit list, not // the derived enum, so this row cannot pick up a member the formula // return type does not have. `currency` joined with #22727; its currency // is the `currencyConfig` row above, shown for a currency formula too. - { 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: [ + // `percent` joined with #35047; its face is the `percentDisplay` row. + { 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: [ { label: 'Text', value: 'text' }, { label: 'Number', value: 'number' }, { label: 'Boolean', value: 'boolean' }, { label: 'Date', value: 'date' }, { label: 'Currency', value: 'currency' }, + { label: 'Percent', value: 'percent' }, ] }, { field: 'summaryOperations', diff --git a/packages/spec/src/data/field.zod.ts b/packages/spec/src/data/field.zod.ts index 237f7da7d42..21d3a4ba55a 100644 --- a/packages/spec/src/data/field.zod.ts +++ b/packages/spec/src/data/field.zod.ts @@ -1679,7 +1679,7 @@ export const FieldSchema = lazySchema(() => { // (batch #218 item 2, letter 乙) words. The describe names the type set the // key still applies to, for the same reason as above. scale: z.number().int().min(0).max(MAX_RENDERABLE_SCALE, { message: SCALE_UPPER_BOUND_MESSAGE }).optional() - .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.'), + .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.'), 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.'), 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.'), /** @@ -1746,7 +1746,7 @@ export const FieldSchema = lazySchema(() => { * header chips. The liveness row is `live` and names the relay sites that * carry the key to that renderer. */ - 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.'), + 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.'), /** * Media Constraints (ADR-0104 D3 wave 2) @@ -2372,7 +2372,8 @@ export const FieldSchema = lazySchema(() => { * Salesforce/Airtable carry a formula's result type). Lets consumers — dataset * measures, display formatting, validation — read a declared type instead of * re-parsing the expression. Authoring stamps it from the inferred CEL type; - * absent when the type can't be proven (an ambiguous/`dyn` expression). + * absent when the type can't be proven (an ambiguous/`dyn` expression), + * except that a declared `percent` or `currency` stays (below). * * `currency` (#22727): the result is an amount of money. It carries its * currency exactly the way a `currency` field does — through the formula's @@ -2382,9 +2383,24 @@ export const FieldSchema = lazySchema(() => { * 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. + * + * `percent` (#35047): the result is a ratio, read exactly as a `percent` + * field reads its stored value — one convention, never a second one. The + * value is a FRACTION (`0.25` reads `25%`), unless the formula declares a + * `max` above 1, the percent field's own whole-percent statement + * (`percentScaleOf`), when it is percentage points. Its `scale` counts the + * decimal places of the displayed percentage, as on a `percent` field + * (absent ⇒ 0), so the engine rounds a fraction to `scale + 2` places and a + * whole percentage to `scale`. It is DECLARED, never inferred: no CEL type + * proves a quotient is a percentage, so authoring keeps a declared `percent` + * 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. */ - returnType: z.enum(['number', 'text', 'boolean', 'date', 'currency']).optional() - .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).'), + 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.'), summaryOperations: strictObject({ surface: 'this roll-up summary', history: FIELD_HISTORY, diff --git a/packages/spec/src/data/filter-number-comparand-declared-type.test.ts b/packages/spec/src/data/filter-number-comparand-declared-type.test.ts index 73dc3534932..d435324184a 100644 --- a/packages/spec/src/data/filter-number-comparand-declared-type.test.ts +++ b/packages/spec/src/data/filter-number-comparand-declared-type.test.ts @@ -382,13 +382,13 @@ describe('numberComparandRefusalMessage', () => { // ── The fixture ────────────────────────────────────────────────────────────── describe('the fixture', () => { - it('carries one field per FieldType member (f_), five typed formulas and one untyped', () => { + it('carries one field per FieldType member (f_), six typed formulas and one untyped', () => { const names = NUMBER_COMPARAND_DOOR_FIXTURE_FIELDS.map((f) => f.name); expect(new Set(names).size).toBe(names.length); const plain = NUMBER_COMPARAND_DOOR_FIXTURE_FIELDS.filter((f) => f.type !== 'formula').map((f) => f.type); expect(sorted(plain)).toEqual(sorted(FieldType.options.filter((t) => t !== 'formula'))); const formulas = NUMBER_COMPARAND_DOOR_FIXTURE_FIELDS.filter((f) => f.type === 'formula'); - expect(sorted(formulas.map((f) => f.returnType ?? '(none)'))).toEqual(['(none)', 'boolean', 'currency', 'date', 'number', 'text']); + expect(sorted(formulas.map((f) => f.returnType ?? '(none)'))).toEqual(['(none)', 'boolean', 'currency', 'date', 'number', 'percent', 'text']); }); it('every field is a legal FieldSchema input, and the object a legal ObjectSchema input', () => { @@ -461,11 +461,11 @@ describe('NUMBER_COMPARAND_DOOR_CASES', () => { } }); - it('the census covers every fixture field, refusing exactly the numeric class and formulas returning number or currency', () => { + it('the census covers every fixture field, refusing exactly the numeric class and formulas returning number, currency or percent', () => { const census = NUMBER_COMPARAND_DOOR_CASES.filter((c) => c.name.startsWith('[census]')); expect(sorted(census.map((c) => c.key))).toEqual(sorted(NUMBER_COMPARAND_DOOR_FIXTURE_FIELDS.map((f) => f.name))); expect(sorted(census.filter(isRefusal).map((c) => c.key))) - .toEqual(sorted([...[...NUMERIC_VALUE_TYPES].map((t) => `f_${t}`), 'f_formula_number', 'f_formula_currency'])); + .toEqual(sorted([...[...NUMERIC_VALUE_TYPES].map((t) => `f_${t}`), 'f_formula_number', 'f_formula_currency', 'f_formula_percent'])); expect(census.filter((c) => c.verdict === 'deferred').map((c) => c.key)).toEqual(['f_formula_untyped']); expect(census.filter(isNarrows)).toEqual([]); }); diff --git a/packages/spec/src/data/filter-text-operator-declared-type.test.ts b/packages/spec/src/data/filter-text-operator-declared-type.test.ts index 23a3251f219..85852c739c2 100644 --- a/packages/spec/src/data/filter-text-operator-declared-type.test.ts +++ b/packages/spec/src/data/filter-text-operator-declared-type.test.ts @@ -215,7 +215,7 @@ describe('textOperatorDoorVerdict — a text operator over a type that never sto // ── The fixture ────────────────────────────────────────────────────────────── describe('the fixture', () => { - it('carries one field per FieldType member (f_), five typed formulas and one untyped', () => { + it('carries one field per FieldType member (f_), six typed formulas and one untyped', () => { const names = TEXT_OPERATOR_DOOR_FIXTURE_FIELDS.map((f) => f.name); expect(new Set(names).size).toBe(names.length); for (const t of FieldType.options) { @@ -224,8 +224,8 @@ describe('the fixture', () => { } const formulas = TEXT_OPERATOR_DOOR_FIXTURE_FIELDS.filter((f) => f.type === 'formula'); expect(sorted(formulas.map((f) => f.returnType ?? '(none)'))) - .toEqual(['(none)', 'boolean', 'currency', 'date', 'number', 'text']); - expect(TEXT_OPERATOR_DOOR_FIXTURE_FIELDS).toHaveLength(FieldType.options.length - 1 + 6); + .toEqual(['(none)', 'boolean', 'currency', 'date', 'number', 'percent', 'text']); + expect(TEXT_OPERATOR_DOOR_FIXTURE_FIELDS).toHaveLength(FieldType.options.length - 1 + 7); }); it('every field is a legal FieldSchema input, and the object a legal ObjectSchema input', () => { @@ -276,8 +276,8 @@ describe('TEXT_OPERATOR_DOOR_CASES', () => { it('covers all three verdicts — a table with one answer would not need the discriminant', () => { const count = (v: string) => TEXT_OPERATOR_DOOR_CASES.filter((c) => c.verdict === v).length; - // `+ 4`: the formulas returning number, boolean, date and (#22727) currency. - expect(count('door-refusal')).toBe((TEXT_OPERATOR_DOOR_REFUSED_TYPES.size + 4) * TEXT_FILTER_OPERATORS.length); + // `+ 5`: the formulas returning number, boolean, date, (#22727) currency and (#35047) percent. + expect(count('door-refusal')).toBe((TEXT_OPERATOR_DOOR_REFUSED_TYPES.size + 5) * TEXT_FILTER_OPERATORS.length); expect(count('passes')).toBe((TEXT_OPERATOR_DOOR_PASSING_TYPES.size + 1) * TEXT_FILTER_OPERATORS.length); expect(count('deferred')).toBe((1 + STRUCTURED_JSON_TYPES.size) * TEXT_FILTER_OPERATORS.length); }); diff --git a/packages/spec/src/data/filter-text-operator-declared-type.ts b/packages/spec/src/data/filter-text-operator-declared-type.ts index a6d32576eaa..e5ef665fc20 100644 --- a/packages/spec/src/data/filter-text-operator-declared-type.ts +++ b/packages/spec/src/data/filter-text-operator-declared-type.ts @@ -245,6 +245,7 @@ export const TEXT_OPERATOR_DOOR_PASSING_TYPES: ReadonlySet = new Set([ * `currency` (#22727) is judged as the `currency` field it reads like: a member * of the numeric class, so this door refuses a text operator on it and the * number door judges its comparands, exactly as for a `currency` field. + * `percent` (#35047) is judged as the `percent` field it reads like, the same way. */ export const FORMULA_RETURN_TYPE_AS_FIELD_TYPE: ReadonlyMap = new Map([ ['number', 'number'], @@ -252,6 +253,7 @@ export const FORMULA_RETURN_TYPE_AS_FIELD_TYPE: ReadonlyMap = ne ['boolean', 'boolean'], ['date', 'date'], ['currency', 'currency'], + ['percent', 'percent'], ]); /** diff --git a/packages/spec/src/data/formula-currency-result.test.ts b/packages/spec/src/data/formula-currency-result.test.ts index 96be4afebe1..65434684199 100644 --- a/packages/spec/src/data/formula-currency-result.test.ts +++ b/packages/spec/src/data/formula-currency-result.test.ts @@ -109,6 +109,6 @@ describe('CONTROL — a numeric formula stays `number`', () => { it('the widening adds exactly `currency` — the four earlier members are still declared', () => { const members = (FieldSchema.shape.returnType.unwrap().options as readonly string[]).slice().sort(); - expect(members).toEqual(['boolean', 'currency', 'date', 'number', 'text']); + expect(members).toEqual(['boolean', 'currency', 'date', 'number', 'percent', 'text']); }); }); diff --git a/packages/spec/src/data/formula-percent-result.test.ts b/packages/spec/src/data/formula-percent-result.test.ts new file mode 100644 index 00000000000..14bb7a5fd48 --- /dev/null +++ b/packages/spec/src/data/formula-percent-result.test.ts @@ -0,0 +1,89 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * #35047 — a formula field declares a percent result. + * + * `FieldSchema.returnType` gains `percent`, mirroring how #22727 added + * `currency`: the result reads as a `percent` field reads its stored value, + * one convention and never a second one. So the assertions below compare a + * percent formula against a percent field rather than restating the rule. + */ + +import { describe, it, expect } from 'vitest'; + +import { FieldSchema } from './field.zod'; +import { ObjectSchema } from './object.zod'; +import { percentScaleOf } from './percent-scale'; +import { resolveFieldScale } from './field-scale'; +import { FORMULA_RETURN_TYPE_AS_FIELD_TYPE } from './filter-text-operator-declared-type'; +import { numberComparandFieldVerdict } from './filter-number-comparand-declared-type'; +import { isAggregateCompatibleWithFieldType } from './aggregate-field-type-compatibility'; + +function percentFormula(extra: Record = {}): Record { + return { + name: 'budget_used_pct', + label: 'Budget Used', + type: 'formula', + expression: 'record.spent / record.budget', + returnType: 'percent', + ...extra, + }; +} + +describe('a formula declares a percent result', () => { + it('`returnType: percent` parses, with a `scale`, a `max` and a `percentDisplay` as a percent field takes them', () => { + for (const extra of [{}, { scale: 1 }, { max: 100 }, { percentDisplay: 'plain' }]) { + const r = FieldSchema.safeParse(percentFormula(extra)); + expect(r.success, JSON.stringify(r.success ? extra : r.error.issues)).toBe(true); + if (r.success) expect(r.data.returnType).toBe('percent'); + } + }); + + it('a percent formula over two amounts parses inside a legal object', () => { + const r = ObjectSchema.safeParse({ + name: 'project', + label: 'Project', + fields: { + budget: { name: 'budget', label: 'Budget', type: 'number' }, + spent: { name: 'spent', label: 'Spent', type: 'number' }, + budget_used_pct: percentFormula({ scale: 1 }), + }, + }); + expect(r.success, r.success ? '' : JSON.stringify(r.error.issues)).toBe(true); + }); + + it('is judged as the `percent` field it reads like — the shared return-type map', () => { + expect(FORMULA_RETURN_TYPE_AS_FIELD_TYPE.get('percent')).toBe('percent'); + expect(numberComparandFieldVerdict({ type: 'formula', returnType: 'percent' })) + .toBe(numberComparandFieldVerdict({ type: 'percent' })); + }); + + it('reads with the percent field\'s convention: the storage and the absent width are the percent field\'s', () => { + // The faces hand a percent formula to the percent field's own resolvers + // as `percent`; these are the answers they get. + expect(percentScaleOf({ type: 'percent' })).toBe('fraction'); + expect(percentScaleOf({ type: 'percent', max: 100 })).toBe('whole'); + expect(resolveFieldScale({ type: 'percent' })).toBe(0); + expect(resolveFieldScale({ type: 'percent', scale: 1 })).toBe(1); + }); + + it('is refused by every value-reading aggregate, as every formula is, whatever it returns', () => { + // A formula is computed on read and has no column: the aggregate table + // keys on `formula`, not on the declared result. + for (const fn of ['sum', 'avg', 'min', 'max'] as const) { + expect(isAggregateCompatibleWithFieldType(fn, 'formula'), fn).toBe(false); + } + expect(isAggregateCompatibleWithFieldType('count', 'formula')).toBe(true); + }); +}); + +describe('CONTROL — the widening adds exactly `percent`', () => { + it('the five earlier members are still declared', () => { + const members = (FieldSchema.shape.returnType.unwrap().options as readonly string[]).slice().sort(); + expect(members).toEqual(['boolean', 'currency', 'date', 'number', 'percent', 'text']); + }); + + it('a value outside the six is still refused', () => { + expect(FieldSchema.safeParse(percentFormula({ returnType: 'ratio' })).success).toBe(false); + }); +}); diff --git a/packages/spec/src/data/object.form.ts b/packages/spec/src/data/object.form.ts index 09eccec1833..4a7f7066fcf 100644 --- a/packages/spec/src/data/object.form.ts +++ b/packages/spec/src/data/object.form.ts @@ -381,7 +381,7 @@ export const objectForm = defineForm({ // engine computes and stores it on write (`planStoredExpressions`), // so a formula-only row hid a live key on a stored field. { field: 'expression', type: 'code', language: 'expression', 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.' }, - // The five members are what `FieldSchema.returnType` declares, and + // The six members are what `FieldSchema.returnType` declares, and // the same explicit list the field designer's own control carries // in `field.form.ts` (#19677). This grid additionally offered // `datetime` and `currency`, so an author who added a formula field @@ -389,11 +389,12 @@ export const objectForm = defineForm({ // refusal arriving from the save door, naming a key they never // typed. Declared-vs-enforced, one seam before that door. // `currency` is declared since #22727 and offered again, in the + // same change as the enum; `percent` joined with #35047, in the // same change as the enum; `datetime` is still refused. { field: 'returnType', type: 'select', helpText: 'Result type for formulas', visibleWhen: "data.type == 'formula'", options: [ { label: 'Text', value: 'text' }, { label: 'Number', value: 'number' }, { label: 'Boolean', value: 'boolean' }, { label: 'Date', value: 'date' }, - { label: 'Currency', value: 'currency' }, + { label: 'Currency', value: 'currency' }, { label: 'Percent', value: 'percent' }, ] }, // A roll-up is ONE key — `summaryOperations` {object, field, function}. // The flat `summaryType` / `summaryField` pair named neither of them diff --git a/packages/spec/src/stack.zod.ts b/packages/spec/src/stack.zod.ts index eb0cbc7ac11..974bfbff8ac 100644 --- a/packages/spec/src/stack.zod.ts +++ b/packages/spec/src/stack.zod.ts @@ -4551,7 +4551,7 @@ const LOOKUP_AUTOFILL_RELATIONSHIP_TYPES: ReadonlySet = new Set(['lookup const LOOKUP_AUTOFILL_INHERENTLY_MULTI_TYPES: ReadonlySet = new Set(['multiselect', 'checkboxes', 'tags']); /** A `formula` source's value type, from its `returnType`. */ const LOOKUP_AUTOFILL_FORMULA_VALUE_TYPE: Readonly> = { - number: 'number', currency: 'currency', text: 'text', boolean: 'boolean', date: 'date', + number: 'number', currency: 'currency', text: 'text', boolean: 'boolean', date: 'date', percent: 'percent', }; /** diff --git a/packages/spec/src/ui/component.zod.ts b/packages/spec/src/ui/component.zod.ts index 1c1a95576cc..bad1ec4979c 100644 --- a/packages/spec/src/ui/component.zod.ts +++ b/packages/spec/src/ui/component.zod.ts @@ -6957,7 +6957,7 @@ function buildObjectFormRuntimeField() { minLength: FieldSchema.shape.minLength.describe('Minimum character count — the native control\'s `minlength`'), maxLength: FieldSchema.shape.maxLength.describe('Maximum character count — the control\'s ceiling (a textarea also draws its counter)'), pattern: z.string().optional().describe('Regular expression the value must match, as a string — the native control\'s `pattern`, enforced by the browser at submit'), - returnType: FieldSchema.shape.returnType.describe('The value type a formula field displays (number / text / boolean / date / currency)'), + returnType: FieldSchema.shape.returnType.describe('The value type a formula field displays (number / text / boolean / date / currency / percent)'), summaryOperations: FieldSchema.shape.summaryOperations.describe('The roll-up a summary field displays — the object field\'s own `{ object, field, function, … }`'), columns: FieldSchema.shape.inlineColumns.describe('The columns of a `grid` field — the strict, name-keyed inline grid column a relationship field\'s `inlineColumns` takes'), // [#21768] The `grid` widget's eight field-level keys, camelCase since 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 ef39500cb17..c4358bf578e 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 @@ -17,6 +17,10 @@ */ 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 '@objectstack/lint'; import * as React from 'react'; import { describe, it, expect, vi, afterEach } from 'vitest'; import { render, screen, fireEvent, cleanup, waitFor } from '@testing-library/react'; @@ -52,23 +56,27 @@ function stubEngine() { ? { ok: false, errors: [{ message: 'Parse error: unexpected end of input' }], warnings: [] } : { ok: true, errors: [], warnings: [] }; }, - introspectScope: () => ({ fields: ['est_hours'], roots: ['record'], functions: ['has'] }), + introspectScope: () => ({ fields: ['est_hours', 'budget'], roots: ['record'], functions: ['has'] }), // A broken source proves no type, as the engine answers it. inferExpressionType: (input: unknown) => { const src = typeof input === 'string' ? input : ''; if (BROKEN.test(src)) return 'unknown' as const; if (src.includes("'")) return 'text' as const; if (src.includes('+')) return 'unknown' as const; + // A field-over-field operator types `dyn`, as the engine answers it + // (formula-return.ts): the quotient's type is unproven. + if (/record\.\w+\s*\/\s*record\./.test(src)) return 'unknown' as const; + if (src.includes('>')) return 'boolean' as const; return 'number' as const; }, }), ); } -function Harness({ onDef }: { onDef: (def: Record) => void }) { +function Harness({ onDef, returnType = 'number' }: { onDef: (def: Record) => void; returnType?: string }) { const [fields, setFields] = React.useState>>({ est_hours: { type: 'number' }, - f_total: { type: 'formula', label: 'F Total', expression: 'record.est_hours * 2', returnType: 'number' }, + f_total: { type: 'formula', label: 'F Total', expression: 'record.est_hours * 2', returnType }, }); React.useEffect(() => { onDef(fields.f_total); @@ -89,10 +97,10 @@ function Harness({ onDef }: { onDef: (def: Record) => void }) { ); } -function renderFormula() { +function renderFormula(returnType?: string) { stubEngine(); const defs: Array> = []; - render( defs.push(def)} />); + render( defs.push(def)} returnType={returnType} />); const box = screen.getByText('Formula (CEL)').parentElement!.querySelector('[role="combobox"]') as HTMLTextAreaElement; const latest = () => defs.at(-1)!; return { box, latest }; @@ -124,3 +132,67 @@ describe('ObjectFieldInspector — a broken formula keeps the stored returnType await waitFor(() => expect(latest().returnType).toBeUndefined(), { timeout: 3000 }); }); }); + +describe('ObjectFieldInspector — a declared percent survives a number verdict (objectstack#35047)', () => { + it('an edit the engine proves `number` keeps `percent`: nothing infers a percentage', async () => { + const { box, latest } = renderFormula('percent'); + fireEvent.change(box, { target: { value: 'record.est_hours / 40' } }); + await waitFor(() => expect(latest().expression).toBe('record.est_hours / 40'), { timeout: 3000 }); + await settle(); + expect(latest().returnType).toBe('percent'); + }); + + it('a verdict that is not `number` still stamps over it', async () => { + const { box, latest } = renderFormula('percent'); + fireEvent.change(box, { target: { value: "'hours: ' + string(record.est_hours)" } }); + await waitFor(() => expect(latest().returnType).toBe('text'), { timeout: 3000 }); + }); + + it('CONTROL — a declared `number` takes the `number` verdict, as before', async () => { + const { box, latest } = renderFormula(); + fireEvent.change(box, { target: { value: 'record.est_hours / 40' } }); + await waitFor(() => expect(latest().expression).toBe('record.est_hours / 40'), { timeout: 3000 }); + await settle(); + expect(latest().returnType).toBe('number'); + }); +}); + +describe('ObjectFieldInspector — a declared percent or currency survives an unproven verdict (objectstack#35047)', () => { + const RATIO = 'record.est_hours / record.budget'; + + it("the spec's ratio shape: a field-over-field quotient proves no type and keeps `percent`", async () => { + const { box, latest } = renderFormula('percent'); + fireEvent.change(box, { target: { value: RATIO } }); + await waitFor(() => expect(latest().expression).toBe(RATIO), { timeout: 3000 }); + await settle(); + expect(latest().returnType).toBe('percent'); + }); + + it('the same quotient keeps a declared `currency`', async () => { + const { box, latest } = renderFormula('currency'); + fireEvent.change(box, { target: { value: RATIO } }); + await waitFor(() => expect(latest().expression).toBe(RATIO), { timeout: 3000 }); + await settle(); + expect(latest().returnType).toBe('currency'); + }); + + it('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 }); + await settle(); + expect(latest().returnType).toBe('currency'); + }); + + it('a verdict that proves another type still stamps over a declared `currency`', async () => { + const { box, latest } = renderFormula('currency'); + fireEvent.change(box, { target: { value: 'record.est_hours > 40' } }); + await waitFor(() => expect(latest().returnType).toBe('boolean'), { timeout: 3000 }); + }); + + it('CONTROL — the same quotient still clears a declared `number`, as before', async () => { + const { box, latest } = renderFormula(); + fireEvent.change(box, { target: { value: RATIO } }); + await waitFor(() => expect(latest().returnType).toBeUndefined(), { timeout: 3000 }); + }); +}); 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 6e60361a298..f1651274c71 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 @@ -1101,6 +1101,12 @@ export function ObjectFieldInspector({ // 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 }); }; diff --git a/ui/packages/fields/src/__tests__/formulaFaces.returnType-11748.test.tsx b/ui/packages/fields/src/__tests__/formulaFaces.returnType-11748.test.tsx index 13f974a844f..4166e303bc7 100644 --- a/ui/packages/fields/src/__tests__/formulaFaces.returnType-11748.test.tsx +++ b/ui/packages/fields/src/__tests__/formulaFaces.returnType-11748.test.tsx @@ -51,9 +51,11 @@ import { DateField, NumberCellRenderer, NumberField, + PercentCellRenderer, getCellRenderer, } from '../index'; import { FormulaField } from '../widgets/FormulaField'; +import { PercentField } from '../widgets/PercentField'; afterEach(() => cleanup()); @@ -350,3 +352,66 @@ describe('one stored value, one reading: the form face equals the cell (objectui }); }); }); + +// ── percent ──────────────────────────────────────────────────────────────── + +/** + * objectstack#35047 — a formula declares a `percent` result, and it reads as + * a `percent` field reads its stored value: a fraction unless the formula + * declares a `max` above 1, at the decimal places its `scale` gives (absent: + * the percent default, 0). Before the card the member did not exist; a value + * the cell did not know fell to the text face and a ratio read `0.25`. + */ +describe('percent: both faces draw the percent field\'s own faces (objectstack#35047)', () => { + const percentCell = (locale: Locale, value: number, extra: FormulaExtra = {}) => + textOf(locale, ); + const percentForm = (locale: Locale, value: number, extra: FormulaExtra = {}) => + textOf( + locale, + , + ); + + describe.each(LOCALES)('%s', (locale) => { + it.each(FACES)('%s — a fraction reads as a percentage, at the percent default width', (_face, draw) => { + const text = textOf(locale, draw(0.25, { returnType: 'percent' })); + expect(text).toBe('25%'); + expect(text).not.toBe('0.25'); + }); + + it.each(FACES)('%s — a declared scale counts the displayed percentage\'s places', (_face, draw) => { + expect(textOf(locale, draw(0.417, { returnType: 'percent', scale: 1 }))).toBe('41.7%'); + }); + + it.each(FACES)('%s — a declared `max` above 1 says whole percentage points', (_face, draw) => { + expect(textOf(locale, draw(41.7, { returnType: 'percent', scale: 1, max: 100 }))).toBe('41.7%'); + }); + + it("both faces equal the percent field's own faces for the same value", () => { + for (const extra of [{}, { scale: 2 }, { max: 100 }] as FormulaExtra[]) { + const value = 'max' in extra ? 12.5 : 0.125; + expect(textOf(locale, formFace(value, { returnType: 'percent', ...extra }))).toBe(percentForm(locale, value, extra)); + expect(textOf(locale, cellFace(value, { returnType: 'percent', ...extra }))).toBe(percentCell(locale, value, extra)); + } + }); + + it('CONTROL — the same fraction under `returnType: number` still reads as a number', () => { + expect(textOf(locale, cellFace(0.25, { returnType: 'number' }))).toBe('0.25'); + expect(textOf(locale, formFace(0.25, { returnType: 'number' }))).toBe('0.25'); + }); + }); + + it('the cell draws the percent bar unless the formula declares `percentDisplay: plain`', () => { + const { container } = renderSession('en-US', cellFace(0.25, { returnType: 'percent' })); + expect(container.querySelector('[role="progressbar"]')).not.toBeNull(); + cleanup(); + const plain = renderSession('en-US', cellFace(0.25, { returnType: 'percent', percentDisplay: 'plain' })); + expect(plain.container.querySelector('[role="progressbar"]')).toBeNull(); + expect(plain.container.textContent).toBe('25%'); + }); + + it.each(FACES)('%s — whitespace is empty, not a fabricated 0%%', (_face, draw) => { + const { container } = renderSession('en-US', draw(' ', { returnType: 'percent' })); + expect(affordance(container)).not.toBeNull(); + expect(container.textContent).not.toContain('0%'); + }); +}); diff --git a/ui/packages/fields/src/index.tsx b/ui/packages/fields/src/index.tsx index 6f2e6c238cb..9c6f19e3a97 100644 --- a/ui/packages/fields/src/index.tsx +++ b/ui/packages/fields/src/index.tsx @@ -2901,6 +2901,19 @@ export function FormulaCellRenderer({ value, field, dependentValues }: CellRende return ; } + // A declared PERCENT is a ratio (objectstack#35047): the spec reads it + // "as a `percent` field reads its stored value", so it is drawn by the + // percent cell itself, as the percent field it reads like. The cell asks + // `resolveFieldScale` by the field's `type`, so the type handed over is + // `percent`: a formula's own type has no absent-`scale` row, and an + // undeclared width would fall to `formatPercent`'s private default while + // the form face read `0`. Everything else is this formula's own — `scale`, + // the `max` that says whole-percent storage, `percentDisplay`. + // ⛔ No second percent formatter here. + if (valueType === 'percent') { + return ; + } + // A declared BOOLEAN reads the locale's Yes / No word (objectui#11748), the // word `BooleanField`'s read-only branch and the form face draw, and not // `BooleanCellRenderer`'s checkbox: a box has no text to agree with the diff --git a/ui/packages/fields/src/widgets/FormulaField.tsx b/ui/packages/fields/src/widgets/FormulaField.tsx index 2be3e73af4f..22c579da769 100644 --- a/ui/packages/fields/src/widgets/FormulaField.tsx +++ b/ui/packages/fields/src/widgets/FormulaField.tsx @@ -7,6 +7,7 @@ import { FieldWidgetComponentProps } from './types.js'; import { useBooleanValueLabel } from './booleanValueLabel.js'; import { formatNumberFieldValue } from './number-format.js'; import { CurrencyField } from './CurrencyField.js'; +import { PercentField } from './PercentField.js'; import { coerceToSafeValue } from '../coerceToSafeValue.js'; /** @@ -38,6 +39,10 @@ import { coerceToSafeValue } from '../coerceToSafeValue.js'; * read-only here, `CurrencyCellRenderer` in the cell), reading the * formula's own `currencyConfig` as they read a currency field's * (objectui#12111). + * - percent: a ratio, through the percent field's own faces (`PercentField` + * read-only here, `PercentCellRenderer` in the cell), reading the + * formula's own `scale` and `max` as they read a percent field's + * (objectstack#35047). * - boolean: the locale's word, as `BooleanField`'s read-only branch draws * it; only a JS boolean is a boolean, as there (objectui#8593). * - date: `formatDate`'s DEFAULT face, as `DateField`'s read-only branch @@ -73,7 +78,7 @@ export function FormulaField({ value, field, ...props }: FieldWidgetComponentPro } // The spec's `returnType` (`number` / `text` / `boolean` / `date` / - // `currency`), the spelling object metadata carries — authoring stamps it from the inferred + // `currency` / `percent`), the spelling object metadata carries — authoring stamps it from the inferred // CEL type. It is the ONLY spelling read: the snake_case `return_type` this // widget used to read is retired, so an object-bound formula field is // formatted by what its definition declares (objectui#11070). @@ -119,6 +124,23 @@ export function FormulaField({ value, field, ...props }: FieldWidgetComponentPro return ; } + if (valueType === 'percent') { + // A ratio (objectstack#35047), drawn by `PercentField`'s own read-only + // face, handed this formula's definition: that widget resolves the width + // and the storage as `percent` whatever the bag's `type` says — the + // formula's own `scale` (absent: the percent default) and `max` (above 1: + // whole percentage points; otherwise a fraction) — and formats through + // `formatPercentPoints`, the call the percent cell makes too. ⛔ No second + // percent formatter here. Read as the percent cell reads it: blank is + // empty, and a value that is not a number keeps its text. + if (typeof safe === 'string' && safe.trim() === '') { + return ; + } + const ratio = Number(safe); + if (isNaN(ratio)) return {String(safe)}; + return ; + } + if (valueType === 'boolean') { // The locale's word (objectui#11689), drawn under `BooleanField`'s // read-only rule (objectui#8593): only a JS boolean is a boolean. This