Пример #1
0
    def compute_rule(self, rule_id, localdict):
        rule = self.browse(rule_id)
        if not rule.calculo_nao_padrao:
            if rule.amount_select != 'code':
                return super(HrSalaryRule,
                             self).compute_rule(rule_id, localdict)

            codigo_python = python_pt_BR(rule.amount_python_compute or '',
                                         CALCULO_FOLHA_PT_BR)
        else:
            if rule.custom_amount_select == 'code':
                codigo_python = python_pt_BR(
                    rule.custom_amount_python_compute or '',
                    CALCULO_FOLHA_PT_BR)
            elif rule.custom_amount_select == 'fix':
                try:
                    return rule.custom_amount_fix, Decimal(
                        safe_eval(rule.custom_quantity, localdict)), 100.0
                except:
                    raise osv.except_osv(
                        _('Error!'),
                        _('Wrong quantity defined for salary rule %s (%s).') %
                        (rule.name, rule.code))
            elif rule.custom_amount_select == 'percentage':
                try:
                    return (Decimal(
                        safe_eval(rule.custom_amount_percentage_base,
                                  localdict)),
                            float(safe_eval(rule.custom_quantity, localdict)),
                            rule.custom_amount_percentage)
                except:
                    raise osv.except_osv(
                        _('Error!'),
                        _('Wrong percentage base or quantity defined for '
                          'salary rule %s (%s).') % (rule.name, rule.code))

        if codigo_python:
            if True:  # try:
                for variavel in localdict:
                    if isinstance(localdict[variavel], float):
                        localdict[variavel] = Decimal(localdict[variavel] or 0)
                safe_eval(codigo_python, localdict, mode='exec', nocopy=True)
                result = localdict['result']

                if 'result_qty' in localdict:
                    result_qty = localdict['result_qty']
                else:
                    result_qty = 1

                if 'result_rate' in localdict:
                    result_rate = localdict['result_rate']
                else:
                    result_rate = 100

                return result, result_qty, result_rate
    def _compute_inss(self, BASE_INSS, date_from):
        ano = fields.Datetime.from_string(date_from).year
        tabela_inss_obj = self.env['l10n_br.hr.social.security.tax']
        tabela_vigente = tabela_inss_obj.search([('year', '=', ano)])

        if tabela_vigente:
            for faixa in tabela_vigente:
                if BASE_INSS < faixa.max_wage:
                    inss = Decimal(BASE_INSS)
                    inss *= Decimal(faixa.rate) / 100
                    inss = inss.quantize(Decimal('0.01'), ROUND_DOWN)
                    return inss

            inss = Decimal(tabela_vigente[-1].max_wage)
            inss *= Decimal(tabela_vigente[-1].rate) / 100
            inss = inss.quantize(Decimal('0.01'), ROUND_DOWN)
            return inss

        else:
            raise exceptions.Warning(
                _('Tabela de INSS do ano Vigente Não encontrada!'))
Пример #3
0
 def _compute_total(self):
     for linha in self:
         total = Decimal(linha.amount or 0)
         total *= Decimal(linha.quantity or 0)
         total *= Decimal(linha.rate or 0)
         total /= 100
         total = total.quantize(Decimal('0.01'))
         linha.total = total
Пример #4
0
    def _onchange_payment_term(self):
        res = {}
        valores = {}
        res['value'] = valores

        if not (self.payment_term_id and self.valor and self.documento_id):
            return res

        valor = Decimal(self.valor or 0)

        #
        # Para a compatibilidade com a chamada original (super), que usa
        # o decorator deprecado api.one, pegamos aqui sempre o 1º elemento
        # da lista que vai ser retornada
        #
        lista_vencimentos = self.payment_term_id.compute(
            valor,
            self.documento_id.data_emissao,
        )[0]

        duplicata_ids = [
            [5, False, {}],
        ]

        parcela = 1
        for data_vencimento, valor in lista_vencimentos:
            duplicata = {
                'numero': str(parcela),
                'data_vencimento': data_vencimento,
                'valor': valor,
            }
            duplicata_ids.append([0, False, duplicata])
            parcela += 1

        valores['duplicata_ids'] = duplicata_ids
        valores['forma_pagamento'] = self.payment_term_id.forma_pagamento
        valores['bandeira_cartao'] = self.payment_term_id.bandeira_cartao
        valores['integracao_cartao'] = self.payment_term_id.integracao_cartao

        if self.payment_term_id.participante_id:
            valores['participante_id'] = \
                self.payment_term_id.participante_id.id
            valores['cnpj_cpf'] = \
                self.payment_term_id.participante_id.cnpj_cpf
        else:
            valores['participante_id'] = False
            valores['cnpj_cpf'] = False

        return res
