Advertisement
Guest User

Ads Budżet

a guest
Jan 28th, 2020
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function main() {
  2.   var WARNING_PERCENTAGE_CAP = 95;  
  3.   //Ustaw procent budżetu, którego przekroczenie zatrzyma kampenie
  4.   // -1 for all values including 0
  5.   // The percentage of a campaign's budget that needs to have been spent for
  6.   // the tool to consider that campaign over cap and warn about it.
  7.  
  8.   var EMAILS = ['name@example.com'];
  9.   // The email address you want the hourly update to be sent to.
  10.   // If you'd like to send to multiple addresses then have them separated by commas,
  11.   // for example ["aa@example.com", "bb@example.com"]
  12.  
  13.   var CAMPAIGN_NAME_CONTAINS = [];
  14.   //Bierz pod uwagę tylko kampanie o okreśłonych nazwach
  15.   // Use this if you only want to look at some campaigns.
  16.   // For example ["Generic"] would only look at campaigns with 'generic' in the name,
  17.   // while ["Generic", "Competitor"] would only look at campaigns with either
  18.   // 'generic' or 'competitor' in the name.
  19.   // Leave as [] to include all campaigns.
  20.  
  21.   var CAMPAIGN_NAME_EXCLUDES = [];
  22.   //Wyklucz kampanie o okreśłonych nazwach
  23.   // Use this if you want to exclude some campaigns.
  24.   // For example ["Brand"] would ignore any campaigns with 'brand' in the name,
  25.   // while ["Brand", "Key Terms"] would ignore any campaigns with 'brand' or
  26.   // 'key terms' in the name.
  27.   // Leave as [] to not exclude any campaigns.
  28.  
  29.   //This is a helper function to create the label if it does not already exist
  30.  
  31.   try {
  32.     var campaigns = getCampaigns(CAMPAIGN_NAME_CONTAINS, CAMPAIGN_NAME_EXCLUDES);  
  33.     var overCap = getOverCap(WARNING_PERCENTAGE_CAP, campaigns);
  34.  
  35.     if(overCap.length > 0) {
  36.       alert(overCap, EMAILS);
  37.     }
  38.  
  39.   } catch(e) {
  40.     alertError(e, EMAILS);
  41.   }
  42. }
  43.  
  44. function getCampaigns(campNameContains, campNameExcludes) {
  45.   var campaigns = {};
  46.   var whereStatementsArray = buildWhereStatements(campNameContains, campNameExcludes);
  47.   for (var i = 0; i < whereStatementsArray.length; i++) {
  48.     var query = "SELECT CampaignId, Date, Cost, Amount, CampaignName, CampaignStatus" +
  49.       " FROM CAMPAIGN_PERFORMANCE_REPORT " +
  50.       whereStatementsArray[i] +
  51.       "DURING TODAY";
  52.     var rows = AdWordsApp.report(query).rows();
  53.     while (rows.hasNext()) {
  54.       var campaign = campaignFromRow(rows.next());
  55.       campaigns[campaign.id] = campaign;
  56.     }
  57.   }
  58.   return campaigns;
  59. }
  60.  
  61. function buildWhereStatements(campNameContains, campNameExlcudes) {
  62.   var whereStatement = "WHERE CampaignStatus IN ['ENABLED'] "; //['ENABLED','PAUSED']
  63.   for (var i = 0; i < campNameExlcudes.length; i++) {
  64.     whereStatement += "AND CampaignName DOES_NOT_CONTAIN_IGNORE_CASE '"
  65.     + campNameExlcudes[i].replace(/"/g,'\\\"') + "' ";
  66.   }
  67.   var whereStatementsArray = [];
  68.   if (campNameContains.length == 0) {
  69.     whereStatementsArray = [whereStatement];
  70.   } else {
  71.     for (var i = 0; i < campNameContains.length; i++) {
  72.       whereStatementsArray.push(whereStatement + 'AND CampaignName CONTAINS_IGNORE_CASE "'
  73.       + campNameContains[i].replace(/"/g,'\\\"') + '" ');
  74.     }
  75.   }
  76.   return whereStatementsArray;
  77. }
  78.  
  79. function campaignFromRow(reportRow) {
  80.   var obj = {};
  81.   obj.id = reportRow["CampaignId"];
  82.   obj.name = reportRow["CampaignName"];
  83.   obj.budget = reportRow["Amount"];
  84.   obj.spend = reportRow["Cost"];
  85.  
  86.   if(reportRow["CampaignStatus"] == 'enabled') {
  87.       obj.status = 'Włączona';
  88.   } else {
  89.       obj.status = 'Zatrzymana';
  90.   }
  91.  
  92.   obj.spent = function() {
  93.     return 100 * (1 - (obj.budget - obj.spend)/obj.budget);
  94.   }
  95.   obj.overSpendCap = function(cap) {
  96.     return obj.spent() > cap;
  97.   }
  98.   return obj;
  99. }
  100.  
  101. function createLabelIfNeeded(labelName) {
  102.   if(!AdsApp.labels().withCondition('Name = "' + labelName + '"').get().hasNext()) {
  103.     AdsApp.createLabel(labelName);
  104.     Logger.log('Etykieta dodana.');
  105.   } else {
  106.     Logger.log('Etykieta już istnieje.');
  107.   }
  108. }
  109.  
  110. function applyLabelAndPause(campaignId) {
  111.   var label = 'Przekroczony budżet';
  112.   createLabelIfNeeded(label);
  113.  
  114.   // Retrieve a campaign, and apply a label to it. Applying labels to other
  115.   // object types are similar.
  116.   var campaignIterator = AdsApp.campaigns()
  117.       .withIds([campaignId])
  118.       .get();
  119.   if (campaignIterator.hasNext()) {
  120.  
  121.     var campaign = campaignIterator.next();
  122.     campaign.applyLabel(label);
  123.     campaign.pause();
  124.  
  125.     Logger.log('dodano etykietę do kampanii ' + campaignId);
  126.   } else {
  127.     Logger.log('Nie znalazł kampanii po ID ' + campaignId);
  128.   }
  129. }
  130.  
  131. function getOverCap(cap, campaigns) {
  132.   var overCap = [];
  133.   for (var campaignId in campaigns) {
  134.     var campaign = campaigns[campaignId];
  135.     if (campaign.overSpendCap(cap)) {
  136.       //add label and pause the campaign
  137.       applyLabelAndPause(campaign.id);
  138.  
  139.       //change status for campaign object
  140.       campaign.status = 'Zatrzymana do 00:00';
  141.       overCap.push(campaign);
  142.     }
  143.   }
  144.   return overCap;
  145. }
  146.  
  147. function alert(campaigns, EMAILS) {
  148.   var subject = AdWordsApp.currentAccount().getName() + " - dzienny raport wydatków";
  149.   var message = buildTable(campaigns);
  150.  
  151.   MailApp.sendEmail({
  152.     to: EMAILS.join(','),
  153.     subject: subject,
  154.     htmlBody: message
  155.   });
  156. }
  157.  
  158. function buildTable(campaigns) {
  159.   var table = "<table border=1 style='border: 1px solid black; border-collapse: collapse;'>";
  160.   table += "<tr><th>ID</th><th>Kampania</th><th>Budżet</th><th>Wydatki</th><th>Wydatki %</th><th>Status</th></tr>";
  161.   for (var campaignId in campaigns) {
  162.     var campaign = campaigns[campaignId];
  163.     table += "<tr><td>" + campaign.id + "</td>";
  164.     table += "<td>" + campaign.name + "</td>";
  165.     table += "<td>" + campaign.budget + "zł</td>";
  166.     table += "<td>" + campaign.spend + "zł</td>";
  167.     table += "<td>" + campaign.spent().toFixed(2) + "%</td>";
  168.     table += "<td>" + campaign.status + "</td>";
  169.     table += "</tr>";
  170.   }
  171.   table += "</table>";
  172.   return table;
  173. }
  174.  
  175. function alertError(error, emails) {
  176.   MailApp.sendEmail(
  177.     emails.join(','),
  178.     'Budget Script - Error',
  179.     error);
  180. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement