-
Notifications
You must be signed in to change notification settings - Fork 36
/
Automation.js
1570 lines (1493 loc) · 66.6 KB
/
Automation.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const MetadataType = require('./MetadataType');
const TYPE = require('../../types/mcdev.d');
const Util = require('../util/util');
const File = require('../util/file');
const Definitions = require('../MetadataTypeDefinitions');
const cache = require('../util/cache');
const pLimit = require('p-limit');
/**
* Automation MetadataType
*
* @augments MetadataType
*/
class Automation extends MetadataType {
static notificationUpdates = {};
/**
* Retrieves Metadata of Automation
*
* @param {string} retrieveDir Directory where retrieved metadata directory will be saved
* @param {void} [_] unused parameter
* @param {void} [__] unused parameter
* @param {string} [key] customer key of single item to retrieve
* @returns {Promise.<TYPE.AutomationMapObj>} Promise of metadata
*/
static async retrieve(retrieveDir, _, __, key) {
/** @type {TYPE.SoapRequestParams} */
let requestParams = null;
if (key) {
requestParams = {
filter: {
leftOperand: 'CustomerKey',
operator: 'equals',
rightOperand: key,
},
};
}
const results = await this.client.soap.retrieveBulk('Program', ['ObjectID'], requestParams);
if (results.Results?.length && !key) {
// empty results will come back without "Results" defined
Util.logger.info(
Util.getGrayMsg(
` - ${results.Results?.length} automation${
results.Results?.length === 1 ? '' : 's'
} found. Retrieving details...`
)
);
}
// the API seems to handle 100 concurrent requests nicely
const rateLimit = pLimit(100);
const details = results.Results
? await Promise.all(
results.Results.map(async (item) =>
rateLimit(async () => {
try {
return await this.client.rest.get(
'/automation/v1/automations/' + item.ObjectID
);
} catch (ex) {
try {
if (ex.message == 'socket hang up') {
// one more retry; it's a rare case but retrying again should solve the issue gracefully
return await this.client.rest.get(
'/automation/v1/automations/' + item.ObjectID
);
}
} catch {
// no extra action needed, handled below
}
// if we do get here, we should log the error and continue instead of failing to download all automations
Util.logger.error(
` ☇ skipping Automation ${item.ObjectID}: ${ex.message} ${ex.code}`
);
return null;
}
})
)
)
: [];
// * if retrieving some automations fails, a null element would remain in the details-array for each of them that needs to be filtered to prevent it from causing issues elsewhere
let metadataMap = this.parseResponseBody({ items: details.filter(Boolean) });
if (Object.keys(metadataMap).length) {
// attach notification information to each automation that has any
await this.#getAutomationNotificationsREST(metadataMap);
}
// * retrieveDir can be empty when we use it in the context of postDeployTasks
if (retrieveDir) {
metadataMap = await this.saveResults(metadataMap, retrieveDir, null, null);
Util.logger.info(
`Downloaded: ${this.definition.type} (${Object.keys(metadataMap).length})` +
Util.getKeysString(key)
);
await this.runDocumentOnRetrieve(key, metadataMap);
}
return { metadata: metadataMap, type: this.definition.type };
}
/**
* helper for {@link Automation.retrieve} to get Automation Notifications
*
* @private
* @param {TYPE.MetadataTypeMap} metadataMap keyField => metadata map
* @returns {Promise.<void>} Promise of nothing
*/
static async #getAutomationNotificationsREST(metadataMap) {
Util.logger.info(Util.getGrayMsg(` Retrieving Automation Notification information...`));
// get list of keys that we retrieved so far
const foundKeys = Object.keys(metadataMap);
// get encodedAutomationID to retrieve notification information
const iteratorBackup = this.definition.bodyIteratorField;
this.definition.bodyIteratorField = 'entry';
const automationLegacyMapObj = await super.retrieveREST(
undefined,
`/legacy/v1/beta/bulk/automations/automation/definition/`
);
this.definition.bodyIteratorField = iteratorBackup;
const automationLegacyMap = Object.keys(automationLegacyMapObj.metadata)
.filter((key) => foundKeys.includes(key))
// ! using the `id` field to retrieve notifications does not work. instead one needs to use the URL in the `notifications` field
.map((key) => ({
id: automationLegacyMapObj.metadata[key].id,
key,
}));
// get notifications for each automation
const rateLimit = pLimit(5);
let found = 0;
let skipped = 0;
const promiseMap = await Promise.all(
automationLegacyMap.map((automationLegacy) =>
rateLimit(async () => {
// this is a file so extended is at another endpoint
try {
const notificationsResult = await this.client.rest.get(
'/legacy/v1/beta/automations/notifications/' + automationLegacy.id
);
if (Array.isArray(notificationsResult?.workers)) {
metadataMap[automationLegacy.key].notifications =
notificationsResult.workers.map((n) => ({
email: n.definition.split(',').map((item) => item.trim()),
message: n.body,
type: n.notificationType,
}));
found++;
} else {
if (
!notificationsResult ||
typeof notificationsResult !== 'object' ||
Object.keys(notificationsResult).length !== 1 ||
!notificationsResult?.programId
) {
throw new TypeError(JSON.stringify(notificationsResult));
}
// * if there are no automation notifications, the API returns a single object with the programId
}
} catch (ex) {
Util.logger.debug(
` ☇ issue retrieving Notifications for automation ${automationLegacy.key}: ${ex.message} ${ex.code}`
);
skipped++;
}
})
)
);
Util.logger.info(
Util.getGrayMsg(` Notifications found for ${found} automation${found === 1 ? '' : 's'}`)
);
Util.logger.debug(
`Notifications not found for ${skipped} automation${skipped === 1 ? '' : 's'}`
);
return promiseMap;
}
/**
* Retrieves Metadata of Automation
*
* @returns {Promise.<TYPE.AutomationMapObj>} Promise of metadata
*/
static async retrieveChangelog() {
const results = await this.client.soap.retrieveBulk('Program', ['ObjectID']);
const details = [];
for (const item of results.Results
? await Promise.all(
results.Results.map((a) =>
this.client.soap.retrieveBulk(
'Automation',
[
'ProgramID',
'Name',
'CustomerKey',
'CategoryID',
'LastSaveDate',
'LastSavedBy',
'CreatedBy',
'CreatedDate',
],
{
filter: {
leftOperand: 'ProgramID',
operator: 'equals',
rightOperand: a.ObjectID,
},
}
)
)
)
: []) {
details.push(...item.Results);
}
details.map((item) => {
item.key = item.CustomerKey;
});
const parsed = this.parseResponseBody({ items: details });
return { metadata: parsed, type: this.definition.type };
}
/**
* Retrieves automation metadata for caching
*
* @returns {Promise.<TYPE.AutomationMapObj>} Promise of metadata
*/
static async retrieveForCache() {
// get automations for cache
const results = await this.client.soap.retrieveBulk('Program', [
'ObjectID',
'CustomerKey',
'Name',
]);
const resultsConverted = {};
if (Array.isArray(results?.Results)) {
// get encodedAutomationID to retrieve notification information
const keyBackup = this.definition.keyField;
const iteratorBackup = this.definition.bodyIteratorField;
this.definition.keyField = 'key';
this.definition.bodyIteratorField = 'entry';
const automationsLegacy = await super.retrieveREST(
undefined,
`/legacy/v1/beta/bulk/automations/automation/definition/`
);
this.definition.keyField = keyBackup;
this.definition.bodyIteratorField = iteratorBackup;
// merge encodedAutomationID into results
for (const m of results.Results) {
resultsConverted[m.CustomerKey] = {
id: m.ObjectID,
key: m.CustomerKey,
name: m.Name,
programId: automationsLegacy.metadata[m.CustomerKey]?.id,
status: automationsLegacy.metadata[m.CustomerKey]?.status,
};
}
}
return { metadata: resultsConverted, type: this.definition.type };
}
/**
* Retrieve a specific Automation Definition by Name
*
* @param {string} templateDir Directory where retrieved metadata directory will be saved
* @param {string} name name of the metadata file
* @param {TYPE.TemplateMap} templateVariables variables to be replaced in the metadata
* @returns {Promise.<TYPE.AutomationItemObj>} Promise of metadata
*/
static async retrieveAsTemplate(templateDir, name, templateVariables) {
const results = await this.client.soap.retrieve('Program', ['ObjectID', 'Name'], {
filter: {
leftOperand: 'Name',
operator: 'equals',
rightOperand: name,
},
});
if (Array.isArray(results?.Results)) {
// eq-operator returns a similar, not exact match and hence might return more than 1 entry
const metadata = results.Results.find((item) => item.Name === name);
if (!metadata) {
Util.logger.error(`${this.definition.type} '${name}' not found on server.`);
return;
}
let details = await this.client.rest.get(
'/automation/v1/automations/' + metadata.ObjectID
);
const metadataMap = this.parseResponseBody({ items: [details] });
if (Object.keys(metadataMap).length) {
// attach notification information to each automation that has any
await this.#getAutomationNotificationsREST(metadataMap);
details = Object.values(metadataMap)[0];
}
let val = null;
let originalKey;
// if parsing fails, we should just save what we get
try {
const parsedDetails = this.postRetrieveTasks(details);
originalKey = parsedDetails[this.definition.keyField];
if (parsedDetails !== null) {
val = JSON.parse(
Util.replaceByObject(JSON.stringify(parsedDetails), templateVariables)
);
}
} catch {
val = JSON.parse(JSON.stringify(details));
}
if (val === null) {
throw new Error(
`Automations '${name}' was skipped and hence cannot be used for templating.`
);
}
// remove all fields not listed in Definition for templating
this.keepTemplateFields(val);
await File.writeJSONToFile(
[templateDir, this.definition.type].join('/'),
originalKey + '.' + this.definition.type + '-meta',
val
);
Util.logger.info(`- templated ${this.definition.type}: ${name}`);
return { metadata: val, type: this.definition.type };
} else if (results) {
Util.logger.error(`${this.definition.type} '${name}' not found on server.`);
Util.logger.info(`Downloaded: automation (0)`);
return { metadata: {}, type: this.definition.type };
} else {
throw new Error(JSON.stringify(results));
}
}
/**
* helper for {@link Automation.postRetrieveTasks} and {@link Automation.execute}
*
* @param {TYPE.AutomationItem} metadata a single automation
* @returns {boolean} true if the automation schedule is valid
*/
static #isValidSchedule(metadata) {
if (metadata.type === 'scheduled' && metadata.schedule?.startDate) {
try {
if (this.definition.timeZoneMapping[metadata.schedule.timezoneName]) {
// if we found the id in our list, remove the redundant data
delete metadata.schedule.timezoneId;
}
} catch {
Util.logger.debug(
`- Schedule name '${metadata.schedule.timezoneName}' not found in definition.timeZoneMapping`
);
}
return true;
} else {
return false;
}
}
/**
* manages post retrieve steps
*
* @param {TYPE.AutomationItem} metadata a single automation
* @returns {TYPE.AutomationItem | void} parsed item
*/
static postRetrieveTasks(metadata) {
// folder
this.setFolderPath(metadata);
// automations are often skipped due to lack of support.
try {
if (metadata.type === 'scheduled' && metadata.schedule?.startDate) {
// Starting Source == 'Schedule'
if (!this.#isValidSchedule(metadata)) {
return;
}
// type 'Running' is temporary status only, overwrite with Scheduled for storage.
if (metadata.type === 'scheduled' && metadata.status === 'Running') {
metadata.status = 'Scheduled';
}
} else if (metadata.type === 'triggered' && metadata.fileTrigger) {
// Starting Source == 'File Drop'
// Do nothing for now
}
if (metadata.steps) {
for (const step of metadata.steps) {
const stepNumber = step.stepNumber || step.step;
delete step.stepNumber;
delete step.step;
for (const activity of step.activities) {
try {
// get metadata type of activity
activity.r__type = Util.inverseGet(
this.definition.activityTypeMapping,
activity.objectTypeId
);
delete activity.objectTypeId;
} catch {
Util.logger.warn(
` - Unknown activity type '${activity.objectTypeId}'` +
` in step ${stepNumber}.${activity.displayOrder}` +
` of Automation '${metadata.name}'`
);
continue;
}
// if no activityObjectId then either serialized activity
// (config in Automation ) or unconfigured so no further action to be taken
if (
activity.activityObjectId === '00000000-0000-0000-0000-000000000000' ||
activity.activityObjectId == null
) {
Util.logger.debug(
` - skipping ${
metadata[this.definition.keyField]
} activity ${stepNumber}.${
activity.displayOrder
} due to missing activityObjectId: ${JSON.stringify(activity)}`
);
// empty if block
} else if (!this.definition.dependencies.includes(activity.r__type)) {
Util.logger.debug(
` - skipping ${
metadata[this.definition.keyField]
} activity ${stepNumber}.${
activity.displayOrder
} because the type ${
activity.r__type
} is not set up as a dependency for ${this.definition.type}`
);
}
// / if managed by cache we can update references to support deployment
else if (
Definitions[activity.r__type]?.['idField'] &&
cache.getCache(this.buObject.mid)[activity.r__type]
) {
try {
// this will override the name returned by the API in case this activity's name was changed since the automation was last updated, keeping things nicely in sync for mcdev
const name = cache.searchForField(
activity.r__type,
activity.activityObjectId,
Definitions[activity.r__type].idField,
Definitions[activity.r__type].nameField
);
if (name !== activity.name) {
Util.logger.debug(
` - updated name of step ${stepNumber}.${activity.displayOrder}` +
` in Automation '${metadata.name}' from ${activity.name} to ${name}`
);
activity.name = name;
}
} catch (ex) {
// getFromCache throws error where the dependent metadata is not found
Util.logger.warn(
` - Missing ${activity.r__type} activity '${activity.name}'` +
` in step ${stepNumber}.${activity.displayOrder}` +
` of Automation '${metadata.name}' (${ex.message})`
);
}
} else {
Util.logger.warn(
` - Missing ${activity.r__type} activity '${activity.name}'` +
` in step ${stepNumber}.${activity.displayOrder}` +
` of Automation '${metadata.name}' (Not Found in Cache)`
);
}
}
}
}
return JSON.parse(JSON.stringify(metadata));
} catch (ex) {
Util.logger.warn(
` - ${this.definition.typeName} '${metadata[this.definition.nameField]}': ${
ex.message
}`
);
return null;
}
}
/**
* a function to start query execution via API
*
* @param {string[]} keyArr customerkey of the metadata
* @returns {Promise.<string[]>} Returns list of keys that were executed
*/
static async execute(keyArr) {
const metadataMap = {};
for (const key of keyArr) {
if (Util.OPTIONS.schedule) {
// schedule
const results = await this.retrieve(undefined, undefined, undefined, key);
if (Object.keys(results.metadata).length) {
for (const key of Object.keys(results.metadata)) {
if (this.#isValidSchedule(results.metadata[key])) {
metadataMap[key] = results.metadata[key];
} else {
Util.logger.error(
` - skipping ${this.definition.type} ${results.metadata[key].name}: no valid schedule settings found.`
);
}
}
}
} else {
// runOnce
const objectId = await this.#getObjectIdForSingleRetrieve(key);
metadataMap[key] = {};
metadataMap[key][this.definition.idField] = objectId;
metadataMap[key][this.definition.keyField] = key;
}
}
if (!Object.keys(metadataMap).length) {
Util.logger.error(`No ${this.definition.type} to execute`);
return false;
}
Util.logger.info(
`Starting automations ${
Util.OPTIONS.schedule
? 'according to schedule'
: 'to run once (use --schedule or --execute=schedule to schedule instead)'
}: ${Object.keys(metadataMap).length}`
);
const promiseResults = [];
for (const key of Object.keys(metadataMap)) {
if (Util.OPTIONS.schedule && metadataMap[key].status === 'Scheduled') {
// schedule
Util.logger.info(
` - skipping ${this.definition.type} ${metadataMap[key].name}: already scheduled.`
);
} else {
// schedule + runOnce
promiseResults.push(this.#executeItem(metadataMap, key));
}
}
const results = await Promise.all(promiseResults);
const executedKeyArr = results
.filter(Boolean)
.filter((r) => r.response.OverallStatus === 'OK')
.map((r) => r.key);
Util.logger.info(`Executed ${executedKeyArr.length} of ${keyArr.length} items`);
return executedKeyArr;
}
/**
* helper for {@link Automation.execute}
*
* @param {TYPE.AutomationMap} metadataMap map of metadata
* @param {string} key key of the metadata
* @returns {Promise.<{key:string, response:object}>} metadata key and API response
*/
static async #executeItem(metadataMap, key) {
if (Util.OPTIONS.schedule) {
this.#preDeploySchedule(metadataMap[key]);
metadataMap[key].status = 'Scheduled';
return this.#scheduleAutomation(metadataMap, metadataMap, key);
} else {
return this.#runOnce(metadataMap[key]);
}
}
/**
* helper for {@link Automation.execute}
*
* @param {TYPE.AutomationItem} metadataEntry metadata object
* @returns {Promise.<{key:string, response:object}>} metadata key and API response
*/
static async #runOnce(metadataEntry) {
return super.executeSOAP(metadataEntry);
}
/**
* Standardizes a check for multiple messages but adds query specific filters to error texts
*
* @param {object} ex response payload from REST API
* @returns {string[] | void} formatted Error Message
*/
static getErrorsREST(ex) {
const errors = super.getErrorsREST(ex);
if (errors?.length > 0) {
return errors.map((msg) =>
msg
.split('403 Forbidden')
.join('403 Forbidden: Please check if the automation is currently running.')
);
}
return errors;
}
/**
* a function to start query execution via API
*
* @param {string[]} keyArr customerkey of the metadata
* @returns {Promise.<string[]>} Returns list of keys that were paused
*/
static async pause(keyArr) {
const metadataMap = {};
for (const key of keyArr) {
if (key) {
const results = await this.retrieve(undefined, undefined, undefined, key);
if (Object.keys(results.metadata).length) {
for (const key of Object.keys(results.metadata)) {
if (this.#isValidSchedule(results.metadata[key])) {
metadataMap[key] = results.metadata[key];
} else {
Util.logger.error(
` - skipping ${this.definition.type} ${results.metadata[key].name}: no valid schedule settings found.`
);
}
}
}
}
}
Util.logger.info(`Pausing automations: ${Object.keys(metadataMap).length}`);
const promiseResults = [];
for (const key of Object.keys(metadataMap)) {
if (metadataMap[key].status === 'Scheduled') {
promiseResults.push(this.#pauseItem(metadataMap[key]));
} else if (metadataMap[key].status === 'PausedSchedule') {
Util.logger.info(
` - skipping ${this.definition.type} ${metadataMap[key].name}: already paused.`
);
} else {
Util.logger.error(
` - skipping ${this.definition.type} ${
metadataMap[key].name
}: currently ${metadataMap[
key
].status.toLowerCase()}. Please try again in a few minutes.`
);
}
}
const pausedKeyArr = (await Promise.all(promiseResults))
.filter(Boolean)
.filter((r) => r.response.OverallStatus === 'OK')
.map((r) => r.key);
Util.logger.info(`Paused ${pausedKeyArr.length} of ${keyArr.length} items`);
return pausedKeyArr;
}
/**
* helper for {@link Automation.pause}
*
* @param {TYPE.AutomationItem} metadata automation metadata
* @returns {Promise.<{key:string, response:object}>} metadata key and API response
*/
static async #pauseItem(metadata) {
const schedule = {};
try {
const response = await this.client.soap.schedule(
'Automation',
schedule,
{
Interaction: {
ObjectID: metadata[this.definition.idField],
},
},
'pause',
{}
);
Util.logger.info(
` - paused ${this.definition.type}: ${metadata[this.definition.keyField]} / ${
metadata[this.definition.nameField]
}`
);
return { key: metadata[this.definition.keyField], response };
} catch (ex) {
this._handleSOAPErrors(ex, 'pausing', metadata, false);
return null;
}
}
/**
* Deploys automation - the saved file is the original one due to large differences required for deployment
*
* @param {TYPE.AutomationMap} metadata metadata mapped by their keyField
* @param {string} targetBU name/shorthand of target businessUnit for mapping
* @param {string} retrieveDir directory where metadata after deploy should be saved
* @returns {Promise.<TYPE.AutomationMap>} Promise
*/
static async deploy(metadata, targetBU, retrieveDir) {
const upsertResults = await this.upsert(metadata, targetBU);
const savedMetadata = await this.saveResults(upsertResults, retrieveDir, null);
if (
this.properties.metaDataTypes.documentOnRetrieve.includes(this.definition.type) &&
!this.definition.documentInOneFile
) {
const count = Object.keys(savedMetadata).length;
Util.logger.debug(` - Running document for ${count} record${count === 1 ? '' : 's'}`);
await this.document(savedMetadata);
}
return upsertResults;
}
/**
* Creates a single automation
*
* @param {TYPE.AutomationItem} metadata single metadata entry
* @returns {Promise} Promise
*/
static create(metadata) {
const uri = '/automation/v1/automations/';
return super.createREST(metadata, uri);
}
/**
* Updates a single automation
*
* @param {TYPE.AutomationItem} metadata single metadata entry
* @param {TYPE.AutomationItem} metadataBefore metadata mapped by their keyField
* @returns {Promise} Promise
*/
static update(metadata, metadataBefore) {
if (metadataBefore.status === 'Running') {
Util.logger.error(
` ☇ error updating ${this.definition.type} ${
metadata[this.definition.keyField] || metadata[this.definition.nameField]
} / ${
metadata[this.definition.nameField]
}: You cannot update an automation that's currently running. Please wait a bit and retry.`
);
return null;
}
const uri = '/automation/v1/automations/' + metadata.id;
return super.updateREST(metadata, uri);
}
/**
* helper for {@link Automation.preDeployTasks} and {@link Automation.execute}
*
* @param {TYPE.AutomationItem} metadata metadata mapped by their keyField
*/
static #preDeploySchedule(metadata) {
delete metadata.schedule.rangeTypeId;
delete metadata.schedule.pattern;
delete metadata.schedule.scheduledTime;
delete metadata.schedule.scheduledStatus;
if (this.definition.timeZoneMapping[metadata.schedule.timezoneName]) {
metadata.schedule.timezoneId =
this.definition.timeZoneMapping[metadata.schedule.timezoneName];
} else {
Util.logger.error(
`Could not find timezone ${metadata.schedule.timezoneName} in definition.timeZoneMapping`
);
}
// the upsert API needs this to be named scheduleTypeId; the retrieve API returns it as typeId
metadata.schedule.scheduleTypeId = metadata.schedule.typeId;
delete metadata.schedule.typeId;
// prep startSource
metadata.startSource = { schedule: metadata.schedule, typeId: 1 };
}
/**
* Gets executed before deploying metadata
*
* @param {TYPE.AutomationItem} metadata metadata mapped by their keyField
* @returns {Promise.<TYPE.AutomationItem>} Promise
*/
static async preDeployTasks(metadata) {
if (metadata.notifications) {
this.notificationUpdates[metadata.key] = metadata.notifications;
} else {
const cached = cache.getByKey(metadata.key);
if (cached?.notifications) {
// if notifications existed but are no longer present in the deployment package, we need to run an empty update call to remove them
this.notificationUpdates[metadata.key] = [];
}
}
if (this.validateDeployMetadata(metadata)) {
// folder
this.setFolderId(metadata);
if (metadata.type === 'scheduled' && metadata?.schedule?.startDate) {
// Starting Source == 'Schedule'
this.#preDeploySchedule(metadata);
// * run _buildSchedule here but only to check if things look ok - do not use the returned schedule object for deploy
this._buildSchedule(metadata.schedule);
delete metadata.schedule.timezoneName;
delete metadata.startSource.schedule.timezoneName;
} else if (metadata.type === 'triggered' && metadata.fileTrigger) {
// Starting Source == 'File Drop'
// prep startSource
metadata.startSource = {
fileDrop: {
filenamePattern: metadata.fileTrigger.fileNamingPattern,
filenamePatternTypeId: metadata.fileTrigger.fileNamePatternTypeId,
folderLocation: metadata.fileTrigger.folderLocationText,
queueFiles: metadata.fileTrigger.queueFiles,
},
typeId: 2,
};
delete metadata.fileTrigger;
}
delete metadata.schedule;
delete metadata.type;
let i = 0;
if (metadata.steps) {
for (const step of metadata.steps) {
let displayOrder = 0;
for (const activity of step.activities) {
activity.displayOrder = ++displayOrder;
if (
activity.name &&
this.definition.dependencies.includes(activity.r__type)
) {
// automations can have empty placeholder for activities with only their type defined
activity.activityObjectId = cache.searchForField(
activity.r__type,
activity.name,
Definitions[activity.r__type].nameField,
Definitions[activity.r__type].idField
);
}
activity.objectTypeId =
this.definition.activityTypeMapping[activity.r__type];
delete activity.r__type;
}
step.annotation = step.name;
step.stepNumber = i;
delete step.name;
delete step.step;
i++;
}
}
return metadata;
} else {
return null;
}
}
/**
* Validates the automation to be sure it can be deployed.
* Whitelisted Activites are deployed but require configuration
*
* @param {TYPE.AutomationItem} metadata single automation record
* @returns {boolean} result if automation can be deployed based on steps
*/
static validateDeployMetadata(metadata) {
let deployable = true;
const errors = [];
if (metadata.steps) {
let stepNumber = 0;
for (const step of metadata.steps) {
stepNumber++;
let displayOrder = 0;
for (const activity of step.activities) {
displayOrder++;
// check if manual deploy required. if so then log warning
if (this.definition.manualDeployTypes.includes(activity.r__type)) {
Util.logger.warn(
`- ${this.definition.type} '${metadata.name}' requires additional manual configuration: '${activity.name}' in step ${stepNumber}.${displayOrder}`
);
}
// cannot deploy because it is not supported
else if (!this.definition.dependencies.includes(activity.r__type)) {
errors.push(
` • not supported ${activity.r__type} activity '${activity.name}' in step ${stepNumber}.${displayOrder}`
);
deployable = false;
}
}
}
}
if (!deployable) {
Util.logger.error(
` ☇ skipping ${this.definition.type} ${metadata[this.definition.keyField]} / ${
metadata[this.definition.nameField]
}:`
);
for (const error of errors) {
Util.logger.error(error);
}
}
return deployable;
}
/**
* Gets executed after deployment of metadata type
*
* @param {TYPE.AutomationMap} metadataMap metadata mapped by their keyField
* @param {TYPE.AutomationMap} originalMetadataMap metadata to be updated (contains additioanl fields)
* @returns {Promise.<void>} -
*/
static async postDeployTasks(metadataMap, originalMetadataMap) {
for (const key in metadataMap) {
if (!metadataMap[key].type) {
// create response does not return the type attribute
const scheduleHelper =
metadataMap[key].schedule || metadataMap[key].startSource.schedule;
// el.type
metadataMap[key].type = scheduleHelper
? 'scheduled'
: metadataMap[key].fileTrigger
? 'triggered'
: undefined;
// el.schedule.timezoneName
if (metadataMap[key].type === 'scheduled') {
// not existing for triggered automations
scheduleHelper.timezoneName ||= Util.inverseGet(
this.definition.timeZoneMapping,
scheduleHelper.timezoneId
);
}
// el.status
metadataMap[key].status ||= Util.inverseGet(
this.definition.statusMapping,
metadataMap[key].statusId
);
}
// need to put schedule on here if status is scheduled
await Automation.#scheduleAutomation(metadataMap, originalMetadataMap, key);
// need to update notifications separately if there are any
await Automation.#updateNotificationInfoREST(metadataMap, key);
// rewrite upsert to retrieve fields
const metadata = metadataMap[key];
if (metadata.steps) {
for (const step of metadata.steps) {
step.name = step.annotation;
delete step.annotation;
}
}
}
if (Util.OPTIONS.execute || Util.OPTIONS.schedule) {
Util.logger.info(`Executing: ${this.definition.type}`);
await this.execute(Object.keys(metadataMap));
}
}
/**
* helper for {@link Automation.postDeployTasks}
*
* @param {TYPE.AutomationMap} metadataMap metadata mapped by their keyField
* @param {string} key current customer key
* @returns {Promise.<void>} -
*/
static async #updateNotificationInfoREST(metadataMap, key) {
if (this.notificationUpdates[key]) {
// create & update automation calls return programId as 'legacyId'; retrieve does not return it
const programId = metadataMap[key]?.legacyId;
if (programId) {
const notificationBody = {
programId,
workers: this.notificationUpdates[key].map((notification) => ({
programId,
notificationType: notification.type,
definition: Array.isArray(notification.email)
? notification.email.join(',')
: notification.email,
body: notification.message,
channelType: 'Account',
})),
};
try {
const result = await this.client.rest.post(
'/legacy/v1/beta/automations/notifications/' + programId,
notificationBody
);
if (result) {
// should be empty if all OK
throw new Error(result);
}
} catch (ex) {
Util.logger.error(
`Error updating notifications for automation '${metadataMap[key].name}': ${ex.message} (${ex.code}))`
);
}
Util.logger.info(
Util.getGrayMsg(
` - updated notifications for automation '${metadataMap[key].name}'`
)
);
}
}
}
/**
* helper for {@link Automation.postDeployTasks}
*
* @param {TYPE.AutomationMap} metadataMap metadata mapped by their keyField
* @param {TYPE.AutomationMap} originalMetadataMap metadata to be updated (contains additioanl fields)
* @param {string} key current customer key
* @returns {Promise.<{key:string, response:object}>} metadata key and API response
*/
static async #scheduleAutomation(metadataMap, originalMetadataMap, key) {
let response = null;
if (originalMetadataMap[key]?.type === 'scheduled') {
// Starting Source == 'Schedule': Try starting the automation
if (originalMetadataMap[key].status === 'Scheduled') {
let schedule = null;
try {