def __init__(self, inicialDate, finalDate, payments=[], extracts=[]): self._payments = payments self._extracts = extracts self._paymentsWithFilter = [] self._extractsWithFilter = [] self._inicialDate = funcoesUteis.retornaCampoComoData(inicialDate) self._finalDate = funcoesUteis.retornaCampoComoData(finalDate)
def returnCompetenceStartEnd(companie, filterMonthStart, filterYearStart, filterMonthEnd, filterYearEnd): dcad_emp = funcoesUteis.retornaCampoComoData( funcoesUteis.returnDataFieldInDict(companie, ['dcad_emp']), 2) dina_emp = funcoesUteis.retornaCampoComoData( funcoesUteis.returnDataFieldInDict(companie, ['dina_emp']), 2) if dcad_emp is not None: if dcad_emp.year > filterYearStart: filterYearStart = dcad_emp.year if dcad_emp.month > filterMonthStart: filterMonthStart = dcad_emp.month if dina_emp is not None: if dina_emp.year < filterYearEnd: filterYearEnd = dina_emp.year if dina_emp.month < filterMonthEnd: filterMonthEnd = dina_emp.month return { "filterMonthStart": filterMonthStart, "filterYearStart": filterYearStart, "filterMonthEnd": filterMonthEnd, "filterYearEnd": filterYearEnd }
def __init__(self): self._startDate = retornaCampoComoData( input('Informe o data inicial (dd/mm/aaaa): ') ) #retornaCampoComoData('01/01/2019') self._endDate = retornaCampoComoData( input('Informe o data final (dd/mm/aaaa): ')) processCompetences = ProcessCompetences(self._startDate, self._endDate) processCompetences.process()
def noteIsAnAsset(self, notesProducts, notes): with open(notesProducts) as products: data = json.load(products) for product in data: if str(product['cfop_mep']) in ('1556', '2556', '1407', '2407'): for nameProduct in self._namesProductsBase: nameProduct = removerAcentosECaracteresEspeciais( nameProduct[0]).upper() nameProductSystem = removerAcentosECaracteresEspeciais( product['desc_pdi']).upper() if nameProductSystem.find(nameProduct) > 0: dataEmp = self.returnDataEmp(product['codi_emp']) dataNote = self.returnDataNote( notes, product['codi_emp'], product['codi_ent']) dateEntrada = transformaCampoDataParaFormatoBrasileiro( retornaCampoComoData(dataNote['dent_ent'], 2)) dateEmissao = transformaCampoDataParaFormatoBrasileiro( retornaCampoComoData(dataNote['ddoc_ent'], 2)) print( f"- Processando empresa {product['codi_emp']} - {dataEmp['name_emp']}" ) self._exportNotas.write( f"{product['codi_emp']};" f"{dataEmp['name_emp']};" f"'{dataEmp['cnpj_emp']};" f"{dataNote['codi_ent']};" f"{dataNote['nume_ent']};" f"{dataNote['codi_for']};" f"{dataNote['nome_for']};" f"{dateEmissao};" f"{dateEntrada};" f"{dataNote['codi_esp']};" f"{dataNote['seri_ent']};" f"{dataNote['codi_acu']};" f"{dataNote['vcon_ent']};" f"{str(product['codi_pdi']).strip()};" f"{product['desc_pdi']};" f"{product['cfop_mep']};" f"{product['qtde_mep']};" f"{product['valor_unit_mep']};" f"{product['vlor_mep']};" f"{product['bicms_mep']};" f"{product['aliicms_mep']};" f"{product['valor_icms_mep']};" f"{product['bicmsst_mep']};" f"{product['valor_subtri_mep']};" f"\n")
def readNFeCanceled(self): keyNF = funcoesUteis.returnDataFieldInDict( self._dataXml, ['procEventoNFe', 'evento', 'infEvento', 'chNFe']) numberNF = int(keyNF[25:33]) issueDateNF = funcoesUteis.transformDateFieldToString( funcoesUteis.retornaCampoComoData( f'01/{keyNF[4:6]}/20{keyNF[2:4]}')) modelNF = keyNF[20:22] serieNF = keyNF[22:25] cnpjIssuer = keyNF[6:20] typeNF = keyNF[34] return { "numberNF": numberNF, "serieNF": serieNF, "modelNF": modelNF, "typeNF": typeNF, "issueDateNF": issueDateNF, "cnpjIssuer": cnpjIssuer, "keyNF": keyNF, "statusNF": 1 # cancelada }
def __init__(self): self._wayToRead = input( '- Informe o caminho onde estão os XMLs que deseja ler: ').replace( '\\', '/').replace('"', '') self._wayToSave = input( '- Agora informe o caminho onde deseja salvar o arquivo CSV: ' ).replace('\\', '/').replace('"', '') self._filterDate = input( '- A partir de qual data deseja organizar estes XMLs (dd/mm/aaaa): ' ) # self._wayToRead = "C:\\notas_fiscais\\modelo_55".replace('\\', '/').replace('"', '') # self._wayToSave = "C:\\notas_fiscais\\modelo_55".replace('\\', '/').replace('"', '') # self._filterDate = "01/01/2020" self._filtersFolder = '2020,Saidas,NF-e'.split(',') self._filterDate = funcoesUteis.retornaCampoComoData(self._filterDate) self._apiRest = ApiRest('extract_companies') self._companies = self._apiRest.get() self._outputfile = open(os.path.join(self._wayToSave, 'notas_refnfe.csv'), 'w', encoding='utf-8') self._outputfile.write( 'Codigo Empresa;Numero Nota;Data Nota;Tipo Emissao;Modelo;Serie;Valor;Valor ICMS;CNPJ Emitente;Nome Emitente;' 'CNPJ Destinatario;Nome Destinatario;Chave Atual;Chave Referencial\n' )
def __init__(self, codiEmp, finalDate, payments=[]): self._codiEmp = codiEmp self._finalDate = funcoesUteis.retornaCampoComoData(finalDate) self._payments = payments self._providers = readJson( os.path.join( fileDir, f'{folderExtractDatabaseAccount}/fornecedores/{self._codiEmp}-effornece.json' )) self._installments = readJson( os.path.join( fileDir, f'{folderExtractDatabaseAccount}/entradas_parcelas/{self._codiEmp}-efentradaspar.json' )) self._paymentsFinal = [] self._listWordsNotConsiderInTheName = ['LTDA', 'LTDA.', '-', 'ME', 'ME.', 'EPP', 'EPP.', 'EIRELI', 'EIRELI.', \ 'MEI', 'MEI.', 'EI', 'EI.', 'S.A.', 'SA', 'S.A', 'S/A'] self._listWordsAbbreviatedToChange = { "COM.": "COMERCIO", "PROD.": "PRODUCAO", "IND.": "INDUSTRIA", "IMP.": "IMPORTACAO", "EXP.": "EXPORTACAO", "MAT.": "MATERIAIS", "LIMP.": "LIMPEZA", "SERV.": "SERVICO", "EQUIP.": "EQUIPAMENTOS", "P/": "PARA", "ARTIG.": "ARTIGOS", "DIST.": "DISTRIBUIDORA", "CONST.": "CONSTRUCAO" }
def process(self, xml): callReadXmls = CallReadXmls(xml) nf = callReadXmls.process() if nf is not None: cnpjIssuer = funcoesUteis.analyzeIfFieldIsValid(nf, 'cnpjIssuer') cnpjReceiver = funcoesUteis.analyzeIfFieldIsValid( nf, 'cnpjReceiver') issueDate = funcoesUteis.retornaCampoComoData( funcoesUteis.analyzeIfFieldIsValid(nf, 'issueDateNF'), 2) keyNF = funcoesUteis.analyzeIfFieldIsValid(nf, 'keyNF') if issueDate < self._filterDate: return "" codiEmpIssuer = self.returnDataEmp(cnpjIssuer) codiEmpReceiver = self.returnDataEmp(cnpjReceiver) try: self.copyXmlToFolderCompanieAndCompetence( self._wayToSave, codiEmpIssuer, issueDate, xml, 'Saidas', keyNF) except Exception: pass try: self.copyXmlToFolderCompanieAndCompetence( self._wayToSave, codiEmpReceiver, issueDate, xml, 'Entradas', keyNF) except Exception: pass
def __init__(self, wayToRead, filterDate="01/01/2019"): self._wayToRead = wayToRead self._filterDate = funcoesUteis.retornaCampoComoData(filterDate) self._companies = readJson(os.path.join(wayToSaveFile, 'empresas.json')) self._hourProcessing = datetime.datetime.now() self._client = MongoClient() # conecta num cliente do MongoDB rodando na sua máquina self._db = self._client.baymax self._collection = self._db[f'MeshNote']
def readNFe(self): keyNF = funcoesUteis.returnDataFieldInDict(self._dataXml, ['nfeProc', 'NFe', 'infNFe', '@Id']) keyNF = keyNF[3:] numberNF = funcoesUteis.returnDataFieldInDict(self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'ide', 'nNF']) issueDateNF = funcoesUteis.returnDataFieldInDict(self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'ide', 'dhEmi']) issueDateNF2 = funcoesUteis.returnDataFieldInDict(self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'ide', 'dEmi']) issueDateNF = issueDateNF2 if ( issueDateNF == "" or issueDateNF is None ) else issueDateNF issueDateNF = funcoesUteis.transformDateFieldToString(funcoesUteis.retornaCampoComoData(issueDateNF, 2)) modelNF = funcoesUteis.returnDataFieldInDict(self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'ide', 'mod']) serieNF = funcoesUteis.returnDataFieldInDict(self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'ide', 'serie']) valueNF = funcoesUteis.returnDataFieldInDict(self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'total', 'ICMSTot', 'vNF']) valueICMS = funcoesUteis.returnDataFieldInDict(self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'total', 'ICMSTot', 'vICMS']) nameIssuer = funcoesUteis.justLettersNumbersDots(funcoesUteis.returnDataFieldInDict(self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'emit', 'xNome'])) nameReceiver = funcoesUteis.justLettersNumbersDots(funcoesUteis.returnDataFieldInDict(self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'dest', 'xNome'])) typeNF = funcoesUteis.returnDataFieldInDict(self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'ide', 'tpNF']) cnpjIssuer = funcoesUteis.returnDataFieldInDict(self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'emit', 'CNPJ']) cpfIssuer = funcoesUteis.returnDataFieldInDict(self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'emit', 'CPF']) cnpjIssuer = cpfIssuer if cnpjIssuer == "" else cnpjIssuer cnpjReceiver = funcoesUteis.returnDataFieldInDict(self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'dest', 'CNPJ']) cpfReceiver = funcoesUteis.returnDataFieldInDict(self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'dest', 'CPF']) cnpjReceiver = cpfReceiver if cnpjReceiver == "" else cnpjReceiver if typeNF == "0": # quem emitiu foi quem comprou a nota, então o dest vira o emit (nota própria) cnpjIssuerCorrect = cnpjReceiver nameIssuerCorrect = nameReceiver cnpjReceiverCorrect = cnpjIssuer nameReceiverCorrect = nameIssuer else: cnpjIssuerCorrect = cnpjIssuer nameIssuerCorrect = nameIssuer cnpjReceiverCorrect = cnpjReceiver nameReceiverCorrect = nameReceiver produtos = funcoesUteis.returnDataFieldInDict(self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'det']) return { "numberNF": numberNF, "serieNF": serieNF, "modelNF": modelNF, "typeNF": typeNF, "issueDateNF": issueDateNF, "valueNF": valueNF, "valueICMS": valueICMS, "nameIssuer": nameIssuerCorrect, "cnpjIssuer": cnpjIssuerCorrect, "nameReceiver": nameReceiverCorrect, "cnpjReceiver": cnpjReceiverCorrect, "keyNF": keyNF, "statusNF": 0, # ativa "produtos": produtos }
def startAndDate(self): last_day_end_date = monthrange(self._year, self._month)[1] self._end_date = f"{self._year}-{self._month:0>2}-{last_day_end_date:0>2}" self._competence = self._end_date[:7] if self._companie['regime_emp'] in (2, 4): self._start_date = f"{self._year}-01-01" else: self._start_date = f"{self._year}-{(self._month-2):0>2}-01" if self._companie['dina_emp'] is not None: dina_emp = retornaCampoComoData(self._companie['dina_emp'][:10], formatoData=2) year_dina_emp = dina_emp.year month_dina_emp = dina_emp.month start_date = retornaCampoComoData(self._start_date, formatoData=2) end_date = retornaCampoComoData(self._end_date, formatoData=2) if start_date <= dina_emp and dina_emp <= end_date: last_day_end_date = monthrange(year_dina_emp, month_dina_emp)[1] self._end_date = f"{year_dina_emp}-{month_dina_emp:0>2}-{last_day_end_date:0>2}"
def saveMongo(self, codiEmp, cgceMatriz, companieMonthsAmountNotes): dateStart = retornaCampoComoData('01/01/2021') dateNow = datetime.today() - relativedelta(months=1) year = dateStart.year startYear = dateStart.year startMonth = dateStart.month endYear = dateNow.year endMonth = dateNow.month while year <= endYear: months = extractFunctions.returnMonthsOfYear(year, startMonth, startYear, endMonth, endYear) print('\t\t - ', end='') for month in months: companieDataToSave = {} monthYearFormated = f'{month:0>2}/{year}' print(f'{monthYearFormated}, ', end='') amountNotaSaida = list(filter(lambda companieMonths: companieMonths['comp'][:10] == f"{year}-{month:0>2}-01" \ and companieMonths['tipo'] == 'SAIDA', companieMonthsAmountNotes)) amountNotaSaida = analyzeIfFieldIsValidMatrix(amountNotaSaida, 1, []) amountNotaEntrada = list(filter(lambda companieMonths: companieMonths['comp'][:10] == f"{year}-{month:0>2}-01" \ and companieMonths['tipo'] == 'ENTRADA', companieMonthsAmountNotes)) amountNotaEntrada = analyzeIfFieldIsValidMatrix(amountNotaEntrada, 1, []) amountNotaServico = list(filter(lambda companieMonths: companieMonths['comp'][:10] == f"{year}-{month:0>2}-01" \ and companieMonths['tipo'] == 'SERVICO', companieMonthsAmountNotes)) amountNotaServico = analyzeIfFieldIsValidMatrix(amountNotaServico, 1, []) companieDataToSave['qtd_notas_saidas_operacao'] = analyzeIfFieldIsValid(amountNotaSaida, 'qtd_notas_operacao', 0) companieDataToSave['qtd_notas_saidas_operacao_dori'] = analyzeIfFieldIsValid(amountNotaSaida, 'qtd_notas_operacao_dori', 0) companieDataToSave['qtd_notas_entradas_operacao'] = analyzeIfFieldIsValid(amountNotaEntrada, 'qtd_notas_operacao', 0) companieDataToSave['qtd_notas_entradas_operacao_dori'] = analyzeIfFieldIsValid(amountNotaEntrada, 'qtd_notas_operacao_dori', 0) companieDataToSave['qtd_notas_servicos_operacao'] = analyzeIfFieldIsValid(amountNotaServico, 'qtd_notas_operacao', 0) companieDataToSave['qtd_notas_servicos_operacao_dori'] = analyzeIfFieldIsValid(amountNotaServico, 'qtd_notas_operacao_dori', 0) companieDataToSave['codi_emp'] = codiEmp companieDataToSave['cgce_matriz'] = cgceMatriz companieDataToSave['competence'] = f'{year}-{month:0>2}' self._collection.update_one( { "codi_emp": companieDataToSave['codi_emp'], "competence": companieDataToSave['competence'] }, { "$set": companieDataToSave }, upsert=True ) print('') year += 1
def __init__(self): self._wayToRead = input( '- Informe o caminho onde estão os XMLs que deseja organizar: ') self._wayToSave = input( '- Agora informe o caminho onde deseja salvar os XMLs organizados: ' ) self._filterDate = input( '- A partir de qual data deseja organizar estes XMLs (dd/mm/aaaa): ' ) self._filterDate = funcoesUteis.retornaCampoComoData(self._filterDate) self._companies = readJson(os.path.join(wayToSaveFile, 'empresas.json'))
def __init__(self): self._wayToRead = input( '- Informe o caminho onde estão os XMLs que deseja organizar: ' ).replace('\\', '/').replace('"', '') self._wayToSave = input( '- Agora informe o caminho onde deseja salvar os XMLs organizados: ' ).replace('\\', '/').replace('"', '') self._filterDate = input( '- A partir de qual data deseja organizar estes XMLs (dd/mm/aaaa): ' ) # self._wayToRead = "C:\\notas_fiscais\\goiania\\teste".replace('\\', '/').replace('"', '') # self._wayToSave = "C:\\notas_fiscais".replace('\\', '/').replace('"', '') # self._filterDate = "01/01/2020" self._filterDate = funcoesUteis.retornaCampoComoData(self._filterDate) self._apiRest = ApiRest('extract_companies') self._companies = self._apiRest.get()
def process(self, file): dataFile = leTxt(file) self.processAccountPlan(dataFile) valuesOfLine = {} valuesOfFile = [] for key, data in enumerate(dataFile): try: recordType = data[0:2] dateLivro = funcoesUteis.retornaCampoComoData(data[3:11], 4) account = data[11:19] nameAccount = funcoesUteis.analyzeIfFieldIsValid(self._accountPlan, account)[0] historic = funcoesUteis.treatTextField(data[19:274]) amount = funcoesUteis.treatDecimalField(f'{data[274:285]},{data[285:287]}') note = self.searchIfANote(historic) if note != "": documentType = 1 else: documentType = 2 if account[0] == "1": movementType = 'Receitas' else: movementType = 'Despesas' if recordType == "03": valuesOfLine = { 'dateLivro': dateLivro, 'movementType':movementType, 'account': account, 'nameAccount': nameAccount, 'amount': amount, 'document': note, 'documentType': documentType, 'historic': historic } valuesOfFile.append(valuesOfLine.copy()) except Exception as e: pass return valuesOfFile
def readNFe(self): nfs = [] nfsXml = funcoesUteis.returnDataFieldInDict(self._dataXml, ['geral', 'GerarNfseResposta']) if type(nfsXml) is not list: nfs.append(nfsXml) else: nfs = nfsXml for nf in nfs: nfsConvertToXml = OrderedDict() nfsConvertToXml['GerarNfseResposta'] = nf nfsConvertToXml = xmldict.unparse(nfsConvertToXml) nfsConvertToXml = funcoesUteis.removerAcentosECaracteresEspeciais(nfsConvertToXml) objNF = {} objNF['numberNF'] = funcoesUteis.returnDataFieldInDict(nf, ['ListaNfse', 'CompNfse', 'Nfse', 'InfNfse', 'Numero']) objNF['keyNF'] = funcoesUteis.returnDataFieldInDict(nf, ['ListaNfse', 'CompNfse', 'Nfse', 'InfNfse', 'CodigoVerificacao']) objNF['keyNF'] = f"{objNF['numberNF']}-{objNF['keyNF']}" objNF['issueDateNF'] = funcoesUteis.returnDataFieldInDict(nf, ['ListaNfse', 'CompNfse', 'Nfse', 'InfNfse', 'DataEmissao']) objNF['issueDateNF'] = funcoesUteis.retornaCampoComoData(objNF['issueDateNF'], 2) objNF['valueNF'] = funcoesUteis.returnDataFieldInDict(nf, ['ListaNfse', 'CompNfse', 'Nfse', 'InfNfse', 'DeclaracaoPrestacaoServico', 'InfDeclaracaoPrestacaoServico', 'Servico', 'Valores', 'ValorServicos']) objNF['cnpjIssuer'] = funcoesUteis.returnDataFieldInDict(nf, ['ListaNfse', 'CompNfse', 'Nfse', 'InfNfse', 'DeclaracaoPrestacaoServico', 'InfDeclaracaoPrestacaoServico', 'Prestador', 'CpfCnpj', 'Cnpj']) objNF['cpfIssuer'] = funcoesUteis.returnDataFieldInDict(nf, ['ListaNfse', 'CompNfse', 'Nfse', 'InfNfse', 'DeclaracaoPrestacaoServico', 'InfDeclaracaoPrestacaoServico', 'Prestador', 'CpfCnpj', 'Cpf']) objNF['cgceIssuer'] = objNF['cpfIssuer'] if objNF['cnpjIssuer'] == "" else objNF['cnpjIssuer'] objNF['cnpjReceiver'] = funcoesUteis.returnDataFieldInDict(nf, ['ListaNfse', 'CompNfse', 'Nfse', 'InfNfse', 'DeclaracaoPrestacaoServico', 'InfDeclaracaoPrestacaoServico', 'Tomador', 'IdentificacaoTomador', 'CpfCnpj', 'Cnpj']) objNF['cpfReceiver'] = funcoesUteis.returnDataFieldInDict(nf, ['ListaNfse', 'CompNfse', 'Nfse', 'InfNfse', 'DeclaracaoPrestacaoServico', 'InfDeclaracaoPrestacaoServico', 'Tomador', 'IdentificacaoTomador', 'CpfCnpj', 'Cpf']) objNF['cgceReceiver'] = objNF['cpfReceiver'] if objNF['cnpjReceiver'] == "" else objNF['cnpjReceiver'] objNF['statusNF'] = funcoesUteis.returnDataFieldInDict(nf, ['ListaMensagemRetorno', 'MensagemRetorno', 'Mensagem']) objNF['modelNF'] = 'NFS-e' objNF['xml'] = nfsConvertToXml self._nfs.append(objNF) return self._nfs
def __init__(self, filterDate="01/01/2019"): self._wayToReadXMLs = input( '- Informe a pasta onde estão os XMLs que servirão como base na comparação: ' ) self._wayToRead = [ os.path.join(wayToSaveFile, 'entradas_produtos'), os.path.join(wayToSaveFile, 'saidas_produtos') ] self._filterDate = funcoesUteis.retornaCampoComoData(filterDate) self._companies = readJson(os.path.join(wayToSaveFile, 'empresas.json')) self._hourProcessing = datetime.datetime.now() self._client = MongoClient( ) # conecta num cliente do MongoDB rodando na sua máquina self._db = self._client.baymax self._collection = self._db[ f'ProductComparationBetweenAccountSystemAndXML']
def process(self, xml): callReadXmls = CallReadXmls(xml) nf = callReadXmls.process() if nf is None: return "" cnpjIssuer = funcoesUteis.analyzeIfFieldIsValid(nf, 'cnpjIssuer') cnpjReceiver = funcoesUteis.analyzeIfFieldIsValid(nf, 'cnpjReceiver') issueDate = funcoesUteis.retornaCampoComoData( funcoesUteis.analyzeIfFieldIsValid(nf, 'issueDateNF'), 2) keyNF = funcoesUteis.analyzeIfFieldIsValid(nf, 'keyNF') monthIssueDateNF = issueDate.month yearIssueDateNF = issueDate.year codiEmpIssuer = self.returnDataEmp(cnpjIssuer) codiEmpReceiver = self.returnDataEmp(cnpjReceiver) outputNoteDominio = None entryNoteDominio = None if codiEmpIssuer is not None: outputNoteDominio = self.returnDataOutputNoteDominio( codiEmpIssuer, monthIssueDateNF, yearIssueDateNF, keyNF) if codiEmpReceiver is not None: entryNoteDominio = self.returnDataEntryNoteDominio( codiEmpReceiver, monthIssueDateNF, yearIssueDateNF, keyNF) dataProcessNF = { "codiEmpIssuer": codiEmpIssuer, "codiEmpReceiver": codiEmpReceiver, "keyNF": keyNF, "nfXml": nf, "nfEntryNoteDominio": entryNoteDominio, "nfOutputNoteDominio": outputNoteDominio, "wayXml": xml.replace('\\', '/') } self.saveResultProcessEntryNote(dataProcessNF) self.saveResultProcessOutputNote(dataProcessNF)
def process(self, jsonNF): nf = '' productsXML = [] typeNF = '' noteHasProducts = False products = readJson(jsonNF) if len(products) == 0: return "" for key, product in enumerate(products): codi_emp = product['codi_emp'] cgce_emp = self.returnDataEmp(codi_emp) # ignora empresas inativas if cgce_emp is None: continue keyNF = product['chave_nfe'] # ignora notas que não são NF-e if keyNF == "" or keyNF is None: continue emissao = product['emissao'] emissao = funcoesUteis.retornaCampoComoData(emissao, 2) month = emissao.month year = emissao.year previousProduct = funcoesUteis.analyzeIfFieldIsValidMatrix( products, key - 1) previousKeyNF = funcoesUteis.analyzeIfFieldIsValid( previousProduct, 'chave_nfe') # busca os dados das notas de entradas if jsonNF.find('entradas_produtos') >= 0: typeNF = 'Entradas' if jsonNF.find('saidas_produtos') >= 0: typeNF = 'Saidas' if keyNF != previousKeyNF or len(products) == 1: wayXml = os.path.join(self._wayToReadXMLs, f'{codi_emp} -', f'{str(year)}-{month:0>2}', f'{typeNF}', f'{keyNF}.xml') callReadXmls = CallReadXmls(wayXml) nf = callReadXmls.process() productsXML = funcoesUteis.analyzeIfFieldIsValid( nf, 'produtos') noteHasProducts = False if len(productsXML) == 0 else True # quando existe apenas um produto no XML ele não cria um array de produtos, e sim apenas um objeto. Todavia, pra função de # comparação funcionar preciso que seja um array. As linhas abaixo fazem esta análise e cria o array quando necessário productsWhenExistOneProductXML = [] onlyProductInXML = funcoesUteis.analyzeIfFieldIsValid( productsXML, 'prod', False) if onlyProductInXML is not False: productsWhenExistOneProductXML.append(productsXML) productsXML = productsWhenExistOneProductXML productXML = self.returnProductComparation(product, productsXML) if productXML is not None: valueComparationBetweenAccountSystemAndXML = productXML[ 'valueComparationBetweenAccountSystemAndXML'] # deleta o campo pois pra remover o productXML do arrays de products as informações tem que ser idênticas del productXML['valueComparationBetweenAccountSystemAndXML'] # remove o produto pra ele não processar 2 vezes dizendo como seria de outro produto productsXML.remove(productXML) else: valueComparationBetweenAccountSystemAndXML = 0 if valueComparationBetweenAccountSystemAndXML <= 0.3 and noteHasProducts is True: dataProcess = { "codiEmp": codi_emp, "keyNF": keyNF, "typeNF": typeNF[:3].upper(), "productDominio": product, "productXML": productXML, "valueComparationBetweenAccountSystemAndXML": valueComparationBetweenAccountSystemAndXML } self.saveResultProcess(dataProcess)
def sheetProducts(self): sheet = self._workbook.add_worksheet('Products') sheet.freeze_panes(1, 0) sheet.set_column(10, 12, options={ 'hidden': True }) # qtd, valor unitário e valor total domínio sheet.set_column(15, 17, options={'hidden': True }) # qtd, valor unitário e valor total xml sheet.write(0, 0, "Código Empresa", self._cell_format_header) sheet.write(0, 1, "Código Nota", self._cell_format_header) sheet.write(0, 2, "Número", self._cell_format_header) sheet.write(0, 3, "Tipo Nota", self._cell_format_header) sheet.write(0, 4, "Cliente/Fornecedor", self._cell_format_header) sheet.write(0, 5, "Emissão", self._cell_format_header) sheet.write(0, 6, "Entrada/Saída", self._cell_format_header) sheet.write(0, 7, "Código Produto Domínio", self._cell_format_header) sheet.write(0, 8, "Descrição", self._cell_format_header) sheet.write(0, 9, "CFOP", self._cell_format_header) sheet.write(0, 10, "Quantidade", self._cell_format_header) sheet.write(0, 11, "Valor Unitário", self._cell_format_header) sheet.write(0, 12, "Valor Total", self._cell_format_header) sheet.write(0, 13, "Código Produto XML", self._cell_format_header) sheet.write(0, 14, "Descrição", self._cell_format_header) sheet.write(0, 15, "Quantidade", self._cell_format_header) sheet.write(0, 16, "Valor Unitário", self._cell_format_header) sheet.write(0, 17, "Valor Total", self._cell_format_header) sheet.write(0, 18, "Comparação", self._cell_format_header) sheet.write(0, 19, "Chave Nota", self._cell_format_header) productsAccountSystemXXML = self._collection.find() for key, productAccountSystemXXML in enumerate( productsAccountSystemXXML): row = key + 1 print(f' - Processando {row}') codiEmp = funcoesUteis.analyzeIfFieldIsValid( productAccountSystemXXML, "codiEmp") codiNote = funcoesUteis.returnDataFieldInDict( productAccountSystemXXML, ["productDominio", "codigo_nota"]) numberNote = funcoesUteis.returnDataFieldInDict( productAccountSystemXXML, ["productDominio", "numero"]) typeNF = funcoesUteis.analyzeIfFieldIsValid( productAccountSystemXXML, "typeNF") cliFor = funcoesUteis.returnDataFieldInDict( productAccountSystemXXML, ["productDominio", "cli_for"]) issueDate = funcoesUteis.retornaCampoComoData( funcoesUteis.returnDataFieldInDict( productAccountSystemXXML, ["productDominio", "emissao"]), 2) saidaEntradaDate = funcoesUteis.retornaCampoComoData( funcoesUteis.returnDataFieldInDict( productAccountSystemXXML, ["productDominio", "saida_entrada"]), 2) codeProductAccountSystem = funcoesUteis.returnDataFieldInDict( productAccountSystemXXML, ["productDominio", "codi_pdi"]).strip() nameProductAccountSystem = funcoesUteis.treatTextField( funcoesUteis.returnDataFieldInDict( productAccountSystemXXML, ["productDominio", "desc_pdi"])) cfopProductAccountSystem = funcoesUteis.returnDataFieldInDict( productAccountSystemXXML, ["productDominio", "cfop"]) qtdProductAccountSystem = funcoesUteis.treatDecimalField( funcoesUteis.returnDataFieldInDict(productAccountSystemXXML, ["productDominio", "qtd"])) vunitProductAccountSystem = funcoesUteis.treatDecimalField( funcoesUteis.returnDataFieldInDict( productAccountSystemXXML, ["productDominio", "vunit"])) vtotProductAccountSystem = funcoesUteis.treatDecimalField( funcoesUteis.returnDataFieldInDict(productAccountSystemXXML, ["productDominio", "vtot"])) codeProductXML = funcoesUteis.returnDataFieldInDict( productAccountSystemXXML, ["productXML", "prod", "cProd"]).strip() nameProductXML = funcoesUteis.treatTextField( funcoesUteis.returnDataFieldInDict( productAccountSystemXXML, ["productXML", "prod", "xProd"])) qtdProductXML = funcoesUteis.treatDecimalField( funcoesUteis.returnDataFieldInDict( productAccountSystemXXML, ["productXML", "prod", "qCom"])) vunitProductXML = funcoesUteis.treatDecimalField( funcoesUteis.returnDataFieldInDict( productAccountSystemXXML, ["productXML", "prod", "vUnCom"])) vtotProductXML = funcoesUteis.treatDecimalField( funcoesUteis.returnDataFieldInDict( productAccountSystemXXML, ["productXML", "prod", "vProd"])) valueComparationBetweenAccountSystemAndXML = funcoesUteis.treatDecimalField( funcoesUteis.returnDataFieldInDict( productAccountSystemXXML, ["valueComparationBetweenAccountSystemAndXML"])) keyNF = funcoesUteis.returnDataFieldInDict( productAccountSystemXXML, ["productDominio", "chave_nfe"]) sheet.write(row, 0, codiEmp) sheet.write(row, 1, codiNote) sheet.write(row, 2, numberNote) sheet.write(row, 3, typeNF) sheet.write(row, 4, cliFor) sheet.write(row, 5, issueDate, self._cell_format_date) sheet.write(row, 6, saidaEntradaDate, self._cell_format_date) sheet.write(row, 7, codeProductAccountSystem) sheet.write(row, 8, nameProductAccountSystem) sheet.write(row, 9, cfopProductAccountSystem) sheet.write(row, 10, qtdProductAccountSystem, self._cell_format_money) sheet.write(row, 11, vunitProductAccountSystem, self._cell_format_money) sheet.write(row, 12, vtotProductAccountSystem, self._cell_format_money) sheet.write(row, 13, codeProductXML) sheet.write(row, 14, nameProductXML) sheet.write(row, 15, qtdProductXML, self._cell_format_money) sheet.write(row, 16, vunitProductXML, self._cell_format_money) sheet.write(row, 17, vtotProductXML, self._cell_format_money) sheet.write(row, 18, valueComparationBetweenAccountSystemAndXML, self._cell_format_money) sheet.write(row, 19, keyNF)
def process(self): valuesOfLine = {} isPagamento = False nameProvider = "" historic = "" amountPaid = float(0) account = "" amountOriginal = float(0) amountDiscount = float(0) amountInterest = float(0) amountFine = float(0) paymentDate = None dueDate = None for data in self._dataFile: if isPagamento == False and data.find( 'COMPROVANTE DE PAGAMENTO') >= 0: isPagamento = True data = str(data) dataSplit = data.split(':') fieldOne = funcoesUteis.treatTextField( funcoesUteis.analyzeIfFieldIsValidMatrix(dataSplit, 1)) fieldTwo = funcoesUteis.treatTextField( funcoesUteis.analyzeIfFieldIsValidMatrix(dataSplit, 2)) fieldThree = funcoesUteis.treatTextField( funcoesUteis.analyzeIfFieldIsValidMatrix(dataSplit, 3)) if fieldOne.count('DO DOCUMENTO') > 0 and fieldTwo.count( "DATA") > 0: paymentDate = funcoesUteis.retornaCampoComoData(fieldThree) if fieldOne == 'CONTA': account = str( funcoesUteis.treatNumberField(fieldTwo, isInt=True)) if fieldOne.count('BENEFICIARIO') > 0: self._accountDebitOrCredit = 'DEBIT' elif fieldOne.count('PAGADOR') > 0: self._accountDebitOrCredit = 'CREDIT' elif fieldOne.count('SACADOR') > 0: self._accountDebitOrCredit = '' if self._accountDebitOrCredit == 'DEBIT': if fieldOne == 'RAZAO SOCIAL': nameProvider = fieldTwo if fieldOne == 'CNPJ/CPF': cgceProvider = fieldTwo elif self._accountDebitOrCredit == 'CREDIT': if fieldOne == "DATA DO PAGAMENTO": paymentDate = funcoesUteis.retornaCampoComoData(fieldTwo) if fieldOne == "DATA DE VENCIMENTO": dueDate = funcoesUteis.retornaCampoComoData(fieldTwo) if fieldOne == "VALOR NOMINAL": amountOriginal = funcoesUteis.treatDecimalField(fieldTwo) if fieldOne == 'ENCARGOS': amountInterest = funcoesUteis.treatDecimalField(fieldTwo) if fieldOne == "VALOR PAGO": amountPaid = funcoesUteis.treatDecimalField(fieldTwo) if fieldOne == "DESCONTO": amountDiscount = funcoesUteis.treatDecimalField(fieldTwo) if fieldOne == "VALOR PAGO": if paymentDate is not None and amountPaid > 0 and isPagamento is True: valuesOfLine = { "paymentDate": paymentDate, "nameProvider": nameProvider, "cgceProvider": cgceProvider, "dueDate": dueDate, "bank": 'AMAZONIA', "account": account, "amountPaid": round(amountPaid, 2), "amountInterest": round(amountInterest, 2), "amountDiscount": round(amountDiscount, 2), "amountFine": round(amountFine, 2), "amountOriginal": round(amountOriginal, 2), "historic": historic, "category": 'PAGAMENTO', "cgcePaying": "", "foundProof": True, "amountPaidPerLote": round(amountPaid, 2), "wayFile": self._file } return valuesOfLine.copy()
def returnDataInstallmentsEntryNote(self, dueDate=None, note=0, cgceProvider=None, ddoc_ent=None, dent_ent=None, amountPayment=0.0, amountOriginal=0.0): if dueDate is None: return None # se a data de vencimento for nula já nem processa o resto if note == "" or note is None: note = 0 if cgceProvider == "": cgceProvider = None if ddoc_ent == "": ddoc_ent = None if dent_ent == "": dent_ent = None # se o vencimento for nulo já nem percorre os dados if dueDate is None: return None for installment in self._installments: provider = self.returnDataProvider(installment["codi_for"]) dueDateEntryNote = funcoesUteis.transformaCampoDataParaFormatoBrasileiro( \ funcoesUteis.retornaCampoComoData(funcoesUteis.analyzeIfFieldIsValid(installment, "vcto_entp"), 2) ) cgceProviderEntryNote = funcoesUteis.analyzeIfFieldIsValid( provider, "cgce_for", None) noteEntryNote = int( funcoesUteis.analyzeIfFieldIsValid(installment, "nume_ent", 0)) issueEntryNote = funcoesUteis.transformaCampoDataParaFormatoBrasileiro( \ funcoesUteis.retornaCampoComoData(funcoesUteis.analyzeIfFieldIsValid(installment, "ddoc_ent"), 2) ) entryEntryNote = funcoesUteis.transformaCampoDataParaFormatoBrasileiro( \ funcoesUteis.retornaCampoComoData(funcoesUteis.analyzeIfFieldIsValid(installment, "dent_ent"), 2) ) amountInstallmentEntryNote = float( funcoesUteis.analyzeIfFieldIsValid(installment, "vlor_entp", 0.0)) # o int é pra poder tirar o .0 de quando é exportado os dados note = funcoesUteis.treatNumberField(note, True) if note != 0: # se a nota for válida compara os dados com ela, uma comparação no mínimo tem que ser igual, pq a se a nota tá preenchida ela tem que existir na domínio (mesmo número) if dueDateEntryNote == dueDate and noteEntryNote == note: return installment else: if dueDateEntryNote == dueDate and cgceProviderEntryNote == cgceProvider: return installment if dueDateEntryNote == dueDate and issueEntryNote == ddoc_ent and ddoc_ent is not None: return installment if dueDateEntryNote == dueDate and entryEntryNote == dent_ent and dent_ent is not None: return installment if dueDateEntryNote == dueDate and amountInstallmentEntryNote == amountOriginal and amountOriginal > 0: return installment if dueDateEntryNote == dueDate and amountInstallmentEntryNote == amountPayment and amountPayment > 0: return installment
def sheetPayments(self, payments): sheet = self._workbook.add_worksheet('Pagamentos') sheet.freeze_panes(1, 0) sheet.set_column(3, 3, options={'hidden': True}) # parcela sheet.set_column(5, 5, options={'hidden': True}) # cnpj fornecedor sheet.set_column(8, 8, options={'hidden': True}) # comprovante pagto sheet.set_column(10, 10, options={'hidden': True}) # data extrato sheet.set_column(12, 12, options={'hidden': True}) # data vencimento sheet.set_column(13, 13, options={'hidden': True}) # data emissão sheet.write(0, 0, "Lote", self._cell_format_header) sheet.write(0, 1, "Documento", self._cell_format_header) sheet.write(0, 2, "NF na Domínio?", self._cell_format_header) sheet.write(0, 3, "Parcela", self._cell_format_header) # hidden sheet.write(0, 4, "Fornecedor", self._cell_format_header) sheet.write(0, 5, "CNPJ Fornecedor", self._cell_format_header) # hidden sheet.write(0, 6, "Banco Financeiro", self._cell_format_header) sheet.write(0, 7, "Banco Extrato", self._cell_format_header) sheet.write(0, 8, "Comprovante Pagto?", self._cell_format_header) sheet.write(0, 9, "Data Financeiro", self._cell_format_header) sheet.write(0, 10, "Data Extrato", self._cell_format_header) sheet.write(0, 11, "Importação Domínio", self._cell_format_header) sheet.write(0, 12, "Vencimento", self._cell_format_header) sheet.write(0, 13, "Emissão", self._cell_format_header) sheet.write(0, 14, "Valor Pago", self._cell_format_header) sheet.write(0, 15, "Desconto", self._cell_format_header) sheet.write(0, 16, "Juros", self._cell_format_header) sheet.write(0, 17, "Multa", self._cell_format_header) sheet.write(0, 18, "Valor Original", self._cell_format_header) sheet.write(0, 19, "Conta Contabil Domínio", self._cell_format_header) sheet.write(0, 20, "Codigo Empresa", self._cell_format_header) sheet.write(0, 21, "Historico Financeiro", self._cell_format_header) sheet.write(0, 22, "Categoria", self._cell_format_header) sheet.write(0, 23, "Plano de Contas", self._cell_format_header) sheet.write(0, 24, "CNPJ Pagador", self._cell_format_header) sheet.write(0, 25, "Historico Extrato Bancário", self._cell_format_header) sheet.write(0, 26, "Conta Contabil Sistema Cliente", self._cell_format_header) sheet.write(0, 27, "Total no Extrato por Banco e Dia", self._cell_format_header_orange) # ordena os payments por data payments = sorted(payments, key=itemgetter('bank', 'account', 'dateOfImport')) for key, payment in enumerate(payments): row = key + 1 row2 = key + 2 numberLote = funcoesUteis.analyzeIfFieldIsValid( payment, "numberLote", 0) numberLote = row if numberLote == 0 else numberLote document = funcoesUteis.analyzeIfFieldIsValid(payment, "document") findNote = funcoesUteis.analyzeIfFieldIsValid(payment, "findNote") parcelNumber = funcoesUteis.analyzeIfFieldIsValid( payment, "parcelNumber") nameProvider = funcoesUteis.analyzeIfFieldIsValid( payment, "nameProvider") cgceProvider = funcoesUteis.analyzeIfFieldIsValid( payment, "cgceProvider") bankAndAccount = f'{funcoesUteis.analyzeIfFieldIsValid(payment, "bank")}-{funcoesUteis.analyzeIfFieldIsValid(payment, "account")}' bankAndAccountExtract = f'{funcoesUteis.analyzeIfFieldIsValid(payment, "bankExtract")}-{funcoesUteis.analyzeIfFieldIsValid(payment, "accountExtract")}' foundProof = funcoesUteis.analyzeIfFieldIsValid( payment, "foundProof") paymentDate = funcoesUteis.analyzeIfFieldIsValid( payment, "paymentDate", None) extractDate = funcoesUteis.analyzeIfFieldIsValid( payment, "dateExtract", None) dateOfImport = funcoesUteis.analyzeIfFieldIsValid( payment, "dateOfImport", None) dueDate = funcoesUteis.retornaCampoComoData( funcoesUteis.analyzeIfFieldIsValid(payment, "dueDate")) issueDate = funcoesUteis.retornaCampoComoData( funcoesUteis.analyzeIfFieldIsValid(payment, "issueDate")) amountPaid = funcoesUteis.analyzeIfFieldIsValid( payment, "amountPaid") amountDiscount = funcoesUteis.analyzeIfFieldIsValid( payment, "amountDiscount", 0.0) amountInterest = funcoesUteis.analyzeIfFieldIsValid( payment, "amountInterest", 0.0) amountFine = funcoesUteis.analyzeIfFieldIsValid( payment, "amountFine", 0.0) amountOriginal = funcoesUteis.analyzeIfFieldIsValid( payment, "amountOriginal", 0.0) accountCode = funcoesUteis.analyzeIfFieldIsValid( payment, "accountCode") codiEmp = funcoesUteis.analyzeIfFieldIsValid( payment, "companyBranch", None) codiEmp = self._codiEmp if codiEmp is None or str( codiEmp).isnumeric() is False else codiEmp historic = funcoesUteis.analyzeIfFieldIsValid(payment, "historic") category = funcoesUteis.analyzeIfFieldIsValid(payment, "category") accountPlan = funcoesUteis.analyzeIfFieldIsValid( payment, "accountPlan") cgcePaying = funcoesUteis.analyzeIfFieldIsValid( payment, "cgcePaying") historicExtract = funcoesUteis.analyzeIfFieldIsValid( payment, "historicExtract") accountCodeOld = funcoesUteis.analyzeIfFieldIsValid( payment, "accountCodeOld") sheet.write(row, 0, numberLote) sheet.write(row, 1, document) sheet.write(row, 2, findNote) sheet.write(row, 3, parcelNumber) sheet.write(row, 4, nameProvider) sheet.write(row, 5, cgceProvider) sheet.write(row, 6, bankAndAccount) sheet.write(row, 7, bankAndAccountExtract) sheet.write(row, 8, foundProof) sheet.write(row, 9, paymentDate, self._cell_format_date) sheet.write(row, 10, extractDate, self._cell_format_date) sheet.write(row, 11, dateOfImport, self._cell_format_date) sheet.write(row, 12, dueDate, self._cell_format_date) sheet.write(row, 13, issueDate, self._cell_format_date) sheet.write(row, 14, amountPaid, self._cell_format_money) sheet.write(row, 15, amountDiscount, self._cell_format_money) sheet.write(row, 16, amountInterest, self._cell_format_money) sheet.write(row, 17, amountFine, self._cell_format_money) sheet.write(row, 18, amountOriginal, self._cell_format_money) sheet.write(row, 19, accountCode) sheet.write(row, 20, codiEmp) sheet.write(row, 21, historic) sheet.write(row, 22, category) sheet.write(row, 23, accountPlan) sheet.write(row, 24, cgcePaying) sheet.write(row, 25, historicExtract) sheet.write(row, 26, accountCodeOld) sheet.write_formula( row, 27, f'=SUMIFS(ExtratosBancarios!D:D,ExtratosBancarios!S:S,G{row2},ExtratosBancarios!A:A,L{row2},ExtratosBancarios!N:N,"-")', self._cell_format_money)
def process(self): valuesOfLine = {} isPagamentoInss = False nameProvider = "" historic = "" amountPaid = float(0) account = "" amountOriginal = float(0) amountDiscount = float(0) amountInterest = float(0) amountFine = float(0) paymentDate = None dueDate = None for data in self._dataFile: if isPagamentoInss == False and data.find( 'COMPROVANTE DE PAGAMENTO') >= 0 and (data.find('INSS') or data.find('DARF')): isPagamentoInss = True data = str(data) dataSplit = data.split(':') fieldOne = funcoesUteis.treatTextField( funcoesUteis.analyzeIfFieldIsValidMatrix(dataSplit, 1)) fieldTwo = funcoesUteis.treatTextField( funcoesUteis.analyzeIfFieldIsValidMatrix(dataSplit, 2)) fieldThree = funcoesUteis.treatTextField( funcoesUteis.analyzeIfFieldIsValidMatrix(dataSplit, 3)) if fieldOne.count('DO DOCUMENTO') > 0 and fieldTwo.count( "DATA") > 0: paymentDate = funcoesUteis.retornaCampoComoData(fieldThree) if fieldOne == 'CONTA': account = str( funcoesUteis.treatNumberField(fieldTwo, isInt=True)) if fieldOne.count('MULTA') > 0 or fieldOne.count('JUROS') > 0: amountInterest = funcoesUteis.treatDecimalField(fieldTwo) if fieldOne == "VALOR TOTAL": amountPaid = funcoesUteis.treatDecimalField(fieldTwo) if fieldOne == 'DESCRICAO': nameProvider = fieldTwo if fieldOne == "DESCRICAO": if paymentDate is not None and amountPaid > 0 and isPagamentoInss is True: valuesOfLine = { "paymentDate": paymentDate, "nameProvider": nameProvider, "cgceProvider": "", "dueDate": dueDate, "bank": 'AMAZONIA', "account": account, "amountPaid": round(amountPaid, 2), "amountInterest": round(amountInterest, 2), "amountDiscount": round(amountDiscount, 2), "amountFine": round(amountFine, 2), "amountOriginal": round(amountOriginal, 2), "historic": historic, "category": 'PAGAMENTO', "cgcePaying": "", "foundProof": True, "amountPaidPerLote": round(amountPaid, 2), "wayFile": self._file } return valuesOfLine.copy()
def process(self): valuesOfLine = {} isProofTransferencia = False nameProvider = "" historic = "" amountPaid = float(0) account = "" for data in self._dataFile: if isProofTransferencia == False and data.find( 'COMPROVANTE DE TRANSFERENCIA') >= 0: isProofTransferencia = True data = str(data) dataSplit = data.split(':') fieldOne = funcoesUteis.treatTextField( funcoesUteis.analyzeIfFieldIsValidMatrix(dataSplit, 1)) fieldTwo = funcoesUteis.treatTextField( funcoesUteis.analyzeIfFieldIsValidMatrix(dataSplit, 2)) if fieldOne.count('IDENTIFICACAO NO EXTRATO') > 0: historic = funcoesUteis.treatTextField(fieldTwo) if fieldOne.count('CONTA DEBITADA') > 0: self._accountDebitOrCredit = 'DEBIT' elif fieldOne.count('CONTA CREDITADA') > 0: self._accountDebitOrCredit = 'CREDIT' if self._accountDebitOrCredit == 'DEBIT': if fieldOne.count('AGENCIA') > 0: account = funcoesUteis.treatTextField( funcoesUteis.analyzeIfFieldIsValidMatrix(dataSplit, 3)) account = str(funcoesUteis.treatNumberField(account)) # account = funcoesUteis.treatTextField(funcoesUteis.analyzeIfFieldIsValidMatrix(account.split('-'), 1)) # if account.find(' ') > 0: # account = funcoesUteis.treatTextField(funcoesUteis.analyzeIfFieldIsValidMatrix(account.split(' '), 1)) elif self._accountDebitOrCredit == 'CREDIT': if fieldOne == "NOME": nameProvider = fieldTwo if fieldOne.count("VALOR") > 0: amountPaid = funcoesUteis.treatDecimalField(fieldTwo) for valueOfLineDatePayment in self._valuesOfLineDatePayment: if data[0:len(valueOfLineDatePayment )] == valueOfLineDatePayment: paymentDate = funcoesUteis.treatTextField( data[len(valueOfLineDatePayment) + 1:len(valueOfLineDatePayment) + 11]) if paymentDate.find('.') >= 0: paymentDate = funcoesUteis.retornaCampoComoData( paymentDate.replace('.', '/')) else: paymentDate = funcoesUteis.retornaCampoComoData( paymentDate) if paymentDate is not None and amountPaid > 0 and isProofTransferencia is True: valuesOfLine = { "paymentDate": paymentDate, "nameProvider": nameProvider, "cgceProvider": '', "dueDate": '', "bank": 'ITAU', "account": account, "amountPaid": round(amountPaid, 2), "historic": historic, "category": 'TRANSFERENCIA', "cgcePaying": '', "foundProof": True, "amountPaidPerLote": round(amountPaid, 2), "wayFile": self._file } return valuesOfLine.copy()
def process(self, file): # se não for desta classe nem segue pra frente if self.isProof(file) is None: return [] funcoesUteis.updateFilesRead(self._wayTempFilesRead, file.replace('.txt', '.pdf'), 'ProofsPaymentsSantander') valuesOfLine = {} valuesOfFile = [] dataFile = leTxt(file, treatAsText=True, removeBlankLines=True) nameProvider = "" historic = "" dueDate = None paymentDate = None company = "" cnpjProvider = "" amountPaid = float(0) amountOriginal = float(0) amountInterest = float(0) category = "" bank = "SANTANDER" account = "" for data in dataFile: data = str(data) dataSplit = data.split(':') fieldOne = funcoesUteis.treatTextField( funcoesUteis.analyzeIfFieldIsValidMatrix(dataSplit, 1)) fieldTwo = funcoesUteis.treatTextField( funcoesUteis.analyzeIfFieldIsValidMatrix(dataSplit, 2)) if data.find('CONTA CORRENTE:') >= 0: account = data[data.find('CONTA CORRENTE:') + 15:] account = funcoesUteis.treatTextField(account) accountSplit = account.split('-') account = f"{funcoesUteis.analyzeIfFieldIsValidMatrix(accountSplit, 1)}{funcoesUteis.analyzeIfFieldIsValidMatrix(accountSplit, 2)}" if data.find('BENEFICIARIO ORIGINAL') >= 0: self._beneficiaryOrPayer = 'BENEFICIARIO' elif data.count('PAGADOR ORIGINAL') > 0: self._beneficiaryOrPayer = 'PAGADOR' if self._beneficiaryOrPayer == 'PAGADOR': pass elif self._beneficiaryOrPayer == 'BENEFICIARIO': if fieldOne == "RAZAO SOCIAL": nameProvider = fieldTwo.replace('RAZAO SOCIAL', '') if fieldOne == "CNPJ": cnpjProvider = fieldTwo.replace('CNPJ', '') if fieldOne == "DATA DE VENCIMENTO": dueDate = funcoesUteis.transformaCampoDataParaFormatoBrasileiro( funcoesUteis.retornaCampoComoData(fieldTwo)) if fieldOne.count("VALOR NOMINAL") > 0: amountOriginal = funcoesUteis.treatDecimalField(fieldTwo) if fieldOne.count("ENCARGOS") > 0: amountInterest = funcoesUteis.treatDecimalField(fieldTwo) if fieldOne.count("TOTAL A COBRAR") > 0: amountPaid = funcoesUteis.treatDecimalField(fieldTwo) if amountInterest > 0: amountOriginal = amountPaid - amountInterest # é necessário fazer pois as vezes tem juros mas o valor nominal tá igual ao valor pago else: amountInterest = amountPaid - amountOriginal # é necessário fazer pois as vezes tem juros, mas não tem o campo encargos if fieldOne == "DATA DA TRANSACAO": paymentDate = funcoesUteis.retornaCampoComoData(fieldTwo) if paymentDate is not None and amountPaid > 0: valuesOfLine = { "paymentDate": paymentDate, "nameProvider": nameProvider, "cnpjProvider": cnpjProvider, "dueDate": dueDate, "bank": bank, "account": account, "amountPaid": amountPaid, "amountDiscount": float(0), "amountInterest": amountInterest, "amountOriginal": amountOriginal, "historic": historic, "category": category, "company": company, "foundProof": True } valuesOfFile.append(valuesOfLine.copy()) paymentDate = None amountPaid = float(0) return valuesOfFile
def process(self): valuesOfLine = {} isProofFileThisClass = False nameProvider = "" cgceProvider = "" historic = "" amountPaid = float(0) account = "" dueDate = None amountOriginal = float(0) amountDiscount = float(0) amountInterest = float(0) paymentDate = None for data in self._dataFile: # if isProofFileThisClass == False and data.find('TIPO DE PAGAMENTO PIX') >= 0: # isProofFileThisClass = True data = str(data) dataSplitTwoPoints = data.split(':') fieldOne = funcoesUteis.treatTextField( funcoesUteis.analyzeIfFieldIsValidMatrix( dataSplitTwoPoints, 1)) fieldTwo = funcoesUteis.treatTextField( funcoesUteis.analyzeIfFieldIsValidMatrix( dataSplitTwoPoints, 2)) if data.find('DADOS DO PAGADOR') >= 0: self._typeLineRead = 'PAGADOR' elif data.find('DADOS DO RECEBEDOR') >= 0: self._typeLineRead = 'RECEBEDOR' elif data.find('DADOS DA TRANSACAO') >= 0: self._typeLineRead = 'TRANSACAO' if self._typeLineRead == 'PAGADOR': if fieldOne.count('AGENCIA/CONTA') > 0: account = funcoesUteis.analyzeIfFieldIsValidMatrix( fieldTwo.split('/'), 2) account = str(funcoesUteis.treatNumberField(account)) if fieldOne.count('CPF / CNPJ') > 0: cgcePaying = fieldTwo elif self._typeLineRead == 'RECEBEDOR': if fieldOne == "NOME DO RECEBEDOR": nameProvider = fieldTwo if fieldOne.count('CPF / CNPJ') > 0: cgceProvider = funcoesUteis.treatNumberField(fieldTwo) elif self._typeLineRead == 'TRANSACAO': if fieldOne == "VALOR": amountPaid = funcoesUteis.treatDecimalField(fieldTwo) if fieldOne.count('DATA DA TRANSF') > 0: paymentDate = funcoesUteis.retornaCampoComoData(fieldTwo) if fieldOne.count('TIPO DE PAGAMENTO') > 0: # print(fieldOne, fieldTwo, paymentDate, amountPaid, isProofFileThisClass) if paymentDate is not None and amountPaid > 0: valuesOfLine = { "paymentDate": paymentDate, "nameProvider": nameProvider, "cgceProvider": cgceProvider, "dueDate": dueDate, "bank": 'ITAU', "account": account, "amountPaid": round(amountPaid, 2), "amountInterest": round(amountInterest, 2), "amountDiscount": round(amountDiscount, 2), "amountOriginal": round(amountOriginal, 2), "historic": historic, "category": 'PIX', "cgcePaying": cgcePaying, "foundProof": True, "amountPaidPerLote": round(amountPaid, 2), "wayFile": self._file } return valuesOfLine.copy()
def readNFe(self): objNF = {} keyNF = funcoesUteis.returnDataFieldInDict( self._dataXml, ['nfeProc', 'NFe', 'infNFe', '@Id']) keyNF = keyNF[3:] objNF['keyNF'] = keyNF numberNF = funcoesUteis.returnDataFieldInDict( self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'ide', 'nNF']) objNF['numberNF'] = numberNF issueDateNF = funcoesUteis.returnDataFieldInDict( self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'ide', 'dhEmi']) issueDateNF2 = funcoesUteis.returnDataFieldInDict( self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'ide', 'dEmi']) issueDateNF = issueDateNF2 if (issueDateNF == "" or issueDateNF is None) else issueDateNF issueDateNF = funcoesUteis.retornaCampoComoData(issueDateNF, 2) objNF['issueDateNF'] = issueDateNF modelNF = funcoesUteis.returnDataFieldInDict( self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'ide', 'mod']) objNF['modelNF'] = modelNF serieNF = funcoesUteis.returnDataFieldInDict( self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'ide', 'serie']) objNF['serieNF'] = serieNF valueNF = funcoesUteis.returnDataFieldInDict( self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'total', 'ICMSTot', 'vNF']) objNF['valueNF'] = valueNF valueICMS = funcoesUteis.returnDataFieldInDict( self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'total', 'ICMSTot', 'vICMS']) objNF['valueICMS'] = valueICMS refNFe = funcoesUteis.returnDataFieldInDict( self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'ide', 'NFref', 'refNFe']) objNF['refNFe'] = refNFe typeNF = funcoesUteis.returnDataFieldInDict( self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'ide', 'tpNF']) objNF['typeNF'] = typeNF nameIssuer = funcoesUteis.justLettersNumbersDots( funcoesUteis.returnDataFieldInDict( self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'emit', 'xNome'])) nameReceiver = funcoesUteis.justLettersNumbersDots( funcoesUteis.returnDataFieldInDict( self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'dest', 'xNome'])) cnpjIssuer = funcoesUteis.returnDataFieldInDict( self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'emit', 'CNPJ']) cpfIssuer = funcoesUteis.returnDataFieldInDict( self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'emit', 'CPF']) cnpjIssuer = cpfIssuer if cnpjIssuer == "" else cnpjIssuer cnpjReceiver = funcoesUteis.returnDataFieldInDict( self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'dest', 'CNPJ']) cpfReceiver = funcoesUteis.returnDataFieldInDict( self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'dest', 'CPF']) cnpjReceiver = cpfReceiver if cnpjReceiver == "" else cnpjReceiver if typeNF == "0": # quem emitiu foi quem comprou a nota, então o dest vira o emit (nota própria) cnpjIssuerCorrect = cnpjReceiver nameIssuerCorrect = nameReceiver cnpjReceiverCorrect = cnpjIssuer nameReceiverCorrect = nameIssuer else: cnpjIssuerCorrect = cnpjIssuer nameIssuerCorrect = nameIssuer cnpjReceiverCorrect = cnpjReceiver nameReceiverCorrect = nameReceiver objNF['cnpjIssuer'] = cnpjIssuerCorrect objNF['nameIssuer'] = nameIssuerCorrect objNF['cnpjReceiver'] = cnpjReceiverCorrect objNF['nameReceiver'] = nameReceiverCorrect # produtos = funcoesUteis.returnDataFieldInDict(self._dataXml, ['nfeProc', 'NFe', 'infNFe', 'det']) # objNF['produtos'] = produtos self._nfs.append(objNF) return self._nfs
def checkMonthsIntegrated(self, companieSettingView, companieMonthsIntegrated): statusAccountPaid = treatTextField( companieSettingView['statusAccountPaid']) isCompanyBranch = treatTextField( companieSettingView['isCompanyBranch']) dateAccountPaid = retornaCampoComoData( analyzeIfFieldIsValid(companieSettingView, 'dateAccountPaid', '01/01/1900')) dateStart = retornaCampoComoData('01/01/2021') dateNow = datetime.today() - relativedelta(months=1) year = dateStart.year startYear = dateStart.year startMonth = dateStart.month endYear = dateNow.year endMonth = dateNow.month while year <= endYear: months = extractFunctions.returnMonthsOfYear( year, startMonth, startYear, endMonth, endYear) print('\t\t - ', end='') for month in months: monthYearFormated = f'{month:0>2}/{year}' competence = retornaCampoComoData(f"01/{monthYearFormated}") print(f'{monthYearFormated}, ', end='') integrated = list( filter( lambda companieMonths: companieMonths['comp'][:10] == f"{year}-{month:0>2}-01", companieMonthsIntegrated)) try: companieSettingView['monthIntegratedMandatory'] = True if dateAccountPaid < competence and \ statusAccountPaid.find('CONCLUIDA') >= 0 and statusAccountPaid.find('ANTIGO') < 0 and \ isCompanyBranch == "NAO" else False except Exception: companieSettingView['monthIntegratedMandatory'] = False if len(integrated) > 0: integrated = integrated[0] companieSettingView[ 'existIntegrated'] = True if integrated[ 'qtd_lan_ti_importado_dlan'] > 0 else False companieSettingView[ 'qtd_lan_ti_importado_dlan'] = analyzeIfFieldIsValid( integrated, 'qtd_lan_ti_importado_dlan', 0) companieSettingView[ 'qtd_lan_ti_importado_dori'] = analyzeIfFieldIsValid( integrated, 'qtd_lan_ti_importado_dori', 0) companieSettingView[ 'qtd_lan_operacao'] = analyzeIfFieldIsValid( integrated, 'qtd_lan_operacao', 0) companieSettingView[ 'qtd_lan_operacao_dori'] = analyzeIfFieldIsValid( integrated, 'qtd_lan_operacao_dori', 0) companieSettingView['cgce_matriz'] = analyzeIfFieldIsValid( integrated, 'cgce_matriz') companieSettingView['competence'] = f'{year}-{month:0>2}' self._collection.update_one( { "codi_emp": companieSettingView['codi_emp'], "competence": companieSettingView['competence'] }, {"$set": companieSettingView}, upsert=True) print('') year += 1
def process(self): valuesOfLine = {} isTransferencia = False nameProvider = "" cgceProvider = '' historic = "" amountPaid = float(0) account = "" amountOriginal = float(0) amountDiscount = float(0) amountInterest = float(0) amountFine = float(0) paymentDate = None for data in self._dataFile: if isTransferencia == False and data.find('COMPROVANTE DE TRANSF') >= 0: isTransferencia = True data = str(data) dataSplit = data.split(':') fieldOne = funcoesUteis.treatTextField(funcoesUteis.analyzeIfFieldIsValidMatrix(dataSplit, 1)) fieldTwo = funcoesUteis.treatTextField(funcoesUteis.analyzeIfFieldIsValidMatrix(dataSplit, 2)) fieldThree = funcoesUteis.treatTextField(funcoesUteis.analyzeIfFieldIsValidMatrix(dataSplit, 3)) if fieldOne.count('DO DOCUMENTO') > 0: self._accountDebitOrCredit = 'DEBIT' elif fieldOne.count('FAVORECIDO') > 0: self._accountDebitOrCredit = 'CREDIT' if fieldTwo.count("DATA DA TRANSF") > 0: paymentDate = funcoesUteis.retornaCampoComoData(fieldThree) if self._accountDebitOrCredit == 'DEBIT': if fieldOne == 'CONTA': account = str(funcoesUteis.treatNumberField(fieldTwo, isInt=True)) if fieldOne == 'NOME': nameProvider = fieldTwo if fieldOne == 'CPF': cgceProvider = fieldTwo if fieldOne == 'CNPJ': cgceProvider = fieldTwo if fieldOne == "VALOR": amountPaid = funcoesUteis.treatDecimalField(fieldTwo) if fieldOne.count("DATA DA TRANSF") > 0: paymentDate = funcoesUteis.retornaCampoComoData(fieldTwo) if fieldOne == "DESCRICAO": if paymentDate is not None and amountPaid > 0 and isTransferencia is True: valuesOfLine = { "paymentDate": paymentDate, "nameProvider": nameProvider, "cgceProvider": cgceProvider, "dueDate": None, "bank": 'AMAZONIA', "account": account, "amountPaid": round(amountPaid, 2), "amountInterest": round(amountInterest, 2), "amountDiscount": round(amountDiscount, 2), "amountFine": round(amountFine, 2), "amountOriginal": round(amountOriginal, 2), "historic": historic, "category": 'TRANSFERENCIA', "cgcePaying": "", "foundProof": True, "amountPaidPerLote": round(amountPaid, 2), "wayFile": self._file } return valuesOfLine.copy()