//Url config spreadsheet-------------------------------------------------------------------------------------------------------------
//***********************************************************************************************************************************
var ss_config = SpreadsheetApp.openByUrl('config spreadsheet url');
var notification_email = "email@email.cz";
/************************************************************************************************************************************
Script:      Cost import
Version:     30.11.2019
Created By:  Stanislav Jilek [standajilek.cz] pro import nakladu z vice portalu me muzete kontaktovat
Idea:        Karel Rujzl [rujzl.cz] a Petra Vetrovska [vetrovka.cz]
/***********************************************************************************************************************************/

function main() {
//Settings*************************************************************************************************************************** 
//Spreadsheet
    var settings_sheet = ss_config.getSheetByName("cost_import");
    var settings = settings_sheet.getRange("A4:FL" + settings_sheet.getLastRow()).getValues();

    //count of accounts
    for (var i = 0; i < settings.length; i++)
    {
//Google Analytics
        var account_name = settings[i][0], account_id = settings[i][1], web_property_id = settings[i][2], import_id = settings[i][3], days_back = settings[i][4];
        var data = [["ga:date", "ga:medium", "ga:source", "ga:adCost", "ga:adClicks", "ga:impressions", "ga:campaign"]];

//Sklik.cz
        try {
            var sklik_token = settings[i][5], sklik_account = settings[i][6], sklik_source = settings[i][7], sklik_medium = settings[i][8], sklik_level = settings[i][9], sklik_exchange_rate = (settings[i][10] != "") ? settings[i][10] : 1, sklik_filter = settings[i][11], sklik_condition = settings[i][12];
            if (sklik_token != "") {
                data = data.concat(sklik(account_name, sklik_token, sklik_account, sklik_source, sklik_medium, sklik_level, sklik_exchange_rate, sklik_filter, sklik_condition, days_back));
            }
        } catch (err)
        {
        }

//Facebook.com
        try {
            var facebook_token = settings[i][13], facebook_account = settings[i][14], facebook_source = settings[i][15], facebook_medium = settings[i][16], facebook_level = settings[i][17], facebook_exchange_rate = (settings[i][18] != "") ? settings[i][18] : 1, facebook_filter = settings[i][19], facebook_condition = settings[i][20];
            if (facebook_token != "") {
                data = data.concat(facebook(account_name, facebook_token, facebook_account, facebook_source, facebook_medium, facebook_level, facebook_exchange_rate, facebook_filter, facebook_condition, days_back));
            }
        } catch (err)
        {
        }

//Heureka.cz    
        var heureka_cz_user_name = settings[i][21], heureka_cz_password = settings[i][22].toString(), heureka_cz_shop_id = settings[i][23], heureka_cz_source = settings[i][24], heureka_cz_medium = settings[i][25], heureka_cz_campaign = settings[i][26], heureka_cz_exchange_rate = (settings[i][27] != "") ? settings[i][27] : 1;
        try {
            if (heureka_cz_user_name != "") {
                data = data.concat(heureka_cz(account_name, heureka_cz_user_name, heureka_cz_password, heureka_cz_shop_id, heureka_cz_source, heureka_cz_medium, heureka_cz_campaign, heureka_cz_exchange_rate, days_back));
            }
        } catch (err)
        {
        }

//Heureka.sk    
        var heureka_sk_user_name = settings[i][28], heureka_sk_password = settings[i][29].toString(), heureka_sk_shop_id = settings[i][30], heureka_sk_source = settings[i][31], heureka_sk_medium = settings[i][32], heureka_sk_campaign = settings[i][33], heureka_sk_exchange_rate = (settings[i][34] != "") ? settings[i][34] : 1;
        try {
            if (heureka_sk_user_name != "") {
                data = data.concat(heureka_sk(account_name, heureka_sk_user_name, heureka_sk_password, heureka_sk_shop_id, heureka_sk_source, heureka_sk_medium, heureka_sk_campaign, heureka_sk_exchange_rate, days_back));
            }
        } catch (err)
        {
        }      
            
//Zbozi.cz 
        var zbozi_user_name = settings[i][35], zbozi_password = settings[i][36].toString(), zbozi_shop_id = settings[i][37], zbozi_source = settings[i][38], zbozi_medium = settings[i][39], zbozi_campaign = settings[i][40], zbozi_exchange_rate = (settings[i][41] != "") ? settings[i][41] : 1;
        try {
            if (zbozi_user_name != "") {
                data = data.concat(zbozi(account_name, zbozi_user_name, zbozi_password, zbozi_shop_id, zbozi_source, zbozi_medium, zbozi_campaign, zbozi_exchange_rate, days_back));
            }
        } catch (err)
        {
        }
      
//Glami.cz 
        var glami_cz_user_name = settings[i][42], glami_cz_password = settings[i][43].toString(), glami_cz_shop_id = settings[i][44], glami_cz_source = settings[i][45], glami_cz_medium = settings[i][46], glami_cz_campaign = settings[i][47], glami_cz_exchange_rate = (settings[i][48] != "") ? settings[i][48] : 1;
        try {
            if (glami_cz_user_name != "") {
                data = data.concat(glami_cz(account_name, glami_cz_user_name, glami_cz_password, glami_cz_shop_id, glami_cz_source, glami_cz_medium, glami_cz_campaign, glami_cz_exchange_rate, days_back));
            }
        } catch (err)
        {
        }

//Glami.sk 
        var glami_sk_user_name = settings[i][49], glami_sk_password = settings[i][50].toString(), glami_sk_shop_id = settings[i][51], glami_sk_source = settings[i][52], glami_sk_medium = settings[i][53], glami_sk_campaign = settings[i][54], glami_sk_exchange_rate = (settings[i][55] != "") ? settings[i][55] : 1;
        try {
            if (glami_sk_user_name != "") {
                data = data.concat(glami_sk(account_name, glami_sk_user_name, glami_sk_password, glami_sk_shop_id, glami_sk_source, glami_sk_medium, glami_sk_campaign, glami_sk_exchange_rate, days_back));
            }
        } catch (err)
        {
        }

//Glami.hu 
        var glami_hu_user_name = settings[i][56], glami_hu_password = settings[i][57].toString(), glami_hu_shop_id = settings[i][58], glami_hu_source = settings[i][59], glami_hu_medium = settings[i][60], glami_hu_campaign = settings[i][61], glami_hu_exchange_rate = (settings[i][62] != "") ? settings[i][62] : 1;
        try {
            if (glami_hu_user_name != "") {
                data = data.concat(glami_hu(account_name, glami_hu_user_name, glami_hu_password, glami_hu_shop_id, glami_hu_source, glami_hu_medium, glami_hu_campaign, glami_hu_exchange_rate, days_back));
            }
        } catch (err)
        {
        }

//Glami.ro 
        var glami_ro_user_name = settings[i][63], glami_ro_password = settings[i][64].toString(), glami_ro_shop_id = settings[i][65], glami_ro_source = settings[i][66], glami_ro_medium = settings[i][67], glami_ro_campaign = settings[i][68], glami_ro_exchange_rate = (settings[i][69] != "") ? settings[i][69] : 1;
        try {
            if (glami_ro_user_name != "") {
                data = data.concat(glami_ro(account_name, glami_ro_user_name, glami_ro_password, glami_ro_shop_id, glami_ro_source, glami_ro_medium, glami_ro_campaign, glami_ro_exchange_rate, days_back));
            }
        } catch (err)
        {
        }

//Biano.cz 
        var biano_cz_user_name = settings[i][70], biano_cz_password = settings[i][71].toString(), biano_cz_shop_id = settings[i][72], biano_cz_source = settings[i][73], biano_cz_medium = settings[i][74], biano_cz_campaign = settings[i][75], biano_cz_exchange_rate = (settings[i][76] != "") ? settings[i][76] : 1;
        try {
            if (biano_cz_user_name != "") {
                data = data.concat(biano_cz(account_name, biano_cz_user_name, biano_cz_password, biano_cz_shop_id, biano_cz_source, biano_cz_medium, biano_cz_campaign, biano_cz_exchange_rate, days_back));
            }
        } catch (err)
        {
        }

//Biano.sk 
        var biano_sk_user_name = settings[i][77], biano_sk_password = settings[i][78].toString(), biano_sk_shop_id = settings[i][79], biano_sk_source = settings[i][80], biano_sk_medium = settings[i][81], biano_sk_campaign = settings[i][82], biano_sk_exchange_rate = (settings[i][83] != "") ? settings[i][83] : 1;
        try {
            if (biano_sk_user_name != "") {
                data = data.concat(biano_sk(account_name, biano_sk_user_name, biano_sk_password, biano_sk_shop_id, biano_sk_source, biano_sk_medium, biano_sk_campaign, biano_sk_exchange_rate, days_back));
            }
        } catch (err)
        {
        }
      
//Biano.ro 
        var biano_ro_user_name = settings[i][84], biano_ro_password = settings[i][85].toString(), biano_ro_shop_id = settings[i][86], biano_ro_source = settings[i][87], biano_ro_medium = settings[i][88], biano_ro_campaign = settings[i][89], biano_ro_exchange_rate = (settings[i][90] != "") ? settings[i][90] : 1;
        try {
            if (biano_ro_user_name != "") {
                data = data.concat(biano_ro(account_name, biano_ro_user_name, biano_ro_password, biano_ro_shop_id, biano_ro_source, biano_ro_medium, biano_ro_campaign, biano_ro_exchange_rate, days_back));
            }
        } catch (err)
        {
        }  

//Favi.cz
        var favi_cz_cookie = settings[i][91], favi_cz_shop_name = settings[i][92], favi_cz_source = settings[i][93], favi_cz_medium = settings[i][94], favi_cz_campaign = settings[i][95], favi_cz_exchange_rate = (settings[i][96] != "") ? settings[i][96] : 1;
        try {
            if (favi_cz_cookie != "") {
                data = data.concat(favi_cz(account_name, favi_cz_cookie, favi_cz_shop_name, favi_cz_source, favi_cz_medium, favi_cz_campaign, favi_cz_exchange_rate, days_back));
            }
        } catch (err)
        {
        }

//Favi.sk
        var favi_sk_cookie = settings[i][97], favi_sk_shop_name = settings[i][98], favi_sk_source = settings[i][99], favi_sk_medium = settings[i][100], favi_sk_campaign = settings[i][101], favi_sk_exchange_rate = (settings[i][102] != "") ? settings[i][102] : 1;
        try {
            if (favi_sk_cookie != "") {
                data = data.concat(favi_sk(account_name, favi_sk_cookie, favi_sk_shop_name, favi_sk_source, favi_sk_medium, favi_sk_campaign, favi_sk_exchange_rate, days_back));
            }
        } catch (err)
        {
        }
      
//Favi.hu
        var favi_hu_cookie = settings[i][103], favi_hu_shop_name = settings[i][104], favi_hu_source = settings[i][105], favi_hu_medium = settings[i][106], favi_hu_campaign = settings[i][107], favi_hu_exchange_rate = (settings[i][108] != "") ? settings[i][108] : 1;
        try {
            if (favi_hu_cookie != "") {
                data = data.concat(favi_hu(account_name, favi_hu_cookie, favi_hu_shop_name, favi_hu_source, favi_hu_medium, favi_hu_campaign, favi_hu_exchange_rate, days_back));
            }
        } catch (err)
        {
        }

//Favi.ro
        var favi_ro_cookie = settings[i][109], favi_ro_shop_name = settings[i][110], favi_ro_source = settings[i][111], favi_ro_medium = settings[i][112], favi_ro_campaign = settings[i][113], favi_ro_exchange_rate = (settings[i][114] != "") ? settings[i][114] : 1;
        try {
            if (favi_ro_cookie != "") {
                data = data.concat(favi_ro(account_name, favi_ro_cookie, favi_ro_shop_name, favi_ro_source, favi_ro_medium, favi_ro_campaign, favi_ro_exchange_rate, days_back));
            }
        } catch (err)
        {
        }
      
//Favi.pl
        var favi_pl_cookie = settings[i][115], favi_pl_shop_name = settings[i][116], favi_pl_source = settings[i][117], favi_pl_medium = settings[i][118], favi_pl_campaign = settings[i][119], favi_pl_exchange_rate = (settings[i][120] != "") ? settings[i][120] : 1;
        try {
            if (favi_pl_cookie != "") {
                data = data.concat(favi_pl(account_name, favi_pl_cookie, favi_pl_shop_name, favi_pl_source, favi_pl_medium, favi_pl_campaign, favi_pl_exchange_rate, days_back));
            }
        } catch (err)
        {
        }   

//Hledejceny.cz
        var hledejceny_cz_user_name = settings[i][121], hledejceny_cz_password = settings[i][122].toString(), hledejceny_cz_shop_id = settings[i][123], hledejceny_cz_source = settings[i][124], hledejceny_cz_medium = settings[i][125], hledejceny_cz_campaign = settings[i][126], hledejceny_cz_exchange_rate = (settings[i][127] != "") ? settings[i][127] : 1;
        try {
            if (hledejceny_cz_user_name != "") {
                data = data.concat(hledejceny_cz(account_name, hledejceny_cz_user_name, hledejceny_cz_password, hledejceny_cz_shop_id, hledejceny_cz_source, hledejceny_cz_medium, hledejceny_cz_campaign, hledejceny_cz_exchange_rate, days_back));
            }
        } catch (err)
        {
        }
      
//Srovname.cz
        var srovname_cz_user_name = settings[i][128], srovname_cz_password = settings[i][129].toString(), srovname_cz_source = settings[i][130], srovname_cz_medium = settings[i][131], srovname_cz_campaign = settings[i][132], srovname_cz_exchange_rate = (settings[i][133] != "") ? settings[i][133] : 1;
        try {
            if (srovname_cz_user_name != "") {
                data = data.concat(srovname_cz(account_name, srovname_cz_user_name, srovname_cz_password, srovname_cz_source, srovname_cz_medium, srovname_cz_campaign, srovname_cz_exchange_rate, days_back));
            }
        } catch (err)
        {
        }
      
//Arukereso.hu 
        var arukereso_user_name = settings[i][134], arukereso_password = settings[i][135].toString(), arukereso_shop_id = settings[i][136], arukereso_source = settings[i][137], arukereso_medium = settings[i][138], arukereso_campaign = settings[i][139], arukereso_exchange_rate = (settings[i][140] != "") ? settings[i][140] : 1;
        try {
            if (arukereso_user_name != "") {
                data = data.concat(arukereso(account_name, arukereso_user_name, arukereso_password, arukereso_shop_id, arukereso_source, arukereso_medium, arukereso_campaign, arukereso_exchange_rate, days_back));
            }
        } catch (err)
        {
        }
          
//Compari.ro
        var compari_user_name = settings[i][141], compari_password = settings[i][142].toString(), compari_shop_id = settings[i][143], compari_source = settings[i][144], compari_medium = settings[i][145], compari_campaign = settings[i][146], compari_exchange_rate = (settings[i][147] != "") ? settings[i][147] : 1;
        try {
            if (compari_user_name != "") {
                data = data.concat(compari(account_name, compari_user_name, compari_password, compari_shop_id, compari_source, compari_medium, compari_campaign, compari_exchange_rate, days_back));
            }
        } catch (err)
        {
        }
         
//Pazaruvaj.com
        var pazaruvaj_user_name = settings[i][148], pazaruvaj_password = settings[i][149].toString(), pazaruvaj_shop_id = settings[i][150], pazaruvaj_source = settings[i][151], pazaruvaj_medium = settings[i][152], pazaruvaj_campaign = settings[i][153], pazaruvaj_exchange_rate = (settings[i][154] != "") ? settings[i][154] : 1;
        try {
            if (pazaruvaj_user_name != "") {
                data = data.concat(pazaruvaj(account_name, pazaruvaj_user_name, pazaruvaj_password, pazaruvaj_shop_id, pazaruvaj_source, pazaruvaj_medium, pazaruvaj_campaign, pazaruvaj_exchange_rate, days_back));
            }
        } catch (err)
        {
        }

//Domodi.pl
        var domodi_pl_user_name = settings[i][155], domodi_pl_password = settings[i][156].toString(), domodi_pl_shop_id = settings[i][157], domodi_pl_source = settings[i][158], domodi_pl_medium = settings[i][159], domodi_pl_campaign = settings[i][160], domodi_pl_exchange_rate = (settings[i][161] != "") ? settings[i][161] : 1;
        try {
            if (domodi_pl_user_name != "") {
                data = data.concat(domodi_pl(account_name, domodi_pl_user_name, domodi_pl_password, domodi_pl_shop_id, domodi_pl_source, domodi_pl_medium, domodi_pl_campaign, domodi_pl_exchange_rate, days_back));
            }
        } catch (err)
        {
        }

//Criteo.com
        var criteo_client_id = settings[i][162], criteo_client_secret = settings[i][163].toString(), criteo_source = settings[i][164], criteo_medium = settings[i][165], criteo_level = settings[i][166], criteo_exchange_rate = (settings[i][167] != "") ? settings[i][167] : 1;
        try {
            if (criteo_client_id != "") {
                data = data.concat(criteo(account_name, criteo_client_id, criteo_client_secret, criteo_source, criteo_medium, criteo_level, criteo_exchange_rate, days_back));
            }
        } catch (err)
        {
        }
            
//Google Analytics upload
        analytics_upload(account_name, account_id, web_property_id, import_id, data);

    }
}

