예제 #1
0
 def _document_status(self):
     for record in self.filtered(filter_oca_nfse).filtered(
             filter_paulistana):
         processador = record._processador_erpbrasil_nfse()
         processo = processador.consulta_nfse_rps(
             numero_rps=record.rps_number,
             serie_rps=record.document_serie,
             insc_prest=misc.punctuation_rm(
                 record.company_id.partner_id.inscr_mun or "") or None,
             cnpj_prest=misc.punctuation_rm(
                 record.company_id.partner_id.cnpj_cpf),
         )
         consulta = processador.analisa_retorno_consulta(processo)
         if isinstance(consulta, dict):
             record.write({
                 "verify_code": consulta["codigo_verificacao"],
                 "document_number": consulta["numero"],
                 "authorization_date": consulta["data_emissao"],
             })
             record.authorization_event_id.set_done(
                 status_code=4,
                 response=_("Procesado com Sucesso"),
                 protocol_date=consulta["data_emissao"],
                 protocol_number=record.authorization_protocol,
                 file_response_xml=processo.retorno,
             )
         return _(consulta)
    def dados_boleto(self):
        journal = self.env['account.journal'].search([('code', '=', 'Inter')])
        dados = []
        myself = User(
            name=self.company_id.legal_name,
            identifier=misc.punctuation_rm(self.company_id.cnpj_cpf),
            bank=UserBank(
                bankId=journal.bank_account_id.bank_id.bic,
                branchCode=journal.bank_account_id.bra_number,
                accountNumber=journal.bank_account_id.acc_number,
                accountVerifier=journal.bank_account_id.acc_number_dig,
                bankName=journal.bank_account_id.bank_id.name
            ),
        )
        payer = User(
            name=self.partner_id.name,
            identifier=misc.punctuation_rm(self.partner_id.cnpj_cpf),
            email=self.partner_id.email,
            personType='FISICA' if self.partner_id.company_type == 'person' else 'JURIDICA',
            phone=caracteres_rm(self.partner_id.phone),
            address=UserAddress(
                streetLine1=self.partner_id.street,
                district=self.partner_id.district,
                city=self.partner_id.city_id.name,
                stateCode=self.partner_id.state_id.code,
                zipCode=misc.punctuation_rm(self.partner_id.zip),
                streetNumber=self.partner_id.number,
            )
        )

        slip = BoletoInter(
            sender=myself,
            amount=self.amount_total,
            payer=payer,
            issue_date=datetime.now(),
            identifier=misc.punctuation_rm(self.partner_id.cnpj_cpf),
            instructions=[
                journal.instrucao1,
                journal.instrucao2,
                journal.instrucao3,
                journal.instrucao4,
            ],
            multa=dict(
                codigoMulta=journal.codigo_multa,
                data=str(self.date_due + timedelta(days=journal.dia_carencia_multa)),
                valor=0 if journal.codigo_multa == 'PERCENTUAL' else journal.valor_multa,
                taxa=0 if journal.codigo_multa == 'VALORFIXO' else journal.taxa_multa
            ),
            mora=dict(
                codigoMora=journal.codigo_mora,
                data=str(self.date_due + timedelta(days=journal.dia_carencia_mora)),
                valor=0 if journal.codigo_mora == 'TAXAMENSAL' else journal.valor_mora,
                taxa=0 if journal.codigo_mora == 'VALORFIXO' else journal.taxa_mora
            ),
            due_date=self.date_due,
        )
        dados.append(slip)
        return dados
예제 #3
0
 def _create_tempfile_path(self, document):
     fsc_op_type = {'out': 'Saída', 'in': 'Entrada', 'all': 'Todos'}
     document_path = '/'.join([
         misc.punctuation_rm(document.company_cnpj_cpf),
         document.date.strftime("%m-%Y"),
         PATH_MODELO[document.document_type_id.code],
         fsc_op_type.get(document.fiscal_operation_type),
         (document.document_serie or '').zfill(3) +
         ('-' + misc.punctuation_rm(str(document.number)).zfill(9)
          if self.group_folder else '')
     ])
     return document_path
