Ejemplo n.º 1
0
    def process(self):
        dataXml = readXml(self._xml)

        isNFe = funcoesUteis.returnDataFieldInDict(
            dataXml, ['nfeProc', 'NFe', 'infNFe', '@Id'])
        isNFeCanceled = funcoesUteis.returnDataFieldInDict(
            dataXml, ['procEventoNFe', 'evento', 'infEvento', 'chNFe'])
        isNFSeGoiania = funcoesUteis.returnDataFieldInDict(
            dataXml, ['geral', 'GerarNfseResposta'])

        nf = None

        if isNFe != "" and self._filterTypeNFs.count('nfe') > 0:
            nfe = NFe(dataXml)
            nf = nfe.readNFe()

        if isNFeCanceled != "" and self._filterTypeNFs.count('nfe_events') > 0:
            nfeCanceled = NFeCanceled(dataXml)
            nf = nfeCanceled.readNFeCanceled()

        if isNFSeGoiania != "" and self._filterTypeNFs.count(
                'nfse_goiania') > 0:
            nfseGoiania = NFSeGoiania(dataXml)
            nf = nfseGoiania.readNFe()

        return nf


# if __name__ == "__main__":
#     callReadXmls = CallReadXmls('C:/_temp/notas_mirene/52190505452064000490550010000065851000065850.xml')
#     nf = callReadXmls.process()
#     print(nf)
Ejemplo n.º 2
0
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
    }
Ejemplo n.º 3
0
    def __init__(self):
        self._payments = []
        self._paymentsDates = []
        self._proofsOfPayments = []
        self._extracts = []
        self._codiEmp = int(
            input(
                f'\n - Digite o código da empresa dentro da Domínio que será realizada a integração: '
            ))
        self._inicialDate = input(
            f'\n - Informe a data inicial (dd/mm/aaaa): ')
        self._finalDate = input(f' - Informe a data final (dd/mm/aaaa): ')
        # self._codiEmp = 118
        # self._inicialDate = '01/07/2020'
        # self._finalDate = '31/07/2020'
        self._lenghtLayoutsAccountPaid = 0
        self._waySettings = os.path.join(
            fileDir,
            f'backend/accounting_integration/data/settings/company{self._codiEmp}.json'
        )
        if os.path.exists(self._waySettings) is False:
            getSettingsCompany = GetSettingsCompany(self._codiEmp)
            self._settings = getSettingsCompany.getSettingsFinancy()
            self._lenghtLayoutsAccountPaid = len(
                self._settings['settingsLayouts'])
            self._banksToProof = funcoesUteis.returnDataFieldInDict(
                self._settings, ["proofPayment"], [{
                    "value": 0,
                    "label": ""
                }])
        else:
            self._settings = leArquivos.readJson(self._waySettings)
            self._banksToProof = funcoesUteis.returnDataFieldInDict(
                self._settings, ["banks", "listNumbers"], [{
                    "value": 0,
                    "label": ""
                }])

        self._wayFilesToRead = os.path.join(
            folderToSaveFilesAccountIntegration,
            f'{self._codiEmp}/arquivos_originais')
        self._wayFilesTemp = os.path.join(
            fileDir,
            f'backend/accounting_integration/data/temp/{self._codiEmp}')
        if os.path.exists(self._wayFilesTemp) is False:
            os.makedirs(self._wayFilesTemp)

        try:
            shutil.rmtree(self._wayFilesTemp)
        except OSError as e:
            print(f"Error: {e.filename}, {e.strerror}")

        if os.path.exists(self._wayFilesTemp) is False:
            os.makedirs(self._wayFilesTemp)

        self._wayReadFiles = os.path.join(self._wayFilesTemp,
                                          'FilesReads.json')
        if os.path.exists(self._wayReadFiles) is False:
            with open(self._wayReadFiles, 'w') as fileRead:
                json.dump({}, fileRead)
Ejemplo n.º 4
0
    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
        }
Ejemplo n.º 5
0
    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
Ejemplo n.º 6
0
    def process(self):
        dataXml = readXml(self._xml)

        isNFe = funcoesUteis.returnDataFieldInDict(dataXml, ['nfeProc', 'NFe', 'infNFe', '@Id'])
        isNFeCanceled = funcoesUteis.returnDataFieldInDict(dataXml, ['procEventoNFe', 'evento', 'infEvento', 'chNFe'])
        
        nf = None

        if isNFe != "":
            nfe = NFe(dataXml)
            nf = nfe.readNFe()

        if isNFeCanceled != "":
            nfeCanceled = NFeCanceled(dataXml)
            nf = nfeCanceled.readNFeCanceled()

        return nf