function facebook(account_name, facebook_token, facebook_account, facebook_source, facebook_medium, facebook_level, facebook_exchange_rate, facebook_filter, facebook_condition, days_back) {
    var data = [];

    try
    {
        var offset = 0;
        var limit = 15;

        if (facebook_level == "account")
        {
            limit = 730;
        }

        if (limit > days_back)
        {
            limit = days_back;
        }

        var facebook_api_url = "https://developers.facebook.com/docs/graph-api/changelog";

        try {
            var facebook_api_version = UrlFetchApp.fetch(facebook_api_url).getContentText();
        } catch (err)
        {
            Utilities.sleep(1000);
            try {
                var facebook_api_version = UrlFetchApp.fetch(facebook_api_url).getContentText();
            } catch (err)
            {
                Utilities.sleep(1000);
                var facebook_api_version = UrlFetchApp.fetch(facebook_api_url).getContentText();
            }
        }

        facebook_api_version = facebook_api_version.substring(facebook_api_version.indexOf("<code>") + 6, facebook_api_version.indexOf("</code>"));

        do {

            if (offset + limit > days_back)
            {
                offset += days_back - offset - limit;
            }

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

            var url = "/" + facebook_api_version + "/act_" + facebook_account + "/insights?" +
                    "fields=date_start,spend,clicks,impressions,campaign_name" +
                    "&level=" + facebook_level.replace("s", "") +
                    "&time_range[since]=" + start_date + "&time_range[until]=" + end_date +
                    "&sort=date_start_ascending" +
                    "&time_increment=1" +
                    "&limit=1000000" +
                    "&access_token=" + facebook_token;

            var response = fb_api(url);
          
            if (response.data === undefined)
            {
                MailApp.sendEmail({to: notification_email, subject: "Cost import | Obnova FB tokenu", htmlBody: "Je nutné obnovit FB token u účtu: " + account_name});
            }  

            for (var i = 0; i < response.data.length; i++)
            {
                var campaign_name = "";
                if (facebook_level == "campaigns")
                {
                    campaign_name = response.data[i].campaign_name;
                }

                if (new RegExp(facebook_filter.toString().toLowerCase(), "i").test(campaign_name.toLowerCase()) == facebook_condition || facebook_filter == "" || facebook_level == "account")
                {

                    if (campaign_name != "")
                    {
                        campaign_name = '"' + campaign_name.split('"').join('').split('„').join('').split('“').join('') + '"';
                    }

                    data.push([response.data[i].date_start.replace("-", "").replace("-", "").replace("-", ""),
                        facebook_medium,
                        facebook_source,
                        (response.data[i].spend * facebook_exchange_rate).toFixed(2),
                        response.data[i].clicks,
                        response.data[i].impressions,
                        campaign_name]);
                }
            }
            offset += limit;
        } while (offset < days_back)
    } catch (err)
    {
        Logger.log("FACEBOOK (" + account_name + "): " + err);
        MailApp.sendEmail({to: notification_email, subject: "COST IMPORT ERROR", htmlBody: "FACEBOOK (" + account_name + ")"});
    }

    return data;

}

