Skip to content

Commit

Permalink
fix(banrisul): add route for request download and return for approval
Browse files Browse the repository at this point in the history
  • Loading branch information
wisley7l committed Sep 11, 2023
1 parent 05d7d14 commit 5f65029
Show file tree
Hide file tree
Showing 6 changed files with 52 additions and 18 deletions.
2 changes: 1 addition & 1 deletion functions/lib/banrisul/auth/create-access.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ module.exports = function (clientId, clientSecret, storeId, isSandbox, firestore
this.preparing = new Promise((resolve, reject) => {
const authenticate = (accessToken, documentRef) => {
self.axios = createAxios(accessToken, false, isSandbox)
// self.documentRef = documentRef
self.documentRef = documentRef
if (documentRef) {
documentRef
.set({ accessToken, isSandbox }, { merge: true })
Expand Down
6 changes: 4 additions & 2 deletions functions/lib/banrisul/calculate-our-number.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,13 @@ const mod11 = (number, mod10) => {
return 11 - rest
}

const ourNumber = (number) => {
const ourNumber = (number, isSandbox, storeId, orderId) => {
const dvMod10 = mod10(number)
const dvMod11 = mod11(number, dvMod10)
// console.log(`>> number: ${number} mod10: ${dvMod10} mod11: ${dvMod11} <= ${storeId} #${orderId}`)
const ourNumber = isSandbox ? '264' : `${number}${dvMod10}${dvMod11}`

return `${number}${dvMod10}${dvMod11}`.padStart(10, '0')
return ourNumber.padStart(10, '0')
}

module.exports = ourNumber
4 changes: 2 additions & 2 deletions functions/lib/banrisul/payload-to-billet.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const abbreviateAddress = (address) => {
.substring(0, 35)
}

const createBodyToBillet = (appData, params) => {
const createBodyToBillet = (appData, params, ourNumber) => {
const { amount, buyer, to } = params
const {
fees, // Juros
Expand Down Expand Up @@ -52,7 +52,7 @@ const createBodyToBillet = (appData, params) => {
codigo: 3
},
valor_nominal: (amount.total).toFixed(2),
// nosso_numero: ourNumber, // OBS.: in case it is necessary to calculate our number
nosso_numero: ourNumber, // OBS.: in case it is necessary to calculate our number
seu_numero: Date.now().toString()
}

Expand Down
39 changes: 28 additions & 11 deletions functions/routes/ecom/modules/create-transaction.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const { baseUri } = require('../../../__env')
const Banrisul = require('../../../lib/banrisul/auth/create-access')
// const getOurNumber = require('../../../lib/banrisul/calculate-our-number')
const getOurNumber = require('../../../lib/banrisul/calculate-our-number')
const { createBodyToBillet } = require('../../../lib/banrisul/payload-to-billet')

exports.post = async ({ appSdk, admin }, req, res) => {
Expand Down Expand Up @@ -46,26 +46,29 @@ exports.post = async ({ appSdk, admin }, req, res) => {
await banrisul.preparing

// OBS.: in case it is necessary to calculate our number
// const documentRef = banrisul.documentRef && await banrisul.documentRef.get()
// const docAuthBarisul = documentRef?.data()
// const lastBilletNumber = (docAuthBarisul?.lastBilletNumber || 0) + 1
const documentRef = banrisul.documentRef && await banrisul.documentRef.get()
const docAuthBarisul = documentRef?.data()
const lastBilletNumber = (docAuthBarisul?.lastBilletNumber || 0) + 1

const banrisulAxios = banrisul.axios

// const ourNumber = getOurNumber(lastBilletNumber)
const body = createBodyToBillet(appData, params)
const ourNumber = getOurNumber(lastBilletNumber, appData.envoriment === 'teste', storeId, orderId)
const body = createBodyToBillet(appData, params, ourNumber)

console.log('>>body ', JSON.stringify(body))
redirectToPayment = false

// test
// const data = require('../../../lib/billet/billet-test')
if (!appData.beneficiary_code && appData.envoriment !== 'teste') {
throw new Error('Beneficiary code not found')
}

// test
// const data = require('../../../lib/billet/billet-test')

const beneficiaryCode = appData.envoriment === 'teste' ? '0010000001088' : appData.beneficiary_code
const { data } = await banrisulAxios.post('/boletos', body, {
headers: {
'bergs-beneficiario': appData.envoriment === 'teste' ? '0010000001088' : appData.beneficiary_code
'bergs-beneficiario': beneficiaryCode
}
})

Expand Down Expand Up @@ -96,9 +99,23 @@ exports.post = async ({ appSdk, admin }, req, res) => {

await collectionBillet.doc(orderId).set({ ...data, storeId, envoriment: appData.envoriment })

if (appData.envoriment && appData.envoriment !== 'produção') {
transaction.notes = `<div style="display:block;margin:0 auto">
<a href='${baseUri}/homologacao?orderId=${orderId}&request=${Buffer.from(JSON.stringify(body), 'utf-8').toString('base64url')}'>
<button type="button" class="btn btn-sm btn-light">Download Requisição</button>
<a>
</div>` +
'<br/>' +
`<div style="display:block;margin:0 auto">
<a href='${baseUri}/homologacao?orderId=${orderId}&response=${Buffer.from(JSON.stringify(data), 'utf-8').toString('base64url')}'>
<button type="button" class="btn btn-sm btn-light">Download Retorno</button>
<a>
</div>`
}

// OBS.: in case it is necessary to calculate our number
// banrisul.documentRef.set({ lastBilletNumber }, { merge: true })
// .catch(console.error)
banrisul.documentRef.set({ lastBilletNumber }, { merge: true })
.catch(console.error)

res.send({
redirect_to_payment: redirectToPayment,
Expand Down
15 changes: 15 additions & 0 deletions functions/routes/homologacao.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
exports.get = async ({ appSdk, admin }, req, res) => {
const { orderId, request, response } = req.query
let text = ''
let typeFile = ''
if (request) {
text = Buffer.from(request, 'base64url').toString('utf-8')
typeFile = 'resquest'
} else if (response) {
text = Buffer.from(response, 'base64url').toString('utf-8')
typeFile = 'response'
}
res.attachment(`${typeFile}-${orderId}.json`)
res.type('json')
res.send(text)
}
4 changes: 2 additions & 2 deletions hosting/description.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,8 @@ Após cadastro realizado no portal do Desenvolvedor do Banrisul, obtenha as cred
## 3) Homologação

* Crie um pedido com a opção de ambiente selecionada em `homologação`.
* Em seguida na opção de ambiente selecione `produção` e crie 5 pedidos e salve os PDFs
* Envie os 5 PDFs juntamente com os códigos de retornos, que são códigos das transações, para o e-mail: `atendimento_teste_cobranca@banrisul.com.br` para conferência.
* Em seguida na opção de ambiente selecione `produção` e crie 5 pedidos e salve os PDFs e os arquivos de requisição e retorno.
* Envie os 5 PDFs juntamente com os arquivos de requisição e retorno, que são códigos das transações, para o e-mail: `atendimento_teste_cobranca@banrisul.com.br` para conferência.

<br />

Expand Down

0 comments on commit 5f65029

Please sign in to comment.