Пример #5
0
    def _onchange_payment_term(self):
        res = {}
        valores = {}
        res['value'] = valores

        if not (self.payment_term_id and self.valor and self.documento_id):
            return res

        valor = Decimal(self.valor or 0)

        lista_vencimentos = self.payment_term_id.compute(
            valor,
            self.documento_id.data_emissao,
        )

        duplicata_ids = [
            [5, False, {}],
        ]

        parcela = 1
        for data_vencimento, valor in lista_vencimentos:
            duplicata = {
                'numero': str(parcela),
                'data_vencimento': data_vencimento,
                'valor': valor,
            }
            duplicata_ids.append([0, False, duplicata])
            parcela += 1

        valores['duplicata_ids'] = duplicata_ids
        valores['forma_pagamento'] = self.payment_term_id.forma_pagamento
        valores['bandeira_cartao'] = self.payment_term_id.bandeira_cartao
        valores['integracao_cartao'] = self.payment_term_id.integracao_cartao

        if self.payment_term_id.participante_id:
            valores['participante_id'] = \
                self.payment_term_id.participante_id.id
            valores['cnpj_cpf'] = \
                self.payment_term_id.participante_id.cnpj_cpf
        else:
            valores['participante_id'] = False
            valores['cnpj_cpf'] = False

        return res
    def _compute_irrf(self, BASE_IRRF, employee_id, inss, date_from):
        ano = fields.Datetime.from_string(date_from).year
        tabela_irrf_obj = self.env['l10n_br.hr.income.tax']
        tabela_vigente = tabela_irrf_obj.search([('year', '=', ano)],
                                                order='rate DESC')

        if tabela_vigente:
            for faixa in tabela_vigente:
                if BASE_IRRF > faixa.max_wage:
                    irrf = \
                        Decimal(BASE_IRRF or 0) * (
                            Decimal(faixa.rate) / 100.00
                        ) - Decimal(faixa.deductable)
                    irrf = irrf.quantize(Decimal('0.01'))
                    return irrf, faixa.rate
        else:
            raise UserError(_('Tabela de IRRF do ano Vigente Não encontrada!'))
