diff --git a/boleto_cloud/__manifest__.py b/boleto_cloud/__manifest__.py index 27e1f6cd..43e43f8d 100644 --- a/boleto_cloud/__manifest__.py +++ b/boleto_cloud/__manifest__.py @@ -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 ', + 'Felipe Paloschi ', + 'Renan Silveira ' ], 'depends': [ 'l10n_br_account', 'l10n_br_automated_payment', 'l10n_br_eletronic_document', - 'l10n_br_sale', ], 'data': [ 'security/ir.model.access.csv', @@ -23,4 +24,4 @@ 'views/account_move.xml', 'reports/boleto.xml', ], -} \ No newline at end of file +} diff --git a/boleto_cloud/models/__init__.py b/boleto_cloud/models/__init__.py index dbc43520..36fec5d1 100644 --- a/boleto_cloud/models/__init__.py +++ b/boleto_cloud/models/__init__.py @@ -2,4 +2,5 @@ from . import account_journal from . import res_company from . import boleto_cloud -from . import wizard_new_payment \ No newline at end of file +from . import wizard_new_payment +from . import eletronic_document diff --git a/boleto_cloud/models/account_move.py b/boleto_cloud/models/account_move.py index f1fac3c1..ca53ce5f 100644 --- a/boleto_cloud/models/account_move.py +++ b/boleto_cloud/models/account_move.py @@ -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)], }) diff --git a/boleto_cloud/models/boleto_cloud.py b/boleto_cloud/models/boleto_cloud.py index f85f48a5..a9cfc38f 100644 --- a/boleto_cloud/models/boleto_cloud.py +++ b/boleto_cloud/models/boleto_cloud.py @@ -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 @@ -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"], + } + ) diff --git a/boleto_cloud/models/eletronic_document.py b/boleto_cloud/models/eletronic_document.py index a568f15d..1ca793ff 100644 --- a/boleto_cloud/models/eletronic_document.py +++ b/boleto_cloud/models/eletronic_document.py @@ -20,4 +20,4 @@ def _find_attachment_ids_email(self): )) atts.append(pdf_id.id) - return atts \ No newline at end of file + return atts diff --git a/boleto_cloud/reports/boleto.py b/boleto_cloud/reports/boleto.py index 520fdc55..f631b408 100644 --- a/boleto_cloud/reports/boleto.py +++ b/boleto_cloud/reports/boleto.py @@ -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)]) diff --git a/boleto_cloud/views/account_journal.xml b/boleto_cloud/views/account_journal.xml index f249035b..0be419f3 100644 --- a/boleto_cloud/views/account_journal.xml +++ b/boleto_cloud/views/account_journal.xml @@ -4,7 +4,7 @@ account.journal - +