This commit is contained in:
Kenio 2025-11-16 11:29:45 -03:00
parent fe7bb3545f
commit 2b24a5e25c

View file

@ -24,11 +24,11 @@ def _remove_source_code(item: Dict) -> Dict:
"""
item_copy = item.copy()
# Verifica as chaves comuns (maioria dos bancos retorna em maiúsculas, mas o JSON pode ter minúsculas)
# Verifica as chaves comuns
if 'SOURCE_CODE' in item_copy:
del item_copy['SOURCE_CODE']
if 'source_code' in item_copy: # Tratamento para o caso reportado (minúsculas)
if 'source_code' in item_copy:
del item_copy['source_code']
return item_copy
@ -38,6 +38,7 @@ def _remove_source_code(item: Dict) -> Dict:
def compare_fields(standard_fields: List[Dict], client_fields: List[Dict], table_name: str) -> List[Dict]:
"""
Compara os campos de uma tabela entre as estruturas padrão e cliente.
(Mantida sem alteração, pois 'SOURCE_CODE' não é campo de tabela).
"""
discrepancies = []
@ -81,7 +82,7 @@ def compare_fields(standard_fields: List[Dict], client_fields: List[Dict], table
return discrepancies
# --- FUNÇÃO PRINCIPAL DE COMPARAÇÃO DE ESTRUTURAS ---
# --- FUNÇÃO PRINCIPAL DE COMPARAÇÃO DE ESTRUTURAS (ADICIONANDO ELEMENTOS ENCONTRADOS) ---
def compare_structures(standard_structure: Dict[str, Any], client_structure: Dict[str, Any]) -> Dict[str, Any]:
@ -97,7 +98,9 @@ def compare_structures(standard_structure: Dict[str, Any], client_structure: Dic
"tabelas_padrao": [],
"tabelas_cliente": [],
"outros_elementos": []
}
},
# NOVO CAMPO: Retorna os elementos que foram comparados e são idênticos/existentes
"elementos_encontrados_e_comparados": {}
}
if not standard_structure or not client_structure:
@ -125,7 +128,7 @@ def compare_structures(standard_structure: Dict[str, Any], client_structure: Dic
if is_ignored(table_name):
audit_log["elementos_ignorados"]["tabelas_padrao"].append({
"identificador": table_name,
"estrutura_completa": _remove_source_code(t) # Limpeza de SOURCE_CODE
"estrutura_completa": _remove_source_code(t)
})
elif table_name:
standard_tables_filtered.append(t)
@ -134,6 +137,7 @@ def compare_structures(standard_structure: Dict[str, Any], client_structure: Dic
client_tables_map = {}
malformed_tables_data = []
tables_found_and_compared = [] # Lista temporária para tabelas encontradas
for t in client_structure.get('tables', []):
table_name = t.get('TABLE_NAME')
@ -141,13 +145,20 @@ def compare_structures(standard_structure: Dict[str, Any], client_structure: Dic
if is_ignored(table_name):
audit_log["elementos_ignorados"]["tabelas_cliente"].append({
"identificador": table_name,
"estrutura_completa": _remove_source_code(t) # Limpeza de SOURCE_CODE
"estrutura_completa": _remove_source_code(t)
})
elif table_name:
client_tables_map[table_name] = t
if table_name in standard_tables_map:
# Adiciona a tabela do padrão na lista de encontradas (sem SOURCE_CODE)
tables_found_and_compared.append(_remove_source_code(standard_tables_map[table_name]))
else:
malformed_tables_data.append(t)
if tables_found_and_compared:
# Armazena as tabelas encontradas
audit_log["elementos_encontrados_e_comparados"]["tabelas"] = tables_found_and_compared
if malformed_tables_data:
audit_log["discrepancias_encontradas"] = True
audit_log["detalhes"]["estrutura_malformada_cliente"] = {
@ -191,7 +202,7 @@ def compare_structures(standard_structure: Dict[str, Any], client_structure: Dic
"origem": "padrao",
"tipo": element_key,
"identificador": identifier,
"estrutura_completa": _remove_source_code(item) # Limpeza de SOURCE_CODE
"estrutura_completa": _remove_source_code(item)
})
else:
standard_elements_filtered.append(item)
@ -204,13 +215,23 @@ def compare_structures(standard_structure: Dict[str, Any], client_structure: Dic
"origem": "cliente",
"tipo": element_key,
"identificador": identifier,
"estrutura_completa": _remove_source_code(item) # Limpeza de SOURCE_CODE
"estrutura_completa": _remove_source_code(item)
})
else:
client_elements_filtered.append(item)
# Criação de Sets a partir dos elementos normalizados (sem SOURCE_CODE)
standard_elements_normalized = [_remove_source_code(item) for item in standard_elements_filtered]
# Mapeamento para buscar o original em caso de match
# Usamos o dump do elemento limpo (sem source code) como chave
standard_map_normalized = {}
standard_elements_normalized = []
for item in standard_elements_filtered:
normalized_item = _remove_source_code(item)
standard_elements_normalized.append(normalized_item)
# Mapeia o item normalizado para o item original (ainda sem source code, para evitar duplicação)
standard_map_normalized[json.dumps(normalized_item, sort_keys=True)] = normalized_item
client_elements_normalized = [_remove_source_code(item) for item in client_elements_filtered]
try:
@ -222,7 +243,15 @@ def compare_structures(standard_structure: Dict[str, Any], client_structure: Dic
continue
missing_elements = standard_set - client_set
found_elements = standard_set & client_set # Interseção dos sets
# 3. Adiciona os elementos encontrados à nova chave
if found_elements:
audit_log["elementos_encontrados_e_comparados"][element_key] = [
standard_map_normalized[found_str] for found_str in found_elements
]
# 4. Adiciona os elementos faltantes
if missing_elements:
audit_log["discrepancias_encontradas"] = True
@ -252,7 +281,7 @@ class ShowDatabaseService:
for key in keys_to_clean:
if key in cleaned and isinstance(cleaned[key], list):
# Aplica a limpeza a cada item da lista usando a função helper _remove_source_code
# Aplica a limpeza a cada item da lista
cleaned[key] = [_remove_source_code(item) for item in cleaned[key]]
# Garante que, se houver campos (FIELDS) aninhados, eles também sejam limpos
@ -305,10 +334,10 @@ class ShowDatabaseService:
"db_accessible": database_data.get("db_accessible", {}),
"last_modified": database_data.get("last_modified", {}),
# --- CAMPOS DE DEBUG (AGORA TOTALMENTE FILTRADOS) ---
# --- CAMPOS DE DEBUG (FILTRADOS) ---
"estrutura_cliente_debug": debug_cliente,
"estrutura_padrao_debug": debug_padrao,
# ----------------------------------------------------
# ------------------------------------
"auditoria_do_banco": auditoria_do_banco
}