-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcampaign-budget-overspend-monitoring.js
More file actions
375 lines (321 loc) · 12.9 KB
/
campaign-budget-overspend-monitoring.js
File metadata and controls
375 lines (321 loc) · 12.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
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
// ID: 9603512cc806b0a3cdbe3cbe8d1c8908
/**
*
* Campaign Budget Overspend Monitoring
*
* This script labels campaigns whose spend today is more than their daily
* budgets. Optionally, it also pauses campaigns whose spend exceeds the
* budget by too much. An email is then sent, listing the newly labelled
* and paused campaigns.
* When spend no longer exceeds budget, the campaigns are reactivated and
* labels are removed.
*
* Version: 1.0
* Google AdWords Script maintained on brainlabsdigital.com
*
*/
// ////////////////////////////////////////////////////////////////////////////
// Options
var campaignNameContains = [];
// Use this if you only want to look at some campaigns.
// For example ["Generic"] would only look at campaigns with 'generic' in the name,
// while ["Generic", "Competitor"] would only look at campaigns with either
// 'generic' or 'competitor' in the name.
// Leave as [] to include all campaigns.
var campaignNameDoesNotContain = [];
// Use this if you want to exclude some campaigns.
// For example ["Brand"] would ignore any campaigns with 'brand' in the name,
// while ["Brand", "Key Terms"] would ignore any campaigns with 'brand' or
// 'key terms' in the name.
// Leave as [] to not exclude any campaigns.
var email = ['youremail@domain.com'];
// The email address you want the hourly update to be sent to.
// If you'd like to send to multiple addresses then have them separated by commas,
// for example ["aa@example.com", "bb@example.com"]
var currencySymbol = '£';
// Used for formatting in the email.
var thousandsSeparator = ',';
// Numbers will be formatted with this as the thousands separator.
// eg If this is ",", 1000 will appear in the email as 1,000
// If this is ".", 1000 will appear in the email as 1.000
// If this is "" 1000 will appear as 1000.
var decimalMark = '.';
// Numbers will be formatted with this as the decimal mark
// eg if this is ".", one and a half will appear in the email as 1.5
// and if this is "," it will be 1,5
var labelThreshold = 1.0;
// This is multiplied by the campaign's daily budget to create a threshold.
// If the campaign spend is higher than the threshold, it will be labelled
// (and you will be emailed).
// For example if labelThreshold = 1.0 then campaigns are labelled when
// their spend is greater than or equal to their budget.
var labelName = 'Over Budget';
// The name of the label you want to apply to campaigns that have gone
// over budget.
var campaignPauser = false;
// Set this to true to pause campaigns if spend exceeds the pauseThreshold.
// Set to false if campaigns are to be kept enabled.
var pauseThreshold = 1.2;
// This is multiplied by the campaign's daily budget to create a threshold.
// If campaignPauser is true and the campaign spend is higher than this threshold,
// it will be paused (and you will be emailed).
// For example if pauseThreshold = 1.2 then campaigns are paused when
// their spend is greater than or equal to 120% of their budget.
// pauseThreshold MUST be greater than or equal to the labelThreshold, so that all
// campaigns that the script pauses are also labelled.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Functions
function main() {
checkInputs();
// Get the campaign IDs (based on campaignNameDoesNotContain and campaignNameContains)
var campaignData = getCampaignIds();
var campaignsToAddLabel = [];
var campaignsToRemoveLabel = [];
var campaignsToPause = [];
var campaignsToEnable = [];
for (var campaignId in campaignData) {
var currentCampaign = campaignData[campaignId];
var budget = currentCampaign.Budget;
var status = currentCampaign.CampaignStatus;
var spend = currentCampaign.Spend;
var label = currentCampaign.Labels;
var pauseBudgetCap = pauseThreshold * budget;
var labelBudgetCap = labelThreshold * budget;
if (status == 'enabled' && label.indexOf('"' + labelName + '"') == -1) {
if (spend >= labelBudgetCap) {
campaignsToAddLabel.push(currentCampaign);
}
}
if (status == 'enabled') {
if (spend >= pauseBudgetCap) {
campaignsToPause.push(currentCampaign);
}
}
if (status == 'paused' && label.indexOf('"' + labelName + '"') != -1) {
if (spend <= pauseBudgetCap) {
campaignsToEnable.push(currentCampaign);
}
}
if (status == 'enabled' && label.indexOf('"' + labelName + '"') != -1) {
if (spend <= labelBudgetCap) {
campaignsToRemoveLabel.push(currentCampaign);
}
}
}
// Change and update campaigns
if (campaignsToEnable.length > 0 && campaignPauser === true) {
Logger.log(campaignsToEnable.length + ' campaigns to enable');
enableCampaigns(campaignsToEnable);
}
if (campaignsToRemoveLabel.length > 0) {
Logger.log(campaignsToRemoveLabel.length + ' campaigns to unlabel');
removeLabel(campaignsToRemoveLabel);
}
if (campaignsToAddLabel.length > 0) {
Logger.log(campaignsToAddLabel.length + ' campaigns to label');
addLabel(campaignsToAddLabel);
}
if (campaignsToPause.length > 0 && campaignPauser === true) {
Logger.log(campaignsToPause.length + ' campaigns to pause');
pauseCampaigns(campaignsToPause);
}
// Send an email, if actions were taken
sendSummaryEmail(campaignsToAddLabel, campaignsToPause, campaignPauser, email);
}
// Check the inputs
function checkInputs() {
if (!isValidNumber(labelThreshold)) {
throw "labelThreshold '" + labelThreshold + "' is not a valid, positive number.";
}
if (labelThreshold > 2) {
Logger.log("Warning: labelThreshold '" + labelThreshold + "' is greater than 2. As AdWords does not spend more than twice the budget, this threshold will not be reached.");
}
if (campaignPauser) {
if (!isValidNumber(pauseThreshold)) {
throw "pauseThreshold '" + pauseThreshold + "' is not a valid, positive number.";
}
if (pauseThreshold < labelThreshold) {
throw "pauseThreshold '" + pauseThreshold + "' is less than labelThreshold '" + labelThreshold + "'. It should be greater than or equal to labelThreshold.";
}
if (pauseThreshold > 2) {
Logger.log("Warning: pauseThreshold '" + pauseThreshold + "' is greater than 2. As AdWords does not spend more than twice the budget, this threshold will not be reached.");
}
}
}
// Checks the input is a number that's finite and greater than zero
function isValidNumber(number) {
var isANumber = !isNaN(number) && isFinite(number);
var isPositive = number > 0;
return isANumber && isPositive;
}
// Get the IDs of campaigns which match the given options
function getCampaignIds() {
var whereStatement = "WHERE CampaignStatus IN ['ENABLED','PAUSED'] ";
var whereStatementsArray = [];
var campData = {};
for (var i = 0; i < campaignNameDoesNotContain.length; i++) {
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, '\\\"') + '" ');
}
}
for (var i = 0; i < whereStatementsArray.length; i++) {
var report = AdWordsApp.report(
'SELECT CampaignId, CampaignName, CampaignStatus, Amount, Labels, LabelIds, Cost '
+ 'FROM CAMPAIGN_PERFORMANCE_REPORT '
+ whereStatementsArray[i]
+ "AND AdvertisingChannelType IN ['SEARCH', 'DISPLAY'] "
+ 'DURING TODAY'
);
var rows = report.rows();
while (rows.hasNext()) {
var row = rows.next();
var budget = parseFloat(row.Amount.replace(/,/g, ''));
var spend = parseFloat(row.Cost.replace(/,/g, ''));
var campaignId = row.CampaignId;
campData[campaignId] = {
CampaignId: campaignId,
CampaignName: row.CampaignName,
CampaignStatus: row.CampaignStatus,
Spend: spend,
Budget: budget,
Labels: row.Labels,
LabelId: row.LabelIds
};
}
}
var campaignIds = Object.keys(campData);
if (campaignIds.length == 0) {
throw ('No campaigns found with the given settings.');
}
Logger.log(campaignIds.length + ' campaigns found');
return campData;
}
// Create the label if it doesn't exist, and return its ID.
// (Returns a dummy ID if the label does not exist and this is a preview run,
// because we can't create or apply the label)
function getOrCreateLabelId(labelName) {
var labels = AdWordsApp.labels().withCondition("Name = '" + labelName + "'").get();
if (!labels.hasNext()) {
AdWordsApp.createLabel(labelName);
labels = AdWordsApp.labels().withCondition("Name = '" + labelName + "'").get();
}
if (AdWordsApp.getExecutionInfo().isPreview() && !labels.hasNext()) {
var labelId = 0;
} else {
var labelId = labels.next().getId();
}
return labelId;
}
// Pause Campaigns
function pauseCampaigns(campaignData) {
for (j = 0; j < campaignData.length; j++) {
var campaignIterator = AdWordsApp.campaigns()
.withCondition('CampaignId = ' + campaignData[j].CampaignId)
.get();
if (campaignIterator.hasNext()) {
var campaign = campaignIterator.next();
campaign.pause();
campaignData[j].CampaignStatus = 'paused';
}
}
}
// Enable Campaigns that were paused
function enableCampaigns(campaignData) {
for (j = 0; j < campaignData.length; j++) {
var campaignIterator = AdWordsApp.campaigns()
.withCondition('CampaignId = ' + campaignData[j].CampaignId)
.get();
if (campaignIterator.hasNext()) {
var campaign = campaignIterator.next();
campaign.enable();
campaignData[j].CampaignStatus = 'enabled';
}
}
}
// Add Labels to campaigns
function addLabel(campaignData) {
for (j = 0; j < campaignData.length; j++) {
var campaign = AdWordsApp.campaigns()
.withCondition('CampaignId = ' + campaignData[j].CampaignId).get().next();
getOrCreateLabelId(labelName);
campaign.applyLabel(labelName);
}
}
// Remove Labels from campaigns
function removeLabel(campaignData) {
for (j = 0; j < campaignData.length; j++) {
var campaign = AdWordsApp.campaigns()
.withCondition('CampaignId = ' + campaignData[j].CampaignId).get().next();
campaign.removeLabel(labelName);
}
}
// Combines information on labelled and paused campaigns and emails this
function sendSummaryEmail(campaignsToAddLabel, campaignsToPause, campaignPauser, email) {
var localDate = Utilities.formatDate(new Date(), AdWordsApp.currentAccount().getTimeZone(), 'yyyy-MM-dd');
var localTime = Utilities.formatDate(new Date(), AdWordsApp.currentAccount().getTimeZone(), 'HH:mm');
// Assemble the email message
var subject = AdWordsApp.currentAccount().getName() + ' - Budget Overspend Email';
var message = '';
message += makeChangeMessage(campaignsToAddLabel, 'labelled');
if (campaignPauser) {
message += makeChangeMessage(campaignsToPause, 'paused');
}
if (message == '') {
Logger.log('No message to send.');
return;
}
message = localDate + ' at ' + localTime + ' :' + message;
MailApp.sendEmail({
to: email.join(','),
subject: subject,
htmlBody: message
});
Logger.log('Message to ' + email.join(',') + ' sent.');
}
// Turns campaign data into an HTML table
function makeChangeMessage(campaignData, changed) {
if (campaignData.length == 0) {
return '';
}
var message = '<br><br>Campaigns that have been ' + changed + '<br><br>';
var table = "<table border=1 style='border: 1px solid black; border-collapse: collapse;'>";
table += '<tr><th>Campaign ID</th><th>Campaign Name</th><th>Status</th><th>Spend</th><th>Budget</th></tr>';
for (var k = 0; k < campaignData.length; k++) {
table += '<tr><td>' + campaignData[k].CampaignId + '</td><td>' + campaignData[k].CampaignName + '</td><td>'
+ campaignData[k].CampaignStatus + '</td><td>' + formatNumber(campaignData[k].Spend, true) + '</td><td>' + formatNumber(campaignData[k].Budget, true) + '</td>';
table += '</tr>';
}
table += '</table>';
message += table;
return message;
}
// Formats a number with the specified thousand separator and decimal mark
// Adds the currency symbol and two decimal places if isCurrency is true
function formatNumber(number, isCurrency) {
if (isCurrency) {
var formattedNumber = number.toFixed(2);
formattedNumber = formattedNumber.substr(0, formattedNumber.length - 3);
formattedNumber = formattedNumber.split('').reverse().join('').replace(/(...)/g, '$1 ')
.trim()
.split('')
.reverse()
.join('')
.replace(/ /g, thousandsSeparator);
formattedNumber = currencySymbol + formattedNumber + decimalMark + number.toFixed(2).substr(-2);
} else {
var formattedNumber = number.toFixed(0).split('').reverse().join('')
.replace(/(...)/g, '$1 ')
.trim()
.split('')
.reverse()
.join('')
.replace(/ /g, thousandsSeparator);
}
return formattedNumber;
}