Skip to content

Commit 422df61

Browse files
fix(core,plugin-grid): the duplicate-match-key import row refusal reads in the request language, and a record-level row error shows no _record: prefix (#37009)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBP9pYn3ZkhGT2R2hstwEY6w)_ Fixes #36980 Clause-②: no Metadata-protocol: none repo:objectstack#3 · os-support-ai · session_01WGufzh1FMUQYf1PcEunaaK ## 维护者速读 - 用户能看到什么变化:在控制台导入数据时,文件里两行用了同一个匹配键(比如同一个邮箱)而被拒,这条提示改用用户自己的语言,并用字段名称(如「邮箱」)代替内部字段名;被整条记录校验规则拒绝的行,不再显示内部的「_record:」前缀,只显示规则的提示语,校验预览、结果页和下载的失败行文件都一样。 - 为什么做:属于「导入体验」这一组工作,替中文用户解决导入时同一屏里中英文混杂、看到内部字段名的问题(在 HotCRM 线索导入中发现)。 - 出错会怎样:只影响这两类提示的文字,哪些行被拒、拒绝规则和写入结果都不变,可以直接撤回。 - 要你做的:无。 ## What changes **1. The duplicate-match-key row refusal reads in the request language and names the key by label** (`packages/core/src/utils/import-runner.ts`, `packages/spec/src/system/validation-message.ts`). The `DUPLICATE_MATCH_KEY` row's `error` was an English template naming the key set by API name (`email`). It is now rendered through `renderValidationMessage`, with the same request locale (`context.locale`) and the same override hook (`messageTranslator`) that the cell-coercion errors in the same row report already use. The sentence comes from a new catalog entry, `import_duplicate_match_key`, in all four platform locales (`en`, `zh-CN`, `ja-JP`, `es-ES`). It sits beside the importer's other `import_*` row sentences, and a deployment can override it under `validation.field.import_duplicate_match_key`. `{{label}}` is the key set by field label, joined with ` + `, and falls back to the API name only for a field with no label. `{{rows}}` keeps the row numbers. The row keeps its shape (`row`, `ok`, `action`, `code`, `error`), so `Clause-②: no`. The English sentence keeps its wording, with the label where the API name was. **2. A record-level row error shows no `_record:` prefix** (`ui/packages/plugin-grid/src/ImportWizard.tsx`). When an object-level validation rule names no field, the rule validator reports it on the `_record` sentinel. The wizard prefixed every row error with the field's label and fell back to the API name, so such a row read `Row 3: _record: RULE_MESSAGE`. A new `rowErrorFieldLabel` gives no label for `_record`, as the record form's save bar (`RECORD_LEVEL_FIELD` in plugin-detail) already does. It serves all three readers: the dry-run findings and the result screen (through `formatDryRunError`), and the failed-rows download. A field-level error keeps its `Label: message` form. **Bounded in-place fix, declared:** the failed-rows download prefixed a field-level error with the field's API name (`title: …`), where the two screens use the label. It now uses the same label helper. This is the same defect class (a row error naming an internal identifier), a mechanical change in the claimed file, and part of the same gate family. It is pinned in the download case below. **Existing pin updated:** `packages/rest/src/import-upsert-in-file-duplicate-key.test.ts` asserted the old sentence with API names. Its expected key set now reads by label (`Supplier + Type + No.`, `Supplier + Note`), because the fixture's fields carry those labels. This is a respelling only; every row, code and count assertion is unchanged. ADRs read near the edited lines: ADR-0104 D1/D2 (value-shape refusal wording; nothing here touches a value-shape refusal), ADR-0002 §4, ADR-0031 §4/§6, ADR-0032 §1, ADR-0077 §3, ADR-0137 D2. None governs these two sentences. **L2 contract review owed:** this PR edits non-test `packages/spec/src/**` (`validation-message.ts`). It adds one key to the built-in validation message catalog in four locales and one docblock paragraph. No Zod shape, export, error code or authorable key changes. ## Tests - `packages/core/src/utils/import-runner-duplicate-match-key-36980.test.ts` (new): in zh-CN, the row's `error` is the zh-CN catalog entry. It names `邮箱`, keeps `1, 3`, contains no `email`, and carries Han script. In en, it names `(Email)`. With no locale on the context, it reads English. A multi-field key is named by each label, and a field with no label falls back to its API name. A deployment override wins. The row result's keys are exactly `action, code, error, ok, row`. - `ui/packages/plugin-grid/src/ImportWizard.recordLevelRowError-36980.test.tsx` (new): on the dry-run findings, the result screen and the failed-rows download, a `_record` row reads as its message alone, and a field-level row reads `Title: …`. - `packages/rest/src/import-upsert-in-file-duplicate-key.test.ts`: the expected key set is now spelled by label. It runs through the real `POST /data/:object/import` route over a real SQL engine. ## Acceptance notes - **Other English row sentences in the same runner.** `BLANK_MATCH_KEY` (ordered key sets, `The row has no match key: every key set in matchFields (…)`), the multi-value match-key refusal and the `AMBIGUOUS_MATCH` text are still English and name API names. The wizard already localizes `AMBIGUOUS_MATCH` from its `code`. The other two were only read here, not reproduced through a public door, so they are noted rather than filed. They are the same family as this card. - **The download's `_error` cell** carries the server's `error` text, not the wizard's code-driven rewording that the two screens show for known cell codes. That was already the case and is unchanged here. ## Verification Two-minute check: `pnpm --filter @objectstack/core exec vitest run --maxWorkers=2 src/utils/import-runner-duplicate-match-key-36980.test.ts`. Expect 5 passed, including "zh-CN: the sentence is the zh-CN catalog entry, names the key by its label and keeps the row numbers". <details><summary>Local readings at 5ed720f</summary> - Dependency closure builds: `@objectstack/rest...` (rest and its dependencies, spec and core included) and `@object-ui/plugin-grid^...`. Lock VERDICT command-exit 0 for both. - Typecheck: `@objectstack/core`, `@objectstack/rest` (each includes `check:test-typecheck`), `@objectstack/spec` and `@object-ui/plugin-grid` `type-check` (its `tsconfig.test.json` includes `src/**`): exit 0. - Full `@objectstack/core` vitest: Test Files 165 passed (165), Tests 3854 passed (3854). - Full `@objectstack/spec` vitest: Test Files 982 passed (982), Tests 29733 passed, 1 todo. This includes `validation-message.test.ts`'s "every locale defines every message key". - `@objectstack/rest`: `import-upsert-in-file-duplicate-key.test.ts` and `import-row-cell-errors.test.ts`, Test Files 2 passed, Tests 15 passed. The rest of the rest suite is left to CI `Test Core`, since the diff there is that one test file. - UI: `pnpm --dir ui exec vitest run packages/plugin-grid/`: Test Files 311 passed (311), Tests 2763 passed (2763). `pnpm check:new-line-citations` (ui): 0 new, exit 0. - Derived gate list (`dispatch-gates.mjs --commands`, 93 commands): 92 exit 0, and 1 exit 3 (PREREQUISITE NOT MET, so NOT MEASURED): `check:dual-build-cjs-loads`, which needs a full workspace build. `--ran` with exit codes: "93 derived famil(ies) accounted for — 92 run, 1 NOT-MEASURED (1 DERIVED from a recorded exit 3)". - Ablations, each through `scripts/ablation-replace.mjs`, with the restore proven by `git diff HEAD` empty and the blob equal to HEAD: - runner key label replaced by `keySet.join(' + ')` (API names): `import-runner-duplicate-match-key-36980` 5 failed / 5; - wizard sentinel check dropped (`if (!field) return undefined;`): `ImportWizard.recordLevelRowError-36980` 3 failed / 3. - `overlap-check --branch=claude/issue-36980-import-row-errors-reader-language`: VERDICT clean exit 0. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01WGufzh1FMUQYf1PcEunaaK)_ <!-- signed: repo:objectstack#3 · os-support-ai · session_01WGufzh1FMUQYf1PcEunaaK --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 8e4ac50 commit 422df61

7 files changed

Lines changed: 307 additions & 8 deletions

File tree

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
'@objectstack/spec': patch
3+
'@objectstack/core': patch
4+
'@objectstack/rest': patch
5+
'@object-ui/plugin-grid': patch
6+
---
7+
8+
Clause-②: no
9+
Metadata-protocol: none
10+
11+
An import row refused because another row of the same file carries the same match key (`DUPLICATE_MATCH_KEY`) now reads in the importing user's language, like the cell errors beside it, and names the key by its field label (`Email`, `Supplier + Type`) instead of its API name; the row numbers stay in the sentence. The sentence is the new `import_duplicate_match_key` entry of the built-in validation message catalog (`BUILTIN_VALIDATION_MESSAGES`, in all four platform locales), so a deployment can override it under `validation.field.import_duplicate_match_key`. The row keeps its shape (`code`, `error`); only the `error` text changes. An English deployment reads the same sentence as before, with the field label where the API name was.
12+
13+
The console import wizard shows a row refused by an object-level validation rule (a rule that names no field, reported on the `_record` field) as its message alone, without a `_record:` prefix, in the dry-run findings, on the result screen and in the failed-rows download. A field-level error keeps its `Label: message` form; the failed-rows download now prefixes it with the field label too, where it used the API name.
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#36980] The `DUPLICATE_MATCH_KEY` row refusal reads in the importing
5+
* principal's language and names the key by field LABEL, as the cell-coercion
6+
* failures in the same row report already do. It is rendered from the shared
7+
* validation catalog (`validation.field.import_duplicate_match_key`) with the
8+
* request locale and the deployment's override hook; the row numbers stay in
9+
* the sentence, and the row result keeps its shape (`row`, `ok`, `action`,
10+
* `code`, `error`).
11+
*
12+
* Driven against an `ImportProtocolLike` double; the route over a real engine
13+
* is pinned in `packages/rest/src/import-upsert-in-file-duplicate-key.test.ts`.
14+
*/
15+
16+
import { describe, it, expect, vi } from 'vitest';
17+
import { renderValidationMessage, type ValidationMessageTranslator } from '@objectstack/spec/system';
18+
import { runImport, type ImportProtocolLike } from './import-runner';
19+
import type { ExportFieldMeta } from './import-field-meta.js';
20+
21+
type ValidateArgs = Parameters<NonNullable<ImportProtocolLike['validateData']>>[0];
22+
23+
const OBJECT = 'crm_lead';
24+
25+
function protocol(): ImportProtocolLike {
26+
return {
27+
findData: vi.fn(async () => []),
28+
createData: vi.fn(async (args: any) => ({ record: { id: 'r1', ...args.data } })),
29+
updateData: vi.fn(),
30+
validateData: vi.fn(async (args: ValidateArgs) => ({
31+
object: OBJECT, mode: args.mode ?? 'insert', valid: true,
32+
results: [{ valid: true, errors: [], warnings: [] }],
33+
posture: { valueShapeStrict: false, mediaValueShapeStrict: false },
34+
})),
35+
};
36+
}
37+
38+
const meta = (labels: { email?: string; company?: string }) => new Map<string, ExportFieldMeta>([
39+
['first_name', { name: 'first_name', type: 'text', label: 'First Name' }],
40+
['email', { name: 'email', type: 'email', ...(labels.email !== undefined ? { label: labels.email } : {}) }],
41+
['company', { name: 'company', type: 'text', ...(labels.company !== undefined ? { label: labels.company } : {}) }],
42+
]);
43+
44+
/** Rows 1 and 3 share the key; row 2 does not. */
45+
const ROWS = [
46+
{ first_name: 'Ada', email: 'ada@example.com', company: 'Acme' },
47+
{ first_name: 'Bob', email: 'bob@example.com', company: 'Beta' },
48+
{ first_name: 'Ada again', email: 'ada@example.com', company: 'Acme' },
49+
];
50+
51+
async function importWith(opts: {
52+
locale?: string;
53+
labels: { email?: string; company?: string };
54+
matchFields?: string[];
55+
translate?: ValidationMessageTranslator;
56+
}) {
57+
return runImport({
58+
p: protocol(),
59+
objectName: OBJECT,
60+
context: (opts.locale ? { locale: opts.locale } : {}) as any,
61+
rows: ROWS,
62+
metaMap: meta(opts.labels),
63+
...(opts.translate ? { translate: opts.translate } : {}),
64+
writeMode: 'upsert',
65+
matchFields: opts.matchFields ?? ['email'],
66+
dryRun: true,
67+
runAutomations: false,
68+
trimWhitespace: true,
69+
createMissingOptions: false,
70+
skipBlankMatchKey: false,
71+
});
72+
}
73+
74+
const expected = (label: string, locale: string) =>
75+
renderValidationMessage({ messageKey: 'import_duplicate_match_key', label, params: { rows: '1, 3' } }, { locale });
76+
77+
describe('[#36980] the duplicate-match-key row refusal reads in the request language', () => {
78+
it('zh-CN: the sentence is the zh-CN catalog entry, names the key by its label and keeps the row numbers', async () => {
79+
const s = await importWith({ locale: 'zh-CN', labels: { email: '邮箱' } });
80+
expect(s).toMatchObject({ ok: 1, errors: 2 });
81+
for (const row of [1, 3]) {
82+
const r = s.results[row - 1]!;
83+
// The row result keeps its shape: no new member.
84+
expect(Object.keys(r).sort()).toEqual(['action', 'code', 'error', 'ok', 'row']);
85+
expect(r).toMatchObject({ row, ok: false, action: 'failed', code: 'DUPLICATE_MATCH_KEY' });
86+
expect(r.error).toBe(expected('邮箱', 'zh-CN'));
87+
expect(r.error).toContain('邮箱');
88+
expect(r.error).toContain('1, 3');
89+
expect(r.error).not.toContain('email');
90+
expect(r.error).toMatch(/\p{Script=Han}/u);
91+
expect(r.error).not.toBe(expected('邮箱', 'en'));
92+
}
93+
expect(s.results[1]).toMatchObject({ row: 2, ok: true });
94+
});
95+
96+
it('en: the English sentence names the key by its label, never the API name', async () => {
97+
const s = await importWith({ locale: 'en', labels: { email: 'Email' } });
98+
const r = s.results[0]!;
99+
expect(r).toMatchObject({ code: 'DUPLICATE_MATCH_KEY', error: expected('Email', 'en') });
100+
expect(r.error).toContain('(Email)');
101+
expect(r.error).toContain('1, 3');
102+
expect(r.error).not.toMatch(/\p{Script=Han}/u);
103+
});
104+
105+
it('no locale on the context renders the English catalog entry', async () => {
106+
const s = await importWith({ labels: { email: 'Email' } });
107+
expect(s.results[0]!.error).toBe(expected('Email', 'en'));
108+
});
109+
110+
it('a key set of several fields is named by each label; a field with no label falls back to its API name', async () => {
111+
const s = await importWith({ locale: 'zh-CN', labels: { email: '邮箱' }, matchFields: ['email', 'company'] });
112+
expect(s.results[0]!.error).toBe(expected('邮箱 + company', 'zh-CN'));
113+
const labelled = await importWith({ locale: 'zh-CN', labels: { email: '邮箱', company: '公司' }, matchFields: ['email', 'company'] });
114+
expect(labelled.results[0]!.error).toBe(expected('邮箱 + 公司', 'zh-CN'));
115+
});
116+
117+
it("a deployment's `validation.field.import_duplicate_match_key` override wins, filled with the same label and rows", async () => {
118+
const translate: ValidationMessageTranslator = (key, locale) =>
119+
key === 'validation.field.import_duplicate_match_key' && locale === 'zh-CN'
120+
? '重复的匹配键 {{label}}:第 {{rows}} 行' : key;
121+
const s = await importWith({ locale: 'zh-CN', labels: { email: '邮箱' }, translate });
122+
expect(s.results[0]!.error).toBe('重复的匹配键 邮箱:第 1, 3 行');
123+
});
124+
});

‎packages/core/src/utils/import-runner.ts‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import { randomUUID } from 'node:crypto';
44
import { coerceRow, type CoerceContext, type ReferenceMaster, type RefResolver, type RefMatch } from './import-coerce.js';
55
import type { ExportFieldMeta } from './import-field-meta.js';
6-
import type { ValidationMessageTranslator } from '@objectstack/spec/system';
6+
import { renderValidationMessage, type ValidationMessageTranslator } from '@objectstack/spec/system';
77
import {
88
canServeApiOperation, isMultiValueField, isUniqueDeclared, isVirtualSearchField, referenceTargetOf, resolveDisplayField,
99
STRUCTURED_JSON_TYPES,
@@ -1070,6 +1070,23 @@ export function runImport(opts: RunImportOptions): Promise<ImportRunSummary> {
10701070
? String(context.timezone) : undefined,
10711071
};
10721072

1073+
/**
1074+
* The sentence a {@link rowsSharingKey} row is refused with, in the importing
1075+
* principal's locale through the same catalog and override hook as the cell
1076+
* failures beside it (`validation.field.import_duplicate_match_key`). The
1077+
* key set is named by field LABEL, the API name only where a field has none,
1078+
* as the cell failures name their column; the row numbers are kept.
1079+
*/
1080+
const duplicateMatchKeyMessage = (rowNos: readonly number[], keySet: readonly string[]): string =>
1081+
renderValidationMessage(
1082+
{
1083+
messageKey: 'import_duplicate_match_key',
1084+
label: keySet.map((f) => metaMap.get(f)?.label?.trim() || f).join(' + '),
1085+
params: { rows: rowNos.join(', ') },
1086+
},
1087+
{ locale: coerceCtx.locale, translate: coerceCtx.translate },
1088+
);
1089+
10731090
/**
10741091
* [#26133] The rows of this import that share a match key, each mapped to
10751092
* the row numbers carrying that key and the key set it was read by. Asked
@@ -1587,7 +1604,7 @@ export function runImport(opts: RunImportOptions): Promise<ImportRunSummary> {
15871604
errCount++;
15881605
results[i] = {
15891606
row: rowNo, ok: false, action: 'failed', code: 'DUPLICATE_MATCH_KEY',
1590-
error: `Rows ${shared.rowNos.join(', ')} of this import have the same match key (${shared.keySet.join(' + ')}), so none of them was written: keep one row per key and import again`,
1607+
error: duplicateMatchKeyMessage(shared.rowNos, shared.keySet),
15911608
};
15921609
} else {
15931610
// [#22183] This row's write context: the kept option values ride along.

‎packages/rest/src/import-upsert-in-file-duplicate-key.test.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,8 @@ const csvOf = (...lines: string[]) => ['Supplier,Type,No,Note', ...lines].join('
105105
const upsert = (csv: string, extra: Record<string, unknown> = {}) =>
106106
({ format: 'csv', csv, mapping: MAPPING, writeMode: 'upsert', matchFields: KEY, ...extra });
107107

108-
const duplicate = (row: number, rows: number[], keySet = 'supplier + cert_type + cert_no') => ({
108+
// The key set is named by field label (#36980), as the cell errors name their column.
109+
const duplicate = (row: number, rows: number[], keySet = 'Supplier + Type + No.') => ({
109110
row, ok: false, action: 'failed', code: 'DUPLICATE_MATCH_KEY',
110111
error: `Rows ${rows.join(', ')} of this import have the same match key (${keySet}), so none of them was written: keep one row per key and import again`,
111112
});
@@ -210,8 +211,8 @@ describe('[#26133] an upsert import refuses rows of its own that share a match k
210211
expect(summary.results).toEqual([
211212
{ row: 1, ok: true, action: 'created', id: expect.any(String) },
212213
{ row: 2, ok: true, action: 'created', id: expect.any(String) },
213-
duplicate(3, [3, 4], 'supplier + note'),
214-
duplicate(4, [3, 4], 'supplier + note'),
214+
duplicate(3, [3, 4], 'Supplier + Note'),
215+
duplicate(4, [3, 4], 'Supplier + Note'),
215216
]);
216217
});
217218

‎packages/spec/src/system/validation-message.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,13 @@
6060
* this issue is about; the column and the offending value are what the importer
6161
* can act on.
6262
*
63+
* `import_duplicate_match_key` is the importer's ROW refusal for rows of one
64+
* file that share a match key (`DUPLICATE_MATCH_KEY`, `core/import-runner.ts`):
65+
* not a cell's failure, but a sentence in the same row report, so it is read in
66+
* the same language. `{{label}}` is the key set by field LABEL (`Email`,
67+
* `Supplier + Type`), never the API names, and `{{rows}}` the row numbers that
68+
* carry the key, both filled by the runner.
69+
*
6370
* ## Interpolation
6471
*
6572
* `{{name}}` placeholders, matching `II18nService.t()`'s convention, filled from
@@ -162,6 +169,7 @@ export const BUILTIN_VALIDATION_MESSAGES: Record<string, Record<string, string>>
162169
import_unknown_option: '{{label}}: "{{value}}" is not a known option',
163170
import_reference_ambiguous: '{{label}}: "{{value}}" matches more than one record — use a unique value or the record id',
164171
import_reference_not_found: '{{label}}: no record matches "{{value}}"',
172+
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',
165173
},
166174
'zh-CN': {
167175
required: '{{label}}不能为空',
@@ -212,6 +220,7 @@ export const BUILTIN_VALIDATION_MESSAGES: Record<string, Record<string, string>>
212220
import_unknown_option: '{{label}}:“{{value}}”不是可选值之一',
213221
import_reference_ambiguous: '{{label}}:“{{value}}”匹配到多条记录,请改用唯一值或记录 ID',
214222
import_reference_not_found: '{{label}}:未找到与“{{value}}”匹配的记录',
223+
import_duplicate_match_key: '本次导入的第 {{rows}} 行匹配键({{label}})相同,因此均未写入:每个匹配键只保留一行后重新导入',
215224
},
216225
'ja-JP': {
217226
required: '{{label}}は必須です',
@@ -259,6 +268,7 @@ export const BUILTIN_VALIDATION_MESSAGES: Record<string, Record<string, string>>
259268
import_unknown_option: '{{label}}:「{{value}}」は選択肢にありません',
260269
import_reference_ambiguous: '{{label}}:「{{value}}」に複数のレコードが一致します。一意の値かレコード ID を指定してください',
261270
import_reference_not_found: '{{label}}:「{{value}}」に一致するレコードが見つかりません',
271+
import_duplicate_match_key: 'このインポートの {{rows}} 行目は一致キー({{label}})が同じため、いずれも書き込まれませんでした。キーごとに 1 行だけ残して、もう一度インポートしてください',
262272
},
263273
'es-ES': {
264274
required: '{{label}} es obligatorio',
@@ -306,6 +316,7 @@ export const BUILTIN_VALIDATION_MESSAGES: Record<string, Record<string, string>>
306316
import_unknown_option: '{{label}}: «{{value}}» no es una opción conocida',
307317
import_reference_ambiguous: '{{label}}: «{{value}}» coincide con más de un registro; use un valor único o el id del registro',
308318
import_reference_not_found: '{{label}}: ningún registro coincide con «{{value}}»',
319+
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',
309320
},
310321
};
311322

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
/**
2+
* ObjectUI – Copyright (c) 2024-present ObjectStack Inc.
3+
* Licensed under MIT.
4+
*/
5+
6+
/**
7+
* A record-level row error shows no `_record:` prefix (objectstack#36980).
8+
*
9+
* The rule validator attributes an object-level rule that declares no field to
10+
* the `_record` sentinel, and the import row carries it as `field`. The wizard
11+
* prefixed every row error with the field's label, falling back to the API
12+
* name, so such a row read `Row 3: _record: <rule message>`. It now shows the
13+
* message alone, as a record form's banner does, on all three surfaces that
14+
* print row errors: the dry-run findings, the result screen and the failed-rows
15+
* download. A field-level error keeps its `label: message` form.
16+
*
17+
* Driven through the real wizard and a stubbed data source.
18+
*/
19+
import { describe, it, expect, vi, afterEach } from 'vitest';
20+
import { render, screen, fireEvent, waitFor, act, within } from '@testing-library/react';
21+
import '@testing-library/jest-dom';
22+
import React from 'react';
23+
24+
import { ImportWizard } from './ImportWizard';
25+
import type { ImportRecordsResult } from '@object-ui/types';
26+
27+
type WizardField = React.ComponentProps<typeof ImportWizard>['fields'][number];
28+
29+
const FIELDS: WizardField[] = [
30+
{ name: 'title', label: 'Title', type: 'text' },
31+
{ name: 'status', label: 'Lead Status', type: 'text' },
32+
];
33+
const WAIT = { timeout: 6000 };
34+
const RULE_MESSAGE = 'A disqualified lead needs a disqualification reason';
35+
const FIELD_MESSAGE = 'must start with a capital letter';
36+
37+
afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); });
38+
39+
function pasteRows(text: string) {
40+
const evt = new Event('paste', { bubbles: true, cancelable: true }) as Event & {
41+
clipboardData: { getData: (type: string) => string };
42+
};
43+
evt.clipboardData = { getData: (type: string) => (type === 'text/plain' ? text : '') };
44+
act(() => { window.dispatchEvent(evt); });
45+
}
46+
47+
async function openPreview(dataSource: unknown) {
48+
render(<ImportWizard objectName="crm_lead" fields={FIELDS} dataSource={dataSource} open onOpenChange={() => {}} />);
49+
pasteRows('Title\tLead Status\nalpha\tOpen\nBeta\tDisqualified');
50+
const next = await screen.findByTestId('import-next-btn');
51+
await waitFor(() => expect(next).toBeEnabled());
52+
fireEvent.click(next);
53+
return screen.findByTestId('import-run-btn');
54+
}
55+
56+
/** Row 1 refused on a field, row 2 by an object-level rule. */
57+
function result(dryRun: boolean): ImportRecordsResult {
58+
return {
59+
object: 'crm_lead', dryRun, writeMode: 'insert', total: 2, ok: 0, errors: 2, created: 0, updated: 0, skipped: 0,
60+
results: [
61+
{ row: 1, ok: false, action: 'failed', field: 'title', code: 'title_capitalised', error: FIELD_MESSAGE },
62+
{ row: 2, ok: false, action: 'failed', field: '_record', code: 'disqualification_reason_required', error: RULE_MESSAGE },
63+
],
64+
};
65+
}
66+
67+
describe('ImportWizard: a record-level row error shows no `_record:` prefix (objectstack#36980)', () => {
68+
it('the dry-run findings: the record-level error is the message alone; the field-level one keeps its label', async () => {
69+
const importRecords = vi.fn().mockResolvedValue(result(true));
70+
await openPreview({ importRecords });
71+
fireEvent.click(screen.getByTestId('import-validate-btn'));
72+
await screen.findByTestId('import-validate-result');
73+
74+
const rows = within(screen.getByTestId('import-findings')).getAllByRole('listitem');
75+
expect(rows.map((r) => r.textContent)).toEqual([
76+
`Row 1: Title: ${FIELD_MESSAGE}`,
77+
`Row 2: ${RULE_MESSAGE}`,
78+
]);
79+
expect(screen.getByTestId('import-findings')).not.toHaveTextContent('_record');
80+
});
81+
82+
it('the result screen: the same two lines', async () => {
83+
const importRecords = vi.fn().mockResolvedValue(result(false));
84+
fireEvent.click(await openPreview({ importRecords }));
85+
await screen.findByTestId('import-close-btn', undefined, WAIT);
86+
87+
expect(screen.getByText(`Row 1: Title: ${FIELD_MESSAGE}`)).toBeInTheDocument();
88+
expect(screen.getByText(`Row 2: ${RULE_MESSAGE}`)).toBeInTheDocument();
89+
expect(screen.queryByText(/_record/)).not.toBeInTheDocument();
90+
});
91+
92+
it('the failed-rows download: the `_error` cell carries no `_record:`; a field error is prefixed by its label', async () => {
93+
const importRecords = vi.fn().mockResolvedValue(result(false));
94+
fireEvent.click(await openPreview({ importRecords }));
95+
await screen.findByTestId('import-close-btn', undefined, WAIT);
96+
97+
const written: string[] = [];
98+
vi.stubGlobal('Blob', class {
99+
constructor(parts: unknown[]) { written.push(parts.map(String).join('')); }
100+
});
101+
vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:36980');
102+
vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});
103+
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
104+
fireEvent.click(screen.getByTestId('import-download-failed'));
105+
106+
expect(written).toHaveLength(1);
107+
const csv = written[0]!.replace(/^\uFEFF/, '');
108+
expect(csv).not.toContain('_record');
109+
const lines = csv.split(/\r?\n/).filter(Boolean);
110+
expect(lines[0]).toBe('Title,Lead Status,_error');
111+
expect(lines[1]).toContain(`Title: ${FIELD_MESSAGE}`);
112+
expect(lines[1]).not.toContain('title:');
113+
expect(lines[2]?.endsWith(`,${RULE_MESSAGE}`)).toBe(true);
114+
});
115+
});

0 commit comments

Comments
 (0)