-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaccount-grader.js
More file actions
7826 lines (6727 loc) · 296 KB
/
account-grader.js
File metadata and controls
7826 lines (6727 loc) · 296 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
/**
* Debug function to log the structure of an object
* @param {Object} obj The object to log
* @param {string} label A label for the log
* @param {number} depth The maximum depth to log (default: 2)
*/
function debugObject(obj, label = 'Object', depth = 2) {
try {
const seen = new Set();
const stringifyWithDepth = (obj, currentDepth = 0) => {
if (currentDepth > depth) return '[Max Depth Reached]';
if (obj === null) return 'null';
if (obj === undefined) return 'undefined';
if (typeof obj !== 'object') return String(obj);
if (seen.has(obj)) return '[Circular Reference]';
seen.add(obj);
if (Array.isArray(obj)) {
const items = obj.map(item => stringifyWithDepth(item, currentDepth + 1));
return '[' + items.join(', ') + ']';
}
const entries = Object.entries(obj).map(([key, value]) => {
return key + ': ' + stringifyWithDepth(value, currentDepth + 1);
});
return '{' + entries.join(', ') + '}';
};
Logger.log(label + ': ' + stringifyWithDepth(obj));
} catch (e) {
Logger.log('Error in debugObject: ' + e.message);
}
}
/**
* Google Ads Account Grader
*
* This script performs a comprehensive analysis of your Google Ads account,
* evaluating performance across 10 key categories of PPC best practices:
* - Campaign Organization
* - Conversion Tracking
* - Keyword Strategy
* - Negative Keywords
* - Bidding Strategy
* - Ad Creative & Extensions
* - Quality Score
* - Audience Strategy
* - Landing Page Optimization
* - Competitive Analysis
*
* Each category is scored on a 0-100% scale with detailed metrics and formulas,
* and assigned a letter grade (A-F). The script provides actionable recommendations
* prioritized by potential impact.
*
* @version 2.0
*/
// Configuration
const CONFIG = {
// Date range for data collection
dateRange: {
// Set to true to use custom date range, false to use lookback period
useCustomDateRange: true,
// Custom date range (only used if useCustomDateRange is true)
// Format: YYYYMMDD (e.g., 20220701 for July 1, 2022)
customStartDate: "20220715", // July 1, 2022
customEndDate: "20220915", // August 28, 2022
// Lookback period in days (only used if useCustomDateRange is false)
lookbackDays: 30
},
// Email settings
email: {
sendEmail: true,
sendReport: true,
sendErrorNotifications: true,
emailAddress: 'testing-aaaaps4alpegluwh74tgzcehfa@letstalkdigit-sp51764.slack.com',
errorRecipients: ['testing-aaaaps4alpegluwh74tgzcehfa@letstalkdigit-sp51764.slack.com'],
includeSpreadsheetLink: true
},
// Spreadsheet settings
spreadsheet: {
createNew: true,
existingSpreadsheetUrl: '', // Only used if createNew is false
includeRawData: false // Whether to include raw data sheets
},
// Thresholds for letter grades
gradeThresholds: {
A: 90, // 90-100%
B: 80, // 80-89%
C: 70, // 70-79%
D: 60, // 60-69%
F: 0 // 0-59%
},
// Industry benchmarks (customize for your industry)
industryBenchmarks: {
ctr: 3.17,
conversionRate: 3.75,
cpc: 2.69,
qualityScore: 6
},
// Best practice thresholds
bestPractices: {
keywordsPerAdGroup: 20,
adsPerAdGroup: 3,
minExtensionTypes: 4,
minQualityScore: 7,
maxCampaignsPerNegativeList: 20
},
// Category weights (must sum to 100)
categoryWeights: {
campaignOrganization: 10,
conversionTracking: 15,
keywordStrategy: 12,
negativeKeywords: 8,
biddingStrategy: 12,
adCreative: 10,
qualityScore: 10,
audienceStrategy: 8,
landingPage: 8,
competitiveAnalysis: 7
}
};
// Define evaluation categories
const EVALUATION_CATEGORIES = [
{
name: "Campaign Organization",
weight: CONFIG.categoryWeights.campaignOrganization,
criteria: [
{ name: "Logical Campaign & Ad Group Structure", weight: 40 },
{ name: "Clear Naming Conventions & Segmentation", weight: 30 },
{ name: "No Internal Competition", weight: 30 }
]
},
{
name: "Conversion Tracking",
weight: CONFIG.categoryWeights.conversionTracking,
criteria: [
{ name: "Comprehensive Conversion Coverage", weight: 40 },
{ name: "Accurate and Verified Tracking Implementation", weight: 35 },
{ name: "Enhanced & Offline Conversion Tracking", weight: 25 }
]
},
{
name: "Keyword Strategy",
weight: CONFIG.categoryWeights.keywordStrategy,
criteria: [
{ name: "Extensive Keyword Research & Relevance", weight: 30 },
{ name: "Strategic Match Type Use", weight: 25 },
{ name: "Brand vs Non-Brand Segmentation", weight: 25 },
{ name: "Continuous Keyword Optimization", weight: 20 }
]
},
{
name: "Negative Keywords",
weight: CONFIG.categoryWeights.negativeKeywords,
criteria: [
{ name: "Routine Search Query Mining", weight: 40 },
{ name: "Negative Keyword Lists and Hierarchy", weight: 35 },
{ name: "Balanced Exclusion (Avoid False Negatives)", weight: 25 }
]
},
{
name: "Bidding Strategy",
weight: CONFIG.categoryWeights.biddingStrategy,
criteria: [
{ name: "Goal-Aligned Bidding Approach", weight: 35 },
{ name: "Optimize Automated Bidding with Data", weight: 25 },
{ name: "Device, Location, and Time Bid Adjustments", weight: 20 },
{ name: "Budget Management & Bid Strategy Alignment", weight: 20 }
]
},
{
name: "Ad Creative & Extensions",
weight: CONFIG.categoryWeights.adCreative,
criteria: [
{ name: "Compelling Ad Copy with Relevance", weight: 30 },
{ name: "Ad Variety and Continuous Testing", weight: 25 },
{ name: "Leverage Ad Extensions", weight: 30 },
{ name: "Ad Quality and Compliance", weight: 15 }
]
},
{
name: "Quality Score",
weight: CONFIG.categoryWeights.qualityScore,
criteria: [
{ name: "Monitor Quality Score & Components", weight: 25 },
{ name: "Improve Ad Relevance", weight: 25 },
{ name: "Improve Expected CTR", weight: 25 },
{ name: "Improve Landing Page Experience", weight: 25 }
]
},
{
name: "Audience Strategy",
weight: CONFIG.categoryWeights.audienceStrategy,
criteria: [
{ name: "Remarketing & Retargeting", weight: 35 },
{ name: "Customer Match & Similar Audiences", weight: 25 },
{ name: "In-Market, Affinity, and Demographic Targeting", weight: 25 },
{ name: "Personalized Ad Experiences by Audience", weight: 15 }
]
},
{
name: "Landing Page Optimization",
weight: CONFIG.categoryWeights.landingPage,
criteria: [
{ name: "Relevance and Message Match", weight: 30 },
{ name: "Conversion-Focused Design", weight: 30 },
{ name: "Page Speed and Mobile Optimization", weight: 25 },
{ name: "A/B Testing & Iteration", weight: 15 }
]
},
{
name: "Competitive Analysis",
weight: CONFIG.categoryWeights.competitiveAnalysis,
criteria: [
{ name: "Auction Insights Monitoring", weight: 35 },
{ name: "Competitor Keyword and Ad Analysis", weight: 25 },
{ name: "Benchmarking Performance Metrics", weight: 25 },
{ name: "Adaptive Strategy to Competitor Moves", weight: 15 }
]
}
];
/**
* Main function that runs the account grader
* @param {Object} options Optional parameters to customize the script behavior
* @param {string} options.startDate Optional start date in YYYYMMDD format
* @param {string} options.endDate Optional end date in YYYYMMDD format
* @return {string} URL of the generated report spreadsheet
*/
function main(options = {}) {
Logger.log("Starting Google Ads Account Grader...");
// Apply custom date range if provided
if (options.startDate && options.endDate) {
CONFIG.dateRange.useCustomDateRange = true;
CONFIG.dateRange.customStartDate = options.startDate;
CONFIG.dateRange.customEndDate = options.endDate;
Logger.log(`Using custom date range: ${options.startDate} to ${options.endDate}`);
}
try {
// Collect account data
Logger.log("Collecting account data...");
const accountData = collectAccountData();
// Evaluate each category
const evaluationResults = {
campaignorganization: evaluateCampaignOrganization(accountData),
conversiontracking: evaluateConversionTracking(accountData),
keywordstrategy: evaluateKeywordStrategy(accountData),
negativekeywords: evaluateNegativeKeywords(accountData),
biddingstrategy: evaluateBiddingStrategy(accountData),
adcreativeextensions: evaluateAdCreative(accountData),
qualityscore: evaluateQualityScore(accountData),
audiencestrategy: evaluateAudienceStrategy(accountData),
landingpageoptimization: evaluateLandingPage(accountData),
competitiveanalysis: evaluateCompetitiveAnalysis(accountData)
};
// Enhance evaluation results with raw data to ensure detailed reports
enhanceEvaluationResults(evaluationResults, accountData);
// Fix category keys to match EVALUATION_CATEGORIES
// This ensures compatibility between the keys used in evaluationResults and the names in EVALUATION_CATEGORIES
const fixedEvaluationResults = {};
for (const category in evaluationResults) {
let fixedKey = category;
// Special case for adcreativeextensions
if (category === 'adcreativeextensions') {
fixedKey = 'adcreative&extensions';
}
fixedEvaluationResults[fixedKey] = evaluationResults[category];
}
// Calculate overall grade
const overallGrade = calculateOverallGrade(fixedEvaluationResults);
// Generate prioritized recommendations
const prioritizedRecommendations = generatePrioritizedRecommendations(fixedEvaluationResults);
// Create report
const reportSpreadsheet = createReport(fixedEvaluationResults, overallGrade, prioritizedRecommendations, accountData);
// Send email notification if configured
if (CONFIG.email.sendReport) {
sendEmailReport(reportSpreadsheet.getUrl(), fixedEvaluationResults, overallGrade, accountData);
}
Logger.log("Account grading completed successfully!");
Logger.log("Overall grade: " + overallGrade.letter + " (" + overallGrade.score.toFixed(1) + ")");
return reportSpreadsheet.getUrl();
} catch (error) {
Logger.log("Error running account grader: " + error.message);
Logger.log(error);
// Send error notification
sendErrorNotification(error);
throw error;
}
}
/**
* Gets the date range for analysis
* @return {Object} Date range object with start and end dates
*/
/**
* Gets the date range for analysis
* @return {Object} Date range object with start and end dates
*/
function getDateRange() {
Logger.log("Getting date range...");
// Initialize date range object
let dateRange = {
start: '',
end: ''
};
// Get today's date
const today = new Date();
// Format dates as YYYYMMDD
const formatDate = function(date) {
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
return year.toString() + month + day;
};
let formattedStartDate = '';
let formattedEndDate = '';
// Check if using custom date range
if (CONFIG.dateRange.useCustomDateRange) {
// Use custom date range from CONFIG
formattedStartDate = CONFIG.dateRange.customStartDate;
formattedEndDate = CONFIG.dateRange.customEndDate;
// Validate custom dates
if (!formattedStartDate || !formattedEndDate ||
!/^\d{8}$/.test(formattedStartDate) || !/^\d{8}$/.test(formattedEndDate)) {
Logger.log("Warning: Invalid custom date format. Using lookback period instead.");
// Fall back to lookback period
const lookbackDays = CONFIG.dateRange.lookbackDays || 30;
// Calculate start date by subtracting lookback days
const startDate = new Date(today);
startDate.setDate(startDate.getDate() - lookbackDays);
// Format dates
formattedStartDate = formatDate(startDate);
formattedEndDate = formatDate(today);
}
} else {
// Use lookback period
const lookbackDays = CONFIG.dateRange.lookbackDays || 30;
// Calculate start date by subtracting lookback days
const startDate = new Date(today);
startDate.setDate(startDate.getDate() - lookbackDays);
// Format dates
formattedStartDate = formatDate(startDate);
formattedEndDate = formatDate(today);
}
// Set date range
dateRange.start = formattedStartDate;
dateRange.end = formattedEndDate;
// Log date range
Logger.log("Date range: " + dateRange.start + " to " + dateRange.end + " (" +
dateRange.start.substring(0, 4) + "-" +
dateRange.start.substring(4, 6) + "-" +
dateRange.start.substring(6, 8) + " to " +
dateRange.end.substring(0, 4) + "-" +
dateRange.end.substring(4, 6) + "-" +
dateRange.end.substring(6, 8) + ")");
return dateRange;
}
/**
* Gets the date range for the previous period (same length as current period)
* @param {Object} currentDateRange The current date range object
* @return {Object} The previous period date range
*/
function getPreviousPeriodDateRange(currentDateRange) {
try {
// Parse current date range
const startDate = new Date(currentDateRange.start.substring(0, 4) + '-' +
currentDateRange.start.substring(4, 6) + '-' +
currentDateRange.start.substring(6, 8));
const endDate = new Date(currentDateRange.end.substring(0, 4) + '-' +
currentDateRange.end.substring(4, 6) + '-' +
currentDateRange.end.substring(6, 8));
// Calculate period length in days
const periodLength = Math.round((endDate - startDate) / (1000 * 60 * 60 * 24));
// Calculate previous period dates
const previousEndDate = new Date(startDate);
previousEndDate.setDate(previousEndDate.getDate() - 1);
const previousStartDate = new Date(previousEndDate);
previousStartDate.setDate(previousStartDate.getDate() - periodLength);
// Format dates as YYYYMMDD
const formatDate = function(date) {
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
return year.toString() + month + day;
};
// Log the calculated date ranges for debugging
Logger.log("Current period: " + currentDateRange.start + " to " + currentDateRange.end);
Logger.log("Previous period: " + formatDate(previousStartDate) + " to " + formatDate(previousEndDate));
return {
start: formatDate(previousStartDate),
end: formatDate(previousEndDate)
};
} catch (e) {
Logger.log("Error calculating previous period date range: " + e.message);
return null;
}
}
function generatePrioritizedRecommendations(evaluationResults) {
Logger.log("Generating prioritized recommendations...");
// Collect all recommendations from all categories
const allRecommendations = [];
for (const category in evaluationResults) {
try {
// Find the category in EVALUATION_CATEGORIES
const categoryObj = EVALUATION_CATEGORIES.find(c =>
c.name.toLowerCase().replace(/\s+/g, '') === category);
// Skip if category not found or has no recommendations
if (!categoryObj || !evaluationResults[category] || !evaluationResults[category].recommendations) {
continue;
}
const categoryName = categoryObj.name;
evaluationResults[category].recommendations.forEach(rec => {
allRecommendations.push({
category: categoryName,
text: rec.text,
impact: rec.impact
});
});
} catch (e) {
Logger.log(`Error processing recommendations for category ${category}: ${e.message}`);
}
}
// Sort recommendations by impact (highest first)
allRecommendations.sort((a, b) => b.impact - a.impact);
return allRecommendations;
}
/**
* Creates a report spreadsheet with the evaluation results
* @param {Object} evaluationResults The results of all category evaluations
* @param {Object} overallGrade The overall account grade
* @param {Array} prioritizedRecommendations The prioritized recommendations
* @param {Object} accountData The collected account data
* @return {Spreadsheet} The created spreadsheet
*/
function createReport(evaluationResults, overallGrade, prioritizedRecommendations, accountData) {
Logger.log("Creating report spreadsheet...");
const accountName = AdsApp.currentAccount().getName();
const accountId = AdsApp.currentAccount().getCustomerId();
const date = Utilities.formatDate(new Date(), AdsApp.currentAccount().getTimeZone(), "yyyy-MM-dd");
// Create a new spreadsheet
const spreadsheet = SpreadsheetApp.create("Google Ads Account Grader - " + accountName + " - " + date);
const summarySheet = spreadsheet.getActiveSheet().setName("Summary");
// Add account info
let row = 1;
summarySheet.getRange(row, 1).setValue("Google Ads Account Grader Report");
summarySheet.getRange(row, 1).setFontWeight("bold").setFontSize(16);
row += 2;
summarySheet.getRange(row, 1).setValue("Account:");
summarySheet.getRange(row, 2).setValue(accountName + " (" + accountId + ")");
row++;
summarySheet.getRange(row, 1).setValue("Date:");
summarySheet.getRange(row, 2).setValue(date);
row += 2;
// Add overall grade
summarySheet.getRange(row, 1).setValue("Overall Account Grade:");
summarySheet.getRange(row, 2).setValue(overallGrade.letter + " (" + overallGrade.score.toFixed(1) + ")");
// Format the grade cell based on the grade
const gradeCell = summarySheet.getRange(row, 2);
if (overallGrade.letter === 'A') {
gradeCell.setBackground("#b7e1cd"); // Green
} else if (overallGrade.letter === 'B') {
gradeCell.setBackground("#c9daf8"); // Light blue
} else if (overallGrade.letter === 'C') {
gradeCell.setBackground("#fce8b2"); // Yellow
} else if (overallGrade.letter === 'D') {
gradeCell.setBackground("#f7c8a2"); // Orange
} else {
gradeCell.setBackground("#f4c7c3"); // Red
}
row += 2;
// Add category summary
summarySheet.getRange(row, 1).setValue("Category Grades");
summarySheet.getRange(row, 1).setFontWeight("bold").setFontSize(14);
row += 1;
// Create header row
summarySheet.getRange(row, 1).setValue("Category");
summarySheet.getRange(row, 2).setValue("Grade");
summarySheet.getRange(row, 3).setValue("Score");
summarySheet.getRange(row, 1, 1, 3).setFontWeight("bold").setBackground("#efefef");
row++;
// Add each category grade
for (const category in evaluationResults) {
try {
// Find the category in EVALUATION_CATEGORIES
const categoryObj = EVALUATION_CATEGORIES.find(c =>
c.name.toLowerCase().replace(/\s+/g, '') === category);
// Skip if category not found
if (!categoryObj) {
Logger.log(`Category not found in EVALUATION_CATEGORIES: ${category}`);
continue;
}
const categoryName = categoryObj.name;
const result = evaluationResults[category];
if (!result || result.score === undefined || !result.letter) {
Logger.log(`Missing result data for category: ${category}`);
continue;
}
summarySheet.getRange(row, 1).setValue(categoryName);
summarySheet.getRange(row, 2).setValue(result.letter);
summarySheet.getRange(row, 3).setValue(result.score.toFixed(1));
// Format the grade cell based on the grade
const gradeCellCategory = summarySheet.getRange(row, 2);
if (result.letter === 'A') {
gradeCellCategory.setBackground("#b7e1cd"); // Green
} else if (result.letter === 'B') {
gradeCellCategory.setBackground("#c9daf8"); // Light blue
} else if (result.letter === 'C') {
gradeCellCategory.setBackground("#fce8b2"); // Yellow
} else if (result.letter === 'D') {
gradeCellCategory.setBackground("#f7c8a2"); // Orange
} else {
gradeCellCategory.setBackground("#f4c7c3"); // Red
}
row++;
} catch (e) {
Logger.log(`Error processing category ${category} for report: ${e.message}`);
}
}
row += 2;
// Add top recommendations
summarySheet.getRange(row, 1).setValue("Top Recommendations");
summarySheet.getRange(row, 1).setFontWeight("bold").setFontSize(14);
row += 1;
// Create header row
summarySheet.getRange(row, 1).setValue("Recommendation");
summarySheet.getRange(row, 2).setValue("Category");
summarySheet.getRange(row, 3).setValue("Impact");
summarySheet.getRange(row, 1, 1, 3).setFontWeight("bold").setBackground("#efefef");
row++;
// Add each recommendation
prioritizedRecommendations.forEach(rec => {
try {
summarySheet.getRange(row, 1).setValue(rec.text);
summarySheet.getRange(row, 2).setValue(rec.category);
// Convert impact score to text
let impactText = "";
if (rec.impact >= 0.9) {
impactText = "Critical";
} else if (rec.impact >= 0.7) {
impactText = "High";
} else if (rec.impact >= 0.5) {
impactText = "Medium";
} else {
impactText = "Low";
}
summarySheet.getRange(row, 3).setValue(impactText);
// Format impact cell
const impactCell = summarySheet.getRange(row, 3);
if (rec.impact >= 0.9) {
impactCell.setBackground("#f4c7c3");
} else if (rec.impact >= 0.7) {
impactCell.setBackground("#f7c8a2");
} else if (rec.impact >= 0.5) {
impactCell.setBackground("#fce8b2");
} else {
impactCell.setBackground("#b7e1cd");
}
row++;
} catch (e) {
Logger.log(`Error adding recommendation to report: ${e.message}`);
}
});
// Auto-resize columns
summarySheet.autoResizeColumns(1, 3);
// Create detailed sheets for each category
for (const category in evaluationResults) {
try {
// Find the category in EVALUATION_CATEGORIES
const categoryObj = EVALUATION_CATEGORIES.find(c =>
c.name.toLowerCase().replace(/\s+/g, '') === category);
// Skip if category not found
if (!categoryObj) {
Logger.log(`Category not found in EVALUATION_CATEGORIES for detailed sheet: ${category}`);
continue;
}
const categoryName = categoryObj.name;
const result = evaluationResults[category];
if (!result) {
Logger.log(`Missing result data for category detailed sheet: ${category}`);
continue;
}
// Create a new sheet for this category
const categorySheet = spreadsheet.insertSheet(categoryName);
// Add category info
let catRow = 1;
categorySheet.getRange(catRow, 1).setValue(categoryName + " Analysis");
categorySheet.getRange(catRow, 1).setFontWeight("bold").setFontSize(16);
catRow += 2;
categorySheet.getRange(catRow, 1).setValue("Grade:");
categorySheet.getRange(catRow, 2).setValue(result.letter + " (" + result.score.toFixed(1) + ")");
// Format the grade cell
const catGradeCell = categorySheet.getRange(catRow, 2);
if (result.letter === 'A') {
catGradeCell.setBackground("#b7e1cd");
} else if (result.letter === 'B') {
catGradeCell.setBackground("#c9daf8");
} else if (result.letter === 'C') {
catGradeCell.setBackground("#fce8b2");
} else if (result.letter === 'D') {
catGradeCell.setBackground("#f7c8a2");
} else {
catGradeCell.setBackground("#f4c7c3");
}
catRow += 2;
// Add criteria scores
if (result.criteria && result.criteria.length > 0) {
categorySheet.getRange(catRow, 1).setValue("Criteria Scores");
categorySheet.getRange(catRow, 1).setFontWeight("bold").setFontSize(14);
catRow++;
// Create header row
categorySheet.getRange(catRow, 1).setValue("Criterion");
categorySheet.getRange(catRow, 2).setValue("Score");
categorySheet.getRange(catRow, 1, 1, 2).setFontWeight("bold").setBackground("#efefef");
catRow++;
// Add each criterion
result.criteria.forEach(criterion => {
categorySheet.getRange(catRow, 1).setValue(criterion.name);
categorySheet.getRange(catRow, 2).setValue(criterion.score.toFixed(1));
// Format score cell
const scoreCell = categorySheet.getRange(catRow, 2);
if (criterion.score >= 90) {
scoreCell.setBackground("#b7e1cd");
} else if (criterion.score >= 80) {
scoreCell.setBackground("#c9daf8");
} else if (criterion.score >= 70) {
scoreCell.setBackground("#fce8b2");
} else if (criterion.score >= 60) {
scoreCell.setBackground("#f7c8a2");
} else {
scoreCell.setBackground("#f4c7c3");
}
catRow++;
});
}
catRow += 2;
// Add recommendations
if (result.recommendations && result.recommendations.length > 0) {
categorySheet.getRange(catRow, 1).setValue("Recommendations");
categorySheet.getRange(catRow, 1).setFontWeight("bold").setFontSize(14);
catRow++;
// Create header row
categorySheet.getRange(catRow, 1).setValue("Recommendation");
categorySheet.getRange(catRow, 2).setValue("Impact");
categorySheet.getRange(catRow, 1, 1, 2).setFontWeight("bold").setBackground("#efefef");
catRow++;
// Add each recommendation
result.recommendations.forEach(rec => {
categorySheet.getRange(catRow, 1).setValue(rec.text);
// Convert impact score to text
let impactText = "";
if (rec.impact >= 0.9) {
impactText = "Critical";
} else if (rec.impact >= 0.7) {
impactText = "High";
} else if (rec.impact >= 0.5) {
impactText = "Medium";
} else {
impactText = "Low";
}
categorySheet.getRange(catRow, 2).setValue(impactText);
// Format impact cell
const impactCell = categorySheet.getRange(catRow, 2);
if (rec.impact >= 0.9) {
impactCell.setBackground("#f4c7c3");
} else if (rec.impact >= 0.7) {
impactCell.setBackground("#f7c8a2");
} else if (rec.impact >= 0.5) {
impactCell.setBackground("#fce8b2");
} else {
impactCell.setBackground("#b7e1cd");
}
catRow++;
});
}
// Add data section if available
if (result.data) {
catRow += 2;
categorySheet.getRange(catRow, 1).setValue("Data");
categorySheet.getRange(catRow, 1).setFontWeight("bold").setFontSize(14);
catRow++;
// Special handling for bidding strategy data
if (categoryName === "Bidding Strategy" && result.data.bidding) {
// Add bidding data
for (const key in result.data.bidding) {
if (key === 'strategies') {
// Add strategies header
categorySheet.getRange(catRow, 1).setValue("Strategies");
categorySheet.getRange(catRow, 1).setFontWeight("bold");
catRow++;
// Add each strategy
const strategies = result.data.bidding.strategies;
for (const strategy in strategies) {
categorySheet.getRange(catRow, 1).setValue(" " + strategy);
categorySheet.getRange(catRow, 2).setValue(strategies[strategy]);
catRow++;
}
} else if (key === 'portfolioBiddingStrategies' && Array.isArray(result.data.bidding.portfolioBiddingStrategies)) {
// Add portfolio bidding strategies header
categorySheet.getRange(catRow, 1).setValue("Portfolio Bidding Strategies");
categorySheet.getRange(catRow, 1).setFontWeight("bold");
catRow++;
// Add each portfolio bidding strategy
const portfolioStrategies = result.data.bidding.portfolioBiddingStrategies;
if (portfolioStrategies.length > 0) {
for (let i = 0; i < portfolioStrategies.length; i++) {
const strategy = portfolioStrategies[i];
const strategyName = strategy.name || 'Unnamed Strategy';
const strategyType = strategy.type || 'Unknown Type';
const campaignCount = strategy.campaignCount || 0;
categorySheet.getRange(catRow, 1).setValue(` ${i+1}. ${strategyName}`);
categorySheet.getRange(catRow, 2).setValue(`${strategyType} (${campaignCount} campaigns)`);
catRow++;
}
} else {
categorySheet.getRange(catRow, 1).setValue(" No portfolio bidding strategies found");
catRow++;
}
} else {
// Format the key name
const keyName = key
.replace(/([A-Z])/g, ' $1')
.replace(/^./, function(str) { return str.toUpperCase(); });
// Format the value
let value = result.data.bidding[key];
if (typeof value === 'number') {
if (key.toLowerCase().includes('percentage') ||
key.toLowerCase().includes('share')) {
value = value.toFixed(2) + '%';
} else if (Number.isInteger(value)) {
value = value.toString();
} else {
value = value.toFixed(2);
}
} else if (typeof value === 'boolean') {
value = value ? 'TRUE' : 'FALSE';
}
categorySheet.getRange(catRow, 1).setValue(keyName);
categorySheet.getRange(catRow, 2).setValue(value);
catRow++;
}
}
} else {
// Add data as a table
addDataSection(result.data, categorySheet, catRow, 1);
}
}
// Auto-resize columns
categorySheet.autoResizeColumns(1, 3);
} catch (e) {
Logger.log(`Error creating detailed sheet for category ${category}: ${e.message}`);
}
}
// Add data sheet
try {
const dataSheet = spreadsheet.insertSheet("Account Data");
// Add account data
let dataRow = 1;
dataSheet.getRange(dataRow, 1).setValue("Account Data");
dataSheet.getRange(dataRow, 1).setFontWeight("bold").setFontSize(16);
dataRow += 2;
// Add account data sections
if (accountData) {
// Performance data
if (accountData.performance) {
dataSheet.getRange(dataRow, 1).setValue("Performance Metrics");
dataSheet.getRange(dataRow, 1).setFontWeight("bold").setFontSize(14);
dataRow++;
dataRow = addDataSection(accountData.performance, dataSheet, dataRow, 1);
dataRow += 2;
}
// Campaign data
if (accountData.campaigns) {
dataSheet.getRange(dataRow, 1).setValue("Campaign Data");
dataSheet.getRange(dataRow, 1).setFontWeight("bold").setFontSize(14);
dataRow++;
dataRow = addDataSection(accountData.campaigns, dataSheet, dataRow, 1);
dataRow += 2;
}
// Keyword data
if (accountData.keywords) {
dataSheet.getRange(dataRow, 1).setValue("Keyword Data");
dataSheet.getRange(dataRow, 1).setFontWeight("bold").setFontSize(14);
dataRow++;
dataRow = addDataSection(accountData.keywords, dataSheet, dataRow, 1);
dataRow += 2;
}
// Ad data
if (accountData.ads) {
dataSheet.getRange(dataRow, 1).setValue("Ad Data");
dataSheet.getRange(dataRow, 1).setFontWeight("bold").setFontSize(14);
dataRow++;
dataRow = addDataSection(accountData.ads, dataSheet, dataRow, 1);
dataRow += 2;
}
// Quality Score data
if (accountData.qualityScore) {
dataSheet.getRange(dataRow, 1).setValue("Quality Score Data");
dataSheet.getRange(dataRow, 1).setFontWeight("bold").setFontSize(14);
dataRow++;
dataRow = addDataSection(accountData.qualityScore, dataSheet, dataRow, 1);
dataRow += 2;
}
}
// Auto-resize columns
dataSheet.autoResizeColumns(1, 2);
} catch (e) {
Logger.log(`Error creating data sheet: ${e.message}`);
}
// Set the active sheet to the summary sheet
spreadsheet.setActiveSheet(summarySheet);
return spreadsheet;
}
/**
* Sends an email report with the evaluation results
* @param {string} spreadsheetUrl URL of the report spreadsheet
* @param {Object} evaluationResults The results of all category evaluations
* @param {Object} overallGrade The overall account grade
* @param {Object} accountData The collected account data
*/
function sendEmailReport(spreadsheetUrl, evaluationResults, overallGrade, accountData) {
// **************************************************************************
// WARNING: DO NOT MODIFY THE CONTACT INFORMATION IN THE EMAIL FOOTER.
// MODIFYING THE CONTACT INFORMATION WILL BREAK THE SCRIPT FUNCTIONALITY.
// Contact: john@itallstartedwithaidea.com | Website: itallstartedwithaidea.com
// **************************************************************************
Logger.log("Sending email report...");
// Debug accountData object
debugObject(accountData, 'accountData in sendEmailReport');
if (accountData.previousPeriod) {
debugObject(accountData.previousPeriod, 'accountData.previousPeriod');
debugObject(accountData.previousPeriod.performance, 'accountData.previousPeriod.performance');
} else {
Logger.log('accountData.previousPeriod is not defined');
}
const accountName = AdsApp.currentAccount().getName();
const accountId = AdsApp.currentAccount().getCustomerId();
const date = Utilities.formatDate(new Date(), AdsApp.currentAccount().getTimeZone(), "yyyy-MM-dd");
// Create email subject
const subject = `Google Ads Account Grader Report - ${accountName} (${accountId}) - ${date}`;
// Create email body with improved styling
let body = `
<div style="font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; border: 1px solid #e0e0e0; border-radius: 5px;">
<div style="text-align: center; background-color: #4285f4; color: white; padding: 15px; border-radius: 5px 5px 0 0;">
<h1 style="margin: 0;">Google Ads Account Grader</h1>
<p style="margin: 10px 0 0 0; font-size: 16px;">Comprehensive Performance Analysis</p>
</div>
<div style="padding: 20px;">
<div style="margin-bottom: 20px;">
<p><strong>Account:</strong> ${accountName} (${accountId})</p>
<p><strong>Date:</strong> ${date}</p>
<p><strong>Analysis Period:</strong> ${accountData.dateRange ? accountData.dateRange.start + ' to ' + accountData.dateRange.end : 'Last 30 days'}</p>
</div>
<div style="background-color: #f8f9fa; padding: 15px; border-radius: 5px; margin-bottom: 20px; text-align: center;">
<h2 style="margin-top: 0;">Overall Account Grade</h2>
<div style="font-size: 48px; font-weight: bold; color: ${getGradeColor(overallGrade.letter)}">${overallGrade.letter}</div>
<div style="font-size: 18px;">${overallGrade.score.toFixed(1)}/100</div>
<p style="margin-top: 10px;">${getOverallGradeDescription(overallGrade.letter)}</p>
</div>
<div style="margin-bottom: 30px;">
<h2>Category Performance</h2>
<table style="width: 100%; border-collapse: collapse; margin-top: 10px;">