예제 #1
0
    def noteIsAnAsset(self, notesProducts, notes):
        with open(notesProducts) as products:
            data = json.load(products)
            for product in data:
                if str(product['cfop_mep']) in ('1556', '2556', '1407',
                                                '2407'):
                    for nameProduct in self._namesProductsBase:
                        nameProduct = removerAcentosECaracteresEspeciais(
                            nameProduct[0]).upper()

                        nameProductSystem = removerAcentosECaracteresEspeciais(
                            product['desc_pdi']).upper()
                        if nameProductSystem.find(nameProduct) > 0:

                            dataEmp = self.returnDataEmp(product['codi_emp'])
                            dataNote = self.returnDataNote(
                                notes, product['codi_emp'],
                                product['codi_ent'])

                            dateEntrada = transformaCampoDataParaFormatoBrasileiro(
                                retornaCampoComoData(dataNote['dent_ent'], 2))
                            dateEmissao = transformaCampoDataParaFormatoBrasileiro(
                                retornaCampoComoData(dataNote['ddoc_ent'], 2))

                            print(
                                f"- Processando empresa {product['codi_emp']} - {dataEmp['name_emp']}"
                            )

                            self._exportNotas.write(
                                f"{product['codi_emp']};"
                                f"{dataEmp['name_emp']};"
                                f"'{dataEmp['cnpj_emp']};"
                                f"{dataNote['codi_ent']};"
                                f"{dataNote['nume_ent']};"
                                f"{dataNote['codi_for']};"
                                f"{dataNote['nome_for']};"
                                f"{dateEmissao};"
                                f"{dateEntrada};"
                                f"{dataNote['codi_esp']};"
                                f"{dataNote['seri_ent']};"
                                f"{dataNote['codi_acu']};"
                                f"{dataNote['vcon_ent']};"
                                f"{str(product['codi_pdi']).strip()};"
                                f"{product['desc_pdi']};"
                                f"{product['cfop_mep']};"
                                f"{product['qtde_mep']};"
                                f"{product['valor_unit_mep']};"
                                f"{product['vlor_mep']};"
                                f"{product['bicms_mep']};"
                                f"{product['aliicms_mep']};"
                                f"{product['valor_icms_mep']};"
                                f"{product['bicmsst_mep']};"
                                f"{product['valor_subtri_mep']};"
                                f"\n")
예제 #2
0
    def entry6100(self, data):
        idRecord = '6100'
        user = ""
        branch = ""
        scp = ""
        historicCode = 0
        accountCodeDebit = 0
        accountCodeCredit = 0

        dateLivro = funcoesUteis.transformaCampoDataParaFormatoBrasileiro(funcoesUteis.analyzeIfFieldIsValid(data, "dateLivro"))
        movementType = funcoesUteis.analyzeIfFieldIsValid(data, "movementType")
        accountCode = funcoesUteis.analyzeIfFieldIsValid(data, "accountCode")
        historic = funcoesUteis.analyzeIfFieldIsValid(data, "historic")

        amount = funcoesUteis.analyzeIfFieldIsValid(data, "amount")
        amount = str(amount).replace('.', ',')   

        if movementType == "RECEITAS":
            accountCodeDebit = 5
            accountCodeCredit = accountCode
        elif movementType == "DESPESAS":
            accountCodeDebit = accountCode
            accountCodeCredit = 5

        return f"{idRecord}|{dateLivro}|{accountCodeDebit}|{accountCodeCredit}|{amount}|{historicCode}|{historic}|{user}|{branch}|{scp}|\n"
