argos-cli 0.3.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. argos/__init__.py +5 -0
  2. argos/__main__.py +4 -0
  3. argos/adapters/__init__.py +9 -0
  4. argos/adapters/_libreoffice_worker.py +111 -0
  5. argos/adapters/ai.py +1506 -0
  6. argos/adapters/ai_remote.py +654 -0
  7. argos/adapters/attachment_conversion.py +132 -0
  8. argos/adapters/capabilities.py +31 -0
  9. argos/adapters/chart_render.py +72 -0
  10. argos/adapters/docx_pdf.py +2953 -0
  11. argos/adapters/limesurvey.py +1079 -0
  12. argos/adapters/model_call.py +274 -0
  13. argos/adapters/report_publication.py +1530 -0
  14. argos/adapters/url_fetch.py +146 -0
  15. argos/adapters/xlsx.py +454 -0
  16. argos/analytics.py +731 -0
  17. argos/assets.py +257 -0
  18. argos/audit_result.py +369 -0
  19. argos/booleans.py +105 -0
  20. argos/catalog.py +1205 -0
  21. argos/cli.py +606 -0
  22. argos/contracts.py +532 -0
  23. argos/core.py +325 -0
  24. argos/default_skills/README.md +23 -0
  25. argos/default_skills/criar-matriz-planejamento/SKILL.md +200 -0
  26. argos/default_skills/elaborar-survey-limesurvey/SKILL.md +106 -0
  27. argos/default_skills/operar-argos/SKILL.md +74 -0
  28. argos/default_skills/verificar-diretrizes-fiscalizacao/SKILL.md +129 -0
  29. argos/default_skills/verificar-diretrizes-fiscalizacao/assets/relatorio-avaliacao.md +54 -0
  30. argos/default_skills/verificar-diretrizes-fiscalizacao/references/contrato-saidas.md +36 -0
  31. argos/default_skills/verificar-diretrizes-fiscalizacao/references/papeis-das-pastas.md +37 -0
  32. argos/default_skills/verificar-diretrizes-fiscalizacao/references/roteiro-verificacoes.md +27 -0
  33. argos/default_skills/verificar-diretrizes-fiscalizacao/scripts/avaliacao.py +253 -0
  34. argos/engines/__init__.py +3 -0
  35. argos/engines/adjustments.py +571 -0
  36. argos/engines/analytics.py +195 -0
  37. argos/engines/audit.py +2730 -0
  38. argos/engines/evaluation.py +6088 -0
  39. argos/engines/index.py +1683 -0
  40. argos/engines/matrix.py +5736 -0
  41. argos/engines/matrix_html.py +698 -0
  42. argos/engines/model_request.py +201 -0
  43. argos/engines/report_document.py +137 -0
  44. argos/engines/reports.py +1200 -0
  45. argos/engines/survey.py +4445 -0
  46. argos/envfile.py +53 -0
  47. argos/errors.py +29 -0
  48. argos/evidence_staging.py +293 -0
  49. argos/executions.py +565 -0
  50. argos/findings_matrix.py +2549 -0
  51. argos/fingerprints.py +487 -0
  52. argos/index_dsl.py +2100 -0
  53. argos/matrix_markdown.py +475 -0
  54. argos/matrix_widths.py +280 -0
  55. argos/pipeline.py +1745 -0
  56. argos/products.py +220 -0
  57. argos/progress.py +221 -0
  58. argos/project.py +608 -0
  59. argos/report_config.py +158 -0
  60. argos/resources/ESPECIFICACAO_MARKDOWN_MATRIZ_ACHADOS.md +539 -0
  61. argos/resources/ESPECIFICACAO_MARKDOWN_MATRIZ_PLANEJAMENTO.md +1000 -0
  62. argos/resources/ESPECIFICACAO_UNIFICADA_MATRIZES_V1_3.md +1142 -0
  63. argos/resources/anexo-evidencias-base.docx +0 -0
  64. argos/resources/argos-index-dsl-v1.schema.json +539 -0
  65. argos/resources/argos-report-config-v1.schema.json +113 -0
  66. argos/resources/diretrizes-projeto.md +476 -0
  67. argos/resources/env.example +37 -0
  68. argos/resources/exemplos/matriz_achados_boilerplate.md +61 -0
  69. argos/resources/exemplos/matriz_achados_draft.md +106 -0
  70. argos/resources/exemplos/matriz_achados_larguras_v1_3.md +114 -0
  71. argos/resources/exemplos/matriz_achados_v1_3.md +107 -0
  72. argos/resources/exemplos/matriz_planejamento_boilerplate.md +64 -0
  73. argos/resources/exemplos/matriz_planejamento_larguras_v1_3.md +115 -0
  74. argos/resources/exemplos/matriz_planejamento_v1_3.md +108 -0
  75. argos/resources/template-base-estilos-sigiloso.docx +0 -0
  76. argos/resources/template-base-estilos.docx +0 -0
  77. argos/resources/template-matriz-planejamento.docx +0 -0
  78. argos/resources/template-relatorio-consolidado-comum.docx +0 -0
  79. argos/resources/template-relatorio-consolidado-institucional.docx +0 -0
  80. argos/response_profiles.py +856 -0
  81. argos/scheduler.py +142 -0
  82. argos/status.py +367 -0
  83. argos/store.py +1228 -0
  84. argos/survey_collection.py +832 -0
  85. argos/telemetry.py +84 -0
  86. argos/tui.py +1262 -0
  87. argos/tui.tcss +827 -0
  88. argos/tui_models.py +466 -0
  89. argos/tui_path.py +155 -0
  90. argos/tui_widgets.py +482 -0
  91. argos/version.py +3 -0
  92. argos_cli-0.3.1.dist-info/METADATA +570 -0
  93. argos_cli-0.3.1.dist-info/RECORD +96 -0
  94. argos_cli-0.3.1.dist-info/WHEEL +5 -0
  95. argos_cli-0.3.1.dist-info/entry_points.txt +2 -0
  96. argos_cli-0.3.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1079 @@
