Skip to content

Commit

Permalink
fix(ecom config): add field envoriment
Browse files Browse the repository at this point in the history
  • Loading branch information
wisley7l committed Aug 28, 2023
1 parent 6bf1907 commit d38b7b3
Show file tree
Hide file tree
Showing 9 changed files with 74 additions and 66 deletions.
15 changes: 10 additions & 5 deletions functions/ecom.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -165,12 +165,17 @@ const app = {
},
hide: true
},
is_homologation: {
envoriment: {
schema: {
type: 'boolean',
title: 'Ambiente de Homologação',
description: 'Habilitar ambiente para Homologação',
default: false
type: 'string',
enum: [
'teste',
'homologação',
'produção'
],
default: 'produção',
title: 'Ambiente',
description: 'Definir o ambiente'
},
hide: false
},
Expand Down
8 changes: 4 additions & 4 deletions functions/lib/banrisul/auth/create-access.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const createAxios = require('./create-axios')
const getOAuth = require('./get-token')

module.exports = function (clientId, clientSecret, storeId, firestoreColl = 'banrisul_auth') {
module.exports = function (clientId, clientSecret, storeId, isSandbox, firestoreColl = 'banrisul_auth') {
const self = this

let documentRef
Expand All @@ -14,19 +14,19 @@ module.exports = function (clientId, clientSecret, storeId, firestoreColl = 'ban

this.preparing = new Promise((resolve, reject) => {
const authenticate = (accessToken, documentRef) => {
self.axios = createAxios(accessToken)
self.axios = createAxios(accessToken, false, isSandbox)
// self.documentRef = documentRef
if (documentRef) {
documentRef
.set({ accessToken }, { merge: true })
.set({ accessToken, isSandbox }, { merge: true })
.catch(console.error)
}
resolve(self)
}

const handleAuth = () => {
console.log('> Banrisul Auth02 ', storeId)
getOAuth(clientId, clientSecret)
getOAuth(clientId, clientSecret, isSandbox)
.then((accessToken) => {
console.log(`>> s:${storeId} token => ${accessToken}`)
authenticate(accessToken, documentRef)
Expand Down
5 changes: 2 additions & 3 deletions functions/lib/banrisul/auth/create-axios.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
const axios = require('axios')
module.exports = (accessToken, isGetToken) => {
const isSandbox = false // TODO: false

module.exports = (accessToken, isGetToken, isSandbox) => {
console.log('>> ', isSandbox)
const headers = {
'Content-Type': 'application/json'
}
Expand Down
4 changes: 2 additions & 2 deletions functions/lib/banrisul/auth/get-token.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const axios = require('./create-axios')
const qs = require('qs')

module.exports = (clientId, clientSecret) => new Promise((resolve, reject) => {
const banrisulAxios = axios(null, true)
module.exports = (clientId, clientSecret, isSandbox) => new Promise((resolve, reject) => {
const banrisulAxios = axios(null, true, isSandbox)

const request = async (isRetry) => {
try {
Expand Down
8 changes: 4 additions & 4 deletions functions/lib/banrisul/check-billet.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,22 +51,22 @@ module.exports = async (admin, appSdk) => {
storeIds.push(storeId)
const auth = await appSdk.getAuth(storeId)
const appData = await getAppData({ appSdk, storeId, auth })
const banrisul = new Banrisul(appData.client_id, appData.client_secret, storeId)
const banrisul = new Banrisul(appData.client_id, appData.client_secret, storeId, appData.envoriment === 'teste')

await banrisul.preparing
const barisulAxios = banrisul.axios

for (let j = 0; j < docsBillets.length; j++) {
try {
const { titulo, orderId, refDoc } = docsBillets[j]
const idBoleto = titulo.nosso_numero
console.log('>> orderId: ', orderId, ' nosso numero', idBoleto)
const idBoleto = appData.envoriment === 'teste' ? '264' : titulo.nosso_numero
console.log('>> orderId: ', orderId, ' nosso numero', idBoleto, ' envoriment: ', appData.envoriment)

const { data: billet } = await barisulAxios.get(
`/boletos/${idBoleto}`,
{
headers: {
'bergs-beneficiario': appData.beneficiary_code
'bergs-beneficiario': appData.envoriment === 'teste' ? '0010000001088' : appData.beneficiary_code
}
}
)
Expand Down
6 changes: 3 additions & 3 deletions functions/lib/banrisul/payload-to-billet.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ const parseAddress = to => ({
complement: to.complement || ''
})

const createBodyToBillet = (appData, params, ourNumber) => {
const createBodyToBillet = (appData, params) => {
const { amount, buyer, to } = params
const {
fees, // Juros
tax // Multa
} = appData

const isHomologation = appData.is_homologation
const isTest = appData.envoriment === 'homologação' || appData.envoriment === 'teste'
const daysToExpiry = appData.days_to_expiry

const createdAt = new Date()
Expand Down Expand Up @@ -115,7 +115,7 @@ const createBodyToBillet = (appData, params, ourNumber) => {

Object.assign(titulo, { pagador })

return { ambiente: isHomologation ? 'T' : 'P', titulo }
return { ambiente: isTest ? 'T' : 'P', titulo }
}

module.exports = createBodyToBillet
86 changes: 45 additions & 41 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 @@ -34,56 +34,60 @@ exports.post = async ({ appSdk, admin }, req, res) => {

if (params.payment_method.code === 'banking_billet') {
try {
const banrisul = new Banrisul(appData.client_id, appData.client_secret, storeId)
console.log('>> s: ', storeId, ' beneficiary Code: ', appData.beneficiary_code)
if (appData.beneficiary_code) {
await banrisul.preparing
console.log('>> s: ', storeId, ' beneficiary Code: ', appData.beneficiary_code, ' envoriment: ', appData.envoriment)
const banrisul = new Banrisul(appData.client_id, appData.client_secret, storeId, appData.envoriment === 'teste')
// if (appData.beneficiary_code) {
await banrisul.preparing

//
// const documentRef = banrisul.documentRef && await banrisul.documentRef.get()
// const docAuthBarisul = documentRef?.data()
// const lastBilletNumber = (docAuthBarisul?.lastBilletNumber || 0) + 1
const banrisulAxios = banrisul.axios
//
// 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)
const body = createBodyToBillet(appData, params)

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

// test
// const data = require('../../../lib/billet/billet-test')
const { data } = await banrisulAxios.post('/boletos', body, {
headers: {
'bergs-beneficiario': appData.beneficiary_code
}
})
// test
// const data = require('../../../lib/billet/billet-test')
if (!appData.beneficiary_code && appData.envoriment !== 'teste') {
throw new Error('Beneficiary code not found')
}

console.log('>> boleto ', JSON.stringify(data))
transaction.banking_billet = {
code: data.titulo?.linha_digitavel,
valid_thru: new Date(data.titulo?.data_vencimento).toISOString(),
link: `${baseUri}/billet?orderId=${orderId}`
const { data } = await banrisulAxios.post('/boletos', body, {
headers: {
'bergs-beneficiario': appData.envoriment === 'teste' ? '0010000001088' : appData.beneficiary_code
}
})

transaction.intermediator = {
transaction_id: data?.titulo?.nosso_numero,
transaction_reference: data?.titulo?.nosso_numero,
transaction_code: data.retorno
}
console.log('>> boleto ', JSON.stringify(data))
transaction.banking_billet = {
code: data.titulo?.linha_digitavel,
valid_thru: new Date(data.titulo?.data_vencimento).toISOString(),
link: `${baseUri}/billet?orderId=${orderId}`
}

await collectionBillet.doc(orderId).set({ ...data, storeId, isHomologation: appData.is_homologation })
transaction.intermediator = {
transaction_id: data?.titulo?.nosso_numero,
transaction_reference: data?.titulo?.nosso_numero,
transaction_code: data.retorno
}

// banrisul.documentRef.set({ lastBilletNumber }, { merge: true })
// .catch(console.error)
await collectionBillet.doc(orderId).set({ ...data, storeId, envoriment: appData.envoriment })

res.send({
redirect_to_payment: redirectToPayment,
transaction
})
} else {
throw new Error('Beneficiary code not found')
}
// banrisul.documentRef.set({ lastBilletNumber }, { merge: true })
// .catch(console.error)

res.send({
redirect_to_payment: redirectToPayment,
transaction
})
// } else {
// throw new Error('Beneficiary code not found')
// }
} catch (error) {
console.log(error.response)
// try to debug request error
Expand Down
4 changes: 2 additions & 2 deletions functions/routes/ecom/modules/list-payments.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ exports.post = ({ appSdk }, req, res) => {
payment_gateways: []
}
const appData = Object.assign({}, application.data, application.hidden_data)
const isHomologation = appData.is_homologation
// const isProdution = appData.envoriment === 'produção'

const amount = { ...params.amount } || {}

Expand All @@ -42,7 +42,7 @@ exports.post = ({ appSdk }, req, res) => {
code: 'banking_billet',
name: 'Boleto Bancário'
},
label: `Boleto Bancário${isHomologation ? ' - Homologação' : ''}`,
label: `Boleto Bancário${appData.envoriment !== 'produção' ? ` - ${appData.envoriment}` : ''}`,
expiration_date: appData.expiration_date || 7
}

Expand Down
4 changes: 2 additions & 2 deletions hosting/description.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@ Após cadastro realizado no portal do Desenvolvedor do Banrisul, obtenha as cred

## 3) Homologação

* Crie um pedido com a opção homologação habilitada.
* Em seguida desabilite a opção homologação e crie 5 pedidos e salve os PDFs
* 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.

<br />
Expand Down

0 comments on commit d38b7b3

Please sign in to comment.