예제 #4
0
 def _create_tempfile_path(self, document):
     fsc_op_type = {"out": "Saída", "in": "Entrada", "all": "Todos"}
     document_path = "/".join([
         misc.punctuation_rm(document.company_cnpj_cpf),
         document.document_date.strftime("%m-%Y"),
         PATH_MODELO[document.document_type_id.code],
         fsc_op_type.get(document.fiscal_operation_type),
         (document.document_serie or "").zfill(3) +
         ("-" + misc.punctuation_rm(str(document.document_number)).zfill(9)
          if self.group_folder else ""),
     ])
     return document_path
예제 #5
0
 def _generate_bank_inter_boleto_data(self):
     dados = []
     myself = User(
         name=self.company_id.legal_name,
         identifier=misc.punctuation_rm(self.company_id.cnpj_cpf),
         bank=UserBank(
             bankId=self.company_partner_bank_id.bank_id.code_bc,
             branchCode=self.company_partner_bank_id.bra_number,
             accountNumber=self.company_partner_bank_id.acc_number,
             accountVerifier=self.company_partner_bank_id.acc_number_dig,
             bankName=self.company_partner_bank_id.bank_id.name,
         ),
     )
     for line in self.bank_line_ids:
         payer = User(
             name=line.partner_id.legal_name,
             identifier=misc.punctuation_rm(
                 line.partner_id.cnpj_cpf
             ),
             email=line.partner_id.email or '',
             personType=(
                 "FISICA" if line.partner_id.company_type == 'person'
                 else 'JURIDICA'),
             phone=misc.punctuation_rm(
                 line.partner_id.phone).replace(" ", ""),
             address=UserAddress(
                 streetLine1=line.partner_id.street or '',
                 district=line.partner_id.district or '',
                 city=line.partner_id.city_id.name or '',
                 stateCode=line.partner_id.state_id.code or '',
                 zipCode=misc.punctuation_rm(line.partner_id.zip),
                 streetNumber=line.partner_id.street_number,
             )
         )
         slip = BoletoInter(
             sender=myself,
             amount=line.amount_currency,
             payer=payer,
             issue_date=line.create_date,
             due_date=line.date,
             identifier=line.document_number,
             instructions=[
                 'TESTE 1',
                 'TESTE 2',
                 'TESTE 3',
                 'TESTE 4',
             ]
         )
         dados.append(slip)
     return dados
예제 #6
0
    def _set_domain(
        self,
        country_id=False,
        state_id=False,
        city_id=False,
        district=False,
        street=False,
        zip_code=False,
    ):
        domain = []
        if zip_code:
            new_zip = misc.punctuation_rm(zip_code or "")
            domain.append(("zip_code", "=", new_zip))
        else:
            if not state_id or not city_id or len(street or "") == 0:
                raise UserError(
                    _("Necessário informar Estado, município e logradouro"))

            if country_id:
                domain.append(("country_id", "=", country_id))
            if state_id:
                domain.append(("state_id", "=", state_id))
            if city_id:
                domain.append(("city_id", "=", city_id))
            if district:
                domain.append(("district", "ilike", district))
            if street:
                domain.append(("street", "ilike", street))

        return domain
예제 #7
0
 def prepare_line_servico(self):
     return {
         'valor_servicos': self.fiscal_price,
         'valor_deducoes': self.fiscal_deductions_value,
         'valor_pis': round(self.pis_value, 2),
         'valor_pis_retido': round(self.pis_wh_value, 2),
         'valor_cofins': round(self.cofins_value, 2),
         'valor_cofins_retido': round(self.cofins_wh_value, 2),
         'valor_inss': round(self.inss_value, 2),
         'valor_inss_retido': round(self.inss_wh_value, 2),
         'valor_ir': round(self.irpj_value, 2),
         'valor_ir_retido': round(self.irpj_wh_value, 2),
         'valor_csll': round(self.csll_value, 2),
         'valor_csll_retido': round(self.csll_wh_value, 2),
         'iss_retido': '1' if self.issqn_wh_value else '2',
         'valor_iss': round(self.issqn_value, 2),
         'valor_iss_retido': round(self.issqn_wh_value, 2),
         'outras_retencoes': self.other_retentions_value,
         'base_calculo': self.issqn_base,
         'aliquota': self.issqn_percent / 100,
         'valor_liquido_nfse': self.amount_financial,
         'item_lista_servico':
             self.service_type_id.code and
             self.service_type_id.code.replace('.', ''),
         'codigo_tributacao_municipio':
             self.city_taxation_code_id.code or '',
         'discriminacao': str(self.name[:2000] or ''),
         'codigo_cnae': misc.punctuation_rm(self.cnae_id.code) or None,
     }
