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

12.0 mig cnab_erpbrasil_febraban #769

Closed
wants to merge 12 commits into from
127 changes: 127 additions & 0 deletions cnab_erpbrasil_febraban/README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
=======================
Cnab Erpbrasil Febraban
=======================

.. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! This file is generated by oca-gen-addon-readme !!
!! changes will be overwritten. !!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

.. |badge1| image:: https://img.shields.io/badge/maturity-Beta-yellow.png
:target: https://odoo-community.org/page/development-status
:alt: Beta
.. |badge2| image:: https://img.shields.io/badge/licence-AGPL--3-blue.png
:target: http://www.gnu.org/licenses/agpl-3.0-standalone.html
:alt: License: AGPL-3
.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Fl10n--brazil-lightgray.png?logo=github
:target: https://github.com/OCA/l10n-brazil/tree/12.0/cnab_erpbrasil_febraban
:alt: OCA/l10n-brazil
.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png
:target: https://translation.odoo-community.org/projects/l10n-brazil-12-0/l10n-brazil-12-0-cnab_erpbrasil_febraban
:alt: Translate me on Weblate
.. |badge5| image:: https://img.shields.io/badge/runbot-Try%20me-875A7B.png
:target: https://runbot.odoo-community.org/runbot/124/12.0
:alt: Try me on Runbot

|badge1| |badge2| |badge3| |badge4| |badge5|

Este módulo permite a exportação e importação de arquivos bancários no formato CNAB 240,
permitindo as seguintes operações:

- Pagamento de Boletos;
- TED;
- DOC;
- Transferência entre contas do mesmo Banco;
- Pagamento de Impostos:
- DAS;
- ISS;
- DARF;
- GPS;
- Guias sem código de barras;

**Table of contents**

.. contents::
:local:

Installation
============

[ This file must only be present if there are very specific
installation instructions, such as installing non-python
dependencies. The audience is systems administrators. ]

* Este módulo tem uma depedencia do pacote python https://github.com/starkbank/febraban-python/

Usage
=====

[ This file must be present and contains the usage instructions
for end-users. As all other rst files included in the README,
it MUST NOT contain reStructuredText sections
only body text (paragraphs, lists, tables, etc). Should you need
a more elaborate structure to explain the addon, please create a
Sphinx documentation (which may include this file as a "quick start"
section). ]

To use this module, you need to:

#. Go to ...

Known issues / Roadmap
======================

[ Enumerate known caveats and future potential improvements.
It is mostly intended for end-users, and can also help
potential new contributors discovering new features to implement. ]

* ...

Bug Tracker
===========

Bugs are tracked on `GitHub Issues <https://github.com/OCA/l10n-brazil/issues>`_.
In case of trouble, please check there if your issue has already been reported.
If you spotted it first, help us smashing it by providing a detailed and welcomed
`feedback <https://github.com/OCA/l10n-brazil/issues/new?body=module:%20cnab_erpbrasil_febraban%0Aversion:%2012.0%0A%0A**Steps%20to%20reproduce**%0A-%20...%0A%0A**Current%20behavior**%0A%0A**Expected%20behavior**>`_.

Do not contact contributors directly about support or help with technical issues.

Credits
=======

Authors
~~~~~~~

* KMEE

Contributors
~~~~~~~~~~~~

* Luis Felipe Mileo <mileo@kmee.com.br>
* Gabriel Cardoso <gabriel.cardoso@kmee.com.br>

Other credits
~~~~~~~~~~~~~

O desenvolvimento deste módulo foi apoiado financeiramente por:

* KMEE


Maintainers
~~~~~~~~~~~

This module is maintained by the OCA.

.. image:: https://odoo-community.org/logo.png
:alt: Odoo Community Association
:target: https://odoo-community.org

OCA, or the Odoo Community Association, is a nonprofit organization whose
mission is to support the collaborative development of Odoo features and
promote its widespread use.

