diff --git a/.changeset/33888-unserved-parent-code-message.md b/.changeset/33888-unserved-parent-code-message.md new file mode 100644 index 00000000000..b6da587021f --- /dev/null +++ b/.changeset/33888-unserved-parent-code-message.md @@ -0,0 +1,10 @@ +--- +'@objectstack/objectql': patch +--- + +fix(objectql): a following amount whose parent code field is no longer served is refused with a message that says so + +Clause-②: no +Metadata-protocol: none + +A `record`-mode amount that follows its parent's currency (`currencyField: 'MASTER_DETAIL.CODE'`) is still refused `ERR_CURRENCY_CODE_REQUIRED` / 400 when the parent object, as served at the write, no longer declares the code field (the package that contributed it was disabled or uninstalled). The message used to say the parent's code was blank and asked for a code to be written into that field, which is not there. It now says the parent does not serve the field, names the disabled package when the registry still holds its contribution, and says the amount has no code to follow until the field is served again, or that the amount can be left empty. The code, status, `field` and `amountField` are unchanged, and so is the message for a served code field that is blank. diff --git a/packages/objectql/src/engine-insert.ts b/packages/objectql/src/engine-insert.ts index 0c042d8791b..cc7c40cc50a 100644 --- a/packages/objectql/src/engine-insert.ts +++ b/packages/objectql/src/engine-insert.ts @@ -51,7 +51,7 @@ import { ASSIGNMENT_RULE_TYPE, AssignmentRuleEvaluator, OWNERSHIP_QUEUE_SOURCE_S import type { AssignmentQueueService } from './assignment-rules.js'; import { redactBoundStatement } from '@objectstack/types'; import { ORGANIZATION_OBJECT } from './tenancy/system-write-organization.js'; -import { assertRecordCurrencyCodes, followParentCurrencyCodes, recordCurrencyPairs } from './validation/record-currency-code.js'; +import { assertRecordCurrencyCodes, followParentCurrencyCodes, parentCodeFieldServingOf, recordCurrencyPairs } from './validation/record-currency-code.js'; import { planHomeAmounts, projectHomeAmounts } from './home-amount-projection.js'; import { stripSearchCompanion } from './search-companion.js'; import type { EvalPermissions } from '@objectstack/formula'; @@ -1337,7 +1337,7 @@ export class InsertFacet { // [ADR-0144 D8 rule 4] A `record`-mode amount is stored with its // currency code, or the row is refused (`ERR_CURRENCY_CODE_REQUIRED`). // [ADR-0144 D2, amended] A child amount's code is its parent's, laid on a copy of the row. - assertRecordCurrencyCodes(object, (schemaForValidation as { fields?: unknown } | undefined)?.fields, rows[i] && typeof rows[i] === 'object' ? followCodes(rows[i]) : rows[i], 'insert', undefined, undefined, msgCtx); + assertRecordCurrencyCodes(object, (schemaForValidation as { fields?: unknown } | undefined)?.fields, rows[i] && typeof rows[i] === 'object' ? followCodes(rows[i]) : rows[i], 'insert', undefined, undefined, msgCtx, parentCodeFieldServingOf(this._registry)); // [#29029] A write that is not a system write has its references // checked BEFORE the record's validation rules: a reference the // caller cannot read answers `reference_not_found`, whatever a rule diff --git a/packages/objectql/src/engine-update.ts b/packages/objectql/src/engine-update.ts index 2a2410b28aa..92f0c059204 100644 --- a/packages/objectql/src/engine-update.ts +++ b/packages/objectql/src/engine-update.ts @@ -49,7 +49,7 @@ import { NotNullRefusalError, envelopeDriverWriteRefusal } from './not-null-refu import { redactBoundStatement } from '@objectstack/types'; import { ORGANIZATION_OBJECT } from './tenancy/system-write-organization.js'; import { rejectCredentialEvaluation } from './credential-evaluation-guard.js'; -import { assertRecordCurrencyCodes, followParentCurrencyCodes, recordCurrencyPairs, touchesRecordCurrency } from './validation/record-currency-code.js'; +import { assertRecordCurrencyCodes, followParentCurrencyCodes, parentCodeFieldServingOf, recordCurrencyPairs, touchesRecordCurrency } from './validation/record-currency-code.js'; import { homeAmountsTouched, planHomeAmounts, projectHomeAmounts, settleBulkHomeAmounts } from './home-amount-projection.js'; import { assertFollowedCurrencyCodesUnchanged, parentCurrencyLockReads, touchesFollowedCurrencyCode } from './record-currency-parent-lock.js'; import { stripSearchCompanion } from './search-companion.js'; @@ -1545,7 +1545,7 @@ export class UpdateFacet { : undefined; assertRecordCurrencyCodes( object, currencyFields, followCodes ? followCodes(currencyImage) : currencyImage, - 'update', currencyPayload, hookContext.input.id, updateMsgCtx, + 'update', currencyPayload, hookContext.input.id, updateMsgCtx, parentCodeFieldServingOf(this._registry), ); } // [ADR-0144 D2, amended] …and a record a child row follows the @@ -1954,7 +1954,7 @@ export class UpdateFacet { recordCurrencyPairs(currencyFields), images.map((i) => i.image), this.homeAmountServing(opCtx.context).parentRows, ); for (const { row, image } of images) { - assertRecordCurrencyCodes(object, currencyFields, followCodes(image), 'update', currencyPayload, row?.id, updateMsgCtx); + assertRecordCurrencyCodes(object, currencyFields, followCodes(image), 'update', currencyPayload, row?.id, updateMsgCtx, parentCodeFieldServingOf(this._registry)); } } // [ADR-0144 D2, amended] The predicate-path twin of the diff --git a/packages/objectql/src/engine-validate.ts b/packages/objectql/src/engine-validate.ts index 358244cf2ac..55a80d424bc 100644 --- a/packages/objectql/src/engine-validate.ts +++ b/packages/objectql/src/engine-validate.ts @@ -50,7 +50,7 @@ import type { WriteObservabilityOptions } from '@objectstack/spec/contracts'; import { validateRecordInScope, normalizeBlankTypedValues, normalizeNumericStringValues, ValidationError, valueShapeStrictEffective, mediaStrictEffective } from './validation/record-validator.js'; import { evaluateValidationRules, hasParentScopedRequiredWhen, stripReadonlyFields, stripRuntimeOwnedFields } from './validation/rule-validator.js'; import { createBatchSummaryAccumulator } from './summary-batch-accumulation.js'; -import { assertRecordCurrencyCodes, followParentCurrencyCodes, recordCurrencyPairs, RecordCurrencyCodeRequiredError, touchesRecordCurrency } from './validation/record-currency-code.js'; +import { assertRecordCurrencyCodes, followParentCurrencyCodes, parentCodeFieldServingOf, recordCurrencyPairs, RecordCurrencyCodeRequiredError, touchesRecordCurrency } from './validation/record-currency-code.js'; import { assertFollowedCurrencyCodesUnchanged, parentCurrencyLockReads, touchesFollowedCurrencyCode } from './record-currency-parent-lock.js'; import { isHomeAmountRefusal } from './home-amount-projection.js'; import { referencesCheckedBeforeRules } from './engine-referential-integrity.js'; @@ -580,7 +580,7 @@ export async function validate( assertRecordCurrencyCodes( object, currencyFields, followCodes && currencyImage ? followCodes(currencyImage) : currencyImage, mode, mode === 'insert' ? undefined : row, storedIds[i], - messages, + messages, parentCodeFieldServingOf(this._registry), ); // [ADR-0144 D2, amended] …and the write's parent-code lock, on the // stored row the by-id update writes: a record a child row follows diff --git a/packages/objectql/src/record-currency-guards.test.ts b/packages/objectql/src/record-currency-guards.test.ts index ac2bdefae44..171c38cee73 100644 --- a/packages/objectql/src/record-currency-guards.test.ts +++ b/packages/objectql/src/record-currency-guards.test.ts @@ -1342,3 +1342,67 @@ describe('a single-object save is refused a `dynamic` roll-up over a child field expect(() => save(valid.engine, project('ext_home'))).not.toThrow(); }); }); + +// ── [ADR-0144 D2, amended] A followed parent code field the parent no longer serves ── +// +// The fixture is the package-lifecycle measurement's shape: `billing` owns +// `suite_invoice` and `suite_line`, `supplier` extends `suite_invoice` with the +// code field, and `suite_line.amount` follows `invoice.currency_code`. After the +// supplier leaves, the next child write is still refused ERR_CURRENCY_CODE_REQUIRED +// / 400, and the message says the field is not served instead of asking for a +// code to be written into a field that is not there. + +describe('a following amount whose parent code field is no longer served is refused, and the message says so (ADR-0144 D2, amended)', () => { + const BILLING = 'com.test.billing'; + const SUPPLIER = 'com.test.supplier'; + const NOT_SERVED = "and 'suite_invoice' does not serve a field 'currency_code' ("; + const NO_CODE_TO_FOLLOW = "; the amount has no code to follow until that field is served again, or leave 'amount' empty. The row was not written."; + + async function bootSuite() { + const booted = await bootEngine(); + booted.engine.registerApp({ + id: BILLING, name: 'billing', + objects: [ + { name: 'suite_invoice', fields: { title: { type: 'text' } } }, + { name: 'suite_line', fields: { title: { type: 'text' }, invoice: { type: 'master_detail', reference: 'suite_invoice' }, amount: { type: 'currency', currencyConfig: FOLLOWS } } }, + ], + } as any); + booted.engine.registerApp({ id: SUPPLIER, name: 'supplier', objectExtensions: [{ extend: 'suite_invoice', fields: { currency_code: CODE_FIELD } }] } as any); + await booted.engine.insert('suite_invoice', { id: 'inv_usd', title: 'usd', currency_code: 'USD' }); + await booted.engine.insert('suite_invoice', { id: 'inv_blank', title: 'blank' }); + // CONTROL: while the supplier serves the field, a line under a parent holding a code is written. + await booted.engine.insert('suite_line', { title: 'before', invoice: 'inv_usd', amount: 100 }); + return booted; + } + + it('disable: the supplier disabled, a line with an amount is refused naming the field as not served and the disabled package', async () => { + const { engine, storeFor } = await bootSuite(); + engine.registry.disablePackage(SUPPLIER); + expect((engine.registry.getObject('suite_invoice')?.fields as any)?.currency_code).toBeUndefined(); + const err = await refusalOf(engine.insert('suite_line', { title: 'after', invoice: 'inv_usd', amount: 100 })); + expect(envelopeOf(err)).toEqual(CODE_REQUIRED); + expect(err?.field).toBe('invoice.currency_code'); + expect(err?.message).toContain(`${NOT_SERVED}the package '${SUPPLIER}' that contributed it is disabled)${NO_CODE_TO_FOLLOW}`); + expect(err?.message).not.toContain('has a blank'); + expect(storeFor('suite_line').size).toBe(1); + // Uninstalled, the registry no longer holds the contribution: the package clause is the generic one. + engine.registry.uninstallPackage(SUPPLIER); + const gone = await refusalOf(engine.insert('suite_line', { title: 'gone', invoice: 'inv_usd', amount: 100 })); + expect(envelopeOf(gone)).toEqual(CODE_REQUIRED); + expect(gone?.message).toContain(`${NOT_SERVED}a package that contributed it may be disabled or uninstalled)${NO_CODE_TO_FOLLOW}`); + }); + + it('CONTROL: a served code field that is blank on the parent keeps the blank-code text', async () => { + const { engine } = await bootSuite(); + const err = await refusalOf(engine.insert('suite_line', { title: 'blank', invoice: 'inv_blank', amount: 100 })); + expect(envelopeOf(err)).toEqual(CODE_REQUIRED); + expect(err?.message).toBe( + "Insert on 'suite_line' was REFUSED: 'amount' holds an amount in its parent record's currency (currencyMode: 'record', " + + "following 'invoice.currency_code' through the master_detail 'invoice'), and the 'suite_invoice' record it names " + + "has a blank 'currency_code', or it names none. The row was not written. Write the parent's ISO 4217 code (for " + + "example 'USD') into 'suite_invoice.currency_code' first, and name that parent in 'invoice', or leave 'amount' " + + 'empty. A child stores no code of its own: it follows its parent\'s. The server never fills a currency in: a ' + + 'form pre-fills the organization\'s currency, and the stored code is always the one submitted.', + ); + }); +}); diff --git a/packages/objectql/src/validation/record-currency-code.ts b/packages/objectql/src/validation/record-currency-code.ts index 01b463883d8..c74cd8bdd6d 100644 --- a/packages/objectql/src/validation/record-currency-code.ts +++ b/packages/objectql/src/validation/record-currency-code.ts @@ -48,7 +48,11 @@ * read it. A field's machine name never holds a dot, so that key can never be * a stored column. A parent with a blank code refuses the child's amount here, * as a blank sibling code does ("a child amount beside a blank code is - * refused at its own write", the D2 note). + * refused at its own write", the D2 note). A parent object that, as served at + * the write, declares no such code field (the package that contributed it is + * disabled or uninstalled) refuses it with the same code, and the message + * says the field is not served, naming the disabled package when the registry + * still holds its contribution ({@link parentCodeFieldServingOf}). * * The parent is read the way the write's other header reads are: first * through the WRITER's read door, then elevated, keeping the organization. A @@ -298,6 +302,103 @@ export function isRecordCurrencyBlank(value: unknown): boolean { const isBlank = isRecordCurrencyBlank; +/** + * [ADR-0144 D2, amended] A followed parent object, as served at the write, + * that declares no field under the code segment of the pointer: a package that + * contributed the field was disabled or uninstalled after the pointer was + * admitted. The amount then has no code to follow at all, and the refusal says + * so instead of asking for a code to be written into a field that is not + * there. + */ +export interface ParentCodeFieldUnserved { + /** + * The disabled packages whose contribution to the parent still declares the + * field, as the registry holds them; empty when it holds none (the package + * was uninstalled, or the field left in some other way). + */ + readonly disabledContributors: readonly string[]; +} + +/** + * Asks whether parent object `master` serves field `code` at the write: + * `undefined` when it does (or when `master` itself is not served, which the + * write's own reads answer), a {@link ParentCodeFieldUnserved} when it does + * not. Read only on the refusal path. + */ +export type ParentCodeFieldServing = (master: string, code: string) => ParentCodeFieldUnserved | undefined; + +/** The registry reads {@link parentCodeFieldServingOf} makes; `SchemaRegistry` answers them. */ +export interface ParentCodeFieldRegistry { + getObject(name: string): { readonly fields?: unknown } | undefined; + getObjectContributors(name: string): ReadonlyArray<{ readonly packageId: string | undefined; readonly definition: unknown }>; + isPackageDisabled(packageId?: string): boolean; +} + +const declaresField = (fields: unknown, name: string): boolean => + fields !== null && typeof fields === 'object' && !Array.isArray(fields) && Object.prototype.hasOwnProperty.call(fields, name); + +/** + * The {@link ParentCodeFieldServing} a write passes {@link assertRecordCurrencyCodes}: + * the parent's served field map (the fold, a disabled package's extension left + * out) decides whether the field is served, and the parent's contributors name + * the disabled packages that still declare it. + */ +export function parentCodeFieldServingOf(registry: ParentCodeFieldRegistry): ParentCodeFieldServing { + return (master, code) => { + const served = registry.getObject(master); + if (served === undefined || declaresField(served.fields, code)) return undefined; + const disabledContributors = [...new Set(registry.getObjectContributors(master) + .filter((c) => typeof c.packageId === 'string' && registry.isPackageDisabled(c.packageId) + && declaresField((c.definition as { fields?: unknown } | null | undefined)?.fields, code)) + .map((c) => c.packageId as string))]; + return { disabledContributors }; + }; +} + +/** The message of {@link RecordCurrencyCodeRequiredError}: the first hit's verdict and remedy, and the other hits. */ +function codeRequiredMessage( + object: string, + operation: 'insert' | 'update', + hits: readonly RecordCurrencyPair[], + recordId: unknown, + unserved: ParentCodeFieldUnserved | undefined, +): string { + const [first] = hits; + const row = recordId === undefined || recordId === null ? '' : ` (record ${String(recordId)})`; + const path = first.path; + const head = `${operation === 'insert' ? 'Insert' : 'Update'} on '${object}'${row} was REFUSED: '${first.amountField}' `; + const also = hits.length > 1 ? ` (also: ${hits.slice(1).map((h) => `'${h.codeField}' for '${h.amountField}'`).join(', ')})` : ''; + if (path && path.master !== undefined && unserved) { + const ids = unserved.disabledContributors; + const names = ids.map((id) => `'${id}'`).join(', '); + const contributed = ids.length === 0 + ? 'a package that contributed it may be disabled or uninstalled' + : `the ${ids.length === 1 ? 'package' : 'packages'} ${names} that contributed it ${ids.length === 1 ? 'is' : 'are'} disabled`; + return `${head}holds an amount in its parent record's currency (currencyMode: 'record', following '${first.codeField}' ` + + `through the master_detail '${path.via}'), and '${path.master}' does not serve a field '${path.code}' ` + + `(${contributed})${also}; the amount has no code to follow until that field is served again, or leave ` + + `'${first.amountField}' empty. The row was not written.`; + } + return head + + (path + ? `holds an amount in its parent record's currency (currencyMode: 'record', following '${first.codeField}' ` + + `through the master_detail '${path.via}'), and ` + + (path.master === undefined + ? `'${path.via}' is no master_detail field naming a parent object, so no parent holds its code` + : `the '${path.master}' record it names has a blank '${path.code}', or it names none`) + : `holds an amount in the record's own currency (currencyMode: 'record'), and its currency code field ` + + `'${first.codeField}' is blank`) + + also + + (path + ? `. The row was not written. Write the parent's ISO 4217 code (for example 'USD') into ` + + `'${path.master ?? path.via}.${path.code}' first, and name that parent in '${path.via}', or leave ` + + `'${first.amountField}' empty. A child stores no code of its own: it follows its parent's.` + : `. The row was not written. Write the record's ISO 4217 code (for example 'USD') into '${first.codeField}' ` + + `in the same write, or leave '${first.amountField}' empty.`) + + ` The server never fills a currency in: a form pre-fills the organization's currency, and the stored code ` + + `is always the one submitted.`; +} + /** * `ERR_CURRENCY_CODE_REQUIRED` / 400 — see the module header. Identified by * `code`, which survives crossing package boundaries. @@ -316,35 +417,25 @@ export class RecordCurrencyCodeRequiredError extends Error { /** The record-mode amount whose currency `field` holds. */ readonly amountField: string; - constructor(object: string, operation: 'insert' | 'update', hits: readonly RecordCurrencyPair[], recordId?: unknown) { - const [first] = hits; - const row = recordId === undefined || recordId === null ? '' : ` (record ${String(recordId)})`; - const path = first.path; - super( - `${operation === 'insert' ? 'Insert' : 'Update'} on '${object}'${row} was REFUSED: '${first.amountField}' ` - + (path - ? `holds an amount in its parent record's currency (currencyMode: 'record', following '${first.codeField}' ` - + `through the master_detail '${path.via}'), and ` - + (path.master === undefined - ? `'${path.via}' is no master_detail field naming a parent object, so no parent holds its code` - : `the '${path.master}' record it names has a blank '${path.code}', or it names none`) - : `holds an amount in the record's own currency (currencyMode: 'record'), and its currency code field ` - + `'${first.codeField}' is blank`) - + (hits.length > 1 ? ` (also: ${hits.slice(1).map((h) => `'${h.codeField}' for '${h.amountField}'`).join(', ')})` : '') - + (path - ? `. The row was not written. Write the parent's ISO 4217 code (for example 'USD') into ` - + `'${path.master ?? path.via}.${path.code}' first, and name that parent in '${path.via}', or leave ` - + `'${first.amountField}' empty. A child stores no code of its own: it follows its parent's.` - : `. The row was not written. Write the record's ISO 4217 code (for example 'USD') into '${first.codeField}' ` - + `in the same write, or leave '${first.amountField}' empty.`) - + ` The server never fills a currency in: a form pre-fills the organization's currency, and the stored code ` - + `is always the one submitted.`, - ); + /** + * @param unserved set when the first hit follows a parent whose object, as + * served at the write, declares no field `path.code` + * ({@link ParentCodeFieldServing}); the message then says that field is not + * served instead of asking for a code to be written into it. + */ + constructor( + object: string, + operation: 'insert' | 'update', + hits: readonly RecordCurrencyPair[], + recordId?: unknown, + unserved?: ParentCodeFieldUnserved, + ) { + super(codeRequiredMessage(object, operation, hits, recordId, unserved)); this.name = 'RecordCurrencyCodeRequiredError'; this.object = object; - this.field = first.codeField; + this.field = hits[0].codeField; this.fields = [...new Set(hits.map((h) => h.codeField))]; - this.amountField = first.amountField; + this.amountField = hits[0].amountField; } } @@ -365,6 +456,9 @@ export class RecordCurrencyCodeRequiredError extends Error { * @param touched an update's payload: only the pairs it carries an input of are judged; * omitted on insert, where every pair is judged * @param messages the write's validation message context, for the reference finding's locale + * @param parentCodeServing asked about the first refused pair's parent code field + * ({@link parentCodeFieldServingOf}): a field the parent object no longer + * serves is said so, instead of asking for a code to be written into it */ export function assertRecordCurrencyCodes( object: string, @@ -374,6 +468,7 @@ export function assertRecordCurrencyCodes( touched?: Record | null, recordId?: unknown, messages?: ValidationMessageContext, + parentCodeServing?: ParentCodeFieldServing, ): void { if (!image) return; const pairs = recordCurrencyPairs(fields); @@ -396,7 +491,10 @@ export function assertRecordCurrencyCodes( ))); } const hits = judged.filter((p) => !isBlank(image[p.amountField]) && isBlank(image[p.codeField])); - if (hits.length > 0) throw new RecordCurrencyCodeRequiredError(object, operation, hits, recordId); + if (hits.length === 0) return; + const path = hits[0].path; + const unserved = path?.master !== undefined ? parentCodeServing?.(path.master, path.code) : undefined; + throw new RecordCurrencyCodeRequiredError(object, operation, hits, recordId, unserved); } /**