diff --git a/.changeset/33713-dynamic-rollup-engine-door.md b/.changeset/33713-dynamic-rollup-engine-door.md new file mode 100644 index 00000000000..e24f8f4d98f --- /dev/null +++ b/.changeset/33713-dynamic-rollup-engine-door.md @@ -0,0 +1,24 @@ +--- +'@objectstack/objectql': minor +'@objectstack/spec': minor +--- + +fix(objectql, spec)!: a single-object save on a running server refuses a `dynamic` roll-up over a child field that is not a stored home amount, in `defineStack`'s words + +Clause-②: no (narrowing) +Metadata-protocol: narrowed +Skills-docs: none — `skills/**` teaches no `dynamic` roll-up yet (its home roll-up paragraph is owed by follow-up #33714), so no page states which door refuses the wrong one. + + + +**BREAKING** for a hand-written object body saved on a running server. A `summary` with `function` `sum` / `min` / `max` / `avg` that declares `currencyMode: 'dynamic'` (or a `currencyConfig` naming no mode) is admitted only when it rolls up a stored home amount: a child field that the `homeAmount.field` of a record-mode amount on the child names. `defineStack` already refused every other one; the engine registry, which a single-object save meets, judged only `record` roll-ups, so a `dynamic` roll-up over a `fixed` EUR amount, a plain number or a formula was stored there and its total drawn with the home currency's symbol. + +What moves (each line FROM → TO): + +- a published save or publish of an object through the `/meta` doors (`PUT /meta/object/:name`, the runtime `/meta` dispatcher, `POST /meta/object/:name/publish`, a datasource table import) whose `dynamic` roll-up reads a child field that is not a stored home amount, with the child registered: FROM stored, 200 TO refused 422 `INVALID_METADATA`, nothing stored, with the sentence `defineStack` prints (`recordCurrencyDynamicRollupNotHomeError`, `@objectstack/spec/data`). The same holds in the other order: a child saved so that a registered parent's `dynamic` roll-up no longer reads a home amount is refused, naming the parent's roll-up. +- the same roll-up added by an `objectExtensions` entry or an `object_extension` item, or reading a child field an extension adds: judged against the parent and the child as the server serves them, at the end of an install, upgrade or reload run, on a published single save of the item, and in the batch writers (a package publish, a duplicate, an import): FROM installed or stored TO refused 422. +- a `homeAmount` makes a field a stored home amount only where it is valid as declared: on a `record`-mode `currency` amount, naming another field of the same object that is a `currency` field in `dynamic` mode, `readonly: true`, with no `expression`, and claimed by that one amount (`storedHomeAmountSourceOf`, `@objectstack/spec/data`). The object door already guaranteed this for an authored object; a field map merged with an extension's was taken at its word. At `defineStack` and at the engine registry alike, a `dynamic` roll-up over a field an extension's `homeAmount` names without that reading: FROM admitted TO refused. + +The fix: roll up the child's stored home amount (the refusal lists them), declare `currencyMode: 'fixed'` with the code when every amount the roll-up reads is in that one currency, or delete `currencyConfig` on the summary. An extension declaring a home amount gives it a `readonly` `dynamic` currency field of its own. + +Unchanged: the `dynamic` roll-up of a stored home amount (the shape `currencyMode: 'dynamic'` was admitted for) saves and is served; a summary with no `currencyConfig`, or `fixed`, is not judged by this arm; a `count` roll-up and every `record` case answer exactly as before; a roll-up over a child amount in each row's own currency is still refused by D6's roll-up door first, whatever it declares. Roll-ups stored before this release keep loading at every boot, which is not asked, and a run that leaves such a pair as it found it is not refused over it. `FieldSchema.currencyConfig`'s description now says that every door refuses the roll-ups it names. The latest stable `@objectstack/spec` (18.4.0) never admitted a `dynamic` summary at all; only the `next` snapshot of 2026-11-15 did, before this door judged it. diff --git a/content/docs/data-modeling/currency.mdx b/content/docs/data-modeling/currency.mdx index a8bb2446bdb..a548a4dea56 100644 --- a/content/docs/data-modeling/currency.mdx +++ b/content/docs/data-modeling/currency.mdx @@ -258,12 +258,14 @@ that column. A `count` column never carries `currencyField`. See the `currencyMode`) is admitted only for a `sum`, `avg`, `min` or `max` of a stored home amount, a child field that a `homeAmount.field` on the child object names (see [Totals in the home currency](#totals-in-the-home-currency)), and naming no currency - code. `defineStack` (`os validate` and the build) refuses one over any other - child field, naming the child's home amounts. A single-object save or publish through the - metadata API on a running server does not judge the child field yet: it parses the one - object, so it refuses only what that object shows (#33713). The object itself refuses - one that names no child field, one that names a currency code, and a `count` in - every mode, at every door. + code. One over any other child field is refused, naming the child's home amounts: + `defineStack` (`os validate` and the build) refuses it, and on a running server a save or + publish through the metadata API refuses it with **`INVALID_METADATA` / 422** and the + same message, whichever object is saved second, judging each object as the server serves + it, extensions included. A `homeAmount` makes a field a home amount only where it is + valid as declared, so an extension cannot make a plain number one by naming it. The + object itself refuses one that names no child field, one that names a currency code, and + a `count` in every mode, at every door. - **A dataset measure that declares `currency` over a record-mode amount** is refused at compile with **`DATASET_INVALID` / 400**, and so is a `currency` on a derived measure that sums record-mode amounts. One code cannot label amounts in several currencies: delete @@ -472,9 +474,9 @@ actual_cost: { The Console then draws the total in `localization.currency` on the record page and in the list cell (`$250.00` under a USD home currency, `CN¥1,800.00` under CNY), the same currency a dashboard metric over `amount_home` shows. Without the declaration the roll-up stays a -bare number. `defineStack` (`os validate` and the build) refuses `dynamic` on any other -roll-up, because the amounts it reads are not known to be in the home currency; a -single-object save on a running server does not check that yet (#33713, see +bare number. `dynamic` on any other roll-up is refused, because the amounts it reads are +not known to be in the home currency: by `defineStack` (`os validate` and the build), and +by a save or publish through the metadata API on a running server (see [Roll-ups and datasets](#roll-ups-and-datasets)). ## See also diff --git a/content/docs/references/data/field.mdx b/content/docs/references/data/field.mdx index be1873f8d53..2cdcb5671ff 100644 --- a/content/docs/references/data/field.mdx +++ b/content/docs/references/data/field.mdx @@ -102,7 +102,7 @@ const result = CurrencyConfigSchema.parse(data); | **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) | -| **currencyConfig** | `{ currencyMode?: Enum<'dynamic' \| 'fixed' \| 'record'>; defaultCurrency?: string; currencyField?: string; homeAmount?: object }` | optional | Which currency an amount is in: for a currency field, for a formula field whose returnType is currency, and for a summary that rolls up, through a master_detail, child amounts that follow this record's currency (`currencyMode: 'record'` naming this object's own code field). A summary that rolls up a stored home amount (a child field some `homeAmount.field` names) declares `currencyMode: 'dynamic'`, with no `defaultCurrency`, and shows in the organization's home currency. A summary may otherwise declare only `currencyMode: 'fixed'`, when every amount it reads is in that one currency; a `count` summary, any other `dynamic` summary and any other `record` roll-up are refused. Absent: dynamic mode, and no currency on a summary. | +| **currencyConfig** | `{ currencyMode?: Enum<'dynamic' \| 'fixed' \| 'record'>; defaultCurrency?: string; currencyField?: string; homeAmount?: object }` | optional | Which currency an amount is in: for a currency field, for a formula field whose returnType is currency, and for a summary that rolls up, through a master_detail, child amounts that follow this record's currency (`currencyMode: 'record'` naming this object's own code field). A summary that rolls up a stored home amount (a child field some `homeAmount.field` names) declares `currencyMode: 'dynamic'`, with no `defaultCurrency`, and shows in the organization's home currency. A summary may otherwise declare only `currencyMode: 'fixed'`, when every amount it reads is in that one currency; a `count` summary, any other `dynamic` summary and any other `record` roll-up are refused, by `defineStack` and by a single-object save or publish on a running server alike. Absent: dynamic mode, and no currency on a summary. | | **dimensions** | `integer` | optional | Vector dimensionality (e.g., 1536 for OpenAI embeddings) | | **trackHistory** | `boolean` | optional | Render this field's value changes as human-readable entries on the record activity timeline (ADR-0052 §5b). Opt-in per field. | | **group** | `string` | optional | Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system") | diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index 5f7952b4c68..986d7a6dc41 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -279,7 +279,7 @@ const result = ApiMethod.parse(data); | **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) | -| **currencyConfig** | `{ currencyMode?: Enum<'dynamic' \| 'fixed' \| 'record'>; defaultCurrency?: string; currencyField?: string; homeAmount?: object }` | optional | Which currency an amount is in: for a currency field, for a formula field whose returnType is currency, and for a summary that rolls up, through a master_detail, child amounts that follow this record's currency (`currencyMode: 'record'` naming this object's own code field). A summary that rolls up a stored home amount (a child field some `homeAmount.field` names) declares `currencyMode: 'dynamic'`, with no `defaultCurrency`, and shows in the organization's home currency. A summary may otherwise declare only `currencyMode: 'fixed'`, when every amount it reads is in that one currency; a `count` summary, any other `dynamic` summary and any other `record` roll-up are refused. Absent: dynamic mode, and no currency on a summary. | +| **currencyConfig** | `{ currencyMode?: Enum<'dynamic' \| 'fixed' \| 'record'>; defaultCurrency?: string; currencyField?: string; homeAmount?: object }` | optional | Which currency an amount is in: for a currency field, for a formula field whose returnType is currency, and for a summary that rolls up, through a master_detail, child amounts that follow this record's currency (`currencyMode: 'record'` naming this object's own code field). A summary that rolls up a stored home amount (a child field some `homeAmount.field` names) declares `currencyMode: 'dynamic'`, with no `defaultCurrency`, and shows in the organization's home currency. A summary may otherwise declare only `currencyMode: 'fixed'`, when every amount it reads is in that one currency; a `count` summary, any other `dynamic` summary and any other `record` roll-up are refused, by `defineStack` and by a single-object save or publish on a running server alike. Absent: dynamic mode, and no currency on a summary. | | **dimensions** | `integer` | optional | Vector dimensionality (e.g., 1536 for OpenAI embeddings) | | **trackHistory** | `boolean` | optional | Render this field's value changes as human-readable entries on the record activity timeline (ADR-0052 §5b). Opt-in per field. | | **group** | `string` | optional | Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system") | @@ -656,7 +656,7 @@ const result = ApiMethod.parse(data); | **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) | -| **currencyConfig** | `{ currencyMode?: Enum<'dynamic' \| 'fixed' \| 'record'>; defaultCurrency?: string; currencyField?: string; homeAmount?: object }` | optional | Which currency an amount is in: for a currency field, for a formula field whose returnType is currency, and for a summary that rolls up, through a master_detail, child amounts that follow this record's currency (`currencyMode: 'record'` naming this object's own code field). A summary that rolls up a stored home amount (a child field some `homeAmount.field` names) declares `currencyMode: 'dynamic'`, with no `defaultCurrency`, and shows in the organization's home currency. A summary may otherwise declare only `currencyMode: 'fixed'`, when every amount it reads is in that one currency; a `count` summary, any other `dynamic` summary and any other `record` roll-up are refused. Absent: dynamic mode, and no currency on a summary. | +| **currencyConfig** | `{ currencyMode?: Enum<'dynamic' \| 'fixed' \| 'record'>; defaultCurrency?: string; currencyField?: string; homeAmount?: object }` | optional | Which currency an amount is in: for a currency field, for a formula field whose returnType is currency, and for a summary that rolls up, through a master_detail, child amounts that follow this record's currency (`currencyMode: 'record'` naming this object's own code field). A summary that rolls up a stored home amount (a child field some `homeAmount.field` names) declares `currencyMode: 'dynamic'`, with no `defaultCurrency`, and shows in the organization's home currency. A summary may otherwise declare only `currencyMode: 'fixed'`, when every amount it reads is in that one currency; a `count` summary, any other `dynamic` summary and any other `record` roll-up are refused, by `defineStack` and by a single-object save or publish on a running server alike. Absent: dynamic mode, and no currency on a summary. | | **dimensions** | `integer` | optional | Vector dimensionality (e.g., 1536 for OpenAI embeddings) | | **trackHistory** | `boolean` | optional | Render this field's value changes as human-readable entries on the record activity timeline (ADR-0052 §5b). Opt-in per field. | | **group** | `string` | optional | Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system") | diff --git a/content/docs/references/system/migration.mdx b/content/docs/references/system/migration.mdx index cd39e63ca00..9fc86fb0f73 100644 --- a/content/docs/references/system/migration.mdx +++ b/content/docs/references/system/migration.mdx @@ -105,7 +105,7 @@ Add a new field to an existing object | **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) | -| **currencyConfig** | `{ currencyMode?: Enum<'dynamic' \| 'fixed' \| 'record'>; defaultCurrency?: string; currencyField?: string; homeAmount?: object }` | optional | Which currency an amount is in: for a currency field, for a formula field whose returnType is currency, and for a summary that rolls up, through a master_detail, child amounts that follow this record's currency (`currencyMode: 'record'` naming this object's own code field). A summary that rolls up a stored home amount (a child field some `homeAmount.field` names) declares `currencyMode: 'dynamic'`, with no `defaultCurrency`, and shows in the organization's home currency. A summary may otherwise declare only `currencyMode: 'fixed'`, when every amount it reads is in that one currency; a `count` summary, any other `dynamic` summary and any other `record` roll-up are refused. Absent: dynamic mode, and no currency on a summary. | +| **currencyConfig** | `{ currencyMode?: Enum<'dynamic' \| 'fixed' \| 'record'>; defaultCurrency?: string; currencyField?: string; homeAmount?: object }` | optional | Which currency an amount is in: for a currency field, for a formula field whose returnType is currency, and for a summary that rolls up, through a master_detail, child amounts that follow this record's currency (`currencyMode: 'record'` naming this object's own code field). A summary that rolls up a stored home amount (a child field some `homeAmount.field` names) declares `currencyMode: 'dynamic'`, with no `defaultCurrency`, and shows in the organization's home currency. A summary may otherwise declare only `currencyMode: 'fixed'`, when every amount it reads is in that one currency; a `count` summary, any other `dynamic` summary and any other `record` roll-up are refused, by `defineStack` and by a single-object save or publish on a running server alike. Absent: dynamic mode, and no currency on a summary. | | **dimensions** | `integer` | optional | Vector dimensionality (e.g., 1536 for OpenAI embeddings) | | **trackHistory** | `boolean` | optional | Render this field's value changes as human-readable entries on the record activity timeline (ADR-0052 §5b). Opt-in per field. | | **group** | `string` | optional | Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system") | @@ -541,7 +541,7 @@ Add a new field to an existing object | **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) | -| **currencyConfig** | `{ currencyMode?: Enum<'dynamic' \| 'fixed' \| 'record'>; defaultCurrency?: string; currencyField?: string; homeAmount?: object }` | optional | Which currency an amount is in: for a currency field, for a formula field whose returnType is currency, and for a summary that rolls up, through a master_detail, child amounts that follow this record's currency (`currencyMode: 'record'` naming this object's own code field). A summary that rolls up a stored home amount (a child field some `homeAmount.field` names) declares `currencyMode: 'dynamic'`, with no `defaultCurrency`, and shows in the organization's home currency. A summary may otherwise declare only `currencyMode: 'fixed'`, when every amount it reads is in that one currency; a `count` summary, any other `dynamic` summary and any other `record` roll-up are refused. Absent: dynamic mode, and no currency on a summary. | +| **currencyConfig** | `{ currencyMode?: Enum<'dynamic' \| 'fixed' \| 'record'>; defaultCurrency?: string; currencyField?: string; homeAmount?: object }` | optional | Which currency an amount is in: for a currency field, for a formula field whose returnType is currency, and for a summary that rolls up, through a master_detail, child amounts that follow this record's currency (`currencyMode: 'record'` naming this object's own code field). A summary that rolls up a stored home amount (a child field some `homeAmount.field` names) declares `currencyMode: 'dynamic'`, with no `defaultCurrency`, and shows in the organization's home currency. A summary may otherwise declare only `currencyMode: 'fixed'`, when every amount it reads is in that one currency; a `count` summary, any other `dynamic` summary and any other `record` roll-up are refused, by `defineStack` and by a single-object save or publish on a running server alike. Absent: dynamic mode, and no currency on a summary. | | **dimensions** | `integer` | optional | Vector dimensionality (e.g., 1536 for OpenAI embeddings) | | **trackHistory** | `boolean` | optional | Render this field's value changes as human-readable entries on the record activity timeline (ADR-0052 §5b). Opt-in per field. | | **group** | `string` | optional | Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system") | diff --git a/packages/objectql/src/protocol-batch-object-registration.test.ts b/packages/objectql/src/protocol-batch-object-registration.test.ts index 77b5e5938db..e7def62c570 100644 --- a/packages/objectql/src/protocol-batch-object-registration.test.ts +++ b/packages/objectql/src/protocol-batch-object-registration.test.ts @@ -600,3 +600,108 @@ describe('[#33593] an extension\'s record-mode amount on a single save and in th expect(registry.objectRegistrationRefusal(plainLine('ledger') as never, P, 'own', { againstRegistry: true })).toBeNull(); }); }); + +// ── [#33713, ADR-0144 D6 and D8 rule 5] A `dynamic` roll-up on a metadata-API save ── +// +// `defineStack` admits a `dynamic` summary only over a stored home amount +// (case (d)); a published save through the metadata API answers the same, +// with the same sentence, through the registry's follow door. +describe('[#33713] a metadata-API save of a `dynamic` roll-up over a child field that is not a stored home amount', () => { + const P = 'com.qa.homeroll'; + /** The #33659 probe's child: an amount converted at write into `amount_home`, beside amounts that are not home amounts. */ + const expense = { + name: 'homeroll_expense', label: 'Expense', sharingModel: 'private', + fields: { + project: { name: 'project', type: 'master_detail', reference: 'homeroll_project', label: 'Project' }, + currency_code: { name: 'currency_code', type: 'text', label: 'Currency', ...CODE }, + expense_date: { name: 'expense_date', type: 'date', label: 'Date' }, + rate_used: { name: 'rate_used', type: 'number', label: 'Rate', readonly: true }, + amount: { + name: 'amount', type: 'currency', label: 'Amount', + currencyConfig: { currencyMode: 'record', currencyField: 'currency_code', homeAmount: { field: 'amount_home', rateDate: 'expense_date', rateField: 'rate_used' } }, + }, + amount_home: { name: 'amount_home', type: 'currency', label: 'Amount (home)', readonly: true }, + eur_amount: { name: 'eur_amount', type: 'currency', label: 'EUR', currencyConfig: { currencyMode: 'fixed', defaultCurrency: 'EUR' } }, + plain: { name: 'plain', type: 'number', label: 'Plain' }, + doubled: { name: 'doubled', type: 'formula', label: 'Doubled', expression: 'record.plain * 2', returnType: 'number' }, + }, + }; + const total = (field: string, extra: Record = { currencyConfig: { currencyMode: 'dynamic' } }, fn = 'sum') => ({ + name: 'total', type: 'summary', label: 'Total', + summaryOperations: { object: 'homeroll_expense', field, function: fn, relationshipField: 'project' }, + ...extra, + }); + const project = (fields: Record = {}) => ({ + name: 'homeroll_project', label: 'Project', sharingModel: 'private', + fields: { title: { name: 'title', type: 'text', label: 'Title' }, ...fields }, + }); + const publish = (h: Harness, type: string, item: Record, name = String(item.name ?? item.extend)) => + h.protocol.saveMetaItem({ type, name, packageId: P, item, mode: 'publish', writeFace: 'meta-envelope' }); + const caught = async (run: () => Promise): Promise => { + try { + await run(); + } catch (e) { + return e; + } + return undefined; + }; + const DYNAMIC_HEAD = "Object 'homeroll_project' field 'total' currencyConfig: `currencyMode: 'dynamic'` on a summary is admitted only for a roll-up of a stored home amount"; + async function bootWithExpense(): Promise { + const h = await boot(); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + await h.protocol.installPackage({ manifest: { id: P, name: 'Home roll-up', type: 'app' } }); + await publish(h, 'object', expense); + return h; + } + + it('refuses one over a fixed EUR amount, a plain number and a formula 422 INVALID_METADATA, with case (d)\'s sentence, and stores nothing', async () => { + for (const [field, says] of [['eur_amount', 'is fixed to EUR'], ['plain', 'is not a stored home amount'], ['doubled', 'is not a stored home amount']] as const) { + const h = await bootWithExpense(); + const err = await caught(() => publish(h, 'object', project({ total: total(field) }))); + expect(err, field).toMatchObject({ status: 422, code: 'INVALID_METADATA', name: 'RecordCurrencyFollowRefusedError' }); + expect(String(err.message).startsWith(DYNAMIC_HEAD), field).toBe(true); + expect(err.message, field).toContain(`This summary rolls up sum(homeroll_expense.${field})`); + expect(err.message, field).toContain(says); + expect(activeRow(h, 'object', 'homeroll_project', P), field).toBeUndefined(); + expect(registered(h, 'homeroll_project'), field).toBeUndefined(); + await h.kernel.shutdown(); + } + }); + + it('CONTROL: the #33659 probe shape, a `dynamic` roll-up over the stored home amount, saves and is served', async () => { + const h = await bootWithExpense(); + await publish(h, 'object', project({ total: total('amount_home') })); + expect(registered(h, 'homeroll_project')?.fields?.total?.currencyConfig).toEqual({ currencyMode: 'dynamic' }); + expect(bodyOf(activeRow(h, 'object', 'homeroll_project', P))?.fields?.total?.summaryOperations?.field).toBe('amount_home'); + }); + + it('CONTROL: a `count` roll-up, and a roll-up declaring no currency, save as before', async () => { + const h = await bootWithExpense(); + await publish(h, 'object', project({ + total: total('plain', {}), + lines: { name: 'lines', type: 'summary', label: 'Lines', summaryOperations: { object: 'homeroll_expense', function: 'count', relationshipField: 'project' } }, + })); + expect(registered(h, 'homeroll_project')?.fields?.lines?.type).toBe('summary'); + }); + + it('a `record` roll-up over the fixed EUR amount answers as before: 422, with case (c)\'s sentence', async () => { + const h = await bootWithExpense(); + const err = await caught(() => publish(h, 'object', project({ + currency_code: { name: 'currency_code', type: 'text', label: 'Currency', ...CODE }, + total: total('eur_amount', { currencyConfig: { currencyMode: 'record', currencyField: 'currency_code' } }), + }))); + expect(err).toMatchObject({ status: 422, code: 'INVALID_METADATA', name: 'RecordCurrencyFollowRefusedError' }); + expect(err.message).toContain("`currencyMode: 'record'` on a summary is admitted only for a roll-up through a master_detail"); + expect(err.message).toContain("'homeroll_expense.eur_amount' is fixed to EUR"); + }); + + it('[N6] an object_extension adding the roll-up to the parent is refused 422 with the same sentence, and stores nothing', async () => { + const h = await bootWithExpense(); + await publish(h, 'object', project()); + const err = await caught(() => publish(h, 'object_extension', { extend: 'homeroll_project', fields: { total: total('plain') } })); + expect(err).toMatchObject({ status: 422, code: 'INVALID_METADATA' }); + expect(String(err.message).startsWith(DYNAMIC_HEAD)).toBe(true); + expect(registered(h, 'homeroll_project')?.fields?.total).toBeUndefined(); + expect(activeRow(h, 'object_extension', 'homeroll_project', P)).toBeUndefined(); + }); +}); diff --git a/packages/objectql/src/record-currency-aggregate-door.ts b/packages/objectql/src/record-currency-aggregate-door.ts index b6542b7f040..a193269eb91 100644 --- a/packages/objectql/src/record-currency-aggregate-door.ts +++ b/packages/objectql/src/record-currency-aggregate-door.ts @@ -81,7 +81,12 @@ */ import { StandardErrorCode } from '@objectstack/spec/api'; -import { recordCurrencyFollowedCodeError, recordCurrencyUnfollowedRollupError } from '@objectstack/spec/data'; +import { + recordCurrencyDynamicRollupNotHomeError, + recordCurrencyFollowedCodeError, + recordCurrencyUnfollowedRollupError, + storedHomeAmountSourceOf, +} from '@objectstack/spec/data'; import { recordCurrencyFieldOf, recordCurrencyPathOf, type RecordCurrencyPath } from './validation/record-currency-code.js'; /** @@ -400,9 +405,9 @@ export function recordCurrencySummaryRefusal( } /** - * [ADR-0144 D2 and D6, amended] A declaration that claims a currency it does - * not follow, refused at registration: the two cross-object halves - * `defineStack` judges where a stack holds both objects + * [ADR-0144 D2, D6 and D8 rule 5, amended] A declaration that claims a + * currency it does not follow, refused at registration: the cross-object + * halves `defineStack` judges where a stack holds both objects * (`collectRecordCurrencyPathErrors`), for the single-object save that holds * one, in the same words (`@objectstack/spec/data`'s * `record-currency-path.ts`). See {@link recordCurrencyFollowRefusal}. @@ -415,7 +420,7 @@ export class RecordCurrencyFollowRefusedError extends Error { readonly httpStatus = 422; /** The object declaring the refused field (the child, for an amount; the parent, for a roll-up). */ readonly objectName: string; - /** The refused field: a record-mode amount following its parent, or a `record` roll-up. */ + /** The refused field: a record-mode amount following its parent, or a `record` or `dynamic` roll-up. */ readonly fieldName: string; constructor(objectName: string, fieldName: string, message: string) { @@ -456,6 +461,16 @@ function declaresRecordCurrency(def: unknown): boolean { return config !== null && typeof config === 'object' && (config as { currencyMode?: unknown }).currencyMode === 'record'; } +/** + * A `summary` field declaring `currencyConfig.currencyMode: 'dynamic'`, or a + * `currencyConfig` naming no mode, which the spec parses as `dynamic`. + */ +function declaresDynamicCurrency(def: unknown): boolean { + const config = (def as { currencyConfig?: unknown } | null)?.currencyConfig; + return config !== null && typeof config === 'object' + && ((config as { currencyMode?: unknown }).currencyMode ?? 'dynamic') === 'dynamic'; +} + /** How {@link recordCurrencyFollowRefusal} reads the registry. */ export interface RecordCurrencyFollowRegistryView { /** A REGISTERED object by name, as served. */ @@ -490,7 +505,17 @@ export interface RecordCurrencyFollowRegistryView { * registration with the child registered, and at the child's with the * parent registered. A child amount in its own record currency, or * following another record, is D6's ({@link recordCurrencySummaryRefusal}), - * which refuses any such roll-up whatever it declares. + * which refuses any such roll-up whatever it declares; + * - (d) a `summary` declaring `currencyMode: 'dynamic'` (or a `currencyConfig` + * naming no mode) that rolls up `sum` / `avg` / `min` / `max` of a child + * field that is not a stored home amount: no valid `homeAmount` on the child + * as served names it (`storedHomeAmountSourceOf`, which reads a + * `homeAmount` only where it is valid as declared, so an extension cannot + * make a plain number a home amount by naming it). The faces draw such a + * total in the organization's home currency, which its rows are not known + * to be in (ADR-0144 D8 rule 5). Judged at both ends, as (c) is; a child + * field the child does not hold is no verdict. A child amount in its own + * record currency is D6's first, as for (c). * * `served` is the layer's object AS SERVED with the layer in place: its base * (`overlay ?? own`), every enabled extension, and the incoming layer filling @@ -555,7 +580,7 @@ export function recordCurrencyFollowRefusal( * well as the pointer: a run that re-points the pair's master_detail onto * another parent makes a new pair, so it is that run's to answer for. */ -function followPairKey(kind: 'follow' | 'rollup', object: string, field: string, target: string): string { +function followPairKey(kind: 'follow' | 'rollup' | 'dynamic', object: string, field: string, target: string): string { return `${kind}\u0000${object}\u0000${field}\u0000${target}`; } @@ -583,6 +608,20 @@ function* followRefusalsOf( ))]; } + // (d) at the parent: the object's `dynamic` roll-ups, over a child already registered (or itself). + for (const [summaryField, def] of Object.entries(own)) { + const rollup = rawRollupOf(def); + if (!rollup || !declaresDynamicCurrency(def)) continue; + const childFields = rollup.child === name ? own : fieldsOf(view.lookup(rollup.child)); + if (!childFields || !Object.prototype.hasOwnProperty.call(childFields, rollup.childField)) continue; + if (storedHomeAmountSourceOf(childFields, rollup.childField) !== undefined) continue; + yield [followPairKey('dynamic', name, summaryField, `${rollup.child}.${rollup.childField}`), new RecordCurrencyFollowRefusedError(name, summaryField, recordCurrencyDynamicRollupNotHomeError( + { object: name, field: summaryField, fn: rollup.fn, childObject: rollup.child, childField: rollup.childField }, + childFields, + childFields[rollup.childField], + ))]; + } + // (a) at the child: the object's following amounts, under a parent already registered (or itself). for (const [field, def] of Object.entries(own)) { const pointer = recordCurrencyFieldOf(def); @@ -596,7 +635,7 @@ function* followRefusalsOf( if (message !== undefined) yield [followPairKey('follow', name, field, `${path.master}.${String(pointer)}`), new RecordCurrencyFollowRefusedError(name, field, message)]; } - // The other ends, already registered: (a) at the parent, (c) at the child. + // The other ends, already registered: (a) at the parent, (c) and (d) at the child. for (const other of view.all()) { const otherName = typeof other.name === 'string' ? other.name : undefined; const otherFields = fieldsOf(other); @@ -623,9 +662,19 @@ function* followRefusalsOf( continue; } const rollup = rawRollupOf(def); - if (!rollup || rollup.child !== name || !declaresRecordCurrency(def)) continue; + if (!rollup || rollup.child !== name) continue; const childDef = Object.prototype.hasOwnProperty.call(own, rollup.childField) ? own[rollup.childField] : undefined; - if (childDef === undefined || recordCurrencyAggregandOf(childDef) !== undefined) continue; + if (childDef === undefined) continue; + if (declaresDynamicCurrency(def)) { + if (storedHomeAmountSourceOf(own, rollup.childField) !== undefined) continue; + yield [followPairKey('dynamic', otherName, field, `${name}.${rollup.childField}`), new RecordCurrencyFollowRefusedError(otherName, field, recordCurrencyDynamicRollupNotHomeError( + { object: otherName, field, fn: rollup.fn, childObject: name, childField: rollup.childField }, + own, + childDef, + ))]; + continue; + } + if (!declaresRecordCurrency(def) || recordCurrencyAggregandOf(childDef) !== undefined) continue; yield [followPairKey('rollup', otherName, field, `${name}.${rollup.childField}`), new RecordCurrencyFollowRefusedError(otherName, field, recordCurrencyUnfollowedRollupError( { object: otherName, field, fn: rollup.fn, childObject: name, childField: rollup.childField }, childDef, diff --git a/packages/objectql/src/record-currency-guards.test.ts b/packages/objectql/src/record-currency-guards.test.ts index f56e0b9cbf0..ac2bdefae44 100644 --- a/packages/objectql/src/record-currency-guards.test.ts +++ b/packages/objectql/src/record-currency-guards.test.ts @@ -28,7 +28,13 @@ import { describe, it, expect, beforeEach } from 'vitest'; import { defineStack } from '@objectstack/spec'; -import { RECYCLE_BIN_ENTRY_FIELDS, RECYCLE_BIN_OBJECT, type EngineAggregateOptions, type EngineUpdateOptions } from '@objectstack/spec/data'; +import { + RECYCLE_BIN_ENTRY_FIELDS, + RECYCLE_BIN_OBJECT, + recordCurrencyDynamicRollupNotHomeError, + type EngineAggregateOptions, + type EngineUpdateOptions, +} from '@objectstack/spec/data'; import { resolveThrownHttpError } from '@objectstack/types'; import { ObjectQL } from './engine.js'; import { aggregateSummaryValue } from './summary-aggregate.js'; @@ -1112,3 +1118,227 @@ describe('a single-object save is refused when the currency it follows is not th expect(engine.registry.getObject('pp_invoice')).toBeDefined(); }); }); + +// ── [#33713, ADR-0144 D6 and D8 rule 5] A `dynamic` roll-up at the single-object save ── +// +// `defineStack`'s case (d) admits a `dynamic` summary only over a stored home +// amount. The follow door asks the same of a single save, a batch writer's row +// and a registration run's end, against the objects as served, in the same +// words (`recordCurrencyDynamicRollupNotHomeError`, `@objectstack/spec/data`). +describe('a single-object save is refused a `dynamic` roll-up over a child field that is not a stored home amount (case (d))', () => { + async function bootSealed() { + const booted = await bootEngine(); + booted.engine.registry.sealBareNameHolders(); + return booted; + } + const save = (engine: ObjectQL, def: unknown, packageId?: string, ownership: 'own' | 'extend' = 'own') => { + const refusal = engine.registry.objectRegistrationRefusal(def as any, packageId, ownership, { againstRegistry: true }); + if (refusal) throw refusal; + return engine.registry.registerObject(def as any, packageId, undefined, ownership); + }; + const FOLLOW_REFUSED = 'RecordCurrencyFollowRefusedError'; + /** The child: an amount in each expense's own currency, converted at write into `amount_home` (the #33659 probe). */ + const EXPENSE = { + name: 'hr_expense', + fields: { + project: { type: 'master_detail', reference: 'hr_project' }, + currency_code: CODE_FIELD, + expense_date: { type: 'date' }, + rate_used: { type: 'number', readonly: true }, + amount: { + type: 'currency', + currencyConfig: { currencyMode: 'record', currencyField: 'currency_code', homeAmount: { field: 'amount_home', rateDate: 'expense_date', rateField: 'rate_used' } }, + }, + amount_home: { type: 'currency', readonly: true }, + eur_amount: { type: 'currency', currencyConfig: { currencyMode: 'fixed', defaultCurrency: 'EUR' } }, + plain: { type: 'number' }, + doubled: { type: 'formula', expression: 'plain * 2', returnType: 'number' }, + }, + }; + /** The parent, rolling `fn(hr_expense.field)` up in `currencyConfig` (dynamic unless given; `null` declares none). */ + const project = (field: string, currencyConfig: unknown = { currencyMode: 'dynamic' }, fn = 'sum') => ({ + name: 'hr_project', + fields: { + title: { type: 'text' }, + total: { + type: 'summary', + ...(currencyConfig === null ? {} : { currencyConfig }), + summaryOperations: { object: 'hr_expense', field, function: fn, relationshipField: 'project' }, + }, + }, + }); + const stackFinding = (objects: unknown[], objectExtensions?: unknown[]): string => { + try { + defineStack({ manifest: { id: 'com.example.dyndoor', name: 'dyn-door', version: '1.0.0', type: 'app' }, objects, objectExtensions } as Parameters[0]); + } catch (e) { + const issues = (e as { issues?: unknown[] }).issues ?? []; + expect(issues).toHaveLength(1); + return String(issues[0]); + } + throw new Error('defineStack accepted the pair'); + }; + + it('a `dynamic` roll-up over a fixed EUR amount, a plain number or a formula is refused 422, whichever end registers second, in defineStack\'s words', async () => { + for (const [field, says] of [ + ['eur_amount', 'is fixed to EUR'], + ['plain', 'is not a stored home amount'], + ['doubled', 'is not a stored home amount'], + ] as const) { + const parent = project(field); + for (const order of [[EXPENSE, parent], [parent, EXPENSE]]) { + const { engine } = await bootSealed(); + engine.registry.registerObject(order[0] as any); + const second = (order[1] as { name: string }).name; + const err = await refusalOf(() => save(engine, order[1])); + const at = `${field}, ${second} second`; + expect(envelopeOf(err), at).toEqual(INVALID_METADATA); + expect(err?.name, at).toBe(FOLLOW_REFUSED); + expect(err?.objectName, at).toBe('hr_project'); + expect(err?.fieldName, at).toBe('total'); + expect(err?.message, at).toBe(stackFinding([parent, EXPENSE])); + expect(err?.message, at).toContain(says); + expect(engine.registry.getObject(second), at).toBeUndefined(); + } + } + }); + + it('a `dynamic` roll-up over the record-mode amount itself was already refused by D6, whatever it declares (pinned, not re-judged)', async () => { + for (const order of [[EXPENSE, project('amount')], [project('amount'), EXPENSE]]) { + const { engine } = await bootSealed(); + engine.registry.registerObject(order[0] as any); + const err = await refusalOf(() => save(engine, order[1])); + expect(envelopeOf(err)).toEqual(INVALID_METADATA); + expect(err?.name).toBe('RecordCurrencySummaryRefusedError'); + } + }); + + it('a `currencyConfig` naming no mode is `dynamic`, and min / max / avg are judged as sum is', async () => { + for (const [config, fn] of [[{}, 'sum'], [{ currencyMode: 'dynamic' }, 'min'], [{ currencyMode: 'dynamic' }, 'max'], [{ currencyMode: 'dynamic' }, 'avg']] as const) { + const { engine } = await bootSealed(); + engine.registry.registerObject(EXPENSE as any); + const err = await refusalOf(() => save(engine, project('plain', config, fn))); + expect(err?.name, fn).toBe(FOLLOW_REFUSED); + expect(err?.message, fn).toBe(stackFinding([project('plain', config, fn), EXPENSE])); + } + }); + + it('CONTROL: the #33659 probe shape, a `dynamic` roll-up of the stored home amount, registers in either order', async () => { + for (const fn of ['sum', 'min', 'max', 'avg']) { + for (const order of [[EXPENSE, project('amount_home', undefined, fn)], [project('amount_home', undefined, fn), EXPENSE]]) { + const { engine } = await bootSealed(); + for (const o of order) save(engine, o); + expect(engine.registry.getObject('hr_project'), fn).toBeDefined(); + expect(engine.registry.getObject('hr_expense'), fn).toBeDefined(); + } + } + }); + + it('CONTROL: a summary with no currency, or `fixed`, over the same fields is not judged by this arm', async () => { + for (const config of [null, { currencyMode: 'fixed', defaultCurrency: 'EUR' }]) { + const { engine } = await bootSealed(); + engine.registry.registerObject(EXPENSE as any); + for (const field of ['eur_amount', 'plain', 'doubled']) { + expect(() => save(engine, project(field, config)), `${field} ${JSON.stringify(config)}`).not.toThrow(); + } + } + }); + + it('the child re-saved so that a registered `dynamic` roll-up no longer reads a home amount is refused, naming the roll-up; a run leaving a refused pair as it found it is not refused for it', async () => { + const { engine } = await bootSealed(); + save(engine, EXPENSE); + save(engine, project('amount_home')); + const dehomed = { ...EXPENSE, fields: { ...EXPENSE.fields, amount_home: { type: 'currency' } } }; + const err = await refusalOf(() => save(engine, dehomed)); + expect(envelopeOf(err)).toEqual(INVALID_METADATA); + expect(err?.name).toBe(FOLLOW_REFUSED); + expect(err?.objectName).toBe('hr_project'); + expect(err?.fieldName).toBe('total'); + // `defineStack` never meets this pair: its object door refuses a writable home field first. + expect(err?.message).toBe(recordCurrencyDynamicRollupNotHomeError( + { object: 'hr_project', field: 'total', fn: 'sum', childObject: 'hr_expense', childField: 'amount_home' }, + dehomed.fields, + dehomed.fields.amount_home, + )); + expect(err?.message).toContain("'hr_expense' stores no home amount"); + expect((engine.registry.getObject('hr_expense')?.fields as any)?.amount_home?.readonly).toBe(true); + + // A roll-up registered past the door (a stored row's hydration): a run that + // re-registers the child unchanged leaves the pair as it found it, so its + // end does not refuse it (#33593 ruling R7); one that de-homes it does. + const second = await bootSealed(); + second.engine.registry.registerObject(EXPENSE as any); + second.engine.registry.registerObject(project('plain') as any); + expect(() => second.engine.registry.restoringOnRefusal(() => second.engine.registry.registerObject({ ...EXPENSE, label: 'Expense' } as any))).not.toThrow(); + second.engine.registry.registerObject(project('amount_home') as any); + const run = await refusalOf(() => second.engine.registry.restoringOnRefusal(() => second.engine.registry.registerObject(dehomed as any))); + expect(run?.name).toBe(FOLLOW_REFUSED); + expect((second.engine.registry.getObject('hr_expense')?.fields as any)?.amount_home?.readonly).toBe(true); + }); + + it('[N6] an `object_extension` adding the roll-up to the parent is judged as the parent is served', async () => { + const { engine } = await bootSealed(); + save(engine, EXPENSE); + save(engine, { name: 'hr_project', fields: { title: { type: 'text' } } }, 'pkg_owner'); + const total = project('plain').fields.total; + const err = await refusalOf(() => save(engine, { name: 'hr_project', fields: { total } }, 'pkg_ext', 'extend')); + expect(envelopeOf(err)).toEqual(INVALID_METADATA); + expect(err?.name).toBe(FOLLOW_REFUSED); + expect(err?.message).toBe(stackFinding([project('plain'), EXPENSE])); + expect((engine.registry.getObject('hr_project')?.fields as any)?.total).toBeUndefined(); + // CONTROL: the extension adding the roll-up of the home amount is served. + save(engine, { name: 'hr_project', fields: { total: project('amount_home').fields.total } }, 'pkg_ext', 'extend'); + expect((engine.registry.getObject('hr_project')?.fields as any)?.total?.type).toBe('summary'); + }); + + it('[N6] a child field an `object_extension` adds is judged as the child is served, at either end', async () => { + const { fields: { plain: _plain, ...ownFields } } = EXPENSE; + // Parent second: the child as served holds the extension's field. + const first = await bootSealed(); + save(first.engine, { ...EXPENSE, fields: ownFields }, 'pkg_owner'); + save(first.engine, { name: 'hr_expense', fields: { plain: { type: 'number' } } }, 'pkg_ext', 'extend'); + const atParent = await refusalOf(() => save(first.engine, project('plain'))); + expect(atParent?.name).toBe(FOLLOW_REFUSED); + expect(atParent?.message).toBe(stackFinding([project('plain'), EXPENSE])); + // Extension second: the parent's roll-up names a field no layer adds yet (no verdict), then the extension adds it. + const second = await bootSealed(); + save(second.engine, { ...EXPENSE, fields: ownFields }, 'pkg_owner'); + save(second.engine, project('plain')); + const atExtension = await refusalOf(() => save(second.engine, { name: 'hr_expense', fields: { plain: { type: 'number' } } }, 'pkg_ext', 'extend')); + expect(atExtension?.name).toBe(FOLLOW_REFUSED); + expect(atExtension?.objectName).toBe('hr_project'); + expect((second.engine.registry.getObject('hr_expense')?.fields as any)?.plain).toBeUndefined(); + }); + + it('[N6] a post-seal `registerApp` whose `objectExtensions` add the roll-up is refused at the end of its run, and leaves nothing of the package', async () => { + const { engine } = await bootSealed(); + save(engine, EXPENSE, 'pkg_owner'); + save(engine, { name: 'hr_project', fields: { title: { type: 'text' } } }, 'pkg_owner'); + const err = await refusalOf(() => engine.registerApp({ + id: 'com.test.dyn_ext', name: 'dyn-ext', + objectExtensions: [{ extend: 'hr_project', fields: { total: project('eur_amount').fields.total } }], + } as any)); + expect(envelopeOf(err)).toEqual(INVALID_METADATA); + expect(err?.name).toBe(FOLLOW_REFUSED); + expect(err?.message).toBe(stackFinding([project('eur_amount'), EXPENSE])); + expect((engine.registry.getObject('hr_project')?.fields as any)?.total).toBeUndefined(); + expect(engine.registry.getPackage('com.test.dyn_ext')).toBeUndefined(); + }); + + it('[N7] a `homeAmount` an extension forges on the child does not make a plain number a home amount; a valid one does', async () => { + const forging = (target: string) => ({ + forged: { type: 'currency', currencyConfig: { currencyMode: 'record', currencyField: 'currency_code', homeAmount: { field: target, rateDate: 'expense_date', rateField: 'rate_used' } } }, + }); + const { engine } = await bootSealed(); + save(engine, EXPENSE, 'pkg_owner'); + save(engine, { name: 'hr_expense', fields: forging('plain') }, 'pkg_ext', 'extend'); + const err = await refusalOf(() => save(engine, project('plain'))); + expect(envelopeOf(err)).toEqual(INVALID_METADATA); + expect(err?.name).toBe(FOLLOW_REFUSED); + expect(err?.message).toBe(stackFinding([project('plain'), EXPENSE], [{ extend: 'hr_expense', fields: forging('plain') }])); + // CONTROL: the extension adds its own readonly home field and the amount that converts into it. + const valid = await bootSealed(); + save(valid.engine, EXPENSE, 'pkg_owner'); + save(valid.engine, { name: 'hr_expense', fields: { ext_home: { type: 'currency', readonly: true }, ...forging('ext_home') } }, 'pkg_ext', 'extend'); + expect(() => save(valid.engine, project('ext_home'))).not.toThrow(); + }); +}); diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index 97b8901acb1..232ca32bc7d 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -1063,6 +1063,7 @@ "readAutonumberCounter (function)", "readBooleanComparand (function)", "readNumericString (function)", + "recordCurrencyDynamicRollupNotHomeError (function)", "recordCurrencyFollowedCodeError (function)", "recordCurrencyRecordRollupError (function)", "recordCurrencyUnfollowedRollupError (function)", @@ -1099,6 +1100,7 @@ "resolveSearchFields (function)", "seedFile (function)", "sequenceWidth (function)", + "storedHomeAmountSourceOf (function)", "stringStoredComparandDoorVerdict (function)", "stringStoredComparandFieldVerdict (function)", "stripLegacyApiMethods (function)", diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index d15ca9d0c1c..62c0528ff73 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -1049,6 +1049,7 @@ "readAutonumberCounter": "src/data/autonumber-format.ts#readAutonumberCounter (function)", "readBooleanComparand": "src/data/filter-boolean-comparand-declared-type.ts#readBooleanComparand (function)", "readNumericString": "src/data/filter-number-comparand-declared-type.ts#readNumericString (function)", + "recordCurrencyDynamicRollupNotHomeError": "src/data/record-currency-path.ts#recordCurrencyDynamicRollupNotHomeError (function)", "recordCurrencyFollowedCodeError": "src/data/record-currency-path.ts#recordCurrencyFollowedCodeError (function)", "recordCurrencyRecordRollupError": "src/data/record-currency-path.ts#recordCurrencyRecordRollupError (function)", "recordCurrencyUnfollowedRollupError": "src/data/record-currency-path.ts#recordCurrencyUnfollowedRollupError (function)", @@ -1085,6 +1086,7 @@ "resolveSearchFields": "src/data/search-fields.ts#resolveSearchFields (function)", "seedFile": "src/data/seed-file.zod.ts#seedFile (function)", "sequenceWidth": "src/data/autonumber-format.ts#sequenceWidth (function)", + "storedHomeAmountSourceOf": "src/data/record-currency-path.ts#storedHomeAmountSourceOf (function)", "stringStoredComparandDoorVerdict": "src/data/filter-string-stored-comparand-declared-type.ts#stringStoredComparandDoorVerdict (function)", "stringStoredComparandFieldVerdict": "src/data/filter-string-stored-comparand-declared-type.ts#stringStoredComparandFieldVerdict (function)", "stripLegacyApiMethods": "src/data/object.zod.ts#stripLegacyApiMethods (function)", diff --git a/packages/spec/liveness/field.json b/packages/spec/liveness/field.json index ccffb163c1e..7729ec8a37b 100644 --- a/packages/spec/liveness/field.json +++ b/packages/spec/liveness/field.json @@ -436,7 +436,7 @@ "verifiedAt": "2026-09-27", "evidenceScope": "in-repo", "evidence": "ui/packages/i18n/src/currency.ts:60 reads field.currencyConfig.defaultCurrency ONLY when currencyConfig.currencyMode is 'fixed' — the second step of resolveFieldCurrency's precedence chain; a 'dynamic' config, or one naming no mode, skips it for the tenant default localization.currency; ui/packages/fields/src/widgets/CurrencyField.tsx:55 calls resolveFieldCurrency and applies the resolved code at :91 through formatAmount, which passes it to Intl.NumberFormat via formatDisplayNumber — measured objectui @25c7d584", - "note": "WIDENED 2026-11-15 (#33659, spec seat 4 claim 6890000941): a `summary` with `function` `sum` / `min` / `max` / `avg` that rolls up a stored home amount (a child field some `homeAmount.field` on the child object names) is admitted with `currencyMode: 'dynamic'` and no `defaultCurrency`, the roll-up of ADR-0144 D6's consolidation path in the home currency without metadata naming it (D8 rule 5). The reader that now consumes `dynamic` on a summary is ui/packages/fields/src/currency.ts#summaryDeclaresCurrency, read by both roll-up faces (ui/packages/fields/src/widgets/SummaryField.tsx#SummaryField and ui/packages/fields/src/index.tsx#FormulaCellRenderer), which draw the total through resolveFieldCurrency in the tenant default `localization.currency`, the code ObjectMetricWidget resolves for a tile over the same home field. Judged at the object door (`refuseUnadmittedSummaryCurrency`: a `dynamic` summary naming no child field, or carrying a `defaultCurrency`, stays refused, and a `count` refuses every mode as before) and in `defineStack` (case (d) of `collectRecordCurrencyPathErrors`: any other `dynamic` roll-up is refused). service-analytics is unchanged: `sourceFieldMeta` relays no code for `dynamic`, as for the home field itself. Verdict unchanged: LIVE. NARROWED 2026-11-09 (#31958, claim amend 1, record 6746006322): on a `summary` field the config is refused outside the ADR-0144 D6 admitted roll-up. A `count` roll-up refuses every mode, `fixed` included (a count is never an amount); `dynamic` is refused on every summary, since no reader consumes it there (the Console's roll-up faces read no `currencyConfig`; service-analytics relays only `fixed` and `record`); `record` is refused unless the roll-up runs through the `master_detail` its child amount follows (object door `refuseUnadmittedSummaryCurrency` in data/object.zod.ts, stack door case (c) of `collectRecordCurrencyPathErrors` in stack.zod.ts). `fixed` stays accepted on sum / min / max / avg because a reader consumes it: packages/services/service-analytics/src/plugin.ts sourceFieldMeta relays its `defaultCurrency` for any field type and packages/services/service-analytics/src/measure-currency-coherence.ts#assertMeasureCurrenciesCoherent refuses a measure labelling it another code. The container stays one blanket row and its keys are unchanged, so the verdict stays LIVE. WIDENED 2026-11-09 (#31910, ADR-0144 D2 as amended by #31743, ruling A recorded in 6739066323): a `record`-mode `currencyField` may be the two-segment path `PARENT_FIELD.CODE_FIELD` through a `master_detail` field of the same object, and a `summary` rolled up through that same `master_detail` declares its currency here as `currencyMode: 'record'` naming the parent's own code field. The row's verdict stays LIVE, since this container is one blanket row (`field/currencyConfig` in undrilled-containers.baseline.json) and the keys it reads are unchanged; the two new SHAPES are PLANNED, with no reader yet: the objectql projection, code guard, backfill, roll-up admission and the parent's code lock are #31911's, and the Console drawing the child amount and the roll-up in the parent's currency is #31912's. Until #31911 lands, the engine still reads a path pointer as a sibling field name. NARROWED 2026-10-28 (#27157, ruling 6464202770 on #27119, Q2 = X): `defaultCurrency` lost its `'CNY'` default and is required under `fixed` (a `fixed` config without a code is refused with the prescription); a `dynamic` config parses with no `defaultCurrency`, and stored rows lose the baked code through the ADR-0087 conversion `currency-config-dynamic-default-currency-removed`. The reader is unchanged and was re-read on this date: ui/packages/i18n/src/currency.ts#resolveFieldCurrency still takes the code only under `fixed`, so a `dynamic` config that no longer carries `CNY` displays exactly as before. Verdict unchanged: LIVE. RE-CITED 2026-09-27 (#20126): since objectui#10461 the reader takes defaultCurrency only under currencyMode 'fixed', and the chain no longer cites the date/datetime-semantics ADR, which never names currency; line pointers moved with it (currency.ts :32 → :60, CurrencyField.tsx :45/:51 → :55/:91). Verdict unchanged: LIVE. RE-CITED 2026-08-10 (#7133/#7142): the old pointer 'packages/fields/src/index.tsx:469' now lands in formatRelativeDays, a date-phrase helper with no currency involvement — the resolver moved to @object-ui/i18n and packages/fields/src/currency.ts:14 only re-exports it, which is why the old line drifted onto unrelated code rather than disappearing. Verdict unchanged: LIVE, and now cited at both the reader that consumes the key and the widget that applies the resolved currency. The removed `currencyConfig.precision` (#19992; packages/spec/src/data/field.zod.ts; moved out of spec source, #23434): the widget's one width is the currency's CLDR fraction digits, objectui @b9814b334 packages/fields/src/widgets/CurrencyField.tsx#CurrencyField through objectui @b9814b334 packages/fields/src/widgets/number-format.ts#currencyDisplayWidth over objectui @b9814b334 packages/fields/src/currency.ts#currencyFractionDigits, and no objectui code reads `currencyConfig.precision`; re-read 2026-10-15, first cited sha-less (the source then named `currencyFractionDigits(currency)` as the widget's own line)." + "note": "NARROWED 2026-11-15 (#33713, spec seat 4 claim 6893268160): the engine registry now judges a `dynamic` summary roll-up as `defineStack` does, at a single-object save or publish on a running server and at the end of an install or upgrade run (packages/objectql/src/record-currency-aggregate-door.ts#recordCurrencyFollowRefusal, case (d), against the objects as served, extensions included), in the same words (packages/spec/src/data/record-currency-path.ts#recordCurrencyDynamicRollupNotHomeError). A stored home amount now counts only where its `homeAmount` is valid as declared (packages/spec/src/data/record-currency-path.ts#storedHomeAmountSourceOf), at both doors. The reader is unchanged; verdict unchanged: LIVE. WIDENED 2026-11-15 (#33659, spec seat 4 claim 6890000941): a `summary` with `function` `sum` / `min` / `max` / `avg` that rolls up a stored home amount (a child field some `homeAmount.field` on the child object names) is admitted with `currencyMode: 'dynamic'` and no `defaultCurrency`, the roll-up of ADR-0144 D6's consolidation path in the home currency without metadata naming it (D8 rule 5). The reader that now consumes `dynamic` on a summary is ui/packages/fields/src/currency.ts#summaryDeclaresCurrency, read by both roll-up faces (ui/packages/fields/src/widgets/SummaryField.tsx#SummaryField and ui/packages/fields/src/index.tsx#FormulaCellRenderer), which draw the total through resolveFieldCurrency in the tenant default `localization.currency`, the code ObjectMetricWidget resolves for a tile over the same home field. Judged at the object door (`refuseUnadmittedSummaryCurrency`: a `dynamic` summary naming no child field, or carrying a `defaultCurrency`, stays refused, and a `count` refuses every mode as before) and in `defineStack` (case (d) of `collectRecordCurrencyPathErrors`: any other `dynamic` roll-up is refused). service-analytics is unchanged: `sourceFieldMeta` relays no code for `dynamic`, as for the home field itself. Verdict unchanged: LIVE. NARROWED 2026-11-09 (#31958, claim amend 1, record 6746006322): on a `summary` field the config is refused outside the ADR-0144 D6 admitted roll-up. A `count` roll-up refuses every mode, `fixed` included (a count is never an amount); `dynamic` is refused on every summary, since no reader consumes it there (the Console's roll-up faces read no `currencyConfig`; service-analytics relays only `fixed` and `record`); `record` is refused unless the roll-up runs through the `master_detail` its child amount follows (object door `refuseUnadmittedSummaryCurrency` in data/object.zod.ts, stack door case (c) of `collectRecordCurrencyPathErrors` in stack.zod.ts). `fixed` stays accepted on sum / min / max / avg because a reader consumes it: packages/services/service-analytics/src/plugin.ts sourceFieldMeta relays its `defaultCurrency` for any field type and packages/services/service-analytics/src/measure-currency-coherence.ts#assertMeasureCurrenciesCoherent refuses a measure labelling it another code. The container stays one blanket row and its keys are unchanged, so the verdict stays LIVE. WIDENED 2026-11-09 (#31910, ADR-0144 D2 as amended by #31743, ruling A recorded in 6739066323): a `record`-mode `currencyField` may be the two-segment path `PARENT_FIELD.CODE_FIELD` through a `master_detail` field of the same object, and a `summary` rolled up through that same `master_detail` declares its currency here as `currencyMode: 'record'` naming the parent's own code field. The row's verdict stays LIVE, since this container is one blanket row (`field/currencyConfig` in undrilled-containers.baseline.json) and the keys it reads are unchanged; the two new SHAPES are PLANNED, with no reader yet: the objectql projection, code guard, backfill, roll-up admission and the parent's code lock are #31911's, and the Console drawing the child amount and the roll-up in the parent's currency is #31912's. Until #31911 lands, the engine still reads a path pointer as a sibling field name. NARROWED 2026-10-28 (#27157, ruling 6464202770 on #27119, Q2 = X): `defaultCurrency` lost its `'CNY'` default and is required under `fixed` (a `fixed` config without a code is refused with the prescription); a `dynamic` config parses with no `defaultCurrency`, and stored rows lose the baked code through the ADR-0087 conversion `currency-config-dynamic-default-currency-removed`. The reader is unchanged and was re-read on this date: ui/packages/i18n/src/currency.ts#resolveFieldCurrency still takes the code only under `fixed`, so a `dynamic` config that no longer carries `CNY` displays exactly as before. Verdict unchanged: LIVE. RE-CITED 2026-09-27 (#20126): since objectui#10461 the reader takes defaultCurrency only under currencyMode 'fixed', and the chain no longer cites the date/datetime-semantics ADR, which never names currency; line pointers moved with it (currency.ts :32 → :60, CurrencyField.tsx :45/:51 → :55/:91). Verdict unchanged: LIVE. RE-CITED 2026-08-10 (#7133/#7142): the old pointer 'packages/fields/src/index.tsx:469' now lands in formatRelativeDays, a date-phrase helper with no currency involvement — the resolver moved to @object-ui/i18n and packages/fields/src/currency.ts:14 only re-exports it, which is why the old line drifted onto unrelated code rather than disappearing. Verdict unchanged: LIVE, and now cited at both the reader that consumes the key and the widget that applies the resolved currency. The removed `currencyConfig.precision` (#19992; packages/spec/src/data/field.zod.ts; moved out of spec source, #23434): the widget's one width is the currency's CLDR fraction digits, objectui @b9814b334 packages/fields/src/widgets/CurrencyField.tsx#CurrencyField through objectui @b9814b334 packages/fields/src/widgets/number-format.ts#currencyDisplayWidth over objectui @b9814b334 packages/fields/src/currency.ts#currencyFractionDigits, and no objectui code reads `currencyConfig.precision`; re-read 2026-10-15, first cited sha-less (the source then named `currencyFractionDigits(currency)` as the widget's own line)." }, "dimensions": { "status": "live", diff --git a/packages/spec/src/data/currency-summary-home-rollup.test.ts b/packages/spec/src/data/currency-summary-home-rollup.test.ts index c842ada2818..17c432d02a6 100644 --- a/packages/spec/src/data/currency-summary-home-rollup.test.ts +++ b/packages/spec/src/data/currency-summary-home-rollup.test.ts @@ -21,6 +21,7 @@ import { describe, it, expect } from 'vitest'; import { ObjectSchema } from './object.zod'; +import { recordCurrencyDynamicRollupNotHomeError, storedHomeAmountSourceOf } from './record-currency-path'; import { defineStack } from '../stack.zod'; const stackManifest = { @@ -184,3 +185,107 @@ describe('every other `dynamic` summary stays refused', () => { expect(() => buildStack([project()])).not.toThrow(); }); }); + +/** + * [#33713, N7] A stored home amount counts only where its `homeAmount` is + * valid as declared — the reading the object door guarantees for an authored + * object. An `objectExtensions` entry merges its fields into the child without + * that reading, so it cannot make a field that is not a home amount one by + * naming it in a `homeAmount`. The one reading lives in + * `record-currency-path.ts` (`storedHomeAmountSourceOf`), which the engine + * registry reads too. + */ +describe('a `homeAmount` makes a home amount only where it is valid as declared', () => { + /** A record-mode amount an extension adds to the child, whose `homeAmount.field` names `target`. */ + const forging = (target: string) => ({ + forged: { + type: 'currency', label: 'Forged', + currencyConfig: { + currencyMode: 'record', currencyField: 'currency_code', + homeAmount: { field: target, rateDate: 'expense_date', rateField: 'rate_used' }, + }, + }, + }); + const overNote = { summaryOperations: { object: 'crm_probe_expense', field: 'note_amount', function: 'sum', relationshipField: 'project' } }; + const stackWith = (extensionFields: Record, rollup: Record = overNote, child = expense()) => ({ + manifest: stackManifest, + objects: [project(rollup), child], + objectExtensions: [{ extend: 'crm_probe_expense', fields: extensionFields }], + }); + const refusalOf = (stack: unknown): string => { + let refusal: { code?: string; issues?: unknown[] } | undefined; + try { + defineStack(stack as Parameters[0]); + } catch (error) { + refusal = error as typeof refusal; + } + expect(refusal, 'expected defineStack to REFUSE this stack, and it accepted it').toBeDefined(); + expect(refusal!.code).toBe('STACK_CROSS_REFERENCE_INVALID'); + expect(refusal!.issues).toHaveLength(1); + return String(refusal!.issues![0]); + }; + + it('refuses a `dynamic` roll-up over a writable plain amount an extension names as a home field', () => { + const finding = refusalOf(stackWith(forging('note_amount'))); + expect(finding.startsWith(DYNAMIC_PREFIX)).toBe(true); + expect(finding).toContain("'crm_probe_expense.note_amount' is not a stored home amount"); + // The forged pointer is not offered as a home amount either. + expect(finding).toContain("The home amounts of 'crm_probe_expense' are 'amount_home';"); + }); + + it('refuses one over a `number` field, a `fixed` amount, or a field with an `expression`, each named by an extension', () => { + const readonlyFixed = { type: 'currency', label: 'Fixed', readonly: true, currencyConfig: { currencyMode: 'fixed', defaultCurrency: 'EUR' } }; + const computed = { type: 'currency', label: 'Computed', readonly: true, expression: 'amount * 2' }; + for (const [target, extra] of [ + ['rate_used', {}], + ['fixed_amount', { fixed_amount: readonlyFixed }], + ['computed_amount', { computed_amount: computed }], + ] as const) { + const summaryOperations = { object: 'crm_probe_expense', field: target, function: 'sum', relationshipField: 'project' }; + const finding = refusalOf(stackWith({ ...extra, ...forging(target) }, { summaryOperations })); + expect(finding.startsWith(DYNAMIC_PREFIX), target).toBe(true); + } + }); + + it('refuses one over a home field two amounts claim: one column, two writers', () => { + const summaryOperations = { object: 'crm_probe_expense', field: 'amount_home', function: 'sum', relationshipField: 'project' }; + const finding = refusalOf(stackWith(forging('amount_home'), { summaryOperations })); + expect(finding.startsWith(DYNAMIC_PREFIX)).toBe(true); + expect(finding).toContain("'crm_probe_expense' stores no home amount"); + }); + + it('CONTROL: an extension declaring a valid home amount on the child is admitted, as an authored one is', () => { + const home = { ext_home: { type: 'currency', label: 'Home', readonly: true }, ...forging('ext_home') }; + const summaryOperations = { object: 'crm_probe_expense', field: 'ext_home', function: 'sum', relationshipField: 'project' }; + expect(() => defineStack(stackWith(home, { summaryOperations }) as Parameters[0])).not.toThrow(); + }); + + it('reads the object door\'s guarantee: every authored home amount the object parses is one, and nothing else is', () => { + const fields = (ObjectSchema.parse(expense()) as { fields: Record }).fields; + expect(storedHomeAmountSourceOf(fields, 'amount_home')).toBe('amount'); + for (const other of ['amount', 'note_amount', 'rate_used', 'currency_code', 'absent']) { + expect(storedHomeAmountSourceOf(fields, other), other).toBeUndefined(); + } + }); +}); + +/** + * [#33713] The (d) sentence has one spelling, `record-currency-path.ts`'s, + * which `defineStack` and the engine registry both print. This pins the + * stack's half; the registry's equality with `defineStack` is pinned in + * `@objectstack/objectql`'s `record-currency-guards.test.ts`. + */ +describe('case (d) is worded once', () => { + it('defineStack prints `recordCurrencyDynamicRollupNotHomeError` for each refused child field', () => { + const fixedChild = expense({ note_amount: { type: 'currency', label: 'Plain', currencyConfig: { currencyMode: 'fixed', defaultCurrency: 'EUR' } } }); + for (const [field, child] of [['note_amount', expense()], ['note_amount', fixedChild], ['amount', expense()], ['rate_used', expense()]] as const) { + const summaryOperations = { object: 'crm_probe_expense', field, function: 'sum', relationshipField: 'project' }; + const childFields = (child as { fields: Record }).fields; + expect(stackRefusal([project({ summaryOperations }), child]), field).toBe(recordCurrencyDynamicRollupNotHomeError( + { object: 'crm_probe_project', field: 'home_expense_total', fn: 'sum', childObject: 'crm_probe_expense', childField: field }, + childFields, + childFields[field], + )); + } + }); +}); diff --git a/packages/spec/src/data/field.zod.ts b/packages/spec/src/data/field.zod.ts index ce200b1c16e..8793bdbc096 100644 --- a/packages/spec/src/data/field.zod.ts +++ b/packages/spec/src/data/field.zod.ts @@ -2246,7 +2246,7 @@ export const FieldSchema = lazySchema(() => { // Currency config — read for a `currency` field and for a `formula` whose // `returnType` is `currency` (#22727): one shape for both, never a second one. - currencyConfig: CurrencyConfigSchema.optional().describe('Which currency an amount is in: for a currency field, for a formula field whose returnType is currency, and for a summary that rolls up, through a master_detail, child amounts that follow this record\'s currency (`currencyMode: \'record\'` naming this object\'s own code field). A summary that rolls up a stored home amount (a child field some `homeAmount.field` names) declares `currencyMode: \'dynamic\'`, with no `defaultCurrency`, and shows in the organization\'s home currency. A summary may otherwise declare only `currencyMode: \'fixed\'`, when every amount it reads is in that one currency; a `count` summary, any other `dynamic` summary and any other `record` roll-up are refused. Absent: dynamic mode, and no currency on a summary.'), + currencyConfig: CurrencyConfigSchema.optional().describe('Which currency an amount is in: for a currency field, for a formula field whose returnType is currency, and for a summary that rolls up, through a master_detail, child amounts that follow this record\'s currency (`currencyMode: \'record\'` naming this object\'s own code field). A summary that rolls up a stored home amount (a child field some `homeAmount.field` names) declares `currencyMode: \'dynamic\'`, with no `defaultCurrency`, and shows in the organization\'s home currency. A summary may otherwise declare only `currencyMode: \'fixed\'`, when every amount it reads is in that one currency; a `count` summary, any other `dynamic` summary and any other `record` roll-up are refused, by `defineStack` and by a single-object save or publish on a running server alike. Absent: dynamic mode, and no currency on a summary.'), // Vector field — flat dimensionality (the live authoring path). // The renderer reads this flat sibling (read point recorded in diff --git a/packages/spec/src/data/record-currency-path.ts b/packages/spec/src/data/record-currency-path.ts index dc6c082ce11..45ae471e08d 100644 --- a/packages/spec/src/data/record-currency-path.ts +++ b/packages/spec/src/data/record-currency-path.ts @@ -22,8 +22,14 @@ * the parent, or a field that holds no code. * - {@link recordCurrencyUnfollowedRollupError}: (c), the arm of a * `currencyMode: 'record'` roll-up whose child amount follows no parent. + * - {@link storedHomeAmountSourceOf}: is a child field a stored home amount, + * named by a `homeAmount` that is valid where it is declared? The test (d) + * reads. + * - {@link recordCurrencyDynamicRollupNotHomeError}: (d), a + * `currencyMode: 'dynamic'` roll-up over a child field that is not a stored + * home amount. * - * Messages only and one predicate: each door decides when a pair is judged. + * Messages only and two predicates: each door decides when a pair is judged. */ import { VALUE_DOMAIN_FIELD_TYPES } from './field.zod'; @@ -152,3 +158,94 @@ function unfollowedAmountReason(childObject: string, childField: string, def: un export function recordCurrencyUnfollowedRollupError(rollup: RecordCurrencyRecordRollup, childDef: unknown): string { return recordCurrencyRecordRollupError(rollup, unfollowedAmountReason(rollup.childObject, rollup.childField, childDef)); } + +/** A field's `currencyConfig`, when it is an object. */ +function currencyConfigOf(def: unknown): Record | undefined { + return isRecord(def) && isRecord(def.currencyConfig) ? def.currencyConfig : undefined; +} + +/** + * [ADR-0144 D5, D8 rule 5] Is `def` a field the engine alone writes a home + * amount into: a stored `currency` field in `dynamic` mode (an absent mode is + * `dynamic`), `readonly: true` and with no `expression`? The object door's + * reading of a `homeAmount.field` target (`refuseDishonestHomeAmount`, + * `data/object.zod.ts`). + */ +function isStoredHomeField(def: unknown): boolean { + if (!isRecord(def) || def.type !== 'currency') return false; + const mode = currencyConfigOf(def)?.currencyMode ?? 'dynamic'; + return mode === 'dynamic' && def.readonly === true && def.expression === undefined; +} + +/** Does `def` declare a `homeAmount` whose `field` is `target`, where a `homeAmount` is valid: on a `record`-mode `currency` amount? */ +function claimsHomeField(def: unknown, target: string): boolean { + const config = currencyConfigOf(def); + return isRecord(def) && def.type === 'currency' && config?.currencyMode === 'record' + && isRecord(config.homeAmount) && config.homeAmount.field === target; +} + +/** + * [ADR-0144 D5] The amount field of `fields` whose `currencyConfig.homeAmount` + * stores its home-currency value in `field`, or `undefined` when `field` is + * not a stored home amount: the test (d) reads for "a stored home amount". + * + * A `homeAmount` counts only where it is valid as declared, the reading the + * object door (`refuseDishonestHomeAmount`, `data/object.zod.ts`) guarantees + * for an authored object: it sits on a `record`-mode `currency` amount, and its + * `field` names another field of the same map that is a stored `currency` + * field in `dynamic` mode, `readonly: true` and with no `expression`, claimed + * by that one amount alone. So a map the object door never parsed (an + * object's fields merged with an extension's, or an object as a server serves + * it) cannot make a plain number, a `fixed` amount or a writable field a home + * amount by naming it in a `homeAmount`. The `rateDate` and `rateField` + * pointers say nothing about which currency `field` holds, and are not read. + */ +export function storedHomeAmountSourceOf(fields: Record, field: string): string | undefined { + if (!hasOwnKey(fields, field) || !isStoredHomeField(fields[field])) return undefined; + const claimants = Object.keys(fields).filter((name) => name !== field && claimsHomeField(fields[name], field)); + return claimants.length === 1 ? claimants[0] : undefined; +} + +/** + * [ADR-0144 D6, D8 rule 5] (d): a `summary` (`sum`, `min`, `max`, `avg`) + * declaring `currencyMode: 'dynamic'` (or a `currencyConfig` with no + * `currencyMode`) rolls up `childDef`, a field of `childFields` that is not a + * stored home amount ({@link storedHomeAmountSourceOf}), with the declaration + * the child field does support. The faces draw a `dynamic` summary in the + * organization's home currency, which the amounts it reads are not known to + * be in. + */ +export function recordCurrencyDynamicRollupNotHomeError( + rollup: RecordCurrencyRecordRollup, + childFields: Record, + childDef: unknown, +): string { + const named = `'${rollup.childObject}.${rollup.childField}'`; + const config = currencyConfigOf(childDef); + const declaredHome = isRecord(config?.homeAmount) && typeof config.homeAmount.field === 'string' ? config.homeAmount.field : undefined; + const home = declaredHome !== undefined && storedHomeAmountSourceOf(childFields, declaredHome) === rollup.childField + ? declaredHome + : undefined; + const homes = Object.keys(childFields).filter((name) => storedHomeAmountSourceOf(childFields, name) !== undefined); + const why = config?.currencyMode === 'record' + ? `${named} is an amount in ${typeof config.currencyField === 'string' && config.currencyField.includes('.') ? 'its parent\'s' : 'each record\'s own'} ` + + `currency (\`currencyMode: 'record'\`), not the home currency. ` + + (home !== undefined + ? `Roll up its stored home amount '${rollup.childObject}.${home}' instead, ` + : 'Roll up a stored home amount of the child instead (declare `homeAmount` on the amount), ') + + 'or, when the amounts follow this record through the master_detail the roll-up runs through, declare ' + + '`currencyMode: \'record\'` naming this object\'s own code field.' + : config?.currencyMode === 'fixed' && typeof config.defaultCurrency === 'string' + ? `${named} is fixed to ${config.defaultCurrency}. Declare \`currencyConfig: { currencyMode: 'fixed', defaultCurrency: ` + + `'${config.defaultCurrency}' }\` on the summary instead.` + : `${named} is not a stored home amount, so its rows are not known to be in the home currency. ` + + (homes.length > 0 + ? `The home amounts of '${rollup.childObject}' are ${homes.map((h) => `'${h}'`).join(', ')}; roll up one of them, ` + : `'${rollup.childObject}' stores no home amount; `) + + 'or delete `currencyConfig` on the summary, or declare `currencyMode: \'fixed\'` if every amount it reads is in ' + + 'one currency.'; + return `Object '${rollup.object}' field '${rollup.field}' currencyConfig: \`currencyMode: 'dynamic'\` on a summary is ` + + 'admitted only for a roll-up of a stored home amount (a child field that a `homeAmount.field` on the child object ' + + 'names), whose every row is in the organization\'s home currency. This summary rolls up ' + + `${rollup.fn}(${rollup.childObject}.${rollup.childField}), and ${why}`; +} diff --git a/packages/spec/src/migrations/entries/semantic/18.summary-dynamic-currency-rollup-home-amount-judged-as-served.ts b/packages/spec/src/migrations/entries/semantic/18.summary-dynamic-currency-rollup-home-amount-judged-as-served.ts new file mode 100644 index 00000000000..35a975da05f --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.summary-dynamic-currency-rollup-home-amount-judged-as-served.ts @@ -0,0 +1,42 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// The upgrade-guide entry of a `dynamic` summary roll-up (ADR-0144 D6 and D8 +// rule 5) as the engine registry now judges it, beside `defineStack`: only +// over a stored home amount, against the objects as the server serves them. +// The widening that admitted the home roll-up shipped in a `next` snapshot of +// the spec before the engine door judged it, so a body that snapshot accepted +// on a running server can be refused now. No conversion: which child field +// holds the home amount is the author's to say. +export const entry: SemanticMigration = { + id: 'summary-dynamic-currency-rollup-home-amount-judged-as-served', + surface: + 'data.Field.currencyConfig on a `summary` field with `function` `sum` / `min` / `max` / `avg` that declares ' + + '`currencyMode: \'dynamic\'` (or a `currencyConfig` naming no mode). Where it is asked: a published single save or ' + + 'publish of an object or an `object_extension` item through the `/meta` doors, the batch writers, and the end of ' + + 'an install, upgrade or reload run on a running server, against the parent and the child as served (their bases ' + + 'and every enabled extension), in both directions: a parent saving such a roll-up, and a child saved so that a ' + + 'registered parent\'s roll-up no longer reads a home amount. Also `defineStack`, where a home amount now counts ' + + 'only when its `homeAmount` is valid as declared. Not the cold boot', + replacement: + 'Roll up the child\'s stored home amount (a `readonly` `dynamic` currency field that the `homeAmount.field` of one ' + + 'record-mode amount on the child names; the refusal lists them), declare `currencyMode: \'fixed\'` with the code ' + + 'when every amount the roll-up reads is in that one currency, or delete `currencyConfig` on the summary. When an ' + + '`objectExtensions` entry declares the home amount, give it a `readonly` `dynamic` currency field of its own and ' + + 'the record-mode amount that converts into it', + reason: + 'A `dynamic` summary is drawn in the organization\'s home currency, which is right only for a roll-up of a stored ' + + 'home amount. `defineStack` admitted it only there, but the engine registry, which a single-object save on a ' + + 'running server meets, judged only `record` roll-ups, so a `dynamic` roll-up over a `fixed` EUR amount, a plain ' + + 'number or a formula was stored and its total shown with the home currency\'s symbol. It is now refused 422 ' + + '`INVALID_METADATA` there, in the words `defineStack` uses. A `homeAmount` makes a field a home amount only where ' + + 'it is valid as declared (a record-mode `currency` amount naming another `readonly` `dynamic` currency field of ' + + 'the same object, with no `expression`, claimed by that one amount), so an extension cannot make a plain number ' + + 'a home amount by naming it. Roll-ups stored before this release keep loading at every boot, which is not asked. ' + + 'There is no mechanical rewrite: only the author knows which amount the roll-up should total', + acceptanceCriteria: + 'Save the parent with its `dynamic` roll-up of the child\'s home amount through PUT /api/v1/meta/object/PARENT on a ' + + 'running server and confirm the answer is 200 and the record page shows the total with the home currency\'s ' + + 'symbol. Save one over another child field and confirm the answer is 422 `INVALID_METADATA` naming the field', +}; diff --git a/packages/spec/src/stack.zod.ts b/packages/spec/src/stack.zod.ts index 70e8c8454da..c1eebd00341 100644 --- a/packages/spec/src/stack.zod.ts +++ b/packages/spec/src/stack.zod.ts @@ -45,9 +45,11 @@ import { externalBindingDatasourceRefusal } from './data/external-binding-dataso import { InlineGridColumnSchema, summaryFunctionReadsField } from './data/field.zod'; import { isRecordCurrencyCodeField, + recordCurrencyDynamicRollupNotHomeError, recordCurrencyFollowedCodeError, recordCurrencyRecordRollupError, recordCurrencyUnfollowedRollupError, + storedHomeAmountSourceOf, } from './data/record-currency-path'; import { AUDIT_FIELD_DEFS } from './data/injected-system-column-provenance'; import { pageComponentSlotPositions } from './ui/component.zod'; @@ -4695,60 +4697,6 @@ function recordCurrencyPathOf(field: unknown): { via: string; code: string } | u return { via: segments[0]!, code: segments[1]! }; } -/** - * The amount field of `childFields` whose `currencyConfig.homeAmount.field` - * names `field`, or `undefined` when no amount stores its home-currency value - * there: the test (d) of {@link collectRecordCurrencyPathErrors} reads for "a - * stored home amount" (ADR-0144 D5, the `homeAmount` declaration). - */ -function homeAmountSourceOf(childFields: Record, field: string): string | undefined { - return Object.keys(childFields).find((name) => { - const def = childFields[name]; - const config = isRecord(def) && isRecord(def.currencyConfig) ? def.currencyConfig : undefined; - return isRecord(config?.homeAmount) && config.homeAmount.field === field; - }); -} - -/** - * [#33659] (d)'s refusal: a `dynamic` roll-up over a child field that is not - * a stored home amount, with the declaration the child field does support. - */ -function dynamicRollupNotHomeError( - rollup: { object: string; field: string; fn: string; childObject: string; childField: string }, - childFields: Record, - childDef: unknown, -): string { - const named = `'${rollup.childObject}.${rollup.childField}'`; - const config = isRecord(childDef) && isRecord(childDef.currencyConfig) ? childDef.currencyConfig : undefined; - const home = isRecord(config?.homeAmount) && typeof config.homeAmount.field === 'string' ? config.homeAmount.field : undefined; - const homes = Object.keys(childFields).flatMap((name) => { - const def = childFields[name]; - const c = isRecord(def) && isRecord(def.currencyConfig) ? def.currencyConfig : undefined; - return isRecord(c?.homeAmount) && typeof c.homeAmount.field === 'string' ? [c.homeAmount.field] : []; - }); - const why = config?.currencyMode === 'record' - ? `${named} is an amount in ${typeof config.currencyField === 'string' && config.currencyField.includes('.') ? 'its parent\'s' : 'each record\'s own'} ` - + `currency (\`currencyMode: 'record'\`), not the home currency. ` - + (home !== undefined - ? `Roll up its stored home amount '${rollup.childObject}.${home}' instead, ` - : 'Roll up a stored home amount of the child instead (declare `homeAmount` on the amount), ') - + 'or, when the amounts follow this record through the master_detail the roll-up runs through, declare ' - + '`currencyMode: \'record\'` naming this object\'s own code field.' - : config?.currencyMode === 'fixed' && typeof config.defaultCurrency === 'string' - ? `${named} is fixed to ${config.defaultCurrency}. Declare \`currencyConfig: { currencyMode: 'fixed', defaultCurrency: ` - + `'${config.defaultCurrency}' }\` on the summary instead.` - : `${named} is not a stored home amount, so its rows are not known to be in the home currency. ` - + (homes.length > 0 - ? `The home amounts of '${rollup.childObject}' are ${homes.map((h) => `'${h}'`).join(', ')}; roll up one of them, ` - : `'${rollup.childObject}' stores no home amount; `) - + 'or delete `currencyConfig` on the summary, or declare `currencyMode: \'fixed\'` if every amount it reads is in ' - + 'one currency.'; - return `Object '${rollup.object}' field '${rollup.field}' currencyConfig: \`currencyMode: 'dynamic'\` on a summary is ` - + 'admitted only for a roll-up of a stored home amount (a child field that a `homeAmount.field` on the child object ' - + 'names), whose every row is in the organization\'s home currency. This summary rolls up ' - + `${rollup.fn}(${rollup.childObject}.${rollup.childField}), and ${why}`; -} - /** * [ADR-0144 D2 and D6, amended 2026-11-09 by #31743, ruling A recorded in * 6739066323] The two halves of a child that follows its parent's currency @@ -4796,7 +4744,10 @@ function dynamicRollupNotHomeError( * `currencyMode: 'dynamic'` (or a `currencyConfig` with no `currencyMode`, * which is `dynamic`) is admitted only when the child field it rolls up is a * stored home amount: a field that some `currencyConfig.homeAmount.field` on - * the child object names (#33659). ADR-0144 D6 has consolidated totals read + * the child object names (#33659), where that `homeAmount` is valid as declared + * (`storedHomeAmountSourceOf`: a field merged in from an extension never had + * the object door's reading, so a `homeAmount` naming a plain number, a `fixed` + * amount or a writable field does not make it a home amount). ADR-0144 D6 has consolidated totals read * that home field, and D8 rule 5 makes it "a `dynamic`-mode currency field", * displayed in the organization's home currency (`localization.currency`); * every row of it is in that one currency, so its total is too, and declaring @@ -4813,9 +4764,11 @@ function dynamicRollupNotHomeError( * fields live elsewhere), nor, for (c), a child it knows only through an * extension or a child field it does not hold (for (c) and (d) alike); and neither is a roll-up whose * relationship field is neither written nor the child's one relation back to - * the parent. + * the parent. A pair this pass skips because the stack knows an end only + * through an extension is judged by the engine registry against the objects + * as the server serves them, at the end of the run that installs the stack. * - * The (a) and (c)-unfollowed wording is `data/record-currency-path.ts`'s, + * The (a), (c)-unfollowed and (d) wording is `data/record-currency-path.ts`'s, * shared with the engine registry, which judges the same pairs at a * single-object save. */ @@ -4864,7 +4817,9 @@ function collectRecordCurrencyPathErrors(config: ObjectStackDefinition): string[ summaryCurrency !== undefined && (summaryCurrency.currencyMode ?? 'dynamic') === 'dynamic' && declared.has(ops.object) && childField !== undefined ) { - if (homeAmountSourceOf(child, ops.field) === undefined) errors.push(dynamicRollupNotHomeError(rollup, child, childField)); + if (storedHomeAmountSourceOf(child, ops.field) === undefined) { + errors.push(recordCurrencyDynamicRollupNotHomeError(rollup, child, childField)); + } continue; } const refuseRecord = (why: string): void => {