This module is part of the `OCA/l10n-brazil <https://github.com/OCA/l10n-brazil/tree/12.0/cnab_erpbrasil_febraban>`_ project on GitHub.

You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.
1 change: 1 addition & 0 deletions cnab_erpbrasil_febraban/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from . import models
25 changes: 25 additions & 0 deletions cnab_erpbrasil_febraban/__manifest__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Copyright 2019 KMEE
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

{
'name': 'Cnab Erpbrasil Febraban',
'summary': """
Integração com CNAB através da biblioteca erpbrasil.febraban""",
'version': '12.0.1.0.0',
'license': 'AGPL-3',
'author': 'KMEE, Odoo Community Association (OCA)',
'website': 'http://odoo-brasil.org',
'depends': [
'l10n_br_account_payment_order',
],
'data': [
],
'demo': [
'demo/account_payment_order.xml',
],
'external_dependencies': {
'python': [
'febraban',
],
},
}
7 changes: 7 additions & 0 deletions cnab_erpbrasil_febraban/demo/account_payment_order.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<odoo noupdate="1">

<function model="account.payment.order" name="draft2open" eval="[[ref('l10n_br_account_payment_order.account_payment_order_demo')]]"/>
<function model="account.payment.order" name="open2generated" eval="[[ref('l10n_br_account_payment_order.account_payment_order_demo')]]"/>

</odoo>
6 changes: 6 additions & 0 deletions cnab_erpbrasil_febraban/febraban/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# -*- coding: utf-8 -*-
# © 2012 KMEE INFORMATICA LTDA
# @author Luis Felipe Mileo <mileo@kmee.com.br>
# @author Daniel Sadamo <daniel.sadamo@kmee.com.br>
# @author Fernando Marcato <fernando.marcato@kmee.com.br>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
160 changes: 160 additions & 0 deletions cnab_erpbrasil_febraban/febraban/cnab.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
# © 2012 KMEE INFORMATICA LTDA
# @author Luis Felipe Mileo <mileo@kmee.com.br>
# @author Daniel Sadamo <daniel.sadamo@kmee.com.br>
# @author Fernando Marcato <fernando.marcato@kmee.com.br>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

import logging
import base64
import codecs
from unidecode import unidecode

_logger = logging.getLogger(__name__)

try:
from febraban.cnab240.itau.sispag import \
Transfer, DasPayment, IssPayment, UtilityPayment, File
from febraban.cnab240.itau.sispag.file.lot import Lot
from febraban.cnab240.libs.barCode import LineNumberO
from febraban.cnab240.user import User, UserAddress, UserBank
except ImportError as err:
_logger.debug = (err)


class Cnab(object):

def __init__(self):
self.arquivo = False
self.cnab_type = False

@staticmethod
def gerar_remessa(order):
bank_id = order.company_partner_bank_id.bank_id
bank_code = bank_id.code_bc
cnab_type = order.payment_mode_id.payment_method_id.code

if cnab_type == '240':
sender = User(
name=order.company_id.legal_name.upper(),
identifier=order.company_id.cnpj_cpf.replace(
'.', '').replace('/', '').replace('-', ''),
bank=UserBank(
bankId=bank_code,
branchCode=order.company_partner_bank_id.bra_number,
accountNumber=order.company_partner_bank_id.acc_number,
accountVerifier=
order.company_partner_bank_id.acc_number_dig
),
address=UserAddress(
streetLine1=(order.company_id.partner_id.street + ' ' +
(order.company_id.partner_id.street_number
or '')).upper(),
city=unidecode(order.company_id.city_id.name).upper(),
stateCode=order.company_id.state_id.code,
zipCode=order.company_id.zip.replace('-', '')
)
)

bank_line_obj = order.env['bank.payment.line']
option_obj = order.env['l10n_br.cnab.option']

file = File()
file.setSender(sender)

