Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Corrige erro ao emitir boleto via boleto_cloud e atualiza a base do código para a v14 #408

Open
wants to merge 1 commit into
base: 15.0
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions boleto_cloud/__manifest__.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
{ # pylint: disable=C8101,C8103
'name': 'Integração Boleto Cloud',
'version': '13.0.1.0.2',
'version': '15.0.0.0.0',
'category': 'account',
'author': 'Trustcode',
'website': 'http://www.trustcode.com.br',
'contributors': [
'Danimar Ribeiro <[email protected]>',
'Felipe Paloschi <[email protected]>',
'Renan Silveira <[email protected]>'
],
'depends': [
'l10n_br_account',
'l10n_br_automated_payment',
'l10n_br_eletronic_document',
'l10n_br_sale',
],
'data': [
'security/ir.model.access.csv',
Expand All @@ -23,4 +24,4 @@
'views/account_move.xml',
'reports/boleto.xml',
],
}
}
3 changes: 2 additions & 1 deletion boleto_cloud/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@
from . import account_journal
from . import res_company
from . import boleto_cloud
from . import wizard_new_payment
from . import wizard_new_payment
from . import eletronic_document
2 changes: 1 addition & 1 deletion boleto_cloud/models/account_move.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def send_information_to_boleto_cloud(self):
'amount': moveline.amount_residual,
'currency_id': moveline.move_id.currency_id.id,
'partner_id': moveline.partner_id.id,
'type': 'server2server',
#'type': 'server2server',
'date_maturity': moveline.date_maturity,
'invoice_ids': [(6, 0, self.ids)],
})
Expand Down
206 changes: 138 additions & 68 deletions boleto_cloud/models/boleto_cloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,43 @@
class BoletoCloud(models.Model):
_inherit = "payment.acquirer"

provider = fields.Selection(selection_add=[("boleto.cloud", "Boleto Cloud")], ondelete={'boleto.cloud': 'set default'})
provider = fields.Selection(
selection_add=[("boleto.cloud", "Boleto Cloud")],
ondelete={"boleto.cloud": "set default"},
)


class PaymentTransaction(models.Model):
_inherit = 'payment.transaction'
_inherit = "payment.transaction"

boleto_pdf = fields.Binary(string="Boleto PDF")
boleto_pdf_name = fields.Char(string="Nome Boleto")

def _find_attachment_ids_email(self):
atts = super(PaymentTransaction, self)._find_attachment_ids_email()

attachment_obj = self.env["ir.attachment"]
for transaction in self:

if transaction.boleto_pdf:
pdf_id = attachment_obj.create(
dict(
name=transaction.boleto_pdf_name,
datas=transaction.boleto_pdf,
mimetype="application/pdf",
res_model="account.move",
res_id=transaction.invoice_ids[0].id,
)
)
atts.append(pdf_id.id)

return atts


class CnabRemessa(models.Model):
_name = 'cnab.remessa'
_name = "cnab.remessa"
_description = "Remessa de CNAB"
_order = 'id desc'
_order = "id desc"

def _default_company(self):
return self.env.company
Expand All @@ -30,100 +53,147 @@ def _default_user(self):
return self.env.user

def _default_journal(self):
journal = self.env['account.journal'].search([('use_boleto_cloud', '=', True)], limit=1)
journal = self.env["account.journal"].search(
[("use_boleto_cloud", "=", True)], limit=1
)
return journal

name = fields.Char(max_length=30, string="Nome", required=True, default='/')
company_id = fields.Many2one('res.company', string='Company', default=_default_company)
user_id = fields.Many2one('res.users', string='Responsável', default=_default_user)
journal_id = fields.Many2one('account.journal', string="Diário", default=_default_journal)

cnab_file = fields.Binary('CNAB File', readonly=True)
cnab_file_name = fields.Binary('CNAB Name', readonly=True)
data_emissao_cnab = fields.Datetime('Data de Emissão do CNAB', readonly=True)
name = fields.Char(
max_length=30, string="Nome", required=True, default="/"
)
company_id = fields.Many2one(
"res.company", string="Company", default=_default_company
)
user_id = fields.Many2one(
"res.users", string="Responsável", default=_default_user
)
journal_id = fields.Many2one(
"account.journal", string="Diário", default=_default_journal
)

