diff --git a/.changeset/36794-wizard-reference-out-of-scope.md b/.changeset/36794-wizard-reference-out-of-scope.md new file mode 100644 index 00000000000..6ebed79ecea --- /dev/null +++ b/.changeset/36794-wizard-reference-out-of-scope.md @@ -0,0 +1,19 @@ +--- +'@objectstack/spec': patch +'@objectstack/core': patch +'@object-ui/plugin-grid': patch +'@object-ui/i18n': patch +--- + +feat(plugin-grid,core): the Import Wizard names the column a lookup cell was scoped by when the value belongs to another parent; a scope no read could filter by says so + +Clause-②: yes (widening) +Metadata-protocol: none + +The Import Wizard's dry run and completion screen render the import cell error `reference_out_of_scope` (#36794) with their own text, `"Design review" was found, but not under Project "Gemini"`, built from the cell error's `scope` (each scoping column by its label, with the cell the row gave it) and translated in all eleven UI locales (`grid.import.referenceOutOfScope`, `grid.import.scopeEntry`). The Wizard keys on the code and the structured `scope`, never on the server's sentence; a cell error with no `scope` shows the server's own sentence, already in the caller's locale. + +The importer no longer reports a scoped lookup as `reference_out_of_scope` when the engine refused its scoped reads because of the scope: a `dependsOn` whose `param` names a target field the engine cannot filter by (a `formula`) has every scoped read refused (`INVALID_FIELD` naming that field), so the scope was never asked. That cell keeps `reference_not_found`, with its own catalog sentence `import_reference_scope_unqueryable` in all four platform locales, which says the lookup could not be made within the scope and that the `dependsOn` entry should point at a stored target field. No unscoped probe runs for it and it carries no `scope`. A scoped lookup whose reads are all refused for any other reason (no read access to the target, say) keeps the plain `no record matches` sentence. + +Wording: `ImportRowResultSchema.errors` and the runner's `ImportRowResult.errors` now say that a `reference_out_of_scope` element carries `scope`; the error catalog page says `scope` names the row's own scoping columns, not the parent's. + +What to do: nothing. A client that matches `reference_not_found` for "the lookup cell did not resolve" keeps receiving it for the unfilterable scope. diff --git a/content/docs/api/error-catalog.mdx b/content/docs/api/error-catalog.mdx index e1d76c527ca..9cc1289bb15 100644 --- a/content/docs/api/error-catalog.mdx +++ b/content/docs/api/error-catalog.mdx @@ -930,7 +930,7 @@ snake_case, so the code and the schema property are the same word. | Presence and shape | `required`, `invalid_type`, `invalid_shape`, `unknown_field` | | Per-type parse | `invalid_boolean`, `invalid_number`, `invalid_date`, `invalid_time`, `invalid_email`, `invalid_url`, `invalid_phone`, `invalid_json`, `invalid_format` | | Bounded ranges | `min_length`, `max_length`, `min_value`, `max_value`, `max_scale`, `max_precision`, `min_items`, `max_items` | -| Closed sets and references | `invalid_option`, `value_domain` (the written value is not a member of the field's declared `valueDomain` standard), `invalid_value`, `reference_not_found`, `reference_ambiguous`, `reference_out_of_scope` (an import lookup cell whose value matches a record only under another parent than the row's own; the cell error names that parent's columns in `scope`) | +| Closed sets and references | `invalid_option`, `value_domain` (the written value is not a member of the field's declared `valueDomain` standard), `invalid_value`, `reference_not_found`, `reference_ambiguous`, `reference_out_of_scope` (an import lookup cell whose value matches a record only under another parent than the row's own; the cell error's `scope` names the row's own scoping columns and the cells the row gave them) | | Declarative rules | `rule_violation`, `json_schema_violation`, `invalid_initial_state`, `invalid_transition` | Branch on `code` to decide *how* to mark an input; show `message` to the user. diff --git a/content/docs/data-modeling/import-mappings.mdx b/content/docs/data-modeling/import-mappings.mdx index 247e0bdedb3..9d0dd701dbf 100644 --- a/content/docs/data-modeling/import-mappings.mdx +++ b/content/docs/data-modeling/import-mappings.mdx @@ -369,6 +369,15 @@ scoped lookup refused, and the cell fails with `reference_not_found`, even for a that caller can read and whose name is unique. Without the master (or the `dependsOn` sibling) in the row, the same cell resolves. +A `dependsOn` entry whose `param` names a target field the engine cannot filter by (a +`formula`) cannot scope the lookup at all: the engine refuses every scoped read, so the cell +fails with `reference_not_found` and a sentence that says the lookup could not be made within +the scope and names the cause (`Task: "Design review" could not be looked up within Project = +"Gemini": the target field this lookup's dependsOn filters by cannot be filtered on, …`), +never `reference_out_of_scope`. Point `param` at a stored field of the target. A scoped +lookup whose reads are refused for any other reason, such as no read access to the target, +keeps the plain `no record matches` sentence. + A pasted id is scoped too, so a row that means another master's detail cannot be linked in one import. Correct the master cell; or, when the cross-master link is intended, leave the master column out of the import and set it in a second update. For the diff --git a/content/docs/references/api/export.mdx b/content/docs/references/api/export.mdx index f6945cc8c9c..6c342759524 100644 --- a/content/docs/references/api/export.mdx +++ b/content/docs/references/api/export.mdx @@ -232,7 +232,7 @@ const result = CreateImportJobRequestSchema.parse(data); | **field** | `string` | optional | Field that caused a coercion/validation error (element 0 of `errors` when present) | | **code** | `string` | optional | Error code (failed rows; element 0 of `errors` when present) | | **error** | `string` | optional | Human-readable error message (failed rows; element 0 of `errors` when present) | -| **errors** | `{ field: string; code: string; message: string; rule?: string; … }[]` | optional | Every cell error of a failed row, one element per failed cell, in the validate verdict's issue shape (`field`, `code`, `message`). The list holds the import's cell-coercion errors, and a cell error never carries the advisory-only `rule` or `severity`. Present only on a failed row that has at least one cell error, so a row that failed for another reason (a duplicate or ambiguous match key, say) omits it. The first-error keys `field`, `code` and `error` stay and name element 0, so a reader of those keys sees the same answer as before. A server that does not produce this list omits the key, and the row then reports its first error only. | +| **errors** | `{ field: string; code: string; message: string; rule?: string; … }[]` | optional | Every cell error of a failed row, one element per failed cell, in the validate verdict's issue shape (`field`, `code`, `message`). The list holds the import's cell-coercion errors, and a cell error never carries the advisory-only `rule` or `severity`. A `reference_out_of_scope` cell error also carries `scope`: the row's own columns the lookup was resolved within, each with the cell the row gave it. Present only on a failed row that has at least one cell error, so a row that failed for another reason (a duplicate or ambiguous match key, say) omits it. The first-error keys `field`, `code` and `error` stay and name element 0, so a reader of those keys sees the same answer as before. A server that does not produce this list omits the key, and the row then reports its first error only. | | **warnings** | `{ field: string; code: string; message: string; rule?: string; … }[]` | optional | Findings this deployment ADMITS rather than rejects, copied verbatim from the validate verdict's row `warnings`: ADR-0104 value shapes under a warn-first posture, then the hits of advisory validation rules (`severity: 'warning'` or `'info'`, each naming its `rule` and `severity`). Set only on a dry-run row the verdict accepted: the row is `ok` because the write would store it. A committed row does not carry it: the import does not copy a write answer's `warnings` onto the row. | | **droppedFields** | `{ object: string; fields: string[]; reason: Enum<'readonly' \| 'readonly_when' \| 'primary_key' \| 'computed' \| 'stored_expression'> }[]` | optional | Write-observability: caller-supplied fields the engine LEGALLY strips from THIS row, one event per reason, in the engine's own `droppedFields` shape and reason vocabulary. A committed row reports the strips its write made. A dry-run row reports the strips its preview runs, which for a row the import would update excludes `readonlyWhen` and primary-key strips, so that row can name fewer fields than its commit. The row still succeeds: `ok` and `action` are unchanged. Present only when at least one field was dropped. A server or write path that does not produce this report omits the key too, so an absent key alone does not prove nothing was dropped. In an async job's `results`, an ok row's drops reach the reader only if the row falls inside that capped, failures-first sample. | @@ -362,7 +362,7 @@ Type: `{ sourceField: string; targetField: string; targetLabel?: string; transfo | **field** | `string` | optional | Field that caused a coercion/validation error (element 0 of `errors` when present) | | **code** | `string` | optional | Error code (failed rows; element 0 of `errors` when present) | | **error** | `string` | optional | Human-readable error message (failed rows; element 0 of `errors` when present) | -| **errors** | `{ field: string; code: string; message: string; rule?: string; … }[]` | optional | Every cell error of a failed row, one element per failed cell, in the validate verdict's issue shape (`field`, `code`, `message`). The list holds the import's cell-coercion errors, and a cell error never carries the advisory-only `rule` or `severity`. Present only on a failed row that has at least one cell error, so a row that failed for another reason (a duplicate or ambiguous match key, say) omits it. The first-error keys `field`, `code` and `error` stay and name element 0, so a reader of those keys sees the same answer as before. A server that does not produce this list omits the key, and the row then reports its first error only. | +| **errors** | `{ field: string; code: string; message: string; rule?: string; … }[]` | optional | Every cell error of a failed row, one element per failed cell, in the validate verdict's issue shape (`field`, `code`, `message`). The list holds the import's cell-coercion errors, and a cell error never carries the advisory-only `rule` or `severity`. A `reference_out_of_scope` cell error also carries `scope`: the row's own columns the lookup was resolved within, each with the cell the row gave it. Present only on a failed row that has at least one cell error, so a row that failed for another reason (a duplicate or ambiguous match key, say) omits it. The first-error keys `field`, `code` and `error` stay and name element 0, so a reader of those keys sees the same answer as before. A server that does not produce this list omits the key, and the row then reports its first error only. | | **warnings** | `{ field: string; code: string; message: string; rule?: string; … }[]` | optional | Findings this deployment ADMITS rather than rejects, copied verbatim from the validate verdict's row `warnings`: ADR-0104 value shapes under a warn-first posture, then the hits of advisory validation rules (`severity: 'warning'` or `'info'`, each naming its `rule` and `severity`). Set only on a dry-run row the verdict accepted: the row is `ok` because the write would store it. A committed row does not carry it: the import does not copy a write answer's `warnings` onto the row. | | **droppedFields** | `{ object: string; fields: string[]; reason: Enum<'readonly' \| 'readonly_when' \| 'primary_key' \| 'computed' \| 'stored_expression'> }[]` | optional | Write-observability: caller-supplied fields the engine LEGALLY strips from THIS row, one event per reason, in the engine's own `droppedFields` shape and reason vocabulary. A committed row reports the strips its write made. A dry-run row reports the strips its preview runs, which for a row the import would update excludes `readonlyWhen` and primary-key strips, so that row can name fewer fields than its commit. The row still succeeds: `ok` and `action` are unchanged. Present only when at least one field was dropped. A server or write path that does not produce this report omits the key too, so an absent key alone does not prove nothing was dropped. In an async job's `results`, an ok row's drops reach the reader only if the row falls inside that capped, failures-first sample. | @@ -382,7 +382,7 @@ Type: `{ sourceField: string; targetField: string; targetLabel?: string; transfo | **field** | `string` | optional | Field that caused a coercion/validation error (element 0 of `errors` when present) | | **code** | `string` | optional | Error code (failed rows; element 0 of `errors` when present) | | **error** | `string` | optional | Human-readable error message (failed rows; element 0 of `errors` when present) | -| **errors** | `{ field: string; code: string; message: string; rule?: string; … }[]` | optional | Every cell error of a failed row, one element per failed cell, in the validate verdict's issue shape (`field`, `code`, `message`). The list holds the import's cell-coercion errors, and a cell error never carries the advisory-only `rule` or `severity`. Present only on a failed row that has at least one cell error, so a row that failed for another reason (a duplicate or ambiguous match key, say) omits it. The first-error keys `field`, `code` and `error` stay and name element 0, so a reader of those keys sees the same answer as before. A server that does not produce this list omits the key, and the row then reports its first error only. | +| **errors** | `{ field: string; code: string; message: string; rule?: string; … }[]` | optional | Every cell error of a failed row, one element per failed cell, in the validate verdict's issue shape (`field`, `code`, `message`). The list holds the import's cell-coercion errors, and a cell error never carries the advisory-only `rule` or `severity`. A `reference_out_of_scope` cell error also carries `scope`: the row's own columns the lookup was resolved within, each with the cell the row gave it. Present only on a failed row that has at least one cell error, so a row that failed for another reason (a duplicate or ambiguous match key, say) omits it. The first-error keys `field`, `code` and `error` stay and name element 0, so a reader of those keys sees the same answer as before. A server that does not produce this list omits the key, and the row then reports its first error only. | | **warnings** | `{ field: string; code: string; message: string; rule?: string; … }[]` | optional | Findings this deployment ADMITS rather than rejects, copied verbatim from the validate verdict's row `warnings`: ADR-0104 value shapes under a warn-first posture, then the hits of advisory validation rules (`severity: 'warning'` or `'info'`, each naming its `rule` and `severity`). Set only on a dry-run row the verdict accepted: the row is `ok` because the write would store it. A committed row does not carry it: the import does not copy a write answer's `warnings` onto the row. | | **droppedFields** | `{ object: string; fields: string[]; reason: Enum<'readonly' \| 'readonly_when' \| 'primary_key' \| 'computed' \| 'stored_expression'> }[]` | optional | Write-observability: caller-supplied fields the engine LEGALLY strips from THIS row, one event per reason, in the engine's own `droppedFields` shape and reason vocabulary. A committed row reports the strips its write made. A dry-run row reports the strips its preview runs, which for a row the import would update excludes `readonlyWhen` and primary-key strips, so that row can name fewer fields than its commit. The row still succeeds: `ok` and `action` are unchanged. Present only when at least one field was dropped. A server or write path that does not produce this report omits the key too, so an absent key alone does not prove nothing was dropped. In an async job's `results`, an ok row's drops reach the reader only if the row falls inside that capped, failures-first sample. | diff --git a/packages/core/src/utils/import-coerce.ts b/packages/core/src/utils/import-coerce.ts index c59f943d038..3429b9f5eff 100644 --- a/packages/core/src/utils/import-coerce.ts +++ b/packages/core/src/utils/import-coerce.ts @@ -96,6 +96,15 @@ export interface RefMatch { * as a record under another parent. */ scopeDenied?: boolean; + /** + * [#36794] The SCOPED lookup asked nothing: no candidate read answered, and + * the engine's filter seam refused a read because the scope names a target + * field it cannot filter by (a formula), judged off that refusal's declared + * `code` and `fields`. Every other all-refused lookup is a plain miss. The + * refusal stays `reference_not_found` and says the lookup could not be made + * within the row's scope, never that the value lives under another parent. + */ + scopeUnqueryable?: boolean; } /** @@ -178,6 +187,11 @@ interface ScopedBy { * A scoped read the field-predicate guard refused (`RefMatch.scopeDenied`: the * scope names a target field the caller cannot read) is never probed: its miss * says nothing about where the value lives, so it stays `reference_not_found`. + * A scoped lookup none of whose reads answered because the engine's filter seam + * refused the scope (`RefMatch.scopeUnqueryable`: the scope names a target field + * the engine cannot filter by, such as a formula) is not probed either: it + * stays `reference_not_found` with its own sentence, which says the lookup + * could not be made within the row's scope. * * The probe is the caller's own read: the resolver runs every lookup as the * importing principal, so it can find only a record that principal can already @@ -199,9 +213,15 @@ async function referenceNotFound( // A scope the caller may not filter by was never asked: nothing is known about // where the value lives, so it is not "under another parent". if (scopedMatch.scopeDenied) return refusal; + const qualifier = scopedBy.map((s) => `${s.label} = "${s.value}"`).join(', '); + // A scope no read could filter by: say the lookup could not be made, not that nothing matched. + if (scopedMatch.scopeUnqueryable) { + return coerceError( + meta, field, 'reference_not_found', 'import_reference_scope_unqueryable', value, ctx, { scope: qualifier }, + ); + } const unscoped = normalizeRefMatch(await ctx.resolveRef(meta.reference, value, meta)); if (unscoped.id === undefined && !unscoped.ambiguous) return refusal; - const qualifier = scopedBy.map((s) => `${s.label} = "${s.value}"`).join(', '); const outOfScope = coerceError( meta, field, 'reference_out_of_scope', 'import_reference_out_of_scope', value, ctx, { scope: qualifier }, ); diff --git a/packages/core/src/utils/import-runner-reference-master-scope.test.ts b/packages/core/src/utils/import-runner-reference-master-scope.test.ts index fa7a782333b..b74b3a087a8 100644 --- a/packages/core/src/utils/import-runner-reference-master-scope.test.ts +++ b/packages/core/src/utils/import-runner-reference-master-scope.test.ts @@ -335,6 +335,68 @@ describe('[#36159] [#36794] a scoped miss whose value exists outside the row\'s for (const c of taskReads) expect(c.query!.where).toHaveProperty('project'); }); + it('a scope the engine cannot filter by (every scoped read refused): reference_not_found saying the lookup could not be made, never out of scope', async () => { + const { p, findData } = protocol(); + // The scope names a target field no driver can filter by (a formula): the + // engine's filter seam refuses every read carrying it, as INVALID_FIELD. + findData.mockImplementation(async (args: FindArgs) => { + const where = args.query!.where as Record; + if (args.object === 'xm_task' && 'project' in where) { + throw Object.assign(new Error("ObjectQL.find('xm_task') filters on 'project', a virtual formula field"), { + code: 'INVALID_FIELD', status: 400, field: 'project', fields: ['project'], + }); + } + return (ROWS[args.object] ?? []).filter((r) => matches(r, where)); + }); + // "Design review" exists, under Apollo, and the row names Gemini: still no + // out-of-scope claim, because the scoped question was never asked. + const summary = await run(p, [{ name: 'INV-1', project: 'Gemini', task: 'Design review' }]); + expect(summary.results.map(refusal)).toEqual([{ + ok: false, code: 'reference_not_found', field: 'task', + error: 'task: "Design review" could not be looked up within Project = "Gemini": the target field this lookup\'s ' + + 'dependsOn filters by cannot be filtered on, so point that dependsOn entry at a stored field', + }]); + expect(summary.results.map(cellErrors)).toEqual([[{ field: 'task', code: 'reference_not_found', scope: undefined }]]); + // No unscoped probe ran. + const taskReads = findData.mock.calls.map(([c]) => c).filter((c) => c.object === 'xm_task'); + expect(taskReads.length).toBeGreaterThan(0); + for (const c of taskReads) expect(c.query!.where).toHaveProperty('project'); + }); + + it('a scoped lookup whose every read is refused for another reason (no read on the target): the plain sentence, no cause claimed', async () => { + const { p, findData } = protocol(); + // The caller holds no read on xm_task: every read of it is refused, naming no field. + findData.mockImplementation(async (args: FindArgs) => { + if (args.object === 'xm_task') { + throw Object.assign(new Error('[Security] Access denied'), { + code: 'PERMISSION_DENIED', status: 403, details: { object: 'xm_task' }, + }); + } + return (ROWS[args.object] ?? []).filter((r) => matches(r, args.query!.where as Record)); + }); + const summary = await run(p, [{ name: 'INV-1', project: 'Gemini', task: 'Design review' }]); + expect(summary.results.map(refusal)).toEqual([ + { ok: false, code: 'reference_not_found', field: 'task', error: 'task: no record matches "Design review"' }, + ]); + expect(summary.results.map(cellErrors)).toEqual([[{ field: 'task', code: 'reference_not_found', scope: undefined }]]); + }); + + it('an INVALID_FIELD refusal naming a field outside the scope is not the scope\'s: the plain sentence', async () => { + const { p, findData } = protocol(); + findData.mockImplementation(async (args: FindArgs) => { + if (args.object === 'xm_task') { + throw Object.assign(new Error("ObjectQL.find('xm_task') filters on 'name', a virtual formula field"), { + code: 'INVALID_FIELD', status: 400, field: 'name', fields: ['name'], + }); + } + return (ROWS[args.object] ?? []).filter((r) => matches(r, args.query!.where as Record)); + }); + const summary = await run(p, [{ name: 'INV-1', project: 'Gemini', task: 'Design review' }]); + expect(summary.results.map(refusal)).toEqual([ + { ok: false, code: 'reference_not_found', field: 'task', error: 'task: no record matches "Design review"' }, + ]); + }); + it('the unscoped probe is the importing caller\'s own read, and a record that caller cannot read stays unnamed', async () => { const { p, findData } = protocol(); // The caller's reads see no Apollo task: the fake hides xm_task rows of p1 diff --git a/packages/core/src/utils/import-runner.ts b/packages/core/src/utils/import-runner.ts index 42267edb120..424d45aa56f 100644 --- a/packages/core/src/utils/import-runner.ts +++ b/packages/core/src/utils/import-runner.ts @@ -89,6 +89,8 @@ export interface ImportRowResult { /** * [#25582] Every cell error of a failed row, one element per failed cell in * column order, each `{ field, code, message }` (`ImportRowResultSchema.errors`), + * plus `scope` on a `reference_out_of_scope` cell (the row's own columns the + * lookup was resolved within, #36794), * so one import names every bad cell instead of one per re-import. Filled * only from `coerceRow`'s cell errors, where `field` / `code` / `error` above * are element 0. ⛔ Never on a validate-verdict row or a refused write: their @@ -828,6 +830,21 @@ function isScopeFieldDenial(e: unknown, scope: Readonly> return details.fields.some((f) => typeof f === 'string' && Object.prototype.hasOwnProperty.call(scope, f)); } +/** + * [#36794] Whether a scoped lookup read was refused because its scope names a + * target field the engine cannot filter by (a `formula`): the filter seam's + * refusal (`code: 'INVALID_FIELD'`, the code both filter doors declare) naming + * at least one scope field in its `fields`. Read off the error's declared + * properties, never its message, so any other refusal of the read (no read + * grant on the target, a driver fault) is not taken for this one. + */ +function isScopeFilterRefusal(e: unknown, scope: Readonly>): boolean { + const err = e as { code?: unknown; fields?: unknown; details?: { fields?: unknown } } | null; + if (err?.code !== 'INVALID_FIELD') return false; + const fields = Array.isArray(err.fields) ? err.fields : Array.isArray(err.details?.fields) ? err.details!.fields : []; + return (fields as unknown[]).some((f) => typeof f === 'string' && Object.prototype.hasOwnProperty.call(scope, f)); +} + /** * [#27465] The refusal of a match key naming a field that holds a list or a * structured value, or `undefined` when every named field can be a key. @@ -997,6 +1014,12 @@ export function runImport(opts: RunImportOptions): Promise { .filter((f) => !scope || !Object.prototype.hasOwnProperty.call(scope, f)); const lookup = async (): Promise => { let match: RefMatch = {}; + // [#36794] Whether any candidate read ran to an answer, and whether a read + // was refused because the scope names a target field the engine cannot + // filter by (a formula). A scoped lookup none of whose reads answered, and + // at least one of whose refusals said so, never asked its question. + let asked = false; + let scopeUnfilterable = false; for (const f of candidates) { try { const r = await p.findData(findArgsBase({ @@ -1006,6 +1029,7 @@ export function runImport(opts: RunImportOptions): Promise { // more conditions on the same read, run as the same caller. query: { object: referenceObject, where: { [f]: display, ...(scope ?? {}) }, limit: 2 }, })); + asked = true; const recs = findRows(r); if (recs.length === 0) continue; if (recs.length > 1) { match = { ambiguous: true, matchedField: f }; break; } @@ -1016,9 +1040,13 @@ export function runImport(opts: RunImportOptions): Promise { // about where the value lives: report it as such, never as a record // that lives under another parent. if (scope && isScopeFieldDenial(e, scope)) { match = { scopeDenied: true }; break; } + if (scope && isScopeFilterRefusal(e, scope)) scopeUnfilterable = true; /* field absent on target object — try the next candidate */ } } + // Any other refusal (no read grant on the target, a driver fault) keeps the + // plain miss: nothing says the scope column was the cause. + if (scope && !asked && scopeUnfilterable && !match.scopeDenied) match = { scopeUnqueryable: true }; return match; }; let match = await lookup(); diff --git a/packages/qa/dogfood/test/import-reference-out-of-scope.dogfood.test.ts b/packages/qa/dogfood/test/import-reference-out-of-scope.dogfood.test.ts new file mode 100644 index 00000000000..ff41f45fccd --- /dev/null +++ b/packages/qa/dogfood/test/import-reference-out-of-scope.dogfood.test.ts @@ -0,0 +1,182 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [#36794] A scoped import lookup cell (`dependsOn`) whose value names a record +// that lives only under ANOTHER parent answers `reference_out_of_scope`, with +// the row's own scoping column and its cell as data on the cell error — on a +// real boot: the real SecurityPlugin (its field-predicate guard), ObjectQL, the +// SQL driver and the REST import door. +// +// Two answers the reason must NOT give, each pinned through the real seam that +// produces it, never a fake's string: +// +// • A caller who cannot read the scope field has every scoped read refused by +// the field-predicate guard. That miss says nothing about where the value +// lives, so it stays `reference_not_found`, with no `scope`, even for a value +// that sits under the row's own parent. +// • A `dependsOn` whose `param` names a target field the engine cannot filter +// by (a formula) never asks its scoped question: `reference_not_found` with +// the sentence that says the lookup could not be made within the scope. +// +// ## Armed before anything is believed +// +// The guard is shown live first (the member's own filter on the hidden field is +// refused, the admin's is served), and the admin's in-scope row is the control +// that the scope resolves at all. +// +// Fixtures are synthetic. `@objectstack/core` (the import runner) resolves +// through its BUILT output here, so a verdict on a change to it is a verdict on +// its last build. + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { bootStack, type VerifyStack } from '@objectstack/verify'; +import { defineStack } from '@objectstack/spec'; +import { ObjectSchema, Field } from '@objectstack/spec/data'; +import { PermissionSetSchema } from '@objectstack/spec/security'; +import { SecurityPlugin, securityDefaultPermissionSets } from '@objectstack/plugin-security'; + +const SYS = { context: { isSystem: true } } as const; + +const Project = ObjectSchema.create({ + name: 'oos_project', + sharingModel: 'public_read_write', + label: 'Project', + pluralLabel: 'Projects', + fields: { name: Field.text({ label: 'Name', required: true }) }, +}); + +const Task = ObjectSchema.create({ + name: 'oos_task', + sharingModel: 'public_read_write', + label: 'Task', + pluralLabel: 'Tasks', + fields: { + name: Field.text({ label: 'Name', required: true }), + project: Field.lookup('oos_project', { label: 'Project' }), + // A computed copy of the project: a field no driver can filter by. + project_ref: Field.formula({ label: 'Project ref', expression: 'record.project', returnType: 'text' } as never), + }, +}); + +const Timesheet = ObjectSchema.create({ + name: 'oos_timesheet', + sharingModel: 'public_read_write', + label: 'Timesheet', + pluralLabel: 'Timesheets', + fields: { + name: Field.text({ label: 'Name', required: true }), + project: Field.lookup('oos_project', { label: 'Project' }), + task: Field.lookup('oos_task', { label: 'Task', dependsOn: [{ field: 'project', param: 'project' }] } as never), + // The same scope, filtered by the task's formula copy of its project. + task_by_ref: Field.lookup('oos_task', { + label: 'Task by ref', dependsOn: [{ field: 'project', param: 'project_ref' }], + } as never), + }, +}); + +const stackDef = defineStack({ + manifest: { + id: 'com.dogfood.import-reference-out-of-scope', + namespace: 'oos', + version: '0.0.0', + type: 'app', + name: 'Import Reference Out Of Scope Fixture', + description: 'A timesheet whose task lookup is scoped by its project: a task of another project is out of scope.', + }, + objects: [Project, Task, Timesheet], +}); + +const crud = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }; + +/** CRUD on every fixture object, but the task's project is hidden from this member. */ +const member = PermissionSetSchema.parse({ + name: 'oos_fixture_member', + label: 'Out-of-scope fixture member', + objects: { oos_project: crud, oos_task: crud, oos_timesheet: crud }, + fields: { 'oos_task.project': { readable: false, editable: false } }, +}); + +type CellError = { field: string; code: string; message: string; scope?: Array<{ field: string; value: string }> }; +type Row = { ok: boolean; code?: string; field?: string; error?: string; id?: string; errors?: CellError[] }; + +describe('[#36794] a scoped import lookup naming another parent\'s record answers reference_out_of_scope, on a real boot', () => { + let stack: VerifyStack; + const token: Record<'admin' | 'member', string> = { admin: '', member: '' }; + const ids: Record = {}; + + beforeAll(async () => { + stack = await bootStack(stackDef as never, { + security: new SecurityPlugin({ + defaultPermissionSets: [...securityDefaultPermissionSets, member], + fallbackPermissionSet: member.name, + }), + }); + token.admin = await stack.signIn(); + token.member = await stack.signUp('oos-member@verify.test'); + const ql = (await stack.kernel.getServiceAsync('objectql')) as any; + ids.apollo = String((await ql.insert('oos_project', { name: 'Apollo' }, SYS)).id); + ids.gemini = String((await ql.insert('oos_project', { name: 'Gemini' }, SYS)).id); + ids.design = String((await ql.insert('oos_task', { name: 'Design review', project: ids.apollo }, SYS)).id); + }, 180_000); + + afterAll(async () => { + await stack?.stop?.(); + }); + + const importAs = async (who: string, rows: object[]): Promise => { + const res = await stack.apiAs(who, 'POST', '/data/oos_timesheet/import', { format: 'json', rows }); + expect(res.status, await res.clone().text()).toBe(200); + return ((await res.json()) as { results: Row[] }).results; + }; + const cells = (r: Row) => (r.errors ?? []).map(({ field, code, scope }) => ({ field, code, scope })); + + it('ARMED — the field guard refuses the member\'s filter on the hidden scope field, and serves the admin\'s', async () => { + const asMember = await stack.apiAs(token.member, 'GET', `/data/oos_task?project=${ids.apollo}`); + expect(asMember.status, await asMember.clone().text()).toBe(403); + const asAdmin = await stack.apiAs(token.admin, 'GET', `/data/oos_task?project=${ids.apollo}`); + expect(asAdmin.status, await asAdmin.clone().text()).toBe(200); + }); + + it('admin: a task of another project is reference_out_of_scope naming Project and its cell; one nobody has stays reference_not_found', async () => { + const [inScope, outOfScope, missing] = await importAs(token.admin, [ + { name: 'TS-A1', project: 'Apollo', task: 'Design review' }, // the control: resolves under its own project + { name: 'TS-A2', project: 'Gemini', task: 'Design review' }, // Apollo's task, the row says Gemini + { name: 'TS-A3', project: 'Gemini', task: 'Retrospective' }, // no task has this name + ]); + expect(inScope!.ok, JSON.stringify(inScope)).toBe(true); + const ql = (await stack.kernel.getServiceAsync('objectql')) as any; + expect((await ql.find('oos_timesheet', { where: { id: inScope!.id }, ...SYS }))[0]?.task).toBe(ids.design); + + expect(outOfScope).toMatchObject({ + ok: false, field: 'task', code: 'reference_out_of_scope', + error: 'Task: no record matches "Design review" (Project = "Gemini")', + }); + expect(cells(outOfScope!)).toEqual([ + { field: 'task', code: 'reference_out_of_scope', scope: [{ field: 'project', value: 'Gemini' }] }, + ]); + expect(missing).toMatchObject({ ok: false, field: 'task', code: 'reference_not_found' }); + expect(missing!.errors?.[0]).not.toHaveProperty('scope'); + }); + + it('member who cannot read the scope field: reference_not_found with no scope, even for a task under the row\'s own project', async () => { + const results = await importAs(token.member, [ + { name: 'TS-M1', project: 'Apollo', task: 'Design review' }, // the task IS Apollo's + { name: 'TS-M2', project: 'Gemini', task: 'Design review' }, // the admin's out-of-scope row + ]); + for (const r of results) { + expect(r, JSON.stringify(r)).toMatchObject({ + ok: false, field: 'task', code: 'reference_not_found', error: 'Task: no record matches "Design review"', + }); + expect(cells(r)).toEqual([{ field: 'task', code: 'reference_not_found', scope: undefined }]); + } + }); + + it('a dependsOn param naming a formula the engine cannot filter by: reference_not_found saying the lookup could not be made within the scope', async () => { + const [row] = await importAs(token.admin, [{ name: 'TS-F1', project: 'Gemini', task_by_ref: 'Design review' }]); + expect(row, JSON.stringify(row)).toMatchObject({ + ok: false, field: 'task_by_ref', code: 'reference_not_found', + error: 'Task by ref: "Design review" could not be looked up within Project = "Gemini": the target field this ' + + 'lookup\'s dependsOn filters by cannot be filtered on, so point that dependsOn entry at a stored field', + }); + expect(row!.errors?.[0]).not.toHaveProperty('scope'); + }); +}); diff --git a/packages/spec/src/api/export.zod.ts b/packages/spec/src/api/export.zod.ts index 16fcf0fed24..4071d6630fc 100644 --- a/packages/spec/src/api/export.zod.ts +++ b/packages/spec/src/api/export.zod.ts @@ -431,7 +431,8 @@ export const ImportRowResultSchema = lazySchema(() => z.object({ errors: z.array(ValidateDataIssueSchema).optional().describe( 'Every cell error of a failed row, one element per failed cell, in the validate verdict\'s issue shape ' + '(`field`, `code`, `message`). The list holds the import\'s cell-coercion errors, and a cell error never ' - + 'carries the advisory-only `rule` or `severity`. ' + + 'carries the advisory-only `rule` or `severity`. A `reference_out_of_scope` cell error also carries ' + + '`scope`: the row\'s own columns the lookup was resolved within, each with the cell the row gave it. ' + 'Present only on a failed row that has at least one cell error, so a row ' + 'that failed for another reason (a duplicate or ambiguous match key, say) omits it. The first-error keys ' + '`field`, `code` and `error` stay and name element 0, so a reader of those keys sees the same answer ' diff --git a/packages/spec/src/system/validation-message.test.ts b/packages/spec/src/system/validation-message.test.ts index b8419e3941c..f63ea541faf 100644 --- a/packages/spec/src/system/validation-message.test.ts +++ b/packages/spec/src/system/validation-message.test.ts @@ -306,3 +306,28 @@ describe('import_reference_out_of_scope — names the value and the scope in eve ).toBe('合同:在 Account = "Acme" 下未找到与“CTR-0006”匹配的记录'); }); }); + +/** + * #36794 review — `import_reference_scope_unqueryable`: `reference_not_found`'s + * sentence for a scoped lookup none of whose reads ran (the scope names a target + * field the engine cannot filter by). Every locale names the value and the scope, + * and says why the lookup could not be made, never that nothing matched. + */ +describe('import_reference_scope_unqueryable — names the value and the scope in every locale', () => { + it('every locale interpolates {{value}} and {{scope}} and names dependsOn', () => { + for (const [locale, catalog] of Object.entries(BUILTIN_VALIDATION_MESSAGES)) { + const template = catalog.import_reference_scope_unqueryable; + expect(template, locale).toBeDefined(); + expect(template, locale).toContain('{{value}}'); + expect(template, locale).toContain('{{scope}}'); + expect(template, locale).toContain('dependsOn'); + } + }); + + it('renders the English sentence', () => { + const params = { value: 'Design review', scope: 'Project = "Gemini"' }; + expect(renderValidationMessage({ messageKey: 'import_reference_scope_unqueryable', label: 'Task', params })) + .toBe('Task: "Design review" could not be looked up within Project = "Gemini": the target field this lookup\'s ' + + 'dependsOn filters by cannot be filtered on, so point that dependsOn entry at a stored field'); + }); +}); diff --git a/packages/spec/src/system/validation-message.ts b/packages/spec/src/system/validation-message.ts index f2b25edd755..62ba35d1848 100644 --- a/packages/spec/src/system/validation-message.ts +++ b/packages/spec/src/system/validation-message.ts @@ -68,6 +68,14 @@ * as structured `scope` entries, so a client renders its own text from them * instead of parsing this one. * + * `import_reference_scope_unqueryable` is `reference_not_found`'s sentence for a + * scoped lookup that asked nothing: the engine's filter seam refused its reads + * because the scope names a target field the engine cannot filter by (a + * formula), as that refusal's declared `code` and `fields` say. Any other + * refusal keeps the plain sentence. The remedy names the target field the + * `dependsOn` entry filters by (its `param`), never a row column. `{{scope}}` is + * the same composition as above. + * * `import_duplicate_match_key` is the importer's ROW refusal for rows of one * file that share a match key (`DUPLICATE_MATCH_KEY`, `core/import-runner.ts`): * not a cell's failure, but a sentence in the same row report, so it is read in @@ -196,6 +204,7 @@ export const BUILTIN_VALIDATION_MESSAGES: Record> import_reference_ambiguous: '{{label}}: "{{value}}" matches more than one record — use a unique value or the record id', import_reference_not_found: '{{label}}: no record matches "{{value}}"', import_reference_out_of_scope: '{{label}}: no record matches "{{value}}" ({{scope}})', + import_reference_scope_unqueryable: '{{label}}: "{{value}}" could not be looked up within {{scope}}: the target field this lookup\'s dependsOn filters by cannot be filtered on, so point that dependsOn entry at a stored field', import_duplicate_match_key: 'Rows {{rows}} of this import have the same match key ({{label}}), so none of them was written: keep one row per key and import again', import_blank_match_key: 'The row has no match key: every key set ({{label}}) has a blank field on it', import_multi_value_match_key: 'The match key cannot use {{label}}: a match key compares one value per field, and a field holding a list or a structured value has no one value to compare — match on single-value fields (a code, a name, an email) instead', @@ -251,6 +260,7 @@ export const BUILTIN_VALIDATION_MESSAGES: Record> import_reference_ambiguous: '{{label}}:“{{value}}”匹配到多条记录,请改用唯一值或记录 ID', import_reference_not_found: '{{label}}:未找到与“{{value}}”匹配的记录', import_reference_out_of_scope: '{{label}}:在 {{scope}} 下未找到与“{{value}}”匹配的记录', + import_reference_scope_unqueryable: '{{label}}:无法在 {{scope}} 范围内查找“{{value}}”:该查找字段的 dependsOn 所筛选的目标字段无法用于筛选,请把这条 dependsOn 改为指向一个存储字段', import_duplicate_match_key: '本次导入的第 {{rows}} 行匹配键({{label}})相同,因此均未写入:每个匹配键只保留一行后重新导入', import_blank_match_key: '该行没有匹配键:每组匹配键({{label}})在该行都有空白字段', import_multi_value_match_key: '不能用{{label}}作为匹配键:匹配键每个字段只比较一个值,而列表或结构化值没有单一的值可比较,请改用单值字段(如编码、名称、邮箱)匹配', @@ -303,6 +313,7 @@ export const BUILTIN_VALIDATION_MESSAGES: Record> import_reference_ambiguous: '{{label}}:「{{value}}」に複数のレコードが一致します。一意の値かレコード ID を指定してください', import_reference_not_found: '{{label}}:「{{value}}」に一致するレコードが見つかりません', import_reference_out_of_scope: '{{label}}:{{scope}} の範囲に「{{value}}」に一致するレコードが見つかりません', + import_reference_scope_unqueryable: '{{label}}:{{scope}} の範囲で「{{value}}」を検索できません。この参照項目の dependsOn が絞り込みに使う参照先の項目では絞り込めないため、その dependsOn を保存される項目に向けてください', import_duplicate_match_key: 'このインポートの {{rows}} 行目は一致キー({{label}})が同じため、いずれも書き込まれませんでした。キーごとに 1 行だけ残して、もう一度インポートしてください', import_blank_match_key: 'この行には一致キーがありません。どの一致キーの組み合わせ({{label}})にも空欄の項目があります', import_multi_value_match_key: '{{label}} は一致キーに使えません。一致キーは項目ごとに 1 つの値を比較しますが、リストや構造化された値を持つ項目には比較できる 1 つの値がありません。単一値の項目(コード、名前、メールアドレスなど)で照合してください', @@ -355,6 +366,7 @@ export const BUILTIN_VALIDATION_MESSAGES: Record> import_reference_ambiguous: '{{label}}: «{{value}}» coincide con más de un registro; use un valor único o el id del registro', import_reference_not_found: '{{label}}: ningún registro coincide con «{{value}}»', import_reference_out_of_scope: '{{label}}: ningún registro coincide con «{{value}}» ({{scope}})', + import_reference_scope_unqueryable: '{{label}}: no se pudo buscar «{{value}}» dentro de {{scope}}: el campo de destino por el que filtra el dependsOn de esta búsqueda no se puede usar como filtro, así que apunte esa entrada de dependsOn a un campo almacenado', import_duplicate_match_key: 'Las filas {{rows}} de esta importación tienen la misma clave de coincidencia ({{label}}), así que no se escribió ninguna: deje una sola fila por clave e importe de nuevo', import_blank_match_key: 'La fila no tiene clave de coincidencia: cada conjunto de claves ({{label}}) tiene un campo vacío en ella', import_multi_value_match_key: 'La clave de coincidencia no puede usar {{label}}: una clave de coincidencia compara un valor por campo, y un campo que contiene una lista o un valor estructurado no tiene un único valor que comparar; use campos de un solo valor (un código, un nombre, un correo) en su lugar', diff --git a/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts b/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts index 21f12f8c8e8..4b7cca84297 100644 --- a/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts +++ b/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts @@ -493,7 +493,10 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // 133 once objectstack-ai/objectstack#36999 added `console.ai.focus.switchPrompt`, // the offer to ask about the record in view instead („{{target}}“) — one // interpolated span. - expect(okSpans, 'correctly paired spans').toBe(133); + // 135 once objectstack-ai/objectstack#36794 added `grid.import.referenceOutOfScope` + // („{{value}}“) and `grid.import.scopeEntry` („{{value}}“), the Import + // Wizard's line for a lookup value under another parent — two interpolated spans. + expect(okSpans, 'correctly paired spans').toBe(135); }); it('keeps the count identity that replaces the card’s count(„) === count(“)', () => { @@ -636,7 +639,9 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // 132 / 132 / 0 after objectstack-ai/objectstack#36739 removed the // checklist's `organizationName.todo` and `timezone.todo`, two pairs fewer. // 133 / 133 / 0 after objectstack-ai/objectstack#36999 added `console.ai.focus.switchPrompt`. - expect({ open, close, rdq }).toEqual({ open: 133, close: 133, rdq: 0 }); + // 135 / 135 / 0 after objectstack-ai/objectstack#36794 added `grid.import.referenceOutOfScope` + // and `grid.import.scopeEntry`. + expect({ open, close, rdq }).toEqual({ open: 135, close: 135, rdq: 0 }); // The durable shape: every „ closed by a “, every surplus “ an English // opener answered by a ”. Survived translating the two English values. expect(close).toBe(open + rdq); diff --git a/ui/packages/i18n/src/__tests__/untranslated-identity-4376.test.ts b/ui/packages/i18n/src/__tests__/untranslated-identity-4376.test.ts index 684411081b1..4f6fb4a15fe 100644 --- a/ui/packages/i18n/src/__tests__/untranslated-identity-4376.test.ts +++ b/ui/packages/i18n/src/__tests__/untranslated-identity-4376.test.ts @@ -129,6 +129,7 @@ const LEGITIMATE_IDENTITIES: Record = { 'detail.fieldChangeLabel': 'Activity field-change line label — the field hole and a separator, no prose; zh-Hans, zh-Hant and ja set a fullwidth colon, fr its space-before-colon, ko/ru/ar keep `:` as their punctuation (objectstack#36290).', 'console.firstRunChecklist.pill.count': 'Sidebar 「Get started」 pill count — the done and total holes joined by a slash, a format string with no word to translate (objectstack#36739).', 'console.changeOwner.failure': 'Change Owner report row — the row id and the server\'s own sentence joined by a colon, a format string with no word to translate; zh-Hans and fr use their own colon (objectstack#35403).', + 'grid.import.scopeEntry': 'Import Wizard scope entry — the column label and the row\'s cell in quotes, a format string with no word to translate; de, es, fr, ja, ru and ar use their own quotes, zh-Hans, zh-Hant and ko keep the straight quotes their `grid.import.*` lines use (objectstack#36794).', 'console.changeOwner.cascadeOption': 'Change Owner cascade tick — the related object and its reference field, the field in parentheses, a format string with no word to translate; zh-Hans, zh-Hant and ja use fullwidth parentheses (objectstack#35315).', // Loanwords these packs have adopted as their OWN vocabulary (checked against diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index a3eea273fc0..8efa9bd1c0b 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -850,6 +850,9 @@ const ar = { errorRowPrefix: "الصف {{row}}: ", referenceNotFound: "لا يوجد سجل مطابق لـ «{{value}}»", referenceAmbiguous: "«{{value}}» يطابق أكثر من سجل — استخدم قيمة فريدة أو معرّف السجل", + referenceOutOfScope: "تم العثور على «{{value}}»، لكن ليس ضمن {{scope}}", + scopeEntry: "{{label}} «{{value}}»", + scopeSeparator: "، ", invalidBoolean: "«{{value}}» ليست قيمة صواب/خطأ صالحة", invalidNumber: "«{{value}}» ليست رقمًا صالحًا", invalidDate: "«{{value}}» ليست تاريخًا صالحًا", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 85cb01f6d6d..70b940ba6e0 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -776,6 +776,9 @@ const de = { errorRowPrefix: "Zeile {{row}}: ", referenceNotFound: "Kein passender Datensatz für „{{value}}“", referenceAmbiguous: "„{{value}}“ passt zu mehreren Datensätzen — verwenden Sie einen eindeutigen Wert oder die Datensatz-ID", + referenceOutOfScope: "„{{value}}“ wurde gefunden, aber nicht unter {{scope}}", + scopeEntry: "{{label}} „{{value}}“", + scopeSeparator: ", ", invalidBoolean: "„{{value}}“ ist kein gültiger Wahr/Falsch-Wert", invalidNumber: "„{{value}}“ ist keine gültige Zahl", invalidDate: "„{{value}}“ ist kein gültiges Datum", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index ad149d80afa..0669c4d1ef1 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1097,6 +1097,9 @@ const en = { errorRowPrefix: 'Row {{row}}: ', referenceNotFound: 'No matching record for "{{value}}"', referenceAmbiguous: '"{{value}}" matches more than one record — use a unique value or the record id', + referenceOutOfScope: '"{{value}}" was found, but not under {{scope}}', + scopeEntry: '{{label}} "{{value}}"', + scopeSeparator: ', ', invalidBoolean: '"{{value}}" is not a valid true/false value', invalidNumber: '"{{value}}" is not a valid number', invalidDate: '"{{value}}" is not a valid date', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index bc44871fe39..ec25c2f7521 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -798,6 +798,9 @@ const es = { errorRowPrefix: "Fila {{row}}: ", referenceNotFound: "No hay ningún registro que coincida con «{{value}}»", referenceAmbiguous: "«{{value}}» coincide con más de un registro: use un valor único o el id del registro", + referenceOutOfScope: "Se encontró «{{value}}», pero no en {{scope}}", + scopeEntry: "{{label}} «{{value}}»", + scopeSeparator: ", ", invalidBoolean: "«{{value}}» no es un valor verdadero/falso válido", invalidNumber: "«{{value}}» no es un número válido", invalidDate: "«{{value}}» no es una fecha válida", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index f25f86cb702..c068cb8191e 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -793,6 +793,9 @@ const fr = { errorRowPrefix: "Ligne {{row}} : ", referenceNotFound: "Aucun enregistrement correspondant à « {{value}} »", referenceAmbiguous: "« {{value}} » correspond à plusieurs enregistrements — utilisez une valeur unique ou l'identifiant de l'enregistrement", + referenceOutOfScope: "« {{value}} » existe, mais pas sous {{scope}}", + scopeEntry: "{{label}} « {{value}} »", + scopeSeparator: ", ", invalidBoolean: "« {{value}} » n'est pas une valeur vrai/faux valide", invalidNumber: "« {{value}} » n'est pas un nombre valide", invalidDate: "« {{value}} » n'est pas une date valide", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index d25d1b388f8..4c7333b0b26 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -776,6 +776,9 @@ const ja = { errorRowPrefix: "{{row}} 行目: ", referenceNotFound: "「{{value}}」に一致するレコードがありません", referenceAmbiguous: "「{{value}}」は複数のレコードに一致します — 一意の値かレコード ID を使用してください", + referenceOutOfScope: "「{{value}}」は見つかりましたが、{{scope}} の下にはありません", + scopeEntry: "{{label}}「{{value}}」", + scopeSeparator: "、", invalidBoolean: "「{{value}}」は有効な true/false の値ではありません", invalidNumber: "「{{value}}」は有効な数値ではありません", invalidDate: "「{{value}}」は有効な日付ではありません", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 3aae4350d8c..31baa30de05 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -776,6 +776,9 @@ const ko = { errorRowPrefix: "{{row}}행: ", referenceNotFound: "\"{{value}}\"과(와) 일치하는 레코드가 없습니다", referenceAmbiguous: "\"{{value}}\"이(가) 여러 레코드와 일치합니다 — 고유한 값이나 레코드 ID를 사용하세요", + referenceOutOfScope: "\"{{value}}\"을(를) 찾았지만 {{scope}}에 속하지 않습니다", + scopeEntry: "{{label}} \"{{value}}\"", + scopeSeparator: ", ", invalidBoolean: "\"{{value}}\"은(는) 유효한 true/false 값이 아닙니다", invalidNumber: "\"{{value}}\"은(는) 유효한 숫자가 아닙니다", invalidDate: "\"{{value}}\"은(는) 유효한 날짜가 아닙니다", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index cb9e0a0ab6c..d37c6d05cb7 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -793,6 +793,9 @@ const pt = { errorRowPrefix: "Linha {{row}}: ", referenceNotFound: "Nenhum registro corresponde a \"{{value}}\"", referenceAmbiguous: "\"{{value}}\" corresponde a mais de um registro — use um valor único ou o id do registro", + referenceOutOfScope: "\"{{value}}\" foi encontrado, mas não em {{scope}}", + scopeEntry: "{{label}} \"{{value}}\"", + scopeSeparator: ", ", invalidBoolean: "\"{{value}}\" não é um valor verdadeiro/falso válido", invalidNumber: "\"{{value}}\" não é um número válido", invalidDate: "\"{{value}}\" não é uma data válida", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 6fb51e03a05..e97bf44374a 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -813,6 +813,9 @@ const ru = { errorRowPrefix: "Строка {{row}}: ", referenceNotFound: "Нет записи, соответствующей «{{value}}»", referenceAmbiguous: "«{{value}}» соответствует нескольким записям — используйте уникальное значение или идентификатор записи", + referenceOutOfScope: "«{{value}}» найдено, но не в {{scope}}", + scopeEntry: "{{label}} «{{value}}»", + scopeSeparator: ", ", invalidBoolean: "«{{value}}» не является допустимым значением true/false", invalidNumber: "«{{value}}» не является допустимым числом", invalidDate: "«{{value}}» не является допустимой датой", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index f9bb950a450..8f08ea714da 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -804,6 +804,9 @@ const zh = { // 服务端结构化导入错误的友好文案 referenceNotFound: '找不到匹配 "{{value}}" 的记录', referenceAmbiguous: '"{{value}}" 匹配到多条记录,请使用唯一值或记录 ID', + referenceOutOfScope: '找到了 "{{value}}",但它不在 {{scope}} 下', + scopeEntry: '{{label}} "{{value}}"', + scopeSeparator: '、', invalidBoolean: '"{{value}}" 不是有效的是/否值', invalidNumber: '"{{value}}" 不是有效的数字', invalidDate: '"{{value}}" 不是有效的日期', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 43b3fc4ab87..16d9c20b8c6 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -804,6 +804,9 @@ const zhHant = { // 服務端結構化匯入錯誤的友好文案 referenceNotFound: '找不到匹配 "{{value}}" 的記錄', referenceAmbiguous: '"{{value}}" 匹配到多條記錄,請使用唯一值或記錄 ID', + referenceOutOfScope: '找到了 "{{value}}",但它不在 {{scope}} 下', + scopeEntry: '{{label}} "{{value}}"', + scopeSeparator: '、', invalidBoolean: '"{{value}}" 不是有效的是/否值', invalidNumber: '"{{value}}" 不是有效的數字', invalidDate: '"{{value}}" 不是有效的日期', diff --git a/ui/packages/plugin-grid/src/ImportWizard.tsx b/ui/packages/plugin-grid/src/ImportWizard.tsx index 0aa79662408..525be815d5b 100644 --- a/ui/packages/plugin-grid/src/ImportWizard.tsx +++ b/ui/packages/plugin-grid/src/ImportWizard.tsx @@ -174,6 +174,9 @@ export const IMPORT_DEFAULT_TRANSLATIONS: Record = { // baked-in api-name and internal object name) never reaches the user. 'grid.import.referenceNotFound': 'No matching record for "{{value}}"', 'grid.import.referenceAmbiguous': '"{{value}}" matches more than one record — use a unique value or the record id', + 'grid.import.referenceOutOfScope': '"{{value}}" was found, but not under {{scope}}', + 'grid.import.scopeEntry': '{{label}} "{{value}}"', + 'grid.import.scopeSeparator': ', ', 'grid.import.invalidBoolean': '"{{value}}" is not a valid true/false value', 'grid.import.invalidNumber': '"{{value}}" is not a valid number', 'grid.import.invalidDate': '"{{value}}" is not a valid date', @@ -455,7 +458,7 @@ export interface ImportResult { totalRows: number; importedRows: number; skippedRows: number; - errors: Array<{ row: number; field: string; message: string; code?: string }>; + errors: Array<{ row: number; field: string; message: string; code?: string; scope?: CellErrorScope }>; /** Rows that created a new record (server-side import). */ createdRows?: number; /** Rows that updated an existing record (server-side import). */ @@ -573,6 +576,17 @@ function rowErrorFieldLabel(field: string | undefined, fieldLabelByName: Map[number]['scope']>; + +/** + * The `scope` of a failed row's first cell error, the one `field` / `code` / + * `error` name (`ImportRowResultSchema`): present only on `reference_out_of_scope`. + */ +function firstCellScope(r: Pick): CellErrorScope | undefined { + return r.errors?.[0]?.scope; +} + /** * Turn one failed dry-run row into a friendly, localizable error line. * @@ -586,7 +600,7 @@ function rowErrorFieldLabel(field: string | undefined, fieldLabelByName: Map:` prefix — for codes we don't recognize. */ function formatDryRunError( - r: Pick, + r: Pick & { scope?: CellErrorScope }, fieldLabelByName: Map, value: string | undefined, t: (key: string, vars?: Record) => string, @@ -600,6 +614,17 @@ function formatDryRunError( return { fieldLabel, message: t('grid.import.referenceNotFound', { value: shown }) }; case 'reference_ambiguous': return { fieldLabel, message: t('grid.import.referenceAmbiguous', { value: shown }) }; + case 'reference_out_of_scope': { + // [objectstack#36794] The value names a record under ANOTHER parent: say + // which of the row's own columns it was looked up within, from the + // structured `scope` (never the server sentence). With no scope to name, + // the server's own sentence (already in the caller's locale) is shown. + const scope = (r.scope ?? []) + .map((s) => t('grid.import.scopeEntry', { label: fieldLabelByName.get(s.field) ?? s.field, value: s.value })) + .join(t('grid.import.scopeSeparator')); + if (scope) return { fieldLabel, message: t('grid.import.referenceOutOfScope', { value: shown, scope }) }; + break; + } case 'invalid_boolean': return { fieldLabel, message: t('grid.import.invalidBoolean', { value: shown }) }; case 'invalid_number': @@ -1156,7 +1181,10 @@ function jobResultToImportResult(res: ImportJobResultsInfo): ImportResult { updatedRows: res.updated, errors: (res.results ?? []) .filter((r) => !r.ok) - .map((r) => ({ row: r.row, field: r.field ?? '', message: r.error ?? r.code ?? 'Import failed', code: r.code })), + .map((r) => ({ + row: r.row, field: r.field ?? '', message: r.error ?? r.code ?? 'Import failed', code: r.code, + ...(firstCellScope(r) ? { scope: firstCellScope(r) } : {}), + })), resultsTruncated: res.resultsTruncated, }; } @@ -2675,7 +2703,10 @@ export const ImportWizard: React.FC = ({ ); const describeFinding: DescribeFinding = (finding) => { if (finding.source === 'server') { - return formatDryRunError(finding.result, fieldLabelByName, dryRunCellValue(finding.result.row, finding.result.field), t); + return formatDryRunError( + { ...finding.result, scope: firstCellScope(finding.result) }, + fieldLabelByName, dryRunCellValue(finding.result.row, finding.result.field), t, + ); } // Named the way formatDryRunError names a server finding's field, so the // two halves of one row read alike. @@ -2936,7 +2967,10 @@ export const ImportWizard: React.FC = ({ updatedRows: res.updated, errors: res.results .filter((r) => !r.ok) - .map((r) => ({ row: r.row, field: r.field ?? '', message: r.error ?? r.code ?? 'Import failed', code: r.code })), + .map((r) => ({ + row: r.row, field: r.field ?? '', message: r.error ?? r.code ?? 'Import failed', code: r.code, + ...(firstCellScope(r) ? { scope: firstCellScope(r) } : {}), + })), serverResult: res, }; setProgress(100); @@ -3390,7 +3424,7 @@ export const ImportWizard: React.FC = ({ // server text for known codes) so the completion screen and // the pre-check read identically (objectstack#3566). const { fieldLabel, message } = formatDryRunError( - { field: err.field, error: err.message, code: err.code }, + { field: err.field, error: err.message, code: err.code, scope: err.scope }, fieldLabelByName, dryRunCellValue(err.row, err.field), t, diff --git a/ui/packages/plugin-grid/src/importAsyncPath.test.ts b/ui/packages/plugin-grid/src/importAsyncPath.test.ts index 8c6862c91a7..fee5d9e8521 100644 --- a/ui/packages/plugin-grid/src/importAsyncPath.test.ts +++ b/ui/packages/plugin-grid/src/importAsyncPath.test.ts @@ -100,6 +100,22 @@ describe('jobResultToImportResult', () => { expect(r.errors).toEqual([{ row: 5, field: 'amount', message: 'not a number', code: 'COERCE' }]); }); + it('[objectstack#36794] carries a reference_out_of_scope cell\'s scope onto the error, so the completion screen can name it', () => { + const scope = [{ field: 'project', value: 'Gemini' }]; + const r = jobResultToImportResult({ + ...base, + results: [{ + row: 2, ok: false, action: 'failed', field: 'task', code: 'reference_out_of_scope', + error: 'Task: no record matches "Design review" (Project = "Gemini")', + errors: [{ field: 'task', code: 'reference_out_of_scope', message: 'Task: no record matches "Design review" (Project = "Gemini")', scope }], + }], + }); + expect(r.errors).toEqual([{ + row: 2, field: 'task', code: 'reference_out_of_scope', + message: 'Task: no record matches "Design review" (Project = "Gemini")', scope, + }]); + }); + it('carries the resultsTruncated flag through when the server capped the report', () => { const r = jobResultToImportResult({ ...base, resultsTruncated: true, results: [] }); expect(r.resultsTruncated).toBe(true); diff --git a/ui/packages/plugin-grid/src/importDryRun.test.ts b/ui/packages/plugin-grid/src/importDryRun.test.ts index b03b6f15569..360caefb2f4 100644 --- a/ui/packages/plugin-grid/src/importDryRun.test.ts +++ b/ui/packages/plugin-grid/src/importDryRun.test.ts @@ -143,3 +143,53 @@ describe('formatDryRunError', () => { expect(message).toBe('value is out of range'); }); }); + +describe('formatDryRunError — reference_out_of_scope (objectstack#36794)', () => { + const labels = new Map([['task', '任务'], ['project', '项目']]); + const t = (key: string, vars?: Record) => + ({ + 'grid.import.referenceOutOfScope': `"${vars?.value}" was found, but not under ${vars?.scope}`, + 'grid.import.scopeEntry': `${vars?.label} "${vars?.value}"`, + 'grid.import.scopeSeparator': '; ', + 'grid.import.referenceNotFound': `No matching record for "${vars?.value}"`, + } as Record)[key] ?? key; + const serverSentence = 'task: no record matches "Design review" (Project = "Gemini")'; + + it('names the scoping column by its label and the row\'s cell, from the structured scope', () => { + const { fieldLabel, message } = formatDryRunError( + { field: 'task', code: 'reference_out_of_scope', error: serverSentence, scope: [{ field: 'project', value: 'Gemini' }] }, + labels, 'Design review', t, + ); + expect(fieldLabel).toBe('任务'); + expect(message).toBe('"Design review" was found, but not under 项目 "Gemini"'); + }); + + it('names every scoping column of a multi-column scope', () => { + const { message } = formatDryRunError( + { + field: 'task', code: 'reference_out_of_scope', error: serverSentence, + scope: [{ field: 'project', value: 'Gemini' }, { field: 'phase', value: 'P2' }], + }, + labels, 'Design review', t, + ); + // A column with no label is named by its api-name. + // Joined by the pack's own separator, never a hard-coded comma. + expect(message).toBe('"Design review" was found, but not under 项目 "Gemini"; phase "P2"'); + }); + + it('is never rendered as "no matching record"', () => { + const { message } = formatDryRunError( + { field: 'task', code: 'reference_out_of_scope', error: serverSentence, scope: [{ field: 'project', value: 'Gemini' }] }, + labels, 'Design review', t, + ); + expect(message).not.toContain('No matching record'); + }); + + it('with no scope to name, shows the server\'s own sentence minus the api-name prefix, never parsing it', () => { + const { message } = formatDryRunError( + { field: 'task', code: 'reference_out_of_scope', error: serverSentence }, + labels, 'Design review', t, + ); + expect(message).toBe('no record matches "Design review" (Project = "Gemini")'); + }); +});