예제 #8
0
    def _consultar_cep(self, zip_code):
        zip_str = misc.punctuation_rm(zip_code)
        try:
            cep = pycep_correios.consultar_cep(zip_str)
        except Exception as e:
            raise UserError(
                _('Erro no PyCEP-Correios : ') + str(e))

        values = {}
        if cep:
            # Search Brazil id
            country = self.env['res.country'].search(
                [('code', '=', 'BR')], limit=1)

            # Search state with state_code and country id
            state = self.env['res.country.state'].search([
                ('code', '=', cep['uf']),
                ('country_id', '=', country.id)], limit=1)

            # search city with name and state
            city = self.env['res.city'].search([
                ('name', '=', cep['cidade']),
                ('state_id.id', '=', state.id)], limit=1)

            values = {
                'zip_code': zip_str,
                'street': cep['end'],
                'zip_complement': cep['complemento2'],
                'district': cep['bairro'],
                'city_id': city.id or False,
                'state_id': state.id or False,
                'country_id': country.id or False,
            }
        return values
예제 #9
0
 def _check_cpf(self):
     for record in self:
         country_code = record.country_id.code or ""
         if record.cpf and country_code.upper() == "BR":
             cpf = misc.punctuation_rm(record.cpf)
             if not cnpj_cpf.validar(cpf):
                 raise ValidationError(_("CPF: {} Invalid!").format(cpf))
예제 #10
0
 def prepare_line_servico(self):
     return {
         "valor_servicos": round(self.fiscal_price, 2),
         "valor_deducoes": round(self.fiscal_deductions_value, 2),
         "valor_pis": round(self.pis_value, 2) or round(self.pis_wh_value, 2),
         "valor_pis_retido": round(self.pis_wh_value, 2),
         "valor_cofins": round(self.cofins_value, 2)
         or round(self.cofins_wh_value, 2),
         "valor_cofins_retido": round(self.cofins_wh_value, 2),
         "valor_inss": round(self.inss_value, 2) or round(self.inss_wh_value, 2),
         "valor_inss_retido": round(self.inss_wh_value, 2),
         "valor_ir": round(self.irpj_value, 2) or round(self.irpj_wh_value, 2),
         "valor_ir_retido": round(self.irpj_wh_value, 2),
         "valor_csll": round(self.csll_value, 2) or round(self.csll_wh_value, 2),
         "valor_csll_retido": round(self.csll_wh_value, 2),
         "iss_retido": "1" if self.issqn_wh_value else "2",
         "valor_iss": round(self.issqn_value, 2),
         "valor_iss_retido": round(self.issqn_wh_value, 2),
         "outras_retencoes": round(self.other_retentions_value, 2),
         "base_calculo": round(self.issqn_base, 2) or round(self.issqn_wh_base, 2),
         "aliquota": (self.issqn_percent / 100) or (self.issqn_wh_percent / 100),
         "valor_liquido_nfse": round(self.amount_taxed, 2),
         "item_lista_servico": self.service_type_id.code
         and self.service_type_id.code.replace(".", ""),
         "codigo_tributacao_municipio": self.city_taxation_code_id.code or "",
         "municipio_prestacao_servico": self.issqn_fg_city_id.ibge_code or "",
         "discriminacao": str(self.name[:2000] or ""),
         "codigo_cnae": misc.punctuation_rm(self.cnae_id.code) or None,
         "valor_desconto_incondicionado": round(self.discount_value, 2),
     }
