//Nastavení----------------------------------------------------------------------------------------------
//*******************************************************************************************************
var spreadsheet = 'https://docs.google.com/spreadsheets/d/1J1efr15eFtggt5sffsre544e5mNX_SGfU/edit';
var token = '0x101c0a3dd0654sd5fsdcgt1r56sf6f1s5f6sd65sdf4fs58ssf6fee1051c92b230514a-account@seznam.cz';
var sklik_account = 'account@seznam.cz'; //pokud používáte token z MCC účtu, zadejte název single účtu
/********************************************************************************************************    
Skript:         Sklik API client historical data
Verze:          06.12.2017
Návod vytvořil: Stanislav Jílek [standajilek.cz]
*********************************************************************************************************/

function main() {
//Nadefinování spreadsheetu
    var ss = SpreadsheetApp.openByUrl(spreadsheet);
    var sheet = ss.getSheetByName('data');

//Pole pro export do spreadsheetu  
    var sheet_export = [];
    var sheet_row = [];

//Přihlášení
//client.login-------------------------------------------------------------------------------------------
    var client_login = sklik_api([token], 'client.loginByToken');
    var session = client_login.session;

//client.get---------------------------------------------------------------------------------------------
    var client_get = sklik_api([{'session': session}], 'client.get');
    //Cyklus, který projde všechny účty a přiřadí správné userId vámi nadefinovaného účtu
    for (var i = 0; i < client_get.foreignAccounts.length; i++)
    {
        if (sklik_account.toLowerCase() == client_get.foreignAccounts[i].username.toLowerCase())
        {
            var sklik_account_id = client_get.foreignAccounts[i].userId;
        }
    }

//client.stats------------------------------------------------------------------------------------------- 
    //Datum
    var days_back = 7;
    var start_date = new Date();
    start_date.setUTCDate(start_date.getUTCDate() - days_back);
    start_date = Utilities.formatDate(start_date, 'GTM - 1', 'yyyy-MM-dd');
    //start_date = "2016-01-01";

    var end_date = new Date();
    end_date.setUTCDate(end_date.getUTCDate() - 1);
    end_date = Utilities.formatDate(end_date, 'GTM - 1', 'yyyy-MM-dd');

    var client_stats = sklik_api([{'session': session, 'userId': sklik_account_id}, {'dateFrom': start_date, 'dateTo': end_date, 'granularity': 'daily'}], 'client.stats');
    for (var i = 0; i < client_stats.report.length; i++)
    {
        var date = (client_stats.report[i].date).substr(0, 4) + "-" + (client_stats.report[i].date).substr(4, 2) + "-" + (client_stats.report[i].date).substr(6, 2);
        var clicks = client_stats.report[i].clicks;
        var impressions = client_stats.report[i].impressions;
        var cost = client_stats.report[i].price / 100;
        var conversions = client_stats.report[i].conversions;
        var conversionValue = client_stats.report[i].conversionValue / 100;

        //export do pole                     
        sheet_row = [date, clicks, impressions, cost, conversions, conversionValue];
        sheet_export.push(sheet_row);
    }

    //hlavička tabulky 
    sheet.getRange('A1:F1').setValues([['Datum', 'Prokliky', 'Zobrazení', 'Cena', 'Konverze', 'Hodnota konverze']])
    //smazání předchozích dat
    sheet.getRange("A2:F").clearContent();
    //export do spreadsheetu  
    if (sheet_export.length > 0 && sheet_row.length > 0)
    {
        sheet.getRange(2, 1, sheet_export.length, sheet_row.length).setValues(sheet_export);
    }

//client.logout-----------------------------------------------------------------------------------------
    var client_logout = sklik_api([{'session': session}], 'client.logout');
}

//------------------------------------------------------------------------------------------------------
//funkce pro komunikaci
function sklik_api(parameters, method) {
    var url = 'https://api.sklik.cz/jsonApi/drak/'  + method;
    var options = {'method': 'post', 'contentType': 'application/json', 'muteHttpExceptions': true, 'payload': JSON.stringify(parameters)};

    try {
        return(JSON.parse(UrlFetchApp.fetch(url, options)));
    } catch (err)
    {
        Utilities.sleep(1000);
        try {
            return(JSON.parse(UrlFetchApp.fetch(url, options)));
        } catch (err)
        {
            Utilities.sleep(1000);
            return(JSON.parse(UrlFetchApp.fetch(url, options)));
        }
    }
}