Beispiel #1
0
    def process(self):
        try:
            companiesDominio = self._geempre.getCompanies()

            companiesExcel = leXls_Xlsx(
                'C:/Programming/baymax/backend/extract/data/empresas_grupo.xlsm',
                'EMPRESAS')

            print('- Exportando dados de movimentação geral empresas:')

            for companie in companiesExcel:
                codi_emp = funcoesUteis.treatNumberField(companie[0],
                                                         isInt=True)
                nome_emp = funcoesUteis.treatTextField(companie[1])
                group = funcoesUteis.treatTextField(companie[2])

                dataCompanie = {'codi_emp': codi_emp, 'groupCompanie': group}

                existCompanieDominio = list(
                    filter(
                        lambda companieDominio: companieDominio['codi_emp'] ==
                        codi_emp, companiesDominio))
                if len(existCompanieDominio) > 0:
                    self._collection.update_one({"codi_emp": codi_emp},
                                                {"$set": dataCompanie},
                                                upsert=True)
                    print(f"\t - {codi_emp} - {nome_emp}")

        except Exception as e:
            print(f"O erro é: {e}")
        finally:
            self._connectionMongo.closeConnection()
Beispiel #2
0
    def returnProductComparation(self, productAccountSystem, productsXML):
        if len(productsXML) == 0:
            return None

        nameProductAccountSystem = funcoesUteis.treatTextField(
            productAccountSystem['desc_pdi'])
        qtdAccountSystem = round(
            funcoesUteis.treatDecimalField(productAccountSystem['qtd']), 2)
        vunitAccountSystem = round(
            funcoesUteis.treatDecimalField(productAccountSystem['vunit']), 2)
        vtotAccountSystem = round(
            funcoesUteis.treatDecimalField(productAccountSystem['vtot']), 2)

        productXML = None

        if len(productsXML) == 1:
            productXML = productsXML[0]
            nameProductXML = funcoesUteis.treatTextField(
                productXML['prod']['xProd'])
            productXML[
                'valueComparationBetweenAccountSystemAndXML'] = SequenceMatcher(
                    None, nameProductAccountSystem, nameProductXML).ratio()
        else:
            productXML = self.foundProductInNote(productsXML,
                                                 nameProductAccountSystem,
                                                 qtdAccountSystem,
                                                 vunitAccountSystem)

        return productXML
Beispiel #3
0
    def processAccountPlan(self, dataFile):
        for key, data in enumerate(dataFile):

            try:
                recordType = data[0:2]
                account = data[2:10]
                nameAccount = funcoesUteis.treatTextField(data[246:356])
                nameAccountMain = funcoesUteis.treatTextField(data[26:136])
                nameAccountSubMain = funcoesUteis.treatTextField(data[136:246])

                if recordType == '05':
                    self._accountPlan[account] = [nameAccount, nameAccountMain, nameAccountSubMain]

            except Exception as e:
                pass
