Skip to content

Commit

Permalink
Merge branch '10.0' into 10.0-importar_retorno_cnab
Browse files Browse the repository at this point in the history
  • Loading branch information
felipepaloschi committed Feb 21, 2018
2 parents bddcb7f + 95634d0 commit d10ea3d
Show file tree
Hide file tree
Showing 42 changed files with 362 additions and 181 deletions.
78 changes: 59 additions & 19 deletions br_account/models/account_fiscal_position.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,28 +127,23 @@ def _filter_rules(self, fpos_id, type_tax, partner, product, state):
if rules:
rules_points = {}
for rule in rules:
rules_points[rule.id] = 0
if rule.tipo_produto == product.fiscal_type:
rules_points[rule.id] += 1
if state in rule.state_ids:
rules_points[rule.id] += 1
if product.categ_id in rule.product_category_ids:
rules_points[rule.id] += 1
if product in rule.product_ids:
rules_points[rule.id] += 1
if len(rule.product_ids) > 0:
rules_points[rule.id] -= 1
if not rule.tipo_produto:
rules_points[rule.id] -= 1
if len(rule.product_category_ids) > 0:
rules_points[rule.id] -= 1
if len(rule.state_ids) > 0:
rules_points[rule.id] -= 1

# Calcula a pontuacao da regra.
# Quanto mais alto, mais adequada está a regra em relacao ao
# faturamento
rules_points[rule.id] = self._calculate_points(
rule, product, state, partner)

# Calcula o maior valor para os resultados obtidos
greater_rule = max([(v, k) for k, v in rules_points.items()])
if greater_rule[0] <= 0:
# Se o valor da regra for menor do que 0, a regra é descartada.
if greater_rule[0] < 0:
return {}

# Procura pela regra associada ao id -> (greater_rule[1])
rules = [rules.browse(greater_rule[1])]

# Retorna dicionario com o valores dos campos de acordo com a regra
return {
('%s_rule_id' % type_tax): rules[0],
'cfop_id': rules[0].cfop_id,
Expand Down Expand Up @@ -179,7 +174,7 @@ def _filter_rules(self, fpos_id, type_tax, partner, product, state):
'cofins_cst': rules[0].cst_cofins,
}
else:
return {}
return{}

@api.model
def map_tax_extra_values(self, company, product, partner):
Expand All @@ -194,3 +189,48 @@ def map_tax_extra_values(self, company, product, partner):
res.update({k: v for k, v in vals.items() if v})

return res

def _calculate_points(self, rule, product, state, partner):
"""Calcula a pontuação das regras. A pontuação aumenta de acordo
com os 'matches'. Não havendo match(exceto quando o campo não está
definido) retorna o valor -1, que posteriormente será tratado como
uma regra a ser descartada.
"""

rule_points = 0

# Verifica o tipo do produto. Se sim, avança para calculo da pontuação
# Se não, retorna o valor -1 (a regra será descartada)
if product.fiscal_type == rule.tipo_produto:

# Verifica a categoria fiscal. Se contido, adiciona 1 ponto
# Se não, retorna valor -1 (a regra será descartada)
if product.categ_id in rule.product_category_ids:
rule_points += 1
elif len(rule.product_category_ids) > 0:
return -1

# Verifica produtos. Se contido, adiciona 1 ponto
# Se não, retorna -1
if product in rule.product_ids:
rule_points += 1
elif len(rule.product_ids) > 0:
return -1

# Verifica o estado. Se contido, adiciona 1 ponto
# Se não, retorna -1
if state in rule.state_ids:
rule_points += 1
elif len(rule.state_ids) > 0:
return -1

# Verifica o cliente. Se está contido, adiciona 1 ponto
# Se não, retorna -1
if partner in rule.partner_ids:
rule_points += 1
elif len(rule.partner_ids) > 0:
return -1
else:
return -1

return rule_points
6 changes: 4 additions & 2 deletions br_account/models/account_invoice_line.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ def _prepare_tax_context(self):
'cofins_base_calculo_manual': self.cofins_base_calculo_manual,
'ii_base_calculo': self.ii_base_calculo,
'issqn_base_calculo': self.issqn_base_calculo,
'icms_aliquota_inter_part': self.icms_aliquota_inter_part,
}

