-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbid-strategy-monitor.js
More file actions
334 lines (286 loc) · 10.9 KB
/
bid-strategy-monitor.js
File metadata and controls
334 lines (286 loc) · 10.9 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
// ID: f9f1aab1b70628be9e156f6b09e9f32e
/**
*
* Bid Strategy Performance Monitor
*
* This script allows Google Ads MCC Accounts to monitor the performance
* of various bidding strategies on child accounts based on defined
* metrics.
*
* Version: 1.0
* Google Ads Script maintained on brainlabsdigital.com
*
**/
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//Options
//Spreadsheet URL
var SPREADSHEET_URL = 'https://docs.google.com/YOUR-SPREADSHEET-URL-HERE';
//Ignore Paused Campaigns
// Set to 'false' to include paused campaigns in data.
var ignorePausedCampaigns = true;
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// Metrics
// Metrics are written onto output sheet in order stated below. Read the 'Metric'
// column of the Google Ads documentation to find other metrics to include:
// https://developers.google.com/adwords/api/docs/appendix/reports/campaign-performance-report
var METRICS = [
'AverageCpc',
'Clicks',
'Conversions',
'Cost',
'Ctr',
'Impressions',
'TopImpressionPercentage'
];
//Bidding Strategies
var BIDDING_STRATEGIES =
{
'Manual CPC': 'MANUAL_CPC',
'Manual CPV': 'MANUAL_CPV',
'Manual CPM': 'MANUAL_CPM',
'Target search page location': 'PAGE_ONE_PROMOTED',
'Maximize clicks': 'TARGET_SPEND',
'Target CPA': 'TARGET_CPA',
'Target ROAS': 'TARGET_ROAS',
'Maximize Conversions': 'MAXIMIZE_CONVERSIONS',
'Maximize Conversion Value': 'MAXIMIZE_CONVERSION_VALUE',
'Target Outranking Share': 'TARGET_OUTRANK_SHARE'
};
// Indices
var INPUT_HEADER_ROW = 1;
var INPUT_DATA_ROW = 3;
var OUTPUT_HEADER_ROW = 2;
//////////////////////////////////////////////////////////////////////////////
// Functions
function main() {
var spreadsheet = getSpreadsheet(SPREADSHEET_URL);
var inputSheet = spreadsheet.getSheetByName("Input");
var outputSheet = spreadsheet.getSheetByName("Output");
var tz = AdsApp.currentAccount().getTimeZone();
//Store Sheet Headers and Indices
var inputHeaders = inputSheet.getRange(INPUT_HEADER_ROW + ":" + INPUT_HEADER_ROW).getValues()[0];
var statusColumnIndex = inputHeaders.indexOf("Status");
var accountIDColumnIndex = inputHeaders.indexOf("Account ID");
var accountNameColumnIndex = inputHeaders.indexOf("Account Name")
var biddingStrategyColumnIndex = inputHeaders.indexOf("Bidding Strategy");
var campaignNameContainsIndex = inputHeaders.indexOf("Campaign Name Contains");
var campaignNameDoesNotContainIndex = inputHeaders.indexOf("Campaign Name Doesn't Contain");
var contactEmailsColumnIndex = inputHeaders.indexOf("Contact email(s)")
var startDateColumnIndex = inputHeaders.indexOf("Start Date");
var endDateColumnIndex = inputHeaders.indexOf("End Date");
var outputHeaders = outputSheet.getRange(OUTPUT_HEADER_ROW + ":" + OUTPUT_HEADER_ROW).getValues()[0];
var timeRunIndex = outputHeaders.indexOf("Time Run");
//Get all rows of data.
var allData = inputSheet.getRange(INPUT_DATA_ROW, 1, inputSheet.getLastRow() - (INPUT_HEADER_ROW + 1), inputSheet.getLastColumn()).getValues();
//For each row of data:
Logger.log("Verifying each row of data...")
for (var i = 0; i < allData.length; i++) {
var row = allData[i];
if (row[statusColumnIndex] == "Paused") {
continue;
};
var accountName = row[accountNameColumnIndex];
var contacts = (row[contactEmailsColumnIndex]).split(',').map(function(item){
return item.trim();
});
var childAccount = getAccountId(row[accountIDColumnIndex], contacts, accountName);
AdsManagerApp.select(childAccount);
var dates = getDates([row[startDateColumnIndex], row[endDateColumnIndex]], tz, contacts, accountName);
var combinedQueries = makeQueries(dates, row[campaignNameContainsIndex], row[campaignNameDoesNotContainIndex],row[biddingStrategyColumnIndex])
var dataRow = getMetricsforRow(combinedQueries, contacts, accountName);
var outputRows = [];
outputRows = [row[accountNameColumnIndex], row[accountIDColumnIndex], row[biddingStrategyColumnIndex]]
.concat(dataRow.map(function (data) {
return data.value
}));
writeRows(outputSheet, outputRows);
setDate(outputSheet, timeRunIndex);
}
Logger.log("Success.")
}
function getSpreadsheet(spreadsheetUrl) {
Logger.log('Checking spreadsheet: ' + SPREADSHEET_URL + ' is valid.');
if (spreadsheetUrl.replace(/[AEIOU]/g, "X") == "https://docs.google.com/YXXR-SPRXXDSHXXT-XRL-HXRX") {
throw ("Problem with " + SPREADSHEET_URL +
" URL: make sure you've replaced the default with a valid spreadsheet URL."
);
}
try {
var spreadsheet = SpreadsheetApp.openByUrl(spreadsheetUrl);
var sheet = spreadsheet.getSheets()[0];
var sheetName = sheet.getName();
sheet.setName(sheetName);
return spreadsheet;
} catch (e) {
throw ("Problem with " + SPREADSHEET_URL + " URL: '" + e + "'. You may not have edit access");
}
}
function getAccountId(accountId, contacts, accountName) {
var childAccount = AdsManagerApp.accounts().withIds([accountId]).get();
if (childAccount.hasNext()) {
return childAccount.next();
}
else {
MailApp.sendEmail({
to: contacts.join(),
subject: "Bid Strategy Performance Monitor: error with account " + accountName,
htmlBody: "Could not find account with ID: " + accountId + "."
});
throw ("Could not find account with ID: " + accountId);
}
}
function getDates(dates, tz, contacts, accountName) {
var validatedDates = dates.map(function (date) {
if (date.length === 0) {
var today = new Date()
return Utilities.formatDate(today, tz, 'yyyyMMdd');
}
else {
return Utilities.formatDate(new Date(date), tz, 'yyyyMMdd');
}
})
if (validatedDates[0] <= validatedDates[1]) {
return validatedDates;
}
else {
MailApp.sendEmail({
to: contacts.join(),
subject: "Bid Strategy Performance Monitor: error with account " + accountName,
htmlBody: ("Invalid date ranges (yyyMMdd): End Date: "
+ validatedDates[1] + " precedes Start date: " + validatedDates[0])
})
throw ("Invalid date ranges: End Date precedes Start Date.");
}
}
function makeQueries(dates, campaignNameContains, campaignNameDoesNotContain, biddingStrategy){
var campaignNameContains = campaignNameContains.split(',').map(function(item){
return item.trim();
});
var campaignNameDoesNotContain = campaignNameDoesNotContain.split(',').map(function(item){
return item.trim();
});
var campaignFilterQueries = makeCampaignFilterStatements(campaignNameContains, campaignNameDoesNotContain, ignorePausedCampaigns);
var biddingStrategyQuery = makeBiddingStrategyStatement((biddingStrategy));
var combinedQueries = combineQueries(dates, biddingStrategyQuery, campaignFilterQueries);
return combinedQueries;
}
function makeCampaignFilterStatements(campaignNameContains, campaignNameDoesNotContain, ignorePausedCampaigns) {
var whereStatement = "WHERE ";
var whereStatementsArray = [];
if (ignorePausedCampaigns) {
whereStatement += "CampaignStatus = ENABLED ";
} else {
whereStatement += "CampaignStatus IN ['ENABLED','PAUSED'] ";
}
for (var i = 0; i < campaignNameDoesNotContain.length; i++) {
if (campaignNameDoesNotContain == ""){
break;;
}
else {
whereStatement += "AND CampaignName DOES_NOT_CONTAIN_IGNORE_CASE '"
+ campaignNameDoesNotContain[i].replace(/"/g, '\\\"') + "' ";
}
}
if (campaignNameContains.length == 0) {
whereStatementsArray = [whereStatement];
}
else {
for (var i = 0; i < campaignNameContains.length; i++) {
whereStatementsArray.push(whereStatement + 'AND CampaignName CONTAINS_IGNORE_CASE "'
+ campaignNameContains[i].replace(/"/g, '\\\"') + '" '
);
}
}
return whereStatementsArray;
}
function makeBiddingStrategyStatement(biddingStrategy) {
if (biddingStrategy.length === 0) {
return ""
}
else {
for (var key in BIDDING_STRATEGIES) {
if (key == biddingStrategy) {
return " AND BiddingStrategyType = " + BIDDING_STRATEGIES[key]
};
}
}
};
function combineQueries(dates, biddingStrategyQuery, campaignFilterQueries) {
var combinedQueries = []
for (var i = 0; i < campaignFilterQueries.length; i++) {
combinedQueries.push(campaignFilterQueries[i]
.concat(biddingStrategyQuery + " DURING " + dates[0] + "," + dates[1]
));
}
return combinedQueries;
}
function getMetricsforRow(queries, contacts, accountName) {
var ReportRows = getMetricsforSettings(queries, contacts, accountName);
return ReportRows;
}
function getMetricsforSettings(queries, contacts, accountName) {
var metricCounter = makeEmptyMetricCounter()
var totalCampaignCount = 0;
for (var i = 0; i < queries.length; i++) {
var singleCampaignCount = 0
var report = AdsApp.report(
"SELECT " + METRICS.map(function (field) {
return field;
}).join(',') + " FROM CAMPAIGN_PERFORMANCE_REPORT " + queries[i]
);
var rows = report.rows();
if (rows.hasNext() === false) {
MailApp.sendEmail({
to: contacts.join(),
subject: "Bid Strategy Performance Monitor: error with account " + accountName,
htmlBody: "No campaigns found with the given settings: " + queries[i]
});
}
while (rows.hasNext()) {
singleCampaignCount = parseInt(singleCampaignCount) + parseInt(1);
var row = rows.next();
metricCounter.map(function (metric) {
metric.value = parseFloat(metric.value) + (parseFloat((row[metric.name])) || 0);
return metric.value;
});
}
totalCampaignCount = parseInt(totalCampaignCount) + parseInt(singleCampaignCount)
}
metricCounter.push({name: "Total Campaigns", value: totalCampaignCount})
return metricCounter;
function makeEmptyMetricCounter() {
var metricCounter = [];
metricCounter.push(METRICS.map(function (field) {
return {name: field, value: 0};
}));
return metricCounter[0];
}
}
function writeRows(sheet, rows) {
for (var i = 0; i < 5; i++) {
try {
sheet.getRange((sheet.getLastRow() + 1), 1, 1, rows.length).setValues([rows]);
break;
} catch (e) {
if (e == "Exception: This action would increase the number of cells in the worksheet above the limit of 2000000 cells.") {
Logger.log("Could not write to spreadsheet: '" + e + "'");
try {
sheet.getRange("R" + (sheet.getLastRow() + 2) + "C1")
.setValue("Not enough space to write the data - try again in an empty spreadsheet");
} catch (e2) {
Logger.log("Error writing 'not enough space' message: " + e2);
}
break;
}
if (i == 4) {
Logger.log("Could not write to spreadsheet: '" + e + "'");
}
}
}
}
function setDate(sheet, columnIndex) {
var now = new Date();
sheet.getRange((sheet.getLastRow()), columnIndex + 1).setValue(now);
}