Beispiel #4
0
    def foundProductInNote(self, productsXML, nameProductAccountSystem,
                           qtdAccountSystem, vunitAccountSystem):
        productsEquals = []

        for productXML in productsXML:
            nameProductXML = funcoesUteis.treatTextField(
                productXML['prod']['xProd'])
            qtdProductXML = round(
                funcoesUteis.treatDecimalField(productXML['prod']['qCom']), 2)
            vunitProductXML = round(
                funcoesUteis.treatDecimalField(productXML['prod']['vUnCom']),
                2)
            # vtotProductXML = round(funcoesUteis.treatDecimalField(productXML['prod']['vProd']),2)

            if qtdProductXML == qtdAccountSystem and vunitProductXML == vunitAccountSystem:
                productXML[
                    'valueComparationBetweenAccountSystemAndXML'] = SequenceMatcher(
                        None, nameProductAccountSystem,
                        nameProductXML).ratio()
                if productXML[
                        'valueComparationBetweenAccountSystemAndXML'] > 0.85:
                    return productXML
                else:
                    productsEquals.append(productXML)

        if len(productsEquals) > 0:
            return sorted(productsEquals,
                          key=itemgetter(
                              'valueComparationBetweenAccountSystemAndXML'))[0]
    def getSettingsFromToOfAccounts(self):
        dataFile = leXls_Xlsx(self._wayFileSettings, 'DeParaPlanoContas')

        for data in dataFile:
            try:
                fieldHeader = funcoesUteis.treatTextFieldInVector(data, 1)
                if fieldHeader.count('CODIGO CONTA SISTEMA CLIENTE') > 0:
                    self._posionsOfHeaderFromToAccounts.clear()
                    for keyField, nameField in enumerate(data):
                        nameField = funcoesUteis.treatTextField(nameField)
                        self._posionsOfHeaderFromToAccounts[
                            nameField] = keyField
                    continue

                valueComparation = funcoesUteis.treatTextFieldInVector(
                    data, 1, self._posionsOfHeaderFromToAccounts,
                    "Código Conta Sistema Cliente")

                accountDominio = int(
                    funcoesUteis.treatNumberFieldInVector(
                        data, 4, self._posionsOfHeaderFromToAccounts,
                        "Conta Contábil Domínio"))

                if valueComparation != "" and accountDominio != "":
                    self._valuesFromToAccounts[
                        valueComparation] = accountDominio
            except Exception as e:
                pass

        return self._valuesFromToAccounts
    def exportData(self):
        print('- Exportando dados de integração:')
        try:
            companiesSettingsView = list(self._dbMongo['CompaniesSettingsView'].find({}))
            for companieSettingView in companiesSettingsView:
                del companieSettingView['_id']

                codiEmp = companieSettingView['codi_emp']                
                print(f"\t- Processando empresa {codiEmp} - {companieSettingView['nome_emp']}")

                cgceEmp = str(treatNumberField(companieSettingView['cgce_emp']))
                cgceMatriz = cgceEmp[:8]

                isCompanyBranch = treatTextField(companieSettingView['isCompanyBranch'])

                if isCompanyBranch == 'NAO':
                    companieMonthsAmountNotes = self.getCompaniesMonthsAmountNotes(cgceMatriz)
                else:
                    companieMonthsAmountNotes = self.getCompaniesMonthsAmountNotes(cgceEmp)
                
                self.saveMongo(codiEmp, cgceMatriz, companieMonthsAmountNotes)

        except Exception as e:
            print(f"Erro ao executar a consulta. O erro é: {e}")
        finally:
            self._connectionMongo.closeConnection()
            self._DB.closeConnection()
    def returnDataEmp(self, cgce):
        for companie in self._companies:
            cgceCompanie = funcoesUteis.treatTextField(companie["cgce_emp"])
            if cgceCompanie == "":
                continue

            if companie["cgce_emp"] == cgce:
                return companie

        return None
    def getSettingsProviderOrExpense(self):
        dataFile = leXls_Xlsx(self._wayFileSettings, 'FornecedorOuDespesa')

        for data in dataFile:
            try:
                if str(data[0]).upper().count('QUANDO NO CAMPO') > 0:
                    self._posionsOfHeaderProviderOrExpense.clear()
                    for keyField, nameField in enumerate(data):
                        nameField = funcoesUteis.treatTextField(nameField)
                        self._posionsOfHeaderProviderOrExpense[
                            nameField] = keyField
                    continue

                fieldComparation = funcoesUteis.treatTextFieldInVector(
                    data, 1, self._posionsOfHeaderProviderOrExpense,
                    "Quando no Campo")
                fieldComparation = self._settingsFieldComparation[
                    fieldComparation]

                typeComparation = funcoesUteis.treatTextFieldInVector(
                    data, 2, self._posionsOfHeaderProviderOrExpense,
                    "Tipo comparação")
                typeComparation = self._settingsTypeComparation[
                    typeComparation]

                valueComparation = funcoesUteis.treatTextFieldInVector(
                    data, 3, self._posionsOfHeaderProviderOrExpense, "Valor")

                accountDominio = int(
                    funcoesUteis.treatNumberFieldInVector(
                        data, 4, self._posionsOfHeaderProviderOrExpense,
                        "Conta Contábil Domínio"))

                overwriteAccount = funcoesUteis.treatTextFieldInVector(
                    data, 5, self._posionsOfHeaderProviderOrExpense,
                    "Sobrescrever a Conta na Planilha Processada?")

                if fieldComparation != "" and valueComparation != "" and accountDominio > 0:
                    self._valuesOfLineProviderOrExpense = {
                        "fieldComparation": fieldComparation,
                        "typeComparation": typeComparation,
                        "valueComparation": valueComparation,
                        "accountDominio": accountDominio,
                        "overwriteAccount": overwriteAccount
                    }

                    self._valuesOfFileProviderOrExpense.append(
                        self._valuesOfLineProviderOrExpense.copy())
            except Exception as e:
                pass

        return self._valuesOfFileProviderOrExpense
    def getSettingsAccountAndHistoricOthers(self):
        dataFile = leXls_Xlsx(self._wayFileSettings, 'ContasEHistoricoOutros')

        for data in dataFile:
            try:
                fieldHeader = funcoesUteis.treatTextFieldInVector(data, 1)
                if fieldHeader.count('QUANDO HOUVER') > 0:
                    self._posionsOfHeaderAccountAndHistoricOthers.clear()
                    for keyField, nameField in enumerate(data):
                        nameField = funcoesUteis.treatTextField(nameField)
                        self._posionsOfHeaderAccountAndHistoricOthers[
                            nameField] = keyField
                    continue

                # juros, multa, desconto
                fieldComparation = funcoesUteis.treatTextFieldInVector(
                    data, 1, self._posionsOfHeaderAccountAndHistoricOthers,
                    "Quando houver")
                if fieldComparation == "":
                    continue

                # historico ou conta contabil
                fieldOthers = funcoesUteis.treatTextFieldInVector(
                    data, 2, self._posionsOfHeaderAccountAndHistoricOthers,
                    "na Domínio o código do(a)")

                valueDominio = funcoesUteis.treatNumberFieldInVector(
                    data, 3, self._posionsOfHeaderAccountAndHistoricOthers,
                    "Será o")

                if fieldComparation != "" and fieldOthers != "" and valueDominio != "":
                    self._valuesAccountAndHistoricOthers[
                        fieldComparation, fieldOthers] = valueDominio

                whenColumnDocumento = funcoesUteis.treatTextFieldInVector(
                    data, 7, self._posionsOfHeaderAccountAndHistoricOthers,
                    "Quando na Coluna Documento")

                compositionHistoric = funcoesUteis.treatTextFieldInVector(
                    data,
                    8,
                    self._posionsOfHeaderAccountAndHistoricOthers,
                    "Composição Histórico",
                    keepTextOriginal=False)

                if whenColumnDocumento != "" and compositionHistoric != "":
                    self._valuesAccountAndHistoricOthers[
                        whenColumnDocumento] = compositionHistoric

            except Exception as e:
                pass
    def getSettingsExtract(self):
        dataFile = leXls_Xlsx(self._wayFileSettings, 'ExtratoBancario')

        for data in dataFile:
            try:
                if str(data[0]).upper().count('QUANDO NO CAMPO') > 0:
                    self._posionsOfHeaderExtracts.clear()
                    for keyField, nameField in enumerate(data):
                        nameField = funcoesUteis.treatTextField(nameField)
                        self._posionsOfHeaderExtracts[nameField] = keyField
                    continue

                fieldComparation = funcoesUteis.treatTextFieldInVector(
                    data, 1, self._posionsOfHeaderExtracts, "Quando no Campo")
                fieldComparation = self._settingsFieldComparationExtract[
                    fieldComparation]

                operationComparation = funcoesUteis.treatTextFieldInVector(
                    data, 2, self._posionsOfHeaderExtracts, "Operação for")
                operationComparation = self._settingsOperationComparation[
                    operationComparation]

                typeComparation = funcoesUteis.treatTextFieldInVector(
                    data, 3, self._posionsOfHeaderExtracts, "Tipo comparação")
                typeComparation = self._settingsTypeComparation[
                    typeComparation]

                valueComparation = funcoesUteis.treatTextFieldInVector(
                    data, 4, self._posionsOfHeaderExtracts, "Valor")

                accountDominio = int(
                    funcoesUteis.treatNumberFieldInVector(
                        data, 5, self._posionsOfHeaderExtracts,
                        "Conta Contábil Domínio"))

                if fieldComparation != "" and valueComparation != "" and accountDominio > 0:
                    self._valuesOfLineExtracts = {
                        "fieldComparation": fieldComparation,
                        "operationComparation": operationComparation,
                        "typeComparation": typeComparation,
                        "valueComparation": valueComparation,
                        "accountDominio": accountDominio
                    }

                    self._valuesOfFileExtracts.append(
                        self._valuesOfLineExtracts.copy())
            except Exception as e:
                pass

        return self._valuesOfFileExtracts