Пример #7
0
    def get_payslip_lines(self):
        """
        """

        def _sum_salary_rule_category(localdict, category, amount):
            if category.parent_id:
                localdict = _sum_salary_rule_category(
                    localdict, category.parent_id, amount)
            localdict['categories'].dict[category.code] = \
                category.code in localdict['categories'].dict and \
                localdict['categories'].dict[category.code] + amount or amount
            return localdict

        class BrowsableObject(object):
            def __init__(self, employee_id, dict):
                self.employee_id = employee_id
                self.dict = dict

            def __getattr__(self, attr):
                return attr in self.dict and self.dict.__getitem__(attr) or 0.0

        # we keep a dict with the result because a value can be overwritten
        # by another rule with the same code
        result_dict = {}
        rules = {}
        categories_dict = {}
        blacklist = []
        payslip_obj = self.env['hr.payslip']
        obj_rule = self.env['hr.salary.rule']
        medias = {}
        categories_obj = BrowsableObject(self.employee_id.id, categories_dict)

        # Variaveis para INSS patronal
        rat_fap = self._get_rat_fap_period_values(self.ano)

        baselocaldict = {
            'CALCULAR': self,
            'BASE_INSS': 0.0, 'BASE_FGTS': 0.0, 'BASE_IR': 0.0,
            'categories': categories_obj,
            'locals': locals, 'globals': locals,
            'Decimal': Decimal, 'D': Decimal,
            'payslip': self,
            'RAT_FAP': rat_fap,
        }

        for contract_id in self.contract_id:
            # recuperar todas as estrututras que serao processadas
            # (estruturas da payslip atual e as estruturas pai da payslip)
            structure_ids = self.struct_id._get_parent_structure()

            # recuperar as regras das estruturas e filha de cada regra
            rule_ids = self.env['hr.payroll.structure'].browse(
                structure_ids).get_all_rules()

            # Caso nao esteja computando holerite de provisão de ferias ou
            # de decimo terceiro recuperar as regras especificas do contrato
            applied_specific_rule = \
                self.get_contract_specific_rubrics(contract_id, rule_ids)

            # organizando as regras pela sequencia de execução definida
            sorted_rule_ids = \
                [id for id, sequence in sorted(rule_ids, key=lambda x: x[1])]

            employee = contract_id.employee_id
            localdict = \
                dict(baselocaldict, employee=employee, contract=contract_id)

            for rule in obj_rule.browse(sorted_rule_ids):
                key = rule.code + '-' + str(self.id)
                localdict['result'] = None
                localdict['result_qty'] = 1.0
                localdict['result_rate'] = 100
                localdict['rubrica'] = rule
                id_rubrica_especifica = 0
                beneficiario_id = False

                # check if the rule can be applied
                if obj_rule.satisfy_condition(rule.id, localdict) \
                        and rule.id not in blacklist:
                    # compute the amount of the rule
                    amount, qty, rate = \
                        obj_rule.compute_rule(rule.id, localdict)

                    # se ja tiver sido calculado a media dessa rubrica,
                    # utilizar valor da media e multiplicar
                    # pela reinciden.
                    if medias.get(rule.code):
                        amount = medias.get(rule.code).media / 12
                        qty = medias.get(rule.code).meses
                        rule.name += ' (Media) '

                    # check if there is already a rule computed
                    # with that code
                    previous_amount = \
                        rule.code in localdict and \
                        localdict[rule.code] or 0.0
                    # previous_amount = 0
                    # set/overwrite the amount computed
                    # for this rule in the localdict
                    tot_rule = Decimal(amount or 0) * Decimal(
                        qty or 0) * Decimal(rate or 0) / 100.0
                    tot_rule = tot_rule.quantize(Decimal('0.01'))
                    localdict[rule.code] = tot_rule
                    rules[rule.code] = rule

                    # Adiciona a rubrica especifica ao localdict
                    if id_rubrica_especifica:
                        localdict['RUBRICAS_ESPEC_CALCULADAS'].append(
                            id_rubrica_especifica)

                    # sum the amount for its salary category
                    localdict = _sum_salary_rule_category(
                        localdict, rule.category_id,
                        tot_rule - previous_amount)

                    # Definir o partner que recebera o pagamento da linha
                    if not beneficiario_id and \
                            contract_id.employee_id.address_home_id:
                        beneficiario_id = \
                            contract_id.employee_id.address_home_id.id

                    # create/overwrite the rule in the temporary results
                    result_dict[key] = {
                        'salary_rule_id': rule.id,
                        'contract_id': contract_id.id,
                        'name': rule.name,
                        'code': rule.code,
                        'category_id': rule.category_id.id,
                        'sequence': rule.sequence,
                        'appears_on_payslip': rule.appears_on_payslip,
                        'condition_select': rule.condition_select,
                        'condition_python': rule.condition_python,
                        'condition_range': rule.condition_range,
                        'condition_range_min':
                            rule.condition_range_min,
                        'condition_range_max':
                            rule.condition_range_max,
                        'amount_select': rule.amount_select,
                        'amount_fix': rule.amount_fix,
                        'amount_python_compute':
                            rule.amount_python_compute,
                        'amount_percentage': rule.amount_percentage,
                        'amount_percentage_base':
                            rule.amount_percentage_base,
                        'register_id': rule.register_id.id,
                        'amount': amount,
                        'employee_id': contract_id.employee_id.id,
                        'quantity': qty,
                        'rate': rate,
                        'partner_id': beneficiario_id or 1,
                    }

                    blacklist.append(rule.id)
                else:
                    rules_seq = rule._model._recursive_search_of_rules(
                        self._cr, self._uid, rule, self._context)
                    blacklist += [id for id, seq in rules_seq]
                    continue

                if rule.category_id.code == 'DEDUCAO':
                    if rule.compoe_base_INSS:
                        localdict['BASE_INSS'] -= tot_rule
                    if rule.compoe_base_IR:
                        localdict['BASE_IR'] -= tot_rule
                    if rule.compoe_base_FGTS:
                        localdict['BASE_FGTS'] -= tot_rule
                else:
                    if rule.compoe_base_INSS:
                        localdict['BASE_INSS'] += tot_rule
                    if rule.compoe_base_IR:
                        localdict['BASE_IR'] += tot_rule
                    if rule.compoe_base_FGTS:
                        localdict['BASE_FGTS'] += tot_rule

            result = [value for code, value in result_dict.items()]
            return result