예제 #3
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}')
예제 #4
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")
예제 #5
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
    def returnDataInstallmentsEntryNote(self,
                                        dueDate=None,
                                        note=0,
                                        cgceProvider=None,
                                        ddoc_ent=None,
                                        dent_ent=None,
                                        amountPayment=0.0,
                                        amountOriginal=0.0):
        if dueDate is None:
            return None  # se a data de vencimento for nula já nem processa o resto

        if note == "" or note is None:
            note = 0
        if cgceProvider == "":
            cgceProvider = None
        if ddoc_ent == "":
            ddoc_ent = None
        if dent_ent == "":
            dent_ent = None

        # se o vencimento for nulo já nem percorre os dados
        if dueDate is None:
            return None

        for installment in self._installments:
            provider = self.returnDataProvider(installment["codi_for"])

            dueDateEntryNote = funcoesUteis.transformaCampoDataParaFormatoBrasileiro( \
                funcoesUteis.retornaCampoComoData(funcoesUteis.analyzeIfFieldIsValid(installment, "vcto_entp"), 2) )
            cgceProviderEntryNote = funcoesUteis.analyzeIfFieldIsValid(
                provider, "cgce_for", None)
            noteEntryNote = int(
                funcoesUteis.analyzeIfFieldIsValid(installment, "nume_ent", 0))
            issueEntryNote = funcoesUteis.transformaCampoDataParaFormatoBrasileiro( \
                funcoesUteis.retornaCampoComoData(funcoesUteis.analyzeIfFieldIsValid(installment, "ddoc_ent"), 2) )
            entryEntryNote = funcoesUteis.transformaCampoDataParaFormatoBrasileiro( \
                funcoesUteis.retornaCampoComoData(funcoesUteis.analyzeIfFieldIsValid(installment, "dent_ent"), 2) )
            amountInstallmentEntryNote = float(
                funcoesUteis.analyzeIfFieldIsValid(installment, "vlor_entp",
                                                   0.0))

            # o int é pra poder tirar o .0 de quando é exportado os dados
            note = funcoesUteis.treatNumberField(note, True)

            if note != 0:  # se a nota for válida compara os dados com ela, uma comparação no mínimo tem que ser igual, pq a se a nota tá preenchida ela tem que existir na domínio (mesmo número)
                if dueDateEntryNote == dueDate and noteEntryNote == note:
                    return installment
            else:
                if dueDateEntryNote == dueDate and cgceProviderEntryNote == cgceProvider:
                    return installment

                if dueDateEntryNote == dueDate and issueEntryNote == ddoc_ent and ddoc_ent is not None:
                    return installment

                if dueDateEntryNote == dueDate and entryEntryNote == dent_ent and dent_ent is not None:
                    return installment

                if dueDateEntryNote == dueDate and amountInstallmentEntryNote == amountOriginal and amountOriginal > 0:
                    return installment

                if dueDateEntryNote == dueDate and amountInstallmentEntryNote == amountPayment and amountPayment > 0:
                    return installment
    def returnDataEntryNote(self,
                            note=0,
                            cgceProvider=None,
                            ddoc_ent=None,
                            dent_ent=None,
                            amountPayment=0.0,
                            nameProvider=None,
                            dueDate=None,
                            amountOriginal=0.0):
        if note == "" or note is None:
            note = 0
        if cgceProvider == "":
            cgceProvider = None
        if ddoc_ent == "":
            ddoc_ent = None
        if dent_ent == "":
            dent_ent = None
        if dueDate == "":
            dueDate = None
        if nameProvider == "":
            nameProvider = None

        note = funcoesUteis.treatNumberField(note, True)

        if note == 0 and ddoc_ent is None and dent_ent is None and cgceProvider is None and nameProvider is None:
            return None

        wayFiles = os.path.join(fileDir,
                                f'{folderExtractDatabaseAccount}/entradas/',
                                str(self._codiEmp))

        for root, dirs, files in os.walk(wayFiles):
            for file in sorted(files, reverse=True):
                if file.lower().endswith(('.json')):
                    competenceFile = funcoesUteis.retornaCampoComoData(
                        f'{file[0:4]}-{file[4:6]}-01', 2)
                    if competenceFile > self._finalDate:
                        continue

                    wayFile = os.path.join(root, file)
                    entryNotes = readJson(wayFile)

                    for entryNote in entryNotes:
                        provider = self.returnDataProvider(
                            entryNote["codi_for"])

                        cgceProviderEntryNote = funcoesUteis.analyzeIfFieldIsValid(
                            provider, "cgce_for", None)
                        nameProviderEntryNote = funcoesUteis.analyzeIfFieldIsValid(
                            provider, "nome_for", None)
                        noteEntryNote = int(
                            funcoesUteis.analyzeIfFieldIsValid(
                                entryNote, "nume_ent", 0))
                        issueEntryNote = funcoesUteis.transformaCampoDataParaFormatoBrasileiro( \
                            funcoesUteis.retornaCampoComoData(funcoesUteis.analyzeIfFieldIsValid(entryNote, "ddoc_ent"), 2) )
                        entryEntryNote = funcoesUteis.transformaCampoDataParaFormatoBrasileiro( \
                            funcoesUteis.retornaCampoComoData(funcoesUteis.analyzeIfFieldIsValid(entryNote, "dent_ent"), 2) )
                        amountAccountEntryNote = float(
                            funcoesUteis.analyzeIfFieldIsValid(
                                entryNote, "vcon_ent", 0.0))

                        if note != 0:  # se a nota for válida compara os dados com ela, uma comparação no mínimo tem que ser igual, pq a se a nota tá preenchida ela tem que existir na domínio (mesmo número)
                            if noteEntryNote == note and cgceProviderEntryNote == cgceProvider:
                                return entryNote

                            if noteEntryNote == note and issueEntryNote == ddoc_ent and ddoc_ent is not None:
                                return entryNote

                            if noteEntryNote == note and entryEntryNote == dent_ent and dent_ent is not None:
                                return entryNote

                            if noteEntryNote == note and issueEntryNote == dueDate and dueDate is not None:  # a comparação por vencimento e emissão é pq algumas vezes a data de vencimento é a própria emissão
                                return entryNote

                            if noteEntryNote == note and amountAccountEntryNote == amountOriginal and amountOriginal > 0:
                                return entryNote

                            if noteEntryNote == note and amountAccountEntryNote == amountPayment and amountPayment > 0:
                                return entryNote
                        else:  # se não tiver a nota olha outros pontos de apoios que não são tão confiáveis
                            if issueEntryNote == ddoc_ent and cgceProviderEntryNote == cgceProvider and ddoc_ent is not None:
                                return entryNote

                            if entryEntryNote == dent_ent and cgceProviderEntryNote == cgceProvider and dent_ent is not None:
                                return entryNote

                            if issueEntryNote == dueDate and cgceProviderEntryNote == cgceProvider and dueDate is not None:
                                return entryNote

                            if amountAccountEntryNote == amountOriginal and cgceProviderEntryNote == cgceProvider and amountOriginal > 0:
                                return entryNote

                            if amountAccountEntryNote == amountPayment and cgceProviderEntryNote == cgceProvider and amountPayment > 0:
                                return entryNote

                        # comparação pelo nome, caso as hipóteses acima não retorne nada
                        compareTwoWords = self.compareTwoNames(
                            nameProviderEntryNote, nameProvider)
                        if compareTwoWords[
                                "first7LettersEquals"] is True or compareTwoWords[
                                    "percentWordsEqualsAboutNameTwo"] >= 0.25:
                            if note != 0:  # se a nota for válida compara os dados com ela, uma comparação no mínimo tem que ser igual, pq a se a nota tá preenchida ela tem que existir na domínio (mesmo número)
                                if noteEntryNote == note:
                                    return entryNote
                            else:
                                if issueEntryNote == ddoc_ent and ddoc_ent is not None:
                                    return entryNote

                                if entryEntryNote == dent_ent and dent_ent is not None:
                                    return entryNote

                                if issueEntryNote == dueDate and dueDate is not None:
                                    return entryNote

                                if amountAccountEntryNote == amountOriginal and amountOriginal > 0:
                                    return entryNote

                                if amountAccountEntryNote == amountPayment and amountPayment > 0:
                                    return entryNote
예제 #8
0
    def process(self):
        valuesOfLine = {}

        isProofDefaultSispag = False

        nameProvider = ""
        namePayee = ""
        historic = ""
        dueDate = None
        cgcePaying = ""
        cnpjProvider = ""
        amountPaid = float(0)
        category = ""
        bank = "ITAU"
        account = ""

        for data in self._dataFile:

            data = str(data)
            dataSplit = data.split(':')

            fieldOne = funcoesUteis.treatTextField(funcoesUteis.analyzeIfFieldIsValidMatrix(dataSplit, 1))

            fieldTwo = funcoesUteis.treatTextField(funcoesUteis.analyzeIfFieldIsValidMatrix(dataSplit, 2))

            if fieldOne.count('COMPROVANTE DE OPERACAO') > 0:
                category = funcoesUteis.treatTextField(funcoesUteis.analyzeIfFieldIsValidMatrix(data.split('-'), 2))
            if fieldOne.count('PAGAMENTO COM CODIGO DE BARRAS') > 0:
                category = 'PAGTO COD BARRA'
            if fieldOne.count("PAGAMENTO DE CONCESSIONARIAS") > 0:
                category = 'PAGTO CONCESSIONARIA'
            if fieldOne.count("FGTS") > 0 or fieldOne.count("GRRF") > 0:
                category = 'PAGTO FGTS-GRRF'
            if fieldOne.count("GUIA DE RECOLHIMENTO") > 0:
                category = 'PAGTO GRF'
                historic = funcoesUteis.treatTextField(data)
            
            if fieldOne.count("IDENTIFICACAO NO EXTRATO") > 0:
                historic = fieldTwo

            if fieldOne.count('CONTA') > 0 and fieldOne.count('DEBITADA') > 0:
                self._accountDebitOrCredit = 'DEBIT'
            elif fieldOne.count('CONTA A SER CREDITADA') > 0 or fieldOne.count('DADOS DO PAGAMENTO') > 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 == "NOME DO FAVORECIDO":
                    nameProvider = fieldTwo
                    namePayee = nameProvider
                    
                if fieldOne == "INFORMACOES FORNECIDAS PELO PAGADOR":
                    historic = fieldTwo
                
                if fieldOne == "DATA DE VENCIMENTO":
                    dueDate = funcoesUteis.transformaCampoDataParaFormatoBrasileiro(funcoesUteis.retornaCampoComoData(fieldTwo))

                if ( fieldOne.count("CPF") > 0 or fieldOne.count("CNPJ") > 0 ) and fieldOne.count("PAGADOR") > 0:
                    cgcePaying = funcoesUteis.treatNumberField(fieldTwo)

                if ( fieldOne.count("CPF") > 0 or fieldOne.count("CNPJ") > 0 ) and fieldOne.count("PAGADOR") == 0:
                    cnpjProvider = funcoesUteis.treatNumberField(fieldTwo)

                if fieldOne.count("VALOR") > 0:
                    amountPaid = funcoesUteis.treatDecimalField(fieldTwo)

			# quando é pagamento de imposto não tem o nome do fornecedor, o dados vem na informação complementar
            if historic != "" and dueDate == "" and namePayee == "":
                nameProvider = historic

            # se o nome do fornecedor ainda for vazio, então considero a categoria como fornecedor
            if nameProvider == "" and category != "":
                nameProvider = category

            for valueOfLineDatePayment in self._valuesOfLineDatePayment:
                if data[0 : len(valueOfLineDatePayment) ] == valueOfLineDatePayment:
                    paymentDate = funcoesUteis.treatTextField(data[len(valueOfLineDatePayment)+1:len(valueOfLineDatePayment)+11])
                    paymentDate = funcoesUteis.retornaCampoComoData(paymentDate.replace('.', '/'))

                    if paymentDate is not None and amountPaid > 0:
                        valuesOfLine = {
                            "paymentDate": paymentDate,
                            "nameProvider": nameProvider,
                            "cgceProvider": cnpjProvider,
                            "dueDate": dueDate,
                            "bank": bank,
                            "account": account,
                            "amountPaid": round(amountPaid, 2),
                            "historic": historic,
                            "category": category,
                            "cgcePaying": cgcePaying,
                            "foundProof": True,
                            "amountPaidPerLote": round(amountPaid, 2),
                            "wayFile": self._file
                        }

                        return valuesOfLine.copy()
