-
Notifications
You must be signed in to change notification settings - Fork 36
/
TriggeredSend.js
411 lines (390 loc) · 15.8 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
'use strict';
const TYPE = require('../../types/mcdev.d');
const MetadataType = require('./MetadataType');
const Util = require('../util/util');
const cache = require('../util/cache');
const cacheTypes = {
asset: require('./Asset'),
folder: require('./Folder'),
list: require('./List'),
};
/**
* 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} [_] unused parameter
* @param {void} [__] unused parameter
* @param {string} [key] customer key of single item to retrieve
* @returns {Promise.<TYPE.MetadataTypeMapObj>} Promise of metadata
*/
static retrieve(retrieveDir, _, __, key) {
/** @type {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 {TYPE.MetadataTypeItem} metadata single metadata entry
* @returns {Promise} Promise
*/
static create(metadata) {
return super.createSOAP(metadata);
}
/**
* Updates a single TSD.
*
* @param {TYPE.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 {TYPE.MetadataTypeItem} metadata a single item
* @returns {TYPE.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 {
// classic
const classicEmail = cache.searchForField('email', metadata.Email.ID, 'ID', 'Name');
metadata.r__email_Name = classicEmail;
delete metadata.Email;
} catch {
try {
// content builder
const contentBuilderEmailName = cache.searchForField(
'asset',
metadata.Email.ID,
'legacyData.legacyId',
'name'
);
metadata.r__assetMessage_Name_readOnly = contentBuilderEmailName;
const contentBuilderEmailKey = cache.searchForField(
'asset',
metadata.Email.ID,
'legacyData.legacyId',
'customerKey'
);
metadata.r__assetMessage_Key = contentBuilderEmailKey;
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 replublished 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
}
}
// 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
}
}
return metadata;
}
/**
* prepares a TSD for deployment
*
* @param {TYPE.MetadataTypeItem} metadata of a single TSD
* @returns {TYPE.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__assetMessage_Key) {
// content builder
// * this ignores r__assetMessage_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__assetMessage_Key,
'customerKey',
'legacyData.legacyId'
),
};
delete metadata.r__assetMessage_Key;
delete metadata.r__assetMessage_Name_readOnly;
} else if (metadata?.Email?.ID) {
throw new Error(
`r__assetMessage_Key / r__email_Name not defined but instead found Email.ID. Please try re-retrieving this TSD from your BU.`
);
}
// 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.`
);
}
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 {TYPE.MetadataTypeMapObj} 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.<TYPE.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,
};
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 {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 {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;
}
}
// Assign definition to static attributes
TriggeredSend.definition = require('../MetadataTypeDefinitions').triggeredSend;
module.exports = TriggeredSend;