Skip to content

Instantly share code, notes, and snippets.

@CoutinhoElias
Last active January 14, 2022 12:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CoutinhoElias/83d80525197f95eb98be0b42f6b0f6b5 to your computer and use it in GitHub Desktop.
Save CoutinhoElias/83d80525197f95eb98be0b42f6b0f6b5 to your computer and use it in GitHub Desktop.
Descobrir_um_bug
from ast import Try
from peewee import *
from peewee import SqliteDatabase, Model, TextField, ForeignKeyField
import xmltodict
import glob, os
# Abre a base de dados que receberá as informações dos XML'
database = SqliteDatabase('/home/elias/Área de Trabalho/notas_emissor/NfEasy2.db')
class UnknownField(object):
def __init__(self, *_, **__): pass
class BaseModel(Model):
class Meta:
database = database
class Empresa(BaseModel):
ambiente_mdfe = TextField(null=True)
ambiente_nfce = TextField(null=True)
ambiente_nfe = TextField(null=True)
ambiente_nfse = TextField(null=True)
aproveitamento_icms = BooleanField(null=True)
bairro = TextField(null=True)
cep = TextField(null=True)
cnae_fiscal = TextField(null=True)
cnpj = TextField(primary_key=True)
codigo_crm = TextField(null=True)
codigo_seguranca_contribuinte = TextField(null=True)
complemento = TextField(null=True)
danfe_contigencia = BooleanField(null=True)
data_exclusao = DateTimeField(null=True)
data_ultima_sincronizacao = TextField(null=True)
descricao_certificado = TextField(null=True)
diretorio_logo = TextField(null=True)
email = TextField(null=True)
email_adicional_envio_nota = TextField(null=True)
emite_mdfe = BooleanField(null=True)
emite_nfce = BooleanField(null=True)
emite_tef = BooleanField(null=True)
empresa_contabilidade = BooleanField(null=True)
empresa_master = TextField(null=True)
fonte_tributos_nfe = TextField(null=True)
identificacao_codigo_seguranca_contribuinte = TextField(null=True)
inscricao_estadual = TextField(null=True)
inscricao_estadual_substituto_tributario = TextField(null=True)
inscricao_municipal = TextField(null=True)
logradouro = TextField(null=True)
mensagem_generica_nfce = TextField(null=True)
mensagem_regime_normal = TextField(null=True)
mensagem_simples = TextField(null=True)
mensagem_simples_sublimite = TextField(null=True)
municipio = TextField(null=True)
nome = TextField()
nome_fantasia = TextField(null=True)
numero = TextField(null=True)
pais = TextField(null=True)
produtor_cana = BooleanField(null=True)
regime_tributario = TextField(null=True)
serial_certificado = TextField(null=True)
site = TextField(null=True)
status_produto_subempresa = TextField(null=True)
telefone = TextField(null=True)
tipo_certificado = TextField(null=True)
tipo_emissao = TextField(null=True)
tipo_pessoa = TextField(constraints=[SQL("DEFAULT 'Juridica'")], null=True)
uf = TextField()
class Meta:
table_name = 'empresa'
#-------------------------------------------------------------------------------------------------------------------
data_empresa = []
def ler_xml(_file):
xml_empresa = {}
# Seleciona os dados do arquivo
handle = open(_file,"r")
content = handle.read()
d = xmltodict.parse(content)
try:
xml_empresa['cnpj'] = d['nfeProc']['NFe']['infNFe']['emit']['CNPJ']
if len(d['nfeProc']['NFe']['infNFe']['emit']['CNPJ']) > 11:
xml_empresa['tipo_pessoa'] = 'Juridica'
else:
xml_empresa['tipo_pessoa'] = 'Fisica'
xml_empresa['nome'] = d['nfeProc']['NFe']['infNFe']['emit']['xNome']
xml_empresa['uf'] = d['nfeProc']['NFe']['infNFe']['emit']['enderEmit']['UF']
xml_empresa['diretorio_logo'] = ''
xml_empresa['danfe_contigencia'] = 0
xml_empresa['produtor_cana'] = 0
xml_empresa['aproveitamento_icms'] = 0
xml_empresa['mensagem_simples'] = 'DOCUMENTO EMITIDO POR ME OU EPP OPTANTE PELO SIMPLES NACIONAL.NÃO GERA DIREITO A CRÉDITO FISCALDE IPI.'
xml_empresa['mensagem_simples_sublimite'] = ''
xml_empresa['mensagem_regime_normal'] = ''
xml_empresa['mensagem_generica_nfce'] = ''
xml_empresa['emite_tef'] = 0
xml_empresa['emite_nfce'] = 0
xml_empresa['emite_mdfe'] = 0
xml_empresa['codigo_seguranca_contribuinte'] = ''
xml_empresa['identificacao_codigo_seguranca_contribuinte'] = ''
xml_empresa['tipo_certificado'] = 'A1'
xml_empresa['serial_certificado'] = ''
xml_empresa['descricao_certificado'] = ''
xml_empresa['tipo_emissao'] = 'ContingenciaFSIA'
xml_empresa['ambiente_nfe'] = 'Produção'
xml_empresa['ambiente_mdfe'] = 0
xml_empresa['ambiente_nfce'] = 0
xml_empresa['ambiente_nfse'] = 0
xml_empresa['data_exclusao'] = None
xml_empresa['nome_fantasia'] = d['nfeProc']['NFe']['infNFe']['emit']['xNome']
xml_empresa['cnae_fiscal'] = ''
xml_empresa['inscricao_estadual'] = d['nfeProc']['NFe']['infNFe']['emit']['IE']
xml_empresa['inscricao_estadual_substituto_tributario'] = None
xml_empresa['inscricao_municipal'] = None
xml_empresa['regime_tributario'] = 'SimplesNacional'
xml_empresa['logradouro'] = d['nfeProc']['NFe']['infNFe']['emit']['enderEmit']['xLgr']
xml_empresa['numero'] = d['nfeProc']['NFe']['infNFe']['emit']['enderEmit']['nro']
xml_empresa['complemento'] = None
xml_empresa['bairro'] = d['nfeProc']['NFe']['infNFe']['emit']['enderEmit']['xBairro']
xml_empresa['municipio'] = d['nfeProc']['NFe']['infNFe']['emit']['enderEmit']['xMun']
xml_empresa['pais'] = None
xml_empresa['telefone'] = '859999999'
xml_empresa['email'] = 'sem@email.com.br'
xml_empresa['cep'] = d['nfeProc']['NFe']['infNFe']['emit']['enderEmit']['CEP']
xml_empresa['fonte_tributos_nfe'] = None
xml_empresa['site'] = None
xml_empresa['email_adicional_envio_nota'] = 'nfstock@alterdata.com.br'
xml_empresa['empresa_master'] = None
xml_empresa['status_produto_subempresa'] = None
xml_empresa['data_ultima_sincronizacao'] = None
xml_empresa['empresa_contabilidade'] = 0
#--------------------------------------------------------------------------
# Verifica se existe um emitente cadastrado na tabela, caso verdade ele passa.
exists_c = sum(emitente.get('cnpj') == xml_empresa['cnpj'] for emitente in data_empresa)
if not exists_c:
data_empresa.append(xml_empresa)
try:
res = Empresa.insert_many(xml_empresa).execute()
except IntegrityError:
print('Já existe')
xml_empresa = {}
except:
pass
import json
#print(len(data_empresa),json.dumps(data_empresa[0]['nome'], indent=4))
#--------------------------------------------------------------------------
# Identifica os arquivos xml
os.chdir("/home/elias/Área de Trabalho/notas_emissor/")
for file in glob.glob("*.xml"):
ler_xml(file)
#nrows = Empresa.delete().where(Empresa.cnpj == '42696844372').execute()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment