-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauction-insights.js
More file actions
1382 lines (1181 loc) · 50.4 KB
/
auction-insights.js
File metadata and controls
1382 lines (1181 loc) · 50.4 KB
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
// ID: 49b262a518e68d401b6a69f62ddf5d05
/**
* Brainlabs Auctions Insights Report Generator
*
* This script will take data from an Auctions Insights reports and create reports
* and charts showing the changes over time for your your domain and selected
* competitors over time.
*
* Version: 3.0
* Google Apps Script maintained on brainlabsdigital.com
*/
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Information about the different columns of the Auctions Insights report
// (Will only be included if column names are given in English)
var subtitle = {};
subtitle['Impr. share'] = 'How often a participant received an impression, as a proportion of the auctions in which you were also competing.';
subtitle['Avg. position'] = 'The average position on the search results page for the participant’s ads when they received an impression.';
subtitle['Overlap rate'] = "How often another participant's ad received an impression when your ad also received an impression.";
subtitle['Position above rate'] = 'When you and another participant received an impression in the same auctions, % when participant’s ad was shown in a higher position.';
subtitle['Top of page rate'] = 'When a participant’s ads received impressions, how often it appeared at the top of the page above the search results.';
subtitle['Outranking share'] = "How often your ad ranked higher in the auction than another participant's ad, or your ad showed when theirs did not.";
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// The function to keep the prefills in the setting sheet up-to-date
function onEdit() {
// Find the sheets that give settings and data
var settingsSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Settings');
if (settingsSheet == null) {
return;
}
var totalSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Auction Insights');
var byDeviceSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Auction Insights By Device');
if (totalSheet != null) {
// Get the column names and copy to the settings sheet
var columnHeaders = getHeaders(totalSheet);
if (columnHeaders[0] != '') {
settingsSheet.getRange('ColumnNames').setValues([columnHeaders.concat(['', '', '', '', '', '']).slice(2, 8)]);
}
if (settingsSheet.getRange('competitorListAutoRefresh').getValue().toLowerCase() == 'yes') {
listCompetitors();
}
}
// Get the device names, and copy to the settings sheet
if (byDeviceSheet != null && byDeviceSheet.getLastRow() > 1) {
var columnHeaders = getHeaders(byDeviceSheet).map(function (a) {
return a.toLowerCase();
});
var deviceColumnName = settingsSheet.getRange('deviceColumnName').getValue().toLowerCase();
var deviceIndex = columnHeaders.indexOf(deviceColumnName);
if (deviceColumnName != '' && deviceIndex != -1) {
var deviceNames = [];
var deviceNamesInColumn = [];
var allDeviceNames = byDeviceSheet.getRange(3, deviceIndex + 1, 100, 1).getValues();
for (var d = 0; d < allDeviceNames.length; d++) {
if (allDeviceNames[d][0].toString() == '' || allDeviceNames[d][0].toString().toLowerCase() == deviceColumnName) {
continue;
}
if (deviceNames.indexOf(allDeviceNames[d][0]) == -1) {
deviceNames.push(allDeviceNames[d][0]);
deviceNamesInColumn.push([allDeviceNames[d][0]]);
}
Logger.log(allDeviceNames[d][0]);
if (deviceNamesInColumn.length >= 3) {
break;
}
}
Logger.log(deviceNamesInColumn);
settingsSheet.getRange('DeviceNames').setValues(deviceNamesInColumn.slice(0, 3));
}
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// This function takes the competitor names from the totals sheet,
// and lists them in the Settings sheet.
function listCompetitors() {
var settingsSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Settings');
var totalSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Auction Insights');
if (settingsSheet == null || totalSheet == null) {
return;
}
// Get the column names and copy to the settings sheet
var columnHeaders = getHeaders(totalSheet).map(function (a) {
return a.toLowerCase();
});
var displayDomainColumnName = settingsSheet.getRange('displayDomainColumnName').getValue();
var domainIndex = columnHeaders.indexOf(displayDomainColumnName.toLowerCase());
if (displayDomainColumnName != '' && domainIndex != -1) {
var namesInColumn = getCompetitorsByMaxImprShare(settingsSheet, totalSheet, domainIndex);
settingsSheet.getRange('CompetitorNames').setValues(namesInColumn);
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// This function removes any existing report sheets
function deleteReports() {
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
var nonReportSheetNames = ['Settings', 'Auction Insights', 'Auction Insights By Device', 'Performance Data'];
for (var i = 0; i < sheets.length; i++) {
if (nonReportSheetNames.indexOf(sheets[i].getName()) < 0) {
SpreadsheetApp.getActiveSpreadsheet().deleteSheet(sheets[i]);
}
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// This function goes through the Settings sheet to find the reports to make,
// and makes them
function generateReports() {
// Find the sheets that give settings and data
var sheetNames = ['Settings', 'Auction Insights', 'Auction Insights By Device', 'Performance Data'];
var sheet = {};
for (var i = 0; i < sheetNames.length; i++) {
sheet[sheetNames[i]] = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetNames[i]);
if (sheet[sheetNames[i]] == null) {
Browser.msgBox('The ' + sheetNames[i] + ' sheet could not be found. Please check you have not deleted or renamed it.');
return;
}
}
var youName = sheet.Settings.getRange('youName').getValue();
var dateName = sheet.Settings.getRange('dateColumnName').getValue();
var domainName = sheet.Settings.getRange('displayDomainColumnName').getValue();
if (youName == '') {
Browser.msgBox('You name is blank. Please make sure you have entered the name that the report uses when giving your performance.');
return;
}
if (dateName == '') {
Browser.msgBox('Date column name is blank. Please make sure you have entered a name for the date column.');
return;
}
if (domainName == '') {
Browser.msgBox('Display URL Domain column name is blank. Please make sure you have entered a name for the Display URL Domain column.');
return;
}
// Get a list of competitors
var allCompetitorNames = sheet.Settings.getRange('CompetitorNames').getValues();
var competitorNameSelection = sheet.Settings.getRange('CompetitorNameSelection').getValues();
var competitors = [];
var orderedCompetitors = {};
for (var i = 0; i < allCompetitorNames.length; i++) {
if (competitorNameSelection[i][0] != '' && allCompetitorNames[i][0] != '') {
competitors.push(allCompetitorNames[i][0]);
if (!isNaN(competitorNameSelection[i][0])) {
orderedCompetitors[allCompetitorNames[i][0]] = competitorNameSelection[i][0];
}
}
}
var includeAllCompetitors = sheet.Settings.getRange('includeAllCompetitors').getValue().toLowerCase();
if (includeAllCompetitors == 'yes') {
competitors = getAllCompetitors(sheet['Auction Insights'], youName, domainName);
}
// Get list of stats
var statsToReport = [];
var statsInChart = [];
var statsToReportTable = sheet.Settings.getRange('StatsToReport').getValues();
for (var i = 0; i < statsToReportTable.length; i++) {
if (statsToReportTable[i][1].toLowerCase() == 'yes') {
statsToReport.push(statsToReportTable[i][0]);
}
if (statsToReportTable[i][2].toLowerCase() == 'yes' && statsInChart.length < 2) {
statsInChart.push(statsToReportTable[i][0]);
if (statsToReportTable[i][1].toLowerCase() != 'yes') {
statsToReport.push(statsToReportTable[i][0]);
}
}
}
if (statsToReport.length > 0) {
var statsReadable = sheet['Performance Data'].getLastColumn() > 0;
if (statsReadable) {
var statNames = [];
statNames.Clicks = sheet.Settings.getRange('clicksColumnName').getValue();
statNames.Impressions = sheet.Settings.getRange('impressionsColumnName').getValue();
statNames.Cost = sheet.Settings.getRange('costColumnName').getValue();
for (var statName in statNames) {
if (statNames[statName] == '') {
Browser.msgBox(statName + ' column name is blank. Please make sure you have entered a name for the ' + statName.toLowerCase() + ' column if you want stats to be reported.');
statsReadable = false;
break;
}
}
}
if (statsReadable) {
var statHeaders = getHeaders(sheet['Performance Data']).map(function (a) {
return a.toLowerCase();
});
var nonBlankHeaders = statHeaders.filter(function (a) {
return a != '';
});
if (nonBlankHeaders.length == 0) {
Browser.msgBox("No headers found in the 'Performance Data' sheet. Please make sure you have copied in your data if you want stats to be reported.");
statsReadable = false;
}
}
if (statsReadable) {
if (statHeaders.indexOf(statNames.Impressions.toLowerCase()) < 0
&& statHeaders.indexOf('impr.') >= 0) {
statNames.Impressions = 'impr.';
}
for (var statName in statNames) {
if (statHeaders.indexOf(statNames[statName].toLowerCase()) < 0) {
if (statName == 'Impressions' && getStatColumnIndex(sheet.Settings, statHeaders, 'impressionsColumnName') >= 0) {
continue;
} else if (statName == 'Clicks' && getStatColumnIndex(sheet.Settings, statHeaders, 'clicksColumnName') >= 0) {
continue;
}
Browser.msgBox('Could not find the ' + statName.toLowerCase() + " column '" + statNames[statName] + "'. Please check it is typed correctly if you want stats to be reported.");
statsReadable = false;
break;
}
}
}
if (!statsReadable) {
statsToReport = [];
statsInChart = [];
}
}
var deviceNames = sheet.Settings.getRange('DeviceNames').getValues();
var columnNames = sheet.Settings.getRange('ColumnNames').getValues()[0];
var reportsToBeMadeTable = sheet.Settings.getRange('ReportsToMake').getValues();
var reportCount = 0;
// Reports for 'Total'
var totalSheetChecked = false;
for (var j = 0; j < columnNames.length; j++) {
if (reportsToBeMadeTable[0][j].toLowerCase() == 'yes' && columnNames[j] != '') {
reportCount++;
if (!totalSheetChecked) {
var totalSheetFilledIn = checkSheetIsFilledIn(sheet.Settings, sheet['Auction Insights'], 'Auction Insights', dateName, domainName, youName);
if (totalSheetFilledIn) {
totalSheetChecked = true;
} else {
totalSheetChecked = null;
break;
}
}
makeReport(columnNames[j], 'Total', competitors, orderedCompetitors, statsToReport, statsInChart);
}
}
// Reports for each device
var deviceSheetChecked = false;
for (var i = 0; i < deviceNames.length; i++) {
for (var j = 0; j < columnNames.length; j++) {
if (reportsToBeMadeTable[i + 1][j].toLowerCase() == 'yes' && columnNames[j] != '') {
reportCount++;
if (!deviceSheetChecked) {
var deviceSheetFilledIn = checkSheetIsFilledIn(sheet.Settings, sheet['Auction Insights By Device'], 'Auction Insights By Device', dateName, domainName, youName);
if (deviceSheetFilledIn) {
deviceSheetChecked = true;
} else {
deviceSheetChecked = null;
break;
}
}
makeReport(columnNames[j], deviceNames[i][0], competitors, orderedCompetitors, statsToReport, statsInChart);
}
}
}
if (totalSheetChecked == null || deviceSheetChecked == null) {
return;
}
// 'Compare All Devices' reports
for (var j = 0; j < columnNames.length; j++) {
if (reportsToBeMadeTable[4][j].toLowerCase() == 'yes' && columnNames[j] != '') {
reportCount++;
if (!totalSheetChecked) {
var totalSheetFilledIn = checkSheetIsFilledIn(sheet.Settings, sheet['Auction Insights'], 'Auction Insights', dateName, domainName, youName);
if (totalSheetFilledIn) {
totalSheetChecked = true;
} else {
break;
}
}
if (!deviceSheetChecked) {
var deviceSheetFilledIn = checkSheetIsFilledIn(sheet.Settings, sheet['Auction Insights By Device'], 'Auction Insights By Device', dateName, domainName, youName);
if (deviceSheetFilledIn) {
deviceSheetChecked = true;
} else {
break;
}
}
makeAllDeviceReport(columnNames[j], statsToReport, statsInChart);
}
}
if (reportCount == 0) {
Browser.msgBox('No reports requested to be made.');
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// The function to make reports comparing domains for a particular column header
// 'device' is a string indicating which device the report is for
// 'competitors' is an array of competitor names to include
// 'statsToReport' is an array of the stats to add to the data table
// 'statsInChart' is an array of the stats to add to the chart
function makeReport(columnHeader, device, competitors, orderedCompetitors, statsToReport, statsInChart) {
var displayColumnHeader = getDisplayName(columnHeader);
var displayDevice = getDisplayName(device);
// If the report's sheet exists, delete it
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(displayColumnHeader + ' - ' + displayDevice);
if (sheet != null) {
SpreadsheetApp.getActiveSpreadsheet().deleteSheet(sheet);
}
// Create a new sheet for the report
var sheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet(displayColumnHeader + ' - ' + displayDevice);
// Get the existing sheets for the settings and data
var settingsSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Settings');
var performanceSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Performance Data');
if (device == 'Total') {
var dataSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Auction Insights');
} else {
var dataSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Auction Insights By Device');
}
var youName = settingsSheet.getRange('youName').getValue();
var youNameLowerCase = youName.toLowerCase();
var data = getDataByDate(settingsSheet, dataSheet, columnHeader, device, competitors, youNameLowerCase, false);
var dates = data.dates;
var domains = data.data;
var domainNames = data.domainNames;
if (statsToReport.indexOf('Searches') != -1) {
var allColumnHeaders = settingsSheet.getRange('ColumnNames').getValues()[0];
var imprShareName = allColumnHeaders[0];
var imprShareData = getDataByDate(settingsSheet, dataSheet, imprShareName, device, [], youNameLowerCase, false).data;
} else {
var imprShareData = {};
}
var statData = getStatByDate(settingsSheet, performanceSheet, statsToReport, device);
// Get the total impressions, cost and clicks to calculate CPC, etc
dates.sort();
// Sorts the dates alphabetically - as they're in bigendian format, this means they are sorted oldest to newest
domainNames.sort(compareDomainNames);
// Sorts the domain names by their highest impression share, using the function below
function compareDomainNames(a, b) {
// user defined ordering has priority
var aHasOrder = orderedCompetitors[a] != undefined;
var bHasOrder = orderedCompetitors[b] != undefined;
if (aHasOrder && !bHasOrder) {
return -1;
} if (!aHasOrder && bHasOrder) {
return 1;
} if (aHasOrder && bHasOrder) {
return orderedCompetitors[a] - orderedCompetitors[b];
}
// otherwise use max impression share
var aIsString = typeof (domains[a]['Max Impr Share']) === 'string';
var bIsString = typeof (domains[b]['Max Impr Share']) === 'string';
if (aIsString && !bIsString) {
return 1;
} if (!aIsString && bIsString) {
return -1;
} if (!aIsString && !bIsString && domains[a]['Max Impr Share'] != domains[b]['Max Impr Share']) {
// If the max impression shares are different, the domain with the highest is put first
return domains[b]['Max Impr Share'] - domains[a]['Max Impr Share'];
}
// If both domains have the same max impression share, the one with data for the most dates is put first
return Object.keys(domains[b]).length - Object.keys(domains[a]).length;
}
var includeYou = false;
for (var i = 0; i < dates.length; i++) {
if (domains[youNameLowerCase] != undefined && domains[youNameLowerCase][dates[i]] != undefined && domains[youNameLowerCase][dates[i]] != '--') {
includeYou = true;
break;
}
}
domainNames.splice(domainNames.indexOf(youNameLowerCase), 1);
// Removes "You" from the array
if (includeYou) {
// If this graph is supposed to include 'You', then it's added to the start of the array
domainNames.unshift(youName);
}
// The first row of the report sheet is the column name
if (device == 'Total') {
sheet.getRange('A1').setValue(displayColumnHeader);
} else {
sheet.getRange('A1').setValue(displayColumnHeader + ' - ' + displayDevice);
}
sheet.getRange('A1').setFontWeight('bold');
// Check there is data
if (!includeYou && competitors.length == 0) {
sheet.getRange('A2').setValue('No competitors are selected, so there is no data to show.');
Browser.msgBox("No competitors are selected, so there is no data to show in the '" + displayColumnHeader + ' - ' + displayDevice + "' report.");
return;
}
if (domainNames.length == 0) {
sheet.getRange('A2').setValue('No data was found for this report.');
return;
}
// The second row of the report sheet is the headings
var outputHeaders = ['Date'];
for (var i = 0; i < statsToReport.length; i++) {
outputHeaders.push(getDisplayName(statsToReport[i]));
}
for (var d = 0; d < domainNames.length; d++) {
outputHeaders.push(getDisplayName(domainNames[d]));
}
sheet.getRange(2, 1, 1, outputHeaders.length).setValues([outputHeaders]);
sheet.getRange(2, 1, 1, outputHeaders.length).setFontWeight('bold');
// 'output' is a multi-dimensional array that will become the rest of the cells in the spreadsheet
var output = [];
// We loop though the dates to make their lines of output
// (the date, the CPC, then each domain's metric)
for (var i = 0; i < dates.length; i++) {
output[i] = [stringToDate(dates[i])];
for (var j = 0; j < statsToReport.length; j++) {
output[i].push(calculateStat(statsToReport[j], statData, dates[i], imprShareData[youNameLowerCase]));
}
for (var d = 0; d < domainNames.length; d++) {
if (domains[domainNames[d].toLowerCase()][dates[i]] === undefined || domains[domainNames[d].toLowerCase()][dates[i]] === '--') {
if (columnHeader.toLowerCase() == 'avg. position') {
output[i].push('');
} else {
output[i].push(0);
}
} else {
output[i].push(domains[domainNames[d].toLowerCase()][dates[i]]);
}
}
}
// Write the data to the sheet
sheet.getRange(3, 1, output.length, output[0].length).setValues(output);
// Format the tables
var dateFormat = settingsSheet.getRange('dateFormat').getValue();
var currencySymbol = settingsSheet.getRange('currencySymbol').getValue();
for (var i = 0; i < outputHeaders.length; i++) {
if (outputHeaders[i] == 'Date') {
sheet.getRange(3, i + 1, output.length).setNumberFormat(dateFormat);
} else if (outputHeaders[i] == 'CPC') {
sheet.getRange(3, i + 1, output.length).setNumberFormat(currencySymbol + '0.00');
} else if (outputHeaders[i] == 'Impressions' || outputHeaders[i] == 'Searches') {
sheet.getRange(3, i + 1, output.length).setNumberFormat('#,###,##0');
} else if (outputHeaders[i].substr(-3) == 'CTR') {
sheet.getRange(3, i + 1, output.length).setNumberFormat('0.00%');
} else if (columnHeader == 'Avg. position' || sheet.getRange(4, i + 1).getValue() >= 1) {
// average position is not a percentage
sheet.getRange(3, i + 1, output.length).setNumberFormat('0.0');
} else {
sheet.getRange(3, i + 1, output.length).setNumberFormat('0.00%');
}
}
// Centralise the data
sheet.getRange(2, 1, output.length + 1, output[0].length).setHorizontalAlignment('center');
// Make the chart
// Get the width in pixels for the chart, so the chart is 11 columns wide
var width = 0;
for (var i = 1; i < 12; i++) {
width += sheet.getColumnWidth(i);
}
// Remove stat columns if there's no impressions, as that suggests there's
// a problem with the data (and the graph will be flat anyway)
if (statData.zeroImpressions) {
statsInChart = [];
}
// Creates the chart
var chartTitle = displayColumnHeader;
if (typeof subtitle[columnHeader] !== 'undefined') {
chartTitle = displayColumnHeader + ' - ' + subtitle[columnHeader];
}
var chartBuilder = sheet.newChart()
.setChartType(Charts.ChartType.LINE)
.setOption('chartArea', {
left: '10%',
top: '15%',
width: '80%',
height: '70%'
})
.setPosition(4 + output.length, 1, 0, 0)
.setOption('width', width)
.setOption('height', 500)
.setOption('title', chartTitle)
.setOption('legend', {
position: 'top'
});
var statFormat = {
CPC: 'currency',
CTR: 'percent',
Impressions: 'decimal',
Searches: 'decimal'
};
if (statsInChart.length == 0) {
chartBuilder.setOption('vAxes', {
// Adds titles to the axis.
0: {
title: displayColumnHeader
}
});
} else if (statsInChart.length == 1) {
chartBuilder.setOption('vAxes', {
// Adds titles to both axes.
0: {
title: displayColumnHeader
},
1: {
title: statsInChart[0],
format: statFormat[statsInChart[0]]
}
});
} else {
chartBuilder.setOption('vAxes', {
// Adds title to the first axis, blanks the others.
0: {
title: displayColumnHeader
},
1: {
format: statFormat[statsInChart[0]],
textPosition: 'in'
},
2: {
format: statFormat[statsInChart[1]],
textPosition: 'out'
},
3: {
textStyle: {
color: 'white'
}
}
});
}
var seriesOptions = [];
var statColours = ['#999999', '#a2c4c9']; // grey, grey-blue
var statDashStyles = [
[10, 5],
[3, 3]
]; // dashed, dotted
var regularColours = ['#3366cc', '#dc3912', '#ff9900', '#109618', '#994499', '#ea9999']; // blue, red, yellow, green, purple, pink
chartBuilder.addRange(sheet.getRange(2, 1, output.length + 1, 1)); // Date
for (var j = 0; j < statsToReport.length; j++) {
var statIndex = statsInChart.indexOf(statsToReport[j]);
if (statIndex != -1) {
chartBuilder.addRange(sheet.getRange(2, j + 2, output.length + 1, 1));
seriesOptions.push({
targetAxisIndex: statIndex + 1,
lineDashStyle: statDashStyles[statIndex],
color: statColours[statIndex]
});
}
}
if (domainNames.length < regularColours.length) {
var numberOfColumns = domainNames.length;
} else {
var numberOfColumns = regularColours.length;
}
if (includeYou) {
numberOfColumns++;
}
chartBuilder.addRange(sheet.getRange(2, statsToReport.length + 2, output.length + 1, numberOfColumns)); // You and Competitors
if (includeYou) {
// Format the 'You' line to be black and thicker
seriesOptions.push({
targetAxisIndex: 0,
color: '#000000',
lineWidth: 4
});
}
// Format the competitor lines
for (var i = 0; i < output[0].length - statsToReport.length - 2 && i < regularColours.length; i++) {
seriesOptions.push({
targetAxisIndex: 0,
color: regularColours[i]
});
}
chartBuilder.setOption('series', seriesOptions);
var chart = chartBuilder.build();
sheet.insertChart(chart);
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// The function to make reports comparing your performance on different devices for
// a particular column header
function makeAllDeviceReport(columnHeader, statsToReport, statsInChart) {
var displayColumnHeader = getDisplayName(columnHeader);
// If the report's sheet exists, delete it
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(displayColumnHeader + ' - All Devices');
if (sheet != null) {
SpreadsheetApp.getActiveSpreadsheet().deleteSheet(sheet);
}
// Create a new sheet for the report
var sheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet(displayColumnHeader + ' - All Devices');
// Find the sheets that give settings and data
var settingsSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Settings');
var totalSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Auction Insights');
var byDeviceSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Auction Insights By Device');
var performanceSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Performance Data');
var youName = settingsSheet.getRange('youName').getValue();
var youNameLowerCase = youName.toLowerCase();
var totalData = getDataByDate(settingsSheet, totalSheet, columnHeader, 'Total', [], youNameLowerCase, false);
var deviceData = getDataByDate(settingsSheet, byDeviceSheet, columnHeader, 'Total', [], youNameLowerCase, true);
var dates = totalData.dates;
for (var i = 0; i < deviceData.dates.length; i++) {
if (dates.indexOf(deviceData.dates[i]) == -1) {
dates.push(deviceData.dates[i]);
}
}
// Get the other stats from the performance sheet
var totalStats = getStatByDate(settingsSheet, performanceSheet, statsToReport, 'Total');
var deviceStats = {};
for (var d = 0; d < deviceData.domainNames.length && d < 6; d++) {
deviceStats[deviceData.domainNames[d]] = getStatByDate(settingsSheet, performanceSheet, statsToReport, deviceData.domainNames[d]);
}
if (statsToReport.indexOf('Searches') != -1) {
var totalImprShare = getDataByDate(settingsSheet, totalSheet, 'Impr. share', 'Total', [], youNameLowerCase, false).data;
var deviceImprShare = getDataByDate(settingsSheet, byDeviceSheet, 'Impr. share', 'Total', [], youNameLowerCase, true).data;
} else {
var deviceImprShare = {};
var totalImprShare = {};
}
dates.sort();
// Sorts the dates alphabetically - as they're in bigendian format, this means they are sorted oldest to newest
var deviceDisplayNames = [];
for (var d = 0; d < deviceData.domainNames.length; d++) {
deviceDisplayNames[d] = getDisplayName(deviceData.domainNames[d]);
}
var statDisplayNames = [];
for (var i = 0; i < statsToReport.length; i++) {
statDisplayNames[i] = getDisplayName(statsToReport[i]);
}
// The first row of the report sheet is the report name
sheet.getRange('A1').setValue(displayColumnHeader + ' - All Devices');
sheet.getRange('A1').setFontWeight('bold');
// The second row of the report sheet is the headings
var outputHeaders = ['Date'];
for (var i = 0; i < statDisplayNames.length; i++) {
outputHeaders.push('Total ' + statDisplayNames[i]);
for (var d = 0; d < deviceDisplayNames.length; d++) {
outputHeaders.push(deviceDisplayNames[d] + ' ' + statDisplayNames[i]);
}
}
outputHeaders.push('Total ' + columnHeader);
for (var d = 0; d < deviceDisplayNames.length; d++) {
outputHeaders.push(deviceDisplayNames[d] + ' ' + displayColumnHeader);
}
sheet.getRange(2, 1, 1, outputHeaders.length).setValues([outputHeaders]);
sheet.getRange(2, 1, 1, outputHeaders.length).setFontWeight('bold');
// 'output' is a multi-dimensional array that will become the rest of the cells in the spreadsheet
var output = [];
// We loop though the dates to make their lines of output
for (var i = 0; i < dates.length; i++) {
output[i] = [stringToDate(dates[i])];
for (var j = 0; j < statsToReport.length; j++) {
output[i].push(calculateStat(statsToReport[j], totalStats, dates[i], totalImprShare[youNameLowerCase]));
for (var d = 0; d < deviceData.domainNames.length; d++) {
output[i].push(calculateStat(statsToReport[j], deviceStats[deviceData.domainNames[d]], dates[i], deviceImprShare[deviceData.domainNames[d]]));
}
}
if (totalData.data[youNameLowerCase][dates[i]] === undefined || totalData.data[youNameLowerCase][dates[i]] == '--') {
if (columnHeader.toLowerCase() == 'avg. position') {
output[i].push('');
} else {
output[i].push(0);
}
} else {
output[i].push(totalData.data[youNameLowerCase][dates[i]]);
}
for (var d = 0; d < deviceData.domainNames.length; d++) {
if (deviceData.data[deviceData.domainNames[d]][dates[i]] === undefined || deviceData.data[deviceData.domainNames[d]][dates[i]] === '--') {
if (columnHeader.toLowerCase() == 'avg. position') {
output[i].push('');
} else {
output[i].push(0);
}
} else {
output[i].push(deviceData.data[deviceData.domainNames[d]][dates[i]]);
}
}
}
// Write the data to the sheet
sheet.getRange(3, 1, output.length, output[0].length).setValues(output);
// Format the tables
var dateFormat = settingsSheet.getRange('dateFormat').getValue();
var currencySymbol = settingsSheet.getRange('currencySymbol').getValue();
for (var i = 0; i < outputHeaders.length; i++) {
if (outputHeaders[i] == 'Date') {
sheet.getRange(3, i + 1, output.length).setNumberFormat(dateFormat);
} else if (outputHeaders[i].substr(-3) == 'CPC') {
sheet.getRange(3, i + 1, output.length).setNumberFormat(currencySymbol + '0.00');
} else if (outputHeaders[i].substr(-11) == 'Impressions' || outputHeaders[i].substr(-11) == 'Impr.' || outputHeaders[i].substr(-8) == 'Searches') {
sheet.getRange(3, i + 1, output.length).setNumberFormat('#,###,##0');
} else if (outputHeaders[i].substr(-3) == 'CTR') {
sheet.getRange(3, i + 1, output.length).setNumberFormat('0.00%');
} else if (columnHeader == 'Avg. position' || sheet.getRange(4, i + 1).getValue() >= 1) {
// must be average position
sheet.getRange(3, i + 1, output.length).setNumberFormat('0.0');
} else {
sheet.getRange(3, i + 1, output.length).setNumberFormat('0.00%');
}
}
// Centralise the data
sheet.getRange(3, 1, output.length, output[0].length).setHorizontalAlignment('center');
// Make the chart
// Get the width in pixels for the chart, so the chart is 11 columns wide
var width = 0;
for (var i = 1; i < 12; i++) {
width += sheet.getColumnWidth(i);
}
// Remove stat columns if there's no impressions, as that suggests there's
// a problem with the data (and the graph will be flat anyway)
if (totalStats.zeroImpressions) {
statsInChart = [];
}
// Creates the chart
var chartTitle = displayColumnHeader;
if (typeof subtitle[columnHeader] !== 'undefined') {
chartTitle = chartTitle + ' - ' + subtitle[columnHeader];
}
var chartBuilder = sheet.newChart()
.setChartType(Charts.ChartType.LINE)
.setOption('chartArea', {
left: '10%',
top: '15%',
width: '80%',
height: '70%'
})
.setPosition(4 + output.length, 1, 0, 0)
.setOption('width', width)
.setOption('height', 500)
.setOption('title', chartTitle)
.setOption('legend', {
position: 'top'
});
var statFormat = {
CPC: 'currency',
CTR: 'percentage',
Impressions: 'decimal',
Searches: 'decimal'
};
if (statsInChart.length == 0) {
chartBuilder.setOption('vAxes', {
// Adds titles to the axis.
0: {
title: displayColumnHeader
}
});
} else if (statsInChart.length == 1) {
chartBuilder.setOption('vAxes', {
// Adds titles to both axes.
0: {
title: displayColumnHeader
},
1: {
title: statDisplayNames[0],
format: statFormat[statsInChart[0]]
}
});
} else {
chartBuilder.setOption('vAxes', {
// Adds title to the first axis, blanks the others.
0: {
title: displayColumnHeader
},
1: {
textStyle: {
color: 'white'
}
},
2: {
title: statDisplayNames[1],
format: statFormat[statsInChart[1]]
},
3: {
textStyle: {
color: 'white'
}
}
});
}
var seriesOptions = [];
var colours = [];
colours.push(['#3366cc', '#dc3912', '#ff9900', '#109618']); // blue, red, yellow, green
colours.push(['#9fc5e8', '#ea9999', '#f9cb9c', '#b6d7a8']);
var lineDashStyles = [];
lineDashStyles.push([10, 5]);
lineDashStyles.push([3, 3]);
chartBuilder.addRange(sheet.getRange(2, 1, output.length + 1, 1)); // Date
for (var j = 0; j < statsToReport.length; j++) {
var statIndex = statsInChart.indexOf(statsToReport[j]);
if (statIndex != -1) {
chartBuilder.addRange(sheet.getRange(2, (4 * j) + 2, output.length + 1, 4));
for (var x = 0; x < 4; x++) {
seriesOptions.push({
targetAxisIndex: statIndex + 1,
lineDashStyle: lineDashStyles[statIndex],
color: colours[statIndex][x]
});
}
}
}
chartBuilder.addRange(sheet.getRange(2, (4 * statsToReport.length) + 2, output.length + 1, 4));
for (var x = 0; x < 4; x++) {
seriesOptions.push({
targetAxisIndex: 0,
color: colours[0][x]
});
}
chartBuilder.setOption('series', seriesOptions);
var chart = chartBuilder.build();
sheet.insertChart(chart);
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// The function calculates a stat, or returns 0 if there is no data or that stat would
// involve dividing by zero
function calculateStat(stat, statData, date, imprShareData) {
switch (stat) {
case 'CPC':
if (statData.cost[date] == undefined || statData.clicks[date] == undefined || statData.clicks[date] == 0) {
return 0;
}
return statData.cost[date] / statData.clicks[date];
break;
case 'CTR':
if (statData.impr[date] == undefined || statData.clicks[date] == undefined || statData.impr[date] == 0) {
return 0;
}
return statData.clicks[date] / statData.impr[date];
break;
case 'Impressions':
if (statData.impr[date] == undefined) {
return 0;
}
return statData.impr[date];
break;
case 'Searches':
if (statData.impr[date] == undefined || imprShareData[date] == undefined || imprShareData[date] == 0) {
return 0;
}
return statData.impr[date] / imprShareData[date];
break;
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// The function to take the data from the data sheet organised by date and by domain
// name or (if recordDeviceAsDomain is true) by device
function getDataByDate(settingsSheet, dataSheet, columnHeader, device, competitors, youName, recordDeviceAsDomain) {
// Dates are stored as bigendian date strings, then converted back to dates at the end
var bigendianDate = 'yyyy-MM-dd';
// The timezone is used to convert them back
var timezone = SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone();
var domains = {};
var dates = [];
var domainNames = [];
// Headers are made lowercase so that the column headers can be case insensitive
var headers = getHeaders(dataSheet).map(function (a) {
return a.toLowerCase();
});
var dateIndex = headers.indexOf(settingsSheet.getRange('dateColumnName').getValue().toLowerCase());
var domainIndex = headers.indexOf(settingsSheet.getRange('displayDomainColumnName').getValue().toLowerCase());
var deviceIndex = headers.indexOf(settingsSheet.getRange('deviceColumnName').getValue().toLowerCase());
var under10Percent = settingsSheet.getRange('under10Percent').getValue();
if (settingsSheet.getRange('deviceColumnName') == '' || deviceIndex == -1) {
// If there is no device column, the impression share column is 2
var imprShareIndex = 2;
} else {
// If there *is* a device column, then the impr share column is bumped up to 3
var imprShareIndex = 3;
}
if (columnHeader == 'Impr. share') {
var columnIndex = imprShareIndex;
} else {
var columnIndex = headers.indexOf(columnHeader.toLowerCase());
// The index of the required stat
}
var dataTable = dataSheet.getRange(2, 1, dataSheet.getLastRow(), dataSheet.getLastColumn()).getValues();
if (dataTable[0][0].toString().toLowerCase() == headers[0]) {
// First row of data is the headers and can be removed
dataTable.shift();
}
// First we record the stats for each domain, by month
// and record each domain's highest impression share
for (var i = 0; i < dataTable.length; i++) {
// auditInsights is a multi-dimensional array containing the values of the auditInsights cells.
// So auditInsights[i] is a row on the Auction Insights report
// The loop starts at 2 as auditInsights[0] is the title and auditInsights[1] is the headers.
var date = dataTable[i][dateIndex];
if (!date) {
// If the date field is blank, there isn't data on this row
continue;
}