예제 #11
0
    def _consultar_cep(self, zip_code):
        zip_str = misc.punctuation_rm(zip_code)
        try:
            cep = pycep_correios.get_address_from_cep(zip_str)
        except Exception as e:
            raise UserError(_("Erro no PyCEP-Correios : ") + str(e))

        values = {}
        if cep:
            # Search Brazil id
            country = self.env["res.country"].search([("code", "=", "BR")],
                                                     limit=1)

            # Search state with state_code and country id
            state = self.env["res.country.state"].search(
                [("code", "=", cep.get("uf")),
                 ("country_id", "=", country.id)],
                limit=1)

            # search city with name and state
            city = self.env["res.city"].search(
                [("name", "=", cep.get("cidade")),
                 ("state_id.id", "=", state.id)],
                limit=1)

            values = {
                "zip_code": zip_str,
                "street": cep.get("logradouro"),
                "zip_complement": cep.get("complemento"),
                "district": cep.get("bairro"),
                "city_id": city.id or False,
                "state_id": state.id or False,
                "country_id": country.id or False,
            }
        return values
예제 #12
0
    def _compute_nfe_data(self):
        """Set schema data which are not just related fields"""
        for rec in self:
            if rec.cnpj_cpf:
                if rec.country_id.code != "BR":
                    rec.nfe40_choice7 = "nfe40_idEstrangeiro"
                elif rec.is_company:
                    rec.nfe40_CNPJ = punctuation_rm(rec.cnpj_cpf)
                    rec.nfe40_choice7 = "nfe40_CNPJ"
                else:
                    rec.nfe40_CPF = punctuation_rm(rec.cnpj_cpf)
                    rec.nfe40_choice7 = "nfe40_CPF"

            if rec.inscr_est and rec.is_company:
                rec.nfe40_IE = punctuation_rm(rec.inscr_est)
            else:
                rec.nfe40_IE = None
예제 #13
0
 def _processador_erpbrasil_nfse(self):
     certificado = cert.Certificado(
         arquivo=self.company_id.certificate_nfe_id.file,
         senha=self.company_id.certificate_nfe_id.password,
     )
     session = Session()
     session.verify = False
     transmissao = TransmissaoSOAP(certificado, session)
     return NFSeFactory(
         transmissao=transmissao,
         ambiente=self.nfse_environment,
         cidade_ibge=int(self.company_id.partner_id.city_id.ibge_code),
         cnpj_prestador=misc.punctuation_rm(
             self.company_id.partner_id.cnpj_cpf),
         im_prestador=misc.punctuation_rm(
             self.company_id.partner_id.inscr_mun or ""),
     )
예제 #14
0
    def prepare_partner_tomador(self, company_id):
        if self.is_company:
            tomador_cnpj = misc.punctuation_rm(
                self.cnpj_cpf or '')
            tomador_cpf = None
        else:
            tomador_cnpj = None
            tomador_cpf = misc.punctuation_rm(
                self.cnpj_cpf or '')
        partner_cep = misc.punctuation_rm(self.zip)

        if self.country_id.id != company_id:
            address_invoice_state_code = 'EX'
            address_invoice_city_code = int('9999999')
            address_invoice_city_description = 'EX Description'
        else:
            address_invoice_state_code = self.state_id.code
            address_invoice_city_code = int('%s%s' % (
                self.state_id.ibge_code,
                self.city_id.ibge_code))
            address_invoice_city_description = self.city_id.name

        if self.email:
            email = self.email
        else:
            email = None

        return {
            'cnpj': tomador_cnpj,
            'cpf': tomador_cpf,
            'email': email,
            'inscricao_municipal': misc.punctuation_rm(
                self.inscr_mun or '') or None,
            'inscricao_estadual': misc.punctuation_rm(
                self.inscr_est or '') or None,
            'razao_social': str(self.legal_name[:60] or ''),
            'endereco': str(self.street or
                            self.street_name or ''),
            'numero': self.street_number or '',
            'bairro': str(self.district or 'Sem Bairro'),
            'codigo_municipio': address_invoice_city_code,
            'descricao_municipio': address_invoice_city_description,
            'uf': address_invoice_state_code,
            'municipio': self.city or None,
            'cep': int(partner_cep),
        }
