@pdfbutler/migration-cli 0.0.27 → 0.0.28

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.
Files changed (48) hide show
  1. package/README.md +193 -30
  2. package/lib/commands/butler/pb/admincredentials.js +37 -37
  3. package/lib/commands/butler/pb/admincredentials.js.map +1 -1
  4. package/lib/commands/butler/pb/adminsettings.d.ts +1 -2
  5. package/lib/commands/butler/pb/adminsettings.js +32 -32
  6. package/lib/commands/butler/pb/adminsettings.js.map +1 -1
  7. package/lib/commands/butler/pb/export.d.ts +10 -3
  8. package/lib/commands/butler/pb/export.js +295 -197
  9. package/lib/commands/butler/pb/export.js.map +1 -1
  10. package/lib/commands/butler/pb/exportdatasource.d.ts +27 -0
  11. package/lib/commands/butler/pb/exportdatasource.js +161 -0
  12. package/lib/commands/butler/pb/exportdatasource.js.map +1 -0
  13. package/lib/commands/butler/pb/exportpack.js +43 -46
  14. package/lib/commands/butler/pb/exportpack.js.map +1 -1
  15. package/lib/commands/butler/pb/import.d.ts +17 -3
  16. package/lib/commands/butler/pb/import.js +415 -183
  17. package/lib/commands/butler/pb/import.js.map +1 -1
  18. package/lib/commands/butler/pb/importdatasource.d.ts +30 -0
  19. package/lib/commands/butler/pb/importdatasource.js +250 -0
  20. package/lib/commands/butler/pb/importdatasource.js.map +1 -0
  21. package/lib/commands/butler/pb/importpack.js +38 -38
  22. package/lib/commands/butler/pb/importpack.js.map +1 -1
  23. package/lib/commands/butler/sb/export/signtemplate.d.ts +23 -0
  24. package/lib/commands/butler/sb/export/signtemplate.js +111 -0
  25. package/lib/commands/butler/sb/export/signtemplate.js.map +1 -0
  26. package/lib/commands/butler/sb/import/signtemplate.d.ts +23 -0
  27. package/lib/commands/butler/sb/import/signtemplate.js +108 -0
  28. package/lib/commands/butler/sb/import/signtemplate.js.map +1 -0
  29. package/lib/utils/authentication.d.ts +3 -1
  30. package/lib/utils/authentication.js +13 -17
  31. package/lib/utils/authentication.js.map +1 -1
  32. package/lib/utils/constants.d.ts +125 -89
  33. package/lib/utils/constants.js +56 -20
  34. package/lib/utils/constants.js.map +1 -1
  35. package/lib/utils/extract-templates.d.ts +1 -0
  36. package/lib/utils/extract-templates.js +89 -0
  37. package/lib/utils/extract-templates.js.map +1 -0
  38. package/lib/utils/logger.d.ts +2 -1
  39. package/lib/utils/logger.js +15 -7
  40. package/lib/utils/logger.js.map +1 -1
  41. package/messages/butler.pb.export.md +4 -0
  42. package/messages/butler.pb.exportdatasource.md +51 -0
  43. package/messages/butler.pb.import.md +4 -0
  44. package/messages/butler.pb.importdatasource.md +51 -0
  45. package/messages/butler.sb.export.signtemplate.md +35 -0
  46. package/messages/butler.sb.import.signtemplate.md +35 -0
  47. package/oclif.manifest.json +322 -43
  48. package/package.json +223 -215
@@ -1,60 +1,215 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- /* eslint-disable @typescript-eslint/no-var-requires */
4
- /* eslint-disable @typescript-eslint/no-unsafe-return */
5
- /* eslint-disable @typescript-eslint/restrict-template-expressions */
6
- /* eslint-disable @typescript-eslint/no-unsafe-argument */
7
- /* eslint-disable @typescript-eslint/no-unsafe-call */
8
- /* eslint-disable @typescript-eslint/no-unsafe-member-access */
9
- /* eslint-disable @typescript-eslint/no-unsafe-assignment */
10
- /* eslint-disable no-console */
11
6
  const path = require("path");
12
7
  const fs = require("graceful-fs");
13
8
  const sf_plugins_core_1 = require("@salesforce/sf-plugins-core");
14
9
  const core_1 = require("@salesforce/core");
15
10
  const FormData = require("form-data");
16
11
  const AdmZip = require("adm-zip");
17
- const got_1 = require("got");
12
+ const got_1 = __importDefault(require("got"));
18
13
  const logger_1 = require("../../../utils/logger");
