@pdfbutler/migration-cli 0.0.26 → 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 (51) hide show
  1. package/README.md +193 -30
  2. package/lib/commands/butler/pb/admincredentials.d.ts +0 -5
  3. package/lib/commands/butler/pb/admincredentials.js +46 -115
  4. package/lib/commands/butler/pb/admincredentials.js.map +1 -1
  5. package/lib/commands/butler/pb/adminsettings.d.ts +1 -7
  6. package/lib/commands/butler/pb/adminsettings.js +41 -110
  7. package/lib/commands/butler/pb/adminsettings.js.map +1 -1
  8. package/lib/commands/butler/pb/export.d.ts +10 -8
  9. package/lib/commands/butler/pb/export.js +302 -312
  10. package/lib/commands/butler/pb/export.js.map +1 -1
  11. package/lib/commands/butler/pb/exportdatasource.d.ts +27 -0
  12. package/lib/commands/butler/pb/exportdatasource.js +161 -0
  13. package/lib/commands/butler/pb/exportdatasource.js.map +1 -0
  14. package/lib/commands/butler/pb/exportpack.d.ts +0 -5
  15. package/lib/commands/butler/pb/exportpack.js +60 -142
  16. package/lib/commands/butler/pb/exportpack.js.map +1 -1
  17. package/lib/commands/butler/pb/import.d.ts +16 -9
  18. package/lib/commands/butler/pb/import.js +400 -267
  19. package/lib/commands/butler/pb/import.js.map +1 -1
  20. package/lib/commands/butler/pb/importdatasource.d.ts +30 -0
  21. package/lib/commands/butler/pb/importdatasource.js +250 -0
  22. package/lib/commands/butler/pb/importdatasource.js.map +1 -0
  23. package/lib/commands/butler/pb/importpack.d.ts +0 -5
  24. package/lib/commands/butler/pb/importpack.js +57 -138
  25. package/lib/commands/butler/pb/importpack.js.map +1 -1
  26. package/lib/commands/butler/sb/export/signtemplate.d.ts +23 -0
  27. package/lib/commands/butler/sb/export/signtemplate.js +111 -0
  28. package/lib/commands/butler/sb/export/signtemplate.js.map +1 -0
  29. package/lib/commands/butler/sb/import/signtemplate.d.ts +23 -0
  30. package/lib/commands/butler/sb/import/signtemplate.js +108 -0
  31. package/lib/commands/butler/sb/import/signtemplate.js.map +1 -0
  32. package/lib/utils/authentication.d.ts +4 -0
  33. package/lib/utils/authentication.js +69 -0
  34. package/lib/utils/authentication.js.map +1 -0
  35. package/lib/utils/constants.d.ts +137 -0
  36. package/lib/utils/constants.js +141 -0
  37. package/lib/utils/constants.js.map +1 -0
  38. package/lib/utils/extract-templates.d.ts +1 -0
  39. package/lib/utils/extract-templates.js +89 -0
  40. package/lib/utils/extract-templates.js.map +1 -0
  41. package/lib/utils/logger.d.ts +9 -0
  42. package/lib/utils/logger.js +51 -0
  43. package/lib/utils/logger.js.map +1 -0
  44. package/messages/butler.pb.export.md +4 -0
  45. package/messages/butler.pb.exportdatasource.md +51 -0
  46. package/messages/butler.pb.import.md +4 -0
  47. package/messages/butler.pb.importdatasource.md +51 -0
  48. package/messages/butler.sb.export.signtemplate.md +35 -0
  49. package/messages/butler.sb.import.signtemplate.md +35 -0
  50. package/oclif.manifest.json +321 -48
  51. package/package.json +223 -215