# if __name__ == "__main__":
#     callReadXmls = CallReadXmls('C:/_temp/notas-fiscais/1033 - OLIVEIRA MALTA COMERCIO DE BOLSAS E ARTI/2019-10/Entradas/NFe32191091681973000865550000000578841003314896.xml')
#     nf = callReadXmls.process()
#     print(nf)
Ejemplo n.º 7
0
    def getSettingsFinancy(self):
        try:
            settings = self._collection.find_one( { "codi_emp": self._codiEmp } )

            layouts = funcoesUteis.returnDataFieldInDict(settings, ['accountPaid', 'layouts'])

            settingsLayouts = self.getSettingsLayout(layouts)

            settings['settingsLayouts'] = settingsLayouts
        except Exception:
            settings = None
        finally:
            self._connectionMongo.closeConnection()

        return settings
 def __init__(self, settings, extracts=[], payments=[], proofOfPayments=[]):
     self._settings = settings
     self._extracts = extracts
     self._payments = payments
     self._proofOfPayments = proofOfPayments
     self._paymentsWithProofAndFinancy = [
     ]  # vai unir os comprovantes de pagamento com os pagamentos do financeiro do cliente
     self._paymentsFinal = []
     self._paymentsAlreadyRead = []
     self._extractsExistsInPayments = [
     ]  # este daqui são para os extratos que encontrou correlação nos pagamentos, na planilha de extratos conterá um campo com esta informação
     self._extractsToSearch = self._extracts.copy(
     )  # este daqui é que vai ser utilizado pra procurar se o pagamento existe correspondente no extrato, conforme for encontrando vai excluindo pra não procurar novamente num que já tinha retornado
     self._paymentsToSearch = self._payments.copy(
     )  # este daqui é que vai ser utilizado pra procurar se o pagamento existe correspondente no comprovante de pagamento, conforme for encontrando vai excluindo pra não procurar novamente num que já tinha retornado
     self._extractsFinal = []
     self._numberOfDaysInterval = 3
     self._numberOfDaysIntervalPaymentWithProof = 3
     self._financyIsReliable = funcoesUteis.returnDataFieldInDict(
         self._settings, ['accountPaid', 'isReliable'], True)
    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)