function sklik(account_name, sklik_token, sklik_account, sklik_source, sklik_medium, sklik_level, sklik_exchange_rate, sklik_filter, sklik_condition, days_back) {
    var data = [];

    try
    {
        var start_date = new Date();
        start_date.setUTCDate(start_date.getUTCDate() - days_back);
        start_date = Utilities.formatDate(start_date, 'GTM - 1', 'yyyy-MM-dd');
        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_login = sklik_api([sklik_token], 'client.loginByToken');
        var session = client_login.session;

        var client_get = sklik_api([{'session': session}], 'client.get');
        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;
            }
        }

        if (sklik_level.toLowerCase() == "account")
        {
            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++)
            {
                data.push([(client_stats.report[i].date).substr(0, 8), sklik_medium, sklik_source, (client_stats.report[i].price / 100 * sklik_exchange_rate).toFixed(2), client_stats.report[i].clicks, client_stats.report[i].impressions, ""]);
            }
        }

        if (sklik_level.toLowerCase() == "campaigns")
        {
            var campaigns_createReport = sklik_api([{'session': session, 'userId': sklik_account_id}, {'dateFrom': start_date, 'dateTo': end_date}, {'statGranularity': 'daily'}], 'campaigns.createReport');

            var report_id = campaigns_createReport.reportId;
            var limit = campaigns_createReport.totalCount;

            var offset = Math.ceil(limit / (parseInt(5000 / days_back)));

            if (limit > 0)
            {
                for (var i = 0; i < offset; i++)
                {
                    try
                    {
                        var campaigns_readReport = sklik_api([{'session': session, 'userId': sklik_account_id},
                            report_id,
                            {'offset': i * (parseInt(5000 / days_back)),
                                'limit': parseInt(5000 / days_back),
                                'allowEmptyStatistics': false,
                                'displayColumns': ['name', 'totalMoney', 'clicks', 'impressions']}],
                                'campaigns.readReport');

                        for (var k = 0; k < campaigns_readReport.report.length; k++)
                        {
                            for (var l = 0; l < days_back; l++)
                            {
                                try {
                                    if (new RegExp(sklik_filter.toString().toLowerCase(), "i").test(campaigns_readReport.report[k].name.toLowerCase()) == sklik_condition || sklik_filter == "")
                                    {
                                        data.push([campaigns_readReport.report[k].stats[l].date, sklik_medium, sklik_source, (campaigns_readReport.report[k].stats[l].totalMoney / 100 * sklik_exchange_rate).toFixed(2), campaigns_readReport.report[k].stats[l].clicks, campaigns_readReport.report[k].stats[l].impressions, '"' + campaigns_readReport.report[k].name.split('"').join('') + '"']);
                                    }
                                } catch (err)
                                {
                                }
                            }
                        }
                    } catch (err)
                    {
                        Logger.log("SKLIK: " + err);
                    }
                    Utilities.sleep(200);
                }
            }
        }

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

    } catch (err)
    {
        Logger.log("SKLIK (" + account_name + "): " + err);
        MailApp.sendEmail({to: notification_email, subject: "COST IMPORT ERROR", htmlBody: "SKLIK (" + account_name + ")"});
    }

    return data;

}

function analytics_upload(account_name, account_id, web_property_id, import_id, data) {
    try
    {
        if (data.length > 1)
        {
            var blob = Utilities.newBlob(data.join("\n"), "application/octet-stream", "Cost import");
            var upload = Analytics.Management.Uploads.uploadData(account_id, web_property_id, import_id, blob);
        }
    } catch (err)
    {
        Logger.log("ANALYTICS (" + account_name + "): " + err);
        MailApp.sendEmail({to: notification_email, subject: "COST IMPORT ERROR", htmlBody: "ANALYTICS (" + account_name + "): Chybný import"});
    }
}

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)));
        }
    }
}

function fb_api(settings_url) {
    var url = 'https://graph.facebook.com' + settings_url;
    var options = {'method': 'get', 'contentType': 'application/json', 'muteHttpExceptions': true};

    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)));
        }
    }
}