@api.one
Expand All @@ -60,7 +61,8 @@ def _prepare_tax_context(self):
'icms_st_aliquota_deducao', 'icms_st_base_calculo_manual',
'icms_base_calculo_manual', 'ipi_base_calculo_manual',
'pis_base_calculo_manual', 'cofins_base_calculo_manual',
'icms_st_aliquota_deducao', 'ii_base_calculo')
'icms_st_aliquota_deducao', 'ii_base_calculo',
'icms_aliquota_inter_part')
def _compute_price(self):
currency = self.invoice_id and self.invoice_id.currency_id or None
price = self.price_unit * (1 - (self.discount or 0.0) / 100.0)
Expand Down Expand Up @@ -282,7 +284,7 @@ def _compute_cst_icms(self):
tax_icms_fcp_id = fields.Many2one(
'account.tax', string="% FCP", domain=[('domain', '=', 'fcp')])
icms_aliquota_inter_part = fields.Float(
u'% Partilha', default=40.0, digits=dp.get_precision('Discount'))
u'% Partilha', default=20.0, digits=dp.get_precision('Discount'))
icms_fcp_uf_dest = fields.Float(
string=u'Valor FCP', compute='_compute_price',
digits=dp.get_precision('Discount'), )
Expand Down
11 changes: 9 additions & 2 deletions br_account/models/account_tax.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,9 +244,16 @@ def _compute_difal(self, price_base, ipi_value):
interestadual = icms_inter._compute_amount(base_icms, 1.0)
interno = icms_intra._compute_amount(base_icms, 1.0)

vals_inter['amount'] = round((interno - interestadual) * 0.4, 2)
if 'icms_aliquota_inter_part' in self.env.context:
icms_inter_part = self.env.context["icms_aliquota_inter_part"]
else:
icms_inter_part = 20.0

vals_inter['amount'] = round((interno - interestadual) *
icms_inter_part / 100, 2)
vals_inter['base'] = base_icms
vals_intra['amount'] = round((interno - interestadual) * 0.6, 2)
vals_intra['amount'] = round((interno - interestadual) *
(100 - icms_inter_part) / 100, 2)
vals_intra['base'] = base_icms

taxes = [vals_inter, vals_intra]
Expand Down
15 changes: 8 additions & 7 deletions br_account/tests/test_taxes.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,12 +223,13 @@ def test_difal_incomplete(self):

def test_tax_difal(self):
taxes = self.icms_difal_inter_700 | self.icms_difal_intra_1700
res = taxes.compute_all(100.0)
res = taxes.with_context(icms_aliquota_inter_part=30)\
.compute_all(100.0)
self.assertEquals(res['total_excluded'], 100.0)
self.assertEquals(res['total_included'], 100.0)
self.assertEquals(len(res['taxes']), 2)
self.assertEquals(res['taxes'][0]['amount'], 4.0) # Remetente
self.assertEquals(res['taxes'][1]['amount'], 6.0) # Destinatário
self.assertEquals(res['taxes'][0]['amount'], 3.0) # Remetente
self.assertEquals(res['taxes'][1]['amount'], 7.0) # Destinatário

def test_difal_fcp(self):
taxes = self.icms_difal_inter_700 | self.icms_difal_intra_1700 | \
Expand All @@ -237,8 +238,8 @@ def test_difal_fcp(self):
self.assertEquals(res['total_excluded'], 100.0)
self.assertEquals(res['total_included'], 100.0)
self.assertEquals(len(res['taxes']), 3)
self.assertEquals(res['taxes'][0]['amount'], 4.0) # Remetente
self.assertEquals(res['taxes'][1]['amount'], 6.0) # Destinatário
self.assertEquals(res['taxes'][0]['amount'], 2.0) # Remetente
self.assertEquals(res['taxes'][1]['amount'], 8.0) # Destinatário
self.assertEquals(res['taxes'][2]['amount'], 2.0) # FCP

def test_difal_fcp_reducao_frete_seguro_despesas(self):
Expand All @@ -251,6 +252,6 @@ def test_difal_fcp_reducao_frete_seguro_despesas(self):
self.assertEquals(res['total_excluded'], 100.0)
self.assertEquals(res['total_included'], 100.0)
self.assertEquals(len(res['taxes']), 3)
self.assertEquals(res['taxes'][0]['amount'], 4.48) # Remetente
self.assertEquals(res['taxes'][1]['amount'], 6.72) # Destinatário
self.assertEquals(res['taxes'][0]['amount'], 2.24) # Remetente
self.assertEquals(res['taxes'][1]['amount'], 8.96) # Destinatário
self.assertEquals(res['taxes'][2]['amount'], 2.24) # FCP
6 changes: 6 additions & 0 deletions br_account/views/account_invoice_view.xml
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,12 @@
<xpath expr="//field[@name='invoice_line_ids']/tree" position="inside">
<field name="valor_bruto" invisible="1" />
<field name="valor_desconto" invisible="1" />
<field name="ii_rule_id" invisible="1"/>
<field name="issqn_rule_id" invisible="1"/>
<field name="cofins_rule_id" invisible="1" />
<field name="pis_rule_id" invisible="1"/>
<field name="ipi_rule_id" invisible="1"/>
<field name="icms_rule_id" invisible="1"/>
</xpath>
<xpath expr="//notebook/page" position="after">
<page name="vencimentos" string="Vencimentos">
Expand Down
7 changes: 4 additions & 3 deletions br_account_einvoice/models/invoice_eletronic.py
Original file line number Diff line number Diff line change
Expand Up @@ -518,9 +518,10 @@ class InvoiceEletronicItem(models.Model):
uom_id = fields.Many2one(
'product.uom', string=u'Unidade Medida', readonly=True, states=STATE)
quantidade = fields.Float(
string=u'Quantidade', readonly=True, states=STATE)
preco_unitario = fields.Monetary(
string=u'Preço Unitário', digits=dp.get_precision('Account'),
string=u'Quantidade', readonly=True, states=STATE,
digits=dp.get_precision('Product Unit of Measure'))
preco_unitario = fields.Float(
string=u'Preço Unitário', digits=dp.get_precision('Product Price'),
readonly=True, states=STATE)

item_pedido_compra = fields.Char(
Expand Down
1 change: 1 addition & 0 deletions br_account_payment/__manifest__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
'views/payment_mode.xml',
'views/account_payment.xml',
'views/account_journal.xml',
'security/account_security.xml',
],
'installable': True,
'application': True,
Expand Down
3 changes: 1 addition & 2 deletions br_account_payment/models/account_invoice.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ class AccountInvoice(models.Model):
_inherit = 'account.invoice'

payment_mode_id = fields.Many2one(
'payment.mode', readonly=True,
states=FIELD_STATE, string=u"Modo de pagamento")
'payment.mode', string=u"Modo de pagamento")

@api.multi
def finalize_invoice_move_lines(self, move_lines):
Expand Down
8 changes: 8 additions & 0 deletions br_account_payment/security/account_security.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<data noupdate="1">
<record id="account_payment_mode_comp_rule" model="ir.rule">
<field name="name">Account Payment Mode Mapping company rule</field>
<field name="model_id" ref="model_payment_mode"/>
<field name="global" eval="True"/>
<field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field>
</record>
</data>
27 changes: 18 additions & 9 deletions br_base/tools/fiscal.py
Original file line number Diff line number Diff line change
Expand Up @@ -379,16 +379,23 @@ def validate_ie_to(inscr_est):
inscr_est = re.sub('[^0-9]', '', inscr_est)

# verificando o tamanho da inscrição estadual
if len(inscr_est) != 11:
return False
if len(inscr_est) == 11:

# verificando os dígitos 3 e 4
if not inscr_est[2:4] in ['01', '02', '03', '99']:
return False
# verificando os dígitos 3 e 4
if not inscr_est[2:4] in ['01', '02', '03', '99']:
return False

# Pega apenas os dígitos que entram no cálculo
inscr_est = map(int, inscr_est)
nova_ie = inscr_est[:2] + inscr_est[4:10]
# Pega apenas os dígitos que entram no cálculo
inscr_est = map(int, inscr_est)
nova_ie = inscr_est[:2] + inscr_est[4:10]

# Contemplando o novo IE de Tocantins de 9 digitos
elif len(inscr_est) == 9:
inscr_est = map(int, inscr_est)
nova_ie = inscr_est[:8]

else:
return False

prod = [9, 8, 7, 6, 5, 4, 3, 2]
r = sum([x * y for (x, y) in zip(nova_ie, prod)]) % 11
Expand All @@ -398,7 +405,9 @@ def validate_ie_to(inscr_est):
f = 0
nova_ie.append(f)

nova_ie = nova_ie[:2] + inscr_est[2:4] + nova_ie[2:]
# Se o IE for antigo, adicionar os digitos 3 e 4
if len(inscr_est) == 11:
nova_ie = nova_ie[:2] + inscr_est[2:4] + nova_ie[2:]

return nova_ie == inscr_est

Expand Down
5 changes: 2 additions & 3 deletions br_boleto/boleto/document.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,8 @@ def _move_line(self, move_line):
self.boleto.data_documento = datetime.date(datetime.strptime(
move_line.invoice_id.date_invoice, '%Y-%m-%d'))
self.boleto.data_processamento = date.today()
self.boleto.valor = str("%.2f" % (move_line.debit or move_line.credit))
self.boleto.valor_documento = str("%.2f" % (move_line.debit or
move_line.credit))
self.boleto.valor = str("%.2f" % (move_line.amount_residual))
self.boleto.valor_documento = str("%.2f" % (move_line.amount_residual))
self.boleto.especie = \
move_line.currency_id and move_line.currency_id.symbol or 'R$'
self.boleto.quantidade = '1'
Expand Down
31 changes: 30 additions & 1 deletion br_boleto/models/account_invoice.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,31 @@
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

import base64
from odoo import api, models
from odoo import api, models, fields
from odoo.exceptions import UserError


class AccountInvoice(models.Model):
_inherit = 'account.invoice'

update_boleto = fields.Boolean(
string="Atualizar boletos",
compute='_compute_update_boletos')

@api.depends('payment_mode_id')
@api.multi
def _compute_update_boletos(self):
for item in self:
if item.state != 'open':
item.update_boleto = False
else:
for line in item.receivable_move_line_ids:
if line.payment_mode_id != item.payment_mode_id and not\
line.boleto_emitido:
item.update_boleto = True
return
item.update_boleto = False

@api.multi
def send_email_boleto_queue(self):
mail = self.env.user.company_id.boleto_email_tmpl
Expand Down Expand Up @@ -104,3 +122,14 @@ def action_register_boleto(self):
u'Fatura provisória ou cancelada não permite emitir boleto')
self = self.with_context({'origin_model': 'account.invoice'})
return self.env['report'].get_action(self.id, 'br_boleto.report.print')

def onchange_payment_mode(self):
receivable_ids = self.receivable_move_line_ids
change = False
for line in receivable_ids:
if not line.boleto_emitido:
change = True
line.payment_mode_id = self.payment_mode_id
if not change:
raise UserError("Todos os boletos já foram emitidos, \
não é possível mudar o modo de pagamento!")
18 changes: 18 additions & 0 deletions br_boleto/models/account_move_line.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,3 +95,21 @@ def open_wizard_print_boleto(self):
'default_move_line_id': self.id,
}
})

@api.multi
def unlink(self):
order_lines = self.env['payment.order.line'].search([(
'move_line_id', 'in', self.ids)])
order_lines.unlink()
return super(AccountMoveLine, self).unlink()


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

@api.multi
def unlink(self):
order_lines = self.env['payment.order.line'].search([(
'move_id', 'in', self.ids)])
order_lines.unlink()
return super(AccountMove, self).unlink()

0 comments on commit d10ea3d

Please sign in to comment.