Ejemplo n.º 10
0
    def processPayments(self):

        for key, payment in enumerate(self._payments):
            document = funcoesUteis.analyzeIfFieldIsValid(
                payment, "document", None)
            nameProvider = funcoesUteis.analyzeIfFieldIsValid(
                payment, "nameProvider", None)
            accountPlan = funcoesUteis.analyzeIfFieldIsValid(
                payment, "accountPlan", None)
            category = funcoesUteis.analyzeIfFieldIsValid(
                payment, "category", None)
            historic = funcoesUteis.analyzeIfFieldIsValid(
                payment, "historic", None)
            bank = funcoesUteis.analyzeIfFieldIsValid(payment, "bank", None)
            account = funcoesUteis.analyzeIfFieldIsValid(payment, "account")

            # busca a conta da despesa/fornecedor
            accountCode = funcoesUteis.treatNumberField(
                funcoesUteis.analyzeIfFieldIsValid(payment, "accountCode", 0),
                isInt=True)
            dataProviderOrExpense = self.returnDataProviderOrExpense(
                nameProvider, accountPlan, category, historic)
            accountCodeNew = funcoesUteis.analyzeIfFieldIsValid(
                dataProviderOrExpense, 'accountDominio', None)
            overwriteAccount = funcoesUteis.analyzeIfFieldIsValid(
                dataProviderOrExpense, 'overwriteAccount', '')
            if overwriteAccount == 'SIM':
                accountCode = 0 if accountCodeNew is None else accountCodeNew
            else:
                if accountCode == 0:
                    accountCode = 0 if accountCodeNew is None else accountCodeNew

            # pra empresas que tem plano de contas no sistema deles e o plano não bate, tem que fazer um de-para
            accountCodeOld = funcoesUteis.analyzeIfFieldIsValid(
                payment, "accountCodeOld", None)
            if accountCode == 0 and accountCodeOld != "" and accountCodeOld is not None:
                accountCode = funcoesUteis.treatNumberField(
                    funcoesUteis.analyzeIfFieldIsValid(
                        self._valuesFromToAccounts, accountCodeOld, None),
                    isInt=True)
                accountCode = 0 if accountCode is None else accountCode

            accountCodeBank = self.returnDataBanks(bank, account,
                                                   'FINANCEIRO DO CLIENTE')

            payment["accountCode"] = accountCode
            payment["accountCodeBank"] = accountCodeBank

            # print(self._valuesAccountAndHistoricOthers)
            payment[
                "historicCodeDiscount"] = funcoesUteis.returnDataFieldInDict(
                    self._valuesAccountAndHistoricOthers,
                    [("DESCONTO", "HISTORICO")], 0)
            payment[
                "historicCodeInterest"] = funcoesUteis.returnDataFieldInDict(
                    self._valuesAccountAndHistoricOthers,
                    [("JUROS", "HISTORICO")], 0)
            payment["historicCodeFine"] = funcoesUteis.returnDataFieldInDict(
                self._valuesAccountAndHistoricOthers, [("MULTA", "HISTORICO")],
                0)
            payment[
                "historicCodePagamento"] = funcoesUteis.returnDataFieldInDict(
                    self._valuesAccountAndHistoricOthers,
                    [("PAGAMENTO", "HISTORICO")], 0)
            payment[
                "accountCodeDiscount"] = funcoesUteis.returnDataFieldInDict(
                    self._valuesAccountAndHistoricOthers,
                    [("DESCONTO", "CONTA CONTABIL")], 434)
            payment[
                "accountCodeInterest"] = funcoesUteis.returnDataFieldInDict(
                    self._valuesAccountAndHistoricOthers,
                    [("JUROS", "CONTA CONTABIL")], 372)
            payment["accountCodeFine"] = funcoesUteis.returnDataFieldInDict(
                self._valuesAccountAndHistoricOthers,
                [("MULTA", "CONTA CONTABIL")], 352)

            compositionHistoricPrimeiraPalavraNumero = funcoesUteis.analyzeIfFieldIsValid(
                self._valuesAccountAndHistoricOthers,
                "PRIMEIRA PALAVRA E UM NUMERO")
            compositionHistoricPrimeiraPalavraNaoNumero = funcoesUteis.analyzeIfFieldIsValid(
                self._valuesAccountAndHistoricOthers,
                "PRIMEIRA PALAVRA NAO E UM NUMERO")
            compositionHistoricDiferenteVazio = funcoesUteis.analyzeIfFieldIsValid(
                self._valuesAccountAndHistoricOthers, "FOR DIFERENTE DE VAZIO")
            compositionHistoricVazio = funcoesUteis.analyzeIfFieldIsValid(
                self._valuesAccountAndHistoricOthers, "FOR VAZIO")

            if document is not None and document != "":
                documentSplit = str(document).split()

                if funcoesUteis.treatNumberField(
                        documentSplit[0], True
                ) > 0 and compositionHistoricPrimeiraPalavraNumero != "":
                    payment[
                        "compositionHistoric"] = compositionHistoricPrimeiraPalavraNumero
                if funcoesUteis.treatNumberField(
                        documentSplit[0], True
                ) == 0 and compositionHistoricPrimeiraPalavraNaoNumero != "":
                    payment[
                        "compositionHistoric"] = compositionHistoricPrimeiraPalavraNaoNumero
                if document != "" and compositionHistoricDiferenteVazio != "":
                    payment[
                        "compositionHistoric"] = compositionHistoricDiferenteVazio
            else:
                payment["compositionHistoric"] = compositionHistoricVazio

            # print(payment)

            self._paymentsWithNewAccountCode.append(payment)

            # show de warnings
            if self._updateOrExtract is True:
                self.showWarningsPayments(payment, key)

        return self._paymentsWithNewAccountCode
Ejemplo n.º 11
0
    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
Ejemplo n.º 12
0
    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
        }