Beispiel #11
0
    def isProof(self, file):
        dataFile = leTxt(file, treatAsText=True, removeBlankLines=True)
        countProof = 0
        for data in dataFile:
            data = funcoesUteis.treatTextField(data)

            if data.find('CENTRAL DE ATENDIMENTO SANTANDER EMPRESARIAL') >= 0:
                countProof += 1
            if (data.find('4004') >= 0
                    or data.find('726')) and data.find('2125') >= 0:
                countProof += 1

            if countProof == 3:
                return True
    def getLivroCaixa(self):
        dataFile = leXls_Xlsx(self._file, 'Lancamentos')

        for data in dataFile:
            if str(data[0]).upper().count('DOCUMENTO') > 0:
                self._posionsOfHeader.clear()
                for keyField, nameField in enumerate(data):
                    nameField = funcoesUteis.treatTextField(nameField)
                    self._posionsOfHeader[nameField] = keyField
                continue

            dateLivro = funcoesUteis.treatDateFieldInVector(
                data, 1, self._posionsOfHeader, "Data")
            movementType = funcoesUteis.treatTextFieldInVector(
                data, 2, self._posionsOfHeader, "Tipo Movimento")
            account = funcoesUteis.treatTextFieldInVector(
                data, 3, self._posionsOfHeader, "Conta Contábil")
            nameAccount = funcoesUteis.treatTextFieldInVector(
                data, 4, self._posionsOfHeader, "Nome Conta")
            amount = funcoesUteis.treatDecimalFieldInVector(
                data, 5, self._posionsOfHeader, "Valor")
            document = funcoesUteis.treatTextFieldInVector(
                data, 6, self._posionsOfHeader, "Documento")
            documentType = funcoesUteis.treatTextFieldInVector(
                data, 7, self._posionsOfHeader, "Tipo Documento")
            participante = funcoesUteis.treatTextFieldInVector(
                data, 8, self._posionsOfHeader, "Participante")
            imovelRural = funcoesUteis.treatTextFieldInVector(
                data, 9, self._posionsOfHeader, "Imóvel Rural")
            historic = funcoesUteis.treatTextFieldInVector(
                data, 10, self._posionsOfHeader, "Histórico")

            if amount != 0:
                self._dataOfLine = {
                    'dateLivro': dateLivro,
                    'movementType': movementType,
                    'account': account,
                    'nameAccount': nameAccount,
                    'amount': amount,
                    'document': document,
                    'documentType': documentType,
                    'participante': participante,
                    'imovelRural': imovelRural,
                    'historic': historic
                }

                self._dataOfFile.append(self._dataOfLine.copy())

        return self._dataOfFile
