senado-br-mcp 3.27.0 → 3.38.4

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.
package/README.md CHANGED
@@ -639,7 +639,7 @@ The frozen NDJSON is **not** committed (built from the sovereign D1 corpus on de
639
639
 
640
640
  | Tool | Description |
641
641
  |------|-------------|
642
- | `senado_buscar_materias` ⊕ | Busca matérias por tipo, número, ano, palavra-chave, autor ou tramitação (via v3 `/processo`) |
642
+ | `senado_buscar_materias` ⊕ | Busca matérias por tipo, número, ano, palavra-chave, autor ou tramitação (via v3 `/processo`); com `agruparPor: "partido"` e `ano`, conta quantas matérias cada partido apresentou no ano, numa chamada |
643
643
  | `senado_obter_materia` ⊕ | Dados de uma matéria via `secao` enum: detalhe (situação/relator), tramitacao (histórico) ou textos (documentos) |
644
644
 
645
645
  ### Group C — Processes (5 tools)
@@ -679,7 +679,7 @@ The frozen NDJSON is **not** committed (built from the sovereign D1 corpus on de
679
679
  | `senado_agenda_plenario` | Plenary schedule — by day, month or Congress (escopo dia/mes/cn) |
680
680
  | `senado_resultado_plenario` | Session results: items deliberated, opinions, outcomes (SF/CN/month) |
681
681
  | `senado_orientacao_bancada` | Party leadership voting instructions per vote, with tallies |
682
- | `senado_vetos` | Presidential vetoes by year or tramitation status |
682
+ | `senado_vetos` | Presidential vetoes by year or tramitation status; with `apuracao`, how many of a year's vetoes were overridden, partly overridden or upheld, in one call |
683
683
  | `senado_resultado_veto` | Nominal veto vote results (by veto, vetoed bill or device) |
684
684
  | `senado_encontro_plenario` | Legislative session detail, agenda items, results or summary |
685
685
  | `senado_tabelas_plenario` | Session types, attendance types, legislatures list |
@@ -754,7 +754,7 @@ The frozen NDJSON is **not** committed (built from the sovereign D1 corpus on de
754
754
  |------|-------------|
755
755
  | `senado_servidores` | Civil servants by status (active/effective/commissioned/inactive), filterable by name, unit, position |
756
756
  | `senado_remuneracoes_servidores` | Monthly payroll — summary by payroll type or per-person composition with computed gross; `estatisticas=true` returns whole-payroll stats (min/max/mean/median/percentiles) + top/bottom ranking, with `campo`, `consolidarPorServidor`, `agruparPor` and `topN` |
757
- | `senado_horas_extras` | Overtime payments by month with totals; `estatisticas=true` returns whole-set distribution stats (min/max/mean/median/percentiles) + top/bottom ranking, or a per-servant ranking by summed value via `agruparPor` (name/competência), with `topN` |
757
+ | `senado_horas_extras` | Overtime payments by month with totals — or, without `mes`, the whole year in one call (monthly series by payment month; merges the rows the source splits); `estatisticas=true` returns whole-set distribution stats (min/max/mean/median/percentiles) + top/bottom ranking, or a per-servant ranking by summed value via `agruparPor` (name/competência), with `topN` |
758
758
  | `senado_pessoal_tabelas` | Tabelas de pessoal via `tabela` enum: quantitativos (pessoal, cargos-funcoes, previsao-aposentadoria, senadores) e listas (estagiarios, pensionistas, lotacoes, cargos) |
759
759
 
760
760
  ### Group Q — Contratações (6 tools)
package/dist/envelope.js CHANGED
@@ -208,28 +208,54 @@ export class LeitorDeEnvelope {
208
208
  }
209
209
  }
210
210
  /**
211
- * Consome um stream inteiro e devolve os desfechos por `id`. Nunca lança: se o
212
- * stream for cortado no meio (cliente desconectou, container caiu), vale o que
213
- * deu para ler até ali e o resto fica sem desfecho.
211
+ * Prazo da leitura do envelope. Ela corre em `ctx.waitUntil`, e a Cloudflare cancela o que passa de
212
+ * 30 s depois do fim da invocação, com o aviso "waitUntil() tasks did not complete…" (9–22 por hora nos
213
+ * logs até 01/12/2026). Medido nesse dia pelo `wrangler tail`: a causa é o `subscriptions/listen` do
214
+ * protocolo 2026-07-28 (cliente Cowork), um POST cujo stream fica aberto enquanto o cliente quiser
215
+ * ouvir — 272 s no caso visto, terminando `canceled` quando o cliente saiu. A leitura esperava o fim
216
+ * de um stream que não tem fim, era cortada, e a linha de telemetria daquela chamada nunca era gravada.
217
+ * Com o prazo, ela para antes do corte e grava com o que leu (sem desfecho = vale o HTTP, como sempre).
214
218
  */
215
- export async function desfechosDoCorpo(corpo) {
219
+ export const PRAZO_LEITURA_ENVELOPE_MS = 20_000;
220
+ /**
221
+ * Consome um stream e devolve os desfechos por `id`. Nunca lança: se o stream for cortado no meio
222
+ * (cliente desconectou, container caiu) ou passar de `prazoMs` sem terminar (stream longo, como o
223
+ * `subscriptions/listen`), vale o que deu para ler até ali e o resto fica sem desfecho. Cancelar
224
+ * este ramo do `tee` não afeta o ramo do cliente.
225
+ */
226
+ export async function desfechosDoCorpo(corpo, prazoMs = PRAZO_LEITURA_ENVELOPE_MS) {
216
227
  const leitor = new LeitorDeEnvelope();
217
228
  const decoder = new TextDecoder();
218
229
  const reader = corpo.getReader();
230
+ let timer;
231
+ const venceu = new Promise((resolve) => {
232
+ timer = setTimeout(() => resolve("prazo"), prazoMs);
233
+ });
234
+ let cortadoPeloPrazo = false;
219
235
  try {
220
236
  for (;;) {
221
- const { done, value } = await reader.read();
222
- if (done)
237
+ const r = await Promise.race([reader.read(), venceu]);
238
+ if (r === "prazo") {
239
+ cortadoPeloPrazo = true;
223
240
  break;
224
- if (value)
225
- leitor.push(decoder.decode(value, { stream: true }));
241
+ }
242
+ if (r.done)
243
+ break;
244
+ if (r.value)
245
+ leitor.push(decoder.decode(r.value, { stream: true }));
226
246
  }
227
- leitor.push(decoder.decode());
247
+ if (!cortadoPeloPrazo)
248
+ leitor.push(decoder.decode());
228
249
  }
229
250
  catch {
230
251
  // Stream interrompido: o que já foi lido continua valendo.
231
252
  }
232
253
  finally {
254
+ clearTimeout(timer);
255
+ if (cortadoPeloPrazo) {
256
+ // Solta o ramo de leitura do tee: sem isto ele seguiria acumulando o que o cliente recebe.
257
+ reader.cancel().catch(() => { });
258
+ }
233
259
  try {
234
260
  reader.releaseLock();
235
261
  }
@@ -17,6 +17,7 @@
17
17
  * As funções de mapeamento são puras e exportadas para os testes; as de leitura só montam SQL estático
18
18
  * com parâmetros ligados (`?`).
19
19
  */
20
+ import { avisarFalhaDoD1, lerD1ComRetentativa } from "./store.js";
20
21
  import { tabelaC3, TABELA_CONTROLE_C3 } from "./camada3-tabelas.js";
21
22
  import { isoDeDataExtenso } from "./ideia-detalhe.js";
22
23
  /** As colunas de origem de uma linha, na ordem do dicionário (só as que a linha tem). */
@@ -265,20 +266,23 @@ export async function metaDaC3(db, tabelas, staleMaxMin, now = new Date()) {
265
266
  if (!db)
266
267
  return null;
267
268
  try {
268
- const marcas = tabelas.map(() => "?").join(",");
269
- const rs = await db
270
- .prepare(`SELECT tabela, gerado_em, linhas FROM ${TABELA_CONTROLE_C3} WHERE tabela IN (${marcas})`)
271
- .bind(...tabelas)
272
- .all();
273
- const linhas = rs.results ?? [];
274
- if (linhas.length !== tabelas.length || linhas.some((l) => !l.linhas))
275
- return null;
276
- const geradoEm = linhas.map((l) => l.gerado_em ?? "").sort()[0] || null;
277
- const idadeMin = geradoEm ? (now.getTime() - new Date(geradoEm).getTime()) / 60000 : Infinity;
278
- const velha = idadeMin > staleMaxMin;
279
- return { fonte: "camada3", lastScrapedAt: geradoEm, possivelDesatualizacao: velha, ...(velha ? { motivo: "camada3-desatualizada" } : {}) };
269
+ return await lerD1ComRetentativa("metaDaC3", async () => {
270
+ const marcas = tabelas.map(() => "?").join(",");
271
+ const rs = await db
272
+ .prepare(`SELECT tabela, gerado_em, linhas FROM ${TABELA_CONTROLE_C3} WHERE tabela IN (${marcas})`)
273
+ .bind(...tabelas)
274
+ .all();
275
+ const linhas = rs.results ?? [];
276
+ if (linhas.length !== tabelas.length || linhas.some((l) => !l.linhas))
277
+ return null;
278
+ const geradoEm = linhas.map((l) => l.gerado_em ?? "").sort()[0] || null;
279
+ const idadeMin = geradoEm ? (now.getTime() - new Date(geradoEm).getTime()) / 60000 : Infinity;
280
+ const velha = idadeMin > staleMaxMin;
281
+ return { fonte: "camada3", lastScrapedAt: geradoEm, possivelDesatualizacao: velha, ...(velha ? { motivo: "camada3-desatualizada" } : {}) };
282
+ });
280
283
  }
281
- catch {
284
+ catch (e) {
285
+ avisarFalhaDoD1("metaDaC3", e);
282
286
  return null;
283
287
  }
284
288
  }
@@ -296,15 +300,18 @@ export async function consultasDaC3(db, staleMaxMin) {
296
300
  if (!meta || !db)
297
301
  return null;
298
302
  try {
299
- const rs = await db.prepare(`SELECT ${COLS_CONSULTA} FROM ${T.consultas} ORDER BY id DESC`).all();
300
- const extras = await doCorpusForaDaC3(db, "consultas", T.consultas, "id");
301
- const items = [
302
- ...extras.map((e) => ({ ...e.payload, ...origensDoCorpus(e.scrapedAt, ["Resumo", "Detalhe"]) })),
303
- ...(rs.results ?? []).map(consultaDaC3),
304
- ];
305
- return { items, meta: { ...meta, itensDoCorpus: extras.length } };
303
+ return await lerD1ComRetentativa("consultasDaC3", async () => {
304
+ const rs = await db.prepare(`SELECT ${COLS_CONSULTA} FROM ${T.consultas} ORDER BY id DESC`).all();
305
+ const extras = await doCorpusForaDaC3(db, "consultas", T.consultas, "id");
306
+ const items = [
307
+ ...extras.map((e) => ({ ...e.payload, ...origensDoCorpus(e.scrapedAt, ["Resumo", "Detalhe"]) })),
308
+ ...(rs.results ?? []).map(consultaDaC3),
309
+ ];
310
+ return { items, meta: { ...meta, itensDoCorpus: extras.length } };
311
+ });
306
312
  }
307
- catch {
313
+ catch (e) {
314
+ avisarFalhaDoD1("consultasDaC3", e);
308
315
  return null;
309
316
  }
310
317
  }
@@ -314,18 +321,21 @@ export async function eventosDaC3(db, staleMaxMin) {
314
321
  if (!meta || !db)
315
322
  return null;
316
323
  try {
317
- const rs = await db.prepare(`SELECT ${COLS_EVENTO} FROM ${T.eventos} ORDER BY id DESC`).all();
318
- const extras = await doCorpusForaDaC3(db, "eventos", T.eventos, "id");
319
- const items = [
320
- ...extras.map((e) => {
321
- const { pauta: _p, convidados: _c, ...resto } = e.payload;
322
- return { ...resto, ...origensDoCorpus(e.scrapedAt, ["Resumo", "Detalhe", "Comentarios"]) };
323
- }),
324
- ...(rs.results ?? []).map(eventoDaC3),
325
- ];
326
- return { items, meta: { ...meta, itensDoCorpus: extras.length } };
324
+ return await lerD1ComRetentativa("eventosDaC3", async () => {
325
+ const rs = await db.prepare(`SELECT ${COLS_EVENTO} FROM ${T.eventos} ORDER BY id DESC`).all();
326
+ const extras = await doCorpusForaDaC3(db, "eventos", T.eventos, "id");
327
+ const items = [
328
+ ...extras.map((e) => {
329
+ const { pauta: _p, convidados: _c, ...resto } = e.payload;
330
+ return { ...resto, ...origensDoCorpus(e.scrapedAt, ["Resumo", "Detalhe", "Comentarios"]) };
331
+ }),
332
+ ...(rs.results ?? []).map(eventoDaC3),
333
+ ];
334
+ return { items, meta: { ...meta, itensDoCorpus: extras.length } };
335
+ });
327
336
  }
328
- catch {
337
+ catch (e) {
338
+ avisarFalhaDoD1("eventosDaC3", e);
329
339
  return null;
330
340
  }
331
341
  }
@@ -340,34 +350,37 @@ export async function acervoDaC3(db, staleMaxMin, uf) {
340
350
  if (!meta || !db)
341
351
  return null;
342
352
  try {
343
- const [ms, vs] = await Promise.all([
344
- db.prepare(`SELECT codigo, materia, ementa, autoria, status, referencePeriod, votosSim, votosNao, totalVotos, url, origem, coletadoEm FROM ${T.materias}`).all(),
345
- uf ? db.prepare(`SELECT codigo, uf, sim, nao, desde, ate FROM ${T.votosUf} WHERE uf = ?`).bind(uf).all() : Promise.resolve({ results: [] }),
346
- ]);
347
- const daUf = votosPorUfDaC3(vs.results ?? []);
348
- const extras = await doCorpusForaDaC3(db, "consultas_votos", T.materias, "codigo");
349
- const doBanco = new Set();
350
- const items = [
351
- ...extras.map((e) => ({ ...e.payload, origem: "corpus", coletadoEm: e.scrapedAt })),
352
- ...(ms.results ?? []).map((m) => {
353
- doBanco.add(m.codigo);
354
- return materiaDaC3(m, daUf.get(m.codigo) ?? {});
355
- }),
356
- ];
357
- const completar = async (itens) => {
358
- const codigos = itens.filter((i) => doBanco.has(i.id)).map((i) => i.id);
359
- if (!codigos.length)
360
- return itens;
361
- const rs = await db
362
- .prepare(`SELECT codigo, uf, sim, nao, desde, ate FROM ${T.votosUf} WHERE codigo IN (${codigos.map(() => "?").join(",")})`)
363
- .bind(...codigos)
364
- .all();
365
- const mapa = votosPorUfDaC3(rs.results ?? []);
366
- return itens.map((i) => (doBanco.has(i.id) ? { ...i, votosPorUf: mapa.get(i.id) ?? {} } : i));
367
- };
368
- return { items, meta: { ...meta, itensDoCorpus: extras.length }, completar };
353
+ return await lerD1ComRetentativa("acervoDaC3", async () => {
354
+ const [ms, vs] = await Promise.all([
355
+ db.prepare(`SELECT codigo, materia, ementa, autoria, status, referencePeriod, votosSim, votosNao, totalVotos, url, origem, coletadoEm FROM ${T.materias}`).all(),
356
+ uf ? db.prepare(`SELECT codigo, uf, sim, nao, desde, ate FROM ${T.votosUf} WHERE uf = ?`).bind(uf).all() : Promise.resolve({ results: [] }),
357
+ ]);
358
+ const daUf = votosPorUfDaC3(vs.results ?? []);
359
+ const extras = await doCorpusForaDaC3(db, "consultas_votos", T.materias, "codigo");
360
+ const doBanco = new Set();
361
+ const items = [
362
+ ...extras.map((e) => ({ ...e.payload, origem: "corpus", coletadoEm: e.scrapedAt })),
363
+ ...(ms.results ?? []).map((m) => {
364
+ doBanco.add(m.codigo);
365
+ return materiaDaC3(m, daUf.get(m.codigo) ?? {});
366
+ }),
367
+ ];
368
+ const completar = async (itens) => {
369
+ const codigos = itens.filter((i) => doBanco.has(i.id)).map((i) => i.id);
370
+ if (!codigos.length)
371
+ return itens;
372
+ const rs = await db
373
+ .prepare(`SELECT codigo, uf, sim, nao, desde, ate FROM ${T.votosUf} WHERE codigo IN (${codigos.map(() => "?").join(",")})`)
374
+ .bind(...codigos)
375
+ .all();
376
+ const mapa = votosPorUfDaC3(rs.results ?? []);
377
+ return itens.map((i) => (doBanco.has(i.id) ? { ...i, votosPorUf: mapa.get(i.id) ?? {} } : i));
378
+ };
379
+ return { items, meta: { ...meta, itensDoCorpus: extras.length }, completar };
380
+ });
369
381
  }
370
- catch {
382
+ catch (e) {
383
+ avisarFalhaDoD1("acervoDaC3", e);
371
384
  return null;
372
385
  }
373
386
  }
@@ -415,25 +428,30 @@ export async function paginaDeIdeiasDaC3(db, staleMaxMin, p) {
415
428
  if (!meta || !db)
416
429
  return null;
417
430
  try {
418
- const ordem = p.ordenarPorApoios ? `apoios ${p.ordenarPorApoios === "asc" ? "ASC" : "DESC"}, id DESC` : "id DESC";
419
- const onde = p.status ? "WHERE status = ?" : "";
420
- const ate = p.offset + p.limite;
421
- const stmt = db.prepare(`SELECT ${COLS_IDEIA} FROM ${T.ideias} ${onde} ORDER BY ${ordem} LIMIT ?`);
422
- const rs = await (p.status ? stmt.bind(p.status, ate) : stmt.bind(ate)).all();
423
- const extras = (await doCorpusForaDaC3(db, "ideias", T.ideias, "id"))
424
- .map((e) => ({ ...e.payload, ...origensDoCorpus(e.scrapedAt, ["Resumo", "Detalhe"]) }))
425
- .filter((i) => !p.status || i.status === p.status);
426
- const todas = [...extras.map((item) => ({ item })), ...(rs.results ?? []).map((linha) => ({ item: ideiaDaC3(linha), linha }))];
427
- const cmp = (x, y) => {
428
- const a = x.item, b = y.item;
429
- return p.ordenarPorApoios === "asc" ? a.apoios - b.apoios || b.id - a.id : p.ordenarPorApoios === "desc" ? b.apoios - a.apoios || b.id - a.id : b.id - a.id;
430
- };
431
- const fatia = todas.sort(cmp).slice(p.offset, ate);
432
- const props = await proposicoesDe(db, fatia.flatMap((c) => (c.linha ? [c.linha] : [])));
433
- const items = fatia.map((c) => (c.linha ? ideiaDaC3(c.linha, props.get(c.linha.id)) : c.item));
434
- return { items, meta: { ...meta, itensDoCorpus: extras.length } };
431
+ return await lerD1ComRetentativa("paginaDeIdeiasDaC3", async () => {
432
+ const ordem = p.ordenarPorApoios ? `apoios ${p.ordenarPorApoios === "asc" ? "ASC" : "DESC"}, id DESC` : "id DESC";
433
+ const onde = p.status ? "WHERE status = ?" : "";
434
+ const ate = p.offset + p.limite;
435
+ const stmt = db.prepare(`SELECT ${COLS_IDEIA} FROM ${T.ideias} ${onde} ORDER BY ${ordem} LIMIT ?`);
436
+ const rs = await (p.status ? stmt.bind(p.status, ate) : stmt.bind(ate)).all();
437
+ const extras = (await doCorpusForaDaC3(db, "ideias", T.ideias, "id"))
438
+ .map((e) => ({ ...e.payload, ...origensDoCorpus(e.scrapedAt, ["Resumo", "Detalhe"]) }))
439
+ .filter((i) => !p.status || i.status === p.status);
440
+ const todas = [...extras.map((item) => ({ item })), ...(rs.results ?? []).map((linha) => ({ item: ideiaDaC3(linha), linha }))];
441
+ const cmp = (x, y) => {
442
+ const a = x.item, b = y.item;
443
+ return p.ordenarPorApoios === "asc" ? a.apoios - b.apoios || b.id - a.id : p.ordenarPorApoios === "desc" ? b.apoios - a.apoios || b.id - a.id : b.id - a.id;
444
+ };
445
+ const fatia = todas.sort(cmp).slice(p.offset, ate);
446
+ const props = await proposicoesDe(db, fatia.flatMap((c) => (c.linha ? [c.linha] : [])));
447
+ const items = fatia.map((c) => (c.linha ? ideiaDaC3(c.linha, props.get(c.linha.id)) : c.item));
448
+ const contagem = db.prepare(`SELECT COUNT(*) AS n FROM ${T.ideias} ${onde}`);
449
+ const n = (await (p.status ? contagem.bind(p.status) : contagem).first())?.n ?? 0;
450
+ return { items, total: Number(n) + extras.length, meta: { ...meta, itensDoCorpus: extras.length } };
451
+ });
435
452
  }
436
- catch {
453
+ catch (e) {
454
+ avisarFalhaDoD1("paginaDeIdeiasDaC3", e);
437
455
  return null;
438
456
  }
439
457
  }
@@ -446,21 +464,24 @@ export async function ideiasParaEnqueteDaC3(db, staleMaxMin, o) {
446
464
  if (!meta || !db)
447
465
  return null;
448
466
  try {
449
- const onde = o.apenasAbertas ? "WHERE status = 'aberta'" : "";
450
- const e = o.apenasAbertas ? "AND" : "WHERE";
451
- const [n, q, top] = await Promise.all([
452
- db.prepare(`SELECT COUNT(*) AS n FROM ${T.ideias} ${onde}`).first(),
453
- db.prepare(`SELECT COUNT(*) AS n FROM ${T.ideias} ${onde} ${e} apoios >= ?`).bind(o.minimo).first(),
454
- db.prepare(`SELECT ${COLS_IDEIA} FROM ${T.ideias} ${onde} ${e} apoios >= ? ORDER BY apoios DESC, id DESC LIMIT ?`).bind(o.minimo, o.topo).all(),
455
- ]);
456
- const extras = (await doCorpusForaDaC3(db, "ideias", T.ideias, "id"))
457
- .map((x) => ({ ...x.payload, ...origensDoCorpus(x.scrapedAt, ["Resumo", "Detalhe"]) }))
458
- .filter((i) => !o.apenasAbertas || i.status === "aberta");
459
- const extrasQ = extras.filter((i) => i.apoios >= o.minimo);
460
- const topo = [...extrasQ, ...(top.results ?? []).map((l) => ideiaDaC3(l))].sort((a, b) => b.apoios - a.apoios || b.id - a.id).slice(0, o.topo);
461
- return { analisadas: (n?.n ?? 0) + extras.length, qualificadas: (q?.n ?? 0) + extrasQ.length, topo, meta: { ...meta, itensDoCorpus: extras.length } };
467
+ return await lerD1ComRetentativa("ideiasParaEnqueteDaC3", async () => {
468
+ const onde = o.apenasAbertas ? "WHERE status = 'aberta'" : "";
469
+ const e = o.apenasAbertas ? "AND" : "WHERE";
470
+ const [n, q, top] = await Promise.all([
471
+ db.prepare(`SELECT COUNT(*) AS n FROM ${T.ideias} ${onde}`).first(),
472
+ db.prepare(`SELECT COUNT(*) AS n FROM ${T.ideias} ${onde} ${e} apoios >= ?`).bind(o.minimo).first(),
473
+ db.prepare(`SELECT ${COLS_IDEIA} FROM ${T.ideias} ${onde} ${e} apoios >= ? ORDER BY apoios DESC, id DESC LIMIT ?`).bind(o.minimo, o.topo).all(),
474
+ ]);
475
+ const extras = (await doCorpusForaDaC3(db, "ideias", T.ideias, "id"))
476
+ .map((x) => ({ ...x.payload, ...origensDoCorpus(x.scrapedAt, ["Resumo", "Detalhe"]) }))
477
+ .filter((i) => !o.apenasAbertas || i.status === "aberta");
478
+ const extrasQ = extras.filter((i) => i.apoios >= o.minimo);
479
+ const topo = [...extrasQ, ...(top.results ?? []).map((l) => ideiaDaC3(l))].sort((a, b) => b.apoios - a.apoios || b.id - a.id).slice(0, o.topo);
480
+ return { analisadas: (n?.n ?? 0) + extras.length, qualificadas: (q?.n ?? 0) + extrasQ.length, topo, meta: { ...meta, itensDoCorpus: extras.length } };
481
+ });
462
482
  }
463
- catch {
483
+ catch (e) {
484
+ avisarFalhaDoD1("ideiasParaEnqueteDaC3", e);
464
485
  return null;
465
486
  }
466
487
  }
@@ -470,19 +491,22 @@ export async function ideiaInteiraDaC3(db, id, staleMaxMin) {
470
491
  if (!meta || !db)
471
492
  return null;
472
493
  try {
473
- const linha = await db.prepare(`SELECT ${COLS_IDEIA} FROM ${T.ideias} WHERE id = ?`).bind(id).first();
474
- if (!linha)
475
- return null;
476
- const [tl, ap, si, props] = await Promise.all([
477
- db.prepare(`SELECT id, ordem, data, tipo, texto FROM ${T.linhaDoTempo} WHERE id = ? ORDER BY ordem`).bind(id).all(),
478
- db.prepare(`SELECT entity_id, origem, apoios, desde, ate, leituras FROM ${T.serieApoios} WHERE entity_id = ?`).bind(String(id)).all(),
479
- db.prepare(`SELECT entity_id, origem, situacao_codigo, situacao_nome, status, desde, ate, leituras FROM ${T.situacao} WHERE entity_id = ?`).bind(String(id)).all(),
480
- proposicoesDe(db, [linha]),
481
- ]);
482
- const detalhe = detalheDaC3(linha, tl.results ?? [], props.get(id) ?? []);
483
- return { linha, detalhe, serieApoios: ap.results ?? [], situacoes: si.results ?? [], meta };
494
+ return await lerD1ComRetentativa("ideiaInteiraDaC3", async () => {
495
+ const linha = await db.prepare(`SELECT ${COLS_IDEIA} FROM ${T.ideias} WHERE id = ?`).bind(id).first();
496
+ if (!linha)
497
+ return null;
498
+ const [tl, ap, si, props] = await Promise.all([
499
+ db.prepare(`SELECT id, ordem, data, tipo, texto FROM ${T.linhaDoTempo} WHERE id = ? ORDER BY ordem`).bind(id).all(),
500
+ db.prepare(`SELECT entity_id, origem, apoios, desde, ate, leituras FROM ${T.serieApoios} WHERE entity_id = ?`).bind(String(id)).all(),
501
+ db.prepare(`SELECT entity_id, origem, situacao_codigo, situacao_nome, status, desde, ate, leituras FROM ${T.situacao} WHERE entity_id = ?`).bind(String(id)).all(),
502
+ proposicoesDe(db, [linha]),
503
+ ]);
504
+ const detalhe = detalheDaC3(linha, tl.results ?? [], props.get(id) ?? []);
505
+ return { linha, detalhe, serieApoios: ap.results ?? [], situacoes: si.results ?? [], meta };
506
+ });
484
507
  }
485
- catch {
508
+ catch (e) {
509
+ avisarFalhaDoD1("ideiaInteiraDaC3", e);
486
510
  return null;
487
511
  }
488
512
  }
@@ -492,13 +516,16 @@ export async function consultaInteiraDaC3(db, id, staleMaxMin) {
492
516
  if (!meta || !db)
493
517
  return null;
494
518
  try {
495
- const linha = await db.prepare(`SELECT ${COLS_CONSULTA} FROM ${T.consultas} WHERE id = ?`).bind(id).first();
496
- if (!linha)
497
- return null;
498
- const s = await db.prepare(`SELECT id, voto, votos, desde, ate, leituras, origem FROM ${T.serieVotos} WHERE id = ?`).bind(id).all();
499
- return { linha, serie: s.results ?? [], meta };
519
+ return await lerD1ComRetentativa("consultaInteiraDaC3", async () => {
520
+ const linha = await db.prepare(`SELECT ${COLS_CONSULTA} FROM ${T.consultas} WHERE id = ?`).bind(id).first();
521
+ if (!linha)
522
+ return null;
523
+ const s = await db.prepare(`SELECT id, voto, votos, desde, ate, leituras, origem FROM ${T.serieVotos} WHERE id = ?`).bind(id).all();
524
+ return { linha, serie: s.results ?? [], meta };
525
+ });
500
526
  }
501
- catch {
527
+ catch (e) {
528
+ avisarFalhaDoD1("consultaInteiraDaC3", e);
502
529
  return null;
503
530
  }
504
531
  }
@@ -508,16 +535,19 @@ export async function eventoInteiroDaC3(db, id, staleMaxMin) {
508
535
  if (!meta || !db)
509
536
  return null;
510
537
  try {
511
- const linha = await db.prepare(`SELECT ${COLS_EVENTO} FROM ${T.eventos} WHERE id = ?`).bind(id).first();
512
- if (!linha)
513
- return null;
514
- const [p, c] = await Promise.all([
515
- db.prepare(`SELECT texto FROM ${T.pauta} WHERE id = ? ORDER BY ordem`).bind(id).all(),
516
- db.prepare(`SELECT texto FROM ${T.convidados} WHERE id = ? ORDER BY ordem`).bind(id).all(),
517
- ]);
518
- return { linha, pauta: (p.results ?? []).map((x) => x.texto), convidados: (c.results ?? []).map((x) => x.texto), meta };
538
+ return await lerD1ComRetentativa("eventoInteiroDaC3", async () => {
539
+ const linha = await db.prepare(`SELECT ${COLS_EVENTO} FROM ${T.eventos} WHERE id = ?`).bind(id).first();
540
+ if (!linha)
541
+ return null;
542
+ const [p, c] = await Promise.all([
543
+ db.prepare(`SELECT texto FROM ${T.pauta} WHERE id = ? ORDER BY ordem`).bind(id).all(),
544
+ db.prepare(`SELECT texto FROM ${T.convidados} WHERE id = ? ORDER BY ordem`).bind(id).all(),
545
+ ]);
546
+ return { linha, pauta: (p.results ?? []).map((x) => x.texto), convidados: (c.results ?? []).map((x) => x.texto), meta };
547
+ });
519
548
  }
520
- catch {
549
+ catch (e) {
550
+ avisarFalhaDoD1("eventoInteiroDaC3", e);
521
551
  return null;
522
552
  }
523
553
  }
@@ -167,8 +167,24 @@ export function extractTime(text) {
167
167
  *
168
168
  * `totalVotos` is taken from the caller when provided (the REST endpoint reports its own total,
169
169
  * which may differ slightly from votosSim+votosNao) and otherwise derived as votosSim+votosNao.
170
- * Percentuais are always derived here with `Math.round`.
170
+ * Percentuais are always derived here with `Math.round` (inteiro) — é o que fica GRAVADO, e mudar o
171
+ * arredondamento aqui mudaria o `contentHash` de toda linha. A RESPOSTA das tools recalcula com uma casa
172
+ * (`comPercentuaisDeUmaCasa`), como o dataset publica: o ao vivo dava 67 onde a camada 3 dá 66,7.
171
173
  */
174
+ /** Percentual de votos com uma casa decimal — a mesma conta do dataset (`scripts/publicacao/comum.ts`); 0 sem votos. */
175
+ export function percentualDeVotos(parte, total) {
176
+ return total > 0 ? Math.round((parte / total) * 1000) / 10 : 0;
177
+ }
178
+ /**
179
+ * A consulta com `percentualSim`/`percentualNao` recalculados com uma casa, a partir dos votos que ela traz.
180
+ * Para o que vem do corpus ou da leitura ao vivo (gravados inteiros); a camada 3 já vem com uma casa.
181
+ */
182
+ export function comPercentuaisDeUmaCasa(c) {
183
+ const { votosSim, votosNao, totalVotos } = c;
184
+ if (typeof votosSim !== "number" || typeof votosNao !== "number" || typeof totalVotos !== "number")
185
+ return c;
186
+ return { ...c, percentualSim: percentualDeVotos(votosSim, totalVotos), percentualNao: percentualDeVotos(votosNao, totalVotos) };
187
+ }
172
188
  export function buildConsultaResumo(fields) {
173
189
  const votosSim = fields.votosSim;
174
190
  const votosNao = fields.votosNao;