Last active
February 27, 2018 13:54
-
-
Save bruno2ms/fcceb8a15a286e46d9e7935e69eff015 to your computer and use it in GitHub Desktop.
Script para preencher planilha de horas com base na API do Toggl
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Acesse o menu na aba da sua Planilha de Jornada de Horas | |
// Ferramentas > Editor de Script | |
// Cole e salve este script, o Google provavelmente pedirá permissão de execução do script | |
// Acesse as configurações do Toggl no endereço https://toggl.com/app/profile | |
// Copie a sua apiToken | |
// Substitua aqui as variáveis necessárias | |
var apiToken = 'xxxxxxxxxxxxxxxxxxxxxxxxxx'; | |
// Para obter os id`s de workspace e clientes, acesse a página reports, selecione o workspace e cliente e aplice o filtro | |
// Você será redirecionado para a página com a seguinte url: | |
// https://toggl.com/app/reports/summary/[WORKSPACE_ID]/period/thisWeek/clients/CLIENTS_ID/billable/both | |
var workspace_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxx'; | |
// Comente esta variável caso todas suas entradas sejam do mesmo cliente | |
var clients_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxx'; | |
// Configure o trigger no GOOGLE SCRIPTS | |
// Edit > Current project's triggers | |
// Clique em "Add a new trigger" | |
// Selecione a função "__init" e configure a frequência desejada | |
// Caso queira ser notificado quando ocorrer um erro, configure as notifications | |
// Configure o trigger no GOOGLE SCRIPTS | |
// Edit > Current project's triggers | |
// Clique em "Add a new trigger" | |
// Selecione a função "__init" e configure a frequência desejada | |
// Caso queira ser notificado quando ocorrer um erro, configure as notifications | |
var ss = SpreadsheetApp.getActiveSpreadsheet(); | |
var sheets = ss.getSheets(); | |
var sheet = sheets[0]; | |
var TIMEZONE = "America/Sao_Paulo"; | |
var MESES = { | |
'JAN': 0, | |
'FEV': 1, | |
'MAR': 2, | |
'ABR': 3, | |
'MAI': 4, | |
'JUN': 5, | |
'JUL': 6, | |
'AGO': 7, | |
'SET': 8, | |
'OUT': 9, | |
'NOV': 10, | |
'DEZ': 11, | |
} | |
function onOpen() { | |
var entries = [{ | |
name : "Preencher planilha atual", | |
functionName : "atualizaAtual" | |
}]; | |
ss.addMenu("Toggl", entries); | |
}; | |
function __init() { | |
getSheetData(); | |
} | |
function atualizaAtual() { | |
sheet = ss.getActiveSheet(); | |
getSheetData(); | |
} | |
function getSheetData() { | |
var sheetName = sheet.getName().toUpperCase().split('/'); | |
var mes = MESES[sheetName[0]]; | |
var ano = Number(sheetName[1]); | |
var dataInicial = new Date(ano, mes, 1); | |
var datafinal = new Date(ano, mes + 1, 1); | |
dataInicial = Utilities.formatDate(dataInicial , TIMEZONE, "yyyy-MM-dd"); | |
datafinal = Utilities.formatDate(datafinal , TIMEZONE, "yyyy-MM-dd"); | |
getEntries(dataInicial, datafinal); | |
} | |
function getEntries(dataInicial, datafinal, page) { | |
page = page || 1; | |
var headers = { | |
"Authorization" : "Basic " + Utilities.base64Encode(apiToken + ':api_token') | |
}; | |
var options = { | |
"method":"get", | |
"headers":headers | |
}; | |
var url = 'https://toggl.com/reports/api/v2/details'; | |
var queryString = '?workspace_id=' + workspace_id; | |
queryString += '&since=' + dataInicial; | |
queryString += '&until=' + datafinal; | |
if (clients_id) { | |
queryString += '&client_ids=' + clients_id; | |
} | |
queryString += '&page=' + page; | |
queryString += '&user_agent=api_test'; | |
try { | |
var result = UrlFetchApp.fetch(url + queryString, options); | |
} catch(err) { | |
adicionaErro(err); | |
} | |
if (result.getResponseCode() == 200) { | |
var response = JSON.parse(result.getContentText()); | |
preencheTabela(response, page); | |
Logger.log(url + queryString); | |
Logger.log('Resultados: ' + response.data.lentgh); | |
// verifica se há mais itens do que foi listado até o momento | |
if (response.total_count > page * response.per_page) { | |
getEntries(dataInicial, datafinal, ++page); | |
} | |
} else { | |
adicionaErro('Não foi possível obter dados.'); | |
} | |
} | |
function adicionaErro(erro) { | |
sheet.getRange('G1').setValue('Falha na execução em:'); | |
sheet.getRange('G2').setValue(new Date()); | |
sheet.getRange('G3').setValue(erro); | |
} | |
function preencheTabela(response, page) { | |
if (page == 1) { | |
sheet.getRange('A2:E200').clear(); | |
sheet.getRange('G1:G3').clear(); | |
} | |
response.data.forEach(function(time, index) { | |
var i = index + ( (page -1) *response.per_page ) + 2; | |
const COLS = { | |
DATA: 1, | |
DESC: 2, | |
INICIO: 3, | |
FIM: 4, | |
DURACAO: 5 | |
}; | |
sheet.getRange(i, COLS.DATA).setValue(Utilities.formatDate(new Date(time.start), TIMEZONE, 'dd/MM/yyyy')); | |
sheet.getRange(i, COLS.DESC).setValue(time.description); | |
sheet.getRange(i, COLS.INICIO).setValue(Utilities.formatDate(new Date(time.start), TIMEZONE, 'hh:mm:ss')); | |
sheet.getRange(i, COLS.FIM).setValue(Utilities.formatDate(new Date(time.end), TIMEZONE, 'hh:mm:ss')); | |
sheet.getRange(i, COLS.DURACAO).setValue(msToTime(time.dur)); | |
}); | |
sheet.getRange('G1').setValue('Última execução:'); | |
sheet.getRange('G2').setValue(new Date()); | |
} | |
function msToTime(s) { | |
var ms = s % 1000; | |
s = (s - ms) / 1000; | |
var secs = s % 60; | |
s = (s - secs) / 60; | |
var mins = s % 60; | |
var hrs = (s - mins) / 60; | |
return hrs + ':' + mins + ':' + secs; // milliSecs are not shown but you can use ms if needed | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment