DocBits- IDP for Infor ERP
HomeAppStatusAPI
🇵🇹 Português
🇵🇹 Português
  • Visão geral e noções básicas
    • DocBits
      • Principais Recursos do DocBits
    • Arquitetura
      • DocBits Informações sobre Cliente On-Premise
      • Certificações
    • Infraestrutura Infor
  • Notas de versão
  • Secção Utilizador Final e Parceiro
    • Secção Utilizador Final
      • Painel
        • Ferramentas do Painel
        • Fusão de Documentos
        • Status do Documento
        • Filtrando Documentos
        • Visão Geral dos Documentos Enviados
        • Contador de Tarefas
        • Campos Extraídos Validados
        • Fluxo de Documentos
        • Solução de Problemas
        • Atalhos de Teclado
      • Tarefas
      • Painel de Envio Antecipado
      • Painel de pedidos de compra
      • Painel de Faturas
      • Painel de Pedidos de Envio
      • Opções de Configuração do Usuário
      • Tabela de IA
        • Tags de Tabela de IA
      • Tela de Validação
        • Dados Fuzzy
        • Códigos QR
        • Atalhos de Teclado
      • Propósito e Uso
      • Correspondência de Pedido de Compra
        • Correspondência Automática de Dados de Pedido de Compra
        • Mapa de Número de Item do Fornecedor
        • Atalhos de Teclado
      • Contabilização de Fatura de Custo e Vendas Indiretas
      • Como Importar Documentos
        • FTP
        • Importação Manual
        • Webhook
        • Email
          • IMAP
          • OAuth Office365
      • Suporte Técnico no DocBits
        • Criar um ticket
        • Ícones de Ajuda
      • Curso
        • Introdução
        • Painel
        • Documentos Validados
        • Tabela de IA
        • Master PO Matching com DocBits
      • Nosso Sistema de Prioridade de Documentos
      • Portal do Fornecedor
        • Registro de Fornecedor
        • Status do Fornecedor
      • Recursos e suporte
        • Suporte ao Usuário
    • Seção de Parceiros
      • Teste de Automação de Faturas com DocBits
  • Administração e configuração
    • Configurações
      • Global Settings
        • Informações da Empresa
          • Definindo a Cor do App nas Configurações da Empresa
        • Custom Filters
        • Document Expiry
        • Document Types
          • Layout Manager
            • Navegando no Gerenciador de Layout
          • Document Sub Types
          • Table Columns
          • Fields
            • Adicionando e Editando Campos
          • Model Training
          • Regex
          • Script
          • EDI
          • More Settings
            • Propósito e uso
            • Melhores práticas
            • Resolução de Problemas
            • Tratamento de Documentos Duplicados
            • Selo de Aprovação
            • Mapa de Números de Itens do Fornecedor - Documentação do Administrador
            • Configurações de tolerância de pedido de compra / Tolerância adicional de pedido de compra
            • Status de desativação de pedido de compra
            • Tabela de PO no Construtor de Layout
            • Verificação automática de atualizações de PO
            • Calcular preço unitário do PO
            • Exportar linhas de PO não correspondidas
          • e-docs
            • eSLOG 1.6 i 2.0
        • Notificação por Email
          • Configurando Notificações
          • Gerenciando Notificações
          • Melhores Práticas
          • Solução de Problemas
        • Custom Filters
        • Groups, Users and Permissions
          • Usuários
            • Modificando Detalhes do Usuário
            • Privilégios de Administrador
          • Suborganizações
            • Como criar uma Sub-Organização
          • Grupos e Permissões
            • Propósito e Uso
            • Adicionando/Editando Grupos
            • Ativando Permissões
            • Controle de Acesso
            • Resolução de Problemas
        • Integração
          • API Calls and Examples
        • Painel de Controle
      • Processamento de documentos
        • Documents Expiry
        • Import
        • Gerenciador de Regras
        • Ocr Settings
        • Classificação e extração
          • Extração de tabela para elemento de custo
          • Extração automática do código tributário
        • Master Data Lookup
        • List Of Values
        • Export
        • Module
          • Modo de Anotação
          • Approval Before Export
          • Doc Scan
          • Doc Script
          • Atualizador de ACL do IDM
          • Swiss QR Code
        • Árvores de Decisão
      • Log Settings
        • Gerenciamento de Tarefas
        • Sincronização de Dados
      • Licenças da API
      • Configuração do Fornecedor
        • Configurações Gerais do Fornecedor
        • Edição de Modelos de Email
        • Configuração de exportação para o Portal do Fornecedor para M3
      • Gerenciamento de Cache
    • Fluxo de Trabalho
      • When
        • Card description
        • Document Operator for Sub-Organizations
        • Document Type Operation
      • And
        • Assigned User Condition
        • Checkbox Field Condition
        • Checkbox
        • Combined Price of Quantity Difference
        • Compare two fields
        • Compare with Purchase Order
        • Confirmed Delivery Date
        • Docfield is
        • Document Field Comparison
        • Document Field
        • Document Status Condition List
        • Document Type Operation one of
        • In Order Confirmation Purchase Order
        • Single Assigned User Condition
        • Single Document Status Condition
        • Supplier on Invoice
        • Text in field
        • Unit Price Combined with Fields
      • Then
      • Workflow Description: Conditional Export Trigger
      • Workflow Documentation
      • Standard Workflow
        • Above Max Amount
        • Cost Invoice - Export
        • Less than Max Amount
        • Purchase Invoice - 2nd Approval Quantity Export
        • Purchase Invoice - 2nd Approval Quantity
        • Purchase Invoice - 2nd Approval Unit Price Export
        • Purchase Invoice - 2nd Approval Unit Price
      • Material Ordering and Processing Workflow
    • Setup
      • Document Types
        • EDI Data Transformation Process
        • Layout Builder
        • Origin Layouts
        • Regex Manager
      • Document Training
        • Training Header Fields
        • Training Line Fields/Table Training
          • Adding New Columns
          • Advanced Settings
          • Defining Tables and Columns
          • Grouping Function
          • Manual Row Selection
          • Mapping Columns
          • Save and Delete Rules
      • SSO Configuration
      • Testing
        • PO Matching
        • Auto Accounting
          • LN
          • M3
      • Portal do Fornecedor
      • Instalação do WatchDog
  • Integração e configuração Infor
    • Importing Master Data
      • Field Mappings
      • LN
        • Auto Accounting
        • Suppliers and Purchase Orders
        • Tax Codes
      • M3
        • Auto Accounting
        • Suppliers and Purchase Orders
        • Extração de tabela para elemento de custo
    • Exporting in DocBits
      • Export Module
    • Exporting to INFOR
      • Creating a BOD Mapping File
      • Criando um Arquivo de Mapeamento IDM
      • Creating an ION API Endpoint
      • Creating an ION API File
      • Export to M3 Mapping (API)
      • Exporting to IDM
      • M3
        • M3 Configuration
      • LN
        • Exportar códigos fiscais para LN
        • LN Configuration
  • Funções e ferramentas avançadas
    • Scripting em DocBits
      • Calculating Total Charges Script for Docbits
      • Calculating Total Charges Script for Docbits
      • Delete lines with empty quantity and amount
      • Formatting Export Certificate Reference Numbers Script for Docbits
      • Funções
      • Generating Extended Invoice Numbers Script for Docbits
      • Generating Extended Invoice Numbers Script for Docbits
    • Postman for DocBits
    • Importando Dados de Fornecedor e Pedido de Compra no DocBits a partir de Arquivos CSV
Powered by GitBook
On this page

Was this helpful?

Edit on GitHub
Export as PDF
  1. Funções e ferramentas avançadas
  2. Scripting em DocBits

Delete lines with empty quantity and amount

Part 1: Delete Lines with Empty Quantity and Amount

This section of the script processes an invoice table to remove any lines where both the quantity and the total amount are zero or not provided.

  • Check for INVOICE_TABLE: It starts by checking if the INVOICE_TABLE key exists in the tables_dict dictionary.

  • Iterate Over Rows: For each row in the table, the script initializes flags and variables to determine if the TOTAL_AMOUNT and QUANTITY columns exist and to capture their values.

  • Check Column Names: As it iterates through each column in a row, it looks for columns named TOTAL_AMOUNT and QUANTITY.

    • If TOTAL_AMOUNT is found, it captures the value. If this value is non-zero, it converts it to a float.

    • Similarly for QUANTITY, capturing and converting the value if it is non-zero.

  • Mark Row for Deletion: After checking both columns in a row, if both the total amount and quantity are effectively zero (either by being zero or not existing), the row is marked for deletion by setting row['is_deleted'] to True.

Part 2: Validate Line Total Against Invoice Total

This section calculates the total amount from all lines in an invoice and compares it to the invoice’s reported total to validate their consistency.

  • Initialize Line Total: Starts by setting a variable lines_total to 0.0 to accumulate the total amount from all lines.

  • Sum Line Amounts: Iterates over each row in the INVOICE_TABLE, extracting the TOTAL_AMOUNT from each and adding it to lines_total.

  • Retrieve and Convert Invoice Total: Fetches the total invoice amount using a helper function get_field_value and converts it to a float.

  • Compare Totals: Finally, it checks if the absolute difference between the calculated line total (lines_total) and the reported invoice total (total_amount) exceeds a threshold of 0.05. If so, it marks the invoice total field as invalid using another helper function set_field_as_invalid, citing a mismatch.

##################################################
# Delete lines with empty quantity and amount 
##################################################


if tables_dict.get('INVOICE_TABLE'):
    for row in tables_dict['INVOICE_TABLE']['rows']:
        amount_col_found = False
        quantity_col_found = False
        line_amount = 0.0
        line_quantity = 0.0
        for col in row['columns']:
            if col['name'] == 'TOTAL_AMOUNT':
                amount_col_found = True
                line_amount = col.get('value', 0)
                if line_amount:
                    line_amount = float(line_amount)
            if col['name'] == 'QUANTITY':
                quantity_col_found = True
                line_quantity = col.get('value', 0)
                if line_quantity:
                    line_quantity = float(line_quantity)
            if amount_col_found and quantity_col_found:
                break
        if amount_col_found and quantity_col_found and (not line_amount and not line_quantity or (line_amount + line_quantity) == 0):
            row['is_deleted'] = True
        
##################################################
# End: Delete lines with empty quantity and amount 
##################################################

##################################################
# Validating Line total againg invoice total
##################################################
lines_total = 0.0
# Getting Lines Total
if tables_dict.get('INVOICE_TABLE'):
    for row in tables_dict['INVOICE_TABLE']['rows']:
        line_amount = 0.0
        for col in row['columns']:
            if col['name'] == 'TOTAL_AMOUNT':
                line_amount = col.get('value', 0)
                if line_amount:
                    line_amount = float(line_amount)
                break
        lines_total += line_amount

# Getting Invoice total
total_amount = get_field_value(fields_dict, "net_amount", "0.0")
if total_amount:
    total_amount = float(total_amount)

# Comparing lines total with invoice total    
if abs(total_amount - lines_total) > 0.05:
    set_field_as_invalid(fields_dict, "net_amount", "Invoice total mismatches lines total", "AMOUNTS_MISMATCH")

##################################################
# End: Validating Line total againg invoice total
##################################################






    

Summary

The script effectively ensures data integrity by:

  1. Removing data rows that do not contribute to the invoice’s financial total due to lacking quantities or amounts.

  2. Validating the consistency between the sum of individual line amounts and the overall invoice total, highlighting discrepancies for further action.

This automation helps maintain accurate financial records and can be crucial for systems like ERP that require precise data for accounting and financial reporting.

PreviousCalculating Total Charges Script for DocbitsNextFormatting Export Certificate Reference Numbers Script for Docbits

Last updated 1 year ago

Was this helpful?