Skrypt Google Ads: GA Performance Checker (7 Days)

Skrypt GA Performance Checker (1 Day) okazał się najpopularniejszym rozwiązaniem do tej pory. W związku tym przygotowałem jego drugą wersję.

Tym razem skrypt sprawdzi ostatnie 7 dni oraz poprzedni okres.

Dłuższy zakres czasowy pozwoli uzyskać lepszy obraz wyników ze wszystkich kanałów. Całość zostanie wysłana w formie tabeli na wskazany adres e-mail.

Przykład:

Legenda:
Kolor zielony: wzrost względem poprzedniego tygodnia
Kolor żółty: wynika taki sam jak w poprzednim tygodniu
Kolor czerwony: spadek względem poprzedniego tygodnia

Konfiguracja:
1. Wprowadź ID wybranego widoku Google Analytics (administracja -> ustawienia widoku -> Identyfikator widoku danych) do zmiennej ANALYTICS_VIEW_ID
2. Wprowadź swój e-mail do zmiennej EMAIL
3. Wprowadź nazwę (dowolną, zostanie dodana w nagłówku tabeli) konta do zmiennej ACCOUNT_NAME
3. W zaawansowanych ustawieniach włącz „Analytics„:
https://developers.google.com/google-ads/scripts/docs/features/advanced-apis

Harmonogram: raz na tydzień, w godzinach porannych


Po więcej na temat Skryptów zapraszam na grupę FB:
https://www.facebook.com/groups/zaawansowane.google.ads