예제 #9
0
    def entry6100(self,
                  data,
                  typeData,
                  typeEntry='N',
                  isAmountPaidPerLote=False):
        # o typeData é pra identificar se é débito ou crédito
        # o typeEntry é pra identificar se é um lançamento de juros (J), multa (M), desconto (D) ou normal (N)
        # o isAmountPaidPerLote serve pra pegar o valor do lançamento em vez da chave 'amountPaid' pelo 'amountPaidPerLote'
        paymentOrExtract = self.isPaymentOrExtract(data)
        accountCodeDebit = ""
        accountCodeCredit = ""

        if paymentOrExtract == "E":
            exportDate = funcoesUteis.transformaCampoDataParaFormatoBrasileiro(
                funcoesUteis.analyzeIfFieldIsValid(data, "dateTransaction",
                                                   None))
            if typeData == 'D':
                accountCodeDebit = funcoesUteis.analyzeIfFieldIsValid(
                    data, "accountCodeDebit", "")
            else:
                accountCodeCredit = funcoesUteis.analyzeIfFieldIsValid(
                    data, "accountCodeCredit", "")
            amount = funcoesUteis.analyzeIfFieldIsValid(data, "amount", 0.0)
            amountFloat = amount
            amount = str(amount).replace('.', ',')
            historicCode = funcoesUteis.analyzeIfFieldIsValid(
                data, "historicCode", "")
            historic = funcoesUteis.analyzeIfFieldIsValid(data, "historic", "")

        elif paymentOrExtract == "P":
            exportDate = funcoesUteis.transformaCampoDataParaFormatoBrasileiro(
                funcoesUteis.analyzeIfFieldIsValid(data, "dateOfImport", None))
            amountPaid = funcoesUteis.analyzeIfFieldIsValid(
                data, "amountPaid", 0.0)
            amountPaidPerLote = funcoesUteis.analyzeIfFieldIsValid(
                data, "amountPaidPerLote", 0.0)
            amountPaidPerLoteOriginal = amountPaidPerLote
            if amountPaid < 0:  # quando negativo multipla por menos 1, geralmente são os descontos
                amountPaid *= -1
            if amountPaidPerLote < 0:
                amountPaidPerLote *= -1
            if isAmountPaidPerLote is True:
                amountPaid = amountPaidPerLote
            amountDiscount = funcoesUteis.analyzeIfFieldIsValid(
                data, "amountDiscount", 0.0)
            amountInterest = funcoesUteis.analyzeIfFieldIsValid(
                data, "amountInterest", 0.0)
            amountFine = funcoesUteis.analyzeIfFieldIsValid(
                data, "amountFine", 0.0)
            amountLiquid = amountPaid - amountInterest - amountFine + amountDiscount

            if typeEntry == 'N':
                if typeData == 'D':
                    accountCodeDebit = funcoesUteis.analyzeIfFieldIsValid(
                        data, "accountCode", "")
                    amount = amountLiquid
                else:
                    if isAmountPaidPerLote is True:
                        if amountPaidPerLoteOriginal < 0:  # se for o total do lote então o crédito é o banco se o valor for maior que zero, se não é débito
                            accountCodeDebit = funcoesUteis.analyzeIfFieldIsValid(
                                data, "accountCodeBank", "")
                        else:
                            accountCodeCredit = funcoesUteis.analyzeIfFieldIsValid(
                                data, "accountCodeBank", "")
                    else:  # se não for o total do lote e for lançamento de crédito então provavelmente são os descontos
                        accountCodeCredit = funcoesUteis.analyzeIfFieldIsValid(
                            data, "accountCode", "")
                    amount = amountPaid
                historicCode = funcoesUteis.analyzeIfFieldIsValid(
                    data, "historicCodePagamento", 0)
            elif typeEntry == 'J':
                accountCodeDebit = funcoesUteis.analyzeIfFieldIsValid(
                    data, "accountCodeInterest", 372)
                historicCode = funcoesUteis.analyzeIfFieldIsValid(
                    data, "historicCodeInterest", 26)
                amount = funcoesUteis.analyzeIfFieldIsValid(
                    data, "amountInterest", 0.0)
            elif typeEntry == 'M':
                accountCodeDebit = funcoesUteis.analyzeIfFieldIsValid(
                    data, "accountCodeFine", 352)
                historicCode = funcoesUteis.analyzeIfFieldIsValid(
                    data, "historicCodeFine", 25)
                amount = funcoesUteis.analyzeIfFieldIsValid(
                    data, "amountFine", 0.0)
            elif typeEntry == 'D':
                accountCodeCredit = funcoesUteis.analyzeIfFieldIsValid(
                    data, "accountCodeDiscount", 434)
                historicCode = funcoesUteis.analyzeIfFieldIsValid(
                    data, "historicCodeDiscount", 28)
                amount = funcoesUteis.analyzeIfFieldIsValid(
                    data, "amountDiscount", 0.0)

            amountFloat = amount
            amount = str(amount).replace('.', ',')

            document = funcoesUteis.analyzeIfFieldIsValid(data, "document")
            nameProvider = funcoesUteis.analyzeIfFieldIsValid(
                data, "nameProvider")

            accountPlan = funcoesUteis.analyzeIfFieldIsValid(
                data, "accountPlan")
            accountPlan = f" / {accountPlan}" if accountPlan != "" else ""

            historicTemp = funcoesUteis.analyzeIfFieldIsValid(data, "historic")
            historicTemp = f" / {historicTemp}" if historicTemp != "" else accountPlan

            historic = ""
            compositionHistoric = funcoesUteis.analyzeIfFieldIsValid(
                data, "compositionHistoric")
            compositionHistoricSplit = compositionHistoric.split('-')
            if compositionHistoric == "":
                if document != "" and document != "0":
                    historic = f"PAGAMENTO CFE. NF/DUP {document} REFERENTE {nameProvider}{historicTemp}"
                else:
                    historic = f"PAGAMENTO REFERENTE {nameProvider}{historicTemp}"
            else:
                for value in compositionHistoricSplit:
                    if value.find('historicCode') >= 0:
                        continue

                    historic += f'{funcoesUteis.analyzeIfFieldIsValid(data, value)} '
                historic = historic.strip()

            # mudo o histórico pois num pagamento em lote (diferentes fornecedores e mesmo banco) não pode vir a informação do fornecedor, pois cada pagamento é um diferente
            amountPaidOriginal = funcoesUteis.analyzeIfFieldIsValid(
                data, "amountPaid", 0.0)
            amountPaidPerLote = funcoesUteis.analyzeIfFieldIsValid(
                data, "amountPaidPerLote", 0.0)
            if isAmountPaidPerLote is True and amountPaidOriginal != amountPaidPerLote:
                historicCode = funcoesUteis.analyzeIfFieldIsValid(
                    data, "historicCodePagamento", 0)
                historic = "PAGAMENTO" if historicCode == 0 else ""

            # se não achar na configuração o código do histórico mas estiver configurado pra impotar histórico manipulado seta como zero
            if compositionHistoricSplit != "" and compositionHistoricSplit.count(
                    'historicCodePagamento') == 0 and typeEntry == 'N':
                historicCode = 0

        branch = funcoesUteis.analyzeIfFieldIsValid(data, "companyBranch",
                                                    self._codiEmp)

        idRecord = '6100'
        user = ""
        scp = ""
        historic = funcoesUteis.treatTextField(historic)

        if amountFloat > 0:
            return f"{idRecord}|{exportDate}|{accountCodeDebit}|{accountCodeCredit}|{amount}|{historicCode}|{historic}|{user}|{branch}|{scp}|\n"
        else:
            return ""
