Skip to content

Commit

Permalink
Merge pull request odoo-brazil#14 from kmee/fix/refactory_module_paym…
Browse files Browse the repository at this point in the history
…ent_mode

Refatorar modulo para CNAB240
mileo authored Jul 20, 2017
2 parents d485b9c + 9abc03d commit cefbdc7
Showing 46 changed files with 1,923 additions and 481 deletions.
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
@@ -31,7 +31,7 @@ install:
- pip install git+https://github.com/aricaldeira/pybrasil.git
- pip install pyboleto
- pip install fixedwidth
- pip install https://github.com/kmee/cnab240/archive/master.zip
- pip install git+https://github.com/kmee/cnab240.git@feature/pagamento
- travis_install_nightly

before_script:
3 changes: 1 addition & 2 deletions l10n_br_account_banking_payment/__openerp__.py
Original file line number Diff line number Diff line change
@@ -32,7 +32,6 @@
'website': 'https://github.com/odoo-brazil/odoo-brazil-banking',
'category': 'Banking addons',
'depends': [
'l10n_br_account',
'l10n_br_account',
'account_banking_payment_export',
],
@@ -42,7 +41,7 @@
'views/payment_mode.xml',
'views/payment_mode_type.xml',
'wizard/payment_order_create_view.xml',
'data/payment_mode_type.xml',
# 'data/payment_mode_type.xml',
],
'demo': [
],
16 changes: 14 additions & 2 deletions l10n_br_account_banking_payment/models/account_payment.py
Original file line number Diff line number Diff line change
@@ -26,6 +26,7 @@
from openerp import models, fields, api
from openerp.addons import decimal_precision as dp
from openerp.tools.float_utils import float_round as round
from openerp.exceptions import ValidationError


class PaymentOrder(models.Model):
@@ -41,6 +42,17 @@ class PaymentOrder(models.Model):
def _compute_total(self):
self.total = sum(self.mapped('line_ids.amount') or [0.0])

@api.multi
def action_open(self):
"""
Validacao para nao confirmar ordem de pagamento vazia
"""
for record in self:
if not record.line_ids:
raise ValidationError("Impossivel confirmar linha vazia!")
res = super(PaymentOrder, self).action_open()
return res


class PaymentLine(models.Model):
_inherit = 'payment.line'
@@ -58,8 +70,8 @@ def _get_info_partner(self, cr, uid, partner_record, context=None):
cntry = partner_record.country_id and \
partner_record.country_id.name or ''
cnpj = partner_record.cnpj_cpf or ''
return partner_record.legal_name + "\n" + cnpj + "\n" + st + ", " \
+ n + " " + st1 + "\n" + zip_city + "\n" + cntry
return partner_record.legal_name or '' + "\n" + cnpj + "\n" + st \
+ ", " + n + " " + st1 + "\n" + zip_city + "\n" + cntry

@api.one
@api.depends('percent_interest', 'amount_currency')
3 changes: 0 additions & 3 deletions l10n_br_account_banking_payment/views/account_payment.xml
Original file line number Diff line number Diff line change
@@ -12,9 +12,6 @@
<field name="inherit_id"
ref="account_payment.view_payment_order_form"/>
<field name="arch" type="xml">
<field name="date" position="before">
<field name="linha_digitavel" colspan="4"/>
</field>
<xpath expr="//form[@string='Payment Line']/notebook/page/group/div" position="after">
<field name="percent_interest"/>
<field name="amount_interest"/>
Original file line number Diff line number Diff line change
@@ -26,10 +26,10 @@
class PaymentMode(models.Model):
_inherit = "payment.mode"

payment_order_type = fields.Selection(
selection_add=[
('tax', u'Tributos'),
])
# payment_order_type = fields.Selection(
# selection_add=[
# ('tax', u'Tributos'),
# ])
gnre_value_field = fields.Many2one(
'ir.model.fields', 'Value field',
domain=[('model_id', '=', 'account.invoice')])
@@ -40,24 +40,24 @@ class PaymentModeType(models.Model):
_inherit = 'payment.mode.type'
_description = 'Payment Mode Type'

payment_order_type = fields.Selection(
selection_add=[
('tax', u'Tributos'),
])
# payment_order_type = fields.Selection(
# selection_add=[
# ('tax', u'Tributos'),
# ])


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

payment_order_type = fields.Selection(
selection_add=[
('tax', u'Tributos'),
])
# payment_order_type = fields.Selection(
# selection_add=[
# ('tax', u'Tributos'),
# ])


class AccountMoveLine(models.Model):
_inherit = 'account.move.line'

has_gnre = fields.Boolean(
related='stored_invoice_id.has_gnre',
string="Tem GNRE")
# has_gnre = fields.Boolean(
# related='stored_invoice_id.has_gnre',
# string="Tem GNRE")
12 changes: 9 additions & 3 deletions l10n_br_account_banking_payment_cnab/__openerp__.py
Original file line number Diff line number Diff line change
@@ -37,22 +37,28 @@
'l10n_br_account_payment_boleto',
'l10n_br_account_payment_mode',
'l10n_br_account_product',
'account_banking_payment_export',
],
'data': [
'security/cnab_cobranca_security.xml',
'view/l10n_br_payment_cnab.xml',
'view/payment_order.xml',
'view/l10n_br_cnab_sequence.xml',
'view/l10n_br_cobranca_cnab.xml',
'view/l10n_br_cobranca_cnab_lines.xml',
'view/account_move_line.xml',
'view/res_partner_bank.xml',
'view/l10n_br_cnab_retorno_view.xml',
'view/payment_mode.xml',
'view/payment_line.xml',
'view/bank_payment_line.xml',
'data/l10n_br_payment_export_type.xml',
'data/l10n_br_payment_mode.xml',
'security/ir.model.access.csv',
],
'demo': [
# 'demo/l10n_br_payment_mode.xml',
],
'test': [
'tests/invoice_create.yml'
# 'tests/invoice_create.yml'
],
"installable": True,
"auto_install": False,
418 changes: 418 additions & 0 deletions l10n_br_account_banking_payment_cnab/constantes.py

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -3,16 +3,16 @@
<data noupdate="1">

<!-- payment.mode.type -->
<!-- CNAB 240 -->
<record id="payment_mode_type_cnab240" model="payment.mode.type">
<field name="code">240</field>
<field name="name">Cnab240</field>
<field name="active">True</field>
<field name="payment_order_type">cobranca</field>
<field name="ir_model_id"
ref="l10n_br_account_banking_payment_cnab.model_payment_cnab"/>
<field name="payment_order_type">payment</field>
<field name="ir_model_id" ref="l10n_br_account_banking_payment_cnab.model_payment_cnab"/>
<field name="suitable_bank_types"
eval="[(6,0,[ref('l10n_br_base.fund')])]"/>
<field name="company_id" ref="base.main_company"/>
<!--<field name="company_id" ref="base.main_company"/>-->
</record>

<!-- CNAB 400 -->
@@ -24,7 +24,7 @@
ref="l10n_br_account_banking_payment_cnab.model_payment_cnab"/>
<field name="suitable_bank_types"
eval="[(6,0,[ref('l10n_br_base.fund')])]"/>
<field name="company_id" ref="base.main_company"/>
<!--<field name="company_id" ref="base.main_company"/>-->
</record>

<!-- CNAB 500 -->
@@ -37,7 +37,7 @@
ref="l10n_br_account_banking_payment_cnab.model_payment_cnab"/>
<field name="suitable_bank_types"
eval="[(6,0,[ref('l10n_br_base.fund')])]"/>
<field name="company_id" ref="base.main_company"/>
<!--<field name="company_id" ref="base.main_company"/>-->
</record>

</data>
2 changes: 2 additions & 0 deletions l10n_br_account_banking_payment_cnab/febraban/cnab.py
Original file line number Diff line number Diff line change
@@ -22,6 +22,8 @@
##############################################################################
# TODO: implement abc factory?

from __future__ import division, print_function, unicode_literals


class Cnab(object):

Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# coding: utf-8

from __future__ import division, print_function, unicode_literals

import re
import string

from ..cnab_240 import Cnab240


class BB240(Cnab240):

def __init__(self):
super(Cnab240, self).__init__()
from cnab240.bancos import bancodobrasil
self.bank = bancodobrasil

