-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsfmcHelper.js
410 lines (358 loc) · 10.6 KB
/
sfmcHelper.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
// ==============================================================
// SETUP
// ==============================================================
// Require Marketing Cloud Packages + Parameters
const env = require('dotenv').config();
const ET_Client = require('sfmc-fuelsdk-node');
const clientId = process.env.REACT_APP_SFMC_CLIENTID;
const clientSecret = process.env.REACT_APP_SFMC_CLIENTSECRET;
const stack = process.env.REACT_APP_SFMC_STACK;
const origin = process.env.REACT_APP_SFMC_ORIGIN;
const authOrigin = process.env.REACT_APP_SFMC_AUTHORIGIN;
const soapOrigin = process.env.REACT_APP_SFMC_SOAPORIGIN;
// Instantiating Node Class
const sfmcNode = new ET_Client(clientId, clientSecret, stack, {
origin,
authOrigin,
soapOrigin,
authOptions: {
authVersion: 2,
// accountId: parentBU,
applicationType: 'Server'
}
});
// console.log(sfmcNode)
// ==============================================================
// DEBUG
// ==============================================================
let debug = true;
let sampleDataExtensionObj = {
Client: { ID: '523005765' },
PartnerKey: '',
CreatedDate: '2021-01-28T09:51:52.33',
ModifiedDate: '2021-01-28T09:51:52.33',
ObjectID: '915f39bb-8061-eb11-a2f1-1402ec938de9',
CustomerKey: 'Contact_Salesforce',
IsPlatformObject: 'false',
Name: 'Contact_Salesforce',
Description: '',
IsSendable: 'true',
IsTestable: 'true',
SendableDataExtensionField: {
PartnerKey: '',
ObjectID: '',
Name: '_ContactKey'
},
SendableSubscriberField: { Name: '_SubscriberKey' },
DataRetentionPeriodUnitOfMeasure: '0',
RowBasedRetention: 'false',
ResetRetentionPeriodOnImport: 'false',
DeleteAtEndOfRetentionPeriod: 'false',
RetainUntil: '',
CategoryID: '1693962',
Status: 'None'
};
let sampleDataExtensionObj2 = {
Client: { ID: '523005765' },
PartnerKey: '',
CreatedDate: '2021-02-08T12:39:07.5',
ModifiedDate: '2021-02-08T12:45:00.447',
ObjectID: 'b1b59aeb-3c6a-eb11-a2f1-1402ec938de9',
CustomerKey: '324C7C3C-7EDB-4EE9-B46F-72E20FC6FEBD',
IsPlatformObject: 'false',
Name: '2_1_1_Master_SMS',
Description: '',
IsSendable: 'false',
IsTestable: 'false',
RowBasedRetention: 'false',
ResetRetentionPeriodOnImport: 'false',
DeleteAtEndOfRetentionPeriod: 'false',
RetainUntil: '',
CategoryID: '1697783',
Status: 'None'
};
let sampleEmailColumn = {
Client: { ID: '523005765' },
PartnerKey: '',
CreatedDate: '2021-01-28T09:51:52.33',
ModifiedDate: '2021-01-28T09:51:52.33',
ObjectID: '985f39bb-8061-eb11-a2f1-1402ec938de9',
CustomerKey: '[Contact_Salesforce].[Email]',
Name: 'Email',
Scale: '0',
DefaultValue: '',
MaxLength: '80',
IsRequired: 'false',
Ordinal: '7',
IsPrimaryKey: 'false',
FieldType: 'EmailAddress'
};
if (debug === true) {
console.log('RESULTS START HERE:');
}
// CODE THAT HELPS YOU SEE WHAT PROPERTIES ARE RETRIEVABLE IN API OBJECT
// sfmcNode.SoapClient.describe('Subscriber', (err, response) => {
// let properties = response.body.ObjectDefinition.Properties
// let propertyArray = [];
// properties.forEach(property => {
// if (property.IsRetrievable == 'true') {
// propertyArray.push(property.Name)
// }
// })
// console.log(propertyArray)
// })
// ==============================================================
// FUNCTIONS
// ==============================================================
function getAllDataExtensions() {
var options = {
props: [
'ObjectID',
'PartnerKey',
'CustomerKey',
'Name',
'CreatedDate',
'ModifiedDate',
'Client.ID',
'Description',
'IsSendable',
'IsTestable',
'SendableDataExtensionField.Name',
'SendableSubscriberField.Name',
'Template.CustomerKey',
'CategoryID',
'Status',
'IsPlatformObject',
'DataRetentionPeriodLength',
'DataRetentionPeriodUnitOfMeasure',
'RowBasedRetention',
'ResetRetentionPeriodOnImport',
'DeleteAtEndOfRetentionPeriod',
'RetainUntil',
'DataRetentionPeriod'
],
filter: {
leftOperand: 'Client.ID',
operator: 'isNotNull',
rightOperand: ''
}
};
const de = sfmcNode.dataExtension(options);
let dataExtensionsResult = new Promise((resolve, reject) => {
de.get((err, res) => {
if (err) console.log(err);
if (res) resolve(res.body.Results);
});
});
return dataExtensionsResult;
}
function getAllDataExtensionColumns(dataExtensionObject) {
var options = {
props: [
'ObjectID',
'PartnerKey',
'Name',
'DefaultValue',
'MaxLength',
'IsRequired',
'Ordinal',
'IsPrimaryKey',
'FieldType',
'CreatedDate',
'ModifiedDate',
'Scale',
'Client.ID',
'CustomerKey'
],
filter: {
leftOperand: 'DataExtension.CustomerKey',
operator: 'equals',
rightOperand: dataExtensionObject.CustomerKey
}
};
let deColumn = sfmcNode.dataExtensionColumn(options);
const allDataExtensionColumns = new Promise((resolve, reject) => {
deColumn.get((err, res) => {
if (err) reject(err);
if (res) resolve(res.body.Results);
});
});
return allDataExtensionColumns;
}
async function getMatchingDataExtensionRows(
dataExtensionObject,
columnName,
valueToMatch
) {
let dataExtensionColumnNames = [];
let dataExtensionColumns = await getAllDataExtensionColumns(
dataExtensionObject
);
for (let column of dataExtensionColumns) {
dataExtensionColumnNames.push(column.Name);
}
let options = {
Name: dataExtensionObject.CustomerKey,
props: dataExtensionColumnNames,
filter: {
leftOperand: columnName,
operator: 'equals',
rightOperand: valueToMatch
}
};
let deRow = sfmcNode.dataExtensionRow(options);
let matchingDataExtensionRows = new Promise((resolve, reject) => {
deRow.get((err, res) => {
if (err) {
reject(err);
} else {
let results = res.body.Results;
let rows = [];
results.forEach((result) => {
// SFMC returns the results in an array of Key/Value Obj pairs, like this [{Name:Name, Value:Value}]
let arrayOfNameValuePairs = result.Properties.Property;
// ...Because that's dumb, we flatten it into a single obj, like so {Name: Value}
let flattenedObj = arrayOfNameValuePairs.reduce(
(obj, item) => Object.assign(obj, { [item.Name]: item.Value }),
{}
);
// ...And push the result into the rows array
rows.push(flattenedObj);
});
resolve(rows);
}
});
});
return matchingDataExtensionRows;
}
function getFolder(categoryId) {
var options = {
props: [
'ID',
'Client.ID',
'ParentFolder.ID',
'ParentFolder.CustomerKey',
'ParentFolder.ObjectID',
'ParentFolder.Name',
'ParentFolder.Description',
'ParentFolder.ContentType',
'ParentFolder.IsActive',
'ParentFolder.IsEditable',
'ParentFolder.AllowChildren',
'Name',
'Description',
'ContentType',
'IsActive',
'IsEditable',
'AllowChildren',
'CreatedDate',
'ModifiedDate',
'Client.ModifiedBy',
'ObjectID',
'CustomerKey'
],
filter: {
leftOperand: 'ID',
operator: 'equals',
rightOperand: categoryId
}
};
let folder = sfmcNode.folder(options);
let folderData = new Promise((resolve, reject) => {
folder.get((err, res) => {
if (err) {
reject(console.log(err));
}
if (res) {
resolve(res.body.Results[0]);
}
});
});
return folderData;
}
async function getFolderPath(categoryId) {
let folderHierarchy = [];
let parentFolder;
do {
let folder = await getFolder(categoryId);
folderHierarchy.unshift(folder.Name);
parentFolder = folder.ParentFolder;
if (parentFolder.Name) {
categoryId = parentFolder.ID;
} else {
parentFolder = '';
}
} while (parentFolder);
let folderPath = folderHierarchy.join(' > ');
// returns string 'A > B > C'
return folderPath;
}
function getSubscriberInfo(emailOrContactKey) {
let inputType = emailOrContactKey.includes('@') ? 'Email' : 'Text';
let options = {
props: [
'ID',
'CreatedDate',
'Client.ID',
'EmailAddress',
'SubscriberKey',
'UnsubscribedDate',
'Status'
],
filter: {
leftOperand: inputType === 'Email' ? 'EmailAddress' : 'SubscriberKey',
operator: 'equals',
rightOperand: emailOrContactKey
}
};
let subscriberInfo = sfmcNode.subscriber(options);
const subscriberInfoResult = new Promise((resolve, reject) => {
subscriberInfo.get((err, res) => {
if (err) reject(err);
if (res) resolve(res.body.Results);
});
});
return subscriberInfoResult;
}
async function findSubscriber(input) {
// 1. If input contains '@' assume inputType = Email, otherwise assume input is a SubscriberKey (i.e. inputType = Text)
// 2. If inputType = Email, for each data extension, search if there's a column name where fieldType = 'Email'
// 3. If there's an Email field in a data extension, try to retrieve rows based on that field using the given input
// 4. If results are found, return the rows
let inputType = input.includes('@') ? 'Email' : 'Text';
let allDataExtensions = await getAllDataExtensions();
let subscriberInfo = await getSubscriberInfo(input);
let dataExtensionResults = [];
let results = {
subscriberInfo,
dataExtensionResults
};
if (inputType === 'Email') {
for (const dataExtension of allDataExtensions) {
let deColumns = await getAllDataExtensionColumns(dataExtension);
for (const column of deColumns) {
if (column.FieldType === 'EmailAddress') {
let matchingRows = await getMatchingDataExtensionRows(
dataExtension,
column.Name,
input
);
if (matchingRows.length > 0) {
let folderPath = await getFolderPath(dataExtension.CategoryID);
dataExtensionResults.push({
dataExtension,
column,
matchingRows,
folderPath
});
}
}
}
}
}
return results;
}
// findSubscriber('[email protected]').then(console.log)
module.exports = {
findSubscriber
};