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.
- argos/__init__.py +5 -0
- argos/__main__.py +4 -0
- argos/adapters/__init__.py +9 -0
- argos/adapters/_libreoffice_worker.py +111 -0
- argos/adapters/ai.py +1506 -0
- argos/adapters/ai_remote.py +654 -0
- argos/adapters/attachment_conversion.py +132 -0
- argos/adapters/capabilities.py +31 -0
- argos/adapters/chart_render.py +72 -0
- argos/adapters/docx_pdf.py +2953 -0
- argos/adapters/limesurvey.py +1079 -0
- argos/adapters/model_call.py +274 -0
- argos/adapters/report_publication.py +1530 -0
- argos/adapters/url_fetch.py +146 -0
- argos/adapters/xlsx.py +454 -0
- argos/analytics.py +731 -0
- argos/assets.py +257 -0
- argos/audit_result.py +369 -0
- argos/booleans.py +105 -0
- argos/catalog.py +1205 -0
- argos/cli.py +606 -0
- argos/contracts.py +532 -0
- argos/core.py +325 -0
- argos/default_skills/README.md +23 -0
- argos/default_skills/criar-matriz-planejamento/SKILL.md +200 -0
- argos/default_skills/elaborar-survey-limesurvey/SKILL.md +106 -0
- argos/default_skills/operar-argos/SKILL.md +74 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/SKILL.md +129 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/assets/relatorio-avaliacao.md +54 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/references/contrato-saidas.md +36 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/references/papeis-das-pastas.md +37 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/references/roteiro-verificacoes.md +27 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/scripts/avaliacao.py +253 -0
- argos/engines/__init__.py +3 -0
- argos/engines/adjustments.py +571 -0
- argos/engines/analytics.py +195 -0
- argos/engines/audit.py +2730 -0
- argos/engines/evaluation.py +6088 -0
- argos/engines/index.py +1683 -0
- argos/engines/matrix.py +5736 -0
- argos/engines/matrix_html.py +698 -0
- argos/engines/model_request.py +201 -0
- argos/engines/report_document.py +137 -0
- argos/engines/reports.py +1200 -0
- argos/engines/survey.py +4445 -0
- argos/envfile.py +53 -0
- argos/errors.py +29 -0
- argos/evidence_staging.py +293 -0
- argos/executions.py +565 -0
- argos/findings_matrix.py +2549 -0
- argos/fingerprints.py +487 -0
- argos/index_dsl.py +2100 -0
- argos/matrix_markdown.py +475 -0
- argos/matrix_widths.py +280 -0
- argos/pipeline.py +1745 -0
- argos/products.py +220 -0
- argos/progress.py +221 -0
- argos/project.py +608 -0
- argos/report_config.py +158 -0
- argos/resources/ESPECIFICACAO_MARKDOWN_MATRIZ_ACHADOS.md +539 -0
- argos/resources/ESPECIFICACAO_MARKDOWN_MATRIZ_PLANEJAMENTO.md +1000 -0
- argos/resources/ESPECIFICACAO_UNIFICADA_MATRIZES_V1_3.md +1142 -0
- argos/resources/anexo-evidencias-base.docx +0 -0
- argos/resources/argos-index-dsl-v1.schema.json +539 -0
- argos/resources/argos-report-config-v1.schema.json +113 -0
- argos/resources/diretrizes-projeto.md +476 -0
- argos/resources/env.example +37 -0
- argos/resources/exemplos/matriz_achados_boilerplate.md +61 -0
- argos/resources/exemplos/matriz_achados_draft.md +106 -0
- argos/resources/exemplos/matriz_achados_larguras_v1_3.md +114 -0
- argos/resources/exemplos/matriz_achados_v1_3.md +107 -0
- argos/resources/exemplos/matriz_planejamento_boilerplate.md +64 -0
- argos/resources/exemplos/matriz_planejamento_larguras_v1_3.md +115 -0
- argos/resources/exemplos/matriz_planejamento_v1_3.md +108 -0
- argos/resources/template-base-estilos-sigiloso.docx +0 -0
- argos/resources/template-base-estilos.docx +0 -0
- argos/resources/template-matriz-planejamento.docx +0 -0
- argos/resources/template-relatorio-consolidado-comum.docx +0 -0
- argos/resources/template-relatorio-consolidado-institucional.docx +0 -0
- argos/response_profiles.py +856 -0
- argos/scheduler.py +142 -0
- argos/status.py +367 -0
- argos/store.py +1228 -0
- argos/survey_collection.py +832 -0
- argos/telemetry.py +84 -0
- argos/tui.py +1262 -0
- argos/tui.tcss +827 -0
- argos/tui_models.py +466 -0
- argos/tui_path.py +155 -0
- argos/tui_widgets.py +482 -0
- argos/version.py +3 -0
- argos_cli-0.3.1.dist-info/METADATA +570 -0
- argos_cli-0.3.1.dist-info/RECORD +96 -0
- argos_cli-0.3.1.dist-info/WHEEL +5 -0
- argos_cli-0.3.1.dist-info/entry_points.txt +2 -0
- argos_cli-0.3.1.dist-info/top_level.txt +1 -0
argos/findings_matrix.py
ADDED
|
@@ -0,0 +1,2549 @@
|
|
|
1
|
+
"""Gramática unificada v1.3 das matrizes e enriquecimento de achados.
|
|
2
|
+
|
|
3
|
+
Este módulo concentra o contrato autoral das duas matrizes:
|
|
4
|
+
|
|
5
|
+
* front matter YAML comum, com precedência **local > global** por campo;
|
|
6
|
+
* gramática da matriz de achados com os seis blocos editoriais e sem
|
|
7
|
+
``ocorrencias``/``universo``;
|
|
8
|
+
* normalização, em memória, do JSON ``argos.audit-result/v1`` quando o
|
|
9
|
+
comando recebe ``--resultado-auditoria``.
|
|
10
|
+
|
|
11
|
+
A renderização DOCX/PDF permanece no motor (``argos.engines.matrix``); aqui não
|
|
12
|
+
há XML nem I/O de produto. A ausência de resultado é tratada como **modo
|
|
13
|
+
editorial**: nada é derivado do texto, nada é contado e nada é associado por
|
|
14
|
+
jurisdicionado.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import json
|
|
20
|
+
import re
|
|
21
|
+
from dataclasses import dataclass, field as dataclass_field
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any, Iterable, Mapping, Sequence
|
|
24
|
+
|
|
25
|
+
from .core import InputValidationError, sha256_bytes
|
|
26
|
+
from .engines.audit import audit_rows_from_result
|
|
27
|
+
from .matrix_markdown import (
|
|
28
|
+
field_values,
|
|
29
|
+
load_yaml_mapping,
|
|
30
|
+
normalize_text as _normalize_matrix_text,
|
|
31
|
+
parse_field_value,
|
|
32
|
+
parse_token_list,
|
|
33
|
+
split_front_matter,
|
|
34
|
+
)
|
|
35
|
+
from .matrix_widths import ColumnWidths, validate_column_widths
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
#: Campos de front matter aceitos nos dois tipos de matriz.
|
|
39
|
+
FRONT_MATTER_FIELDS = (
|
|
40
|
+
"title",
|
|
41
|
+
"fiscalizacao",
|
|
42
|
+
"jurisdicionados",
|
|
43
|
+
"objetivo_auditoria",
|
|
44
|
+
"processo",
|
|
45
|
+
"orgao",
|
|
46
|
+
"unidade_responsavel",
|
|
47
|
+
"tipo_matriz",
|
|
48
|
+
"larguras_colunas_percentuais",
|
|
49
|
+
"origem",
|
|
50
|
+
"equipe_auditoria",
|
|
51
|
+
"supervisor",
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
#: Campos de assinatura, aceitos só na matriz de planejamento.
|
|
55
|
+
SIGNATURE_FIELDS = ("equipe_auditoria", "supervisor")
|
|
56
|
+
|
|
57
|
+
#: Metadados editoriais obrigatórios no front matter.
|
|
58
|
+
REQUIRED_METADATA = ("title", "fiscalizacao", "jurisdicionados", "objetivo_auditoria")
|
|
59
|
+
|
|
60
|
+
#: Chaves que declaram fatos de execução e não pertencem ao Markdown.
|
|
61
|
+
FORBIDDEN_FACT_FIELDS = (
|
|
62
|
+
"ocorrencias",
|
|
63
|
+
"universo",
|
|
64
|
+
"contagens_por_situacao",
|
|
65
|
+
"cobertura",
|
|
66
|
+
"auditados",
|
|
67
|
+
"com_achados",
|
|
68
|
+
"situacoes_ocorridas",
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
#: Aliases entre o front matter local e o cadastro do projeto.
|
|
72
|
+
METADATA_ALIASES: dict[str, tuple[str, ...]] = {
|
|
73
|
+
"title": ("title", "titulo", "nome"),
|
|
74
|
+
"fiscalizacao": ("fiscalizacao", "numero"),
|
|
75
|
+
"jurisdicionados": ("jurisdicionados",),
|
|
76
|
+
"objetivo_auditoria": ("objetivo_auditoria", "objetivo"),
|
|
77
|
+
"processo": ("processo", "numero_processo"),
|
|
78
|
+
"orgao": ("orgao",),
|
|
79
|
+
"unidade_responsavel": ("unidade_responsavel",),
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
FINDINGS_FINDING_FIELDS = (
|
|
83
|
+
"questao",
|
|
84
|
+
"situacao_encontrada",
|
|
85
|
+
"criterios",
|
|
86
|
+
"evidencias",
|
|
87
|
+
"causas",
|
|
88
|
+
"efeitos",
|
|
89
|
+
"encaminhamentos",
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
FINDINGS_REQUIRED_FINDING_FIELDS = (
|
|
93
|
+
"situacao_encontrada",
|
|
94
|
+
"criterios",
|
|
95
|
+
"evidencias",
|
|
96
|
+
"causas",
|
|
97
|
+
"efeitos",
|
|
98
|
+
"encaminhamentos",
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
FINDING_ID = re.compile(r"^A\d+$")
|
|
102
|
+
SITUATION_ID = re.compile(r"^S\d+\.\d+$")
|
|
103
|
+
EVIDENCE_ID = re.compile(r"^EV\d+$")
|
|
104
|
+
REFERRAL_ID = re.compile(r"^EN\d+$")
|
|
105
|
+
EFFECT_ID = re.compile(r"^EF\d+$")
|
|
106
|
+
LOCAL_CRITERION_ID = re.compile(r"^C\d+$")
|
|
107
|
+
QUALIFIED_CRITERION_ID = re.compile(r"^Q[A-Z0-9]+\.C\d+$")
|
|
108
|
+
MATRIX_REFERENCE = re.compile(r"^[A-Z]{1,3}\d+(?:\.\d+)?$")
|
|
109
|
+
QUESTIONNAIRE_CODE = re.compile(r"^[A-Za-z0-9_]+(?:\[[A-Za-z0-9_]+\])?$")
|
|
110
|
+
HASH_PATTERN = re.compile(r"^[0-9a-fA-F]{64}$")
|
|
111
|
+
_PLACEHOLDER = re.compile(r"\[PREENCHER:[^\]]*\]")
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def normalize_text(text: str) -> str:
|
|
115
|
+
"""Normaliza quebras de linha e remove BOM sem tocar no conteúdo autoral."""
|
|
116
|
+
return _normalize_matrix_text(text)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _error(path: str, message: str, *, line: int | None = None) -> InputValidationError:
|
|
120
|
+
location = f"linha {line}, " if line is not None else ""
|
|
121
|
+
return InputValidationError(f"{location}{path}: {message}")
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _yaml_mapping(text: str, *, path: str, line: int, allow_empty: bool = False) -> dict[str, Any]:
|
|
125
|
+
"""Carrega YAML seguro com a política comum aos dois parsers."""
|
|
126
|
+
return load_yaml_mapping(text, path=path, line=line, allow_empty=allow_empty)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _text(value: Any, *, path: str, line: int | None = None) -> str:
|
|
130
|
+
if not isinstance(value, str) or not value.strip():
|
|
131
|
+
raise _error(path, "deve ser um texto não vazio", line=line)
|
|
132
|
+
return value.strip()
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _optional_text(value: Any, *, path: str, line: int | None = None) -> str | None:
|
|
136
|
+
if value is None:
|
|
137
|
+
return None
|
|
138
|
+
return _text(value, path=path, line=line)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _boolean(value: Any, *, path: str, line: int | None = None, allow_none: bool = False) -> bool | None:
|
|
142
|
+
if allow_none and value is None:
|
|
143
|
+
return None
|
|
144
|
+
if type(value) is not bool:
|
|
145
|
+
raise _error(path, "deve ser booleano" + (" ou nulo" if allow_none else ""), line=line)
|
|
146
|
+
return value
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _token_list(
|
|
150
|
+
value: Any,
|
|
151
|
+
*,
|
|
152
|
+
path: str,
|
|
153
|
+
line: int | None = None,
|
|
154
|
+
pattern: re.Pattern[str] | None = None,
|
|
155
|
+
nonempty: bool = False,
|
|
156
|
+
) -> list[str]:
|
|
157
|
+
return parse_token_list(value, path=path, pattern=pattern, nonempty=nonempty)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _text_list(value: Any, *, path: str, line: int | None = None, nonempty: bool = False) -> list[str]:
|
|
161
|
+
if not isinstance(value, list):
|
|
162
|
+
raise _error(path, "deve ser uma lista de textos", line=line)
|
|
163
|
+
if nonempty and not value:
|
|
164
|
+
raise _error(path, "a lista não pode ficar vazia", line=line)
|
|
165
|
+
return [_text(item, path=f"{path}[{index}]", line=line) for index, item in enumerate(value)]
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _mapping(
|
|
169
|
+
value: Any,
|
|
170
|
+
*,
|
|
171
|
+
path: str,
|
|
172
|
+
allowed: Sequence[str],
|
|
173
|
+
required: Sequence[str] = (),
|
|
174
|
+
line: int | None = None,
|
|
175
|
+
) -> Mapping[str, Any]:
|
|
176
|
+
if not isinstance(value, Mapping):
|
|
177
|
+
raise _error(path, "deve ser um mapeamento YAML", line=line)
|
|
178
|
+
if any(not isinstance(key, str) for key in value):
|
|
179
|
+
raise _error(path, "as chaves devem ser textos", line=line)
|
|
180
|
+
for key in value:
|
|
181
|
+
if key in FORBIDDEN_FACT_FIELDS:
|
|
182
|
+
raise _error(
|
|
183
|
+
f"{path}.{key}",
|
|
184
|
+
f"o campo {key!r} não pertence à matriz; esses dados são derivados do JSON informado em --resultado-auditoria",
|
|
185
|
+
line=line,
|
|
186
|
+
)
|
|
187
|
+
if key not in allowed:
|
|
188
|
+
raise _error(f"{path}.{key}", "atributo desconhecido", line=line)
|
|
189
|
+
missing = [key for key in required if key not in value]
|
|
190
|
+
if missing:
|
|
191
|
+
raise _error(f"{path}.{missing[0]}", "atributo obrigatório ausente", line=line)
|
|
192
|
+
return value
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
# --------------------------------------------------------------------------------------
|
|
196
|
+
# Metadados editoriais
|
|
197
|
+
# --------------------------------------------------------------------------------------
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
@dataclass(frozen=True)
|
|
201
|
+
class MatrixMetadata:
|
|
202
|
+
"""Metadados editoriais efetivos, já resolvidos por campo."""
|
|
203
|
+
|
|
204
|
+
title: str
|
|
205
|
+
fiscalizacao: str
|
|
206
|
+
jurisdicionados: str
|
|
207
|
+
objetivo_auditoria: str
|
|
208
|
+
processo: str | None = None
|
|
209
|
+
orgao: str | None = None
|
|
210
|
+
unidade_responsavel: str | None = None
|
|
211
|
+
tipo_matriz: str | None = None
|
|
212
|
+
column_widths: ColumnWidths | None = None
|
|
213
|
+
origem: Mapping[str, Any] = dataclass_field(default_factory=dict)
|
|
214
|
+
fontes: Mapping[str, str] = dataclass_field(default_factory=dict)
|
|
215
|
+
equipe_auditoria: tuple[str, ...] = ()
|
|
216
|
+
supervisor: tuple[str, ...] = ()
|
|
217
|
+
|
|
218
|
+
def header_values(self) -> dict[str, str]:
|
|
219
|
+
"""Formata os metadados como o cabeçalho DOCX espera."""
|
|
220
|
+
values = {
|
|
221
|
+
"numero": self.fiscalizacao,
|
|
222
|
+
"titulo": self.title,
|
|
223
|
+
"nome": self.title,
|
|
224
|
+
"objetivo": self.objetivo_auditoria,
|
|
225
|
+
"jurisdicionados": self.jurisdicionados,
|
|
226
|
+
}
|
|
227
|
+
if self.processo:
|
|
228
|
+
values["numero_processo"] = self.processo
|
|
229
|
+
if self.orgao:
|
|
230
|
+
values["orgao"] = self.orgao
|
|
231
|
+
if self.unidade_responsavel:
|
|
232
|
+
values["unidade_responsavel"] = self.unidade_responsavel
|
|
233
|
+
return values
|
|
234
|
+
|
|
235
|
+
def to_mapping(self) -> dict[str, Any]:
|
|
236
|
+
payload: dict[str, Any] = {
|
|
237
|
+
"title": self.title,
|
|
238
|
+
"fiscalizacao": self.fiscalizacao,
|
|
239
|
+
"jurisdicionados": self.jurisdicionados,
|
|
240
|
+
"objetivo_auditoria": self.objetivo_auditoria,
|
|
241
|
+
}
|
|
242
|
+
for name in ("processo", "orgao", "unidade_responsavel", "tipo_matriz"):
|
|
243
|
+
value = getattr(self, name)
|
|
244
|
+
if value:
|
|
245
|
+
payload[name] = value
|
|
246
|
+
if self.column_widths is not None:
|
|
247
|
+
payload["larguras_colunas_percentuais"] = self.column_widths.as_json_mapping()
|
|
248
|
+
if self.origem:
|
|
249
|
+
payload["origem"] = dict(self.origem)
|
|
250
|
+
if self.equipe_auditoria:
|
|
251
|
+
payload["equipe_auditoria"] = list(self.equipe_auditoria)
|
|
252
|
+
if self.supervisor:
|
|
253
|
+
payload["supervisor"] = list(self.supervisor)
|
|
254
|
+
return payload
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def validate_front_matter(
|
|
258
|
+
raw: Mapping[str, Any],
|
|
259
|
+
*,
|
|
260
|
+
kind: str,
|
|
261
|
+
path: str = "front_matter",
|
|
262
|
+
) -> dict[str, Any]:
|
|
263
|
+
"""Valida as chaves e os tipos do front matter para o tipo de matriz."""
|
|
264
|
+
if not raw:
|
|
265
|
+
return {}
|
|
266
|
+
for key in raw:
|
|
267
|
+
if key in FORBIDDEN_FACT_FIELDS:
|
|
268
|
+
raise _error(
|
|
269
|
+
f"{path}.{key}",
|
|
270
|
+
f"o campo {key!r} não pertence ao front matter; esses dados são derivados do JSON informado em --resultado-auditoria",
|
|
271
|
+
)
|
|
272
|
+
if key not in FRONT_MATTER_FIELDS:
|
|
273
|
+
raise _error(f"{path}.{key}", "atributo desconhecido no front matter")
|
|
274
|
+
normalized: dict[str, Any] = {}
|
|
275
|
+
for key in REQUIRED_METADATA:
|
|
276
|
+
if key in raw:
|
|
277
|
+
normalized[key] = _text(raw[key], path=f"{path}.{key}")
|
|
278
|
+
for key in ("processo", "orgao", "unidade_responsavel"):
|
|
279
|
+
if key in raw:
|
|
280
|
+
normalized[key] = _optional_text(raw[key], path=f"{path}.{key}")
|
|
281
|
+
if "tipo_matriz" in raw:
|
|
282
|
+
tipo = _text(raw["tipo_matriz"], path=f"{path}.tipo_matriz")
|
|
283
|
+
if tipo not in ("planejamento", "achados"):
|
|
284
|
+
raise _error(f"{path}.tipo_matriz", "deve ser 'planejamento' ou 'achados'")
|
|
285
|
+
if tipo != kind:
|
|
286
|
+
raise _error(
|
|
287
|
+
f"{path}.tipo_matriz",
|
|
288
|
+
f"declara {tipo!r}, mas a matriz em processamento é do tipo {kind!r}",
|
|
289
|
+
)
|
|
290
|
+
normalized["tipo_matriz"] = tipo
|
|
291
|
+
if "larguras_colunas_percentuais" in raw:
|
|
292
|
+
normalized["larguras_colunas_percentuais"] = validate_column_widths(
|
|
293
|
+
raw["larguras_colunas_percentuais"],
|
|
294
|
+
kind=kind,
|
|
295
|
+
path=f"{path}.larguras_colunas_percentuais",
|
|
296
|
+
)
|
|
297
|
+
for key in SIGNATURE_FIELDS:
|
|
298
|
+
if key not in raw:
|
|
299
|
+
continue
|
|
300
|
+
if kind != "planejamento":
|
|
301
|
+
raise _error(f"{path}.{key}", "atributo aceito somente na matriz de planejamento")
|
|
302
|
+
value = raw[key]
|
|
303
|
+
if isinstance(value, str):
|
|
304
|
+
value = [value]
|
|
305
|
+
normalized[key] = tuple(_text_list(value, path=f"{path}.{key}", nonempty=True))
|
|
306
|
+
if "origem" in raw:
|
|
307
|
+
origem = _mapping(
|
|
308
|
+
raw["origem"],
|
|
309
|
+
path=f"{path}.origem",
|
|
310
|
+
allowed=("cenario", "resultado_sha256", "fiscalizacao_sha256", "fiscalizacao_id"),
|
|
311
|
+
)
|
|
312
|
+
normalized_origem: dict[str, Any] = {}
|
|
313
|
+
for key, value in origem.items():
|
|
314
|
+
if key.endswith("_sha256"):
|
|
315
|
+
digest = _text(value, path=f"{path}.origem.{key}")
|
|
316
|
+
if HASH_PATTERN.fullmatch(digest) is None:
|
|
317
|
+
raise _error(f"{path}.origem.{key}", "deve conter 64 caracteres hexadecimais")
|
|
318
|
+
normalized_origem[key] = digest
|
|
319
|
+
else:
|
|
320
|
+
normalized_origem[key] = _text(value, path=f"{path}.origem.{key}")
|
|
321
|
+
normalized["origem"] = normalized_origem
|
|
322
|
+
return normalized
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _project_field(project: Mapping[str, Any], aliases: Iterable[str]) -> str | None:
|
|
326
|
+
nested = project.get("fiscalizacao")
|
|
327
|
+
sources: list[Mapping[str, Any]] = [project]
|
|
328
|
+
if isinstance(nested, Mapping):
|
|
329
|
+
sources.append(nested)
|
|
330
|
+
for alias in aliases:
|
|
331
|
+
for source in sources:
|
|
332
|
+
value = source.get(alias)
|
|
333
|
+
if isinstance(value, Mapping) or isinstance(value, (list, tuple, set)):
|
|
334
|
+
continue
|
|
335
|
+
if value is not None and str(value).strip():
|
|
336
|
+
return str(value).strip()
|
|
337
|
+
return None
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def resolve_metadata(
|
|
341
|
+
local: Mapping[str, Any],
|
|
342
|
+
project: Mapping[str, Any] | None = None,
|
|
343
|
+
*,
|
|
344
|
+
kind: str,
|
|
345
|
+
require_editorial: bool = False,
|
|
346
|
+
) -> MatrixMetadata:
|
|
347
|
+
"""Resolve os metadados editoriais campo a campo: local > cadastro do projeto."""
|
|
348
|
+
project = project or {}
|
|
349
|
+
if require_editorial:
|
|
350
|
+
missing_local = [
|
|
351
|
+
field
|
|
352
|
+
for field in REQUIRED_METADATA
|
|
353
|
+
if field not in local or not str(local[field]).strip()
|
|
354
|
+
]
|
|
355
|
+
if missing_local:
|
|
356
|
+
raise _error(
|
|
357
|
+
"front_matter",
|
|
358
|
+
"metadado obrigatório deve ser declarado localmente: " + ", ".join(missing_local),
|
|
359
|
+
)
|
|
360
|
+
values: dict[str, str] = {}
|
|
361
|
+
fontes: dict[str, str] = {}
|
|
362
|
+
missing_required: list[str] = []
|
|
363
|
+
for field in REQUIRED_METADATA:
|
|
364
|
+
if field in local and str(local[field]).strip():
|
|
365
|
+
values[field] = str(local[field]).strip()
|
|
366
|
+
fontes[field] = "local"
|
|
367
|
+
continue
|
|
368
|
+
inherited = _project_field(project, METADATA_ALIASES[field])
|
|
369
|
+
if inherited:
|
|
370
|
+
values[field] = inherited
|
|
371
|
+
fontes[field] = "projeto"
|
|
372
|
+
continue
|
|
373
|
+
missing_required.append(field)
|
|
374
|
+
for field in ("processo", "orgao", "unidade_responsavel"):
|
|
375
|
+
if field in local and local[field] is not None:
|
|
376
|
+
values[field] = str(local[field]).strip()
|
|
377
|
+
fontes[field] = "local"
|
|
378
|
+
continue
|
|
379
|
+
inherited = _project_field(project, METADATA_ALIASES[field])
|
|
380
|
+
if inherited:
|
|
381
|
+
values[field] = inherited
|
|
382
|
+
fontes[field] = "projeto"
|
|
383
|
+
if missing_required and (require_editorial or local):
|
|
384
|
+
raise _error(
|
|
385
|
+
"front_matter",
|
|
386
|
+
"metadado obrigatório ausente ou vazio: " + ", ".join(missing_required),
|
|
387
|
+
)
|
|
388
|
+
return MatrixMetadata(
|
|
389
|
+
title=values.get("title", ""),
|
|
390
|
+
fiscalizacao=values.get("fiscalizacao", ""),
|
|
391
|
+
jurisdicionados=values.get("jurisdicionados", ""),
|
|
392
|
+
objetivo_auditoria=values.get("objetivo_auditoria", ""),
|
|
393
|
+
processo=values.get("processo"),
|
|
394
|
+
orgao=values.get("orgao"),
|
|
395
|
+
unidade_responsavel=values.get("unidade_responsavel"),
|
|
396
|
+
tipo_matriz=kind,
|
|
397
|
+
column_widths=local.get("larguras_colunas_percentuais"),
|
|
398
|
+
origem=dict(local.get("origem") or {}),
|
|
399
|
+
fontes=fontes,
|
|
400
|
+
equipe_auditoria=tuple(local.get("equipe_auditoria") or ()),
|
|
401
|
+
supervisor=tuple(local.get("supervisor") or ()),
|
|
402
|
+
)
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
# --------------------------------------------------------------------------------------
|
|
406
|
+
# Modelo editorial da matriz de achados
|
|
407
|
+
# --------------------------------------------------------------------------------------
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
@dataclass(frozen=True)
|
|
411
|
+
class FindingCriterion:
|
|
412
|
+
id: str
|
|
413
|
+
id_local: str
|
|
414
|
+
descricao: str
|
|
415
|
+
natureza_fundamento: str | None = None
|
|
416
|
+
apto_a_fundamentar_determinacao: bool | None = None
|
|
417
|
+
publico: str | None = None
|
|
418
|
+
especifico: bool | None = None
|
|
419
|
+
aplica_se: Mapping[str, list[str]] | None = None
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
@dataclass(frozen=True)
|
|
423
|
+
class EvidenceRecord:
|
|
424
|
+
id: str
|
|
425
|
+
relato: str
|
|
426
|
+
itens: tuple[str, ...] = ()
|
|
427
|
+
itens_questionario: tuple[str, ...] = ()
|
|
428
|
+
referencias_matriz: tuple[str, ...] = ()
|
|
429
|
+
fontes: tuple[Mapping[str, str], ...] = ()
|
|
430
|
+
ressalva: str | None = None
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
@dataclass(frozen=True)
|
|
434
|
+
class EvidenceSituation:
|
|
435
|
+
id: str
|
|
436
|
+
descricao: str
|
|
437
|
+
registros: tuple[EvidenceRecord, ...] = ()
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
@dataclass(frozen=True)
|
|
441
|
+
class FindingEffect:
|
|
442
|
+
id: str | None
|
|
443
|
+
titulo: str
|
|
444
|
+
descricao: str
|
|
445
|
+
situacoes: tuple[str, ...] = ()
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
@dataclass(frozen=True)
|
|
449
|
+
class ReferralProposal:
|
|
450
|
+
id: str
|
|
451
|
+
tipo_encaminhamento: str
|
|
452
|
+
encaminhamento: str
|
|
453
|
+
fundamentacao_encaminhamento: str = ""
|
|
454
|
+
criterios: tuple[str, ...] = ()
|
|
455
|
+
publico: str | None = None
|
|
456
|
+
id_variante: str | None = None
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
@dataclass(frozen=True)
|
|
460
|
+
class ReferralSituation:
|
|
461
|
+
id: str
|
|
462
|
+
propostas: tuple[ReferralProposal, ...] = ()
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
@dataclass(frozen=True)
|
|
466
|
+
class Finding:
|
|
467
|
+
id: str
|
|
468
|
+
titulo: str
|
|
469
|
+
questao: str | None
|
|
470
|
+
situacao_encontrada: str
|
|
471
|
+
criterios: tuple[FindingCriterion, ...]
|
|
472
|
+
evidencias: tuple[EvidenceSituation, ...]
|
|
473
|
+
causas: str
|
|
474
|
+
efeitos: tuple[FindingEffect, ...] | str
|
|
475
|
+
encaminhamentos: tuple[ReferralSituation, ...]
|
|
476
|
+
|
|
477
|
+
def criterio(self, identifier: str) -> FindingCriterion | None:
|
|
478
|
+
for criterion in self.criterios:
|
|
479
|
+
if identifier in (criterion.id, criterion.id_local):
|
|
480
|
+
return criterion
|
|
481
|
+
return None
|
|
482
|
+
|
|
483
|
+
def situation_ids(self) -> tuple[str, ...]:
|
|
484
|
+
return tuple(situation.id for situation in self.evidencias)
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
@dataclass(frozen=True)
|
|
488
|
+
class FindingsPresentation:
|
|
489
|
+
mostrar_referencias: bool = True
|
|
490
|
+
numeracao_criterios: str = "compacta_por_achado"
|
|
491
|
+
quebra_pagina_entre_achados: bool = True
|
|
492
|
+
espacamento_titulo_evidencia_por_situacao_twips: Mapping[str, int] = dataclass_field(default_factory=dict)
|
|
493
|
+
painel: Mapping[str, Any] = dataclass_field(default_factory=dict)
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
@dataclass(frozen=True)
|
|
497
|
+
class FindingsDocument:
|
|
498
|
+
metadata: MatrixMetadata
|
|
499
|
+
achados: tuple[Finding, ...]
|
|
500
|
+
apresentacao: FindingsPresentation
|
|
501
|
+
front_matter: Mapping[str, Any] = dataclass_field(default_factory=dict)
|
|
502
|
+
|
|
503
|
+
@property
|
|
504
|
+
def sem_achados(self) -> bool:
|
|
505
|
+
return not self.achados
|
|
506
|
+
|
|
507
|
+
def finding(self, finding_id: str) -> Finding | None:
|
|
508
|
+
for finding in self.achados:
|
|
509
|
+
if finding.id == finding_id:
|
|
510
|
+
return finding
|
|
511
|
+
return None
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
PANEL_DEFAULTS = {
|
|
515
|
+
"incluir": True,
|
|
516
|
+
"titulo": "Situações encontradas por auditado",
|
|
517
|
+
"legenda": "D = determinação; R = recomendação.",
|
|
518
|
+
"codigos": {"Determinação": "D", "Recomendação": "R"},
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
def _presentation(raw: Any) -> FindingsPresentation:
|
|
523
|
+
data = _mapping(
|
|
524
|
+
raw if raw is not None else {},
|
|
525
|
+
path="apresentacao",
|
|
526
|
+
allowed=(
|
|
527
|
+
"mostrar_referencias",
|
|
528
|
+
"numeracao_criterios",
|
|
529
|
+
"quebra_pagina_entre_achados",
|
|
530
|
+
"espacamento_titulo_evidencia_por_situacao_twips",
|
|
531
|
+
"painel",
|
|
532
|
+
),
|
|
533
|
+
)
|
|
534
|
+
numeracao = str(data.get("numeracao_criterios") or "compacta_por_achado")
|
|
535
|
+
if numeracao not in ("compacta_por_achado", "canonica"):
|
|
536
|
+
raise _error("apresentacao.numeracao_criterios", "use 'compacta_por_achado' ou 'canonica'")
|
|
537
|
+
spacing_raw = data.get("espacamento_titulo_evidencia_por_situacao_twips") or {}
|
|
538
|
+
if not isinstance(spacing_raw, Mapping):
|
|
539
|
+
raise _error("apresentacao.espacamento_titulo_evidencia_por_situacao_twips", "deve ser um mapeamento")
|
|
540
|
+
spacing: dict[str, int] = {}
|
|
541
|
+
for key, value in spacing_raw.items():
|
|
542
|
+
if not isinstance(key, str) or SITUATION_ID.fullmatch(key) is None:
|
|
543
|
+
raise _error("apresentacao.espacamento_titulo_evidencia_por_situacao_twips", f"chave inválida: {key!r}")
|
|
544
|
+
if type(value) is not int or value < 0:
|
|
545
|
+
raise _error(f"apresentacao.espacamento_titulo_evidencia_por_situacao_twips.{key}", "deve ser inteiro não negativo")
|
|
546
|
+
spacing[key] = value
|
|
547
|
+
panel_raw = _mapping(
|
|
548
|
+
data.get("painel") or {},
|
|
549
|
+
path="apresentacao.painel",
|
|
550
|
+
allowed=("incluir", "titulo", "legenda", "codigos"),
|
|
551
|
+
)
|
|
552
|
+
panel = dict(PANEL_DEFAULTS)
|
|
553
|
+
if "incluir" in panel_raw:
|
|
554
|
+
panel["incluir"] = _boolean(panel_raw["incluir"], path="apresentacao.painel.incluir")
|
|
555
|
+
if "titulo" in panel_raw:
|
|
556
|
+
panel["titulo"] = _text(panel_raw["titulo"], path="apresentacao.painel.titulo")
|
|
557
|
+
if "legenda" in panel_raw:
|
|
558
|
+
panel["legenda"] = _text(panel_raw["legenda"], path="apresentacao.painel.legenda")
|
|
559
|
+
if "codigos" in panel_raw:
|
|
560
|
+
codes = panel_raw["codigos"]
|
|
561
|
+
if not isinstance(codes, Mapping):
|
|
562
|
+
raise _error("apresentacao.painel.codigos", "deve ser um mapeamento tipo -> código")
|
|
563
|
+
panel["codigos"] = {
|
|
564
|
+
str(key): _text(value, path=f"apresentacao.painel.codigos.{key}")
|
|
565
|
+
for key, value in codes.items()
|
|
566
|
+
}
|
|
567
|
+
return FindingsPresentation(
|
|
568
|
+
mostrar_referencias=(
|
|
569
|
+
_boolean(data["mostrar_referencias"], path="apresentacao.mostrar_referencias")
|
|
570
|
+
if "mostrar_referencias" in data
|
|
571
|
+
else True
|
|
572
|
+
),
|
|
573
|
+
numeracao_criterios=numeracao,
|
|
574
|
+
quebra_pagina_entre_achados=(
|
|
575
|
+
_boolean(data["quebra_pagina_entre_achados"], path="apresentacao.quebra_pagina_entre_achados")
|
|
576
|
+
if "quebra_pagina_entre_achados" in data
|
|
577
|
+
else True
|
|
578
|
+
),
|
|
579
|
+
espacamento_titulo_evidencia_por_situacao_twips=spacing,
|
|
580
|
+
painel=panel,
|
|
581
|
+
)
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
def question_identifier(questao: str | None) -> str | None:
|
|
585
|
+
"""Extrai o ID da questão (``Q1``) do campo ``questao`` do achado."""
|
|
586
|
+
if not questao:
|
|
587
|
+
return None
|
|
588
|
+
match = re.match(r"^(Q[A-Z0-9]+)\.", questao.strip())
|
|
589
|
+
return match.group(1) if match else None
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
# --------------------------------------------------------------------------------------
|
|
593
|
+
# Leitura da matriz de achados
|
|
594
|
+
# --------------------------------------------------------------------------------------
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
def _normalize_criterion_id(identifier: str, *, question_id: str | None, path: str) -> tuple[str, str]:
|
|
598
|
+
"""Devolve ``(id_canonico, id_local)`` a partir de um ID escrito pelo auditor."""
|
|
599
|
+
if LOCAL_CRITERION_ID.fullmatch(identifier):
|
|
600
|
+
if not question_id:
|
|
601
|
+
raise _error(
|
|
602
|
+
path,
|
|
603
|
+
f"o critério {identifier!r} é local à questão; declare 'questao: Q1. ...' ou use o ID qualificado",
|
|
604
|
+
)
|
|
605
|
+
return f"{question_id}.{identifier}", identifier
|
|
606
|
+
if QUALIFIED_CRITERION_ID.fullmatch(identifier):
|
|
607
|
+
return identifier, identifier.rsplit(".", 1)[1]
|
|
608
|
+
raise _error(path, f"ID de critério inválido: {identifier!r} (use C1 ou Q1.C1)")
|
|
609
|
+
|
|
610
|
+
|
|
611
|
+
def _parse_criterion(
|
|
612
|
+
raw: Any,
|
|
613
|
+
*,
|
|
614
|
+
path: str,
|
|
615
|
+
question_id: str | None,
|
|
616
|
+
) -> FindingCriterion:
|
|
617
|
+
record = _mapping(
|
|
618
|
+
raw,
|
|
619
|
+
path=path,
|
|
620
|
+
allowed=(
|
|
621
|
+
"id",
|
|
622
|
+
"descricao",
|
|
623
|
+
"natureza_fundamento",
|
|
624
|
+
"apto_a_fundamentar_determinacao",
|
|
625
|
+
"publico",
|
|
626
|
+
"especifico",
|
|
627
|
+
"aplica_se",
|
|
628
|
+
),
|
|
629
|
+
required=("id", "descricao"),
|
|
630
|
+
)
|
|
631
|
+
canonical, local = _normalize_criterion_id(
|
|
632
|
+
_text(record["id"], path=f"{path}.id"),
|
|
633
|
+
question_id=question_id,
|
|
634
|
+
path=f"{path}.id",
|
|
635
|
+
)
|
|
636
|
+
aplica_se: dict[str, list[str]] | None = None
|
|
637
|
+
if record.get("aplica_se") is not None:
|
|
638
|
+
raw_selectors = _mapping(
|
|
639
|
+
record["aplica_se"],
|
|
640
|
+
path=f"{path}.aplica_se",
|
|
641
|
+
allowed=("segmentos", "naturezas", "tags_todas", "tags_alguma", "tags_excluidas"),
|
|
642
|
+
)
|
|
643
|
+
aplica_se = {
|
|
644
|
+
key: _text_list(
|
|
645
|
+
values,
|
|
646
|
+
path=f"{path}.aplica_se.{key}",
|
|
647
|
+
nonempty=True,
|
|
648
|
+
)
|
|
649
|
+
for key, values in raw_selectors.items()
|
|
650
|
+
}
|
|
651
|
+
return FindingCriterion(
|
|
652
|
+
id=canonical,
|
|
653
|
+
id_local=local,
|
|
654
|
+
descricao=_text(record["descricao"], path=f"{path}.descricao"),
|
|
655
|
+
natureza_fundamento=_optional_text(record["natureza_fundamento"], path=f"{path}.natureza_fundamento")
|
|
656
|
+
if "natureza_fundamento" in record
|
|
657
|
+
else None,
|
|
658
|
+
apto_a_fundamentar_determinacao=_boolean(
|
|
659
|
+
record["apto_a_fundamentar_determinacao"],
|
|
660
|
+
path=f"{path}.apto_a_fundamentar_determinacao",
|
|
661
|
+
allow_none=True,
|
|
662
|
+
)
|
|
663
|
+
if "apto_a_fundamentar_determinacao" in record
|
|
664
|
+
else None,
|
|
665
|
+
publico=_optional_text(record["publico"], path=f"{path}.publico") if "publico" in record else None,
|
|
666
|
+
especifico=_boolean(record["especifico"], path=f"{path}.especifico", allow_none=True)
|
|
667
|
+
if "especifico" in record
|
|
668
|
+
else None,
|
|
669
|
+
aplica_se=aplica_se,
|
|
670
|
+
)
|
|
671
|
+
|
|
672
|
+
|
|
673
|
+
def _parse_criteria(raw: Any, *, path: str, question_id: str | None) -> tuple[FindingCriterion, ...]:
|
|
674
|
+
if not isinstance(raw, list):
|
|
675
|
+
raise _error(path, "deve ser uma lista de critérios")
|
|
676
|
+
if not raw:
|
|
677
|
+
raise _error(path, "o achado precisa de pelo menos um critério")
|
|
678
|
+
criteria: list[FindingCriterion] = []
|
|
679
|
+
seen: set[str] = set()
|
|
680
|
+
for index, item in enumerate(raw):
|
|
681
|
+
criterion = _parse_criterion(item, path=f"{path}[{index}]", question_id=question_id)
|
|
682
|
+
if criterion.id in seen:
|
|
683
|
+
raise _error(f"{path}[{index}]", f"critério repetido: {criterion.id}")
|
|
684
|
+
seen.add(criterion.id)
|
|
685
|
+
criteria.append(criterion)
|
|
686
|
+
return tuple(criteria)
|
|
687
|
+
|
|
688
|
+
|
|
689
|
+
def _parse_fontes(raw: Any, *, path: str) -> tuple[Mapping[str, str], ...]:
|
|
690
|
+
if not isinstance(raw, list):
|
|
691
|
+
raise _error(path, "deve ser uma lista de fontes")
|
|
692
|
+
sources: list[Mapping[str, str]] = []
|
|
693
|
+
identifiers: set[str] = set()
|
|
694
|
+
for index, item in enumerate(raw):
|
|
695
|
+
record = _mapping(
|
|
696
|
+
item,
|
|
697
|
+
path=f"{path}[{index}]",
|
|
698
|
+
allowed=("id", "descricao"),
|
|
699
|
+
required=("id", "descricao"),
|
|
700
|
+
)
|
|
701
|
+
identifier = _text(record["id"], path=f"{path}[{index}].id")
|
|
702
|
+
if MATRIX_REFERENCE.fullmatch(identifier) is None:
|
|
703
|
+
raise _error(f"{path}[{index}].id", f"identificador de fonte inválido: {identifier!r}")
|
|
704
|
+
if identifier in identifiers:
|
|
705
|
+
raise _error(f"{path}[{index}].id", f"fonte repetida: {identifier}")
|
|
706
|
+
identifiers.add(identifier)
|
|
707
|
+
sources.append({"id": identifier, "descricao": _text(record["descricao"], path=f"{path}[{index}].descricao")})
|
|
708
|
+
return tuple(sources)
|
|
709
|
+
|
|
710
|
+
|
|
711
|
+
def _parse_evidence_record(raw: Any, *, path: str) -> EvidenceRecord:
|
|
712
|
+
record = _mapping(
|
|
713
|
+
raw,
|
|
714
|
+
path=path,
|
|
715
|
+
allowed=(
|
|
716
|
+
"id",
|
|
717
|
+
"relato",
|
|
718
|
+
"itens",
|
|
719
|
+
"itens_questionario",
|
|
720
|
+
"referencias_matriz",
|
|
721
|
+
"fontes",
|
|
722
|
+
"ressalva",
|
|
723
|
+
),
|
|
724
|
+
required=("id", "relato"),
|
|
725
|
+
)
|
|
726
|
+
identifier = _text(record["id"], path=f"{path}.id")
|
|
727
|
+
if EVIDENCE_ID.fullmatch(identifier) is None:
|
|
728
|
+
raise _error(f"{path}.id", f"ID de evidência inválido: {identifier!r} (use EV1)")
|
|
729
|
+
return EvidenceRecord(
|
|
730
|
+
id=identifier,
|
|
731
|
+
relato=_text(record["relato"], path=f"{path}.relato"),
|
|
732
|
+
itens=tuple(_text_list(record.get("itens") or [], path=f"{path}.itens")),
|
|
733
|
+
itens_questionario=tuple(
|
|
734
|
+
_token_list(
|
|
735
|
+
record.get("itens_questionario") or [],
|
|
736
|
+
path=f"{path}.itens_questionario",
|
|
737
|
+
pattern=QUESTIONNAIRE_CODE,
|
|
738
|
+
)
|
|
739
|
+
),
|
|
740
|
+
referencias_matriz=tuple(
|
|
741
|
+
_token_list(
|
|
742
|
+
record.get("referencias_matriz") or [],
|
|
743
|
+
path=f"{path}.referencias_matriz",
|
|
744
|
+
pattern=MATRIX_REFERENCE,
|
|
745
|
+
)
|
|
746
|
+
),
|
|
747
|
+
fontes=_parse_fontes(record.get("fontes") or [], path=f"{path}.fontes"),
|
|
748
|
+
ressalva=_optional_text(record["ressalva"], path=f"{path}.ressalva") if "ressalva" in record else None,
|
|
749
|
+
)
|
|
750
|
+
|
|
751
|
+
|
|
752
|
+
def _parse_evidence(raw: Any, *, path: str) -> tuple[EvidenceSituation, ...]:
|
|
753
|
+
if not isinstance(raw, list):
|
|
754
|
+
raise _error(path, "deve ser uma lista de situações verificáveis")
|
|
755
|
+
if not raw:
|
|
756
|
+
raise _error(path, "o achado precisa de pelo menos uma situação verificável")
|
|
757
|
+
situations: list[EvidenceSituation] = []
|
|
758
|
+
seen: set[str] = set()
|
|
759
|
+
for index, item in enumerate(raw):
|
|
760
|
+
item_path = f"{path}[{index}]"
|
|
761
|
+
if not isinstance(item, Mapping) or len(item) != 1:
|
|
762
|
+
raise _error(item_path, "cada situação deve ser um mapeamento com uma única chave 'S<id>:'")
|
|
763
|
+
situation_id, body = next(iter(item.items()))
|
|
764
|
+
situation_id = str(situation_id).strip()
|
|
765
|
+
if SITUATION_ID.fullmatch(situation_id) is None:
|
|
766
|
+
raise _error(item_path, f"ID de situação inválido: {situation_id!r} (use S1.1)")
|
|
767
|
+
if situation_id in seen:
|
|
768
|
+
raise _error(item_path, f"situação repetida no achado: {situation_id}")
|
|
769
|
+
seen.add(situation_id)
|
|
770
|
+
situation = _mapping(
|
|
771
|
+
body,
|
|
772
|
+
path=f"{item_path}.{situation_id}",
|
|
773
|
+
allowed=("descricao", "registros"),
|
|
774
|
+
required=("descricao", "registros"),
|
|
775
|
+
)
|
|
776
|
+
registros = situation["registros"]
|
|
777
|
+
if not isinstance(registros, list) or not registros:
|
|
778
|
+
raise _error(f"{item_path}.{situation_id}.registros", "informe pelo menos um registro de evidência")
|
|
779
|
+
records = tuple(
|
|
780
|
+
_parse_evidence_record(registro, path=f"{item_path}.{situation_id}.registros[{position}]")
|
|
781
|
+
for position, registro in enumerate(registros)
|
|
782
|
+
)
|
|
783
|
+
if len({record.id for record in records}) != len(records):
|
|
784
|
+
raise _error(f"{item_path}.{situation_id}.registros", "IDs de evidência repetidos na situação")
|
|
785
|
+
situations.append(
|
|
786
|
+
EvidenceSituation(
|
|
787
|
+
id=situation_id,
|
|
788
|
+
descricao=_text(situation["descricao"], path=f"{item_path}.{situation_id}.descricao"),
|
|
789
|
+
registros=records,
|
|
790
|
+
)
|
|
791
|
+
)
|
|
792
|
+
return tuple(situations)
|
|
793
|
+
|
|
794
|
+
|
|
795
|
+
def _parse_effects(raw: Any, *, path: str, situation_ids: Sequence[str]) -> tuple[FindingEffect, ...] | str:
|
|
796
|
+
if isinstance(raw, str):
|
|
797
|
+
return _text(raw, path=path)
|
|
798
|
+
if not isinstance(raw, list):
|
|
799
|
+
raise _error(path, "deve ser um texto ou uma lista de efeitos")
|
|
800
|
+
if not raw:
|
|
801
|
+
return ()
|
|
802
|
+
if all(isinstance(item, str) for item in raw):
|
|
803
|
+
return tuple(FindingEffect(id=None, titulo="", descricao=_text(item, path=f"{path}[{index}]")) for index, item in enumerate(raw))
|
|
804
|
+
effects: list[FindingEffect] = []
|
|
805
|
+
seen: set[str] = set()
|
|
806
|
+
for index, item in enumerate(raw):
|
|
807
|
+
item_path = f"{path}[{index}]"
|
|
808
|
+
record = _mapping(
|
|
809
|
+
item,
|
|
810
|
+
path=item_path,
|
|
811
|
+
allowed=("id", "titulo", "descricao", "situacoes"),
|
|
812
|
+
required=("titulo", "descricao"),
|
|
813
|
+
)
|
|
814
|
+
identifier: str | None = None
|
|
815
|
+
if "id" in record:
|
|
816
|
+
identifier = _text(record["id"], path=f"{item_path}.id")
|
|
817
|
+
if EFFECT_ID.fullmatch(identifier) is None:
|
|
818
|
+
raise _error(f"{item_path}.id", f"ID de efeito inválido: {identifier!r} (use EF1)")
|
|
819
|
+
if identifier in seen:
|
|
820
|
+
raise _error(f"{item_path}.id", f"efeito repetido: {identifier}")
|
|
821
|
+
seen.add(identifier)
|
|
822
|
+
related = tuple(
|
|
823
|
+
_token_list(
|
|
824
|
+
record.get("situacoes") or [],
|
|
825
|
+
path=f"{item_path}.situacoes",
|
|
826
|
+
pattern=SITUATION_ID,
|
|
827
|
+
)
|
|
828
|
+
)
|
|
829
|
+
unknown = [value for value in related if value not in situation_ids]
|
|
830
|
+
if unknown:
|
|
831
|
+
raise _error(f"{item_path}.situacoes", f"situação não declarada nas evidências do achado: {unknown[0]}")
|
|
832
|
+
effects.append(
|
|
833
|
+
FindingEffect(
|
|
834
|
+
id=identifier,
|
|
835
|
+
titulo=_text(record["titulo"], path=f"{item_path}.titulo"),
|
|
836
|
+
descricao=_text(record["descricao"], path=f"{item_path}.descricao"),
|
|
837
|
+
situacoes=related,
|
|
838
|
+
)
|
|
839
|
+
)
|
|
840
|
+
return tuple(effects)
|
|
841
|
+
|
|
842
|
+
|
|
843
|
+
def _parse_referrals(
|
|
844
|
+
raw: Any,
|
|
845
|
+
*,
|
|
846
|
+
path: str,
|
|
847
|
+
situation_ids: Sequence[str],
|
|
848
|
+
criteria: Sequence[FindingCriterion],
|
|
849
|
+
) -> tuple[ReferralSituation, ...]:
|
|
850
|
+
if not isinstance(raw, list):
|
|
851
|
+
raise _error(path, "deve ser uma lista de encaminhamentos por situação")
|
|
852
|
+
criteria_by_local: dict[str, set[str]] = {}
|
|
853
|
+
for criterion in criteria:
|
|
854
|
+
criteria_by_local.setdefault(criterion.id_local, set()).add(criterion.id)
|
|
855
|
+
criteria_ids = {criterion.id for criterion in criteria}
|
|
856
|
+
situations: list[ReferralSituation] = []
|
|
857
|
+
seen_situations: set[str] = set()
|
|
858
|
+
seen_referrals: set[str] = set()
|
|
859
|
+
for index, item in enumerate(raw):
|
|
860
|
+
item_path = f"{path}[{index}]"
|
|
861
|
+
if not isinstance(item, Mapping) or len(item) != 1:
|
|
862
|
+
raise _error(item_path, "cada encaminhamento deve ser um mapeamento com uma única chave 'S<id>:'")
|
|
863
|
+
situation_id, body = next(iter(item.items()))
|
|
864
|
+
situation_id = str(situation_id).strip()
|
|
865
|
+
if SITUATION_ID.fullmatch(situation_id) is None:
|
|
866
|
+
raise _error(item_path, f"ID de situação inválido: {situation_id!r} (use S1.1)")
|
|
867
|
+
if situation_id not in situation_ids:
|
|
868
|
+
raise _error(item_path, f"a situação {situation_id} não foi declarada nas evidências do achado")
|
|
869
|
+
if situation_id in seen_situations:
|
|
870
|
+
raise _error(item_path, f"encaminhamentos repetidos para a situação {situation_id}")
|
|
871
|
+
seen_situations.add(situation_id)
|
|
872
|
+
situation = _mapping(
|
|
873
|
+
body,
|
|
874
|
+
path=f"{item_path}.{situation_id}",
|
|
875
|
+
allowed=("propostas",),
|
|
876
|
+
required=("propostas",),
|
|
877
|
+
)
|
|
878
|
+
proposals_raw = situation["propostas"]
|
|
879
|
+
if not isinstance(proposals_raw, list):
|
|
880
|
+
raise _error(f"{item_path}.{situation_id}.propostas", "deve ser uma lista de propostas")
|
|
881
|
+
proposals: list[ReferralProposal] = []
|
|
882
|
+
for position, proposal_raw in enumerate(proposals_raw):
|
|
883
|
+
proposal_path = f"{item_path}.{situation_id}.propostas[{position}]"
|
|
884
|
+
record = _mapping(
|
|
885
|
+
proposal_raw,
|
|
886
|
+
path=proposal_path,
|
|
887
|
+
allowed=(
|
|
888
|
+
"id",
|
|
889
|
+
"tipo_encaminhamento",
|
|
890
|
+
"encaminhamento",
|
|
891
|
+
"fundamentacao_encaminhamento",
|
|
892
|
+
"criterios",
|
|
893
|
+
"publico",
|
|
894
|
+
"id_variante",
|
|
895
|
+
),
|
|
896
|
+
required=("id", "tipo_encaminhamento", "encaminhamento"),
|
|
897
|
+
)
|
|
898
|
+
identifier = _text(record["id"], path=f"{proposal_path}.id")
|
|
899
|
+
if REFERRAL_ID.fullmatch(identifier) is None:
|
|
900
|
+
raise _error(f"{proposal_path}.id", f"ID de encaminhamento inválido: {identifier!r} (use EN1)")
|
|
901
|
+
if identifier in seen_referrals:
|
|
902
|
+
raise _error(f"{proposal_path}.id", f"encaminhamento repetido no achado: {identifier}")
|
|
903
|
+
seen_referrals.add(identifier)
|
|
904
|
+
references: list[str] = []
|
|
905
|
+
for position_ref, reference in enumerate(record.get("criterios") or []):
|
|
906
|
+
token = _text(reference, path=f"{proposal_path}.criterios[{position_ref}]")
|
|
907
|
+
canonical = token if token in criteria_ids else None
|
|
908
|
+
if canonical is None:
|
|
909
|
+
local_matches = sorted(criteria_by_local.get(token, set()))
|
|
910
|
+
if len(local_matches) > 1:
|
|
911
|
+
raise _error(
|
|
912
|
+
f"{proposal_path}.criterios[{position_ref}]",
|
|
913
|
+
f"critério local ambíguo {token!r}; use um ID qualificado entre {', '.join(local_matches)}",
|
|
914
|
+
)
|
|
915
|
+
canonical = local_matches[0] if local_matches else None
|
|
916
|
+
if canonical is None:
|
|
917
|
+
raise _error(
|
|
918
|
+
f"{proposal_path}.criterios[{position_ref}]",
|
|
919
|
+
f"critério não declarado no achado: {token!r}",
|
|
920
|
+
)
|
|
921
|
+
references.append(canonical)
|
|
922
|
+
proposals.append(
|
|
923
|
+
ReferralProposal(
|
|
924
|
+
id=identifier,
|
|
925
|
+
tipo_encaminhamento=_text(record["tipo_encaminhamento"], path=f"{proposal_path}.tipo_encaminhamento"),
|
|
926
|
+
encaminhamento=_text(record["encaminhamento"], path=f"{proposal_path}.encaminhamento"),
|
|
927
|
+
fundamentacao_encaminhamento=(
|
|
928
|
+
_text(
|
|
929
|
+
record["fundamentacao_encaminhamento"],
|
|
930
|
+
path=f"{proposal_path}.fundamentacao_encaminhamento",
|
|
931
|
+
)
|
|
932
|
+
if record.get("fundamentacao_encaminhamento")
|
|
933
|
+
else ""
|
|
934
|
+
),
|
|
935
|
+
criterios=tuple(references),
|
|
936
|
+
publico=_optional_text(record["publico"], path=f"{proposal_path}.publico")
|
|
937
|
+
if "publico" in record
|
|
938
|
+
else None,
|
|
939
|
+
id_variante=_optional_text(record["id_variante"], path=f"{proposal_path}.id_variante")
|
|
940
|
+
if "id_variante" in record
|
|
941
|
+
else None,
|
|
942
|
+
)
|
|
943
|
+
)
|
|
944
|
+
situations.append(ReferralSituation(id=situation_id, propostas=tuple(proposals)))
|
|
945
|
+
return tuple(situations)
|
|
946
|
+
|
|
947
|
+
|
|
948
|
+
def _parse_finding(
|
|
949
|
+
finding_id: str,
|
|
950
|
+
titulo: str,
|
|
951
|
+
block: str,
|
|
952
|
+
*,
|
|
953
|
+
line: int,
|
|
954
|
+
) -> Finding:
|
|
955
|
+
path = f"Achado {finding_id}"
|
|
956
|
+
fields = field_values(
|
|
957
|
+
block,
|
|
958
|
+
path=path,
|
|
959
|
+
line=line,
|
|
960
|
+
allowed=(*FINDINGS_FINDING_FIELDS, *FORBIDDEN_FACT_FIELDS),
|
|
961
|
+
reject_unknown=True,
|
|
962
|
+
)
|
|
963
|
+
data = {
|
|
964
|
+
name: parse_field_value(
|
|
965
|
+
field,
|
|
966
|
+
path=f"{path}.{name}",
|
|
967
|
+
nested_token_lists=("itens_questionario",) if name == "evidencias" else (),
|
|
968
|
+
)
|
|
969
|
+
for name, field in fields.items()
|
|
970
|
+
}
|
|
971
|
+
if not data:
|
|
972
|
+
raise _error(path, "seção vazia: declare os seis atributos editoriais", line=line)
|
|
973
|
+
for key in data:
|
|
974
|
+
if key in FORBIDDEN_FACT_FIELDS:
|
|
975
|
+
raise _error(
|
|
976
|
+
f"{path}.{key}",
|
|
977
|
+
f"o campo {key!r} não pertence à matriz de achados; informe --resultado-auditoria para derivar esses dados",
|
|
978
|
+
line=line,
|
|
979
|
+
)
|
|
980
|
+
if key not in FINDINGS_FINDING_FIELDS:
|
|
981
|
+
raise _error(f"{path}.{key}", "atributo desconhecido no achado", line=line)
|
|
982
|
+
missing = [key for key in FINDINGS_REQUIRED_FINDING_FIELDS if key not in data]
|
|
983
|
+
if missing:
|
|
984
|
+
raise _error(f"{path}.{missing[0]}", "atributo editorial obrigatório ausente", line=line)
|
|
985
|
+
questao = _optional_text(data["questao"], path=f"{path}.questao", line=line) if "questao" in data else None
|
|
986
|
+
question_id = question_identifier(questao)
|
|
987
|
+
criteria = _parse_criteria(data["criterios"], path=f"{path}.criterios", question_id=question_id)
|
|
988
|
+
evidencias = _parse_evidence(data["evidencias"], path=f"{path}.evidencias")
|
|
989
|
+
evidence_ids: set[str] = set()
|
|
990
|
+
for situation in evidencias:
|
|
991
|
+
for record in situation.registros:
|
|
992
|
+
if record.id in evidence_ids:
|
|
993
|
+
raise _error(
|
|
994
|
+
f"{path}.evidencias.{situation.id}.registros",
|
|
995
|
+
f"ID de evidência repetido no achado: {record.id}",
|
|
996
|
+
)
|
|
997
|
+
evidence_ids.add(record.id)
|
|
998
|
+
efeitos = _parse_effects(
|
|
999
|
+
data["efeitos"],
|
|
1000
|
+
path=f"{path}.efeitos",
|
|
1001
|
+
situation_ids=tuple(situation.id for situation in evidencias),
|
|
1002
|
+
)
|
|
1003
|
+
encaminhamentos = _parse_referrals(
|
|
1004
|
+
data["encaminhamentos"],
|
|
1005
|
+
path=f"{path}.encaminhamentos",
|
|
1006
|
+
situation_ids=tuple(situation.id for situation in evidencias),
|
|
1007
|
+
criteria=criteria,
|
|
1008
|
+
)
|
|
1009
|
+
return Finding(
|
|
1010
|
+
id=finding_id,
|
|
1011
|
+
titulo=titulo,
|
|
1012
|
+
questao=questao,
|
|
1013
|
+
situacao_encontrada=_text(data["situacao_encontrada"], path=f"{path}.situacao_encontrada", line=line),
|
|
1014
|
+
criterios=criteria,
|
|
1015
|
+
evidencias=evidencias,
|
|
1016
|
+
causas=_text(data["causas"], path=f"{path}.causas", line=line),
|
|
1017
|
+
efeitos=efeitos,
|
|
1018
|
+
encaminhamentos=encaminhamentos,
|
|
1019
|
+
)
|
|
1020
|
+
|
|
1021
|
+
|
|
1022
|
+
def _scan_body(body: str, *, path: str) -> tuple[list[tuple[int, str, str, int]], str, int | None]:
|
|
1023
|
+
"""Localiza H1/H2 de conteúdo e devolve seções ``(índice, id, título, linha)``."""
|
|
1024
|
+
lines = body.split("\n")
|
|
1025
|
+
h1_lines: list[int] = []
|
|
1026
|
+
sections: list[tuple[int, str, str, int]] = []
|
|
1027
|
+
for index, line in enumerate(lines):
|
|
1028
|
+
if line.startswith("# "):
|
|
1029
|
+
h1_lines.append(index)
|
|
1030
|
+
continue
|
|
1031
|
+
if not line.startswith("## "):
|
|
1032
|
+
continue
|
|
1033
|
+
heading = line[3:].strip()
|
|
1034
|
+
match = re.fullmatch(r"Achado\s+(\S+)\s+-\s+(.+?)\s*", heading)
|
|
1035
|
+
if match is None:
|
|
1036
|
+
raise _error(f"{path}.cabeçalho", "use '## Achado <ID> - <título>'", line=index + 1)
|
|
1037
|
+
finding_id, title = match.groups()
|
|
1038
|
+
if FINDING_ID.fullmatch(finding_id) is None:
|
|
1039
|
+
raise _error(f"{path}.cabeçalho", f"ID de achado inválido: {finding_id!r} (use A1)", line=index + 1)
|
|
1040
|
+
normalized_id = f"A{int(finding_id[1:])}"
|
|
1041
|
+
sections.append((index, normalized_id, title.strip(), index + 1))
|
|
1042
|
+
first_section = sections[0][0] if sections else len(lines)
|
|
1043
|
+
if len(h1_lines) > 1 or (h1_lines and h1_lines[0] > first_section):
|
|
1044
|
+
raise _error(
|
|
1045
|
+
f"{path}.cabeçalho",
|
|
1046
|
+
"permite-se um único título H1, antes do primeiro '## Achado ...'",
|
|
1047
|
+
line=(h1_lines[1] if len(h1_lines) > 1 else h1_lines[0]) + 1,
|
|
1048
|
+
)
|
|
1049
|
+
h1_line = h1_lines[0] if h1_lines else None
|
|
1050
|
+
preamble_lines = [line for position, line in enumerate(lines[:first_section]) if position != h1_line]
|
|
1051
|
+
return sections, "\n".join(preamble_lines), h1_line
|
|
1052
|
+
|
|
1053
|
+
|
|
1054
|
+
def parse_findings_markdown(
|
|
1055
|
+
markdown: str,
|
|
1056
|
+
*,
|
|
1057
|
+
project_metadata: Mapping[str, Any] | None = None,
|
|
1058
|
+
fiscalizacao_id: str | None = None,
|
|
1059
|
+
path: str = "matriz de achados",
|
|
1060
|
+
) -> FindingsDocument:
|
|
1061
|
+
"""Lê o Markdown v1.3 da matriz de achados (front matter + seis blocos)."""
|
|
1062
|
+
if not isinstance(markdown, str) or not markdown.strip():
|
|
1063
|
+
raise _error(path, "Markdown vazio", line=1)
|
|
1064
|
+
text = normalize_text(markdown)
|
|
1065
|
+
if text.lstrip().startswith("{"):
|
|
1066
|
+
try:
|
|
1067
|
+
json.loads(text)
|
|
1068
|
+
except json.JSONDecodeError:
|
|
1069
|
+
pass
|
|
1070
|
+
else:
|
|
1071
|
+
raise _error(
|
|
1072
|
+
path,
|
|
1073
|
+
"o conteúdo é JSON; use o Markdown revisado para publicar ou `matriz rascunho` para criar o rascunho",
|
|
1074
|
+
line=1,
|
|
1075
|
+
)
|
|
1076
|
+
front = split_front_matter(text, required=True, path=path)
|
|
1077
|
+
if not front.metadata:
|
|
1078
|
+
raise _error(f"{path}.front_matter", "front matter vazio", line=1)
|
|
1079
|
+
local = validate_front_matter(front.metadata, kind="achados", path=f"{path}.front_matter")
|
|
1080
|
+
metadata = resolve_metadata(local, project_metadata, kind="achados", require_editorial=True)
|
|
1081
|
+
declared_id = local.get("origem", {}).get("fiscalizacao_id")
|
|
1082
|
+
if fiscalizacao_id is not None and declared_id and declared_id != fiscalizacao_id:
|
|
1083
|
+
raise _error(
|
|
1084
|
+
f"{path}.front_matter.origem.fiscalizacao_id",
|
|
1085
|
+
"o documento pertence a outro projeto",
|
|
1086
|
+
)
|
|
1087
|
+
|
|
1088
|
+
body_line = front.body_line
|
|
1089
|
+
sections, preamble, h1_line = _scan_body(front.body, path=path)
|
|
1090
|
+
preamble_data = _yaml_mapping(
|
|
1091
|
+
preamble,
|
|
1092
|
+
path=f"{path}.preambulo",
|
|
1093
|
+
line=body_line + 1,
|
|
1094
|
+
allow_empty=True,
|
|
1095
|
+
)
|
|
1096
|
+
for key in preamble_data:
|
|
1097
|
+
if key in FORBIDDEN_FACT_FIELDS:
|
|
1098
|
+
raise _error(
|
|
1099
|
+
f"{path}.{key}",
|
|
1100
|
+
f"o campo {key!r} não pertence à matriz de achados; informe --resultado-auditoria para derivar esses dados",
|
|
1101
|
+
)
|
|
1102
|
+
if key not in ("achados", "apresentacao"):
|
|
1103
|
+
raise _error(f"{path}.{key}", "atributo desconhecido no preâmbulo")
|
|
1104
|
+
presentation = _presentation(preamble_data.get("apresentacao"))
|
|
1105
|
+
empty_declared = "achados" in preamble_data
|
|
1106
|
+
if empty_declared and preamble_data["achados"] != []:
|
|
1107
|
+
raise _error(
|
|
1108
|
+
f"{path}.achados",
|
|
1109
|
+
"para o documento sem achados declare exatamente 'achados: []'; nos demais casos use '## Achado <ID> - <título>'",
|
|
1110
|
+
)
|
|
1111
|
+
findings: list[Finding] = []
|
|
1112
|
+
if sections:
|
|
1113
|
+
if empty_declared:
|
|
1114
|
+
raise _error(f"{path}.achados", "não declare 'achados: []' junto com cabeçalhos de achado")
|
|
1115
|
+
seen: set[str] = set()
|
|
1116
|
+
body_lines = front.body.split("\n")
|
|
1117
|
+
for position, (index, finding_id, title, heading_line) in enumerate(sections):
|
|
1118
|
+
if finding_id in seen:
|
|
1119
|
+
raise _error(f"{path}.cabeçalho", f"ID de achado duplicado: {finding_id}", line=body_line + index)
|
|
1120
|
+
seen.add(finding_id)
|
|
1121
|
+
end = sections[position + 1][0] if position + 1 < len(sections) else len(body_lines)
|
|
1122
|
+
block = "\n".join(body_lines[index + 1 : end])
|
|
1123
|
+
findings.append(_parse_finding(finding_id, title, block, line=body_line + index + 1))
|
|
1124
|
+
elif not empty_declared:
|
|
1125
|
+
raise _error(
|
|
1126
|
+
f"{path}",
|
|
1127
|
+
"sem '## Achado ...' o documento precisa declarar 'achados: []'",
|
|
1128
|
+
line=body_line + 1,
|
|
1129
|
+
)
|
|
1130
|
+
situation_ids: set[str] = set()
|
|
1131
|
+
for finding in findings:
|
|
1132
|
+
for situation in finding.evidencias:
|
|
1133
|
+
if situation.id in situation_ids:
|
|
1134
|
+
raise _error(
|
|
1135
|
+
f"{path}.achado {finding.id}",
|
|
1136
|
+
f"ID de situação repetido no documento: {situation.id}",
|
|
1137
|
+
)
|
|
1138
|
+
situation_ids.add(situation.id)
|
|
1139
|
+
unknown_spacing = set(presentation.espacamento_titulo_evidencia_por_situacao_twips) - situation_ids
|
|
1140
|
+
if unknown_spacing:
|
|
1141
|
+
raise _error(
|
|
1142
|
+
f"{path}.apresentacao.espacamento_titulo_evidencia_por_situacao_twips",
|
|
1143
|
+
f"situação não declarada: {sorted(unknown_spacing)[0]}",
|
|
1144
|
+
)
|
|
1145
|
+
document = FindingsDocument(
|
|
1146
|
+
metadata=metadata,
|
|
1147
|
+
achados=tuple(findings),
|
|
1148
|
+
apresentacao=presentation,
|
|
1149
|
+
front_matter=dict(local),
|
|
1150
|
+
)
|
|
1151
|
+
return document
|
|
1152
|
+
|
|
1153
|
+
|
|
1154
|
+
# --------------------------------------------------------------------------------------
|
|
1155
|
+
# Validação editorial (sem JSON)
|
|
1156
|
+
# --------------------------------------------------------------------------------------
|
|
1157
|
+
|
|
1158
|
+
|
|
1159
|
+
def _finding_texts(finding: Finding) -> Iterable[tuple[str, str]]:
|
|
1160
|
+
yield "situacao_encontrada", finding.situacao_encontrada
|
|
1161
|
+
yield "causas", finding.causas
|
|
1162
|
+
if isinstance(finding.efeitos, str):
|
|
1163
|
+
yield "efeitos", finding.efeitos
|
|
1164
|
+
else:
|
|
1165
|
+
for index, effect in enumerate(finding.efeitos):
|
|
1166
|
+
yield f"efeitos[{index}].titulo", effect.titulo
|
|
1167
|
+
yield f"efeitos[{index}].descricao", effect.descricao
|
|
1168
|
+
for situation in finding.evidencias:
|
|
1169
|
+
yield f"evidencias.{situation.id}.descricao", situation.descricao
|
|
1170
|
+
for record in situation.registros:
|
|
1171
|
+
yield f"evidencias.{situation.id}.{record.id}.relato", record.relato
|
|
1172
|
+
for situation in finding.encaminhamentos:
|
|
1173
|
+
for proposal in situation.propostas:
|
|
1174
|
+
yield f"encaminhamentos.{situation.id}.{proposal.id}.encaminhamento", proposal.encaminhamento
|
|
1175
|
+
yield (
|
|
1176
|
+
f"encaminhamentos.{situation.id}.{proposal.id}.fundamentacao_encaminhamento",
|
|
1177
|
+
proposal.fundamentacao_encaminhamento,
|
|
1178
|
+
)
|
|
1179
|
+
|
|
1180
|
+
|
|
1181
|
+
def pending_placeholders(document: FindingsDocument) -> list[str]:
|
|
1182
|
+
"""Lista os marcadores ``[PREENCHER: ...]`` ainda visíveis no documento."""
|
|
1183
|
+
pending: list[str] = []
|
|
1184
|
+
for field, value in document.metadata.to_mapping().items():
|
|
1185
|
+
if field == "origem" or value is None:
|
|
1186
|
+
continue
|
|
1187
|
+
if _PLACEHOLDER.search(str(value)):
|
|
1188
|
+
pending.append(f"front_matter.{field}")
|
|
1189
|
+
for finding in document.achados:
|
|
1190
|
+
for field, text in _finding_texts(finding):
|
|
1191
|
+
if _PLACEHOLDER.search(text or ""):
|
|
1192
|
+
pending.append(f"Achado {finding.id}.{field}")
|
|
1193
|
+
return pending
|
|
1194
|
+
|
|
1195
|
+
|
|
1196
|
+
def validate_findings_markdown(
|
|
1197
|
+
markdown: str,
|
|
1198
|
+
*,
|
|
1199
|
+
strict: bool = False,
|
|
1200
|
+
project_metadata: Mapping[str, Any] | None = None,
|
|
1201
|
+
) -> dict[str, Any]:
|
|
1202
|
+
"""Valida a matriz de achados apenas com o escopo editorial disponível."""
|
|
1203
|
+
messages: list[dict[str, Any]] = []
|
|
1204
|
+
document: FindingsDocument | None = None
|
|
1205
|
+
try:
|
|
1206
|
+
document = parse_findings_markdown(markdown, project_metadata=project_metadata)
|
|
1207
|
+
except InputValidationError as exc:
|
|
1208
|
+
messages.append({"level": "ERROR", "code": "ESTRUTURA", "text": str(exc), "line": None})
|
|
1209
|
+
pending = 0
|
|
1210
|
+
if document is not None:
|
|
1211
|
+
for field in pending_placeholders(document):
|
|
1212
|
+
if not field.startswith("Achado "):
|
|
1213
|
+
pending += 1
|
|
1214
|
+
messages.append(
|
|
1215
|
+
{
|
|
1216
|
+
"level": "WARNING",
|
|
1217
|
+
"code": "PENDENCIA_EDITORIAL",
|
|
1218
|
+
"text": f"{field}: substitua o marcador [PREENCHER: ...] pelo metadado revisado.",
|
|
1219
|
+
"line": None,
|
|
1220
|
+
}
|
|
1221
|
+
)
|
|
1222
|
+
for finding in document.achados:
|
|
1223
|
+
if not finding.questao:
|
|
1224
|
+
messages.append(
|
|
1225
|
+
{
|
|
1226
|
+
"level": "WARNING",
|
|
1227
|
+
"code": "QUESTAO_AUSENTE",
|
|
1228
|
+
"text": f"Achado {finding.id}: declare 'questao' para vincular o achado ao planejamento.",
|
|
1229
|
+
"line": None,
|
|
1230
|
+
}
|
|
1231
|
+
)
|
|
1232
|
+
for field, text in _finding_texts(finding):
|
|
1233
|
+
if _PLACEHOLDER.search(text or ""):
|
|
1234
|
+
pending += 1
|
|
1235
|
+
messages.append(
|
|
1236
|
+
{
|
|
1237
|
+
"level": "WARNING",
|
|
1238
|
+
"code": "PENDENCIA_EDITORIAL",
|
|
1239
|
+
"text": f"Achado {finding.id}.{field}: substitua o marcador [PREENCHER: ...] pelo texto revisado antes de publicar.",
|
|
1240
|
+
"line": None,
|
|
1241
|
+
}
|
|
1242
|
+
)
|
|
1243
|
+
if isinstance(finding.efeitos, tuple) and not finding.efeitos:
|
|
1244
|
+
pending += 1
|
|
1245
|
+
messages.append(
|
|
1246
|
+
{
|
|
1247
|
+
"level": "WARNING",
|
|
1248
|
+
"code": "PENDENCIA_EDITORIAL",
|
|
1249
|
+
"text": f"Achado {finding.id}.efeitos: nenhum efeito registrado; preencha a coluna EFEITO.",
|
|
1250
|
+
"line": None,
|
|
1251
|
+
}
|
|
1252
|
+
)
|
|
1253
|
+
declared = {situation.id for situation in finding.encaminhamentos}
|
|
1254
|
+
for situation in finding.evidencias:
|
|
1255
|
+
if situation.id not in declared:
|
|
1256
|
+
pending += 1
|
|
1257
|
+
messages.append(
|
|
1258
|
+
{
|
|
1259
|
+
"level": "WARNING",
|
|
1260
|
+
"code": "PENDENCIA_EDITORIAL",
|
|
1261
|
+
"text": f"Achado {finding.id}: a situação {situation.id} não possui encaminhamento declarado.",
|
|
1262
|
+
"line": None,
|
|
1263
|
+
}
|
|
1264
|
+
)
|
|
1265
|
+
errors = sum(1 for message in messages if message["level"] == "ERROR")
|
|
1266
|
+
warnings = sum(1 for message in messages if message["level"] == "WARNING")
|
|
1267
|
+
valid = errors == 0 and not (strict and warnings)
|
|
1268
|
+
warning_messages = tuple(
|
|
1269
|
+
f"[{message['level']}] {message['code']}: {message['text']}"
|
|
1270
|
+
for message in messages
|
|
1271
|
+
if message["level"] == "WARNING"
|
|
1272
|
+
)
|
|
1273
|
+
summary: dict[str, Any] = {
|
|
1274
|
+
"findings": len(document.achados) if document else 0,
|
|
1275
|
+
"situations": sum(len(finding.evidencias) for finding in document.achados) if document else 0,
|
|
1276
|
+
"criteria": sum(len(finding.criterios) for finding in document.achados) if document else 0,
|
|
1277
|
+
"evidence_records": (
|
|
1278
|
+
sum(len(situation.registros) for finding in document.achados for situation in finding.evidencias)
|
|
1279
|
+
if document
|
|
1280
|
+
else 0
|
|
1281
|
+
),
|
|
1282
|
+
"referrals": (
|
|
1283
|
+
sum(len(situation.propostas) for finding in document.achados for situation in finding.encaminhamentos)
|
|
1284
|
+
if document
|
|
1285
|
+
else 0
|
|
1286
|
+
),
|
|
1287
|
+
"pending_editorial": pending,
|
|
1288
|
+
"occurrences": None,
|
|
1289
|
+
"auditees_with_findings": None,
|
|
1290
|
+
}
|
|
1291
|
+
return {
|
|
1292
|
+
"valid": valid,
|
|
1293
|
+
"messages": messages,
|
|
1294
|
+
"errors": errors,
|
|
1295
|
+
"warning_count": warnings,
|
|
1296
|
+
"warnings": warning_messages,
|
|
1297
|
+
"summary": summary,
|
|
1298
|
+
"metadata": document.metadata.to_mapping() if document else {},
|
|
1299
|
+
"metadata_sources": dict(document.metadata.fontes) if document else {},
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
|
|
1303
|
+
# --------------------------------------------------------------------------------------
|
|
1304
|
+
# Serialização e rascunho
|
|
1305
|
+
# --------------------------------------------------------------------------------------
|
|
1306
|
+
|
|
1307
|
+
|
|
1308
|
+
_RESERVED_SCALARS = {
|
|
1309
|
+
"null",
|
|
1310
|
+
"~",
|
|
1311
|
+
"true",
|
|
1312
|
+
"false",
|
|
1313
|
+
"yes",
|
|
1314
|
+
"no",
|
|
1315
|
+
"on",
|
|
1316
|
+
"off",
|
|
1317
|
+
"y",
|
|
1318
|
+
"n",
|
|
1319
|
+
}
|
|
1320
|
+
|
|
1321
|
+
|
|
1322
|
+
def _plain_scalar_ok(text: str) -> bool:
|
|
1323
|
+
if not text or text != text.strip() or "\n" in text:
|
|
1324
|
+
return False
|
|
1325
|
+
if text.casefold() in _RESERVED_SCALARS:
|
|
1326
|
+
return False
|
|
1327
|
+
if re.fullmatch(r"[-+]?[0-9][0-9_.:+-]*", text):
|
|
1328
|
+
return False
|
|
1329
|
+
if text[0] in "-?:,[]{}#&*!|>'\"%@` ":
|
|
1330
|
+
return False
|
|
1331
|
+
if ": " in text or text.endswith(":") or " #" in text:
|
|
1332
|
+
return False
|
|
1333
|
+
return not any(character in text for character in "[]{}&*!|>\"@`\t")
|
|
1334
|
+
|
|
1335
|
+
|
|
1336
|
+
def _scalar(value: Any) -> str:
|
|
1337
|
+
text = str(value)
|
|
1338
|
+
if _plain_scalar_ok(text):
|
|
1339
|
+
return text
|
|
1340
|
+
return json.dumps(text, ensure_ascii=False)
|
|
1341
|
+
|
|
1342
|
+
|
|
1343
|
+
def _block_scalar(key: str, text: str, *, indent: int) -> list[str]:
|
|
1344
|
+
prefix = " " * indent
|
|
1345
|
+
lines = [f"{prefix}{key}: |-"]
|
|
1346
|
+
for line in text.split("\n"):
|
|
1347
|
+
lines.append(f"{prefix} {line}" if line.strip() else "")
|
|
1348
|
+
return lines
|
|
1349
|
+
|
|
1350
|
+
|
|
1351
|
+
def _emit_value(key: str, value: Any, *, indent: int) -> list[str]:
|
|
1352
|
+
prefix = " " * indent
|
|
1353
|
+
if isinstance(value, bool):
|
|
1354
|
+
return [f"{prefix}{key}: {'true' if value else 'false'}"]
|
|
1355
|
+
if value is None:
|
|
1356
|
+
return [f"{prefix}{key}: null"]
|
|
1357
|
+
text = str(value)
|
|
1358
|
+
if "\n" in text:
|
|
1359
|
+
return _block_scalar(key, text, indent=indent)
|
|
1360
|
+
return [f"{prefix}{key}: {_scalar(text)}"]
|
|
1361
|
+
|
|
1362
|
+
|
|
1363
|
+
def _emit_token_list(key: str, values: Sequence[str], *, indent: int) -> list[str]:
|
|
1364
|
+
prefix = " " * indent
|
|
1365
|
+
if not values:
|
|
1366
|
+
return [f"{prefix}{key}: []"]
|
|
1367
|
+
if all(_plain_scalar_ok(value) and "," not in value for value in values):
|
|
1368
|
+
return [f"{prefix}{key}: [{', '.join(values)}]"]
|
|
1369
|
+
lines = [f"{prefix}{key}:"]
|
|
1370
|
+
for value in values:
|
|
1371
|
+
lines.append(f"{prefix} - {_scalar(value)}")
|
|
1372
|
+
return lines
|
|
1373
|
+
|
|
1374
|
+
|
|
1375
|
+
def _criterion_reference(identifier: str, *, finding: Finding) -> str:
|
|
1376
|
+
question = question_identifier(finding.questao)
|
|
1377
|
+
prefix = f"{question}." if question else None
|
|
1378
|
+
if prefix and identifier.startswith(prefix):
|
|
1379
|
+
return identifier[len(prefix) :]
|
|
1380
|
+
return identifier
|
|
1381
|
+
|
|
1382
|
+
|
|
1383
|
+
def serialize_findings_markdown(document: FindingsDocument) -> str:
|
|
1384
|
+
"""Serializa o documento no contrato v1.3, de forma determinística."""
|
|
1385
|
+
lines: list[str] = ["---"]
|
|
1386
|
+
metadata = document.metadata
|
|
1387
|
+
lines.extend(_emit_value("title", metadata.title, indent=0))
|
|
1388
|
+
lines.extend(_emit_value("fiscalizacao", metadata.fiscalizacao, indent=0))
|
|
1389
|
+
lines.extend(_emit_value("jurisdicionados", metadata.jurisdicionados, indent=0))
|
|
1390
|
+
lines.extend(_emit_value("objetivo_auditoria", metadata.objetivo_auditoria, indent=0))
|
|
1391
|
+
for key in ("processo", "orgao", "unidade_responsavel"):
|
|
1392
|
+
value = getattr(metadata, key)
|
|
1393
|
+
if value:
|
|
1394
|
+
lines.extend(_emit_value(key, value, indent=0))
|
|
1395
|
+
lines.append("tipo_matriz: achados")
|
|
1396
|
+
if metadata.column_widths is not None:
|
|
1397
|
+
lines.append("larguras_colunas_percentuais:")
|
|
1398
|
+
for key, value in zip(
|
|
1399
|
+
metadata.column_widths.keys,
|
|
1400
|
+
metadata.column_widths.percentages,
|
|
1401
|
+
strict=True,
|
|
1402
|
+
):
|
|
1403
|
+
lines.append(f" {key}: {format(value, 'f')}")
|
|
1404
|
+
if metadata.origem:
|
|
1405
|
+
lines.append("origem:")
|
|
1406
|
+
for key, value in metadata.origem.items():
|
|
1407
|
+
lines.extend(_emit_value(key, value, indent=2))
|
|
1408
|
+
lines.append("---")
|
|
1409
|
+
lines.append("")
|
|
1410
|
+
lines.append("# Matriz de Achados")
|
|
1411
|
+
if document.sem_achados:
|
|
1412
|
+
lines.append("")
|
|
1413
|
+
lines.append("achados: []")
|
|
1414
|
+
for finding in document.achados:
|
|
1415
|
+
lines.append("")
|
|
1416
|
+
lines.append(f"## Achado {finding.id} - {finding.titulo}")
|
|
1417
|
+
lines.append("")
|
|
1418
|
+
if finding.questao:
|
|
1419
|
+
lines.extend(_emit_value("questao", finding.questao, indent=0))
|
|
1420
|
+
lines.extend(_block_scalar("situacao_encontrada", finding.situacao_encontrada, indent=0))
|
|
1421
|
+
lines.append("criterios:")
|
|
1422
|
+
for criterion in finding.criterios:
|
|
1423
|
+
identifier = _criterion_reference(criterion.id, finding=finding)
|
|
1424
|
+
lines.append(f"- id: {_scalar(identifier)}")
|
|
1425
|
+
lines.extend(_emit_value("descricao", criterion.descricao, indent=2))
|
|
1426
|
+
if criterion.natureza_fundamento:
|
|
1427
|
+
lines.extend(_emit_value("natureza_fundamento", criterion.natureza_fundamento, indent=2))
|
|
1428
|
+
if criterion.apto_a_fundamentar_determinacao is not None:
|
|
1429
|
+
lines.extend(
|
|
1430
|
+
_emit_value(
|
|
1431
|
+
"apto_a_fundamentar_determinacao",
|
|
1432
|
+
criterion.apto_a_fundamentar_determinacao,
|
|
1433
|
+
indent=2,
|
|
1434
|
+
)
|
|
1435
|
+
)
|
|
1436
|
+
if criterion.publico:
|
|
1437
|
+
lines.extend(_emit_value("publico", criterion.publico, indent=2))
|
|
1438
|
+
if criterion.especifico is not None:
|
|
1439
|
+
lines.extend(_emit_value("especifico", criterion.especifico, indent=2))
|
|
1440
|
+
if criterion.aplica_se:
|
|
1441
|
+
lines.append(" aplica_se:")
|
|
1442
|
+
for key, values in criterion.aplica_se.items():
|
|
1443
|
+
lines.extend(_emit_token_list(key, values, indent=4))
|
|
1444
|
+
lines.append("evidencias:")
|
|
1445
|
+
for situation in finding.evidencias:
|
|
1446
|
+
lines.append(f"- {situation.id}:")
|
|
1447
|
+
lines.extend(_emit_value("descricao", situation.descricao, indent=4))
|
|
1448
|
+
lines.append(" registros:")
|
|
1449
|
+
for record in situation.registros:
|
|
1450
|
+
lines.append(f" - id: {_scalar(record.id)}")
|
|
1451
|
+
lines.extend(_block_scalar("relato", record.relato, indent=6))
|
|
1452
|
+
if record.itens:
|
|
1453
|
+
lines.append(" itens:")
|
|
1454
|
+
for item in record.itens:
|
|
1455
|
+
lines.append(f" - {_scalar(item)}")
|
|
1456
|
+
if record.itens_questionario:
|
|
1457
|
+
lines.extend(_emit_token_list("itens_questionario", record.itens_questionario, indent=6))
|
|
1458
|
+
if record.referencias_matriz:
|
|
1459
|
+
lines.extend(_emit_token_list("referencias_matriz", record.referencias_matriz, indent=6))
|
|
1460
|
+
if record.fontes:
|
|
1461
|
+
lines.append(" fontes:")
|
|
1462
|
+
for source in record.fontes:
|
|
1463
|
+
lines.append(f" - id: {_scalar(source['id'])}")
|
|
1464
|
+
lines.extend(_emit_value("descricao", source["descricao"], indent=8))
|
|
1465
|
+
if record.ressalva:
|
|
1466
|
+
lines.extend(_emit_value("ressalva", record.ressalva, indent=6))
|
|
1467
|
+
lines.extend(_block_scalar("causas", finding.causas, indent=0))
|
|
1468
|
+
if isinstance(finding.efeitos, str):
|
|
1469
|
+
lines.extend(_block_scalar("efeitos", finding.efeitos, indent=0))
|
|
1470
|
+
elif not finding.efeitos:
|
|
1471
|
+
lines.append("efeitos: []")
|
|
1472
|
+
else:
|
|
1473
|
+
lines.append("efeitos:")
|
|
1474
|
+
for effect in finding.efeitos:
|
|
1475
|
+
if effect.id:
|
|
1476
|
+
lines.append(f"- id: {_scalar(effect.id)}")
|
|
1477
|
+
lines.extend(_emit_value("titulo", effect.titulo, indent=2))
|
|
1478
|
+
lines.extend(_emit_value("descricao", effect.descricao, indent=2))
|
|
1479
|
+
if effect.situacoes:
|
|
1480
|
+
lines.extend(_emit_token_list("situacoes", effect.situacoes, indent=2))
|
|
1481
|
+
else:
|
|
1482
|
+
lines.append(f"- {_scalar(effect.descricao)}")
|
|
1483
|
+
if not finding.encaminhamentos:
|
|
1484
|
+
lines.append("encaminhamentos: []")
|
|
1485
|
+
else:
|
|
1486
|
+
lines.append("encaminhamentos:")
|
|
1487
|
+
for situation in finding.encaminhamentos:
|
|
1488
|
+
lines.append(f"- {situation.id}:")
|
|
1489
|
+
if not situation.propostas:
|
|
1490
|
+
lines.append(" propostas: []")
|
|
1491
|
+
continue
|
|
1492
|
+
lines.append(" propostas:")
|
|
1493
|
+
for proposal in situation.propostas:
|
|
1494
|
+
lines.append(f" - id: {_scalar(proposal.id)}")
|
|
1495
|
+
if proposal.publico:
|
|
1496
|
+
lines.extend(_emit_value("publico", proposal.publico, indent=6))
|
|
1497
|
+
if proposal.id_variante:
|
|
1498
|
+
lines.extend(_emit_value("id_variante", proposal.id_variante, indent=6))
|
|
1499
|
+
lines.extend(_emit_value("tipo_encaminhamento", proposal.tipo_encaminhamento, indent=6))
|
|
1500
|
+
if proposal.criterios:
|
|
1501
|
+
references = [
|
|
1502
|
+
_criterion_reference(identifier, finding=finding)
|
|
1503
|
+
for identifier in proposal.criterios
|
|
1504
|
+
]
|
|
1505
|
+
lines.extend(_emit_token_list("criterios", references, indent=6))
|
|
1506
|
+
if proposal.fundamentacao_encaminhamento:
|
|
1507
|
+
lines.extend(
|
|
1508
|
+
_emit_value(
|
|
1509
|
+
"fundamentacao_encaminhamento",
|
|
1510
|
+
proposal.fundamentacao_encaminhamento,
|
|
1511
|
+
indent=6,
|
|
1512
|
+
)
|
|
1513
|
+
)
|
|
1514
|
+
lines.extend(_block_scalar("encaminhamento", proposal.encaminhamento, indent=6))
|
|
1515
|
+
lines.append("")
|
|
1516
|
+
return "\n".join(lines)
|
|
1517
|
+
|
|
1518
|
+
|
|
1519
|
+
def normalize_project_metadata(project: Mapping[str, Any] | None) -> dict[str, Any]:
|
|
1520
|
+
"""Aceita metadados planos (``numero``/``titulo``) ou aninhados em ``fiscalizacao``."""
|
|
1521
|
+
if not project:
|
|
1522
|
+
return {}
|
|
1523
|
+
normalized = dict(project)
|
|
1524
|
+
nested = project.get("fiscalizacao")
|
|
1525
|
+
if isinstance(nested, Mapping):
|
|
1526
|
+
for key, value in nested.items():
|
|
1527
|
+
normalized.setdefault(key, value)
|
|
1528
|
+
return normalized
|
|
1529
|
+
|
|
1530
|
+
|
|
1531
|
+
# --------------------------------------------------------------------------------------
|
|
1532
|
+
# JSON de auditoria: carga, normalização em memória e enriquecimento
|
|
1533
|
+
# --------------------------------------------------------------------------------------
|
|
1534
|
+
|
|
1535
|
+
|
|
1536
|
+
@dataclass(frozen=True)
|
|
1537
|
+
class EffectiveDecision:
|
|
1538
|
+
"""Decisão efetiva emitida pelo resultado de auditoria para um par."""
|
|
1539
|
+
|
|
1540
|
+
tipo: str | None
|
|
1541
|
+
encaminhamento: str
|
|
1542
|
+
fundamentacao: str
|
|
1543
|
+
criterios: tuple[str, ...]
|
|
1544
|
+
publico: str | None = None
|
|
1545
|
+
id_variante: str | None = None
|
|
1546
|
+
variant_resolved: bool = False
|
|
1547
|
+
ids_acoes: tuple[str, ...] = ()
|
|
1548
|
+
|
|
1549
|
+
|
|
1550
|
+
@dataclass(frozen=True)
|
|
1551
|
+
class EffectiveOccurrence:
|
|
1552
|
+
"""Ocorrência transitória ``(auditado, achado, situação)`` derivada do JSON."""
|
|
1553
|
+
|
|
1554
|
+
auditado: str
|
|
1555
|
+
nome: str | None
|
|
1556
|
+
achado: str
|
|
1557
|
+
situacao: str
|
|
1558
|
+
criterios: tuple[str, ...]
|
|
1559
|
+
decisions: tuple[EffectiveDecision, ...]
|
|
1560
|
+
publico: str | None = None
|
|
1561
|
+
id_variante: str | None = None
|
|
1562
|
+
tipo_encaminhamento: str | None = None
|
|
1563
|
+
propostas: tuple[str, ...] = ()
|
|
1564
|
+
ids_acoes: tuple[str, ...] = ()
|
|
1565
|
+
ids_procedimentos: tuple[str, ...] = ()
|
|
1566
|
+
evidencias: tuple[Mapping[str, Any], ...] = ()
|
|
1567
|
+
itens: tuple[str, ...] = ()
|
|
1568
|
+
|
|
1569
|
+
|
|
1570
|
+
@dataclass(frozen=True)
|
|
1571
|
+
class FindingsEnrichment:
|
|
1572
|
+
"""Camada factual opcional, derivada exclusivamente do JSON informado."""
|
|
1573
|
+
|
|
1574
|
+
cenario: str
|
|
1575
|
+
resultado_sha256: str
|
|
1576
|
+
cobertura: Mapping[str, Any]
|
|
1577
|
+
occurrences: tuple[EffectiveOccurrence, ...]
|
|
1578
|
+
quantidade_por_situacao: Mapping[tuple[str, str], int]
|
|
1579
|
+
quantidade_por_achado: Mapping[str, int]
|
|
1580
|
+
auditados_por_situacao: Mapping[tuple[str, str], tuple[str, ...]]
|
|
1581
|
+
auditados_por_proposta: Mapping[tuple[str, str, str], tuple[str, ...]]
|
|
1582
|
+
auditados: tuple[str, ...]
|
|
1583
|
+
com_achados: int
|
|
1584
|
+
proveniencia: str = "conferida"
|
|
1585
|
+
warnings: tuple[str, ...] = ()
|
|
1586
|
+
|
|
1587
|
+
def situacao_occurrences(self, achado: str, situacao: str) -> tuple[EffectiveOccurrence, ...]:
|
|
1588
|
+
return tuple(
|
|
1589
|
+
item for item in self.occurrences if item.achado == achado and item.situacao == situacao
|
|
1590
|
+
)
|
|
1591
|
+
|
|
1592
|
+
def achado_occurrences(self, achado: str) -> tuple[EffectiveOccurrence, ...]:
|
|
1593
|
+
return tuple(item for item in self.occurrences if item.achado == achado)
|
|
1594
|
+
|
|
1595
|
+
|
|
1596
|
+
def _normalize_label(value: Any) -> str:
|
|
1597
|
+
return " ".join(str(value or "").split()).casefold()
|
|
1598
|
+
|
|
1599
|
+
|
|
1600
|
+
def _canonical_criteria(raw: Any, *, path: str) -> tuple[str, ...]:
|
|
1601
|
+
if raw is None:
|
|
1602
|
+
return ()
|
|
1603
|
+
if not isinstance(raw, list):
|
|
1604
|
+
raise _error(path, "critérios do resultado devem ser uma lista")
|
|
1605
|
+
result: list[str] = []
|
|
1606
|
+
for index, item in enumerate(raw):
|
|
1607
|
+
if isinstance(item, str):
|
|
1608
|
+
token = item.strip()
|
|
1609
|
+
elif isinstance(item, Mapping):
|
|
1610
|
+
token = str(item.get("id") or item.get("id_local") or "").strip()
|
|
1611
|
+
question = str(item.get("id_questao") or "").strip()
|
|
1612
|
+
if token and "." not in token and question:
|
|
1613
|
+
token = f"{question}.{token}"
|
|
1614
|
+
else:
|
|
1615
|
+
raise _error(f"{path}[{index}]", "critério do resultado deve ser texto ou mapeamento")
|
|
1616
|
+
if not token:
|
|
1617
|
+
raise _error(f"{path}[{index}]", "critério do resultado sem identificador")
|
|
1618
|
+
result.append(token.upper())
|
|
1619
|
+
return tuple(dict.fromkeys(result))
|
|
1620
|
+
|
|
1621
|
+
|
|
1622
|
+
def _finding_identifier(procedure: Mapping[str, Any], *, auditado: str) -> str:
|
|
1623
|
+
detail = procedure.get("achado")
|
|
1624
|
+
nested = detail if isinstance(detail, Mapping) else {}
|
|
1625
|
+
value = (
|
|
1626
|
+
procedure.get("numero_achado")
|
|
1627
|
+
or nested.get("numero")
|
|
1628
|
+
or nested.get("id_achado")
|
|
1629
|
+
or procedure.get("id_achado")
|
|
1630
|
+
)
|
|
1631
|
+
text = str(value or "").strip().upper()
|
|
1632
|
+
if not text:
|
|
1633
|
+
raise _error(
|
|
1634
|
+
f"resultado.auditados.{auditado}.procedimentos_executados",
|
|
1635
|
+
"procedimento com achado ocorrido sem identificação do achado (numero_achado/id_achado)",
|
|
1636
|
+
)
|
|
1637
|
+
match = re.fullmatch(r"A?(\d+)", text)
|
|
1638
|
+
if match is None:
|
|
1639
|
+
raise _error(
|
|
1640
|
+
f"resultado.auditados.{auditado}.procedimentos_executados",
|
|
1641
|
+
f"identificação de achado inválida: {text!r}",
|
|
1642
|
+
)
|
|
1643
|
+
return f"A{int(match.group(1))}"
|
|
1644
|
+
|
|
1645
|
+
|
|
1646
|
+
def _procedure_situations(procedure: Mapping[str, Any], *, auditado: str) -> list[Mapping[str, Any]]:
|
|
1647
|
+
raw = procedure.get("situacoes_detalhadas") or []
|
|
1648
|
+
nested = procedure.get("achado")
|
|
1649
|
+
if not raw and isinstance(nested, Mapping):
|
|
1650
|
+
raw = nested.get("situacoes_detalhadas") or []
|
|
1651
|
+
if not isinstance(raw, list) or not raw:
|
|
1652
|
+
raise _error(
|
|
1653
|
+
f"resultado.auditados.{auditado}.procedimentos_executados",
|
|
1654
|
+
"achado ocorrido sem situações detalhadas",
|
|
1655
|
+
)
|
|
1656
|
+
situations: list[Mapping[str, Any]] = []
|
|
1657
|
+
for index, item in enumerate(raw):
|
|
1658
|
+
if not isinstance(item, Mapping):
|
|
1659
|
+
raise _error(
|
|
1660
|
+
f"resultado.auditados.{auditado}.situacoes_detalhadas[{index}]",
|
|
1661
|
+
"situação detalhada deve ser um objeto",
|
|
1662
|
+
)
|
|
1663
|
+
situation_id = str(item.get("id_situacao") or item.get("id") or "").strip()
|
|
1664
|
+
if SITUATION_ID.fullmatch(situation_id) is None:
|
|
1665
|
+
raise _error(
|
|
1666
|
+
f"resultado.auditados.{auditado}.situacoes_detalhadas[{index}]",
|
|
1667
|
+
f"ID de situação inválido: {situation_id!r}",
|
|
1668
|
+
)
|
|
1669
|
+
if item.get("ativa") is False:
|
|
1670
|
+
continue
|
|
1671
|
+
situations.append(item)
|
|
1672
|
+
return situations
|
|
1673
|
+
|
|
1674
|
+
|
|
1675
|
+
def _decision_from(entry: Mapping[str, Any], *, situation: Mapping[str, Any]) -> EffectiveDecision:
|
|
1676
|
+
tipo = entry.get("tipo") or entry.get("tipo_encaminhamento") or situation.get("tipo_encaminhamento")
|
|
1677
|
+
encaminhamento = str(
|
|
1678
|
+
entry.get("encaminhamento") or entry.get("texto") or situation.get("encaminhamento") or ""
|
|
1679
|
+
).strip()
|
|
1680
|
+
fundamentacao = str(
|
|
1681
|
+
entry.get("fundamentacao_encaminhamento")
|
|
1682
|
+
or entry.get("fundamentacao")
|
|
1683
|
+
or situation.get("fundamentacao_encaminhamento")
|
|
1684
|
+
or ""
|
|
1685
|
+
).strip()
|
|
1686
|
+
criteria = _canonical_criteria(
|
|
1687
|
+
entry.get("criterios") if entry.get("criterios") is not None else situation.get("criterios"),
|
|
1688
|
+
path="resultado.decisao.criterios",
|
|
1689
|
+
)
|
|
1690
|
+
actions = entry.get("id_acoes") if entry.get("id_acoes") is not None else situation.get("id_acoes")
|
|
1691
|
+
variant_source = entry if "id_variante" in entry else situation
|
|
1692
|
+
variant_value = variant_source.get("id_variante")
|
|
1693
|
+
return EffectiveDecision(
|
|
1694
|
+
tipo=str(tipo).strip() if tipo not in (None, "") else None,
|
|
1695
|
+
encaminhamento=encaminhamento,
|
|
1696
|
+
fundamentacao=fundamentacao,
|
|
1697
|
+
criterios=criteria,
|
|
1698
|
+
publico=(
|
|
1699
|
+
str(entry.get("publico")).strip()
|
|
1700
|
+
if entry.get("publico") not in (None, "")
|
|
1701
|
+
else (str(situation.get("publico")).strip() if situation.get("publico") not in (None, "") else None)
|
|
1702
|
+
),
|
|
1703
|
+
id_variante=str(variant_value).strip() if variant_value not in (None, "") else None,
|
|
1704
|
+
variant_resolved="id_variante" in entry or "id_variante" in situation,
|
|
1705
|
+
ids_acoes=_text_list(actions, path="resultado.decisao.id_acoes") if actions else (),
|
|
1706
|
+
)
|
|
1707
|
+
|
|
1708
|
+
|
|
1709
|
+
def _situation_decisions(procedure: Mapping[str, Any], situation: Mapping[str, Any], *, auditado: str) -> list[EffectiveDecision]:
|
|
1710
|
+
situation_id = str(situation.get("id_situacao") or situation.get("id") or "").strip()
|
|
1711
|
+
entries = procedure.get("encaminhamentos") or []
|
|
1712
|
+
if not isinstance(entries, list):
|
|
1713
|
+
raise _error(f"resultado.auditados.{auditado}.encaminhamentos", "deve ser uma lista")
|
|
1714
|
+
matched = [
|
|
1715
|
+
entry
|
|
1716
|
+
for entry in entries
|
|
1717
|
+
if isinstance(entry, Mapping)
|
|
1718
|
+
and str(entry.get("id_situacao") or "").strip() in ("", situation_id)
|
|
1719
|
+
]
|
|
1720
|
+
decisions: list[EffectiveDecision] = []
|
|
1721
|
+
for entry in matched:
|
|
1722
|
+
decisions.append(_decision_from(entry, situation=situation))
|
|
1723
|
+
if not decisions:
|
|
1724
|
+
decisions.append(_decision_from({}, situation=situation))
|
|
1725
|
+
unique: list[EffectiveDecision] = []
|
|
1726
|
+
seen: set[tuple[Any, ...]] = set()
|
|
1727
|
+
for decision in decisions:
|
|
1728
|
+
key = (
|
|
1729
|
+
_normalize_label(decision.tipo),
|
|
1730
|
+
decision.encaminhamento,
|
|
1731
|
+
decision.fundamentacao,
|
|
1732
|
+
decision.criterios,
|
|
1733
|
+
_normalize_label(decision.publico),
|
|
1734
|
+
decision.id_variante,
|
|
1735
|
+
decision.variant_resolved,
|
|
1736
|
+
)
|
|
1737
|
+
if key in seen:
|
|
1738
|
+
continue
|
|
1739
|
+
seen.add(key)
|
|
1740
|
+
unique.append(decision)
|
|
1741
|
+
return unique
|
|
1742
|
+
|
|
1743
|
+
|
|
1744
|
+
@dataclass
|
|
1745
|
+
class _OccurrenceBuilder:
|
|
1746
|
+
auditado: str
|
|
1747
|
+
nome: str | None
|
|
1748
|
+
achado: str
|
|
1749
|
+
situacao: str
|
|
1750
|
+
criterios: set[str] = dataclass_field(default_factory=set)
|
|
1751
|
+
decisions: list[EffectiveDecision] = dataclass_field(default_factory=list)
|
|
1752
|
+
publico: str | None = None
|
|
1753
|
+
id_variante: str | None = None
|
|
1754
|
+
tipo_encaminhamento: str | None = None
|
|
1755
|
+
ids_acoes: set[str] = dataclass_field(default_factory=set)
|
|
1756
|
+
ids_procedimentos: set[str] = dataclass_field(default_factory=set)
|
|
1757
|
+
evidencias: list[Mapping[str, Any]] = dataclass_field(default_factory=list)
|
|
1758
|
+
itens: set[str] = dataclass_field(default_factory=set)
|
|
1759
|
+
|
|
1760
|
+
|
|
1761
|
+
def _collect_occurrences(rows: Mapping[str, Mapping[str, Any]]) -> tuple[EffectiveOccurrence, ...]:
|
|
1762
|
+
builders: dict[tuple[str, str, str], _OccurrenceBuilder] = {}
|
|
1763
|
+
for signature, row in rows.items():
|
|
1764
|
+
auditado = str(row.get("sigla") or row.get("auditado") or signature).strip().upper()
|
|
1765
|
+
if not auditado:
|
|
1766
|
+
raise _error(f"resultado.auditados.{signature}", "auditado sem sigla")
|
|
1767
|
+
evaluated = row.get("foi_auditado") is True
|
|
1768
|
+
procedures = row.get("procedimentos_executados") or []
|
|
1769
|
+
if not isinstance(procedures, list):
|
|
1770
|
+
raise _error(f"resultado.auditados.{auditado}.procedimentos_executados", "deve ser uma lista")
|
|
1771
|
+
for procedure in procedures:
|
|
1772
|
+
if not isinstance(procedure, Mapping):
|
|
1773
|
+
raise _error(f"resultado.auditados.{auditado}.procedimentos_executados", "procedimento deve ser um objeto")
|
|
1774
|
+
occurred = procedure.get("achado_ocorreu")
|
|
1775
|
+
if occurred is None:
|
|
1776
|
+
nested = procedure.get("achado")
|
|
1777
|
+
occurred = bool(
|
|
1778
|
+
procedure.get("situacoes_detalhadas")
|
|
1779
|
+
or (isinstance(nested, Mapping) and nested.get("situacoes_detalhadas"))
|
|
1780
|
+
or procedure.get("situacoes_inconformes")
|
|
1781
|
+
or procedure.get("situacoes_encontradas")
|
|
1782
|
+
)
|
|
1783
|
+
if not occurred:
|
|
1784
|
+
continue
|
|
1785
|
+
if procedure.get("executado") is False:
|
|
1786
|
+
raise _error(
|
|
1787
|
+
f"resultado.auditados.{auditado}.procedimentos_executados",
|
|
1788
|
+
"procedimento não executado não pode confirmar achado",
|
|
1789
|
+
)
|
|
1790
|
+
if not evaluated:
|
|
1791
|
+
raise _error(
|
|
1792
|
+
f"resultado.auditados.{auditado}",
|
|
1793
|
+
"auditado não avaliado não pode confirmar achado",
|
|
1794
|
+
)
|
|
1795
|
+
achado = _finding_identifier(procedure, auditado=auditado)
|
|
1796
|
+
procedure_id = str(procedure.get("id") or procedure.get("id_procedimento") or "").strip()
|
|
1797
|
+
for situation in _procedure_situations(procedure, auditado=auditado):
|
|
1798
|
+
situation_id = str(situation.get("id_situacao") or situation.get("id") or "").strip()
|
|
1799
|
+
key = (auditado, achado, situation_id)
|
|
1800
|
+
builder = builders.get(key)
|
|
1801
|
+
if builder is None:
|
|
1802
|
+
builder = _OccurrenceBuilder(
|
|
1803
|
+
auditado=auditado,
|
|
1804
|
+
nome=str(row.get("nome") or "").strip() or None,
|
|
1805
|
+
achado=achado,
|
|
1806
|
+
situacao=situation_id,
|
|
1807
|
+
)
|
|
1808
|
+
builders[key] = builder
|
|
1809
|
+
criteria = _canonical_criteria(situation.get("criterios"), path="resultado.criterios")
|
|
1810
|
+
builder.criterios.update(criteria)
|
|
1811
|
+
publico = str(situation.get("publico") or "").strip() or None
|
|
1812
|
+
variante = str(situation.get("id_variante") or "").strip() or None
|
|
1813
|
+
if builder.publico is None:
|
|
1814
|
+
builder.publico = publico
|
|
1815
|
+
elif publico and _normalize_label(publico) != _normalize_label(builder.publico):
|
|
1816
|
+
raise _error(
|
|
1817
|
+
f"resultado.auditados.{auditado}.{situation_id}",
|
|
1818
|
+
f"público divergente entre procedimentos do mesmo par: {builder.publico!r} e {publico!r}",
|
|
1819
|
+
)
|
|
1820
|
+
if builder.id_variante is None:
|
|
1821
|
+
builder.id_variante = variante
|
|
1822
|
+
elif variante and variante != builder.id_variante:
|
|
1823
|
+
raise _error(
|
|
1824
|
+
f"resultado.auditados.{auditado}.{situation_id}",
|
|
1825
|
+
f"variante divergente entre procedimentos do mesmo par: {builder.id_variante!r} e {variante!r}",
|
|
1826
|
+
)
|
|
1827
|
+
if builder.tipo_encaminhamento is None:
|
|
1828
|
+
tipo = situation.get("tipo_encaminhamento")
|
|
1829
|
+
builder.tipo_encaminhamento = str(tipo).strip() if tipo not in (None, "") else None
|
|
1830
|
+
decisions = _situation_decisions(procedure, situation, auditado=auditado)
|
|
1831
|
+
for decision in decisions:
|
|
1832
|
+
builder.decisions.append(decision)
|
|
1833
|
+
builder.criterios.update(decision.criterios)
|
|
1834
|
+
builder.ids_acoes.update(decision.ids_acoes)
|
|
1835
|
+
actions = situation.get("id_acoes")
|
|
1836
|
+
if actions:
|
|
1837
|
+
builder.ids_acoes.update(_text_list(actions, path="resultado.id_acoes"))
|
|
1838
|
+
if procedure_id:
|
|
1839
|
+
builder.ids_procedimentos.add(procedure_id)
|
|
1840
|
+
for motivo in situation.get("motivos") or []:
|
|
1841
|
+
if isinstance(motivo, Mapping) and str(motivo.get("descricao") or "").strip():
|
|
1842
|
+
builder.itens.add(str(motivo["descricao"]).strip())
|
|
1843
|
+
evidence = procedure.get("evidencias_detalhadas")
|
|
1844
|
+
nested_evidence = (procedure.get("achado") or {}).get("evidencias_detalhadas") if isinstance(procedure.get("achado"), Mapping) else None
|
|
1845
|
+
for collection in (evidence, nested_evidence):
|
|
1846
|
+
if isinstance(collection, list):
|
|
1847
|
+
for item in collection:
|
|
1848
|
+
if not isinstance(item, Mapping):
|
|
1849
|
+
continue
|
|
1850
|
+
builder.evidencias.append(item)
|
|
1851
|
+
for detail in item.get("itens") or []:
|
|
1852
|
+
if str(detail).strip():
|
|
1853
|
+
builder.itens.add(str(detail).strip())
|
|
1854
|
+
occurrences: list[EffectiveOccurrence] = []
|
|
1855
|
+
for key in sorted(builders, key=lambda item: (item[0], int(item[1][1:]), item[2])):
|
|
1856
|
+
builder = builders[key]
|
|
1857
|
+
unique_decisions: list[EffectiveDecision] = []
|
|
1858
|
+
seen: set[tuple[Any, ...]] = set()
|
|
1859
|
+
for decision in builder.decisions:
|
|
1860
|
+
fingerprint = (
|
|
1861
|
+
_normalize_label(decision.tipo),
|
|
1862
|
+
decision.encaminhamento,
|
|
1863
|
+
decision.fundamentacao,
|
|
1864
|
+
decision.criterios,
|
|
1865
|
+
_normalize_label(decision.publico),
|
|
1866
|
+
decision.id_variante,
|
|
1867
|
+
decision.variant_resolved,
|
|
1868
|
+
)
|
|
1869
|
+
if fingerprint in seen:
|
|
1870
|
+
continue
|
|
1871
|
+
seen.add(fingerprint)
|
|
1872
|
+
unique_decisions.append(decision)
|
|
1873
|
+
occurrences.append(
|
|
1874
|
+
EffectiveOccurrence(
|
|
1875
|
+
auditado=builder.auditado,
|
|
1876
|
+
nome=builder.nome,
|
|
1877
|
+
achado=builder.achado,
|
|
1878
|
+
situacao=builder.situacao,
|
|
1879
|
+
criterios=tuple(sorted(builder.criterios)),
|
|
1880
|
+
decisions=tuple(unique_decisions),
|
|
1881
|
+
publico=builder.publico or next(
|
|
1882
|
+
(decision.publico for decision in unique_decisions if decision.publico),
|
|
1883
|
+
None,
|
|
1884
|
+
),
|
|
1885
|
+
id_variante=builder.id_variante or next(
|
|
1886
|
+
(decision.id_variante for decision in unique_decisions if decision.id_variante),
|
|
1887
|
+
None,
|
|
1888
|
+
),
|
|
1889
|
+
tipo_encaminhamento=builder.tipo_encaminhamento,
|
|
1890
|
+
ids_acoes=tuple(sorted(builder.ids_acoes)),
|
|
1891
|
+
ids_procedimentos=tuple(sorted(builder.ids_procedimentos)),
|
|
1892
|
+
evidencias=tuple(builder.evidencias),
|
|
1893
|
+
itens=tuple(sorted(builder.itens)),
|
|
1894
|
+
)
|
|
1895
|
+
)
|
|
1896
|
+
return tuple(occurrences)
|
|
1897
|
+
|
|
1898
|
+
|
|
1899
|
+
def _coverage(payload: Mapping[str, Any]) -> dict[str, Any]:
|
|
1900
|
+
raw = payload.get("cobertura")
|
|
1901
|
+
if not isinstance(raw, Mapping):
|
|
1902
|
+
raise _error("resultado.cobertura", "o resultado exige o bloco cobertura")
|
|
1903
|
+
values: dict[str, Any] = {}
|
|
1904
|
+
for key in ("total", "avaliados", "com_achados", "respondentes"):
|
|
1905
|
+
if key not in raw:
|
|
1906
|
+
if key == "respondentes":
|
|
1907
|
+
values[key] = None
|
|
1908
|
+
continue
|
|
1909
|
+
raise _error(f"resultado.cobertura.{key}", "campo obrigatório ausente")
|
|
1910
|
+
value = raw[key]
|
|
1911
|
+
if value is None and key == "respondentes":
|
|
1912
|
+
values[key] = None
|
|
1913
|
+
continue
|
|
1914
|
+
if type(value) is not int or value < 0:
|
|
1915
|
+
raise _error(f"resultado.cobertura.{key}", "deve ser inteiro não negativo")
|
|
1916
|
+
values[key] = value
|
|
1917
|
+
if values["com_achados"] > values["avaliados"] or values["avaliados"] > values["total"]:
|
|
1918
|
+
raise _error("resultado.cobertura", "exige com_achados <= avaliados <= total")
|
|
1919
|
+
if values["respondentes"] is not None and values["respondentes"] > values["total"]:
|
|
1920
|
+
raise _error("resultado.cobertura.respondentes", "não pode exceder total")
|
|
1921
|
+
return values
|
|
1922
|
+
|
|
1923
|
+
|
|
1924
|
+
def _matrix_context(payload: Mapping[str, Any]) -> dict[str, list[Mapping[str, Any]]]:
|
|
1925
|
+
raw = payload.get("contexto_matriz")
|
|
1926
|
+
context: dict[str, list[Mapping[str, Any]]] = {"questoes": [], "achados": [], "situacoes": [], "criterios": [], "fontes": []}
|
|
1927
|
+
if raw is None:
|
|
1928
|
+
return context
|
|
1929
|
+
if not isinstance(raw, Mapping):
|
|
1930
|
+
raise _error("resultado.contexto_matriz", "deve ser um objeto")
|
|
1931
|
+
for key in context:
|
|
1932
|
+
values = raw.get(key) or []
|
|
1933
|
+
if not isinstance(values, list):
|
|
1934
|
+
raise _error(f"resultado.contexto_matriz.{key}", "deve ser uma lista")
|
|
1935
|
+
context[key] = [item for item in values if isinstance(item, Mapping)]
|
|
1936
|
+
return context
|
|
1937
|
+
|
|
1938
|
+
|
|
1939
|
+
def validate_audit_payload(payload: Any) -> dict[str, Any]:
|
|
1940
|
+
"""Valida o envelope ``argos.audit-result/v1`` ou ``/v2`` sem cruzar com o Markdown."""
|
|
1941
|
+
from .audit_result import FORMATOS, expandir
|
|
1942
|
+
|
|
1943
|
+
if not isinstance(payload, Mapping):
|
|
1944
|
+
raise _error("resultado", "o resultado de auditoria deve ser um objeto JSON")
|
|
1945
|
+
schema = str(payload.get("schema_version") or "").strip()
|
|
1946
|
+
if schema not in FORMATOS:
|
|
1947
|
+
raise _error(
|
|
1948
|
+
"resultado.schema_version",
|
|
1949
|
+
f"esperado {' ou '.join(repr(item) for item in FORMATOS)}, encontrado {schema or 'ausente'!r}",
|
|
1950
|
+
)
|
|
1951
|
+
try:
|
|
1952
|
+
payload = expandir(payload)
|
|
1953
|
+
except (ValueError, KeyError) as exc:
|
|
1954
|
+
raise _error("resultado", f"resultado v2 inválido: {exc}") from exc
|
|
1955
|
+
cenario = str(payload.get("cenario") or "").strip()
|
|
1956
|
+
if not cenario:
|
|
1957
|
+
raise _error("resultado.cenario", "o resultado exige o cenário de execução")
|
|
1958
|
+
rows = audit_rows_from_result(payload)
|
|
1959
|
+
coverage = _coverage(payload)
|
|
1960
|
+
context = _matrix_context(payload)
|
|
1961
|
+
return {
|
|
1962
|
+
"cenario": cenario,
|
|
1963
|
+
"rows": dict(rows),
|
|
1964
|
+
"cobertura": coverage,
|
|
1965
|
+
"contexto": context,
|
|
1966
|
+
"payload": payload,
|
|
1967
|
+
}
|
|
1968
|
+
|
|
1969
|
+
|
|
1970
|
+
def load_audit_result(path: Path) -> tuple[dict[str, Any], str]:
|
|
1971
|
+
"""Lê o JSON informado e devolve o conteúdo e o SHA-256 dos bytes."""
|
|
1972
|
+
try:
|
|
1973
|
+
data = Path(path).read_bytes()
|
|
1974
|
+
except OSError as exc:
|
|
1975
|
+
raise InputValidationError(
|
|
1976
|
+
f"resultado de auditoria informado em --resultado-auditoria ausente ou ilegível: {path}"
|
|
1977
|
+
) from exc
|
|
1978
|
+
try:
|
|
1979
|
+
payload = json.loads(data.decode("utf-8"))
|
|
1980
|
+
except (UnicodeError, json.JSONDecodeError) as exc:
|
|
1981
|
+
raise InputValidationError(f"resultado de auditoria contém JSON inválido: {path}") from exc
|
|
1982
|
+
return payload, sha256_bytes(data)
|
|
1983
|
+
|
|
1984
|
+
|
|
1985
|
+
def _proposal_matches(decision: EffectiveDecision, proposals: Sequence[ReferralProposal]) -> list[ReferralProposal]:
|
|
1986
|
+
pool = list(proposals)
|
|
1987
|
+
if decision.variant_resolved:
|
|
1988
|
+
if decision.id_variante:
|
|
1989
|
+
pool = [
|
|
1990
|
+
proposal
|
|
1991
|
+
for proposal in pool
|
|
1992
|
+
if proposal.id_variante
|
|
1993
|
+
and _normalize_label(proposal.id_variante) == _normalize_label(decision.id_variante)
|
|
1994
|
+
]
|
|
1995
|
+
else:
|
|
1996
|
+
pool = [proposal for proposal in pool if proposal.id_variante is None]
|
|
1997
|
+
if decision.tipo:
|
|
1998
|
+
pool = [
|
|
1999
|
+
proposal
|
|
2000
|
+
for proposal in pool
|
|
2001
|
+
if _normalize_label(proposal.tipo_encaminhamento) == _normalize_label(decision.tipo)
|
|
2002
|
+
]
|
|
2003
|
+
if decision.publico:
|
|
2004
|
+
pool = [
|
|
2005
|
+
proposal
|
|
2006
|
+
for proposal in pool
|
|
2007
|
+
if proposal.publico and _normalize_label(proposal.publico) == _normalize_label(decision.publico)
|
|
2008
|
+
]
|
|
2009
|
+
if decision.criterios:
|
|
2010
|
+
pool = [
|
|
2011
|
+
proposal
|
|
2012
|
+
for proposal in pool
|
|
2013
|
+
if frozenset(proposal.criterios) == frozenset(decision.criterios)
|
|
2014
|
+
]
|
|
2015
|
+
return pool
|
|
2016
|
+
|
|
2017
|
+
|
|
2018
|
+
def _associate_occurrence(
|
|
2019
|
+
occurrence: EffectiveOccurrence,
|
|
2020
|
+
proposals: Sequence[ReferralProposal],
|
|
2021
|
+
) -> tuple[ReferralProposal, ...]:
|
|
2022
|
+
"""Associa, de forma determinística, cada decisão efetiva a uma proposta editorial."""
|
|
2023
|
+
location = f"auditado {occurrence.auditado}, achado {occurrence.achado}, situação {occurrence.situacao}"
|
|
2024
|
+
if not proposals:
|
|
2025
|
+
raise _error(location, "o resultado confirma a situação, mas o Markdown não declara propostas de encaminhamento")
|
|
2026
|
+
matched: list[ReferralProposal] = []
|
|
2027
|
+
for decision in occurrence.decisions:
|
|
2028
|
+
candidates = _proposal_matches(decision, proposals)
|
|
2029
|
+
if len(candidates) == 1:
|
|
2030
|
+
matched.append(candidates[0])
|
|
2031
|
+
continue
|
|
2032
|
+
if not candidates:
|
|
2033
|
+
raise _error(
|
|
2034
|
+
location,
|
|
2035
|
+
"decisão efetiva do resultado sem proposta editorial correspondente "
|
|
2036
|
+
f"(tipo={decision.tipo!r}, público={decision.publico!r}, variante={decision.id_variante!r}, "
|
|
2037
|
+
f"critérios={list(decision.criterios)}); propostas: {[proposal.id for proposal in proposals]}",
|
|
2038
|
+
)
|
|
2039
|
+
raise _error(
|
|
2040
|
+
location,
|
|
2041
|
+
"associação ambígua entre decisão efetiva e propostas editoriais; candidatas: "
|
|
2042
|
+
f"{[proposal.id for proposal in candidates]} (tipo={decision.tipo!r}, público={decision.publico!r}, "
|
|
2043
|
+
f"variante={decision.id_variante!r})",
|
|
2044
|
+
)
|
|
2045
|
+
seen: dict[str, EffectiveDecision] = {}
|
|
2046
|
+
for decision, proposal in zip(occurrence.decisions, matched):
|
|
2047
|
+
previous = seen.get(proposal.id)
|
|
2048
|
+
if previous is None:
|
|
2049
|
+
seen[proposal.id] = decision
|
|
2050
|
+
continue
|
|
2051
|
+
same = (
|
|
2052
|
+
_normalize_label(previous.tipo) == _normalize_label(decision.tipo)
|
|
2053
|
+
and previous.encaminhamento == decision.encaminhamento
|
|
2054
|
+
and previous.fundamentacao == decision.fundamentacao
|
|
2055
|
+
and previous.criterios == decision.criterios
|
|
2056
|
+
and _normalize_label(previous.publico) == _normalize_label(decision.publico)
|
|
2057
|
+
and previous.id_variante == decision.id_variante
|
|
2058
|
+
and previous.variant_resolved == decision.variant_resolved
|
|
2059
|
+
)
|
|
2060
|
+
if not same:
|
|
2061
|
+
raise _error(
|
|
2062
|
+
location,
|
|
2063
|
+
f"duas decisões distintas do resultado foram associadas à mesma proposta {proposal.id}; "
|
|
2064
|
+
"distinga as propostas por público, variante ou critérios",
|
|
2065
|
+
)
|
|
2066
|
+
return tuple(matched)
|
|
2067
|
+
|
|
2068
|
+
|
|
2069
|
+
def _context_question_map(context: Mapping[str, list[Mapping[str, Any]]]) -> dict[str, str]:
|
|
2070
|
+
mapping: dict[str, str] = {}
|
|
2071
|
+
for item in context.get("achados", []):
|
|
2072
|
+
identifier = str(item.get("id") or "").strip().upper()
|
|
2073
|
+
question = str(item.get("id_questao") or "").strip()
|
|
2074
|
+
if identifier and question:
|
|
2075
|
+
mapping[identifier] = question
|
|
2076
|
+
return mapping
|
|
2077
|
+
|
|
2078
|
+
|
|
2079
|
+
def _context_situation_map(context: Mapping[str, list[Mapping[str, Any]]]) -> dict[str, str]:
|
|
2080
|
+
mapping: dict[str, str] = {}
|
|
2081
|
+
for item in context.get("situacoes", []):
|
|
2082
|
+
identifier = str(item.get("id") or "").strip()
|
|
2083
|
+
finding_id = str(item.get("id_achado") or "").strip().upper()
|
|
2084
|
+
if identifier and finding_id:
|
|
2085
|
+
mapping[identifier] = finding_id
|
|
2086
|
+
return mapping
|
|
2087
|
+
|
|
2088
|
+
|
|
2089
|
+
def _validate_cross_references(
|
|
2090
|
+
document: FindingsDocument,
|
|
2091
|
+
occurrences: Sequence[EffectiveOccurrence],
|
|
2092
|
+
context: Mapping[str, list[Mapping[str, Any]]],
|
|
2093
|
+
) -> None:
|
|
2094
|
+
"""Confere IDs, situações, critérios e questões entre o Markdown e o JSON."""
|
|
2095
|
+
question_map = _context_question_map(context)
|
|
2096
|
+
situation_map = _context_situation_map(context)
|
|
2097
|
+
for finding in document.achados:
|
|
2098
|
+
expected = question_map.get(finding.id)
|
|
2099
|
+
if expected and finding.questao:
|
|
2100
|
+
declared = question_identifier(finding.questao)
|
|
2101
|
+
if declared and declared != expected:
|
|
2102
|
+
raise _error(
|
|
2103
|
+
f"achado {finding.id}",
|
|
2104
|
+
f"o Markdown vincula o achado à questão {declared}, mas o resultado registra {expected}",
|
|
2105
|
+
)
|
|
2106
|
+
for situation in finding.evidencias:
|
|
2107
|
+
owner = situation_map.get(situation.id)
|
|
2108
|
+
if owner and owner != finding.id:
|
|
2109
|
+
raise _error(
|
|
2110
|
+
f"achado {finding.id}",
|
|
2111
|
+
f"a situação {situation.id} pertence ao achado {owner} no resultado informado",
|
|
2112
|
+
)
|
|
2113
|
+
declared_criteria = {finding.id: {criterion.id for criterion in finding.criterios} for finding in document.achados}
|
|
2114
|
+
for occurrence in occurrences:
|
|
2115
|
+
finding = document.finding(occurrence.achado)
|
|
2116
|
+
if finding is None:
|
|
2117
|
+
raise _error(
|
|
2118
|
+
f"auditado {occurrence.auditado}",
|
|
2119
|
+
f"o resultado confirma o achado {occurrence.achado}, que não tem representação no Markdown",
|
|
2120
|
+
)
|
|
2121
|
+
if occurrence.situacao not in finding.situation_ids():
|
|
2122
|
+
raise _error(
|
|
2123
|
+
f"auditado {occurrence.auditado}, achado {occurrence.achado}",
|
|
2124
|
+
f"o resultado confirma a situação {occurrence.situacao}, que não tem representação no Markdown",
|
|
2125
|
+
)
|
|
2126
|
+
missing = [criterion for criterion in occurrence.criterios if criterion not in declared_criteria[finding.id]]
|
|
2127
|
+
if missing:
|
|
2128
|
+
raise _error(
|
|
2129
|
+
f"auditado {occurrence.auditado}, achado {occurrence.achado}",
|
|
2130
|
+
"critério aplicado no resultado sem declaração editorial no achado: " + ", ".join(missing),
|
|
2131
|
+
)
|
|
2132
|
+
|
|
2133
|
+
|
|
2134
|
+
def _check_coverage(
|
|
2135
|
+
validated: Mapping[str, Any],
|
|
2136
|
+
occurrences: Sequence[EffectiveOccurrence],
|
|
2137
|
+
) -> None:
|
|
2138
|
+
rows = validated["rows"]
|
|
2139
|
+
declared = validated["cobertura"]
|
|
2140
|
+
evaluated = {signature for signature, row in rows.items() if row.get("foi_auditado") is True}
|
|
2141
|
+
with_findings = {occurrence.auditado for occurrence in occurrences}
|
|
2142
|
+
respondents = {
|
|
2143
|
+
signature
|
|
2144
|
+
for signature, row in rows.items()
|
|
2145
|
+
if row.get("respondeu_questionario") is True
|
|
2146
|
+
}
|
|
2147
|
+
declared_total = declared["total"]
|
|
2148
|
+
if declared_total != len(rows):
|
|
2149
|
+
raise _error("resultado.cobertura.total", f"declara {declared_total}, mas há {len(rows)} auditados no resultado")
|
|
2150
|
+
if declared["avaliados"] != len(evaluated):
|
|
2151
|
+
raise _error(
|
|
2152
|
+
"resultado.cobertura.avaliados",
|
|
2153
|
+
f"declara {declared['avaliados']}, mas o resultado contém {len(evaluated)} auditados avaliados",
|
|
2154
|
+
)
|
|
2155
|
+
if declared["com_achados"] != len(with_findings):
|
|
2156
|
+
raise _error(
|
|
2157
|
+
"resultado.cobertura.com_achados",
|
|
2158
|
+
f"declara {declared['com_achados']}, mas as ocorrências contêm {len(with_findings)} auditados distintos",
|
|
2159
|
+
)
|
|
2160
|
+
if declared["respondentes"] is not None:
|
|
2161
|
+
has_boolean = any(isinstance(row.get("respondeu_questionario"), bool) for row in rows.values())
|
|
2162
|
+
if has_boolean and declared["respondentes"] != len(respondents):
|
|
2163
|
+
raise _error(
|
|
2164
|
+
"resultado.cobertura.respondentes",
|
|
2165
|
+
f"declara {declared['respondentes']}, mas o resultado contém {len(respondents)} respondentes",
|
|
2166
|
+
)
|
|
2167
|
+
for signature, row in rows.items():
|
|
2168
|
+
if "tem_achados" not in row:
|
|
2169
|
+
continue
|
|
2170
|
+
auditado = str(row.get("sigla") or row.get("auditado") or signature).strip().upper()
|
|
2171
|
+
declared_flag = row.get("tem_achados") is True
|
|
2172
|
+
actual = auditado in with_findings
|
|
2173
|
+
if declared_flag != actual:
|
|
2174
|
+
raise _error(
|
|
2175
|
+
f"resultado.auditados.{auditado}.tem_achados",
|
|
2176
|
+
f"declara {declared_flag}, mas a normalização encontrou {'achados' if actual else 'nenhum achado'}",
|
|
2177
|
+
)
|
|
2178
|
+
|
|
2179
|
+
|
|
2180
|
+
def enrich_findings_document(
|
|
2181
|
+
document: FindingsDocument,
|
|
2182
|
+
payload: Any,
|
|
2183
|
+
*,
|
|
2184
|
+
resultado_sha256: str,
|
|
2185
|
+
strict: bool = False,
|
|
2186
|
+
) -> FindingsEnrichment:
|
|
2187
|
+
"""Cruza o documento editorial com o JSON e deriva a camada factual."""
|
|
2188
|
+
validated = validate_audit_payload(payload)
|
|
2189
|
+
declared_hash = str(document.metadata.origem.get("resultado_sha256") or "").strip()
|
|
2190
|
+
# O hash declarado pode ser o do arquivo ou, no v2, o do conteúdo (independe da indentação).
|
|
2191
|
+
content_hash = str(((payload.get("proveniencia") or {}) if isinstance(payload, Mapping) else {}).get("conteudo_sha256") or "")
|
|
2192
|
+
if declared_hash and declared_hash.casefold() not in {resultado_sha256.casefold(), content_hash.casefold()}:
|
|
2193
|
+
raise _error(
|
|
2194
|
+
"front_matter.origem.resultado_sha256",
|
|
2195
|
+
"o hash declarado no Markdown diverge do SHA-256 do JSON informado",
|
|
2196
|
+
)
|
|
2197
|
+
declared_scenario = str(document.metadata.origem.get("cenario") or "").strip()
|
|
2198
|
+
if declared_scenario and declared_scenario != validated["cenario"]:
|
|
2199
|
+
raise _error(
|
|
2200
|
+
"front_matter.origem.cenario",
|
|
2201
|
+
f"o cenário declarado ({declared_scenario!r}) diverge do cenário do resultado ({validated['cenario']!r})",
|
|
2202
|
+
)
|
|
2203
|
+
occurrences = _collect_occurrences(validated["rows"])
|
|
2204
|
+
_check_coverage(validated, occurrences)
|
|
2205
|
+
_validate_cross_references(document, occurrences, validated["contexto"])
|
|
2206
|
+
|
|
2207
|
+
resolved: list[EffectiveOccurrence] = []
|
|
2208
|
+
warnings: list[str] = []
|
|
2209
|
+
covered: dict[tuple[str, str, str], set[str]] = {}
|
|
2210
|
+
for occurrence in occurrences:
|
|
2211
|
+
finding = document.finding(occurrence.achado)
|
|
2212
|
+
assert finding is not None # garantido por _validate_cross_references
|
|
2213
|
+
situation = next(
|
|
2214
|
+
(item for item in finding.encaminhamentos if item.id == occurrence.situacao),
|
|
2215
|
+
None,
|
|
2216
|
+
)
|
|
2217
|
+
proposals = situation.propostas if situation else ()
|
|
2218
|
+
matched = _associate_occurrence(occurrence, proposals)
|
|
2219
|
+
proposal_ids = tuple(dict.fromkeys(proposal.id for proposal in matched))
|
|
2220
|
+
for proposal_id in proposal_ids:
|
|
2221
|
+
covered.setdefault((occurrence.achado, occurrence.situacao, proposal_id), set()).add(occurrence.auditado)
|
|
2222
|
+
resolved.append(
|
|
2223
|
+
EffectiveOccurrence(
|
|
2224
|
+
auditado=occurrence.auditado,
|
|
2225
|
+
nome=occurrence.nome,
|
|
2226
|
+
achado=occurrence.achado,
|
|
2227
|
+
situacao=occurrence.situacao,
|
|
2228
|
+
criterios=occurrence.criterios,
|
|
2229
|
+
decisions=occurrence.decisions,
|
|
2230
|
+
publico=occurrence.publico,
|
|
2231
|
+
id_variante=occurrence.id_variante,
|
|
2232
|
+
tipo_encaminhamento=occurrence.tipo_encaminhamento,
|
|
2233
|
+
propostas=proposal_ids,
|
|
2234
|
+
ids_acoes=occurrence.ids_acoes,
|
|
2235
|
+
ids_procedimentos=occurrence.ids_procedimentos,
|
|
2236
|
+
evidencias=occurrence.evidencias,
|
|
2237
|
+
itens=occurrence.itens,
|
|
2238
|
+
)
|
|
2239
|
+
)
|
|
2240
|
+
for finding in document.achados:
|
|
2241
|
+
for situation in finding.encaminhamentos:
|
|
2242
|
+
for proposal in situation.propostas:
|
|
2243
|
+
key = (finding.id, situation.id, proposal.id)
|
|
2244
|
+
if key not in covered:
|
|
2245
|
+
message = (
|
|
2246
|
+
f"achado {finding.id}, situação {situation.id}: a proposta {proposal.id} não corresponde a "
|
|
2247
|
+
"nenhuma decisão efetiva do resultado informado"
|
|
2248
|
+
)
|
|
2249
|
+
if strict:
|
|
2250
|
+
raise _error("encaminhamentos", message)
|
|
2251
|
+
warnings.append(message)
|
|
2252
|
+
by_situation: dict[tuple[str, str], set[str]] = {}
|
|
2253
|
+
by_finding: dict[str, set[str]] = {}
|
|
2254
|
+
for occurrence in resolved:
|
|
2255
|
+
by_situation.setdefault((occurrence.achado, occurrence.situacao), set()).add(occurrence.auditado)
|
|
2256
|
+
by_finding.setdefault(occurrence.achado, set()).add(occurrence.auditado)
|
|
2257
|
+
com_achados = {occurrence.auditado for occurrence in resolved}
|
|
2258
|
+
return FindingsEnrichment(
|
|
2259
|
+
cenario=validated["cenario"],
|
|
2260
|
+
resultado_sha256=resultado_sha256,
|
|
2261
|
+
cobertura=dict(validated["cobertura"]),
|
|
2262
|
+
occurrences=tuple(resolved),
|
|
2263
|
+
quantidade_por_situacao={key: len(value) for key, value in by_situation.items()},
|
|
2264
|
+
quantidade_por_achado={key: len(value) for key, value in by_finding.items()},
|
|
2265
|
+
auditados_por_situacao={key: tuple(sorted(value)) for key, value in by_situation.items()},
|
|
2266
|
+
auditados_por_proposta={key: tuple(sorted(value)) for key, value in covered.items()},
|
|
2267
|
+
auditados=tuple(sorted(com_achados)),
|
|
2268
|
+
com_achados=len(com_achados),
|
|
2269
|
+
warnings=tuple(warnings),
|
|
2270
|
+
)
|
|
2271
|
+
|
|
2272
|
+
|
|
2273
|
+
# --------------------------------------------------------------------------------------
|
|
2274
|
+
# Rascunho a partir do resultado de auditoria
|
|
2275
|
+
# --------------------------------------------------------------------------------------
|
|
2276
|
+
|
|
2277
|
+
|
|
2278
|
+
def _draft_title(project: Mapping[str, Any]) -> str:
|
|
2279
|
+
return (
|
|
2280
|
+
_project_field(project, METADATA_ALIASES["title"])
|
|
2281
|
+
or "[PREENCHER: título da fiscalização]"
|
|
2282
|
+
)
|
|
2283
|
+
|
|
2284
|
+
|
|
2285
|
+
def _draft_metadata(
|
|
2286
|
+
project: Mapping[str, Any],
|
|
2287
|
+
*,
|
|
2288
|
+
cenario: str,
|
|
2289
|
+
resultado_sha256: str | None,
|
|
2290
|
+
) -> MatrixMetadata:
|
|
2291
|
+
origem: dict[str, Any] = {"cenario": cenario}
|
|
2292
|
+
if resultado_sha256:
|
|
2293
|
+
origem["resultado_sha256"] = resultado_sha256
|
|
2294
|
+
return MatrixMetadata(
|
|
2295
|
+
title=_draft_title(project),
|
|
2296
|
+
fiscalizacao=(
|
|
2297
|
+
_project_field(project, METADATA_ALIASES["fiscalizacao"])
|
|
2298
|
+
or "[PREENCHER: número da fiscalização]"
|
|
2299
|
+
),
|
|
2300
|
+
jurisdicionados=(
|
|
2301
|
+
_project_field(project, METADATA_ALIASES["jurisdicionados"])
|
|
2302
|
+
or "[PREENCHER: jurisdicionados]"
|
|
2303
|
+
),
|
|
2304
|
+
objetivo_auditoria=(
|
|
2305
|
+
_project_field(project, METADATA_ALIASES["objetivo_auditoria"])
|
|
2306
|
+
or "[PREENCHER: objetivo da auditoria]"
|
|
2307
|
+
),
|
|
2308
|
+
processo=_project_field(project, METADATA_ALIASES["processo"]),
|
|
2309
|
+
orgao=_project_field(project, METADATA_ALIASES["orgao"]),
|
|
2310
|
+
unidade_responsavel=_project_field(project, METADATA_ALIASES["unidade_responsavel"]),
|
|
2311
|
+
tipo_matriz="achados",
|
|
2312
|
+
origem=origem,
|
|
2313
|
+
)
|
|
2314
|
+
|
|
2315
|
+
|
|
2316
|
+
def _draft_criteria(
|
|
2317
|
+
identifiers: Sequence[str],
|
|
2318
|
+
context: Mapping[str, list[Mapping[str, Any]]],
|
|
2319
|
+
) -> tuple[FindingCriterion, ...]:
|
|
2320
|
+
catalog = {str(item.get("id") or "").strip().upper(): item for item in context.get("criterios", [])}
|
|
2321
|
+
criteria: list[FindingCriterion] = []
|
|
2322
|
+
for identifier in identifiers:
|
|
2323
|
+
item = catalog.get(identifier.upper())
|
|
2324
|
+
if item is None:
|
|
2325
|
+
criteria.append(
|
|
2326
|
+
FindingCriterion(
|
|
2327
|
+
id=identifier.upper(),
|
|
2328
|
+
id_local=identifier.rsplit(".", 1)[-1],
|
|
2329
|
+
descricao="[PREENCHER: descrição do critério]",
|
|
2330
|
+
)
|
|
2331
|
+
)
|
|
2332
|
+
continue
|
|
2333
|
+
canonical = str(item.get("id") or "").strip().upper()
|
|
2334
|
+
local = str(item.get("id_local") or canonical.rsplit(".", 1)[-1]).strip()
|
|
2335
|
+
selectors = item.get("aplica_se")
|
|
2336
|
+
criteria.append(
|
|
2337
|
+
FindingCriterion(
|
|
2338
|
+
id=canonical,
|
|
2339
|
+
id_local=local,
|
|
2340
|
+
descricao=str(item.get("descricao") or "[PREENCHER: descrição do critério]").strip(),
|
|
2341
|
+
natureza_fundamento=(
|
|
2342
|
+
str(item.get("natureza_fundamento")).strip()
|
|
2343
|
+
if item.get("natureza_fundamento")
|
|
2344
|
+
else None
|
|
2345
|
+
),
|
|
2346
|
+
apto_a_fundamentar_determinacao=(
|
|
2347
|
+
item.get("apto_a_fundamentar_determinacao")
|
|
2348
|
+
if type(item.get("apto_a_fundamentar_determinacao")) is bool
|
|
2349
|
+
else None
|
|
2350
|
+
),
|
|
2351
|
+
publico=str(item.get("publico")).strip() if item.get("publico") else None,
|
|
2352
|
+
especifico=item.get("especifico") if type(item.get("especifico")) is bool else None,
|
|
2353
|
+
aplica_se=(
|
|
2354
|
+
{
|
|
2355
|
+
str(key): [str(value) for value in values]
|
|
2356
|
+
for key, values in selectors.items()
|
|
2357
|
+
if isinstance(values, list)
|
|
2358
|
+
}
|
|
2359
|
+
if isinstance(selectors, Mapping)
|
|
2360
|
+
else None
|
|
2361
|
+
),
|
|
2362
|
+
)
|
|
2363
|
+
)
|
|
2364
|
+
return tuple(criteria)
|
|
2365
|
+
|
|
2366
|
+
|
|
2367
|
+
def build_findings_markdown_draft(
|
|
2368
|
+
payload: Any,
|
|
2369
|
+
*,
|
|
2370
|
+
project_metadata: Mapping[str, Any] | None = None,
|
|
2371
|
+
resultado_sha256: str | None = None,
|
|
2372
|
+
) -> tuple[str, dict[str, Any]]:
|
|
2373
|
+
"""Cria o rascunho v1.3 a partir do JSON, sem ocorrências nem universo."""
|
|
2374
|
+
project = normalize_project_metadata(project_metadata)
|
|
2375
|
+
validated = validate_audit_payload(payload)
|
|
2376
|
+
context = validated["contexto"]
|
|
2377
|
+
occurrences = _collect_occurrences(validated["rows"])
|
|
2378
|
+
if not occurrences:
|
|
2379
|
+
metadata = _draft_metadata(project, cenario=validated["cenario"], resultado_sha256=resultado_sha256)
|
|
2380
|
+
document = FindingsDocument(metadata=metadata, achados=(), apresentacao=FindingsPresentation())
|
|
2381
|
+
return serialize_findings_markdown(document), {
|
|
2382
|
+
"findings": 0,
|
|
2383
|
+
"situations": 0,
|
|
2384
|
+
"criteria": 0,
|
|
2385
|
+
"evidence_records": 0,
|
|
2386
|
+
"referrals": 0,
|
|
2387
|
+
"occurrences": 0,
|
|
2388
|
+
"auditees_with_findings": 0,
|
|
2389
|
+
"cenario": validated["cenario"],
|
|
2390
|
+
"resultado_sha256": resultado_sha256,
|
|
2391
|
+
}
|
|
2392
|
+
questions = {
|
|
2393
|
+
str(item.get("id") or "").strip(): str(item.get("texto") or "").strip()
|
|
2394
|
+
for item in context.get("questoes", [])
|
|
2395
|
+
}
|
|
2396
|
+
context_findings = {
|
|
2397
|
+
str(item.get("id") or "").strip().upper(): item for item in context.get("achados", [])
|
|
2398
|
+
}
|
|
2399
|
+
context_situations: dict[str, list[Mapping[str, Any]]] = {}
|
|
2400
|
+
for item in context.get("situacoes", []):
|
|
2401
|
+
context_situations.setdefault(str(item.get("id_achado") or "").strip().upper(), []).append(item)
|
|
2402
|
+
context_sources: dict[str, list[Mapping[str, Any]]] = {}
|
|
2403
|
+
for item in context.get("fontes", []):
|
|
2404
|
+
context_sources.setdefault(str(item.get("id_questao") or "").strip(), []).append(item)
|
|
2405
|
+
order = {identifier: position for position, identifier in enumerate(context_findings)}
|
|
2406
|
+
grouped: dict[str, list[EffectiveOccurrence]] = {}
|
|
2407
|
+
for occurrence in occurrences:
|
|
2408
|
+
grouped.setdefault(occurrence.achado, []).append(occurrence)
|
|
2409
|
+
findings: list[Finding] = []
|
|
2410
|
+
for finding_id in sorted(grouped, key=lambda identifier: (order.get(identifier, 10**6), identifier)):
|
|
2411
|
+
items = grouped[finding_id]
|
|
2412
|
+
context_finding = context_findings.get(finding_id, {})
|
|
2413
|
+
question_id = str(context_finding.get("id_questao") or "").strip()
|
|
2414
|
+
questao_text = questions.get(question_id) or ""
|
|
2415
|
+
if question_id and questao_text and not questao_text.startswith(f"{question_id}."):
|
|
2416
|
+
questao = f"{question_id}. {questao_text}"
|
|
2417
|
+
else:
|
|
2418
|
+
questao = questao_text or None
|
|
2419
|
+
ordered_situations = [
|
|
2420
|
+
item for item in context_situations.get(finding_id, []) if isinstance(item, Mapping)
|
|
2421
|
+
]
|
|
2422
|
+
ordered_situations.sort(key=lambda item: (int(item.get("ordem") or 0), str(item.get("id") or "")))
|
|
2423
|
+
situation_ids: list[str] = []
|
|
2424
|
+
for item in ordered_situations:
|
|
2425
|
+
identifier = str(item.get("id") or "").strip()
|
|
2426
|
+
if identifier and any(
|
|
2427
|
+
occurrence.situacao == identifier for occurrence in items
|
|
2428
|
+
) and identifier not in situation_ids:
|
|
2429
|
+
situation_ids.append(identifier)
|
|
2430
|
+
for occurrence in items:
|
|
2431
|
+
if occurrence.situacao not in situation_ids:
|
|
2432
|
+
situation_ids.append(occurrence.situacao)
|
|
2433
|
+
descriptions = {
|
|
2434
|
+
str(item.get("id") or "").strip(): str(item.get("descricao") or "").strip()
|
|
2435
|
+
for item in ordered_situations
|
|
2436
|
+
}
|
|
2437
|
+
criteria_ids: list[str] = []
|
|
2438
|
+
for occurrence in items:
|
|
2439
|
+
for criterion in occurrence.criterios:
|
|
2440
|
+
if criterion not in criteria_ids:
|
|
2441
|
+
criteria_ids.append(criterion)
|
|
2442
|
+
if not criteria_ids and question_id:
|
|
2443
|
+
for item in context.get("criterios", []):
|
|
2444
|
+
if str(item.get("id_questao") or "").strip() == question_id:
|
|
2445
|
+
criteria_ids.append(str(item.get("id") or "").strip().upper())
|
|
2446
|
+
criteria = _draft_criteria(criteria_ids, context)
|
|
2447
|
+
sources = tuple(
|
|
2448
|
+
{"id": str(item.get("id") or "").strip(), "descricao": str(item.get("descricao") or "").strip()}
|
|
2449
|
+
for item in context_sources.get(question_id, [])
|
|
2450
|
+
if item.get("id") and item.get("descricao")
|
|
2451
|
+
)
|
|
2452
|
+
evidences: list[EvidenceSituation] = []
|
|
2453
|
+
for position, situation_id in enumerate(situation_ids, start=1):
|
|
2454
|
+
related = [occurrence for occurrence in items if occurrence.situacao == situation_id]
|
|
2455
|
+
narratives: list[str] = []
|
|
2456
|
+
items_list: list[str] = []
|
|
2457
|
+
ressalvas: list[str] = []
|
|
2458
|
+
for occurrence in related:
|
|
2459
|
+
for evidence in occurrence.evidencias:
|
|
2460
|
+
introduction = str(evidence.get("introducao") or "").strip()
|
|
2461
|
+
if introduction and introduction not in narratives:
|
|
2462
|
+
narratives.append(introduction)
|
|
2463
|
+
ressalva = str(evidence.get("ressalva") or "").strip()
|
|
2464
|
+
if ressalva and ressalva not in ressalvas:
|
|
2465
|
+
ressalvas.append(ressalva)
|
|
2466
|
+
for item in occurrence.itens:
|
|
2467
|
+
if item not in items_list:
|
|
2468
|
+
items_list.append(item)
|
|
2469
|
+
relato = "\n\n".join(narratives) or "[PREENCHER: relato da evidência]"
|
|
2470
|
+
evidences.append(
|
|
2471
|
+
EvidenceSituation(
|
|
2472
|
+
id=situation_id,
|
|
2473
|
+
descricao=descriptions.get(situation_id) or "[PREENCHER: descrição da situação]",
|
|
2474
|
+
registros=(
|
|
2475
|
+
EvidenceRecord(
|
|
2476
|
+
id=f"EV{position}",
|
|
2477
|
+
relato=relato,
|
|
2478
|
+
itens=tuple(items_list),
|
|
2479
|
+
fontes=sources,
|
|
2480
|
+
ressalva=ressalvas[0] if len(ressalvas) == 1 else None,
|
|
2481
|
+
),
|
|
2482
|
+
),
|
|
2483
|
+
)
|
|
2484
|
+
)
|
|
2485
|
+
proposals: list[ReferralProposal] = []
|
|
2486
|
+
scenario_proposals: list[ReferralSituation] = []
|
|
2487
|
+
for situation_id in situation_ids:
|
|
2488
|
+
related = [occurrence for occurrence in items if occurrence.situacao == situation_id]
|
|
2489
|
+
seen: set[tuple[Any, ...]] = set()
|
|
2490
|
+
local: list[ReferralProposal] = []
|
|
2491
|
+
for occurrence in related:
|
|
2492
|
+
for decision in occurrence.decisions:
|
|
2493
|
+
key = (
|
|
2494
|
+
_normalize_label(decision.publico),
|
|
2495
|
+
_normalize_label(decision.id_variante),
|
|
2496
|
+
_normalize_label(decision.tipo),
|
|
2497
|
+
decision.criterios,
|
|
2498
|
+
decision.encaminhamento,
|
|
2499
|
+
decision.fundamentacao,
|
|
2500
|
+
)
|
|
2501
|
+
if key in seen:
|
|
2502
|
+
continue
|
|
2503
|
+
seen.add(key)
|
|
2504
|
+
local.append(
|
|
2505
|
+
ReferralProposal(
|
|
2506
|
+
id=f"EN{len(proposals) + len(local) + 1}",
|
|
2507
|
+
tipo_encaminhamento=decision.tipo or "[PREENCHER: tipo de encaminhamento]",
|
|
2508
|
+
encaminhamento=decision.encaminhamento or "[PREENCHER: encaminhamento]",
|
|
2509
|
+
fundamentacao_encaminhamento=decision.fundamentacao,
|
|
2510
|
+
criterios=tuple(decision.criterios),
|
|
2511
|
+
publico=decision.publico,
|
|
2512
|
+
id_variante=decision.id_variante,
|
|
2513
|
+
)
|
|
2514
|
+
)
|
|
2515
|
+
proposals.extend(local)
|
|
2516
|
+
scenario_proposals.append(ReferralSituation(id=situation_id, propostas=tuple(local)))
|
|
2517
|
+
findings.append(
|
|
2518
|
+
Finding(
|
|
2519
|
+
id=finding_id,
|
|
2520
|
+
titulo=str(context_finding.get("titulo") or "[PREENCHER: título do achado]").strip(),
|
|
2521
|
+
questao=questao,
|
|
2522
|
+
situacao_encontrada="[PREENCHER: relato analítico do achado, com contexto, extensão e limitações]",
|
|
2523
|
+
criterios=criteria,
|
|
2524
|
+
evidencias=tuple(evidences),
|
|
2525
|
+
causas="[PREENCHER: causas]",
|
|
2526
|
+
efeitos=(),
|
|
2527
|
+
encaminhamentos=tuple(scenario_proposals),
|
|
2528
|
+
)
|
|
2529
|
+
)
|
|
2530
|
+
metadata = _draft_metadata(project, cenario=validated["cenario"], resultado_sha256=resultado_sha256)
|
|
2531
|
+
document = FindingsDocument(
|
|
2532
|
+
metadata=metadata,
|
|
2533
|
+
achados=tuple(findings),
|
|
2534
|
+
apresentacao=FindingsPresentation(),
|
|
2535
|
+
)
|
|
2536
|
+
summary = {
|
|
2537
|
+
"findings": len(document.achados),
|
|
2538
|
+
"situations": sum(len(finding.evidencias) for finding in document.achados),
|
|
2539
|
+
"criteria": sum(len(finding.criterios) for finding in document.achados),
|
|
2540
|
+
"evidence_records": sum(
|
|
2541
|
+
len(situation.registros) for finding in document.achados for situation in finding.evidencias
|
|
2542
|
+
),
|
|
2543
|
+
"referrals": sum(len(situation.propostas) for finding in document.achados for situation in finding.encaminhamentos),
|
|
2544
|
+
"occurrences": len(occurrences),
|
|
2545
|
+
"auditees_with_findings": len({occurrence.auditado for occurrence in occurrences}),
|
|
2546
|
+
"cenario": validated["cenario"],
|
|
2547
|
+
"resultado_sha256": resultado_sha256,
|
|
2548
|
+
}
|
|
2549
|
+
return serialize_findings_markdown(document), summary
|