Skip to content

Instantly share code, notes, and snippets.

@tiagoengel
Created April 8, 2019 09:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiagoengel/d0d02e89d59244b0f79b346a427ef680 to your computer and use it in GitHub Desktop.
Save tiagoengel/d0d02e89d59244b0f79b346a427ef680 to your computer and use it in GitHub Desktop.
/**
* Regra de converção de moedas para o imposto de renda:
*
* Valor do dólar dos Estados Unidos da América, fixado pela autoridade monetária
* do país de origem dos rendimentos na data do recebimento.
*
* Em seguida convertido para reais pelo valor de compra do dólar fixado pelo Banco Central do Brasil
* para o último dia útil da 1a quinzena do mês anterior ao do recebimento dos rendimentos.
*/
const https = require('https')
if (process.argv.length < 4) {
console.log('Usage:\n\tpound-to-blr.js [value] [date]')
process.exit(-1)
}
const USD = 220
const BLR = 790
const POUND = 540
const value = process.argv[2]
const date = process.argv[3]
function dateForRequest(date) {
if (typeof date === 'string') {
return date.split('/').reverse().join('-')
} else {
return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
}
}
function get(path, cb) {
console.debug(`\t${path}`)
return https.get(path, cb)
}
function convert(from, to, value, date) {
const dateWithFormat = dateForRequest(date)
const path = `${value.replace(',', '.')}/1/${from}/${to}/${dateWithFormat}`
return new Promise((resolve, reject) => {
const req = get(`https://www3.bcb.gov.br/bc_moeda/rest/converter/${path}`, (res) => {
res.setEncoding('latin1')
res.on('data', (chunk) => {
resolve(extractResponse(chunk, '(<valor-convertido>)(([0-9]|[\.]|[,])+)'))
})
req.on('error', reject)
})
})
}
function getLastClosing(currency, date) {
const dateWithFormat = dateForRequest(date)
return new Promise((resolve, reject) => {
const req = get(`https://www3.bcb.gov.br/bc_moeda/rest/cotacao/fechamento/ultima/1/${currency}/${dateWithFormat}`, (res) => {
res.setEncoding('latin1')
res.on('data', (chunk) => {
resolve(new Date(extractResponse(chunk, '(<data>)((\.?)+)(\<\/data)')))
})
req.on('error', reject)
})
})
}
function extractResponse(data, pattern) {
const r = data.match(new RegExp(pattern))
if (r) {
return r[2]
}
throw new Error(`Could not parse response with pattern ${pattern}.\n\n${data}`)
}
getLastClosing(USD, date)
.then(closingDate => {
console.log('\x1b[37m', `Using dollar quotation at ${closingDate.toLocaleString()}`, '\x1b[0m')
return convert(POUND, USD, value, closingDate)
}).then(usdValue => {
const blrDate = date.split('/')
blrDate[1] = `${parseInt(blrDate[1], 10) - 1}`
blrDate[0] = '15'
if (blrDate[1] == '0') {
blrDate[1] = '12'
blrDate[2] = `${parseInt(blrDate[2], 10) - 1}`
}
return getLastClosing(USD, blrDate.join('/')).then(closingDate => {
console.log('\x1b[37m', `Using dollar quotation at ${closingDate.toLocaleString()}`, '\x1b[0m')
return convert(USD, BLR, usdValue, closingDate)
});
})
.then(v => {
console.log(`${value} pounds is equal to`, '\x1b[36m', `${parseFloat(v).toFixed(2)}`, '\x1b[0m', 'reals')
})
.catch(console.error)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment