Last active
June 7, 2022 20:29
-
-
Save sidneycalebe/e79084e6a4fc3eef19c8e98430967e80 to your computer and use it in GitHub Desktop.
This file contains 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
/* Como utilizar: | |
- Antes de executar, garanta que: [1] As tabelas 'Contatos' e 'Log de exportações' foram criadas e estão vazias; [2] O Token da API V2 está preenchido na tabela 'Dados'. | |
- Para iniciar a exportação, execute a função start. | |
- A tabela 'Log de exportações' registrará alguns dados da exportação para referência. | |
OBS: Caso o script seja interrompido ou parado, execute novamente a função start, para a exportação continuar do ponto que parou. | |
*/ | |
var CurrentSheet = SpreadsheetApp.getActiveSpreadsheet(); | |
var contatosTab = CurrentSheet.getSheetByName('Contatos'); | |
var logExportacoesTab = CurrentSheet.getSheetByName('Log de exportações'); | |
var token = CurrentSheet.getSheetByName('Token').getRange('A2').getValue(); | |
var cumulateContacts = logExportacoesTab.getRange('F2').getValue() || 0; | |
var totalApiCalls = 1; | |
var totalContacts = 0; | |
var timeLog = []; | |
async function startContactsExport() { // Inicia a execução do script | |
if (validateTableFields() !== false) { | |
startLogs(); | |
var tableHeaders = await getTabContactsHeaders(); | |
createHeadersInContactsTable(tableHeaders); | |
callRequests(getPage(), tableHeaders); | |
}; | |
}; | |
function validateTableFields() { | |
if (token === '') { | |
createLogs('insertToken'); | |
return false; | |
}; | |
if (logExportacoesTab.getRange('E2').getValue() === "Sim") { | |
createLogs('cleanTablesBefore'); | |
return false; | |
}; | |
return true; | |
}; | |
function setTime(position) { | |
timeLog.splice(position, 1, Utilities.formatDate(new Date(), "GMT-3", "dd/MM/yyyy HH:mm:ss")); | |
}; | |
function startLogs() { | |
setTime(0); | |
createLogs('start'); | |
createLogs('tabLogHeaders'); | |
createLogs('cumulateContacts'); | |
}; | |
function createHeadersInContactsTable(tableHeaders) { | |
var columnsNames = tableHeaders.map((elemento) => elemento.replace('contato.', '')); | |
columnsNames = columnsNames.map((elemento) => elemento.replace('customFields.', '')); | |
contatosTab.appendRow(columnsNames); | |
}; | |
async function getTabContactsHeaders() { | |
var contactsArray = await doRequest(0); | |
var arrayDefaultKeys = Object.keys(contactsArray[0]); | |
var arrayCustomFieldsKeys = Object.keys(contactsArray[0].customFields); | |
arrayDefaultKeys.pop('customFields'); | |
arrayDefaultKeys = arrayDefaultKeys.map((key) => "contato." + key); | |
arrayCustomFieldsKeys = arrayCustomFieldsKeys.map((key) => "contato.customFields." + key); | |
return arrayDefaultKeys.concat(arrayCustomFieldsKeys); | |
}; | |
async function callRequests(page, tableHeaders) { | |
var contactsArray = await doRequest(page); | |
var valuesForSheet = createValuesForSheet(contactsArray, tableHeaders); | |
writeRowsInTable(valuesForSheet, page); | |
contactsArray.length != 0 ? callRequests(page + 1, tableHeaders) && totalApiCalls++ : createLogs('finish'); | |
}; | |
function getPage() { | |
var nextPage = logExportacoesTab.getRange('D2').getValue(); | |
return nextPage == '' ? 0 : nextPage + 1; | |
}; | |
async function doRequest(page) { | |
var options = { | |
'method': 'get', | |
'headers': { | |
'Authorization': 'Bearer ' + token, | |
'Content-Type': 'application/json', | |
'Accept': 'application/json', | |
}, | |
}; | |
var resposta = UrlFetchApp.fetch(`https://api.huggy.app/v2/contacts/?page=${page}`, options); | |
return JSON.parse(resposta); | |
}; | |
function createValuesForSheet(contactsArray, tableHeaders) { | |
var valuesForSheet = []; | |
contactsArray.forEach(function (contato) { | |
var dataRow = []; | |
tableHeaders.forEach((header) => dataRow.push(eval(header))); | |
valuesForSheet.push(dataRow); | |
totalContacts++; | |
}); | |
return valuesForSheet; | |
}; | |
function writeRowsInTable(valuesForSheet, page) { | |
if (valuesForSheet.length == 0) { | |
setTime(1); | |
} | |
else { | |
contatosTab.getRange(contatosTab.getLastRow() + 1, 1, valuesForSheet.length, valuesForSheet[0].length).setValues(valuesForSheet); | |
createLogs('current', page); | |
}; | |
}; | |
function createTableLog(table, numeros, valores) { | |
valores.forEach((element, index) => CurrentSheet.getSheetByName(table).getRange(numeros[index]).setValue(valores[index])); | |
}; | |
function createLogs(logType, page) { | |
switch (logType) { | |
case 'insertToken': | |
Logger.log('Insira o Token na célula antes de executar a exportação'); | |
break; | |
case 'start': | |
Logger.log(`Exportação inciada em ${timeLog[0]}.`); | |
break; | |
case 'finish': createTableLog('Log de exportações', ['E2', 'B2'], ['Sim', timeLog[1]]); | |
Logger.log(`Exportação finalizada! A exportação iniciou em ${timeLog[0]} e finalizou em ${timeLog[1]}. Foram exportados ${totalContacts} contatos.`); | |
break; | |
case 'current': | |
createTableLog('Log de exportações', ['A2', 'B2', 'C2', 'D2', 'E2', 'F2'], [timeLog[0], '...exportando', totalContacts, page, 'Não', cumulateContacts + totalContacts]); | |
Logger.log(`${totalContacts} exportados.`); | |
break; | |
case 'cleanTablesBefore': | |
Logger.log("A última exportação de dados foi concluída com sucesso. Para realizar uma nova, limpe as tabelas 'Contatos' e 'Log de exportações'."); | |
break; | |
case 'tabLogHeaders': | |
createTableLog('Log de exportações', ['A1', 'B1', 'C1', 'D1', 'E1', 'F1'], ['Inicio da exportação', 'Fim da exportação', 'Qtd. contatos na execução', 'Página', 'Exportação finalizada', 'Total de contatos']); | |
break; | |
case 'cumulateContacts': | |
createTableLog('Log de exportações', ['F2'], [cumulateContacts]); | |
break; | |
case 'warning': | |
Logger.log(`Aviso: Caso a exportação seja parada ou interrompida antes de finalizar, execute a função 'start' novamente. A exportação continuará do ponto onde parou.`); | |
break; | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment