forked from google/bulkdozer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Loaders.js
2787 lines (2283 loc) · 84 KB
/
Loaders.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
/***************************************************************************
*
* Copyright 2022 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Note that these code samples being shared are not official Google
* products and are not formally supported.
*
***************************************************************************/
/*
* Gets the profile id from the Store tab
*
* returns: profile id
*/
function getProfileId() {
return getSheetDAO().getValue('Store', 'B2');
}
/*
* Gets the Creative Name + Creative ID concatenation configuration - Feature #1
*
* returns: boolean flag to turn on/off this feature
*/
function getCreativeNameCreativeIdFeatureConfig() {
return getSheetDAO().getValue('Store', 'B8')
}
/*
* Gets the ActiveOnly flag from the store tab
*
* returns: boolean representing the value of the active flag
*/
function getActiveOnlyFlag() {
var flag = getSheetDAO().getValue('Store', 'B5');
if(typeof(flag) == 'string') {
flag = flag.toLowerCase() == 'true'
}
return flag;
}
/*
* Gets the UnarchivedOnly flag from the store tab
*
* returns: boolean representing the value of the active flag
*/
function getUnarchivedOnlyFlag() {
var flag = getSheetDAO().getValue('Store', 'B7');
if(typeof(flag) == 'string') {
flag = flag.toLowerCase() == 'true'
}
return flag;
}
/**
*
* Gets the default creative type configuration from the store tab
*
* returns: String with the value from the default creative type
*/
var defaultCreativeType = null;
function getDefaultCreativeType() {
if(defaultCreativeType == null) {
defaultCreativeType = getSheetDAO().getValue('Store', 'B6');
}
return defaultCreativeType;
}
var DataUtils = function() {
var timezone = getSheetDAO().getValue('Store', 'B6');
var dateFormat = getSheetDAO().getValue('Store', 'B7');
var dateTimeFormat = getSheetDAO().getValue('Store', 'B8');
/**
* Given a creative rotation object from the API returns the value that
* represents that rotation in the feed and matches the CM UI
*
* params: creativeRotation: object with the creative rotation details from CM
*
* returns: String containing the string representation of the rotation and
* strategy
*/
this.creativeRotationType = function(creativeRotation) {
if (creativeRotation) {
if (creativeRotation.type == 'CREATIVE_ROTATION_TYPE_SEQUENTIAL' &&
!creativeRotation.weightCalculationStrategy) {
return 'SEQUENTIAL';
} else if (
creativeRotation.type == 'CREATIVE_ROTATION_TYPE_RANDOM' &&
creativeRotation.weightCalculationStrategy ==
'WEIGHT_STRATEGY_EQUAL') {
return 'EVEN'
} else if (
creativeRotation.type == 'CREATIVE_ROTATION_TYPE_RANDOM' &&
creativeRotation.weightCalculationStrategy ==
'WEIGHT_STRATEGY_CUSTOM') {
return 'CUSTOM'
} else if (
creativeRotation.type == 'CREATIVE_ROTATION_TYPE_RANDOM' &&
creativeRotation.weightCalculationStrategy ==
'WEIGHT_STRATEGY_HIGHEST_CTR') {
return 'CLICK-THROUGH RATE'
} else if (
creativeRotation.type == 'CREATIVE_ROTATION_TYPE_RANDOM' &&
creativeRotation.weightCalculationStrategy ==
'WEIGHT_STRATEGY_OPTIMIZED') {
return 'OPTIMIZED'
}
}
}
this.formatDateTime = function(value) {
if(typeof(value) == 'string') {
return Utilities.formatDate(new Date(value), 'GMT', "yyyy-MM-dd'T'HH:mm:ssZ");
} else if(value) {
return Utilities.formatDate(value, SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "yyyy-MM-dd'T'HH:mm:ssZ");
} else {
return ''
}
}
this.formatDate = function(value) {
if(typeof(value) == 'string') {
return Utilities.formatDate(new Date(value), 'GMT', 'yyyy-MM-dd');
} else if(value) {
return Utilities.formatDate(value, SpreadsheetApp.getActive().getSpreadsheetTimeZone(), 'yyyy-MM-dd');
} else {
return ''
}
}
this.formatDateUserFormat = function(value) {
if(!value) {
return '';
}
if(typeof(value) == 'string') {
value = new Date(value);
}
return Utilities.formatDate(value, timezone, dateFormat);
}
this.formatDateTimeUserFormat = function(value) {
if(!value) {
return '';
}
if(typeof(value) == 'string') {
value = new Date(value);
}
return Utilities.formatDate(value, timezone, dateTimeFormat);
}
}
var dataUtils;
function getDataUtils() {
if(!dataUtils) {
dataUtils = new DataUtils();
}
return dataUtils;
}
/**
* Base class for all loaders, provides common functionality and top level
* orchestration of common flows
*/
var BaseLoader = function(cmDAO) {
// PRIVATE FIELDS
// Provides access to private methods to the this instance
var that = this;
var references = [];
var children = [];
function whichTab(tabs) {
tabs = Array.isArray(tabs) ? tabs : [tabs];
var result = null;
forEach(tabs, function(index, value) {
if(!result && sheetDAO.tabExists(value)) {
result = value;
}
});
return result;
}
this.tabName = whichTab(this.tabName);
/**
* Maps child relationships defined in the children intenrnal field
* by injecting a list of children in the feedItem.
*
* params:
* feedItem: The feed item to map
*/
function mapChildRelationships(feedItem) {
for(var i = 0; i < children.length; i++) {
var childConfig = children[i];
var childMap = {};
var feedProvider = new FeedProvider(childConfig.tabName).load();
var child = null;
while(child = feedProvider.next()) {
child[childConfig.relationshipField] = that.translateId(that.tabName, child, childConfig.relationshipField);
var key = child[childConfig.relationshipField];
if(!childMap[key]) {
childMap[key] = [];
}
childMap[key].push(child);
}
var key = feedItem[childConfig.relationshipField];
if(childMap[key]) {
feedItem[childConfig.listName] = childMap[key];
}
}
}
/**
* Pushes an item to an array if the item isn't present
*
* params:
* list: the array into which the item should be added
* item: value to be added to the array
*/
this.pushUnique = function(list, item) {
if (list.indexOf(item) === -1) {
list.push(item);
}
}
/**
* Returns if a given value is true regardless if it is a boolean or a string
* representation.
*
* params
* value: value to verify
*
* returns: true if the value represents true, or false otherwise
*/
this.isTrue = function(value) {
if(typeof(value) === 'string') {
return value.toLowerCase() === 'true';
} else {
return value === true;
}
}
/**
* Formats a date in the format CM requires
*
* params:
* feedItem: Bulkdozer feed item that contains the date
* fieldNam: the name of the date field
*
* returns: the formatted date value
*/
this.formatDate = function(feedItem, fieldName) {
var value = feedItem[fieldName];
if(typeof(value) == 'string') {
return Utilities.formatDate(new Date(value), 'GMT', 'yyyy-MM-dd');
} else if(value) {
return Utilities.formatDate(value, SpreadsheetApp.getActive().getSpreadsheetTimeZone(), 'yyyy-MM-dd');
} else {
return ''
}
}
/**
* Formats a date time in the format CM requires
*
* params:
* feedItem: Bulkdozer feed item that contains the date time
* fieldNam: the name of the date time field
*
* returns: the formatted date time value
*/
this.formatDateTime = function(feedItem, fieldName) {
var value = feedItem[fieldName];
if(value && typeof(value) == 'string') {
return value;
} else if(value) {
return Utilities.formatDate(value, SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "yyyy-MM-dd'T'HH:mm:ssZ");
} else {
return null;
}
}
/**
* Pre-fetches entities from CM using the list endpoint which can return
* several items, these items are then cached and when the process invokes the
* get() method the entity is returned from the cache dramatically reducing the
* number of calls made to the CM API.
*
* params:
* entity: name of the entity to pre fetch
* listName: list name of the API return
* filterName: name of the filter to pass to the API call
* filterValues: list of values to be used to filter entities in conjunction
* of the filterName
*/
this.preFetch = function(entity, listName, filterName, filterValues) {
// The CM API throws a 400 if too many items are specified in the
// filterValue, and therefore we use this chunk value to limit the number of
// filters per call
var chunk = 200;
if(filterName && filterValues && filterValues.length > 0) {
while(filterValues.length > 0) {
var searchOptions = {};
chunkFilterValues = filterValues.splice(0, chunk);
if(chunkFilterValues.length > 0) {
searchOptions[filterName] = chunkFilterValues;
cmDAO.list(entity, listName, searchOptions);
}
}
}
}
/**
* Performs pre-fetch of entities that are related to this one based on feed
* items, this causes entities to be cached reducing the number of API calls
* to CM
*
* params:
* entity: name of the entity to pre fetch
* listName: list name of the API return
* filterName: name of the filter to pass to the API call
* feedItems: list of feed items the entity
* fieldName: name of the field in the feedItem to get values for the filter
*/
this.preFetchFromFeed = function(entity, listName, filterName, feedProvider, fieldName) {
if(filterName && feedProvider && !feedProvider.isEmpty()) {
var filterValues = [];
var feedItem = null;
while(feedItem = feedProvider.next()) {
if(feedItem[fieldName] && filterValues.indexOf(feedItem[fieldName]) == -1 && typeof(feedItem[fieldName]) == 'number') {
filterValues.push(feedItem[fieldName]);
}
}
this.preFetch(entity, listName, filterName, filterValues);
}
}
/**
* Performs pre-fetch of entities that are related to this one, this causes
* other entities to be cached and reduce the number of API calls to CM
*
* params:
* entity: name of the entity to pre fetch
* listName: list name of the API return
* filterName: name of the filter to pass to the API call
* items: list of CM objects of the child entity
* fieldName: name of the field in the child entity from which to get values
* for the filter
*/
this.preFetchFromObjs = function(entity, listName, filterName, items, fieldName) {
if(filterName && items && items.length > 0) {
var filterValues = [];
for(var i = 0; i < items.length; i++) {
var item = items[i];
if(item[fieldName] && filterValues.indexOf(item[fieldName]) == -1) {
filterValues.push(item[fieldName]);
}
}
this.preFetch(entity, listName, filterName, filterValues);
}
}
/**
* Adds an item to the list of items only if it is unique. Uniquenes is
* determined by item.id
*
* params:
* job: the current job object
* entity: the name of the entity being processed
* item: the item to add
*/
this.add = function(job, entity, item) {
if (!job[entity]) {
job[entity] = [];
}
var items = job[entity];
for (var i = 0; i < items.length; i++) {
var current = items[i];
if (current.id == item.id) {
return;
}
}
job[entity].push(item);
};
/**
* Adds a log entry to the job logs
*
* params:
* job: the job object
* message: the log message to be added
*/
this.log = function(job, message) {
if(!job.logs) {
job.logs = [];
}
job.logs.push([new Date(), message]);
}
/**
* Based on the data in the feed, identify which items need to be loaded
*
* params:
* job: the job object
*/
this.identifyItemsToLoad = function(job) {
this.log(job, 'Identifying items to load: ' + this.label);
var feedProvider = new FeedProvider(this.tabName, this.keys).load();
var idsToLoad = [];
job.idsToLoad = idsToLoad;
idsToLoad[this.entity] = idsToLoad;
var item = null;
while(item = feedProvider.next()) {
if(item[this.idField]) {
var idString = new String(item[this.idField]).trim().toLowerCase();
if(idString && idString != 'null' && idString.toLowerCase().indexOf('ext') != 0 && idString.length > 0) {
this.pushUnique(idsToLoad, item[this.idField]);
}
}
}
}
/**
* Fetches items that need to be loaded from Campaign Manager based on the job
* specification. This defers to the processSearchOptions method in child
* classes to determine cascade items to load.
*
* This method can be overriden so child classes can fully control how to load
* items from CM, e.g. EventTags have a different list function API signature
* than other entities, and therefore needs to process the list with "gets"
*
* params:
* job: job specification
* job.idsToLoad: specific item ids to load
*
* returns: items loaded from Campaign Manager
*/
this.fetchItemsToLoad = function(job) {
var searchOptions = {};
var hasItemsToLoad = false;
if(job.idsToLoad && job.idsToLoad.length > 0) {
searchOptions['ids'] = job.idsToLoad;
hasItemsToLoad = true;
}
if(this.processSearchOptions) {
if(this.processSearchOptions(job, searchOptions)) {
hasItemsToLoad = true;
}
}
this.log(job, 'Fetching ' + this.label + ' from campaign manager');
var itemsToLoad = [];
if(hasItemsToLoad) {
itemsToLoad = cmDAO.list(that.entity, that.listField, searchOptions);
}
return itemsToLoad;
}
/**
* Performs load from CM to the sheet. This method will read data from
* Campaign Manager, transform it, and write to the respective tab in the
* feed. What controls this execution are fields overriden by child classes.
* This also calls "abstract" methods to delegate certain functionality such
* as identifying cascade items to load to child classes.
*
* params:
* job: object representing the load task to execute
* job.idsToLoad: represent the item ids to load specified in the sheet by
* the user
*/
this.load = function(job) {
console.log('Loading ' + this.label);
cmDAO.setCache(getCache('MEMORY'));
var itemsToLoad = this.fetchItemsToLoad(job);
if(itemsToLoad.length > 0 && job.preFetchConfigs && job.preFetchConfigs.length > 0) {
for(var i = 0; i < job.preFetchConfigs.length; i++) {
var preFetchConfig = job.preFetchConfigs[i];
this.preFetchFromObjs(preFetchConfig.entity, preFetchConfig.listName, preFetchConfig.filterName, itemsToLoad, preFetchConfig.fieldName);
}
}
// Map data from CM object to the feed
this.log(job, 'Mapping ' + this.label + ' to the feed');
var feed = [];
var loadedIds = [];
job.loadedIds = loadedIds;
if(this.mapFeed) {
for(var i = 0; i < itemsToLoad.length; i++) {
var item = itemsToLoad[i];
var mappedFeed = this.mapFeed(item);
if(mappedFeed) {
if(Array.isArray(mappedFeed)) {
for(var j = 0; j < mappedFeed.length; j++) {
feed.push(mappedFeed[j]);
}
} else {
feed.push(mappedFeed);
}
}
loadedIds.push(parseInt(item.id));
}
}
// Clear feed and write loaded items to the feed
var feedProvider = new FeedProvider(this.tabName, this.keys).setFeed(feed).save();
}
/**
* Create one push job per item in the sheet.
*
* params:
* job: the job object
*
* returns: this method communicates back throuh the job object by parsing the
* sheet of the tab of this instance into the job.jobs field. Fields include
* "entity" with the entity name, "feedItem" with the line from the sheet, and
* all references loaded identified in the pre-fetch configs defined in each
* loader.
*/
this.createPushJobs = function(job) {
var feedProvider = new FeedProvider(this.tabName, this.keys).load();
job.jobs = [];
// Add Creative Name + Creative ID configuration setting to control the feature in the frontend - Feature #1
job.configCreativeNameCreativeID = getCreativeNameCreativeIdFeatureConfig();
if(!feedProvider.isEmpty() && job.preFetchConfigs && job.preFetchConfigs.length > 0) {
for(var i = 0; i < job.preFetchConfigs.length; i++) {
var preFetchConfig = job.preFetchConfigs[i];
this.preFetchFromFeed(preFetchConfig.entity, preFetchConfig.listName, preFetchConfig.filterName, feedProvider, preFetchConfig.fieldName);
}
}
feedProvider.reset();
var feedItem = null;
while(feedItem = feedProvider.next(true)) {
var pushJob = {
'entity': job.entity,
'feedItem': feedItem
}
if(this.preparePushJob) {
this.preparePushJob(job, pushJob);
}
job.jobs.push(pushJob);
}
}
/**
* Assigns a value from the feed to a field in the campaign manager object.
* This handles checks to not update fields that are not required, which
* defaults to keeping the value in CM
*
* params:
* cmObj: Campaign Manager object to update
* cmField: Field to update in the Campaign Manger Object
* feedItem: Dictionary representing an entry in the bulkdozer feed
* required: true if the field is required (will always update), false if not
* required, will keep value from CM
* defaultValue: value to default to in case of null
*/
this.assign = function(cmObj, cmField, feedItem, feedField, required, defaultValue) {
if(required) {
cmObj[cmField] = feedItem[feedField] || defaultValue;
} else {
delete cmObj[cmField];
if(feedItem[feedField] || defaultValue) {
cmObj[cmField] = feedItem[feedField] || defaultValue;
}
}
}
/**
* Adds a reference to the entity, indicating a given field in the feed maps
* to another tab in the feed.
*
* params:
* tabName: The referenced tab
* field: the field in this entity's tab that references tabName
*/
this.addReference = function(tabName, field) {
var reference = {};
reference.tabName = tabName;
reference.field = field;
references.push(reference);
}
/**
* Adds a child relationship, which is automatically loaded into the feed as a
* sub list identified by the name of the list name.
*
* params:
* tabName: Name of the feed tab that contains the child records
* listName: Name of the field to be used to hold the list of child feedItems
* in the parent feedItem
* childRelationshipField: Field in the child feedItem that points back to
* the parent (akin to a foreign key).
*/
this.addChildRelationship = function(childTabName, childListName, childRelationshipField) {
childTabName = whichTab(childTabName);
children.push({
'tabName': childTabName,
'listName': childListName,
'relationshipField': childRelationshipField
});
}
/**
* Translates the ext id to a concrete id of a given field in the feed
*
* params:
* tabName: Tab name referenced by the relationship
* feedItem: feed item
* fieldName: name of the field that is a reference to an item in tabName
*
* returns: the translated id
*/
this.translateId = function(tabName, feedItem, fieldName) {
var idValue = feedItem[fieldName];
var translatedId = null;
tabName = whichTab([tabName, 'QA']);
if(String(idValue).indexOf('ext') == 0) {
translatedId = getIdStore().translate(tabName, idValue);
}
return translatedId || idValue;
}
/**
* Maps a feed to a CM object and updates CM
*
* params:
* job: the job object
* job.feedItem: feed item to map and push, it is updated with changes such
* as new ids
*/
this.push = function(job) {
if(job.feedItem.unkeyed) {
this.log(job, this.idField + ' is empty for ' + this.label + '. Skipping');
return;
}
cmDAO.setCache(getCache('SERVICE'));
var idValue = job.feedItem[this.idField];
try {
getIdStore().initialize(job.idMap);
var insert = true;
this.log(job, 'Processing ' + this.label + ': ' + idValue);
job.cmObject = {};
if(idValue && !String(idValue).indexOf('ext') == 0) {
job.cmObject = cmDAO.get(this.entity, idValue);
insert = false;
}
mapChildRelationships(job.feedItem);
for(var j = 0; j < references.length; j++) {
var reference = references[j];
job.feedItem[reference.field] = this.translateId(reference.tabName, job.feedItem, reference.field);
}
if(this.preProcessPush) {
this.preProcessPush(job);
}
// Map feed to object
this.processPush(job);
job.cmObject = cmDAO.update(this.entity, job.cmObject);
job.feedItem[this.idField] = job.cmObject.id;
// Store new ids
if(idValue && String(idValue).indexOf('ext') == 0) {
getIdStore().addId(this.tabName, idValue, job.cmObject.id);
}
if(this.postProcessPush) {
this.postProcessPush(job);
}
} catch(error) {
this.log(job, 'Error processing ' + this.label + ': ' + idValue);
this.log(job, 'Error Message: ' + error.message);
throw error;
}
}
/**
* Updates the feed with new values from the job
*
* params:
* job.feed: list of dictionaries to flatten and update the feed
*
* returns: job
*/
this.updateFeed = function(job) {
new FeedProvider(this.tabName, this.keys).setFeed(job.feed).save();
for(var i = 0; i < children.length; i++) {
var childConfig = children[i];
var childFeed = [];
for(var j = 0; j < job.feed.length; j++) {
feedItem = job.feed[j];
if(feedItem[childConfig.listName]) {
childFeed = childFeed.concat(feedItem[childConfig.listName]);
}
}
new FeedProvider(childConfig.tabName).setFeed(childFeed).save();
}
return job;
}
}
/**
* Advertiser Creative Loader
*/
var AdvertiserCreativeLoader = function(cmDAO) {
this.label = 'Advertiser Creative';
this.entity = 'AdvertiserCreative';
this.tabName = ['Advertiser Creative'];
this.idField = fields.creativeId;
this.listField = 'creatives';
BaseLoader.call(this, cmDAO);
this.addReference('Advertiser', fields.advertiserId);
/**
* Override this method since it has a different logic to identify
* items to load sending only specific advertiser-creative ids
* Based on the data in the feed, identify which items need to be loaded
*
* params:
* job: the job object
*/
this.identifyItemsToLoad = function(job) {
this.log(job, 'Identifying items to load: ' + this.label);
var feedProvider = new FeedProvider(this.tabName, this.keys).load();
var idsToLoad = [];
job.idsToLoad = idsToLoad;
idsToLoad[this.entity] = idsToLoad;
// Gather IDs from the feedProvider
var item = null;
while(item = feedProvider.next()) {
// Advertiser ID is required
if(item[fields.advertiserId]) {
let advertiserId = item[fields.advertiserId];
let creativeId = item[this.idField];
if(validId(advertiserId)) {
let id = `${advertiserId}-${creativeId}`;
this.pushUnique(idsToLoad, id);
}
}
}
}
/**
* Override this method since it has a different logic to fetch
* items to load sending only specific advertiser-creative ids
* @see BaseLoader.fetchItemsToLoad
*/
this.fetchItemsToLoad = function(job) {
console.log('FetchItemsToLoad in ' + this.label);
let advertisersMap = {};
let advertiserCreatives = [];
// If only advertiser id was provided, load all creatives under it
// If creative ids are provided, only load those specific ids
if(job.idsToLoad) {
for(let i = 0; i < job.idsToLoad.length; i++) {
// This is an advertiserId-creativeId combination
let uniqueId = job.idsToLoad[i];
let idParts = uniqueId.split('-');
if(idParts.length === 2) {
let advertiserId = idParts[0];
let creativeId = idParts[1];
if(!advertisersMap[advertiserId]) {
advertisersMap[advertiserId] = [];
}
// Check if creativeId was provided and not empty
if(creativeId) {
advertisersMap[advertiserId].push(creativeId);
}
}
}
for(advId in advertisersMap) {
let advertiserCreativesIds = advertisersMap[advId];
if(advertiserCreativesIds.length > 0) {
// Only load the provided creative ids under the advertiser
advertiserCreatives = cmDAO.list('Creatives', 'creatives', {
'advertiserId': advId,
'ids': advertiserCreativesIds
});
} else {
// No creative ids were provided, load all the creatives
// under the advertiser
advertiserCreatives = cmDAO.list('Creatives', 'creatives', {
'advertiserId': advId
});
}
}
}
return advertiserCreatives;
}
/**
* Turns a Campaign Manager Advertiser Creative object from the API into
* a feed item to be written to the sheet
*
* params:
* advertiserCreative: Advertiser Creative object returned from the Campaign Manager API
*
* returns: a feed item representing the advertiser creative to be written to the sheet
*/
this.mapFeed = function(advertiserCreative) {
var feedItem = {};
feedItem[fields.advertiserId] = advertiserCreative.advertiserId;
feedItem[fields.creativeName] = advertiserCreative.name;
feedItem[fields.creativeId] = advertiserCreative.id;
return feedItem;
};
function validId(idString) {
idString = idString.toString();
return idString && idString != 'null' && idString.toLowerCase().indexOf('ext') != 0 && idString.length > 0
}
}
AdvertiserCreativeLoader.prototype = Object.create(BaseLoader.prototype);
/**
* Campaign Loader
*/
var CampaignLoader = function(cmDAO) {
this.label = 'Campaign';
this.entity = 'Campaigns';
this.tabName = ['Campaign', 'QA'];
this.idField = fields.campaignId;
this.listField = 'campaigns';
BaseLoader.call(this, cmDAO);
this.addReference('Landing Page', fields.landingPageId);
/**
* @see LandingPageLoader
*/
this.processSearchOptions = function(job, searchOptions) {
result = false;
if(getUnarchivedOnlyFlag()) {
searchOptions['archived'] = false;
}
return result;
}
/**
* Turns a Campaign Manager Campaign object from the API into a feed item to
* be written to the sheet
*
* params:
* campaign: Campaign object returned from the Campaign Manager API
*
* returns: a feed item representing the campaign to be written to the sheet
*/
this.mapFeed = function(campaign) {
var landingPage =
cmDAO.get('AdvertiserLandingPages', campaign.defaultLandingPageId);
var feedItem = {};
feedItem[fields.campaignId] = campaign.id;
feedItem[fields.campaignName] = campaign.name;
feedItem[fields.advertiserId] = campaign.advertiserId;
feedItem[fields.landingPageId] = campaign.defaultLandingPageId;
feedItem[fields.landingPageName] = landingPage.name;
feedItem[fields.campaignStartDate] = campaign.startDate;
feedItem[fields.campaignEndDate] = campaign.endDate;
feedItem[fields.billingInvoiceCode] = campaign.billingInvoiceCode;
return feedItem;
};
/**
* This is called before an item is processed to allow an entity specific
* loader to perform pre processing tasks, such as formatting dates,
* validating fields, and changing data types.
*
* params:
* job: the push job
*/
this.preProcessPush = function(job) {
job.feedItem[fields.campaignStartDate] = this.formatDate(job.feedItem, fields.campaignStartDate);
job.feedItem[fields.campaignEndDate] = this.formatDate(job.feedItem, fields.campaignEndDate);
}
/**
* @see LandingPageLoader
*/
this.processPush = function(job) {
this.assign(job.cmObject, 'name', job.feedItem, fields.campaignName, true);
this.assign(job.cmObject, 'advertiserId', job.feedItem, fields.advertiserId, true);
this.assign(job.cmObject, 'defaultLandingPageId', job.feedItem, fields.landingPageId, true);
this.assign(job.cmObject, 'startDate', job.feedItem, fields.campaignStartDate, true);
this.assign(job.cmObject, 'endDate', job.feedItem, fields.campaignEndDate, true);
}
/**
* This is called after an item is processed to allow an entity specific
* loader to perform post processing tasks, such as updating informational
* fields. This method changes the job properties directly.
*
* params:
* job: The job being post processed
*/