argos-cli 0.3.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. argos/__init__.py +5 -0
  2. argos/__main__.py +4 -0
  3. argos/adapters/__init__.py +9 -0
  4. argos/adapters/_libreoffice_worker.py +111 -0
  5. argos/adapters/ai.py +1506 -0
  6. argos/adapters/ai_remote.py +654 -0
  7. argos/adapters/attachment_conversion.py +132 -0
  8. argos/adapters/capabilities.py +31 -0
  9. argos/adapters/chart_render.py +72 -0
  10. argos/adapters/docx_pdf.py +2953 -0
  11. argos/adapters/limesurvey.py +1079 -0
  12. argos/adapters/model_call.py +274 -0
  13. argos/adapters/report_publication.py +1530 -0
  14. argos/adapters/url_fetch.py +146 -0
  15. argos/adapters/xlsx.py +454 -0
  16. argos/analytics.py +731 -0
  17. argos/assets.py +257 -0
  18. argos/audit_result.py +369 -0
  19. argos/booleans.py +105 -0
  20. argos/catalog.py +1205 -0
  21. argos/cli.py +606 -0
  22. argos/contracts.py +532 -0
  23. argos/core.py +325 -0
  24. argos/default_skills/README.md +23 -0
  25. argos/default_skills/criar-matriz-planejamento/SKILL.md +200 -0
  26. argos/default_skills/elaborar-survey-limesurvey/SKILL.md +106 -0
  27. argos/default_skills/operar-argos/SKILL.md +74 -0
  28. argos/default_skills/verificar-diretrizes-fiscalizacao/SKILL.md +129 -0
  29. argos/default_skills/verificar-diretrizes-fiscalizacao/assets/relatorio-avaliacao.md +54 -0
  30. argos/default_skills/verificar-diretrizes-fiscalizacao/references/contrato-saidas.md +36 -0
  31. argos/default_skills/verificar-diretrizes-fiscalizacao/references/papeis-das-pastas.md +37 -0
  32. argos/default_skills/verificar-diretrizes-fiscalizacao/references/roteiro-verificacoes.md +27 -0
  33. argos/default_skills/verificar-diretrizes-fiscalizacao/scripts/avaliacao.py +253 -0
  34. argos/engines/__init__.py +3 -0
  35. argos/engines/adjustments.py +571 -0
  36. argos/engines/analytics.py +195 -0
  37. argos/engines/audit.py +2730 -0
  38. argos/engines/evaluation.py +6088 -0
  39. argos/engines/index.py +1683 -0
  40. argos/engines/matrix.py +5736 -0
  41. argos/engines/matrix_html.py +698 -0
  42. argos/engines/model_request.py +201 -0
  43. argos/engines/report_document.py +137 -0
  44. argos/engines/reports.py +1200 -0
  45. argos/engines/survey.py +4445 -0
  46. argos/envfile.py +53 -0
  47. argos/errors.py +29 -0
  48. argos/evidence_staging.py +293 -0
  49. argos/executions.py +565 -0
  50. argos/findings_matrix.py +2549 -0
  51. argos/fingerprints.py +487 -0
  52. argos/index_dsl.py +2100 -0
  53. argos/matrix_markdown.py +475 -0
  54. argos/matrix_widths.py +280 -0
  55. argos/pipeline.py +1745 -0
  56. argos/products.py +220 -0
  57. argos/progress.py +221 -0
  58. argos/project.py +608 -0
  59. argos/report_config.py +158 -0
  60. argos/resources/ESPECIFICACAO_MARKDOWN_MATRIZ_ACHADOS.md +539 -0
  61. argos/resources/ESPECIFICACAO_MARKDOWN_MATRIZ_PLANEJAMENTO.md +1000 -0
  62. argos/resources/ESPECIFICACAO_UNIFICADA_MATRIZES_V1_3.md +1142 -0
  63. argos/resources/anexo-evidencias-base.docx +0 -0
  64. argos/resources/argos-index-dsl-v1.schema.json +539 -0
  65. argos/resources/argos-report-config-v1.schema.json +113 -0
  66. argos/resources/diretrizes-projeto.md +476 -0
  67. argos/resources/env.example +37 -0
  68. argos/resources/exemplos/matriz_achados_boilerplate.md +61 -0
  69. argos/resources/exemplos/matriz_achados_draft.md +106 -0
  70. argos/resources/exemplos/matriz_achados_larguras_v1_3.md +114 -0
  71. argos/resources/exemplos/matriz_achados_v1_3.md +107 -0
  72. argos/resources/exemplos/matriz_planejamento_boilerplate.md +64 -0
  73. argos/resources/exemplos/matriz_planejamento_larguras_v1_3.md +115 -0
  74. argos/resources/exemplos/matriz_planejamento_v1_3.md +108 -0
  75. argos/resources/template-base-estilos-sigiloso.docx +0 -0
  76. argos/resources/template-base-estilos.docx +0 -0
  77. argos/resources/template-matriz-planejamento.docx +0 -0
  78. argos/resources/template-relatorio-consolidado-comum.docx +0 -0
  79. argos/resources/template-relatorio-consolidado-institucional.docx +0 -0
  80. argos/response_profiles.py +856 -0
  81. argos/scheduler.py +142 -0
  82. argos/status.py +367 -0
  83. argos/store.py +1228 -0
  84. argos/survey_collection.py +832 -0
  85. argos/telemetry.py +84 -0
  86. argos/tui.py +1262 -0
  87. argos/tui.tcss +827 -0
  88. argos/tui_models.py +466 -0
  89. argos/tui_path.py +155 -0
  90. argos/tui_widgets.py +482 -0
  91. argos/version.py +3 -0
  92. argos_cli-0.3.1.dist-info/METADATA +570 -0
  93. argos_cli-0.3.1.dist-info/RECORD +96 -0
  94. argos_cli-0.3.1.dist-info/WHEEL +5 -0
  95. argos_cli-0.3.1.dist-info/entry_points.txt +2 -0
  96. argos_cli-0.3.1.dist-info/top_level.txt +1 -0
