@pdfbutler/migration-cli 0.0.27 → 0.0.29

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