-
Notifications
You must be signed in to change notification settings - Fork 36
/
TriggeredSend.js
562 lines (537 loc) · 21.1 KB
/
TriggeredSend.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
'use strict';
import MetadataType from './MetadataType.js';
import { Util } from '../util/util.js';
import cache from '../util/cache.js';
import asset from './Asset.js';
import folder from './Folder.js';
import list from './List.js';
import ReplaceCbReference from '../util/replaceContentBlockReference.js';
/**
* @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
*/
/**
* MessageSendActivity MetadataType
*
* @augments MetadataType
*/
class TriggeredSend extends MetadataType {
/**
* Retrieves SOAP based metadata of metadata type into local filesystem. executes callback with retrieved metadata
*
* @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 of metadata
*/
static retrieve(retrieveDir, _, __, key) {
/** @type {SoapRequestParams} */
let requestParams = {
filter: {
leftOperand: 'TriggeredSendStatus',
operator: 'IN',
rightOperand: ['New', 'Active', 'Inactive', 'Moved', 'Canceled'], // New, Active=Running, Inactive=Paused, (Deleted)
},
};
if (key) {
// move original filter down one level into rightOperand and add key filter into leftOperand
requestParams = {
filter: {
leftOperand: {
leftOperand: 'CustomerKey',
operator: 'equals',
rightOperand: key,
},
operator: 'AND',
rightOperand: requestParams.filter,
},
};
}
return super.retrieveSOAP(retrieveDir, requestParams, key);
}
/**
* Create a single TSD.
*
* @param {MetadataTypeItem} metadata single metadata entry
* @returns {Promise} Promise
*/
static create(metadata) {
return super.createSOAP(metadata);
}
/**
* Updates a single TSD.
*
* @param {MetadataTypeItem} metadata single metadata entry
* @returns {Promise} Promise
*/
static update(metadata) {
// * in case of update and active definition, we need to pause first.
// * this should be done manually to not accidentally pause production queues without restarting them
return super.updateSOAP(metadata);
}
/**
* Delete a metadata item from the specified business unit
*
* @param {string} customerKey Identifier of data extension
* @returns {Promise.<boolean>} deletion success status
*/
static deleteByKey(customerKey) {
return super.deleteByKeySOAP(customerKey);
}
/**
* parses retrieved Metadata before saving
*
* @param {MetadataTypeItem} metadata a single item
* @returns {MetadataTypeItem | void} Array with one metadata object and one sql string
*/
static postRetrieveTasks(metadata) {
// remove IsPlatformObject, always has to be 'false'
delete metadata.IsPlatformObject;
// folder
this.setFolderPath(metadata);
if (!metadata.r__folder_Path) {
Util.logger.verbose(
` ☇ skipping ${this.definition.typeName} '${metadata.Name}'/'${metadata.CustomerKey}': Could not find folder.`
);
// do not save this TSD because it would not be visible in the user interface
return;
}
// email
try {
// content builder
const contentBuilderEmailName = cache.searchForField(
'asset',
metadata.Email.ID,
'legacyData.legacyId',
'name'
);
metadata.r__asset_name_readOnly = contentBuilderEmailName;
const contentBuilderEmailKey = cache.searchForField(
'asset',
metadata.Email.ID,
'legacyData.legacyId',
'customerKey'
);
metadata.r__asset_key = contentBuilderEmailKey;
delete metadata.Email;
} catch {
try {
// classic
const classicEmail = cache.searchForField('email', metadata.Email.ID, 'ID', 'Name');
metadata.r__email_name = classicEmail;
delete metadata.Email;
} catch {
Util.logger.verbose(
` - ${this.definition.typeName} '${metadata.Name}'/'${metadata.CustomerKey}': Could not find email with ID ${metadata.Email.ID} in Classic nor in Content Builder. This TSD cannot be republished but potentially restarted with its cached version of the email.`
);
// save this TSD because it could be fixed by the user or potentially restarted without a fix; also, it might be used by a journey
}
}
// message priority
if (metadata.Priority) {
metadata.c__priority = Util.inverseGet(
this.definition.priorityMapping,
metadata.Priority
);
delete metadata.Priority;
}
// List (optional)
if (metadata.List) {
try {
metadata.r__list_PathName = cache.getListPathName(metadata.List.ID, 'ID');
delete metadata.List;
} catch (ex) {
Util.logger.verbose(
` - ${this.definition.typeName} '${metadata.Name}'/'${metadata.CustomerKey}': ${ex.message}`
);
// save this TSD because it could be fixed by the user
}
}
// sender profile
if (metadata.SenderProfile?.CustomerKey) {
try {
cache.searchForField(
'senderProfile',
metadata.SenderProfile.CustomerKey,
'CustomerKey',
'CustomerKey'
);
metadata.r__senderProfile_key = metadata.SenderProfile.CustomerKey;
delete metadata.SenderProfile;
} catch (ex) {
Util.logger.warn(
` - ${this.definition.type} ${metadata.CustomerKey}: ${ex.message}`
);
}
}
// send classification
if (metadata.SendClassification?.CustomerKey) {
try {
cache.searchForField(
'sendClassification',
metadata.SendClassification.CustomerKey,
'CustomerKey',
'CustomerKey'
);
metadata.r__sendClassification_key = metadata.SendClassification.CustomerKey;
delete metadata.SendClassification;
} catch (ex) {
Util.logger.warn(
` - ${this.definition.type} ${metadata.CustomerKey}: ${ex.message}`
);
}
}
return metadata;
}
/**
* prepares a TSD for deployment
*
* @param {MetadataTypeItem} metadata of a single TSD
* @returns {Promise.<MetadataTypeItem>} metadata object
*/
static async preDeployTasks(metadata) {
const cachedVersion = cache.getByKey(this.definition.type, metadata.CustomerKey);
if (
cachedVersion?.TriggeredSendStatus === 'Active' &&
cachedVersion?.TriggeredSendStatus === metadata.TriggeredSendStatus
) {
throw new Error(
`Please pause the Triggered Send '${metadata.Name}' before updating it. You may do so via GUI; or via Accenture SFMC DevTools by setting TriggeredSendStatus to 'Inactive'.`
);
}
// re-add IsPlatformObject, required for visibility
metadata.IsPlatformObject = false;
// folder
super.setFolderId(metadata);
// email
if (metadata.r__email_name) {
// classic
metadata.Email = {
ID: cache.searchForField('email', metadata.r__email_name, 'Name', 'ID'),
};
delete metadata.r__email_name;
} else if (metadata.r__asset_key) {
// content builder
// * this ignores r__asset_name_readOnly on purpose as that is only unique per parent folder but useful during PR reviews
metadata.Email = {
ID: cache.searchForField(
'asset',
metadata.r__asset_key,
'customerKey',
'legacyData.legacyId'
),
};
delete metadata.r__asset_key;
delete metadata.r__asset_name_readOnly;
} else if (metadata?.Email?.ID) {
throw new Error(
`r__asset_key / r__email_name not defined but instead found Email.ID. Please try re-retrieving this TSD from your BU.`
);
}
// message priority
if (metadata.c__priority) {
metadata.Priority = this.definition.priorityMapping[metadata.c__priority];
delete metadata.c__priority;
}
// get List (optional)
if (metadata.r__list_PathName) {
metadata.List = {
ID: cache.getListObjectId(metadata.r__list_PathName, 'ID'),
};
delete metadata.r__list_PathName;
} else if (metadata?.List?.ID) {
throw new Error(
`r__list_PathName not defined but instead found List.ID. Please try re-retrieving this TSD from your BU.`
);
}
// sender profile
if (metadata.r__senderProfile_key) {
cache.searchForField(
'senderProfile',
metadata.r__senderProfile_key,
'CustomerKey',
'CustomerKey'
);
metadata.SenderProfile = {
CustomerKey: metadata.r__senderProfile_key,
};
delete metadata.r__senderProfile_key;
}
// send classification
if (metadata.r__sendClassification_key) {
cache.searchForField(
'sendClassification',
metadata.r__sendClassification_key,
'CustomerKey',
'CustomerKey'
);
metadata.SendClassification = {
CustomerKey: metadata.r__sendClassification_key,
};
delete metadata.r__sendClassification_key;
}
return metadata;
}
/**
* TSD-specific refresh method that finds active TSDs and refreshes them
*
* @param {string[]} [keyArr] metadata keys
* @param {boolean} [checkKey] whether to check if the key is valid
* @returns {Promise.<void>} -
*/
static async refresh(keyArr, checkKey = true) {
console.time('Time'); // eslint-disable-line no-console
if (!keyArr) {
keyArr = await this.getKeysForValidTSDs((await this.findRefreshableItems()).metadata);
checkKey = false;
}
// then executes pause, publish, start on them.
const refreshList = [];
Util.logger.info(`Refreshing ${keyArr.length} ${this.definition.typeName}...`);
Util.logger.debug(`Refreshing keys: ${keyArr.join(', ')}`);
for (const key of keyArr) {
refreshList.push(this._refreshItem(key, checkKey));
}
const successCounter = (await Promise.all(refreshList)).filter(Boolean).length;
Util.logger.info(`Refreshed ${successCounter} of ${keyArr.length}`);
console.timeEnd('Time'); // eslint-disable-line no-console
}
/**
* helper for {@link TriggeredSend.refresh} that extracts the keys from the TSD item map and eli
*
* @param {MetadataTypeMap} metadata TSD item map
* @returns {Promise.<string[]>} keyArr
*/
static async getKeysForValidTSDs(metadata) {
const keyArr = Object.keys(metadata).filter((key) => {
const test = this.postRetrieveTasks(metadata[key]);
return test?.CustomerKey || false;
});
Util.logger.info(`Found ${keyArr.length} refreshable items.`);
return keyArr;
}
/**
* helper for {@link TriggeredSend.refresh} that finds active TSDs on the server and filters it by the same rules that {@link TriggeredSend.retrieve} is using to avoid refreshing TSDs with broken dependencies
*
* @param {boolean} [assetLoaded] if run after Asset.deploy via --refresh option this will skip caching assets
* @returns {Promise.<MetadataTypeMapObj>} Promise of TSD item map
*/
static async findRefreshableItems(assetLoaded = false) {
Util.logger.info('Finding refreshable items...');
// cache dependencies to test for broken links
// skip deprecated classic emails here, assuming they cannot be updated and hence are not relevant for {@link refresh}
const requiredCache = {
folder: [
'hidden',
'list',
'mysubs',
'suppression_list',
'publication',
'contextual_suppression_list',
'triggered_send',
'triggered_send_journeybuilder',
],
asset: ['message'],
list: null,
};
const cacheTypes = {
asset,
folder,
list,
};
for (const [type, subTypeArr] of Object.entries(requiredCache)) {
if (type === 'asset' && assetLoaded) {
continue;
}
Util.logger.info(` - Caching dependent Metadata: ${type}`);
Util.logSubtypes(subTypeArr);
cacheTypes[type].client = this.client;
cacheTypes[type].buObject = this.buObject;
cacheTypes[type].properties = this.properties;
const result = await cacheTypes[type].retrieveForCache(null, subTypeArr);
if (cache.getCache()?.[type]) {
// re-run caching to merge with existing cache, assuming we might have missed subtypes
cache.mergeMetadata(type, result.metadata);
} else {
cache.setMetadata(type, result.metadata);
}
}
// cache ACTIVE triggeredSends from the server
/** @type {SoapRequestParams} */
const requestParams = {
filter: {
leftOperand: 'TriggeredSendStatus',
operator: 'IN',
rightOperand: ['dummy', 'Active'], // using equals does not work for this field for an unknown reason and IN requires at least 2 values, hence the 'dummy' entry
},
};
return super.retrieveSOAP(null, requestParams);
}
/**
* helper for {@link TriggeredSend.refresh} that pauses, publishes and starts a triggered send
*
* @param {string} key external key of triggered send item
* @param {boolean} checkKey whether to check if key exists on the server
* @returns {Promise.<boolean>} true if refresh was successful
*/
static async _refreshItem(key, checkKey) {
const item = {};
let test;
item[this.definition.keyField] = key;
// check triggeredSend-key exists on the server AND its status==ACTIVE
if (checkKey) {
/** @type {SoapRequestParams} */
const requestParams = {
filter: {
leftOperand: 'CustomerKey',
operator: 'equals',
rightOperand: key,
},
};
try {
test = (
await super.retrieveSOAP(null, requestParams, key, [
'CustomerKey',
'TriggeredSendStatus',
])
)?.metadata;
} catch (ex) {
const errorMsg = super.getSOAPErrorMsg(ex);
Util.logger.error(` ☇ skipping ${this.definition.typeName}: ${key} - ${errorMsg}}`);
return false;
}
if (!test[key]) {
Util.logger.error(
` ☇ skipping ${this.definition.typeName}: ${key} - not found on server`
);
return false;
}
if (test[key].TriggeredSendStatus !== 'Active') {
Util.logger.error(
` ☇ skipping ${this.definition.typeName}: ${key} - refresh only needed for running entries (TriggeredSendStatus=Active)`
);
return false;
}
}
// pause
try {
item.TriggeredSendStatus = 'Inactive';
test = await super.updateSOAP(item, true);
if (test.OverallStatus !== 'OK') {
throw new Error(test.Results[0].StatusMessage);
}
delete item.TriggeredSendStatus;
Util.logger.info(` - paused ${this.definition.typeName}: ${key}`);
} catch (ex) {
const errorMsg = super.getSOAPErrorMsg(ex);
Util.logger.error(
` - failed to pause ${this.definition.typeName}: ${key} - ${errorMsg}`
);
return false;
}
// publish
try {
item.RefreshContent = 'true';
test = await super.updateSOAP(item, true);
if (test.OverallStatus !== 'OK') {
throw new Error(test.Results[0].StatusMessage);
}
delete item.RefreshContent;
Util.logger.info(` - published ${this.definition.typeName}: ${key}`);
} catch (ex) {
const errorMsg = super.getSOAPErrorMsg(ex);
Util.logger.error(
` - failed to publish ${this.definition.typeName}: ${key} - ${errorMsg}`
);
return false;
}
// start
try {
item.TriggeredSendStatus = 'Active';
test = await super.updateSOAP(item, true);
if (test.OverallStatus !== 'OK') {
throw new Error(test.Results[0].StatusMessage);
}
delete item.RefreshContent;
Util.logger.info(` - started ${this.definition.typeName}: ${key}`);
} catch (ex) {
const errorMsg = super.getSOAPErrorMsg(ex);
Util.logger.error(
` - failed to publish ${this.definition.typeName}: ${key} - ${errorMsg}`
);
return false;
}
return true;
}
/**
*
* @param {MetadataTypeItem} item single metadata item
* @returns {Promise.<MetadataTypeItem>} key of the item that was updated
*/
static async replaceCbReference(item) {
const parentName = `${this.definition.type} ${item[this.definition.keyField]}`;
let changes = false;
let error;
// *** type specific logic ***
try {
item.FromName = ReplaceCbReference.replaceReference(item.FromName, parentName);
changes = true;
} catch (ex) {
if (ex.code !== 200) {
error = ex;
}
}
try {
item.FromAddress = ReplaceCbReference.replaceReference(item.FromAddress, parentName);
changes = true;
} catch (ex) {
if (ex.code !== 200) {
error = ex;
}
}
try {
item.EmailSubject = ReplaceCbReference.replaceReference(item.EmailSubject, parentName);
changes = true;
} catch (ex) {
if (ex.code !== 200) {
error = ex;
}
}
try {
item.DynamicEmailSubject = ReplaceCbReference.replaceReference(
item.DynamicEmailSubject,
parentName
);
changes = true;
} catch (ex) {
if (ex.code !== 200) {
error = ex;
}
}
if (error) {
throw error;
}
if (!changes) {
const ex = new Error('No changes made to the code.');
ex.code = 200;
throw ex;
}
// *** finish ***
// replaceReference will throw an error if nothing was updated which will end execution here
// no error means we have a new item to deploy and need to update the item in our retrieve folder
return item;
}
}
// Assign definition to static attributes
import MetadataTypeDefinitions from '../MetadataTypeDefinitions.js';
TriggeredSend.definition = MetadataTypeDefinitions.triggeredSend;
export default TriggeredSend;