Skip to content

Commit 696c3f2

Browse files
committed
feat(objectql): record-currency guards — blank code refuses the write, ungrouped raw aggregate refused, summary roll-up refused at registration
ADR-0144 D6 and D8 rule 4. A record-mode amount beside a blank currency code is refused ERR_CURRENCY_CODE_REQUIRED (registered in the ADR-0112 ledger); sum/avg/min/max over a record-mode amount refuses INVALID_FIELD unless grouped by its code field; a summary roll-up reading one refuses INVALID_METADATA at registration. Rider: inferFormulaReturn carries record mode and its currencyField for a formula over a record-mode amount. Claude-Session: https://claude.ai/code/session_01Utp6CboxRwQPbQZnhxyuzt Co-authored-by: Claude <noreply@anthropic.com>
1 parent 5232c8b commit 696c3f2

8 files changed

Lines changed: 828 additions & 14 deletions

File tree

‎packages/formula/src/formula-return.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,3 +165,40 @@ describe('CONTROL — a numeric formula stays `number`', () => {
165165
expect(inferFormulaReturn('record.amount *', FIELDS)).toEqual({});
166166
});
167167
});
168+
169+
describe('a formula over a record-mode amount carries the record currency (ADR-0144 D2)', () => {
170+
const RECORD = { currencyMode: 'record', currencyField: 'currency_code' } as const;
171+
const RECORD_FIELDS: Readonly<Record<string, FormulaSourceField>> = {
172+
currency_code: { type: 'text' },
173+
other_code: { type: 'text' },
174+
amount: { type: 'currency', currencyConfig: RECORD },
175+
tax: { type: 'currency', currencyConfig: RECORD },
176+
fee: { type: 'currency', currencyConfig: { currencyMode: 'record', currencyField: 'other_code' } },
177+
budget: { type: 'currency' },
178+
usd: { type: 'currency', currencyConfig: USD },
179+
quantity: { type: 'number' },
180+
};
181+
182+
it('stamps `record` mode with the source amount\'s code field, never the tenant default', () => {
183+
expect(inferFormulaReturn('record.amount * 0.1', RECORD_FIELDS))
184+
.toEqual({ returnType: 'currency', currencyConfig: RECORD });
185+
expect(inferFormulaReturn('record.amount + record.tax', RECORD_FIELDS))
186+
.toEqual({ returnType: 'currency', currencyConfig: RECORD });
187+
expect(inferFormulaReturn('round(record.amount * record.quantity)', RECORD_FIELDS))
188+
.toEqual({ returnType: 'currency', currencyConfig: RECORD });
189+
});
190+
191+
it('an amount over its own currency is a plain ratio', () => {
192+
expect(inferFormulaReturn('record.tax / record.amount', RECORD_FIELDS).returnType).not.toBe('currency');
193+
});
194+
195+
it('two different currencies meeting are not one amount', () => {
196+
for (const source of [
197+
'record.amount + record.fee', // two code fields
198+
'record.amount + record.budget', // record + the tenant default
199+
'record.amount + record.usd', // record + fixed USD
200+
]) {
201+
expect(inferFormulaReturn(source, RECORD_FIELDS).returnType, source).not.toBe('currency');
202+
}
203+
});
204+
});

‎packages/formula/src/formula-return.ts‎