cnab_file = fields.Binary("CNAB File", readonly=True)
cnab_file_name = fields.Binary("CNAB Name", readonly=True)
data_emissao_cnab = fields.Datetime(
"Data de Emissão do CNAB", readonly=True
)
cnab_location = fields.Char()
state = fields.Selection([('draft', 'Provisorio'), ('done', 'Pronto')], default='draft')
state = fields.Selection(
[("draft", "Provisorio"), ("done", "Pronto")], default="draft"
)

def action_get_remessa(self):
if self.state == 'done':
raise UserError('Não é possível gerar o arquivo novamente!')
acquirer = self.env['payment.acquirer'].search([('provider', '=', 'boleto.cloud')])
if acquirer.state == 'enabled':
url = 'https://app.boletocloud.com/api/v1/arquivos/cnab/remessas'
if self.state == "done":
raise UserError("Não é possível gerar o arquivo novamente!")
acquirer = self.env["payment.acquirer"].search(
[("provider", "=", "boleto.cloud")]
)
if acquirer.state == "enabled":
url = "https://app.boletocloud.com/api/v1/arquivos/cnab/remessas"
else:
url = 'https://sandbox.boletocloud.com/api/v1/arquivos/cnab/remessas'
url = "https://sandbox.boletocloud.com/api/v1/arquivos/cnab/remessas"
api_token = self.company_id.boleto_cloud_api_token
data = {
'remessa.conta.token': self.journal_id.boleto_cloud_bank_account_api_key,
"remessa.conta.token": self.journal_id.boleto_cloud_bank_account_api_key,
}
response = requests.post(url, data=data, auth=(api_token, 'token'))
response = requests.post(url, data=data, auth=(api_token, "token"))

if response.status_code == 204:
raise UserError('Não há remessas CNAB a serem geradas.')
raise UserError("Não há remessas CNAB a serem geradas.")
elif response.status_code == 201:
arquivo = base64.b64encode(response.content)
remessa = self.write({
'cnab_file': arquivo,
'data_emissao_cnab': datetime.now(),
'cnab_location': response.headers['Location'],
'name': response.headers['Content-Disposition'].split('=')[1],
'state': 'done',
})
remessa = self.write(
{
"cnab_file": arquivo,
"data_emissao_cnab": datetime.now(),
"cnab_location": response.headers["Location"],
"name": response.headers["Content-Disposition"].split(
"="
)[1],
"state": "done",
}
)
else:
jsonp = response.json()
message = '\n'.join([x['mensagem'] for x in jsonp['erro']['causas']])
raise UserError('Houve um erro com a API do Boleto Cloud:\n%s' % message)
message = "\n".join(
[x["mensagem"] for x in jsonp["erro"]["causas"]]
)
raise UserError(
"Houve um erro com a API do Boleto Cloud:\n%s" % message
)
return remessa


class WizardImportCnabRetorno(models.TransientModel):
_name = 'wizard.import.cnab.retorno'
_name = "wizard.import.cnab.retorno"

def _default_journal(self):
journal = self.env['account.journal'].search([('use_boleto_cloud', '=', True)], limit=1)
journal = self.env["account.journal"].search(
[("use_boleto_cloud", "=", True)], limit=1
)
return journal

cnab_file = fields.Binary('Arquivo CNAB')
journal_id = fields.Many2one('account.journal', string='Diário', default=_default_journal)
cnab_file = fields.Binary("Arquivo CNAB")
journal_id = fields.Many2one(
"account.journal", string="Diário", default=_default_journal
)

def action_import_cnab_file(self):
if not self.cnab_file:
raise UserError('Arquivo CNAB não definido.')
raise UserError("Arquivo CNAB não definido.")
if not (self.journal_id or self.journal_id.use_boleto_cloud):
raise UserError('Diário não definido ou não configurado para usar o Boleto Cloud.')

acquirer = self.env['payment.acquirer'].search([('provider', '=', 'boleto.cloud')])
if acquirer.state == 'enabled':
url = 'https://app.boletocloud.com/api/v1/arquivos/cnab/retornos'
raise UserError(
"Diário não definido ou não configurado para usar o Boleto Cloud."
)

acquirer = self.env["payment.acquirer"].search(
[("provider", "=", "boleto.cloud")]
)
if acquirer.state == "enabled":
url = "https://app.boletocloud.com/api/v1/arquivos/cnab/retornos"
else:
url = 'https://sandbox.boletocloud.com/api/v1/arquivos/cnab/retornos'
url = "https://sandbox.boletocloud.com/api/v1/arquivos/cnab/retornos"
api_token = self.env.company.boleto_cloud_api_token