@@ -1,33 +1,124 @@
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");
18
- const jsforce = require('jsforce');
19
- const MSG_CONNECTION_FAILED = 'Connection to Salesforce has been failed.';
20
- const MSG_CREATION_CONNECTION = 'Creating Connection with the Salesforce org.';
21
- const MSG_AUTHORIZATION = 'Authorization with the username: [VALUE].';
22
- const MSG_NO_AUTH_PARAMS = 'No authentication parameters provided. Please provide either username or session and instance parameters.';
23
- const MSG_RUN_AUTH_COMMAND = 'Run the command "sf org login web" before authenticating with the target.';
24
- const MSG_CHECK_SESSION_INSTANCE = 'Check if the session is up to date and if the instance is correct.';
25
- const RESULT_STATUS_FAILED = 'FAILED';
26
- const RESULT_STATUS_SUCCESS = 'SUCCESS';
27
- const RESULT_STATUS_SUCCESS_WITH_WARNINGS = 'SUCCESS_WITH_WARNINGS';
12
+ const got_1 = __importDefault(require("got"));
13
+ const logger_1 = require("../../../utils/logger");
14
+ const authentication_1 = require("../../../utils/authentication");
15
+ const constants_1 = require("../../../utils/constants");
16
+ const extract_templates_1 = require("../../../utils/extract-templates");
28
17
  core_1.Messages.importMessagesDirectory(__dirname);
29
18
  const messages = core_1.Messages.loadMessages('@pdfbutler/migration-cli', 'butler.pb.import');
30
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
+ }
31
122
  static getTargetPath(recordType) {
32
123
  switch (recordType) {
33
124
  case 'EXCEL':
@@ -43,25 +134,82 @@ class ButlerPbImport extends sf_plugins_core_1.SfCommand {
43
134
  case 'CSV':
44
135
  return 'config/csv/import-config';
45
136
  }
46
- throw new Error('Unsupported record type');
137
+ throw new Error(constants_1.ERROR.UNSUPPORTED_RECORD_TYPE);
138
+ }
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;
47
147
  }
48
- static getFiles(dir, docConfigIds, files) {
49
- const fileList = fs.readdirSync(dir, { withFileTypes: true });
50
- for (const file of fileList) {
51
- const name = `${dir}/${file.name}`;
52
- if (fs.statSync(name).isDirectory() && file.name === 'sfdc') {
53
- ButlerPbImport.getFiles(name, docConfigIds, files);
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
+ }
54
163
  }
55
- else {
56
- if (!docConfigIds.includes(path.parse(file.name).name))
57
- continue;
58
- 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));
59
179
  }
60
180
  }
61
- if (files.length <= 0) {
62
- throw new Error('No matching files found');
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;
63
212
  }
64
- return files;
65
213
  }
66
214
  static getDocConfigIds(id) {
67
215
  const docConfigIds = id.split(/([\w-]{36})/).filter((n) => n);
@@ -71,274 +219,259 @@ class ButlerPbImport extends sf_plugins_core_1.SfCommand {
71
219
  }
72
220
  });
73
221
  if (docConfigIds.length <= 0) {
74
- throw new Error('No matching Doc Configs ids found');
222
+ throw new Error(constants_1.ERROR.NO_MATCHING_DOC_CONFIGS);
75
223
  }
76
224
  return docConfigIds;
77
225
  }