예제 #10
0
    def process(self, file):

        if self.isPaymentsLysPorData(file) is not True:
            return []

        dataFile = leXls_Xlsx(file)

        valuesOfLine = {}
        valuesOfFile = []
        posionsOfHeader = {}

        for data in dataFile:
            try:
                headerField = funcoesUteis.treatTextFieldInVector(data, 5)
                if headerField.count('IDPESSOACREDORA') > 0:
                    posionsOfHeader.clear()
                    for keyField, nameField in enumerate(data):
                        nameField = funcoesUteis.treatTextField(nameField)
                        posionsOfHeader[nameField] = keyField
                    continue

                idAccountPaid = funcoesUteis.treatTextFieldInVector(
                    data, 1, posionsOfHeader, "idsContaPagar")
                parcelNumber = funcoesUteis.treatTextFieldInVector(
                    data, 2, posionsOfHeader, "cdParcela")
                dueDate = funcoesUteis.transformaCampoDataParaFormatoBrasileiro(
                    funcoesUteis.treatDateFieldInVector(
                        data, 4, posionsOfHeader, "dtVencimento"))
                nameProvider = funcoesUteis.treatTextFieldInVector(
                    data, 6, posionsOfHeader, "nmPessoaCredora")
                document = funcoesUteis.treatTextFieldInVector(
                    data, 11, posionsOfHeader, "nrDocFiscalOriginal")
                issueDate = funcoesUteis.transformaCampoDataParaFormatoBrasileiro(
                    funcoesUteis.treatDateFieldInVector(
                        data, 12, posionsOfHeader, "dtEmissao"))
                amountPaid = funcoesUteis.treatDecimalFieldInVector(
                    data, 36, posionsOfHeader, "valorLiquido")
                amountDiscount = funcoesUteis.treatDecimalFieldInVector(
                    data, 19, posionsOfHeader, "valordesconto")
                amountInterest = funcoesUteis.treatDecimalFieldInVector(
                    data, 20, posionsOfHeader, "valormulta")
                amountFine = funcoesUteis.treatDecimalFieldInVector(
                    data, 30, posionsOfHeader, "valorjuro")
                amountOriginal = funcoesUteis.treatDecimalFieldInVector(
                    data, 10)
                historic = funcoesUteis.treatTextFieldInVector(
                    data, 34, posionsOfHeader, "justificaticaDaConta")

                paymentsMoeda = self.returnDataPaymentsPorMoeda(idAccountPaid)

                paymentDate = funcoesUteis.analyzeIfFieldIsValid(
                    paymentsMoeda, "paymentDate", None)
                bank = funcoesUteis.analyzeIfFieldIsValid(
                    paymentsMoeda, "bank")
                accountBank = funcoesUteis.analyzeIfFieldIsValid(
                    paymentsMoeda, "accountBank")
                accountCode = funcoesUteis.analyzeIfFieldIsValid(
                    paymentsMoeda, "accountCode")

                if paymentDate is not None and amountPaid > 0:
                    valuesOfLine = {
                        "document": document,
                        "parcelNumber": parcelNumber,
                        "nameProvider": nameProvider,
                        "paymentDate": paymentDate,
                        "dueDate": dueDate,
                        "issueDate": issueDate,
                        "bank": bank,
                        "account": accountBank,
                        "amountPaid": amountPaid,
                        "amountDiscount": amountDiscount,
                        "amountInterest": amountInterest,
                        "amountFine": amountFine,
                        "amountOriginal": amountOriginal,
                        "accountCodeOld": accountCode,
                        "historic": historic
                    }

                    valuesOfFile.append(valuesOfLine.copy())
            except Exception:
                pass
        return valuesOfFile