Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* 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
You can’t perform that action at this time.