1
+ """Exportação, download e coleta de respostas do LimeSurvey."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import zipfile
7
+ from dataclasses import dataclass
8
+ from html.parser import HTMLParser
9
+ from pathlib import Path
10
+ from typing import Any
11
+ from urllib.parse import unquote, urlsplit
12
+ from ..errors import InputValidationError
13
+ from .xlsx import workbook_records
14
+ import datetime
15
+ import math
16
+ import os
17
+ from typing import Iterable, Mapping, Protocol
18
+ import shutil
19
+ from ..core import OperationContext, OperationResult, ProductDraft, ResourceProfile, ScheduledUnit, canonical_json, sha256_bytes, sha256_file
20
+ from ..survey_collection import (
21
+ CURRENT_STATUS_ATUAL,
22
+ DOWNLOADED,
23
+ ERROR,
24
+ NO_ATTACHMENT,
25
+ REUSE,
26
+ REVALIDATED,
27
+ UPDATED,
28
+ SurveyLayout,
29
+ apply_execution,
30
+ archive_current,
31
+ content_fingerprint,
32
+ current_key,
33
+ current_path_for,
34
+ decide_attachment,
35
+ execution_manifest_bytes,
36
+ execution_row,
37
+ install_stable,
38
+ load_or_rebuild_manifest,
39
+ manifest_bytes,
40
+ observation_row,
41
+ quarantine_current,
42
+ relative_for,
43
+ restore_current,
44
+ snapshot_manifest,
45
+ snapshot_responses,
46
+ snapshot_responses_labels,
47
+ consolidated_paths,
48
+ survey_lock,
49
+ verify_file,
50
+ version_row,
51
+ write_bytes_atomic,
52
+ )
53
+ from ..errors import MissingInputError
54
+
55
+
56
+ def survey_address(base_url: str, survey_id: Any) -> tuple[str, str]:
57
+ """Valida a instalação e o SID, sem aceitar cookies ou query na URL."""
58
+ parts = urlsplit(str(base_url).strip())
59
+ if (parts.scheme not in {"http", "https"} or not parts.hostname
60
+ or parts.username or parts.password or parts.query or parts.fragment):
61
+ raise InputValidationError("base_url deve ser a URL HTTP(S) da instalação, sem credenciais ou query")
62
+ sid = str(survey_id).strip()
63
+ if not re.fullmatch(r"[1-9][0-9]*", sid):
64
+ raise InputValidationError("survey_id deve ser um inteiro positivo")
65
+ base = str(base_url).strip().rstrip("/")
66
+ if not base.endswith("/index.php"):
67
+ base += "/index.php"
68
+ return base, sid
69
+
70
+
71
+ class _ExportParser(HTMLParser):
72
+ def __init__(self) -> None:
73
+ super().__init__()
74
+ self.values: dict[str, str] = {}
75
+ self.options: dict[str, list[str]] = {}
76
+ self.selected: dict[str, str] = {}
77
+ self.select = ""
78
+ self.login = False
79
+
80
+ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
81
+ attributes = dict(attrs)
82
+ name = attributes.get("name") or ""
83
+ if tag == "input":
84
+ if attributes.get("type") == "password":
85
+ self.login = True
86
+ if name in {"YII_CSRF_TOKEN", "export_from", "export_to", "exportlang"}:
87
+ self.values[name] = attributes.get("value") or ""
88
+ if name == "attribute_select[]" and "disabled" not in attributes:
89
+ self.options.setdefault(name, []).append(attributes.get("value") or "")
90
+ elif tag == "select":
91
+ self.select = name
92
+ self.options.setdefault(name, [])
93
+ elif tag == "option" and self.select and "disabled" not in attributes:
94
+ value = attributes.get("value")
95
+ if value is not None:
96
+ self.options[self.select].append(value)
97
+ if "selected" in attributes:
98
+ self.selected[self.select] = value
99
+
100
+ def handle_endtag(self, tag: str) -> None:
101
+ if tag == "select":
102
+ self.select = ""
103
+
104
+
105
+ @dataclass(frozen=True, repr=False)
106
+ class ExportForm:
107
+ columns: tuple[str, ...]
108
+ attributes: tuple[str, ...]
109
+ language: str
110
+ first: str
111
+ last: str
112
+ csrf: str
113
+
114
+ def payload(self, sid: str, kind: str, response_id: str | None = None,
115
+ answers: str = "long") -> list[tuple[str, str]]:
116
+ # `headstyle` define só o cabeçalho das colunas; os valores das respostas
117
+ # (código ou texto da alternativa) dependem de `answers` (short | long).
118
+ data = {
119
+ "YII_CSRF_TOKEN": self.csrf, "type": kind, "sid": sid,
120
+ "completionstate": "complete", "exportlang": self.language,
121
+ "export_from": self.first, "export_to": self.last,
122
+ "answers": answers, "headstyle": "code" if kind == "xls" else "full",
123
+ "csvfieldseparator": ",", "maskequations": "Y", "striphtmlcode": "1",
124
+ "headspacetounderscores": "0", "abbreviatedtext": "0", "emcode": "0",
125
+ "abbreviatedtextto": "15", "codetextseparator": ". ",
126
+ }
127
+ if response_id is not None:
128
+ # O filtro e o intervalo coincidem para impedir PDFs com várias respostas.
129
+ data.update(response_id=response_id, export_from=response_id, export_to=response_id)
130
+ return (list(data.items()) + [("colselect[]", value) for value in self.columns]
131
+ + [("attribute_select[]", value) for value in self.attributes])
132
+
133
+
134
+ def discover_form(session: Any, base: str, sid: str, csrf_cookie: str,
135
+ language: str | None = None) -> ExportForm:
136
+ url = f"{base}/admin/export/sa/exportresults/surveyid/{sid}"
137
+ with session.get(url, timeout=DOWNLOAD_TIMEOUT, allow_redirects=True) as response:
138
+ response.raise_for_status()
139
+ parser = _ExportParser()
140
+ parser.feed(response.text)
141
+ if parser.login:
142
+ raise SessionExpiredError("Sessão LimeSurvey expirada; renove as credenciais no ambiente")
143
+ columns = tuple(dict.fromkeys(parser.options.get("colselect[]", [])))
144
+ if "id" not in columns or "submitdate" not in columns:
145
+ raise InputValidationError("formulário de exportação sem id/submitdate; confira permissões e versão do LimeSurvey")
146
+ languages = parser.options.get("exportlang", [])
147
+ if language and language not in languages:
148
+ raise InputValidationError("language não está disponível no formulário do survey")
149
+ chosen = language or parser.selected.get("exportlang") or parser.values.get("exportlang")
150
+ chosen = chosen or (languages[0] if languages else "")
151
+ if not chosen:
152
+ raise InputValidationError("idioma de exportação não encontrado no formulário")
153
+ first, last = parser.values.get("export_from", ""), parser.values.get("export_to", "")
154
+ if not first.isdigit() or not last.isdigit():
155
+ raise InputValidationError("intervalo de respostas não encontrado no formulário de exportação")
156
+ return ExportForm(columns, tuple(dict.fromkeys(parser.options.get("attribute_select[]", []))),
157
+ chosen, first, last, parser.values.get("YII_CSRF_TOKEN") or unquote(csrf_cookie))
158
+
159
+
160
+ def _save_response(response: Any, destination: Path, kind: str) -> None:
161
+ response.raise_for_status()
162
+ if "text/html" in str(response.headers.get("Content-Type", "")).lower():
163
+ # Nunca incorporar HTML (pode conter CSRF/cookies) em erros ou produtos.
164
+ parser = _ExportParser()
165
+ parser.feed(response.text)
166
+ if parser.login:
167
+ raise SessionExpiredError("Sessão LimeSurvey expirada; renove as credenciais no ambiente")
168
+ raise InputValidationError("LimeSurvey retornou HTML em vez do arquivo; confira permissões e disponibilidade")
169
+ try:
170
+ with destination.open("wb") as output:
171
+ for chunk in response.iter_content(chunk_size=DOWNLOAD_CHUNK_SIZE):
172
+ if chunk:
173
+ output.write(chunk)
174
+ if kind == "pdf":
175
+ with destination.open("rb") as source:
176
+ if source.read(5) != b"%PDF-":
177
+ raise InputValidationError("exportação não é um PDF válido")
178
+ else:
179
+ with zipfile.ZipFile(destination) as archive:
180
+ if kind == "xls" and "xl/workbook.xml" not in archive.namelist():
181
+ raise InputValidationError("exportação Excel não é XLSX; esta versão não oferece o formato esperado")
182
+ if archive.testzip() is not None:
183
+ raise InputValidationError("arquivo ZIP/XLSX corrompido")
184
+ except Exception:
185
+ destination.unlink(missing_ok=True)
186
+ raise
187
+
188
+
189
+ def export_response(session: Any, base: str, sid: str, form: ExportForm,
190
+ destination: Path, kind: str, response_id: str | None = None,
191
+ answers: str = "long") -> None:
192
+ url = f"{base}/admin/export/sa/exportresults/surveyid/{sid}"
193
+ referer = url if response_id is None else f"{url}/id/{response_id}"
194
+ with session.post(url, data=form.payload(sid, kind, response_id, answers),
195
+ headers={"Referer": referer, "Origin": f"{urlsplit(base).scheme}://{urlsplit(base).netloc}"},
196
+ stream=True, timeout=DOWNLOAD_TIMEOUT, allow_redirects=True) as response:
197
+ _save_response(response, destination, kind)
198
+
199
+
200
+ def download_evidence(session: Any, base: str, sid: str, response_id: str, destination: Path) -> None:
201
+ # Os nomes de parâmetros variam com a versão; sem o ID correto pode vir o survey inteiro.
202
+ urls = (f"{base}/responses/downloadfiles/surveyId/{sid}/responseIds/{response_id}",
203
+ f"{base}/admin/responses/sa/actionDownloadfiles/surveyid/{sid}/sResponseId/{response_id}")
204
+ for index, url in enumerate(urls):
205
+ with session.get(url, stream=True, timeout=DOWNLOAD_TIMEOUT, allow_redirects=True) as response:
206
+ if response.status_code == 404 and index == 0:
207
+ continue
208
+ _save_response(response, destination, "zip")
209
+ return
210
+
211
+
212
+ def _source_fingerprint(row: Mapping[str, Any]) -> str:
213
+ """Hash estável da linha exportada, usado para evitar redownload."""
214
+ normalized: dict[str, Any] = {}
215
+ for key, value in row.items():
216
+ if isinstance(value, (datetime.datetime, datetime.date)):
217
+ value = value.isoformat()
218
+ elif isinstance(value, float) and value.is_integer():
219
+ value = int(value)
220
+ elif value is None:
221
+ value = ""
222
+ else:
223
+ value = str(value)
224
+ normalized[str(key)] = value
225
+ return sha256_bytes(canonical_json(normalized).encode("utf-8"))
226
+
227
+
228
+ def submitted_responses(path: Path, coluna_auditado: str | None = None) -> list[dict[str, Any]]:
229
+ headers, rows = workbook_records(path)
230
+ names = {str(name).strip().casefold(): name for name in headers}
231
+ if "id" not in names or "submitdate" not in names:
232
+ raise InputValidationError("XLSX exportado sem as colunas id/submitdate")
233
+ selected_column = coluna_auditado or "firstname"
234
+ label_column = names.get(selected_column.casefold())
235
+ if selected_column.casefold() != "firstname" and label_column is None:
236
+ raise InputValidationError("coluna_auditado não existe no XLSX exportado")
237
+ submitted: list[dict[str, Any]] = []
238
+ seen: set[str] = set()
239
+ for row in rows:
240
+ if not row.get(names["submitdate"]):
241
+ continue
242
+ raw_id = row.get(names["id"])
243
+ response_id = str(int(raw_id)) if isinstance(raw_id, float) and raw_id.is_integer() else str(raw_id)
244
+ if not re.fullmatch(r"[1-9][0-9]*", response_id) or response_id in seen:
245
+ raise InputValidationError("XLSX contém ID de resposta inválido ou repetido")
246
+ seen.add(response_id)
247
+ label = str(row.get(label_column) or "").strip() if label_column else ""
248
+ counts = [value for key, value in row.items()
249
+ if re.search(r"(?:_filecount|\[filecount\])$", str(key), re.IGNORECASE)]
250
+ has_evidence = None
251
+ if counts:
252
+ try:
253
+ has_evidence = any(float(value or 0) > 0 for value in counts)
254
+ except (TypeError, ValueError):
255
+ pass # contagem não reconhecida: consultar o ZIP no servidor
256
+ submitted.append({"id": response_id, "auditado": label or f"resposta-{response_id}",
257
+ "submitdate": str(row[names["submitdate"]]), "has_evidence": has_evidence,
258
+ "source_fingerprint": _source_fingerprint(row)})
259
+ return submitted
260
+
261
+
262
+ DOWNLOAD_REQUIRED_COLUMNS = frozenset({"id", "orgao", "datestamp", "url", "completed"})
263
+ DOWNLOAD_TIMEOUT = 180
264
+ DOWNLOAD_CHUNK_SIZE = 1024 * 1024
265
+ LOGIN_INDICATORS = ("login", "username", "password", "loginform")
266
+
267
+ # Cabeçalhos de navegador usados pelo coletor legado.
268
+ DOWNLOAD_HEADERS = {
269
+ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
270
+ "Accept-Language": "pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7",
271
+ "Cache-Control": "no-cache",
272
+ "Pragma": "no-cache",
273
+ "Upgrade-Insecure-Requests": "1",
274
+ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36",
275
+ }
276
+
277
+ # Caracteres inválidos em nomes de arquivo Windows (extração).
278
+ _INVALID_CHARS = re.compile(r'[<>:"|?*\x00-\x1f]')
279
+ _MAX_NAME_LEN = 200
280
+
281
+
282
+ def normalize_download_url(value: Any) -> str:
283
+ """Retorna URL utilizável ou vazio quando a resposta não possui anexo."""
284
+ if value is None:
285
+ return ""
286
+ if isinstance(value, float) and math.isnan(value):
287
+ return ""
288
+ url = str(value).strip()
289
+ if url.lower() in {"", "nan", "none", "<na>"}:
290
+ return ""
291
+ return url
292
+
293
+
294
+ def clean_text(value: Any) -> str:
295
+ texto = (
296
+ ""
297
+ if value is None or (isinstance(value, float) and math.isnan(value))
298
+ else str(value).strip()
299
+ )
300
+ texto = re.sub(r'[\\/:*?"<>|]', "_", texto)
301
+ texto = re.sub(r"\s+", " ", texto)
302
+ return texto or "SEM_VALOR"
303
+
304
+
305
+ def clean_datestamp(value: Any) -> str:
306
+ datestamp = (
307
+ ""
308
+ if value is None or (isinstance(value, float) and math.isnan(value))
309
+ else str(value).strip()
310
+ )
311
+ datestamp = datestamp.replace(".", "-")
312
+ datestamp = datestamp.replace(":", "")
313
+ datestamp = re.sub(r"\s+", "_", datestamp)
314
+ datestamp = re.sub(r'[\\/:*?"<>|]', "_", datestamp)
315
+ return datestamp or "SEM_DATA"
316
+
317
+
318
+ def destination_name(orgao: Any, datestamp: Any, id_resposta: Any, output_dir: Path) -> Path:
319
+ orgao_limpo = clean_text(orgao)
320
+ data_limpa = clean_datestamp(datestamp)
321
+ id_limpo = clean_text(id_resposta)
322
+ return output_dir / f"{orgao_limpo}_{data_limpa}_id{id_limpo}.zip"
323
+
324
+
325
+ def read_download_table(path: Path) -> tuple[list[str], list[dict[str, Any]]]:
326
+ """Lê a relação de respostas e valida as colunas obrigatórias."""
327
+
328
+ headers, rows = workbook_records(path)
329
+ present = {str(header).strip().casefold() for header in headers if header}
330
+ faltantes = sorted(
331
+ str(column).casefold() for column in DOWNLOAD_REQUIRED_COLUMNS if column not in present
332
+ )
333
+ if faltantes:
334
+ raise InputValidationError(f"Colunas ausentes na planilha: {faltantes}")
335
+ return headers, rows
336
+
337
+
338
+ def parse_datestamp(value: Any) -> datetime.datetime:
339
+ texto = (
340
+ ""
341
+ if value is None or (isinstance(value, float) and math.isnan(value))
342
+ else str(value).strip()
343
+ )
344
+ normalizado = texto.replace(".", "/")
345
+ try:
346
+ return datetime.datetime.strptime(normalizado, "%d/%m/%Y %H:%M:%S")
347
+ except ValueError as exc:
348
+ raise InputValidationError(f"Datas inválidas na coluna datestamp: {texto}") from exc
349
+
350
+
351
+ def attach_parsed_dates(rows: Iterable[Mapping[str, Any]]) -> None:
352
+ """Anexa ``parsed_date`` a cada linha, falhando com até 5 exemplos inválidos."""
353
+ invalidas: list[str] = []
354
+ for row in rows:
355
+ try:
356
+ row["parsed_date"] = parse_datestamp(row.get("datestamp"))
357
+ except InputValidationError:
358
+ invalidas.append(str(row.get("datestamp")))
359
+ if invalidas:
360
+ exemplos = ", ".join(invalidas[:5])
361
+ raise InputValidationError(f"Datas inválidas na coluna datestamp: {exemplos}")
362
+
363
+
364
+ def latest_row_keys(rows: Iterable[Mapping[str, Any]], *, by: str = "orgao") -> set[int]:
365
+ """Índices do primeiro registro que atinge a data máxima por órgão.
366
+
367
+ Espelha ``groupby(orgao).idxmax()``: em empate de data, o primeiro
368
+ registro vence; órgãos sem valor ficam fora do conjunto.
369
+ """
370
+ melhor: dict[str, tuple[datetime.datetime, int]] = {}
371
+ for index, row in enumerate(rows):
372
+ chave = str(row.get(by) or "").strip()
373
+ data = row.get("parsed_date")
374
+ if not chave or data is None:
375
+ continue
376
+ if chave not in melhor or data > melhor[chave][0]:
377
+ melhor[chave] = (data, index)
378
+ return {valor[1] for valor in melhor.values()}
379
+
380
+
381
+ class SessionExpiredError(InputValidationError):
382
+ """A sessão do LimeSurvey expirou (redirecionou para a tela de login)."""
383
+
384
+
385
+ class DownloadSession(Protocol):
386
+ def get(self, url: str, *, stream: bool = False, timeout: int, allow_redirects: bool = True) -> Any: ...
387
+
388
+
389
+ def requests_session(phpsessid: str, yii_csrf_token: str) -> Any:
390
+ """Constrói a sessão HTTP real com os cookies administrativos."""
391
+ try:
392
+ import requests
393
+ except ImportError as exc: # pragma: no cover - opcional no pacote base
394
+ raise InputValidationError(
395
+ "a coleta de anexos requer requests; instale argos-cli[downloads]"
396
+ ) from exc
397
+ session = requests.Session()
398
+ session.headers.update(dict(DOWNLOAD_HEADERS))
399
+ session.cookies.update(
400
+ {
401
+ "cookieconsent_status": "allow",
402
+ "PHPSESSID": phpsessid,
403
+ "YII_CSRF_TOKEN": yii_csrf_token,
404
+ }
405
+ )
406
+ return session
407
+
408
+
409
+ def download_file(session: DownloadSession, url: str, destination: Path) -> None:
410
+ """Baixa o anexo para disco, detectando redirecionamento para login."""
411
+ with session.get(url, stream=True, timeout=DOWNLOAD_TIMEOUT, allow_redirects=True) as resp:
412
+ resp.raise_for_status()
413
+
414
+ content_type = str(resp.headers.get("Content-Type", "")).lower()
415
+
416
+ if "text/html" in content_type:
417
+ # Texto completo para buscar indicadores de expiração de sessão.
418
+ texto = resp.text.lower()
419
+
420
+ if any(marcador in texto for marcador in LOGIN_INDICATORS):
421
+ raise SessionExpiredError(
422
+ "Sessão expirada (LimeSurvey redirecionou para tela de login). "
423
+ "Forneça novos valores por parâmetro ou variável de ambiente."
424
+ )
425
+
426
+ title_match = re.search(r"<title>(.*?)</title>", resp.text, re.IGNORECASE | re.DOTALL)
427
+ title = title_match.group(1).strip() if title_match else "Sem título"
428
+ snippet = resp.text[:150].replace("\n", " ").strip()
429
+ raise RuntimeError(
430
+ f"Resposta HTML recebida (HTTP {resp.status_code}, Content-Type: '{content_type}'). "
431
+ f"Título: '{title}'. Início: '{snippet}...'"
432
+ )
433
+
434
+ with open(destination, "wb") as stream:
435
+ for chunk in resp.iter_content(chunk_size=DOWNLOAD_CHUNK_SIZE):
436
+ if chunk:
437
+ stream.write(chunk)
438
+
439
+
440
+ def decide_download(
441
+ index: int,
442
+ row: Mapping[str, Any],
443
+ *,
444
+ only_latest: bool,
445
+ latest: set[int],
446
+ overwrite: bool,
447
+ output_dir: Path,
448
+ ) -> tuple[str, Path]:
449
+ """Status planejado do download e destino, na ordem de decisão do legado."""
450
+ orgao = str(row.get("orgao") or "")
451
+ destino = destination_name(orgao, row.get("datestamp"), row.get("id"), output_dir)
452
+ if only_latest and index not in latest:
453
+ return "pulado_nao_mais_recente", destino
454
+ if str(row.get("completed") or "").strip().lower() != "sim":
455
+ return "pulado_incompleto", destino
456
+ if not normalize_download_url(row.get("url")):
457
+ return "sem_anexo", destino
458
+ if destino.exists() and destino.stat().st_size > 0 and not overwrite:
459
+ return "pulado_existente", destino
460
+ return "baixar", destino
461
+
462
+
463
+ def collect_attachments(
464
+ session: DownloadSession,
465
+ rows: Iterable[Mapping[str, Any]],
466
+ output_dir: Path,
467
+ *,
468
+ only_latest: bool = True,
469
+ overwrite: bool = False,
470
+ ) -> list[dict[str, Any]]:
471
+ """Baixa os anexos, registrando um registro de manifesto por linha."""
472
+ output_dir.mkdir(parents=True, exist_ok=True)
473
+ linhas = [dict(row) for row in rows]
474
+ latest = latest_row_keys(linhas) if only_latest else set()
475
+ manifest: list[dict[str, Any]] = []
476
+ for index, row in enumerate(linhas):
477
+ orgao = str(row.get("orgao") or "")
478
+ status, destino = decide_download(
479
+ index,
480
+ row,
481
+ only_latest=only_latest,
482
+ latest=latest,
483
+ overwrite=overwrite,
484
+ output_dir=output_dir,
485
+ )
486
+ entrada = {
487
+ "id": row.get("id"),
488
+ "orgao": orgao,
489
+ "datestamp": row.get("datestamp"),
490
+ "status": status,
491
+ "destino": str(destino),
492
+ "erro": "",
493
+ }
494
+ if status != "baixar":
495
+ manifest.append(entrada)
496
+ continue
497
+ try:
498
+ download_file(session, str(row.get("url")).strip(), destino)
499
+ entrada["status"] = "baixado"
500
+ except SessionExpiredError:
501
+ raise
502
+ except Exception as exc: # noqa: BLE001 - erro por arquivo não aborta a coleta
503
+ entrada["status"] = "erro"
504
+ entrada["erro"] = f"{type(exc).__name__}: {exc}"
505
+ manifest.append(entrada)
506
+ return manifest
507
+
508
+
509
+ def sanitize_filename(name: str) -> str:
510
+ """Normaliza o nome para ser válido no Windows e no Python."""
511
+ name = str(name).replace("/", "_").replace("\\", "_")
512
+ name = _INVALID_CHARS.sub("_", name)
513
+ name = name.strip(" .")
514
+ return name or "arquivo"
515
+
516
+
517
+ def split_name(name: str) -> tuple[str, str]:
518
+ """Separa o nome base da extensão final (após o último ponto)."""
519
+ if "." in name[1:]: # ignora ponto inicial
520
+ idx = name.rfind(".")
521
+ return name[:idx], name[idx:]
522
+ return name, ""
523
+
524
+
525
+ def _decode_member_name(raw_name: str) -> str:
526
+ decoded_name = raw_name
527
+ for enc in ("utf-8", "cp437", "cp1252", "latin-1"):
528
+ try:
529
+ if isinstance(raw_name, bytes):
530
+ decoded_name = raw_name.decode(enc)
531
+ else:
532
+ decoded_name = raw_name.encode("cp437").decode(enc)
533
+ break
534
+ except (UnicodeDecodeError, UnicodeEncodeError):
535
+ continue
536
+ return decoded_name
537
+
538
+
539
+ def extract_zip(zip_path: Path, target_dir: Path) -> None:
540
+ """Extrai o ZIP sanitizando nomes e limitando o tamanho dos nomes."""
541
+ with zipfile.ZipFile(zip_path, "r") as archive:
542
+ for info in archive.infolist():
543
+ if info.is_dir():
544
+ continue
545
+
546
+ safe_name = sanitize_filename(_decode_member_name(info.filename))
547
+
548
+ stem, suffix = split_name(safe_name)
549
+ suffix = suffix.lower()
550
+ max_len = _MAX_NAME_LEN
551
+ if os.name == "nt":
552
+ max_len = min(max_len, max(32, 245 - len(str(target_dir.resolve()))))
553
+ if len(stem) + len(suffix) > max_len:
554
+ stem = stem[: max_len - len(suffix)]
555
+ safe_name = stem + suffix
556
+
557
+ dest_path = target_dir / safe_name
558
+ dest_path.parent.mkdir(parents=True, exist_ok=True)
559
+
560
+ with archive.open(info) as src, open(dest_path, "wb") as dst:
561
+ dst.write(src.read())
562
+
563
+
564
+ def extract_attachments(output_dir: Path, extract_dir: Path) -> list[dict[str, Any]]:
565
+ """Extrai todos os ZIPs do diretório em pastas por auditado."""
566
+ extract_dir.mkdir(parents=True, exist_ok=True)
567
+ zip_files = sorted(output_dir.glob("*.zip"))
568
+ manifest: list[dict[str, Any]] = []
569
+ for zip_path in zip_files:
570
+ # O prefixo anterior ao primeiro '_' identifica o auditado.
571
+ auditado = zip_path.name.split("_")[0]
572
+ try:
573
+ extract_zip(zip_path, extract_dir / auditado)
574
+ status, erro = "extraido", ""
575
+ except Exception as exc: # noqa: BLE001 - erro por arquivo não aborta a passada
576
+ status, erro = "erro", f"{type(exc).__name__}: {exc}"
577
+ manifest.append({"zip": zip_path.name, "auditado": auditado, "status": status, "erro": erro})
578
+ return manifest
579
+
580
+
581
+ XLSX_MEDIA = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
582
+
583
+
584
+ def validate_collection(params: Mapping[str, Any]) -> None:
585
+ survey_address(params["base_url"], params["survey_id"])
586
+ collection_resources(params)
587
+
588
+
589
+ def collection_resources(params: Mapping[str, Any]) -> ResourceProfile:
590
+ try:
591
+ jobs = int(params.get("jobs", 1))
592
+ except (TypeError, ValueError) as exc:
593
+ raise InputValidationError("jobs deve ser inteiro positivo") from exc
594
+ if jobs < 1:
595
+ raise InputValidationError("jobs deve ser inteiro positivo")
596
+ return ResourceProfile(memory_mb=max(256, jobs * 256), network_slots=0 if params.get("dry_run") else jobs)
597
+
598
+
599
+ def _session(context: OperationContext, phpsessid: str, csrf: str) -> Any:
600
+ return (context.download_service.build_session(phpsessid, csrf)
601
+ if context.download_service is not None else requests_session(phpsessid, csrf))
602
+
603
+
604
+ def _close(session: Any) -> None:
605
+ if hasattr(session, "close"):
606
+ session.close()
607
+
608
+
609
+ def _extracted_products(context: OperationContext, archive_path: Path, directory: Path,
610
+ metadata: dict[str, Any]) -> list[ProductDraft]:
611
+ products: list[ProductDraft] = []
612
+ seen: set[str] = set()
613
+ with zipfile.ZipFile(archive_path) as archive:
614
+ for member in archive.infolist():
615
+ if member.is_dir():
616
+ continue
617
+ name = sanitize_filename(member.filename)
618
+ stem, suffix = split_name(name)
619
+ # Preservar os prefixos LimeSurvey e a extensão para os decoders.
620
+ suffix = suffix[:32]
621
+ stem = stem[:180 - len(suffix)]
622
+ reserved = {"CON", "PRN", "AUX", "NUL"} | {f"{prefix}{i}" for prefix in ("COM", "LPT") for i in range(1, 10)}
623
+ if stem.split(".")[0].upper() in reserved:
624
+ stem = "_" + stem
625
+ name = stem + suffix
626
+ if name.casefold() in seen:
627
+ raise InputValidationError("nomes de evidências colidem após saneamento; use o ZIP original")
628
+ seen.add(name.casefold())
629
+ staging = context.stage_file()
630
+ with archive.open(member) as source, staging.open("wb") as target:
631
+ shutil.copyfileobj(source, target, length=1024 * 1024)
632
+ products.append(ProductDraft(kind="coleta-survey-evidencia", path=directory / name,
633
+ content=staging, media_type="application/octet-stream", metadata=metadata))
634
+ return products
635
+
636
+
637
+ def collect_survey(context: OperationContext) -> OperationResult:
638
+ """Coleta respostas e anexos em uma pasta dedicada a um único survey."""
639
+ params = context.params
640
+ base, sid = survey_address(params["base_url"], params["survey_id"])
641
+ survey_root = context.path(params["output_dir"])
642
+ if survey_root.exists() and not survey_root.is_dir():
643
+ raise InputValidationError(f"output_dir não é diretório: {survey_root}")
644
+ layout = SurveyLayout.for_execution(survey_root, sid, context.execution_id)
645
+ summary = {
646
+ "survey_id": sid,
647
+ "base_url": base,
648
+ "output_dir": str(layout.root),
649
+ "survey_root": str(layout.root),
650
+ "snapshot_dir": str(layout.snapshot_dir),
651
+ "attachments_dir": str(layout.attachments_dir),
652
+ "versions_dir": str(layout.versions_root),
653
+ "manifesto_geral": str(layout.central_manifest),
654
+ "dry_run": bool(params.get("dry_run")),
655
+ }
656
+ if params.get("dry_run"):
657
+ # A leitura do manifesto é local; não cria diretórios nem abre rede.
658
+ load_or_rebuild_manifest(layout)
659
+ planned = [
660
+ relative_for(layout, snapshot_responses(layout)),
661
+ relative_for(layout, snapshot_responses_labels(layout)),
662
+ *(relative_for(layout, path) for path in consolidated_paths(
663
+ layout, params.get("nome_consolidado") or "respostas-consolidadas")),
664
+ relative_for(layout, layout.snapshot_dir / "manifesto.xlsx"),
665
+ "auditados/<auditado>-r<id>/respostas.pdf",
666
+ "auditados/<auditado>-r<id>/evidencias.zip",
667
+ "manifesto-geral.xlsx",
668
+ ]
669
+ return OperationResult(
670
+ summary={**summary, "planned": planned},
671
+ warnings=("Dry-run local: campos, permissões e IDs só serão verificados na coleta autenticada.",),
672
+ )
673
+ with survey_lock(layout.root):
674
+ return _collect_survey_locked(context, layout, base, sid, summary)
675
+
676
+
677
+ def _collect_survey_locked(
678
+ context: OperationContext,
679
+ layout: SurveyLayout,
680
+ base: str,
681
+ sid: str,
682
+ summary: Mapping[str, Any],
683
+ ) -> OperationResult:
684
+ params = context.params
685
+ # Valida o nome antes de qualquer acesso à rede.
686
+ consolidated, consolidated_labels = consolidated_paths(
687
+ layout, params.get("nome_consolidado") or "respostas-consolidadas")
688
+ if layout.snapshot_dir.exists():
689
+ raise InputValidationError(
690
+ "o snapshot desta execução já existe; inicie uma nova coleta em vez de reutilizar a pasta"
691
+ )
692
+ state = load_or_rebuild_manifest(layout)
693
+ refresh = bool(params.get("refresh"))
694
+ extract = bool(params.get("extract"))
695
+ extract_dir = context.optional_path(params.get("extract_dir"))
696
+ if extract and extract_dir is not None:
697
+ extract_dir = extract_dir.resolve()
698
+ if not extract_dir.is_relative_to(layout.root):
699
+ raise InputValidationError("extract_dir deve ficar dentro da pasta do survey")
700
+ if extract_dir == layout.attachments_dir or extract_dir.is_relative_to(layout.attachments_dir):
701
+ raise InputValidationError("extract_dir não pode ficar dentro de auditados/")
702
+
703
+ # Não receber segredos pelo catálogo: nunca persistir cookies ou CSRF do formulário.
704
+ phpsessid = os.environ.get("LIMESURVEY_PHPSESSID", "").strip()
705
+ csrf = os.environ.get("LIMESURVEY_YII_CSRF_TOKEN", "").strip()
706
+ if not phpsessid or not csrf:
707
+ raise MissingInputError("defina LIMESURVEY_PHPSESSID e LIMESURVEY_YII_CSRF_TOKEN exclusivamente no ambiente")
708
+
709
+ session = _session(context, phpsessid, csrf)
710
+ xlsx = context.stage_file(".xlsx")
711
+ xlsx_labels = context.stage_file(".xlsx")
712
+ try:
713
+ form = discover_form(session, base, sid, csrf, params.get("language"))
714
+ # Planilha principal com os códigos das alternativas (Y, A1...) e a
715
+ # complementar com o texto por extenso, no mesmo formato de cabeçalho.
716
+ export_response(session, base, sid, form, xlsx, "xls", answers="short")
717
+ export_response(session, base, sid, form, xlsx_labels, "xls", answers="long")
718
+ cookies = session.cookies.copy() if hasattr(session, "cookies") else None
719
+ except InputValidationError:
720
+ raise
721
+ except Exception as exc: # noqa: BLE001 - redirects/erros HTTP podem carregar tokens
722
+ raise InputValidationError(
723
+ f"Falha ao obter a exportação XLSX ({type(exc).__name__}); confira sessão, permissões e formato"
724
+ ) from None
725
+ finally:
726
+ _close(session)
727
+
728
+ # A impressão digital das linhas vem da exportação por extenso, que era a única
729
+ # até aqui: assim os manifestos existentes não forçam novo download dos anexos.
730
+ rows = submitted_responses(xlsx_labels, params.get("coluna_auditado"))
731
+ source_hash = sha256_file(xlsx)
732
+ labels_hash = sha256_file(xlsx_labels)
733
+ common = {
734
+ "survey_id": sid,
735
+ "responses_sha256": source_hash,
736
+ "responses_labels_sha256": labels_hash,
737
+ "collection_root": str(layout.root),
738
+ "managed_attachments": True,
739
+ }
740
+ products: list[ProductDraft] = [
741
+ ProductDraft(
742
+ kind="coleta-survey-respostas",
743
+ path=snapshot_responses(layout),
744
+ content=xlsx,
745
+ media_type=XLSX_MEDIA,
746
+ metadata={
747
+ **common,
748
+ "completionstate": "complete",
749
+ "headstyle": "code",
750
+ "answers": "short",
751
+ },
752
+ ),
753
+ ProductDraft(
754
+ kind="coleta-survey-respostas-rotulos",
755
+ path=snapshot_responses_labels(layout),
756
+ content=xlsx_labels,
757
+ media_type=XLSX_MEDIA,
758
+ metadata={
759
+ **common,
760
+ "completionstate": "complete",
761
+ "headstyle": "code",
762
+ "answers": "long",
763
+ },
764
+ ),
765
+ ]
766
+ observations: list[dict[str, Any]] = []
767
+ versions: list[dict[str, Any]] = []
768
+ extracted_products: list[ProductDraft] = []
769
+ extraction_errors: list[dict[str, Any]] = []
770
+
771
+ def register_version(rows: list[dict[str, Any]], response_id: Any, tipo: str, sha: str, path: Path) -> None:
772
+ row = version_row(layout=layout, response_id=response_id, tipo=tipo, sha256=sha, path=path)
773
+ if not any(
774
+ item["response_id"] == row["response_id"]
775
+ and item["tipo"] == row["tipo"]
776
+ and item["sha256"] == row["sha256"]
777
+ for item in rows
778
+ ):
779
+ rows.append(row)
780
+
781
+ def archive_existing(row: Mapping[str, Any], tipo: str, stable: Path,
782
+ current: Mapping[str, Any] | None, version_rows: list[dict[str, Any]]) -> None:
783
+ if not stable.exists():
784
+ return
785
+ expected = str((current or {}).get("sha256") or "")
786
+ if (current or {}).get("status") == CURRENT_STATUS_ATUAL and expected and verify_file(stable, expected):
787
+ archived = archive_current(
788
+ layout,
789
+ response_id=row["id"],
790
+ tipo=tipo,
791
+ stable_path=stable,
792
+ sha256=expected,
793
+ )
794
+ if archived is not None:
795
+ register_version(version_rows, row["id"], tipo, expected, archived)
796
+ return
797
+ quarantine_current(layout, response_id=row["id"], tipo=tipo, stable_path=stable)
798
+
799
+ def install_new(row: Mapping[str, Any], tipo: str, stable: Path, staging: Path,
800
+ sha: str, content: str, current: Mapping[str, Any] | None,
801
+ version_rows: list[dict[str, Any]]) -> str:
802
+ if stable.exists():
803
+ if verify_file(stable, sha):
804
+ # O arquivo já é exatamente a versão baixada (por exemplo, após
805
+ # uma falha entre a instalação e a gravação do manifesto).
806
+ return UPDATED if (current or {}).get("status") == CURRENT_STATUS_ATUAL else DOWNLOADED
807
+ if current and verify_file(stable, str(current.get("sha256") or "")):
808
+ archive_existing(row, tipo, stable, current, version_rows)
809
+ else:
810
+ quarantine_current(layout, response_id=row["id"], tipo=tipo, stable_path=stable)
811
+ install_stable(staging, stable)
812
+ return UPDATED if (current or {}).get("status") == CURRENT_STATUS_ATUAL else DOWNLOADED
813
+
814
+ def collect_one(row: dict[str, Any]) -> dict[str, Any]:
815
+ response_id = row["id"]
816
+ auditado = row["auditado"]
817
+ metadata = {
818
+ **common,
819
+ "response_id": response_id,
820
+ "auditado": auditado,
821
+ }
822
+ local_observations: list[dict[str, Any]] = []
823
+ local_versions: list[dict[str, Any]] = []
824
+ local_products: list[ProductDraft] = []
825
+ local_extraction_errors: list[dict[str, Any]] = []
826
+ # Sessão por unidade: requests.Session não é compartilhada entre threads.
827
+ local = _session(context, phpsessid, csrf)
828
+ try:
829
+ if cookies is not None:
830
+ local.cookies.update(cookies)
831
+ for tipo in ("pdf", "zip"):
832
+ key = current_key(sid, response_id, tipo)
833
+ current = state.current.get(key)
834
+ stable = current_path_for(layout, current, row, tipo)
835
+ action = decide_attachment(
836
+ current=current,
837
+ row=row,
838
+ tipo=tipo,
839
+ stable_path=stable,
840
+ layout=layout,
841
+ refresh=refresh,
842
+ )
843
+ if action == NO_ATTACHMENT:
844
+ if tipo == "zip":
845
+ archive_existing(row, tipo, stable, current, local_versions)
846
+ local_observations.append(
847
+ observation_row(layout=layout, row=row, tipo=tipo, status=NO_ATTACHMENT, path=None)
848
+ )
849
+ continue
850
+ if action == REUSE:
851
+ current_sha = str((current or {}).get("sha256") or "")
852
+ local_observations.append(
853
+ observation_row(
854
+ layout=layout,
855
+ row=row,
856
+ tipo=tipo,
857
+ status=REUSE,
858
+ path=stable,
859
+ sha256=current_sha,
860
+ content=str((current or {}).get("content_fingerprint") or ""),
861
+ )
862
+ )
863
+ continue
864
+ if action == "restaurar" and current is not None:
865
+ current_sha = str(current.get("sha256") or "")
866
+ if stable.exists() and not verify_file(stable, current_sha):
867
+ quarantine_current(layout, response_id=response_id, tipo=tipo, stable_path=stable)
868
+ if restore_current(
869
+ layout,
870
+ response_id=response_id,
871
+ tipo=tipo,
872
+ sha256=current_sha,
873
+ stable_path=stable,
874
+ ):
875
+ local_observations.append(
876
+ observation_row(
877
+ layout=layout,
878
+ row=row,
879
+ tipo=tipo,
880
+ status=DOWNLOADED,
881
+ path=stable,
882
+ sha256=current_sha,
883
+ content=str(current.get("content_fingerprint") or ""),
884
+ )
885
+ )
886
+ continue
887
+
888
+ staging = context.stage_file(f".{tipo}")
889
+ try:
890
+ if tipo == "pdf":
891
+ export_response(local, base, sid, form, staging, tipo, response_id)
892
+ else:
893
+ download_evidence(local, base, sid, response_id, staging)
894
+ with zipfile.ZipFile(staging) as archive:
895
+ if not any(not member.is_dir() for member in archive.infolist()):
896
+ archive_existing(row, tipo, stable, current, local_versions)
897
+ local_observations.append(
898
+ observation_row(
899
+ layout=layout, row=row, tipo=tipo,
900
+ status=NO_ATTACHMENT, path=None,
901
+ )
902
+ )
903
+ continue
904
+ sha = sha256_file(staging)
905
+ content = content_fingerprint(staging, tipo)
906
+ same_content = bool(
907
+ current
908
+ and current.get("status") == CURRENT_STATUS_ATUAL
909
+ and (
910
+ str(current.get("content_fingerprint") or "") == content
911
+ or (
912
+ not current.get("content_fingerprint")
913
+ and str(current.get("sha256") or "") == sha
914
+ )
915
+ )
916
+ )
917
+ if same_content:
918
+ current_sha = str(current.get("sha256") or "")
919
+ if current_sha and verify_file(stable, current_sha):
920
+ local_observations.append(
921
+ observation_row(
922
+ layout=layout, row=row, tipo=tipo, status=REVALIDATED,
923
+ path=stable, sha256=current_sha,
924
+ content=content,
925
+ )
926
+ )
927
+ continue
928
+ if stable.exists():
929
+ quarantine_current(layout, response_id=response_id, tipo=tipo, stable_path=stable)
930
+ install_stable(staging, stable)
931
+ local_observations.append(
932
+ observation_row(
933
+ layout=layout, row=row, tipo=tipo, status=DOWNLOADED,
934
+ path=stable, sha256=sha, content=content,
935
+ )
936
+ )
937
+ continue
938
+
939
+ status = install_new(row, tipo, stable, staging, sha, content, current, local_versions)
940
+ local_observations.append(
941
+ observation_row(
942
+ layout=layout, row=row, tipo=tipo, status=status,
943
+ path=stable, sha256=sha, content=content,
944
+ )
945
+ )
946
+ if tipo == "zip" and extract and status in {DOWNLOADED, UPDATED}:
947
+ target = extract_dir or layout.derived_evidence_dir(auditado, response_id)
948
+ try:
949
+ local_products.extend(
950
+ _extracted_products(context, stable, target, metadata)
951
+ )
952
+ except Exception as exc: # noqa: BLE001 - preservar o ZIP e os demais produtos
953
+ local_extraction_errors.append(
954
+ {
955
+ "id": response_id,
956
+ "auditado": auditado,
957
+ "tipo": "extracao",
958
+ "erro": f"Falha de extração ({type(exc).__name__}); confira o ZIP preservado",
959
+ }
960
+ )
961
+ except Exception as exc: # noqa: BLE001 - falha de um produto não impede os demais
962
+ # Mensagens HTTP/HTML podem conter CSRF; persistir apenas a classe.
963
+ local_observations.append(
964
+ observation_row(
965
+ layout=layout, row=row, tipo=tipo, status=ERROR, path=None,
966
+ erro=f"Falha na coleta ({type(exc).__name__}); confira sessão, permissões e formato",
967
+ )
968
+ )
969
+ finally:
970
+ _close(local)
971
+ return {
972
+ "observations": local_observations,
973
+ "versions": local_versions,
974
+ "products": local_products,
975
+ "extraction_errors": local_extraction_errors,
976
+ }
977
+
978
+ batch = context.run_batch(
979
+ (ScheduledUnit(f"resposta-{row['id']}", lambda row=row: collect_one(row),
980
+ ResourceProfile(memory_mb=256, network_slots=1),
981
+ event_meta={"survey_id": sid, "response_id": row["id"]}) for row in rows),
982
+ jobs=int(params.get("jobs", 1)),
983
+ )
984
+ for item in batch.completed:
985
+ result = item["result"]
986
+ observations.extend(result["observations"])
987
+ versions.extend(result["versions"])
988
+ extracted_products.extend(result["products"])
989
+ extraction_errors.extend(result["extraction_errors"])
990
+ observations.sort(key=lambda item: (int(item["response_id"]), 0 if item["tipo"] == "pdf" else 1))
991
+ versions.sort(key=lambda item: (int(item["response_id"]), item["tipo"], item["sha256"]))
992
+ # Versões podem ter sido registradas em unidades diferentes; o manifesto
993
+ # central guarda uma linha por hash lógico, não uma por tentativa.
994
+ unique_versions: list[dict[str, Any]] = []
995
+ seen_versions: set[tuple[str, str, str, str]] = set()
996
+ for item in versions:
997
+ key = (str(item["survey_id"]), str(item["response_id"]), str(item["tipo"]), str(item["sha256"]))
998
+ if key not in seen_versions:
999
+ seen_versions.add(key)
1000
+ unique_versions.append(item)
1001
+ versions = unique_versions
1002
+ counts: dict[str, int] = {}
1003
+ for item in observations:
1004
+ counts[item["status"]] = counts.get(item["status"], 0) + 1
1005
+ execution = execution_row(
1006
+ layout,
1007
+ responses_sha256=source_hash,
1008
+ submitted=len(rows),
1009
+ counts=counts,
1010
+ )
1011
+ failures = [item for item in observations if item["status"] == ERROR]
1012
+ pending = tuple(
1013
+ {
1014
+ "type": "limesurvey_collection_failed",
1015
+ "survey_id": sid,
1016
+ "response_id": item["response_id"],
1017
+ "product": item["tipo"],
1018
+ "error": item["erro"],
1019
+ }
1020
+ for item in failures
1021
+ ) + tuple(
1022
+ {
1023
+ "type": "limesurvey_collection_failed",
1024
+ "survey_id": sid,
1025
+ "response_id": item["id"],
1026
+ "product": "extracao",
1027
+ "error": item["erro"],
1028
+ }
1029
+ for item in extraction_errors
1030
+ )
1031
+ apply_execution(state, observations, versions, execution)
1032
+ write_bytes_atomic(layout.central_manifest, manifest_bytes(state))
1033
+ # Cópias correntes na raiz do survey: insumo estável das etapas seguintes
1034
+ # (derivadas e reconstruíveis; o registro de integridade é o do snapshot).
1035
+ write_bytes_atomic(consolidated, xlsx.read_bytes())
1036
+ write_bytes_atomic(consolidated_labels, xlsx_labels.read_bytes())
1037
+ products.extend(extracted_products)
1038
+ products.append(
1039
+ ProductDraft(
1040
+ kind="coleta-survey-manifest",
1041
+ path=snapshot_manifest(layout),
1042
+ content=execution_manifest_bytes(observations, versions, execution),
1043
+ media_type=XLSX_MEDIA,
1044
+ metadata=common,
1045
+ )
1046
+ )
1047
+ warnings = tuple(
1048
+ f"Resposta {item['response_id']} ({item['tipo']}): {item['erro']}" for item in failures
1049
+ ) + tuple(
1050
+ f"Resposta {item['id']} (extracao): {item['erro']}" for item in extraction_errors
1051
+ ) + batch.errors
1052
+ extract_counts: dict[str, int] = {}
1053
+ for item in extracted_products:
1054
+ status = "extraido"
1055
+ extract_counts[status] = extract_counts.get(status, 0) + 1
1056
+ return OperationResult(
1057
+ summary={
1058
+ **summary,
1059
+ "responses": str(snapshot_responses(layout)),
1060
+ "responses_sha256": source_hash,
1061
+ "responses_labels": str(snapshot_responses_labels(layout)),
1062
+ "consolidated": str(consolidated),
1063
+ "consolidated_labels": str(consolidated_labels),
1064
+ "responses_labels_sha256": labels_hash,
1065
+ "submitted": len(rows),
1066
+ "language": form.language,
1067
+ "manifest_output": str(snapshot_manifest(layout)),
1068
+ "extract": extract,
1069
+ "extract_dir": str(extract_dir) if extract_dir else None,
1070
+ "extract_counts": extract_counts,
1071
+ "counts": counts,
1072
+ "reused": int(counts.get(REUSE, 0)),
1073
+ "failed_products": len(failures) + len(extraction_errors),
1074
+ "failed_units": len(batch.failed),
1075
+ },
1076
+ products=tuple(products),
1077
+ pending=pending,
1078
+ warnings=warnings,
1079
+ )