def _prepare_header(self):
"""
Preparar header do arquivo.
Adicionar informações no header do arquivo do Banco do Brasil
"""
vals = super(BB240, self)._prepare_header()
# vals['servico_servico'] = 1
return vals

def _prepare_cobranca(self, line):
"""
Preparar o evento (segmentoA e segmentoB) apartir da payment.line
:param line - payment.line
:return: dict - Informações
"""
vals = super(BB240, self)._prepare_cobranca(line)
# vals['prazo_baixa'] = unicode(str(
# vals['prazo_baixa']), "utf-8")
# vals['desconto1_percentual'] = Decimal('0.00')
# vals['valor_iof'] = Decimal('0.00')
# # vals['cobrancasimples_valor_titulos'] = Decimal('02.00')
# vals['identificacao_titulo_banco'] = int(
# vals['identificacao_titulo_banco'])
# vals['cedente_conta_dv'] = unicode(str(
# vals['cedente_conta_dv']), "utf-8")
# vals['cedente_agencia_dv'] = unicode(str(
# vals['cedente_agencia_dv']), "utf-8")
# vals['cedente_dv_ag_cc'] = unicode(str(
# vals['cedente_dv_ag_cc']), "utf-8")
return vals

# Override cnab_240.nosso_numero. Diferentes números de dígitos entre
# CEF e Itau
def nosso_numero(self, format):
digito = format[-1:]
carteira = format[:3]
nosso_numero = re.sub(
'[%s]' % re.escape(string.punctuation), '', format[3:-1] or '')
return carteira, nosso_numero, digito

def str_to_unicode(inp_str):
inp_str = unicode(inp_str, "utf-8")
return inp_str
Original file line number Diff line number Diff line change
@@ -47,13 +47,13 @@ def _prepare_header(self):
vals['servico_servico'] = 1
return vals

def _prepare_segmento(self, line):
def _prepare_cobranca(self, line):
"""
:param line:
:return:
"""
vals = super(Bradesco240, self)._prepare_segmento(line)
vals = super(Bradesco240, self)._prepare_cobranca(line)
vals['prazo_baixa'] = unicode(str(
vals['prazo_baixa']), "utf-8")
vals['desconto1_percentual'] = Decimal('0.00')
Original file line number Diff line number Diff line change
@@ -57,13 +57,13 @@ def _prepare_header(self):

return vals

def _prepare_segmento(self, line):
def _prepare_cobranca(self, line):
"""
:param line:
:return:
"""
vals = super(Cef240, self)._prepare_segmento(line)
vals = super(Cef240, self)._prepare_cobranca(line)

carteira, nosso_numero, digito = self.nosso_numero(
line.move_line_id.transaction_ref)
Original file line number Diff line number Diff line change
@@ -54,13 +54,13 @@ def _prepare_header(self):
vals['cedente_agencia_dv']),
return vals

def _prepare_segmento(self, line):
def _prepare_cobranca(self, line):
"""
:param line:
:return:
"""
vals = super(Itau240, self)._prepare_segmento(line)
vals = super(Itau240, self)._prepare_cobranca(line)

carteira, nosso_numero, digito = self.nosso_numero(
line.move_line_id.transaction_ref)
Original file line number Diff line number Diff line change
@@ -49,11 +49,11 @@ def _prepare_header(self):
del vals['arquivo_hora_de_geracao']
return vals

def _prepare_segmento(self, line):
def _prepare_cobranca(self, line):
"""
:param line:
:return:
"""
vals = super(Santander240, self)._prepare_segmento(line)
vals = super(Santander240, self)._prepare_cobranca(line)
return vals
466 changes: 398 additions & 68 deletions l10n_br_account_banking_payment_cnab/febraban/cnab_240/cnab_240.py

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -48,13 +48,13 @@ def _prepare_header(self):
vals['servico_servico'] = 1
return vals

def _prepare_segmento(self, line):
def _prepare_cobranca(self, line):
"""
:param line:
:return:
"""
vals = super(Bradesco400, self)._prepare_segmento(line)
vals = super(Bradesco400, self)._prepare_cobranca(line)
vals['prazo_baixa'] = unicode(str(
vals['prazo_baixa']), "utf-8")
vals['desconto1_percentual'] = Decimal('0.00')
Original file line number Diff line number Diff line change
@@ -136,8 +136,6 @@ def _prepare_header(self):
'cedente_conta_dv': (self.order.mode.bank_id.acc_number_dig),
'cedente_agencia_dv': self.order.mode.bank_id.bra_number_dig,
'cedente_nome': self.order.company_id.legal_name,
# DV ag e conta
'cedente_dv_ag_cc': (self.order.mode.bank_id.bra_acc_dig),
'arquivo_codigo': 1, # Remessa/Retorno
'servico_operacao': u'R',
'nome_banco': unicode(self.order.mode.bank_id.bank_name),
@@ -176,7 +174,7 @@ def rmchar(self, format):
def codificar(self, texto):
return texto.encode('utf-8')

def _prepare_segmento(self, line):
def _prepare_cobranca(self, line):
"""
:param line:
:return:
@@ -236,8 +234,6 @@ def _prepare_segmento(self, line):
'cedente_conta': int(self.order.mode.bank_id.acc_number),
'cedente_conta_dv': self.order.mode.bank_id.acc_number_dig,
'cedente_agencia_dv': self.order.mode.bank_id.bra_number_dig,
# DV ag e cc
'cedente_dv_ag_cc': (self.order.mode.bank_id.bra_acc_dig),
'identificacao_titulo': u'0000000', # TODO
'identificacao_titulo_banco': u'0000000', # TODO
'identificacao_titulo_empresa': line.move_line_id.move_id.name,
@@ -303,7 +299,7 @@ def remessa(self, order):
self.order = order
self.arquivo = ArquivoCobranca400(self.bank, **self._prepare_header())
for line in order.line_ids:
self.arquivo.incluir_cobranca(**self._prepare_segmento(line))
self.arquivo.incluir_cobranca(**self._prepare_cobranca(line))
self.arquivo.trailer.num_seq_registro = self.controle_linha

remessa = unicode(self.arquivo)
Original file line number Diff line number Diff line change
@@ -45,13 +45,13 @@ def _prepare_header(self):
vals['codigo_comunicacao'] = int(self.order.mode.boleto_convenio)
return vals

def _prepare_segmento(self, line, vals):
def _prepare_cobranca(self, line, vals):
"""
:param line:
:return:
"""
vals = super(BradescoPagFor, self)._prepare_segmento(line, vals)
vals = super(BradescoPagFor, self)._prepare_cobranca(line, vals)

# TODO campo para informar a data do pagamento.
vals['data_para_efetivacao_pag'] = self.muda_campos_data(
Original file line number Diff line number Diff line change
@@ -249,7 +249,7 @@ def sacado_inscricao_tipo(self, partner_id):
def rmchar(self, format):
return re.sub('[%s]' % re.escape(string.punctuation), '', format or '')

def _prepare_segmento(self, line, vals):
def _prepare_cobranca(self, line, vals):
"""
:param line:
@@ -436,7 +436,7 @@ def lancamento_credito_bradesco(self, line):
'informacoes_complementares': u'',
}

return self._prepare_segmento(line, vals)
return self._prepare_cobranca(line, vals)

def lancamento_ted(self, line):
# TODO:
@@ -488,14 +488,14 @@ def lancamento_ted(self, line):

}

return self._prepare_segmento(line, vals)
return self._prepare_cobranca(line, vals)

def lancamento_doc(self):
# TODO:

vals = {}

return self._prepare_segmento(vals)
return self._prepare_cobranca(vals)

def lancamento_titulos_terceiros(self, line):
# TODO:
@@ -520,7 +520,7 @@ def lancamento_titulos_terceiros(self, line):

}

return self._prepare_segmento(vals)
return self._prepare_cobranca(vals)

def adiciona_digitos_num_pag(self, campo):
num_digitos = 16
4 changes: 4 additions & 0 deletions l10n_br_account_banking_payment_cnab/model/__init__.py
Original file line number Diff line number Diff line change
@@ -7,3 +7,7 @@
from . import payment_mode
from . import res_partner_bank
from . import res_partner
from .. import constantes
from . import payment_line
from . import bank_payment_line
from . import l10n_br_cnab
100 changes: 100 additions & 0 deletions l10n_br_account_banking_payment_cnab/model/bank_payment_line.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# -*- coding: utf-8 -*-
from openerp import models, fields, api
from ..constantes import COMPLEMENTO_TIPO_SERVICO, CODIGO_FINALIDADE_TED, \
AVISO_FAVORECIDO

