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
|
@@ -0,0 +1,571 @@
|
|
|
1
|
+
"""Aplicação de ajustes imutáveis e preparação de propostas de ajuste."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, Iterable, Mapping
|
|
9
|
+
|
|
10
|
+
from ..booleans import normalize
|
|
11
|
+
from ..core import OperationContext
|
|
12
|
+
from ..contracts import OperationResult, ProductDraft, ScenarioDraft, canonical_json, sha256_bytes, sha256_file
|
|
13
|
+
from ..errors import InputValidationError
|
|
14
|
+
from ..adapters.xlsx import find_column, find_header_row, openpyxl_workbook, require_file
|
|
15
|
+
from ..adapters.xlsx import workbook_bytes as _workbook_bytes_deterministico
|
|
16
|
+
from .evaluation import _yaml
|
|
17
|
+
from .evaluation import ler_xlsx, texto
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _trace_value(value: Any) -> Any:
|
|
21
|
+
"""Mantém detalhes da alteração serializáveis no histórico SQLite."""
|
|
22
|
+
if value is None or isinstance(value, (str, int, float, bool)):
|
|
23
|
+
return value
|
|
24
|
+
isoformat = getattr(value, "isoformat", None)
|
|
25
|
+
if callable(isoformat):
|
|
26
|
+
return isoformat()
|
|
27
|
+
return str(value)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _same_cell_value(current: Any, proposed: Any) -> bool:
|
|
31
|
+
"""Compara valores sem apagar diferenças de tipo XLSX."""
|
|
32
|
+
if current is None or proposed is None:
|
|
33
|
+
return current is None and proposed is None
|
|
34
|
+
return type(current) is type(proposed) and current == proposed
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _assert_execution_inputs_current(context: OperationContext, expected_sha256: str) -> None:
|
|
38
|
+
from ..fingerprints import execution_fingerprint
|
|
39
|
+
|
|
40
|
+
current = execution_fingerprint(
|
|
41
|
+
context.operation, context.params, context.project_root, context.store, context.catalog
|
|
42
|
+
)
|
|
43
|
+
if current != expected_sha256:
|
|
44
|
+
raise InputValidationError(
|
|
45
|
+
"insumos ou estado de revisão mudaram durante a preparação do cenário"
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def adjust_responses(context: OperationContext) -> OperationResult:
|
|
50
|
+
params = context.params
|
|
51
|
+
parent_scenario = str(params.get("parent_scenario") or "base")
|
|
52
|
+
read_scenario = str(params.get("scenario") or "base")
|
|
53
|
+
if read_scenario != parent_scenario:
|
|
54
|
+
raise InputValidationError(
|
|
55
|
+
"o cenário de leitura deve ser o pai declarado do cenário de ajustes"
|
|
56
|
+
)
|
|
57
|
+
response_path = require_file(context, params["respostas"], "respostas")
|
|
58
|
+
adjustments_path = require_file(context, params["ajustes"], "ajustes")
|
|
59
|
+
negative_values: dict[str, Any] = {}
|
|
60
|
+
rules_path = None
|
|
61
|
+
if params.get("regras"):
|
|
62
|
+
rules_path = require_file(context, params["regras"], "regras de ajustes")
|
|
63
|
+
rules = _yaml().safe_load(rules_path.read_text(encoding="utf-8"))
|
|
64
|
+
if not isinstance(rules, Mapping) or not isinstance(rules.get("negative_values"), Mapping):
|
|
65
|
+
raise InputValidationError("regras de ajustes requerem negative_values como mapa coluna → valor")
|
|
66
|
+
negative_values = {str(key).casefold(): value for key, value in rules["negative_values"].items()}
|
|
67
|
+
output_path = context.optional_path(params.get("output"))
|
|
68
|
+
if output_path is None:
|
|
69
|
+
suffix = response_path.suffix
|
|
70
|
+
stem = response_path.stem if suffix else response_path.name
|
|
71
|
+
output_path = response_path.with_name(f"{stem}-ajustado{suffix}")
|
|
72
|
+
load_workbook = openpyxl_workbook()
|
|
73
|
+
responses_book = load_workbook(response_path)
|
|
74
|
+
adjustments_book = load_workbook(adjustments_path, data_only=True)
|
|
75
|
+
try:
|
|
76
|
+
return _apply_adjustments(
|
|
77
|
+
context,
|
|
78
|
+
params,
|
|
79
|
+
parent_scenario=parent_scenario,
|
|
80
|
+
response_path=response_path,
|
|
81
|
+
adjustments_path=adjustments_path,
|
|
82
|
+
rules_path=rules_path,
|
|
83
|
+
negative_values=negative_values,
|
|
84
|
+
output_path=output_path,
|
|
85
|
+
responses_book=responses_book,
|
|
86
|
+
adjustments_book=adjustments_book,
|
|
87
|
+
)
|
|
88
|
+
finally:
|
|
89
|
+
adjustments_book.close()
|
|
90
|
+
responses_book.close()
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _apply_adjustments(
|
|
94
|
+
context: OperationContext,
|
|
95
|
+
params: Mapping[str, Any],
|
|
96
|
+
*,
|
|
97
|
+
parent_scenario: str,
|
|
98
|
+
response_path: Any,
|
|
99
|
+
adjustments_path: Any,
|
|
100
|
+
rules_path: Any,
|
|
101
|
+
negative_values: dict[str, Any],
|
|
102
|
+
output_path: Any,
|
|
103
|
+
responses_book: Any,
|
|
104
|
+
adjustments_book: Any,
|
|
105
|
+
) -> OperationResult:
|
|
106
|
+
response_sheet = responses_book.active
|
|
107
|
+
adjustment_sheet = adjustments_book.active
|
|
108
|
+
response_header_row, response_headers = find_header_row(response_sheet)
|
|
109
|
+
if not response_header_row:
|
|
110
|
+
raise InputValidationError("planilha de respostas sem cabeçalho")
|
|
111
|
+
adjustment_header_row, adjustment_headers = find_header_row(adjustment_sheet)
|
|
112
|
+
if not adjustment_header_row:
|
|
113
|
+
raise InputValidationError("planilha de ajustes sem cabeçalho")
|
|
114
|
+
response_header_map = {
|
|
115
|
+
str(name).strip().casefold(): index + 1
|
|
116
|
+
for index, name in enumerate(response_headers)
|
|
117
|
+
if name
|
|
118
|
+
}
|
|
119
|
+
adjustment_header_map = {
|
|
120
|
+
str(name).strip().casefold(): index
|
|
121
|
+
for index, name in enumerate(adjustment_headers)
|
|
122
|
+
if name
|
|
123
|
+
}
|
|
124
|
+
auditado_response = find_column(response_headers, ("id_org", "firstname", "orgao", "sigla", "auditado"))
|
|
125
|
+
if not auditado_response:
|
|
126
|
+
raise InputValidationError("respostas sem coluna id_org/firstname/orgao/sigla/auditado")
|
|
127
|
+
auditado_response_col = response_header_map[auditado_response.casefold()]
|
|
128
|
+
response_rows: dict[str, int] = {}
|
|
129
|
+
for row_number in range(response_header_row + 1, response_sheet.max_row + 1):
|
|
130
|
+
value = response_sheet.cell(row_number, auditado_response_col).value
|
|
131
|
+
if value not in (None, ""):
|
|
132
|
+
key = normalize(value)
|
|
133
|
+
if key in response_rows:
|
|
134
|
+
raise InputValidationError(f"auditado duplicado na base de respostas: {value}")
|
|
135
|
+
response_rows[key] = row_number
|
|
136
|
+
|
|
137
|
+
configured_columns = {
|
|
138
|
+
"id_org": str(params.get("coluna_org") or "id_org").strip(),
|
|
139
|
+
"chave": str(params.get("coluna_chave") or "chave").strip(),
|
|
140
|
+
"valor": str(params.get("coluna_valor") or "valor").strip(),
|
|
141
|
+
"obs": str(params.get("coluna_obs") or "obs").strip(),
|
|
142
|
+
}
|
|
143
|
+
configured_matches = {
|
|
144
|
+
name: find_column(adjustment_headers, (header,))
|
|
145
|
+
for name, header in configured_columns.items()
|
|
146
|
+
}
|
|
147
|
+
default_columns = {"id_org": "id_org", "chave": "chave", "valor": "valor", "obs": "obs"}
|
|
148
|
+
using_default_columns = all(
|
|
149
|
+
normalize(configured_columns[name]) == normalize(default_columns[name]) for name in configured_columns
|
|
150
|
+
)
|
|
151
|
+
legacy_org = find_column(adjustment_headers, ("Auditado",))
|
|
152
|
+
legacy_key = find_column(adjustment_headers, ("Código do item", "Código do item avaliado"))
|
|
153
|
+
legacy_value = find_column(adjustment_headers, ("Resposta ajustada",))
|
|
154
|
+
reviewer_col = find_column(adjustment_headers, ("Avaliação do auditor revisor",))
|
|
155
|
+
judge_col = find_column(adjustment_headers, ("Resultado da avaliação do juiz",))
|
|
156
|
+
new_schema = all(configured_matches.values())
|
|
157
|
+
legacy_schema = (
|
|
158
|
+
using_default_columns
|
|
159
|
+
and not any(configured_matches[name] for name in ("id_org", "chave", "valor"))
|
|
160
|
+
and legacy_org is not None
|
|
161
|
+
and legacy_key is not None
|
|
162
|
+
and (legacy_value is not None or reviewer_col is not None or judge_col is not None)
|
|
163
|
+
)
|
|
164
|
+
if new_schema:
|
|
165
|
+
adjustment_columns = configured_matches
|
|
166
|
+
explicit_col = adjustment_columns["valor"]
|
|
167
|
+
obs_col = adjustment_columns["obs"]
|
|
168
|
+
elif legacy_schema:
|
|
169
|
+
adjustment_columns = {
|
|
170
|
+
"id_org": legacy_org,
|
|
171
|
+
"chave": legacy_key,
|
|
172
|
+
"valor": legacy_value,
|
|
173
|
+
"obs": configured_matches["obs"],
|
|
174
|
+
}
|
|
175
|
+
explicit_col = legacy_value
|
|
176
|
+
obs_col = configured_matches["obs"] or find_column(adjustment_headers, ("observacao", "Justificativa"))
|
|
177
|
+
else:
|
|
178
|
+
missing = [
|
|
179
|
+
configured_columns[name]
|
|
180
|
+
for name in ("id_org", "chave", "valor", "obs")
|
|
181
|
+
if configured_matches[name] is None
|
|
182
|
+
]
|
|
183
|
+
raise InputValidationError(
|
|
184
|
+
"planilha de ajustes sem colunas obrigatórias: " + ", ".join(missing)
|
|
185
|
+
)
|
|
186
|
+
item_col = adjustment_header_map[adjustment_columns["chave"].casefold()]
|
|
187
|
+
auditado_col = adjustment_header_map[adjustment_columns["id_org"].casefold()]
|
|
188
|
+
explicit_col_index = (
|
|
189
|
+
adjustment_header_map[explicit_col.casefold()] if explicit_col else None
|
|
190
|
+
)
|
|
191
|
+
obs_col_index = adjustment_header_map[obs_col.casefold()] if obs_col else None
|
|
192
|
+
changes: list[dict[str, Any]] = []
|
|
193
|
+
planned_cells: list[tuple[int, int, Any]] = []
|
|
194
|
+
selected_cells: dict[tuple[int, int], dict[str, Any]] = {}
|
|
195
|
+
warnings: list[str] = []
|
|
196
|
+
pending: list[dict[str, Any]] = []
|
|
197
|
+
|
|
198
|
+
def defer(row_number: int, reason: str, *, auditado: Any = None, item: Any = None) -> None:
|
|
199
|
+
"""Registra linhas que exigem revisão, sem inferir valor de resposta."""
|
|
200
|
+
message = f"linha {row_number}: {reason}"
|
|
201
|
+
warnings.append(message)
|
|
202
|
+
pending.append(
|
|
203
|
+
{
|
|
204
|
+
"type": "adjustment_review_required",
|
|
205
|
+
"row": row_number,
|
|
206
|
+
"auditado": _trace_value(auditado),
|
|
207
|
+
"item": _trace_value(item),
|
|
208
|
+
"reason": reason,
|
|
209
|
+
}
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
response_columns = {
|
|
213
|
+
str(value).strip().casefold(): index + 1
|
|
214
|
+
for index, value in enumerate(response_headers)
|
|
215
|
+
if value
|
|
216
|
+
}
|
|
217
|
+
for row_number, values in enumerate(
|
|
218
|
+
adjustment_sheet.iter_rows(min_row=adjustment_header_row + 1, values_only=True),
|
|
219
|
+
start=adjustment_header_row + 1,
|
|
220
|
+
):
|
|
221
|
+
if not values or not any(value not in (None, "") for value in values):
|
|
222
|
+
continue
|
|
223
|
+
auditado = values[auditado_col] if auditado_col < len(values) else None
|
|
224
|
+
item_code = values[item_col] if item_col < len(values) else None
|
|
225
|
+
if auditado in (None, "") or item_code in (None, ""):
|
|
226
|
+
defer(
|
|
227
|
+
row_number,
|
|
228
|
+
"identificação incompleta; informe auditado e item",
|
|
229
|
+
auditado=auditado,
|
|
230
|
+
item=item_code,
|
|
231
|
+
)
|
|
232
|
+
continue
|
|
233
|
+
auditado_text = str(auditado).strip()
|
|
234
|
+
item_text = str(item_code).strip()
|
|
235
|
+
target_row = response_rows.get(normalize(auditado_text))
|
|
236
|
+
if target_row is None:
|
|
237
|
+
defer(row_number, "auditado não encontrado na base de respostas", auditado=auditado_text, item=item_text)
|
|
238
|
+
continue
|
|
239
|
+
target_col = response_columns.get(item_text.casefold())
|
|
240
|
+
if target_col is None:
|
|
241
|
+
match = re.match(r"^(q\d{4})\[([A-Za-z])\]$", item_text)
|
|
242
|
+
if match:
|
|
243
|
+
target_col = response_columns.get(match.group(1).casefold())
|
|
244
|
+
if target_col is None:
|
|
245
|
+
defer(row_number, "coluna não encontrada na base de respostas", auditado=auditado_text, item=item_text)
|
|
246
|
+
continue
|
|
247
|
+
old_value = response_sheet.cell(target_row, target_col).value
|
|
248
|
+
new_value: Any = None
|
|
249
|
+
if explicit_col_index is not None:
|
|
250
|
+
value = values[explicit_col_index] if explicit_col_index < len(values) else None
|
|
251
|
+
new_value = None if value is None or normalize(value) in {"", "nan", "none", "vazio"} else value
|
|
252
|
+
if legacy_schema and item_text.casefold() not in response_columns:
|
|
253
|
+
option = re.fullmatch(r"q\d{4}\[([A-Za-z])\]", item_text)
|
|
254
|
+
if option:
|
|
255
|
+
letter = option[1].casefold()
|
|
256
|
+
labels = (response_sheet.cell(r, target_col).value for r in range(response_header_row + 1, response_sheet.max_row + 1))
|
|
257
|
+
label = next(
|
|
258
|
+
(
|
|
259
|
+
value
|
|
260
|
+
for value in labels
|
|
261
|
+
if str(value or "").strip().casefold().startswith((f"{letter})", f"{letter} "))
|
|
262
|
+
),
|
|
263
|
+
None,
|
|
264
|
+
)
|
|
265
|
+
if label is None:
|
|
266
|
+
defer(
|
|
267
|
+
row_number,
|
|
268
|
+
f"alternativa {item_text} não pôde ser mapeada a um valor declarado",
|
|
269
|
+
auditado=auditado_text,
|
|
270
|
+
item=item_text,
|
|
271
|
+
)
|
|
272
|
+
continue
|
|
273
|
+
new_value = label
|
|
274
|
+
else:
|
|
275
|
+
reviewer = values[adjustment_header_map[reviewer_col.casefold()]] if reviewer_col and adjustment_header_map[reviewer_col.casefold()] < len(values) else None
|
|
276
|
+
judge = values[adjustment_header_map[judge_col.casefold()]] if judge_col and adjustment_header_map[judge_col.casefold()] < len(values) else None
|
|
277
|
+
final = reviewer if reviewer not in (None, "") and normalize(reviewer) != "sem_parecer" else judge
|
|
278
|
+
if normalize(final) not in {"nao conforme", "nao_conforme", "nao-conforme"}:
|
|
279
|
+
continue
|
|
280
|
+
if item_text.casefold() in negative_values:
|
|
281
|
+
new_value = negative_values[item_text.casefold()]
|
|
282
|
+
elif "ext" in item_text.casefold() or "[" in item_text:
|
|
283
|
+
if normalize(old_value) == "y":
|
|
284
|
+
new_value = None
|
|
285
|
+
elif normalize(old_value) == "sim":
|
|
286
|
+
new_value = "Não"
|
|
287
|
+
else:
|
|
288
|
+
defer(
|
|
289
|
+
row_number,
|
|
290
|
+
"resposta de detalhe não permite determinar com segurança o valor negativo",
|
|
291
|
+
auditado=auditado_text,
|
|
292
|
+
item=item_text,
|
|
293
|
+
)
|
|
294
|
+
continue
|
|
295
|
+
else:
|
|
296
|
+
new_value = "Não adota." if any(
|
|
297
|
+
str(response_sheet.cell(r, target_col).value or "").strip().endswith(".")
|
|
298
|
+
for r in range(response_header_row + 1, response_sheet.max_row + 1)
|
|
299
|
+
) else "Não adota"
|
|
300
|
+
cell_key = (target_row, target_col)
|
|
301
|
+
previous = selected_cells.get(cell_key)
|
|
302
|
+
if previous is not None:
|
|
303
|
+
if not _same_cell_value(previous["value"], new_value):
|
|
304
|
+
raise InputValidationError(
|
|
305
|
+
f"ajuste duplicado ou contraditório para {auditado_text}/{item_text}"
|
|
306
|
+
)
|
|
307
|
+
change_index = previous["change_index"]
|
|
308
|
+
if change_index is not None:
|
|
309
|
+
changes[change_index].setdefault("source_rows", [previous["row"]]).append(row_number)
|
|
310
|
+
continue
|
|
311
|
+
selected_cells[cell_key] = {
|
|
312
|
+
"value": new_value,
|
|
313
|
+
"row": row_number,
|
|
314
|
+
"change_index": None,
|
|
315
|
+
}
|
|
316
|
+
if _same_cell_value(old_value, new_value):
|
|
317
|
+
continue
|
|
318
|
+
observation = values[obs_col_index] if obs_col_index is not None and obs_col_index < len(values) else None
|
|
319
|
+
planned_cells.append((target_row, target_col, new_value))
|
|
320
|
+
changes.append(
|
|
321
|
+
{
|
|
322
|
+
"auditado": _trace_value(auditado_text),
|
|
323
|
+
"item": _trace_value(item_text),
|
|
324
|
+
"old": _trace_value(old_value),
|
|
325
|
+
"new": _trace_value(new_value),
|
|
326
|
+
"id_org": _trace_value(auditado_text),
|
|
327
|
+
"chave": _trace_value(item_text),
|
|
328
|
+
"valor": _trace_value(new_value),
|
|
329
|
+
"obs": _trace_value(observation),
|
|
330
|
+
}
|
|
331
|
+
)
|
|
332
|
+
selected_cells[cell_key]["change_index"] = len(changes) - 1
|
|
333
|
+
adjustments_book.close()
|
|
334
|
+
source_hash = sha256_file(response_path)
|
|
335
|
+
adjustments_hash = sha256_file(adjustments_path)
|
|
336
|
+
rules_hash = sha256_file(rules_path) if rules_path is not None else None
|
|
337
|
+
preparation_material = {
|
|
338
|
+
"format": "argos.response-adjustment-preparation.v1",
|
|
339
|
+
"parent_scenario": parent_scenario,
|
|
340
|
+
"output_path": str(output_path),
|
|
341
|
+
"responses_sha256": source_hash,
|
|
342
|
+
"adjustments_sha256": adjustments_hash,
|
|
343
|
+
"rules_sha256": rules_hash,
|
|
344
|
+
"adjustment_columns": adjustment_columns,
|
|
345
|
+
}
|
|
346
|
+
preparation_sha256 = sha256_bytes(canonical_json(preparation_material).encode("utf-8"))
|
|
347
|
+
scenario_identity = str(params.get("scenario_id") or f"ajustes-{preparation_sha256[:16]}")
|
|
348
|
+
scenario_name = str(params.get("scenario_name") or "").strip() or None
|
|
349
|
+
|
|
350
|
+
for row_number, column_number, value in planned_cells:
|
|
351
|
+
response_sheet.cell(row_number, column_number).value = value
|
|
352
|
+
workbook_bytes = _workbook_bytes_deterministico(responses_book)
|
|
353
|
+
responses_book.close()
|
|
354
|
+
output_hash = sha256_bytes(workbook_bytes)
|
|
355
|
+
scenario_input_hash = sha256_bytes(
|
|
356
|
+
canonical_json(
|
|
357
|
+
{
|
|
358
|
+
"preparation_sha256": preparation_sha256,
|
|
359
|
+
"responses_sha256": source_hash,
|
|
360
|
+
"adjustments_sha256": adjustments_hash,
|
|
361
|
+
"rules_sha256": rules_hash,
|
|
362
|
+
"output_sha256": output_hash,
|
|
363
|
+
}
|
|
364
|
+
).encode("utf-8")
|
|
365
|
+
)
|
|
366
|
+
scenario = ScenarioDraft(
|
|
367
|
+
id=scenario_identity,
|
|
368
|
+
name=scenario_name,
|
|
369
|
+
parent_id=parent_scenario,
|
|
370
|
+
kind="response-adjustment",
|
|
371
|
+
input_hash=scenario_input_hash,
|
|
372
|
+
metadata={
|
|
373
|
+
"responses_sha256": source_hash,
|
|
374
|
+
"adjustments_sha256": adjustments_hash,
|
|
375
|
+
"rules_sha256": rules_hash,
|
|
376
|
+
"preparation_sha256": preparation_sha256,
|
|
377
|
+
"output_sha256": output_hash,
|
|
378
|
+
"changes": len(changes),
|
|
379
|
+
"warnings": len(warnings),
|
|
380
|
+
"pending": len(pending),
|
|
381
|
+
"pending_adjustments": pending,
|
|
382
|
+
"adjustment_columns": adjustment_columns,
|
|
383
|
+
"applied_changes": changes,
|
|
384
|
+
},
|
|
385
|
+
)
|
|
386
|
+
return OperationResult(
|
|
387
|
+
summary={
|
|
388
|
+
"changes": len(changes),
|
|
389
|
+
"warnings": len(warnings),
|
|
390
|
+
"pending": len(pending),
|
|
391
|
+
"output": str(output_path),
|
|
392
|
+
"change_details": changes,
|
|
393
|
+
"adjustment_columns": adjustment_columns,
|
|
394
|
+
},
|
|
395
|
+
warnings=tuple(warnings),
|
|
396
|
+
pending=tuple(pending),
|
|
397
|
+
scenarios=(scenario,),
|
|
398
|
+
products=(
|
|
399
|
+
ProductDraft(
|
|
400
|
+
kind="adjusted-responses",
|
|
401
|
+
path=output_path,
|
|
402
|
+
content=workbook_bytes,
|
|
403
|
+
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
404
|
+
metadata={"changes": len(changes), "warnings": len(warnings), "pending": len(pending)},
|
|
405
|
+
),
|
|
406
|
+
),
|
|
407
|
+
)
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def _jsonl(path: Path) -> list[dict[str, Any]]:
|
|
411
|
+
if not path.is_file():
|
|
412
|
+
return []
|
|
413
|
+
return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def _violations(record: Mapping[str, Any], result: Any) -> list[tuple[str, str]]:
|
|
417
|
+
if not isinstance(result, Mapping):
|
|
418
|
+
return [("resultado_ausente", "resultado não é um objeto")]
|
|
419
|
+
if result.get("status", "completed") != "completed":
|
|
420
|
+
return [("status_invalido", "resultado não está concluído")]
|
|
421
|
+
conclusions = result.get("conclusoes") or result.get("conclusions")
|
|
422
|
+
if not isinstance(conclusions, list) or not conclusions:
|
|
423
|
+
return [("conclusoes_ausentes", "resultado não contém conclusões")]
|
|
424
|
+
expected = {
|
|
425
|
+
str(item.get("codigo") or item.get("item_codigo") or "").strip()
|
|
426
|
+
for item in record.get("itens") or []
|
|
427
|
+
if isinstance(item, Mapping)
|
|
428
|
+
}
|
|
429
|
+
if not expected and record.get("codigo"):
|
|
430
|
+
expected = {str(record["codigo"]).strip()}
|
|
431
|
+
received = {
|
|
432
|
+
str(item.get("item_codigo") or item.get("item_code") or item.get("codigo") or "").strip()
|
|
433
|
+
for item in conclusions
|
|
434
|
+
if isinstance(item, Mapping)
|
|
435
|
+
}
|
|
436
|
+
if "" in received:
|
|
437
|
+
return [("codigo_item_ausente", "há conclusão sem código de item")]
|
|
438
|
+
if expected and received != expected:
|
|
439
|
+
return [("escopo_itens", f"itens esperados={sorted(expected)}; recebidos={sorted(received)}")]
|
|
440
|
+
return []
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def validar_resultado_no_escopo(record: Mapping[str, Any], result: Any, *, validar_temporal: bool = False) -> list[tuple[str, str]]:
|
|
444
|
+
del validar_temporal
|
|
445
|
+
return _violations(record, result)
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def formatar_violacoes(values: Iterable[tuple[str, str]]) -> str:
|
|
449
|
+
return "; ".join(f"{code}: {message}" for code, message in values)
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def _responses(path: Path) -> dict[str, dict[str, Any]]:
|
|
453
|
+
_, rows = ler_xlsx(path)
|
|
454
|
+
return {texto(row.get("firstname")).upper(): row for row in rows if texto(row.get("firstname"))}
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def _adjustment_rows(path: Path) -> dict[tuple[str, str], dict[str, Any]]:
|
|
458
|
+
_, rows = ler_xlsx(path)
|
|
459
|
+
return {
|
|
460
|
+
(texto(row.get("Auditado")).upper(), texto(row.get("Código do item avaliado") or row.get("Código do item"))): row
|
|
461
|
+
for row in rows
|
|
462
|
+
if texto(row.get("Auditado")) and texto(row.get("Código do item avaliado") or row.get("Código do item"))
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
def _base_row(**values: Any) -> dict[str, Any]:
|
|
467
|
+
return {
|
|
468
|
+
"Auditado": values.get("auditado", ""),
|
|
469
|
+
"Código do item avaliado": values.get("codigo", ""),
|
|
470
|
+
"Resposta afirmada": values.get("resposta_afirmada", ""),
|
|
471
|
+
"Resposta anterior": values.get("resposta_anterior", ""),
|
|
472
|
+
"Resposta ajustada": values.get("resposta_ajustada", ""),
|
|
473
|
+
"Origem": values.get("origem", ""),
|
|
474
|
+
"Resultado da avaliação do juiz": values.get("resultado", ""),
|
|
475
|
+
"Justificativa do juiz": values.get("justificativa", ""),
|
|
476
|
+
"Case ID": values.get("case_id", ""),
|
|
477
|
+
"Identidade do parecer": values.get("identity", ""),
|
|
478
|
+
"Motivo da pendência": values.get("pendencia", ""),
|
|
479
|
+
"Fonte da ação": values.get("source", ""),
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def mapear_ajustes_secao1(
|
|
484
|
+
*, consolidado: Path, resultado_auditoria: Path, mapa: Path, lss: Path,
|
|
485
|
+
ajustes_pos_avaliacao_evidencias: Path, respostas_base: Path, respostas_originais: Path,
|
|
486
|
+
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
|
487
|
+
del lss
|
|
488
|
+
# O acervo legado pode não permitir reconstruir o contexto completo; use
|
|
489
|
+
# o contexto materializado no próprio registro quando disponível.
|
|
490
|
+
del resultado_auditoria, mapa
|
|
491
|
+
base = _responses(respostas_base)
|
|
492
|
+
proposals: list[dict[str, Any]] = []
|
|
493
|
+
pending: list[dict[str, Any]] = []
|
|
494
|
+
evidence_adjustments = _adjustment_rows(ajustes_pos_avaliacao_evidencias)
|
|
495
|
+
original = _responses(respostas_originais)
|
|
496
|
+
for record in _jsonl(consolidado):
|
|
497
|
+
result = record.get("result") or {}
|
|
498
|
+
violations = formatar_violacoes(_violations(record, result))
|
|
499
|
+
if violations:
|
|
500
|
+
pending.append(_base_row(auditado=texto(record.get("auditado")).upper(), case_id=record.get("case_id"), identity=record.get("identity"), pendencia=violations))
|
|
501
|
+
continue
|
|
502
|
+
conclusions = result.get("conclusoes") or []
|
|
503
|
+
for conclusion in conclusions:
|
|
504
|
+
if not isinstance(conclusion, Mapping):
|
|
505
|
+
continue
|
|
506
|
+
auditado = texto(record.get("auditado")).upper()
|
|
507
|
+
temporal = texto(conclusion.get("estado_temporal"))
|
|
508
|
+
if temporal not in {"afastada_na_data_base", "corrigida_posteriormente"}:
|
|
509
|
+
continue
|
|
510
|
+
context = record.get("contexto") or {}
|
|
511
|
+
actions = [action for reason in context.get("motivos") or [] if isinstance(reason, Mapping) for action in reason.get("acoes") or [] if isinstance(action, Mapping)]
|
|
512
|
+
item_codes = [texto(action.get("informacao_requerida")) for action in actions if texto(action.get("informacao_requerida"))]
|
|
513
|
+
if not item_codes:
|
|
514
|
+
item_codes = [texto(conclusion.get("item_codigo") or record.get("codigo"))]
|
|
515
|
+
for codigo in dict.fromkeys(item_codes):
|
|
516
|
+
old_value = texto((original.get(auditado) or {}).get(codigo) or (base.get(auditado) or {}).get(codigo))
|
|
517
|
+
adjusted = texto((evidence_adjustments.get((auditado, codigo)) or {}).get("Resposta afirmada")) or old_value
|
|
518
|
+
proposals.append(_base_row(auditado=auditado, codigo=codigo, resposta_afirmada=old_value, resposta_anterior=old_value, resposta_ajustada=adjusted, origem="secao_1_situacao", resultado=conclusion.get("estado"), justificativa=conclusion.get("justificativa"), case_id=record.get("case_id"), identity=record.get("identity")))
|
|
519
|
+
return proposals, pending
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
def mapear_ajustes_secao2(*, consolidado: Path, ajustes_pos_avaliacao_evidencias: Path, questionario: Path, saneados_secao1: set[Any] | None = None) -> list[dict[str, Any]]:
|
|
523
|
+
del questionario, saneados_secao1
|
|
524
|
+
adjustments = _adjustment_rows(ajustes_pos_avaliacao_evidencias)
|
|
525
|
+
result: list[dict[str, Any]] = []
|
|
526
|
+
for record in _jsonl(consolidado):
|
|
527
|
+
for conclusion in (record.get("result") or {}).get("conclusoes") or []:
|
|
528
|
+
if not isinstance(conclusion, Mapping):
|
|
529
|
+
continue
|
|
530
|
+
auditado = texto(record.get("auditado")).upper()
|
|
531
|
+
codigo = texto(conclusion.get("item_codigo") or record.get("codigo"))
|
|
532
|
+
source = adjustments.get((auditado, codigo)) or {}
|
|
533
|
+
original = texto(source.get("Resposta afirmada"))
|
|
534
|
+
result.append(_base_row(auditado=auditado, codigo=codigo, resposta_afirmada=original, resposta_anterior=original, resposta_ajustada=original, origem="secao_2_reavaliacao", source="avaliacao_evidencias_ajustes", resultado=conclusion.get("estado"), justificativa=conclusion.get("justificativa"), case_id=record.get("case_id"), identity=record.get("identity")))
|
|
535
|
+
return result
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def gravar_ajustes_combinados_xlsx(path: Path, *, ajustes_secao1: list[Mapping[str, Any]], ajustes_secao2: list[Mapping[str, Any]], pendencias: list[Mapping[str, Any]]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
|
539
|
+
from openpyxl import Workbook
|
|
540
|
+
merged: dict[tuple[str, str], dict[str, Any]] = {}
|
|
541
|
+
for row in [*ajustes_secao1, *ajustes_secao2]:
|
|
542
|
+
key = (texto(row.get("Auditado")).upper(), texto(row.get("Código do item avaliado")))
|
|
543
|
+
if key not in merged:
|
|
544
|
+
merged[key] = dict(row)
|
|
545
|
+
finals = list(merged.values())
|
|
546
|
+
workbook = Workbook()
|
|
547
|
+
sheet = workbook.active
|
|
548
|
+
headers = list(dict.fromkeys(key for row in [*finals, *pendencias] for key in row)) or ["Auditado", "Código do item avaliado"]
|
|
549
|
+
sheet.append(headers)
|
|
550
|
+
|
|
551
|
+
def excel_value(value: Any) -> Any:
|
|
552
|
+
if isinstance(value, (Mapping, list, tuple, set)):
|
|
553
|
+
return json.dumps(value, ensure_ascii=False, sort_keys=True)
|
|
554
|
+
return value
|
|
555
|
+
|
|
556
|
+
for row in [*finals, *pendencias]:
|
|
557
|
+
sheet.append([excel_value(row.get(header, "")) for header in headers])
|
|
558
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
559
|
+
workbook.save(path)
|
|
560
|
+
workbook.close()
|
|
561
|
+
return finals, [dict(row) for row in pendencias]
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
__all__ = [
|
|
565
|
+
"adjust_responses",
|
|
566
|
+
"formatar_violacoes",
|
|
567
|
+
"gravar_ajustes_combinados_xlsx",
|
|
568
|
+
"mapear_ajustes_secao1",
|
|
569
|
+
"mapear_ajustes_secao2",
|
|
570
|
+
"validar_resultado_no_escopo",
|
|
571
|
+
]
|