Beispiel #13
0
    def transformTxt(self, wayFile):
        dataTxt = leTxt(wayFile)
        for data in dataTxt:
            data = funcoesUteis.treatTextField(data)
            if data == '':
                continue
            dataSplit = data.split(' ')

            date = funcoesUteis.treatDateFieldInVector(dataSplit, 1)
            numeroDocumento = funcoesUteis.treatTextFieldInVector(dataSplit, 2)
            creditOrDebit = funcoesUteis.treatTextFieldInVector(dataSplit, 0)
            valorMovimento = funcoesUteis.treatDecimalFieldInVector(dataSplit, -1)
            historico = ' '.join(dataSplit[2:len(dataSplit)-2])
            if valorMovimento > 0:
                dateFormated = funcoesUteis.transformaCampoDataParaFormatoBrasileiro(date)
                print(f'{dateFormated};;;{valorMovimento};;{historico};{numeroDocumento};{creditOrDebit}')
Beispiel #14
0
    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
Beispiel #15
0
    def process(self, file, sequential):
        dataFile = leTxt(file, removeBlankLines=True, treatAsText=True)

        dateExtract = None
        historic = None
        amount = 0
        balance = 0
        document = ''

        extractsTemp = []
        extracts = []

        for data in dataFile:
            dataSplit = data.split(' ')
            dateExtract = funcoesUteis.treatDateFieldInVector(dataSplit, 1)
            document = funcoesUteis.treatTextFieldInVector(dataSplit, -3)
            amount = funcoesUteis.treatDecimalFieldInVector(dataSplit, -2)
            balance = funcoesUteis.treatDecimalFieldInVector(dataSplit, -1)

            historic = ' '.join(dataSplit[1:len(dataSplit)-4])
            historic = funcoesUteis.treatTextField(historic)

            if dateExtract is not None and amount > 0:
                extractsTemp.append({
                    "dateExtract": dateExtract,
                    "document": document,
                    "amount": amount,
                    "balance": balance,
                    "historic": historic
                })

        for key, extract in enumerate(extractsTemp):
            if key > 0:
                beforeExtract = extractsTemp[key-1]

                balanceBefore = beforeExtract['balance']
                balanceActual = extract['balance']
                if balanceBefore > balanceActual:
                    extract['operation'] = '-'
                else:
                    extract['operation'] = '+'
            else:
                extract['operation'] = '+'

            dataFormatada = funcoesUteis.transformaCampoDataParaFormatoBrasileiro(extract['dateExtract'])
            print(f"{dataFormatada};{extract['document']};{extract['historic']};{extract['operation']}{extract['amount']:.2f};{extract['operation']};SANTANDER;0971130017960")
    def getSettingsBanks(self):
        dataFile = leXls_Xlsx(self._wayFileSettings, 'Bancos')

        for data in dataFile:
            try:
                if str(data[0]).upper().count('COMPARAR COM') > 0 or str(
                        data[0]).upper().count('BANCO') > 0:
                    self._posionsOfHeaderBanks.clear()
                    for keyField, nameField in enumerate(data):
                        nameField = funcoesUteis.treatTextField(nameField)
                        self._posionsOfHeaderBanks[nameField] = keyField
                    continue

                compareWith = funcoesUteis.treatTextFieldInVector(
                    data, 1, self._posionsOfHeaderBanks, "Comparar Com")
                compareWith = "" if compareWith != "EXTRATO BANCARIO" and compareWith != "FINANCEIRO DO CLIENTE" else compareWith

                nameBank = funcoesUteis.treatTextFieldInVector(
                    data, 2, self._posionsOfHeaderBanks, "Banco")

                account = funcoesUteis.treatTextFieldInVector(
                    data, 3, self._posionsOfHeaderBanks,
                    "Conta Corrente (Sem o Dígito Verificador)")
                # account = account[:-1] # o -1 é pra tirar o digíto verificador caso o pessoal preencha na configuração, então pega sempre um char a menos evitando este problema

                accountDominio = int(
                    funcoesUteis.treatNumberFieldInVector(
                        data, 4, self._posionsOfHeaderBanks,
                        "Conta Contábil Banco na Domínio"))

                if nameBank != "" and accountDominio > 0:
                    self._valuesOfLineBanks = {
                        "compareWith": compareWith,
                        "nameBankComparation": nameBank,
                        "accountComparation": account,
                        "accountDominio": accountDominio
                    }

                    self._valuesOfFileBanks.append(
                        self._valuesOfLineBanks.copy())
            except Exception as e:
                pass

        return self._valuesOfFileBanks
    def getProductsFixedAssets(self, codi_emp, month, year, products):
        try:
            collectionFixedAssets = self._dbMongo['EntryNoteProductsFixedAssets']
            collectionFixedAssets.delete_many( {"$and": [{'codi_emp': codi_emp}, {'monthFilter': month}, {'yearFilter': year}] } )

            for product in products:
                if str(product['cfop']) in ('1551', '2551', '3551', '1406', '2406'):
                    product['classificado_corretamente_cfop'] = True
                    collectionFixedAssets.insert_one(product)
                elif str(product['cfop']) in ('1556', '2556', '3556', '1407', '2407'):
                    vunit = funcoesUteis.treatDecimalField(product['vunit'])
                    if vunit >= 1200:
                        desc_pdi = funcoesUteis.treatTextField(product['desc_pdi'])
                        hasNameProductFixedAsset = list(filter(lambda name: desc_pdi.find(funcoesUteis.treatTextField(name)) >= 0, self._namesProductsBase))
                        if len(hasNameProductFixedAsset) > 0:
                            product['classificado_corretamente_cfop'] = False
                            collectionFixedAssets.insert_one(product)
                        else:
                            continue
                else:
                    continue
        except Exception:
            pass
    def process(self):
        try:
            companiesDominio = self._geempre.getCompanies()

            companiesExcel = leXls_Xlsx(
                'C:/Programming/baymax/backend/extract/data/empresas_integrattion_old.xlsx',
                'Já Avaliadas - Hist')

            print('- Lendo dados das integrações antigas:')

            for companie in companiesExcel:
                codi_emp = funcoesUteis.treatNumberField(companie[0],
                                                         isInt=True)
                nome_emp = funcoesUteis.treatTextField(companie[1])
                responsibleFinancialClientOld = funcoesUteis.treatTextField(
                    companie[4])
                obsAccountPaidOld = funcoesUteis.treatTextField(companie[8])
                dateAccountPaidOld = funcoesUteis.treatTextField(companie[7])
                layoutsAccountPaidOld = funcoesUteis.treatTextField(
                    companie[9])
                hasIntegrated = funcoesUteis.treatTextField(companie[10])

                dataCompanie = {
                    'codi_emp': codi_emp,
                    'responsibleFinancialClientOld':
                    responsibleFinancialClientOld,
                    'obsAccountPaidOld': obsAccountPaidOld,
                    'dateAccountPaidOld': dateAccountPaidOld,
                    'layoutsAccountPaidOld': layoutsAccountPaidOld
                }

                existCompanieDominio = list(
                    filter(
                        lambda companieDominio: companieDominio['codi_emp'] ==
                        codi_emp, companiesDominio))
                if len(existCompanieDominio) > 0 and hasIntegrated == "SIM":
                    self._collection.update_one({"codi_emp": codi_emp},
                                                {"$set": dataCompanie},
                                                upsert=True)
                    print(f"\t - {codi_emp} - {nome_emp}")

        except Exception as e:
            print(f"O erro é: {e}")
        finally:
            self._connectionMongo.closeConnection()
    def getAccountPlan(self):
        dataFile = leXls_Xlsx(self._file, 'PlanoContas')

        for data in dataFile:
            if str(data[0]).upper().count('CONTA') > 0:
                self._posionsOfHeaderAccountPlan.clear()
                for keyField, nameField in enumerate(data):
                    nameField = funcoesUteis.treatTextField(nameField)
                    self._posionsOfHeaderAccountPlan[nameField] = keyField
                continue

            account = funcoesUteis.treatTextFieldInVector(
                data, 1, self._posionsOfHeaderAccountPlan, "Conta")
            # nameAccount = funcoesUteis.treatTextFieldInVector(data, 2, self._posionsOfHeaderAccountPlan, "Nome")
            # nameAccountMain = funcoesUteis.treatTextFieldInVector(data, 3, self._posionsOfHeaderAccountPlan, "Grupo Principal")
            # nameAccountSubMain = funcoesUteis.treatTextFieldInVector(data, 4, self._posionsOfHeaderAccountPlan, "Subgrupo")
            accountDominio = funcoesUteis.treatNumberFieldInVector(
                data, 5, self._posionsOfHeaderAccountPlan,
                "Código Conta Domínio")

            self._dataOfLineAccountPlan[account] = accountDominio

        return self._dataOfLineAccountPlan