STATE = [
('draft', 'Draft'),
('wait', 'Waiting Paiment'),
('exception', 'Exception'),
('paid', 'Paid'),
]


class BankPaymentLine(models.Model):
_inherit = 'bank.payment.line'

@api.model
def default_get(self, fields_list):
res = super(BankPaymentLine, self).default_get(fields_list)
mode = self.env['payment.order'].browse(
self.env.context.get('order_id')).mode
if mode.codigo_finalidade_doc:
res.update({
'codigo_finalidade_doc': mode.codigo_finalidade_doc})
if mode.codigo_finalidade_ted:
res.update({
'codigo_finalidade_ted': mode.codigo_finalidade_ted
})
if mode.codigo_finalidade_complementar:
res.update({
'codigo_finalidade_complementar':
mode.codigo_finalidade_complementar
})
if mode.aviso_ao_favorecido:
res.update({
'aviso_ao_favorecido': mode.aviso_ao_favorecido
})
return res

codigo_finalidade_doc = fields.Selection(
selection=COMPLEMENTO_TIPO_SERVICO,
string=u'Complemento do Tipo de Serviço',
help=u'Campo P005 do CNAB'
)
codigo_finalidade_ted = fields.Selection(
selection=CODIGO_FINALIDADE_TED,
string=u'Código Finalidade da TED',
help=u'Campo P011 do CNAB'
)
codigo_finalidade_complementar = fields.Char(
size=2,
string=u'Código de finalidade complementar',
help=u'Campo P013 do CNAB'
)
aviso_ao_favorecido = fields.Selection(
selection=AVISO_FAVORECIDO,
string=u'Aviso ao Favorecido',
help=u'Campo P006 do CNAB',
default='0',
)
abatimento = fields.Float(
digits=(13, 2),
string=u'Valor do Abatimento',
help=u'Campo G045 do CNAB',
default=0.00
)
desconto = fields.Float(
digits=(13, 2),
string=u'Valor do Desconto',
help=u'Campo G046 do CNAB',
default=0.00
)
mora = fields.Float(
digits=(13, 2),
string=u'Valor da Mora',
help=u'Campo G047 do CNAB',
default=0.00
)
multa = fields.Float(
digits=(13, 2),
string=u'Valor da Multa',
help=u'Campo G048 do CNAB',
default=0.00
)
state2 = fields.Selection(
string="State",
selection=STATE,
default="draft",
)
evento_id = fields.One2many(
string="Eventos CNAB",
comodel_name="l10n.br.cnab.evento",
inverse_name="bank_payment_line_id",
readonly=True
)
codigo_finalidade_complementar = fields.Char(
size=2,
string=u'Código de finalidade complementar',
help=u'Campo P013 do CNAB',
)
304 changes: 304 additions & 0 deletions l10n_br_account_banking_payment_cnab/model/l10n_br_cnab.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,304 @@
# -*- coding: utf-8 -*-
# Copyright 2017 KMEE - Luiz Felipe do Divino Costa <luiz.divino@kmee.com.br>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

import base64
import codecs
import logging
from datetime import datetime
from ..constantes import CODIGO_OCORRENCIAS

from openerp import api, models, fields, exceptions

_logger = logging.getLogger(__name__)
try:
from cnab240.bancos import bancodobrasil
from cnab240.tipos import Arquivo
except ImportError as err:
_logger.debug = (err)

STATE = [
('draft', 'Novo'),
('done', 'Processado'),
]

TIPO_OPERACAO = {
'C': u'Lançamento a Crédito',
'D': u'Lançamento a Débito',
'E': u'Extrato para Conciliação',
'G': u'Extrato para Gestão de Caixa',
'I': u'Informações de Títulos Capturados do Próprio Banco',
'R': u'Arquivo Remessa',
'T': u'Arquivo Retorno',
}

TIPO_SERVICO = {
'01': 'Cobrança',
'03': 'Boleto de Pagamento Eletrônico',
'04': 'Conciliação Bancária',
'05': 'Débitos',
'06': 'Custódia de Cheques',
'07': 'Gestão de Caixa',
'08': 'Consulta/Informação Margem',
'09': 'Averbação da Consignação/Retenção',
'10': 'Pagamento Dividendos',
'11': 'Manutenção da Consignação',
'12': 'Consignação de Parcelas',
'13': 'Glosa da Consignação (INSS)',
'14': 'Consulta de Tributos a pagar',
'20': 'Pagamento Fornecedor',
'22': 'Pagamento de Contas, Tributos e Impostos',
'23': 'Interoperabilidade entre Contas de Instituições de Pagamentos',
'25': 'Compror',
'26': 'Compror Rotativo',
'29': 'Alegação do Pagador',
'30': 'Pagamento Salários',
'32': 'Pagamento de honorários',
'33': 'Pagamento de bolsa auxílio',
'34': 'Pagamento de prebenda (remuneração a padres e sacerdotes)',
'40': 'Vendor',
'41': 'Vendor a Termo',
'50': 'Pagamento Sinistros Segurados',
'60': 'Pagamento Despesas Viajante em Trânsito',
'70': 'Pagamento Autorizado',
'75': 'Pagamento Credenciados',
'77': 'Pagamento de Remuneração',
'80': 'Pagamento Representantes / Vendedores Autorizados',
'90': 'Pagamento Benefícios',
'98': 'Pagamentos Diversos',
}

TIPO_INSCRICAO_EMPRESA = {
0: 'Isento / Não informado',
1: 'CPF',
2: 'CGC / CNPJ',
3: 'PIS / PASEP',
9: 'Outros',
}


class L10nBrHrCnab(models.Model):
_name = "l10n.br.cnab"
_rec_name = "display_name"

@api.multi
def processar_arquivo_retorno(self):
arquivo_retono = base64.b64decode(self.arquivo_retorno)
f = open('/tmp/cnab_retorno.ret', 'wb')
f.write(arquivo_retono)
f.close()
arquivo_retono = codecs.open('/tmp/cnab_retorno.ret', encoding='ascii')
arquivo_parser = Arquivo(bancodobrasil, arquivo=arquivo_retono)
if not arquivo_parser.header.arquivo_codigo == u'2':
raise exceptions.Warning(
u"Este não é um arquivo de retorno!"
)
data_arquivo = str(arquivo_parser.header.arquivo_data_de_geracao)
self.data_arquivo = fields.Date.from_string(
data_arquivo[4:] + "-" + data_arquivo[2:4] + "-" +
data_arquivo[0:2]
)
self.bank_account_id = self.env['res.partner.bank'].search(
[('acc_number', '=', arquivo_parser.header.cedente_conta)]).id
self.num_lotes = arquivo_parser.trailer.totais_quantidade_lotes
self.num_eventos = arquivo_parser.trailer.totais_quantidade_registros
for lote in arquivo_parser.lotes:
account_bank_id_lote = self.env['res.partner.bank'].search(
[('acc_number', '=', lote.header.cedente_conta)]
).id
vals = {
'account_bank_id': account_bank_id_lote,
'empresa_inscricao_numero':
str(lote.header.empresa_inscricao_numero),
'empresa_inscricao_tipo':
TIPO_INSCRICAO_EMPRESA[lote.header.empresa_inscricao_tipo],
'servico_operacao':
TIPO_OPERACAO[lote.header.servico_operacao],
'tipo_servico': TIPO_SERVICO[str(lote.header.servico_servico)],
'mensagem': lote.header.mensagem1,
'qtd_registros': lote.trailer.quantidade_registros,
'total_valores': float(lote.trailer.somatoria_valores),
'cnab_id': self.id,
}
lote_id = self.env['l10n.br.cnab.lote'].create(vals)
for evento in lote.eventos:
data_evento = str(
evento.credito_data_real)
data_evento = fields.Date.from_string(
data_evento[4:] + "-" + data_evento[2:4] + "-" +
data_evento[0:2]
)
account_bank_id_lote = self.env['res.partner.bank'].search(
[
('bra_number', '=', evento.favorecido_agencia),
('bra_number_dig', '=', evento.favorecido_agencia_dv),
('acc_number', '=', evento.favorecido_conta),
('acc_number_dig', '=', evento.favorecido_conta_dv)
])
account_bank_id_lote = account_bank_id_lote.ids[0] \
if account_bank_id_lote else False
favorecido_partner = self.env['res.partner.bank'].search(
[('owner_name', 'ilike', evento.favorecido_nome)]
)
favorecido_partner = favorecido_partner[0].partner_id.id \
if favorecido_partner else False
bank_payment_line_id = self.env['bank.payment.line'].search(
[
('name', '=', evento.credito_seu_numero)
]
)
ocorrencias_dic = dict(CODIGO_OCORRENCIAS)
ocorrencias = [
evento.ocorrencias[0:2],
evento.ocorrencias[2:4],
evento.ocorrencias[4:6],
evento.ocorrencias[6:8],
evento.ocorrencias[8:10]
]
vals_evento = {
'data_real_pagamento': data_evento,
'segmento': evento.servico_segmento,
'favorecido_nome': favorecido_partner,
'favorecido_conta_bancaria': account_bank_id_lote,
'nosso_numero': str(evento.credito_nosso_numero),
'seu_numero': evento.credito_seu_numero,
'tipo_moeda': evento.credito_moeda_tipo,
'valor_pagamento': evento.credito_valor_pagamento,
'ocorrencias': evento.ocorrencias,
'str_motiv_a': ocorrencias_dic[ocorrencias[0]] if
ocorrencias[0] else '',
'str_motiv_b': ocorrencias_dic[ocorrencias[1]] if
ocorrencias[1] else '',
'str_motiv_c': ocorrencias_dic[ocorrencias[2]] if
ocorrencias[2] else '',
'str_motiv_d': ocorrencias_dic[ocorrencias[3]] if
ocorrencias[3] else '',
'str_motiv_e': ocorrencias_dic[ocorrencias[4]] if
ocorrencias[4] else '',
'lote_id': lote_id.id,
'bank_payment_line_id': bank_payment_line_id.id,
}
self.env['l10n.br.cnab.evento'].create(vals_evento)
if evento.ocorrencias and bank_payment_line_id:
if '00' in ocorrencias:
bank_payment_line_id.write({'state2': 'paid'})
else:
bank_payment_line_id.write({'state2': 'exception'})

