@fluxenginejp/sftest 2.3.0 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/pages/common/DataImportWizard.js +1 -1
- package/dist/steps/common/conditional.steps.js +9 -4
- package/dist/steps/common/data.steps.js +19 -9
- package/dist/support/apexBatch.d.ts +11 -4
- package/dist/support/apexBatch.js +32 -7
- package/dist/support/conditionalBlocks.d.ts +6 -1
- package/dist/support/conditionalBlocks.js +6 -1
- package/dist/support/csvInsert.d.ts +34 -23
- package/dist/support/csvInsert.js +218 -557
- package/dist/support/metadataCache.d.ts +51 -0
- package/dist/support/metadataCache.js +164 -0
- package/dist/support/outputPaths.d.ts +0 -8
- package/dist/support/outputPaths.js +1 -12
- package/dist/support/playwrightConfig.d.ts +0 -5
- package/dist/support/playwrightConfig.js +0 -2
- package/dist/support/settings.d.ts +25 -0
- package/dist/support/settings.js +33 -2
- package/dist/support/sf.d.ts +94 -0
- package/dist/support/sf.js +349 -7
- package/dist/support/sobjects.d.ts +3 -2
- package/dist/support/sobjects.js +7 -6
- package/docs/CHANGELOG.md +26 -0
- package/docs/SPEC.md +54 -10
- package/package.json +3 -2
|
@@ -4,15 +4,15 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.defaultCsvInsertApi = void 0;
|
|
7
|
+
exports.featureDir = featureDir;
|
|
7
8
|
exports.resolveCsvPath = resolveCsvPath;
|
|
8
9
|
exports.parseCsv = parseCsv;
|
|
9
10
|
exports.insertCsv = insertCsv;
|
|
10
|
-
exports.canonicalId = canonicalId;
|
|
11
11
|
exports.writeCsv = writeCsv;
|
|
12
12
|
/**
|
|
13
13
|
* CSV のデータを、オブジェクトのレコードとして登録する(「"<オブジェクト>" に CSV "<パス>" のデータを登録する」。20261021-005)。
|
|
14
14
|
*
|
|
15
|
-
* CSV
|
|
15
|
+
* CSV は、シナリオ(.feature)のフォルダからの相対パスで指定する(20261119-001。../ でプロジェクトのフォルダの中の別のフォルダも指せる)。書き方は Salesforce の Data Loader の登録用の CSV に合わせる
|
|
16
16
|
* (1行目は項目の API 名。項目ラベルも使える。空のセルは設定しない、#N/A は null、チェックボックスは true/false・yes/no・1/0 など)。
|
|
17
17
|
* Id は組織ごとに違うため、sfTest の拡張として、参照先を <関係名>.<項目の API 名>(Account.Name など)の列で書ける。
|
|
18
18
|
* 登録できない項目(Id・作成日・数式など)、値の誤り、ない参照先は、登録の前にシナリオ不正とする。1行でも登録に失敗したら、
|
|
@@ -21,27 +21,26 @@ exports.writeCsv = writeCsv;
|
|
|
21
21
|
* (20261114-001。writeCsv。Id か外部 ID の項目で対象を探し、空のセルは値を変えない。失敗したら作成した行を削除し、更新した行を戻す)。
|
|
22
22
|
* 登録・更新・Upsert は Salesforce CLI のユーザ(.env の SF_ORG_ALIAS)で行う。
|
|
23
23
|
*
|
|
24
|
+
* 見出しの項目への対応付け、値・参照先・一致・権限の確認、行ごとの作成か更新かの決定、送る値と送る単位の組み立ては、共通のライブラリ
|
|
25
|
+
* soql-core の表のデータの処理(prepareTableWrite・completeTableWrite・tableWriteBatches。0.2.0。SOQL Editor と同じ規則)で行う
|
|
26
|
+
* (20261119-002。2026-11-19、PO の決定 1A・2A。メッセージと判定は soql-core に合わせる)。このファイルは、CSV のファイルの読み込み、
|
|
27
|
+
* SOQL の実行、送信、失敗したときの戻し(作成した行の削除・更新した行の復元)を行う。
|
|
28
|
+
*
|
|
24
29
|
* @author Fluxengine.co.jp
|
|
25
30
|
*/
|
|
26
31
|
const node_fs_1 = require("node:fs");
|
|
27
32
|
const node_path_1 = __importDefault(require("node:path"));
|
|
33
|
+
const soql_core_1 = require("@fluxenginejp/soql-core");
|
|
28
34
|
const dataRestore_1 = require("./dataRestore");
|
|
29
35
|
const executionControl_1 = require("./executionControl");
|
|
30
|
-
const outputPaths_1 = require("./outputPaths");
|
|
31
36
|
const settings_1 = require("./settings");
|
|
32
37
|
const sf_1 = require("./sf");
|
|
33
38
|
const sobjects_1 = require("./sobjects");
|
|
34
39
|
const soqlQuery_1 = require("./soqlQuery");
|
|
35
40
|
/** REST API の基準のパス。 */
|
|
36
41
|
const API = '/services/data/v62.0';
|
|
37
|
-
/** 1
|
|
42
|
+
/** 1回の SOQL で変更前の値を読むレコードの数(Id の IN の数)。 */
|
|
38
43
|
const CHUNK = 200;
|
|
39
|
-
/** Data Loader で、値を空(null)にする書き方。 */
|
|
40
|
-
const NULL_VALUE = '#N/A';
|
|
41
|
-
/** チェックボックスの値の書き方(Data Loader と同じ。大文字・小文字は区別しない)。 */
|
|
42
|
-
const BOOLEAN_VALUES = { true: true, yes: true, y: true, on: true, '1': true, false: false, no: false, n: false, off: false, '0': false };
|
|
43
|
-
/** 数値として扱う項目の型。 */
|
|
44
|
-
const NUMBER_TYPES = new Set(['double', 'int', 'long', 'currency', 'percent']);
|
|
45
44
|
/**
|
|
46
45
|
* sObject Collections の応答を、行ごとの結果にする(登録・更新で共通。項目の誤りは項目名を添える)。
|
|
47
46
|
*
|
|
@@ -84,29 +83,83 @@ exports.defaultCsvInsertApi = {
|
|
|
84
83
|
queryExact: (soql) => (0, sf_1.sfQuery)(soql, true),
|
|
85
84
|
};
|
|
86
85
|
/**
|
|
87
|
-
* CSV
|
|
86
|
+
* 今までの CSV の置き場所(プロジェクトのフォルダの testdata)。見つからない時の案内だけに使う(20261119-001)。
|
|
87
|
+
*/
|
|
88
|
+
const LEGACY_TEST_DATA_DIR = 'testdata';
|
|
89
|
+
/**
|
|
90
|
+
* フォルダ(root)からのパス(target)が、そのフォルダの中を指すかを返す。
|
|
91
|
+
*
|
|
92
|
+
* 最初の階層が .. そのものかで判定する(..archive のように .. で始まる名前のフォルダは、中にある)。
|
|
93
|
+
*
|
|
94
|
+
* @param root - 基準のフォルダの絶対パス。
|
|
95
|
+
* @param target - 確かめるパスの絶対パス。
|
|
96
|
+
* @returns 中(root そのものを含む)なら true、外なら false。
|
|
97
|
+
*/
|
|
98
|
+
function isInside(root, target) {
|
|
99
|
+
const relative = node_path_1.default.relative(root, target);
|
|
100
|
+
return !node_path_1.default.isAbsolute(relative) && relative.split(/[\\/]/)[0] !== '..';
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* パスを、シナリオに書く形(/ 区切り)にする。
|
|
104
|
+
*
|
|
105
|
+
* @param from - 基準のフォルダの絶対パス。
|
|
106
|
+
* @param to - 示すファイルの絶対パス。
|
|
107
|
+
* @returns from からの相対パス(/ 区切り)。
|
|
108
|
+
*/
|
|
109
|
+
function scenarioPath(from, to) {
|
|
110
|
+
return node_path_1.default.relative(from, to).replace(/\\/g, '/');
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* シナリオ(.feature)があるフォルダの絶対パスを返す(20261119-001。CSV のパスの基準)。
|
|
114
|
+
*
|
|
115
|
+
* playwright-bdd は、生成したテストコードに、機能ファイルのパスを Playwright の設定ファイルのフォルダ(configDir)からの相対パスで持たせる
|
|
116
|
+
* (フィクスチャ $uri。区切りは OS のもの)。機能ファイルのフォルダのサブフォルダにある機能ファイルでは、そのサブフォルダを返す。
|
|
117
|
+
*
|
|
118
|
+
* @param bddConfig - playwright-bdd の設定(フィクスチャ $bddConfig)。configDir は絶対パス。
|
|
119
|
+
* @param uri - 機能ファイルの、設定ファイルのフォルダからの相対パス(フィクスチャ $uri)。
|
|
120
|
+
* @returns 機能ファイルがあるフォルダの絶対パス。
|
|
121
|
+
* @throws uri が空の場合(playwright-bdd が生成したテストコードの外で呼んだ場合。実行時エラー)。
|
|
122
|
+
*/
|
|
123
|
+
function featureDir(bddConfig, uri) {
|
|
124
|
+
if (!uri)
|
|
125
|
+
throw new Error('シナリオの機能ファイルのパス($uri)が分かりません(playwright-bdd が生成したテストコードの中で呼んでください)');
|
|
126
|
+
return node_path_1.default.dirname(node_path_1.default.resolve(bddConfig.configDir, uri));
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* CSV のパスを、シナリオ(.feature)のフォルダを基準とする絶対パスにする(20261119-001。2026-11-19、PO の決定 1A・3A)。
|
|
130
|
+
*
|
|
131
|
+
* パスは相対パスだけを書ける(./・../・サブフォルダ。区切りは / か \)。../ でシナリオのフォルダの外を指してもよいが、
|
|
132
|
+
* プロジェクトのフォルダの外は指せない。見つからない時、プロジェクトのフォルダの testdata(今までの置き場所)に同じパスのファイルがあれば、
|
|
133
|
+
* シナリオのフォルダからの書き方を案内する。
|
|
88
134
|
*
|
|
89
|
-
* @param
|
|
90
|
-
* @param
|
|
135
|
+
* @param csvPath - シナリオに書いたパス(ファイル名と拡張子まで)。
|
|
136
|
+
* @param baseDir - 基準のフォルダ(シナリオの .feature があるフォルダ)の絶対パス。
|
|
137
|
+
* @param projectRoot - プロジェクトのフォルダ(作業フォルダ)の絶対パス。省略時は baseDir(単体の確認で、基準のフォルダの外を禁止する場合)。
|
|
91
138
|
* @returns CSV の絶対パス。
|
|
92
|
-
* @throws
|
|
139
|
+
* @throws 空・絶対パス・プロジェクトのフォルダの外を指すパス・拡張子が .csv でない・ない・ファイルでない場合(シナリオ不正)。
|
|
93
140
|
*/
|
|
94
|
-
function resolveCsvPath(
|
|
95
|
-
const where =
|
|
96
|
-
if (!
|
|
141
|
+
function resolveCsvPath(csvPath, baseDir, projectRoot = baseDir) {
|
|
142
|
+
const where = `シナリオのフォルダ(${scenarioPath(projectRoot, baseDir) || '.'})`;
|
|
143
|
+
if (!csvPath.trim())
|
|
97
144
|
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV のパスが空です。${where}からの相対パスで、ファイル名と拡張子まで書いてください`);
|
|
98
|
-
if (node_path_1.default.isAbsolute(
|
|
99
|
-
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV のパスは、${where}からの相対パスで書いてください(絶対パスは書けません。指定値: "${
|
|
145
|
+
if (node_path_1.default.isAbsolute(csvPath) || /^[a-zA-Z]:/.test(csvPath) || /^[\\/]/.test(csvPath)) {
|
|
146
|
+
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV のパスは、${where}からの相対パスで書いてください(絶対パスは書けません。指定値: "${csvPath}")`);
|
|
100
147
|
}
|
|
101
|
-
const
|
|
102
|
-
const
|
|
103
|
-
if (!
|
|
104
|
-
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV
|
|
148
|
+
const normalized = csvPath.replace(/\\/g, '/');
|
|
149
|
+
const file = node_path_1.default.resolve(baseDir, normalized);
|
|
150
|
+
if (!isInside(projectRoot, file)) {
|
|
151
|
+
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV のパスが、プロジェクトのフォルダの外を指しています(${where}からの相対パスで書いてください。指定値: "${csvPath}")`);
|
|
105
152
|
}
|
|
106
153
|
if (node_path_1.default.extname(file).toLowerCase() !== '.csv')
|
|
107
|
-
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV のパスは、拡張子 .csv まで書いてください(指定値: "${
|
|
108
|
-
if (!(0, node_fs_1.existsSync)(file) || !(0, node_fs_1.statSync)(file).isFile())
|
|
109
|
-
|
|
154
|
+
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV のパスは、拡張子 .csv まで書いてください(指定値: "${csvPath}")`);
|
|
155
|
+
if (!(0, node_fs_1.existsSync)(file) || !(0, node_fs_1.statSync)(file).isFile()) {
|
|
156
|
+
// 今までの書き方(testdata からの相対パス)で書いたシナリオには、新しい書き方を案内する。
|
|
157
|
+
const legacy = node_path_1.default.resolve(projectRoot, LEGACY_TEST_DATA_DIR, normalized);
|
|
158
|
+
const hint = isInside(node_path_1.default.join(projectRoot, LEGACY_TEST_DATA_DIR), legacy) && (0, node_fs_1.existsSync)(legacy) && (0, node_fs_1.statSync)(legacy).isFile()
|
|
159
|
+
? `。CSV のパスは${where}から数えます。${LEGACY_TEST_DATA_DIR}/ のファイルなら "${scenarioPath(baseDir, legacy)}" と書いてください`
|
|
160
|
+
: '';
|
|
161
|
+
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${csvPath}" が${where}にありません(探した場所: ${file})${hint}`);
|
|
162
|
+
}
|
|
110
163
|
return file;
|
|
111
164
|
}
|
|
112
165
|
/**
|
|
@@ -193,212 +246,108 @@ function readUtf8(file, relativePath) {
|
|
|
193
246
|
}
|
|
194
247
|
}
|
|
195
248
|
/**
|
|
196
|
-
*
|
|
249
|
+
* soql-core の値(DmlValue)を、送る本文の値にする(数値は書いた桁のまま送るため、RawJsonNumber にする)。
|
|
197
250
|
*
|
|
198
|
-
* @param
|
|
199
|
-
* @
|
|
200
|
-
* @param objectName - オブジェクト(メッセージに使う)。
|
|
201
|
-
* @param checkCreateable - 作成できない項目を誤りにするか(登録では true。更新・Upsert では、行ごとに作成か更新かが決まってから
|
|
202
|
-
* 呼び出し元が確かめるため false。20261114-001)。
|
|
203
|
-
* @returns 列の扱い。
|
|
204
|
-
* @throws ない項目・登録できない項目・同じ項目の重複・あいまいな項目ラベル・空の見出しがある場合(シナリオ不正。該当する列をすべて示す)。
|
|
251
|
+
* @param value - soql-core が作った値。
|
|
252
|
+
* @returns 送る本文の値。
|
|
205
253
|
*/
|
|
206
|
-
function
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
continue;
|
|
216
|
-
}
|
|
217
|
-
const dot = header.indexOf('.');
|
|
218
|
-
if (dot > 0) {
|
|
219
|
-
const relationship = header.slice(0, dot).toLowerCase();
|
|
220
|
-
const field = fields.find((f) => f.type === 'reference' && f.relationshipName?.toLowerCase() === relationship);
|
|
221
|
-
if (!field) {
|
|
222
|
-
unknown.push(header);
|
|
223
|
-
continue;
|
|
224
|
-
}
|
|
225
|
-
if (checkCreateable && !field.createable)
|
|
226
|
-
notCreateable.push(`${header}(${field.name})`);
|
|
227
|
-
columns.push({ header, field, lookup: { targetField: header.slice(dot + 1), targetObjects: field.referenceTo ?? [] } });
|
|
228
|
-
continue;
|
|
229
|
-
}
|
|
230
|
-
let matches = fields.filter((f) => f.name.toLowerCase() === header.toLowerCase());
|
|
231
|
-
if (!matches.length)
|
|
232
|
-
matches = fields.filter((f) => f.label === header);
|
|
233
|
-
if (!matches.length) {
|
|
234
|
-
unknown.push(header);
|
|
235
|
-
continue;
|
|
236
|
-
}
|
|
237
|
-
if (matches.length > 1) {
|
|
238
|
-
ambiguous.push(`${header}(${matches.map((f) => f.name).join('、')})`);
|
|
239
|
-
continue;
|
|
240
|
-
}
|
|
241
|
-
if (checkCreateable && !matches[0].createable)
|
|
242
|
-
notCreateable.push(header === matches[0].name ? header : `${header}(${matches[0].name})`);
|
|
243
|
-
columns.push({ header, field: matches[0] });
|
|
244
|
-
}
|
|
245
|
-
const problems = [];
|
|
246
|
-
if (unknown.length)
|
|
247
|
-
problems.push(`"${objectName}" にない項目: ${unknown.join('、')}`);
|
|
248
|
-
if (ambiguous.length)
|
|
249
|
-
problems.push(`同じ項目ラベルの項目が複数あるため、API 名で書いてください: ${ambiguous.join('、')}`);
|
|
250
|
-
if (notCreateable.length)
|
|
251
|
-
problems.push(`登録できない項目(Id・作成日・数式・自動採番など): ${notCreateable.join('、')}。この列を CSV から消してください`);
|
|
252
|
-
const seen = new Map();
|
|
253
|
-
for (const column of columns) {
|
|
254
|
-
const other = seen.get(column.field.name);
|
|
255
|
-
if (other)
|
|
256
|
-
problems.push(`同じ項目(${column.field.name})の列が2つあります: ${other}、${column.header}`);
|
|
257
|
-
seen.set(column.field.name, column.header);
|
|
254
|
+
function bodyValue(value) {
|
|
255
|
+
switch (value.kind) {
|
|
256
|
+
case 'string':
|
|
257
|
+
case 'boolean':
|
|
258
|
+
return value.value;
|
|
259
|
+
case 'number':
|
|
260
|
+
return (0, sf_1.parseJsonExact)(value.text);
|
|
261
|
+
case 'null':
|
|
262
|
+
return null;
|
|
258
263
|
}
|
|
259
|
-
if (problems.length)
|
|
260
|
-
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV の1行目(見出し)が正しくありません:\n${problems.join('\n')}`);
|
|
261
|
-
return columns;
|
|
262
264
|
}
|
|
263
265
|
/**
|
|
264
|
-
*
|
|
266
|
+
* soql-core が作った送る1件を、組織の操作に渡すレコードの本文にする(更新は Id を含める)。
|
|
265
267
|
*
|
|
266
|
-
* @param
|
|
267
|
-
* @returns
|
|
268
|
+
* @param record - 送る1件。
|
|
269
|
+
* @returns レコードの本文(項目の API 名 → 値)。
|
|
268
270
|
*/
|
|
269
|
-
function
|
|
270
|
-
const
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
const date = new Date(Date.UTC(y, m - 1, d));
|
|
275
|
-
if (date.getUTCFullYear() !== y || date.getUTCMonth() !== m - 1 || date.getUTCDate() !== d)
|
|
276
|
-
return undefined;
|
|
277
|
-
return `${match[1]}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}`;
|
|
271
|
+
function recordBody(record) {
|
|
272
|
+
const body = record.operation === 'update' ? { Id: record.id } : {};
|
|
273
|
+
for (const [name, value] of record.fields)
|
|
274
|
+
body[name] = bodyValue(value);
|
|
275
|
+
return body;
|
|
278
276
|
}
|
|
279
277
|
/**
|
|
280
|
-
*
|
|
278
|
+
* CSV の見出しと行から、soql-core の表のデータの処理で送る内容を作る(SOQL は組織の操作で実行する)。
|
|
281
279
|
*
|
|
282
|
-
*
|
|
283
|
-
*
|
|
284
|
-
|
|
285
|
-
function dateTimeValue(value) {
|
|
286
|
-
const withOffset = /^(\d{4}-\d{2}-\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?(Z|[+-]\d{2}:?\d{2})$/.exec(value);
|
|
287
|
-
if (withOffset) {
|
|
288
|
-
// JavaScript の Date は、存在しない暦日(2026-02-30)や範囲の外の時刻を、別の日時に直してしまうため、先に確かめる(独立レビューの指摘)。
|
|
289
|
-
const [h, mi, s] = [Number(withOffset[2]), Number(withOffset[3]), Number(withOffset[4] ?? 0)];
|
|
290
|
-
const offsetMatch = /^[+-](\d{2}):?(\d{2})$/.exec(withOffset[6]);
|
|
291
|
-
if (!dateValue(withOffset[1]) || h > 23 || mi > 59 || s > 59)
|
|
292
|
-
return undefined;
|
|
293
|
-
if (offsetMatch && (Number(offsetMatch[1]) > 14 || Number(offsetMatch[2]) > 59))
|
|
294
|
-
return undefined;
|
|
295
|
-
const offset = withOffset[6] === 'Z' ? 'Z' : withOffset[6].replace(/^([+-]\d{2})(\d{2})$/, '$1:$2');
|
|
296
|
-
const time = new Date(`${withOffset[1]}T${withOffset[2]}:${withOffset[3]}:${withOffset[4] ?? '00'}.${(withOffset[5] ?? '0').padEnd(3, '0')}${offset}`);
|
|
297
|
-
return Number.isNaN(time.getTime()) ? undefined : time.toISOString();
|
|
298
|
-
}
|
|
299
|
-
const local = /^(\d{4})([-/])(\d{1,2})\2(\d{1,2})[ T](\d{1,2}):(\d{2})(?::(\d{2}))?$/.exec(value);
|
|
300
|
-
if (!local || !dateValue(`${local[1]}-${local[3]}-${local[4]}`))
|
|
301
|
-
return undefined;
|
|
302
|
-
const [h, mi, s] = [Number(local[5]), Number(local[6]), Number(local[7] ?? 0)];
|
|
303
|
-
if (h > 23 || mi > 59 || s > 59)
|
|
304
|
-
return undefined;
|
|
305
|
-
return new Date(Number(local[1]), Number(local[3]) - 1, Number(local[4]), h, mi, s).toISOString();
|
|
306
|
-
}
|
|
307
|
-
/**
|
|
308
|
-
* CSV の値を、項目の型に合わせて API の値にする。
|
|
280
|
+
* 誤りは、soql-core のメッセージ(TableInputError は表題と1件ずつの行、ほかは1文)に CSV のパスを付けてシナリオ不正にする(2026-11-19、
|
|
281
|
+
* PO の決定 2A)。参照先を探す SOQL が、参照先の項目のないオブジェクト(所有者のユーザ・キューなど複数の参照先の一部)で INVALID_FIELD に
|
|
282
|
+
* なった場合は、見つからないものとして続ける(tolerateInvalidField)。
|
|
309
283
|
*
|
|
310
|
-
* @param
|
|
311
|
-
* @param
|
|
312
|
-
* @
|
|
313
|
-
|
|
314
|
-
function apiValue(field, value) {
|
|
315
|
-
if (field.type === 'boolean') {
|
|
316
|
-
const parsed = BOOLEAN_VALUES[value.toLowerCase()];
|
|
317
|
-
return parsed === undefined ? { error: 'チェックボックスは true・false(yes・no、1・0 なども可)で書いてください' } : { value: parsed };
|
|
318
|
-
}
|
|
319
|
-
if (field.type === 'date') {
|
|
320
|
-
const date = dateValue(value);
|
|
321
|
-
return date ? { value: date } : { error: '日付は YYYY-MM-DD(または YYYY/MM/DD)で、ある日付を書いてください(月が先の 12/31/2026 などは書けません)' };
|
|
322
|
-
}
|
|
323
|
-
if (field.type === 'datetime') {
|
|
324
|
-
const time = dateTimeValue(value);
|
|
325
|
-
return time ? { value: time } : { error: '日付時刻は YYYY-MM-DDTHH:mm:ss.SSS+0900 などの時差付きの形、または YYYY-MM-DD HH:mm(実行する PC の時間帯)で書いてください' };
|
|
326
|
-
}
|
|
327
|
-
if (NUMBER_TYPES.has(field.type)) {
|
|
328
|
-
// 数値は、書いた桁のまま送る(倍精度に丸めない)。JSON の数値は整数部の先頭に余分な 0 を書けないため(000900 は JSON の数値でない)、
|
|
329
|
-
// 先頭の 0 だけを除いてから読む(小数部の桁は変えない。2026-11-14、Codex のレビューの指摘。登録・更新・Upsert で共通)。
|
|
330
|
-
return /^-?\d+(\.\d+)?$/.test(value) ? { value: (0, sf_1.parseJsonExact)(value.replace(/^(-?)0+(?=\d)/, '$1')) } : { error: '数値は、桁区切りのない数字で書いてください(例: 1000000、-12.5)' };
|
|
331
|
-
}
|
|
332
|
-
return { value };
|
|
333
|
-
}
|
|
334
|
-
/**
|
|
335
|
-
* 参照先を名前などで書いた列の値から、参照先の Id を探す。
|
|
336
|
-
*
|
|
337
|
-
* @param column - 参照先を名前などで書いた列。
|
|
338
|
-
* @param values - その列の値(空と #N/A を除いた、重なりのない値)。
|
|
284
|
+
* @param apiName - オブジェクトの API 名。
|
|
285
|
+
* @param fields - オブジェクトの項目の情報。
|
|
286
|
+
* @param records - CSV の件(1件目が見出し)。
|
|
287
|
+
* @param operation - 登録・更新・Upsert。
|
|
339
288
|
* @param api - 組織の操作。
|
|
340
|
-
* @
|
|
341
|
-
* @
|
|
289
|
+
* @param relativePath - シナリオに書いた CSV のパス(メッセージに使う)。
|
|
290
|
+
* @returns 送る内容。
|
|
291
|
+
* @throws 見出し・行・値・参照先・一致・権限の誤り、SOQL の誤り(シナリオ不正)。
|
|
342
292
|
*/
|
|
343
|
-
function
|
|
344
|
-
const
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
293
|
+
function planTableWrite(apiName, fields, records, operation, api, relativePath) {
|
|
294
|
+
const [header, ...rows] = records;
|
|
295
|
+
try {
|
|
296
|
+
const preparation = (0, soql_core_1.prepareTableWrite)({
|
|
297
|
+
objectApiName: apiName,
|
|
298
|
+
fields,
|
|
299
|
+
headers: header.cells,
|
|
300
|
+
rows: rows.map((row) => ({ cells: row.cells, line: row.line })),
|
|
301
|
+
operation,
|
|
302
|
+
});
|
|
303
|
+
const answers = preparation.queries.map((query) => {
|
|
354
304
|
try {
|
|
355
|
-
|
|
305
|
+
// 数値の外部 ID は、桁を丸めずに読む(queryExact がない組織の操作では query)。メソッドとして呼ぶ(this を保つ)。
|
|
306
|
+
return query.exact && api.queryExact ? api.queryExact(query.soql) : api.query(query.soql);
|
|
356
307
|
}
|
|
357
308
|
catch (error) {
|
|
358
309
|
if ((0, executionControl_1.isExecutionFailure)(error))
|
|
359
310
|
throw error;
|
|
360
311
|
const message = error instanceof Error ? error.message : String(error);
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
throw new executionControl_1.ExecutionFailure('scenario-invalid',
|
|
365
|
-
}
|
|
366
|
-
for (const record of records) {
|
|
367
|
-
const key = String(record[targetField] ?? '');
|
|
368
|
-
const match = values.find((v) => v.toLowerCase() === key.toLowerCase()) ?? key;
|
|
369
|
-
found.set(match, [...(found.get(match) ?? []), String(record.Id)]);
|
|
312
|
+
if (query.tolerateInvalidField && /INVALID_FIELD/.test(message))
|
|
313
|
+
return 'invalid-field';
|
|
314
|
+
const what = query.purpose === 'lookup' ? `CSV の見出し "${query.header}" の参照先` : `CSV "${relativePath}" の一致するレコード`;
|
|
315
|
+
throw new executionControl_1.ExecutionFailure('scenario-invalid', `${what}を探せません${(0, soqlQuery_1.describeQueryError)(message)}\n実行した SOQL: ${query.soql}`, { cause: error });
|
|
370
316
|
}
|
|
371
|
-
}
|
|
317
|
+
});
|
|
318
|
+
return (0, soql_core_1.completeTableWrite)(preparation, answers);
|
|
372
319
|
}
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
if (
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
320
|
+
catch (error) {
|
|
321
|
+
// 表題が項目の API 名(Id の列が…)で始まる場合は、「の」の後に空白を置く(今までのメッセージと同じ書き方)。
|
|
322
|
+
if (error instanceof soql_core_1.TableInputError)
|
|
323
|
+
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" の${/^[A-Za-z]/.test(error.message) ? ' ' : ''}${error.message}`, { cause: error });
|
|
324
|
+
if (error instanceof soql_core_1.SoqlInputError)
|
|
325
|
+
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}": ${error.message}`, { cause: error });
|
|
326
|
+
throw error;
|
|
379
327
|
}
|
|
380
|
-
return result;
|
|
381
328
|
}
|
|
382
329
|
/**
|
|
383
|
-
* CSV
|
|
330
|
+
* CSV のファイルを読み、行の数を確かめ、オブジェクトの API 名と項目の情報を得る(登録・更新・Upsert で共通)。
|
|
384
331
|
*
|
|
385
332
|
* @param objectName - オブジェクト(表示ラベルまたは API 名)。
|
|
386
|
-
* @param relativePath -
|
|
387
|
-
* @param
|
|
388
|
-
* @param
|
|
389
|
-
* @
|
|
390
|
-
* @
|
|
333
|
+
* @param relativePath - シナリオのフォルダからの相対パス。
|
|
334
|
+
* @param what - メッセージの中の操作の名前(登録・更新・Upsert)。
|
|
335
|
+
* @param api - 組織の操作。
|
|
336
|
+
* @param baseDir - 基準のフォルダ(シナリオの .feature があるフォルダ)の絶対パス。
|
|
337
|
+
* @param projectRoot - プロジェクトのフォルダの絶対パス。
|
|
338
|
+
* @returns CSV の絶対パス、件(1件目が見出し)、オブジェクトの API 名、項目の情報。
|
|
339
|
+
* @throws パス・文字コード・空・行がない・行が多すぎる・オブジェクトがない場合(シナリオ不正)。
|
|
391
340
|
*/
|
|
392
|
-
function
|
|
393
|
-
const file = resolveCsvPath(relativePath,
|
|
341
|
+
function readCsvTable(objectName, relativePath, what, api, baseDir, projectRoot) {
|
|
342
|
+
const file = resolveCsvPath(relativePath, baseDir, projectRoot);
|
|
394
343
|
const records = parseCsv(readUtf8(file, relativePath));
|
|
395
344
|
if (!records.length)
|
|
396
345
|
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" が空です。1行目に項目名を書いてください`);
|
|
397
|
-
const
|
|
398
|
-
if (!rows
|
|
399
|
-
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}"
|
|
400
|
-
if (rows
|
|
401
|
-
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" の行が ${settings_1.MAX_SOQL_ROWS} 行を超えています(${rows
|
|
346
|
+
const rows = records.length - 1;
|
|
347
|
+
if (!rows)
|
|
348
|
+
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" に${what}する行がありません(2行目から、1行に1件を書いてください)`);
|
|
349
|
+
if (rows > settings_1.MAX_SOQL_ROWS)
|
|
350
|
+
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" の行が ${settings_1.MAX_SOQL_ROWS} 行を超えています(${rows} 行)。CSV を分けてください`);
|
|
402
351
|
let apiName;
|
|
403
352
|
try {
|
|
404
353
|
apiName = api.objectApiName(objectName);
|
|
@@ -408,56 +357,29 @@ function insertCsv(objectName, relativePath, api = exports.defaultCsvInsertApi,
|
|
|
408
357
|
throw error;
|
|
409
358
|
throw new executionControl_1.ExecutionFailure('scenario-invalid', `オブジェクト "${objectName}" が見つかりません: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
410
359
|
}
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
});
|
|
426
|
-
const
|
|
427
|
-
for (const row of rows) {
|
|
428
|
-
const body = {};
|
|
429
|
-
columns.forEach((column, index) => {
|
|
430
|
-
const cell = row.cells[index];
|
|
431
|
-
if (cell === '')
|
|
432
|
-
return; // 空のセルは設定しない(Data Loader と同じ)。
|
|
433
|
-
if (cell === NULL_VALUE) {
|
|
434
|
-
body[column.field.name] = null;
|
|
435
|
-
return;
|
|
436
|
-
}
|
|
437
|
-
if (column.lookup) {
|
|
438
|
-
const resolved = lookups.get(column)?.get(cell);
|
|
439
|
-
if (resolved?.id)
|
|
440
|
-
body[column.field.name] = resolved.id;
|
|
441
|
-
else
|
|
442
|
-
problems.push(`${row.line} 行目の ${column.header}: ${resolved?.error ?? '参照先が見つかりません'}`);
|
|
443
|
-
return;
|
|
444
|
-
}
|
|
445
|
-
const converted = apiValue(column.field, cell);
|
|
446
|
-
if ('error' in converted)
|
|
447
|
-
problems.push(`${row.line} 行目の ${column.header}(値: "${cell}"): ${converted.error}`);
|
|
448
|
-
else
|
|
449
|
-
body[column.field.name] = converted.value;
|
|
450
|
-
});
|
|
451
|
-
bodies.push(body);
|
|
452
|
-
}
|
|
453
|
-
if (problems.length)
|
|
454
|
-
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" の値が正しくありません:\n${problems.join('\n')}`);
|
|
360
|
+
return { file, records, apiName, fields: api.describeFields(apiName) };
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* CSV のデータを、オブジェクトのレコードとして登録する。
|
|
364
|
+
*
|
|
365
|
+
* @param objectName - オブジェクト(表示ラベルまたは API 名)。
|
|
366
|
+
* @param relativePath - シナリオのフォルダからの相対パス(resolveCsvPath)。
|
|
367
|
+
* @param api - 組織の操作(単体の確認で差し替える)。
|
|
368
|
+
* @param baseDir - 基準のフォルダ(シナリオの .feature があるフォルダ)の絶対パス。
|
|
369
|
+
* @param projectRoot - プロジェクトのフォルダの絶対パス。省略時は baseDir。
|
|
370
|
+
* @returns 登録した行。
|
|
371
|
+
* @throws パス・文字コード・見出し・値・参照先・件数の誤り、登録の失敗(シナリオ不正。登録した行は削除して戻す)。戻せなかった場合(実行時エラー)。
|
|
372
|
+
*/
|
|
373
|
+
function insertCsv(objectName, relativePath, api = exports.defaultCsvInsertApi, baseDir, projectRoot = baseDir) {
|
|
374
|
+
const { file, records, apiName, fields } = readCsvTable(objectName, relativePath, '登録', api, baseDir, projectRoot);
|
|
375
|
+
const plan = planTableWrite(apiName, fields, records, { kind: 'insert' }, api, relativePath);
|
|
455
376
|
const inserted = [];
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
const
|
|
377
|
+
// 送る単位(200 件ずつ)は soql-core が決める。1回の呼び出しの中は、すべて登録するか、すべて登録しない。
|
|
378
|
+
for (const batch of (0, soql_core_1.tableWriteBatches)(plan)) {
|
|
379
|
+
const results = api.insertRecords(apiName, batch.records.map(recordBody));
|
|
380
|
+
const failed = results.map((r, j) => ({ ...r, line: batch.records[j].line })).filter((r) => !r.success);
|
|
459
381
|
if (!failed.length) {
|
|
460
|
-
results.forEach((r, j) => inserted.push({ line:
|
|
382
|
+
results.forEach((r, j) => inserted.push({ line: batch.records[j].line, id: r.id }));
|
|
461
383
|
continue;
|
|
462
384
|
}
|
|
463
385
|
// 1回の呼び出しの中は登録されていない。先の呼び出しで登録した行を削除して戻す。
|
|
@@ -473,319 +395,62 @@ function insertCsv(objectName, relativePath, api = exports.defaultCsvInsertApi,
|
|
|
473
395
|
}
|
|
474
396
|
return { apiName, file, inserted };
|
|
475
397
|
}
|
|
476
|
-
/** Id の形(15 桁か 18 桁の英数字)。 */
|
|
477
|
-
const ID_FORM = /^[a-zA-Z0-9]{15}(?:[a-zA-Z0-9]{3})?$/;
|
|
478
|
-
/** 18 桁の Id の末尾3桁に使われる文字(先頭15桁の大文字の位置を5桁ずつ表す)。 */
|
|
479
|
-
const ID_SUFFIX_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ012345';
|
|
480
398
|
/**
|
|
481
|
-
*
|
|
399
|
+
* soql-core が作った送る1件を、書き込む1行の内容にする。
|
|
482
400
|
*
|
|
483
|
-
*
|
|
484
|
-
*
|
|
485
|
-
*
|
|
486
|
-
* @param id - 15 桁か 18 桁の Id(ID_FORM に合うもの)。
|
|
487
|
-
* @returns 大文字・小文字を正しくした 15 桁の Id。18 桁の末尾3桁が Id の形でない場合は undefined。
|
|
401
|
+
* @param record - 送る1件。
|
|
402
|
+
* @returns 書き込む1行の内容。
|
|
488
403
|
*/
|
|
489
|
-
function
|
|
490
|
-
|
|
491
|
-
return id;
|
|
492
|
-
const suffix = id.slice(15).toUpperCase();
|
|
493
|
-
const bits = [...suffix].map((c) => ID_SUFFIX_CHARS.indexOf(c));
|
|
494
|
-
if (bits.some((b) => b < 0))
|
|
495
|
-
return undefined;
|
|
496
|
-
let result = '';
|
|
497
|
-
for (let i = 0; i < 15; i++) {
|
|
498
|
-
const upper = (bits[Math.floor(i / 5)] >> (i % 5)) & 1;
|
|
499
|
-
const c = id[i];
|
|
500
|
-
result += /[a-zA-Z]/.test(c) ? (upper ? c.toUpperCase() : c.toLowerCase()) : c;
|
|
501
|
-
}
|
|
502
|
-
return result;
|
|
503
|
-
}
|
|
504
|
-
/**
|
|
505
|
-
* 数値を、桁を失わずに比べられる形にする(整数部の先頭の 0 と小数部の末尾の 0 を除く。Number に変換しない)。
|
|
506
|
-
*
|
|
507
|
-
* @param text - 数字の文字列(-?\d+(\.\d+)?)。
|
|
508
|
-
* @returns 比べる形(例: "00123.50" → "123.5"、"-0.0" → "0")。
|
|
509
|
-
*/
|
|
510
|
-
function canonicalNumber(text) {
|
|
511
|
-
const m = /^(-?)(\d+)(?:\.(\d+))?$/.exec(text);
|
|
512
|
-
const int = m[2].replace(/^0+(?=\d)/, '');
|
|
513
|
-
const frac = (m[3] ?? '').replace(/0+$/, '');
|
|
514
|
-
const body = frac ? `${int}.${frac}` : int;
|
|
515
|
-
return body === '0' ? '0' : `${m[1]}${body}`;
|
|
516
|
-
}
|
|
517
|
-
/**
|
|
518
|
-
* 一致に使う項目の、値の比べ方を決める(Salesforce の upsert と Data Loader の照合に合わせる。2026-11-14、Codex のレビューの指摘)。
|
|
519
|
-
*
|
|
520
|
-
* - Id: 15 桁は大文字・小文字を区別し、18 桁は区別しない(canonicalId で同じ15桁にする)。
|
|
521
|
-
* - 数値の外部 ID: 数値として比べる(先頭・末尾の 0 の違いは同じ値。桁を丸めない)。SOQL には引用符なしで書く。
|
|
522
|
-
* - テキスト・メールの外部 ID: ユニークで大文字・小文字を区別しない設定の項目だけ、大文字・小文字を区別しない。それ以外は区別する。
|
|
523
|
-
*
|
|
524
|
-
* @param field - 一致に使う項目。
|
|
525
|
-
* @returns 比べ方。
|
|
526
|
-
*/
|
|
527
|
-
function keyRuleOf(field) {
|
|
528
|
-
if (field.name.toLowerCase() === 'id') {
|
|
529
|
-
return {
|
|
530
|
-
normalize: (value) => (ID_FORM.test(value) && canonicalId(value)) || { error: `Id "${value}" の形が正しくありません(15 桁か 18 桁の英数字)` },
|
|
531
|
-
literal: (value) => (0, sf_1.soqlString)(canonicalId(value) ?? value),
|
|
532
|
-
exact: false,
|
|
533
|
-
description: '15 桁は大文字・小文字を区別し、18 桁は区別しない',
|
|
534
|
-
};
|
|
535
|
-
}
|
|
536
|
-
if (NUMBER_TYPES.has(field.type)) {
|
|
537
|
-
return {
|
|
538
|
-
normalize: (value) => (/^-?\d+(\.\d+)?$/.test(value) ? canonicalNumber(value) : { error: `${field.name} "${value}" は数値の外部 ID の形ではありません(桁区切りのない数字)` }),
|
|
539
|
-
// SOQL にも、作成の本文(apiValue)と同じく整数部の余分な先頭の 0 を除いて書く(000900 → 900。2026-11-14、Codex のレビューの指摘)。
|
|
540
|
-
literal: (value) => canonicalNumber(value),
|
|
541
|
-
exact: true,
|
|
542
|
-
description: '数値として比べる',
|
|
543
|
-
};
|
|
544
|
-
}
|
|
545
|
-
const ignoreCase = field.unique === true && field.caseSensitive !== true;
|
|
546
|
-
return {
|
|
547
|
-
normalize: (value) => (ignoreCase ? value.toLowerCase() : value),
|
|
548
|
-
literal: (value) => (0, sf_1.soqlString)(value),
|
|
549
|
-
exact: false,
|
|
550
|
-
description: ignoreCase ? '大文字・小文字を区別しない(ユニークで大文字・小文字を区別しない設定の項目)' : '大文字・小文字を区別する',
|
|
551
|
-
};
|
|
404
|
+
function writePlanOf(record) {
|
|
405
|
+
return { line: record.line, operation: record.operation === 'update' ? '更新' : '作成', body: recordBody(record) };
|
|
552
406
|
}
|
|
553
407
|
/**
|
|
554
408
|
* CSV のデータで、オブジェクトのレコードを更新する、または Upsert する(20261114-001。2026-11-14、PO の決定 1A〜5A)。
|
|
555
409
|
*
|
|
556
410
|
* CSV の書き方は登録と同じ(見出しは API 名か項目ラベル、参照先は <関係名>.<項目の API 名> の列、#N/A は null)。違いは次のとおり(Data Loader と同じ)。
|
|
557
411
|
* - 一致: 更新は Id の列で、Upsert は Id か外部 ID の項目(mode.key)の列で、組織のレコードを探す。Upsert で一致がなければ作成する
|
|
558
|
-
* (Id で一致を探す Upsert では、Id が空の行を作成する)。値の比べ方は、項目の型と設定で決める(
|
|
412
|
+
* (Id で一致を探す Upsert では、Id が空の行を作成する)。値の比べ方は、項目の型と設定で決める(soql-core の tableKeyRule。Salesforce の upsert と同じ)。
|
|
559
413
|
* - 空のセル: 更新する行では、その項目の値を変えない。作成する行では、登録と同じく設定しない。#N/A は null にする。
|
|
560
414
|
* 書き込む前に、値・参照先・一致(Id が見つからない、一致が2件以上、CSV の中の重なり)・権限(作成する行は作成できる項目、更新する行は
|
|
561
|
-
*
|
|
415
|
+
* 更新できる項目)を soql-core で確かめ、誤りがあればシナリオ不正にする(書き込まない)。1行でも書き込みに失敗したら、作成した行を削除し、
|
|
562
416
|
* 更新した行を変更前の値に戻してから、シナリオ不正にする(一部だけ書き込まれた状態を残さない。登録と同じ)。送信が例外で終わった場合
|
|
563
417
|
* (反映が分からない)、戻せなかった場合は、戻せる行を戻してから実行時エラーにする(rollBack)。
|
|
564
418
|
* シナリオの終わりに自動では戻さない(戻す場合は「… の状態を記憶し、シナリオの終わりに戻す」と組み合わせる)。
|
|
565
419
|
*
|
|
566
420
|
* @param objectName - オブジェクト(表示ラベルまたは API 名)。
|
|
567
|
-
* @param relativePath -
|
|
421
|
+
* @param relativePath - シナリオのフォルダからの相対パス(resolveCsvPath)。
|
|
568
422
|
* @param mode - 更新か、Upsert と一致に使う項目(Id、または外部 ID の項目の API 名か項目ラベル)。
|
|
569
423
|
* @param api - 組織の操作(単体の確認で差し替える)。
|
|
570
|
-
* @param
|
|
424
|
+
* @param baseDir - 基準のフォルダ(シナリオの .feature があるフォルダ)の絶対パス。
|
|
425
|
+
* @param projectRoot - プロジェクトのフォルダの絶対パス。省略時は baseDir。
|
|
571
426
|
* @returns 書き込んだ行。
|
|
572
427
|
* @throws パス・文字コード・見出し・値・参照先・一致・権限・件数の誤り、書き込みの失敗(シナリオ不正。書き込んだ行は戻す)。戻せなかった場合(実行時エラー)。
|
|
573
428
|
*/
|
|
574
|
-
function writeCsv(objectName, relativePath, mode, api = exports.defaultCsvInsertApi,
|
|
429
|
+
function writeCsv(objectName, relativePath, mode, api = exports.defaultCsvInsertApi, baseDir, projectRoot = baseDir) {
|
|
575
430
|
// メッセージの中の操作の名前(英字の Upsert は、前後に空白を置く)。
|
|
576
431
|
const what = mode.kind === 'update' ? '更新' : ' Upsert ';
|
|
577
|
-
const file = resolveCsvPath(relativePath, root);
|
|
578
|
-
const records = parseCsv(readUtf8(file, relativePath));
|
|
579
|
-
if (!records.length)
|
|
580
|
-
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" が空です。1行目に項目名を書いてください`);
|
|
581
|
-
const [header, ...rows] = records;
|
|
582
|
-
if (!rows.length)
|
|
583
|
-
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" に${what}する行がありません(2行目から、1行に1件を書いてください)`);
|
|
584
|
-
if (rows.length > settings_1.MAX_SOQL_ROWS)
|
|
585
|
-
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" の行が ${settings_1.MAX_SOQL_ROWS} 行を超えています(${rows.length} 行)。CSV を分けてください`);
|
|
586
432
|
if (!api.updateRecords || !api.restoreRecords)
|
|
587
433
|
throw new Error('組織の操作に、更新と変更前の値に戻す処理がありません');
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
}
|
|
592
|
-
catch (error) {
|
|
593
|
-
if ((0, executionControl_1.isExecutionFailure)(error))
|
|
594
|
-
throw error;
|
|
595
|
-
throw new executionControl_1.ExecutionFailure('scenario-invalid', `オブジェクト "${objectName}" が見つかりません: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
596
|
-
}
|
|
597
|
-
const fields = api.describeFields(apiName);
|
|
598
|
-
const keyField = resolveKeyField(mode, fields, objectName);
|
|
599
|
-
const byId = keyField.name.toLowerCase() === 'id';
|
|
600
|
-
const columns = mapColumns(header.cells, fields, objectName, false);
|
|
601
|
-
const keyIndex = columns.findIndex((c) => !c.lookup && c.field.name === keyField.name);
|
|
602
|
-
if (keyIndex < 0)
|
|
603
|
-
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" に、${mode.kind === 'update' ? '更新' : 'Upsert '}の一致に使う列 "${keyField.name}" がありません(1行目に ${keyField.name} の列を書いてください)`);
|
|
604
|
-
const problems = [];
|
|
605
|
-
for (const row of rows)
|
|
606
|
-
if (row.cells.length !== columns.length)
|
|
607
|
-
problems.push(`${row.line} 行目: 列の数が見出しと違います(見出し ${columns.length} 列、この行 ${row.cells.length} 列)`);
|
|
608
|
-
if (problems.length)
|
|
609
|
-
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" の行が正しくありません:\n${problems.join('\n')}`);
|
|
610
|
-
// 一致に使う値を確かめる(形・空・CSV の中の重なり)。比べ方は項目の型と設定で決める(keyRuleOf)。
|
|
611
|
-
const rule = keyRuleOf(keyField);
|
|
612
|
-
const keyOf = (row) => row.cells[keyIndex].trim();
|
|
613
|
-
const hasKey = (key) => key !== '' && key !== NULL_VALUE;
|
|
614
|
-
const normalizedKeys = new Map();
|
|
615
|
-
const seenKeys = new Map();
|
|
616
|
-
for (const row of rows) {
|
|
617
|
-
const key = keyOf(row);
|
|
618
|
-
if (!hasKey(key)) {
|
|
619
|
-
if (!(mode.kind === 'upsert' && byId))
|
|
620
|
-
problems.push(`${row.line} 行目: ${keyField.name} が空です(${what}する行には ${keyField.name} を書いてください)`);
|
|
621
|
-
continue;
|
|
622
|
-
}
|
|
623
|
-
const normalized = rule.normalize(key);
|
|
624
|
-
if (typeof normalized !== 'string') {
|
|
625
|
-
problems.push(`${row.line} 行目: ${normalized.error}`);
|
|
626
|
-
continue;
|
|
627
|
-
}
|
|
628
|
-
normalizedKeys.set(row, normalized);
|
|
629
|
-
const first = seenKeys.get(normalized);
|
|
630
|
-
if (first !== undefined)
|
|
631
|
-
problems.push(`${row.line} 行目: ${keyField.name} "${key}" が ${first} 行目と重なっています(同じレコードを2回書けません。${rule.description})`);
|
|
632
|
-
else
|
|
633
|
-
seenKeys.set(normalized, row.line);
|
|
634
|
-
}
|
|
635
|
-
if (problems.length)
|
|
636
|
-
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" の ${keyField.name} の列が正しくありません:\n${problems.join('\n')}`);
|
|
637
|
-
// 組織の一致するレコードを探す(比べる形の値 → レコードの Id)。
|
|
638
|
-
const existing = findExisting(apiName, keyField.name, rule, rows.filter((row) => normalizedKeys.has(row)).map(keyOf), api, relativePath);
|
|
639
|
-
// 参照先を名前などで書いた列は、値ごとに参照先を探す(登録と同じ)。
|
|
640
|
-
const lookups = new Map();
|
|
641
|
-
columns.forEach((column, index) => {
|
|
642
|
-
if (!column.lookup)
|
|
643
|
-
return;
|
|
644
|
-
const values = [...new Set(rows.map((row) => row.cells[index]).filter((v) => v !== '' && v !== NULL_VALUE))];
|
|
645
|
-
lookups.set(column, values.length ? resolveLookups(column, values, api) : new Map());
|
|
646
|
-
});
|
|
647
|
-
// 行ごとに作成か更新かを決め、送る値を作る。
|
|
648
|
-
const plans = [];
|
|
649
|
-
const denied = new Map();
|
|
650
|
-
for (const row of rows) {
|
|
651
|
-
const key = keyOf(row);
|
|
652
|
-
const normalized = normalizedKeys.get(row);
|
|
653
|
-
const id = normalized === undefined ? undefined : existing.get(normalized);
|
|
654
|
-
if (!id && hasKey(key) && (mode.kind === 'update' || byId)) {
|
|
655
|
-
const hint = mode.kind === 'update' ? '削除済み、または別のオブジェクトの Id' : 'Id で一致を探す Upsert では、作成する行の Id を空にします';
|
|
656
|
-
problems.push(`${row.line} 行目: Id "${key}" のレコードが "${objectName}" にありません(${hint})`);
|
|
657
|
-
continue;
|
|
658
|
-
}
|
|
659
|
-
const operation = id ? '更新' : '作成';
|
|
660
|
-
const body = id ? { Id: id } : {};
|
|
661
|
-
columns.forEach((column, index) => {
|
|
662
|
-
// Id の列と、更新する行の外部 ID の値は送らない(一致に使った値のまま)。
|
|
663
|
-
if (index === keyIndex && (byId || id))
|
|
664
|
-
return;
|
|
665
|
-
const cell = row.cells[index];
|
|
666
|
-
// 空のセルは、更新する行では値を変えず、作成する行では設定しない(Data Loader と同じ)。
|
|
667
|
-
if (cell === '')
|
|
668
|
-
return;
|
|
669
|
-
const allowed = operation === '更新' ? column.field.updateable === true : column.field.createable;
|
|
670
|
-
if (!allowed) {
|
|
671
|
-
const label = `${operation}できない項目 ${column.header}(${column.field.name})`;
|
|
672
|
-
denied.set(label, [...(denied.get(label) ?? []), row.line]);
|
|
673
|
-
return;
|
|
674
|
-
}
|
|
675
|
-
if (cell === NULL_VALUE) {
|
|
676
|
-
body[column.field.name] = null;
|
|
677
|
-
return;
|
|
678
|
-
}
|
|
679
|
-
if (column.lookup) {
|
|
680
|
-
const resolved = lookups.get(column)?.get(cell);
|
|
681
|
-
if (resolved?.id)
|
|
682
|
-
body[column.field.name] = resolved.id;
|
|
683
|
-
else
|
|
684
|
-
problems.push(`${row.line} 行目の ${column.header}: ${resolved?.error ?? '参照先が見つかりません'}`);
|
|
685
|
-
return;
|
|
686
|
-
}
|
|
687
|
-
const converted = apiValue(column.field, cell);
|
|
688
|
-
if ('error' in converted)
|
|
689
|
-
problems.push(`${row.line} 行目の ${column.header}(値: "${cell}"): ${converted.error}`);
|
|
690
|
-
else
|
|
691
|
-
body[column.field.name] = converted.value;
|
|
692
|
-
});
|
|
693
|
-
plans.push({ row, operation, body });
|
|
694
|
-
}
|
|
695
|
-
for (const [label, lines] of denied)
|
|
696
|
-
problems.push(`${label}: ${lines.join('・')} 行目(この列の値を空にするか、列を消してください)`);
|
|
697
|
-
if (problems.length)
|
|
698
|
-
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" の値が正しくありません:\n${problems.join('\n')}`);
|
|
699
|
-
const updates = plans.filter((p) => p.operation === '更新');
|
|
700
|
-
const inserts = plans.filter((p) => p.operation === '作成');
|
|
434
|
+
const { file, records, apiName, fields } = readCsvTable(objectName, relativePath, what, api, baseDir, projectRoot);
|
|
435
|
+
const plan = planTableWrite(apiName, fields, records, mode, api, relativePath);
|
|
436
|
+
const updates = plan.records.filter((r) => r.operation === 'update').map(writePlanOf);
|
|
701
437
|
const before = rememberBefore(apiName, updates, api);
|
|
702
|
-
//
|
|
438
|
+
// 書き込む(soql-core が、更新、作成の順に 200 件ずつに分ける。1回の呼び出しの中は、すべて成功するか、すべて書き込まない)。
|
|
703
439
|
const done = [];
|
|
704
440
|
// 値を変える項目がない更新の行(一致の列だけの行)は、送らずに更新した行として数える。
|
|
705
|
-
for (const
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
const
|
|
709
|
-
|
|
441
|
+
for (const record of plan.unchanged)
|
|
442
|
+
done.push({ plan: writePlanOf(record), id: String(record.id) });
|
|
443
|
+
let failure;
|
|
444
|
+
for (const batch of (0, soql_core_1.tableWriteBatches)(plan)) {
|
|
445
|
+
const plans = batch.records.map(writePlanOf);
|
|
446
|
+
failure = sendPlans(plans, (bodies) => (batch.operation === 'update' ? api.updateRecords(apiName, bodies) : api.insertRecords(apiName, bodies)), done);
|
|
447
|
+
if (failure)
|
|
448
|
+
break;
|
|
449
|
+
}
|
|
710
450
|
if (failure)
|
|
711
451
|
throw rollBack(failure, done, before, apiName, api, `CSV "${relativePath}" の${what}`);
|
|
712
|
-
const written = done.map((d) => ({ line: d.plan.
|
|
713
|
-
return { apiName, file, keyField: keyField
|
|
714
|
-
}
|
|
715
|
-
/**
|
|
716
|
-
* 更新・Upsert の一致に使う項目を決める(更新は Id。Upsert は Id か外部 ID の項目)。
|
|
717
|
-
*
|
|
718
|
-
* @param mode - 操作。
|
|
719
|
-
* @param fields - オブジェクトの項目の情報。
|
|
720
|
-
* @param objectName - オブジェクト(メッセージに使う)。
|
|
721
|
-
* @returns 一致に使う項目。
|
|
722
|
-
* @throws 項目がない・項目ラベルが1つに決まらない・外部 ID の項目でない場合(シナリオ不正)。
|
|
723
|
-
*/
|
|
724
|
-
function resolveKeyField(mode, fields, objectName) {
|
|
725
|
-
const keyName = mode.kind === 'update' ? 'Id' : mode.key.trim();
|
|
726
|
-
if (keyName.toLowerCase() === 'id')
|
|
727
|
-
return fields.find((f) => f.name.toLowerCase() === 'id') ?? { name: 'Id', label: 'Id', type: 'id', createable: false };
|
|
728
|
-
const byName = fields.filter((f) => f.name.toLowerCase() === keyName.toLowerCase());
|
|
729
|
-
const matches = byName.length ? byName : fields.filter((f) => f.label === keyName);
|
|
730
|
-
if (matches.length !== 1) {
|
|
731
|
-
throw new executionControl_1.ExecutionFailure('scenario-invalid', matches.length
|
|
732
|
-
? `Upsert の一致に使う項目 "${keyName}" の項目ラベルの項目が複数あります。API 名で書いてください(${matches.map((f) => f.name).join('、')})`
|
|
733
|
-
: `Upsert の一致に使う項目 "${keyName}" が "${objectName}" にありません(Id か外部 ID の項目の API 名・項目ラベルで書いてください)`);
|
|
734
|
-
}
|
|
735
|
-
if (!matches[0].externalId) {
|
|
736
|
-
throw new executionControl_1.ExecutionFailure('scenario-invalid', `Upsert の一致に使う項目 "${keyName}"(${matches[0].name})は外部 ID の項目ではありません。Id か外部 ID の項目を指定してください(Data Loader と同じ)`);
|
|
737
|
-
}
|
|
738
|
-
return matches[0];
|
|
739
|
-
}
|
|
740
|
-
/**
|
|
741
|
-
* 一致に使う値で、組織のレコードを探す。
|
|
742
|
-
*
|
|
743
|
-
* SOQL の IN は、テキストの値の大文字・小文字を区別せずに当てるため、取得した後に、項目の比べ方(rule)で CSV の値と同じものだけを残す
|
|
744
|
-
* (大文字・小文字を区別する外部 ID で、"ABC" と "abc" を別のレコードとして扱うため)。数値の外部 ID は、書かれた桁のまま読む。
|
|
745
|
-
*
|
|
746
|
-
* @param apiName - オブジェクトの API 名。
|
|
747
|
-
* @param keyName - 一致に使う項目の API 名。
|
|
748
|
-
* @param rule - 一致に使う値の比べ方。
|
|
749
|
-
* @param keys - 一致に使う値(空を除き、形を確かめたもの)。
|
|
750
|
-
* @param api - 組織の操作。
|
|
751
|
-
* @param relativePath - CSV のパス(メッセージに使う)。
|
|
752
|
-
* @returns 比べる形の値 → レコードの Id。
|
|
753
|
-
* @throws SOQL の誤り、一致するレコードが2件以上ある場合(シナリオ不正)。
|
|
754
|
-
*/
|
|
755
|
-
function findExisting(apiName, keyName, rule, keys, api, relativePath) {
|
|
756
|
-
const byId = keyName.toLowerCase() === 'id';
|
|
757
|
-
const wanted = new Set(keys.map((key) => rule.normalize(key)));
|
|
758
|
-
const existing = new Map();
|
|
759
|
-
const duplicated = [];
|
|
760
|
-
for (let i = 0; i < keys.length; i += 100) {
|
|
761
|
-
const soql = `SELECT Id${byId ? '' : `, ${keyName}`} FROM ${apiName} WHERE ${keyName} IN (${keys.slice(i, i + 100).map((key) => rule.literal(key)).join(',')})`;
|
|
762
|
-
let found;
|
|
763
|
-
try {
|
|
764
|
-
// 数値の外部 ID は、桁を丸めずに読む(queryExact がない組織の操作では query)。メソッドとして呼ぶ(this を保つ)。
|
|
765
|
-
found = rule.exact && api.queryExact ? api.queryExact(soql) : api.query(soql);
|
|
766
|
-
}
|
|
767
|
-
catch (error) {
|
|
768
|
-
if ((0, executionControl_1.isExecutionFailure)(error))
|
|
769
|
-
throw error;
|
|
770
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
771
|
-
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" の一致するレコードを探せません${(0, soqlQuery_1.describeQueryError)(message)}\n実行した SOQL: ${soql}`, { cause: error });
|
|
772
|
-
}
|
|
773
|
-
for (const record of found) {
|
|
774
|
-
const id = String(record.Id);
|
|
775
|
-
const raw = byId ? id : record[keyName];
|
|
776
|
-
const text = (0, sf_1.isRawJsonNumber)(raw) ? raw.rawJSON : String(raw ?? '');
|
|
777
|
-
const key = rule.normalize(text);
|
|
778
|
-
if (typeof key !== 'string' || !wanted.has(key))
|
|
779
|
-
continue;
|
|
780
|
-
const other = existing.get(key);
|
|
781
|
-
if (other && other !== id)
|
|
782
|
-
duplicated.push(`${keyName} "${text}" に一致するレコードが2件以上あります(${other}、${id}。${rule.description})`);
|
|
783
|
-
existing.set(key, id);
|
|
784
|
-
}
|
|
785
|
-
}
|
|
786
|
-
if (duplicated.length)
|
|
787
|
-
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" の対象を1件に決められません:\n${duplicated.join('\n')}`);
|
|
788
|
-
return existing;
|
|
452
|
+
const written = done.map((d) => ({ line: d.plan.line, id: d.id, operation: d.plan.operation })).sort((a, b) => a.line - b.line);
|
|
453
|
+
return { apiName, file, keyField: plan.keyField ?? 'Id', written };
|
|
789
454
|
}
|
|
790
455
|
/**
|
|
791
456
|
* 更新する行の、変える項目の変更前の値を、書かれた桁のまま記憶する(失敗したときに戻すため)。
|
|
@@ -835,7 +500,7 @@ function rollBack(failure, done, before, apiName, api, what) {
|
|
|
835
500
|
...done.filter((d) => d.plan.operation === '更新').map((d) => d.id),
|
|
836
501
|
...failure.unknown.filter((p) => p.operation === '更新').map((p) => String(p.body.Id)),
|
|
837
502
|
].filter((id) => before.has(id));
|
|
838
|
-
const unknownCreates = failure.unknown.filter((p) => p.operation === '作成').map((p) => p.
|
|
503
|
+
const unknownCreates = failure.unknown.filter((p) => p.operation === '作成').map((p) => p.line);
|
|
839
504
|
const left = [];
|
|
840
505
|
/** 戻す処理を1つ試み、戻せなかった Id を left に加える(例外でも、ほかの戻す処理を止めない)。 */
|
|
841
506
|
const attempt = (ids, label, run) => {
|
|
@@ -865,33 +530,29 @@ function rollBack(failure, done, before, apiName, api, what) {
|
|
|
865
530
|
return new executionControl_1.ExecutionFailure('runtime-error', `${what}の途中で失敗しました。先に書き込んだ行のうち ${restored} 行は戻しました${left.length || unknownCreates.length ? 'が、戻せなかった行・反映が分からない行があります' : ''}:\n${details}`);
|
|
866
531
|
}
|
|
867
532
|
/**
|
|
868
|
-
*
|
|
533
|
+
* 1回分の書き込む行を送る。送れた行は done に加える。
|
|
869
534
|
*
|
|
870
|
-
* @param plans -
|
|
535
|
+
* @param plans - 送る行(soql-core の送る単位の1回分)。
|
|
871
536
|
* @param write - 1回分を送る処理(1回の呼び出しの中は、すべて成功するか、すべて書き込まない)。
|
|
872
537
|
* @param done - 送れた行(この関数が加える)。
|
|
873
|
-
* @returns
|
|
538
|
+
* @returns 失敗した場合は、その失敗(結果の誤りの行、または例外と反映が分からない行)。すべて送れたら undefined。
|
|
874
539
|
*/
|
|
875
540
|
function sendPlans(plans, write, done) {
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
results.forEach((r, j) => done.push({ plan: part[j], id: r.id || String(part[j].body.Id ?? '') }));
|
|
890
|
-
continue;
|
|
891
|
-
}
|
|
892
|
-
// 1件の誤りで、同じ呼び出しのほかの行も ALL_OR_NONE_OPERATION_ROLLED_BACK になるため、誤りの行だけを示す。
|
|
893
|
-
const causes = failed.filter((r) => !/ALL_OR_NONE_OPERATION_ROLLED_BACK/.test(r.error ?? ''));
|
|
894
|
-
return { lines: (causes.length ? causes : failed).map((r) => `${r.line} 行目: ${r.error}`), unknown: [] };
|
|
541
|
+
let results;
|
|
542
|
+
try {
|
|
543
|
+
results = write(plans.map((p) => p.body));
|
|
544
|
+
}
|
|
545
|
+
catch (error) {
|
|
546
|
+
// 通信の失敗などで応答を受け取れなかった。この回の行は、反映されたかどうか分からない。
|
|
547
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
548
|
+
return { lines: [`${plans[0].line}〜${plans[plans.length - 1].line} 行目の送信で失敗しました(反映されたかどうか分かりません): ${message}`], unknown: plans };
|
|
549
|
+
}
|
|
550
|
+
const failed = results.map((r, j) => ({ ...r, line: plans[j].line })).filter((r) => !r.success);
|
|
551
|
+
if (!failed.length) {
|
|
552
|
+
results.forEach((r, j) => done.push({ plan: plans[j], id: r.id || String(plans[j].body.Id ?? '') }));
|
|
553
|
+
return undefined;
|
|
895
554
|
}
|
|
896
|
-
|
|
555
|
+
// 1件の誤りで、同じ呼び出しのほかの行も ALL_OR_NONE_OPERATION_ROLLED_BACK になるため、誤りの行だけを示す。
|
|
556
|
+
const causes = failed.filter((r) => !/ALL_OR_NONE_OPERATION_ROLLED_BACK/.test(r.error ?? ''));
|
|
557
|
+
return { lines: (causes.length ? causes : failed).map((r) => `${r.line} 行目: ${r.error}`), unknown: [] };
|
|
897
558
|
}
|