Beispiel #20
0
    def process(self):
        try:
            companiesDominio = list(self._collection.find({}))

            companiesExcel = leXls_Xlsx(
                'C:/Programming/baymax/backend/extract/data/empresas_externos.xlsx',
                'GERAL')

            print('- Processando empresas dos externos:')

            for companie in companiesExcel:
                codi_emp = funcoesUteis.treatNumberField(companie[0],
                                                         isInt=True)
                nome_emp = funcoesUteis.treatTextField(companie[1])

                existCompanieDominio = list(
                    filter(
                        lambda companieDominio: companieDominio['codi_emp'] ==
                        codi_emp, companiesDominio))
                if len(existCompanieDominio) > 0:
                    dataCompanie = {
                        'codi_emp':
                        codi_emp,
                        'grupos_contabil':
                        f"{existCompanieDominio[0]['grupos_contabil']},EXTERNOS",
                        'grupos_fiscal':
                        f"{existCompanieDominio[0]['grupos_fiscal']},EXTERNOS"
                    }
                    self._collection.update_one({"codi_emp": codi_emp},
                                                {"$set": dataCompanie},
                                                upsert=True)
                    print(f"\t - {codi_emp} - {nome_emp}")

        except Exception as e:
            print(f"O erro é: {e}")
        finally:
            self._connectionMongo.closeConnection()
    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)