예제 #15
0
 def _check_cpf(self):
     for record in self:
         country_code = record.country_id.code or ''
         if record.cpf and country_code.upper() == 'BR':
             cpf = misc.punctuation_rm(record.cpf)
             if not fiscal.validate_cpf(cpf):
                 raise ValidationError(_('CPF inválido!'))
         return True
예제 #16
0
 def _check_cnpj(self):
     for record in self:
         country_code = record.country_id.code or ""
         if record.cnpj and country_code.upper() == "BR":
             cnpj = misc.punctuation_rm(record.cnpj)
             if not cnpj_cpf.validar(cnpj):
                 raise ValidationError(_("CNPJ inválido!"))
         return True
예제 #17
0
 def _check_cnpj(self):
     for record in self:
         country_code = record.country_id.code or ''
         if record.cnpj and country_code.upper() == 'BR':
             cnpj = misc.punctuation_rm(record.cnpj)
             if not fiscal.validate_cnpj(cnpj):
                 raise ValidationError(_('CNPJ inválido!'))
         return True
예제 #18
0
 def _prepare_lote_rps(self):
     num_rps = self.rps_number
     return {
         "cnpj":
         misc.punctuation_rm(self.company_id.partner_id.cnpj_cpf),
         "inscricao_municipal":
         misc.punctuation_rm(self.company_id.partner_id.inscr_mun or "")
         or None,
         "id":
         "rps" + str(num_rps),
         "numero":
         num_rps,
         "serie":
         self.document_serie_id.code or "",
         "tipo":
         self.rps_type,
         "data_emissao":
         fields.Datetime.context_timestamp(
             self, fields.Datetime.from_string(
                 self.document_date)).strftime("%Y-%m-%dT%H:%M:%S"),
         "date_in_out":
         fields.Datetime.context_timestamp(
             self, self.date_in_out).strftime("%Y-%m-%dT%H:%M:%S"),
         "natureza_operacao":
         self.operation_nature,
         "regime_especial_tributacao":
         self.taxation_special_regime,
         "optante_simples_nacional":
         "1" if self.company_id.tax_framework in TAX_FRAMEWORK_SIMPLES_ALL
         else "2",
         "incentivador_cultural":
         "1" if self.company_id.cultural_sponsor else "2",
         "status":
         "1",
         "rps_substitiuido":
         None,
         "intermediario_servico":
         None,
         "construcao_civil":
         None,
         "carga_tributaria":
         self.amount_tax,
         "total_recebido":
         self.amount_total,
     }
예제 #19
0
    def _prepare_lote_rps(self):
        num_rps = self.rps_number

        dh_emi = fields.Datetime.context_timestamp(
            self, fields.Datetime.from_string(
                self.date)).strftime('%Y-%m-%dT%H:%M:%S')
        return {
            'cnpj':
            misc.punctuation_rm(self.company_id.partner_id.cnpj_cpf),
            'inscricao_municipal':
            misc.punctuation_rm(self.company_id.partner_id.inscr_mun or '')
            or None,
            'id':
            'rps' + str(num_rps),
            'numero':
            num_rps,
            'serie':
            self.document_serie_id.code or '',
            'tipo':
            self.rps_type,
            'data_emissao':
            dh_emi,
            'natureza_operacao':
            self.operation_nature,
            'regime_especial_tributacao':
            self.taxation_special_regime,
            'optante_simples_nacional':
            '1' if self.company_id.tax_framework in TAX_FRAMEWORK_SIMPLES_ALL
            else '2',
            'incentivador_cultural':
            '1' if self.company_id.cultural_sponsor else '2',
            'status':
            '1',
            'rps_substitiuido':
            None,
            'intermediario_servico':
            None,
            'construcao_civil':
            None,
            'carga_tributaria':
            self.amount_tax,
            'total_recebido':
            self.amount_financial,
        }
