-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathaccount-grader-v2.js
More file actions
9249 lines (7947 loc) · 352 KB
/
Copy pathaccount-grader-v2.js
File metadata and controls
9249 lines (7947 loc) · 352 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 - ENHANCED EDITION
*
* 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.2 PROFESSIONAL
* @changelog
* v2.2 - Added: Historical Trend Tracking (6 months), Budget Efficiency Analysis
* (11th category), Search Term Analysis (deep dive), Master tracking spreadsheet
* v2.1 - Added: Configuration validation, Progress indicators, Dry run mode,
* MCC support, Error recovery with retry, Performance profiling
* v2.0 - Initial comprehensive grader with 10 categories
*/
// 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: "20250715", // July 1, 2022
customEndDate: "20250915", // 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: 'youremail@slack.com',
errorRecipients: ['youremail@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: 9,
conversionTracking: 14,
keywordStrategy: 11,
negativeKeywords: 7,
biddingStrategy: 11,
adCreative: 9,
qualityScore: 9,
audienceStrategy: 7,
landingPage: 7,
competitiveAnalysis: 6,
budgetEfficiency: 10 // NEW v2.2: Budget efficiency category
},
// ===== NEW v2.1 ENHANCED FEATURES =====
// Testing & Development settings
testing: {
dryRun: false, // Set to true to test without sending emails/creating sheets
logDataToConsole: false, // Set to true for verbose debug logging
enableProfiling: true // Track execution time per function
},
// MCC (Manager Account) settings
mcc: {
enabled: false, // Set to true to run on all child accounts
maxAccounts: 50, // Maximum number of accounts to process
accountFilter: '', // Optional: filter accounts by name (empty = all)
sendConsolidatedReport: true // Send one summary report for all accounts
},
// Error handling settings
errorHandling: {
enableRetry: true, // Retry failed API calls
maxRetries: 3, // Maximum number of retry attempts
retryDelayMs: 1000, // Base delay between retries (exponential backoff)
continueOnError: true // Continue processing other categories if one fails
},
// Progress reporting
progress: {
enableProgressLogs: true, // Log progress percentage
logInterval: 10 // Log every N% progress
},
// ===== NEW v2.2 PROFESSIONAL FEATURES =====
// Historical trend tracking
historicalTracking: {
enabled: true, // Enable historical comparison
masterSpreadsheetId: '', // ID of master tracking sheet (auto-created if empty)
monthsToTrack: 6, // Track last 6 months
showTrendCharts: true, // Add trend visualizations
alertOnDecline: true, // Alert if grades decline
declineThreshold: 10 // Alert if score drops 10+ points
},
// Budget efficiency analysis (11th category)
budgetEfficiency: {
enabled: true, // Enable budget efficiency category
wastedSpendThreshold: 100, // Flag keywords with $100+ wasted
lowPerformanceClickThreshold: 10, // Clicks before considering as low-performing
zeroConversionDaysThreshold: 30 // Flag keywords with no conversions in 30 days
},
// Search term analysis
searchTermAnalysis: {
enabled: true, // Enable deep search term analysis
minImpressions: 10, // Minimum impressions to analyze
minClicks: 5, // Minimum clicks for deeper analysis
identifyNewOpportunities: true, // Find converting search terms not in keywords
identifyWaste: true, // Find expensive non-converting terms
analyzeIntent: true, // Analyze search intent patterns
maxTermsToAnalyze: 1000 // Limit for performance
}
};
// 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 }
]
},
{
name: "Budget Efficiency",
weight: CONFIG.categoryWeights.budgetEfficiency,
criteria: [
{ name: "Wasted Spend Identification", weight: 35 },
{ name: "Budget Allocation Optimization", weight: 30 },
{ name: "Day-Parting and Scheduling Efficiency", weight: 20 },
{ name: "Device and Location Budget Distribution", weight: 15 }
]
}
];
// ===== NEW v2.1 ENHANCED UTILITY FUNCTIONS =====
/**
* Validates the CONFIG object before execution
* @throws {Error} If configuration is invalid
* @return {boolean} True if config is valid
*/
function validateConfig() {
Logger.log("🔍 Validating configuration...");
const errors = [];
// Validate email
if (!CONFIG.email.emailAddress || !CONFIG.email.emailAddress.includes('@')) {
errors.push('❌ Invalid email address in CONFIG.email.emailAddress');
}
// Validate date range
if (CONFIG.dateRange.useCustomDateRange) {
if (!/^\d{8}$/.test(CONFIG.dateRange.customStartDate)) {
errors.push('❌ Invalid customStartDate format (use YYYYMMDD)');
}
if (!/^\d{8}$/.test(CONFIG.dateRange.customEndDate)) {
errors.push('❌ Invalid customEndDate format (use YYYYMMDD)');
}
// Validate start is before end
if (CONFIG.dateRange.customStartDate > CONFIG.dateRange.customEndDate) {
errors.push('❌ customStartDate must be before customEndDate');
}
} else {
if (!CONFIG.dateRange.lookbackDays || CONFIG.dateRange.lookbackDays < 1) {
errors.push('❌ lookbackDays must be at least 1');
}
}
// Validate category weights sum to 100
const weightSum = Object.values(CONFIG.categoryWeights).reduce((a, b) => a + b, 0);
if (Math.abs(weightSum - 100) > 0.01) {
errors.push(`❌ Category weights must sum to 100 (current: ${weightSum})`);
}
// Validate thresholds
if (CONFIG.gradeThresholds.A < CONFIG.gradeThresholds.B ||
CONFIG.gradeThresholds.B < CONFIG.gradeThresholds.C ||
CONFIG.gradeThresholds.C < CONFIG.gradeThresholds.D) {
errors.push('❌ Grade thresholds must be in descending order (A > B > C > D)');
}
// Log results
if (errors.length > 0) {
Logger.log('❌ Configuration validation FAILED:');
errors.forEach(error => Logger.log(' ' + error));
throw new Error('Configuration errors:\n' + errors.join('\n'));
}
Logger.log('✅ Configuration validation PASSED');
return true;
}
/**
* Logs progress with percentage indicator
* @param {number} current Current step number
* @param {number} total Total number of steps
* @param {string} label Description of current step
*/
function logProgress(current, total, label) {
if (!CONFIG.progress.enableProgressLogs) return;
const percent = Math.round((current / total) * 100);
const shouldLog = percent % CONFIG.progress.logInterval === 0 || current === 1 || current === total;
if (shouldLog) {
const bar = '█'.repeat(Math.floor(percent / 10)) + '░'.repeat(10 - Math.floor(percent / 10));
Logger.log(`📊 [${percent}%] ${bar} ${label}`);
}
}
/**
* Profiles function execution time
* @param {Function} fn Function to profile
* @param {string} label Label for the profile
* @return {*} Result of the function
*/
function profile(fn, label) {
if (!CONFIG.testing.enableProfiling) {
return fn();
}
const start = new Date().getTime();
const result = fn();
const duration = new Date().getTime() - start;
Logger.log(`⏱️ ${label}: ${duration}ms (${(duration / 1000).toFixed(2)}s)`);
return result;
}
/**
* Retries a function with exponential backoff
* @param {Function} fn Function to retry
* @param {number} maxRetries Maximum number of retries
* @return {*} Result of the function
*/
function retryWithBackoff(fn, maxRetries = CONFIG.errorHandling.maxRetries) {
if (!CONFIG.errorHandling.enableRetry) {
return fn();
}
let attempt = 0;
while (attempt < maxRetries) {
try {
return fn();
} catch (e) {
attempt++;
if (attempt >= maxRetries) {
Logger.log(`❌ Failed after ${maxRetries} attempts: ${e.message}`);
throw e;
}
const delay = CONFIG.errorHandling.retryDelayMs * Math.pow(2, attempt);
Logger.log(`⚠️ Retry attempt ${attempt}/${maxRetries} after ${delay}ms: ${e.message}`);
Utilities.sleep(delay);
}
}
}
/**
* Safely executes a function with error handling
* @param {Function} fn Function to execute
* @param {string} label Label for logging
* @param {*} defaultValue Value to return on error
* @return {*} Result of function or default value
*/
function safeExecute(fn, label, defaultValue = null) {
try {
return fn();
} catch (e) {
Logger.log(`⚠️ Error in ${label}: ${e.message}`);
if (CONFIG.errorHandling.continueOnError) {
Logger.log(` Continuing with default value...`);
return defaultValue;
} else {
throw e;
}
}
}
// ===== NEW v2.2 HISTORICAL TRACKING FUNCTIONS =====
/**
* Gets or creates the master tracking spreadsheet
* @return {Spreadsheet} The master tracking spreadsheet
*/
function getMasterTrackingSpreadsheet() {
Logger.log("📊 Getting master tracking spreadsheet...");
if (!CONFIG.historicalTracking.enabled) {
return null;
}
try {
// Try to open existing spreadsheet
if (CONFIG.historicalTracking.masterSpreadsheetId) {
try {
const sheet = SpreadsheetApp.openById(CONFIG.historicalTracking.masterSpreadsheetId);
Logger.log(`✅ Opened existing master spreadsheet: ${sheet.getName()}`);
return sheet;
} catch (e) {
Logger.log(`⚠️ Could not open existing spreadsheet: ${e.message}`);
}
}
// Create new master tracking spreadsheet
const accountName = AdsApp.currentAccount().getName();
const accountId = AdsApp.currentAccount().getCustomerId();
const sheet = SpreadsheetApp.create(`Google Ads Grader - Master Tracking - ${accountName} (${accountId})`);
// Initialize with headers
const trackingSheet = sheet.getActiveSheet();
trackingSheet.setName("Historical Grades");
trackingSheet.getRange(1, 1, 1, 14).setValues([[
'Date',
'Overall Grade',
'Overall Score',
'Campaign Organization',
'Conversion Tracking',
'Keyword Strategy',
'Negative Keywords',
'Bidding Strategy',
'Ad Creative & Extensions',
'Quality Score',
'Audience Strategy',
'Landing Page',
'Competitive Analysis',
'Budget Efficiency'
]]);
trackingSheet.getRange(1, 1, 1, 14).setFontWeight("bold").setBackground("#4285f4").setFontColor("#ffffff");
trackingSheet.setFrozenRows(1);
trackingSheet.autoResizeColumns(1, 14);
Logger.log(`✅ Created new master tracking spreadsheet: ${sheet.getUrl()}`);
Logger.log(`⚠️ IMPORTANT: Save this spreadsheet ID to CONFIG.historicalTracking.masterSpreadsheetId:`);
Logger.log(` masterSpreadsheetId: '${sheet.getId()}'`);
return sheet;
} catch (e) {
Logger.log(`❌ Error with master tracking spreadsheet: ${e.message}`);
return null;
}
}
/**
* Saves current grades to master tracking spreadsheet
* @param {Object} evaluationResults The evaluation results
* @param {Object} overallGrade The overall grade
*/
function saveToHistoricalTracking(evaluationResults, overallGrade) {
if (!CONFIG.historicalTracking.enabled) {
return;
}
Logger.log("💾 Saving to historical tracking...");
try {
const masterSheet = getMasterTrackingSpreadsheet();
if (!masterSheet) {
Logger.log("⚠️ No master spreadsheet available for historical tracking");
return;
}
const trackingSheet = masterSheet.getSheetByName("Historical Grades");
if (!trackingSheet) {
Logger.log("❌ Historical Grades sheet not found");
return;
}
// Get current date
const today = Utilities.formatDate(new Date(), AdsApp.currentAccount().getTimeZone(), "yyyy-MM-dd");
// Prepare row data
const rowData = [
today,
overallGrade.letter,
overallGrade.score.toFixed(1)
];
// Add category scores in order
const categoryOrder = [
'campaignorganization',
'conversiontracking',
'keywordstrategy',
'negativekeywords',
'biddingstrategy',
'adcreativeextensions',
'qualityscore',
'audiencestrategy',
'landingpageoptimization',
'competitiveanalysis',
'budgetefficiency'
];
categoryOrder.forEach(category => {
const result = evaluationResults[category];
if (result && result.score !== undefined) {
rowData.push(result.score.toFixed(1));
} else {
rowData.push('N/A');
}
});
// Append to sheet
const lastRow = trackingSheet.getLastRow();
trackingSheet.getRange(lastRow + 1, 1, 1, rowData.length).setValues([rowData]);
Logger.log(`✅ Saved historical data for ${today}`);
// Add trend chart if enabled and enough data
if (CONFIG.historicalTracking.showTrendCharts && lastRow >= 3) {
createTrendChart(trackingSheet);
}
} catch (e) {
Logger.log(`❌ Error saving to historical tracking: ${e.message}`);
}
}
/**
* Gets historical grades from master tracking spreadsheet
* @return {Array} Array of historical grade records
*/
function getHistoricalGrades() {
if (!CONFIG.historicalTracking.enabled) {
return [];
}
try {
const masterSheet = getMasterTrackingSpreadsheet();
if (!masterSheet) {
return [];
}
const trackingSheet = masterSheet.getSheetByName("Historical Grades");
if (!trackingSheet) {
return [];
}
const lastRow = trackingSheet.getLastRow();
if (lastRow <= 1) {
return []; // Only header row
}
// Get last N months of data
const monthsToGet = CONFIG.historicalTracking.monthsToTrack;
const startRow = Math.max(2, lastRow - monthsToGet + 1);
const numRows = lastRow - startRow + 1;
const data = trackingSheet.getRange(startRow, 1, numRows, 14).getValues();
const historicalData = data.map(row => ({
date: row[0],
overallGrade: row[1],
overallScore: parseFloat(row[2]) || 0,
categories: {
campaignOrganization: parseFloat(row[3]) || 0,
conversionTracking: parseFloat(row[4]) || 0,
keywordStrategy: parseFloat(row[5]) || 0,
negativeKeywords: parseFloat(row[6]) || 0,
biddingStrategy: parseFloat(row[7]) || 0,
adCreative: parseFloat(row[8]) || 0,
qualityScore: parseFloat(row[9]) || 0,
audienceStrategy: parseFloat(row[10]) || 0,
landingPage: parseFloat(row[11]) || 0,
competitiveAnalysis: parseFloat(row[12]) || 0,
budgetEfficiency: parseFloat(row[13]) || 0
}
}));
Logger.log(`📊 Retrieved ${historicalData.length} months of historical data`);
return historicalData;
} catch (e) {
Logger.log(`❌ Error retrieving historical grades: ${e.message}`);
return [];
}
}
/**
* Creates trend chart in tracking spreadsheet
* @param {Sheet} trackingSheet The tracking sheet
*/
function createTrendChart(trackingSheet) {
try {
// Remove existing charts
const charts = trackingSheet.getCharts();
charts.forEach(chart => trackingSheet.removeChart(chart));
const lastRow = trackingSheet.getLastRow();
const dataRange = trackingSheet.getRange(1, 1, lastRow, 3); // Date, Grade Letter, Score
const chart = trackingSheet.newChart()
.setChartType(Charts.ChartType.LINE)
.addRange(dataRange)
.setPosition(lastRow + 3, 1, 0, 0)
.setOption('title', 'Overall Grade Trend')
.setOption('hAxis', {title: 'Date'})
.setOption('vAxis', {title: 'Score', minValue: 0, maxValue: 100})
.setOption('legend', {position: 'bottom'})
.setOption('width', 800)
.setOption('height', 400)
.build();
trackingSheet.insertChart(chart);
Logger.log("📈 Created trend chart");
} catch (e) {
Logger.log(`⚠️ Could not create trend chart: ${e.message}`);
}
}
/**
* Checks for grade declines and sends alerts
* @param {Object} currentGrade Current overall grade
* @param {Array} historicalGrades Historical grade data
*/
function checkForDeclineAlerts(currentGrade, historicalGrades) {
if (!CONFIG.historicalTracking.enabled || !CONFIG.historicalTracking.alertOnDecline) {
return;
}
if (historicalGrades.length === 0) {
Logger.log("No historical data for decline comparison");
return;
}
try {
const previousGrade = historicalGrades[historicalGrades.length - 1];
const scoreDiff = currentGrade.score - previousGrade.overallScore;
if (Math.abs(scoreDiff) >= CONFIG.historicalTracking.declineThreshold) {
if (scoreDiff < 0) {
// Score declined
sendDeclineAlert(currentGrade, previousGrade, scoreDiff);
} else {
// Score improved
Logger.log(`📈 Score improved by ${scoreDiff.toFixed(1)} points!`);
}
}
} catch (e) {
Logger.log(`❌ Error checking for declines: ${e.message}`);
}
}
/**
* Sends alert email for grade declines
* @param {Object} currentGrade Current grade
* @param {Object} previousGrade Previous grade
* @param {number} scoreDiff Score difference
*/
function sendDeclineAlert(currentGrade, previousGrade, scoreDiff) {
Logger.log(`🚨 ALERT: Score declined by ${Math.abs(scoreDiff).toFixed(1)} points`);
const accountName = AdsApp.currentAccount().getName();
const accountId = AdsApp.currentAccount().getCustomerId();
const subject = `🚨 ALERT: Google Ads Grade Declined - ${accountName}`;
const body = `
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; border: 2px solid #ea4335; border-radius: 5px;">
<div style="background-color: #ea4335; color: white; padding: 15px; text-align: center;">
<h1 style="margin: 0;">🚨 Grade Decline Alert</h1>
</div>
<div style="padding: 20px;">
<p><strong>Account:</strong> ${accountName} (${accountId})</p>
<p><strong>Alert Reason:</strong> Grade declined significantly</p>
<table style="width: 100%; border-collapse: collapse; margin: 20px 0;">
<tr style="background-color: #f1f3f4;">
<th style="padding: 10px; text-align: left;">Metric</th>
<th style="padding: 10px; text-align: center;">Previous</th>
<th style="padding: 10px; text-align: center;">Current</th>
<th style="padding: 10px; text-align: center;">Change</th>
</tr>
<tr>
<td style="padding: 10px;"><strong>Grade</strong></td>
<td style="padding: 10px; text-align: center;">${previousGrade.overallGrade}</td>
<td style="padding: 10px; text-align: center;">${currentGrade.letter}</td>
<td style="padding: 10px; text-align: center; color: #ea4335; font-weight: bold;">
${previousGrade.overallGrade} → ${currentGrade.letter}
</td>
</tr>
<tr>
<td style="padding: 10px;"><strong>Score</strong></td>
<td style="padding: 10px; text-align: center;">${previousGrade.overallScore.toFixed(1)}</td>
<td style="padding: 10px; text-align: center;">${currentGrade.score.toFixed(1)}</td>
<td style="padding: 10px; text-align: center; color: #ea4335; font-weight: bold;">
▼ ${Math.abs(scoreDiff).toFixed(1)} points
</td>
</tr>
</table>
<p><strong>Recommended Action:</strong> Review your detailed report to identify which categories declined and implement the top recommendations.</p>
<p style="margin-top: 30px; padding-top: 20px; border-top: 1px solid #ddd; font-size: 12px; color: #666;">
This alert was triggered because the score dropped by ${Math.abs(scoreDiff).toFixed(1)} points,
which exceeds your threshold of ${CONFIG.historicalTracking.declineThreshold} points.
</p>
</div>
</div>`;
MailApp.sendEmail({
to: CONFIG.email.emailAddress,
subject: subject,
htmlBody: body
});
Logger.log("📧 Decline alert email sent");
}
/**
* Main function that runs the account grader (with MCC support)
* @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 = {}) {
// Validate configuration first
validateConfig();
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 {
const totalSteps = 14; // Total major steps in the process
let currentStep = 0;
// Step 1: Collect account data
logProgress(++currentStep, totalSteps, "Collecting account data...");
const accountData = profile(() => collectAccountData(), "Data Collection");
// Step 2-11: Evaluate each category (10 categories)
logProgress(++currentStep, totalSteps, "Evaluating Campaign Organization...");
const campaignOrg = profile(() => safeExecute(
() => evaluateCampaignOrganization(accountData),
"Campaign Organization",
{score: 0, letter: 'F', criteria: {}, recommendations: []}
), "Campaign Organization Evaluation");
logProgress(++currentStep, totalSteps, "Evaluating Conversion Tracking...");
const convTracking = profile(() => safeExecute(
() => evaluateConversionTracking(accountData),
"Conversion Tracking",
{score: 0, letter: 'F', criteria: {}, recommendations: []}
), "Conversion Tracking Evaluation");
logProgress(++currentStep, totalSteps, "Evaluating Keyword Strategy...");
const keywordStrat = profile(() => safeExecute(
() => evaluateKeywordStrategy(accountData),
"Keyword Strategy",
{score: 0, letter: 'F', criteria: {}, recommendations: []}
), "Keyword Strategy Evaluation");
logProgress(++currentStep, totalSteps, "Evaluating Negative Keywords...");
const negKeywords = profile(() => safeExecute(
() => evaluateNegativeKeywords(accountData),
"Negative Keywords",
{score: 0, letter: 'F', criteria: {}, recommendations: []}
), "Negative Keywords Evaluation");
logProgress(++currentStep, totalSteps, "Evaluating Bidding Strategy...");
const biddingStrat = profile(() => safeExecute(
() => evaluateBiddingStrategy(accountData),
"Bidding Strategy",
{score: 0, letter: 'F', criteria: {}, recommendations: []}
), "Bidding Strategy Evaluation");
logProgress(++currentStep, totalSteps, "Evaluating Ad Creative & Extensions...");
const adCreative = profile(() => safeExecute(
() => evaluateAdCreative(accountData),
"Ad Creative",
{score: 0, letter: 'F', criteria: {}, recommendations: []}
), "Ad Creative Evaluation");
logProgress(++currentStep, totalSteps, "Evaluating Quality Score...");
const qualityScore = profile(() => safeExecute(
() => evaluateQualityScore(accountData),
"Quality Score",
{score: 0, letter: 'F', criteria: {}, recommendations: []}
), "Quality Score Evaluation");
logProgress(++currentStep, totalSteps, "Evaluating Audience Strategy...");
const audienceStrat = profile(() => safeExecute(
() => evaluateAudienceStrategy(accountData),
"Audience Strategy",
{score: 0, letter: 'F', criteria: {}, recommendations: []}
), "Audience Strategy Evaluation");
logProgress(++currentStep, totalSteps, "Evaluating Landing Page Optimization...");
const landingPage = profile(() => safeExecute(
() => evaluateLandingPage(accountData),
"Landing Page",
{score: 0, letter: 'F', criteria: {}, recommendations: []}
), "Landing Page Evaluation");
logProgress(++currentStep, totalSteps, "Evaluating Competitive Analysis...");
const competitive = profile(() => safeExecute(
() => evaluateCompetitiveAnalysis(accountData),
"Competitive Analysis",
{score: 0, letter: 'F', criteria: {}, recommendations: []}
), "Competitive Analysis Evaluation");
// NEW v2.2: Evaluate Budget Efficiency (11th category)
logProgress(++currentStep, totalSteps, "Evaluating Budget Efficiency...");
const budgetEff = profile(() => safeExecute(
() => evaluateBudgetEfficiency(accountData),
"Budget Efficiency",
{score: 0, letter: 'F', criteria: {}, recommendations: []}
), "Budget Efficiency Evaluation");
// Compile evaluation results
const evaluationResults = {
campaignorganization: campaignOrg,
conversiontracking: convTracking,
keywordstrategy: keywordStrat,
negativekeywords: negKeywords,
biddingstrategy: biddingStrat,
adcreativeextensions: adCreative,
qualityscore: qualityScore,
audiencestrategy: audienceStrat,
landingpageoptimization: landingPage,
competitiveanalysis: competitive,
budgetefficiency: budgetEff
};
// Enhance evaluation results with raw data to ensure detailed reports
logProgress(++currentStep, totalSteps, "Enhancing results with detailed data...");
enhanceEvaluationResults(evaluationResults, accountData);
// Fix category keys to match EVALUATION_CATEGORIES
const fixedEvaluationResults = {};
for (const category in evaluationResults) {
let fixedKey = category;
if (category === 'adcreativeextensions') {
fixedKey = 'adcreative&extensions';
}
fixedEvaluationResults[fixedKey] = evaluationResults[category];
}
// Calculate overall grade
logProgress(++currentStep, totalSteps, "Calculating overall grade...");
const overallGrade = profile(() => calculateOverallGrade(fixedEvaluationResults), "Overall Grade Calculation");
// Generate prioritized recommendations
const prioritizedRecommendations = profile(() => generatePrioritizedRecommendations(fixedEvaluationResults), "Recommendations Generation");
// Create report (or skip in dry run mode)
logProgress(++currentStep, totalSteps, "Creating report...");
let reportSpreadsheet;
if (CONFIG.testing.dryRun) {
Logger.log("🧪 DRY RUN MODE: Skipping Google Sheets creation");
reportSpreadsheet = { getUrl: () => "DRY_RUN_MODE_NO_SHEET_CREATED" };
} else {
reportSpreadsheet = profile(() => createReport(fixedEvaluationResults, overallGrade, prioritizedRecommendations, accountData), "Report Creation");
}
// Send email notification if configured (or skip in dry run mode)
logProgress(++currentStep, totalSteps, "Sending email notification...");
if (CONFIG.email.sendReport && !CONFIG.testing.dryRun) {
profile(() => sendEmailReport(reportSpreadsheet.getUrl(), fixedEvaluationResults, overallGrade, accountData), "Email Sending");
} else if (CONFIG.testing.dryRun) {
Logger.log("🧪 DRY RUN MODE: Skipping email send to " + CONFIG.email.emailAddress);
}
// NEW v2.2: Save to historical tracking and check for declines
if (CONFIG.historicalTracking.enabled && !CONFIG.testing.dryRun) {
logProgress(++currentStep, totalSteps, "Saving to historical tracking...");
const historicalGrades = getHistoricalGrades();
saveToHistoricalTracking(fixedEvaluationResults, overallGrade);
checkForDeclineAlerts(overallGrade, historicalGrades);
}
Logger.log("✅ Account grading completed successfully!");
Logger.log("📊 Overall grade: " + overallGrade.letter + " (" + overallGrade.score.toFixed(1) + "%)");
if (CONFIG.testing.dryRun) {
Logger.log("🧪 DRY RUN MODE: Script completed without sending emails or creating sheets");
}
return reportSpreadsheet.getUrl();
} catch (error) {
Logger.log("❌ Error running account grader: " + error.message);
Logger.log(error);
// Send error notification (unless in dry run mode)
if (!CONFIG.testing.dryRun) {
sendErrorNotification(error);
} else {
Logger.log("🧪 DRY RUN MODE: Skipping error notification");
}
throw error;
}
}
/**
* NEW v2.1: Main function for MCC accounts - processes multiple child accounts
* @param {Object} options Optional parameters
* @return {Array} Array of results for each account
*/
function mainForAllAccounts(options = {}) {
if (!CONFIG.mcc.enabled) {
Logger.log("⚠️ MCC mode is not enabled. Running on current account only.");
return [main(options)];
}
// Validate configuration for MCC mode