return self.write({'state': 'done'})

@api.multi
def _get_name(self, data):
cnab_ids = self.search([('data', '=', data)])
return data + " - " + (
str(len(cnab_ids) + 1) if cnab_ids else '1'
)

@api.model
def create(self, vals):
name = self._get_name(vals['data'])
vals.update({'name': name})
return super(L10nBrHrCnab, self).create(vals)

arquivo_retorno = fields.Binary(string='Arquivo Retorno')
data = fields.Date(
string="Data CNAB",
required=True,
default=datetime.now()
)
name = fields.Char(
string="Name",
)
lote_id = fields.One2many(
string="Lotes",
comodel_name="l10n.br.cnab.lote",
inverse_name="cnab_id"
)
state = fields.Selection(
string=u"Estágio",
selection=STATE,
default="draft",
)
data_arquivo = fields.Datetime(
string="Data Criação no Banco",
)
bank_account_id = fields.Many2one(
string="Conta cedente",
comodel_name="res.partner.bank",
)
num_lotes = fields.Integer(
string=u"Número de Lotes",
)
num_eventos = fields.Integer(
string=u"Número de Eventos",
)


class L10nBrHrCnabLote(models.Model):
_name = "l10n.br.cnab.lote"

account_bank_id = fields.Many2one(
string=u"Conta Bancária",
comodel_name="res.partner.bank",
)
empresa_inscricao_numero = fields.Char(string=u"Número de Inscrição")
empresa_inscricao_tipo = fields.Char(string=u"Tipo de Inscrição")
servico_operacao = fields.Char(string=u"Tipo de Operação")
tipo_servico = fields.Char(strin=u"Tipo do Serviço")
mensagem = fields.Char(string="Mensagem")
qtd_registros = fields.Integer(string="Quantidade de Registros")
total_valores = fields.Float(string="Valor Total")
evento_id = fields.One2many(
string="Eventos",
comodel_name="l10n.br.cnab.evento",
inverse_name="lote_id",
)
cnab_id = fields.Many2one(
string="CNAB",
comodel_name="l10n.br.cnab"
)
state = fields.Selection(
string="State",
related="cnab_id.state",
selection=STATE,
default="draft",
)


class L10nBrHrCnabEvento(models.Model):
_name = "l10n.br.cnab.evento"

data_real_pagamento = fields.Datetime(string="Data Real do Pagamento")
segmento = fields.Char(string="Segmento")
favorecido_nome = fields.Many2one(
string="Favorecido",
comodel_name="res.partner"
)
favorecido_conta_bancaria = fields.Many2one(
string=u"Conta Bancária",
comodel_name="res.partner.bank",
)
nosso_numero = fields.Char(string=u"Nosso Número")
seu_numero = fields.Char(string=u"Seu Número")
tipo_moeda = fields.Char(string=u"Tipo de Moeda")
valor_pagamento = fields.Float(string="Valor do Pagamento")
ocorrencias = fields.Char(string=u"Ocorrências")
str_motiv_a = fields.Char(u'Motivo da ocorrência 01')
str_motiv_b = fields.Char(u'Motivo de ocorrência 02')
str_motiv_c = fields.Char(u'Motivo de ocorrência 03')
str_motiv_d = fields.Char(u'Motivo de ocorrência 04')
str_motiv_e = fields.Char(u'Motivo de ocorrência 05')
bank_payment_line_id = fields.Many2one(
string="Bank Payment Line",
comodel_name="bank.payment.line",
)
lote_id = fields.Many2one(
string="Lote",
comodel_name="l10n.br.cnab.lote",
)
state = fields.Selection(
string="State",
related="lote_id.state",
selection=STATE,
default="draft",
)
94 changes: 94 additions & 0 deletions l10n_br_account_banking_payment_cnab/model/payment_line.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# -*- coding: utf-8 -*-
from openerp import models, fields, api
from ..constantes import COMPLEMENTO_TIPO_SERVICO, CODIGO_FINALIDADE_TED, \
AVISO_FAVORECIDO

STATE = [
('draft', 'Draft'),
('wait', 'Waiting Paiment'),
('exception', 'Exception'),
('paid', 'Paid'),
]


class PaymentLine(models.Model):
_inherit = 'payment.line'

@api.model
def default_get(self, fields_list):
res = super(PaymentLine, self).default_get(fields_list)
mode = self.env['payment.order'].browse(
self.env.context.get('order_id')).mode
if mode.codigo_finalidade_doc:
res.update({
'codigo_finalidade_doc': mode.codigo_finalidade_doc})
if mode.codigo_finalidade_ted:
res.update({
'codigo_finalidade_ted': mode.codigo_finalidade_ted
})
if mode.codigo_finalidade_complementar:
res.update({
'codigo_finalidade_complementar':
mode.codigo_finalidade_complementar
})
if mode.aviso_ao_favorecido:
res.update({
'aviso_ao_favorecido': mode.aviso_ao_favorecido
})
return res

seu_numero = fields.Char(
string=u'Seu Número',
size=20,
help=u'Campo G064'
)
codigo_finalidade_doc = fields.Selection(
selection=COMPLEMENTO_TIPO_SERVICO,
string=u'Complemento do Tipo de Serviço',
help=u'Campo P005 do CNAB',
)
codigo_finalidade_ted = fields.Selection(
selection=CODIGO_FINALIDADE_TED,
string=u'Código Finalidade da TED',
help=u'Campo P011 do CNAB',
)
codigo_finalidade_complementar = fields.Char(
size=2,
string=u'Código de finalidade complementar',
help=u'Campo P013 do CNAB',
)
aviso_ao_favorecido = fields.Selection(
selection=AVISO_FAVORECIDO,
string=u'Aviso ao Favorecido',
help=u'Campo P006 do CNAB',
default='0',
)
abatimento = fields.Float(
digits=(13, 2),
string=u'Valor do Abatimento',
help=u'Campo G045 do CNAB',
default=0.00
)
desconto = fields.Float(
digits=(13, 2),
string=u'Valor do Desconto',
help=u'Campo G046 do CNAB',
default=0.00
)
mora = fields.Float(
digits=(13, 2),
string=u'Valor da Mora',
help=u'Campo G047 do CNAB',
default=0.00
)
multa = fields.Float(
digits=(13, 2),
string=u'Valor da Multa',
help=u'Campo G048 do CNAB',
default=0.00
)
state2 = fields.Selection(
related="bank_line_id.state2",
selection=STATE,
default="draft",
)
39 changes: 39 additions & 0 deletions l10n_br_account_banking_payment_cnab/model/payment_mode.py
Original file line number Diff line number Diff line change
@@ -22,6 +22,8 @@