예제 #20
0
    def setUp(self):
        certificado_nfe_caminho = os.environ.get(
            'certificado_nfe_caminho', 'test/fixtures/dummy_cert.pfx')
        certificado_nfe_senha = os.environ.get('certificado_nfe_senha',
                                               'dummy_password')
        self.certificado = Certificado(certificado_nfe_caminho,
                                       certificado_nfe_senha)
        session = Session()
        session.verify = False

        transmissao = TransmissaoSOAP(self.certificado, session)

        self.nfse = NFSeFactory(
            transmissao=transmissao,
            ambiente='2',
            cidade_ibge=3132404,
            cnpj_prestador=misc.punctuation_rm('23.130.935/0001-98'),
            im_prestador=misc.punctuation_rm('35172'),
        )
예제 #21
0
    def _prepare_files(self, temp_dir):
        domain = self._document_domain()
        documents = self.env["l10n_br_fiscal.document"].search(domain)

        attachment_ids = self.env["ir.attachment"]

        attachment_ids |= documents.mapped("invalidate_event_id").mapped(
            "file_response_id")

        if attachment_ids:
            try:
                path = "/".join([
                    misc.punctuation_rm(self.company_id.cnpj_cpf),
                    "invalidate_numbers",
                ])
                for attachment in attachment_ids:
                    self._save_tempfile(path, attachment, temp_dir)
            except OSError:
                raise RedirectWarning(_("Error!"), _("I/O Error"))
            except PermissionError:
                raise RedirectWarning(
                    _("Error!"),
                    _("Check write permissions in your system temp folder"))

        for document in documents:
            attachment_ids = document.authorization_event_id.mapped(
                "file_response_id")
            attachment_ids |= document.cancel_event_id.mapped(
                "file_response_id")
            attachment_ids |= document.correction_event_ids.mapped(
                "file_response_id")
            if self.include_pdf_file:
                attachment_ids |= document.file_report_id

            if self.export_type == "period":
                document.close_id = self.id

            try:
                document_path = self._create_tempfile_path(document)

                for attachment in attachment_ids:
                    self._save_tempfile(document_path, attachment, temp_dir)
            except OSError:
                raise RedirectWarning(_("Error!"), _("I/O Error"))
            except PermissionError:
                raise RedirectWarning(
                    _("Error!"),
                    _("Check write permissions in your system temp folder"))
            except Exception:
                _logger.error(
                    _("Replication failed: document attachments "
                      "[id =% s] is not present in the database." %
                      document.id))
        return temp_dir.name
예제 #22
0
 def monta_caminho(self, document):
     document_path = '/'.join([
         # TODO: Colocar ambiente
         # PATH_AMBIENTE[documento.nfe_environment],
         misc.punctuation_rm(document.company_cnpj_cpf),
         PATH_MODELO[document.document_type_id.code],
         document.date.strftime("%m-%Y"),
         document.document_serie_id.code.zfill(3) +
         ('-' + misc.punctuation_rm(str(document.number)).zfill(9)
          if self.group_folder else '')
     ])
     if self.raiz:
         if not os.path.exists(self.raiz + '/' + document_path):
             try:
                 os.makedirs(self.raiz + '/' + document_path)
             except OSError:
                 raise RedirectWarning(
                     _('Error!'),
                     _('Check write permissions and folder path'))
     return document_path
예제 #23
0
 def _prepare_boleto_bank_line_vals(self):
     return {
         "valor": self.amount_currency,
         "data_vencimento": self.date.strftime("%Y/%m/%d"),
         "nosso_numero": self.own_number,
         "documento_sacado": misc.punctuation_rm(self.partner_id.cnpj_cpf),
         "nome_sacado": self.partner_id.legal_name.strip()[:40],
         "numero": self.document_number,
         "endereco_sacado": str(
             self.partner_id.street_name + ", " + str(self.partner_id.street_number)
         )[:40],
         "bairro_sacado": self.partner_id.district.strip(),
         "cep_sacado": misc.punctuation_rm(self.partner_id.zip),
         "cidade_sacado": self.partner_id.city_id.name,
         "uf_sacado": self.partner_id.state_id.code,
         # Codigo da Ocorrencia usado pode variar por Banco, CNAB e operação
         # ex.: UNICRED 240/400 é 01 - Remessa*, 02 - Pedido de Baixa e
         # 06 - Alteração de vencimento . Veja que está sendo informado
         # o campo Code do objeto.
         "identificacao_ocorrencia": self.mov_instruction_code_id.code,
     }
    def _prepare_remessa_sicredi_240(self, remessa_values):

        bank_account_id = self.journal_id.bank_account_id
        remessa_values.update({
            # Aparentemente a validação do BRCobranca nesse caso gera erro
            # quando é feito o int(misc.punctuation_rm(bank_account_id.acc_number))
            "conta_corrente":
            misc.punctuation_rm(bank_account_id.acc_number),
            "posto":
            self.payment_mode_id.boleto_post,
            "byte_idt":
            self.payment_mode_id.boleto_byte_idt,
        })
예제 #25
0
    def _export_field(self, xsd_field, class_obj, member_spec):
        # TODO: Export number required fields with Zero.
        # xsd_required = class_obj._fields[xsd_field]._attrs.get(
        #    'xsd_required')

        if (hasattr(class_obj._fields[xsd_field], "xsd_type")
                and class_obj._fields[xsd_field].xsd_type in ("TCnpj", "TCpf")
                and self[xsd_field] is not False):
            return misc.punctuation_rm(self[xsd_field])
        elif (hasattr(class_obj._fields[xsd_field], "xsd_type")
              and "TIe" in class_obj._fields[xsd_field].xsd_type
              and self[xsd_field] is not False):
            return misc.punctuation_rm(self[xsd_field])
        elif (hasattr(class_obj._fields[xsd_field], "xsd_type")
              and "foneType" in class_obj._fields[xsd_field].xsd_type
              and self[xsd_field] is not False):
            return (self[xsd_field].replace("(", "").replace(")", "").replace(
                " ", "").replace("-", "").replace("+", ""))
        elif (hasattr(class_obj._fields[xsd_field], "xsd_type")
              and "CEPType" in class_obj._fields[xsd_field].xsd_type
              and self[xsd_field] is not False):
            return self[xsd_field].replace("-", "")
        else:
            return super()._export_field(xsd_field, class_obj, member_spec)
예제 #26
0
def caminho_empresa(company_id, document):
    db_name = company_id._cr.dbname
    cnpj = misc.punctuation_rm(company_id.cnpj_cpf)

    filestore = config.filestore(db_name)
    path = "/".join([filestore, "edoc", document, cnpj])
    if not os.path.exists(path):
        try:
            os.makedirs(path)
        except OSError:
            raise UserError(
                _("Erro!"),
                _("""Verifique as permissões de escrita
                    e o caminho da pasta"""),
            )
    return path
예제 #27
0
    def _consultar_cep(self, zip_code):
        zip_str = misc.punctuation_rm(zip_code)
        try:
            cep_ws_providers = {
                "apicep": WebService.APICEP,
                "viacep": WebService.VIACEP,
                "correios": WebService.CORREIOS,
            }
            cep_ws_provide = str(
                self.env["ir.config_parameter"].sudo().get_param(
                    "l10n_zip.cep_ws_provider", default="correios"))
            cep = get_address_from_cep(
                zip_str, webservice=cep_ws_providers.get(cep_ws_provide))
        except Exception as e:
            raise UserError(_("Erro no PyCEP-Correios : ") + str(e))

        values = {}
        if cep and any(cep.values()):
            # Search Brazil id
            country = self.env["res.country"].search([("code", "=", "BR")],
                                                     limit=1)

            # Search state with state_code and country id
            state = self.env["res.country.state"].search(
                [("code", "=", cep.get("uf")),
                 ("country_id", "=", country.id)],
                limit=1)

            # search city with name and state
            city = self.env["res.city"].search(
                [("name", "=", cep.get("cidade")),
                 ("state_id.id", "=", state.id)],
                limit=1,
            )

            values = {
                "zip_code": zip_str,
                "street": cep.get("logradouro"),
                "zip_complement": cep.get("complemento"),
                "district": cep.get("bairro"),
                "city_id": city.id or False,
                "state_id": state.id or False,
                "country_id": country.id or False,
            }
        return values