78
- static isBlank(value) {
79
- return value?.trim() === ''
80
- || value === null
81
- || value === undefined;
82
- }
83
- static log(message, type = 'info') {
84
- let prefix = '';
85
- let color = '';
86
- switch (type) {
87
- case 'error':
88
- prefix = '[ERROR]';
89
- color = this.colors.red;
90
- break;
91
- case 'success':
92
- prefix = '[SUCCESS]';
93
- color = this.colors.green;
94
- break;
95
- default:
96
- prefix = '[INFO]';
97
- color = this.colors.reset;
98
- break;
226
+ static getLogLvl(result) {
227
+ if (result === constants_1.RESULT.FAILED) {
228
+ return 'error';
99
229
  }
100
- console.log(`${color}${prefix} ${message}${this.colors.reset}`);
101
- }
102
- static async authenticateWithTarget(username) {
103
- try {
104
- if (this.isLogsActive)
105
- this.log(MSG_AUTHORIZATION.replace('[VALUE]', username));
106
- const authInfo = await core_1.AuthInfo.create({ username });
107
- if (this.isLogsActive)
108
- this.log(MSG_CREATION_CONNECTION);
109
- const connection = await core_1.Connection.create({ authInfo });
110
- this.log(`Connected to ${username} (Org ID: ${authInfo.getFields().orgId})`);
111
- return connection;
112
- }
113
- catch (error) {
114
- this.log(MSG_RUN_AUTH_COMMAND, 'error');
115
- throw new Error(MSG_CONNECTION_FAILED);
230
+ else if (result === constants_1.RESULT.SUCCESS || result === constants_1.RESULT.SUCCESS_WITH_WARNINGS) {
231
+ return 'success';
232
+ }
233
+ else {
234
+ return 'info';
116
235
  }
117
236
  }
118
- static async authenticateWitsSession(session, instance) {
119
- if (!this.isBlank(instance) && !this.isBlank(session)) {
120
- const connection = await new jsforce.Connection({
121
- instanceUrl: `${instance}`,
122
- sessionId: `${session}`,
123
- });
124
- this.log(`Connected to ${connection.instanceUrl}`);
125
- return connection;
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;
126
241
  }
127
- else if (!this.isBlank(session) && this.isBlank(instance)) {
128
- this.log('Instance URL (--instance) cannot be empty', 'error');
242
+ const auth = flags['auth-env-var'];
243
+ let base64Auth = auth ?? '';
244
+ if (auth?.indexOf(':')) {
245
+ base64Auth = Buffer.from(auth).toString('base64');
129
246
  }
130
- else if (this.isBlank(session) && !this.isBlank(instance)) {
131
- this.log('Session Id (--session) cannot be empty', 'error');
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));
132
250
  }
133
- else {
134
- this.log('Session Id and Instance URL (--session and --instance) cannot be empty', 'error');
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);
275
+ }
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
+ }
291
+ }
292
+ catch (e) {
293
+ logger_1.Logger.error(constants_1.MESSAGE.JSON_PARSE_FAILED.replace('[PATH]', entry.entryName));
294
+ }
135
295
  }
136
- this.log(MSG_CHECK_SESSION_INSTANCE, 'error');
137
- throw new Error(MSG_CONNECTION_FAILED);
296
+ return Array.from(templateIds);
138
297
  }