Lines changed: 36 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -79,15 +79,25 @@ export interface FormulaSourceField {
7979
*
8080
* - `returnType` — absent when no concrete type can be proven.
8181
* - `currencyConfig` — present only for a `currency` result whose currency is
82-
* `fixed`. A `dynamic` result (the tenant default currency) declares no config,
83-
* exactly as a `dynamic` currency field may carry none.
82+
* `fixed`, or `record` (ADR-0144 D2: each record's own currency, carried as
83+
* the same `currencyField` its source amounts name). A `dynamic` result (the
84+
* tenant default currency) declares no config, exactly as a `dynamic`
85+
* currency field may carry none.
8486
*/
8587
export interface FormulaReturnDeclaration {
8688
readonly returnType?: NonNullable<Field['returnType']>;
87-
readonly currencyConfig?: { readonly currencyMode: 'fixed'; readonly defaultCurrency: string };
89+
readonly currencyConfig?:
90+
| { readonly currencyMode: 'fixed'; readonly defaultCurrency: string }
91+
| { readonly currencyMode: 'record'; readonly currencyField: string };
8892
}
8993

90-
type MoneyCurrency = { readonly mode: 'dynamic' } | { readonly mode: 'fixed'; readonly code: string };
94+
type MoneyCurrency =
95+
| { readonly mode: 'dynamic' }
96+
| { readonly mode: 'fixed'; readonly code: string }
97+
// [ADR-0144 D2] Each record's own currency, the code in the sibling field
98+
// `field` names. Two record-mode amounts are one currency only when they
99+
// name the same code field.
100+
| { readonly mode: 'record'; readonly field: string };
91101

92102
type Dim =
93103
| { readonly kind: 'money'; readonly currency: MoneyCurrency }
@@ -125,17 +135,23 @@ function isNode(v: unknown): v is Node {
125135
}
126136

127137
function sameCurrency(a: MoneyCurrency, b: MoneyCurrency): boolean {
128-
if (a.mode === 'dynamic' || b.mode === 'dynamic') return a.mode === b.mode;
129-
return a.code === b.code;
138+
if (a.mode === 'fixed' && b.mode === 'fixed') return a.code === b.code;
139+
if (a.mode === 'record' && b.mode === 'record') return a.field === b.field;
140+
return a.mode === b.mode;
130141
}
131142

132143
/** A field's currency, read through the schema a currency field is parsed with — or `null` when it does not parse. */
133144
function currencyOf(config: unknown): MoneyCurrency | null {
134145
const parsed = CurrencyConfigSchema.safeParse(config ?? {});
135146
if (!parsed.success) return null;
136-
return parsed.data.currencyMode === 'fixed'
137-
? { mode: 'fixed', code: parsed.data.defaultCurrency }
138-
: { mode: 'dynamic' };
147+
if (parsed.data.currencyMode === 'fixed') return { mode: 'fixed', code: parsed.data.defaultCurrency };
148+
// [ADR-0144 D2] A `record`-mode amount is in the currency its sibling code
149+
// field holds — never the tenant default a `dynamic` stamp would claim. The
150+
// schema requires the pointer under `record`, so a parsed config carries it.
151+
if (parsed.data.currencyMode === 'record') {
152+
return parsed.data.currencyField ? { mode: 'record', field: parsed.data.currencyField } : null;
153+
}
154+
return { mode: 'dynamic' };
139155
}
140156

141157
/** Is `d` a number that is not an amount (a quantity or a constant)? */
@@ -253,8 +269,10 @@ function sourceOf(input: ExprInput): string | null {
253269
*
254270
* - Provably money ⇒ `{ returnType: 'currency' }`, plus
255271
* `currencyConfig: { currencyMode: 'fixed', defaultCurrency }` when the
256-
* source amounts are in one fixed currency. Sources in two different
257-
* currencies are not provably one amount, and fall through.
272+
* source amounts are in one fixed currency, or
273+
* `currencyConfig: { currencyMode: 'record', currencyField }` when they are
274+
* record-mode amounts naming one code field (ADR-0144 D2). Sources in two
275+
* different currencies are not provably one amount, and fall through.
258276
* - Otherwise ⇒ the {@link inferExpressionType} answer as `returnType`
259277
* (`number` / `text` / `boolean` / `date`), or `{}` when that is `unknown` —
260278
* unchanged from before this function existed, so a numeric formula stays
@@ -278,9 +296,13 @@ export function inferFormulaReturn(
278296
if (celType !== null && MONEY_CEL_TYPES.has(celType)) {
279297
const dim = dimOf(parseCelToAst(source), fields);
280298
if (dim.kind === 'money') {
281-
return dim.currency.mode === 'fixed'
282-
? { returnType: 'currency', currencyConfig: { currencyMode: 'fixed', defaultCurrency: dim.currency.code } }
283-
: { returnType: 'currency' };
299+
if (dim.currency.mode === 'fixed') {
300+
return { returnType: 'currency', currencyConfig: { currencyMode: 'fixed', defaultCurrency: dim.currency.code } };
301+
}
302+
if (dim.currency.mode === 'record') {
303+
return { returnType: 'currency', currencyConfig: { currencyMode: 'record', currencyField: dim.currency.field } };
304+
}
305+
return { returnType: 'currency' };
284306
}
285307
}
286308
}

‎packages/objectql/src/engine.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,8 @@ import { count, rejectCredentialAggregation } from './engine-count-aggregate.js'
305305
import { assertGroupByNamesNoJsonStoredField } from './group-by-structured-json-door.js';
306306
import { assertProjectionNamesAField } from './empty-projection-door.js';
307307
import { assertAggregationFieldTypesAccepted } from './aggregate-field-type-door.js';
308+
import { assertRecordCurrencyAggregatesGrouped } from './record-currency-aggregate-door.js';
309+
import { assertRecordCurrencyCodes, touchesRecordCurrency } from './validation/record-currency-code.js';
308310
import { assertAggregatedColumnsAreDistinct, assertDateBucketTargetsAreTemporal } from './aggregate-query-shape-door.js';
309311
import { applyProtection, pluralToSingular, ExternalWriteForbiddenError } from '@objectstack/spec/shared';
310312
import { SchemaRegistry, type ArtifactInstallScope } from './registry.js';
@@ -15382,6 +15384,9 @@ export class ObjectQL implements IObjectQLEngine {
1538215384
normalizeMultiValueFields(schemaForValidation, rows[i], 'include');
1538315385
// [#22183] `keptOptionValues`: the option values an import kept for this write.
1538415386
validateRecordInScope(schemaForValidation, rows[i], 'insert', 'include', { mediaValueShapeStrict, valueShapeStrict, messages: msgCtx, onAdmittedValueShapeViolation, keptOptionValues: opCtx.context?.keptOptionValues });
15387+
// [ADR-0144 D8 rule 4] A `record`-mode amount is stored with its
15388+
// currency code, or the row is refused (`ERR_CURRENCY_CODE_REQUIRED`).
15389+
assertRecordCurrencyCodes(object, (schemaForValidation as { fields?: unknown } | undefined)?.fields, rows[i], 'insert');
1538515390
emitValidationAdvisories(options?.onValidationAdvisory, evaluateValidationRules(schemaForValidation as any, rows[i], 'insert', { logger: this.logger, currentUser: this.buildEvalUser(opCtx.context), skipStateMachine: shouldSkipStateMachine(opCtx.context), messages: msgCtx, parent: insertParentForRow?.(rows[i]), related: batchSummaries ? batchSummaries.overlay(insertRelatedForRow(rows[i])) : insertRelatedForRow(rows[i]), permissions: insertPermissionsFor(rows[i]) }), this.logger, object);
1538615391
await this.assertReferencesResolve(
1538715392
schemaForValidation, rows[i], suppliedPerRow[i], opCtx.context, msgCtx,
@@ -17099,6 +17104,14 @@ export class ObjectQL implements IObjectQLEngine {
1709917104
// because those are already judged. See `ReadonlyValueScope`.
1710017105
normalizeMultiValueFields(updateSchema, hookContext.input.data as Record<string, unknown>, 'only');
1710117106
validateRecordInScope(updateSchema, hookContext.input.data as Record<string, unknown>, 'update', 'only', { mediaValueShapeStrict, valueShapeStrict, messages: updateMsgCtx, onAdmittedValueShapeViolation });
17107+
// [ADR-0144 D8 rule 4] The stored row with the FINAL payload laid
17108+
// over it keeps a currency code beside a record-mode amount the
17109+
// payload touches (`ERR_CURRENCY_CODE_REQUIRED`).
17110+
assertRecordCurrencyCodes(
17111+
object, (updateSchema as { fields?: unknown } | undefined)?.fields,
17112+
{ ...(priorRecord ?? {}), ...(hookContext.input.data as Record<string, unknown>) },
17113+
'update', hookContext.input.data as Record<string, unknown>, hookContext.input.id,
17114+
);
1710217115
// ── [#19989] The post-image seam on the BY-ID path ─────────────
1710317116
//
1710417117
// The by-id twin of the predicate-path call below, placed at the
@@ -17418,6 +17431,20 @@ export class ObjectQL implements IObjectQLEngine {
1741817431
// N rows are written.
1741917432
normalizeMultiValueFields(updateSchema, hookContext.input.data as Record<string, unknown>, 'only');
1742017433
validateRecordInScope(updateSchema, hookContext.input.data as Record<string, unknown>, 'update', 'only', { mediaValueShapeStrict, valueShapeStrict, messages: updateMsgCtx, onAdmittedValueShapeViolation });
17434+
// [ADR-0144 D8 rule 4] The predicate-path twin: every matched row,
17435+
// with the FINAL payload laid over it, keeps a currency code beside
17436+
// a record-mode amount the payload touches. The matched rows are
17437+
// read only for such a payload (`readPriorRows` is the memo the
17438+
// seams below share).
17439+
{
17440+
const currencyPayload = hookContext.input.data as Record<string, unknown>;
17441+
const currencyFields = (updateSchema as { fields?: unknown } | undefined)?.fields;
17442+
if (touchesRecordCurrency(currencyFields, currencyPayload)) {
17443+
for (const row of (await readPriorRows()) ?? []) {
17444+
assertRecordCurrencyCodes(object, currencyFields, { ...row, ...currencyPayload }, 'update', currencyPayload, row?.id);
17445+
}
17446+
}
17447+
}
1742117448
// ── [#19950] The post-image seam on the PREDICATE path ─────────
1742217449
//
1742317450
// An enforcement layer's write `check` must hold for EVERY row a
@@ -20343,6 +20370,11 @@ export class ObjectQL implements IObjectQLEngine {
2034320370
// string on SQLite and a 500 on PostgreSQL; `sum` over one answered `0`,
2034420371
// `0` and a 500. Every row of the table is asked (see the door's header).
2034520372
assertAggregationFieldTypesAccepted(object, this._registry.getObject(object), query.aggregations);
20373+
// [ADR-0144 D6] …and a `sum` / `avg` / `min` / `max` over a `record`-mode
20374+
// amount that does not group by its code field: the rows hold amounts in
20375+
// different currencies, which add into one number under one label.
20376+
// After the type door, so a type it refuses keeps that door's words.
20377+
assertRecordCurrencyAggregatesGrouped(object, this._registry.getObject(object), query.groupBy, query.aggregations);
2034620378
// [#25818] …and the two shapes that answered a plausible wrong table: a
2034720379
// `dateGranularity` over a field declared neither a date nor a datetime
2034820380
// (every row in one null bucket), and two columns of the aggregated row

0 commit comments

Comments
 (0)