19
- const constants_1 = require("../../../utils/constants");
20
14
  const authentication_1 = require("../../../utils/authentication");
15
+ const constants_1 = require("../../../utils/constants");
16
+ const extract_templates_1 = require("../../../utils/extract-templates");
21
17
  core_1.Messages.importMessagesDirectory(__dirname);
22
18
  const messages = core_1.Messages.loadMessages('@pdfbutler/migration-cli', 'butler.pb.import');
23
19
  class ButlerPbImport extends sf_plugins_core_1.SfCommand {
20
+ static summary = messages.getMessage('summary');
21
+ static description = messages.getMessage('description');
22
+ static examples = messages.getMessages('examples');
23
+ static flags = {
24
+ name: sf_plugins_core_1.Flags.string({
25
+ summary: messages.getMessage('flags.name.summary'),
26
+ description: messages.getMessage('flags.name.description'),
27
+ char: 'n',
28
+ required: false,
29
+ }),
30
+ target: sf_plugins_core_1.Flags.string({
31
+ summary: messages.getMessage('flags.target.summary'),
32
+ char: 't',
33
+ required: false,
34
+ }),
35
+ 'auth-env-var': sf_plugins_core_1.Flags.string({
36
+ summary: messages.getMessage('flags.auth-env-var.summary'),
37
+ char: 'a',
38
+ }),
39
+ endpoint: sf_plugins_core_1.Flags.url({
40
+ summary: messages.getMessage('flags.endpoint.summary'),
41
+ char: 'e',
42
+ }),
43
+ stage: sf_plugins_core_1.Flags.string({
44
+ summary: messages.getMessage('flags.stage.summary'),
45
+ char: 's',
46
+ }),
47
+ config: sf_plugins_core_1.Flags.string({
48
+ summary: messages.getMessage('flags.config.summary'),
49
+ char: 'f',
50
+ required: true,
51
+ }),
52
+ logs: sf_plugins_core_1.Flags.boolean({
53
+ summary: messages.getMessage('flags.logs.summary'),
54
+ char: 'l',
55
+ }),
56
+ id: sf_plugins_core_1.Flags.string({
57
+ summary: messages.getMessage('flags.id.summary'),
58
+ char: 'i',
59
+ required: true,
60
+ }),
61
+ clone: sf_plugins_core_1.Flags.boolean({
62
+ summary: messages.getMessage('flags.clone.summary'),
63
+ char: 'c',
64
+ }),
65
+ session: sf_plugins_core_1.Flags.string({
66
+ summary: messages.getMessage('flags.session.summary'),
67
+ }),
68
+ instance: sf_plugins_core_1.Flags.string({
69
+ summary: messages.getMessage('flags.instance.summary'),
70
+ }),
71
+ templates: sf_plugins_core_1.Flags.boolean({
72
+ summary: messages.getMessage('flags.templates.summary'),
73
+ char: 'm',
74
+ }),
75
+ };
76
+ static isLogsActive = false;
77
+ static logIdMappings(entity, idMap) {
78
+ if (!ButlerPbImport.isLogsActive)
79
+ return;
80
+ for (const [oldId, newId] of Object.entries(idMap)) {
81
+ if (!oldId || !newId || oldId === newId)
82
+ continue;
83
+ logger_1.Logger.info(constants_1.MESSAGE.DOC_CONFIG_ID_MAPPED_BLOCK.replace('[ENTITY]', entity)
84
+ .replace('[OLD_ID]', oldId)
85
+ .replace('[NEW_ID]', newId));
86
+ }
87
+ }
88
+ static applyIdMap(value, idMap) {
89
+ if (Array.isArray(value)) {
90
+ return value.map((item) => ButlerPbImport.applyIdMap(item, idMap));
91
+ }
92
+ if (value && typeof value === 'object') {
93
+ const entries = Object.entries(value);
94
+ const next = {};
95
+ for (const [key, val] of entries) {
96
+ next[key] = ButlerPbImport.applyIdMap(val, idMap);
97
+ }
98
+ return next;
99
+ }
100
+ if (typeof value === 'string' && idMap[value]) {
101
+ return idMap[value];
102
+ }
103
+ return value;
104
+ }
105
+ static updateZipJsonEntries(zip, idMap) {
106
+ if (Object.keys(idMap).length === 0)
107
+ return;
108
+ for (const entry of zip.getEntries()) {
109
+ if (!entry.entryName.endsWith('.json'))
110
+ continue;
111
+ try {
112
+ const raw = zip.readFile(entry).toString('utf8');
113
+ const json = JSON.parse(raw);
114
+ const updated = ButlerPbImport.applyIdMap(json, idMap);
115
+ zip.updateFile(entry, Buffer.from(JSON.stringify(updated, null, 2)));
116
+ }
117
+ catch (e) {
118
+ // ignore non-JSON or invalid JSON files
119
+ }
120
+ }
121
+ }
24
122
  static getTargetPath(recordType) {
25
123
  switch (recordType) {
26
124
  case 'EXCEL':
27
- return constants_1.PATH.IMPORT_EXCEL;
125
+ return 'config/xls/import-config';
28
126
  case 'WORD':
29
- return constants_1.PATH.IMPORT_WORD;
127
+ return 'config/import-config';
30
128
  case 'PPTX':
31
- return constants_1.PATH.IMPORT_PPTX;
129
+ return 'config/pptx/import-config';
32
130
  case 'PDF':
33
- return constants_1.PATH.IMPORT_PDF;
131
+ return 'config/pdf/import-config';
34
132
  case 'EMAIL':
35
- return constants_1.PATH.IMPORT_EMAIL;
133
+ return 'config/import-config';
36
134
  case 'CSV':
37
- return constants_1.PATH.IMPORT_CSV;
135
+ return 'config/csv/import-config';
38
136
  }
39
137
  throw new Error(constants_1.ERROR.UNSUPPORTED_RECORD_TYPE);
40
138
  }
41
- static getFiles(dir, docConfigIds, files) {
42
- const fileList = fs.readdirSync(dir, { withFileTypes: true });
43
- for (const file of fileList) {
44
- const name = `${dir}/${file.name}`;
45
- if (fs.statSync(name).isDirectory() && file.name === 'sfdc') {
46
- ButlerPbImport.getFiles(name, docConfigIds, files);
139
+ static getMainZipPath(configDir, docConfigId) {
140
+ const zipPath = path.join(configDir, `${docConfigId}.zip`);
141
+ if (fs.existsSync(zipPath))
142
+ return zipPath;
143
+ const folderPath = path.join(configDir, docConfigId);
144
+ if (fs.existsSync(folderPath))
145
+ return folderPath;
146
+ return undefined;
147
+ }
148
+ static async importSfdcJsons(connection, jsonPaths, isClone, idMap = {}) {
149
+ if (jsonPaths.length === 0)
150
+ return {};
151
+ const responses = await Promise.all(jsonPaths.map(async (jsonFile) => {
152
+ const sfdcConfig = JSON.parse(await fs.promises.readFile(jsonFile, 'utf8'));
153
+ const transformedConfig = ButlerPbImport.applyIdMap(sfdcConfig, idMap);
154
+ return connection.apex.post(`/cadmus_core/DocConfig/Import/?isInsert=${isClone ? 'true' : 'false'}`, transformedConfig, { headers: { 'content-type': 'application/json' } });
155
+ }));
156
+ const responseIdMap = {};
157
+ for (const element of responses) {
158
+ if (typeof element === 'object' && element !== null) {
159
+ for (const [key, value] of Object.entries(element)) {
160
+ if (typeof value === 'string')
161
+ responseIdMap[key] = value;
162
+ }
47
163
  }
48
- else {
49
- if (!docConfigIds.includes(path.parse(file.name).name))
50
- continue;
51
- files.push(name);
164
+ }
165
+ return responseIdMap;
166
+ }
167
+ static async sendZip(zipName, baseUrl, base64Auth, stage, idMap, shouldClone) {
168
+ let zip = new AdmZip();
169
+ if (zipName.endsWith('zip')) {
170
+ zip = new AdmZip(zipName);
171
+ }
172
+ else {
173
+ zip.addLocalFolder(zipName);
174
+ }
175
+ const zipToSend = new AdmZip();
176
+ for (const entry of zip.getEntries()) {
177
+ if (entry != null) {
178
+ zipToSend.addFile(entry.entryName, zip.readFile(entry));
52
179
  }
53
180
  }
54
- if (files.length <= 0) {
55
- throw new Error(constants_1.ERROR.NO_MATCHING_FILES);
181
+ ButlerPbImport.updateZipJsonEntries(zipToSend, idMap);
182
+ const txt = zipToSend.readAsText('doc-config.json');
183
+ const recordType = JSON.parse(txt).recordType;
184
+ const targetPath = ButlerPbImport.getTargetPath(recordType);
185
+ const finalUrl = `${baseUrl}${targetPath}`;
186
+ const fd = new FormData();
187
+ fd.append('zip', zipToSend.toBuffer(), { filename: 'zip' });
188
+ fd.append('metadata', JSON.stringify({
189
+ stage,
190
+ version: 'v10.0',
191
+ }), { contentType: 'application/json' });
192
+ const res = await got_1.default.post(finalUrl, {
193
+ body: fd,
194
+ headers: { Authorization: `Basic ${base64Auth}` },
195
+ responseType: 'json',
196
+ });
197
+ const body = res.body;
198
+ const description = String(body?.issues?.[0]?.description ?? constants_1.MESSAGE.UNDEFINED);
199
+ switch (ButlerPbImport.getLogLvl(body?.result)) {
200
+ case 'info':
201
+ logger_1.Logger.info(description);
202
+ break;
203
+ case 'success':
204
+ logger_1.Logger.success(description);
205
+ break;
206
+ default:
207
+ if (!shouldClone) {
208
+ logger_1.Logger.warn(constants_1.MESSAGE.CLONE_LINKED_ORGS_WARNING);
209
+ }
210
+ logger_1.Logger.error(description);
211
+ break;
56
212
  }
57
- return files;
58
213
  }
59
214
  static getDocConfigIds(id) {
60
215
  const docConfigIds = id.split(/([\w-]{36})/).filter((n) => n);
@@ -68,178 +223,255 @@ class ButlerPbImport extends sf_plugins_core_1.SfCommand {
68
223
  }
69
224
  return docConfigIds;
70
225
  }
71
- async run() {
72
- const { flags } = await this.parse(ButlerPbImport);
73
- const docConfigIds = ButlerPbImport.getDocConfigIds(flags.id);
74
- const zipArray = [];
75
- const jsonArray = [];
76
- const files = ButlerPbImport.getFiles(flags.config, docConfigIds, []);
77
- ButlerPbImport.isLogsActive = !!flags.logs;
78
- await Promise.all(files.map((fileName) => {
79
- const fullPath = fileName;
80
- if (fileName.endsWith('.json')) {
81
- jsonArray.push(fullPath);
226
+ static getLogLvl(result) {
227
+ if (result === constants_1.RESULT.FAILED) {
228
+ return 'error';
229
+ }
230
+ else if (result === constants_1.RESULT.SUCCESS || result === constants_1.RESULT.SUCCESS_WITH_WARNINGS) {
231
+ return 'success';
232
+ }
233
+ else {
234
+ return 'info';
235
+ }
236
+ }
237
+ static buildEndpointAuth(flags) {
238
+ if (flags.endpoint && !flags['auth-env-var']) {
239
+ logger_1.Logger.error(constants_1.ERROR.AUTH_ENV_VAR_REQUIRED);
240
+ return null;
241
+ }
242
+ const auth = flags['auth-env-var'];
243
+ let base64Auth = auth ?? '';
244
+ if (auth?.indexOf(':')) {
245
+ base64Auth = Buffer.from(auth).toString('base64');
246
+ }
247
+ const baseUrl = flags.endpoint ? `${flags.endpoint.toString()}` : '';
248
+ if (flags.endpoint && ButlerPbImport.isLogsActive) {
249
+ logger_1.Logger.info(constants_1.MESSAGE.ENDPOINT_URL.replace('[URL]', baseUrl));
250
+ }
251
+ return { baseUrl, base64Auth };
252
+ }
253
+ static getTemplatePaths(configDir, templateIds) {
254
+ const templateJsonPaths = templateIds
255
+ .map((id) => path.join(configDir, 'sfdc', `${id}.json`))
256
+ .filter((p) => fs.existsSync(p));
257
+ const templateZipTargets = templateIds
258
+ .map((id) => ButlerPbImport.getMainZipPath(configDir, id))
259
+ .filter((p) => typeof p === 'string' && fs.existsSync(p));
260
+ return { templateJsonPaths, templateZipTargets };
261
+ }
262
+ static extractTemplateIdsFromZip(zipPath) {
263
+ const templateIds = new Set();
264
+ const validRecordTypes = ['DOCUMENT_V3', 'DOCUMENT_V2', 'DOCUMENT_V1'];
265
+ const zip = new AdmZip(zipPath);
266
+ const collectFromRecord = (value) => {
267
+ if (!value || typeof value !== 'object')
268
+ return;
269
+ const rec = value;
270
+ const recordType = rec.recordType;
271
+ const templateId = rec.documentConfigTemplateId;
272
+ if (typeof recordType === 'string' && validRecordTypes.includes(recordType)) {
273
+ if (typeof templateId === 'string')
274
+ templateIds.add(templateId);
82
275
  }
83
- else {
84
- zipArray.push(fullPath);
276
+ };
277
+ for (const entry of zip.getEntries()) {
278
+ if (entry.isDirectory)
279
+ continue;
280
+ if (!entry.entryName.includes('ConfigTypes/') || !entry.entryName.endsWith('.json'))
281
+ continue;
282
+ try {
283
+ const raw = zip.readFile(entry);
284
+ if (!raw)
285
+ continue;
286
+ const json = JSON.parse(raw.toString('utf8'));
287
+ const records = Array.isArray(json) ? json : [json];
288
+ for (const rec of records) {
289
+ collectFromRecord(rec);
290
+ }
85
291
  }
86
- }));
87
- const targetUsername = flags.target;
88
- const session = flags.session;
89
- const instance = flags.instance;
90
- const connection = await (0, authentication_1.authenticate)(targetUsername, session, instance);
91
- let responses;
292
+ catch (e) {
293
+ logger_1.Logger.error(constants_1.MESSAGE.JSON_PARSE_FAILED.replace('[PATH]', entry.entryName));
294
+ }
295
+ }
296
+ return Array.from(templateIds);
297
+ }
298
+ static async getTemplateIdsFromMain(mainZipPath) {
299
+ if (mainZipPath.endsWith('.zip')) {
300
+ return ButlerPbImport.extractTemplateIdsFromZip(mainZipPath);
301
+ }
302
+ return (0, extract_templates_1.extractTemplateIds)(mainZipPath);
303
+ }
304
+ static async processTemplates(params) {
305
+ const { connection, templateIds, cloneTemplates, shouldClone, baseUrl, base64Auth, stage, hasEndpoint, configDir, } = params;
306
+ if (templateIds.length === 0)
307
+ return {};
308
+ const { templateJsonPaths, templateZipTargets } = ButlerPbImport.getTemplatePaths(configDir, templateIds);
309
+ let templateIdMap = {};
92
310
  try {
93
- if (jsonArray.length > 0) {
94
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
95
- responses = await Promise.all(jsonArray.map(async (jsonFile) => {
96
- const sfdcConfig = JSON.parse(await fs.promises.readFile(jsonFile, 'utf8'));
97
- return connection.apex.post(`/cadmus_core/DocConfig/Import/?isInsert=${flags.clone === undefined ? 'false' : 'true'}`, sfdcConfig, {
98
- headers: { 'content-type': 'application/json' },
99
- })
100
- .then((data) => data);
101
- }));
102
- logger_1.Logger.info(constants_1.MESSAGE.SUCCESS_DATA_WRITTEN, ButlerPbImport.isLogsActive);
311
+ if (ButlerPbImport.isLogsActive)
312
+ logger_1.Logger.info(constants_1.MESSAGE.IMPORT_TEMPLATES_SFDC);
313
+ templateIdMap = await ButlerPbImport.importSfdcJsons(connection, templateJsonPaths, cloneTemplates);
314
+ if (templateJsonPaths.length > 0 && ButlerPbImport.isLogsActive) {
315
+ logger_1.Logger.success(constants_1.MESSAGE.SUCCESS_DATA_WRITTEN);
103
316
  }
104
317
  }
105
318
  catch (e) {
106
319
  throw new Error(constants_1.ERROR.WRITE_DATA);
107
320
  }
108
- if (zipArray.length === 0 || !flags.endpoint) {
109
- return { success: false };
321
+ if (hasEndpoint && templateZipTargets.length > 0) {
322
+ if (ButlerPbImport.isLogsActive)
323
+ logger_1.Logger.info(constants_1.MESSAGE.IMPORT_TEMPLATES_ZIP);
324
+ await templateZipTargets.reduce(async (previous, zipTarget, index) => {
325
+ await previous;
326
+ try {
327
+ if (ButlerPbImport.isLogsActive) {
328
+ const templateId = path.parse(zipTarget).name;
329
+ logger_1.Logger.info(constants_1.MESSAGE.IMPORTING_ZIP_PROGRESS.replace('[INDEX]', String(index + 1))
330
+ .replace('[COUNT]', String(templateZipTargets.length))
331
+ .replace('[ID]', templateId));
332
+ const mappedTemplateId = templateIdMap[templateId] ?? templateId;
333
+ ButlerPbImport.logIdMappings('Template DocConfig', { [templateId]: mappedTemplateId });
334
+ }
335
+ await ButlerPbImport.sendZip(zipTarget, baseUrl, base64Auth, stage, cloneTemplates ? templateIdMap : {}, shouldClone);
336
+ }
337
+ catch (e) {
338
+ throw new Error(constants_1.ERROR.WRITE_DATA_TO_PDF);
339
+ }
340
+ }, Promise.resolve());
341
+ }
342
+ return templateIdMap;
343
+ }
344
+ static async importMainSfdc(connection, mainJsonPath, shouldClone, idMap) {
345
+ try {
346
+ if (ButlerPbImport.isLogsActive)
347
+ logger_1.Logger.info(constants_1.MESSAGE.IMPORT_MAIN_SFDC);
348
+ const mainIdMap = await ButlerPbImport.importSfdcJsons(connection, [mainJsonPath], shouldClone, idMap);
349
+ if (ButlerPbImport.isLogsActive)
350
+ logger_1.Logger.success(constants_1.MESSAGE.SUCCESS_DATA_WRITTEN);
351
+ return mainIdMap;
352
+ }
353
+ catch (e) {
354
+ throw new Error(constants_1.ERROR.WRITE_DATA);
110
355
  }
111
- if (flags.endpoint) {
112
- if (!flags['auth-env-var']) {
113
- logger_1.Logger.error(constants_1.ERROR.AUTH_ENV_VAR_REQUIRED);
114
- return { success: false };
356
+ }
357
+ static async sendMainZip(params) {
358
+ const { sourceMainId, mainId, mainZipPath, baseUrl, base64Auth, stage, idMap, shouldClone } = params;
359
+ try {
360
+ if (ButlerPbImport.isLogsActive) {
361
+ logger_1.Logger.info(constants_1.MESSAGE.IMPORTING_ZIP_WITH_ID.replace('[ID]', mainId));
362
+ ButlerPbImport.logIdMappings('Main DocConfig', { [sourceMainId]: mainId });
115
363
  }
116
- const auth = flags['auth-env-var'];
117
- let base64Auth = auth;
118
- if (auth?.indexOf(':')) {
119
- base64Auth = Buffer.from(auth).toString('base64');
364
+ await ButlerPbImport.sendZip(mainZipPath, baseUrl, base64Auth, stage, idMap, shouldClone);
365
+ }
366
+ catch (e) {
367
+ throw new Error(constants_1.ERROR.WRITE_DATA_TO_PDF);
368
+ }
369
+ }
370
+ static async processMainImport(params) {
371
+ const { connection, flags, mainId, index, total, baseUrl, base64Auth, cloneTemplates, shouldClone, shouldProcessTemplates, globalTemplateIdMap, } = params;
372
+ if (ButlerPbImport.isLogsActive) {
373
+ logger_1.Logger.info(constants_1.MESSAGE.START_IMPORT_MAIN.replace('[INDEX]', String(index))
374
+ .replace('[COUNT]', String(total))
375
+ .replace('[ID]', mainId));
376
+ }
377
+ const mainJsonPath = path.join(flags.config, 'sfdc', `${mainId}.json`);
378
+ if (!fs.existsSync(mainJsonPath)) {
379
+ throw new Error(constants_1.ERROR.NO_MATCHING_FILES);
380
+ }
381
+ const mainZipPath = ButlerPbImport.getMainZipPath(flags.config, mainId);
382
+ let templateIdMap = {};
383
+ if (mainZipPath) {
384
+ const foundTemplateIds = await ButlerPbImport.getTemplateIdsFromMain(mainZipPath);
385
+ const existingTemplateMap = {};
386
+ for (const id of foundTemplateIds) {
387
+ if (globalTemplateIdMap[id])
388
+ existingTemplateMap[id] = globalTemplateIdMap[id];
120
389
  }
121
- const baseUrl = `${flags.endpoint.toString()}`;
122
- logger_1.Logger.info(constants_1.MESSAGE.ENDPOINT_URL.replace('[URL]', baseUrl), ButlerPbImport.isLogsActive);
123
- zipArray.map(async (zipName) => {
124
- let zip = new AdmZip();
125
- if (zipName.endsWith('zip')) {
126
- zip = new AdmZip(zipName);
127
- }
128
- else {
129
- zip.addLocalFolder(zipName);
130
- }
131
- const zipToSend = new AdmZip();
132
- for (const entry of zip.getEntries()) {
133
- if (entry != null) {
134
- zipToSend.addFile(entry.entryName, zip.readFile(entry));
135
- if (flags.clone && entry.entryName === 'doc-config.json') {
136
- const fileContent = zip.readFile(entry);
137
- /* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */
138
- const docConfig = JSON.parse(fileContent.toString('utf-8'));
139
- responses.forEach((element) => {
140
- if (typeof element === 'object' && element !== null) {
141
- const elementObj = element;
142
- if (elementObj[docConfig.customerDocumentConfigId] !== undefined) {
143
- docConfig.customerDocumentConfigId = elementObj[docConfig.customerDocumentConfigId];
144
- }
145
- }
146
- });
147
- zipToSend.updateFile(entry, Buffer.from(JSON.stringify(docConfig)));
148
- }
149
- }
150
- }
151
- const txt = zip.readAsText('doc-config.json');
152
- const recordType = JSON.parse(txt).recordType;
153
- const targetPath = ButlerPbImport.getTargetPath(recordType);
154
- const finalUrl = `${baseUrl}${targetPath}`;
155
- logger_1.Logger.info(constants_1.MESSAGE.FINAL_URL.replace('[URL]', finalUrl), ButlerPbImport.isLogsActive);
156
- const fd = new FormData();
157
- fd.append('zip', zipToSend.toBuffer(), { filename: 'zip' });
158
- fd.append('metadata', JSON.stringify({
159
- stage: flags.stage,
160
- version: 'v10.0',
161
- }), { contentType: 'application/json' });
162
- try {
163
- const res = await got_1.default.post(finalUrl, {
164
- body: fd,
165
- headers: { Authorization: `Basic ${base64Auth}` },
166
- responseType: 'json',
167
- });
168
- const body = res.body;
169
- const status = body?.result ?? constants_1.RESULT.FAILED;
170
- const description = body?.issues?.[0]?.description ?? constants_1.ERROR.UNKNOWN_SERVER;
171
- const message = description ?? constants_1.ERROR.UNKNOWN_SERVER;
172
- if (status === constants_1.RESULT.FAILED) {
173
- logger_1.Logger.error(message);
174
- }
175
- else if (status === constants_1.RESULT.SUCCESS || constants_1.RESULT.SUCCESS_WITH_WARNINGS) {
176
- logger_1.Logger.success(message);
390
+ templateIdMap = { ...existingTemplateMap };
391
+ if (shouldClone && !shouldProcessTemplates && foundTemplateIds.length > 0) {
392
+ logger_1.Logger.warn(constants_1.MESSAGE.TEMPLATES_DETECTED_WARNING.replace('[ID]', mainId).replace('[TEMPLATES]', foundTemplateIds.join(', ')));
393
+ }
394
+ if (shouldProcessTemplates) {
395
+ const newTemplateIds = foundTemplateIds.filter((id) => !globalTemplateIdMap[id]);
396
+ if (ButlerPbImport.isLogsActive) {
397
+ if (foundTemplateIds.length > 0) {
398
+ logger_1.Logger.info(constants_1.MESSAGE.FOUND_TEMPLATES.replace('[COUNT]', String(foundTemplateIds.length)));
177
399
  }
178
400
  else {
179
- logger_1.Logger.info(message);
401
+ logger_1.Logger.info(constants_1.MESSAGE.NO_TEMPLATES_FOUND);
180
402
  }
181
403
  }
182
- catch (e) {
183
- throw new Error(constants_1.ERROR.WRITE_DATA_TO_PDF);
184
- }
185
- });
404
+ const newTemplateIdMap = await ButlerPbImport.processTemplates({
405
+ connection,
406
+ templateIds: newTemplateIds,
407
+ cloneTemplates,
408
+ shouldClone,
409
+ baseUrl,
410
+ base64Auth,
411
+ stage: flags.stage,
412
+ hasEndpoint: Boolean(flags.endpoint),
413
+ configDir: flags.config,
414
+ });
415
+ Object.assign(globalTemplateIdMap, newTemplateIdMap);
416
+ Object.assign(templateIdMap, newTemplateIdMap);
417
+ }
418
+ }
419
+ if (cloneTemplates && Object.keys(templateIdMap).length > 0 && ButlerPbImport.isLogsActive) {
420
+ logger_1.Logger.info(constants_1.MESSAGE.UPDATE_MAIN_WITH_TEMPLATE_IDS);
186
421
  }
422
+ const mainIdMap = await ButlerPbImport.importMainSfdc(connection, mainJsonPath, shouldClone, templateIdMap);
423
+ const importedMainId = mainIdMap[mainId] ?? mainId;
424
+ if (!flags.endpoint || !mainZipPath) {
425
+ throw new Error(constants_1.ERROR.WRITE_DATA_TO_PDF);
426
+ }
427
+ await ButlerPbImport.sendMainZip({
428
+ sourceMainId: mainId,
429
+ mainId: importedMainId,
430
+ mainZipPath,
431
+ baseUrl,
432
+ base64Auth,
433
+ stage: flags.stage,
434
+ idMap: { ...templateIdMap, ...mainIdMap },
435
+ shouldClone,
436
+ });
437
+ }
438
+ async run() {
439
+ const { flags } = (await this.parse(ButlerPbImport));
440
+ const docConfigIds = ButlerPbImport.getDocConfigIds(flags.id);
441
+ ButlerPbImport.isLogsActive = flags.logs === true;
442
+ if (ButlerPbImport.isLogsActive) {
443
+ logger_1.Logger.info(constants_1.MESSAGE.SPLITTED_DOC_CONFIGS.replace('[VALUE]', String(docConfigIds.length)));
444
+ }
445
+ const targetUsername = flags.target;
446
+ const session = flags.session;
447
+ const instance = flags.instance;
448
+ const connection = (await (0, authentication_1.authenticate)(targetUsername, session, instance));
449
+ const shouldClone = flags.clone === true;
450
+ const shouldProcessTemplates = flags.templates === true;
451
+ const cloneTemplates = shouldProcessTemplates ? shouldClone : false;
452
+ const endpointAuth = ButlerPbImport.buildEndpointAuth(flags);
453
+ if (!endpointAuth)
454
+ return { success: false };
455
+ const { baseUrl, base64Auth } = endpointAuth;
456
+ const globalTemplateIdMap = {};
457
+ await docConfigIds.reduce(async (previous, mainId, index) => {
458
+ await previous;
459
+ await ButlerPbImport.processMainImport({
460
+ connection,
461
+ flags,
462
+ mainId,
463
+ index: index + 1,
464
+ total: docConfigIds.length,
465
+ baseUrl,
466
+ base64Auth,
467
+ cloneTemplates,
468
+ shouldClone,
469
+ shouldProcessTemplates,
470
+ globalTemplateIdMap,
471
+ });
472
+ }, Promise.resolve());
187
473
  return { success: true };
188
474
  }
189
475
  }
190
- ButlerPbImport.summary = messages.getMessage('summary');
191
- ButlerPbImport.description = messages.getMessage('description');
192
- ButlerPbImport.examples = messages.getMessages('examples');
193
- ButlerPbImport.flags = {
194
- name: sf_plugins_core_1.Flags.string({
195
- summary: messages.getMessage('flags.name.summary'),
196
- description: messages.getMessage('flags.name.description'),
197
- char: 'n',
198
- required: false,
199
- }),
200
- target: sf_plugins_core_1.Flags.string({
201
- summary: messages.getMessage('flags.target.summary'),
202
- char: 't',
203
- required: false,
204
- }),
205
- 'auth-env-var': sf_plugins_core_1.Flags.string({
206
- summary: messages.getMessage('flags.auth-env-var.summary'),
207
- char: 'a',
208
- }),
209
- endpoint: sf_plugins_core_1.Flags.url({
210
- summary: messages.getMessage('flags.endpoint.summary'),
211
- char: 'e',
212
- }),
213
- stage: sf_plugins_core_1.Flags.string({
214
- summary: messages.getMessage('flags.stage.summary'),
215
- char: 's',
216
- }),
217
- config: sf_plugins_core_1.Flags.string({
218
- summary: messages.getMessage('flags.config.summary'),
219
- char: 'f',
220
- required: true,
221
- }),
222
- logs: sf_plugins_core_1.Flags.boolean({
223
- summary: messages.getMessage('flags.logs.summary'),
224
- char: 'l',
225
- }),
226
- id: sf_plugins_core_1.Flags.string({
227
- summary: messages.getMessage('flags.id.summary'),
228
- char: 'i',
229
- required: true,
230
- }),
231
- clone: sf_plugins_core_1.Flags.boolean({
232
- // eslint-disable-next-line sf-plugin/no-missing-messages
233
- summary: messages.getMessage('flags.clone.summary'),
234
- char: 'c',
235
- }),
236
- session: sf_plugins_core_1.Flags.string({
237
- summary: messages.getMessage('flags.session.summary'),
238
- }),
239
- instance: sf_plugins_core_1.Flags.string({
240
- summary: messages.getMessage('flags.instance.summary'),
241
- }),
242
- };
243
- ButlerPbImport.isLogsActive = false;
244
476
  exports.default = ButlerPbImport;
245
477
  //# sourceMappingURL=import.js.map