from openerp import models, fields
from openerp.addons import decimal_precision as dp
from ..constantes import TIPO_SERVICO, FORMA_LANCAMENTO, \
COMPLEMENTO_TIPO_SERVICO, CODIGO_FINALIDADE_TED, AVISO_FAVORECIDO


class PaymentMode(models.Model):
@@ -34,5 +36,42 @@ class PaymentMode(models.Model):
cnab_percent_interest = fields.Float(string=u"Percentual de Juros",
digits=dp.get_precision('Account'))
comunicacao_2 = fields.Char("Comunicação para o sacador avalista")
tipo_servico = fields.Selection(
selection=TIPO_SERVICO,
string=u'Tipo de Serviço',
help=u'Campo G025 do CNAB'
)
forma_lancamento = fields.Selection(
selection=FORMA_LANCAMENTO,
string=u'Forma Lançamento',
help=u'Campo G029 do CNAB'
)
codigo_convenio = fields.Char(
size=20,
string=u'Código do Convênio no Banco',
help=u'Campo G007 do CNAB',
default=u'0001222130126',
)
codigo_finalidade_doc = fields.Selection(
selection=COMPLEMENTO_TIPO_SERVICO,
string=u'Complemento do Tipo de Serviço',
help=u'Campo P005 do CNAB'
)
codigo_finalidade_ted = fields.Selection(
selection=CODIGO_FINALIDADE_TED,
string=u'Código Finalidade da TED',
help=u'Campo P011 do CNAB'
)
codigo_finalidade_complementar = fields.Char(
size=2,
string=u'Código de finalidade complementar',
help=u'Campo P013 do CNAB',
)
aviso_ao_favorecido = fields.Selection(
selection=AVISO_FAVORECIDO,
string=u'Aviso ao Favorecido',
help=u'Campo P006 do CNAB',
default=0,
)
# A exportação CNAB não se encaixa somente nos parâmetros de
# débito e crédito.
106 changes: 53 additions & 53 deletions l10n_br_account_banking_payment_cnab/model/payment_order.py
Original file line number Diff line number Diff line change
@@ -1,65 +1,65 @@
# -*- coding: utf-8 -*-
# #############################################################################
#
#
# Copyright (C) 2012 KMEE (http://www.kmee.com.br)
# @author Fernando Marcato Rodrigues
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
# Copyright 2012 KMEE - Fernando Marcato Rodrigues
# Copyright 2017 KMEE - Hendrix Costa <hendrix.costa@kmee.com.br>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

from openerp import api, models, fields
from __future__ import division, print_function, unicode_literals

# TODO: funcao a ser chamada por ação automatizada para resetar o sufixo
# diariamente
from openerp import models, fields

from ..constantes import TIPO_SERVICO, FORMA_LANCAMENTO, \
INDICATIVO_FORMA_PAGAMENTO, TIPO_MOVIMENTO, CODIGO_INSTRUCAO_MOVIMENTO


class PaymentOrder(models.Model):
_inherit = 'payment.order'
_inherit = b'payment.order'

file_number = fields.Integer(
string=u'Número sequencial do arquivo',
)

file_number = fields.Integer(u'Número sequencial do arquivo')
# TODO adicionar domain para permitir o modo de pagamento correspondente
# ao mode
serie_id = fields.Many2one(
'l10n_br_cnab.sequence', u'Sequencia interna')
sufixo_arquivo = fields.Integer(u'Sufixo do arquivo')
serie_sufixo_arquivo = fields.Many2one(
'l10n_br_cnab_file_sufix.sequence', u'Série do Sufixo do arquivo')
cnab_file = fields.Binary(
string='CNAB File',
readonly=True,
)

@api.multi
def get_next_number(self):
for ord in self:
sequence = self.env['ir.sequence']
# sequence_read = sequence.read(
# cr, uid, ord.serie_id.internal_sequence_id.id,
# ['number_next'])
seq_no = sequence.get_id(ord.serie_id.internal_sequence_id.id)
ord.write({'file_number': seq_no})
return seq_no
cnab_filename = fields.Char("CNAB Filename")

@api.multi
def get_next_sufixo(self):
for ord in self:
sequence = self.env['ir.sequence']
# sequence_read = sequence.read(
# cr, uid, ord.serie_id.internal_sequence_id.id,
# ['number_next'])
seq_no = sequence.get_id(
ord.serie_sufixo_arquivo.internal_sequence_id.id)
ord.write({'sufixo_arquivo': seq_no})
return seq_no
tipo_servico = fields.Selection(
selection=TIPO_SERVICO,
string=u'Tipo de Serviço',
help=u'Campo G025 do CNAB',
default='30',
)
forma_lancamento = fields.Selection(
selection=FORMA_LANCAMENTO,
string=u'Forma Lançamento',
help=u'Campo G029 do CNAB'
)
codigo_convenio = fields.Char(
size=20,
string=u'Código do Convênio no Banco',
help=u'Campo G007 do CNAB',
default=u'0001222130126',
)
indicativo_forma_pagamento = fields.Selection(
selection=INDICATIVO_FORMA_PAGAMENTO,
string=u'Indicativo de Forma de Pagamento',
help='Campo P014 do CNAB',
default='01'
)
tipo_movimento = fields.Selection(
selection=TIPO_MOVIMENTO,
string='Tipo de Movimento',
help='Campo G060 do CNAB',
default='0',
)
codigo_instrucao_movimento = fields.Selection(
selection=CODIGO_INSTRUCAO_MOVIMENTO,
string='Código da Instrução para Movimento',
help='Campo G061 do CNAB',
default='0',
)

# @api.multi
# def set_to_draft(self, *args):
54 changes: 23 additions & 31 deletions l10n_br_account_banking_payment_cnab/model/res_partner_bank.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,7 @@
# -*- coding: utf-8 -*-
# #############################################################################
#
#
# Copyright (C) 2012 KMEE (http://www.kmee.com.br)
# @author Fernando Marcato Rodrigues
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
# Copyright 2012 KMEE - Fernando Marcato Rodrigues
# Copyright 2017 KMEE - Hendrix Costa <hendrix.costa@kmee.com.br>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

from openerp import models, fields