Beispiel #22
0
    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()
Beispiel #23
0
    def getPayments(self):
        dataFile = leXls_Xlsx(self._file, 'Pagamentos')

        for data in dataFile:
            if str(data[0]).upper().count('LOTE') > 0:
                self._posionsOfHeaderPayments.clear()
                for keyField, nameField in enumerate(data):
                    nameField = funcoesUteis.treatTextField(nameField)
                    self._posionsOfHeaderPayments[nameField] = keyField
                continue

            numberLote = int(
                funcoesUteis.treatDecimalFieldInVector(
                    data, 1, self._posionsOfHeaderPayments, "Lote"))
            document = funcoesUteis.treatTextFieldInVector(
                data, 2, self._posionsOfHeaderPayments, "Documento")

            findNote = funcoesUteis.treatTextFieldInVector(
                data, 3, self._posionsOfHeaderPayments, "NF na Domínio?")
            if findNote == "1":
                findNote = True
            elif findNote == "0":
                findNote = False
            else:
                findNote = ""

            parcelNumber = funcoesUteis.treatTextFieldInVector(
                data, 4, self._posionsOfHeaderPayments, "Parcela")
            nameProvider = funcoesUteis.treatTextFieldInVector(
                data, 5, self._posionsOfHeaderPayments, "Fornecedor")
            cgceProvider = funcoesUteis.treatTextFieldInVector(
                data, 6, self._posionsOfHeaderPayments, "CNPJ Fornecedor")

            bankAndAccount = funcoesUteis.treatTextFieldInVector(
                data, 7, self._posionsOfHeaderPayments,
                "Banco Financeiro").split('-')
            if len(bankAndAccount) == 2:
                bank = bankAndAccount[0]
                account = bankAndAccount[1]
            elif len(bankAndAccount) == 1:
                bank = bankAndAccount[0]
                account = ""
            else:
                bank = ""
                account = ""

            bankAndAccountExtract = funcoesUteis.treatTextFieldInVector(
                data, 8, self._posionsOfHeaderPayments,
                "Banco Extrato").split('-')
            if len(bankAndAccountExtract) == 2:
                bankExtract = bankAndAccountExtract[0]
                accountExtract = bankAndAccountExtract[1]
            elif len(bankAndAccountExtract) == 1:
                bankExtract = bankAndAccountExtract[0]
                accountExtract = ""
            else:
                bankExtract = ""
                accountExtract = ""

            foundProof = funcoesUteis.treatTextFieldInVector(
                data, 9, self._posionsOfHeaderPayments, "Comprovante Pagto?")
            if foundProof == "1":
                foundProof = True
            elif foundProof == "0":
                foundProof = False
            else:
                foundProof = ""

            paymentDate = funcoesUteis.treatDateFieldInVector(
                data, 10, self._posionsOfHeaderPayments, "Data Financeiro")
            extractDate = funcoesUteis.treatDateFieldInVector(
                data, 11, self._posionsOfHeaderPayments, "Data Extrato")
            dateOfImport = funcoesUteis.treatDateFieldInVector(
                data, 12, self._posionsOfHeaderPayments, "Importação Domínio")
            dueDate = funcoesUteis.treatTextFieldInVector(
                data, 13, self._posionsOfHeaderPayments, "Vencimento")
            issueDate = funcoesUteis.treatTextFieldInVector(
                data, 14, self._posionsOfHeaderPayments, "Emissão")
            amountPaid = funcoesUteis.treatDecimalFieldInVector(
                data, 15, self._posionsOfHeaderPayments, "Valor Pago")
            amountDiscount = funcoesUteis.treatDecimalFieldInVector(
                data, 16, self._posionsOfHeaderPayments, "Desconto")
            amountInterest = funcoesUteis.treatDecimalFieldInVector(
                data, 17, self._posionsOfHeaderPayments, "Juros")
            amountFine = funcoesUteis.treatDecimalFieldInVector(
                data, 18, self._posionsOfHeaderPayments, "Multa")
            amountOriginal = funcoesUteis.treatDecimalFieldInVector(
                data, 19, self._posionsOfHeaderPayments, "Valor Original")
            accountCode = funcoesUteis.treatNumberFieldInVector(
                data, 20, self._posionsOfHeaderPayments,
                "Conta Contabil Domínio")
            codiEmp = funcoesUteis.treatTextFieldInVector(
                data, 21, self._posionsOfHeaderPayments, "Codigo Empresa")
            historic = funcoesUteis.treatTextFieldInVector(
                data, 22, self._posionsOfHeaderPayments,
                "Historico Financeiro")
            category = funcoesUteis.treatTextFieldInVector(
                data, 23, self._posionsOfHeaderPayments, "Categoria")
            accountPlan = funcoesUteis.treatTextFieldInVector(
                data, 24, self._posionsOfHeaderPayments, "Plano de Contas")
            cgcePaying = funcoesUteis.treatTextFieldInVector(
                data, 25, self._posionsOfHeaderPayments, "CNPJ Pagador")
            historicExtract = funcoesUteis.treatTextFieldInVector(
                data, 26, self._posionsOfHeaderPayments,
                "Historico Extrato Bancário")
            accountCodeOld = funcoesUteis.treatTextFieldInVector(
                data, 27, self._posionsOfHeaderPayments,
                "Conta Contabil Sistema Cliente")

            if amountPaid != 0:
                self._paymentsOfLine = {
                    "numberLote": numberLote,
                    "document": document,
                    "findNote": findNote,
                    "parcelNumber": parcelNumber,
                    "nameProvider": nameProvider,
                    "cgceProvider": cgceProvider,
                    "bank": bank,
                    "account": account,
                    "bankExtract": bankExtract,
                    "accountExtract": accountExtract,
                    "foundProof": foundProof,
                    "paymentDate": paymentDate,
                    "dateExtract": extractDate,
                    "dateOfImport": dateOfImport,
                    "dueDate": dueDate,
                    "issueDate": issueDate,
                    "amountPaid": amountPaid,
                    "amountDiscount": amountDiscount,
                    "amountInterest": amountInterest,
                    "amountFine": amountFine,
                    "amountOriginal": amountOriginal,
                    "accountCode": accountCode,
                    "companyBranch": codiEmp,
                    "historic": historic,
                    "category": category,
                    "accountPlan": accountPlan,
                    "cgcePaying": cgcePaying,
                    "historicExtract": historicExtract,
                    "accountCodeOld": accountCodeOld
                }

                self._paymentsOfFile.append(self._paymentsOfLine.copy())

        return self._paymentsOfFile