Ejemplo n.º 13
0
    def process(self):

        print('\n - Etapa 1: Lendo os PDFs')
        readPDFs = ReadPDFs(self._codiEmp, self._wayFilesTemp,
                            self._wayFilesToRead)
        readPDFs.processSplitPdfOnePageEach()
        readPDFs.transformPDFToText()
        readPDFs.doBackupFolderPDF(
        )  # faz o bkp pra não perder os dados quando apagar as informações

        print(' - Etapa 2: Lendo os OFXs ')
        extractsOFX = ExtractsOFX(self._codiEmp, self._wayFilesToRead,
                                  self._wayFilesTemp)
        extracts = extractsOFX.processAll()

        print(' \t- Etapa 2.1: Retirando lançamento de extrato duplicados. ')
        deleteExtractDuplicate = DeleteExtractDuplicate(extracts)
        self._extracts.append(deleteExtractDuplicate.process())

        # reads the financy
        print(' - Etapa 3: Lendo o financeiro do cliente')
        hasFinancy = funcoesUteis.returnDataFieldInDict(
            self._settings, ["financy", "has"])
        if hasFinancy is True or self._lenghtLayoutsAccountPaid > 0:
            systemFinancy = funcoesUteis.returnDataFieldInDict(
                self._settings, ["financy", "system"])
            if systemFinancy == "":
                readGeneral = ReadGeneral(self._codiEmp, self._wayFilesToRead,
                                          self._settings)
                readGeneralData = readGeneral.processAll()
                self._payments = readGeneralData[0]

                self._extracts.append(readGeneralData[1])
            else:
                callReadFilePayments = CallReadFilePayments(
                    systemFinancy, self._codiEmp, self._wayFilesToRead,
                    self._wayFilesTemp)
                self._payments = callReadFilePayments.process()
        else:
            print(
                '\t - Cliente sem a configuração do sistema financeiro realizada (provavelmente esta empresa não possui)'
            )

        self._extracts = funcoesUteis.removeAnArrayFromWithinAnother(
            self._extracts)

        # reads the txts
        print(
            ' - Etapa 4: Lendo os comprovantes de pagamentos e analisando as estruturas deles.'
        )
        callReadFileProofs = CallReadFileProofs(self._codiEmp,
                                                self._wayFilesTemp,
                                                self._wayFilesToRead,
                                                self._banksToProof)
        proofsOfPayments = callReadFileProofs.process()

        print(
            ' - Etapa 4.1: Retirando lançamento de comprovantes duplicados. ')
        deleteProofDuplicate = DeleteProofPaymentDuplicate(proofsOfPayments)
        self._proofsOfPayments = deleteProofDuplicate.process()

        print(
            ' - Etapa 5: Comparação entre o Financeiro com os Comprovantes de Pagamentos e Extratos.'
        )
        comparePaymentsAndProofWithExtracts = ComparePaymentsAndProofWithExtracts(
            self._settings, self._extracts, self._payments,
            self._proofsOfPayments)
        paymentsCompareWithProofAndExtracts = comparePaymentsAndProofWithExtracts.comparePaymentsFinalWithExtract(
        )
        extractsCompareWithProofAndExtracts = comparePaymentsAndProofWithExtracts.analyseIfExtractIsInPayment(
        )
        # print(paymentsCompareWithProofAndExtracts)

        print(' - Etapa 6: Filtrando os pagamentos do período informado.')
        filterPeriod = FilterPeriod(self._inicialDate, self._finalDate,
                                    paymentsCompareWithProofAndExtracts,
                                    extractsCompareWithProofAndExtracts)
        extractsWithFilter = filterPeriod.filterExtracts()
        paymentsWithFilter = filterPeriod.filterPayments()

        sequentialStep = 7

        hasOwnAccountPlan = funcoesUteis.returnDataFieldInDict(
            self._settings, ["financy", "hasOwnAccountPlan"])
        if hasOwnAccountPlan is False or hasOwnAccountPlan == "":
            print(
                f' - Etapa {sequentialStep}: Buscando a conta do fornecedor/despesa dentro do sistema.'
            )
            comparePaymentsFinalWithDataBase = ComparePaymentsFinalWithDataBase(
                self._codiEmp, self._finalDate, paymentsWithFilter)
            paymentsFinal = comparePaymentsFinalWithDataBase.process()
            sequentialStep += 1
        else:
            paymentsFinal = paymentsWithFilter

        print(
            f' - Etapa {sequentialStep}: Configurando as contas contábeis de acordo planilha de configuracoes preenchida.'
        )
        compareWithSettings = CompareWithSettings(self._codiEmp, paymentsFinal,
                                                  extractsWithFilter)
        extractsCompareWithSettings = compareWithSettings.processExtracts()
        paymentsCompareWithSettings = compareWithSettings.processPayments()
        sequentialStep += 1

        print(f' - Etapa {sequentialStep}: Exportando informações')
        generateExcel = GenerateExcel(self._codiEmp)
        generateExcel.sheetPayments(paymentsCompareWithSettings)
        generateExcel.sheetExtract(extractsCompareWithSettings)
        generateExcel.closeFile()
        sequentialStep += 1

        print(
            f' - Etapa {sequentialStep}: Salvando arquivos que não foram lidos'
        )
        returnFilesDontFindForm = ReturnFilesDontFindForm(
            self._codiEmp, self._wayFilesTemp)
        returnFilesDontFindForm.processAll()

        print(' - Processo Finalizado.')
        os.system('pause > nul')