@@ -28,18 +11,27 @@ class ResPartnerBank(models.Model):
bancárias no Brasil."""
_inherit = 'res.partner.bank'

bra_acc_dig = fields.Char(u'Digito Verificador Agência/Conta', size=1)
codigo_da_empresa = fields.Integer(
u'Código da empresa', size=20,
u'Código da empresa',
size=20,
help=u"Será informado pelo banco depois do cadastro do beneficiário "
u"na agência")
u"na agência"
)

tipo_de_conta = fields.Selection(
[('01', u'Conta corrente individual'),
('02', u'Conta poupança individual'),
('03', u'Conta depósito judicial/Depósito em consignação individual'),
('11', u'Conta corrente conjunta'),
('12', u'Conta poupança conjunta'),
('13', u'Conta depósito judicial/Depósito em consignação conjunta')
],
u'Tipo de Conta', default='01'
selection=[
('01', u'Conta corrente individual'),
('02', u'Conta poupança individual'),
('03', u'Conta depósito judicial/Depósito em consignação '
u'individual'),
('11', u'Conta corrente conjunta'),
('12', u'Conta poupança conjunta'),
('13', u'Conta depósito judicial/Depósito em consignação '
u'conjunta')],
string=u'Tipo de Conta',
default='01'
)

bra_number = fields.Char(
size=5,
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8" ?>
<openerp>
<data>

<record id="group_cnab_cobranca" model="res.groups">
<field name="name">CNAB Cobranca</field>
<field name="category_id" ref="base.module_category_accounting_and_finance"/>
</record>

</data>
</openerp>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
"id","name","model_id:id","group_id:id","perm_read","perm_write","perm_create","perm_unlink"
access_l10n_br_cnab,access_l10n_br_cnab,model_l10n_br_cnab,,1,0,0,0
access_l10n_br_cnab_lote,access_l10n_br_cnab_lote,model_l10n_br_cnab_lote,,1,0
access_l10n_br_cnab_evento,access_l10n_br_cnab_evento,model_l10n_br_cnab_evento,,1,0,0,0
access_l10n_br_cnab_sequence,access_l10n_br_cnab_sequence,model_l10n_br_cnab_sequence,,1,0,0,0
access_l10n_br_cnab_file_sufix_sequence,access_l10n_br_cnab_file_sufix_sequence,model_l10n_br_cnab_file_sufix_sequence,,1,0,0,0
207 changes: 0 additions & 207 deletions l10n_br_account_banking_payment_cnab/tests/invoice_create.yml

This file was deleted.

36 changes: 36 additions & 0 deletions l10n_br_account_banking_payment_cnab/view/bank_payment_line.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<openerp>
<data>

<record id="bank_payment_line_form" model="ir.ui.view">
<field name="name">bank.payment.line.form</field>
<field name="model">bank.payment.line</field>
<field name="inherit_id" ref="account_banking_payment_export.bank_payment_line_form"/>
<field name="arch" type="xml">
<group name="main" position="before">
<header>
<field name="state2" widget="statusbar" nolabel="1" statusbar_visible="draft,wait,paid" clickable="True"/>
</header>
</group>
<group name="main" position="after">
<group>
<field name="codigo_finalidade_doc"/>
<field name="codigo_finalidade_ted"/>
<field name="codigo_finalidade_complementar"/>
<field name="abatimento"/>
<field name="desconto"/>
<field name="mora"/>
<field name="multa"/>
<field name="aviso_ao_favorecido"/>
</group>
<xpath expr="//group[@string='Related Payment Lines'" position="after">
<group string="Histórico de Eventos CNAB Relacionados" name="evento-lines">
<field name="evento_id" nolabel="1"/>
</group>
</xpath>
</group>
</field>
</record>

<menuitem id="menu_banking_payment_line" name="Linhas Bancárias de Pagamento" action="account_banking_payment_export.bank_payment_line_action" parent="account_payment.menu_main_payment" sequence="7"/>
</data>
</openerp>
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
<?xml version="1.0" encoding="UTF-8" ?>
<openerp>
<data>

<menuitem id="menu_main_cnab" name="CNAB" parent="account.menu_finance" sequence="6"/>

<record id="view_cnab_retorno_tree" model="ir.ui.view">
<field name="name">cnab.retorno.tree</field>
<field name="model">l10n.br.cnab</field>
<field name="arch" type="xml">
<tree string="CNAB Retorno Lines">
<field name="name" />
<field name="data" />
<field name="arquivo_retorno" />
<field name="data_arquivo" />
<field name="bank_account_id" />
<field name="num_lotes" />
<field name="num_eventos" />
</tree>
</field>
</record>

<record id="view_cnab_lote_tree" model="ir.ui.view">
<field name="name">cnab.lote.tree</field>
<field name="model">l10n.br.cnab.lote</field>
<field name="arch" type="xml">
<tree string="CNAB Lotes Lines">
<field name="account_bank_id" />
<field name="empresa_inscricao_numero" />
<field name="empresa_inscricao_tipo" />
<field name="servico_operacao" />
<field name="tipo_servico" />
<field name="mensagem" />
<field name="qtd_registros" />
<field name="total_valores" />
<field name="evento_id" context="{'form_view_ref':'l10n_br_account_banking_payment_cnab.cnab_retorno_evento_form_view'}" />
</tree>
</field>
</record>

<record id="view_cnab_evento_tree" model="ir.ui.view">
<field name="name">cnab.evento.tree</field>
<field name="model">l10n.br.cnab.evento</field>
<field name="arch" type="xml">
<tree string="CNAB Evento Lines">
<field name="data_real_pagamento" />
<field name="segmento" />
<field name="favorecido_nome" />
<field name="nosso_numero" />
<field name="seu_numero" />
<field name="tipo_moeda" />
<field name="valor_pagamento" />
<field name="ocorrencias" />
<field name="str_motiv_a" />
<field name="str_motiv_b" />
<field name="str_motiv_c" />
<field name="str_motiv_d" />
<field name="str_motiv_e" />
</tree>
</field>
</record>

<record id="cnab_retorno_evento_form_view" model="ir.ui.view">
<field name="name">cnab.retorno.evento.form.view</field>
<field name="model">l10n.br.cnab.evento</field>
<field name="arch" type="xml">
<form>
<header>
<field name="state" widget="statusbar" nolabel="1" statusbar_visible="draft,done" />
</header>
<group>
<group>
<field name="data_real_pagamento" attrs="{'readonly': [('state', '=', 'done')]}" />
<field name="segmento" attrs="{'readonly': [('state', '=', 'done')]}" />
<field name="favorecido_nome" attrs="{'readonly': [('state', '=', 'done')]}" />
<field name="nosso_numero" attrs="{'readonly': [('state', '=', 'done')]}" />
<field name="seu_numero" attrs="{'readonly': [('state', '=', 'done')]}" />
<field name="tipo_moeda" attrs="{'readonly': [('state', '=', 'done')]}" />
<field name="valor_pagamento" attrs="{'readonly': [('state', '=', 'done')]}" />
<field name="bank_payment_line_id" attrs="{'readonly': [('state', '=', 'done')]}" />
</group>
<group>
<field name="ocorrencias" attrs="{'readonly': [('state', '=', 'done')]}" />
<field name="str_motiv_a" attrs="{'readonly': [('state', '=', 'done')]}" />
<field name="str_motiv_b" attrs="{'readonly': [('state', '=', 'done')]}" />
<field name="str_motiv_c" attrs="{'readonly': [('state', '=', 'done')]}" />
<field name="str_motiv_d" attrs="{'readonly': [('state', '=', 'done')]}" />
<field name="str_motiv_e" attrs="{'readonly': [('state', '=', 'done')]}" />
</group>
</group>
</form>
</field>
</record>

<record id="cnab_retorno_lote_form_view" model="ir.ui.view">
<field name="name">cnab.retorno.lote.form.view</field>
<field name="model">l10n.br.cnab.lote</field>
<field name="arch" type="xml">
<form>
<header>
<field name="state" widget="statusbar" nolabel="1" statusbar_visible="draft,done" />
</header>
<group>
<group>
<field name="account_bank_id" attrs="{'readonly': [('state', '=', 'done')]}" />
<field name="empresa_inscricao_numero" attrs="{'readonly': [('state', '=', 'done')]}" />
<field name="empresa_inscricao_tipo" attrs="{'readonly': [('state', '=', 'done')]}" />
<field name="servico_operacao" attrs="{'readonly': [('state', '=', 'done')]}" />
</group>
<group>
<field name="tipo_servico" attrs="{'readonly': [('state', '=', 'done')]}" />
<field name="mensagem" attrs="{'readonly': [('state', '=', 'done')]}" />
<field name="qtd_registros" attrs="{'readonly': [('state', '=', 'done')]}" />
<field name="total_valores" attrs="{'readonly': [('state', '=', 'done')]}" />
</group>
</group>
<group string="Eventos">
<field name="evento_id" ontext="{'form_view_ref':'l10n_br_account_banking_payment_cnab.cnab_retorno_evento_form_view'}" nolabel="1" attrs="{'readonly': [('state', '=', 'done')]}"/>
</group>
</form>
</field>
</record>

<record id="cnab_retorno_form_view" model="ir.ui.view">
<field name="name">cnab.retorno.form.view</field>
<field name="model">l10n.br.cnab</field>
<field name="arch" type="xml">
<form>
<header>
<button name="processar_arquivo_retorno" states="draft" string="Processar Retorno" type="object" class="oe_highlight" attrs="{'invisible': [('state', '=', 'done')]}" />
<field name="state" widget="statusbar" nolabel="1" statusbar_visible="draft,done" />
</header>
<sheet>
<h1>
<field name="name" readonly="1"/>
</h1>
<group>
<group>
<field name="data" attrs="{'readonly': [('state', '=', 'done')]}" />
<field name="arquivo_retorno" attrs="{'readonly': [('state', '=', 'done')]}" />
</group>

</group>
<group attrs="{'invisible': [('state','!=', 'done')], 'readonly': [('state', '=', 'done')]}">
<group>
<field name="data_arquivo" attrs="{'readonly': [('state', '=', 'done')]}"/>
<field name="bank_account_id" attrs="{'readonly': [('state', '=', 'done')]}" />
</group>
<group>
<field name="num_lotes" attrs="{'readonly': [('state', '=', 'done')]}" />
<field name="num_eventos" attrs="{'readonly': [('state', '=', 'done')]}" />
</group>
</group>
<group string="Lote de Eventos" name="evento-lines" attrs="{'invisible': [('state','!=', 'done')]}">
<field name="lote_id" context="{'form_view_ref':'l10n_br_account_banking_payment_cnab.cnab_retorno_lote_form_view'}" nolabel="1" attrs="{'readonly': [('state', '=', 'done')]}" />
</group>
</sheet>
</form>
</field>
</record>

<record id="action_cnab_retorno" model="ir.actions.act_window">
<field name="name">CNAB Retorno</field>
<field name="type">ir.actions.act_window</field>
<field name="res_model">l10n.br.cnab</field>
<field name="view_type">form</field>
<field name="view_mode">tree,form</field>
</record>

<menuitem id="menu_cnab_retorno" parent="menu_main_cnab" name="CNAB Retorno" sequence="1" action="action_cnab_retorno"/>

</data>
</openerp>
Original file line number Diff line number Diff line change
@@ -20,7 +20,7 @@
<field name="help">Crie ordens de cobrança CNAB 240.</field>
</record>

<menuitem action="action_cobranca_tree" id="menu_action_cobranca_tree" parent="account_payment.menu_main_payment" sequence="5"/>
<menuitem action="action_cobranca_tree" id="menu_action_cobranca_tree" parent="account_payment.menu_main_payment" sequence="5" groups="group_cnab_cobranca"/>

<record id="view_payment_order_form" model="ir.ui.view">
<field name="name">payment.order.form</field>
Original file line number Diff line number Diff line change
@@ -87,7 +87,7 @@
<field name="help">Lista das linhas cnab 400.</field>
</record>

<menuitem action="action_cobranca_lines" id="menu_action_cobranca_lines" parent="account_payment.menu_main_payment" sequence="6"/>
<menuitem action="action_cobranca_lines" id="menu_action_cobranca_lines" parent="account_payment.menu_main_payment" sequence="6" groups="group_cnab_cobranca"/>

<!--<record id="view_payment_order_form" model="ir.ui.view">-->
<!--<field name="name">payment.order.form</field>-->
37 changes: 37 additions & 0 deletions l10n_br_account_banking_payment_cnab/view/payment_line.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<openerp>
<data>
<record id="view_payment_order_form" model="ir.ui.view">
<field name="name">payment.order.form</field>
<field name="inherit_id" ref="account_banking_payment_export.view_payment_order_form" />
<field name="model">payment.order</field>
<field name="arch" type="xml">
<field name="line_ids" position="attributes">
<attribute name="context">{'order_id': active_id or False,
'default_mode': mode}</attribute>
</field>
<xpath expr="//field[@name='line_ids']/form/notebook" position="before">
<group name="cnab">
<field name="seu_numero"/>
<field name="codigo_finalidade_doc"/>
<field name="codigo_finalidade_ted"/>
<field name="codigo_finalidade_complementar"/>
<field name="aviso_ao_favorecido"/>
</group>
</xpath>
</field>
</record>

<record id="view_payment_line_form" model="ir.ui.view">
<field name="name">payment.line.form</field>
<field name="model">payment.line</field>
<field name="inherit_id" ref="account_payment.view_payment_line_form" />
<field name="arch" type="xml">
<xpath expr="//notebook" position="before">
<header>
<field name="state2" widget="statusbar" nolabel="1" statusbar_visible="draft,wait,paid" />
</header>
</xpath>
</field>
</record>
</data>
</openerp>
11 changes: 11 additions & 0 deletions l10n_br_account_banking_payment_cnab/view/payment_mode.xml
Original file line number Diff line number Diff line change
@@ -15,6 +15,17 @@
</group>

</field>
<group name="payment_order_create_defaults" position="after">
<group string="CNAB">
<field name="tipo_servico"/>
<field name="forma_lancamento"/>
<field name="codigo_convenio"/>
<field name="codigo_finalidade_doc"/>
<field name="codigo_finalidade_ted"/>
<field name="codigo_finalidade_complementar"/>
<field name="aviso_ao_favorecido"/>
</group>
</group>
</field>
</record>
</data>
25 changes: 13 additions & 12 deletions l10n_br_account_banking_payment_cnab/view/payment_order.xml
Original file line number Diff line number Diff line change
@@ -6,22 +6,23 @@
<field name="name">payment.order.form.sequence</field>
<field name="model">payment.order</field>
<field name="inherit_id"
ref="account_payment.view_payment_order_form"/>
ref="account_banking_payment_export.view_payment_order_form"/>
<field name="priority" eval="15"/>
<field name="arch" type="xml">
<data>
<field name="bank_line_count" position="after">
<field name="tipo_servico"/>
<field name="forma_lancamento"/>
<field name="codigo_convenio"/>
<field name="cnab_filename" invisible="1" />
<field name="cnab_file" attrs="{'invisible': [('cnab_file', '=', False)]}" filename="cnab_filename" />
</field>

<xpath expr="//field[@name='date_scheduled']"
position="after">
<field name="file_number"/>
<!--<field name="serie_id" domain="[('parent_payment_mode', '=', mode)]"/>-->
<field name="serie_id"/>
<field name="sufixo_arquivo"/>
<!--<field name="serie_sufixo_arquivo" domain="[('parent_payment_mode_suf', '=', mode)]"/>-->
<field name="serie_sufixo_arquivo"/>
</xpath>
<field name="company_id" position="after">
<field name="indicativo_forma_pagamento"/>
<field name="codigo_instrucao_movimento"/>
<field name="tipo_movimento"/>
</field>

</data>
</field>
</record>

16 changes: 12 additions & 4 deletions l10n_br_account_banking_payment_cnab/view/res_partner_bank.xml
Original file line number Diff line number Diff line change
@@ -10,14 +10,22 @@
<field name="priority" eval="15"/>
<field name="arch" type="xml">
<data>
<!--<field name="bank_name" position="attributes">-->
<!--<attribute name="attrs">{'readonly': True}</attribute>-->
<!--</field>-->

<field name="bank_bic" position="attributes">
<attribute name="attrs">{'required': True}</attribute>
</field>

<field name="partner_id" position="attributes">
<attribute name="attrs">{'required': True}</attribute>
</field>

<field name="state" position="after">
<field name="tipo_de_conta"/>
</field>

<field name="bra_number_dig" position="after">
<field name="bra_acc_dig"/>
<field name="codigo_da_empresa"/>
</field>
</data>
</field>
</record>
Original file line number Diff line number Diff line change
@@ -24,50 +24,72 @@
import base64
import time

from openerp import models, api, workflow, fields

from openerp import models, api, workflow, fields, _
from openerp.exceptions import Warning as UserError
from ..febraban.cnab import Cnab

import logging

# TODO Server action para a cada dia retornar o sufixo do arquivo para zero
_logger = logging.getLogger(__name__)
try:
from cnab240.errors import (Cnab240Error)
except ImportError as err:
_logger.debug = err


class L10nPaymentCnab(models.TransientModel):
_name = 'payment.cnab'
_description = 'Export payment order(s) in cnab layout'

name = fields.Char(u'Nome', size=255)
cnab_file = fields.Binary('CNAB File', readonly=True)
name = fields.Char(string=u'Nome', size=255)

cnab_file = fields.Binary(string='CNAB File', readonly=True)

state = fields.Selection(
[('init', 'init'),
('done', 'done')],
'state',
string='state',
selection=[('init', 'init'), ('done', 'done')],
default='init',
readonly=True)
readonly=True
)

@api.multi
def export(self):
for order_id in self.env.context.get('active_ids', []):

order = self.env['payment.order'].browse(order_id)
cnab = Cnab.get_cnab(order.mode.bank_id.bank_bic,
order.mode.type.code)()
remessa = cnab.remessa(order)
suf_arquivo = order.get_next_sufixo()
if not order.line_ids:
raise UserError(
_('Error'),
_('Adicione pelo menos uma linha na ordem de pagamento.'))

# Criando instancia do CNAB a partir do código do banco
cnab = Cnab.get_cnab(
order.mode.bank_id.bank_bic, order.mode.type.code)()

# Criando remessa de eventos
try:
remessa = cnab.remessa(order)
except Cnab240Error as e:
from openerp import exceptions
raise exceptions.ValidationError(
"Campo preenchido incorretamente \n\n{0}".format(e))

if order.mode.type.code == '240':
self.name = 'CB%s%s.REM' % (
time.strftime('%d%m'), str(order.file_number))
elif order.mode.type.code == '400':
self.name = 'CB%s%s.REM' % (
time.strftime('%d%m'), str(suf_arquivo))
# elif order.mode.type.code == '400':
# self.name = 'CB%s%s.REM' % (
# time.strftime('%d%m'), str(suf_arquivo))
elif order.mode.type.code == '500':
self.name = 'PG%s%s.REM' % (
time.strftime('%d%m'), str(order.file_number))
self.state = 'done'
self.cnab_file = base64.b64encode(remessa)
workflow.trg_validate(self.env.uid, 'payment.order', order_id,
'done', self.env.cr)
order.cnab_file = base64.b64encode(remessa)
order.cnab_filename = self.name

workflow.trg_validate(
self.env.uid, 'payment.order', order_id, 'done', self.env.cr)

return {
'type': 'ir.actions.act_window',
14 changes: 7 additions & 7 deletions l10n_br_account_payment_boleto/demo/payment_demo.xml
Original file line number Diff line number Diff line change
@@ -20,7 +20,7 @@
<field name="boleto_carteira">18</field>
<field name="boleto_modalidade">DM</field>
<field name="boleto_variacao">29</field>
<field name="aceite">S</field>
<!--<field name="aceite">S</field>-->
</record>

<record id="payment_mode_boleto_unregistred_bradesco"
@@ -43,7 +43,7 @@
<field name="boleto_carteira">03</field>
<field name="boleto_modalidade">DM</field>
<field name="boleto_variacao">19</field>
<field name="aceite">N</field>
<!--<field name="aceite">N</field>-->
</record>

<record id="payment_mode_boleto_unregistred_hsbc" model="payment.mode">
@@ -65,7 +65,7 @@
<field name="boleto_carteira">CNR</field>
<field name="boleto_modalidade">PD</field>
<!--<field name="boleto_variacao">19</field>-->
<field name="aceite">N</field>
<!--<field name="aceite">N</field>-->
</record>

<record id="payment_mode_boleto_unregistred_itau" model="payment.mode">
@@ -87,7 +87,7 @@
<field name="boleto_carteira">109</field>
<field name="boleto_modalidade">DM</field>
<!--<field name="boleto_variacao">19</field>-->
<field name="aceite">N</field>
<!--<field name="aceite">N</field>-->
</record>

<record id="payment_mode_boleto_unregistred_santander"
@@ -110,7 +110,7 @@
<field name="boleto_carteira">102</field>
<field name="boleto_modalidade">DM</field>
<!--<field name="boleto_variacao">19</field>-->
<field name="aceite">N</field>
<!--<field name="aceite">N</field>-->
</record>

<record id="payment_mode_boleto_unregistred_caixa" model="payment.mode">
@@ -132,7 +132,7 @@
<field name="boleto_carteira">SR</field>
<!--<field name="boleto_modalidade">DM</field>-->
<!--<field name="boleto_variacao">19</field>-->
<field name="aceite">N</field>
<!--<field name="aceite">N</field>-->
</record>

<record id="payment_mode_boleto_unregistred_caixa_sigcb"
@@ -155,7 +155,7 @@
<field name="boleto_carteira">SR</field>
<!--<field name="boleto_modalidade">DM</field>-->
<!--<field name="boleto_variacao">19</field>-->
<field name="aceite">N</field>
<!--<field name="aceite">N</field>-->
</record>

</data>
5 changes: 2 additions & 3 deletions l10n_br_account_payment_mode/__openerp__.py
Original file line number Diff line number Diff line change
@@ -8,14 +8,13 @@
'version': '8.0.1.0.0',
'category': 'Banking addons',
'license': 'AGPL-3',
'summary': '',
'author': "KMEE, Odoo Community Association (OCA)",
"website": "https://odoo-community.org/",
'depends': [
'l10n_br_account',
'l10n_br_data_base',
'account_due_list_payment_mode',
'account_banking_payment_export'
'account_banking_payment_export',
'l10n_br_account_banking_payment',
],
'data': [
'views/payment_mode_view.xml',
10 changes: 0 additions & 10 deletions l10n_br_account_payment_mode/models/payment_mode.py
Original file line number Diff line number Diff line change
@@ -39,16 +39,6 @@ class PaymentMode(models.Model):
('99', u'99 - Outros')],
string='Tipo SPED', required=True, default='99')

type_purchase_payment = fields.Selection(
[('01', u'01 - Crédito em conta-corrente ou poupança Bradesco'),
('02', u'02 - Cheque OP ( Ordem de Pagamento'),
('03', u'03 - DOC COMPE'),
('05', u'05 - Crédito em conta real time'),
('08', u'08 - TED'),
('30', u'30 - Rastreamento de Títulos'),
('31', u'31 - Títulos de terceiros'),
]
)
internal_sequence_id = fields.Many2one('ir.sequence', u'Sequência')
instrucoes = fields.Text(u'Instruções de cobrança')
invoice_print = fields.Boolean(
10 changes: 6 additions & 4 deletions l10n_br_account_payment_mode/views/payment_mode_view.xml
Original file line number Diff line number Diff line change
@@ -16,7 +16,8 @@
<xpath expr="//form/group[@string='Note']" position="before">
<group string="Configurações" name='l10n-br-config' col="4">
<notebook colspan="4">
<page string="Cobrança" attrs="{'invisible': [('sale_ok', '!=', True)]}">
<page string="Cobrança" attrs="{'invisible': ['|', ('sale_ok', '!=', True),
('payment_order_type', '!=', 'cobranca')]}">
<group>
<field name="type_sale_payment"/>
<field name="internal_sequence_id"
@@ -41,10 +42,11 @@
</page>
<page string="Pagamento" attrs="{'invisible': [('purchase_ok', '!=', True)]}">
<group>
<field name="type_purchase_payment"/>
<field name="internal_sequence_id"/>
<field name="instrucoes"/>
<field name="invoice_print"/>
<field name="instrucoes"
attrs="{'invisible': [('payment_order_type', '!=', 'cobranca')]}"/>
<field name="invoice_print"
attrs="{'invisible': [('payment_order_type', '!=', 'cobranca')]}"/>
</group>
</page>
</notebook>
2 changes: 1 addition & 1 deletion l10n_br_cnab400_import/__openerp__.py
Original file line number Diff line number Diff line change
@@ -40,7 +40,7 @@
'data/l10n_br_res_partner_bank_type.xml',
],
'active': False,
"installable": True,
"installable": False,
"auto_install": False,
'description': """
Allows to import CNAB 400 (Centro Nacional de Automação Bancária)
2 changes: 1 addition & 1 deletion l10n_br_cnab400_import/models/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-

#from . import account_bank_statement_line
# from . import account_bank_statement_line
from . import account_move_line
from . import account_bank_statement_import
from . import l10n_br_cnab_move
10 changes: 5 additions & 5 deletions l10n_br_cnab400_import/models/account_bank_statement.py
Original file line number Diff line number Diff line change
@@ -28,11 +28,11 @@ class AccountBankStatementLine(models.Model):
@api.model
def get_reconcile_lines_from_cnab_move(self, this, excluded_ids=None):
"""return move.line to reconcile with statement line"""
move_lines = self.env['account.move.line'].search(
[('transaction_ref', '=', this.name),
('name', '=', this.ref),
('company_id', '=', self.env.user.company_id.id)
])
move_lines = self.env['account.move.line'].search([
('transaction_ref', '=', this.name),
('name', '=', this.ref),
('company_id', '=', self.env.user.company_id.id)
])
try:
assert len(move_lines) <= 1
except Exception, e:

0 comments on commit cefbdc7

Please sign in to comment.