예제 #28
0
    def action_ibpt_inquiry(self):
        if not self.env.user.company_id.ibpt_api:
            return False

        object_name = OBJECT_NAMES.get(self._name)
        object_field = OBJECT_FIELDS.get(self._name)

        for record in self:
            try:
                company = self.env.user.company_id

                config = DeOlhoNoImposto(
                    company.ibpt_token,
                    misc.punctuation_rm(company.cnpj_cpf),
                    company.state_id.code,
                )

                result = self._get_ibpt(config, record.code_unmasked)

                values = {
                    object_field: record.id,
                    "key": result.chave,
                    "origin": result.fonte,
                    "state_id": company.state_id.id,
                    "state_taxes": result.estadual,
                    "federal_taxes_national": result.nacional,
                    "federal_taxes_import": result.importado,
                }

                self.env["l10n_br_fiscal.tax.estimate"].create(values)

                record.message_post(
                    body=_("{} Tax Estimate Updated").format(object_name),
                    subject=_("{} Tax Estimate Updated").format(object_name),
                )

            except Exception as e:
                _logger.warning(
                    _("{0} Tax Estimate Failure: {1}").format(object_name, e))
                record.message_post(
                    body=str(e),
                    subject=_("{} Tax Estimate Failure").format(object_name),
                )
                continue
예제 #29
0
    def _invalidate(self, document_id=False):
        processador = self._processador()
        evento = processador.inutilizacao(
            cnpj=punctuation_rm(self.company_id.cnpj_cpf),
            mod=self.document_type_id.code,
            serie=self.document_serie_id.code,
            num_ini=self.number_start,
            num_fin=self.number_end,
            justificativa=self.justification.replace("\n", "\\n"),
        )

        processo = processador.envia_inutilizacao(evento=evento)

        event_id = self.event_ids.create_event_save_xml(
            company_id=self.company_id,
            environment=(EVENT_ENV_PROD if self.company_id.nfe_environment
                         == "1" else EVENT_ENV_HML),
            event_type="3",
            xml_file=processo.envio_xml.decode("utf-8"),
            invalidate_number_id=self,
        )

        if document_id:
            event_id.document_id = document_id
        self.event_ids |= event_id
        self.authorization_event_id = event_id

        if hasattr(processo.resposta.infInut, "dhRegEvento"):
            date_response = processo.resposta.infInut.dhRegEvento
        elif hasattr(processo.resposta.infInut, "dhRecbto"):
            date_response = processo.resposta.infInut.dhRecbto

        event_id.set_done(
            status_code=processo.resposta.infInut.cStat,
            response=processo.resposta.infInut.xMotivo,
            protocol_date=fields.Datetime.to_string(
                datetime.fromisoformat(date_response)),
            protocol_number=processo.resposta.infInut.nProt,
            file_response_xml=processo.retorno.content.decode("utf-8"),
        )

        if processo.resposta.infInut.cStat == "102":
            super(InvalidateNumber, self)._invalidate(document_id)
예제 #30
0
    def _set_domain(self, country_id=False, state_id=False,
                    city_id=False, district=False,
                    street=False, zip_code=False):
        domain = []
        if zip_code:
            new_zip = misc.punctuation_rm(zip_code or '')
            domain.append(('zip_code', '=', new_zip))
        else:
            if not state_id or not city_id or len(street or '') == 0:
                raise UserError(
                    _('Necessário informar Estado, município e logradouro'))

            if country_id:
                domain.append(('country_id', '=', country_id))
            if state_id:
                domain.append(('state_id', '=', state_id))
            if city_id:
                domain.append(('city_id', '=', city_id))
            if district:
                domain.append(('district', 'ilike', district))
            if street:
                domain.append(('street', 'ilike', street))

        return domain