Beispiel #24
0
    def getExtracts(self):
        dataFile = leXls_Xlsx(self._file, 'ExtratosBancarios')

        for key, data in enumerate(dataFile):
            if str(data[0]).upper().count('DATA') > 0:
                self._posionsOfHeaderExtracts.clear()
                for keyField, nameField in enumerate(data):
                    nameField = funcoesUteis.treatTextField(nameField)
                    self._posionsOfHeaderExtracts[nameField] = keyField
                continue

            dateExtract = funcoesUteis.treatDateFieldInVector(data, 1)
            accountCodeDebit = funcoesUteis.treatNumberFieldInVector(
                data, 2, self._posionsOfHeaderExtracts, "Debito")
            accountCodeCredit = funcoesUteis.treatNumberFieldInVector(
                data, 3, self._posionsOfHeaderExtracts, "Credito")
            amount = funcoesUteis.treatDecimalFieldInVector(
                data, 4, self._posionsOfHeaderExtracts, "Valor")
            historicCode = funcoesUteis.treatNumberFieldInVector(
                data, 5, self._posionsOfHeaderExtracts, "Cod. Hist")
            historic = funcoesUteis.treatTextFieldInVector(
                data, 6, self._posionsOfHeaderExtracts, "Historico")

            foundProofInPayments = funcoesUteis.treatTextFieldInVector(
                data, 7, self._posionsOfHeaderExtracts,
                "Encontrou no Financeiro?")
            if foundProofInPayments == "1":
                foundProofInPayments = True
            elif foundProofInPayments == "0":
                foundProofInPayments = False
            else:
                foundProofInPayments = ""

            bank = funcoesUteis.treatTextFieldInVector(
                data, 10, self._posionsOfHeaderExtracts, "Banco")
            account = funcoesUteis.treatTextFieldInVector(
                data, 11, self._posionsOfHeaderExtracts, "Conta Corrente")
            typeTransaction = funcoesUteis.treatTextFieldInVector(
                data, 13, self._posionsOfHeaderExtracts, "Tipo Transacao")
            operation = funcoesUteis.treatTextFieldInVector(
                data, 14, self._posionsOfHeaderExtracts, "Operacao")
            document = funcoesUteis.treatTextFieldInVector(
                data, 16, self._posionsOfHeaderExtracts, "Documento")

            if dateExtract is not None and amount > 0:
                self._extractsOfLine = {
                    "dateTransaction": dateExtract,
                    "accountCodeDebit": accountCodeDebit,
                    "accountCodeCredit": accountCodeCredit,
                    "amount": amount,
                    "historicCode": historicCode,
                    "historic": historic,
                    "foundProofInPayments": foundProofInPayments,
                    "bank": bank,
                    "account": account,
                    "typeTransaction": typeTransaction,
                    "operation": operation,
                    "document": document
                }
                self._extractsOfFile.append(self._extractsOfLine.copy())
                self._extractsOfLine.clear()

        return self._extractsOfFile
