Last active
May 10, 2020 02:56
-
-
Save mendelgusmao/637d4b7c71b9573b7e57a1864686f62b to your computer and use it in GitHub Desktop.
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
/** | |
* Calcula o rendimento de poupança de um valor em um período específico. | |
* | |
* @param {value} input O valor a ser calculado. | |
* @param {initialDate} input Data inicial. | |
* @param {finalDate} input Data final. | |
* @return O valor corrigido. | |
* @customfunction | |
*/ | |
function CORRECAO_POUPANCA(value, initialDate, finalDate = now()) { | |
if (!value) return 0; | |
if (!initialDate) throw 'Invalid initial date'; | |
if (!finalDate) throw 'Invalid final date'; | |
const parts = initialDate.split('/'); | |
if (parts.length === 2) { | |
initialDate = [ | |
28, | |
...initialDate.split('/'), | |
].join('/'); | |
} | |
initialDate = normalizeDate(initialDate); | |
finalDate = normalizeDate(finalDate); | |
value = value.toString().replace('.', ','); | |
const content = request(value, initialDate, finalDate); | |
const interest = parse(content); | |
return interest; | |
} | |
const endpoint = "https://www3.bcb.gov.br/CALCIDADAO/publico/corrigirPelaPoupanca.do?method=corrigirPelaPoupanca"; | |
const valueRE = /R\$ ([\d.]+,\d+) \(REAL\)/g; | |
function now() { | |
const today = new Date(); | |
const month = `${today.getMonth() + 1}`.padStart(2, '0'); | |
return [today.getDate(), month, today.getFullYear()].join('/'); | |
} | |
function parse(response) { | |
return [...response.matchAll(valueRE)].reduce( | |
(max, value) => { | |
value = value.slice(1).shift().replace('.', '').replace(',', '.'); | |
value = parseFloat(value); | |
if (value > max) | |
return value; | |
return max; | |
}, | |
0 | |
); | |
} | |
function request(value, initialDate, finalDate) { | |
const payload = { | |
aba: '3', | |
dataInicial: initialDate, | |
dataFinal: finalDate, | |
valorCorrecao: value, | |
regraNova: true | |
}; | |
const response = UrlFetchApp.fetch( | |
endpoint, | |
{ | |
"method": "post", | |
payload | |
} | |
); | |
return response.toString(); | |
} | |
function normalizeDate(date) { | |
const parts = date.split('/'); | |
return parts.map( | |
(d, i) => { | |
if (i === 2 && d.length === 2) return `20${d}`; | |
return d.padStart(2, '0'); | |
} | |
).join('/'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment