<commit_before># -*- encoding: utf-8 -*-
###############################################################################
#                                                                             #
# Copyright (C) 2013  <NAME> - Akretion                                  #
#                                                                             #
#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/>.        #
###############################################################################

import time
from lxml import etree

from openerp import models, fields, api, _
from openerp.addons import decimal_precision as dp
from openerp.exceptions import except_orm, Warning, RedirectWarning

from openerp.addons.l10n_br_account.account_invoice import (
    OPERATION_TYPE,
    JOURNAL_TYPE)

from .l10n_br_account_product import (
    PRODUCT_FISCAL_TYPE,
    PRODUCT_FISCAL_TYPE_DEFAULT)
from .product import PRODUCT_ORIGIN
from .sped.nfe.validator import txt


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

    @api.one
    @api.depends('invoice_line.price_subtotal', 'tax_line.amount')
    def _compute_amount(self):
        self.icms_base = 0.0
        self.icms_base_other = 0.0
        self.icms_value = 0.0
        self.icms_st_base = 0.0
        self.icms_st_value = 0.0
        self.ipi_base = sum(line.ipi_base for line in self.invoice_line)
        self.ipi_base_other = sum(line.ipi_base_other for line in self.invoice_line)
        self.ipi_value = sum(line.ipi_value for line in self.invoice_line)
        self.pis_base = sum(line.pis_base for line in self.invoice_line)
        self.pis_value = sum(line.pis_value for line in self.invoice_line)
        self.cofins_base = sum(line.cofins_base for line in self.invoice_line)
        self.cofins_value = sum(line.cofins_value for line in self.invoice_line)
        self.ii_value = sum(line.ii_value for line in self.invoice_line)
        self.amount_discount = sum(line.discount_value for line in self.invoice_line)
        self.amount_insurance = sum(line.insurance_value for line in self.invoice_line)
        self.amount_costs = sum(line.other_costs_value for line in self.invoice_line)
        self.amount_total_taxes = sum(line.total_taxes for line in self.invoice_line)
        self.amount_gross = sum(line.price_gross for line in self.invoice_line)
        self.amount_freight = sum(line.freight_value for line in self.invoice_line)
        self.amount_tax_discount = 0.0
        self.amount_untaxed = sum(line.price_total for line in self.invoice_line)
        self.amount_tax = sum(tax.amount for tax in self.tax_line if not tax.tax_code_id.tax_discount)
        self.amount_total = self.amount_tax + self.amount_untaxed

        for line in self.invoice_line:
            if line.icms_cst_id.code not in ('101', '102', '201', '202', '300', '500'):
                self.icms_base += line.icms_base
                self.icms_base_other += line.icms_base_other
                self.icms_value += line.icms_value
            else:
                self.icms_base += 0.00
                self.icms_base_other += 0.00
                self.icms_value += 0.00
            self.icms_st_base += line.icms_st_base
            self.icms_st_value += line.icms_st_value

    @api.model
    @api.returns('l10n_br_account.fiscal_category')
    def _default_fiscal_category(self):
        DEFAULT_FCATEGORY_PRODUCT = {
            'in_invoice': 'in_invoice_fiscal_category_id',
            'out_invoice': 'out_invoice_fiscal_category_id',
            'in_refund': 'in_refund_fiscal_category_id',
            'out_refund': 'out_refund_fiscal_category_id'
        }
        default_fo_category = {'product': DEFAULT_FCATEGORY_PRODUCT}
        invoice_type = self._context.get('type', 'out_invoice')
        invoice_fiscal_type = self._context.get('fiscal_type', 'product')
        company = self.env['res.company'].browse(self.env.user.company_id.id)
        return company[default_fo_category[invoice_fiscal_type][invoice_type]]

    @api.model
    def _default_fiscal_document(self):
        company = self.env['res.company'].browse(self.env.user.company_id.id)
        return company.product_invoice_id

    @api.model
    def _default_fiscal_document_serie(self):
        company = self.env['res.company'].browse(self.env.user.company_id.id)
        fiscal_document_series = [doc_serie for doc_serie in
            company.document_serie_product_ids if
            doc_serie.fiscal_document_id.id ==
            company.product_invoice_id.id and doc_serie.active]
        #if not fiscal_document_series:
            #TODO Adicionar uma mensagem caso não tenha serie
        return fiscal_document_series[0]

    @api.one
    @api.depends('invoice_line.cfop_id')
    def _compute_cfops(self):
        lines = self.env['l10n_br_account_product.cfop']
        for line in self.invoice_line:
            if line.cfop_id:
                lines |= line.cfop_id
        self.cfop_ids = (lines).sorted()

    fiscal_document_id = fields.Many2one(
        'l10n_br_account.fiscal.document', 'Documento', readonly=True,
        states={'draft': [('readonly', False)]},
        default=_default_fiscal_document)
    document_serie_id = fields.Many2one(
        'l10n_br_account.document.serie', u'Série',
        domain="[('fiscal_document_id', '=', fiscal_document_id),\
        ('company_id','=',company_id)]", readonly=True,
        states={'draft': [('readonly', False)]},
        default=_default_fiscal_document_serie)
    fiscal_category_id = fields.Many2one(
        'l10n_br_account.fiscal.category', 'Categoria Fiscal',
        readonly=True, states={'draft': [('readonly', False)]},
        default=_default_fiscal_category)
    date_in_out = fields.Date(u'Data de Entrada/Saida', readonly=True,
        states={'draft': [('readonly', False)]}, select=True,
        help="Deixe em branco para usar a data atual")
    partner_shipping_id = fields.Many2one(
        'res.partner', 'Delivery Address',
        readonly=True, required=True,
        states={'draft': [('readonly', False)]},
        help="Delivery address for current sales order.")
    state = fields.Selection([
        ('draft', 'Draft'),
        ('proforma', 'Pro-forma'),
        ('proforma2', 'Pro-forma'),
        ('sefaz_export', 'Enviar para Receita'),
        ('sefaz_exception', 'Erro de autorização da Receita'),
        ('sefaz_cancelled', u'Cancelado no Sefaz'),
        ('open', 'Open'),
        ('paid', 'Paid'),
        ('cancel', 'Cancelled')
        ], 'State', select=True, readonly=True,
        help=' * The \'Draft\' state is used when a user is encoding a new and unconfirmed Invoice. \
        \n* The \'Pro-forma\' when invoice is in Pro-forma state,invoice does not have an invoice number. \
        \n* The \'Open\' state is used when user create invoice,a invoice number is generated.Its in open state till user does not pay invoice. \
        \n* The \'Paid\' state is set automatically when invoice is paid.\
        \n* The \'sefaz_out\' Gerado aquivo de exportação para sistema daReceita.\
        \n* The \'sefaz_aut\' Recebido arquivo de autolização da Receita.\
        \n* The \'Cancelled\' state is used when user cancel invoice.')
    fiscal_type = fields.Selection(PRODUCT_FISCAL_TYPE,
        'Tipo Fiscal', required=True, default=PRODUCT_FISCAL_TYPE_DEFAULT)
    partner_shipping_id = fields.Many2one(
        'res.partner', 'Endereço de Entrega', readonly=True,
        states={'draft': [('readonly', False)]},
        help="Shipping address for current sales order.")
    nfe_purpose = fields.Selection(
        [('1', 'Normal'),
         ('2', 'Complementar'),
         ('3', 'Ajuste')], 'Finalidade da Emissão', readonly=True,
        states={'draft': [('readonly', False)]}, default='1')
    nfe_access_key = fields.Char(
        'Chave de Acesso NFE', size=44,
        readonly=True, states={'draft': [('readonly', False)]}, copy=False)
    nfe_protocol_number = fields.Char(
        'Protocolo', size=15, readonly=True,
        states={'draft': [('readonly', False)]})
    nfe_status = fields.Char('Status na Sefaz', size=44, readonly=True,
        copy=False)
    nfe_date = fields.Datetime('Data do Status NFE', readonly=True,
        copy=False)
    nfe_export_date = fields.Datetime('Exportação NFE', readonly=True)<commit_msg>added copy=False in some fields in account.invoice<commit_after># -*- encoding: utf-8 -*-
###############################################################################
#                                                                             #
# Copyright (C) 2013  <NAME> - Akretion                                  #
#                                                                             #
#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/>.        #
###############################################################################

import time
from lxml import etree

from openerp import models, fields, api, _
from openerp.addons import decimal_precision as dp
from openerp.exceptions import except_orm, Warning, RedirectWarning

from openerp.addons.l10n_br_account.account_invoice import (
    OPERATION_TYPE,
    JOURNAL_TYPE)

from .l10n_br_account_product import (
    PRODUCT_FISCAL_TYPE,
    PRODUCT_FISCAL_TYPE_DEFAULT)
from .product import PRODUCT_ORIGIN
from .sped.nfe.validator import txt


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

    @api.one
    @api.depends('invoice_line.price_subtotal', 'tax_line.amount')
    def _compute_amount(self):
        self.icms_base = 0.0
        self.icms_base_other = 0.0
        self.icms_value = 0.0
        self.icms_st_base = 0.0
        self.icms_st_value = 0.0
        self.ipi_base = sum(line.ipi_base for line in self.invoice_line)
        self.ipi_base_other = sum(line.ipi_base_other for line in self.invoice_line)
        self.ipi_value = sum(line.ipi_value for line in self.invoice_line)
        self.pis_base = sum(line.pis_base for line in self.invoice_line)
        self.pis_value = sum(line.pis_value for line in self.invoice_line)
        self.cofins_base = sum(line.cofins_base for line in self.invoice_line)
        self.cofins_value = sum(line.cofins_value for line in self.invoice_line)
        self.ii_value = sum(line.ii_value for line in self.invoice_line)
        self.amount_discount = sum(line.discount_value for line in self.invoice_line)
        self.amount_insurance = sum(line.insurance_value for line in self.invoice_line)
        self.amount_costs = sum(line.other_costs_value for line in self.invoice_line)
        self.amount_total_taxes = sum(line.total_taxes for line in self.invoice_line)
        self.amount_gross = sum(line.price_gross for line in self.invoice_line)
        self.amount_freight = sum(line.freight_value for line in self.invoice_line)
        self.amount_tax_discount = 0.0
        self.amount_untaxed = sum(line.price_total for line in self.invoice_line)
        self.amount_tax = sum(tax.amount for tax in self.tax_line if not tax.tax_code_id.tax_discount)
        self.amount_total = self.amount_tax + self.amount_untaxed

        for line in self.invoice_line:
            if line.icms_cst_id.code not in ('101', '102', '201', '202', '300', '500'):
                self.icms_base += line.icms_base
                self.icms_base_other += line.icms_base_other
                self.icms_value += line.icms_value
            else:
                self.icms_base += 0.00
                self.icms_base_other += 0.00
                self.icms_value += 0.00
            self.icms_st_base += line.icms_st_base
            self.icms_st_value += line.icms_st_value

    @api.model
    @api.returns('l10n_br_account.fiscal_category')
    def _default_fiscal_category(self):
        DEFAULT_FCATEGORY_PRODUCT = {
            'in_invoice': 'in_invoice_fiscal_category_id',
            'out_invoice': 'out_invoice_fiscal_category_id',
            'in_refund': 'in_refund_fiscal_category_id',
            'out_refund': 'out_refund_fiscal_category_id'
        }
        default_fo_category = {'product': DEFAULT_FCATEGORY_PRODUCT}
        invoice_type = self._context.get('type', 'out_invoice')
        invoice_fiscal_type = self._context.get('fiscal_type', 'product')
        company = self.env['res.company'].browse(self.env.user.company_id.id)
        return company[default_fo_category[invoice_fiscal_type][invoice_type]]

    @api.model
    def _default_fiscal_document(self):
        company = self.env['res.company'].browse(self.env.user.company_id.id)
        return company.product_invoice_id

    @api.model
    def _default_fiscal_document_serie(self):
        company = self.env['res.company'].browse(self.env.user.company_id.id)
        fiscal_document_series = [doc_serie for doc_serie in
            company.document_serie_product_ids if
            doc_serie.fiscal_document_id.id ==
            company.product_invoice_id.id and doc_serie.active]
        #if not fiscal_document_series:
            #TODO Adicionar uma mensagem caso não tenha serie
        return fiscal_document_series[0]

    @api.one
    @api.depends('invoice_line.cfop_id')
    def _compute_cfops(self):
        lines = self.env['l10n_br_account_product.cfop']
        for line in self.invoice_line:
            if line.cfop_id:
                lines |= line.cfop_id
        self.cfop_ids = (lines).sorted()

    fiscal_document_id = fields.Many2one(
        'l10n_br_account.fiscal.document', 'Documento', readonly=True,
        states={'draft': [('readonly', False)]},
        default=_default_fiscal_document)
    document_serie_id = fields.Many2one(
        'l10n_br_account.document.serie', u'Série',
        domain="[('fiscal_document_id', '=', fiscal_document_id),\
        ('company_id','=',company_id)]", readonly=True,
        states={'draft': [('readonly', False)]},
        default=_default_fiscal_document_serie)
    fiscal_category_id = fields.Many2one(
        'l10n_br_account.fiscal.category', 'Categoria Fiscal',
        readonly=True, states={'draft': [('readonly', False)]},
        default=_default_fiscal_category)
    date_in_out = fields.Date(u'Data de Entrada/Saida', readonly=True,
        states={'draft': [('readonly', False)]}, select=True, copy=False,
        help="Deixe em branco para usar a data atual")
    partner_shipping_id = fields.Many2one(
        'res.partner', 'Delivery Address',
        readonly=True, required=True,
        states={'draft': [('readonly', False)]},
        help="Delivery address for current sales order.")
    state = fields.Selection([
        ('draft', 'Draft'),
        ('proforma', 'Pro-forma'),
        ('proforma2', 'Pro-forma'),
        ('sefaz_export', 'Enviar para Receita'),
        ('sefaz_exception', 'Erro de autorização da Receita'),
        ('sefaz_cancelled', u'Cancelado no Sefaz'),
        ('open', 'Open'),
        ('paid', 'Paid'),
        ('cancel', 'Cancelled')
        ], 'State', select=True, readonly=True,
        help=' * The \'Draft\' state is used when a user is encoding a new and unconfirmed Invoice. \
        \n* The \'Pro-forma\' when invoice is in Pro-forma state,invoice does not have an invoice number. \
        \n* The \'Open\' state is used when user create invoice,a invoice number is generated.Its in open state till user does not pay invoice. \
        \n* The \'Paid\' state is set automatically when invoice is paid.\
        \n* The \'sefaz_out\' Gerado aquivo de exportação para sistema daReceita.\
        \n* The \'sefaz_aut\' Recebido arquivo de autolização da Receita.\
        \n* The \'Cancelled\' state is used when user cancel invoice.')
    fiscal_type = fields.Selection(PRODUCT_FISCAL_TYPE,
        'Tipo Fiscal', required=True, default=PRODUCT_FISCAL_TYPE_DEFAULT)
    partner_shipping_id = fields.Many2one(
        'res.partner', 'Endereço de Entrega', readonly=True,
        states={'draft': [('readonly', False)]},
        help="Shipping address for current sales order.")
    nfe_purpose = fields.Selection(
        [('1', 'Normal'),
         ('2', 'Complementar'),
         ('3', 'Ajuste')], 'Finalidade da Emissão', readonly=True,
        states={'draft': [('readonly', False)]}, default='1')
    nfe_access_key = fields.Char(
        'Chave de Acesso NFE', size=44,
        readonly=True, states={'draft': [('readonly', False)]}, copy=False)
    nfe_protocol_number = fields.Char(
        'Protocolo', size=15, readonly=True,
        copy=False, states={'draft': [('readonly', False)]})
    nfe_status = fields.Char('Status na Sefaz', size=44, readonly=True,
        copy=False)
    nfe_date = fields.Datetime('Data do Status NFE', readonly=True,
        copy=False)
    nfe_export_date = fields.Datetime('Exportação NFE', readonly=True)
{'fraction_non_alphanumeric': 0.1214281855993086, 'fraction_numerical': 0.00821044671312051, 'mean_word_length': 2.6005445352003114, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 26, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2754795', 'n_tokens_mistral': 5792, 'n_tokens_neox': 5660, 'n_words': 1305}