argos/engines/audit.py ADDED
@@ -0,0 +1,2730 @@
1
+ """Verificação de mapas, regras de achados, resultados e impactos de auditoria."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ from copy import deepcopy
7
+ import json
8
+ import math
9
+ import re
10
+ from dataclasses import dataclass, field as dataclass_field, replace
11
+ from pathlib import Path
12
+ from typing import Any, Callable, Iterable, Mapping
13
+
14
+ from ..booleans import normalize, parse_bool
15
+ from ..core import InputValidationError, MissingInputError, OperationContext, OperationResult, ProductDraft, sha256_file, with_params as _with_params
16
+ from ..contracts import canonical_json, sha256_bytes
17
+ from .. import audit_result as formato_resultado
18
+ from ..adapters.xlsx import audit_table_bytes, find_column, openpyxl_workbook, require_file, sheet_records, workbook_summary
19
+ from .evaluation import chave
20
+
21
+
22
+ AtomValidator = Callable[[str], None]
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class LogicNode:
27
+ """Nó imutável da expressão compilada.
28
+
29
+ ``kind`` ∈ {"empty", "atom", "not", "and", "or"}; ``children`` carrega os
30
+ operandos e ``atom`` o texto opaco do átomo.
31
+ """
32
+
33
+ kind: str
34
+ children: tuple["LogicNode", ...] = ()
35
+ atom: str = ""
36
+
37
+
38
+ def _canonical_spacing(text: str) -> str:
39
+ """Normaliza o espaçamento dos operadores lógicos para um espaço único."""
40
+ return re.sub(r"\s*([|&])\s*", r" \1 ", text)
41
+
42
+
43
+ def _is_marker_open(text: str, index: int) -> bool:
44
+ """``(`` parte de um marcador de alternativa (``(c) texto``), não grupo.
45
+
46
+ Letra, ``)``, espaço e continuação alfabética/numérica.
47
+ """
48
+ if index + 3 >= len(text):
49
+ return False
50
+ return (
51
+ text[index + 1].isalpha()
52
+ and text[index + 2] == ")"
53
+ and text[index + 3] == " "
54
+ and (text[index + 4].isalpha() or text[index + 4].isdigit())
55
+ )
56
+
57
+
58
+ def _is_alternative_marker(text: str, index: int) -> bool:
59
+ """``)`` de marcador de alternativa (``f) texto``), não fechamento.
60
+
61
+ Letra, ``)``, espaço e continuação alfabética/numérica — espaço seguido de
62
+ operador (``(A) | B``) ou fim de expressão é fechamento legítimo.
63
+ """
64
+ if index == 0 or not text[index - 1].isalpha():
65
+ return False
66
+ if index + 1 >= len(text) or text[index + 1] != " ":
67
+ return False
68
+ return index + 2 < len(text) and (
69
+ text[index + 2].isalpha() or text[index + 2].isdigit()
70
+ )
71
+
72
+
73
+ class _Parser:
74
+ def __init__(
75
+ self,
76
+ text: str,
77
+ label: str,
78
+ validate_atom: AtomValidator | None,
79
+ ) -> None:
80
+ self.text = text
81
+ self.label = label
82
+ self.validate_atom = validate_atom
83
+ self.position = 0
84
+
85
+ def parse(self) -> LogicNode:
86
+ node = self._parse_or()
87
+ if self.position < len(self.text):
88
+ rest = self.text[self.position:].strip()
89
+ raise InputValidationError(f"{self.label} possui token inválido: {rest!r}")
90
+ return node
91
+
92
+ def _skip_spaces(self) -> None:
93
+ while self.position < len(self.text) and self.text[self.position].isspace():
94
+ self.position += 1
95
+
96
+ def _consume_operator(self, operator: str) -> bool:
97
+ self._skip_spaces()
98
+ if self.position < len(self.text) and self.text[self.position] == operator:
99
+ self.position += 1
100
+ return True
101
+ return False
102
+
103
+ def _parse_or(self) -> LogicNode:
104
+ parts = [self._parse_and()]
105
+ while True:
106
+ if not self._consume_operator("|"):
107
+ break
108
+ parts.append(self._parse_and())
109
+ return LogicNode("or", tuple(parts)) if len(parts) > 1 else parts[0]
110
+
111
+ def _parse_and(self) -> LogicNode:
112
+ parts = [self._parse_unary()]
113
+ while True:
114
+ if not self._consume_operator("&"):
115
+ break
116
+ parts.append(self._parse_unary())
117
+ return LogicNode("and", tuple(parts)) if len(parts) > 1 else parts[0]
118
+
119
+ def _parse_unary(self) -> LogicNode:
120
+ self._skip_spaces()
121
+ if self.text[self.position : self.position + 1] == "~":
122
+ self.position += 1
123
+ return LogicNode("not", (self._parse_unary(),))
124
+ return self._parse_primary()
125
+
126
+ def _parse_primary(self) -> LogicNode:
127
+ self._skip_spaces()
128
+ if self.position >= len(self.text):
129
+ raise InputValidationError(f"{self.label} possui expressão incompleta")
130
+ if self.text[self.position] == "(":
131
+ close = self._matching_close(self.position)
132
+ if close is not None:
133
+ after = close + 1
134
+ while after < len(self.text) and self.text[after].isspace():
135
+ after += 1
136
+ if after == len(self.text) or (
137
+ after < len(self.text) and self.text[after] in "|&"
138
+ ):
139
+ inner = self.text[self.position + 1 : close]
140
+ self.position = after
141
+ return _Parser(inner, self.label, self.validate_atom).parse()
142
+ if not _is_marker_open(self.text, self.position):
143
+ raise InputValidationError(f"{self.label} possui parênteses inválidos")
144
+ return self._parse_atom()
145
+
146
+ def _matching_close(self, open_index: int) -> int | None:
147
+ depth = 0
148
+ index = open_index
149
+ while index < len(self.text):
150
+ char = self.text[index]
151
+ if char == "(":
152
+ # O '(' líder abre o grupo; internos podem ser marcadores.
153
+ if index == open_index or not _is_marker_open(self.text, index):
154
+ depth += 1
155
+ elif char == ")":
156
+ if _is_alternative_marker(self.text, index):
157
+ index += 1
158
+ continue
159
+ depth -= 1
160
+ if depth == 0:
161
+ return index
162
+ index += 1
163
+ return None
164
+
165
+ def _parse_atom(self) -> LogicNode:
166
+ start = self.position
167
+ depth = 0
168
+ while self.position < len(self.text):
169
+ char = self.text[self.position]
170
+ if char == "(" and not _is_marker_open(self.text, self.position):
171
+ depth += 1
172
+ elif char == ")":
173
+ if _is_alternative_marker(self.text, self.position):
174
+ self.position += 1
175
+ continue
176
+ depth -= 1
177
+ if depth < 0:
178
+ break
179
+ elif depth == 0 and char in "|&":
180
+ break
181
+ self.position += 1
182
+ atom = self.text[start : self.position].strip()
183
+ if not atom:
184
+ raise InputValidationError(f"{self.label} possui expressão incompleta")
185
+ if depth != 0:
186
+ raise InputValidationError(f"{self.label} possui parênteses inválidos")
187
+ if self.validate_atom is not None:
188
+ self.validate_atom(atom)
189
+ return LogicNode("atom", atom=atom)
190
+
191
+
192
+ def compile_logic(
193
+ expression: Any,
194
+ *,
195
+ label: str,
196
+ validate_atom: AtomValidator | None = None,
197
+ ) -> LogicNode:
198
+ """Compila uma expressão booleana para uma representação imutável.
199
+
200
+ ``label`` nomeia as mensagens de erro; ``validate_atom`` valida cada
201
+ átomo (ex.: ids de ação conhecidos) durante a compilação.
202
+ """
203
+ text = _canonical_spacing(str(expression or "").strip())
204
+ if not text:
205
+ return LogicNode("empty")
206
+ return _Parser(text, label, validate_atom).parse()
207
+
208
+
209
+ def evaluate_logic(node: LogicNode, atom_value: Callable[[str], bool]) -> bool:
210
+ """Executa a representação compilada; nunca reinterpreta a expressão."""
211
+ if node.kind == "empty":
212
+ return False
213
+ if node.kind == "atom":
214
+ return atom_value(node.atom)
215
+ if node.kind == "not":
216
+ return not evaluate_logic(node.children[0], atom_value)
217
+ if node.kind == "and":
218
+ return all(evaluate_logic(child, atom_value) for child in node.children)
219
+ if node.kind == "or":
220
+ return any(evaluate_logic(child, atom_value) for child in node.children)
221
+ raise ValueError(f"nó lógico desconhecido: {node.kind}")
222
+
223
+
224
+ def _text(value: Any) -> str:
225
+ return re.sub(r"\s+", " ", str(value or "")).strip()
226
+
227
+
228
+ @dataclass(frozen=True)
229
+ class ReasonRule:
230
+ identifier: str
231
+ procedure: str
232
+ situation: str
233
+ description: str
234
+ order: int
235
+ condition: LogicNode | None
236
+ references: tuple[str, ...]
237
+ text: str
238
+ template: Any = None
239
+
240
+
241
+ def compile_reasons(rows, procedures, actions) -> tuple[ReasonRule, ...]:
242
+ from ..booleans import parse_bool
243
+
244
+ known = {identifier.upper() for identifier in actions}
245
+ result = []
246
+ identifiers = set()
247
+ for row in rows:
248
+ identifier = _text(row.get("id"))
249
+ procedure = _text(row.get("id_procedimento"))
250
+ if not identifier or identifier in identifiers:
251
+ raise InputValidationError(f"motivo com id ausente/duplicado: {identifier}")
252
+ identifiers.add(identifier)
253
+ if procedure not in procedures:
254
+ raise InputValidationError(f"motivo {identifier} referencia procedimento desconhecido: {procedure}")
255
+ if not parse_bool(row.get("ativo"), default=True):
256
+ continue
257
+
258
+ def validate(atom):
259
+ if atom.upper() not in known:
260
+ raise InputValidationError(f"motivo {identifier} referencia ação desconhecida: {atom}")
261
+
262
+ condition = _text(row.get("condicao_exibicao"))
263
+ node = compile_logic(condition, label=f"condição do motivo {identifier}", validate_atom=validate) if condition else None
264
+ references = tuple(part.strip().upper() for part in re.split(r"[,;|\n]+", str(row.get("acoes_referencia") or "")) if part.strip())
265
+ for reference in references:
266
+ validate(reference)
267
+ description = _text(row.get("descricao_situacao_inconforme"))
268
+ situation = _text(row.get("id_situacao"))
269
+ if not description and not situation:
270
+ raise InputValidationError(f"motivo {identifier} exige situação de destino")
271
+ declared_sids = {_text(item.get("id_situacao")) for item in actions.values() if item.get("id_situacao")}
272
+ declared_descriptions = {_text(item.get("descricao_situacao_inconforme")) for item in actions.values() if item.get("descricao_situacao_inconforme")}
273
+ if (situation and situation not in declared_sids) or (not situation and description not in declared_descriptions):
274
+ raise InputValidationError(f"motivo {identifier} referencia situação desconhecida")
275
+ text = _text(row.get("texto_motivo"))
276
+ if not text:
277
+ raise InputValidationError(f"motivo {identifier} sem texto")
278
+ try:
279
+ order = int(float(row.get("ordem") or 0))
280
+ except (ValueError, TypeError) as exc:
281
+ raise InputValidationError(f"ordem inválida do motivo {identifier}") from exc
282
+ template = None
283
+ if "{{" in text or "{%" in text:
284
+ try:
285
+ from jinja2 import StrictUndefined, meta
286
+ from jinja2.sandbox import SandboxedEnvironment
287
+
288
+ environment = SandboxedEnvironment(undefined=StrictUndefined, autoescape=False)
289
+ names = meta.find_undeclared_variables(environment.parse(text))
290
+ unknown = names - known - {"auditado", "acoes"}
291
+ if unknown:
292
+ raise InputValidationError(f"motivo {identifier} contém variáveis desconhecidas: {sorted(unknown)}")
293
+ template = environment.from_string(text)
294
+ except ImportError as exc:
295
+ raise InputValidationError("templates de motivos requerem argos-cli[reports]") from exc
296
+ result.append(ReasonRule(identifier, procedure, situation, description, order, node, references, text, template))
297
+ return tuple(sorted(result, key=lambda item: (item.order, item.identifier)))
298
+
299
+
300
+ def materialize_finding(action_ids, actions: Mapping[str, Mapping[str, Any]], auditado, rules: tuple[ReasonRule, ...], *, planning=None) -> dict[str, Any]:
301
+ by_id = {identifier.upper(): {**dict(item), "id": identifier} for identifier, item in actions.items()}
302
+ values = {identifier: bool(item.get("resultado")) for identifier, item in by_id.items()}
303
+ groups: dict[str, dict[str, Any]] = {}
304
+ for identifier in action_ids:
305
+ item = by_id.get(identifier.upper(), {})
306
+ if not item.get("resultado_situacao", item.get("resultado")):
307
+ continue
308
+ description = _text(item.get("descricao_situacao_inconforme"))
309
+ if not description:
310
+ continue
311
+ sid = _text(item.get("id_situacao")) or description # Compatibilidade: descrição era a identidade legada.
312
+ if sid in groups and groups[sid]["descricao"] != description:
313
+ raise InputValidationError(f"descrições divergentes para situação {sid}")
314
+ group = groups.setdefault(sid, {"id_situacao": sid, "descricao": description, "actions": [], "motivos": []})
315
+ group["actions"].append(item)
316
+ evidence = _text(item.get("descricao_evidencia"))
317
+ if evidence:
318
+ description, marker, complement = evidence.partition("Justificativa da avaliação:")
319
+ reason = {"id_acao": identifier, "descricao": description.strip(), "refs_acoes": [identifier],
320
+ "informacao_requerida": item.get("informacao_requerida"), "situacao_encontrada": item.get("situacao_encontrada")}
321
+ if marker:
322
+ reason["complemento"] = marker + complement
323
+ group["motivos"].append(reason)
324
+
325
+ for sid, group in list(groups.items()):
326
+ declared = [rule for rule in rules if rule.situation == sid or (not rule.situation and rule.description == group["descricao"])]
327
+ if not declared:
328
+ continue
329
+ reasons = []
330
+ for rule in declared:
331
+ if rule.condition is not None and not evaluate_logic(rule.condition, lambda atom: values.get(atom.upper(), False)):
332
+ continue
333
+ try:
334
+ text = rule.template.render(auditado=dict(auditado), acoes=by_id, **by_id).strip() if rule.template is not None else rule.text
335
+ except Exception as exc:
336
+ raise InputValidationError(f"não foi possível renderizar motivo {rule.identifier}: {exc}") from exc
337
+ if text:
338
+ refs = list(rule.references) or [item["id"] for item in group["actions"]]
339
+ reasons.append({"id": rule.identifier, "descricao": text, "texto": text, "refs_acoes": refs,
340
+ "acoes_referencia": refs, "id_situacao": sid, "descricao_situacao_inconforme": group["descricao"]})
341
+ if not reasons:
342
+ del groups[sid]
343
+ else:
344
+ group["motivos"] = reasons
345
+ group["references"] = {reference for reason in reasons for reference in reason["refs_acoes"]}
346
+
347
+ evidence: dict[str, dict[str, Any]] = {}
348
+ referrals: list[dict[str, Any]] = []
349
+ referral_positions: dict[tuple[str, str, str, str], int] = {}
350
+
351
+ def add_referral(referral: dict[str, Any]) -> None:
352
+ identity = (
353
+ str(referral.get("id_situacao") or ""),
354
+ str(referral.get("id_variante") or ""),
355
+ str(referral.get("tipo") or ""),
356
+ str(referral.get("encaminhamento") or ""),
357
+ )
358
+ position = referral_positions.get(identity)
359
+ if position is None:
360
+ referral_positions[identity] = len(referrals)
361
+ referrals.append(referral)
362
+ return
363
+ existing = referrals[position]
364
+ for identifier in referral.get("id_acoes", []):
365
+ if identifier not in existing["id_acoes"]:
366
+ existing["id_acoes"].append(identifier)
367
+
368
+ details = []
369
+ for group in groups.values():
370
+ sid = group["id_situacao"]
371
+ group_action_ids = list(dict.fromkeys(item["id"] for item in group["actions"]))
372
+ has_planning = planning is not None and sid in planning
373
+ if has_planning:
374
+ from .matrix import resolve_situation_for_auditee
375
+
376
+ declared = resolve_situation_for_auditee(planning[sid], auditado)
377
+ else:
378
+ declared = {}
379
+
380
+ for item in group["actions"]:
381
+ if "references" in group and item["id"].upper() not in group["references"]:
382
+ continue
383
+ description = str(item.get("descricao_evidencia") or "").strip()
384
+ if description:
385
+ detail = evidence.setdefault(description, {"descricao": description, "id_acoes": []})
386
+ if item["id"] not in detail["id_acoes"]:
387
+ detail["id_acoes"].append(item["id"])
388
+
389
+ details.append({
390
+ **{key: deepcopy(value) for key, value in declared.items() if key != "encaminhamentos_adicionais"},
391
+ "id_situacao": sid,
392
+ "descricao": group["descricao"],
393
+ "ativa": True,
394
+ "motivos": deepcopy(group["motivos"]),
395
+ "id_acoes": group_action_ids,
396
+ })
397
+
398
+ if has_planning:
399
+ referral_text = declared.get("encaminhamento")
400
+ if str(referral_text or "").strip():
401
+ referral = {
402
+ "id_situacao": sid,
403
+ "tipo": deepcopy(declared.get("tipo_encaminhamento")),
404
+ "encaminhamento": deepcopy(referral_text),
405
+ "fundamentacao_encaminhamento": deepcopy(declared.get("fundamentacao_encaminhamento")),
406
+ "criterios": deepcopy(declared.get("criterios") or []),
407
+ "id_acoes": list(group_action_ids),
408
+ }
409
+ if "id_variante" in declared:
410
+ referral["id_variante"] = deepcopy(declared["id_variante"])
411
+ add_referral(referral)
412
+ # Encaminhamentos adicionais somam-se ao principal, com os
413
+ # critérios próprios ou, na falta deles, os da situação.
414
+ for extra in declared.get("encaminhamentos_adicionais") or ():
415
+ additional = {
416
+ **referral,
417
+ "tipo": deepcopy(extra["tipo_encaminhamento"]),
418
+ "encaminhamento": deepcopy(extra["encaminhamento"]),
419
+ "fundamentacao_encaminhamento": deepcopy(extra.get("fundamentacao_encaminhamento") or ""),
420
+ "criterios": deepcopy(
421
+ extra["criterios"] if extra.get("criterios") is not None else referral["criterios"]
422
+ ),
423
+ "id_acoes": list(group_action_ids),
424
+ }
425
+ add_referral(additional)
426
+ continue
427
+
428
+ # Auditorias sem matriz mantêm a seleção por referências do motivo e
429
+ # continuam usando os metadados declarados pelas ações.
430
+ for item in group["actions"]:
431
+ if "references" in group and item["id"].upper() not in group["references"]:
432
+ continue
433
+ referral_text = item.get("encaminhamento")
434
+ if not str(referral_text or "").strip():
435
+ continue
436
+ referral = {
437
+ "id_situacao": sid,
438
+ "tipo": deepcopy(item.get("tipo_encaminhamento")),
439
+ "encaminhamento": deepcopy(referral_text),
440
+ "id_acoes": [item["id"]],
441
+ }
442
+ add_referral(referral)
443
+ descriptions = [group["descricao"] for group in groups.values()]
444
+ return {"situacoes_inconformes": descriptions, "situacoes_encontradas": descriptions,
445
+ "situacoes_detalhadas": details, "motivos_situacoes": {sid: group["motivos"] for sid, group in groups.items()},
446
+ "evidencias": list(evidence), "evidencias_detalhadas": list(evidence.values()), "encaminhamentos": referrals}
447
+
448
+
449
+ def _link_matrix_finding_ids(
450
+ rows: Mapping[str, Mapping[str, Any]], matrix_context: Any
451
+ ) -> Mapping[str, Mapping[str, Any]]:
452
+ """Restores stable matrix metadata omitted from compact procedure rows."""
453
+ if not isinstance(matrix_context, Mapping):
454
+ return rows
455
+
456
+ findings = matrix_context.get("achados")
457
+ by_title: dict[str, list[Mapping[str, Any]]] = {}
458
+ for finding in findings if isinstance(findings, list) else []:
459
+ if not isinstance(finding, Mapping):
460
+ continue
461
+ title = re.sub(r"\s+", " ", str(finding.get("titulo") or "")).strip().casefold()
462
+ if title:
463
+ by_title.setdefault(title, []).append(finding)
464
+
465
+ criteria = matrix_context.get("criterios")
466
+ by_criterion_id: dict[str, list[Mapping[str, Any]]] = {}
467
+ for criterion in criteria if isinstance(criteria, list) else []:
468
+ if not isinstance(criterion, Mapping) or criterion.get("id") is None:
469
+ continue
470
+ by_criterion_id.setdefault(str(criterion["id"]), []).append(criterion)
471
+
472
+ def enrich_situations(situations: Any) -> tuple[Any, bool]:
473
+ if not isinstance(situations, list):
474
+ return situations, False
475
+ result: list[Any] = []
476
+ changed = False
477
+ for situation in situations:
478
+ if not isinstance(situation, Mapping) or not isinstance(situation.get("criterios"), list):
479
+ result.append(situation)
480
+ continue
481
+ situation_copy = dict(situation)
482
+ enriched_criteria: list[Any] = []
483
+ situation_changed = False
484
+ for criterion in situation["criterios"]:
485
+ if not isinstance(criterion, Mapping):
486
+ enriched_criteria.append(criterion)
487
+ continue
488
+ matches = by_criterion_id.get(str(criterion.get("id") or ""), [])
489
+ if len(matches) == 1:
490
+ # Execution facts win; matrix metadata fills fields absent from the result.
491
+ enriched = {**matches[0], **criterion}
492
+ enriched_criteria.append(enriched)
493
+ situation_changed = situation_changed or enriched != criterion
494
+ else:
495
+ enriched_criteria.append(criterion)
496
+ if situation_changed:
497
+ situation_copy["criterios"] = enriched_criteria
498
+ changed = True
499
+ result.append(situation_copy)
500
+ else:
501
+ result.append(situation)
502
+ return (result if changed else situations), changed
503
+
504
+ linked_rows: dict[str, Mapping[str, Any]] = {}
505
+ for organization, row in rows.items():
506
+ procedures = row.get("procedimentos_executados")
507
+ if not isinstance(procedures, list):
508
+ linked_rows[organization] = row
509
+ continue
510
+ linked_procedures: list[Any] = []
511
+ row_changed = False
512
+ for procedure in procedures:
513
+ if not isinstance(procedure, Mapping):
514
+ linked_procedures.append(procedure)
515
+ continue
516
+ nested = procedure.get("achado")
517
+ nested = nested if isinstance(nested, Mapping) else None
518
+ title_value = (
519
+ (nested.get("nome") or nested.get("nome_achado") if nested else None)
520
+ or procedure.get("nome_achado") or procedure.get("nome")
521
+ )
522
+ title = re.sub(r"\s+", " ", str(title_value or "")).strip().casefold()
523
+ matches = by_title.get(title, [])
524
+ procedure_copy = dict(procedure)
525
+ changed = False
526
+ if len(matches) == 1:
527
+ finding = matches[0]
528
+ for field, source in (("id_matriz", "id"), ("id_questao", "id_questao")):
529
+ value = finding.get(source)
530
+ if value is not None and (nested or {}).get(field) is None and procedure.get(field) is None:
531
+ procedure_copy[field] = value
532
+ changed = True
533
+
534
+ top_situations, top_changed = enrich_situations(procedure.get("situacoes_detalhadas"))
535
+ if top_changed:
536
+ procedure_copy["situacoes_detalhadas"] = top_situations
537
+ changed = True
538
+ nested_situations, nested_changed = enrich_situations(
539
+ nested.get("situacoes_detalhadas") if nested else None
540
+ )
541
+ if nested_changed:
542
+ nested_copy = dict(nested or {})
543
+ nested_copy["situacoes_detalhadas"] = nested_situations
544
+ procedure_copy["achado"] = nested_copy
545
+ changed = True
546
+ linked_procedures.append(procedure_copy if changed else procedure)
547
+ row_changed = row_changed or changed
548
+
549
+ if row_changed:
550
+ row_copy = dict(row)
551
+ row_copy["procedimentos_executados"] = linked_procedures
552
+ linked_rows[organization] = row_copy
553
+ else:
554
+ linked_rows[organization] = row
555
+ return linked_rows
556
+
557
+
558
+ def audit_rows_from_result(payload: Any) -> Mapping[str, Mapping[str, Any]]:
559
+ """Normaliza as linhas de auditados aceitas pelo formato de resultado (v2, v1 ou legado)."""
560
+ payload = formato_resultado.expandir(payload)
561
+ if not isinstance(payload, Mapping):
562
+ raise InputValidationError("resultado de auditoria deve ser um objeto JSON")
563
+ if "auditados" in payload:
564
+ rows = payload["auditados"]
565
+ elif "results" in payload:
566
+ rows = payload["results"]
567
+ elif "data" in payload:
568
+ rows = payload["data"]
569
+ else:
570
+ rows = payload
571
+ if isinstance(rows, list):
572
+ normalized: dict[str, Mapping[str, Any]] = {}
573
+ for position, item in enumerate(rows, start=1):
574
+ if not isinstance(item, Mapping):
575
+ continue
576
+ key = str(item.get("sigla") or item.get("auditado") or item.get("id") or position).strip()
577
+ if key:
578
+ normalized[key] = item
579
+ else:
580
+ if not isinstance(rows, Mapping):
581
+ raise InputValidationError("resultado de auditoria não contém auditados")
582
+ normalized = {str(key): item for key, item in rows.items() if isinstance(item, Mapping)}
583
+ if not normalized:
584
+ raise InputValidationError("resultado de auditoria não contém linhas de auditados")
585
+ return _link_matrix_finding_ids(normalized, payload.get("contexto_matriz"))
586
+
587
+
588
+ def matrix_context_from_markdown(markdown: str) -> dict[str, list[dict[str, Any]]]:
589
+ """Captura no resultado da auditoria o contexto documental da matriz usada."""
590
+ from .matrix import parse_matrix, resolve_planning_metadata
591
+
592
+ resolve_planning_metadata(markdown)
593
+ matrix = parse_matrix(markdown)
594
+ context: dict[str, list[dict[str, Any]]] = {
595
+ "questoes": [],
596
+ "achados": [],
597
+ "situacoes": [],
598
+ "criterios": [],
599
+ "fontes": [],
600
+ }
601
+ for question_order, question in enumerate(matrix.questions, start=1):
602
+ context["questoes"].append(
603
+ {
604
+ "id": question.id,
605
+ "titulo": question.title,
606
+ "texto": question.question,
607
+ "ordem": question_order,
608
+ }
609
+ )
610
+ for criterion_order, criterion in enumerate(question.criterios, start=1):
611
+ local_id = str(criterion.id or "").strip()
612
+ if not local_id:
613
+ continue
614
+ criterion_id = (
615
+ local_id
616
+ if local_id.startswith(f"{question.id}.")
617
+ else f"{question.id}.{local_id}"
618
+ )
619
+ metadata = criterion.metadata if isinstance(criterion.metadata, Mapping) else {}
620
+ context["criterios"].append(
621
+ {
622
+ "id": criterion_id,
623
+ "id_local": local_id,
624
+ "id_questao": question.id,
625
+ "descricao": criterion.text,
626
+ "ordem": criterion_order,
627
+ "natureza_fundamento": metadata.get("natureza_fundamento"),
628
+ "apto_a_fundamentar_determinacao": metadata.get(
629
+ "apto_a_fundamentar_determinacao"
630
+ ),
631
+ "publico": metadata.get("publico"),
632
+ "especifico": metadata.get("especifico"),
633
+ "aplica_se": deepcopy(metadata.get("aplica_se")),
634
+ }
635
+ )
636
+ for source_order, source in enumerate(question.fontes, start=1):
637
+ if not source.id:
638
+ continue
639
+ context["fontes"].append(
640
+ {
641
+ "id": source.id,
642
+ "id_questao": question.id,
643
+ "descricao": source.text,
644
+ "ordem": source_order,
645
+ }
646
+ )
647
+ for finding_order, finding in enumerate(question.achados, start=1):
648
+ context["achados"].append(
649
+ {
650
+ "id": finding.id,
651
+ "id_questao": question.id,
652
+ "titulo": finding.title,
653
+ "ordem": finding_order,
654
+ }
655
+ )
656
+ for situation_order, situation in enumerate(finding.situacoes, start=1):
657
+ context["situacoes"].append(
658
+ {
659
+ "id": situation.id,
660
+ "id_achado": finding.id,
661
+ "descricao": situation.descricao,
662
+ "ordem": situation_order,
663
+ "criterios": [
664
+ criterion_id
665
+ if criterion_id.startswith(f"{question.id}.")
666
+ else f"{question.id}.{criterion_id}"
667
+ for criterion_id in situation.criterios
668
+ ],
669
+ }
670
+ )
671
+ return context
672
+
673
+
674
+ def audit_result_payload(context: OperationContext, result) -> dict[str, Any]:
675
+ """Embalagem pública do resultado: fatos calculados mais contexto autoral."""
676
+ rows = result.compact()
677
+ normalized_rows = audit_rows_from_result(rows)
678
+ matrix_context = {"questoes": [], "achados": [], "situacoes": [], "criterios": [], "fontes": []}
679
+ if context.params.get("matriz"):
680
+ matrix_path = require_file(context, context.params["matriz"], "matriz de planejamento")
681
+ matrix_context = matrix_context_from_markdown(matrix_path.read_text(encoding="utf-8"))
682
+
683
+ respondent_values = [row.get("respondeu_questionario") for row in normalized_rows.values()]
684
+ respondents = (
685
+ sum(value is True for value in respondent_values)
686
+ if any(isinstance(value, bool) for value in respondent_values)
687
+ else None
688
+ )
689
+ coverage = {
690
+ "total": len(normalized_rows),
691
+ "avaliados": sum(row.get("foi_auditado") is True for row in normalized_rows.values()),
692
+ "com_achados": sum(row.get("tem_achados") is True for row in normalized_rows.values()),
693
+ "respondentes": respondents,
694
+ }
695
+ return {
696
+ "schema_version": "argos.audit-result/v1",
697
+ "cenario": str(context.params.get("scenario") or "base"),
698
+ "cobertura": coverage,
699
+ "contexto_matriz": matrix_context,
700
+ "auditados": dict(normalized_rows),
701
+ }
702
+
703
+
704
+ def audit_provenance(context: OperationContext, result) -> dict[str, Any]:
705
+ """Versão do Argos, execução e SHA-256 das entradas, com caminhos relativos ao projeto."""
706
+ from .. import __version__
707
+
708
+ def entry(value: Any) -> dict[str, str] | None:
709
+ path = context.optional_path(value)
710
+ if path is None or not Path(path).is_file():
711
+ return None
712
+ try:
713
+ shown = Path(path).resolve().relative_to(Path(context.project_root).resolve()).as_posix()
714
+ except (ValueError, TypeError):
715
+ shown = str(path)
716
+ return {"path": shown, "sha256": sha256_file(Path(path))}
717
+
718
+ # Sem id de execução nem data: as mesmas entradas devem produzir o mesmo arquivo.
719
+ provenance: dict[str, Any] = {"argos_version": __version__}
720
+ for key, param in (("auditados", "base_auditados"), ("mapa", "mapa"), ("matriz", "matriz")):
721
+ item = entry(context.params.get(param))
722
+ if item:
723
+ provenance[key] = item
724
+ sources = getattr(result, "sources", {}) or {}
725
+ provenance["fontes"] = {identifier: entry(path) for identifier, path in sorted(sources.items()) if entry(path)}
726
+ return provenance
727
+
728
+
729
+ def audit_result_content(context: OperationContext, result, audit_payload: Mapping[str, Any]) -> tuple[bytes | Mapping[str, Any], list[str]]:
730
+ """Conteúdo gravado do resultado: v2 por padrão; v1 quando pedido ou se a compactação falhar."""
731
+ if str(context.params.get("formato") or "v2") == "v1":
732
+ return audit_payload, []
733
+ compact = formato_resultado.compactar(audit_payload, audit_provenance(context, result))
734
+ if compact is None:
735
+ return audit_payload, ["o resultado não pôde ser gravado em argos.audit-result/v2 sem perda; gravado em v1"]
736
+ return formato_resultado.serializar(compact), []
737
+
738
+
739
+ def normalizar_texto_relatorio(valor: Any) -> str:
740
+ if valor in (None, "") or (isinstance(valor, float) and str(valor) == "nan"):
741
+ return ""
742
+ return re.sub(r"\s+", " ", str(valor)).strip()
743
+
744
+
745
+ def _valor_vazio(valor: Any) -> bool:
746
+ if valor is None:
747
+ return True
748
+ if isinstance(valor, float):
749
+ import math
750
+
751
+ if math.isnan(valor):
752
+ return True
753
+ return str(valor).strip() == ""
754
+
755
+
756
+ def normalizar_motivo_situacao(descricao: Any) -> dict[str, str] | None:
757
+ if _valor_vazio(descricao):
758
+ return None
759
+ descricao_texto = str(descricao).strip()
760
+ complemento: str | None = None
761
+ marcador = "Justificativa da avaliação:"
762
+ if marcador in descricao_texto:
763
+ descricao_texto, justificativa = descricao_texto.split(marcador, 1)
764
+ descricao_texto = descricao_texto.strip()
765
+ complemento = f"{marcador} {justificativa.strip()}".strip()
766
+ if not descricao_texto:
767
+ return None
768
+ motivo: dict[str, str] = {"descricao": descricao_texto}
769
+ if complemento:
770
+ motivo["complemento"] = complemento
771
+ return motivo
772
+
773
+
774
+ def normalizar_evidencia_relatorio(evidencia: Any) -> dict[str, Any] | None:
775
+ if isinstance(evidencia, Mapping):
776
+ normalizada = normalizar_motivo_situacao(evidencia.get("descricao", ""))
777
+ if not normalizada:
778
+ return None
779
+ item = dict(evidencia)
780
+ item["descricao"] = normalizada.get("descricao", "")
781
+ complemento = normalizar_texto_relatorio(
782
+ evidencia.get("complemento") or normalizada.get("complemento", "")
783
+ )
784
+ if complemento:
785
+ item["complemento"] = complemento
786
+ else:
787
+ item.pop("complemento", None)
788
+ return item
789
+ descricao = normalizar_texto_relatorio(evidencia)
790
+ if not descricao:
791
+ return None
792
+ return {"descricao": descricao}
793
+
794
+
795
+ def _extrair_item_informacao(informacao_requerida: Any) -> str | None:
796
+ if _valor_vazio(informacao_requerida):
797
+ return None
798
+ match = re.search(r"q?(\d{4})", str(informacao_requerida), flags=re.I)
799
+ return match.group(1) if match else None
800
+
801
+
802
+ def _procedimentos_ocorridos(auditado: Mapping[str, Any]) -> list[dict[str, Any]]:
803
+ procedimentos: list[dict[str, Any]] = []
804
+ for procedimento in auditado.get("procedimentos_executados") or []:
805
+ if not isinstance(procedimento, Mapping):
806
+ continue
807
+ achado = procedimento.get("achado") or {}
808
+ ocorreu = procedimento.get("achado_ocorreu")
809
+ if isinstance(achado, bool):
810
+ ocorreu = achado if ocorreu is None else ocorreu
811
+ elif achado:
812
+ ocorreu = True if ocorreu is None else ocorreu
813
+ if not ocorreu:
814
+ continue
815
+ procedimentos.append(procedimento)
816
+ return procedimentos
817
+
818
+
819
+ def _acoes_por_situacao(auditado: Mapping[str, Any], situacao: str) -> list[tuple[str, Mapping[str, Any]]]:
820
+ acoes = auditado.get("acoes") if isinstance(auditado.get("acoes"), Mapping) else {}
821
+ return [
822
+ (str(identificador), acao)
823
+ for identificador, acao in acoes.items()
824
+ if isinstance(acao, Mapping) and chave(acao.get("descricao_situacao_inconforme")) == chave(situacao)
825
+ ]
826
+
827
+
828
+ def _motivos_situacoes(auditado: Mapping[str, Any], procedimento: Mapping[str, Any]) -> dict[str, list[dict[str, Any]]]:
829
+ """Motivos por situação no formato legado, derivados das ações verificadas."""
830
+ motivos_por_situacao: dict[str, list[dict[str, Any]]] = {}
831
+ if isinstance(procedimento.get("motivos_situacoes"), Mapping):
832
+ return deepcopy(dict(procedimento["motivos_situacoes"]))
833
+ situacoes = procedimento.get("situacoes_inconformes") or []
834
+ for situacao in situacoes:
835
+ motivos: list[dict[str, Any]] = []
836
+ for identificador, acao in _acoes_por_situacao(auditado, situacao):
837
+ normalizado = normalizar_motivo_situacao(acao.get("descricao_evidencia"))
838
+ if not normalizado:
839
+ continue
840
+ motivo = dict(normalizado)
841
+ motivo["id"] = f"MR-{identificador}"
842
+ motivo["id_acao"] = identificador
843
+ motivo["refs_acoes"] = [identificador]
844
+ motivo["item"] = _extrair_item_informacao(acao.get("informacao_requerida"))
845
+ motivos.append(motivo)
846
+ motivos_por_situacao[situacao] = motivos
847
+ return motivos_por_situacao
848
+
849
+
850
+ def _evidencias_detalhadas(auditado: Mapping[str, Any]) -> list[dict[str, Any]]:
851
+ acoes = auditado.get("acoes") if isinstance(auditado.get("acoes"), Mapping) else {}
852
+ evidencias: list[dict[str, Any]] = []
853
+ vistos: set[str] = set()
854
+ for identificador, acao in acoes.items():
855
+ if not isinstance(acao, Mapping) or not acao.get("resultado"):
856
+ continue
857
+ descricao = normalizar_texto_relatorio(acao.get("descricao_evidencia"))
858
+ if not descricao:
859
+ continue
860
+ if descricao in vistos:
861
+ continue
862
+ vistos.add(descricao)
863
+ evidencias.append({"descricao": descricao, "id_acoes": [identificador]})
864
+ return evidencias
865
+
866
+
867
+ def normalizar_achado(auditado: Mapping[str, Any], procedimento: Mapping[str, Any]) -> dict[str, Any]:
868
+ """Projeta os fatos de um achado para apresentação, sem alterar as fontes.
869
+
870
+ Resultados aceitos trazem os fatos no procedimento ou em ``achado``.
871
+ Representações simultâneas devem concordar; vazio explícito não autoriza
872
+ ignorar conteúdo contraditório da outra representação.
873
+ """
874
+ nested = procedimento.get("achado")
875
+ nested = nested if isinstance(nested, Mapping) else {}
876
+
877
+ def field(name: str, *aliases: str, default: Any = None) -> Any:
878
+ values = [source[key] for source in (nested, procedimento)
879
+ for key in (name, *aliases) if key in source and source[key] is not None]
880
+ if not values:
881
+ return deepcopy(default)
882
+ if any(value != values[0] for value in values[1:]):
883
+ raise InputValidationError(f"campo {name} contraditório no procedimento {procedimento.get('id')}")
884
+ return deepcopy(values[0])
885
+
886
+ numero = field("numero", "numero_achado", default=0)
887
+ if isinstance(numero, str) and numero.isdigit():
888
+ numero = int(numero)
889
+ result = {
890
+ "id_achado": field("id_achado", default=str(procedimento.get("id") or numero)),
891
+ "id_matriz": field("id_matriz"),
892
+ "id_questao": field("id_questao"),
893
+ "numero": numero,
894
+ "nome": field("nome", "nome_achado", default=""),
895
+ "situacoes_encontradas": field("situacoes_encontradas", "situacoes_inconformes", default=[]),
896
+ "situacoes_detalhadas": field("situacoes_detalhadas", default=[]),
897
+ "evidencias": field("evidencias", default=[]),
898
+ "evidencias_detalhadas": field("evidencias_detalhadas"),
899
+ "encaminhamentos": field("encaminhamentos", default=[]),
900
+ "motivos_situacoes": field("motivos_situacoes"),
901
+ }
902
+ matrix_context = auditado.get("contexto_matriz")
903
+ matrix_findings = matrix_context.get("achados") if isinstance(matrix_context, Mapping) else None
904
+ if isinstance(matrix_findings, list) and result["nome"]:
905
+ title = normalizar_texto_relatorio(result["nome"]).casefold()
906
+ matches = [
907
+ item for item in matrix_findings
908
+ if isinstance(item, Mapping)
909
+ and normalizar_texto_relatorio(item.get("titulo")).casefold() == title
910
+ ]
911
+ # A associação por título só é segura quando a matriz identifica um único achado.
912
+ if len(matches) == 1:
913
+ matrix_finding = matches[0]
914
+ if result["id_matriz"] is None:
915
+ result["id_matriz"] = matrix_finding.get("id")
916
+ if result["id_questao"] is None:
917
+ result["id_questao"] = matrix_finding.get("id_questao")
918
+ if result["motivos_situacoes"] is None:
919
+ result["motivos_situacoes"] = _motivos_situacoes(auditado, {
920
+ "situacoes_inconformes": result["situacoes_encontradas"],
921
+ })
922
+ if result["evidencias_detalhadas"] is None:
923
+ declared = set(str(item) for item in result["evidencias"])
924
+ result["evidencias_detalhadas"] = [
925
+ item for item in _evidencias_detalhadas(auditado)
926
+ if item["descricao"] in declared
927
+ ]
928
+ return result
929
+
930
+
931
+ def get_achados(auditado: Mapping[str, Any]) -> dict[str, dict[str, Any]]:
932
+ """Achados ocorridos por número de exibição, preservando IDs estruturais."""
933
+ result: dict[str, dict[str, Any]] = {}
934
+ for procedure in _procedimentos_ocorridos(auditado):
935
+ finding = normalizar_achado(auditado, procedure)
936
+ key = f"achado{finding['numero']}" if finding["numero"] else finding["id_achado"]
937
+ if key in result:
938
+ raise InputValidationError(f"identificador de achado repetido: {key}")
939
+ result[key] = finding
940
+ return result
941
+
942
+
943
+ def get_achado_por_id(auditado: Mapping[str, Any], identifier: Any) -> dict[str, Any] | None:
944
+ """Resolve IDs do resultado/matriz e, por último, o número de exibição exato."""
945
+ if identifier is None:
946
+ return None
947
+ target = str(identifier).strip()
948
+ findings = list(get_achados(auditado).values())
949
+ for finding in findings:
950
+ if str(finding["id_achado"]) == target:
951
+ return finding
952
+ aliases = [
953
+ finding for finding in findings
954
+ if target in {str(finding.get("id_matriz") or ""), str(finding.get("id_questao") or "")}
955
+ ]
956
+ if len(aliases) == 1:
957
+ return aliases[0]
958
+ if len(aliases) > 1:
959
+ return None
960
+ matches = [finding for finding in findings if str(finding["numero"]) == target]
961
+ return matches[0] if len(matches) == 1 else None
962
+
963
+
964
+ def get_achado_por_nome(auditado: Mapping[str, Any], nome: str) -> dict[str, Any] | None:
965
+ matches = [finding for finding in get_achados(auditado).values() if finding["nome"] == nome]
966
+ if len(matches) > 1:
967
+ raise InputValidationError(f"nome de achado ambíguo; informe o ID: {nome}")
968
+ return matches[0] if matches else None
969
+
970
+
971
+ def _resolver_achado(auditado: Mapping[str, Any], identifier: Any) -> dict[str, Any] | None:
972
+ return get_achado_por_id(auditado, identifier) or get_achado_por_nome(auditado, identifier)
973
+
974
+
975
+ def _ids_relatorio(value: Any) -> list[str]:
976
+ if value is None:
977
+ return []
978
+ if isinstance(value, str):
979
+ value = value.strip()
980
+ if value.startswith("["):
981
+ try:
982
+ value = ast.literal_eval(value)
983
+ except (ValueError, SyntaxError) as exc:
984
+ raise InputValidationError("lista de referências inválida no relatório") from exc
985
+ else:
986
+ value = re.split(r"[;,|\s]+", value)
987
+ if not isinstance(value, (list, tuple, set)):
988
+ raise InputValidationError("referências do relatório devem ser uma lista de IDs")
989
+ return list(dict.fromkeys(str(item).strip() for item in value if str(item).strip()))
990
+
991
+
992
+ def _refs_motivo(evidences: list[dict[str, Any]], reason: Mapping[str, Any]) -> list[str]:
993
+ explicit = _ids_relatorio(reason.get("refs"))
994
+ if explicit:
995
+ return explicit
996
+ actions = set(_ids_relatorio(reason.get("refs_acoes") or reason.get("acoes_referencia")))
997
+ refs = [item["ref"] for item in evidences if actions.intersection(item["id_acoes"])]
998
+ if refs:
999
+ return refs
1000
+ description = normalizar_texto_relatorio(reason.get("descricao", ""))
1001
+ supplement = normalizar_texto_relatorio(reason.get("complemento", ""))
1002
+ for evidence in evidences:
1003
+ other = normalizar_texto_relatorio(evidence.get("descricao", ""))
1004
+ other_supplement = normalizar_texto_relatorio(evidence.get("complemento", ""))
1005
+ if description and other and (description in other or other in description) and (
1006
+ not supplement or supplement in other_supplement or other_supplement in supplement
1007
+ ):
1008
+ refs.append(evidence["ref"])
1009
+ if not refs and reason.get("item"):
1010
+ pattern = re.compile(rf"\b(?:item|q)?{re.escape(str(reason['item']))}\b", re.I)
1011
+ refs = [item["ref"] for item in evidences if pattern.search(
1012
+ " ".join(str(item.get(key) or "") for key in ("descricao", "complemento"))
1013
+ )]
1014
+ return refs
1015
+
1016
+
1017
+ class ReportSituation(dict):
1018
+ """Situação de apresentação: existência do mapeamento não implica ocorrência."""
1019
+
1020
+ def __bool__(self) -> bool:
1021
+ return bool(self.get("ativa", False))
1022
+
1023
+
1024
+ def get_situacao(auditado: Mapping[str, Any], id_achado: Any, id_situacao: Any) -> ReportSituation:
1025
+ finding = _resolver_achado(auditado, id_achado)
1026
+ situation = next((item for item in (finding or {}).get("situacoes_detalhadas", [])
1027
+ if str(item.get("id_situacao")) == str(id_situacao)), None)
1028
+ if situation is None:
1029
+ return ReportSituation(id_situacao=str(id_situacao), descricao="", ativa=False, motivos=[], criterios=[])
1030
+ result = ReportSituation(deepcopy(situation))
1031
+ result.setdefault("ativa", True)
1032
+ result.setdefault("criterios", [])
1033
+ result["motivos"] = get_motivos_situacao(auditado, id_achado, str(id_situacao))
1034
+ return result
1035
+
1036
+
1037
+ def get_criterios_achado(auditado: Mapping[str, Any], identifier: Any) -> list[dict[str, Any]]:
1038
+ finding = _resolver_achado(auditado, identifier)
1039
+ criteria: dict[str, dict[str, Any]] = {}
1040
+ for situation in (finding or {}).get("situacoes_detalhadas", []):
1041
+ if not situation.get("ativa", True):
1042
+ continue
1043
+ for criterion in situation.get("criterios") or []:
1044
+ key = str(criterion.get("id") or criterion.get("descricao") or "")
1045
+ if key not in criteria:
1046
+ criteria[key] = {**deepcopy(criterion), "situacoes": []}
1047
+ sid = situation.get("id_situacao")
1048
+ if sid not in criteria[key]["situacoes"]:
1049
+ criteria[key]["situacoes"].append(sid)
1050
+ return list(criteria.values())
1051
+
1052
+
1053
+ def get_motivos_situacao(auditado: Mapping[str, Any], nome_achado: str, situacao: str) -> list[dict[str, Any]]:
1054
+ achado = _resolver_achado(auditado, nome_achado)
1055
+ if not achado:
1056
+ return []
1057
+ motivos: list[dict[str, Any]] = []
1058
+ vistos: set[tuple[str, ...]] = set()
1059
+ evidencias = get_evidencias_numeradas(auditado, nome_achado)
1060
+ details = achado.get("situacoes_detalhadas") or []
1061
+ matching = [item["id_situacao"] for item in details if item.get("descricao") == situacao]
1062
+ if len(matching) > 1:
1063
+ raise InputValidationError(f"descrição de situação ambígua; informe o ID: {situacao}")
1064
+ reason_key = matching[0] if len(matching) == 1 else situacao
1065
+ reasons = achado.get("motivos_situacoes", {})
1066
+ for motivo in reasons.get(reason_key, reasons.get(situacao, [])) or []:
1067
+ item = dict(motivo) if isinstance(motivo, Mapping) else normalizar_motivo_situacao(motivo)
1068
+ if not item:
1069
+ continue
1070
+ descricao = normalizar_texto_relatorio(item.get("descricao") or item.get("texto", ""))
1071
+ if not descricao:
1072
+ continue
1073
+ complemento = normalizar_texto_relatorio(item.get("complemento", ""))
1074
+ item["descricao"] = descricao
1075
+ item["texto"] = normalizar_texto_relatorio(item.get("texto") or descricao)
1076
+ if complemento:
1077
+ item["complemento"] = complemento
1078
+ else:
1079
+ item.pop("complemento", None)
1080
+ if not item.get("item"):
1081
+ item["item"] = _extrair_item_informacao(
1082
+ item.get("informacao_requerida") or descricao
1083
+ )
1084
+ item["refs"] = _refs_motivo(evidencias, item)
1085
+ chave = (
1086
+ str(item.get("id", "")),
1087
+ str(item.get("id_acao", "")),
1088
+ str(item.get("descricao", "")),
1089
+ str(item.get("complemento", "")),
1090
+ )
1091
+ if chave not in vistos:
1092
+ vistos.add(chave)
1093
+ motivos.append(item)
1094
+ return motivos
1095
+
1096
+
1097
+ def get_evidencias_numeradas(auditado: Mapping[str, Any], nome_achado: str) -> list[dict[str, Any]]:
1098
+ achado = _resolver_achado(auditado, nome_achado)
1099
+ if not achado:
1100
+ return []
1101
+ evidencias: list[dict[str, Any]] = []
1102
+ vistos: set[tuple[str, str]] = set()
1103
+ origem = achado.get("evidencias_detalhadas") or [
1104
+ {"descricao": evidencia, "id_acoes": []} for evidencia in achado.get("evidencias") or []
1105
+ ]
1106
+ for evidencia in origem:
1107
+ item = normalizar_evidencia_relatorio(evidencia)
1108
+ if not item:
1109
+ continue
1110
+ chave = (str(item.get("descricao", "")), str(item.get("complemento", "")))
1111
+ if chave in vistos:
1112
+ continue
1113
+ vistos.add(chave)
1114
+ item["ref"] = f"E{len(evidencias) + 1}"
1115
+ item["id_acoes"] = _ids_relatorio(item.get("id_acoes"))
1116
+ evidencias.append(item)
1117
+ return evidencias
1118
+
1119
+
1120
+ def get_plano_acao(auditado: Mapping[str, Any]) -> list[dict[str, Any]]:
1121
+ encaminhamentos: list[dict[str, Any]] = []
1122
+ for achado in get_achados(auditado).values():
1123
+ numero = achado["numero"]
1124
+ for item in achado["encaminhamentos"]:
1125
+ if not isinstance(item, Mapping):
1126
+ continue
1127
+ encaminhamento = str(item.get("encaminhamento") or "").strip()
1128
+ tipo = str(item.get("tipo") or "").strip()
1129
+ if not encaminhamento or not tipo:
1130
+ continue
1131
+ registro = {"achado_num": numero, "encaminhamento": encaminhamento, "tipo": tipo}
1132
+ if registro not in encaminhamentos:
1133
+ encaminhamentos.append(registro)
1134
+ return encaminhamentos
1135
+
1136
+
1137
+ def anexar_funcoes(auditado: Mapping[str, Any]) -> dict[str, Any]:
1138
+ """Devolve o dict do auditado enriquecido com as chaves-método do template."""
1139
+ enriquecido = dict(auditado)
1140
+ enriquecido["get_achados"] = (lambda a: lambda: get_achados(a))(auditado)
1141
+ enriquecido["get_achado_por_id"] = lambda identifier: get_achado_por_id(auditado, identifier)
1142
+ enriquecido["get_situacao"] = lambda identifier, situation: get_situacao(auditado, identifier, situation)
1143
+ enriquecido["get_criterios_achado"] = lambda identifier: get_criterios_achado(auditado, identifier)
1144
+ enriquecido["get_achado_por_nome"] = (lambda a: lambda nome: get_achado_por_nome(a, nome))(auditado)
1145
+ enriquecido["get_motivos_situacao"] = (
1146
+ lambda a: lambda nome, situacao: get_motivos_situacao(a, nome, situacao)
1147
+ )(auditado)
1148
+ enriquecido["get_evidencias_numeradas"] = (
1149
+ lambda a: lambda nome: get_evidencias_numeradas(a, nome)
1150
+ )(auditado)
1151
+ enriquecido["get_plano_acao"] = (lambda a: lambda: get_plano_acao(a))(auditado)
1152
+ return enriquecido
1153
+
1154
+
1155
+ # ---------------------------------------------------------------------------
1156
+ # Ajustes de respostas (Apêndice B dos relatórios individuais)
1157
+ # ---------------------------------------------------------------------------
1158
+
1159
+ def normalizar_texto_ajuste(valor: Any) -> str:
1160
+ if valor is None:
1161
+ return ""
1162
+ return str(valor).strip().lower().replace("ã", "a").replace("õ", "o").replace("é", "e").replace("á", "a").replace("í", "i")
1163
+
1164
+
1165
+ def is_nao_conforme_ajuste(valor: Any) -> bool:
1166
+ return normalizar_texto_ajuste(valor) in ("nao conforme", "nao_conforme", "nao-conforme")
1167
+
1168
+
1169
+ def valor_texto(valor: Any, vazio: str = "") -> str:
1170
+ if valor is None:
1171
+ return vazio
1172
+ texto = str(valor).strip()
1173
+ if texto == "" or texto.lower() in ("nan", "none"):
1174
+ return vazio
1175
+ return texto
1176
+
1177
+
1178
+ def _valor_texto_ajuste(valor: Any, vazio: Any = "") -> Any:
1179
+ """Match the blank-cell tokens pandas treats as NA in adjustment workbooks."""
1180
+ if isinstance(valor, str) and valor.strip().casefold() in {"na", "n/a", "#n/a", "<na>"}:
1181
+ return vazio
1182
+ return valor_texto(valor, vazio)
1183
+
1184
+
1185
+ def justificativa_pos_comentarios_exibicao(valor: Any) -> str:
1186
+ """Remove da comunicação final digressões sobre a antiga data-base."""
1187
+ texto_original = valor_texto(valor)
1188
+ frases = re.split(r"(?<=[.!?])\s+", texto_original)
1189
+ marca_historica = re.compile(
1190
+ r"data[- ]base|período da auditoria|época da auditoria|correç(?:ão|ao) posterior|regulariza(?:ção|cao) após",
1191
+ re.I,
1192
+ )
1193
+ limpas = [frase for frase in frases if not marca_historica.search(frase)]
1194
+ resultado = " ".join(limpas).strip()
1195
+ resultado = re.sub(r"^Ajuste pós-comentários do gestor:\s*situação\s+\S+\.\s*", "", resultado, flags=re.I)
1196
+ return resultado or "Ajuste decorrente da avaliação dos comentários e evidências apresentados pelo gestor."
1197
+
1198
+
1199
+ def resposta_ajustada_exibicao(item_codigo: Any, resposta_afirmada: Any, resposta_ajustada: Any = None) -> str:
1200
+ if resposta_ajustada is not None:
1201
+ texto = str(resposta_ajustada).strip()
1202
+ if texto and texto.lower() not in ("nan", "none", "vazio"):
1203
+ return texto
1204
+ if texto.lower() == "vazio":
1205
+ return ""
1206
+ item = str(item_codigo or "").strip()
1207
+ afirmada = valor_texto(resposta_afirmada)
1208
+ if "ext" in item.lower() or "[" in item:
1209
+ if afirmada.lower() in ("sim", "y"):
1210
+ return "Não" if afirmada.lower() == "sim" else ""
1211
+ return ""
1212
+ if re.match(r"^q\d{4}$", item.lower()):
1213
+ return "Não adota." if afirmada.endswith(".") else "Não adota"
1214
+ return ""
1215
+
1216
+
1217
+ def carregar_ajustes_respostas(path: Any) -> dict[str, list[dict[str, Any]]]:
1218
+ """Lê a planilha de ajustes e agrupa por auditado (formato do Apêndice B)."""
1219
+ from .evaluation import ler_xlsx
1220
+
1221
+ headers, rows = ler_xlsx(Path(str(path)))
1222
+ tem_ajustada = any(str(h).strip() == "Resposta ajustada" for h in headers)
1223
+ tem_resposta_anterior = any(str(h).strip() == "Resposta anterior" for h in headers)
1224
+ ajustes_por_auditado: dict[str, list[dict[str, Any]]] = {}
1225
+ for row in rows:
1226
+ auditado = row.get("Auditado")
1227
+ item_codigo = row.get("Código do item") if row.get("Código do item") not in (None, "") else row.get("Código do item avaliado")
1228
+ if auditado in (None, "") or item_codigo in (None, ""):
1229
+ continue
1230
+ resposta_ajustada_planilha = row.get("Resposta ajustada") if tem_ajustada else None
1231
+ if not tem_ajustada:
1232
+ revisor_val = _valor_texto_ajuste(row.get("Avaliação do auditor revisor"))
1233
+ juiz_val = _valor_texto_ajuste(row.get("Resultado da avaliação do juiz"))
1234
+ tem_revisor = (
1235
+ revisor_val not in (None, "")
1236
+ and str(revisor_val).strip() != ""
1237
+ and normalizar_texto_ajuste(revisor_val) != "sem_parecer"
1238
+ )
1239
+ resultado_final = revisor_val if tem_revisor else juiz_val
1240
+ if not is_nao_conforme_ajuste(resultado_final):
1241
+ continue
1242
+ justificativa = row.get("Justificativa do auditor revisor") if tem_revisor else row.get("Justificativa do juiz")
1243
+ else:
1244
+ justificativa = _valor_texto_ajuste(row.get("Justificativa"))
1245
+ if justificativa in (None, ""):
1246
+ justificativa = _valor_texto_ajuste(row.get("observacao"))
1247
+ if str(row.get("Origem") or "").startswith("secao_"):
1248
+ justificativa = justificativa_pos_comentarios_exibicao(justificativa)
1249
+ resposta_afirmada = _valor_texto_ajuste(row.get("Resposta afirmada"))
1250
+ if tem_ajustada and tem_resposta_anterior:
1251
+ previous_value = _valor_texto_ajuste(row.get("Resposta anterior"))
1252
+ final_value = _valor_texto_ajuste(resposta_ajustada_planilha)
1253
+ if str(previous_value).strip().casefold() == "vazio":
1254
+ previous_value = ""
1255
+ if str(final_value).strip().casefold() == "vazio":
1256
+ final_value = ""
1257
+ if previous_value == final_value:
1258
+ continue
1259
+ resposta_anterior = (
1260
+ row.get("Resposta anterior")
1261
+ if tem_ajustada and tem_resposta_anterior
1262
+ else resposta_afirmada
1263
+ )
1264
+ ajuste = {
1265
+ "codigo_questao": str(item_codigo).strip(),
1266
+ "de": _valor_texto_ajuste(resposta_anterior, vazio="Vazio"),
1267
+ "para": resposta_ajustada_exibicao(
1268
+ item_codigo,
1269
+ resposta_afirmada,
1270
+ _valor_texto_ajuste(resposta_ajustada_planilha, vazio=None),
1271
+ ),
1272
+ "justificativa": _valor_texto_ajuste(justificativa, vazio="Sem justificativa registrada"),
1273
+ }
1274
+ ajustes_por_auditado.setdefault(str(auditado).strip().upper(), []).append(ajuste)
1275
+ return ajustes_por_auditado
1276
+
1277
+
1278
+ def anexar_ajustes(contexto: dict[str, Any], ajustes: list[dict[str, Any]]) -> dict[str, Any]:
1279
+ """Injeta a seção de ajustes do Apêndice B no contexto do relatório."""
1280
+ enriquecido = dict(contexto)
1281
+ enriquecido["ajustes_respostas"] = list(ajustes or [])
1282
+ enriquecido["teve_ajuste"] = bool(ajustes)
1283
+ return enriquecido
1284
+
1285
+
1286
+ def _split_list(value: Any) -> tuple[str, ...]:
1287
+ if value in (None, ""):
1288
+ return ()
1289
+ return tuple(
1290
+ part.strip().upper()
1291
+ for part in re.split(r"[,;\n]+", str(value))
1292
+ if part.strip()
1293
+ )
1294
+
1295
+
1296
+ def _format_item(field: str) -> str:
1297
+ match = re.search(r"\bq(\d{4})(?:[A-Za-z]+)?(?:\[([A-Za-z0-9]+)\])?", field, flags=re.I)
1298
+ if match is None:
1299
+ return field
1300
+ item, alternative = match.groups()
1301
+ if alternative:
1302
+ alternative = alternative.lower() if alternative.isalpha() else alternative
1303
+ return f"subitem {alternative}) do item {item}"
1304
+ return f"item {item}"
1305
+
1306
+
1307
+ def _safe_compare(value: Any, condition: Any) -> bool:
1308
+ text_condition = str(condition or "").strip()
1309
+ value_text = "" if value is None else str(value).strip()
1310
+ for operator in (">=", "<=", "!=", "==", ">", "<"):
1311
+ if not text_condition.startswith(operator):
1312
+ continue
1313
+ target = text_condition[len(operator) :].strip().strip("'\"")
1314
+ try:
1315
+ left: Any = float(value) if isinstance(value, (bool, int, float)) else float(value_text.replace(",", "."))
1316
+ right: Any = float(target.replace(",", "."))
1317
+ except ValueError:
1318
+ left, right = value_text, target
1319
+ return {
1320
+ ">=": left >= right,
1321
+ "<=": left <= right,
1322
+ "!=": left != right,
1323
+ "==": left == right,
1324
+ ">": left > right,
1325
+ "<": left < right,
1326
+ }[operator]
1327
+ try:
1328
+ return (float(value) if isinstance(value, (bool, int, float)) else float(value_text.replace(",", "."))) == float(
1329
+ text_condition.strip("'\"")
1330
+ )
1331
+ except ValueError:
1332
+ return normalize(value_text) == normalize(text_condition.strip("'\""))
1333
+
1334
+
1335
+ @dataclass(frozen=True)
1336
+ class _ValueExpression:
1337
+ """Condição de inconformidade compilada pela gramática lógica única."""
1338
+
1339
+ node: LogicNode
1340
+
1341
+ @classmethod
1342
+ def compile(cls, expression: Any, *, action_id: str) -> _ValueExpression:
1343
+ node = compile_logic(
1344
+ expression,
1345
+ label=f"situação_inconforme da ação {action_id}",
1346
+ )
1347
+ return cls(node)
1348
+
1349
+ def evaluate(self, value: Any) -> bool:
1350
+ return evaluate_logic(self.node, lambda atom: _safe_compare(value, atom))
1351
+
1352
+
1353
+ @dataclass(frozen=True)
1354
+ class _FindingExpression:
1355
+ """Lógica de achado compilada pela gramática lógica única."""
1356
+
1357
+ node: LogicNode
1358
+
1359
+ @property
1360
+ def action_ids(self) -> frozenset[str]:
1361
+ def atoms(node: LogicNode):
1362
+ if node.kind == "atom":
1363
+ yield node.atom.upper()
1364
+ for child in node.children:
1365
+ yield from atoms(child)
1366
+
1367
+ return frozenset(atoms(self.node))
1368
+
1369
+ @classmethod
1370
+ def compile(
1371
+ cls,
1372
+ expression: Any,
1373
+ *,
1374
+ procedure_id: str,
1375
+ action_ids: Iterable[str],
1376
+ ) -> _FindingExpression:
1377
+ known = frozenset(str(item).upper() for item in action_ids)
1378
+
1379
+ def validate_atom(atom: str) -> None:
1380
+ if str(atom).upper() not in known:
1381
+ raise InputValidationError(
1382
+ f"logica_achado do procedimento {procedure_id} "
1383
+ f"possui token inválido: {atom!r}"
1384
+ )
1385
+
1386
+ node = compile_logic(
1387
+ expression,
1388
+ label=f"logica_achado do procedimento {procedure_id}",
1389
+ validate_atom=validate_atom,
1390
+ )
1391
+ return cls(node)
1392
+
1393
+ def evaluate(self, values: Mapping[str, bool]) -> bool:
1394
+ normalized = {str(key).upper(): bool(value) for key, value in values.items()}
1395
+ return evaluate_logic(self.node, lambda atom: normalized[str(atom).upper()])
1396
+
1397
+
1398
+ @dataclass(frozen=True)
1399
+ class _NumericExpression:
1400
+ tree: ast.Expression
1401
+ columns: Mapping[str, str]
1402
+
1403
+ @classmethod
1404
+ def compile(
1405
+ cls,
1406
+ expression: str,
1407
+ headers: Iterable[str],
1408
+ *,
1409
+ variable_id: str,
1410
+ ) -> _NumericExpression:
1411
+ prepared = str(expression or "")
1412
+ columns: dict[str, str] = {}
1413
+ names = sorted({str(item) for item in headers if item}, key=lambda name: (-len(name), name))
1414
+ aliases = {column: f"__column_{index}" for index, column in enumerate(names)}
1415
+ if names:
1416
+ pattern = re.compile(r"(?<!\w)(?:" + "|".join(re.escape(name) for name in names) + r")(?!\w)")
1417
+
1418
+ def replace(match: re.Match) -> str:
1419
+ column = match.group(0)
1420
+ token = aliases[column]
1421
+ columns[token] = column
1422
+ return token
1423
+
1424
+ # Textos literais não são referências a colunas. Substituição em
1425
+ # uma passagem também evita modificar os aliases já produzidos.
1426
+ pieces = re.split(r'''('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")''', prepared)
1427
+ prepared = "".join(piece if index % 2 else pattern.sub(replace, piece) for index, piece in enumerate(pieces))
1428
+ try:
1429
+ tree = ast.parse(prepared, mode="eval")
1430
+ except SyntaxError as exc:
1431
+ raise InputValidationError(
1432
+ f"variável temporária {variable_id} possui expressão inválida: {expression}"
1433
+ ) from exc
1434
+ allowed = (
1435
+ ast.Expression,
1436
+ ast.Constant,
1437
+ ast.Name,
1438
+ ast.Load,
1439
+ ast.UnaryOp,
1440
+ ast.UAdd,
1441
+ ast.USub,
1442
+ ast.BinOp,
1443
+ ast.Add,
1444
+ ast.Sub,
1445
+ ast.Mult,
1446
+ ast.Div,
1447
+ ast.BitOr,
1448
+ ast.BitAnd,
1449
+ ast.BoolOp,
1450
+ ast.Or,
1451
+ ast.And,
1452
+ ast.Not,
1453
+ ast.Compare,
1454
+ ast.Lt,
1455
+ ast.LtE,
1456
+ ast.Gt,
1457
+ ast.GtE,
1458
+ ast.Eq,
1459
+ ast.NotEq,
1460
+ )
1461
+ for node in ast.walk(tree):
1462
+ if not isinstance(node, allowed):
1463
+ raise InputValidationError(
1464
+ f"variável temporária {variable_id} usa operação não permitida"
1465
+ )
1466
+ if isinstance(node, ast.Name) and node.id not in columns:
1467
+ raise InputValidationError(
1468
+ f"variável temporária {variable_id} referencia coluna ausente: {node.id}"
1469
+ )
1470
+ if isinstance(node, ast.Constant) and not isinstance(node.value, (int, float, str)):
1471
+ raise InputValidationError(
1472
+ f"variável temporária {variable_id} deve usar números ou textos literais"
1473
+ )
1474
+ return cls(tree, columns)
1475
+
1476
+ def evaluate(self, row: Mapping[str, Any]) -> float | bool | None:
1477
+ def visit(node: ast.AST) -> Any:
1478
+ if isinstance(node, ast.Expression):
1479
+ return visit(node.body)
1480
+ if isinstance(node, ast.Constant):
1481
+ return node.value if isinstance(node.value, str) else float(node.value)
1482
+ if isinstance(node, ast.Name):
1483
+ value = row.get(self.columns[node.id])
1484
+ if value in (None, ""):
1485
+ return None
1486
+ try:
1487
+ return float(value) if isinstance(value, (bool, int, float)) else float(str(value).replace(",", "."))
1488
+ except ValueError:
1489
+ return str(value)
1490
+ if isinstance(node, ast.UnaryOp):
1491
+ value = visit(node.operand)
1492
+ if isinstance(node.op, ast.Not):
1493
+ return not value
1494
+ return value if isinstance(node.op, ast.UAdd) else -value
1495
+ if isinstance(node, ast.BoolOp):
1496
+ values = [bool(visit(value)) for value in node.values]
1497
+ return all(values) if isinstance(node.op, ast.And) else any(values)
1498
+ if isinstance(node, ast.BinOp):
1499
+ left, right = visit(node.left), visit(node.right)
1500
+ if isinstance(node.op, ast.BitOr):
1501
+ return bool(left) or bool(right)
1502
+ if isinstance(node.op, ast.BitAnd):
1503
+ return bool(left) and bool(right)
1504
+ if isinstance(node.op, ast.Add):
1505
+ return left + right
1506
+ if isinstance(node.op, ast.Sub):
1507
+ return left - right
1508
+ if isinstance(node.op, ast.Mult):
1509
+ return left * right
1510
+ return left / right if right else 0.0
1511
+ if isinstance(node, ast.Compare):
1512
+ left = visit(node.left)
1513
+ results: list[bool] = []
1514
+ for operator, comparator in zip(node.ops, node.comparators):
1515
+ right = visit(comparator)
1516
+ if isinstance(operator, ast.Gt):
1517
+ results.append(left > right)
1518
+ elif isinstance(operator, ast.Lt):
1519
+ results.append(left < right)
1520
+ elif isinstance(operator, ast.GtE):
1521
+ results.append(left >= right)
1522
+ elif isinstance(operator, ast.LtE):
1523
+ results.append(left <= right)
1524
+ elif isinstance(operator, ast.Eq):
1525
+ results.append(left == right)
1526
+ else:
1527
+ results.append(left != right)
1528
+ left = right
1529
+ return all(results)
1530
+ raise ValueError("expressão numérica inválida")
1531
+
1532
+ try:
1533
+ return visit(self.tree)
1534
+ except (TypeError, ValueError, ZeroDivisionError):
1535
+ return None
1536
+
1537
+
1538
+ @dataclass(frozen=True)
1539
+ class _SourceDefinition:
1540
+ identifier: str
1541
+ filepath: str
1542
+ key: str
1543
+
1544
+
1545
+ @dataclass(frozen=True)
1546
+ class _VariableDefinition:
1547
+ identifier: str
1548
+ source_id: str
1549
+ name: str
1550
+ expression: str
1551
+
1552
+
1553
+ @dataclass(frozen=True)
1554
+ class _ActionDefinition:
1555
+ identifier: str
1556
+ source_id: str
1557
+ fields: tuple[str, ...]
1558
+ condition: _ValueExpression
1559
+ empty_is_finding: bool
1560
+ missing_auditee_is_finding: bool
1561
+ exclusive_auditees: tuple[str, ...]
1562
+ metadata: Mapping[str, Any]
1563
+ situation_logic: _FindingExpression | None = None
1564
+
1565
+
1566
+ @dataclass(frozen=True)
1567
+ class _ProcedureDefinition:
1568
+ identifier: str
1569
+ logic: _FindingExpression
1570
+ metadata: Mapping[str, Any]
1571
+ reasons: tuple[Any, ...] = ()
1572
+ action_ids: tuple[str, ...] = ()
1573
+
1574
+ def __post_init__(self) -> None:
1575
+ object.__setattr__(self, "action_ids", tuple(sorted(self.logic.action_ids)))
1576
+
1577
+
1578
+ @dataclass(frozen=True)
1579
+ class VerificationResult:
1580
+ """Resultado calculado, ainda sem materialização de Produtos."""
1581
+
1582
+ _rows: Mapping[str, Mapping[str, Any]]
1583
+ _trace: Mapping[str, Mapping[str, Any]]
1584
+ _sources: Mapping[str, Path] = dataclass_field(default_factory=dict)
1585
+
1586
+ @property
1587
+ def sources(self) -> Mapping[str, Path]:
1588
+ """Arquivo efetivamente lido para cada fonte do mapa."""
1589
+ return self._sources
1590
+
1591
+ @property
1592
+ def summary(self) -> dict[str, Any]:
1593
+ return {
1594
+ "audited_count": len(self._rows),
1595
+ "findings_count": sum(len(item["achados"]) for item in self._rows.values()),
1596
+ }
1597
+
1598
+ def compact(self) -> dict[str, dict[str, Any]]:
1599
+ fields = (
1600
+ "id",
1601
+ "sigla",
1602
+ "nome",
1603
+ "foi_auditado",
1604
+ "respondeu_questionario",
1605
+ "esfera",
1606
+ "segmento_institucional",
1607
+ "natureza_administrativa",
1608
+ "tags_aplicabilidade",
1609
+ "status_avaliacao",
1610
+ "motivo_nao_avaliacao",
1611
+ "tem_achados",
1612
+ "procedimentos_executados",
1613
+ "achados",
1614
+ "acoes",
1615
+ )
1616
+ return {
1617
+ sigla: {field: data[field] for field in fields}
1618
+ for sigla, data in self._rows.items()
1619
+ }
1620
+
1621
+ def tables(self) -> dict[str, list[dict[str, Any]]]:
1622
+ """Tabelas de leitura: achados, situações e encaminhamentos por extenso; ações enxutas."""
1623
+ catalog_labels = {
1624
+ "id_fonte_informacao": "Fonte",
1625
+ "informacao_requerida": "Informação requerida",
1626
+ "id_situacao": "Situação",
1627
+ "criterio": "Critério declarado",
1628
+ "logica_situacao": "Lógica da situação",
1629
+ "descricao_situacao_inconforme": "Situação inconforme",
1630
+ "tipo_encaminhamento": "Tipo de encaminhamento declarado",
1631
+ "encaminhamento": "Encaminhamento declarado",
1632
+ }
1633
+ catalog: dict[str, dict[str, Any]] = {}
1634
+ action_rows, situation_rows, referral_rows = [], [], []
1635
+ for sigla, data in self._rows.items():
1636
+ for action_id, item in data["acoes"].items():
1637
+ if action_id not in catalog and "resultado" in item and not item.get("skipped"):
1638
+ catalog[action_id] = {"Ação": action_id, **{label: item.get(key) for key, label in catalog_labels.items()}}
1639
+ action_rows.append({
1640
+ "Auditado": sigla,
1641
+ "Ação": action_id,
1642
+ "Situação": item.get("id_situacao"),
1643
+ "Resultado": item.get("resultado"),
1644
+ "Resultado da situação": item.get("resultado_situacao"),
1645
+ "Valores encontrados": item.get("situacoes_encontradas"),
1646
+ "Evidência": item.get("descricao_evidencia"),
1647
+ "Fonte": item.get("source"),
1648
+ })
1649
+ for procedure in data["procedimentos_executados"]:
1650
+ achado = procedure.get("numero_achado") or procedure.get("nome_achado")
1651
+ for situation in procedure.get("situacoes_detalhadas") or []:
1652
+ situation_rows.append({
1653
+ "Auditado": sigla,
1654
+ "Achado": achado,
1655
+ "Situação": situation.get("id_situacao"),
1656
+ "Variante": situation.get("id_variante"),
1657
+ "Descrição": situation.get("descricao"),
1658
+ "Critérios": " | ".join(
1659
+ f"{c.get('id_exibicao') or c.get('id')}: {c.get('descricao')}"
1660
+ for c in situation.get("criterios") or [] if isinstance(c, Mapping)
1661
+ ),
1662
+ "Motivos": " | ".join(
1663
+ str(m.get("descricao") or "") for m in situation.get("motivos") or [] if isinstance(m, Mapping)
1664
+ ),
1665
+ "Ações de origem": situation.get("id_acoes") or [],
1666
+ })
1667
+ for referral in procedure.get("encaminhamentos") or []:
1668
+ criteria = referral.get("criterios") or []
1669
+ referral_rows.append({
1670
+ "Auditado": sigla,
1671
+ "Procedimento": procedure.get("id"),
1672
+ "Achado": achado,
1673
+ "Situação": referral.get("id_situacao"),
1674
+ "Variante": referral.get("id_variante"),
1675
+ "Tipo": referral.get("tipo"),
1676
+ "Encaminhamento": referral.get("encaminhamento"),
1677
+ "Fundamentação": referral.get("fundamentacao_encaminhamento"),
1678
+ "IDs dos critérios": " | ".join(
1679
+ str(item["id"]) for item in criteria
1680
+ if isinstance(item, Mapping) and item.get("id")
1681
+ ),
1682
+ "Critérios": criteria,
1683
+ "Ações de origem": referral.get("id_acoes") or [],
1684
+ })
1685
+ return {
1686
+ "Status": [
1687
+ {
1688
+ "Auditado": sigla,
1689
+ "Nome": data["nome"],
1690
+ "Status da avaliação": data["status_avaliacao"],
1691
+ "Respondeu ao questionário": {True: "Sim", False: "Não"}.get(data.get("respondeu_questionario"), ""),
1692
+ "Tem achados": "Sim" if data["tem_achados"] else "Não",
1693
+ }
1694
+ for sigla, data in self._rows.items()
1695
+ ],
1696
+ "Não respondentes": [
1697
+ {"Auditado": sigla, "Nome": data["nome"], "Status da avaliação": data["status_avaliacao"]}
1698
+ for sigla, data in self._rows.items()
1699
+ if data.get("respondeu_questionario") is False
1700
+ ],
1701
+ "Achados": [
1702
+ {
1703
+ "Auditado": sigla,
1704
+ "Achado": key,
1705
+ "Nome": item.get("nome_achado"),
1706
+ "Situações": " | ".join(item.get("situacoes_inconformes", [])),
1707
+ }
1708
+ for sigla, data in self._rows.items()
1709
+ for key, item in data["achados"].items()
1710
+ ],
1711
+ "Situações": situation_rows,
1712
+ "Encaminhamentos": referral_rows,
1713
+ "Ações": action_rows,
1714
+ "Catálogo": [catalog[key] for key in sorted(catalog)],
1715
+ }
1716
+
1717
+ def detailed(self) -> dict[str, Any]:
1718
+ """Projeta a trilha calculada sem reavaliar ações ou procedimentos."""
1719
+ return {
1720
+ "schema_version": "argos.audit-trace/v1",
1721
+ "summary": self.summary,
1722
+ "auditados": {
1723
+ sigla: {
1724
+ "status_avaliacao": data["status_avaliacao"],
1725
+ "motivo_nao_avaliacao": data["motivo_nao_avaliacao"],
1726
+ "acoes": [
1727
+ {"id": identifier, **dict(action)}
1728
+ for identifier, action in data["acoes"].items()
1729
+ ],
1730
+ "procedimentos": [dict(item) for item in data["procedimentos"]],
1731
+ }
1732
+ for sigla, data in self._trace.items()
1733
+ },
1734
+ }
1735
+
1736
+
1737
+ @dataclass(frozen=True)
1738
+ class VerificationMap:
1739
+ """Mapa validado e compilado, reutilizável sobre fontes compatíveis."""
1740
+
1741
+ _sources: tuple[_SourceDefinition, ...]
1742
+ _variables: tuple[_VariableDefinition, ...]
1743
+ _actions: tuple[_ActionDefinition, ...]
1744
+ _procedures: tuple[_ProcedureDefinition, ...]
1745
+ _reasons: tuple[Any, ...] = ()
1746
+
1747
+ @classmethod
1748
+ def compile(cls, path: Path) -> VerificationMap:
1749
+ path = _require_file(path, "mapa de verificação")
1750
+ load_workbook = openpyxl_workbook()
1751
+ workbook = load_workbook(path, read_only=True, data_only=True)
1752
+ try:
1753
+ sheets = {sheet.title: sheet for sheet in workbook.worksheets}
1754
+ if "Revisão" in sheets:
1755
+ reviews = sheet_records(sheets["Revisão"], required=("aprovado", "revisor"))[2]
1756
+ if len(reviews) != 1 or not parse_bool(reviews[0].get("aprovado"), default=False) or not str(reviews[0].get("revisor") or "").strip():
1757
+ raise InputValidationError("mapa em draft: registrar aprovação humana e revisor na aba Revisão")
1758
+ if "Pendências" not in sheets:
1759
+ raise InputValidationError("mapa revisável sem aba Pendências")
1760
+ pending = sheet_records(sheets["Pendências"], required=("id", "resolvida", "resolucao"))[2]
1761
+ if any(not parse_bool(row.get("resolvida"), default=False) or not str(row.get("resolucao") or "").strip() for row in pending):
1762
+ raise InputValidationError("mapa com pendências não resolvidas; revisar antes da execução")
1763
+ required = {
1764
+ "Fontes de Informação",
1765
+ "Ações de Verificação",
1766
+ "Procedimentos de Auditoria",
1767
+ }
1768
+ missing = sorted(required - set(sheets))
1769
+ if missing:
1770
+ raise InputValidationError(f"abas ausentes no mapa: {', '.join(missing)}")
1771
+ source_rows = sheet_records(
1772
+ sheets["Fontes de Informação"], required=("id",)
1773
+ )[2]
1774
+ action_rows = sheet_records(
1775
+ sheets["Ações de Verificação"], required=("id",)
1776
+ )[2]
1777
+ procedure_rows = sheet_records(
1778
+ sheets["Procedimentos de Auditoria"], required=("id",)
1779
+ )[2]
1780
+ variable_rows = (
1781
+ sheet_records(sheets["Variáveis Temporárias"], required=("id",))[2]
1782
+ if "Variáveis Temporárias" in sheets
1783
+ else []
1784
+ )
1785
+ reason_rows = sheet_records(sheets["Motivos do Relatório"], required=("id",))[2] if "Motivos do Relatório" in sheets else []
1786
+ finally:
1787
+ workbook.close()
1788
+
1789
+ source_map = _rows_by_id(source_rows, "Fontes de Informação")
1790
+ action_map = _rows_by_id(action_rows, "Ações de Verificação")
1791
+ procedure_map = _rows_by_id(procedure_rows, "Procedimentos de Auditoria")
1792
+ variable_map = _rows_by_id(variable_rows, "Variáveis Temporárias")
1793
+ source_definitions: list[_SourceDefinition] = []
1794
+ for identifier, row in source_map.items():
1795
+ filepath = str(row.get("filepath") or "").strip()
1796
+ key = str(row.get("chave_jurisdicionado") or "").strip()
1797
+ if not filepath:
1798
+ raise InputValidationError(f"fonte {identifier!r} sem filepath no mapa")
1799
+ if not key:
1800
+ raise InputValidationError(f"fonte {identifier!r} sem chave_jurisdicionado no mapa")
1801
+ source_definitions.append(
1802
+ _SourceDefinition(identifier=identifier, filepath=filepath, key=key)
1803
+ )
1804
+ sources = tuple(source_definitions)
1805
+ variables: list[_VariableDefinition] = []
1806
+ for identifier, row in variable_map.items():
1807
+ source_id = str(row.get("id_fonte_informacao") or "").strip()
1808
+ name = str(row.get("nome") or "").strip()
1809
+ expression = str(row.get("expressao") or "").strip()
1810
+ if source_id not in source_map:
1811
+ raise InputValidationError(
1812
+ f"variável temporária {identifier} referencia fonte desconhecida: {source_id}"
1813
+ )
1814
+ if not name or not expression:
1815
+ raise InputValidationError(f"variável temporária inválida: {identifier}")
1816
+ variables.append(_VariableDefinition(identifier, source_id, name, expression))
1817
+ actions: list[_ActionDefinition] = []
1818
+ for identifier, row in action_map.items():
1819
+ source_id = str(row.get("id_fonte_informacao") or "").strip()
1820
+ if source_id not in source_map:
1821
+ raise InputValidationError(
1822
+ f"ação {identifier} referencia fonte desconhecida: {source_id}"
1823
+ )
1824
+ fields = tuple(
1825
+ part.strip()
1826
+ for part in str(row.get("informacao_requerida") or "").split("|")
1827
+ if part.strip()
1828
+ )
1829
+ if not fields:
1830
+ raise InputValidationError(
1831
+ f"ação {identifier} não possui informacao_requerida"
1832
+ )
1833
+ actions.append(
1834
+ _ActionDefinition(
1835
+ identifier=identifier,
1836
+ source_id=source_id,
1837
+ fields=fields,
1838
+ condition=_ValueExpression.compile(
1839
+ row.get("situacao_inconforme"), action_id=identifier
1840
+ ),
1841
+ empty_is_finding=parse_bool(
1842
+ row.get("situacao_encontrada_nan_e_achado"), default=False
1843
+ ),
1844
+ missing_auditee_is_finding=parse_bool(
1845
+ row.get("auditado_inexistente_e_achado"), default=False
1846
+ ),
1847
+ exclusive_auditees=_split_list(row.get("acao_exclusiva_auditados")),
1848
+ metadata=dict(row),
1849
+ situation_logic=(
1850
+ _FindingExpression.compile(row["logica_situacao"], procedure_id=f"situação de {identifier}", action_ids=action_map)
1851
+ if str(row.get("logica_situacao") or "").strip() else None
1852
+ ),
1853
+ )
1854
+ )
1855
+ reasons = compile_reasons(reason_rows, procedure_map, action_map)
1856
+ rules_by_procedure = {identifier: tuple(rule for rule in reasons if rule.procedure == identifier) for identifier in procedure_map}
1857
+ procedures = tuple(
1858
+ _ProcedureDefinition(
1859
+ identifier=identifier,
1860
+ logic=_FindingExpression.compile(
1861
+ row.get("logica_achado"),
1862
+ procedure_id=identifier,
1863
+ action_ids=action_map,
1864
+ ),
1865
+ metadata=dict(row),
1866
+ reasons=rules_by_procedure[identifier],
1867
+ )
1868
+ for identifier, row in procedure_map.items()
1869
+ )
1870
+ return cls(sources, tuple(variables), tuple(actions), procedures, reasons)
1871
+
1872
+ def execute(
1873
+ self,
1874
+ auditados_path: Path,
1875
+ source_paths: Iterable[Path],
1876
+ *,
1877
+ source_map: Mapping[str, Path] | None = None,
1878
+ matrix: Any = None,
1879
+ questionnaire_source: str | None = None,
1880
+ ) -> VerificationResult:
1881
+ auditados = self._load_auditees(_require_file(auditados_path, "auditados"))
1882
+ sources = self._load_sources(tuple(source_paths), source_map or {})
1883
+ if questionnaire_source and questionnaire_source not in sources:
1884
+ raise InputValidationError(f"fonte_questionario não é uma fonte do mapa: {questionnaire_source}")
1885
+ answers = sources.get(questionnaire_source) if questionnaire_source else None
1886
+ planning = _planning_situations(matrix) if matrix is not None else {}
1887
+ action_results: dict[str, dict[str, dict[str, Any]]] = {}
1888
+ responded: dict[str, bool] = {}
1889
+ questionnaire = sources.get("questionario")
1890
+ for auditado in auditados:
1891
+ sigla = auditado["sigla"]
1892
+ # Fiscalizações documentais podem não ter fonte questionario.
1893
+ # Quando ela existe, preservar a política de não respondentes.
1894
+ has_response = questionnaire is None or questionnaire["rows"].get(normalize(sigla)) is not None
1895
+ responded[sigla] = has_response
1896
+ action_results[sigla] = (
1897
+ self._execute_actions(sigla, sources) if has_response else {}
1898
+ )
1899
+ rows = {}
1900
+ trace = {}
1901
+ for auditado in auditados:
1902
+ sigla = auditado["sigla"]
1903
+ actions = action_results[sigla]
1904
+ if questionnaire is not None:
1905
+ answered: bool | None = responded[sigla]
1906
+ elif answers is not None:
1907
+ # A fonte declarada só marca quem respondeu; não muda quem é avaliado.
1908
+ answered = answers["rows"].get(normalize(sigla)) is not None
1909
+ else:
1910
+ answered = None
1911
+ row = self._build_auditee_result(
1912
+ auditado,
1913
+ actions,
1914
+ responded[sigla],
1915
+ answered=answered,
1916
+ planning=planning,
1917
+ )
1918
+ rows[sigla] = row
1919
+ procedure_results = {str(item["id"]): item for item in row["procedimentos_executados"]}
1920
+ trace[sigla] = {
1921
+ "status_avaliacao": row["status_avaliacao"],
1922
+ "motivo_nao_avaliacao": row["motivo_nao_avaliacao"],
1923
+ "acoes": row["acoes"],
1924
+ "procedimentos": [
1925
+ {
1926
+ "id": definition.identifier,
1927
+ "numero_achado": definition.metadata.get("numero_achado"),
1928
+ "logica_achado": definition.metadata.get("logica_achado"),
1929
+ "acoes_referenciadas": [
1930
+ {
1931
+ "id": action_id,
1932
+ "resultado": actions.get(action_id, {}).get("resultado"),
1933
+ "resultado_situacao": actions.get(action_id, {}).get("resultado_situacao"),
1934
+ }
1935
+ for action_id in definition.action_ids
1936
+ ],
1937
+ "achado_ocorreu": procedure_results.get(definition.identifier, {}).get("achado_ocorreu"),
1938
+ }
1939
+ for definition in self._procedures
1940
+ ] if responded[sigla] else [],
1941
+ }
1942
+ return VerificationResult(rows, trace, {identifier: item["path"] for identifier, item in sources.items()})
1943
+
1944
+ @staticmethod
1945
+ def _load_auditees(path: Path) -> list[dict[str, Any]]:
1946
+ load_workbook = openpyxl_workbook()
1947
+ workbook = load_workbook(path, read_only=True, data_only=True)
1948
+ try:
1949
+ _, headers, rows = sheet_records(workbook.active, required=("sigla",))
1950
+ finally:
1951
+ workbook.close()
1952
+ sigla_column = find_column(headers, ("sigla",))
1953
+ name_column = find_column(headers, ("orgao",))
1954
+ sphere_column = find_column(headers, ("esfera",))
1955
+ segment_column = find_column(headers, ("segmento_institucional",))
1956
+ nature_column = find_column(headers, ("natureza_administrativa",))
1957
+ tags_column = find_column(headers, ("tags_aplicabilidade",))
1958
+ return [
1959
+ {
1960
+ "sigla": str(row.get(sigla_column, "")).strip(),
1961
+ "nome": row.get(name_column) if name_column else None,
1962
+ "esfera": row.get(sphere_column) if sphere_column else None,
1963
+ "segmento_institucional": row.get(segment_column) if segment_column else None,
1964
+ "natureza_administrativa": row.get(nature_column) if nature_column else None,
1965
+ "tags_aplicabilidade": row.get(tags_column) if tags_column else None,
1966
+ }
1967
+ for row in rows
1968
+ if row.get(sigla_column) not in (None, "")
1969
+ ]
1970
+
1971
+ def _load_sources(
1972
+ self,
1973
+ paths: tuple[Path, ...],
1974
+ explicit: Mapping[str, Path],
1975
+ ) -> dict[str, dict[str, Any]]:
1976
+ if not paths:
1977
+ raise MissingInputError("informe ao menos uma fonte XLSX para a auditoria")
1978
+ files_by_name = {Path(path).name.casefold(): Path(path) for path in paths}
1979
+ unknown_mappings = sorted(
1980
+ set(explicit) - {item.identifier for item in self._sources}
1981
+ )
1982
+ if unknown_mappings:
1983
+ raise InputValidationError(
1984
+ f"mapa_fontes referencia fontes desconhecidas: {', '.join(unknown_mappings)}"
1985
+ )
1986
+ loaded: dict[str, dict[str, Any]] = {}
1987
+ load_workbook = openpyxl_workbook()
1988
+ for definition in self._sources:
1989
+ actual = explicit.get(definition.identifier) or files_by_name.get(
1990
+ Path(definition.filepath).name.casefold()
1991
+ )
1992
+ if actual is None and len(paths) == 1:
1993
+ actual = paths[0]
1994
+ if actual is None:
1995
+ raise MissingInputError(
1996
+ f"fonte do mapa não foi fornecida: {definition.identifier}"
1997
+ )
1998
+ actual = _require_file(Path(actual), f"fonte {definition.identifier}")
1999
+ workbook = load_workbook(actual, read_only=True, data_only=True)
2000
+ try:
2001
+ _, headers, rows = sheet_records(workbook.active)
2002
+ finally:
2003
+ workbook.close()
2004
+ if definition.key and definition.key not in headers:
2005
+ raise InputValidationError(
2006
+ f"fonte {definition.identifier} não possui chave "
2007
+ f"{definition.key!r}"
2008
+ )
2009
+ indexed: dict[str, dict[str, Any]] = {}
2010
+ for row in rows:
2011
+ if definition.key and row.get(definition.key) not in (None, ""):
2012
+ indexed[normalize(row[definition.key])] = row
2013
+ elif not definition.key:
2014
+ indexed.setdefault("*", row)
2015
+ for variable in self._variables:
2016
+ if variable.source_id != definition.identifier:
2017
+ continue
2018
+ compiled = _NumericExpression.compile(
2019
+ variable.expression,
2020
+ headers,
2021
+ variable_id=variable.identifier,
2022
+ )
2023
+ for row in indexed.values():
2024
+ row[variable.name] = compiled.evaluate(row)
2025
+ headers = [*headers, variable.name]
2026
+ required_fields = {
2027
+ field
2028
+ for action in self._actions
2029
+ if action.source_id == definition.identifier
2030
+ for field in action.fields
2031
+ }
2032
+ missing_fields = sorted(required_fields - set(headers))
2033
+ if missing_fields:
2034
+ raise InputValidationError(
2035
+ f"fonte {definition.identifier} não possui colunas requeridas: "
2036
+ f"{', '.join(missing_fields)}"
2037
+ )
2038
+ loaded[definition.identifier] = {
2039
+ "definition": definition,
2040
+ "rows": indexed,
2041
+ "path": actual,
2042
+ }
2043
+ return loaded
2044
+
2045
+ def _execute_actions(
2046
+ self,
2047
+ sigla: str,
2048
+ sources: Mapping[str, Mapping[str, Any]],
2049
+ ) -> dict[str, dict[str, Any]]:
2050
+ results: dict[str, dict[str, Any]] = {}
2051
+ for action in self._actions:
2052
+ if action.exclusive_auditees and sigla.upper() not in action.exclusive_auditees:
2053
+ results[action.identifier] = {"resultado": False, "skipped": True}
2054
+ continue
2055
+ source = sources[action.source_id]
2056
+ definition = source["definition"]
2057
+ source_row = (
2058
+ source["rows"].get(normalize(sigla))
2059
+ if definition.key
2060
+ else source["rows"].get("*")
2061
+ )
2062
+ metadata = action.metadata
2063
+ if source_row is None:
2064
+ results[action.identifier] = {
2065
+ **dict(metadata),
2066
+ "resultado": action.missing_auditee_is_finding,
2067
+ "situacao_encontrada": None,
2068
+ "descricao_evidencia": metadata.get(
2069
+ "descricao_auditado_inexistente"
2070
+ ),
2071
+ "source": action.source_id,
2072
+ "informacao_requerida": list(action.fields),
2073
+ }
2074
+ continue
2075
+ checks: list[bool] = []
2076
+ found_values: list[Any] = []
2077
+ evidence = str(metadata.get("descricao_evidencia") or "")
2078
+ for field in action.fields:
2079
+ found = source_row.get(field)
2080
+ found_values.append(found)
2081
+ check = action.empty_is_finding and found in (None, "")
2082
+ if not check:
2083
+ check = action.condition.evaluate(found)
2084
+ checks.append(check)
2085
+ replacement = str(found) if found is not None else ""
2086
+ evidence = evidence.replace("@", replacement)
2087
+ evidence = evidence.replace("{situacao_encontrada}", replacement)
2088
+ evidence = evidence.replace("{item_avaliado}", _format_item(field))
2089
+ for placeholder, column_suffix in (("avaliacao_justificativa", "__justificativa"), ("resposta_afirmada", "__resposta_afirmada"), ("pratica", "__pratica")):
2090
+ auxiliary = source_row.get(field + column_suffix)
2091
+ evidence = evidence.replace("{" + placeholder + "}", "" if auxiliary is None else str(auxiliary))
2092
+ results[action.identifier] = {
2093
+ **dict(metadata),
2094
+ "resultado": all(checks),
2095
+ "situacao_encontrada": found_values[-1] if found_values else None,
2096
+ "situacoes_encontradas": found_values,
2097
+ "descricao_evidencia": evidence,
2098
+ "source": action.source_id,
2099
+ "informacao_requerida": list(action.fields),
2100
+ "situacao_inconforme": metadata.get("situacao_inconforme"),
2101
+ "descricao_situacao_inconforme": metadata.get(
2102
+ "descricao_situacao_inconforme"
2103
+ ),
2104
+ "tipo_encaminhamento": metadata.get("tipo_encaminhamento"),
2105
+ "encaminhamento": metadata.get("encaminhamento"),
2106
+ }
2107
+ action_values = {identifier: bool(item.get("resultado")) for identifier, item in results.items()}
2108
+ for action in self._actions:
2109
+ if action.situation_logic is not None:
2110
+ results[action.identifier]["resultado_situacao"] = action.situation_logic.evaluate(action_values)
2111
+ return results
2112
+
2113
+ def _build_auditee_result(
2114
+ self,
2115
+ auditado: Mapping[str, Any],
2116
+ actions: Mapping[str, Mapping[str, Any]],
2117
+ responded: bool,
2118
+ *,
2119
+ answered: bool | None = None,
2120
+ planning: Mapping[str, Any] | None = None,
2121
+ ) -> dict[str, Any]:
2122
+ sigla = str(auditado["sigla"])
2123
+ base = {
2124
+ "id": sigla,
2125
+ "sigla": sigla,
2126
+ "nome": auditado.get("nome"),
2127
+ "esfera": auditado.get("esfera"),
2128
+ "segmento_institucional": auditado.get("segmento_institucional"),
2129
+ "natureza_administrativa": auditado.get("natureza_administrativa"),
2130
+ "tags_aplicabilidade": auditado.get("tags_aplicabilidade"),
2131
+ }
2132
+ if not responded:
2133
+ return {
2134
+ **base,
2135
+ "foi_auditado": False,
2136
+ "respondeu_questionario": False,
2137
+ "status_avaliacao": "nao_respondente",
2138
+ "motivo_nao_avaliacao": "Ausência de resposta válida ao questionário.",
2139
+ "tem_achados": False,
2140
+ "acoes": {},
2141
+ "procedimentos": [],
2142
+ "procedimentos_executados": [],
2143
+ "achados": {},
2144
+ }
2145
+ procedures: list[dict[str, Any]] = []
2146
+ findings: dict[str, dict[str, Any]] = {}
2147
+ action_values = {
2148
+ identifier: bool(item.get("resultado"))
2149
+ for identifier, item in actions.items()
2150
+ }
2151
+ for definition in self._procedures:
2152
+ metadata = definition.metadata
2153
+ finding = definition.logic.evaluate(action_values)
2154
+ details = materialize_finding(definition.action_ids, actions, auditado, definition.reasons, planning=planning) if finding else {
2155
+ "situacoes_inconformes": [], "situacoes_encontradas": [], "situacoes_detalhadas": [], "motivos_situacoes": {},
2156
+ "evidencias": [], "evidencias_detalhadas": [], "encaminhamentos": [],
2157
+ }
2158
+ achado_ocorreu = bool(finding)
2159
+ procedure = {
2160
+ "id": definition.identifier,
2161
+ "numero_achado": metadata.get("numero_achado"),
2162
+ "nome_achado": metadata.get("nome_achado"),
2163
+ "logica_achado": metadata.get("logica_achado"),
2164
+ "acoes_procedimento": list(definition.action_ids),
2165
+ "achado": finding,
2166
+ "achado_ocorreu": achado_ocorreu,
2167
+ **details,
2168
+ }
2169
+ procedures.append(procedure)
2170
+ if finding:
2171
+ findings[str(metadata.get("numero_achado") or definition.identifier)] = (
2172
+ procedure
2173
+ )
2174
+
2175
+ published_actions = {
2176
+ identifier: {**deepcopy(dict(item)), "aplicacoes": []}
2177
+ for identifier, item in actions.items()
2178
+ }
2179
+ action_by_id = {identifier.upper(): item for identifier, item in published_actions.items()}
2180
+ for procedure in procedures:
2181
+ for referral in procedure.get("encaminhamentos") or []:
2182
+ application = {
2183
+ "id_procedimento": procedure["id"],
2184
+ "id_situacao": referral.get("id_situacao"),
2185
+ "tipo": deepcopy(referral.get("tipo")),
2186
+ "encaminhamento": deepcopy(referral.get("encaminhamento")),
2187
+ "fundamentacao_encaminhamento": deepcopy(referral.get("fundamentacao_encaminhamento")),
2188
+ "criterios": deepcopy(referral.get("criterios") or []),
2189
+ }
2190
+ if referral.get("id_variante"):
2191
+ application["id_variante"] = deepcopy(referral["id_variante"])
2192
+ for identifier in referral.get("id_acoes") or []:
2193
+ action = action_by_id.get(str(identifier).upper())
2194
+ if action is None:
2195
+ continue
2196
+ if not any(canonical_json(existing) == canonical_json(application) for existing in action["aplicacoes"]):
2197
+ action["aplicacoes"].append(deepcopy(application))
2198
+ return {
2199
+ **base,
2200
+ "foi_auditado": True,
2201
+ "respondeu_questionario": answered,
2202
+ "status_avaliacao": "avaliado",
2203
+ "motivo_nao_avaliacao": None,
2204
+ "tem_achados": bool(findings),
2205
+ "acoes": published_actions,
2206
+ "procedimentos": procedures,
2207
+ "procedimentos_executados": procedures,
2208
+ "achados": findings,
2209
+ }
2210
+
2211
+
2212
+ def _planning_situations(matrix) -> dict[str, Any]:
2213
+ from .matrix import materialize_situation_variant
2214
+
2215
+ result = {}
2216
+ for question in matrix.questions:
2217
+ criteria = {item.id: {**item.metadata, "id": f"{question.id}.{item.id}", "id_exibicao": item.id, "descricao": item.text} for item in question.criterios if item.id}
2218
+ for finding in question.achados:
2219
+ for situation in finding.situacoes:
2220
+ if situation.id in result:
2221
+ raise InputValidationError(f"situação duplicada na matriz: {situation.id}")
2222
+ missing = set(situation.criterios) - set(criteria)
2223
+ if missing:
2224
+ raise InputValidationError(f"situação {situation.id} referencia critérios desconhecidos: {sorted(missing)}")
2225
+ variants = []
2226
+ for variant in getattr(situation, "variantes", ()):
2227
+ var_id, var_crit, var_type, var_found, var_ref = materialize_situation_variant(situation, variant)
2228
+ variants.append({
2229
+ "id_variante": var_id,
2230
+ "publico": variant.publico,
2231
+ "aplica_se": dict(variant.aplica_se),
2232
+ "criterios_ids": list(var_crit),
2233
+ "tipo_encaminhamento": var_type,
2234
+ "fundamentacao_encaminhamento": var_found,
2235
+ "encaminhamento": var_ref,
2236
+ })
2237
+ result[situation.id] = {
2238
+ "id_situacao": situation.id,
2239
+ "criterios": [criteria[ref] for ref in situation.criterios],
2240
+ "tipo_encaminhamento": situation.tipo_encaminhamento,
2241
+ "encaminhamento": situation.encaminhamento,
2242
+ "fundamentacao_encaminhamento": situation.fundamentacao_encaminhamento,
2243
+ "encaminhamentos_adicionais": [
2244
+ {
2245
+ "tipo_encaminhamento": extra.tipo_encaminhamento,
2246
+ "encaminhamento": extra.encaminhamento,
2247
+ "fundamentacao_encaminhamento": extra.fundamentacao_encaminhamento,
2248
+ "criterios": (
2249
+ [criteria[ref] for ref in extra.criterios]
2250
+ if extra.criterios is not None
2251
+ else None
2252
+ ),
2253
+ }
2254
+ for extra in situation.encaminhamentos_adicionais
2255
+ ],
2256
+ "variantes": variants,
2257
+ "all_criteria": criteria,
2258
+ }
2259
+ return result
2260
+
2261
+
2262
+ def _rows_by_id(
2263
+ rows: Iterable[Mapping[str, Any]],
2264
+ sheet_name: str,
2265
+ ) -> dict[str, Mapping[str, Any]]:
2266
+ result: dict[str, Mapping[str, Any]] = {}
2267
+ for row in rows:
2268
+ identifier = str(row.get("id") or "").strip()
2269
+ if not identifier:
2270
+ raise InputValidationError(f"aba {sheet_name!r} possui id vazio")
2271
+ if identifier in result:
2272
+ raise InputValidationError(
2273
+ f"aba {sheet_name!r} possui id duplicado: {identifier}"
2274
+ )
2275
+ result[identifier] = row
2276
+ return result
2277
+
2278
+
2279
+ def _require_file(path: Path, label: str) -> Path:
2280
+ path = Path(path)
2281
+ if not path.is_file():
2282
+ raise MissingInputError(f"{label} não encontrado: {path}")
2283
+ return path
2284
+
2285
+
2286
+ def validate_inputs(context: OperationContext) -> OperationResult:
2287
+ params = context.params
2288
+ paths = {
2289
+ "auditados": require_file(context, params["base_auditados"], "auditados"),
2290
+ "mapa": require_file(context, params["mapa"], "mapa de verificação"),
2291
+ "matriz": require_file(context, params["matriz"], "matriz de planejamento"),
2292
+ "survey": require_file(context, params["exportacao_survey"], "respostas do survey"),
2293
+ }
2294
+ summaries = {
2295
+ "auditados": workbook_summary(paths["auditados"], required=("sigla",)),
2296
+ "mapa": workbook_summary(paths["mapa"]),
2297
+ "survey": workbook_summary(paths["survey"]),
2298
+ "matriz": {
2299
+ "path": str(paths["matriz"]),
2300
+ "sha256": sha256_file(paths["matriz"]),
2301
+ "bytes": paths["matriz"].stat().st_size,
2302
+ },
2303
+ }
2304
+ warnings: list[str] = []
2305
+ first_audit_headers = summaries["auditados"]["sheets"][0]["headers"] if summaries["auditados"]["sheets"] else []
2306
+ if not find_column(first_audit_headers, ("sigla", "orgao")):
2307
+ warnings.append("a base de auditados não expõe sigla/orgao na primeira aba")
2308
+ map_names = {sheet["name"] for sheet in summaries["mapa"]["sheets"]}
2309
+ for expected in ("Ações de Verificação", "Fontes de Informação"):
2310
+ if expected not in map_names:
2311
+ warnings.append(f"aba esperada ausente no mapa: {expected}")
2312
+ survey_headers = summaries["survey"]["sheets"][0]["headers"] if summaries["survey"]["sheets"] else []
2313
+ if not find_column(survey_headers, ("firstname", "orgao", "sigla")):
2314
+ warnings.append("a planilha do survey não expõe uma coluna óbvia de auditado")
2315
+ payload = {"inputs": summaries, "warnings": warnings, "compatible": not warnings}
2316
+ output = context.optional_path(params.get("output"))
2317
+ products = ()
2318
+ if output:
2319
+ products = (
2320
+ ProductDraft(
2321
+ kind="input-validation",
2322
+ path=output,
2323
+ content=payload,
2324
+ metadata={"inputs": list(paths)},
2325
+ ),
2326
+ )
2327
+ return OperationResult(summary=payload, products=products, warnings=tuple(warnings))
2328
+
2329
+
2330
+ def calculate_audit(context: OperationContext):
2331
+ """Executa mapa e regras e devolve o resultado de domínio sem publicar arquivos."""
2332
+ params = context.params
2333
+ auditados_path = require_file(context, params["base_auditados"], "auditados")
2334
+ map_path = require_file(context, params["mapa"], "mapa de verificação")
2335
+ from .matrix import parse_matrix
2336
+
2337
+ matrix = None
2338
+ if params.get("matriz"):
2339
+ matrix_path = require_file(context, params["matriz"], "matriz de planejamento")
2340
+ matrix = parse_matrix(matrix_path.read_text(encoding="utf-8"))
2341
+ sources = params.get("fontes", [])
2342
+ if isinstance(sources, (str, Path)):
2343
+ sources = [sources]
2344
+ source_paths = [context.path(item) for item in sources]
2345
+ source_map_params = params.get("mapa_fontes", [])
2346
+ if isinstance(source_map_params, str):
2347
+ source_map_params = [source_map_params]
2348
+ explicit_source_map: dict[str, Path] = {}
2349
+ for item in source_map_params:
2350
+ if "=" not in str(item):
2351
+ raise InputValidationError(f"mapa_fontes inválido: {item!r}; use id=caminho")
2352
+ source_id, source_path = str(item).split("=", 1)
2353
+ explicit_source_map[source_id.strip()] = context.path(source_path.strip())
2354
+
2355
+ return VerificationMap.compile(map_path).execute(
2356
+ auditados_path,
2357
+ source_paths,
2358
+ source_map=explicit_source_map,
2359
+ matrix=matrix,
2360
+ questionnaire_source=params.get("fonte_questionario") or None,
2361
+ )
2362
+
2363
+
2364
+ def evidence_annex_context(audit_payload: Mapping[str, Any]) -> list[dict[str, Any]]:
2365
+ """Contexto `dados` do anexo: por auditado com achados, cada achado com suas evidências."""
2366
+ dados: list[dict[str, Any]] = []
2367
+ for nome, auditado in sorted(audit_rows_from_result(audit_payload).items()):
2368
+ if not isinstance(auditado, Mapping):
2369
+ continue
2370
+ achados = [
2371
+ {"numero": item["numero"], "nome": item["nome"], "evidencias": [str(e) for e in item["evidencias"]]}
2372
+ for item in get_achados(auditado).values()
2373
+ ]
2374
+ if achados:
2375
+ dados.append({
2376
+ "sigla_orgao": str(auditado.get("sigla") or nome),
2377
+ "nome_orgao": str(auditado.get("nome") or nome),
2378
+ "achados": sorted(achados, key=lambda a: (not str(a["numero"]).isdigit(), int(a["numero"]) if str(a["numero"]).isdigit() else 0)),
2379
+ })
2380
+ return dados
2381
+
2382
+
2383
+ def audit_result_operation(
2384
+ context: OperationContext,
2385
+ result,
2386
+ *,
2387
+ audit_payload: Mapping[str, Any] | None = None,
2388
+ ) -> OperationResult:
2389
+ """Converte um resultado de domínio em produtos da operação atual."""
2390
+ params = context.params
2391
+ audit_payload = audit_payload or audit_result_payload(context, result)
2392
+ output = context.optional_path(params.get("output"))
2393
+ detailed_output = context.optional_path(params.get("expandido_output"))
2394
+ tables_output = context.optional_path(params.get("tabelas_output"))
2395
+ products: list[ProductDraft] = []
2396
+ warnings: list[str] = []
2397
+ if output:
2398
+ content, warnings = audit_result_content(context, result, audit_payload)
2399
+ products.append(ProductDraft(kind="audit-result", path=output, content=content, media_type="application/json"))
2400
+ if detailed_output:
2401
+ # A trilha é a visão expandida (v1), para conferência; o v2 já contém a mesma informação.
2402
+ products.append(ProductDraft(kind="audit-trace", path=detailed_output, content=audit_payload))
2403
+ if tables_output:
2404
+ products.append(
2405
+ ProductDraft(
2406
+ kind="audit-tables",
2407
+ path=tables_output,
2408
+ content=audit_table_bytes(
2409
+ result.tables(),
2410
+ empty_headers={
2411
+ "Status": ("Auditado", "Nome", "Status da avaliação", "Respondeu ao questionário", "Tem achados"),
2412
+ "Não respondentes": ("Auditado", "Nome", "Status da avaliação"),
2413
+ "Achados": ("Auditado", "Achado", "Nome", "Situações"),
2414
+ "Situações": ("Auditado", "Achado", "Situação", "Variante", "Descrição", "Critérios", "Motivos", "Ações de origem"),
2415
+ "Ações": (
2416
+ "Auditado", "Ação", "Situação", "Resultado", "Resultado da situação",
2417
+ "Valores encontrados", "Evidência", "Fonte",
2418
+ ),
2419
+ "Catálogo": ("Ação", "Fonte", "Informação requerida", "Situação", "Critério declarado"),
2420
+ "Encaminhamentos": (
2421
+ "Auditado", "Procedimento", "Achado", "Situação", "Variante", "Tipo",
2422
+ "Encaminhamento", "Fundamentação", "IDs dos critérios", "Critérios", "Ações de origem",
2423
+ ),
2424
+ },
2425
+ ),
2426
+ media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
2427
+ )
2428
+ )
2429
+ return OperationResult(
2430
+ summary={**result.summary, "output_requested": bool(output or detailed_output or tables_output)},
2431
+ products=tuple(products),
2432
+ warnings=tuple(warnings),
2433
+ )
2434
+
2435
+
2436
+ def execute_audit(context: OperationContext) -> OperationResult:
2437
+ return audit_result_operation(context, calculate_audit(context))
2438
+
2439
+
2440
+ def situations(path: Path):
2441
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
2442
+ records = audit_rows_from_result(data)
2443
+ result = {}
2444
+ for organization, record in records.items():
2445
+ if not isinstance(record, Mapping):
2446
+ raise InputValidationError("registro de auditado inválido")
2447
+ findings, states = set(), set()
2448
+ for procedure in record.get("procedimentos_executados") or []:
2449
+ finding = procedure.get("achado") or {}
2450
+ occurred = procedure.get("achado_ocorreu")
2451
+ if occurred is None:
2452
+ occurred = bool(finding)
2453
+ if not occurred:
2454
+ continue
2455
+ number = finding.get("numero") if isinstance(finding, dict) else None
2456
+ number = number or procedure.get("numero_achado")
2457
+ if number is not None:
2458
+ findings.add(str(number).strip())
2459
+ values = finding.get("situacoes_encontradas") if isinstance(finding, dict) else None
2460
+ values = values if values is not None else procedure.get("situacoes_inconformes") or []
2461
+ states.update(str(value).strip() for value in values if str(value).strip())
2462
+ name = str(organization).strip().upper()
2463
+ if not name or name in result:
2464
+ raise InputValidationError("auditado ausente ou duplicado no resultado")
2465
+ result[name] = {"achados": findings, "situacoes": states}
2466
+ return result
2467
+
2468
+
2469
+ def metrics(path, organization_column, value_column):
2470
+ from .evaluation import ler_xlsx
2471
+
2472
+ headers, rows = ler_xlsx(path)
2473
+ lookup = {str(header).casefold(): header for header in headers}
2474
+ organization = lookup.get(organization_column.casefold())
2475
+ value = lookup.get(value_column.casefold())
2476
+ if organization is None or value is None:
2477
+ raise InputValidationError("planilha de índices sem as colunas declaradas")
2478
+ result = {}
2479
+ for row in rows:
2480
+ name = str(row.get(organization) or "").strip().upper()
2481
+ if not name:
2482
+ continue
2483
+ if name in result:
2484
+ raise InputValidationError(f"auditado duplicado nos índices: {name}")
2485
+ raw = row.get(value)
2486
+ if raw is None or str(raw).strip() == "":
2487
+ result[name] = None
2488
+ continue
2489
+ try:
2490
+ number = float(raw)
2491
+ except (TypeError, ValueError) as error:
2492
+ raise InputValidationError(f"índice não numérico para {name}") from error
2493
+ if not math.isfinite(number):
2494
+ raise InputValidationError(f"índice não finito para {name}")
2495
+ result[name] = number
2496
+ return result
2497
+
2498
+
2499
+ def compare(context):
2500
+ from ..adapters.xlsx import xlsx_bytes_with_headers
2501
+
2502
+ before_path = context.path(context.params["resultado_anterior"])
2503
+ after_path = context.path(context.params["resultado_auditoria"])
2504
+ before = situations(before_path)
2505
+ after = situations(after_path)
2506
+ scenario_before = context.params.get("cenario_anterior")
2507
+ scenario_after = context.params.get("cenario_atual")
2508
+ if bool(scenario_before) != bool(scenario_after):
2509
+ raise InputValidationError("informe os cenários anterior e atual em conjunto")
2510
+ if scenario_before:
2511
+ for path, scenario in (
2512
+ (before_path, scenario_before),
2513
+ (after_path, scenario_after),
2514
+ ):
2515
+ if context.store.get_scenario(scenario) is None:
2516
+ raise InputValidationError(f"cenário de impacto inexistente: {scenario}")
2517
+ registered = context.store._execute(
2518
+ "SELECT 1 FROM product p JOIN execution e ON e.id=p.execution_id WHERE e.fiscalizacao_id=? AND e.scenario_id=? AND p.kind='audit-result' AND p.path=? AND p.sha256=? LIMIT 1",
2519
+ (context.store.fiscalizacao_id, scenario, str(path), sha256_file(path)),
2520
+ ).fetchone()
2521
+ if not registered:
2522
+ raise InputValidationError(f"resultado de impacto não está registrado no cenário declarado: {scenario}")
2523
+ metric_before = context.optional_path(context.params.get("metrics_before"))
2524
+ metric_after = context.optional_path(context.params.get("metrics_after"))
2525
+ if bool(metric_before) != bool(metric_after):
2526
+ raise InputValidationError("informe ambos os produtos de índices ou nenhum")
2527
+ options = (
2528
+ context.params.get("organization_column") or "auditado",
2529
+ context.params.get("metric_column") or "indice_principal",
2530
+ )
2531
+ values_before = metrics(metric_before, *options) if metric_before else {}
2532
+ values_after = metrics(metric_after, *options) if metric_after else {}
2533
+ result, pending = {}, []
2534
+ for name in sorted(before.keys() | after.keys() | values_before.keys() | values_after.keys()):
2535
+ previous = before.get(name, {"achados": set(), "situacoes": set()})
2536
+ current = after.get(name, {"achados": set(), "situacoes": set()})
2537
+ old_value, new_value = values_before.get(name), values_after.get(name)
2538
+ item = {}
2539
+ for category in ("situacoes", "achados"):
2540
+ item.update(
2541
+ {
2542
+ f"{category}_antes": len(previous[category]),
2543
+ f"{category}_atuais": len(current[category]),
2544
+ f"{category}_removidas" if category == "situacoes" else f"{category}_removidos": len(
2545
+ previous[category] - current[category]
2546
+ ),
2547
+ f"{category}_adicionadas" if category == "situacoes" else f"{category}_adicionados": len(
2548
+ current[category] - previous[category]
2549
+ ),
2550
+ }
2551
+ )
2552
+ item.update(
2553
+ {
2554
+ "indice_anterior": old_value,
2555
+ "indice_atual": new_value,
2556
+ "variacao_indice": new_value - old_value if old_value is not None and new_value is not None else None,
2557
+ }
2558
+ )
2559
+ item["auditoria_anterior_presente"] = name in before
2560
+ item["auditoria_atual_presente"] = name in after
2561
+ if name not in before or name not in after:
2562
+ pending.append(
2563
+ {
2564
+ "auditado": name,
2565
+ "reason": "auditado ausente em um resultado; contagens isoladas não comprovam saneamento",
2566
+ }
2567
+ )
2568
+ if metric_before and (old_value is None or new_value is None):
2569
+ pending.append({"auditado": name, "reason": "índice ausente em um cenário; variação não calculada"})
2570
+ result[name] = item
2571
+ headers = ("Auditado", *next(iter(result.values()), {}).keys())
2572
+ rows = [{"Auditado": name, **value} for name, value in result.items()]
2573
+ before_sha256 = sha256_file(before_path)
2574
+ # Os relatórios conferem o hash da visão expandida (v1), igual para o arquivo v1 ou v2.
2575
+ after_sha256 = sha256_bytes(canonical_json(dict(formato_resultado.carregar(after_path))).encode("utf-8"))
2576
+ payload = {
2577
+ "format": "argos.audit-impact.v1",
2578
+ "auditados": result,
2579
+ "pending": pending,
2580
+ "scenario_before": scenario_before,
2581
+ "scenario_after": scenario_after,
2582
+ "audit_before_sha256": before_sha256,
2583
+ "audit_after_sha256": after_sha256,
2584
+ }
2585
+ products = [ProductDraft("audit-impact", context.path(context.params["output"]), payload)]
2586
+ output_xlsx = context.optional_path(context.params.get("xlsx_output"))
2587
+ if output_xlsx:
2588
+ products.append(
2589
+ ProductDraft(
2590
+ "audit-impact-workbook",
2591
+ output_xlsx,
2592
+ xlsx_bytes_with_headers({"Impactos": (headers, rows), "Pendencias": (("auditado", "reason"), pending)}),
2593
+ media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
2594
+ )
2595
+ )
2596
+ return OperationResult(
2597
+ summary={"auditados": len(result), "pending": len(pending)}, products=tuple(products), pending=tuple(pending)
2598
+ )
2599
+
2600
+
2601
+ def _strip_text(value: Any) -> str:
2602
+ return "" if value is None else str(value).strip()
2603
+
2604
+
2605
+ def _situations(path: Path | None) -> dict[str, dict[str, set[str]]]:
2606
+ if path is None or not path.is_file():
2607
+ return {}
2608
+
2609
+ return situations(path)
2610
+
2611
+
2612
+ def _indices(path: Path | None, *, auditee_column: str = "sigla", index_columns: tuple[str, ...] = ()) -> tuple[str, dict[str, float]]:
2613
+ if path is None or not path.is_file():
2614
+ return "", {}
2615
+ load_workbook = openpyxl_workbook()
2616
+ workbook = load_workbook(path, read_only=True, data_only=True)
2617
+ try:
2618
+ worksheet = workbook.worksheets[0]
2619
+ headers = [_strip_text(cell.value) for cell in worksheet[1]]
2620
+ id_column = next((header for header in headers if header.casefold() == auditee_column.casefold()), None)
2621
+ candidates = list(index_columns) or [header for header in headers if header and header != id_column]
2622
+ if not id_column:
2623
+ return "", {}
2624
+ id_position = headers.index(id_column)
2625
+ positions = {candidate: headers.index(candidate) for candidate in candidates if candidate in headers}
2626
+ series: dict[str, dict[str, float]] = {candidate: {} for candidate in positions}
2627
+ selected = None
2628
+ for row in worksheet.iter_rows(min_row=2, values_only=True):
2629
+ identifier = _strip_text(row[id_position])
2630
+ for priority, (candidate, position) in enumerate(positions.items()):
2631
+ if selected is not None and priority > selected:
2632
+ break
2633
+ value = row[position]
2634
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
2635
+ if selected is None or priority < selected:
2636
+ selected = priority
2637
+ for obsolete in list(series)[priority + 1:]:
2638
+ series[obsolete].clear()
2639
+ if identifier:
2640
+ series[candidate][identifier.upper()] = float(value)
2641
+ index_column = list(positions)[selected] if selected is not None else ""
2642
+ return index_column, series.get(index_column, {})
2643
+ finally:
2644
+ workbook.close()
2645
+
2646
+
2647
+ def calcular(
2648
+ auditoria_anterior: Path,
2649
+ auditoria_atual: Path,
2650
+ contexto_anterior: Path,
2651
+ contexto_atual: Path,
2652
+ *,
2653
+ auditee_column: str = "sigla",
2654
+ index_columns: tuple[str, ...] = (),
2655
+ ) -> dict[str, dict[str, Any]]:
2656
+ """Compara contagens e, quando declarada, a primeira série numérica."""
2657
+ before = _situations(auditoria_anterior)
2658
+ after = _situations(auditoria_atual)
2659
+ before_name, before_index = _indices(contexto_anterior, auditee_column=auditee_column, index_columns=index_columns)
2660
+ after_name, after_index = _indices(contexto_atual, auditee_column=auditee_column, index_columns=index_columns)
2661
+ index_name = after_name or before_name
2662
+ universe = sorted(set(before) | set(after) | set(before_index) | set(after_index))
2663
+ result: dict[str, dict[str, Any]] = {}
2664
+ for identifier in universe:
2665
+ old = before.get(identifier, {"achados": set(), "situacoes": set()})
2666
+ new = after.get(identifier, {"achados": set(), "situacoes": set()})
2667
+ old_value = before_index.get(identifier)
2668
+ new_value = after_index.get(identifier)
2669
+ row: dict[str, Any] = {
2670
+ "situacoes_antes": len(old["situacoes"]),
2671
+ "situacoes_atuais": len(new["situacoes"]),
2672
+ "situacoes_removidas": len(old["situacoes"] - new["situacoes"]),
2673
+ "achados_antes": len(old["achados"]),
2674
+ "achados_atuais": len(new["achados"]),
2675
+ "achados_removidos": len(old["achados"] - new["achados"]),
2676
+ }
2677
+ if index_name:
2678
+ name = index_name.casefold()
2679
+ row[f"{name}_anterior"] = old_value
2680
+ row[f"{name}_atual"] = new_value
2681
+ row[f"variacao_{name}"] = new_value - old_value if old_value is not None and new_value is not None else None
2682
+ result[identifier] = row
2683
+ return result
2684
+
2685
+
2686
+ def run_auditar(context: OperationContext) -> OperationResult:
2687
+ """Comando `auditar`: valida os insumos (opcional) e executa o mapa de verificação."""
2688
+ params = context.params
2689
+ validation = None
2690
+ if params.get("validar_insumos"):
2691
+ validation = _with_params(
2692
+ context,
2693
+ validate_inputs,
2694
+ {
2695
+ "base_auditados": params["base_auditados"],
2696
+ "mapa": params["mapa"],
2697
+ "matriz": params["matriz"],
2698
+ "exportacao_survey": params["exportacao_survey"],
2699
+ "scenario": params.get("scenario") or "base",
2700
+ "output": params.get("validacao_output"),
2701
+ },
2702
+ )
2703
+ audit_params = {
2704
+ k: params[k]
2705
+ for k in (
2706
+ "base_auditados",
2707
+ "mapa",
2708
+ "matriz",
2709
+ "fontes",
2710
+ "mapa_fontes",
2711
+ "scenario",
2712
+ "output",
2713
+ "expandido_output",
2714
+ "tabelas_output",
2715
+ "fonte_questionario",
2716
+ "formato",
2717
+ )
2718
+ if params.get(k) is not None
2719
+ }
2720
+ audit_context = replace(context, params=audit_params)
2721
+ audit_result = calculate_audit(audit_context)
2722
+ res = audit_result_operation(audit_context, audit_result)
2723
+ if validation is not None:
2724
+ res = context.merge_composed(
2725
+ res,
2726
+ summary={"validacao_insumos": dict(validation.summary)},
2727
+ products=validation.products,
2728
+ warnings=validation.warnings,
2729
+ )
2730
+ return res