data = {'arquivo': base64.b64decode(self.cnab_file)}
response = requests.post(url, files=data, auth=(api_token, 'token'))
data = {"arquivo": base64.b64decode(self.cnab_file)}
response = requests.post(url, files=data, auth=(api_token, "token"))

if response.status_code == 400:
jsonp = response.json()
message = '\n'.join([x['mensagem'] for x in jsonp['erro']['causas']])
raise UserError('Houve um erro com a API do Boleto Cloud:\n%s' % message)

last_statement = self.env['account.bank.statement'].search([], order='id desc', limit=1)

statement = self.env['account.bank.statement'].create({
'name': response['arquivo']['protocolo']['numero'],
'journal_id': self.journal_id.id,
'date': datetime.now().date(),
'balance_start_real': last_statement.balance_end_real,
'balance_end_real': last_statement.balance_end_real + last_statement.total_entry_encoding,
})

for titulo in response['arquivo']['titulos']:
transaction = self.env['payment.transaction'].search([('acquirer_reference', '=', titulo['token'])])
self.env['account.bank.statement.line'].create({
'bank_statement_id': statement.id,
'date': datetime.strptime(titulo['vencimento'], '%Y-%m-%d'),
'name': titulo['numero'],
'partner_id': transaction.partner_id.id,
'ref': titulo['token'],
'amount': titulo['valor'],
})
message = "\n".join(
[x["mensagem"] for x in jsonp["erro"]["causas"]]
)
raise UserError(
"Houve um erro com a API do Boleto Cloud:\n%s" % message
)

last_statement = self.env["account.bank.statement"].search(
[], order="id desc", limit=1
)

statement = self.env["account.bank.statement"].create(
{
"name": response["arquivo"]["protocolo"]["numero"],
"journal_id": self.journal_id.id,
"date": datetime.now().date(),
"balance_start_real": last_statement.balance_end_real,
"balance_end_real": last_statement.balance_end_real
+ last_statement.total_entry_encoding,
}
)

for titulo in response["arquivo"]["titulos"]:
transaction = self.env["payment.transaction"].search(
[("acquirer_reference", "=", titulo["token"])]
)
self.env["account.bank.statement.line"].create(
{
"bank_statement_id": statement.id,
"date": datetime.strptime(
titulo["vencimento"], "%Y-%m-%d"
),
"name": titulo["numero"],
"partner_id": transaction.partner_id.id,
"ref": titulo["token"],
"amount": titulo["valor"],
}
)
2 changes: 1 addition & 1 deletion boleto_cloud/models/eletronic_document.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,4 @@ def _find_attachment_ids_email(self):
))
atts.append(pdf_id.id)

return atts
return atts
8 changes: 4 additions & 4 deletions boleto_cloud/reports/boleto.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,16 @@
class IrActionsReport(models.Model):
_inherit = 'ir.actions.report'

def _render_qweb_html(self, res_ids, data=None):
def render_qweb_html(self, res_ids, data=None):
if self.report_name == 'boleto_cloud.multiple_boleto':
return

return super(IrActionsReport, self)._render_qweb_html(
return super(IrActionsReport, self).render_qweb_html(
res_ids, data=data)

def _render_qweb_pdf(self, res_ids, data=None):
def render_qweb_pdf(self, res_ids, data=None):
if self.report_name != 'boleto_cloud.multiple_boleto':
return super(IrActionsReport, self)._render_qweb_pdf(
return super(IrActionsReport, self).render_qweb_pdf(
res_ids, data=data)

move_ids = self.env['account.move'].search([('id', 'in', res_ids)])
Expand Down
2 changes: 1 addition & 1 deletion boleto_cloud/views/account_journal.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<field name="model">account.journal</field>
<field name="inherit_id" ref="account.view_account_journal_form" />
<field name="arch" type="xml">
<field name="outbound_payment_method_line_ids" position="after">
<field name="code" position="after">
<field name="use_boleto_cloud"/>
<field name="boleto_cloud_bank_account_api_key" password="1"
attrs="{'invisible': [('use_boleto_cloud', '=', False)]}"/>
Expand Down