-
Notifications
You must be signed in to change notification settings - Fork 36
/
DataExtension.js
1515 lines (1426 loc) · 62 KB
/
DataExtension.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 jsonToTable from 'json-to-table';
import TYPE from '../../types/mcdev.d.js';
import MetadataType from './MetadataType.js';
import AttributeSet from './AttributeSet.js';
import DataExtensionField from './DataExtensionField.js';
import Folder from './Folder.js';
import { Util } from '../util/util.js';
import File from '../util/file.js';
import auth from '../util/auth.js';
import cache from '../util/cache.js';
import pLimit from 'p-limit';
import inquirer from 'inquirer';
/**
* DataExtension MetadataType
*
* @augments MetadataType
*/
class DataExtension extends MetadataType {
/**
* Upserts dataExtensions after retrieving them from source and target to compare
* if create or update operation is needed.
*
* @param {TYPE.DataExtensionMap} metadataMap dataExtensions mapped by their customerKey
* @returns {Promise} Promise
*/
static async upsert(metadataMap) {
// get existing DE-fields for DE-keys in deployment package to properly handle add/update/delete of fields
const fieldOptions = {};
for (const key of Object.keys(metadataMap)) {
fieldOptions.filter = fieldOptions.filter
? {
leftOperand: {
leftOperand: 'DataExtension.CustomerKey',
operator: 'equals',
rightOperand: key,
},
operator: 'OR',
rightOperand: fieldOptions.filter,
}
: {
leftOperand: 'DataExtension.CustomerKey',
operator: 'equals',
rightOperand: key,
};
}
Util.logger.info(` - Caching dependent Metadata: dataExtensionField`);
await this.#attachFields(metadataMap, fieldOptions);
/** @type {object[]} */
const metadataToCreate = [];
/** @type {object[]} */
const metadataToUpdate = [];
let filteredByPreDeploy = 0;
for (const metadataKey in metadataMap) {
try {
metadataMap[metadataKey] = await this.preDeployTasks(metadataMap[metadataKey]);
} catch (ex) {
// output error & remove from deploy list
Util.logger.error(
` ☇ skipping ${this.definition.type} ${
metadataMap[metadataKey][this.definition.keyField]
} / ${metadataMap[metadataKey][this.definition.nameField]}: ${ex.message}`
);
delete metadataMap[metadataKey];
// skip rest of handling for this DE
filteredByPreDeploy++;
continue;
}
await this.createOrUpdate(
metadataMap,
metadataKey,
false,
metadataToUpdate,
metadataToCreate
);
}
if (metadataToUpdate.length) {
Util.logger.info(
' - Please note that Data Retention Policies can only be set during creation, not during update.'
);
}
const createLimit = pLimit(10);
const createResults = (
await Promise.allSettled(
metadataToCreate
.filter((r) => r !== undefined && r !== null)
.map((metadataEntry) => createLimit(() => this.create(metadataEntry)))
)
)
.filter((r) => r !== undefined && r !== null)
.filter(this.#filterUpsertResults);
const updateLimit = pLimit(10);
const updateResults = (
await Promise.allSettled(
metadataToUpdate
.filter((r) => r !== undefined && r !== null)
.map((metadataEntry) =>
updateLimit(() => this.update(metadataEntry.after, metadataEntry.before))
)
)
)
.filter((r) => r !== undefined && r !== null)
.filter(this.#filterUpsertResults);
const successfulResults = [...createResults, ...updateResults];
Util.logger.info(
`${this.definition.type} upsert: ${createResults.length} of ${metadataToCreate.length} created / ${updateResults.length} of ${metadataToUpdate.length} updated` +
(filteredByPreDeploy > 0 ? ` / ${filteredByPreDeploy} filtered` : '')
);
let upsertResults;
if (successfulResults.length > 0) {
const metadataResults = successfulResults
.map((r) => r.value.Results[0].Object)
.map((r) => {
// if only one fields added will return object otherwise array
if (Array.isArray(r?.Fields?.Field)) {
r.Fields = r.Fields.Field;
} else if (r?.Fields?.Field) {
r.Fields = [r.Fields.Field];
}
return r;
});
upsertResults = super.parseResponseBody({ Results: metadataResults });
} else {
upsertResults = {};
}
await this.postDeployTasks(upsertResults, metadataMap, {
created: createResults.length,
updated: updateResults.length,
});
return upsertResults;
}
/**
* helper for {@link MetadataType.upsert}
*
* @param {TYPE.MetadataTypeMap} metadataMap list of metadata
* @param {string} metadataKey key of item we are looking at
* @param {boolean} hasError error flag from previous code
* @param {TYPE.MetadataTypeItemDiff[]} metadataToUpdate list of items to update
* @param {TYPE.MetadataTypeItem[]} metadataToCreate list of items to create
* @returns {'create' | 'update' | 'skip'} action to take
*/
static async createOrUpdate(
metadataMap,
metadataKey,
hasError,
metadataToUpdate,
metadataToCreate
) {
const action = await super.createOrUpdate(
metadataMap,
metadataKey,
hasError,
metadataToUpdate,
metadataToCreate
);
if (action === 'update') {
// Update dataExtension + Columns if they already exist; Create them if not
// Modify columns for update call
DataExtensionField.client = this.client;
DataExtensionField.properties = this.properties;
DataExtension.oldFields ||= {};
DataExtension.oldFields[metadataMap[metadataKey][this.definition.keyField]] =
await DataExtensionField.prepareDeployColumnsOnUpdate(
metadataMap[metadataKey].Fields,
metadataKey
);
if (
metadataMap[metadataKey][this.definition.keyField] !== metadataKey &&
metadataMap[metadataKey].Fields.length
) {
// changeKeyValue / changeKeyField used
Util.logger.warn(
` - ${this.definition.type} ${metadataKey}: Cannot change fields while updating the key. Skipping field update in favor of key update.`
);
metadataMap[metadataKey].Fields.length = 0;
}
// convert simple array into object.Array.object format to cope with how the XML body in the SOAP call needs to look like:
// <Fields>
// <Field>
// <CustomerKey>SubscriberKey</CustomerKey>
// ..
// </Field>
// </Fields>
metadataMap[metadataKey].Fields = { Field: metadataMap[metadataKey].Fields };
} else if (action === 'create') {
this.#cleanupRetentionPolicyFields(metadataMap[metadataKey]);
// convert simple array into object.Array.object format to cope with how the XML body in the SOAP call needs to look like:
// <Fields>
// <Field>
// <CustomerKey>SubscriberKey</CustomerKey>
// ..
// </Field>
// </Fields>
metadataMap[metadataKey].Fields = { Field: metadataMap[metadataKey].Fields };
}
}
/**
* helper for {@link DataExtension.upsert}
*
* @private
* @param {object} res -
* @returns {boolean} true: keep, false: discard
*/
static #filterUpsertResults(res) {
if (res.status === 'rejected') {
// promise rejects, whole request failed
Util.logger.error('- error upserting dataExtension: ' + res.reason);
return false;
} else if (res.value == undefined || Object.keys(res.value).length === 0) {
// in case of returning empty result handle gracefully
// TODO: consider if SOAP handler for this should really return empty object
return false;
} else if (res.value.results) {
Util.logger.error(
'- error upserting dataExtension: ' +
(res.value.Results[0].Object ? res.value.Results[0].Object.Name : '') +
'. ' +
res.value.Results[0].StatusMessage
);
return false;
} else if (res.status === 'fulfilled' && res?.value?.faultstring) {
// can happen that the promise does not reject, but that it resolves an error
Util.logger.error('- error upserting dataExtension: ' + res.value.faultstring);
return false;
} else {
return true;
}
}
/**
* Create a single dataExtension. Also creates their columns in 'dataExtension.columns'
*
* @param {TYPE.DataExtensionItem} metadata single metadata entry
* @returns {Promise} Promise
*/
static async create(metadata) {
return super.createSOAP(metadata);
}
/**
* SFMC saves a date in "RetainUntil" under certain circumstances even
* if that field duplicates whats in the period fields
* during deployment, that extra value is not accepted by the APIs which is why it needs to be removed
*
* @private
* @param {TYPE.DataExtensionItem} metadata single metadata entry
* @returns {void}
*/
static #cleanupRetentionPolicyFields(metadata) {
if (
metadata.DataRetentionPeriodLength &&
metadata.DataRetentionPeriodUnitOfMeasure &&
metadata.RetainUntil !== ''
) {
metadata.RetainUntil = '';
Util.logger.warn(
` - RetainUntil date was reset automatically because RetentionPeriod info was found in: ${metadata.CustomerKey}`
);
}
}
/**
* Updates a single dataExtension. Also updates their columns in 'dataExtension.columns'
*
* @param {TYPE.DataExtensionItem} metadata single metadata entry
* @returns {Promise} Promise
*/
static async update(metadata) {
return super.updateSOAP(metadata);
}
/**
* Gets executed after deployment of metadata type
*
* @param {TYPE.DataExtensionMap} upsertedMetadata metadata mapped by their keyField
* @param {TYPE.DataExtensionMap} originalMetadata metadata to be updated (contains additioanl fields)
* @param {{created: number, updated: number}} createdUpdated counter representing successful creates/updates
* @returns {void}
*/
static async postDeployTasks(upsertedMetadata, originalMetadata, createdUpdated) {
for (const key in upsertedMetadata) {
const item = upsertedMetadata[key];
const oldKey = Util.changedKeysMap?.[this.definition.type]?.[key] || key;
delete Util.changedKeysMap?.[this.definition.type]?.[key];
const cachedVersion = createdUpdated.updated
? cache.getByKey(this.definition.type, oldKey)
: null;
if (cachedVersion) {
// UPDATE
// restore retention values that are typically not returned by the update call
item.RowBasedRetention = cachedVersion.RowBasedRetention;
item.ResetRetentionPeriodOnImport = cachedVersion.ResetRetentionPeriodOnImport;
item.DeleteAtEndOfRetentionPeriod = cachedVersion.DeleteAtEndOfRetentionPeriod;
item.RetainUntil = cachedVersion.RetainUntil;
const existingFields = DataExtension.oldFields[item[this.definition.keyField]];
if (item.Fields === '') {
// if no fields were updated, we need to set Fields to "empty string" for the API to work
// reset here to get the correct field list
item.Fields = Object.keys(existingFields)
.map((el) => existingFields[el])
.sort((a, b) => a.Ordinal - b.Ordinal);
} else if (existingFields) {
// get list of updated fields
/** @type {TYPE.DataExtensionFieldItem[]} */
const updatedFieldsArr = originalMetadata[oldKey].Fields.Field.filter(
(field) => field.ObjectID && field.ObjectID !== ''
);
// convert existing fields obj into array and sort
/** @type {TYPE.DataExtensionFieldItem[]} */
const finalFieldsArr = Object.keys(existingFields)
.map((el) => {
/** @type {TYPE.DataExtensionFieldItem} */
const existingField = existingFields[el];
// check if the current field was updated and then override with it. otherwise use existing value
const field =
updatedFieldsArr.find(
(field) => field.ObjectID === existingField.ObjectID
) || existingField;
// field does not have a ordinal value because we rely on array order
field.Ordinal = existingField.Ordinal;
// updating FieldType is not supported by API and hence removed
field.FieldType = existingField.FieldType;
return field;
})
.sort((a, b) => a.Ordinal - b.Ordinal);
// get list of new fields
/** @type {TYPE.DataExtensionFieldItem[]} */
const newFieldsArr = originalMetadata[oldKey].Fields.Field.filter(
(field) => !field.ObjectID
);
// push new fields to end of list
if (newFieldsArr.length) {
finalFieldsArr.push(...newFieldsArr);
}
// sort Fields entry to the end of the object for saving in .json
delete item.Fields;
item.Fields = finalFieldsArr;
}
}
// UPDATE + CREATE
for (const field of item.Fields) {
DataExtensionField.postRetrieveTasks(field, true);
}
}
await this.#fixShared(upsertedMetadata, originalMetadata, createdUpdated);
}
/**
* takes care of updating attribute groups on child BUs after an update to Shared DataExtensions
* helper for {@link DataExtension.postDeployTasks}
* fixes an issue where shared data extensions are not visible in data designer on child BU; SF known issue: https://issues.salesforce.com/#q=W-11031095
*
* @param {TYPE.DataExtensionMap} upsertedMetadata metadata mapped by their keyField
* @param {TYPE.DataExtensionMap} originalMetadata metadata to be updated (contains additioanl fields)
* @param {{created: number, updated: number}} createdUpdated counter representing successful creates/updates
* @returns {void}
*/
static async #fixShared(upsertedMetadata, originalMetadata, createdUpdated) {
if (this.buObject.eid !== this.buObject.mid) {
// only if we were executing a deploy on parent bu could we be deploying shared data extensions
Util.logger.debug(`Skipping fixShared logic because we are not executing on Parent BU`);
return;
}
if (createdUpdated.updated === 0) {
// only if updates were made could the issue in https://issues.salesforce.com/#q=W-11031095 affect data designer
Util.logger.debug(`Skipping fixShared logic because nothing was updated`);
return;
}
// find all shared data extensions
if (!this.deployedSharedKeys.length) {
Util.logger.debug(
`Skipping fixShared logic because no Shared Data Extensions were updated`
);
return;
}
const sharedDataExtensionsKeys = this.deployedSharedKeys;
this.deployedSharedKeys = null;
if (Util.OPTIONS.fixShared) {
// select which BUs to run this for
const selectedBuNames = await this.#fixShared_getBUs();
// backup settings
const buObjectBak = this.buObject;
const clientBak = this.client;
// get dataExtension ID-Key relationship
const sharedDataExtensionMap = {};
for (const key of sharedDataExtensionsKeys) {
try {
const id = cache.searchForField(
'dataExtension',
key,
'CustomerKey',
'ObjectID',
this.buObject.eid
);
sharedDataExtensionMap[id] = key;
} catch {
continue;
}
}
// run the fix-data-model logic
Util.logger.info(
`Fixing Shared Data Extensions details in data models of child BUs` +
Util.getKeysString(sharedDataExtensionsKeys)
);
for (const buName of selectedBuNames) {
await this.#fixShared_onBU(buName, buObjectBak, clientBak, sharedDataExtensionMap);
}
Util.logger.info(`Finished fixing Shared Data Extensions details in data models`);
// restore settings
this.buObject = buObjectBak;
this.client = clientBak;
} else {
Util.logger.warn(
'Shared Data Extensions were updated but --fixShared option is not set. This can result in your changes not being visible in attribute groups on child BUs.'
);
Util.logger.info(
'We recommend to re-run your deployment with the --fixShared option unless you are sure your Shared Data Extension is not used in attribute groups on any child BU.'
);
}
}
/**
* helper for {@link DataExtension.#fixShared}
*
* @returns {string[]} list of selected BU names
*/
static async #fixShared_getBUs() {
const buListObj = this.properties.credentials[this.buObject.credential].businessUnits;
const fixBuPreselected = [];
const availableBuNames = Object.keys(buListObj).filter(
(buName) => buName !== Util.parentBuName
);
if (typeof Util.OPTIONS.fixShared === 'string') {
if (Util.OPTIONS.fixShared === '*') {
// pre-select all BUs
fixBuPreselected.push(...availableBuNames);
} else {
// pre-select BUs from comma-separated list
fixBuPreselected.push(
...Util.OPTIONS.fixShared
.split(',')
.filter(Boolean)
.map((bu) => bu.trim())
.filter((bu) => availableBuNames.includes(bu))
);
}
}
if (Util.skipInteraction && fixBuPreselected.length) {
// assume programmatic use case or user that wants to skip the wizard. Use pre-selected BUs
return fixBuPreselected;
}
const buList = availableBuNames.map((name) => ({
name,
value: name,
checked: fixBuPreselected.includes(name),
}));
const questions = {
type: 'checkbox',
name: 'businessUnits',
message: 'Please select BUs that have access to the updated Shared Data Extensions:',
pageSize: 10,
choices: buList,
};
let responses = null;
try {
responses = await inquirer.prompt(questions);
} catch (ex) {
Util.logger.info(ex);
}
return responses.businessUnits;
}
/**
* helper for {@link DataExtension.#fixShared}
*
* @param {string} childBuName name of child BU to fix
* @param {TYPE.BuObject} buObjectParent bu object for parent BU
* @param {object} clientParent SDK for parent BU
* @param {Object.<string, string>} sharedDataExtensionMap ID-Key relationship of shared data extensions
* @returns {Promise.<string[]>} updated shared DE keys on BU
*/
static async #fixShared_onBU(
childBuName,
buObjectParent,
clientParent,
sharedDataExtensionMap
) {
/** @type {TYPE.BuObject} */
const buObjectChildBu = {
eid: this.properties.credentials[buObjectParent.credential].eid,
mid: this.properties.credentials[buObjectParent.credential].businessUnits[childBuName],
businessUnit: childBuName,
credential: this.buObject.credential,
};
const clientChildBu = auth.getSDK(buObjectChildBu);
try {
// check if shared data Extension is used in an attributeSet on current BU
AttributeSet.properties = this.properties;
AttributeSet.buObject = buObjectChildBu;
AttributeSet.client = clientChildBu;
const sharedDeIdsUsedOnBU = await AttributeSet.fixShared_retrieve(
sharedDataExtensionMap,
DataExtensionField.fixShared_fields
);
if (sharedDeIdsUsedOnBU.length) {
let sharedDataExtensionsKeys = sharedDeIdsUsedOnBU.map(
(deId) => sharedDataExtensionMap[deId]
);
Util.logger.info(
` - Fixing dataExtensions on BU ${childBuName} ` +
Util.getKeysString(sharedDataExtensionsKeys)
);
for (const deId of sharedDeIdsUsedOnBU) {
// dont use Promise.all to ensure order of execution; otherwise, switched BU contexts in one step will affect the next
const fixed = await this.#fixShared_item(
deId,
sharedDataExtensionMap[deId],
buObjectChildBu,
clientChildBu,
buObjectParent,
clientParent
);
if (!fixed) {
// remove from list of shared DEs that were fixed
sharedDataExtensionsKeys = sharedDataExtensionsKeys.filter(
(key) => key !== sharedDataExtensionMap[deId]
);
}
}
if (sharedDataExtensionsKeys.length) {
Util.logger.debug(
` - Fixed ${sharedDataExtensionsKeys.length}/${
sharedDeIdsUsedOnBU.length
}: ${sharedDataExtensionsKeys.join(', ')}`
);
}
return sharedDataExtensionsKeys;
} else {
Util.logger.info(
Util.getGrayMsg(
` - No matching attributeSet found for given Shared Data Extensions keys found on BU ${childBuName}`
)
);
return [];
}
} catch (ex) {
Util.logger.error(ex.message);
return [];
}
}
/**
* method that actually takes care of triggering the update for a particular BU-sharedDe combo
* helper for {@link DataExtension.#fixShared_onBU}
*
* @param {string} deId data extension ObjectID
* @param {string} deKey dataExtension key
* @param {TYPE.BuObject} buObjectChildBu BU object for Child BU
* @param {object} clientChildBu SDK for child BU
* @param {TYPE.BuObject} buObjectParent BU object for Parent BU
* @param {object} clientParent SDK for parent BU
* @returns {Promise.<boolean>} flag that signals if the fix was successful
*/
static async #fixShared_item(
deId,
deKey,
buObjectChildBu,
clientChildBu,
buObjectParent,
clientParent
) {
try {
// add field via child BU
const randomSuffix = await DataExtension.#fixShared_item_addField(
buObjectChildBu,
clientChildBu,
deKey,
deId
);
// get field ID from parent BU (it is not returned on child BU)
const fieldObjectID = await DataExtension.#fixShared_item_getFieldId(
randomSuffix,
buObjectParent,
clientParent,
deKey
);
// delete field via child BU
await DataExtension.#fixShared_item_deleteField(
randomSuffix,
buObjectChildBu,
clientChildBu,
deKey,
fieldObjectID
);
Util.logger.info(
` - Fixed dataExtension ${deKey} on BU ${buObjectChildBu.businessUnit}`
);
return true;
} catch (ex) {
Util.logger.error(
`- error fixing dataExtension ${deKey} on BU ${buObjectChildBu.businessUnit}: ${ex.message}`
);
return false;
}
}
/**
* add a new field to the shared DE to trigger an update to the data model
* helper for {@link DataExtension.#fixShared_item}
*
* @param {TYPE.BuObject} buObjectChildBu BU object for Child BU
* @param {object} clientChildBu SDK for child BU
* @param {string} deKey dataExtension key
* @param {string} deId dataExtension ObjectID
* @returns {Promise.<string>} randomSuffix
*/
static async #fixShared_item_addField(buObjectChildBu, clientChildBu, deKey, deId) {
this.buObject = buObjectChildBu;
this.client = clientChildBu;
const randomSuffix = Util.OPTIONS._runningTest
? '_randomNumber_'
: Math.floor(Math.random() * 9999999999);
// add a new field to the shared DE to trigger an update to the data model
const soapType = this.definition.soapType || this.definition.type;
await this.client.soap.update(
Util.capitalizeFirstLetter(soapType),
{
CustomerKey: deKey,
ObjectID: deId,
Fields: {
Field: [
{
Name: 'TriggerUpdate' + randomSuffix,
IsRequired: false,
IsPrimaryKey: false,
FieldType: 'Boolean',
ObjectID: null,
},
],
},
},
null
);
return randomSuffix;
}
/**
* get ID of the field added by {@link DataExtension.#fixShared_item_addField} on the shared DE via parent BU
* helper for {@link DataExtension.#fixShared_item}
*
* @param {string} randomSuffix -
* @param {TYPE.BuObject} buObjectParent BU object for Parent BU
* @param {object} clientParent SDK for parent BU
* @param {string} deKey dataExtension key
* @returns {Promise.<string>} fieldObjectID
*/
static async #fixShared_item_getFieldId(randomSuffix, buObjectParent, clientParent, deKey) {
DataExtensionField.buObject = buObjectParent;
DataExtensionField.client = clientParent;
const fieldKey = `[${deKey}].[TriggerUpdate${randomSuffix}]`;
const fieldResponse = await DataExtensionField.retrieveForCache(
{
filter: {
leftOperand: 'CustomerKey',
operator: 'equals',
rightOperand: fieldKey,
},
},
['Name', 'ObjectID']
);
const fieldObjectID = fieldResponse.metadata[fieldKey]?.ObjectID;
return fieldObjectID;
}
/**
* delete the field added by {@link DataExtension.#fixShared_item_addField}
* helper for {@link DataExtension.#fixShared_item}
*
* @param {string} randomSuffix -
* @param {TYPE.BuObject} buObjectChildBu BU object for Child BU
* @param {object} clientChildBu SDK for child BU
* @param {string} deKey dataExtension key
* @param {string} fieldObjectID field ObjectID
* @returns {Promise} -
*/
static async #fixShared_item_deleteField(
randomSuffix,
buObjectChildBu,
clientChildBu,
deKey,
fieldObjectID
) {
DataExtensionField.buObject = buObjectChildBu;
DataExtensionField.client = clientChildBu;
await DataExtensionField.deleteByKeySOAP(
deKey + '.TriggerUpdate' + randomSuffix,
fieldObjectID
);
}
/**
* Retrieves dataExtension metadata. Afterwards starts retrieval of dataExtensionColumn metadata retrieval
*
* @param {string} retrieveDir Directory where retrieved metadata directory will be saved
* @param {string[]} [additionalFields] Returns specified fields even if their retrieve definition is not set to true
* @param {void} [_] unused parameter
* @param {string} [key] customer key of single item to retrieve
* @returns {Promise.<{metadata: TYPE.DataExtensionMap, type: string}>} Promise of item map
*/
static async retrieve(retrieveDir, additionalFields, _, key) {
/** @type {TYPE.SoapRequestParams} */
let requestParams = null;
/** @type {TYPE.SoapRequestParams} */
let fieldOptions = null;
if (key) {
requestParams = {
filter: {
leftOperand: 'CustomerKey',
operator: 'equals',
rightOperand: key,
},
};
fieldOptions = {
filter: {
leftOperand: 'DataExtension.CustomerKey',
operator: 'equals',
rightOperand: key,
},
};
}
let metadata = await this._retrieveAll(additionalFields, requestParams);
// in case of cache dont get fields
if (metadata && retrieveDir) {
// get fields from API
await this.#attachFields(metadata, fieldOptions, additionalFields);
}
if (!retrieveDir && this.buObject.eid !== this.buObject.mid) {
const metadataParentBu = await this.retrieveSharedForCache(additionalFields);
// make sure to overwrite parent bu DEs with local ones
metadata = { ...metadataParentBu, ...metadata };
}
if (retrieveDir) {
const savedMetadata = await super.saveResults(metadata, retrieveDir, null);
Util.logger.info(
`Downloaded: ${this.definition.type} (${Object.keys(savedMetadata).length})` +
Util.getKeysString(key)
);
await this.runDocumentOnRetrieve(key, savedMetadata);
}
return { metadata: metadata, type: 'dataExtension' };
}
/**
* get shared dataExtensions from parent BU and merge them into the cache
* helper for {@link DataExtension.retrieve} and for AttributeSet.fixShared_retrieve
*
* @param {string[]} [additionalFields] Returns specified fields even if their retrieve definition is not set to true
* @returns {Promise.<TYPE.DataExtensionMap>} keyField => metadata map
*/
static async retrieveSharedForCache(additionalFields = []) {
// for caching, we want to retrieve shared DEs as well from the instance parent BU
Util.logger.info(' - Caching dependent Metadata: dataExtension (shared via _ParentBU_)');
const buObjectBak = this.buObject;
const clientBak = this.client;
/** @type {TYPE.BuObject} */
const buObjectParentBu = {
eid: this.properties.credentials[this.buObject.credential].eid,
mid: this.properties.credentials[this.buObject.credential].eid,
businessUnit: Util.parentBuName,
credential: this.buObject.credential,
};
try {
this.buObject = buObjectParentBu;
this.client = auth.getSDK(buObjectParentBu);
} catch (ex) {
Util.logger.error(ex.message);
return;
}
const metadataParentBu = await this._retrieveAll(additionalFields);
// get shared folders to match our shared / synched Data Extensions
const subTypeArr = this.definition.dependencies
.filter((item) => item.startsWith('folder-'))
.map((item) => item.slice(7));
Util.logger.info(' - Caching dependent Metadata: folder (shared via _ParentBU_)');
Util.logSubtypes(subTypeArr);
Folder.client = this.client;
Folder.buObject = this.buObject;
Folder.properties = this.properties;
const result = await Folder.retrieveForCache(null, subTypeArr);
cache.mergeMetadata('folder', result.metadata, this.buObject.eid);
// get the types and clean out non-shared ones
const folderTypesFromParent = MetadataTypeDefinitions.folder.folderTypesFromParent;
for (const metadataEntry in metadataParentBu) {
try {
// get the data extension type from the folder
const folderContentType = cache.searchForField(
'folder',
metadataParentBu[metadataEntry].CategoryID,
'ID',
'ContentType',
this.buObject.eid
);
if (!folderTypesFromParent.includes(folderContentType)) {
// Util.logger.verbose(
// `removing ${metadataEntry} because r__folder_ContentType '${folderContentType}' identifies this DE as not being shared`
// );
delete metadataParentBu[metadataEntry];
}
} catch (ex) {
Util.logger.debug(
`removing ${metadataEntry} because of error while retrieving r__folder_ContentType: ${ex.message}`
);
delete metadataParentBu[metadataEntry];
}
}
// revert client to current default
this.client = clientBak;
this.buObject = buObjectBak;
Folder.client = clientBak;
Folder.buObject = buObjectBak;
return metadataParentBu;
}
/**
* helper to retrieve all dataExtension fields and attach them to the dataExtension metadata
*
* @private
* @param {TYPE.DataExtensionMap} metadata already cached dataExtension metadata
* @param {TYPE.SoapRequestParams} [fieldOptions] optionally filter results
* @param {string[]} [additionalFields] Returns specified fields even if their retrieve definition is not set to true
* @returns {Promise.<void>} -
*/
static async #attachFields(metadata, fieldOptions, additionalFields) {
const fieldsObj = await this._retrieveFields(fieldOptions, additionalFields);
const fieldKeys = Object.keys(fieldsObj);
// add fields to corresponding DE
for (const key of fieldKeys) {
const field = fieldsObj[key];
if (metadata[field?.DataExtension?.CustomerKey]) {
metadata[field.DataExtension.CustomerKey].Fields.push(field);
} else {
Util.logger.warn(` - Issue retrieving data extension fields. key='${key}'`);
}
}
// sort fields by Ordinal value (API returns field unsorted)
for (const metadataEntry in metadata) {
metadata[metadataEntry].Fields.sort(DataExtensionField.sortDeFields);
}
// remove attributes that we do not want to retrieve
// * do this after sorting on the DE's field list
for (const key of fieldKeys) {
DataExtensionField.postRetrieveTasks(fieldsObj[key], true);
}
}
/**
* Retrieves dataExtension metadata. Afterwards starts retrieval of dataExtensionColumn metadata retrieval
*
* @param {string[]} [additionalFields] Returns specified fields even if their retrieve definition is not set to true
* @returns {Promise.<{metadata: TYPE.DataExtensionMap, type: string}>} Promise of item map
*/
static async retrieveChangelog(additionalFields) {
const metadata = await this._retrieveAll(additionalFields);
return { metadata: metadata, type: 'dataExtension' };
}
/**
* manages post retrieve steps
*
* @param {TYPE.DataExtensionItem} metadata a single dataExtension
* @returns {TYPE.DataExtensionItem} metadata
*/
static async postRetrieveTasks(metadata) {
// Error during deploy if SendableSubscriberField.Name = '_SubscriberKey' even though it is retrieved like that
// Therefore map it to 'Subscriber Key'. Retrieving afterward still results in '_SubscriberKey'
if (metadata.SendableSubscriberField?.Name === '_SubscriberKey') {
metadata.SendableSubscriberField.Name = 'Subscriber Key';
}
this.setFolderPath(metadata);
// DataExtensionTemplate
if (metadata.Template?.CustomerKey) {
try {
metadata.r__dataExtensionTemplate_Name = cache.searchForField(
'dataExtensionTemplate',
metadata.Template.CustomerKey,
'CustomerKey',
'Name'
);
delete metadata.Template;
} catch (ex) {
Util.logger.debug(ex.message);
// Let's allow retrieving such DEs but warn that they cannot be deployed to another BU.
// Deploying to same BU still works!
// A workaround exists but it's likely not beneficial to explain to users:
// Create a DE based on the not-supported template on the target BU, retrieve it, copy the Template.CustomerKey into the to-be-deployed DE (or use mcdev-templating), done
Util.logger.warn(
` - Issue with dataExtension '${
metadata[this.definition.nameField]
}': Could not find specified DataExtension Template. Please note that DataExtensions based on SMSMessageTracking and SMSSubscriptionLog cannot be deployed automatically across BUs at this point.`
);
}
}
// remove the date fields manually here because we need them in the changelog but not in the saved json
delete metadata.CreatedDate;
delete metadata.ModifiedDate;
return metadata;
}
/**
* Helper to retrieve Data Extension Fields
*
* @private
* @param {TYPE.SoapRequestParams} [options] options (e.g. continueRequest)
* @param {string[]} [additionalFields] Returns specified fields even if their retrieve definition is not set to true
* @returns {Promise.<TYPE.DataExtensionFieldMap>} Promise of items
*/
static async _retrieveFields(options, additionalFields) {
if (!options) {
// dont print this during updates or templating which retrieves fields DE-by-DE
Util.logger.info(' - Caching dependent Metadata: dataExtensionField');
}
DataExtensionField.client = this.client;
DataExtensionField.properties = this.properties;
const response = await DataExtensionField.retrieveForCache(options, additionalFields);
return response.metadata;
}
/**
* helps retrieving fields during templating and deploy where we dont want the full list
*
* @private
* @param {TYPE.DataExtensionMap} metadata list of DEs
* @param {string} customerKey external key of single DE
* @returns {Promise.<void>} -
*/
static async _retrieveFieldsForSingleDe(metadata, customerKey) {
const fieldOptions = {
filter: {
leftOperand: 'DataExtension.CustomerKey',
operator: 'equals',
rightOperand: customerKey,
},
};
const fieldsObj = await this._retrieveFields(fieldOptions);
DataExtensionField.client = this.client;
DataExtensionField.properties = this.properties;
const fieldArr = DataExtensionField.convertToSortedArray(fieldsObj);
// remove attributes that we do not want to retrieve
// * do this after sorting on the DE's field list
for (const field of fieldArr) {
DataExtensionField.postRetrieveTasks(field, true);
}
metadata[customerKey].Fields = fieldArr;
}
/**
* helper for {@link MetadataType.updateREST} and {@link MetadataType.updateSOAP} that removes old files after the key was changed
*
* @private
* @param {TYPE.MetadataTypeItem} metadataEntry a single metadata Entry