@fluxenginejp/sftest 2.2.0 → 3.0.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 → README.md} +13 -12
- package/dist/cli/sftest.js +6 -6
- package/dist/pages/common/RecordFields.d.ts +35 -0
- package/dist/pages/common/RecordFields.js +101 -2
- package/dist/steps/common/conditional.steps.d.ts +1 -0
- package/dist/steps/common/conditional.steps.js +41 -0
- package/dist/steps/common/data.steps.js +51 -13
- package/dist/steps/common/instance.steps.js +22 -2
- package/dist/support/conditionalBlocks.d.ts +110 -0
- package/dist/support/conditionalBlocks.js +153 -0
- package/dist/support/csvInsert.d.ts +92 -8
- package/dist/support/csvInsert.js +359 -247
- package/dist/support/dateValues.d.ts +1 -24
- package/dist/support/dateValues.js +10 -87
- package/dist/support/dmlWrite.d.ts +99 -0
- package/dist/support/dmlWrite.js +194 -0
- package/dist/support/fixtures.d.ts +27 -0
- package/dist/support/fixtures.js +40 -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/recordCondition.d.ts +13 -2
- package/dist/support/recordCondition.js +13 -10
- package/dist/support/settings.d.ts +21 -0
- package/dist/support/settings.js +38 -2
- package/dist/support/sf.d.ts +18 -32
- package/dist/support/sf.js +44 -40
- package/dist/support/sobjects.d.ts +5 -3
- package/dist/support/sobjects.js +7 -16
- package/dist/support/soqlQuery.d.ts +45 -32
- package/dist/support/soqlQuery.js +88 -116
- package/dist/support/standardFunctions.js +7 -0
- package/docs/CHANGELOG.md +80 -40
- package/docs/EXTENSIONS.md +481 -0
- package/docs/SPEC.md +4000 -0
- package/package.json +4 -4
- package/sftest.config.jsonc +6 -0
- package/dist/support/soqlLabels.d.ts +0 -60
- package/dist/support/soqlLabels.js +0 -304
- package/docs/EXTENSIONS.html +0 -843
- package/docs/SPEC.html +0 -9729
|
@@ -4,40 +4,61 @@ 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;
|
|
11
|
+
exports.writeCsv = writeCsv;
|
|
10
12
|
/**
|
|
11
13
|
* CSV のデータを、オブジェクトのレコードとして登録する(「"<オブジェクト>" に CSV "<パス>" のデータを登録する」。20261021-005)。
|
|
12
14
|
*
|
|
13
|
-
* CSV
|
|
15
|
+
* CSV は、シナリオ(.feature)のフォルダからの相対パスで指定する(20261119-001。../ でプロジェクトのフォルダの中の別のフォルダも指せる)。書き方は Salesforce の Data Loader の登録用の CSV に合わせる
|
|
14
16
|
* (1行目は項目の API 名。項目ラベルも使える。空のセルは設定しない、#N/A は null、チェックボックスは true/false・yes/no・1/0 など)。
|
|
15
17
|
* Id は組織ごとに違うため、sfTest の拡張として、参照先を <関係名>.<項目の API 名>(Account.Name など)の列で書ける。
|
|
16
18
|
* 登録できない項目(Id・作成日・数式など)、値の誤り、ない参照先は、登録の前にシナリオ不正とする。1行でも登録に失敗したら、
|
|
17
19
|
* その CSV で登録した行を削除して戻し、シナリオ不正とする(一部だけ登録された状態を残さない。2026-10-21、PO の決定)。
|
|
18
|
-
*
|
|
20
|
+
* 更新(「"<オブジェクト>" を CSV "<パス>" のデータで更新する」)と Upsert(「… のデータを "<項目>" で Upsert する」)も同じ書き方の CSV で行う
|
|
21
|
+
* (20261114-001。writeCsv。Id か外部 ID の項目で対象を探し、空のセルは値を変えない。失敗したら作成した行を削除し、更新した行を戻す)。
|
|
22
|
+
* 登録・更新・Upsert は Salesforce CLI のユーザ(.env の SF_ORG_ALIAS)で行う。
|
|
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 の実行、送信、失敗したときの戻し(作成した行の削除・更新した行の復元)を行う。
|
|
19
28
|
*
|
|
20
29
|
* @author Fluxengine.co.jp
|
|
21
30
|
*/
|
|
22
31
|
const node_fs_1 = require("node:fs");
|
|
23
32
|
const node_path_1 = __importDefault(require("node:path"));
|
|
33
|
+
const soql_core_1 = require("@fluxenginejp/soql-core");
|
|
24
34
|
const dataRestore_1 = require("./dataRestore");
|
|
25
35
|
const executionControl_1 = require("./executionControl");
|
|
26
|
-
const outputPaths_1 = require("./outputPaths");
|
|
27
36
|
const settings_1 = require("./settings");
|
|
28
37
|
const sf_1 = require("./sf");
|
|
29
38
|
const sobjects_1 = require("./sobjects");
|
|
30
39
|
const soqlQuery_1 = require("./soqlQuery");
|
|
31
40
|
/** REST API の基準のパス。 */
|
|
32
41
|
const API = '/services/data/v62.0';
|
|
33
|
-
/** 1
|
|
42
|
+
/** 1回の SOQL で変更前の値を読むレコードの数(Id の IN の数)。 */
|
|
34
43
|
const CHUNK = 200;
|
|
35
|
-
/**
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
44
|
+
/**
|
|
45
|
+
* sObject Collections の応答を、行ごとの結果にする(登録・更新で共通。項目の誤りは項目名を添える)。
|
|
46
|
+
*
|
|
47
|
+
* @param count - 送ったレコードの数。
|
|
48
|
+
* @param response - 応答。
|
|
49
|
+
* @param ids - 更新の場合の Id(送った順。登録の場合は省く)。
|
|
50
|
+
* @returns 行ごとの結果。
|
|
51
|
+
*/
|
|
52
|
+
function collectionWriteResults(count, response, ids) {
|
|
53
|
+
const items = Array.isArray(response) ? response : [];
|
|
54
|
+
return Array.from({ length: count }, (_, i) => {
|
|
55
|
+
const item = items[i];
|
|
56
|
+
if (item?.success)
|
|
57
|
+
return { id: item.id ?? ids?.[i] ?? '', success: true };
|
|
58
|
+
const error = (item?.errors ?? []).map((e) => `${e.statusCode ?? 'エラー'}: ${e.message ?? ''}${e.fields?.length ? `(項目: ${e.fields.join('、')})` : ''}`).join('、') || '結果を受け取れませんでした';
|
|
59
|
+
return { id: ids?.[i] ?? '', success: false, error };
|
|
60
|
+
});
|
|
61
|
+
}
|
|
41
62
|
/** 組織を操作する既定の処理(Salesforce CLI のユーザで行う)。 */
|
|
42
63
|
exports.defaultCsvInsertApi = {
|
|
43
64
|
objectApiName: (labelOrApiName) => (0, sobjects_1.sobjectByLabel)(labelOrApiName).apiName,
|
|
@@ -56,31 +77,89 @@ exports.defaultCsvInsertApi = {
|
|
|
56
77
|
});
|
|
57
78
|
},
|
|
58
79
|
deleteRecords: (ids) => dataRestore_1.defaultDataApi.deleteRecords(ids),
|
|
80
|
+
updateRecords: (apiName, records) => collectionWriteResults(records.length, (0, sf_1.sfRestWrite)('PATCH', `${API}/composite/sobjects`, { allOrNone: true, records: records.map((r) => ({ attributes: { type: apiName }, ...r })) }), records.map((r) => String(r.Id))),
|
|
81
|
+
restoreRecords: (apiName, records) => dataRestore_1.defaultDataApi.updateRecords(apiName, records),
|
|
82
|
+
// 変更前の値は、18桁の数値なども書かれた桁のまま記憶し、戻すときに丸めない(データの記憶・復元と同じ)。
|
|
83
|
+
queryExact: (soql) => (0, sf_1.sfQuery)(soql, true),
|
|
59
84
|
};
|
|
60
85
|
/**
|
|
61
|
-
* 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
|
+
* シナリオのフォルダからの書き方を案内する。
|
|
62
134
|
*
|
|
63
|
-
* @param
|
|
64
|
-
* @param
|
|
135
|
+
* @param csvPath - シナリオに書いたパス(ファイル名と拡張子まで)。
|
|
136
|
+
* @param baseDir - 基準のフォルダ(シナリオの .feature があるフォルダ)の絶対パス。
|
|
137
|
+
* @param projectRoot - プロジェクトのフォルダ(作業フォルダ)の絶対パス。省略時は baseDir(単体の確認で、基準のフォルダの外を禁止する場合)。
|
|
65
138
|
* @returns CSV の絶対パス。
|
|
66
|
-
* @throws
|
|
139
|
+
* @throws 空・絶対パス・プロジェクトのフォルダの外を指すパス・拡張子が .csv でない・ない・ファイルでない場合(シナリオ不正)。
|
|
67
140
|
*/
|
|
68
|
-
function resolveCsvPath(
|
|
69
|
-
const where =
|
|
70
|
-
if (!
|
|
141
|
+
function resolveCsvPath(csvPath, baseDir, projectRoot = baseDir) {
|
|
142
|
+
const where = `シナリオのフォルダ(${scenarioPath(projectRoot, baseDir) || '.'})`;
|
|
143
|
+
if (!csvPath.trim())
|
|
71
144
|
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV のパスが空です。${where}からの相対パスで、ファイル名と拡張子まで書いてください`);
|
|
72
|
-
if (node_path_1.default.isAbsolute(
|
|
73
|
-
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}")`);
|
|
74
147
|
}
|
|
75
|
-
const
|
|
76
|
-
const
|
|
77
|
-
if (!
|
|
78
|
-
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}")`);
|
|
79
152
|
}
|
|
80
153
|
if (node_path_1.default.extname(file).toLowerCase() !== '.csv')
|
|
81
|
-
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV のパスは、拡張子 .csv まで書いてください(指定値: "${
|
|
82
|
-
if (!(0, node_fs_1.existsSync)(file) || !(0, node_fs_1.statSync)(file).isFile())
|
|
83
|
-
|
|
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
|
+
}
|
|
84
163
|
return file;
|
|
85
164
|
}
|
|
86
165
|
/**
|
|
@@ -167,209 +246,108 @@ function readUtf8(file, relativePath) {
|
|
|
167
246
|
}
|
|
168
247
|
}
|
|
169
248
|
/**
|
|
170
|
-
*
|
|
249
|
+
* soql-core の値(DmlValue)を、送る本文の値にする(数値は書いた桁のまま送るため、RawJsonNumber にする)。
|
|
171
250
|
*
|
|
172
|
-
* @param
|
|
173
|
-
* @
|
|
174
|
-
* @param objectName - オブジェクト(メッセージに使う)。
|
|
175
|
-
* @returns 列の扱い。
|
|
176
|
-
* @throws ない項目・登録できない項目・同じ項目の重複・あいまいな項目ラベル・空の見出しがある場合(シナリオ不正。該当する列をすべて示す)。
|
|
251
|
+
* @param value - soql-core が作った値。
|
|
252
|
+
* @returns 送る本文の値。
|
|
177
253
|
*/
|
|
178
|
-
function
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
continue;
|
|
188
|
-
}
|
|
189
|
-
const dot = header.indexOf('.');
|
|
190
|
-
if (dot > 0) {
|
|
191
|
-
const relationship = header.slice(0, dot).toLowerCase();
|
|
192
|
-
const field = fields.find((f) => f.type === 'reference' && f.relationshipName?.toLowerCase() === relationship);
|
|
193
|
-
if (!field) {
|
|
194
|
-
unknown.push(header);
|
|
195
|
-
continue;
|
|
196
|
-
}
|
|
197
|
-
if (!field.createable)
|
|
198
|
-
notCreateable.push(`${header}(${field.name})`);
|
|
199
|
-
columns.push({ header, field, lookup: { targetField: header.slice(dot + 1), targetObjects: field.referenceTo ?? [] } });
|
|
200
|
-
continue;
|
|
201
|
-
}
|
|
202
|
-
let matches = fields.filter((f) => f.name.toLowerCase() === header.toLowerCase());
|
|
203
|
-
if (!matches.length)
|
|
204
|
-
matches = fields.filter((f) => f.label === header);
|
|
205
|
-
if (!matches.length) {
|
|
206
|
-
unknown.push(header);
|
|
207
|
-
continue;
|
|
208
|
-
}
|
|
209
|
-
if (matches.length > 1) {
|
|
210
|
-
ambiguous.push(`${header}(${matches.map((f) => f.name).join('、')})`);
|
|
211
|
-
continue;
|
|
212
|
-
}
|
|
213
|
-
if (!matches[0].createable)
|
|
214
|
-
notCreateable.push(header === matches[0].name ? header : `${header}(${matches[0].name})`);
|
|
215
|
-
columns.push({ header, field: matches[0] });
|
|
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;
|
|
216
263
|
}
|
|
217
|
-
const problems = [];
|
|
218
|
-
if (unknown.length)
|
|
219
|
-
problems.push(`"${objectName}" にない項目: ${unknown.join('、')}`);
|
|
220
|
-
if (ambiguous.length)
|
|
221
|
-
problems.push(`同じ項目ラベルの項目が複数あるため、API 名で書いてください: ${ambiguous.join('、')}`);
|
|
222
|
-
if (notCreateable.length)
|
|
223
|
-
problems.push(`登録できない項目(Id・作成日・数式・自動採番など): ${notCreateable.join('、')}。この列を CSV から消してください`);
|
|
224
|
-
const seen = new Map();
|
|
225
|
-
for (const column of columns) {
|
|
226
|
-
const other = seen.get(column.field.name);
|
|
227
|
-
if (other)
|
|
228
|
-
problems.push(`同じ項目(${column.field.name})の列が2つあります: ${other}、${column.header}`);
|
|
229
|
-
seen.set(column.field.name, column.header);
|
|
230
|
-
}
|
|
231
|
-
if (problems.length)
|
|
232
|
-
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV の1行目(見出し)が正しくありません:\n${problems.join('\n')}`);
|
|
233
|
-
return columns;
|
|
234
264
|
}
|
|
235
265
|
/**
|
|
236
|
-
*
|
|
266
|
+
* soql-core が作った送る1件を、組織の操作に渡すレコードの本文にする(更新は Id を含める)。
|
|
237
267
|
*
|
|
238
|
-
* @param
|
|
239
|
-
* @returns
|
|
268
|
+
* @param record - 送る1件。
|
|
269
|
+
* @returns レコードの本文(項目の API 名 → 値)。
|
|
240
270
|
*/
|
|
241
|
-
function
|
|
242
|
-
const
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
const date = new Date(Date.UTC(y, m - 1, d));
|
|
247
|
-
if (date.getUTCFullYear() !== y || date.getUTCMonth() !== m - 1 || date.getUTCDate() !== d)
|
|
248
|
-
return undefined;
|
|
249
|
-
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;
|
|
250
276
|
}
|
|
251
277
|
/**
|
|
252
|
-
*
|
|
278
|
+
* CSV の見出しと行から、soql-core の表のデータの処理で送る内容を作る(SOQL は組織の操作で実行する)。
|
|
253
279
|
*
|
|
254
|
-
*
|
|
255
|
-
*
|
|
256
|
-
|
|
257
|
-
function dateTimeValue(value) {
|
|
258
|
-
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);
|
|
259
|
-
if (withOffset) {
|
|
260
|
-
// JavaScript の Date は、存在しない暦日(2026-02-30)や範囲の外の時刻を、別の日時に直してしまうため、先に確かめる(独立レビューの指摘)。
|
|
261
|
-
const [h, mi, s] = [Number(withOffset[2]), Number(withOffset[3]), Number(withOffset[4] ?? 0)];
|
|
262
|
-
const offsetMatch = /^[+-](\d{2}):?(\d{2})$/.exec(withOffset[6]);
|
|
263
|
-
if (!dateValue(withOffset[1]) || h > 23 || mi > 59 || s > 59)
|
|
264
|
-
return undefined;
|
|
265
|
-
if (offsetMatch && (Number(offsetMatch[1]) > 14 || Number(offsetMatch[2]) > 59))
|
|
266
|
-
return undefined;
|
|
267
|
-
const offset = withOffset[6] === 'Z' ? 'Z' : withOffset[6].replace(/^([+-]\d{2})(\d{2})$/, '$1:$2');
|
|
268
|
-
const time = new Date(`${withOffset[1]}T${withOffset[2]}:${withOffset[3]}:${withOffset[4] ?? '00'}.${(withOffset[5] ?? '0').padEnd(3, '0')}${offset}`);
|
|
269
|
-
return Number.isNaN(time.getTime()) ? undefined : time.toISOString();
|
|
270
|
-
}
|
|
271
|
-
const local = /^(\d{4})([-/])(\d{1,2})\2(\d{1,2})[ T](\d{1,2}):(\d{2})(?::(\d{2}))?$/.exec(value);
|
|
272
|
-
if (!local || !dateValue(`${local[1]}-${local[3]}-${local[4]}`))
|
|
273
|
-
return undefined;
|
|
274
|
-
const [h, mi, s] = [Number(local[5]), Number(local[6]), Number(local[7] ?? 0)];
|
|
275
|
-
if (h > 23 || mi > 59 || s > 59)
|
|
276
|
-
return undefined;
|
|
277
|
-
return new Date(Number(local[1]), Number(local[3]) - 1, Number(local[4]), h, mi, s).toISOString();
|
|
278
|
-
}
|
|
279
|
-
/**
|
|
280
|
-
* CSV の値を、項目の型に合わせて API の値にする。
|
|
281
|
-
*
|
|
282
|
-
* @param field - 項目の情報。
|
|
283
|
-
* @param value - CSV の値(空と #N/A は呼び出し元で扱う)。
|
|
284
|
-
* @returns API の値。値の形が正しくない場合は、理由の文字列を { error } で返す。
|
|
285
|
-
*/
|
|
286
|
-
function apiValue(field, value) {
|
|
287
|
-
if (field.type === 'boolean') {
|
|
288
|
-
const parsed = BOOLEAN_VALUES[value.toLowerCase()];
|
|
289
|
-
return parsed === undefined ? { error: 'チェックボックスは true・false(yes・no、1・0 なども可)で書いてください' } : { value: parsed };
|
|
290
|
-
}
|
|
291
|
-
if (field.type === 'date') {
|
|
292
|
-
const date = dateValue(value);
|
|
293
|
-
return date ? { value: date } : { error: '日付は YYYY-MM-DD(または YYYY/MM/DD)で、ある日付を書いてください(月が先の 12/31/2026 などは書けません)' };
|
|
294
|
-
}
|
|
295
|
-
if (field.type === 'datetime') {
|
|
296
|
-
const time = dateTimeValue(value);
|
|
297
|
-
return time ? { value: time } : { error: '日付時刻は YYYY-MM-DDTHH:mm:ss.SSS+0900 などの時差付きの形、または YYYY-MM-DD HH:mm(実行する PC の時間帯)で書いてください' };
|
|
298
|
-
}
|
|
299
|
-
if (NUMBER_TYPES.has(field.type)) {
|
|
300
|
-
// 数値は、書いた桁のまま送る(倍精度に丸めない)。
|
|
301
|
-
return /^-?\d+(\.\d+)?$/.test(value) ? { value: (0, sf_1.parseJsonExact)(value) } : { error: '数値は、桁区切りのない数字で書いてください(例: 1000000、-12.5)' };
|
|
302
|
-
}
|
|
303
|
-
return { value };
|
|
304
|
-
}
|
|
305
|
-
/**
|
|
306
|
-
* 参照先を名前などで書いた列の値から、参照先の Id を探す。
|
|
280
|
+
* 誤りは、soql-core のメッセージ(TableInputError は表題と1件ずつの行、ほかは1文)に CSV のパスを付けてシナリオ不正にする(2026-11-19、
|
|
281
|
+
* PO の決定 2A)。参照先を探す SOQL が、参照先の項目のないオブジェクト(所有者のユーザ・キューなど複数の参照先の一部)で INVALID_FIELD に
|
|
282
|
+
* なった場合は、見つからないものとして続ける(tolerateInvalidField)。
|
|
307
283
|
*
|
|
308
|
-
* @param
|
|
309
|
-
* @param
|
|
284
|
+
* @param apiName - オブジェクトの API 名。
|
|
285
|
+
* @param fields - オブジェクトの項目の情報。
|
|
286
|
+
* @param records - CSV の件(1件目が見出し)。
|
|
287
|
+
* @param operation - 登録・更新・Upsert。
|
|
310
288
|
* @param api - 組織の操作。
|
|
311
|
-
* @
|
|
312
|
-
* @
|
|
289
|
+
* @param relativePath - シナリオに書いた CSV のパス(メッセージに使う)。
|
|
290
|
+
* @returns 送る内容。
|
|
291
|
+
* @throws 見出し・行・値・参照先・一致・権限の誤り、SOQL の誤り(シナリオ不正)。
|
|
313
292
|
*/
|
|
314
|
-
function
|
|
315
|
-
const
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
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) => {
|
|
325
304
|
try {
|
|
326
|
-
|
|
305
|
+
// 数値の外部 ID は、桁を丸めずに読む(queryExact がない組織の操作では query)。メソッドとして呼ぶ(this を保つ)。
|
|
306
|
+
return query.exact && api.queryExact ? api.queryExact(query.soql) : api.query(query.soql);
|
|
327
307
|
}
|
|
328
308
|
catch (error) {
|
|
329
309
|
if ((0, executionControl_1.isExecutionFailure)(error))
|
|
330
310
|
throw error;
|
|
331
311
|
const message = error instanceof Error ? error.message : String(error);
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
throw new executionControl_1.ExecutionFailure('scenario-invalid',
|
|
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 });
|
|
336
316
|
}
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
const match = values.find((v) => v.toLowerCase() === key.toLowerCase()) ?? key;
|
|
340
|
-
found.set(match, [...(found.get(match) ?? []), String(record.Id)]);
|
|
341
|
-
}
|
|
342
|
-
}
|
|
317
|
+
});
|
|
318
|
+
return (0, soql_core_1.completeTableWrite)(preparation, answers);
|
|
343
319
|
}
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
if (
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
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;
|
|
350
327
|
}
|
|
351
|
-
return result;
|
|
352
328
|
}
|
|
353
329
|
/**
|
|
354
|
-
* CSV
|
|
330
|
+
* CSV のファイルを読み、行の数を確かめ、オブジェクトの API 名と項目の情報を得る(登録・更新・Upsert で共通)。
|
|
355
331
|
*
|
|
356
332
|
* @param objectName - オブジェクト(表示ラベルまたは API 名)。
|
|
357
|
-
* @param relativePath -
|
|
358
|
-
* @param
|
|
359
|
-
* @param
|
|
360
|
-
* @
|
|
361
|
-
* @
|
|
333
|
+
* @param relativePath - シナリオのフォルダからの相対パス。
|
|
334
|
+
* @param what - メッセージの中の操作の名前(登録・更新・Upsert)。
|
|
335
|
+
* @param api - 組織の操作。
|
|
336
|
+
* @param baseDir - 基準のフォルダ(シナリオの .feature があるフォルダ)の絶対パス。
|
|
337
|
+
* @param projectRoot - プロジェクトのフォルダの絶対パス。
|
|
338
|
+
* @returns CSV の絶対パス、件(1件目が見出し)、オブジェクトの API 名、項目の情報。
|
|
339
|
+
* @throws パス・文字コード・空・行がない・行が多すぎる・オブジェクトがない場合(シナリオ不正)。
|
|
362
340
|
*/
|
|
363
|
-
function
|
|
364
|
-
const file = resolveCsvPath(relativePath,
|
|
341
|
+
function readCsvTable(objectName, relativePath, what, api, baseDir, projectRoot) {
|
|
342
|
+
const file = resolveCsvPath(relativePath, baseDir, projectRoot);
|
|
365
343
|
const records = parseCsv(readUtf8(file, relativePath));
|
|
366
344
|
if (!records.length)
|
|
367
345
|
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}" が空です。1行目に項目名を書いてください`);
|
|
368
|
-
const
|
|
369
|
-
if (!rows
|
|
370
|
-
throw new executionControl_1.ExecutionFailure('scenario-invalid', `CSV "${relativePath}"
|
|
371
|
-
if (rows
|
|
372
|
-
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 を分けてください`);
|
|
373
351
|
let apiName;
|
|
374
352
|
try {
|
|
375
353
|
apiName = api.objectApiName(objectName);
|
|
@@ -379,56 +357,29 @@ function insertCsv(objectName, relativePath, api = exports.defaultCsvInsertApi,
|
|
|
379
357
|
throw error;
|
|
380
358
|
throw new executionControl_1.ExecutionFailure('scenario-invalid', `オブジェクト "${objectName}" が見つかりません: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
381
359
|
}
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
});
|
|
397
|
-
const
|
|
398
|
-
for (const row of rows) {
|
|
399
|
-
const body = {};
|
|
400
|
-
columns.forEach((column, index) => {
|
|
401
|
-
const cell = row.cells[index];
|
|
402
|
-
if (cell === '')
|
|
403
|
-
return; // 空のセルは設定しない(Data Loader と同じ)。
|
|
404
|
-
if (cell === NULL_VALUE) {
|
|
405
|
-
body[column.field.name] = null;
|
|
406
|
-
return;
|
|
407
|
-
}
|
|
408
|
-
if (column.lookup) {
|
|
409
|
-
const resolved = lookups.get(column)?.get(cell);
|
|
410
|
-
if (resolved?.id)
|
|
411
|
-
body[column.field.name] = resolved.id;
|
|
412
|
-
else
|
|
413
|
-
problems.push(`${row.line} 行目の ${column.header}: ${resolved?.error ?? '参照先が見つかりません'}`);
|
|
414
|
-
return;
|
|
415
|
-
}
|
|
416
|
-
const converted = apiValue(column.field, cell);
|
|
417
|
-
if ('error' in converted)
|
|
418
|
-
problems.push(`${row.line} 行目の ${column.header}(値: "${cell}"): ${converted.error}`);
|
|
419
|
-
else
|
|
420
|
-
body[column.field.name] = converted.value;
|
|
421
|
-
});
|
|
422
|
-
bodies.push(body);
|
|
423
|
-
}
|
|
424
|
-
if (problems.length)
|
|
425
|
-
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);
|
|
426
376
|
const inserted = [];
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
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);
|
|
430
381
|
if (!failed.length) {
|
|
431
|
-
results.forEach((r, j) => inserted.push({ line:
|
|
382
|
+
results.forEach((r, j) => inserted.push({ line: batch.records[j].line, id: r.id }));
|
|
432
383
|
continue;
|
|
433
384
|
}
|
|
434
385
|
// 1回の呼び出しの中は登録されていない。先の呼び出しで登録した行を削除して戻す。
|
|
@@ -444,3 +395,164 @@ function insertCsv(objectName, relativePath, api = exports.defaultCsvInsertApi,
|
|
|
444
395
|
}
|
|
445
396
|
return { apiName, file, inserted };
|
|
446
397
|
}
|
|
398
|
+
/**
|
|
399
|
+
* soql-core が作った送る1件を、書き込む1行の内容にする。
|
|
400
|
+
*
|
|
401
|
+
* @param record - 送る1件。
|
|
402
|
+
* @returns 書き込む1行の内容。
|
|
403
|
+
*/
|
|
404
|
+
function writePlanOf(record) {
|
|
405
|
+
return { line: record.line, operation: record.operation === 'update' ? '更新' : '作成', body: recordBody(record) };
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* CSV のデータで、オブジェクトのレコードを更新する、または Upsert する(20261114-001。2026-11-14、PO の決定 1A〜5A)。
|
|
409
|
+
*
|
|
410
|
+
* CSV の書き方は登録と同じ(見出しは API 名か項目ラベル、参照先は <関係名>.<項目の API 名> の列、#N/A は null)。違いは次のとおり(Data Loader と同じ)。
|
|
411
|
+
* - 一致: 更新は Id の列で、Upsert は Id か外部 ID の項目(mode.key)の列で、組織のレコードを探す。Upsert で一致がなければ作成する
|
|
412
|
+
* (Id で一致を探す Upsert では、Id が空の行を作成する)。値の比べ方は、項目の型と設定で決める(soql-core の tableKeyRule。Salesforce の upsert と同じ)。
|
|
413
|
+
* - 空のセル: 更新する行では、その項目の値を変えない。作成する行では、登録と同じく設定しない。#N/A は null にする。
|
|
414
|
+
* 書き込む前に、値・参照先・一致(Id が見つからない、一致が2件以上、CSV の中の重なり)・権限(作成する行は作成できる項目、更新する行は
|
|
415
|
+
* 更新できる項目)を soql-core で確かめ、誤りがあればシナリオ不正にする(書き込まない)。1行でも書き込みに失敗したら、作成した行を削除し、
|
|
416
|
+
* 更新した行を変更前の値に戻してから、シナリオ不正にする(一部だけ書き込まれた状態を残さない。登録と同じ)。送信が例外で終わった場合
|
|
417
|
+
* (反映が分からない)、戻せなかった場合は、戻せる行を戻してから実行時エラーにする(rollBack)。
|
|
418
|
+
* シナリオの終わりに自動では戻さない(戻す場合は「… の状態を記憶し、シナリオの終わりに戻す」と組み合わせる)。
|
|
419
|
+
*
|
|
420
|
+
* @param objectName - オブジェクト(表示ラベルまたは API 名)。
|
|
421
|
+
* @param relativePath - シナリオのフォルダからの相対パス(resolveCsvPath)。
|
|
422
|
+
* @param mode - 更新か、Upsert と一致に使う項目(Id、または外部 ID の項目の API 名か項目ラベル)。
|
|
423
|
+
* @param api - 組織の操作(単体の確認で差し替える)。
|
|
424
|
+
* @param baseDir - 基準のフォルダ(シナリオの .feature があるフォルダ)の絶対パス。
|
|
425
|
+
* @param projectRoot - プロジェクトのフォルダの絶対パス。省略時は baseDir。
|
|
426
|
+
* @returns 書き込んだ行。
|
|
427
|
+
* @throws パス・文字コード・見出し・値・参照先・一致・権限・件数の誤り、書き込みの失敗(シナリオ不正。書き込んだ行は戻す)。戻せなかった場合(実行時エラー)。
|
|
428
|
+
*/
|
|
429
|
+
function writeCsv(objectName, relativePath, mode, api = exports.defaultCsvInsertApi, baseDir, projectRoot = baseDir) {
|
|
430
|
+
// メッセージの中の操作の名前(英字の Upsert は、前後に空白を置く)。
|
|
431
|
+
const what = mode.kind === 'update' ? '更新' : ' Upsert ';
|
|
432
|
+
if (!api.updateRecords || !api.restoreRecords)
|
|
433
|
+
throw new Error('組織の操作に、更新と変更前の値に戻す処理がありません');
|
|
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);
|
|
437
|
+
const before = rememberBefore(apiName, updates, api);
|
|
438
|
+
// 書き込む(soql-core が、更新、作成の順に 200 件ずつに分ける。1回の呼び出しの中は、すべて成功するか、すべて書き込まない)。
|
|
439
|
+
const done = [];
|
|
440
|
+
// 値を変える項目がない更新の行(一致の列だけの行)は、送らずに更新した行として数える。
|
|
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
|
+
}
|
|
450
|
+
if (failure)
|
|
451
|
+
throw rollBack(failure, done, before, apiName, api, `CSV "${relativePath}" の${what}`);
|
|
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 };
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* 更新する行の、変える項目の変更前の値を、書かれた桁のまま記憶する(失敗したときに戻すため)。
|
|
457
|
+
*
|
|
458
|
+
* @param apiName - オブジェクトの API 名。
|
|
459
|
+
* @param updates - 更新する行。
|
|
460
|
+
* @param api - 組織の操作。
|
|
461
|
+
* @returns レコードの Id → 戻す値(Id と変える項目)。
|
|
462
|
+
*/
|
|
463
|
+
function rememberBefore(apiName, updates, api) {
|
|
464
|
+
const before = new Map();
|
|
465
|
+
const changed = [...new Set(updates.flatMap((p) => Object.keys(p.body).filter((k) => k !== 'Id')))];
|
|
466
|
+
if (!changed.length)
|
|
467
|
+
return before;
|
|
468
|
+
const ids = updates.map((p) => String(p.body.Id));
|
|
469
|
+
for (let i = 0; i < ids.length; i += CHUNK) {
|
|
470
|
+
const soql = `SELECT Id, ${changed.join(', ')} FROM ${apiName} WHERE Id IN (${ids.slice(i, i + CHUNK).map(sf_1.soqlString).join(',')})`;
|
|
471
|
+
// queryExact がない組織の操作(単体の確認の差し替えなど)では query を使う。メソッドとして呼ぶ(this を保つ)。
|
|
472
|
+
for (const record of api.queryExact ? api.queryExact(soql) : api.query(soql)) {
|
|
473
|
+
const values = { Id: record.Id };
|
|
474
|
+
for (const name of changed)
|
|
475
|
+
values[name] = record[name] ?? null;
|
|
476
|
+
before.set(String(record.Id), values);
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
return before;
|
|
480
|
+
}
|
|
481
|
+
/**
|
|
482
|
+
* 書き込みに失敗した後に、先に書き込んだ行を戻し、止めるための例外を返す(2026-11-14、Codex のレビューの指摘で、例外の場合も戻すようにした)。
|
|
483
|
+
*
|
|
484
|
+
* 作成した行の削除と、更新した行の変更前の値への復元は、片方が例外で失敗しても、もう片方を試みる。反映が分からない回の更新の行は、
|
|
485
|
+
* 変更前の値に戻す(戻しても害がないため)。反映が分からない回の作成の行は、作成されたかどうか、Id も分からないため、行を示す。
|
|
486
|
+
* 結果で失敗し、すべて戻せた場合はシナリオ不正(書き込んでいない状態に戻った)。例外で失敗した場合、戻せない行・反映が分からない行が
|
|
487
|
+
* ある場合は実行時エラー(「書き込んでいない」と言い切れないため)。
|
|
488
|
+
*
|
|
489
|
+
* @param failure - 書き込みの失敗。
|
|
490
|
+
* @param done - 書き込めた行。
|
|
491
|
+
* @param before - 更新する行の変更前の値(レコードの Id → 値)。
|
|
492
|
+
* @param apiName - オブジェクトの API 名。
|
|
493
|
+
* @param api - 組織の操作。
|
|
494
|
+
* @param what - メッセージの主語(例: CSV "…" の更新)。
|
|
495
|
+
* @returns 止めるための例外。
|
|
496
|
+
*/
|
|
497
|
+
function rollBack(failure, done, before, apiName, api, what) {
|
|
498
|
+
const created = done.filter((d) => d.plan.operation === '作成').map((d) => d.id);
|
|
499
|
+
const updatedIds = [
|
|
500
|
+
...done.filter((d) => d.plan.operation === '更新').map((d) => d.id),
|
|
501
|
+
...failure.unknown.filter((p) => p.operation === '更新').map((p) => String(p.body.Id)),
|
|
502
|
+
].filter((id) => before.has(id));
|
|
503
|
+
const unknownCreates = failure.unknown.filter((p) => p.operation === '作成').map((p) => p.line);
|
|
504
|
+
const left = [];
|
|
505
|
+
/** 戻す処理を1つ試み、戻せなかった Id を left に加える(例外でも、ほかの戻す処理を止めない)。 */
|
|
506
|
+
const attempt = (ids, label, run) => {
|
|
507
|
+
if (!ids.length)
|
|
508
|
+
return;
|
|
509
|
+
try {
|
|
510
|
+
for (const r of run())
|
|
511
|
+
if (!r.success)
|
|
512
|
+
left.push(`${r.id}(${label}: ${r.error ?? '理由なし'})`);
|
|
513
|
+
}
|
|
514
|
+
catch (error) {
|
|
515
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
516
|
+
left.push(...ids.map((id) => `${id}(${label}: ${message})`));
|
|
517
|
+
}
|
|
518
|
+
};
|
|
519
|
+
attempt(created, '削除', () => api.deleteRecords(created));
|
|
520
|
+
attempt(updatedIds, '変更前の値に戻す', () => api.restoreRecords(apiName, updatedIds.map((id) => before.get(id))));
|
|
521
|
+
const restored = created.length + updatedIds.length - left.length;
|
|
522
|
+
const details = [
|
|
523
|
+
...failure.lines,
|
|
524
|
+
...(left.length ? [`戻せなかった Id: ${left.join(', ')}`] : []),
|
|
525
|
+
...(unknownCreates.length ? [`作成されたかどうか分からない行: ${unknownCreates.join('・')} 行目(組織で確かめてください)`] : []),
|
|
526
|
+
].join('\n');
|
|
527
|
+
if (!failure.unknown.length && !left.length) {
|
|
528
|
+
return new executionControl_1.ExecutionFailure('scenario-invalid', `${what}に失敗しました。この CSV の行は書き込んでいません${restored ? `(先に書き込んだ ${restored} 行は戻しました)` : ''}:\n${details}`);
|
|
529
|
+
}
|
|
530
|
+
return new executionControl_1.ExecutionFailure('runtime-error', `${what}の途中で失敗しました。先に書き込んだ行のうち ${restored} 行は戻しました${left.length || unknownCreates.length ? 'が、戻せなかった行・反映が分からない行があります' : ''}:\n${details}`);
|
|
531
|
+
}
|
|
532
|
+
/**
|
|
533
|
+
* 1回分の書き込む行を送る。送れた行は done に加える。
|
|
534
|
+
*
|
|
535
|
+
* @param plans - 送る行(soql-core の送る単位の1回分)。
|
|
536
|
+
* @param write - 1回分を送る処理(1回の呼び出しの中は、すべて成功するか、すべて書き込まない)。
|
|
537
|
+
* @param done - 送れた行(この関数が加える)。
|
|
538
|
+
* @returns 失敗した場合は、その失敗(結果の誤りの行、または例外と反映が分からない行)。すべて送れたら undefined。
|
|
539
|
+
*/
|
|
540
|
+
function sendPlans(plans, write, done) {
|
|
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;
|
|
554
|
+
}
|
|
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: [] };
|
|
558
|
+
}
|