139
- static async authenticate(username, session, instance) {
140
- let connection;
141
- if (this.isBlank(username) && (this.isBlank(session) || this.isBlank(instance))) {
142
- throw new Error(MSG_NO_AUTH_PARAMS);
298
+ static async getTemplateIdsFromMain(mainZipPath) {
299
+ if (mainZipPath.endsWith('.zip')) {
300
+ return ButlerPbImport.extractTemplateIdsFromZip(mainZipPath);
143
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 = {};
144
310
  try {
145
- if (this.isBlank(session) || this.isBlank(instance)) {
146
- connection = await this.authenticateWithTarget(username);
147
- }
148
- else {
149
- connection = await this.authenticateWitsSession(session, instance);
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);
150
316
  }
151
- return connection;
152
317
  }
153
- catch (error) {
154
- throw new Error(MSG_CONNECTION_FAILED);
318
+ catch (e) {
319
+ throw new Error(constants_1.ERROR.WRITE_DATA);
155
320
  }
156
- }
157
- static getLogLvl(result) {
158
- if (result === RESULT_STATUS_FAILED) {
159
- return 'error';
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());
160
341
  }
161
- else if (result === RESULT_STATUS_SUCCESS || RESULT_STATUS_SUCCESS_WITH_WARNINGS) {
162
- return 'success';
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;
163
352
  }
164
- else {
165
- return 'info';
353
+ catch (e) {
354
+ throw new Error(constants_1.ERROR.WRITE_DATA);
166
355
  }
167
356
  }
168
- async run() {
169
- const { flags } = await this.parse(ButlerPbImport);
170
- const docConfigIds = ButlerPbImport.getDocConfigIds(flags.id);
171
- const zipArray = [];
172
- const jsonArray = [];
173
- const files = ButlerPbImport.getFiles(flags.config, docConfigIds, []);
174
- ButlerPbImport.isLogsActive = flags.logs;
175
- await Promise.all(files.map((fileName) => {
176
- const fullPath = fileName;
177
- if (fileName.endsWith('.json')) {
178
- jsonArray.push(fullPath);
179
- }
180
- else {
181
- zipArray.push(fullPath);
182
- }
183
- }));
184
- const targetUsername = flags.target;
185
- const session = flags.session;
186
- const instance = flags.instance;
187
- const connection = await ButlerPbImport.authenticate(targetUsername, session, instance);
188
- let responses;
357
+ static async sendMainZip(params) {
358
+ const { sourceMainId, mainId, mainZipPath, baseUrl, base64Auth, stage, idMap, shouldClone } = params;
189
359
  try {
190
- if (jsonArray.length > 0) {
191
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
192
- responses = await Promise.all(jsonArray.map(async (jsonFile) => {
193
- const sfdcConfig = JSON.parse(await fs.promises.readFile(jsonFile, 'utf8'));
194
- return connection.apex.post(`/cadmus_core/DocConfig/Import/?isInsert=${flags.clone === undefined ? 'false' : 'true'}`, sfdcConfig, {
195
- headers: { 'content-type': 'application/json' },
196
- })
197
- .then((data) => data);
198
- }));
199
- if (ButlerPbImport.isLogsActive)
200
- ButlerPbImport.log('Data successfully written to the target Salesforce org');
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 });
201
363
  }
364
+ await ButlerPbImport.sendZip(mainZipPath, baseUrl, base64Auth, stage, idMap, shouldClone);
202
365
  }
203
366
  catch (e) {
204
- throw new Error('Failed to write data to the target Salesforce org');
367
+ throw new Error(constants_1.ERROR.WRITE_DATA_TO_PDF);
205
368
  }
206
- if (ButlerPbImport.isLogsActive)
207
- ButlerPbImport.log(`zipArray.length - ${zipArray.length}`);
208
- if (zipArray.length === 0 || !flags.endpoint) {
209
- return { success: false };
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);
210
380
  }
211
- if (flags.endpoint) {
212
- if (!flags['auth-env-var']) {
213
- ButlerPbImport.log('auth-env-var parameter is required when endpoint is provided', 'error');
214
- return { success: false };
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];
215
389
  }
216
- const auth = flags['auth-env-var'];
217
- let base64Auth = auth;
218
- if (auth?.indexOf(':')) {
219
- base64Auth = Buffer.from(auth).toString('base64');
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(', ')));
220
393
  }
221
- const baseUrl = `${flags.endpoint.toString()}`;
222
- if (ButlerPbImport.isLogsActive)
223
- ButlerPbImport.log(`Endpoint base URL - ${baseUrl}`);
224
- zipArray.map(async (zipName) => {
225
- let zip = new AdmZip();
226
- if (zipName.endsWith('zip')) {
227
- zip = new AdmZip(zipName);
228
- }
229
- else {
230
- zip.addLocalFolder(zipName);
231
- }
232
- const zipToSend = new AdmZip();
233
- for (const entry of zip.getEntries()) {
234
- if (entry != null) {
235
- zipToSend.addFile(entry.entryName, zip.readFile(entry));
236
- if (flags.clone && entry.entryName === 'doc-config.json') {
237
- const fileContent = zip.readFile(entry);
238
- /* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */
239
- const docConfig = JSON.parse(fileContent.toString('utf-8'));
240
- responses.forEach((element) => {
241
- if (typeof element === 'object' && element !== null) {
242
- const elementObj = element;
243
- if (elementObj[docConfig.customerDocumentConfigId] !== undefined) {
244
- docConfig.customerDocumentConfigId = elementObj[docConfig.customerDocumentConfigId];
245
- }
246
- }
247
- });
248
- zipToSend.updateFile(entry, Buffer.from(JSON.stringify(docConfig)));
249
- }
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)));
399
+ }
400
+ else {
401
+ logger_1.Logger.info(constants_1.MESSAGE.NO_TEMPLATES_FOUND);
250
402
  }
251
403
  }