/*

Copyright 2020 Krzysztof Bycina, www.LiveAds.pl
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/

// --------------------------------------- Configuration:

var EMAIL = "YOUR EMAIL";
var ACCOUNT_NAME = "YOUR STORE NAME";
var ANALYTICS_VIEW_ID = "YOUR VIEW ID";

// --------------------------------------- End of the configuration


//Prepare the dates:
var MILLIS_PER_DAY = 1000 * 60 * 60 * 24;
var now = new Date();
var sevenDays = new Date(now.getTime() - 7 * MILLIS_PER_DAY);
var sevenDaysAgo = formatDate(sevenDays, "yyyy-MM-dd");
var fourteenDays = new Date(now.getTime() - 14 * MILLIS_PER_DAY);
var fourteenDaysAgo = formatDate(fourteenDays, "yyyy-MM-dd");
var eightDays = new Date(now.getTime() - 8 * MILLIS_PER_DAY);
var eightDaysAgo = formatDate(eightDays, "yyyy-MM-dd");
var yesterday = new Date(now.getTime() - 1 * MILLIS_PER_DAY);
var yesterdaysDate = formatDate(yesterday, "yyyy-MM-dd");

function main() {

    //Prepare the HTML tabel
    var htmlData = prepareHTML();

    //Get the data from Google Analytics for previous seven days
    var previousSevenDays = fetchTheData(fourteenDaysAgo, eightDaysAgo);

    //Get the data from Google Analytics for last seven days
    var lastSevenDays = fetchTheData(sevenDaysAgo, yesterdaysDate);

    //Write the Google Analytics data to the HTML format
    htmlData = writeTheDataToHtml(lastSevenDays, previousSevenDays, htmlData);

    //Check if there are differences in the number of channels & write missing data to the HTML format
    if (previousSevenDays.length > lastSevenDays.length) {
        var metricDifference = findMetricDifference(previousSevenDays, lastSevenDays);
        htmlData = writeDifferenceToHtml(metricDifference, htmlData);
    }
  
    //Sum and write the metrics to the HTML format
    htmlData = writeSumToHtml(previousSevenDays, lastSevenDays, htmlData);
  
    //Close the HTML tags:
    htmlData.push('</table>', '</body>', '</html>');

  
        //Send the email:
        sendEmails(htmlData);
    }

    function fetchTheData(startDate, endDate) {
        Logger.log("Google Analytics import was made for START: " + startDate + " END: " + endDate);
        var results = Analytics.Data.Ga.get(
            'ga:' + ANALYTICS_VIEW_ID,
            startDate,
            endDate,
            'ga:transactions,ga:users', {
                'dimensions': 'ga:channelGrouping',
            }
        );
        return results.rows;
    }

    function writeTheDataToHtml(lastSevenDays, previousSevenDays, htmlData) {
        for (i = 0; i < previousSevenDays.length; i++) {
            for (j = 0; j < lastSevenDays.length; j++) {
                if (previousSevenDays[i][0].indexOf(lastSevenDays[j][0]) !== -1) {
                    htmlData.push('<tr>', " <td style='padding: 0px 5px'>" + lastSevenDays[j][0] + '</td>',
                        "<td style='padding: 0px 5px; background-color:" + findColor(lastSevenDays[j][1], previousSevenDays[i][1]) + "'>" + lastSevenDays[j][1] + '</td>',
                        "<td style='padding: 0px 5px; background-color:" + findColor(lastSevenDays[j][2], previousSevenDays[i][2]) + "'>" + lastSevenDays[j][2] + '</td>',
                        "<td style='padding: 0px 5px; background-color:" + findColor(previousSevenDays[j][1], lastSevenDays[i][1]) + "'>" + previousSevenDays[i][1] + '</td>',
                        "<td style='padding: 0px 5px; background-color:" + findColor(previousSevenDays[j][2], lastSevenDays[i][2]) + "'>" + previousSevenDays[i][2] + '</td>', '</tr>');

                }

            }
        }
        return htmlData;
    }

    function writeDifferenceToHtml(metricDifference, htmlData) {
        htmlData.push('<tr>', "<td style='padding: 0px 5px'>" + metricDifference[0][0] + '</td>',
            "<td style='padding: 0px 5px; background-color:" + findColor(0, metricDifference[0][1]) + "'>" + "0" + '</td>',
            "<td style='padding: 0px 5px; background-color:" + findColor(0, metricDifference[0][2]) + "'>" + "0" + '</td>',
            "<td style='padding: 0px 5px; background-color:" + findColor(metricDifference[0][1], 0) + "'>" + metricDifference[0][1] + '</td>',
            "<td style='padding: 0px 5px; background-color:" + findColor(metricDifference[0][2], 0) + "'>" + metricDifference[0][2] + '</td>', '</tr>');
        return htmlData;
    }

    function writeSumToHtml(previousSevenDays, lastSevenDays, htmlData) {
        htmlData.push('<tr>', "<td style='padding: 0px 5px; font-size: large; font-weight: bold'>Total:</td>",
                        "<td style='padding: 0px 5px; font-size: large; font-weight: bold; background-color:" + findColor(sumMetrics(lastSevenDays,1), sumMetrics(previousSevenDays,1)) + "'>" + sumMetrics(lastSevenDays,1) + '</td>',
                        "<td style='padding: 0px 5px; font-size: large; font-weight: bold; background-color:" + findColor(sumMetrics(lastSevenDays,2), sumMetrics(previousSevenDays,2)) + "'>" + sumMetrics(lastSevenDays,2) + '</td>',
                        "<td style='padding: 0px 5px; font-size: large; font-weight: bold; background-color:" + findColor(sumMetrics(previousSevenDays,1), sumMetrics(lastSevenDays,1)) + "'>" + sumMetrics(previousSevenDays,1) + '</td>',
                        "<td style='padding: 0px 5px; font-size: large; font-weight: bold; background-color:" + findColor(sumMetrics(previousSevenDays,2), sumMetrics(lastSevenDays,2)) + "'>" + sumMetrics(previousSevenDays,2) + '</td>','</tr>');
        return htmlData;
    }


    function prepareHTML() {
        var theHTML = [];
        theHTML.push(
            "<html>",
            "<body> ",
                "<table width=700 cellpadding=0 border=1 cellspacing=0>",
                    "<tr>",
                        "<td colspan=5 align=right style='padding: 0px 5px; font-size: small'>Developed by <a href='https://www.Li" +
            "veAds.pl?utm_source=ga_performance&utm_medium=email&utm_campaign=daily' target='_blank'>www.LiveAds.pl</a></td>",
                        "</tr>",
                    "<tr bgcolor='#3c78d8'>",
                        "<td colspan=5 style='font: normal 18pt verdana, sans-serif; padding: 3px 10px; color: white; background-color:#3366ff'>" + ACCOUNT_NAME + " Analytics Summary</div>",
                            "</td>",
                        "</tr>",
                    "<tr>",
                        "<td></td>",
                        "<td colspan='2' style='text-align: center; font-size: x-large'>Last 7 Days:</td>",
                        "<td colspan='2' style='text-align: center; font-size: x-large'>Previous 7 Days:</td>",
                        '</tr>',
                    "<tr>",
                        "<td style='padding: 0px 5px; font-size: large; font-weight: bold'>Channel:</td>",
                        "<td style='padding: 0px 5px; font-size: large; font-weight: bold'>Transactions:</td>",
                        "<td style='padding: 0px 5px; font-size: large; font-weight: bold'>Users:</td>",
                        "<td style='padding: 0px 5px; font-size: large; font-weight: bold'>Transactions:</td>",
                        "<td style='padding: 0px 5px; font-size: large; font-weight: bold'>Users:</td>"
        );
        return theHTML;
    }


    function sumMetrics(data, position) {
      var sum = 0;
      data.forEach(function(channel) {
           sum += parseInt(channel[position]);
        });
      return sum;
    }

    function formatDate(date, format) {
        var timeZone = AdsApp.currentAccount().getTimeZone();
        return Utilities.formatDate(date, timeZone, format);
    }

    function findColor(firstMetric, secondMetric) {
        if (parseInt(firstMetric) > parseInt(secondMetric)) {
            return "#99ff99";
        } else if (parseInt(firstMetric) === parseInt(secondMetric)) {
            return "#ffff99";
        } else {
            return "#ff8080";

        }
    }

    function findMetricDifference(previousSevenDays, lastSevenDays) {
        var metricDifference = [];
        outerloop:
            for (var i = 0; i < previousSevenDays.length; ++i) {
                for (var j = 0; j < lastSevenDays.length; ++j) {
                    if (previousSevenDays[i][0] == lastSevenDays[j][0]) continue outerloop;
                }
                metricDifference.push(previousSevenDays[i]);
            }
        return metricDifference;
    }

    function sendEmails(htmlData) {
        MailApp.sendEmail(EMAIL, ACCOUNT_NAME + ' Google Analytics Weekly Summary', '', {
            htmlBody: htmlData.join('\n')
        });
    }




Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany. Wymagane pola są oznaczone *