for group in bank_line_obj.read_group(
[('id', 'in', order.bank_line_ids.ids)],
[], ['release_form_id', 'service_type_id'], lazy=False
):
lot = Lot()
sender.name = order.company_id.legal_name.upper()
lot.setSender(sender)
lot.setHeaderLotType(
kind=option_obj.browse(group['service_type_id'][0]).code,
method=option_obj.browse(group['release_form_id'][0]).code,
)

for line in bank_line_obj.search(group['__domain']):
receiver = User(
name=line.partner_id.name.upper(),
identifier=(line.partner_id.cnpj_cpf or ''
).replace('-', '').replace(
'.', '').replace('/', ''),
bank=UserBank(
bankId=line.partner_bank_id.bank_id.code_bc,
branchCode=line.partner_bank_id.bra_number,
accountNumber=line.partner_bank_id.acc_number,
accountVerifier=
line.partner_bank_id.acc_number_dig
)
)

if line.release_form_id.code == "41":
payment = Transfer()
payment.setSender(sender)
payment.setReceiver(receiver)
payment.setAmountInCents(str(int(line.amount_currency * 100)))
payment.setScheduleDate(line.date.strftime('%d%m%Y'))
payment.setInfo(
reason="10" # Crédito em Conta Corrente
)
payment.setIdentifier("ID%s" % line.own_number)
elif line.release_form_id.code == "91":
payment = DasPayment()
payment.setPayment(
sender=sender,
scheduleDate=line.date.strftime('%d%m%Y'),
identifier="ID%s" % line.own_number,
lineNumber=LineNumberO(line.communication)
)
elif line.release_form_id.code == "19":
payment = IssPayment()
payment.setPayment(
sender=sender,
scheduleDate=line.date.strftime('%d%m%Y'),
identifier="ID%s" % line.own_number,
lineNumber=LineNumberO(line.communication)
)
elif line.release_form_id.code == "13":
payment = UtilityPayment()
payment.setPayment(
sender=sender,
scheduleDate=line.date.strftime('%d%m%Y'),
identifier="ID%s" % line.own_number,
lineNumber=LineNumberO(line.communication)
)
else:
continue
lot.add(register=payment)

file.addLot(lot)

return file.toString().encode()

@staticmethod
def detectar_retorno(cnab_file_object):
arquivo_retono = base64.b64decode(cnab_file_object)
f = open('/tmp/cnab_retorno.ret', 'wb')
f.write(arquivo_retono)
f.close()
arquivo_retorno = codecs.open(
'/tmp/cnab_retorno.ret',
encoding='ascii'
)
header = arquivo_retorno.readline()
arquivo_retorno.seek(0)

if 210 < len(header) < 410:
cnab_type = '400'
banco = header[76:79]
elif len(header) < 210:
cnab_type = '240'
banco = header[:3]

cnab = Cnab.get_cnab(banco, cnab_type)()
return cnab_type, cnab.retorno(arquivo_retorno)
#
# def retorno(self, arquivo_retorno):
# return ArquivoCobranca400(
# self.classe_retorno,
# arquivo=arquivo_retorno
# )
5 changes: 5 additions & 0 deletions cnab_erpbrasil_febraban/models/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Copyright 2019 KMEE
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

from . import account_payment_order
from . import l10n_br_cnab
27 changes: 27 additions & 0 deletions cnab_erpbrasil_febraban/models/account_payment_order.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Copyright 2019 KMEE
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

import logging

from odoo import api, models, fields
from ..febraban.cnab import Cnab

_logger = logging.getLogger(__name__)


class AccountPaymentOrder(models.Model):
_inherit = 'account.payment.order'

def _generate_payment_file(self):
try:
return Cnab.gerar_remessa(order=self), self.name + '.REM'
except Exception as e:
_logger.error("Erro ao gerar o arquivo: \n\n{0}".format(e))

@api.multi
def generate_payment_file(self):
"""Returns (payment file as string, filename)"""
self.ensure_one()
if self.payment_method_id.code in ('240', '400', '500'):
return self._generate_payment_file()
return super(AccountPaymentOrder, self).generate_payment_file()
Loading