-
Notifications
You must be signed in to change notification settings - Fork 36
/
Journey.js
2098 lines (2002 loc) · 104 KB
/
Journey.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';
import MetadataType from './MetadataType.js';
import TransactionalEmail from './TransactionalEmail.js';
import Event from './Event.js';
import { Util } from '../util/util.js';
import cache from '../util/cache.js';
import File from '../util/file.js';
import ReplaceCbReference from '../util/replaceContentBlockReference.js';
import Retriever from '../Retriever.js';
import pLimit from 'p-limit';
import yoctoSpinner from 'yocto-spinner';
/**
* @typedef {import('../../types/mcdev.d.js').BuObject} BuObject
* @typedef {import('../../types/mcdev.d.js').CodeExtract} CodeExtract
* @typedef {import('../../types/mcdev.d.js').CodeExtractItem} CodeExtractItem
* @typedef {import('../../types/mcdev.d.js').MetadataTypeItem} MetadataTypeItem
* @typedef {import('../../types/mcdev.d.js').MetadataTypeItemDiff} MetadataTypeItemDiff
* @typedef {import('../../types/mcdev.d.js').MetadataTypeItemObj} MetadataTypeItemObj
* @typedef {import('../../types/mcdev.d.js').MetadataTypeMap} MetadataTypeMap
* @typedef {import('../../types/mcdev.d.js').MetadataTypeMapObj} MetadataTypeMapObj
* @typedef {import('../../types/mcdev.d.js').SoapRequestParams} SoapRequestParams
* @typedef {import('../../types/mcdev.d.js').TemplateMap} TemplateMap
*/
/**
* Journey MetadataType
* ! BETA RELEASE of journey support (v4.3.0); it so far only resolves a limited amount of dependencies and will likely break during cross-BU deployments!
* id: A unique id of the journey assigned by the journey’s API during its creation
* key: A unique id of the journey within the MID. Can be generated by the developer
* definitionId: A unique UUID provided by Salesforce Marketing Cloud. Each version of a journey has a unique DefinitionID while the Id and Key remain the same. Version 1 will have id == definitionId
*
* @augments MetadataType
*/
class Journey extends MetadataType {
/**
* Retrieves Metadata of Journey
*
* @param {string} retrieveDir Directory where retrieved metadata directory will be saved
* @param {void | string[]} [_] unused parameter
* @param {void | string[]} [__] unused parameter
* @param {string} [key] customer key of single item to retrieve
* @returns {Promise.<MetadataTypeMapObj>} Promise
*/
static async retrieve(retrieveDir, _, __, key) {
const extrasDefault = 'activities';
if (retrieveDir) {
// only print this during retrieve, not during retrieveForCache
Util.logBeta(this.definition.type);
}
let singleKey = '';
let mode = 'all';
if (key) {
if (key.startsWith('%23')) {
// correct the format
key = 'id:' + key.slice(3);
}
if (key.startsWith('id:')) {
// ! allow selecting journeys by ID because that's what users see in the URL
// if the key started with %23 assume an ID was copied from the URL but the user forgot to prefix it with id:
// remove id: or %23
singleKey = key.slice(3);
if (singleKey.startsWith('%23')) {
// in the journey URL the Id is prefixed with an HTML-encoded "#" which could accidentally be copied by users
// despite the slicing above, this still needs testing here because users might have prefixed the ID with id: but did not know to remove the #23
singleKey = singleKey.slice(3);
// correct the format to ensure we show sth readable in the "Downloaded" log
key = 'id:' + singleKey;
}
if (singleKey.includes('/')) {
// in the journey URL the version is appended after the ID, separated by a forward-slash. Needs to be removed from the ID for the retrieve as we always aim to retrieve the latest version only
singleKey = singleKey.split('/')[0];
}
mode = 'id';
} else if (key.startsWith('name:')) {
singleKey = '?nameOrDescription=' + encodeURIComponent(key.slice(5));
mode = 'name';
} else {
// assume actual key was provided
singleKey = 'key:' + encodeURIComponent(key);
mode = 'key';
}
}
try {
const uri = `/interaction/v1/interactions/`;
if ((singleKey && (mode === 'key' || mode === 'id')) || !retrieveDir) {
// full details for retrieve, only base data for caching; reduces caching time from minutes to seconds
const extras = retrieveDir && singleKey ? extrasDefault : '';
// caching or single retrieve
return await super.retrieveREST(
retrieveDir,
`${uri}${singleKey}?extras=${extras}${key && key.includes('/') ? '&versionNumber=' + key.split('/')[1] : ''}`,
null,
key
);
} else {
// retrieve all
const results = this.definition.restPagination
? await this.client.rest.getBulk(
uri + (mode === 'name' ? singleKey : ''),
this.definition.restPageSize || 500
)
: await this.client.rest.get(uri + (mode === 'name' ? singleKey : ''));
if (results.items?.length) {
// empty results will come back without "items" defined
Util.logger.info(
Util.getGrayMsg(
` - ${results.items?.length} ${this.definition.type}s found. Retrieving details...`
)
);
}
// full details for retrieve
const extras = extrasDefault;
let parsed;
if (retrieveDir) {
const searchName = mode === 'name' ? key.slice(5) : null;
const foundKey = [];
// get extra details for saving this
const details = results.items
? await Promise.all(
results.items.map(async (a) => {
if (mode === 'name') {
// when filtering by name, the API in fact does a LIKE search with placeholders left and right of the search term - and also searches the description field.
if (searchName === a[this.definition.nameField]) {
foundKey.push(a[this.definition.keyField]);
} else {
// skip because the name does not match
return null;
}
}
try {
return await this.client.rest.get(
`${uri}key:${a[this.definition.keyField]}?extras=${extras}` +
`&versionNumber=${a.version}`
);
} catch (ex) {
// if we do get here, we should log the error and continue instead of failing to download all automations
Util.logger.warn(
` ☇ skipping ${this.definition.type} ${
a[this.definition.nameField]
} (${a[this.definition.keyField]}): ${ex.message} (${
ex.code
})${
ex.endpoint
? Util.getGrayMsg(
' - ' +
ex.endpoint.split(
'rest.marketingcloudapis.com'
)[1]
)
: ''
}`
);
return null;
}
})
)
: [];
parsed = this.parseResponseBody({ items: details.filter(Boolean) });
// * retrieveDir is mandatory in this method as it is not used for caching (there is a seperate method for that)
const savedMetadata = await this.saveResults(parsed, retrieveDir, null, null);
Util.logger.info(
`Downloaded: ${this.definition.type} (${Object.keys(savedMetadata).length})` +
Util.getKeysString(
mode === 'name' ? `${foundKey.join(', ')} (${key})` : key
)
);
} else {
// limit to main details for caching
parsed = this.parseResponseBody(results);
}
return {
metadata: parsed,
type: this.definition.type,
};
}
} catch (ex) {
// if the interaction does not exist, the API returns an error code which would otherwise bring execution to a hold
if (
[
'Interaction matching key not found.',
'Must provide a valid ID or Key parameter',
].includes(ex.message)
) {
Util.logger.info(
`Downloaded: ${this.definition.type} (0)${Util.getKeysString(
mode === 'id' ? singleKey : key,
mode === 'id'
)}`
);
} else {
throw ex;
}
}
}
/**
* Delete a metadata item from the specified business unit
*
* @param {string} key Identifier of item
* @returns {Promise.<boolean>} deletion success status
*/
static async deleteByKey(key) {
let version;
let singleKey = '';
if (key.startsWith('id:') || key.startsWith('%23')) {
// ! allow selecting journeys by ID because that's what users see in the URL
// if the key started with %23 assume an ID was copied from the URL but the user forgot to prefix it with id:
// remove id: or %23
singleKey = key.slice(3);
if (singleKey.startsWith('%23')) {
// in the journey URL the Id is prefixed with an HTML-encoded "#" which could accidentally be copied by users
// despite the slicing above, this still needs testing here because users might have prefixed the ID with id: but did not know to remove the #23
singleKey = singleKey.slice(3);
}
if (singleKey.includes('/')) {
// in the journey URL the version is appended after the ID, separated by a forward-slash.
[singleKey, version] = singleKey.split('/');
}
} else {
if (key.includes('/')) {
// in the journey URL the version is appended after the ID, separated by a forward-slash.
[key, version] = key.split('/');
}
// delete by key with specified version does not work, therefore we need to get the ID first
const response = await this.client.rest.get(
`/interaction/v1/interactions/key:${encodeURIComponent(key)}?extras=`
);
const results = this.parseResponseBody(response, key);
singleKey = results[key].id;
if (version && version !== '*' && version > results[key].version) {
Util.logger.error(
`The chosen version (${version}) is higher than the latest known version (${results[key].version}). Please choose a lower version.`
);
return false;
}
Util.logger.debug(`Deleting interaction ${key} via its ID ${singleKey}`);
}
if (version !== '*') {
if (!/^\d+$/.test(version)) {
Util.logger.error(
'Version is required for deleting interactions to avoid accidental deletion of the wrong item. Please append it at the end of the key or id, separated by forward-slash. Example for deleting version 4: ' +
key +
'/4'
);
return false;
}
Util.logger.warn(
`Deleting Journeys via this command breaks following retrieve-by-key/id requests until you've deployed/created a new draft version! You can get still get the latest available version of your journey by retrieving all interactions on this BU.`
);
}
return super.deleteByKeyREST(
'/interaction/v1/interactions/' +
singleKey +
(version === '*' ? '' : `?versionNumber=${version}`),
key,
false
);
}
/**
* Deploys metadata - merely kept here to be able to print {@link Util.logBeta} once per deploy
*
* @param {MetadataTypeMap} metadata metadata mapped by their keyField
* @param {string} deployDir directory where deploy metadata are saved
* @param {string} retrieveDir directory where metadata after deploy should be saved
* @returns {Promise.<MetadataTypeMap>} Promise of keyField => metadata map
*/
static async deploy(metadata, deployDir, retrieveDir) {
Util.logBeta(this.definition.type);
return super.deploy(metadata, deployDir, retrieveDir);
}
/**
* Updates a single item
*
* @param {MetadataTypeItem} metadata a single item
* @returns {Promise} Promise
*/
static update(metadata) {
return super.updateREST(
metadata,
'/interaction/v1/interactions/key:' + metadata.key,
'put'
);
}
/**
* Creates a single item
*
* @param {MetadataTypeItem} metadata a single item
* @returns {Promise} Promise
*/
static create(metadata) {
return super.createREST(metadata, '/interaction/v1/interactions/');
}
/**
* Helper for writing Metadata to disk, used for Retrieve and deploy
*
* @param {MetadataTypeMap} results metadata results from deploy
* @param {string} retrieveDir directory where metadata should be stored after deploy/retrieve
* @param {string} [overrideType] for use when there is a subtype (such as folder-queries)
* @param {TemplateMap} [templateVariables] variables to be replaced in the metadata
* @returns {Promise.<MetadataTypeMap>} Promise of saved metadata
*/
static async saveResults(results, retrieveDir, overrideType, templateVariables) {
if (Object.keys(results).length) {
// only execute the following if records were found
await this._postRetrieveTasksBulk(results);
}
return super.saveResults(results, retrieveDir, overrideType, templateVariables);
}
/**
* helper for Journey's {@link Journey.saveResults}. Gets executed after retreive of metadata type and
*
* @param {MetadataTypeMap} metadataMap key=customer key, value=metadata
*/
static async _postRetrieveTasksBulk(metadataMap) {
let needTransactionalEmail = false;
for (const key in metadataMap) {
if (metadataMap[key].definitionType == 'Transactional') {
needTransactionalEmail = true;
break;
}
}
if (needTransactionalEmail && !cache.getCache()?.transactionalEmail) {
// ! interaction and transactionalEmail both link to each other. caching transactionalEmail here "manually", assuming that it's quicker than the other way round
Util.logger.info(' - Caching dependent Metadata: transactionalEmail');
TransactionalEmail.buObject = this.buObject;
TransactionalEmail.client = this.client;
TransactionalEmail.properties = this.properties;
const result = await TransactionalEmail.retrieveForCache();
cache.setMetadata('transactionalEmail', result.metadata);
}
}
/**
* manages post retrieve steps
*
* @param {MetadataTypeItem} metadata a single item
* @returns {Promise.<MetadataTypeItem>} Array with one metadata object
*/
static async postRetrieveTasks(metadata) {
// folder
super.setFolderPath(metadata);
switch (metadata.definitionType) {
case 'Quicksend': // Single Send Journey
case 'Multistep': {
// Single Send Journey
// ~~~ TRIGGERS ~~~~
// event && triggers[].type === 'ContactAudience'
// Multi-Step Journey
// ~~~ TRIGGERS ~~~~
// event / definitionType==='Multistep' && channel==='' && triggers[].type === 'EmailAudience'|'APIEvent'
if (metadata.triggers?.length > 0) {
const search = ['arguments', 'metaData'];
for (const area of search) {
const config = metadata.triggers[0][area];
if (config?.eventDefinitionId) {
// trigger found; there can only be one entry in this array
try {
const edKey = cache.searchForField(
'event',
config.eventDefinitionId,
'id',
'eventDefinitionKey'
);
if (config.eventDefinitionKey !== edKey) {
Util.logger.debug(
`eventDefinitionKey not matching eventDefinitionId. Overwriting '${config.eventDefinitionKey}' with the correct key '${edKey}'.`
);
}
config.r__event_key = edKey;
delete config.eventDefinitionKey;
delete config.eventDefinitionId;
} catch (ex) {
Util.logger.warn(
` - ${this.definition.type} ${metadata[this.definition.nameField]} (${
metadata[this.definition.keyField]
}): ${ex.message}.`
);
}
}
if (config?.dataExtensionId) {
try {
config.r__dataExtension_key = cache.searchForField(
'dataExtension',
config.dataExtensionId,
'ObjectID',
'CustomerKey'
);
delete config.dataExtensionId;
} catch (ex) {
Util.logger.warn(
` - ${this.definition.type} ${metadata[this.definition.nameField]} (${
metadata[this.definition.keyField]
}): ${ex.message}.`
);
}
}
}
try {
await Event.postRetrieveTasks_SalesforceEntryEvents(
metadata.triggers[0].type,
metadata.triggers[0].configurationArguments,
metadata.key,
metadata.status === 'Published',
this.definition.type
);
} catch (ex) {
Util.logger.warn(
` - ${this.definition.type} '${metadata[this.definition.nameField]}' (${metadata[this.definition.keyField]}): ${ex.message}`
);
}
}
// ~~~ ACTIVITIES ~~~~
this._postRetrieveTasks_activities(metadata);
// TODO: journey template id? / metaData.templateId
break;
}
case 'Transactional': {
// Transactional Send Journey
// ~~~ TRIGGERS ~~~~
// ! journeys so far only supports transactional EMAIL messages. SMS and Push do not create their own journey.
// ! transactional (email) journeys only have a dummy trigger without real content.
// transactionalEmail / definitionType==='Transactional' && channel==='email' && triggers[].type === 'transactional-api'
// --> nothing to do here
// ~~~ ACTIVITIES ~~~~
// ! transactional (email) journeys only have one activity (type=EMAILV2) which links back to the transactionalEmail ()
switch (metadata.channel) {
case 'email': {
if (metadata.activities?.length > 0) {
const activity = metadata.activities[0];
// trigger found; there can only be one entry in this array
if (activity.configurationArguments?.triggeredSendId) {
try {
const tEmailKey = cache.searchForField(
'transactionalEmail',
activity.configurationArguments?.triggeredSendId,
'definitionId',
'definitionKey'
);
if (
activity.configurationArguments?.triggeredSendKey &&
tEmailKey !=
activity.configurationArguments?.triggeredSendKey
) {
Util.logger.debug(
`triggeredSendKey not matching triggeredSendId. Overwriting '${activity.configurationArguments.triggeredSendKey}' with the correct key '${tEmailKey}'.`
);
}
activity.configurationArguments.r__transactionalEmail_key =
activity.configurationArguments.triggeredSendKey;
delete activity.configurationArguments.triggeredSendKey;
delete activity.configurationArguments.triggeredSendId;
} catch (ex) {
Util.logger.warn(
` - ${this.definition.type} ${
metadata[this.definition.nameField]
} (${metadata[this.definition.keyField]}): ${ex.message}.`
);
}
}
if (
activity.metaData?.highThroughput?.definitionKey &&
activity.configurationArguments?.r__transactionalEmail_key &&
activity.metaData?.highThroughput?.definitionKey !=
activity.configurationArguments.r__transactionalEmail_key
) {
Util.logger.warn(
` - ${this.definition.type} ${
metadata[this.definition.nameField]
} (${metadata[this.definition.keyField]}): activities[0].metaData.highThroughput.definitionKey not matching key in activities[0].configurationArguments.r__transactionalEmail_key.`
);
} else if (
activity.configurationArguments?.r__transactionalEmail_key &&
metadata.status === 'Published'
) {
// as long as status is Draft, we wont have r__transactionalEmail_key set as that record will not have been created
delete activity.metaData.highThroughput.definitionKey;
}
if (activity.metaData?.highThroughput?.dataExtensionId) {
try {
activity.metaData.highThroughput.r__dataExtension_key =
cache.searchForField(
'dataExtension',
activity.metaData.highThroughput.dataExtensionId,
'ObjectID',
'CustomerKey'
);
delete activity.metaData.highThroughput.dataExtensionId;
} catch (ex) {
Util.logger.warn(
` - ${this.definition.type} ${
metadata[this.definition.nameField]
} (${metadata[this.definition.keyField]}): ${ex.message}.`
);
}
}
}
// ~~~ ACTIVITIES ~~~~
this._postRetrieveTasks_activities(metadata);
break;
}
default: {
// it is expected that we'll see 'sms' and 'push' here in the future
Util.logger.warn(
` - ${this.definition.type} ${metadata[this.definition.nameField]} (${
metadata[this.definition.keyField]
}): channel ${
metadata.channel
} is not supported yet. Please open a ticket at https://github.com/Accenture/sfmc-devtools/issues/new/choose to request it`
);
}
}
break;
}
default: {
Util.logger.warn(
` - ${this.definition.type} ${metadata[this.definition.nameField]} (${
metadata[this.definition.keyField]
}): definitionType ${
metadata.definitionType
} is not supported yet. Please open a ticket at https://github.com/Accenture/sfmc-devtools/issues/new/choose to request it`
);
}
}
return metadata;
}
/**
* helper for {@link Journey.postRetrieveTasks}
*
* @private
* @param {MetadataTypeItem} metadata a single item
*/
static _postRetrieveTasks_activities(metadata) {
for (const activity of metadata.activities) {
switch (activity.type) {
case 'EMAILV2': {
// triggeredSend + email+asset
const configurationArguments = activity.configurationArguments;
if (configurationArguments) {
try {
// configurationArguments.triggeredSendKey && configurationArguments.triggeredSendId are only set on a running journey; if a journey is new, they do not exist
if (configurationArguments.triggeredSendId) {
// triggeredSendKey is not always set but triggeredSendId is
const tsKey = cache.searchForField(
'triggeredSend',
configurationArguments.triggeredSendId,
'ObjectID',
'CustomerKey'
);
if (configurationArguments.triggeredSendKey != tsKey) {
Util.logger.debug(
`triggeredSendKey not matching triggeredSendId. Overwriting '${configurationArguments.triggeredSendKey}' with the correct key '${tsKey}'.`
);
configurationArguments.triggeredSendKey = tsKey;
}
configurationArguments.r__triggeredSend_key =
configurationArguments.triggeredSendKey;
delete configurationArguments.triggeredSendKey;
delete configurationArguments.triggeredSendId;
} else if (configurationArguments.triggeredSendKey) {
// very rare case but it's been seen that no triggeredSendId was saved
Util.logger.debug(
`triggeredSendKey found on activity but no triggeredSendId present on journey. Checking key directly...`
);
configurationArguments.r__triggeredSend_key = cache.searchForField(
'triggeredSend',
configurationArguments.triggeredSendKey,
'CustomerKey',
'CustomerKey'
);
delete configurationArguments.triggeredSendKey;
}
} catch (ex) {
Util.logger.warn(
` - ${this.definition.type} '${metadata[this.definition.nameField]}' (${
metadata[this.definition.keyField]
}) activity-key=${activity.key}: ${ex.message}`
);
}
}
if (
configurationArguments?.triggeredSend &&
'string' === typeof configurationArguments?.triggeredSend
) {
// sometimes, the API returns this object as a string for unknown reasons. Good job, product team!
configurationArguments.triggeredSend = JSON.parse(
configurationArguments?.triggeredSend
);
}
const triggeredSend = configurationArguments?.triggeredSend;
if (triggeredSend) {
// this section is likely only relevant for QuickSends and not for Multi-Step Journeys
// triggeredSend key
if (configurationArguments.r__triggeredSend_key) {
// if we have a key set outside of this detailed triggeredSend config then lets overwrite what we've got here with what we cached from the related TS as it will be more current; but we cannot retrieve all info unfortunately
triggeredSend.r__triggeredSend_key =
configurationArguments.r__triggeredSend_key;
delete triggeredSend.id;
delete triggeredSend.key;
const linkedTS = cache.getByKey(
'triggeredSend',
triggeredSend.r__triggeredSend_key
);
if (linkedTS) {
triggeredSend.emailId = linkedTS.Email?.ID;
triggeredSend.dynamicEmailSubject = linkedTS.DynamicEmailSubject;
triggeredSend.emailSubject = linkedTS.EmailSubject;
// only the bccEmail field can be retrieved for triggeredSends, not the ccEmail field; for some reason BccEmail can be retrieved but does not return a value even if stored correctly in the journey.
// triggeredSend.bccEmail = linkedTS.BccEmail;
triggeredSend.isMultipart = linkedTS.IsMultipart;
triggeredSend.autoAddSubscribers = linkedTS.AutoAddSubscribers;
triggeredSend.autoUpdateSubscribers =
linkedTS.AutoUpdateSubscribers;
triggeredSend.isTrackingClicks = !linkedTS.SuppressTracking;
triggeredSend.suppressTracking = linkedTS.SuppressTracking;
triggeredSend.triggeredSendStatus = linkedTS.TriggeredSendStatus;
// from name & email are set in the senderProfile, not in the triggeredSend
// triggeredSend.fromName = linkedTS.FromName;
// triggeredSend.fromAddress = linkedTS.FromAddress;
if (linkedTS.List?.ID) {
triggeredSend.publicationListId = linkedTS.List.ID;
} else if (linkedTS.r__list_PathName) {
delete triggeredSend.publicationListId;
triggeredSend.r__list_PathName = {
publicationList: linkedTS.r__list_PathName,
};
}
if (linkedTS.SenderProfile?.CustomerKey) {
try {
const spKey = cache.searchForField(
'senderProfile',
linkedTS.SenderProfile.ObjectID,
'ObjectID',
'CustomerKey'
);
triggeredSend.r__senderProfile_key = spKey;
delete triggeredSend.senderProfileId;
} catch (ex) {
Util.logger.warn(
` - triggeredSend ${linkedTS.CustomerKey}: ${ex.message} (senderProfile key ${linkedTS.SenderProfile.CustomerKey})`
);
}
} else if (linkedTS.r__senderProfile_key) {
triggeredSend.r__senderProfile_key =
linkedTS.r__senderProfile_key;
}
// send classification
if (linkedTS.SendClassification?.CustomerKey) {
try {
const scKey = cache.searchForField(
'sendClassification',
linkedTS.SendClassification.ObjectID,
'ObjectID',
'CustomerKey'
);
triggeredSend.r__sendClassification_key = scKey;
delete triggeredSend.sendClassificationId;
} catch (ex) {
Util.logger.warn(
` - triggeredSend ${linkedTS.CustomerKey}: ${ex.message} (sendClassification key ${linkedTS.SendClassification.CustomerKey})`
);
}
} else if (linkedTS.r__sendClassification_key) {
triggeredSend.r__sendClassification_key =
linkedTS.r__sendClassification_key;
}
if (linkedTS.c__priority) {
delete triggeredSend.priority;
triggeredSend.c__priority = linkedTS.c__priority;
}
if (linkedTS.Email?.ID) {
triggeredSend.emailId = linkedTS.Email.ID;
} else if (linkedTS.r__asset_key) {
delete triggeredSend.emailId;
triggeredSend.r__asset_name_readOnly =
linkedTS.r__asset_name_readOnly;
triggeredSend.r__asset_key = linkedTS.r__asset_key;
}
}
} else if (triggeredSend.id) {
// triggeredSendKey is not always set but id is
const tsKey = cache.searchForField(
'triggeredSend',
triggeredSend.id,
'ObjectID',
'CustomerKey'
);
if (triggeredSend.key != tsKey) {
Util.logger.debug(
`key not matching id. Overwriting '${triggeredSend.key}' with the correct key '${tsKey}'.`
);
triggeredSend.key = tsKey;
}
triggeredSend.r__triggeredSend_key = triggeredSend.key;
delete triggeredSend.key;
delete triggeredSend.id;
} else if (triggeredSend.key) {
// very rare case but it's been seen that no id was saved
Util.logger.debug(
`key found on triggeredSend but no id present on journey activity. Checking key directly...`
);
triggeredSend.r__triggeredSend_key = cache.searchForField(
'triggeredSend',
triggeredSend.key,
'CustomerKey',
'CustomerKey'
);
delete triggeredSend.key;
}
triggeredSend.ccEmail = triggeredSend.ccEmail
.split(';')
.filter((el) => el !== '');
triggeredSend.bccEmail = triggeredSend.bccEmail
.split(';')
.filter((el) => el !== '');
// List (optional)
triggeredSend.r__list_PathName ||= {};
if (triggeredSend.publicationListId) {
try {
triggeredSend.r__list_PathName.publicationList =
cache.getListPathName(triggeredSend.publicationListId, 'ID');
delete triggeredSend.publicationListId;
} catch (ex) {
Util.logger.warn(
` - ${this.definition.typeName} '${metadata.name}'/'${metadata.key}': ${ex.message}`
);
// save this TSD because it could be fixed by the user
}
}
if (
triggeredSend.suppressionLists &&
Array.isArray(triggeredSend.suppressionLists) &&
triggeredSend.suppressionLists.length
) {
triggeredSend.r__list_PathName.suppressionLists =
triggeredSend.suppressionLists.map((sList) => {
try {
return cache.getListPathName(sList.id, 'ID');
} catch (ex) {
Util.logger.warn(
` - ${this.definition.typeName} '${metadata.name}'/'${metadata.key}': ${ex.message}`
);
// save this TSD because it could be fixed by the user
}
});
delete triggeredSend.suppressionLists;
}
if (!Object.keys(triggeredSend.r__list_PathName).length) {
// in case we found no linked lists, remove this empty shell
delete triggeredSend.r__list_PathName;
}
// DataExtension (optional)
triggeredSend.r__dataExtension_key = {};
if (
triggeredSend.domainExclusions &&
Array.isArray(triggeredSend.domainExclusions) &&
triggeredSend.domainExclusions.length
) {
let errors = 0;
triggeredSend.r__dataExtension_key.domainExclusions =
triggeredSend.domainExclusions.map((de) => {
try {
return cache.searchForField(
'dataExtension',
de.id,
'ObjectID',
'CustomerKey'
);
} catch (ex) {
errors++;
Util.logger.warn(
` - ${this.definition.typeName} '${metadata.name}'/'${metadata.key}': ${ex.message}`
);
// save this TSD because it could be fixed by the user
}
});
if (!errors) {
delete triggeredSend.domainExclusions; // array with id & name of DE
}
}
if (!Object.keys(triggeredSend.r__dataExtension_key).length) {
// in case we found no linked dataExtensions, remove this empty shell
delete triggeredSend.r__dataExtension_key;
}
// sender profile
if (triggeredSend.senderProfileId) {
try {
triggeredSend.r__senderProfile_key = cache.searchForField(
'senderProfile',
triggeredSend.senderProfileId,
'ObjectID',
'CustomerKey'
);
delete triggeredSend.senderProfileId;
} catch (ex) {
Util.logger.warn(
` - ${this.definition.type} '${metadata[this.definition.nameField]}' (${
metadata[this.definition.keyField]
}): ${ex.message}`
);
}
}
// send classification
if (triggeredSend.sendClassificationId) {
try {
triggeredSend.r__sendClassification_key = cache.searchForField(
'sendClassification',
triggeredSend.sendClassificationId,
'ObjectID',
'CustomerKey'
);
delete triggeredSend.sendClassificationId;
} catch (ex) {
Util.logger.warn(
` - ${this.definition.type} '${metadata[this.definition.nameField]}' (${
metadata[this.definition.keyField]
}): ${ex.message}`
);
}
}
// delivery profile
if (triggeredSend.deliveryProfileId) {
// remove it because we cannot resolve it and it should be set by selecting the sendClassification
delete triggeredSend.deliveryProfileId;
}
// message priority
if (triggeredSend.priority) {
triggeredSend.c__priority = Util.inverseGet(
this.definition.priorityMapping,
triggeredSend.priority
);
delete triggeredSend.priority;
}
// email
if (triggeredSend.emailId) {
try {
// content builder
triggeredSend.r__asset_name_readOnly = cache.searchForField(
'asset',
triggeredSend.emailId,
'legacyData.legacyId',
'name'
);
triggeredSend.r__asset_key = cache.searchForField(
'asset',
triggeredSend.emailId,
'legacyData.legacyId',
'customerKey'
);
delete triggeredSend.emailId;
} catch {
try {
// classic
triggeredSend.r__email_name = cache.searchForField(
'email',
triggeredSend.emailId,
'ID',
'Name'
);
delete triggeredSend.emailId;
} catch {
Util.logger.warn(
` - ${this.definition.type} '${metadata[this.definition.nameField]}' (${
metadata[this.definition.keyField]
}): Could not find email with ID ${triggeredSend.emailId} in Classic nor in Content Builder.`
);
}
}
}
// sort attributes of triggeredSend alphabetically to allow for easier pull request reviews
configurationArguments.triggeredSend =
Util.sortObjectAttributes(triggeredSend);
}
break;
}
case 'SMSSYNC': {
const configurationArguments = activity.configurationArguments;
if (configurationArguments) {
// mobileMessage
try {
if (configurationArguments.messageId) {
configurationArguments.r__mobileMessage_key = cache.searchForField(
'mobileMessage',
configurationArguments.messageId,
'id',
'id'
);
delete configurationArguments.messageId;
}
} catch (ex) {
Util.logger.warn(
` - ${this.definition.type} '${metadata[this.definition.nameField]}' (${
metadata[this.definition.keyField]
}) activity-key=${activity.key}: ${ex.message}`
);
}
// mobileKeyword
configurationArguments.r__mobileKeyword_key = {};
try {
if (configurationArguments.keywordId) {
configurationArguments.r__mobileKeyword_key.current =
cache.searchForField(
'mobileKeyword',
configurationArguments.keywordId,
'id',
'c__codeKeyword'
);
delete configurationArguments.keywordId;
}
} catch (ex) {
Util.logger.warn(
` - ${this.definition.type} '${metadata[this.definition.nameField]}' (${
metadata[this.definition.keyField]
}) activity-key=${activity.key}: ${ex.message}`
);
}
try {
if (configurationArguments.nextKeywordId) {
configurationArguments.r__mobileKeyword_key.next =
cache.searchForField(
'mobileKeyword',
configurationArguments.nextKeywordId,
'id',
'c__codeKeyword'
);
delete configurationArguments.nextKeywordId;
}
} catch (ex) {
Util.logger.warn(
` - ${this.definition.type} '${metadata[this.definition.nameField]}' (${
metadata[this.definition.keyField]
}) activity-key=${activity.key}: ${ex.message}`
);
}
if (!Object.keys(configurationArguments.r__mobileKeyword_key).length) {
// in case we found no linked dataExtensions, remove this empty shell
delete configurationArguments.r__mobileKeyword_key;
}
// mobileCode
try {
if (configurationArguments.codeId) {
configurationArguments.r__mobileCode_key = cache.searchForField(
'mobileCode',
configurationArguments.codeId,
'id',
'code'
);
delete configurationArguments.codeId;
}
} catch (ex) {
Util.logger.warn(
` - ${this.definition.type} '${metadata[this.definition.nameField]}' (${
metadata[this.definition.keyField]
}) activity-key=${activity.key}: ${ex.message}`
);
}
try {
// asset-asset: jsonmessage
if (configurationArguments.assetId) {
configurationArguments.r__asset_name_readOnly =
cache.searchForField(
'asset',
configurationArguments.assetId,
'id',