Beispiel #25
0
    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()
Beispiel #26
0
    def process(self, file, numberFile):

        valuesOfLine = {}
        valuesOfFile = []

        try:
            with codecs.open(file) as fileobj:
                ofx = OfxParser.parse(fileobj, fail_fast=False)

            accountData = ofx.account

            try:
                institution = accountData.institution
                fid = int(institution.fid)
            except Exception:
                fid = 0

            bankId = int(accountData.routing_number)
            bankId = fid if fid == 82 else bankId
            bankName = funcoesUteis.returnBankForNumber(bankId) #self.returnNameBank(bankId)

            account = accountData.account_id
            account = str(account).replace('-', '')
            account = self.returnAccount(bankId, account)

            # shutil.copy(file, f'{self._wayOriginal}/ofx_organizados/{bankName}_{account}_{numberFile}.ofx')

            transactions = accountData.statement.transactions
            for transaction in transactions:
                typeTransaction = funcoesUteis.treatTextField(transaction.type)
                
                dateTransaction = transaction.date
                dateTransaction = datetime.datetime.date(dateTransaction)
                
                amount = funcoesUteis.treatDecimalField(transaction.amount)
                if amount < 0:
                    operation = '-'
                    amount *= -1
                else:
                    operation = '+'

                if operation == "+":
                    historicCode = 24
                else:
                    historicCode = 78
                
                document = funcoesUteis.treatTextField(transaction.checknum)

                historic = funcoesUteis.treatTextField(transaction.memo)
                # ignora lancamentos no extrato como saldo parcial, pq nao é um lançamento em si
                if historic == 'SALDO' or historic.find('SALDO PARCIAL') >= 0 or historic.find('SALDO INICIAL') >= 0 \
                    or historic.find('SALDO FINAL') >= 0 or historic.find('SALDO APLIC') >= 0 or historic.find('SALDO A LIBERAR') >= 0 \
                    or historic.find('SDO CTA') >= 0 or historic.find('SALDO') >= 0:
                    continue

                valuesOfLine = {
                    "bank": bankName,
                    "account": account,
                    "typeTransaction": typeTransaction,
                    "dateTransaction": dateTransaction,
                    "amount": round(amount, 2),
                    "operation": operation,
                    "document": document,
                    "historicCode": historicCode,
                    "historic": historic,
                    "wayFile": file
                }

                valuesOfFile.append(valuesOfLine.copy())
        except Exception as e:
            print(file, e)
            pass
        
        return valuesOfFile
Beispiel #27
0
    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()
Beispiel #28
0
    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()
Beispiel #29
0
    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()
Beispiel #30
0
    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