252
- const txt = zip.readAsText('doc-config.json');
253
- if (ButlerPbImport.isLogsActive)
254
- ButlerPbImport.log(`doc-config.json length - ${txt.length}`);
255
- const recordType = JSON.parse(txt).recordType;
256
- const targetPath = ButlerPbImport.getTargetPath(recordType);
257
- const finalUrl = `${baseUrl}${targetPath}`;
258
- if (ButlerPbImport.isLogsActive)
259
- ButlerPbImport.log(`Final URL - ${finalUrl}`);
260
- const fd = new FormData();
261
- fd.append('zip', zipToSend.toBuffer(), { filename: 'zip' });
262
- fd.append('metadata', JSON.stringify({
404
+ const newTemplateIdMap = await ButlerPbImport.processTemplates({
405
+ connection,
406
+ templateIds: newTemplateIds,
407
+ cloneTemplates,
408
+ shouldClone,
409
+ baseUrl,
410
+ base64Auth,
263
411
  stage: flags.stage,
264
- version: 'v10.0',
265
- }), { contentType: 'application/json' });
266
- try {
267
- const res = await got_1.default.post(finalUrl, {
268
- body: fd,
269
- headers: { Authorization: `Basic ${base64Auth}` },
270
- responseType: 'json',
271
- });
272
- const body = res.body;
273
- ButlerPbImport.log(body?.issues?.[0]?.description, ButlerPbImport.getLogLvl(body?.result));
274
- }
275
- catch (e) {
276
- throw new Error('Failed to write data to the PDF Butler system');
277
- }
278
- });
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);
279
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());
280
473
  return { success: true };
281
474
  }
282
475
  }
283
- ButlerPbImport.summary = messages.getMessage('summary');
284
- ButlerPbImport.description = messages.getMessage('description');
285
- ButlerPbImport.examples = messages.getMessages('examples');
286
- ButlerPbImport.flags = {
287
- name: sf_plugins_core_1.Flags.string({
288
- summary: messages.getMessage('flags.name.summary'),
289
- description: messages.getMessage('flags.name.description'),
290
- char: 'n',
291
- required: false,
292
- }),
293
- target: sf_plugins_core_1.Flags.string({
294
- summary: messages.getMessage('flags.target.summary'),
295
- char: 't',
296
- required: false,
297
- }),
298
- 'auth-env-var': sf_plugins_core_1.Flags.string({
299
- summary: messages.getMessage('flags.auth-env-var.summary'),
300
- char: 'a',
301
- }),
302
- endpoint: sf_plugins_core_1.Flags.url({
303
- summary: messages.getMessage('flags.endpoint.summary'),
304
- char: 'e',
305
- }),
306
- stage: sf_plugins_core_1.Flags.string({
307
- summary: messages.getMessage('flags.stage.summary'),
308
- char: 's',
309
- }),
310
- config: sf_plugins_core_1.Flags.string({
311
- summary: messages.getMessage('flags.config.summary'),
312
- char: 'f',
313
- required: true,
314
- }),
315
- logs: sf_plugins_core_1.Flags.boolean({
316
- summary: messages.getMessage('flags.logs.summary'),
317
- char: 'l',
318
- }),
319
- id: sf_plugins_core_1.Flags.string({
320
- summary: messages.getMessage('flags.id.summary'),
321
- char: 'i',
322
- required: true,
323
- }),
324
- clone: sf_plugins_core_1.Flags.boolean({
325
- // eslint-disable-next-line sf-plugin/no-missing-messages
326
- summary: messages.getMessage('flags.clone.summary'),
327
- char: 'c',
328
- }),
329
- session: sf_plugins_core_1.Flags.string({
330
- summary: messages.getMessage('flags.session.summary'),
331
- }),
332
- instance: sf_plugins_core_1.Flags.string({
333
- summary: messages.getMessage('flags.instance.summary'),
334
- }),
335
- };
336
- ButlerPbImport.colors = {
337
- blue: '\x1b[34m',
338
- green: '\x1b[32m',
339
- red: '\x1b[31m',
340
- reset: '\x1b[0m',
341
- };
342
- ButlerPbImport.isLogsActive = false;
343
476
  exports.default = ButlerPbImport;
344
477
  //# sourceMappingURL=import.js.map