mirror of
https://github.com/fsolla/teqo.git
synced 2026-12-04 15:13:06 +00:00
Compare commits
11 commits
d0823043ed
...
38e6742673
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
38e6742673 | ||
|
|
8f3118312a | ||
|
|
76416c77b0 | ||
|
|
8318fb5fce | ||
|
|
772a5cf050 | ||
|
|
2c8b38f2be | ||
|
|
9069d23d88 | ||
|
|
133136dda3 | ||
|
|
c320e04de8 | ||
|
|
f8010b41a2 | ||
|
|
d576aa6871 |
128 changed files with 67408 additions and 1519 deletions
|
|
@ -22,7 +22,7 @@ Conceitos e decisões: `docs/ARCHITECTURE.md`. Operação (setup/seeds/deploy/se
|
|||
- `src/components/campaign/<domínio>/` — municipality, activity, supporter, leadership, advisor, demand, organization, stateDeputy, votePledge, invite, map, dashboard, auth, shell (sidebar/nav/PWA), shared (sistema de listas + widgets genéricos).
|
||||
- `src/components/cards/` — estúdio público de cards personalizados (S13): `CardsStudio` (seleção + shell dialog/drawer), `CardComposer`, `CardModelGallery`/`CardModelTile`, `CardPreviewCanvas`, adapters em `cardCanvas.ts`/`cardCutout.ts`/`cardPhotoHarmonyCanvas.ts` (S17). Geometria/catálogo/tom puros em `src/lib/card{Models,NameFit,PhotoTransform,Render,Harmony}.ts`.
|
||||
- `src/components/ui/` — kit shadcn da casa (sem peças mortas; `shadcn add` re-adiciona).
|
||||
- `src/lib/schemas/` — zod de entrada; `src/lib/` também guarda catálogos estáticos e o artefato TSE (`electionAggregates/`), além dos módulos puros do estúdio de cards públicos (`cardModels`, `cardNameFit`, `cardPhotoTransform`, `cardRender`, `cardPhotoHarmony`) e do roster estático das 53 dobradinhas (`stateDeputyCatalog`, S30 — snapshot em `tests/fixtures/state-deputy-catalog.snapshot.json`; artes derivadas por `scripts/build-state-deputy-card-assets.mjs`), além da geometria/linhas da colinha (`cardColinha`, S31 — topo/linha legal/corpo medidos do gate, `colinhaVoteRows` e o fit do candidato).
|
||||
- `src/lib/schemas/` — zod de entrada; `src/lib/` também guarda catálogos estáticos e o artefato TSE (`electionAggregates/`), além dos módulos puros do estúdio de cards públicos (`cardModels`, `cardNameFit`, `cardPhotoTransform`, `cardRender`, `cardPhotoHarmony`) e do roster estático das 53 dobradinhas (`stateDeputyCatalog`, S30 — snapshot em `tests/fixtures/state-deputy-catalog.snapshot.json`; artes derivadas por `scripts/build-state-deputy-card-assets.mjs`), além da geometria da linha do estadual da colinha (`cardColinha`, S34 — a arte aprovada é a base e só a linha `DEPUTADO ESTADUAL` é desenhada por cima, com `fitColinhaRowName`).
|
||||
- `src/migrations/` — história congelada; nunca editar retroativamente.
|
||||
- `tests/` — `unit` primeiro (lógica pura, DATABASE_URL inválida), depois `int` para fronteiras Payload/DB (Payload real em `teqo_test`, fixtures em `tests/helpers/campaignFixtures.ts`), e `e2e` só com benefício real por fluxo que as camadas inferiores não cobrem (Playwright smoke; dono da definição: skill `test-driven-development`).
|
||||
|
||||
|
|
|
|||
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -78,6 +78,8 @@ next-env.d.ts
|
|||
/data/ai-fill/
|
||||
# Câmara pilot media/JSON cache (pnpm camara:pilot — VOD MP4 + report, never commit)
|
||||
/data/camara/
|
||||
# C215 — web-speech ingestion batch cache + reports (pnpm falas-web:import)
|
||||
/data/falas-web/
|
||||
# Solla × Ceuci report HTML cache (scripts/build-solla-ceuci-salvador-report.mjs)
|
||||
/data/solla-ceuci-salvador/
|
||||
|
||||
|
|
|
|||
1
docs/changelog/2026-09-24-c215.md
Normal file
1
docs/changelog/2026-09-24-c215.md
Normal file
|
|
@ -0,0 +1 @@
|
|||
**C215 — Ingestão de falas da internet no acervo (2026-09-24):** a esteira que recebe um lote de achados da web (contrato do C218), baixa/espelha a mídia, transcreve com timestamps, classifica e grava de forma idempotente, com relatório honesto. O `speech` deixou de ser só Câmara: ganhou o discriminador `origin` (`camara` default | `web`) e os campos web nullable (`platform` youtube|instagram|radio|audio, `externalId`, `sourceUrl`, `title`, `channel`, `mirroredMedia`/`thumbnail` → nova collection privada `internetSpeechMedia`), numa migration aditiva (`20260924_042028_add_web_speech_origin`, `origin` NOT NULL DEFAULT `'camara'` — as linhas existentes ficam intactas) e a collection privada registrada no plugin S3 (`internetSpeechMedia: true`; sem isso, produção cairia no disco efêmero), com `read = canReadSpeech` (o gate do acervo, fail-closed), escrita `payloadAdminOnly` (o CLI usa o bypass justificado) e cascade no `beforeDelete` do `Speech` (mídia + capa). A identidade da fala web é namespaced (`web:<platform>:<externalId|url canônica>`, nunca colide com o `sourceKey` da Câmara) e o contrato puro vive em `src/lib/webSpeech.ts` (taxonomia + labels pt-BR, schema zod do lote `{ generatedAt?, findings[] }` com `mediaUrl` obrigatória para rádio/áudio e `publishedAt` normalizado para o `speechAt` wall-clock, canonicalização de URL que colapsa youtu.be/shorts/live/embed e reels e remove tracking, e o `webSpeechSourceKey` estável). A aquisição tem dono único por ferramenta: `src/utilities/media/ytdlp.ts` (YouTube/Instagram via `YTDLP_PATH` → PATH, probe `--version` fail-closed com hint de `pipx install yt-dlp`, `--dump-json` preenchendo lacunas de título/canal/duração/id/capa e download capado em ≤720p H.264/AAC com `--merge-output-format mp4` e `--ffmpeg-location` do binário resolvido) e `src/utilities/media/downloadToFile.ts` (rádio/áudio direto, streaming com timeout); a resolução/probe/runner genérico de binários saiu de `scripts/lib/reelFfmpeg.mjs` para `scripts/lib/mediaBinaries.mjs` (o reel re-exporta — API e unit pins intactos) e o script resolve o ffmpeg com o fallback empacotado, setando `FFMPEG_PATH`. O pipeline `src/utilities/speech/webSpeechIngest.ts` (deps injetáveis para os specs) reusa os donos existentes — `deepInfraTranscribeSegments` + chunk/merge/`searchText` do C199, `classifySpeech` (gazetteer + LLM), `withPayloadTransaction` e o `upsertSpeechBundle` estendido com os campos web e `options.req` (o caminho Câmara segue idêntico) — com a capa em best-effort fora da transação (imagem quebrada nunca perde a fala) e limpeza best-effort do artefato substituído no `--reprocess`. O CLI `pnpm falas-web:import --findings <lote.json> [--out data/falas-web] [--limit n] [--dry-run] [--reprocess]` (relatórios gitignored em `data/falas-web/reports/`) tem as guardas do C155 (`assertLocalDatabase` + `FALAS_WEB_IMPORT_CONFIRM=1` para alvo não-local/produção; `--dry-run` é read-only e não exige a flag), dedupe por `sourceKey` no lote, item inválido vira falha do item (nunca derruba o lote) e o relatório declara achados/novos/atualizados/ignorados/falhas (com estágio e motivo)/tempo/segundos e custo de ASR/custo LLM — exit 1 quando nenhum achado entrou. Blindagem obrigatória das superfícies existentes: `origin: camara` no where da lista/opções da Câmara (`speechListFilters`/`speechPageData`), na cobertura (`speechCoverage`) e no tool do Sollinha (`findSpeechExcerpts`) — a fala web nasce invisível até o C216 abrir a fonte própria; o serving/player fica no C216 (`buildPrivateMediaResponse`) e o corte no C217 (`downloadPrivateMediaToFile`), nada de rota nova aqui e nenhuma URL pública de mídia. Sem UI (Impeccable A), sem PII/`Consent` novo (canal/autor é texto de origem; menções continuam texto), sem segundo cadastro de pessoa. Verificação: unit (`webSpeech` — schema/sourceKey/canonicalização/labels; `webSpeeches` — plano/dedupe/relatório; `ytdlp` — resolução/parse/args; pins de `speechListFilters` e `speechExcerptsTool` atualizados), int (`webSpeechImport` — round-trip dos campos web, idempotência com facetas/segmentos preservados, curadoria `manual` vencendo, cascade da mídia no delete; `webSpeechIngest` — pipeline com fakes de acquirer/ffmpeg/transcriber/classificador, segundo run só atualiza metadados, `--reprocess` troca o artefato e apaga o antigo, falhas honestas por estágio sem linha fantasma, thumbnail espelhada, achado de rádio com `mediaUrl`), smoke local do CLI (`--dry-run` com inválido/duplicado e execução real com yt-dlp ausente → relatório + exit 1), `pnpm gate:fast`, `pnpm test:int` e o e2e afetado local. O run real de um lote em produção é operação do C218 (o PR não escreve no acervo de produção).
|
||||
1
docs/changelog/2026-09-24-c219.md
Normal file
1
docs/changelog/2026-09-24-c219.md
Normal file
|
|
@ -0,0 +1 @@
|
|||
**C219 — Paridade de busca e filtros entre as fontes do acervo (2026-09-24):** "Gravações enviadas" passa a ter os mesmos gestos de garimpo das "Falas da Câmara" — busca `termo|tema`, filtros de Ano, Tema, Alcance, Município citado e Duração (Pessoa segue exclusiva), chips ativos, contagem, ordenação e vazio honesto — com classificação automática e proveniência auditável sobre a transcrição já existente. Schema: `recording` ganha `year` derivado de `recordedAt` (hook espelho do `Speech`, que agora **limpa** o ano quando a data é limpa), `topics`/`scopes` (mesma taxonomia `lib/speechFacets`), `classifiedBy` (`gazetteer|llm|manual`, **nullable** — nulo = "não classificada", nunca proveniência inventada) e `mentionedMunicipalities` (relationship), com `preserveManualFacets` protegendo curadoria humana de escritas sem `req.user` (job/CLI); migration aditiva `20260924_040210_add_recording_facets` com backfill SQL determinístico do ano. Classificação: `classifyRecordingFacets` (novo, `server-only`) reusa o dono `classifySpeech` (gazetteer offline + refinamento LLM validado na DeepInfra, nunca lança) e resolve os slugs do gazetteer no catálogo de municípios; o seam é o fim do `runRecordingJob` (injetável, fora da transação de save — o LLM não entra no lock) e o acervo existente é coberto pelo CLI idempotente `pnpm recordings:classify` (`--dry-run`, `--limit`, `--all`, guard de DB local + `RECORDING_CLASSIFY_CONFIRM=1` para alvo remoto), com o shape de escrita em dono único (`recordingFacetWriteData`). URL/filtros: `recordingListUrl` ganha `mode|year|topic|scope|municipality|duration|sort` na ordem canônica da Câmara, com `sort=recentes`/`mode=termo` nunca serializados e os deep-links `?source=enviadas&q&person&page` byte-idênticos; `buildRecordingListWhere` ANDa as facetas (duração reusa `durationBucketWhere` exportado do dono da Câmara) e, nos sorts de duração, exige `durationSeconds` existir (senão o NULLS FIRST do Postgres abriria a lista com as gravações sem duração); o loader ganha opções de ano/municípios, injeção da expansão de tema e a degradação honesta (`themeUnavailable`/`themeApplied`); `expandSpeechSearchTheme` ganha o corpus `'recording'` (3º consumidor do mesmo mecanismo, prompt próprio) e o adaptador puro `recordingOmnibox` monta chips/seeds/toggles sobre `lib/campaignListOmnibox`. UI (Impeccable B, porte do design aprovado `docs/plans/acervo-paridade-busca-filtros-ui-design.html`): `RecordingAcervoFilters` novo sobre os shells compartilhados (omnibox com chips dentro do campo, seletor `Termo exato|Por tema`, seis facetas em popovers-chip, absorvendo o antigo `RecordingPersonFilter`), `RecordingSortSelect` ("Mais recentes" default · "Duração (maior)" · "Duração (menor)" com o hint das gravações sem duração), `RecordingThemeFallbackNotice` + `CampaignThemeRetryButton` (movido para `shared/`), chip de tema no card e o vazio honesto do modo tema com "Limpar filtros" + "Trocar para termo exato"; no /simplify o seletor de modo e o rótulo de chip viraram donos compartilhados (`CampaignSearchModeControl`, `selectedFilterTriggerLabel`). Access/Consent intocados (gate `communicationCatalog` fail-closed, sem PII nova, sem rota/collection nova). Verificação: unit (URL canônica/deep-link/ordenação, `where` das facetas+tema+gate de duração, omnibox, corpus novo), int (job grava facetas e degrada sem chave, curadoria `manual` preservada inclusive no escape autenticado, ano derivado/limpo, loader filtra/ordena/degrada o tema), e2e do `campaignSpeechAcervo` estendido (barra de facetas, estreitamento + vazio, ordenação por duração, tema degradando) e `campaignSpeechAcervo` no conjunto curado high-risk do PR (a migration torna a entrega high-risk), `pnpm gate:fast`, `pnpm test:int`, `pnpm build` e os e2e locais. Crítica final do `designer` (trigger c) **certificada em tier primário** (`Design tier: openai/gpt-5.6-sol`); o débito do "X" de limpar do omnibox que quebra linha no mobile com chip longo (pré-existente do shell compartilhado, reproduzido na Câmara) ficou fora e virou a Issue C221, com os demais adiamentos anotados com gatilho no `*-impl.md`.
|
||||
1
docs/changelog/2026-09-24-c220.md
Normal file
1
docs/changelog/2026-09-24-c220.md
Normal file
|
|
@ -0,0 +1 @@
|
|||
**C220 — Central de Conteúdos: o link do próprio Instagram baixa e cataloga a peça (2026-09-24):** colar o link de uma peça do próprio perfil (`@depjorgesolla`) na Central (`/campanha/comunicacao/conteudos`) deixava de baixar e analisar em silêncio — virava "peça-link" sem motivo. O parse de link (`lib/contentPiece.ts`) passa a aceitar também a grafia que o browser copia do perfil (`/<perfil>/reel/<shortcode>/`, `p|reel|reels|tv`, com/sem `www.`/`m.`, query ignorada) e rejeita `/stories/`, `instagr.am` e hosts fora de Instagram/YouTube como antes; o match com a mídia oficial passa a ser pelo **shortcode** (o kind é apresentação — `/p/ABC/` casa o reel), o que também garante que link de terceiro nunca baixa. O cliente Graph API (`instagramFeed.ts`) ganhou paginação por cursor com janela total declarada: `maxResults` continua o teto por página (50 ⇒ exatamente uma chamada, board intocado) e o resolver da peça pede **500 mídias** (`CONTENT_PIECE_LINK_INSTAGRAM_WINDOW`, early-stop no match, `paging.next` ignorado de propósito — leva o token na URL); refresh de token segue o contrato do dono e o `refreshedAccessToken` agora é persistido best-effort pelo helper existente. Quando a extração não acontece, a resolução devolve um **motivo honesto** em vocabulário fechado (novo select `linkFailureReason` + migration `20260924_045625_add_content_piece_link_failure_reason`): `nao-encontrado` ("Link não encontrado entre as mídias recentes do perfil"), `carrossel`, `indisponivel` e `sem-credencial` — com o teto de 4 GB da casa, storage e ffmpeg seguindo `falhou`/Reprocessar (sentinela `ContentPieceMediaTooLargeError` distingue o cap do transporte) e YouTube permanecendo link-only **sem** motivo. O job é o único escritor do motivo no write final `pronto`; anexar o arquivo original e o retry limpam o campo. A ficha porta o design aprovado classe-a-classe: placeholder "Buscando a mídia no perfil oficial…", barra "Procurando a publicação no perfil oficial…", card "Processamento da peça" com os três passos no desktop, card verde "Arquivo e transcrição prontos"/"Arquivo pronto" quando a mídia chega, e o card âmbar "Por que o arquivo não foi baixado" com o literal + "A peça continua disponível pelo link." + Anexar; a lista fica limpa, com o rótulo neutro "Instagram · Peça-link" no card mobile (o tipo não é repetido quando é palpite). Crítica final do `designer` certificada em tier primário (`openai/gpt-5.6-sol`) após corrigir o tracker no mobile (`hidden md:block`). Verificação: unit (`contentPiece` com parse prefixado/rejeições/labels verbatim/view model, `instagramFeed` com cursor/paginação/1 página no board), int (`contentPiece`: resolver com deps injetadas para match/carrossel/sem credencial/feed e download falhos/sentinela do teto, job/attach/retry persistindo e limpando o motivo), e2e (`campaignSpeechAcervo`: ficha mostra o literal, lista não), `pnpm gate:fast`, `pnpm test:int` (946) e o e2e afetado local.
|
||||
1
docs/changelog/2026-09-24-s33-card-time-ajuste-livre.md
Normal file
1
docs/changelog/2026-09-24-s33-card-time-ajuste-livre.md
Normal file
|
|
@ -0,0 +1 @@
|
|||
**S33 — Card do time: ajuste da foto livre, sem limite (2026-09-24):** nos dois modelos de time do estúdio de cards (`time-de-voce` e `time-do-estadual`), o ajuste do visitante — arrasto no quadro, botões de ajuste fino e setas/teclado — deixa de ser barrado pelo espaço transparente do recorte: a foto vai a qualquer posição nos dois eixos, inclusive para fora do quadro, revelando a arte de trás, e volta arrastando na mesma área ativa. A decisão é do gate humano de 2026-09-24 (o atrito reencontrado no teste do card com estadual é o mesmo que a S20 tentou resolver com âncora de silhueta — e cuja remoção no revert do S15/`48e08bf7` devolveu o limite): **sem limite nenhum**, sem âncora, caixa medida ou união de alcances. O enquadramento automático S15 (`frameCardPhotoOnBbox`) continua sendo o ponto de partida, aplicado uma vez ao carregar; os limites do zoom seguem `[1,4]`; prévia e PNG baixado mostram a mesma posição (sem "voltar sozinho"). A política é do **modelo**, não da chamada: o catálogo ganhou `photoPosition?: 'bounded' | 'free'` (`src/lib/cardModels.ts`; `'free'` só nos dois modelos do time — os 3 anteriores, a colinha e o nome ficam com o default omitido = bounded de hoje) e o dono da geometria aceita `CardPhotoClampOptions.position` (`clampCardPhotoTransform`/`cardPhotoDrawRect`/`panCardPhotoTransform` no último parâmetro, `zoomCardPhotoTransform` como 6º — o `anchor` segue posicional para não editar os pins S13/S14/S15); com `free`, só o zoom é normalizado e os offsets voltam intactos — inclusive no early-return do caminho "zoom inalterado", que era o ponto silencioso de snap-back. O `renderTeamCard` lê a MESMA política do modelo no desenho e no retorno (o retorno é o contrato do write-back do composer; re-clampar ali reintroduziria o snap-back) e o `renderPhotoCard`/`centerCardPhotoTransform`/`handlePhotoFile` ficam intocados — a superfície S13/S14 não muda em nada. Sem controle, copy, estado ou telemetria novos; sem migration/Consent/access; 100% no aparelho. Verificação: unit (novo describe do free com offsets preservados nos dois eixos, zoom ainda `[1,4]`, anti-snap-back do zoom inalterado e idempotência; pin de catálogo `'free'` só nos dois times; pin do retorno do `renderTeamCard` "zoom clampado, posição preservada" e do `renderPhotoCard` ainda bounded; os descritos default de clamp/pan/zoom/frame passam **sem edição**), e2e novo no `frontend` que discrimina (com o clamp antigo ele falha: 8× `Shift+→` = +384px contra o teto antigo de 88,67px da geometria do stub) e pina as duas falhas reais — o limite que persistia e o snap-back do write-back — sobre a sonda da arte de trás (`[246,246,248,255]`) com o slider ainda em 1, e2e S14/S15/S30/S31 verdes **sem edição** (enquadramento, harmonização, troca de estadual e download intactos), craft no browser com o stub nos dois modelos (foto totalmente fora no desktop 1280 e no drawer 390, arte de trás aparecendo, PNG gerado) e `pnpm gate:fast`. Sem trigger do `designer` (o artefato aprovado registra explicitamente "sem novidade de interface"; o diff não muda estrutura visual — só a régua pura e a fiação dos gestos no markup aprovado).
|
||||
1
docs/changelog/2026-09-24-s34-colinha-arte-exata.md
Normal file
1
docs/changelog/2026-09-24-s34-colinha-arte-exata.md
Normal file
|
|
@ -0,0 +1 @@
|
|||
**S34 — Minha colinha: a arte exata entregue pelo humano + a linha do estadual preenchida (2026-09-24):** a prévia e o PNG 1080×1920 do modelo `minha-colinha` deixam de ser uma recriação do zero e passam a ser **a arte aprovada** (`public/cards/modelo-colinha.jpeg`, 900×1600, o arquivo entregue pelo humano, cópia byte-a-byte do tile, sha256 `76505492…`) desenhada inteira no canvas com ampliação exata de 1,2× (`drawImage` em 1080×1920 + `imageSmoothingQuality='high'`); o único desenho novo é a 2ª linha, `DEPUTADO ESTADUAL`: máscara branca sobre o rótulo queimado, rótulo reposto à esquerda, nome de urna em caixa alta à direita e os cinco dígitos do catálogo S30, um por caixa impressa. Sem estadual escolhido, a arte aparece exatamente como entregue (caixas vazias e selos plenos) e o download segue desabilitado pelo `canAdvance` existente. A composição antiga foi **removida, não duplicada**: `COLINHA_LAYOUT`, `drawColinhaTop/Legal/Digit/Confirm`, `fitColinhaCandidate`, `colinhaVoteRows` e os literais legais/selos saíram; o modelo `minha-colinha` passa a ter `assetSrc` = a arte (sem `overlaySrc`/`lockupSrc`/`previewSrc`, e o campo `lockupSrc` de `CardModel` foi deletado), o tile da galeria cai no fallback `assetSrc` (mesma imagem) e a `Linha conferida` deriva `${COLINHA_ESTADUAL_LABEL} · NOME · 5 dígitos`. O subset `CardDrawContext` ganhou `imageSmoothingEnabled`/`imageSmoothingQuality` (extensão aditiva, só a colinha seta). A crítica final do `designer` (trigger c) reprovou a primeira passada e os ajustes entraram antes do push: o rótulo subiu de 23,22 para **26,9px** (cap height 19,2px igual aos rótulos impressos da arte), a prévia vazia foi de 145 para **248/236px** (cenas 01–02) e o desktop preenchido virou **grid de 2 colunas num dialog de 960px** (`data-colinha-filled` + `has-[[…]]:sm:max-w-[60rem]`, prévia com teto `max-h-[calc(92dvh-14rem)]` para o 9:16 nunca ser cortado pelo footer) — **certificado em tier primário** (`Design tier: openai/gpt-5.6-sol`) na segunda passada. Verificação: unit (`cardColinha` com os pins da geometria do gate/crítica, `fitColinhaRowName` e a varredura das 53 entradas provando `pairLeft ≥ mask.x`, tile sha256/900×1600; `cardRender` com ordem arte→máscara→rótulo→nome→dígitos, suavização, vazio sem um pixel desenhado; `cardModels` com o modelo repontado), e2e (`frontend`: vazio com a tinta queimada em `firstDarkX > 500` sem vermelho e caixas vazias, preenchido com rótulo e nome vermelho dentro da máscara + dígito na caixa + download/evento S32, pior nome `arthur` dentro da máscara, troca), `pnpm gate:fast`, e2e local do spec `frontend` (41/41) e `pnpm push`.
|
||||
1
docs/changelog/2026-09-24-s35.md
Normal file
1
docs/changelog/2026-09-24-s35.md
Normal file
|
|
@ -0,0 +1 @@
|
|||
**S35 — Header do modal de criação de card na largura do card (2026-09-24):** o `DialogHeader` do `CardComposer` no shell desktop ganha `flex-1` (classe final `min-w-0 flex-1 text-left`, paridade com o `DrawerHeader` mobile que já estava correto) — o bloco do título passa a ocupar a linha inteira do modal e o × volta para a borda direita, como nas cenas de dialog aprovadas; um fix cobre os seis modelos, sem tocar nas primitivas `ui/dialog`/`ui/Drawer`, sem copy/tipografia nova e com o drawer mobile pixel-idêntico. Verificação: `pnpm gate:fast` verde (lint + typecheck + 4482 unit); e2e do funil delegado ao CI (mudança de 1 classe sem lógica, decisão discricionária OPS72).
|
||||
1
docs/changelog/2026-09-24-s36.md
Normal file
1
docs/changelog/2026-09-24-s36.md
Normal file
|
|
@ -0,0 +1 @@
|
|||
**S36 — Central de Conteúdos: logo do header no tamanho da marca (2026-09-24):** a marca no header da Central pública (`/conteudos`) lia ~3× menor que a referência (`/jingles`) porque a caixa media a moldura transparente do PNG oficial (`jorge-solla-negativo.png`, canvas 1037×595, tinta 790×285), não o desenho. A correção é só no dono único `ContentPiecePageHeader` (page-local, sem tocar `CampaignPageHeader`): o `Image` direto (`h-7 sm:h-9`) vira a janela de recorte da opção A do design aprovado — `overflow-hidden` 142×39 no mobile (tinta 186px, left −22 / top −29) e 188×50 no desktop (tinta 246px, left −29 / top −38) — com o mesmo PNG oficial, sem binário novo no kit, sem migration/access/Consent e com header (`h-14 sm:h-16`), badge "Central de Conteúdos" e "Voltar à Central" intactos nas três superfícies (catálogo, peça, não-encontrado). Verificação: `pnpm gate:fast` verde (4489 unit), e2e `frontendConteudos` 7/7 verde, lado a lado com `/jingles` em 390/1280 e crítica final do `designer` **certificada** (`Design tier: openai/gpt-5.6-sol`).
|
||||
254
docs/plans/acervo-falas-web-ingestao-impl.md
Normal file
254
docs/plans/acervo-falas-web-ingestao-impl.md
Normal file
|
|
@ -0,0 +1,254 @@
|
|||
# Impl: C215 — Ingestão de falas da internet no acervo (descoberta, espelho e catálogo)
|
||||
|
||||
Status: executado
|
||||
Atualizado em: 2026-09-24
|
||||
Issue: #1291
|
||||
Intenção: docs/plans/acervo-falas-web-ingestao.md
|
||||
Appetite restante: herdado (~3–4 dias de engenharia + tempo de máquina; um outcome verificável — um lote de falas encontradas na web entra no catálogo com transcrição, facetas e mídia espelhada, reexecutável sem duplicar e com relatório honesto)
|
||||
|
||||
## Leitura da intenção
|
||||
|
||||
- **Outcome:** dado um lote de achados da web (plataforma + URL + metadados que a descoberta — C218 — já trouxe), cada fala vira registro no acervo com data, duração, transcrição com timestamps, temas/alcance/menções (mesmas facetas do "Falas da Câmara"), proveniência da classificação, origem (plataforma + URL) e canal/autor; a mídia é espelhada privada e preservada. Reexecutar não duplica nem sobrescreve curadoria manual e cada execução imprime relatório honesto (achados, novos, atualizados, ignorados, falhas, tempo e custo de ASR).
|
||||
- **O que NÃO negociar (lockdowns):**
|
||||
- Mídia espelhada é privada e preservada: nunca URL pública, nunca `/api/media/file`; leitura só pelo gate do acervo (`canReadSpeech`/`canReadCommunicationCatalog`, fail-closed; `advisor`/`leader` negados).
|
||||
- Nenhum segundo pipeline de ASR/classificação/upsert e nenhum segundo cadastro de pessoa (menções continuam texto; sem `Contact`, sem `Consent` novo — não há PII nova).
|
||||
- `sourceKey` da Câmara é identidade por contrato: a fala web nasce em namespace próprio (`web:*`) e não toca os registros existentes.
|
||||
- Guardas de execução: `assertLocalDatabase` + `FALAS_WEB_IMPORT_CONFIRM=1` para alvo não-local/override; `--dry-run` sem flag.
|
||||
- Não tocar feed do site público, Central de Conteúdos (C211 é dona da peça), publicação externa nem score de vaidade.
|
||||
- Curadoria manual nunca sobrescrita (hook `preserveManualFacets` existente é o pino).
|
||||
- **O que reavaliar (hipóteses da intenção vs. exploração):**
|
||||
- A intenção deixou "ferramenta de download e destino do espelho" para a implementação: ficam **yt-dlp** (YouTube/Instagram) + download HTTP direto (rádio/áudio) e uma collection privada nova `internetSpeechMedia` — decisões D2/D4.
|
||||
- "Modelo de dados" também estava em aberto: a exploração confirma que `Speech` não tem origem/plataforma/URL/canal/título/thumb/mídia espelhada e que **quatro superfícies leem `speech` sem discriminador** (`speechPageData`, `speechListFilters`, `speechCoverage`, `findSpeechExcerpts`) — sem blindagem a fala web vazaria para "Falas da Câmara" com crédito errado (D10).
|
||||
- `speechPosterJob`/`speechCutJob` são by-id (VOD Câmara) e degradam sozinhos — não entram nesta fatia.
|
||||
|
||||
## Abordagem recomendada
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
L["lote de achados (JSON)<br/>generatedAt + findings[]"] --> CLI["scripts/import-web-speeches.mjs<br/>zod + dedupe por sourceKey"]
|
||||
CLI --> PLAN["plano do lote<br/>novo · atualizar · ignorar"]
|
||||
PLAN -->|youtube/instagram| YTDLP["yt-dlp --dump-json<br/>YTDLP_PATH fail-closed"]
|
||||
PLAN -->|radio/audio| HTTP["download HTTP do mediaUrl"]
|
||||
YTDLP --> MEDIA[("internetSpeechMedia<br/>upload privado S3/disco")]
|
||||
HTTP --> MEDIA
|
||||
MEDIA --> FFMPEG["ffmpeg: mp3 mono 16k + chunks<br/>buildRecordingAudioFfmpegArgs"]
|
||||
FFMPEG --> ASR["deepInfraTranscribeSegments<br/>merge de offsets"]
|
||||
ASR --> CLS["classifySpeech<br/>gazetteer + LLM"]
|
||||
CLS --> UPSERT["upsertSpeechBundle estendido<br/>tx: speech + speechSegment + searchText"]
|
||||
UPSERT --> DB[("speech origin=web<br/>sourceKey web:...")]
|
||||
CLI --> REPORT["relatório stdout + JSON<br/>data/falas-web/reports"]
|
||||
DB -.->|"origin: camara nas consultas"| CAM["superfícies Câmara<br/>lista · opções · cobertura · Sollinha"]
|
||||
DB -.-> C216["C216: lista/detalhe/player<br/>buildPrivateMediaResponse"]
|
||||
DB -.-> C217["C217: cortes<br/>downloadPrivateMediaToFile"]
|
||||
```
|
||||
|
||||
**Opções consideradas:** A) estender `speech` com discriminador de origem + collection privada própria de mídia + aquisição yt-dlp/HTTP + pipeline com dependências injetadas | B) collection nova `internetSpeech` (gêmea) | C) reusar `recordingMedia` e/ou servir a mídia no próprio C215.
|
||||
**Recomendação:** A — porque preserva o contrato prod da Câmara (`sourceKey`, facetas, segmentos, busca) sem criar uma segunda cópia de todo o conhecimento (classificador, ASR, upsert, busca) e sem forçar relação polimórfica no `SpeechCut` que o C217 vai estender.
|
||||
**Rejeitadas:**
|
||||
|
||||
- **B (collection nova)** porque duplica facets/segmentos/classificador/import/busca e obriga `SpeechCut.speech` (relação fixa a `speech`) a virar polimorfismo, acoplando o C217 sem ganho.
|
||||
- **C (reusar `recordingMedia` / servir no C215)** porque `recordingMedia` é o artefato da gravação enviada (domínio e access próprios), e o serving pertence ao C216 (detalhe/player/baixar) e ao C217 (corte), que já consomem `privateMediaResponse.ts`; rota nova aqui seria trabalho jogado fora.
|
||||
|
||||
### Decisões de engenharia
|
||||
|
||||
**D1 — Modelo de dados: estender `speech` com discriminador de origem; NÃO criar collection de fala nova.**
|
||||
`Decisão: A — novos campos nullable em Speech (só origin obrigatório) + sourceKey namespaced web:*; Câmara intacta.`
|
||||
`Por quê: reusa facetas, segmentos, classificador, upsert, busca trigram e access já existentes; a fala web é a mesma unidade de catálogo ("mesmas facetas, mesmos filtros" — intenção).`
|
||||
`Rejeitadas: B) collection nova internetSpeech porque é gêmea de facets/segmentos/classificador/import/busca e força relação polimórfica no SpeechCut (C217); C) sem migration — impossível: mídia espelhada + origem/canal exigem schema.`
|
||||
|
||||
- Campos novos: `origin` (select `camara` default | `web`, required, index — backfill dos existentes pelo default da migration); `platform` (select `youtube|instagram|radio|audio`, index, web-only); `externalId`; `sourceUrl`; `title`; `channel`; `mirroredMedia` (upload → `internetSpeechMedia`); `thumbnail` (upload → mesma collection).
|
||||
- Reusados sem mudança: `speechAt` (data de publicação no caso web; `deriveSpeechYear` continua), `durationSeconds`, `searchText`, facets, `classifiedBy`, `speechSegment`. `legislature`/`type`/`phase`/VOD ficam nulos na origem web (já são nullable).
|
||||
- `sourceKey` namespaced: `web:<platform>:<externalId>` quando houver id externo; senão `web:<platform>:<url canônica normalizada>`. Câmara permanece exatamente como está (o índice unique já existe e o namespace elimina colisão).
|
||||
|
||||
**D2 — Mídia privada: collection de upload nova `internetSpeechMedia`.**
|
||||
`Decisão: A — collection privada própria; read = canReadSpeech; create/update/delete = payloadAdminOnly (o CLI usa overrideAccess justificado); registro explícito no plugin S3; cascade no beforeDelete do Speech.`
|
||||
`Por quê: a mídia da fala web tem gate do acervo, não o gate da gravação; e o dono do ciclo de vida é o próprio Speech (a mídia não existe sem a fala).`
|
||||
`Rejeitadas: reusar recordingMedia (domínio/labels/access da gravação enviada — faria o modelo mentir); usar media pública (read anônimo por contrato — vazaria mídia de terceiro).`
|
||||
|
||||
- Sem registro no plugin S3 (`internetSpeechMedia: true`), produção cai no disco efêmero do container — mesmo modo de falha documentado no C199.
|
||||
- Cascade: estender o `beforeDelete` do `Speech` (hoje apaga `speechSegment`) para apagar `mirroredMedia`/`thumbnail` quando existirem, com o mesmo bypass justificado (cascade é do dono; roda dentro do delete autorizado do Speech).
|
||||
|
||||
**D3 — Servir o arquivo é do C216/C217, não daqui.**
|
||||
`Decisão: A — C215 entrega só o artefato armazenado + a collection; C216 usa buildPrivateMediaResponse (detalhe/player/baixar) e C217 usa downloadPrivateMediaToFile (corte).`
|
||||
`Por quê: o dono único de I/O privado já existe (privateMediaResponse.ts, C193/C199) e a superfície de leitura nasce no C216; rota nova aqui não tem consumidor.`
|
||||
`Rejeitadas: rota de arquivo no C215 (sem UI/consumidor, morreria no C216); signed URLs do S3 (já rejeitado no C193: endpoint interno inalcançável do browser).`
|
||||
|
||||
**D4 — Aquisição: yt-dlp (YouTube/Instagram) + download HTTP direto (rádio/áudio).**
|
||||
`Decisão: A — yt-dlp via YTDLP_PATH → PATH, fail-closed com hint de instalação; radio/audio exigem mediaUrl no lote; qualidade suficiente (≤720p, H.264/AAC, merge mp4) e áudio direto preservado; metadados do --dump-json preenchem lacunas; resolver de ffmpeg extraído de reelFfmpeg.mjs para módulo neutro.`
|
||||
`Por quê: yt-dlp é a ferramenta que cobre as duas plataformas confirmadas no gate; o lote do C218 já traz URL e (quando houver) mídia direta; o probe/resolução de binário já existe e testado nos reels — extrair o dono é melhor que um segundo resolver.`
|
||||
`Rejeitadas: gallery-dl/TikTok/Facebook/X (fora das plataformas v1); baixar em qualidade máxima/master (disco e tempo sem necessidade); transcode forçado (o ASR extrai o áudio e o player/corte consomem o arquivo como veio); segunda cópia do resolver de ffmpeg (twin).`
|
||||
|
||||
- `YTDLP_PATH` é o seam de teste (padrão do `FFMPEG_PATH`): os testes injetam um fake pelo env. Sem binário e sem caminho → falha fechada com hint (ex.: `pipx install yt-dlp`), nunca "segue sem baixar".
|
||||
- Achado `radio`/`audio` sem `mediaUrl` → falha honesta no relatório (estágio `validation`/`download`), o lote continua.
|
||||
- ffmpeg: extrair `runProcess`/`probeFfmpeg`/`resolveFfmpeg` de `scripts/lib/reelFfmpeg.mjs` para `scripts/lib/mediaBinaries.mjs`; `reelFfmpeg.mjs` re-exporta (API dos reels intacta e unit tests dos reels verdes). O script novo resolve o binário e seta `FFMPEG_PATH` resolvido quando o env não veio explícito, para que `src/utilities/media/ffmpeg.ts` (dono de execução) use o mesmo binário.
|
||||
|
||||
**D5 — Donos únicos reusados (proibido gêmeo).**
|
||||
`Decisão: A — ASR deepInfraTranscribeSegments + chunking/merge puros de recordingTranscription.ts; classificação classifySpeech; upsertSpeechBundle ESTENDIDO com campos web opcionais; privateMediaResponse.ts; withPayloadTransaction.`
|
||||
`Por quê: são os donos já testados e usados pelo Câmara/C199; a fala web tem o mesmo problema (áudio longo → chunks → segmentos com timestamps) e a mesma curadoria.`
|
||||
`Rejeitadas: chamar deepInfraTranscribe sem timestamps (não entrega o aceite); portar o normalizador do CLI da Câmara para um módulo novo (já é dono em recordingTranscription.ts); escrever o upsert da web à parte (dois escritores da mesma tabela = facetas divergindo).`
|
||||
|
||||
- `upsertSpeechBundle` ganha os campos web **opcionais** no bundle (origin/platform/externalId/sourceUrl/title/channel/mirroredMedia/thumbnail) e `findSpeechImportState` passa a devolver o estado web (origin, platform, externalId, sourceUrl, mirroredMedia, thumbnail) para as decisões de skip/reprocess. O caminho Câmara (bundle sem os campos web) continua idêntico; o `metadataData` da Câmara não muda.
|
||||
- Escrita multi-collection: a ingestão cria o upload `internetSpeechMedia` e roda o upsert **na mesma transação** (`withPayloadTransaction`), passando o `req` ao upsert; sem `req`, o upsert abre a própria transação (Câmara segue igual). Objeto S3 órfão em rollback é aceito e registrado (best-effort de limpeza no catch).
|
||||
- O artefato espelhado é o input do ffmpeg: a ingestão baixa o objeto para temp com `downloadPrivateMediaToFile` (mesmo dono do job de gravação), extrai/dividi com `buildRecordingAudioFfmpegArgs` e mescla com `mergeChunkTranscriptions`/`recordingSearchText`.
|
||||
|
||||
**D6 — Contrato do lote (interface do C218).**
|
||||
`Decisão: A — JSON { generatedAt, findings: [...] }, schema zod puro em src/lib/webSpeech.ts; finding com platform/url/mediaUrl?/externalId?/title?/channel?/publishedAt (obrigatório)/durationSeconds?/thumbnailUrl?; mediaUrl obrigatória para radio|audio; dedupe por sourceKey dentro do lote.`
|
||||
`Por quê: o C218 descobre e cura; a ingestão valida — o contrato é a fronteira entre os dois e precisa ser puro (client-safe, unit-testável) e explícito sobre a obrigatoriedade de mediaUrl nas plataformas sem extrator.`
|
||||
`Rejeitadas: aceitar qualquer JSON sem validação (falha silenciosa vira lixo no catálogo); exigir todos os metadados (a descoberta não garante tudo — o yt-dlp completa as lacunas).`
|
||||
|
||||
- O envelope é validado uma vez; cada finding é validado individualmente (`safeParse`) para que um achado inválido vire falha do achado no relatório, sem derrubar o lote (espírito do aceite do C218: falha de um não derruba o lote).
|
||||
- Duplicado dentro do lote (mesmo sourceKey) = ignorado, contado no relatório.
|
||||
|
||||
**D7 — Idempotência.**
|
||||
`Decisão: A — reexecução pula item completo (segmentos + mídia espelhada) atualizando metadados; --reprocess força re-download/re-ASR; curadoria manual nunca sobrescrita; --dry-run planeja sem rede e sem escrita (lê estado do banco); --limit.`
|
||||
`Por quê: o aceite exige reexecutar sem duplicar; o padrão já é o do import da Câmara (skip por estado) e do C199 (retry reusa o que existe).`
|
||||
`Rejeitadas: re-baixar/re-transcrever sempre (tempo e custo de ASR sem ganho); apagar-e-recriar o registro (perderia curadoria manual e quebraria a identidade sourceKey).`
|
||||
|
||||
**D8 — Relatório por execução.**
|
||||
`Decisão: A — stdout + JSON em <out>/reports/<timestamp>.json (out default data/falas-web/, gitignored, padrão data/camara/): achados, novos, atualizados, ignorados (duplicados/já completos), falhas (com estágio e motivo), tempo total, segundos de ASR, custo ASR (constante DeepInfra existente) e custo LLM quando houver.`
|
||||
`Por quê: falha não é maquiada e o operador precisa decidir o que reprocessar; o formato segue o CLI da Câmara (mesma família de relatórios gitignored).`
|
||||
`Rejeitadas: só stdout (não auditável); gravar falha como estado do item no catálogo (a intenção cortou: item que falhou fica fora da lista e aparece no relatório).`
|
||||
|
||||
**D9 — Guardas de execução.**
|
||||
`Decisão: A — assertLocalDatabase + FALAS_WEB_IMPORT_CONFIRM=1 para alvo não-local/override (mesmo padrão de CAMARA_IMPORT_CONFIRM); --dry-run é modo read-only e não exige a flag.`
|
||||
`Por quê: a ingestão escreve no acervo real e baixa mídia de terceiro; o guard de intenção explícita é o mesmo contrato já auditado no C155/C160.`
|
||||
`Rejeitadas: confiar só no host (o proxy do homeserver reescreve para 127.0.0.1 e NODE_ENV=production é o sinal honesto — o guard compartilhado já cobre); --dry-run exigindo a flag (travaria o planejamento inofensivo).`
|
||||
|
||||
**D10 — Blindagem das superfícies Câmara (obrigatória).**
|
||||
`Decisão: A — adicionar origin: camara ao where da lista/opções (speechListFilters.ts/speechPageData.ts), ao speechCoverage.ts (SQL) e ao findSpeechExcerpts.ts; testes pinam.`
|
||||
`Por quê: a fala web nasce invisível às superfícies existentes; sem isso a ingestão vaza para "Falas da Câmara" com crédito errado e o Sollinha sugeriria trechos com link de player da Câmara que não toca o arquivo. C216 abre a fonte própria e C219 cuida da paridade.`
|
||||
`Rejeitadas: filtrar no client/view-model (não protege paginação/contagem/cobertura/SQL); abrir a fonte web nessas superfícies agora (é o C216, com contrato de URL próprio).`
|
||||
|
||||
**D11 — Nomes/arquivos.**
|
||||
`Decisão: A — src/lib/webSpeech.ts (puro: plataformas+labels, schema zod do lote, webSpeechSourceKey, normalização de URL canônica, INTERNET_SPEECH_MEDIA_SLUG); src/utilities/media/ytdlp.ts (dono do binário/execução/metadados); src/utilities/speech/webSpeechIngest.ts (pipeline por achado com deps injetadas — testável); scripts/import-web-speeches.mjs + scripts/lib/webSpeeches.mjs (helpers puros do CLI); src/collections/InternetSpeechMedia.ts; script pnpm falas-web:import.`
|
||||
`Por quê: cada concern cai no dono existente (lib puro, utilities/media, utilities/speech) sem módulo top-level novo em utilities/ (regra do codebase-map); o CLI mantém o padrão scripts/<verbo>-<objeto>.mjs + lib pura.`
|
||||
`Rejeitadas: um único módulo gigante (não testável por camada); pipeline dentro do CLI (não reaproveitável e sem injeção de deps); nome em português para identificadores (convenção: copy pt-BR, identificadores em inglês).`
|
||||
|
||||
**D12 — Migration.**
|
||||
`Decisão: A — pnpm migrate:create add_web_speech_origin (campos + collection + índices); nunca editar migrations existentes; HARD-STOP humano antes de criar/aplicar, mesmo no modo --auto.`
|
||||
`Por quê: schema muda só por migration committed; o build aplica pendentes em produção, então a migration é o ponto de não-retorno e exige confirmação explícita.`
|
||||
`Rejeitadas: push automático (push: false é invariante); editar a migration inicial/prod (história congelada); SQL manual no banco (não sobrevive a deploy).`
|
||||
|
||||
**D13 — Testes.**
|
||||
`Decisão: A — unit de src/lib/webSpeech.ts (schema/sourceKey/URL canônica) + unit dos helpers puros do script (plano/relatório); int do upsert estendido (round-trip dos campos web, idempotência, manual preservado, mídia privada) e do pipeline com fakes (YTDLP_PATH fake, transcriber/classificador injetados, FFMPEG_PATH fake do repo); unit dos reels continua verde após a extração do resolver. Sem e2e novo (sem UI); rodar pnpm test:e2e:affected se o classifier selecionar specs do acervo.`
|
||||
`Por quê: não há superfície nova; as camadas inferiores cobrem o risco real (schema, idempotência, blindagem, download).`
|
||||
`Rejeitadas: e2e de script (não há harness para scripts — o padrão é unit da lib pura + int do upsert); e2e de UI (não há UI no C215).`
|
||||
|
||||
- Atualizar `scripts/lib/e2e-affected-manifest.mjs` (entry do acervo, ~linha 434) com `src/lib/webSpeech`, `src/collections/Speech.ts` e `src/collections/InternetSpeechMedia.ts` para não cair no smoke fallback. (`src/utilities/speech`, `src/utilities/media` e `src/lib/speech*` já estão mapeados; `src/lib/webSpeech` e as collections não casam prefixo nenhum hoje.)
|
||||
|
||||
### Componentes / mudanças
|
||||
|
||||
- **`Speech`** (`src/collections/Speech.ts`, editar): campos de origem/mídia (D1); `beforeDelete` estendido para apagar `mirroredMedia`/`thumbnail` (D2); `admin.description`/`defaultColumns` passam a citar as duas origens. Nenhum campo da Câmara muda.
|
||||
- **`InternetSpeechMedia`** (`src/collections/InternetSpeechMedia.ts`, novo): upload privado; `alt` obrigatório (preenchido pelo pipeline); access D2; `admin.group: 'Comunicação'` com descrição de privacidade (forma de `RecordingMedia.ts`).
|
||||
- **`src/lib/webSpeech.ts`** (novo, puro): `WEB_SPEECH_PLATFORMS` + labels pt-BR ("YouTube", "Instagram", "Rádio", "Áudio"), schema zod do envelope/finding, `webSpeechSourceKey`, `canonicalWebSpeechUrl`, `INTERNET_SPEECH_MEDIA_SLUG`.
|
||||
- **`src/utilities/media/ytdlp.ts`** (novo): resolução fail-closed do binário (`YTDLP_PATH` → PATH), execução e parse do `--dump-json` (título/canal/data/duração/id externo/thumb), args de qualidade ≤720p H.264/AAC `--merge-output-format mp4`.
|
||||
- **`src/utilities/speech/webSpeechIngest.ts`** (novo): pipeline por achado com deps injetadas (downloader, transcriber, classifier, runner de ffmpeg) — reusa os donos do D5 e devolve o resultado por achado (novo/atualizado/ignorado/falha com estágio).
|
||||
- **`src/utilities/speech/speechImport.ts`** (editar): bundle + state com os campos web opcionais; `upsertSpeechBundle` aceita `req` de transação aberta (Câmara sem `req` segue abrindo a própria).
|
||||
- **`scripts/lib/mediaBinaries.mjs`** (novo): extração de `runProcess`/`probeFfmpeg`/`resolveFfmpeg`; `scripts/lib/reelFfmpeg.mjs` re-exporta sem mudar a API.
|
||||
- **`scripts/lib/webSpeeches.mjs`** (novo, puro): plano do lote (dedupe/ordem/skip por estado), agregação e linhas do relatório.
|
||||
- **`scripts/import-web-speeches.mjs`** (novo): CLI (`--findings <arquivo>` — interface do C218 —, `--out`, `--limit`, `--dry-run`, `--reprocess`), guardas D9, caches de download no padrão `ensureCachedDownload`, relatório D8.
|
||||
- **`package.json`** (editar): script `falas-web:import` (padrão do `camara:import`).
|
||||
- **`.gitignore`** (editar): `data/falas-web/`.
|
||||
- **`payload.config.ts`** (editar): registrar `InternetSpeechMedia` na lista de collections e `internetSpeechMedia: true` no plugin S3.
|
||||
- **`scripts/lib/e2e-affected-manifest.mjs`** (editar): prefixos do D13.
|
||||
- **Migration:** `pnpm migrate:create add_web_speech_origin` — enum `origin`/`platform`, colunas em `speech` (`origin` NOT NULL DEFAULT `'camara'`, demais nullable), tabela `internet_speech_media` + FKs + índices (`origin`, `platform`) e as rels de locked documents. Revisar o SQL gerado; **não** criar índice trigram novo (o `speech_search_text_trgm_idx` da C154 cobre as duas origens). **HARD-STOP humano (mesmo em `--auto`), local-only** antes de criar/aplicar; nunca editar migrations antigas.
|
||||
- **Access / Consent:** `read = canReadSpeech`; `create/update/delete = payloadAdminOnly`; o CLI/pipeline usam `overrideAccess: true` com comentário justificado (ator confiável sem sessão, padrão do import da Câmara). Sem `Consent` novo (sem PII/opt-in; menções continuam texto).
|
||||
- **UI:** N/A — sem UI (C216 é dono da tela; Impeccable A no plano de intenção).
|
||||
|
||||
### Dados → forma (se aplicável)
|
||||
|
||||
- **N/A por decisão da intenção** (`acervo-falas-web-ingestao.md:35`): aqui nenhum agregado é apresentado; o relatório de execução é insumo operacional de quem roda o CLI, não superfície de usuário — sem dashboard de vaidade nem score. Nada a apresentar; nenhuma forma nova.
|
||||
|
||||
## Fases verificáveis
|
||||
|
||||
1. **Tracer / schema + server** (~1 dia).
|
||||
- `src/lib/webSpeech.ts`; `InternetSpeechMedia`; campos/`beforeDelete` no `Speech`; registro em `payload.config.ts`; `pnpm generate:types`; `upsertSpeechBundle`/`findSpeechImportState` estendidos.
|
||||
- Unit: schema do lote (envelope/finding, `mediaUrl` obrigatória em radio|audio), `webSpeechSourceKey`, URL canônica, labels.
|
||||
- Int: round-trip dos campos web (create/update), idempotência do upsert, `manual` preservado, cascade da mídia no delete do Speech.
|
||||
- **Migration `add_web_speech_origin` — HARD-STOP humano, local-only** (confirmação explícita antes de criar/aplicar).
|
||||
2. **Aquisição + pipeline** (~1 dia).
|
||||
- `scripts/lib/mediaBinaries.mjs` (extração; unit dos reels verde); `src/utilities/media/ytdlp.ts`; `src/utilities/speech/webSpeechIngest.ts`.
|
||||
- Unit: resolução fail-closed do yt-dlp + parse do metadata (fake via `YTDLP_PATH`); args de qualidade; plano do pipeline.
|
||||
- Int: pipeline com fakes (`YTDLP_PATH` fake, transcriber/classificador injetados, `FFMPEG_PATH` fake) — happy path com espelho + segmentos + searchText; falha de download/ASR → falha no relatório sem row fantasma; `--reprocess` re-baixa/re-transcreve; segunda execução não re-baixa nem re-transcreve.
|
||||
3. **CLI + relatório** (~0,75 dia).
|
||||
- `scripts/lib/webSpeeches.mjs` + `scripts/import-web-speeches.mjs`; `package.json`; `.gitignore`.
|
||||
- Unit: dedupe por sourceKey, plano (novo/atualizar/ignorar), agregação do relatório, falhas por estágio.
|
||||
- Int/manual: `--dry-run` sem rede e sem escrita (lê estado do banco); guardas (`FALAS_WEB_IMPORT_CONFIRM`/`assertLocalDatabase`); JSON em `<out>/reports/<timestamp>.json`.
|
||||
4. **Blindagem Câmara** (~0,25 dia).
|
||||
- `origin: camara` em `buildSpeechFacetWhere` (cobre `buildSpeechListWhere` e `buildSpeechListWhereIncludingCutOrigins`), `loadSpeechFilterOptions`, `speechCoverage.ts` (SQL) e `findSpeechExcerpts.ts`.
|
||||
- Unit: where/coverage com o discriminador; int: fala web não aparece na lista, nas opções, na cobertura nem no Sollinha; cobertura da Câmara inalterada.
|
||||
5. **Testes + gates** (~0,5 dia).
|
||||
- Manifest e2e; `pnpm gate:fast`; `pnpm test` (unit + int); `pnpm test:e2e:affected` (se o classifier selecionar specs do acervo); `pnpm push`.
|
||||
|
||||
Quota: ~3,5 dias eng + tempo de máquina (download/ASR), dentro do appetite herdado. Se apertar, o corte é o enriquecimento de metadados pelo `--dump-json` (o lote já traz os campos) — nunca as garantias: idempotência, guardas, relatório e blindagem.
|
||||
|
||||
## Rabbit holes / Não escopo (engenharia)
|
||||
|
||||
- Descoberta/crawler/monitoramento e agendamento (C218); varredura de perfis.
|
||||
- TikTok/Facebook/X, gallery-dl, login/cookies para conteúdo privado.
|
||||
- Segundo pipeline de ASR/classificação/upsert; segundo serving de mídia (C216/C217); segundo resolver de ffmpeg.
|
||||
- Publicar mídia/URL pública; reusar `media` pública; reusar `recordingMedia`; signed URLs.
|
||||
- Transcode/qualidade máxima/masters; geração de thumbnail (só armazena a da origem quando o lote/yt-dlp trouxer; C216 mostra placeholder sem ela); ffprobe.
|
||||
- UI (C216), cortes (C217), paridade de filtros (C219), diarização, edição de transcrição, publicação.
|
||||
- Merge multi-fonte/busca global; item de nav novo; tocar o feed do site ou a Central de Conteúdos (C211).
|
||||
- Dedupe entre plataformas (mesma fala no YouTube e no Instagram) — identidade é por origem; cross-platform é item próprio.
|
||||
- Limpeza de mídia órfã fora do cascade do Speech; retenção/expurgo.
|
||||
- Alterar `sourceKey`/dados da Câmara; editar migrations antigas; `push` de schema.
|
||||
|
||||
## Riscos e mitigação
|
||||
|
||||
- **yt-dlp ausente ou quebrado por mudança de plataforma.** Fail-closed com hint de instalação; falha por achado no relatório com estágio; rerodar após atualizar; testes injetam fake por `YTDLP_PATH`.
|
||||
- **Instagram bloqueia/expira sem login.** Falha honesta no relatório; fluxo de cookies/login fora da v1 (declarado); o lote pode trazer `mediaUrl` quando a descoberta tiver o arquivo direto.
|
||||
- **Custo/tempo de ASR em horas de vídeo.** `--limit` e `--dry-run`; relatório com segundos e custo; o cap de qualidade evita baixar master (o ASR extrai áudio, não precisa de 4K).
|
||||
- **Disco efêmero em produção (`internetSpeechMedia: true` esquecido).** Registro no plugin no mesmo PR + checklist de aceite; `resolveS3StorageEnv` falha fechado em config S3 parcial; dev/test em disco local.
|
||||
- **Vazamento da fala web para as superfícies Câmara (crédito errado).** D10 + pins unit/int; a fala web nasce invisível à lista/opções/cobertura/Sollinha.
|
||||
- **Duplicata por URL não canônica (tracking params, host, barra final).** `canonicalWebSpeechUrl` unit-pinada + dedupe no lote + `sourceKey` namespaced (índice unique já existente).
|
||||
- **Migração em prod (coluna NOT NULL).** `origin` nasce com default `'camara'` na migration — linhas existentes cobertas; HARD-STOP humano; nunca editar migrations antigas; o deploy aplica pendentes.
|
||||
- **Regressão da Câmara pelo upsert estendido.** Campos web opcionais; `metadataData` da Câmara intocado; os int existentes (`speechImport.int.spec.ts`) são o pino.
|
||||
- **Curadoria manual sobrescrita em `--reprocess`.** Hook `preserveManualFacets` é o pino; int cobre o re-run sobre registro `manual`.
|
||||
- **PR high-risk (migration) roda só o conjunto curado de e2e**, que não inclui `campaignSpeechAcervo` — a blindagem e o pipeline ficam pinados por unit/int; incluir o spec no curado é mudança deliberada de pin, a decidir se a cobertura e2e for exigida.
|
||||
- **Objeto S3 órfão em rollback da transação de upload+upsert.** Best-effort de limpeza no catch; órfão é inofensivo (bucket privado) e reexecutar reusa/sobrescreve.
|
||||
|
||||
## Aceite de engenharia
|
||||
|
||||
- [ ] Aceite de produto da intenção ainda coberto: cada fala com data/duração/transcrição com timestamps/facetas/menções/proveniência/origem/canal; mídia espelhada privada e preservada; reexecução não duplica nem sobrescreve curadoria; relatório honesto (achados/novos/atualizados/ignorados/falhas/tempo/custo ASR); sem espelho público, sem segundo cadastro, sem publicação.
|
||||
- [ ] Invariantes AGENTS/engineering-standards: `overrideAccess: false` + `user` onde há ator (leitura C216/C217 nasce no C216; aqui o CLI é ator confiável com bypass justificado); escrita multi-collection em transação (`withPayloadTransaction` + `req`); sem `Consent`/PII novos; `sourceKey` da Câmara intacto; sem rota/URL pública nova; migração nova sem editar antigas; copy pt-BR / identificadores em inglês; `pnpm gate:fast` e `pnpm push`.
|
||||
- [ ] Testes de domínio previstos (unit/int) onde access/write paths mudam: schema/sourceKey/URL canônica; upsert estendido (round-trip, idempotência, `manual`, mídia privada); pipeline com fakes; cascade da mídia; blindagem Câmara (lista/opções/cobertura/Sollinha); reels unit verde após a extração do resolver.
|
||||
- [ ] Migration `add_web_speech_origin` com HARD-STOP humano (mesmo em `--auto`), local-only, revisada antes de aplicar.
|
||||
- [ ] `internetSpeechMedia: true` no plugin S3 (sem isso, produção cai no disco efêmero).
|
||||
- [ ] Manifest e2e atualizado (`src/lib/webSpeech`, `src/collections/Speech.ts`, `src/collections/InternetSpeechMedia.ts`) para não cair no smoke fallback.
|
||||
|
||||
## Execução — desvios do plano (2026-09-24)
|
||||
|
||||
- **Thumbnail fora da transação principal (D5 refinado).** O upload da capa roda em best-effort **antes** da transação (media + upsert) e é limpo se a transação falhar: uma imagem quebrada (o sharp do Payload reprocessa imagens) nunca derruba a fala — o teste int cobre o caminho com um JPEG real. No `--reprocess`, se a capa nova falhar, a antiga é preservada (só é apagada quando há substituta).
|
||||
- **`publishedAt` é obrigatório no schema** (o aceite exige data por fala) e um valor com fuso explícito é convertido para `America/Bahia` antes de virar `speechAt`; data impossível falha o achado em vez de virar mentira no card.
|
||||
- **Pós-simplify:** o `defaultRun` do `reelFfmpeg` (referência órfã após a extração) foi reconectado; `downloadUrlToFile` ganhou teto de bytes (4 GiB); `databaseTarget`/`assertWriteConfirm` viraram helpers do `scripts/lib/cli.mjs` usados pelos dois CLIs; o predicado de completude foi para `src/lib/webSpeech.ts`; a constante de custo do ASR passou a ter dono único (o CLI da Câmara re-exporta a do app).
|
||||
- **`ytDlpBinary` não usa o resolver de `mediaBinaries.mjs`.** Não existe binário empacotado de yt-dlp; o dono `src/utilities/media/ytdlp.ts` resolve `YTDLP_PATH` → PATH com probe `--version` fail-closed. O resolver extraído de `reelFfmpeg.mjs` continua sendo usado só para o ffmpeg (o script resolve com fallback empacotado e seta `FFMPEG_PATH`).
|
||||
- **`upsertSpeechBundle` ganhou `options.req`** e `origin` no bundle (default `'camara'` no create) em vez de um writer novo — o caminho Câmara não mudou.
|
||||
- **Testes existentes pinados:** `speechListFilters.unit.spec.ts` e `speechExcerptsTool.unit.spec.ts` passam a esperar `origin: camara`; os creates de `speech` em int/e2e ganharam `origin: 'camara'` (o campo é required no tipo gerado).
|
||||
- **`scripts/lib/mediaBinaries.mjs` e `scripts/lib/webSpeeches.mjs` entraram no `SCRIPTS_SPEC_PINNED`** (invariante OPS119++ de blast radius).
|
||||
- **Smoke local:** `pnpm falas-web:import --findings … --dry-run` (plano com inválido/duplicado) e a execução real com yt-dlp ausente (falha honesta no relatório + exit 1) rodados contra o banco local do worktree. O run real com mídia é do operador (C218) — a esteira não é executada em produção por este PR.
|
||||
|
||||
## Simplify — triage dos revisores (2026-09-24)
|
||||
|
||||
Aplicados na sessão (não reabrir): referência órfã do `defaultRun` no `reelFfmpeg` (bug real de produção), teto de bytes no `downloadUrlToFile`, helpers `databaseTarget`/`assertWriteConfirm` no `scripts/lib/cli.mjs` usados pelos dois CLIs, predicado de completude no `src/lib/webSpeech.ts`, dono único da constante de custo de ASR (o CLI da Câmara re-exporta a do app), tipos do `recordingTranscription`, `ffmpegBinary` exportado do dono, mensagens pt-BR no schema do achado, `isComplete`/skip preservando a duração armazenada, capa antiga preservada quando a nova falha, regex de data ancorada + calendário + fuso, testes de `downloadToFile` e asserções endurecidas.
|
||||
|
||||
| ID | Resumo | Origem | Score | Tipo | Destino |
|
||||
| --- | ----------------------------------------------------------------------------------------- | ---------------- | ----- | -------------- | --------------------------------------------------------------------------------- |
|
||||
| S1 | `downloadUrlToFile` como dono único do streamer (os outros 3 paths não têm teto de bytes) | simplify/reuse | 3 | expensive_lock | defer — gatilho: quando o C217 precisar baixar mídia externa ou surgir um 4º path |
|
||||
| S2 | `mediaIdOf` duplicado (hook do `Speech` vs `speechImport`) | simplify/reuse | 1 | cheap_polish | descartar (2 linhas, idioma local) |
|
||||
| S3 | `ingestWebSpeech` ainda com ~180 linhas | simplify/quality | 2 | cheap_polish | descartar (extração feita; fluxo linear pinado por int) |
|
||||
| S4 | Nome do arquivo espelhado genérico (`source.mp4`) | simplify/quality | 2 | cheap_polish | defer — gatilho: C216 define o nome de download (`dispositionFilename`) |
|
||||
| S5 | Cap de bytes ausente nos 3 paths pré-existentes de download | simplify/reuse | 3 | expensive_lock | descartar deste lote (pré-existente em main, fora do escopo; S1 é o gatilho) |
|
||||
|
||||
## Self-score de decision-quality
|
||||
|
||||
**4,5/5.**
|
||||
|
||||
- **Decisões caras com rejeitadas (1):** as 13 decisões registradas têm opções e rejeições ancoradas em file:line/contrato (`sourceKey` unique da Câmara, relação fixa `SpeechCut.speech`, `preserveManualFacets`, `reelFfmpeg` já testado, `resolveS3StorageEnv` fail-closed, `push: false`, ausência de yt-dlp no repo).
|
||||
- **Cabe no appetite (2):** schema+server → aquisição/pipeline → CLI/relatório → blindagem → testes/gates ≈3,5 dias eng + tempo de máquina, dentro dos ~3–4 dias herdados; tracer cedo no schema/upsert antes do pipeline.
|
||||
- **Rabbit holes nomeados (3):** descoberta/crawler, plataformas fora da v1, segundo pipeline/serving, transcode/master, merge multi-fonte, dedupe cross-platform, limpeza de órfãos.
|
||||
- **Depth check (4):** reusa `upsertSpeechBundle`, `deepInfraTranscribeSegments`, `classifySpeech`, `recordingTranscription`, `privateMediaResponse`, `withPayloadTransaction`, `ensureCachedDownload`, `assertLocalDatabase`; extrai o resolver de binário para um dono neutro em vez de criar um segundo; nada de módulo top-level novo em `src/utilities/`.
|
||||
- **Outcome preservado (5):** a engenharia não reescreveu o produto — a fala web entra no catálogo com as mesmas facetas, privada, idempotente e com relatório honesto; o que ficou de fora (tela, cortes, descoberta) é exatamente o que a intenção cortou.
|
||||
|
||||
Perde 0,5 porque duas pontas ficam condicionadas a confirmação humana/execução fora do código: o HARD-STOP da migration (deliberado) e a cobertura e2e do PR high-risk (conjunto curado não inclui `campaignSpeechAcervo`; a blindagem fica pinada por unit/int) — o plano declara isso em vez de fingir que está coberto.
|
||||
209
docs/plans/acervo-paridade-busca-filtros-impl.md
Normal file
209
docs/plans/acervo-paridade-busca-filtros-impl.md
Normal file
|
|
@ -0,0 +1,209 @@
|
|||
# Impl: C219 — Paridade de busca e filtros entre as fontes do acervo
|
||||
|
||||
Status: aprovado
|
||||
Atualizado em: 2026-09-24
|
||||
Issue: #1295
|
||||
Intenção: docs/plans/acervo-paridade-busca-filtros.md
|
||||
Appetite restante: herdado (~2–3 dias eng)
|
||||
|
||||
## Leitura da intenção
|
||||
|
||||
- **Outcome:** "Gravações enviadas" passa a oferecer os mesmos gestos de garimpo da Câmara — busca `termo|tema`, filtros por Ano, Tema, Alcance, Município citado, Duração (e Pessoa, que segue exclusiva), chips ativos, contagem, ordenação e vazio honesto — com classificação automática e proveniência auditável sobre a transcrição já existente, sem tocar no player/download nem no contrato da Câmara.
|
||||
- **O que NÃO negociar:**
|
||||
- "Pessoa" continua **exclusiva** das gravações (rótulo derivado, nunca segundo cadastro de pessoa — C200).
|
||||
- Gate do acervo **fail-closed** (`requireCampaignPageActor({gate:'communicationCatalog'})` + `canReadRecording`/`canReadCommunicationCatalog`); `advisor`/`leader` negados.
|
||||
- Deep-link atual **byte-compatível**: `?source=enviadas&q&person&page` continua canonicalizando para exatamente o mesmo href; `mode=termo` e o sort default nunca serializados.
|
||||
- **Sem lista única** entre fontes; **sem redesenho da barra da Câmara** (ela é a referência).
|
||||
- Classificação **automática e revisável, nunca inventa** — falha degrada para o que existir e é sinalizada; proveniência é rótulo auditável (`gazetteer|llm|manual`), nunca score.
|
||||
- Buckets de duração idênticos à Câmara ("Até 2 min" · "2 a 5 min" · "Mais de 5 min" · "Sem duração"); **Ano derivado de `recordedAt`**, nunca um segundo campo digitado.
|
||||
- **O que reavaliar (hipóteses da intenção):**
|
||||
- "Direção no codebase" aponta `speechClassifier` e `expandSpeechSearchTheme` corretamente, mas o seam real do job é `runRecordingJob` (roda via `after()`, sem request) — a classificação entra ali, **fora** da transação de save, e o backfill das linhas existentes é CLI.
|
||||
- `classifySpeech` é reusável como está, mas pede `transcript` **cru** (o `searchText` da gravação é normalizado; o input tem de ser a concatenação dos `text` dos segmentos).
|
||||
- `expandSpeechSearchTheme` já tem o parâmetro `corpus` desde S28 — a extensão é **um prompt novo**, não mecanismo novo.
|
||||
- Gravações **não têm `keywords`**: a perna textual delas é só `searchText` (a Câmara tem `searchText` OR `keywords`).
|
||||
- `Recording` **não tem** os campos de faceta/proveniência de `Speech`: schema novo + migration são inevitáveis (a intenção já previa "facets + proveniência").
|
||||
|
||||
## Abordagem recomendada
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
UP[upload / retry] --> JOB[runRecordingJob]
|
||||
JOB --> ASR[extrair + transcrever + diarizar]
|
||||
ASR --> CLS{classifyRecordingFacets<br/>classify injetável}
|
||||
CLS -- "sem DEEPINFRA_API_KEY / erro" --> GZ[gazetteer: topics/scopes/municípios]
|
||||
CLS -- ok --> LLM[gazetteer ∪ LLM validado]
|
||||
GZ --> TX[(transação: segments + recording)]
|
||||
LLM --> TX
|
||||
TX --> RDY[ready + facets + classifiedBy]
|
||||
|
||||
CLI["scripts/backfill-recording-facets.mjs<br/>pnpm recordings:classify"] -. mesma função .-> CLS
|
||||
|
||||
Q["assessoria: ?source=enviadas&q&mode&year&topic&scope&municipality&duration&sort&person&page"] --> URL[recordingListUrl<br/>parse + canônico]
|
||||
URL --> MODE{mode=tema?}
|
||||
MODE -- não --> WHERE[buildRecordingListWhere<br/>facetas AND + texto OR + pessoa]
|
||||
MODE -- sim --> EXP[expandRecordingSearchTheme<br/>corpus 'recording']
|
||||
EXP -- null --> DEG[literal + aviso discreto]
|
||||
EXP -- termos --> WHERE
|
||||
DEG --> WHERE
|
||||
WHERE --> FIND["payload.find<br/>user · overrideAccess:false"]
|
||||
FIND --> VM[recordingViewModels<br/>excerto + destaque + chips]
|
||||
VM --> UI[RecordingAcervoFilters + lista + contagem + ordenação]
|
||||
```
|
||||
|
||||
**Opções consideradas | Recomendação | Rejeitadas (decisões caras):**
|
||||
|
||||
| # | Decisão | Opções | Recomendação | Rejeitadas |
|
||||
| --- | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| i | Onde a classificação roda | A) seam no `runRecordingJob` (injetável) + CLI backfill · B) hook `afterChange` da collection · C) on-demand no loader da busca · D) hook por `recordingSegment` | **A** — o job já tem os segmentos em memória no fim da transcrição; o seam injetável é precedente (`catalogContentPiece`); o CLI cobre as linhas já existentes | B (sem transcrição no momento do hook, roda em caminho quente e re-executa por `step`); C (LLM por request, leitura viraria escrita, faceta inexistente não filtra); D (N chamadas por gravação, unidade errada) |
|
||||
| ii | Schema em `Recording` | A) espelhar `Speech` (`year` derivado + `topics`/`scopes`/`classifiedBy`/`mentionedMunicipalities` + `preserveManualFacets`) com migration `add_recording_facets` · B) facetas por segmento · C) sem schema (derivar na busca) · D) ano sem coluna (range sobre `recordedAt`) | **A** — mesma forma de `where`/opções/canônico da Câmara e curadoria manual preservada; a migration é aditiva | B (unidade errada — corte explícito da intenção); C (não filtra/pagina, recalcula a cada busca e morre o "revisável"); D (dois shapes de filtro para o mesmo conceito; a coluna derivada é o que a Câmara tem e o que a intenção chama de "derivado") |
|
||||
| iii | Contrato de duração + omnibox | A) reusar donos da Câmara (buckets/labels/tipo de `speechListUrl`, `durationBucketWhere` exportado de `speechListFilters`, parsers de ano/município movidos para `campaignListUrl`) + adaptador novo `recordingOmnibox` · B) extrair módulo compartilhado novo do acervo e migrar a Câmara · C) duplicar no domínio de gravações | **A** — a paridade manda que o bucket tenha UM dono; o adaptador por domínio já é padrão (`municipalityOmnibox`, `municipalityUpdateOmnibox`) | B (churn na Câmara sem volatilidade; extrair quando C216 chegar — 3º consumidor); C (twin: mudança de bucket divergiria as duas fontes) |
|
||||
| iv | Busca por tema | A) `ThemeSearchCorpus` ganha `'recording'` + prompt próprio + `expandRecordingSearchTheme` · B) reusar o corpus `'speech'` · C) só busca literal | **A** — o mecanismo é um só (S28); o prompt de discursos da Câmara não descreve plenárias enviadas/debates | B (prompt errado degrada a expansão); C (rejeitada no gate: a ponte foi confirmada) |
|
||||
| v | UI | A) `RecordingAcervoFilters` novo sobre os shells compartilhados (absorve o `RecordingPersonFilter`) · B) generalizar `SpeechAcervoFilters` configurável · C) estender `SpeechAcervoFilters` com `source` | **A** — shells compartilhados são os donos das mecânicas; a Câmara não é tocada | B (API genérica rasa e mexe na Câmara — anti-goal); C (acopla os dois contratos num componente) |
|
||||
| vi | Ordenação | A) param `sort` com valores pt-BR (`recentes` default omitido, `duracao_maior`, `duracao_menor`); sort de duração só sobre linhas com duração medida · B) par genérico `sort`/`dir` (C117) · C) sort só de UI | **A** — contrato fechado e legível no deep link; default preserva `-createdAt` (zero regressão) | B (o acervo não é tabela; a Câmara não tem esse contrato); C (quebra "paginação preservada no deep link" e back/forward) |
|
||||
|
||||
**Recomendação (geral):** uma única passada de classificação no job (com o mesmo `classifySpeech`, injetável e com degradação para gazetteer), um CLI idempotente para o acervo já enviado, e a paridade de filtros construída sobre o contrato de URL, o `where`, o adaptador de omnibox e os shells que a Câmara já usa — mudando **só** a fonte de gravações.
|
||||
|
||||
**Rejeitadas (geral):** busca global/lista única (anti-goal); pgvector/embeddings (C192 já rejeitou); facetas por trecho/falante (corte da intenção); qualquer alteração na barra/contrato da Câmara.
|
||||
|
||||
### Componentes / mudanças
|
||||
|
||||
- **`Recording`** (`src/collections/Recording.ts`): novos campos `year` (number, index, readOnly, derivado), `topics` (select hasMany, index, opções `SPEECH_TOPICS`), `scopes` (select hasMany, index, opções `SPEECH_SCOPES`), `classifiedBy` (select, index, **opcional, sem default**, valores `SPEECH_CLASSIFICATION_SOURCES`), `mentionedMunicipalities` (relationship hasMany → `municipality`, index). Hooks: `deriveRecordingYear` (beforeValidate, espelho de `deriveSpeechYear` — `recordedAt` string `slice(0,4)`, com fallback `originalDoc`) e `preserveManualFacets` (beforeChange, espelho de `Speech.ts:43-57`, `FACET_FIELDS = topics|scopes|classifiedBy|mentionedMunicipalities`; escrita sem `req.user` — job/CLI — nunca sobrescreve `manual`). `admin.defaultColumns` ganha `topics` e `classifiedBy` (superfície de revisão da classificação no admin). `admin.description` registra que a classificação é automática sobre o início da transcrição.
|
||||
- **Migration** (`pnpm migrate:create add_recording_facets` → `src/migrations/20260924_120000_add_recording_facets.ts` + `.json` + `index.ts`): tabelas de join `recording_topics`/`recording_scopes` (enums `enum_recording_topics`/`enum_recording_scopes`/`enum_recording_classified_by`), tabela `recording_rels` (`mentionedMunicipalities`), colunas `year`/`classified_by`. **Hand-edit** (precedente `20260913_150000_backfill_speech_search_text_trgm_index`): backfill determinístico de `year` a partir de `recorded_at` (`WHERE recorded_at IS NOT NULL`). Nada destrutivo; `recording_search_text_trgm_idx` já existe (não mexer).
|
||||
- **`src/payload-types.ts`**: regenerado (`pnpm generate:types`) — `Recording` ganha os campos.
|
||||
- **`classifyRecordingFacets`** (`src/utilities/recordings/recordingClassification.ts`, novo, `import 'server-only'`): `({ payload, transcript, classify = classifySpeech })` → `{ topics, scopes, classifiedBy, mentionedMunicipalities } | null`. Reusa `SpeechFacetInput`/`SpeechClassificationResult`, `classifySpeech` (DeepInfra + validação `lib/speechFacets`) e resolve `municipalities[].slug → municipality.id` numa query (bypass justificado — geografia read-only — precedente `speechImport.ts:176-196`). Nunca lança: transcrição vazia ou throw defensivo devolvem `null` e o job segue sem facets.
|
||||
- **`runRecordingJob`** (`src/utilities/recordings/recordingJob.ts`): ganha `classify` injetável (default `classifySpeech`), chamado **depois** de diarizar e **antes** de `markStep('saving')` (o LLM não entra na transação); transcript = `keyedSegments.map(s => s.text).join(' ')`. O update transacional final (`status:'ready'`, `searchText`, `speakerLabels`) passa a incluir `year` (quando houver `recordedAt`), `topics`, `scopes`, `classifiedBy`, `mentionedMunicipalities`.
|
||||
- **`scripts/backfill-recording-facets.mjs`** (novo) + `package.json` `"recordings:classify"`: reusa `classifyRecordingFacets`; default = linhas `ready` com `classifiedBy` ausente (`--all` reclassifica não-`manual`), `--dry-run`, `--limit N`; `assertLocalDatabase` + `RECORDING_CLASSIFY_CONFIRM=1` para alvo remoto/produção (precedente `CAMARA_IMPORT_CONFIRM`); relatório (classificadas/puladas-manual/falhas/tokens/custo) e idempotência por `classifiedBy`.
|
||||
- **URL** (`src/utilities/recordings/recordingListUrl.ts`): `RecordingListState` ganha `mode?` (reusa `SpeechSearchMode`), `years?`, `topics?`, `scopes?`, `municipalities?`, `durations?` (reusa `SpeechDurationBucket`) e `sort?`; `recordingListParamNames` ganha `mode|year|topic|scope|municipality|duration|sort`. Ordem canônica: `source, q, mode, year[], topic[], scope[], municipality[], duration[], sort, person[], page` — os parâmetros novos não perturbam o href dos deep links atuais. Serialização: `mode=tema` só com `q`; `sort` só quando ≠ `recentes`; `page` só > 1. Novos: `RECORDING_SORT_OPTIONS`/`recordingSortLabels` ("Mais recentes" · "Duração (maior)" · "Duração (menor)"), `recordingSortKeys(state)` (`-createdAt` default / `-durationSeconds` / `durationSeconds`) e `buildRecordingFiltersKey(state)` (espelho de `buildSpeechFiltersKey`, usado como `key` do remount da barra).
|
||||
- **`campaignListUrl.ts`**: recebe `parseYearValues`/`parseMunicipalityValues` (movidos de `speechListUrl.ts`, que passa a importá-los) — um dono para a validação estrutural de ano/município nas duas fontes.
|
||||
- **`speechListFilters.ts`**: exporta `durationBucketWhere` (sem mudança de comportamento) para o `where` das gravações.
|
||||
- **Filtros** (`src/utilities/recordings/recordingListFilters.ts`): `buildRecordingListWhere(state, themeTerms = [])` — facetas AND (`year in`, `topics in`, `scopes in`, `mentionedMunicipalities in`, OR de `durationBucketWhere`, OR de `speakerNames contains`), perna textual OR de `{ searchText: { like: normalizeForSearch(term) } }` para `[q, ...themeTerms]` (sem `keywords`), e `{ durationSeconds: { exists: true } }` quando `sort` é de duração (o Postgres ordena NULLS FIRST em DESC; sem isso "Duração (maior)" abriria com as linhas sem duração).
|
||||
- **Loader** (`src/utilities/recordings/recordingPageData.ts`): `RecordingFilterOptions` ganha `years` e `municipalities` (via `loadMunicipalityLabelsByIds`, precedente `loadSpeechFilterOptions`); `loadRecordingsPageData(payload, user, params, expandTheme = expandRecordingSearchTheme)` com o gate de tema (`mode=tema && q && canReadCommunicationCatalog(role)` antes de qualquer chamada externa) e retorno `themeUnavailable`/`themeApplied`; `sort` aplicado; `loadMatchedSegments` passa a receber os termos (`[q, ...themeTerms]`) e casa `or` de `searchText like`; `select` da lista ganha `topics` (chip do card).
|
||||
- **View models** (`src/utilities/recordings/recordingViewModels.ts`): `toRecordingListItemViewModel` ganha `themeTerms`; o excerto prefere a evidência de tema (espelho C192: primeiro termo que casa em `searchText`, segmento via `pickMatchingSegment`, `buildHighlightedExcerpt(..., { phrase: true })`) e cai no literal quando não há; `watchHref` mantém `?t=&q=` com o **`q` literal** (byte-compat; espelho de `buildWatchHref`); `RecordingListItemViewModel` ganha `topics: { value, label }[]` (labels de `speechTopicLabels`).
|
||||
- **Omnibox** (`src/utilities/recordings/recordingOmnibox.ts`, novo, puro/client-safe): chips (`q`, `year`, `topic`, `scope`, `municipality`, `duration`, `person`), seeds (Tema/Alcance/Duração visíveis com query vazia; Ano/Município citado/Pessoa pesquisáveis por palavra-chave), `applyRecordingOmniboxSuggestion`/`removeRecordingOmniboxChip`/`applyRecordingSearchMode`/`clearRecordingOmnibox` (preservando `source: 'enviadas'` no clear) sobre `lib/campaignListOmnibox.ts`; `person` reusa `toggleRecordingPerson`/`removeRecordingPerson` (dedupe case-insensitive já dono) e o prefixo `person:` lê o valor por `slice` (o rótulo pode conter `:`).
|
||||
- **Tema** (`src/utilities/ai/expandSpeechSearchTheme.ts`): `ThemeSearchCorpus` ganha `'recording'`; novo prompt de corpus (plenárias/debates/material próprio enviados pela equipe), `themeExpansionRules('gravação')`; wrapper `expandRecordingSearchTheme` (mesmo timeout/degradação/`normalizeSpeechThemeTerms`).
|
||||
- **UI (Impeccable B — port de `docs/plans/acervo-paridade-busca-filtros-ui-design.html`):**
|
||||
- `src/components/campaign/recording/RecordingAcervoFilters.tsx` (novo, client) — **cenas 01/02**: form `campaignListOmniboxFormClassName` com label "Buscar nas gravações enviadas", `CampaignListOmnibox` (chips dentro do campo, como na Câmara — B184/B127), seletor segmentado `role="group"` `grid grid-cols-2 rounded-lg bg-muted p-1` + `aria-pressed` + `min-h-11 md:min-h-9` (com o estado degradado `themeUnavailable`), e as seis facetas como `CampaignHeaderFilterPopover triggerVariant="chip"` (`Ano`, `Tema`, `Alcance`, `Município citado`, `Duração`, `Pessoa`) com `selectedTriggerLabel` dobrando a seleção. A linha "Ativos:" do artefato é realizada pelos chips do próprio omnibox (shell compartilhado), sem segunda fileira.
|
||||
- `src/components/campaign/recording/RecordingSortSelect.tsx` (novo, client) — **cena 01**: label "Ordenar por" + `select` nativo (`rounded-md border border-input`) via `useCampaignListFilterNavigation`; em sort de duração, hint "Gravações sem duração aparecem apenas em Mais recentes." A contagem fica no `CampaignListFooter` (padrão de todas as listas — sem duplicar a linha).
|
||||
- `src/components/campaign/recording/RecordingThemeFallbackNotice.tsx` (novo) — **cena 04/C192**: `Alert variant="pending"` com a copy de gravações + `CampaignThemeRetryButton`; move `SpeechThemeRetryButton` → `src/components/campaign/shared/CampaignThemeRetryButton.tsx` (componente genérico, zero copy própria) e atualiza o import da página da Câmara.
|
||||
- `src/components/campaign/recording/RecordingResultCard.tsx` — **cena 01 (card)**: chip de tema (`bg-muted`) ao lado do chip de pessoa; destaque do termo continua via `SpeechHighlightParts`.
|
||||
- `src/app/(campaign)/campanha/(app)/comunicacao/acervo/page.tsx` — branch `enviadas`: `key={buildRecordingFiltersKey(data.state)}`, barra nova, aviso de tema, `RecordingSortSelect`, `RecordingStatusRefresher` (intocado), lista/vazio/footer; vazio honesto da **cena 03** (título "Nenhuma gravação encontrada para este tema", descrição do artefato, "Limpar filtros" + "Trocar para termo exato") e `hasFilters` por `buildRecordingFiltersKey`. O `RecordingsSearchForm` inline e o `RecordingPersonFilter` somem (absorvidos).
|
||||
- **Cena 04 (sem permissão)** permanece o redirect fail-closed do gate — a cena é ilustrativa, não vira superfície nova. **Cena 05 (carregando)** é o `CampaignListPendingBoundary`/`CampaignListResults` existente (dima o resultado, não o controle).
|
||||
- Remover `src/components/campaign/recording/RecordingPersonFilter.tsx`.
|
||||
- **Manifest e2e** (`scripts/lib/e2e-affected-manifest.mjs`): `src/collections/Recording.ts` entra no entry da vertical C154/C199 (`campaignSpeechAcervo`) — hoje um diff só nesse arquivo cairia no smoke da home; e `campaignSpeechAcervo` entra em `E2E_CURATED_SPECS` (precedente C167/S19: a migration torna todo PR da entrega high-risk), com o pin de congelamento atualizado em `tests/unit/e2eAffectedManifest.unit.spec.ts`.
|
||||
- **Access / Consent:** **nada muda**. Sem chave `Consent` nova (acervo interno; sem PII nova), sem collection nova, sem rota nova. O classificador fala com a DeepInfra (mesmo provedor/chave que já transcreve a gravação) e o tema com a DeepSeek (só o texto digitado, como na Câmara).
|
||||
|
||||
### Dados → forma (se aplicável)
|
||||
|
||||
N/A justificado. O item não apresenta métrica, agregado nem score: resultados e facetas são recorte editorial. A proveniência é rótulo auditável (`Gazetteer`/`LLM`/`Manual`) no admin — nunca número na UI; "contagem de resultados" é paginação, não métrica de vaidade.
|
||||
|
||||
## Fases verificáveis
|
||||
|
||||
1. **Tracer / schema + server** (~1 dia) — `Recording` com os campos/hooks + migration `add_recording_facets` (com backfill de `year`) + `pnpm generate:types` + `recordingClassification` + seam `classify` no `runRecordingJob` + `scripts/backfill-recording-facets.mjs`.
|
||||
- Prova: `tests/int/recording.int.spec.ts` — job end-to-end grava `topics`/`scopes`/`classifiedBy`/`mentionedMunicipalities`/`year` (classificador injetado determinístico + caminho gazetteer sem `DEEPINFRA_API_KEY`); curadoria `manual` não é sobrescrita por escrita sem `user`; retry reclassifica; `pnpm migrate` local verde.
|
||||
2. **URL / filtros / loader** (~0,5 dia) — params e estado novos, `buildRecordingFiltersKey`, `recordingSortKeys`, `where` com facetas + tema + gate de sort, loader com opções (`years`/`municipalities`) e injeção do tema, corpus `'recording'`.
|
||||
- Prova: `tests/unit/recordingListUrl.unit.spec.ts` (deep-link byte-compat, canônico, enums exaustivos, `sort` default omitido), `tests/unit/recordingListFilters.unit.spec.ts` (facetas AND, tema OR, duração, `exists` do sort), `tests/unit/recordingOmnibox.unit.spec.ts` (novo), `tests/unit/expandSpeechSearchTheme.unit.spec.ts` (corpus novo), `tests/int/recording.int.spec.ts` (loader filtra/ordena/tema e opções).
|
||||
3. **UI port** (~0,5–1 dia) — `RecordingAcervoFilters`, `RecordingSortSelect`, `RecordingThemeFallbackNotice`, `CampaignThemeRetryButton` movido, chip de tema no card, página; remoção do `RecordingPersonFilter`.
|
||||
- Prova: `tests/e2e/campaignSpeechAcervo.e2e.spec.ts` (describe de gravações estendido: barra com chips, filtro que estreita + vazio honesto, modo tema degradando, sort, contagem; o teste de "Pessoa" passa a exercitar a barra nova); `pnpm dev` manual com a cena 01 do artefato.
|
||||
4. **Testes/gates** (~0,5 dia) — `pnpm gate:fast`; depois a cascata cheia (`pnpm lint`, `pnpm format:check`, `tsc --noEmit`, `pnpm exec knip`, `pnpm check:cycles`, `pnpm test`, `pnpm build`); `pnpm push`; entrada em `docs/changelog/<data>-c219.md`; PR ready com auto-merge (o check `checks` é o gate; o e2e curado roda `campaignSpeechAcervo`).
|
||||
|
||||
## Rabbit holes / Não escopo (engenharia)
|
||||
|
||||
- **Generalizar a barra da Câmara** (`SpeechAcervoFilters` configurável / componente `AcervoFilters` genérico) — anti-goal; shells compartilhados já são os donos.
|
||||
- **Extrair o adaptador de omnibox/helpers de estado para um genérico** — 2 call sites; extrair quando C216 ("Falas na internet") chegar (3º).
|
||||
- **Módulo compartilhado novo do contrato do acervo** (mover buckets/parsers para um terceiro) — churn na Câmara sem volatilidade; deferido para C216.
|
||||
- **pgvector/embeddings/índice vetorial** — já rejeitado no C192.
|
||||
- **Classificar por segmento/falante** ou reclassificar a taxonomia (18 temas fixos) — cortes de produto.
|
||||
- **Segundo cadastro de pessoa / inferir falantes** — "Pessoa" segue rótulo (C200).
|
||||
- **Mudar o default de ordenação para `-recordedAt`** — regressão do comportamento atual (`-createdAt`); fora do aceite.
|
||||
- **Busca global entre fontes / lista única** — anti-goal.
|
||||
- **UI de curadoria de facetas além do form do admin** — o form da collection é a superfície de revisão; qualquer coisa além disso é outro item.
|
||||
- **Cache/rerank da expansão de tema** — deferido no C192 (sem cache no v1).
|
||||
|
||||
**Adiado com gatilho (triage do /simplify desta entrega):**
|
||||
|
||||
- **Extração dos helpers de faceta/estado restantes** (`facetRows`/`clearFacet`/`runAction` e o aviso de fallback por domínio) — gatilho: C216 (3º consumidor do acervo), junto do adaptador de omnibox (S2/S3).
|
||||
- **N+1 do backfill** (`scripts/backfill-recording-facets.mjs` consulta os segmentos de cada gravação em queries separadas) — gatilho: acervo na casa das centenas de gravações ou `--all` perceptivelmente lento (S4).
|
||||
- **Ternários aninhados do ramo de gravações** em `acervo/page.tsx` — gatilho: extração do 3º consumidor na C216, quando o ramo for compartilhado (S5).
|
||||
- **"X" de limpar do omnibox quebra linha no mobile com chip longo** — débito do shell compartilhado, pré-existente e reproduzido na Câmara; registrado como Issue própria (C221, `docs/plans/omnibox-limpar-mobile.md`) — fora deste item (S1).
|
||||
|
||||
## Riscos e mitigação
|
||||
|
||||
- **Deep-link/redirect:** os nomes novos entram em `recordingListParamNames` (antes seriam "unsupported" e redirecionariam); o serializer precisa reproduzir `?source=enviadas&q=…&person=…&page=…` **byte a byte** (ordem canônica acima; `page` só >1). Mitigação: pins no `recordingListUrl.unit.spec.ts` (incluindo `mode=tema` sem `q` canonicalizando fora e `sort` default omitido).
|
||||
- **`select` allowlist:** esquecer `topics` no `recordingListSelect` some com o chip do card silenciosamente. Mitigação: o campo é exigido pelo input do view model (typecheck) + int test do loader.
|
||||
- **Manifest e2e:** `src/collections/Recording.ts` está fora do manifest (um diff só nele cairia no smoke da home); `src/payload-types.ts` é `HIGH_RISK_EXACT` → o PR roda o e2e **curado**, que hoje não inclui `campaignSpeechAcervo`. Mitigação: adicionar o arquivo ao entry da vertical e `campaignSpeechAcervo` ao `E2E_CURATED_SPECS` + pin (precedente C167/S19); a suíte full continua no `verify` do deploy.
|
||||
- **Ausência de `DEEPINFRA_API_KEY`:** `classifySpeech` degrada para gazetteer (topics/scopes/municípios do léxico) e nunca lança; o CLI reporta `llm: false` e o `mergeFacetClassification` garante que `classifiedBy: 'llm'` só sai com resposta validada.
|
||||
- **Gravações já existentes:** `classifiedBy` **nulo = "não classificada"** (honesto; nunca inventar `gazetteer` por default); ficam visíveis e sem faceta até o `pnpm recordings:classify` rodar; o CLI é idempotente e não toca `manual`.
|
||||
- **Transcrição longa:** o prompt do LLM trunca em 12k chars (dono: `classifySpeech`) — classificação pelo início da transcrição, registrada no `admin.description`; a busca (trgm) não é afetada. O custo é 1 chamada por gravação `ready` (mesmo provedor/chave do ASR), nunca por request.
|
||||
- **Sort × duração nula:** sem o gate `durationSeconds exists`, o Postgres colocaria as linhas sem duração no topo de "Duração (maior)"; o gate + hint no controle mantêm a ordem honesta. Int test cobre.
|
||||
- **Matriz de papéis:** intocada — gate da página e `canReadRecording` idênticos; a expansão de tema só roda depois de `canReadCommunicationCatalog(role)`; os bypasses do job/CLI são internos e justificados.
|
||||
- **Migration em produção:** aditiva (colunas nulas + joins), aplicada pelo `pnpm build` do deploy; o backfill de `year` é SQL determinístico; `down` gerado cobre rollback.
|
||||
- **Ciclos/convenções:** `recordings → speech` não pode criar ciclo (`speech` não importa `recordings`) — `pnpm check:cycles`; `recordingClassification.ts` declara `import 'server-only'` (regra do `codebaseConventions.unit.spec.ts`).
|
||||
|
||||
## Aceite de engenharia
|
||||
|
||||
- [ ] Aceite de produto da intenção ainda coberto (ano, duração, tema, alcance, município citado, pessoa exclusiva, contagem, chips, ordenação, vazio honesto, tema degradando honestamente).
|
||||
- [ ] Invariantes AGENTS/engineering-standards: `user` + `overrideAccess: false` em toda leitura; bypass do job/CLI justificado; sem `Consent`/PII nova; `leader`/`advisor` fail-closed; sem top-level novo em `utilities/`; copy pt-BR / identificadores em inglês; sem `openai/*` (OPS123).
|
||||
- [ ] Migrations: só arquivos novos (nunca editar antigas); `pnpm migrate` local; `pnpm generate:types`; prod aplica no build.
|
||||
- [ ] Testes de domínio previstos: unit (URL/where/omnibox/corpus), int (job escreve facetas, curadoria manual preservada, loader filtra/ordena/tema), e2e (barra/filtros/ordenação/vazio) — onde os write paths e o contrato de URL mudam.
|
||||
- [ ] Manifest/e2e atualizado (`src/collections/Recording.ts` na vertical; `campaignSpeechAcervo` no curado + pin).
|
||||
- [ ] Gates: `tsc --noEmit`, `pnpm lint` (0 warnings), `pnpm format:check`, `pnpm exec knip`, `pnpm check:cycles`, `pnpm test`, `pnpm build`; `pnpm push`; entrada em `docs/changelog/`.
|
||||
|
||||
## Decisões de engenharia
|
||||
|
||||
**(i) Onde a classificação roda**
|
||||
|
||||
- **Opções:** A) seam no `runRecordingJob` (injetável) + CLI backfill | B) hook `afterChange` da collection | C) on-demand no loader da busca | D) hook por `recordingSegment`.
|
||||
- **Recomendação:** **A** — o job já tem `keyedSegments` em memória ao fim da transcrição, roda fora do request e faz o save transacional; o `classify` injetável (default `classifySpeech`) é o mesmo padrão de `catalogContentPiece` e mantém os testes offline; o CLI cobre as linhas anteriores à entrega com a mesma função.
|
||||
- **Rejeitadas:** B porque o hook dispara em cada transição de `status`/`step` (sem transcrição no momento útil), prenderia um LLM de 60s dentro do ciclo de escrita e re-executaria a cada passo; C porque pagaria o LLM em toda página, transformaria leitura em escrita e não filtraria pelo que ainda não foi classificado; D porque faria N chamadas por gravação e classificaria por trecho — unidade rejeitada pela intenção.
|
||||
|
||||
**(ii) Schema em `Recording`**
|
||||
|
||||
- **Opções:** A) espelhar `Speech` (`year` derivado, `topics`/`scopes`/`classifiedBy`/`mentionedMunicipalities`, `preserveManualFacets`) com a migration `add_recording_facets` | B) facetas por segmento | C) sem schema, derivar na busca | D) ano por range sobre `recordedAt` (sem coluna).
|
||||
- **Recomendação:** **A** — mantém `where`, opções de faceta e canônico idênticos aos da Câmara (a paridade é o objetivo), a curadoria manual preservada (hook espelho) e o "revisável" no admin. `year` derivado no `beforeValidate` com backfill SQL na migration; `classifiedBy` opcional (ver vii).
|
||||
- **Rejeitadas:** B porque a unidade da Câmara é a fala e o corte da intenção é a gravação; C porque não filtra com `where`/paginação, recalcula a cada busca e perde a revisão; D porque criaria um segundo shape de filtro para o mesmo conceito (e teria de repetir a regra de fuso em cada branch), enquanto a coluna derivada é literalmente o "derivado da data já informada" da intenção.
|
||||
|
||||
**(iii) Reuso do contrato de duração e do omnibox**
|
||||
|
||||
- **Opções:** A) reusar os donos da Câmara (buckets/labels/tipo em `speechListUrl`, `durationBucketWhere` exportado de `speechListFilters`, parsers de ano/município em `campaignListUrl`) + `recordingOmnibox` novo | B) extrair módulo compartilhado novo do acervo e migrar a Câmara | C) duplicar buckets/where no domínio de gravações.
|
||||
- **Recomendação:** **A** — um dono para o bucket (mudança na Câmara reflete nas gravações, que é a paridade pedida) e o adaptador por domínio segue o padrão já existente (`municipalityOmnibox`, `municipalityUpdateOmnibox`); o que é genérico (`lib/campaignListOmnibox`) já é compartilhado.
|
||||
- **Rejeitadas:** B porque mover o contrato de referência para um terceiro neutro gera churn na Câmara sem volatilidade real — gatilho de revisitação: a chegada da C216 (3º consumidor); C porque duplicar o bucket/where faz as duas fontes divergirem em silêncio, exatamente o que o item existe para impedir.
|
||||
|
||||
**(iv) Corpus da busca por tema**
|
||||
|
||||
- **Opções:** A) `ThemeSearchCorpus` ganha `'recording'` + prompt próprio + wrapper | B) reusar o corpus `'speech'` | C) só busca literal.
|
||||
- **Recomendação:** **A** — `expandSearchTheme(theme, corpus)` é o mecanismo único desde S28; o que muda é o prompt (plenárias/debates/material próprio enviados pela equipe). Degradação e `normalizeSpeechThemeTerms` são herdados.
|
||||
- **Rejeitadas:** B porque o prompt descreve discursos da Câmara e degradaria a expansão para gravações; C porque a pergunta de produto foi confirmada no gate (estender a ponte é a paridade pedida).
|
||||
|
||||
**(v) UI: componente novo × generalização**
|
||||
|
||||
- **Opções:** A) `RecordingAcervoFilters` novo sobre os shells compartilhados | B) generalizar `SpeechAcervoFilters` configurável | C) estender `SpeechAcervoFilters` com `source`.
|
||||
- **Recomendação:** **A** — os donos das mecânicas são os shells (`CampaignListOmnibox`, `CampaignHeaderFilterPopover`, `useCampaignListFilterNavigation`, `CampaignListPending*`, `CampaignListEmptyState/Footer`); o componente de domínio só monta os facets da fonte, como o da Câmara.
|
||||
- **Rejeitadas:** B porque uma API genérica configurável é pass-through raso e mexeria na Câmara (anti-goal); C porque acoplaria os dois contratos de URL num único componente e twinaria a Câmara dentro dele.
|
||||
|
||||
**(vi) Contrato de ordenação**
|
||||
|
||||
- **Opções:** A) `sort` com valores pt-BR (`recentes` default omitido, `duracao_maior`, `duracao_menor`) + exclusão de linhas sem duração nos sorts de duração | B) `sort`/`dir` genérico (C117) | C) sort só de UI.
|
||||
- **Recomendação:** **A** — contrato fechado (o canonicalizador redireciona valor desconhecido), default preserva `-createdAt` (zero regressão) e o gate `durationSeconds exists` evita NULLS FIRST no Postgres; o controle avisa que gravações sem duração aparecem só em "Mais recentes".
|
||||
- **Rejeitadas:** B porque o acervo não é tabela e a Câmara não tem esse contrato (a paridade pede o gesto, não o par genérico); C porque quebraria "paginação preservada no deep link" e o back/forward.
|
||||
|
||||
**(vii) Proveniência nula nas gravações existentes**
|
||||
|
||||
- **Opções:** A) `classifiedBy` opcional, sem default — nulo = "não classificada" | B) `required` com `defaultValue: 'gazetteer'` (espelho exato de `Speech`).
|
||||
- **Recomendação:** **A** — o default de B afirmaria que o gazetteer classificou linhas que nunca passaram por ele (viola o "nunca inventa"); nulo é o estado honesto até o `pnpm recordings:classify`, e o seletor do CLI fica trivial (`classifiedBy` ausente). Os **valores** persistidos são os mesmos da Câmara (`gazetteer|llm|manual`) — a paridade é do vocabulário, não do `required`.
|
||||
- **Rejeitadas:** B porque a migration carimbaria proveniência falsa nas linhas antigas e o backfill não teria como distinguir "classificada" de "nunca classificada".
|
||||
|
||||
**Decisões baratas (com gatilho de revisitação):**
|
||||
|
||||
- **Excerto no modo tema:** evidência de tema vence o excerto (espelho C192) e o `watchHref` mantém o `q` literal no `?t=&q=` (byte-compat; espelho `buildWatchHref`). Revisitar se a Câmara mudar a regra.
|
||||
- **`CampaignThemeRetryButton` movido para `shared/`** (componente genérico, 1 import atualizado na Câmara) — o aviso em si fica por domínio (copy).
|
||||
- **Helpers de estado do omnibox (`withPageReset`/`toggleValue`/`removeValue`)** duplicados no adaptador de gravações; extrair na C216 (3º).
|
||||
- **Contagem no `CampaignListFooter`** (não na linha do sort, como no artefato) — padrão de todas as listas; sem duplicar a linha.
|
||||
- **Chip de tema no card** usa `bg-muted` (mesma linguagem do chip de pessoa) — sem selo "Tema" (o artefato não pede).
|
||||
|
||||
**Self-score (0–5, gate ≥4): 5/5.**
|
||||
|
||||
1. **Decisões caras com rejeitadas:** 5/5 — as seis decisões caras (seam, schema, reuso de contrato, corpus, UI, sort) e a de proveniência nula têm opções/recomendação/rejeitadas; as baratas ficam com gatilho.
|
||||
2. **Appetite:** 5/5 — sem infra/provedor novo, sem collection/rota nova, reusando classificador, ponte de tema, shells e a transação do job; cabe nos ~2–3 dias.
|
||||
3. **Rabbit holes nomeados:** 5/5 — barra genérica, módulo compartilhado precoce, embeddings, classificação por trecho, segundo cadastro, mudança de default de sort, lista única.
|
||||
4. **Depth check:** 5/5 — reusa `classifySpeech`/`lib/speechFacets`, `expandSearchTheme`, `campaignListOmnibox`, shells de lista, `loadMunicipalityLabelsByIds`, `SpeechHighlightParts`, `withPayloadTransaction`; nada de camada cerimonial.
|
||||
5. **Intenção preservada:** 5/5 — Pessoa exclusiva, gate fail-closed, deep-link byte-compatível, sem lista única, sem redesenho da Câmara, classificação auditável e degradando honestamente.
|
||||
162
docs/plans/cards-colinha-arte-exata-impl.md
Normal file
162
docs/plans/cards-colinha-arte-exata-impl.md
Normal file
|
|
@ -0,0 +1,162 @@
|
|||
# Impl: S34 — Minha colinha: a arte exata entregue pelo humano + a linha do estadual preenchida
|
||||
|
||||
Status: aprovado
|
||||
Atualizado em: 2026-09-24
|
||||
Issue: #1298
|
||||
Intenção: docs/plans/cards-colinha-arte-exata.md
|
||||
Appetite restante: herdado — ~0,5–1 dia eng; 4 fases somam ~1 dia, sem migration, sem asset novo, sem dependência nova
|
||||
|
||||
## Leitura da intenção
|
||||
|
||||
- **Outcome:** a prévia e o PNG 1080×1920 do modelo `minha-colinha` passam a ser o JPEG aprovado (`modelo-colinha.jpeg`, 900×1600) ampliado exatamente 1,2×, como entregue; só a linha `DEPUTADO ESTADUAL` (2ª) é preenchida — nome de urna em caixa alta + os cinco dígitos, um por caixa existente. Sem estadual, a arte aparece intacta e o download fica desabilitado.
|
||||
- **O que NÃO negociar:** nenhum outro pixel redesenhado (topo, cinco linhas fixas, legal e selos vêm da arte); a linha preenchida lê como parte da arte (mesma tipografia/peso/cor/tamanho/linha de base, dígitos centrados, nome sem colidir com rótulo nem borda); 100% no aparelho; um só editor/fluxo (`#cards`, `/cards`, `?model=minha-colinha`); o JPEG continua tile da galeria; `StateDeputySelect`/`stateDeputyCatalog` (S30) e o analytics de S32 intocados; sem CMS/migration; sem PDF/A4; sem nome/foto do visitante; sem superfície nova.
|
||||
- **O que reavaliar (hipóteses da direção):**
|
||||
- "`renderColinhaCard` redesenha a arte inteira" — confirmado: `COLINHA_LAYOUT` + `drawColinhaTop/Legal/Digit/Confirm` compõem tudo do zero (`src/lib/cardRender.ts:338-591`); a maior parte morre (Decisão 3/C).
|
||||
- "`cardModels` muda `assetSrc`/`lockupSrc`" — a entrada passa a ter a arte como `assetSrc` e perde `overlaySrc`/`lockupSrc`/`previewSrc`; o tile segue a mesma arte via `previewSrc ?? assetSrc` (`CardModelTile.tsx:58`), agora pelo fallback (Decisão 4/D).
|
||||
- "o branch da colinha carrega a base" — confirmado; o efeito de carga já lê `model.assetSrc` (`CardComposer.tsx:280-295`); o branch só enxuga (sai `lockupImage`, sai o desenho composto).
|
||||
- "o gate do download sem estadual já existe" — confirmado: `canAdvance` (`CardComposer.tsx:596-598`) e `disabled` (`:1186`) já tratam a colinha; nenhum código novo (Decisão 5/E).
|
||||
- Geometria do design confere com a arte: máscara 55,9%→2,9% = y 1073,28→1128,96; cópia 56,46% = y 1084,03; dígitos top 58,4% = 1121,28, largura 6,1% = 65,88, d1 left 25,9% = 279,72, passo 6,9% = 74,52; escala 1,2 exata do JPEG. Sondagem no JPEG (sharp): o rótulo queimado ocupa x≈571–856 / y≈1088–1108 e as cinco caixas vazias (círculos, interior branco puro) vão de y≈1128 a 1195, centradas em x≈312,6/387,6/462,0/536,4/610,8 — a máscara cobre o rótulo e para no topo das caixas.
|
||||
|
||||
## Abordagem recomendada
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
C["CardComposer — branch kind:'colinha'"] --> RC["renderColinhaCard — cardRender.ts (dono do render)"]
|
||||
ART["/cards/modelo-colinha.jpeg — arte aprovada"] --> RC
|
||||
RC --> PV["prévia canvas 1080×1920"]
|
||||
PV --> DL["Baixar minha colinha — PNG 1080×1920"]
|
||||
SEL["StateDeputySelect (S30)"] --> C
|
||||
CAT["stateDeputyCatalog — 53 entradas"] --> SEL
|
||||
GEO["COLINHA_ROW_LAYOUT + fitColinhaRowName — cardColinha.ts"] --> RC
|
||||
RC -->|"deputy = null"| EMPTY["arte intocada; CTA desabilitado (canAdvance)"]
|
||||
```
|
||||
|
||||
**Opções consideradas:** A) canvas — `drawImage(jpeg, 0, 0, 1080, 1920)` com `imageSmoothingQuality='high'` e a linha desenhada por cima (máscara branca + rótulo + nome + dígitos) | B) sobrepor a linha em DOM/CSS sobre um `<img>` e rasterizar (html2canvas) | C) montar SVG/foreignObject → `Image` → canvas.
|
||||
**Recomendação:** A — é exatamente o caminho do design (as cenas usam esses elementos), mantém o dono único do render (`cardRender.ts`), a prévia e o download já saem do mesmo canvas, e não entra dependência nova.
|
||||
**Rejeitadas:** B porque exigiria dependência nova e uma segunda via de rasterização (fidelidade de fonte/anti-aliasing fora do nosso controle); C porque duplicaria o pipeline de desenho em outro formato (fontes/imagens embutidas, diferenças de browser) sem ganho.
|
||||
|
||||
### Decisões de engenharia
|
||||
|
||||
**1. Composição da linha (A) — canvas por cima do JPEG.**
|
||||
**Opções:** A) desenhar o JPEG ampliado e, por cima, máscara branca + rótulo + nome + dígitos no `renderColinhaCard` | B) renderizar a linha em DOM/CSS e rasterizar | C) offscreen canvas só para a linha e `drawImage` do resultado.
|
||||
**Recomendação:** A — o design já é um overlay de 6 elementos sobre a imagem; o render dono (`cardRender.ts`) desenha na mesma ordem do design (arte → máscara → rótulo → nome → dígitos) e o recorder falso prova a geometria; zero dependência e zero segundo pipeline.
|
||||
**Rejeitadas:** B porque introduz html2canvas e uma rasterização que não controlamos; C porque o offscreen não muda o resultado nem o custo, só adiciona um segundo contexto a manter.
|
||||
|
||||
**2. Fonte do nome/dígitos (B) — face mais próxima do sistema + prova lado a lado.**
|
||||
**Opções:** A) usar os stacks do design (`Arial, Helvetica, sans-serif` no nome/rótulo; `Arial Black, Arial, Helvetica, sans-serif` nos dígitos), com o artefato lado a lado no PR como aceite | B) embarcar uma face Black nova no repo (novo asset licenciado + pipeline de carga) | C) manter `COLINHA_FONT_FAMILY` atual para tudo e só aumentar o peso.
|
||||
**Recomendação:** A — é a resposta assumida da intenção e o NEEDS ASSET explícito do design ("o port deve provar a equivalência lado a lado; este gate decide composição e geometria"); menor custo e nenhum asset novo.
|
||||
**Rejeitadas:** B porque a face exata da arte não foi licenciada/entregue e `ensureCardFont` só carrega 1 família/peso (mexeria no load compartilhado e adicionaria ~100KB+licença por um item que o gate não pediu — vira gatilho de follow-up se a prova reprovar); C porque o design separa peso 400 (rótulo) de 900 (nome) e Arial Black nos dígitos.
|
||||
|
||||
**3. Código morto (C) — remover o que morre; `Linha conferida` derivada.**
|
||||
**Opções:** A) remover `COLINHA_LAYOUT`, `drawColinhaTop/Legal/Digit/Confirm`, `capAt`, `fitColinhaCandidate`, `COLINHA_FIXED_ROWS`, `colinhaVoteRows`, `COLINHA_ESTADUAL_PLACEHOLDER`, `COLINHA_LEGAL_TEXT` e `COLINHA_CONFIRM_LABEL`; a UI deriva `DEPUTADO ESTADUAL · <NOME> · <5 dígitos>` do `COLINHA_ESTADUAL_LABEL` + entrada do catálogo | B) manter `COLINHA_LAYOUT` e os `draw*` como via antiga | C) manter só `colinhaVoteRows` para a UI (tabela fixa).
|
||||
**Recomendação:** A — a intenção manda "a composição do zero deve ser REMOVIDA, não duplicada (sem segunda via morta)"; a linha de conferência não precisa da tabela das 6 linhas (a arte já carrega as 5 fixas); o literal do cargo fica uma vez em `cardColinha.ts` (dono) e é usado pelo renderer e pela UI.
|
||||
**Rejeitadas:** B porque knip acusa órfãos e a via morta convida a divergir da arte; C porque manteria a tabela de linhas fixas só para montar um texto — a fonte da verdade das linhas fixas passa a ser o JPEG, não a tabela.
|
||||
|
||||
**4. Modelo `minha-colinha` (D) — `assetSrc` é a arte; campos da composição antiga saem.**
|
||||
**Opções:** A) `assetSrc: '/cards/modelo-colinha.jpeg'` e remover `overlaySrc`/`lockupSrc`/`previewSrc` da entrada (e o campo `lockupSrc` de `CardModel`, sem outro consumidor) | B) manter `assetSrc` antigo (foto do grupo) e carregar a arte via `previewSrc` | C) criar um campo novo (`artSrc`).
|
||||
**Recomendação:** A — a arte é a base da prévia e do download; o tile continua mostrando a mesma imagem pelo fallback `previewSrc ?? assetSrc`; o composer genérico já carrega `assetSrc`; o campo `lockupSrc` fica órfão e sai junto (sem twinning).
|
||||
**Rejeitadas:** B porque deixaria a arte real num campo de "galeria" e a prévia dependente de semântica de placeholder; C porque cria campo/parallel path para um só modelo ("edite o dono, não gêmeo").
|
||||
|
||||
**5. Gate sem estadual (E) — nenhum código novo.**
|
||||
**Opções:** A) confiar no `canAdvance`/`disabled` existentes e provar o estado vazio com a arte intocada | B) adicionar flag/estado de download desabilitado ou esmaecer a prévia.
|
||||
**Recomendação:** A — `canAdvance` já é `selectedDeputy !== null` para a colinha; o renderer com `deputy = null` desenha só a arte; o e2e pina CTA desabilitado + arte como está.
|
||||
**Rejeitadas:** B porque duplicaria estado e o gate não esmaece a arte (a cena 01 mostra o JPEG pleno).
|
||||
|
||||
**6. Escala 1,2× e suavização (F) — estender o subset com os membros reais.**
|
||||
**Opções:** A) `CardDrawContext` ganha `imageSmoothingEnabled`/`imageSmoothingQuality`; `renderColinhaCard` seta `true`/`'high'` antes de desenhar; o único fake de teste é atualizado | B) aceitar o default do browser (`'low'`) | C) setar a suavização no composer, antes de chamar o renderer.
|
||||
**Recomendação:** A — o renderer é dono do seu requisito de composição; o subset ganha 2 membros estruturais (só um fake consome o tipo); nenhum renderer S13–S30 seta esses membros, então nada muda para eles.
|
||||
**Rejeitadas:** B porque a ampliação 1,2× é o entregável — blur aparece no type pequeno da arte; C porque vaza um detalhe de desenho para o caller e deixa o comportamento fora do teste puro do renderer.
|
||||
|
||||
**7. Fit do nome (G) — uma linha, encolhe para caber na caixa de cópia.**
|
||||
**Opções:** A) `fitColinhaRowName(texto, measure, maxWidth)` → `{ fontSize, text }` com `fontSize = min(ideal 36,72, ideal × maxWidth / width)`, uma linha (sem wrap), par rótulo+nome alinhado à direita em `copy.right`; `maxWidth = (copy.right − mask.x) − officeWidth − gap` (a faixa branca da máscara é a fronteira dura; o próprio CSS do gate deixa o par transbordar `copy.left`) | B) manter 36,72 fixo e deixar nomes longos vazarem para a esquerda sobre a arte | C) quebrar em duas linhas (comportamento S31) ou truncar.
|
||||
**Recomendação:** A — garante "nome cabendo sem colidir com o rótulo nem com a borda do desenho" (por construção, `pairLeft ≥ mask.x`), mantém o par legível e o domínio é o catálogo congelado; a varredura unit das 53 entradas com medida conservadora prova o invariante e o e2e pina o pior nome (`arthur`).
|
||||
**Rejeitadas:** B porque viola o aceite e desenha texto sobre pixels não mascarados da arte; C porque o design é `nowrap` (duas linhas colidem com as caixas/círculos na faixa de 55,68px) e truncar esconderia o nome do candidato.
|
||||
|
||||
### Componentes / mudanças
|
||||
|
||||
- **`src/lib/cardColinha.ts`** (reescrever; segue o dono da geometria da colinha): `COLINHA_FONT_FAMILY` (mantida), `COLINHA_DIGIT_FONT_FAMILY` (nova), `COLINHA_ESTADUAL_LABEL='DEPUTADO ESTADUAL'`, `COLINHA_ROW_LAYOUT` com os números do design em 1080×1920 — `mask { x:264,6, y:1073,28, width:619,92, height:55,68, fill:'#ffffff' }`; `copy { left:290,52, top:1084,03, width:570,24, right:860,76 }`; `office { fontSize:26,9, weight:400, color:'#202020' }` (o 2,15cqw=23,22 do gate foi corrigido na crítica (c) para o cap height 19,2px da arte); `name { fontSize:36,72, weight:900, color:'#e4102f', letterSpacingEm:-0,04 }`; `gap:16,2`; `digit { left:279,72, step:74,52, width:65,88, height:83,52, top:1121,28, fontSize:45,9, weight:900, color:'#171717' }` — e `fitColinhaRowName(text, measure, maxWidth)`. Baseline do par: `copy.top + measure('X', nameSize).actualBoundingBoxAscent` (cap do nome no topo da faixa; rótulo compartilha a baseline). `letterSpacingEm` vira `ctx.letterSpacing` em px (`-0,04 × fontSize`).
|
||||
- **`src/lib/cardRender.ts`** (editar): `CardDrawContext` ganha `imageSmoothingEnabled`/`imageSmoothingQuality`; `ColinhaCardRenderArgs` vira `{ image, deputy, fontFamily, measure }`; `renderColinhaCard` reescrito — `drawImage(image, 0, 0, model.width, model.height)` → `deputy ? máscara + rótulo + nome + dígitos : nada`; removem-se `drawColinhaTop/Legal/Digit/Confirm`, `capAt` e os imports órfãos; `drawCardName`/`renderNameCard`/`renderTeamCard` intocados.
|
||||
- **`src/lib/cardModels.ts`** (editar): entrada `minha-colinha` com `assetSrc:'/cards/modelo-colinha.jpeg'`, sem `overlaySrc`/`lockupSrc`/`previewSrc`; remove o campo `lockupSrc` de `CardModel`; doc-comments S31→arte exata. Sem migration (config estática no código).
|
||||
- **`src/components/cards/CardComposer.tsx`** (editar): branch de desenho passa a exigir só `baseImage` e chama `renderColinhaCard(ctx, model, { image: baseImage, deputy: selectedDeputy, fontFamily: COLINHA_FONT_FAMILY, measure: createCardMeasure(ctx, COLINHA_FONT_FAMILY, 900) })`; remove o estado/carregamento de `lockupImage` e as deps; `Linha conferida` deriva `${COLINHA_ESTADUAL_LABEL} · ${selectedDeputy.name.toLocaleUpperCase('pt-BR')} · ${selectedDeputy.ballotNumber}` (sem `colinhaVoteRows`); prévias 248/236px (vazio, crítica (c)) e 300/405px (preenchido), com o estado preenchido desktop em grid de 2 colunas num dialog de 960px (crítica (c); `data-colinha-filled`); copy, CTA, `canAdvance` e o evento S32 (`sendCardDownloadEvent`) ficam como estão; `ensureCardFont`/carregamento compartilhado de fonte intocados (sem webfont nova; gatilho = Decisão 2/B).
|
||||
- **Testes** (ver seção própria): `tests/unit/cardColinha.unit.spec.ts` (reescrever; manter o describe do tile), `tests/unit/cardRender.unit.spec.ts` (substituir o describe S31 + fake com os 2 membros novos), `tests/unit/cardModels.unit.spec.ts` (pin novo), `tests/e2e/frontend.e2e.spec.ts` (describe S34).
|
||||
- **`docs/changelog/<YYYY-MM-DD>-s34-colinha-arte-exata.md`** (novo).
|
||||
- **`scripts/lib/e2e-affected-manifest.mjs`**: **sem mudança** — `src/components/cards` + `src/lib/card` já mapeiam para o spec `frontend`.
|
||||
- **Migration:** sem migration — nenhuma collection/global/field no schema; `push:false` intocado.
|
||||
- **Access / Consent:** não se aplica — nenhuma superfície Payload, nenhum opt-in; Fluxo 100% client-side e a escolha não sai do aparelho.
|
||||
- **UI:** Impeccable C — shape já fixado no gate (cenas 01–06); craft = port das medidas/classes; critique = prova lado a lado da cena 06 (linha fixa × preenchida) + pior nome; polish se a prova pedir. Shells/tokens reusados: `CardComposer`, `CardPreviewCanvas`, `StateDeputySelect`, `--pt-red`/`--campaign-*`; nada de superfície nova.
|
||||
|
||||
### Dados → forma (se aplicável)
|
||||
|
||||
Não se aplica (data-presentation Q3): nenhum KPI, mapa ou série; a "forma" é a arte + a linha. A escolha do estadual segue insumo local da imagem (nunca coletada/apresentada/enviada); a medição de uso é S32 e fica intocada.
|
||||
|
||||
## Fases verificáveis
|
||||
|
||||
1. **Base + escala (tracer)** — quota ~0,25 dia. `cardModels` com a arte como `assetSrc` (Decisão 4); `renderColinhaCard` desenhando só a arte em 1080×1920 com smoothing (Decisão 6); branch do composer enxuto; `COLINHA_ROW_LAYOUT` + `fitColinhaRowName` nascem.
|
||||
Prova: `pnpm gate:fast`; `?model=minha-colinha` no browser com a prévia = JPEG intacto (rótulo queimado visível) e CTA desabilitado; probe do e2e do vazio atualizado (varredura da faixa com a arte intacta); unit do tile (sha256 + 900×1600) verde.
|
||||
2. **Linha preenchida** — quota ~0,3 dia. Máscara + rótulo + nome (fit) + cinco dígitos na ordem do design; pins de geometria em `cardColinha`/`cardRender`; e2e do preenchido e do pior nome.
|
||||
Prova: `pnpm gate:fast`; unit verdes; e2e do describe verde; prova lado a lado (cena 06) com JULIO PINHEIRO e com `Artur Barachisio Lisbôa` anexada ao PR.
|
||||
3. **Vazio/gate + remoção do código morto** — quota ~0,2 dia. Estado vazio provado (arte + CTA off, Decisão 5); remoção de `COLINHA_LAYOUT`/`draw*`/`capAt`/`fitColinhaCandidate`/`COLINHA_FIXED_ROWS`/`colinhaVoteRows`/placeholder/legal/confirm; remoção de `lockupSrc` + estado/carregamento no composer; `Linha conferida` derivada (Decisão 3).
|
||||
Prova: `pnpm gate:fast` (knip sem órfãos e `tsc --noEmit` limpo); grep de `COLINHA_LAYOUT|colinhaVoteRows|fitColinhaCandidate|drawColinha|lockupSrc` sem referências de produção; e2e do fluxo segue verde.
|
||||
4. **Testes/gates + prova + changelog** — quota ~0,25 dia. e2e completo do describe (download/evento/troca), changelog, prova final no PR e `pnpm push`.
|
||||
Prova: `pnpm test:e2e --no-deps -- tests/e2e/frontend.e2e.spec.ts -g "Minha colinha"` verde; `pnpm push` (pre-push roda o gate de CI).
|
||||
|
||||
### Testes previstos por camada
|
||||
|
||||
- **unit (node + sharp) — `tests/unit/cardColinha.unit.spec.ts` (reescrever):** pins de `COLINHA_ROW_LAYOUT` (máscara/cópia/office/name/gap/dígito), stacks de fonte e `COLINHA_ESTADUAL_LABEL`; `fitColinhaRowName` (ideal mantém; nome longo encolhe em 1 linha; invariante `pairLeft ≥ mask.x` varrendo as 53 entradas do catálogo com medida conservadora); **manter** o describe do tile (sha256 `76505492…` + 900×1600).
|
||||
- **unit (jsdom + recorder falso) — `tests/unit/cardRender.unit.spec.ts` (substituir o describe S31):** ordem arte→máscara→rótulo→nome→dígitos; `drawImage(arte, 0, 0, 1080, 1920)` com `imageSmoothingQuality='high'`; geometria da máscara (264,6; 1073,28; 619,92×55,68); rótulo e nome à direita (`textAlign 'right'`, x = `copy.right` e `copy.right − nameWidth − 16,2`); cinco dígitos centrados em 312,66/387,18/461,70/536,22/610,74 (y 1163,04); `deputy = null` desenha **só** a imagem (zero `fillText`/`fillRect`); `globalAlpha` = 1; `letterSpacing` restaurado a `0px`. O fake ganha `imageSmoothingEnabled`/`imageSmoothingQuality` e registra `fillStyle` por chamada.
|
||||
- **unit — `tests/unit/cardModels.unit.spec.ts` (atualizar):** pin do modelo com `assetSrc:'/cards/modelo-colinha.jpeg'`, sem `overlaySrc`/`lockupSrc`/`previewSrc`, mantendo `kind:'colinha'`, `stateDeputyPicker`, `badge:'NOVO'` e `1080×1920`.
|
||||
- **int:** não se aplica — sem Payload/DB/access/escrita multi-collection; fluxo client-side + assets estáticos (manifesto e2e também não muda).
|
||||
- **e2e — `tests/e2e/frontend.e2e.spec.ts` (reescrever o describe S31 → S34):** vazio (CTA desabilitado; varredura da faixa do rótulo derivada de `COLINHA_ROW_LAYOUT` acha a tinta do rótulo queimado em `firstDarkX > 500`, sem tinta vermelha e com as caixas vazias); seleção por teclado (helper existente); preenchido (`firstDarkX` e `redFirstX` ≥ `mask.x` e `firstDarkX < 450` — rótulo reposto à esquerda e nome vermelho dentro da máscara — e o interior do círculo d1, região 34×34 no centro impresso, com tinta); `Linha conferida` literal; download `card-jorge-solla-minha-colinha.png` + assinatura PNG + evento S32 com slug; troca mantém habilitado; pior nome (`arthur`) com o par dentro da máscara. Sem pin de RGB exato (anti-aliasing de fonte varia) — contagem/luminância em regiões estáveis.
|
||||
|
||||
## Rabbit holes / Não escopo (engenharia)
|
||||
|
||||
- Redesenhar o topo/linhas fixas/legal/selos, "melhorar" a arte ou vetorizá-la (intenção, rabbit holes de produto).
|
||||
- Editar/re-encodar o JPEG (`modelo-colinha.jpeg` é cópia byte-a-byte pinada; nunca tocar).
|
||||
- Segunda via de composição (SVG/DOM/html2canvas) ou segundo editor/rota/`?estadual=`.
|
||||
- Embarcar face tipográfica nova — gatilho: reprovação da prova lado a lado (Decisão 2/B).
|
||||
- PDF/A4; nome/foto do visitante; qualquer medição da escolha (S32 intocado).
|
||||
- CMS/collection/migration; ler `stateDeputy`/`Contact`; qualquer superfície Payload.
|
||||
- Tocar em `StateDeputySelect`, `stateDeputyCatalog`, `CardModelTile`, `CardModelGallery`, `CardsStudio`, `CardPreviewCanvas`, `cardCanvas.ts` (só o `CardDrawContext` muda, em `cardRender.ts`).
|
||||
- Fatiar o `CardComposer` (#1277, OPEN/blocked/P3): não iniciar aqui; se mergear antes, rebase (o branch toca só o branch da colinha).
|
||||
|
||||
## Riscos e mitigação
|
||||
|
||||
- **Fonte NEEDS ASSET (face exata não existe no repo):** stack do design (`Arial Black, Arial, Helvetica, sans-serif`) + prova lado a lado na cena 06 anexada ao PR (o e2e não pina pixels de glifo); gatilho: reprovação no gate → adotar a Decisão 2/B (embarcar face) como follow-up.
|
||||
- **Pins antigos quebram (unit/render/models/e2e e o probe de pixel (426,1102)):** reescrever no mesmo PR; `pnpm gate:fast` (knip) + grep sem referências mortas; a remoção da via antiga é o teste de que não sobrou twin.
|
||||
- **`#1277` no mesmo arquivo (OPEN/blocked/P3):** branch isolado no `if (isColinhaModel)`; rebase se mergear antes; não antecipar a fatia.
|
||||
- **`CardDrawContext` compartilhado:** a extensão é aditiva; só a colinha seta `imageSmoothing*`; nenhum call site S13–S30 muda; o único fake ganha os 2 membros.
|
||||
- **Nomes longos do catálogo:** fit de 1 linha sem floor (domínio = catálogo congelado); varredura das 53 entradas no unit + e2e com `arthur`; se um futuro catálogo trouxer nome absurdo, revisitar a Decisão 7 (não cortar o nome em silêncio).
|
||||
- **Nitidez da ampliação 1,2×:** `imageSmoothingQuality='high'` + conferência do PNG baixado no PR/UAT; sem re-render/reescala parcial.
|
||||
- **Baseline/top da linha vs design (sub-pixel):** baseline compartilhada ancorada no cap do nome em `copy.top`; a prova lado a lado da cena 06 é o aceite e só `copy.top` se move se divergir.
|
||||
- **Probes e2e flaky:** regiões (não pixel único) + limiar de luminância; as áreas sondadas são branco puro na arte (conferido no JPEG: interior dos círculos = 255; faixa da máscara = 255).
|
||||
- **Tile/`previewSrc` removido:** `CardModelTile` cai no fallback `assetSrc` — mesma imagem; unit pina e nenhum visual muda.
|
||||
|
||||
## Aceite de engenharia
|
||||
|
||||
- [ ] Aceite de produto da intenção ainda coberto: prévia/download = JPEG aprovado ampliado 1,2× com só a linha `DEPUTADO ESTADUAL` preenchida (nome caixa alta + 5 dígitos, um por caixa); sem nada mais redesenhado; vazio = arte como está + download desabilitado; tipografia/peso/cor/linha de base da linha; tile segue o JPEG; um só fluxo (`#cards`, `/cards`, `?model=minha-colinha`); 100% no aparelho; S30/S32 intocados.
|
||||
- [ ] Invariantes AGENTS/engineering-standards: sem migration/collection/Consent; `src/lib` puro/client-safe; copy pt-BR e identificadores em inglês; sem `as never`; knip sem órfãos; arte intocada; `pnpm gate:fast` + e2e da superfície + `pnpm push` verdes.
|
||||
- [ ] Testes de domínio previstos (unit/int): unit de `cardColinha` (geometria, fit, catálogo, tile), `cardRender` (ordem/geometria/vazio/smoothing) e `cardModels` (pin do modelo) obrigatórios; e2e do fluxo no spec `frontend` (vazio + CTA off, seleção, preenchido, pior nome, download com assinatura PNG e evento, troca); **int não se aplica** — sem Payload/DB/access nem escrita multi-collection.
|
||||
|
||||
## Self-score decision-quality: 5/5
|
||||
|
||||
1. **Decisões caras com rejeitadas:** composição (canvas × DOM/SVG), fonte (próxima × embarcar × peso só), código morto, modelo/campos, gate vazio, suavização/`CardDrawContext` e fit do nome — todas com Opções/Recomendação/Rejeitadas.
|
||||
2. **Cabe no appetite:** 4 fases ~1 dia, sem migration/asset/dependência; o maior peso é reescrever testes que já existem.
|
||||
3. **Rabbit holes nomeados:** redesenho/vetorização da arte, editar o JPEG, segunda via de composição/editor, embarcar fonte (com gatilho), PDF/A4, CMS, S30/S32, `#1277`.
|
||||
4. **Depth check:** reusa o dono `renderColinhaCard`, o composer/seletor/catálogo/prévia/download existentes, o padrão de pins unit + e2e do estúdio e o manifesto e2e; nada de abstração nova — as constantes/funções novas substituem as antigas no mesmo dono (`cardColinha.ts`).
|
||||
5. **Intenção preservada:** o outcome ("a arte exata + a linha do estadual preenchida") é intocado; a engenharia só resolveu forma (remover a recriação, repontar o modelo, desenhar o overlay no canvas).
|
||||
|
||||
## Addendum — crítica final do designer (c), 2026-09-24
|
||||
|
||||
Primeira passada: **AJUSTES NECESSÁRIOS**; segunda passada: **CERTIFICADO** (tier `openai/gpt-5.6-sol`). Ajustes aplicados sobre o plano original:
|
||||
|
||||
1. **Rótulo (P1):** `office.fontSize` 23,22 → **26,9px** (peso 400 mantido), cap height ≈ 19,2px igual aos rótulos impressos da arte; a exceção ao gate está documentada em `cardColinha.ts`.
|
||||
2. **Prévia vazia (P2):** 145px → **248px mobile / 236px desktop** (`max-w-[15.5rem] sm:max-w-[14.75rem]`), cenas 01–02 do gate S34.
|
||||
3. **Desktop preenchido (P2):** grid de 2 colunas (`sm:grid-cols-[430px_1fr]`, gap 32px) dentro de um dialog de 960px (`data-colinha-filled` + `has-[[...]]:sm:max-w-[60rem]` no `CardsStudio`); o vazio permanece no dialog compacto de 512px. A prévia tem teto de altura (`max-h-[calc(92dvh-14rem)]`) para o 9:16 inteiro nunca ser cortado pelo footer — ~340px de largura em viewport 1280×900, chegando aos 405px da cena 03 em viewports altos.
|
||||
4. **Fit do nome:** a fronteira dura do par passou a ser a máscara (`maxWidth = (copy.right − mask.x) − officeWidth − gap`), como o CSS do gate faz; o e2e pina `firstDarkX`/`redFirstX ≥ mask.x` e o nome vermelho (não só o rótulo escuro).
|
||||
|
||||
## Débitos deferidos com gatilho (/simplify, 2026-09-24)
|
||||
|
||||
- **`imageSmoothing` sem `save/restore` no ctx compartilhado** (`cardRender.ts`): hoje inalcançável (cada modelo remonta o canvas); gatilho — o ctx passar a ser reusado entre desenhos/escalas no mesmo canvas.
|
||||
- **Contrato `data-colinha-filled` → `has-[[…]]:sm:max-w-[60rem]` sem asserção no e2e:** só comentários nos dois lados; gatilho — próxima mudança no dialog da colinha/atributo (ou nova passada de e2e no estúdio).
|
||||
- **Sweep de fit com medida sintética (0,84em/caractere):** o e2e cobre o pior nome (`arthur`) e o sweep é conservador; gatilho — entrada nova no catálogo mais larga que `arthur` ou queixa visual de corte.
|
||||
- Absorvidos em `#1277` (`escala-dry-pos-s30.md`): D1 (uppercase duplicado) e D2 (`ensureCardFont` gateando a colinha).
|
||||
95
docs/plans/cards-header-modal-largura-impl.md
Normal file
95
docs/plans/cards-header-modal-largura-impl.md
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
# Impl: S35 — Header do modal de criação de card: largura do card e fechar na borda
|
||||
|
||||
Status: aprovado
|
||||
Atualizado em: 2026-09-24
|
||||
Issue: #1299
|
||||
Intenção: docs/plans/cards-header-modal-largura.md
|
||||
Appetite restante: ~0,3–0,5 dia (quase intacto; só correção de 1 classe no ponto de uso)
|
||||
|
||||
## Leitura da intenção
|
||||
|
||||
- **Outcome:** modal desktop de criação de card com header na largura do modal — título à esquerda, botão × na borda direita — paridade com artefatos aprovados.
|
||||
- **O que NÃO negociar:**
|
||||
- Drawer mobile inalterado (já correto — `DrawerHeader min-w-0 flex-1 text-left`).
|
||||
- Sem copy nova, sem tipografia nova, sem primitivas novas.
|
||||
- Correção no ponto de uso (`CardComposer.tsx` / `CardsStudio.tsx`), nunca em `src/components/ui/dialog.tsx` ou `src/components/ui/Drawer.tsx`.
|
||||
- Header único para os 6 modelos (`CardComposer.tsx:654-696` + `src/lib/cardModels.ts`) — um fix cobre todos.
|
||||
- **O que reavaliar:** apenas qual classe Tailwind carrega o `flex-1/w-full` — se no `DialogHeader` ou no wrapper. Não reavaliar: primitivas, drawer, redesign do header, outras telas.
|
||||
|
||||
## Abordagem recomendada
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A[CardsStudio Dialog<br/>showCloseButton=false<br/>DialogContent flex flex-col gap-0 p-0 sm:max-w-lg] --> B[CardComposer wrapper<br/>flex items-start gap-3 px-5 pt-5]
|
||||
B --> C{header: DialogHeader<br/>min-w-0 text-left SEM flex-1}
|
||||
B --> D[button aria-label=Fechar<br/>size-11 shrink-0]
|
||||
C -. encolhe, × gruda à esquerda .-> E[BUG gate w-228px]
|
||||
C ==>|fix: min-w-0 flex-1| F[header largura total<br/>× borda direita]
|
||||
```
|
||||
|
||||
**Opções consideradas:** A | B | C
|
||||
**Recomendação:** Opção A — `flex-1` + `min-w-0` no `DialogHeader` do ponto de uso — porque é o depth check mínimo (reusar, não criar módulo), espelha o drawer já correto, e o gate fica determinístico. (Simplify: `w-full` removido como redundante com `flex-1` no flex-row pai — sem mudança de comportamento.)
|
||||
**Rejeitadas:** C porque blast radius global (todos os modais herdam; proibido pela intenção); B porque adiciona DOM/div extra redundante que o drawer prova ser desnecessária.
|
||||
|
||||
### Opção A — `flex-1 + w-full + min-w-0` no `DialogHeader` do ponto de uso (recomendada)
|
||||
|
||||
- Mudar `src/components/cards/CardComposer.tsx:681` de `min-w-0 text-left` para `min-w-0 flex-1 text-left` (manter `min-w-0` para ellipsis não estourar o flex).
|
||||
- Wrapper `:800-810` (`flex items-start gap-3 px-5 pt-5` + `{header}` + botão fechar) e shell `CardsStudio.tsx:74-93` ficam intocados.
|
||||
- Custo: 1 linha. Reversível em segundos. Precedente direto S15/S23/S30/S31 (fix no ponto de uso).
|
||||
|
||||
### Opção B — Alargar pelo wrapper (`flex-1` no slot do header ou `justify-between`/`w-full` no container)
|
||||
|
||||
- Ex.: envolver `{header}` em `<div className="min-w-0 flex-1">` ou dar `w-full` ao wrapper.
|
||||
- Funciona, mas adiciona DOM/div extra para corrigir o que é falta de `flex-1` no próprio `DialogHeader`; diverge do drawer que já resolve com `flex-1` no header (`:689`).
|
||||
|
||||
### Opção C — Corrigir na primitiva `ui/dialog.tsx:51-83`
|
||||
|
||||
- Ex.: forçar `DialogHeader` a `flex-1 w-full` por padrão.
|
||||
- **Rejeitada:** blast radius global — todo `Dialog` do app herdaria o comportamento; viola a regra "correção no ponto de uso, nunca na primitiva".
|
||||
|
||||
### Componentes / mudanças
|
||||
|
||||
- **`src/components/cards/CardComposer.tsx:681`** (`DialogHeader`): adicionar `flex-1` (manter `min-w-0 text-left`). Única mudança de produção esperada.
|
||||
- **`src/components/cards/CardComposer.tsx:800-810`** (wrapper): **somente leitura/verificação**, sem edição salvo se o gate provar insuficiência (fallback: Opção B).
|
||||
- **`src/components/cards/CardsStudio.tsx:74-93`** (shell Dialog): **sem edição** (`showCloseButton={false}`, `DialogContent flex flex-col gap-0 p-0 sm:max-w-lg` já corretos). Mobile `:60-72` (`Drawer` + `h-dvh`): **não tocar**.
|
||||
- **`src/lib/cardModels.ts` + `CardComposer.tsx:654-696`**: nenhum branch por modelo; fix único cobre os 6.
|
||||
- **`tests/e2e/frontend.e2e.spec.ts:1824-2453`**: suíte de referência; estender/ajustar asserção de largura do header se ainda não cobrir (precedente S15/S23/S30/S31).
|
||||
- **NÃO tocar:** `src/components/ui/dialog.tsx:51-83`, `:85-93`, `src/components/ui/Drawer.tsx:161-170`.
|
||||
- **Migration:** sem migration — sem mudança de schema.
|
||||
- **Access / Consent:** N/A — sem mudança de acesso, sem opt-in, sem PII.
|
||||
- **UI:** Impeccable C — sem linguagem visual nova, só alinhamento/ocupação de largura para paridade. Evidência = screenshot desktop antes/depois + gate e2e verde; drawer mobile pixel-idêntico.
|
||||
|
||||
### Dados → forma (se aplicável)
|
||||
|
||||
N/A — nenhum dado novo; header deriva dos 6 modelos existentes em `src/lib/cardModels.ts`.
|
||||
|
||||
## Fases verificáveis
|
||||
|
||||
1. **Tracer / schema+server — visual (0,1 dia):** aplicar Opção A (1 classe em `:681`); subir `pnpm dev`; abrir criação de card no desktop (viewport ≥1024) e confirmar: título à esquerda, × na borda direita, header ocupa a largura do modal; abrir drawer mobile e confirmar inalterado.
|
||||
2. **UI (0,1–0,2 dia):** rodar/estender `tests/e2e/frontend.e2e.spec.ts:1824-2453` — asserção: header com `flex-1` ocupando a linha, botão `aria-label=Fechar` alinhado à borda direita. Rebase sobre `main` e checar conflito com #1277/S33/S34.
|
||||
3. **Gates — `pnpm gate:fast`; push via `pnpm push` (0,1 dia):** lint → format → typecheck → unit/int afetados → build → e2e selecionado; PR com antes/depois desktop + confirmação de drawer inalterado.
|
||||
|
||||
## Rabbit holes / Não escopo (engenharia)
|
||||
|
||||
- **NÃO** editar `src/components/ui/dialog.tsx` nem `src/components/ui/Drawer.tsx`.
|
||||
- **NÃO** redesenhar o header (copy, tipografia, ícone, espaçamento novo).
|
||||
- **NÃO** tocar no drawer mobile (`CardComposer.tsx:689`, `CardsStudio.tsx:60-72`).
|
||||
- **NÃO** investigar `useIsMobileMeasured` / breakpoints do shell.
|
||||
- **NÃO** abrir outras telas/modais.
|
||||
- **Cuidado conflito:** #1277/S33/S34 tocam áreas vizinhas — rebase cedo; manter `flex-1` no `DialogHeader` (Opção A), não duplicar no wrapper.
|
||||
|
||||
## Riscos e mitigação
|
||||
|
||||
- Fix no header não basta (wrapper impõe shrink) — Baixa/baixo — fallback Opção B; gate e2e decide em minutos.
|
||||
- Regressão no drawer mobile — Baixa/médio — não tocar no drawer; verificação manual mobile + e2e existente.
|
||||
- Regressão em outros Dialogs — Muito baixa/alto — não tocar na primitiva; mudança isolada a `CardComposer.tsx:681`.
|
||||
- Conflito com #1277/S33/S34 — Média/baixo — rebase antes da Fase 2; fix de 1 linha reaplica-se trivialmente.
|
||||
- Gate e2e não cobre a largura do header — Média/baixo — estender asserção em `frontend.e2e.spec.ts:1824-2453`.
|
||||
|
||||
## Aceite de engenharia
|
||||
|
||||
- [ ] Aceite de produto da intenção ainda coberto (header largura total desktop, drawer idêntico)
|
||||
- [ ] Invariantes AGENTS/engineering-standards (ponto de uso, sem primitiva, sem migration, sem access/consent)
|
||||
- [ ] Testes de domínio previstos (e2e do funil; sem unit/int — sem lógica pura/fronteira Payload)
|
||||
|
||||
**Self-score decision-quality: 5/5** — só o ponto de uso é decisão (A vs B vs C registradas); depth check = reusar header existente, zero módulo novo; appetite respeitado com tracer bullet; rabbit holes nomeados; reversibilidade explícita (1 classe Tailwind).
|
||||
155
docs/plans/cards-time-ajuste-sem-limite-impl.md
Normal file
155
docs/plans/cards-time-ajuste-sem-limite-impl.md
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
# Impl: S33 — Card do time (você e estadual): ajuste da foto livre, sem limite
|
||||
|
||||
Status: aprovado (modo --auto)
|
||||
Atualizado em: 2026-09-24
|
||||
Issue: #1297
|
||||
Intenção: docs/plans/cards-time-ajuste-sem-limite.md
|
||||
Appetite restante: herdado (~0,5 dia) — sem migration; 3 fases: régua pura ~0,25 + render/composer ~0,2 + gates/changelog ~0,05
|
||||
|
||||
## Leitura da intenção
|
||||
|
||||
- **Outcome:** nos dois modelos de time (`time-de-voce`, `time-do-estadual`), depois do enquadramento automático S15, arrasto/setas/teclado movem a foto livremente nos dois eixos — inclusive para fora do quadro, revelando a arte de trás; a área de arrasto segue ativa para voltar; prévia e PNG mostram a mesma posição (sem "voltar sozinho"); o zoom segue `[1,4]`; S13/S14, colinha e o resto do funil ficam intocados; sem controle, copy ou telemetria novos.
|
||||
- **O que NÃO negociar:**
|
||||
- Sem limite de posição (X e Y) nos dois modelos do time — decisão do gate (2026-09-24); nada de âncora de silhueta, caixa medida, união de alcances, margem de composição ou colisão com candidatos (o S20/revert `48e08bf7` é história, não base).
|
||||
- Enquadramento inicial S15 (`frameCardPhotoOnBbox`) intocado, aplicado uma vez ao carregar a foto; zoom `[1,4]` intocado; preview = PNG (`toBlob` do mesmo canvas, sem re-render).
|
||||
- S13/S14 (`eu-sou-solla`, `perfil-quadrado`, `perfil-retangular`) e `renderPhotoCard` sem mudança de superfície; colinha (S31) não tem transform de foto.
|
||||
- Sem controle/copy/estado de erro/telemetria novos; 100% no aparelho; sem migration/Consent/access/int.
|
||||
- **O que reavaliar (hipóteses da intenção):**
|
||||
- "o limite vive só em `cardPhotoTransform.ts`": há re-clamp no desenho **e** no retorno de `renderTeamCard` (`src/lib/cardRender.ts:312` e `:314`), e o retorno é o contrato do write-back (`CardComposer.tsx:413-415`); se o render não souber da política, o snap-back volta.
|
||||
- "os controles do composer bastam": o pan é um funil (`withTransform` + `panBy` + `zoomTo`, `CardComposer.tsx:527-575`) e o zoom re-clampa a posição também no caminho "zoom inalterado" (`cardPhotoTransform.ts:181`) — ponto silencioso de snap-back.
|
||||
- "não há nada a preservar no S13/S14": há — o default omitido das funções do dono e o `renderPhotoCard` (que não recebe modelo). A garantia mais forte é: **specs S13/S14 passam sem edição**.
|
||||
- "`#1277` só conflita por arquivo": o diff no composer deve ser mínimo (1 constante + 3 closures) para o rebase do S30-FOLLOWUP-DRY ser barato.
|
||||
|
||||
## Abordagem recomendada
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
CAT["catálogo: photoPosition 'free' nos 2 modelos do time"] --> POS{"position do modelo"}
|
||||
POS -->|free| COMP["CardComposer: arrasto/setas/teclado/zoom sem clamp de posição"]
|
||||
POS -->|free| REN["renderTeamCard: drawRect + retorno sem clamp de posição"]
|
||||
COMP --> WB["write-back idempotente (cardPhotoTransformsEqual) — sem snap-back"]
|
||||
REN --> WB
|
||||
REN --> PNG["PNG = canvas já pintado (toBlob, sem re-render)"]
|
||||
POS -->|"omitido = bounded"| S13["renderPhotoCard + centerCardPhotoTransform — S13/S14 de hoje"]
|
||||
INIT["frameCardPhotoOnBbox (S15) — clamp bounded"] -.->|"ponto de partida"| COMP
|
||||
ZOOM["zoom sempre clampado [1,4]"] --> COMP
|
||||
ZOOM --> REN
|
||||
```
|
||||
|
||||
**Opções consideradas:** A) política por modelo no catálogo (`photoPosition`) + opção `position` no dono, default omitido = bounded, lida pelo composer e pelo `renderTeamCard` | B) `kind === 'team'` derivado em cada call site | C) threading do composer → `TeamCardRenderArgs` (forma S20) | D) remover o clamp de posição para todos os modelos | E) branch por `model.id` dentro do render.
|
||||
**Recomendação:** A — a regra é do modelo, não da chamada; o catálogo já carrega as decisões por modelo (`photoWindow`, `overlaySrc`, `stateDeputyPicker`) e passa a ser a **fonte única** consumida pelos dois pontos (composer e render), o que elimina por construção a divergência que a S20 tinha de resolver com threading de um dado dinâmico. O default omitido preserva literalmente S13/S14 e o S15 inicial.
|
||||
**Rejeitadas:** B porque a regra ficaria duplicada em dois call sites e o catálogo não a registraria (o gate diz "os dois modelos do time"); C porque threadar um valor **estático** por toda a cadeia é cerimônia sem volatilidade (na S20 era dado dinâmico: a âncora); D porque reabre o aceite ("os 3 modelos anteriores intocados"); E porque acopla o renderizador a ids e o catálogo já é o dono do comportamento por modelo.
|
||||
|
||||
### Decisões de engenharia
|
||||
|
||||
1. **Onde vive a política: campo `photoPosition` no catálogo, tipo `CardPhotoPosition` exportado de `cardModels.ts`.**
|
||||
Opções: A) `CardPhotoPosition = 'bounded' | 'free'` em `src/lib/cardModels.ts`; `CardModel.photoPosition?: CardPhotoPosition` setado `'free'` só em `time-de-voce` (`cardModels.ts:93-102`) e `time-do-estadual` (`:104-118`); omitido nos demais | B) booleano `freePhoto?: boolean` no catálogo | C) derivar de `kind === 'team'` sem campo | D) `photoPosition` em `cardPhotoTransform.ts` (importado por `cardModels`).
|
||||
Recomendação: A — uma definição só, no vocabulário do catálogo; `cardPhotoTransform.ts` importa o tipo **type-only** na direção que já existe (`cardPhotoTransform` → `cardModels`, como `CardRect`), sem ciclo; `cardModels.unit.spec.ts` pina que só os dois modelos do time são `'free'`.
|
||||
Rejeitadas: B — flag assimétrica ("free quando setado") esconde o valor default; C — regra duplicada em composer/render e invisível no catálogo; D — inverte a direção de dependência e cria ciclo type-only desnecessário com madge/knip.
|
||||
|
||||
2. **API do clamp: opção `position` no dono; `free` clampa só o zoom.**
|
||||
Opções: A) `CardPhotoClampOptions = { position?: CardPhotoPosition }` como último parâmetro de `clampCardPhotoTransform` (`cardPhotoTransform.ts:76-91`), `cardPhotoDrawRect` (`:60-74`) e `panCardPhotoTransform` (`:153-164`), e como 6º parâmetro de `zoomCardPhotoTransform` (`:170-194`; o `anchor` segue posicional no 5º — o objeto de options do S18 não existe mais desde o revert `48e08bf7`, e manter a posição evita editar os pins default); `position: 'free'` devolve `offsetX/offsetY` intactos e clampa `zoom` em `[1,4]` | B) booleano posicional `free?: boolean` | C) gêmeas `panCardPhotoTransformFree`/`cardPhotoDrawRectFree` | D) flag dentro do `CardPhotoTransform`.
|
||||
Recomendação: A — a política fica nomeada no call site (`{ position: 'free' }`), o default omitido é o comportamento de hoje byte a byte, e o clamp continua idempotente (`clamp(clamp(t)) = clamp(t)`) porque `free` só normaliza o zoom. `frameCardPhotoOnBbox` (`:115-150`) fica intocado e bounded.
|
||||
Rejeitadas: B — `pan` chegaria a 6º posicional e o call site não nomeia a política; C — gêmeas rasas que duplicam a régua de zoom e criam superfície morta no knip; D — o transform é o dado que o composer guarda e compara (`cardPhotoTransformsEqual`), embutir política nele polui o contrato do write-back.
|
||||
|
||||
3. **Zoom com posição livre: clamp de zoom sempre, re-clamp de posição nunca — inclusive no caminho "zoom inalterado".**
|
||||
Opções: A) em `zoomCardPhotoTransform`, clampa `nextZoom` a `[1,4]`, preserva a âncora e passa `position` adiante; o early-return `zoom === transform.zoom` (`:181`) também respeita `position` (free = posição intacta) | B) manter o re-clamp no early-return | C) liberar o zoom também.
|
||||
Recomendação: A — o early-return é um ponto silencioso de snap-back: tocar o slider sem mudar o zoom desfaria a posição livre; com free ele devolve a posição intacta (só o zoom normalizado). O zoom continua `[1,4]` em todos os modelos, como o aceite manda.
|
||||
Rejeitadas: B — é exatamente o "voltar sozinho" que o aceite proíbe; C — viola o aceite ("os limites do zoom seguem iguais").
|
||||
|
||||
4. **Render: `renderTeamCard` desenha e devolve com a mesma política lida do `model`; `renderPhotoCard` intocado.**
|
||||
Opções: A) `renderTeamCard` (`cardRender.ts:303-336`) deriva `position = model.photoPosition ?? 'bounded'` e usa no `cardPhotoDrawRect` (`:312`) e no retorno (`:314`); `renderPhotoCard` (`:224-233`) segue chamando as funções sem options (bounded) | B) `renderTeamCard` devolve o transform cru, sem normalizar o zoom | C) o composer passa o transform já livre e o render não clampa.
|
||||
Recomendação: A — o retorno continua normalizando o zoom (contrato do write-back) mas nunca re-limita a posição; desenho e retorno com o **mesmo** contexto derivado do mesmo `model`, então o bug de divergência não volta; `renderPhotoCard` não recebe modelo e permanece bounded por default.
|
||||
Rejeitadas: B — perde a normalização de zoom que o contrato do render sempre teve; C — o render deixa de ser auto-suficiente (um futuro chamador desenharia diferente do que devolve).
|
||||
|
||||
5. **Composer: uma constante de política, usada nos três funis de gesto.**
|
||||
Opções: A) `const photoPosition = model.photoPosition ?? 'bounded'` no `CardComposer` e uso nos closures de `handlePointerMove` (`:556-558`), `panBy` (`:565-569`) e `zoomTo` (`:571-575`); nenhum estado/UI/copy novos | B) cada call site decide | C) mudar `withTransform` para injetar a opção.
|
||||
Recomendação: A — `panBy` já serve setas e teclado (`:832-848`), então os três funis fecham sobre a mesma constante; `withTransform` fica intocado exceto os closures; diff mínimo para o rebase do `#1277`.
|
||||
Rejeitadas: B — divergência silenciosa entre gestos (um gesto limitado e outro livre); C — muda a assinatura de um helper interno sem ganho.
|
||||
|
||||
6. **Divergência registrada — "os 3 modelos anteriores ficam intocados": a superfície S13/S14 não muda em nada.**
|
||||
Opções: A) garantia por construção: defaults omitidos nas funções do dono, `renderPhotoCard` sem options, `centerCardPhotoTransform` intocado, `handlePhotoFile` intocado, catálogo sem `photoPosition` nos modelos de foto; **nenhum spec S13/S14 editado** (se algum precisar de edição, a entrega parou) | B) atualizar os testes S13/S14 "se necessário" | C) unificar os dois renderizadores com a opção nos dois.
|
||||
Recomendação: A — o aceite "intocados" vira uma checagem objetiva: os describes de `clampCardPhotoTransform`/`pan`/`zoom` default, o `renderPhotoCard` e o e2e S14 (`tests/e2e/frontend.e2e.spec.ts:1767`) passam **sem edição**. Só os pins do time mudam (eles pinam o comportamento antigo do time, não o dos 3 anteriores).
|
||||
Rejeitadas: B — editar asserção de modelo anterior é o próprio sinal de regressão; C — "simetria" sem caso de uso que mudaria o desenho do S13/S14 (foto sempre cobrindo a janela).
|
||||
|
||||
7. **Testes de domínio: atualizar os pins do time, adicionar o caminho livre nos dois eixos e manter os pins dos anteriores.**
|
||||
Opções: A) `tests/unit/cardPhotoTransform.unit.spec.ts`: manter `clampCardPhotoTransform` (`:116-142`), `pan` (`:144-155`), `zoom` (`:157-184`) e `frameCardPhotoOnBbox` (`:58-114`) **sem edição**; novo describe do free: offsets preservados nos dois eixos, zoom ainda `[1,4]`, `zoom` inalterado preserva posição (anti-snap-back), idempotência; `tests/unit/cardRender.unit.spec.ts`: atualizar o pin do retorno do `renderTeamCard` (`:290-310`) para "zoom clampado, posição preservada" e adicionar um pin bounded do `renderPhotoCard` (transform fora da janela volta clampado e o retângulo cobre a janela); `tests/unit/cardModels.unit.spec.ts`: pin do `photoPosition` (`'free'` nos dois do time, `undefined` nos demais) | B) apagar os pins antigos do clamp e reescrever tudo | C) só unit, sem catálogo.
|
||||
Recomendação: A — os pins default continuam sendo a cobertura dos 3 anteriores; os novos cobrem X **e** Y livres, a faixa de zoom e o anti-snap-back do caminho de zoom; o pin de catálogo torna a política visível e testável.
|
||||
Rejeitadas: B — apagaria a cobertura dos modelos anteriores; C — a política ficaria sem pin de dados.
|
||||
|
||||
8. **e2e: um teste novo, no seam que já existe — decidido adicionar.**
|
||||
Opções: A) novo describe `Cards personalizados (S33 — ajuste livre do time)` com 1 teste no `frontend.e2e.spec.ts`, usando o stub existente + teclado + sonda de pixel: com stub `ok` e harmonização desligada, a sonda `(500,727)` é azul `[30,120,200,255]` no enquadramento S15; focar o grupo `Ajuste da foto`, 8× `Shift+ArrowRight` (48px de card cada → +384, contra o teto antigo de X do stub: `offsetX` inicial ≈197,33, faixa antiga `[108,67, 286]`), poll da sonda ≠ azul (a foto saiu da janela e a arte de trás aparece), esperar 250ms e conferir que **continua** ≠ azul (sem snap-back do write-back), slider de zoom ainda 1 | B) nenhum e2e novo | C) medir o curso em pixels de card com um seam novo.
|
||||
Recomendação: A — o outcome é comportamento de browser e a fiação composer↔render não tem unit (o `CardComposer` é um client component grande, com `#1277` pendente); o teste usa só seams existentes (stub, handler de teclado, sonda) e pina exatamente as duas falhas reais do histórico: o limite que persiste e o snap-back. O manifest `scripts/lib/e2e-affected-manifest.mjs:189-196` já mapeia `src/components/cards`/`src/lib/card` → `frontend`, sem edição.
|
||||
Rejeitadas: B — deixaria a fiação (3 funis de gesto + write-back) sem cobertura de integração; C — frágil, mediria a geometria do stub e exigiria seam novo (e o unit já pina a régua).
|
||||
|
||||
### Componentes / mudanças
|
||||
|
||||
- **`CardPhotoPosition` + `CardModel.photoPosition`** (`src/lib/cardModels.ts`): união `'bounded' | 'free'` e campo opcional documentado; `'free'` só em `time-de-voce` e `time-do-estadual`; omitido = bounded (S13/S14, nome, colinha).
|
||||
- **`CardPhotoClampOptions` + `position`** (`src/lib/cardPhotoTransform.ts`): `clampCardPhotoTransform`, `cardPhotoDrawRect` e `panCardPhotoTransform` ganham o último parâmetro opcional; `zoomCardPhotoTransform` ganha o `options` no 6º parâmetro (o `anchor` permanece posicional no 5º — o objeto de options do S18 não voltou no revert); free = offsets intactos, zoom sempre `[1,4]`; early-return do zoom respeita `position`. `frameCardPhotoOnBbox` e `centerCardPhotoTransform` intocados.
|
||||
- **`renderTeamCard`** (`src/lib/cardRender.ts:303-336`): deriva `position` do `model` e usa no draw (`:312`) e no retorno (`:314`); `renderPhotoCard` (`:224-233`) intocado.
|
||||
- **`CardComposer`** (`src/components/cards/CardComposer.tsx`): `photoPosition` derivado do `model` e passado nos closures de arrasto (`:556-558`), `panBy` (`:565-569`) e `zoomTo` (`:571-575`). Nenhuma mudança de UI, estado, copy ou erro; `handleDownload` (`:584`) segue `toBlob` do canvas pintado.
|
||||
- **Testes:** `tests/unit/cardPhotoTransform.unit.spec.ts` (novo describe do free; pins default sem edição), `tests/unit/cardRender.unit.spec.ts` (pin do retorno do time atualizado + pin bounded do `renderPhotoCard`), `tests/unit/cardModels.unit.spec.ts` (pin do `photoPosition`), `tests/e2e/frontend.e2e.spec.ts` (novo describe S33; S14/S15/S30/S31 sem edição).
|
||||
- **`docs/changelog/2026-09-24-s33-card-time-ajuste-livre.md`** (novo, additions-only).
|
||||
- **Migration:** sem migration — nenhuma collection/global/field; catálogo estático; `push:false` intocado (100% client-side).
|
||||
- **Access / Consent:** não se aplica — nenhuma superfície Payload; a posição é geometria efêmera no aparelho; sem chave de Consent.
|
||||
- **UI:** Impeccable C — comportamento, sem controle/copy/telemetria novos. O artefato `docs/plans/cards-time-ajuste-sem-limite-ui-design.html` é a referência do gate (Cenas 1/2 e a anotação "Posição: sem clamp em X ou Y"); craft no browser com fotos reais (arrasto até fora do quadro nos dois modelos, voltar, zoom antes/depois, preview×PNG). Sem shape novo.
|
||||
|
||||
### Dados → forma (se aplicável)
|
||||
|
||||
Não se aplica — nenhum KPI, mapa ou série; nenhum dado apresentado/coletado/enviado. A única "forma" é geometria do card (janela `{286,439,592,577}`) e a posição efêmera no aparelho, como a intenção fixou.
|
||||
|
||||
## Fases verificáveis
|
||||
|
||||
1. **Tracer — régua pura do dono** — quota ~0,25 dia. `CardPhotoPosition`/`photoPosition` no catálogo; `CardPhotoClampOptions.position` em `clampCardPhotoTransform`/`cardPhotoDrawRect`/`panCardPhotoTransform`/`zoomCardPhotoTransform`; units novos (free X/Y, zoom `[1,4]`, anti-snap-back do zoom inalterado, idempotência) e pin do catálogo.
|
||||
Prova: `pnpm gate:fast` verde; os describes default de clamp/pan/zoom/frame e o `cardModels.unit.spec.ts` pré-existente seguem valendo sem edição; unit pina que `free` preserva offsets fora da janela nos dois eixos e que `bounded` (omitido) é byte a byte o de hoje.
|
||||
2. **Render + composer + e2e** — quota ~0,2 dia. `renderTeamCard` lendo o `model` no desenho e no retorno; `photoPosition` nos 3 funis do composer; pin do retorno do time atualizado; pin bounded do `renderPhotoCard`; teste e2e S33.
|
||||
Prova: `pnpm gate:fast` verde; unit do render (time devolve zoom clampado com posição livre; `renderPhotoCard` clampa e cobre a janela); e2e local do `frontend` verde, com S14/S15/S30/S31 sem edição.
|
||||
3. **Gates + changelog** — quota ~0,05 dia. e2e da superfície (`pnpm test:e2e:affected` ou `pnpm test:e2e --no-deps -- tests/e2e/frontend.e2e.spec.ts`), changelog, `pnpm gate:fast`, `pnpm push`.
|
||||
Prova: e2e S15 (`:1998`/`:2177`) e S30 (`:2227`) verdes sem edição (enquadramento inicial, harmonização, troca de estadual e download intactos); novo S33 verde; fixture de console/5xx intacta; PNG baixável.
|
||||
|
||||
## Rabbit holes / Não escopo (engenharia)
|
||||
|
||||
- Ressuscitar âncora/rosto/união do S20 (`resolveCardPhotoAnchor`, `anchorBox`, `frameCardPhotoOnFace`, detector): o gate decidiu sem limite e o revert `48e08bf7` removeu por inércia sob o S15; não voltam nem como "proteção".
|
||||
- Limite novo por composição: margem medida, colisão com caixas de candidatos, "não deixar cobrir rostos" — a barreira aprovada é **nenhuma**.
|
||||
- Clipar a foto na janela, manter cover mínimo ou impedir a foto de sair do quadro — contraria o aceite e a Cena 2 do gate.
|
||||
- Controles novos ("centralizar", "voltar ao enquadramento"), copy nova, estado de erro novo, telemetria de foto/posição, persistência.
|
||||
- Mexer no zoom (`[1,4]`), no enquadramento S15/`frameCardPhotoOnBbox`, na janela `{286,439,592,577}`, na arte-mestre ou no `centerCardPhotoTransform`.
|
||||
- Aplicar free a S13/S14 "por simetria", tornar a opção obrigatória, criar funções gêmeas ou mudar `renderPhotoCard`.
|
||||
- e2e medindo o curso em pixels de card (seam novo) ou novos modos de stub; unit de `CardComposer` (sem harness de React no repo para ele).
|
||||
- Fatiar o `CardComposer` (`#1277`) nesta entrega; migration/int/Consent/access.
|
||||
|
||||
## Riscos e mitigação
|
||||
|
||||
- **Snap-back do write-back** → política única lida do catálogo nos dois pontos (composer e `renderTeamCard`), desenho e retorno com o mesmo contexto; unit do retorno do render; e2e S33 pina a persistência após o pan.
|
||||
- **Zoom inalterado re-clampa a posição** → branch explícito no early-return de `zoomCardPhotoTransform`; unit "zoom inalterado preserva a posição livre".
|
||||
- **Deriva de S13/S14** → defaults omitidos; `renderPhotoCard`/`centerCardPhotoTransform`/`handlePhotoFile` sem edição; specs S13/S14 e e2e S14 **sem edição** (se algum pedir edição, parar e reavaliar).
|
||||
- **Foto totalmente fora do quadro** → `drawImage` aceita coordenadas fora do canvas; o canvas tem tamanho fixo e o PNG é o mesmo canvas; craft nos extremos (foto fora à direita/esquerda/cima/baixo) com fotos reais; sem estado de erro novo.
|
||||
- **Conflito com `#1277`** (CardComposer DRY, OPEN/blocked) → diff mínimo (1 constante + 3 closures); rebase antes de abrir o PR; sem tocar em `withTransform`/estado.
|
||||
- **Knip/cycles** → tipo novo importado type-only na direção existente `cardPhotoTransform` → `cardModels`; opção consumida em composer/render/testes; sem export órfão.
|
||||
- **e2e instável** → sonda e contagem de passos calculadas sobre o stub determinístico (4×3 → 400×300; S15: `offsetX≈197,33`, teto antigo 286; 8× `Shift+→` = +384 → 581,33; base em `(500,727)` = `[246,246,248]`); poll + espera de 250ms; sem rede nova.
|
||||
- **A11y/UX** → nenhum controle, copy ou área de toque mudam; foco/teclado/touch seguem iguais; a área de arrasto continua ativa mesmo sem a pessoa visível.
|
||||
|
||||
## Aceite de engenharia
|
||||
|
||||
- [ ] Aceite de produto da intenção ainda coberto: posição livre X+Y nos dois modelos do time (inclusive fora do quadro), S15 como ponto de partida, zoom `[1,4]`, preview = PNG sem snap-back, S13/S14 e colinha intocados, sem controle/copy/telemetria, 100% no aparelho.
|
||||
- [ ] Invariantes AGENTS/engineering-standards: math pura/client-safe em `src/lib` (sem DOM); identificadores em inglês, copy pt-BR; sem migration/Consent/access/int; knip/cycles verdes; `pnpm gate:fast` + e2e da superfície + `pnpm push`.
|
||||
- [ ] Testes de domínio previstos: unit do free nos dois eixos + zoom `[1,4]` + anti-snap-back + idempotência; pin do `photoPosition` no catálogo; pin do retorno do `renderTeamCard` e do `renderPhotoCard` bounded; e2e S33 novo; **specs S13/S14 e e2e S14 sem edição**; **int não se aplica** (client-side, sem DB/access/escrita multi-collection).
|
||||
|
||||
## Já resolvido no simplify/critique (não reabrir)
|
||||
|
||||
- JSDoc do `panCardPhotoTransform`/`zoomCardPhotoTransform` e o doc de `photoWindow`/cabeçalho do catálogo atualizados para o mundo com `free` (achados convergentes dos 2 revisores).
|
||||
- Comentário do pin de catálogo corrigido ("S13/S14 e a colinha" — 4 asserts) e as decisões 1/2 realinhadas ao código (o options object do S18 não existe mais desde o revert `48e08bf7`; o `anchor` segue posicional).
|
||||
- e2e da sonda endurecido: a asserção é a cor exata da arte de trás (`[246,246,248,255]`), não um "≠ azul" que um canvas em branco também passaria.
|
||||
|
||||
## Explicitamente fora / deferido com gatilho (triage)
|
||||
|
||||
- **S1 — `undefined` explícito no 5º parâmetro de `zoomCardPhotoTransform` no composer**: score 2, pureza; mover o `anchor` para um bag de options quebraria os pins default S13/S15 (a prova "sem edição") por ganho cosmético. **Descartado**.
|
||||
- **S2 — `windowPixel` (S33) duplica `windowCenterPixel` (S30) no e2e**: 2 call sites; DRY <3 é rabbit hole do repo e içar o helper editaria o describe S30 (a prova "sem edição"). **Descartado**.
|
||||
- **S3 — e2e cobre só o teclado e só `time-de-voce`**: **defer com gatilho** — o próximo item que mexer no funil de cards acrescenta o e2e de arrasto (pointer) e/ou do `time-do-estadual`; os três gestos compartilham `panCardPhotoTransform` e a política do modelo tem pins de unit/catálogo.
|
||||
- **S4 — renames `CardPhotoClampOptions`/`CardPhotoPosition`**: score 1, cosmético; **descartado**.
|
||||
- **S5 — trocar o `waitForTimeout(250)` do e2e por estabilidade de rAF**: score 1; o teste discrimina e passa (a espera pega a variante draw-free/write-back-bounded). **Descartado**.
|
||||
- **Fora do lote — flake unit do `municipalityRelationEditor.unit.spec.tsx` ("Salvando relações.")**: falhou 2× em 3 runs full sob carga e passa isolado; pré-existente, sem Issue específica aberta (as de flake abertas são e2e/int) e fora da superfície desta entrega. Registrado no resumo da sessão para o humano decidir virar bug à parte.
|
||||
|
||||
## Self-score decision-quality: 5/5
|
||||
|
||||
Decisões caras (onde vive a política, API do clamp, semântica do zoom, render/write-back, garantia S13/S14, testes e e2e) todas com Opções/Recomendação/Rejeitadas; cabe no appetite (~0,5 dia, sem migration); rabbit holes nomeados (S20, limites novos, controles, zoom, seam); depth check reusa o dono (`cardPhotoTransform`), o catálogo e o `renderTeamCard` sem abstração nova; o outcome da intenção permanece intacto — a engenharia só escolheu a forma.
|
||||
656
docs/plans/central-conteudos-cards-no-catalogo-ui-design.html
Normal file
656
docs/plans/central-conteudos-cards-no-catalogo-ui-design.html
Normal file
|
|
@ -0,0 +1,656 @@
|
|||
<!doctype html>
|
||||
<html lang="pt-BR" data-theme="campaign-site">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
|
||||
<title>Design — S38 · Cards misturados ao catálogo</title>
|
||||
<style type="text/tailwindcss">
|
||||
@theme {
|
||||
--font-sans: Arimo, Arial, sans-serif;
|
||||
}
|
||||
:root {
|
||||
--red: #a21c1c;
|
||||
--kit: #e4102f;
|
||||
--blue: #184e92;
|
||||
--yellow: #ffe607;
|
||||
--cream: #fff8f2;
|
||||
--muted: #6c615e;
|
||||
--line: rgb(0 0 0/0.12);
|
||||
--display: 'Exo 2', 'Arial Black', sans-serif;
|
||||
}
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.display {
|
||||
font-family: var(--display);
|
||||
}
|
||||
.board {
|
||||
background: #e7e3e0;
|
||||
background-image: radial-gradient(rgb(24 78 146/0.09) 0.7px, transparent 0.7px);
|
||||
background-size: 18px 18px;
|
||||
}
|
||||
.frame {
|
||||
box-shadow: 0 22px 60px rgb(39 25 22/0.13);
|
||||
}
|
||||
.desktop {
|
||||
width: 1280px;
|
||||
}
|
||||
.phone {
|
||||
width: 390px;
|
||||
border-radius: 28px;
|
||||
}
|
||||
.scene:after {
|
||||
content: '';
|
||||
height: 1px;
|
||||
flex: 1;
|
||||
background: #cfc9c5;
|
||||
}
|
||||
.field {
|
||||
min-height: 44px;
|
||||
border: 1px solid rgb(0 0 0/0.18);
|
||||
border-radius: 10px;
|
||||
background: #fff;
|
||||
padding: 10px 13px;
|
||||
font-size: 15px;
|
||||
}
|
||||
.chip {
|
||||
display: inline-flex;
|
||||
min-height: 36px;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 999px;
|
||||
background: #fff;
|
||||
padding: 6px 11px;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.active {
|
||||
border-color: rgb(24 78 146/0.35);
|
||||
background: #eef4fb;
|
||||
color: #184e92;
|
||||
}
|
||||
.card {
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 14px;
|
||||
background: #fff;
|
||||
box-shadow: 0 8px 24px rgb(71 19 14/0.07);
|
||||
}
|
||||
.tag {
|
||||
display: inline-flex;
|
||||
min-height: 23px;
|
||||
align-items: center;
|
||||
border-radius: 999px;
|
||||
background: #eef4fb;
|
||||
padding: 4px 8px;
|
||||
color: #184e92;
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
}
|
||||
.alias {
|
||||
display: inline-flex;
|
||||
border: 1px solid rgb(0 0 0/0.1);
|
||||
border-radius: 999px;
|
||||
background: #fff;
|
||||
padding: 3px 7px;
|
||||
color: #6c615e;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
min-height: 44px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 10px;
|
||||
border: 1.5px solid rgb(162 28 28/0.28);
|
||||
background: #fff;
|
||||
padding: 9px 13px;
|
||||
color: #a21c1c;
|
||||
font-size: 13px;
|
||||
font-weight: 800;
|
||||
}
|
||||
.art {
|
||||
position: relative;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
overflow: hidden;
|
||||
background: linear-gradient(145deg, #184e92, #0876ac);
|
||||
color: #fff;
|
||||
}
|
||||
.art:before {
|
||||
content: '1313';
|
||||
position: absolute;
|
||||
font-family: var(--display);
|
||||
font-size: 66px;
|
||||
font-weight: 900;
|
||||
color: rgb(255 255 255/0.08);
|
||||
transform: rotate(-8deg);
|
||||
}
|
||||
.art-red {
|
||||
background: linear-gradient(145deg, #e4102f, #a21c1c);
|
||||
}
|
||||
.art-light {
|
||||
background: linear-gradient(145deg, #eee9e5, #fff);
|
||||
}
|
||||
.piece-art {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: linear-gradient(135deg, #e5e2df, #f7f5f3);
|
||||
color: #6c615e;
|
||||
text-align: center;
|
||||
font-size: 10px;
|
||||
font-weight: 800;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body class="board min-h-screen text-black antialiased">
|
||||
<main class="mx-auto max-w-[1480px] space-y-14 px-4 py-12 md:px-8">
|
||||
<header class="max-w-3xl">
|
||||
<span class="rounded-full bg-[#e4102f] px-3 py-1 text-xs font-bold text-white"
|
||||
>S38 · revisão do gate</span
|
||||
>
|
||||
<h1 class="display mt-4 text-4xl font-black">Cards e peças vivem no mesmo board.</h1>
|
||||
<p class="mt-2 text-sm leading-6 text-[#6c615e]">
|
||||
Cada modelo é um item individual na ordem normal do catálogo. Não existe faixa, cabeçalho
|
||||
ou agrupamento próprio para cards.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<section>
|
||||
<div class="scene mb-3 flex items-center gap-3 text-xs font-bold text-[#6c615e]">
|
||||
<span>CENA 01</span>
|
||||
<h2>Board padrão · desktop 1280 · peças e modelos misturados</h2>
|
||||
</div>
|
||||
<div class="desktop frame mx-auto overflow-hidden rounded-xl bg-white">
|
||||
<header class="flex h-16 items-center justify-between bg-[#ae1603] px-10">
|
||||
<div class="h-9 w-44 rounded bg-white/20"></div>
|
||||
<b class="text-sm text-white">Central de Conteúdos</b>
|
||||
</header>
|
||||
<div class="mx-auto max-w-6xl px-10 py-10">
|
||||
<div class="rounded-xl bg-[#fff8f2] p-4">
|
||||
<div class="field text-[#6c615e]">Encontre uma peça por assunto, cidade ou tema…</div>
|
||||
<div class="mt-3 flex gap-2">
|
||||
<span class="chip">Tipo⌄</span><span class="chip">Cidade⌄</span
|
||||
><span class="chip">Região⌄</span><span class="chip">Tema⌄</span
|
||||
><span class="chip">Instituição⌄</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-8">
|
||||
<h2 class="display text-2xl font-black">Escolha, compartilhe e peça voto</h2>
|
||||
<p class="mt-1 text-sm text-[#6c615e]">
|
||||
Uma lista só: peças oficiais e convites para criar seu card.
|
||||
</p>
|
||||
</div>
|
||||
<div class="mt-5 grid grid-cols-3 gap-6">
|
||||
<article class="card">
|
||||
<div class="piece-art relative aspect-video">
|
||||
<span>NEEDS ASSET · POSTER REAL</span
|
||||
><span
|
||||
class="absolute grid size-12 place-items-center rounded-full bg-[#ffe607] text-xl text-black shadow"
|
||||
>▶</span
|
||||
>
|
||||
</div>
|
||||
<div class="p-4">
|
||||
<span class="tag">Vídeo</span>
|
||||
<h3 class="mt-2 font-extrabold">Título da peça publicada</h3>
|
||||
<p class="mt-1 text-xs text-[#6c615e]">Tema · Cidade</p>
|
||||
<div class="mt-4 grid grid-cols-2 gap-2">
|
||||
<span class="btn">Baixar</span><span class="btn">Compartilhar</span>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
<article class="card">
|
||||
<div class="art aspect-video">
|
||||
<b class="relative display text-2xl">#SOU ____</b>
|
||||
</div>
|
||||
<div class="p-4">
|
||||
<span class="tag">Card</span>
|
||||
<h3 class="mt-2 font-extrabold">Card com seu nome</h3>
|
||||
<p class="mt-1 text-xs leading-5 text-[#6c615e]">
|
||||
Coloque seu nome no card oficial.
|
||||
</p>
|
||||
<div class="mt-2 flex gap-1"><span class="alias">nome</span></div>
|
||||
<a class="btn mt-4 w-full">Escolher este modelo →</a>
|
||||
</div>
|
||||
</article>
|
||||
<article class="card">
|
||||
<div class="piece-art aspect-video">NEEDS ASSET · FOTO REAL</div>
|
||||
<div class="p-4">
|
||||
<span class="tag">Foto</span>
|
||||
<h3 class="mt-2 font-extrabold">Outra peça publicada</h3>
|
||||
<p class="mt-1 text-xs text-[#6c615e]">Tema da peça</p>
|
||||
<div class="mt-4 grid grid-cols-2 gap-2">
|
||||
<span class="btn">Baixar</span><span class="btn">Compartilhar</span>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
<article class="card">
|
||||
<div class="art aspect-video">
|
||||
<div class="relative text-center">
|
||||
<b class="display block bg-[#e4102f] px-4 py-1 text-lg text-[#ffeb00]"
|
||||
>TIME DE</b
|
||||
><b class="display mt-1 block bg-[#0061a5] px-4 py-1 text-2xl">VOCÊ</b>
|
||||
</div>
|
||||
<span class="absolute right-2 bottom-2 text-[9px] font-black"
|
||||
>PLACEHOLDER · ARTE EXISTENTE</span
|
||||
>
|
||||
</div>
|
||||
<div class="p-4">
|
||||
<span class="tag">Card</span>
|
||||
<h3 class="mt-2 font-extrabold">Time de você</h3>
|
||||
<p class="mt-1 text-xs text-[#6c615e]">Entre para o time com sua foto.</p>
|
||||
<div class="mt-2 flex gap-1"><span class="alias">santinho</span></div>
|
||||
<a class="btn mt-4 w-full">Escolher este modelo →</a>
|
||||
</div>
|
||||
</article>
|
||||
<article class="card">
|
||||
<div class="piece-art relative aspect-video">
|
||||
<span>NEEDS ASSET · CAPA REAL</span
|
||||
><span
|
||||
class="absolute grid size-12 place-items-center rounded-full bg-[#ffe607] text-xl text-black shadow"
|
||||
>▶</span
|
||||
>
|
||||
</div>
|
||||
<div class="p-4">
|
||||
<span class="tag">Áudio</span>
|
||||
<h3 class="mt-2 font-extrabold">Mensagem para compartilhar</h3>
|
||||
<p class="mt-1 text-xs text-[#6c615e]">Campanha</p>
|
||||
<div class="mt-4 grid grid-cols-2 gap-2">
|
||||
<span class="btn">Baixar</span><span class="btn">Compartilhar</span>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
<article class="card border-2 border-[#e4102f]">
|
||||
<div class="art art-red aspect-video">
|
||||
<span
|
||||
class="absolute top-2 right-2 rounded-full bg-white px-2 py-1 text-[9px] font-black text-[#184e92]"
|
||||
>NOVO</span
|
||||
><b class="relative display text-xl text-[#ffeb00]">MINHA COLINHA</b
|
||||
><span class="absolute right-2 bottom-2 text-[9px] font-black"
|
||||
>PLACEHOLDER · ARTE EXISTENTE</span
|
||||
>
|
||||
</div>
|
||||
<div class="p-4">
|
||||
<span class="tag">Card</span>
|
||||
<h3 class="mt-2 font-extrabold">Minha colinha</h3>
|
||||
<p class="mt-1 text-xs text-[#6c615e]">Monte sua cola de votação.</p>
|
||||
<div class="mt-2 flex gap-1">
|
||||
<span class="alias">santinho</span><span class="alias">colinha</span>
|
||||
</div>
|
||||
<a class="btn mt-4 w-full">Escolher este modelo →</a>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
<div
|
||||
class="mt-7 rounded-xl border border-[#184e92]/20 bg-[#eef4fb] p-4 text-sm leading-6 text-[#184e92]"
|
||||
>
|
||||
<b>Regra do gate:</b> a ordem acima mistura itens por relevância/ordem do catálogo.
|
||||
“Card” é apenas o tipo do item — nunca um cabeçalho ou uma seção dentro do board.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<div class="scene mb-3 flex items-center gap-3 text-xs font-bold text-[#6c615e]">
|
||||
<span>CENA 02</span>
|
||||
<h2>Mobile 390 · board misto e Tipo “Card” ativo</h2>
|
||||
</div>
|
||||
<div class="flex flex-wrap justify-center gap-8">
|
||||
<div class="phone frame min-h-[960px] overflow-hidden bg-white">
|
||||
<header class="flex h-14 items-center justify-between bg-[#ae1603] px-4">
|
||||
<div class="h-7 w-32 rounded bg-white/20"></div>
|
||||
<span class="text-white">☰</span>
|
||||
</header>
|
||||
<div class="p-4">
|
||||
<div class="field text-sm text-[#6c615e]">Busque uma peça ou card…</div>
|
||||
<div class="mt-3 flex gap-2 overflow-hidden">
|
||||
<span class="chip shrink-0">Tipo⌄</span><span class="chip shrink-0">Cidade⌄</span
|
||||
><span class="chip shrink-0">Tema⌄</span>
|
||||
</div>
|
||||
<h2 class="display mt-6 text-2xl font-black">Escolha, compartilhe e peça voto</h2>
|
||||
<div class="mt-4 space-y-4">
|
||||
<article class="card grid grid-cols-[128px_1fr]">
|
||||
<div class="piece-art min-h-40">NEEDS ASSET<br />POSTER REAL</div>
|
||||
<div class="p-4">
|
||||
<span class="tag">Vídeo</span>
|
||||
<h3 class="mt-2 text-sm font-extrabold">Título da peça publicada</h3>
|
||||
<a class="mt-3 block text-xs font-bold text-[#a21c1c]">Ver peça →</a>
|
||||
</div>
|
||||
</article>
|
||||
<article class="card grid grid-cols-[128px_1fr]">
|
||||
<div class="art min-h-40"><b class="relative display text-xl">#SOU</b></div>
|
||||
<div class="p-4">
|
||||
<span class="tag">Card</span>
|
||||
<h3 class="mt-2 text-sm font-extrabold">Card com seu nome</h3>
|
||||
<span class="alias mt-2">nome</span
|
||||
><a class="mt-3 block text-xs font-bold text-[#a21c1c]">Escolher →</a>
|
||||
</div>
|
||||
</article>
|
||||
<article class="card grid grid-cols-[128px_1fr]">
|
||||
<div class="piece-art min-h-40">NEEDS ASSET<br />FOTO REAL</div>
|
||||
<div class="p-4">
|
||||
<span class="tag">Foto</span>
|
||||
<h3 class="mt-2 text-sm font-extrabold">Outra peça publicada</h3>
|
||||
<a class="mt-3 block text-xs font-bold text-[#a21c1c]">Ver peça →</a>
|
||||
</div>
|
||||
</article>
|
||||
<article class="card grid grid-cols-[128px_1fr]">
|
||||
<div class="art art-red min-h-40">
|
||||
<b class="relative display text-center text-lg text-[#ffeb00]"
|
||||
>MINHA<br />COLINHA</b
|
||||
>
|
||||
</div>
|
||||
<div class="p-4">
|
||||
<span class="tag">Card · NOVO</span>
|
||||
<h3 class="mt-2 text-sm font-extrabold">Minha colinha</h3>
|
||||
<div class="mt-2 flex gap-1">
|
||||
<span class="alias">santinho</span><span class="alias">colinha</span>
|
||||
</div>
|
||||
<a class="mt-3 block text-xs font-bold text-[#a21c1c]">Escolher →</a>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
<p class="mt-5 text-center text-[11px] leading-4 text-[#6c615e]">
|
||||
Sem divisor “Cards”. A alternância peça → card → peça é intencional.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="phone frame min-h-[960px] overflow-hidden bg-white">
|
||||
<header class="flex h-14 items-center justify-between bg-[#ae1603] px-4">
|
||||
<div class="h-7 w-32 rounded bg-white/20"></div>
|
||||
<span class="text-white">☰</span>
|
||||
</header>
|
||||
<div class="p-4">
|
||||
<div class="field text-sm text-[#6c615e]">Busque um card…</div>
|
||||
<div class="mt-3 flex gap-2 overflow-hidden">
|
||||
<span class="chip active shrink-0">Tipo · Card ×</span
|
||||
><span class="chip shrink-0">Tema⌄</span>
|
||||
</div>
|
||||
<h2 class="display mt-6 text-2xl font-black">Escolha, compartilhe e peça voto</h2>
|
||||
<p class="mt-1 text-xs text-[#6c615e]">6 itens com o filtro aplicado.</p>
|
||||
<div class="mt-4 space-y-3">
|
||||
<article class="card grid grid-cols-[96px_1fr]">
|
||||
<div class="art min-h-28"><b class="relative display">#SOU</b></div>
|
||||
<div class="p-3">
|
||||
<span class="tag">Card</span>
|
||||
<h3 class="mt-1 text-sm font-extrabold">Card com seu nome</h3>
|
||||
<span class="alias mt-1">nome</span>
|
||||
</div>
|
||||
</article>
|
||||
<article class="card grid grid-cols-[96px_1fr]">
|
||||
<div class="art art-light min-h-28">
|
||||
<span class="relative text-2xl text-[#a21c1c]">◎</span>
|
||||
</div>
|
||||
<div class="p-3">
|
||||
<span class="tag">Card</span>
|
||||
<h3 class="mt-1 text-sm font-extrabold">Moldura quadrada</h3>
|
||||
<span class="alias mt-1">foto de perfil</span>
|
||||
</div>
|
||||
</article>
|
||||
<article class="card grid grid-cols-[96px_1fr]">
|
||||
<div class="art art-light min-h-28">
|
||||
<span class="relative text-2xl text-[#a21c1c]">▯</span>
|
||||
</div>
|
||||
<div class="p-3">
|
||||
<span class="tag">Card</span>
|
||||
<h3 class="mt-1 text-sm font-extrabold">Moldura vertical</h3>
|
||||
<span class="alias mt-1">foto de perfil</span>
|
||||
</div>
|
||||
</article>
|
||||
<article class="card grid grid-cols-[96px_1fr]">
|
||||
<div class="art min-h-28">
|
||||
<b class="relative display text-center text-xs">TIME DE<br />VOCÊ</b>
|
||||
</div>
|
||||
<div class="p-3">
|
||||
<span class="tag">Card</span>
|
||||
<h3 class="mt-1 text-sm font-extrabold">Time de você</h3>
|
||||
<span class="alias mt-1">santinho</span>
|
||||
</div>
|
||||
</article>
|
||||
<article class="card grid grid-cols-[96px_1fr]">
|
||||
<div class="art art-red min-h-28">
|
||||
<b class="relative display text-center text-xs text-[#ffeb00]"
|
||||
>TIME DO<br />ESTADUAL</b
|
||||
>
|
||||
</div>
|
||||
<div class="p-3">
|
||||
<span class="tag">Card</span>
|
||||
<h3 class="mt-1 text-sm font-extrabold">Time do estadual</h3>
|
||||
<span class="alias mt-1">estadual</span>
|
||||
</div>
|
||||
</article>
|
||||
<article class="card grid grid-cols-[96px_1fr] border-2 border-[#e4102f]">
|
||||
<div class="art art-red min-h-28">
|
||||
<b class="relative display text-center text-xs text-[#ffeb00]"
|
||||
>MINHA<br />COLINHA</b
|
||||
>
|
||||
</div>
|
||||
<div class="p-3">
|
||||
<span class="tag">Card · NOVO</span>
|
||||
<h3 class="mt-1 text-sm font-extrabold">Minha colinha</h3>
|
||||
<div class="mt-1 flex gap-1">
|
||||
<span class="alias">santinho</span><span class="alias">colinha</span>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<div class="scene mb-3 flex items-center gap-3 text-xs font-bold text-[#6c615e]">
|
||||
<span>CENA 03</span>
|
||||
<h2>Tipo “Card” ativo · os 6 modelos, sem cabeçalho próprio</h2>
|
||||
</div>
|
||||
<div class="desktop frame mx-auto overflow-hidden rounded-xl bg-white">
|
||||
<header class="flex h-16 items-center justify-between bg-[#ae1603] px-10">
|
||||
<div class="h-9 w-44 rounded bg-white/20"></div>
|
||||
<b class="text-sm text-white">Central de Conteúdos</b>
|
||||
</header>
|
||||
<div class="mx-auto max-w-6xl px-10 py-10">
|
||||
<div class="rounded-xl bg-[#fff8f2] p-4">
|
||||
<div class="field text-[#6c615e]">Encontre uma peça por assunto, cidade ou tema…</div>
|
||||
<div class="mt-3 flex gap-2">
|
||||
<span class="chip active">Tipo · Card ×</span><span class="chip">Cidade⌄</span
|
||||
><span class="chip">Região⌄</span><span class="chip">Tema⌄</span
|
||||
><span class="chip">Instituição⌄</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-8 flex items-end justify-between">
|
||||
<div>
|
||||
<h2 class="display text-2xl font-black">Escolha, compartilhe e peça voto</h2>
|
||||
<p class="mt-1 text-sm text-[#6c615e]">Resultados do filtro aplicado.</p>
|
||||
</div>
|
||||
<span class="text-xs text-[#6c615e]">6 itens</span>
|
||||
</div>
|
||||
<div class="mt-5 grid grid-cols-3 gap-6">
|
||||
<article class="card">
|
||||
<div class="art aspect-video">
|
||||
<b class="relative display text-2xl">#SOU ____</b>
|
||||
</div>
|
||||
<div class="p-4">
|
||||
<span class="tag">Card</span>
|
||||
<h3 class="mt-2 font-extrabold">Card com seu nome</h3>
|
||||
<p class="mt-1 text-xs text-[#6c615e]">Coloque seu nome no card oficial.</p>
|
||||
<span class="alias mt-2">nome</span
|
||||
><a class="btn mt-4 w-full">Escolher este modelo →</a>
|
||||
</div>
|
||||
</article>
|
||||
<article class="card">
|
||||
<div class="art art-light aspect-video">
|
||||
<div
|
||||
class="relative grid size-20 place-items-center rounded-full border-2 border-dashed border-[#a21c1c]/40 text-3xl text-[#a21c1c]"
|
||||
>
|
||||
◎
|
||||
</div>
|
||||
</div>
|
||||
<div class="p-4">
|
||||
<span class="tag">Card</span>
|
||||
<h3 class="mt-2 font-extrabold">Moldura quadrada</h3>
|
||||
<p class="mt-1 text-xs text-[#6c615e]">Foto de perfil quadrada.</p>
|
||||
<span class="alias mt-2">foto de perfil</span
|
||||
><a class="btn mt-4 w-full">Escolher este modelo →</a>
|
||||
</div>
|
||||
</article>
|
||||
<article class="card">
|
||||
<div class="art art-light aspect-video">
|
||||
<div
|
||||
class="relative grid h-24 w-16 place-items-center rounded-lg border-2 border-dashed border-[#a21c1c]/40 text-3xl text-[#a21c1c]"
|
||||
>
|
||||
◎
|
||||
</div>
|
||||
</div>
|
||||
<div class="p-4">
|
||||
<span class="tag">Card</span>
|
||||
<h3 class="mt-2 font-extrabold">Moldura vertical</h3>
|
||||
<p class="mt-1 text-xs text-[#6c615e]">Foto vertical para stories.</p>
|
||||
<span class="alias mt-2">foto de perfil</span
|
||||
><a class="btn mt-4 w-full">Escolher este modelo →</a>
|
||||
</div>
|
||||
</article>
|
||||
<article class="card">
|
||||
<div class="art aspect-video">
|
||||
<b class="relative display text-xl">TIME DE VOCÊ</b>
|
||||
</div>
|
||||
<div class="p-4">
|
||||
<span class="tag">Card</span>
|
||||
<h3 class="mt-2 font-extrabold">Time de você</h3>
|
||||
<p class="mt-1 text-xs text-[#6c615e]">Entre para o time com sua foto.</p>
|
||||
<span class="alias mt-2">santinho</span
|
||||
><a class="btn mt-4 w-full">Escolher este modelo →</a>
|
||||
</div>
|
||||
</article>
|
||||
<article class="card">
|
||||
<div class="art art-red aspect-video">
|
||||
<b class="relative display text-xl text-[#ffeb00]">TIME DO ESTADUAL</b>
|
||||
</div>
|
||||
<div class="p-4">
|
||||
<span class="tag">Card</span>
|
||||
<h3 class="mt-2 font-extrabold">Time do estadual</h3>
|
||||
<p class="mt-1 text-xs text-[#6c615e]">Escolha o estadual e personalize.</p>
|
||||
<span class="alias mt-2">estadual</span
|
||||
><a class="btn mt-4 w-full">Escolher este modelo →</a>
|
||||
</div>
|
||||
</article>
|
||||
<article class="card border-2 border-[#e4102f]">
|
||||
<div class="art art-red aspect-video">
|
||||
<span
|
||||
class="absolute top-2 right-2 rounded-full bg-white px-2 py-1 text-[9px] font-black text-[#184e92]"
|
||||
>NOVO</span
|
||||
><b class="relative display text-xl text-[#ffeb00]">MINHA COLINHA</b>
|
||||
</div>
|
||||
<div class="p-4">
|
||||
<span class="tag">Card</span>
|
||||
<h3 class="mt-2 font-extrabold">Minha colinha</h3>
|
||||
<p class="mt-1 text-xs text-[#6c615e]">Monte sua cola de votação.</p>
|
||||
<div class="mt-2 flex gap-1">
|
||||
<span class="alias">santinho</span><span class="alias">colinha</span>
|
||||
</div>
|
||||
<a class="btn mt-4 w-full">Escolher este modelo →</a>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<div class="scene mb-3 flex items-center gap-3 text-xs font-bold text-[#6c615e]">
|
||||
<span>CENAS 04–05</span>
|
||||
<h2>Busca por apelido · “santinho” e “foto de perfil”</h2>
|
||||
</div>
|
||||
<div class="grid gap-8 lg:grid-cols-2">
|
||||
<div class="frame rounded-xl bg-white p-7">
|
||||
<div class="field flex justify-between">
|
||||
<span>santinho</span><b class="text-[#6c615e]">×</b>
|
||||
</div>
|
||||
<div class="mt-3"><span class="chip active">Busca · “santinho” ×</span></div>
|
||||
<h3 class="display mt-7 text-xl font-black">2 itens encontrados</h3>
|
||||
<div class="mt-4 grid grid-cols-2 gap-4">
|
||||
<article class="card">
|
||||
<div class="art aspect-video">
|
||||
<b class="relative display text-xl">TIME DE VOCÊ</b>
|
||||
</div>
|
||||
<div class="p-4">
|
||||
<span class="tag">Card</span>
|
||||
<h4 class="mt-2 font-extrabold">Time de você</h4>
|
||||
<span class="alias mt-2">santinho</span>
|
||||
</div>
|
||||
</article>
|
||||
<article class="card">
|
||||
<div class="art art-red aspect-video">
|
||||
<b class="relative display text-xl text-[#ffeb00]">MINHA COLINHA</b>
|
||||
</div>
|
||||
<div class="p-4">
|
||||
<span class="tag">Card</span>
|
||||
<h4 class="mt-2 font-extrabold">Minha colinha</h4>
|
||||
<div class="mt-2 flex gap-1">
|
||||
<span class="alias">santinho</span><span class="alias">colinha</span>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
<div class="frame rounded-xl bg-white p-7">
|
||||
<div class="field flex justify-between">
|
||||
<span>foto de perfil</span><b class="text-[#6c615e]">×</b>
|
||||
</div>
|
||||
<div class="mt-3"><span class="chip active">Busca · “foto de perfil” ×</span></div>
|
||||
<h3 class="display mt-7 text-xl font-black">2 itens encontrados</h3>
|
||||
<div class="mt-4 grid grid-cols-2 gap-4">
|
||||
<article class="card">
|
||||
<div class="art art-light aspect-video">
|
||||
<div
|
||||
class="relative grid size-16 place-items-center rounded-full border-2 border-dashed border-[#a21c1c]/40 text-[#a21c1c]"
|
||||
>
|
||||
◎
|
||||
</div>
|
||||
</div>
|
||||
<div class="p-4">
|
||||
<span class="tag">Card</span>
|
||||
<h4 class="mt-2 font-extrabold">Moldura quadrada</h4>
|
||||
<span class="alias mt-2">foto de perfil</span>
|
||||
</div>
|
||||
</article>
|
||||
<article class="card">
|
||||
<div class="art art-light aspect-video">
|
||||
<div
|
||||
class="relative grid h-20 w-12 place-items-center rounded border-2 border-dashed border-[#a21c1c]/40 text-[#a21c1c]"
|
||||
>
|
||||
◎
|
||||
</div>
|
||||
</div>
|
||||
<div class="p-4">
|
||||
<span class="tag">Card</span>
|
||||
<h4 class="mt-2 font-extrabold">Moldura vertical</h4>
|
||||
<span class="alias mt-2">foto de perfil</span>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-7 grid gap-4 md:grid-cols-2">
|
||||
<div
|
||||
class="rounded-xl border border-[#184e92]/20 bg-[#eef4fb] p-4 text-sm leading-6 text-[#184e92]"
|
||||
>
|
||||
<b>Faceta geográfica ativa:</b> os seis modelos somem, pois não são territoriais. Uma
|
||||
peça publicada de tipo Card continua seguindo a regra normal das peças.
|
||||
</div>
|
||||
<div
|
||||
class="rounded-xl border border-dashed bg-white p-4 text-sm leading-6 text-[#6c615e]"
|
||||
>
|
||||
<b class="text-black">Sem convite duplicado:</b> o antigo tile “Card personalizado” foi
|
||||
removido. O estúdio segue acessível por cada modelo e pelo estado vazio já existente.
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
116
docs/plans/central-conteudos-cards-no-catalogo.md
Normal file
116
docs/plans/central-conteudos-cards-no-catalogo.md
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
# S38 — Central de Conteúdos — cards personalizáveis como itens do catálogo
|
||||
|
||||
Status: rascunho
|
||||
Atualizado em: 2026-09-23
|
||||
Issue: #1304
|
||||
Priority: P1
|
||||
Impeccable: B — encaixe no catálogo existente (novos itens + busca/filtros), sem rota nova
|
||||
Design UI: docs/plans/central-conteudos-cards-no-catalogo-ui-design.html
|
||||
Appetite: ~1–1,5 dia eng; um outcome verificável (cada card encontrável por nome, busca e filtro no catálogo)
|
||||
Responsável: —
|
||||
|
||||
## Intenção
|
||||
|
||||
Hoje os cards personalizáveis aparecem em `/conteudos` como **um único convite genérico** ("Faça seu card com Solla 1313"), que só é exibido quando nenhum filtro está ativo e não revela quais modelos existem. Quem procura um card pelo nome popular não acha nada, e quem não conhece a galeria nem sabe que há seis opções. O dono pediu literalmente: buscar **"santinho"** deve trazer os cards **"Time de você"** e **"colinha"**; buscar **"foto de perfil"** deve trazer os cards de foto de perfil. Cada modelo deve ser um item próprio do catálogo — **junto dos demais itens, sem seção separada** —, encontrável pelo próprio nome, por apelido e pelo filtro Tipo "Card", levando ao estúdio já com o modelo escolhido.
|
||||
|
||||
Isso revoga explicitamente a decisão D6 do S27 (`docs/plans/central-conteudos-publica-impl.md:81-85`), que rejeitou a entrada catalogada e fixou o tile único — o tile morre, substituído pelos itens individuais. Card continua **não sendo peça**: sem linha no banco, sem arquivo, sem publicação/kill switch próprio; o estúdio `/cards` segue o único lugar que gera o card, no aparelho do visitante.
|
||||
|
||||
## Persona e fluxo
|
||||
|
||||
- **Persona / contexto:** eleitor/simpatizante no celular, chegando por busca ou link do WhatsApp; conhece os cards pelos apelidos ("santinho", "foto de perfil", "colinha"), não pelos nomes oficiais dos modelos.
|
||||
- **Job principal:** achar o card que ele quer pelo nome que ele usa e cair no estúdio com o modelo já escolhido, sem varrer a galeria inteira.
|
||||
- **Fluxo desejado:** abre `/conteudos` → busca "santinho" (ou "foto de perfil") ou filtra Tipo "Card" → vê cada modelo como item próprio, com nome, explicação curta e arte → toca no item → chega em `/cards?model=<id>` com o modelo selecionado → faz e baixa o card no aparelho → o catálogo segue igual (nada do card fica lá).
|
||||
- **Anti-goals de produto:** não transforma card em peça (arquivo, publicação, kill switch); não cria rota, galeria ou segundo estúdio; não move a geração para o servidor/catálogo; não captura dado novo (a foto continua 100% no aparelho); não vira SEO de palavras-chave nem página própria por card.
|
||||
|
||||
### Esboço de fluxo (B)
|
||||
|
||||
```text
|
||||
[eleitor no celular] → /conteudos
|
||||
→ busca "santinho" · "foto de perfil" · "colinha" · "estadual" ou Tipo "Card"
|
||||
→ cada modelo de card aparece como item próprio, misturado às peças (sem seção separada)
|
||||
→ toca no item → /cards?model=<id> (modelo já escolhido no estúdio)
|
||||
→ faz/baixa o card no aparelho (nada do card fica no catálogo)
|
||||
→ volta ao catálogo: peças e cards juntos, sem convite duplicado
|
||||
[filtro geográfico ativo (Cidade/Região/Instituição)] → cards somem (não são territoriais)
|
||||
[sem JS] → a busca por querystring continua achando os itens do mesmo jeito
|
||||
```
|
||||
|
||||
### Design UI (B)
|
||||
|
||||
- Design UI (gate): `docs/plans/central-conteudos-cards-no-catalogo-ui-design.html` (+ assets em `central-conteudos-cards-no-catalogo-ui-design-assets/`) — itens de card **misturados ao board existente, sem seção/agrupamento próprio** (arte, nome, mini-descrição/apelido, caminho para o estúdio), o estado do filtro Tipo "Card" e o resultado das buscas por apelido. (Revisão do gate: a primeira versão agrupava os cards numa seção própria; o gate cortou a seção.)
|
||||
|
||||
## Objetivo e aceite
|
||||
|
||||
- Cada um dos 6 modelos é um item próprio do catálogo, **na mesma lista dos outros conteúdos, sem seção separada**, encontrável pelo nome do modelo e pelos apelidos: "santinho" traz "Time de você" e "Minha colinha"; "foto de perfil" traz "Moldura quadrada" e "Moldura vertical"; "colinha" traz "Minha colinha"; "estadual" traz "Time do estadual".
|
||||
- O filtro Tipo "Card" traz os itens de card; a busca por termo e os filtros funcionam sem JS (querystring), como no catálogo atual.
|
||||
- Cada item leva ao estúdio com o modelo já escolhido (`/cards?model=<id>`); o estúdio segue alcançável pelo estado vazio.
|
||||
- Guardrail — card não é peça: sem linha no banco, sem mídia, sem publicação/kill switch próprio; o item é um convite ao estúdio, nunca um arquivo para baixar/compartilhar.
|
||||
- Guardrail — o tile único ("Card personalizado") deixa de existir; nada de convite duplicado.
|
||||
- Guardrail — **sem seção/agrupamento separado de cards**: eles aparecem misturados aos demais itens do catálogo, sob a mesma busca e os mesmos filtros; nenhum cabeçalho/faixa própria de cards.
|
||||
- Guardrail — cards não respondem a faceta geográfica (Cidade/Região/Instituição): com faceta ativa, somem do resultado (não são territoriais).
|
||||
- Guardrail — catálogo sem peça publicada mantém o estado honesto atual (com o caminho para o estúdio), sem inventar um board vazio de cards.
|
||||
- Guardrail — nada muda no estúdio: foto/recorte 100% no aparelho, sem PII e sem `Consent` novo; o clique no item pode alimentar o mecanismo anônimo do C213/S32 como abertura de card, nunca como peça.
|
||||
|
||||
## Dados (intenção)
|
||||
|
||||
- **Vou apresentar dados?** Não — o item não exibe número/contador; só roteia o visitante ao estúdio. A contagem de uso continua no mecanismo anônimo do C213/S32 (assunto card), sem métrica nova.
|
||||
- **Decisões desbloqueadas:** o eleitor escolhe o modelo sem varrer a galeria; a comunicação passa a poder ler quais modelos são procurados no catálogo, se a questão (c) for aceita (leitura pelo mecanismo existente).
|
||||
- **Forma:** _adiada ao plano de implementação_ — nenhuma tabela/gráfico; quando muito, o evento anônimo já existente.
|
||||
|
||||
## Dados da decisão (literais)
|
||||
|
||||
- Modelos (id → rótulo atual, fonte única `src/lib/cardModels.ts:65-135`): `eu-sou-solla` → "Card com seu nome"; `perfil-quadrado` → "Moldura quadrada"; `perfil-retangular` → "Moldura vertical"; `time-de-voce` → "Time de você"; `time-do-estadual` → "Time do estadual" (S30, escolha entre 53 estaduais); `minha-colinha` → "Minha colinha" (S31, selo `NOVO`, escolha de estadual).
|
||||
- Apelidos de busca por modelo (proposta verbatim): "santinho" → `time-de-voce` + `minha-colinha`; "foto de perfil" → `perfil-quadrado` + `perfil-retangular`; "colinha" → `minha-colinha`; "estadual" → `time-do-estadual`; o próprio nome de cada modelo sempre vale.
|
||||
- URL de destino: `/cards?model=<id>` — o estúdio já valida o id e pré-seleciona o modelo (`src/app/(frontend)/(home)/cards/page.tsx:20-27`).
|
||||
- Filtro de Tipo: valor existente `card`, rótulo `Card` (`src/lib/contentPiece.ts:24-34`); peça publicada de tipo card continua peça comum, com o comportamento atual.
|
||||
- Supersessão explícita: a decisão D6 do S27 (`docs/plans/central-conteudos-publica-impl.md:81-85`) fica revogada na parte do tile único; valem os itens individuais por modelo, sem peça catalogada e sem linha no banco.
|
||||
- Regra de apresentação (decisão do gate): os itens de card aparecem **junto dos demais itens da Central, sem seção separada** — não existe cabeçalho/faixa própria de cards.
|
||||
- Analytics (se a questão (c) for aceita): o clique no item conta pelo mecanismo único do C213/S32 como abertura de card — `subjectType: 'card'`, `subjectId = model.id` (`src/app/(frontend)/api/content-events/route.ts:95-114`) — nunca como peça; sem segundo analytics.
|
||||
|
||||
## Direção no codebase (hipótese)
|
||||
|
||||
- **Áreas prováveis:** `src/lib/cardModels.ts` (os 6 modelos/rótulos), `src/components/conteudos/` (`ContentPieceCatalog.tsx`, hoje `ContentPieceCardInvite.tsx`), `src/lib/contentPieceCatalog.ts` (itens/facetas/filtro/busca), `src/components/conteudos/ContentPieceFilters.tsx` e `src/app/(frontend)/conteudos/(catalog)/page.tsx` (o `showCardInvite` atual), o deep-link `src/app/(frontend)/(home)/cards/page.tsx` e, se (c) valer, `src/lib/contentEvents.ts` + `src/app/(frontend)/api/content-events/route.ts`.
|
||||
- **Precedente a olhar:** D6 no `central-conteudos-publica-impl.md:81-85` (o que este item revoga) e `ContentPieceCardInvite.tsx:16-44` (o tile que morre); S30/S31 (modelos/pickers) e S32 (`docs/changelog/2026-09-23-s32.md` — `subjectType: 'card'`, `subjectId = model.id`); S28 (facetas + busca por `searchText`).
|
||||
- **Risco de acoplamento:** itens sintéticos — nada de collection/migration/kill switch; a lista de modelos/labels é fonte única (não duplicar copy); a busca sem JS é contrato do catálogo; #1277 (`docs/plans/escala-dry-pos-s30.md`) mexe em `src/components/cards/` — sem conflito esperado com o catálogo público, mas serializar se rodar em paralelo.
|
||||
|
||||
## Dependências
|
||||
|
||||
- Nenhuma dura — catálogo (S27/S28) e os 6 modelos (S13–S16, S30, S31) já estão no repo.
|
||||
- **Suave:** C213/S32, se a questão (c) for aceita (reusa o mecanismo existente, sem nada novo).
|
||||
- Design UI aprovado no gate.
|
||||
|
||||
## Fora de escopo
|
||||
|
||||
- Card virar peça (linha, arquivo, publicação, kill switch) ou ganhar página/detalhe/OG próprios.
|
||||
- Rota nova, segunda galeria, alterar o estúdio `/cards` ou o funil de geração (foto/canvas seguem no aparelho).
|
||||
- Copy editável pelo CMS; busca semântica/tema aplicada a cards além do decidido; facetas próprias de card.
|
||||
- Analytics novo (o mecanismo é o do C213/S32).
|
||||
- Redesenho da Central/shell/nav; mudar a regra das peças publicadas (tipo card continua peça comum).
|
||||
|
||||
## Rabbit holes de produto
|
||||
|
||||
- **"Já que virou item, vira peça".** Se alguém "só completar": collection, migration, mídia, publicação e kill switch para cards — dono duplicado do catálogo. **Corte neste item:** item sintético, sem linha; o estúdio é o dono.
|
||||
- **"Baixar o card direto do catálogo".** Se alguém "só completar": geração no catálogo/servidor e a foto sai do aparelho. **Corte neste item:** o item só leva a `/cards`; o card nasce no aparelho.
|
||||
- **"Um SEO por card".** Se alguém "só completar": página, título e palavras-chave por modelo, virando segundo catálogo. **Corte neste item:** itens do board + apelidos decididos; sem rota nova.
|
||||
- **"Card com tema/cidade para combinar com os filtros".** Se alguém "só completar": metadados territoriais/editoriais por card, um segundo modelo de conteúdo. **Corte neste item:** cards fora das facetas geográficas; tema só se um dia declarado (v1: nenhum).
|
||||
- **"Contar quem fez o card".** Se alguém "só completar": identificar visitante para medir conversão do item. **Corte neste item:** só o evento anônimo existente, se (c) aceita.
|
||||
|
||||
## Questões em aberto (produto)
|
||||
|
||||
- **Como os cards se comportam sob faceta geográfica e temas?** **Opções:** A) ignoram facetas e ficam visíveis | B) excluídos quando faceta geográfica ativa | C) ganham temas próprios declarados. **Recomendação:** B — cards não são territoriais; tema só se declarado por modelo (v1 não declara). _(assumido — validar com produto)_
|
||||
- **O tile único "Card personalizado" fica como "ver todos os cards"?** **Opções:** A) fica como entrada geral | B) morre e é substituído pelos itens individuais, com o estúdio alcançável por cada item e pelo estado vazio. **Recomendação:** B — evita convite duplicado e é o pedido do operador. _(assumido — validar com produto)_
|
||||
- **O clique no item conta abertura de card ou de peça?** **Opções:** A) abertura de card (`subjectType: 'card'`, `subjectId = model`) pelo mecanismo do C213/S32 | B) abertura de peça | C) não conta. **Recomendação:** A — mede o interesse real no modelo sem duplicar como peça. _(assumido — validar com produto)_
|
||||
|
||||
## Referências
|
||||
|
||||
- GitHub Issue — a registrar (`pnpm agent:register`).
|
||||
- Design UI (gate): `docs/plans/central-conteudos-cards-no-catalogo-ui-design.html` (+ assets em `central-conteudos-cards-no-catalogo-ui-design-assets/`)
|
||||
- `docs/plans/central-conteudos-publica-impl.md:81-85` (D6 revogada) e `docs/plans/central-conteudos-publica.md` (S27 — o catálogo e o tile)
|
||||
- `src/components/conteudos/ContentPieceCardInvite.tsx:16-44`, `src/components/conteudos/ContentPieceCatalog.tsx:50-55`, `src/app/(frontend)/conteudos/(catalog)/page.tsx:108,153-157`
|
||||
- `src/lib/cardModels.ts:65-135`, `src/lib/contentPieceCatalog.ts:39-107,155-269,506-548`, `src/components/conteudos/ContentPieceFilters.tsx`
|
||||
- `src/app/(frontend)/api/content-events/route.ts:95-114`, `src/lib/contentEvents.ts`, `docs/changelog/2026-09-23-s32.md`
|
||||
- `docs/plans/escala-dry-pos-s30.md` (#1277 — sobreposição só em `components/cards/`)
|
||||
|
||||
## Self-score (shaping)
|
||||
|
||||
5/5 — (1) fatia = um outcome verificável (cada modelo encontrável por nome, apelido, busca e Tipo "Card"); (2) appetite ~1–1,5 dia cabe: itens sintéticos no board e nos filtros existentes, sem rota nem migration; (3) persona/job/aceite em linguagem de produto, com os apelidos literais do dono e o guardrail "card não é peça"; (4) direção no codebase é hipótese, com D6 e o tile atual abertos como pista; (5) zero decisão dura de engenharia — sem collection/schema/signature, com as três dúvidas de produto posicionadas.
|
||||
118
docs/plans/central-conteudos-header-logo-impl.md
Normal file
118
docs/plans/central-conteudos-header-logo-impl.md
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
# Impl: S36 — Central de Conteúdos — logo do header no tamanho da marca
|
||||
|
||||
Status: aprovado
|
||||
Atualizado em: 2026-09-24
|
||||
Issue: #1301
|
||||
Intenção: docs/plans/central-conteudos-header-logo.md
|
||||
Design UI (gate): docs/plans/central-conteudos-header-logo-ui-design.html
|
||||
Appetite restante: ~0,25–0,5 dia eng — correção de fidelidade visual no header, só componente + CSS, sem schema/migration.
|
||||
Modo: autônomo (`--auto`) — impl plan nasce aprovado pelo agente.
|
||||
|
||||
## Leitura da intenção
|
||||
|
||||
- **Outcome:** a marca no header da Central (`/conteudos`) lê, nos dois breakpoints, no mesmo peso visual do header público de referência (`/jingles`) — aferido lado a lado em staging.
|
||||
- **O que NÃO negociar:**
|
||||
- **Fonte única kit 1313:** `public/campaign-kit/`; nenhum lockup recriado, nenhuma cor ou tipografia inventada.
|
||||
- **Correção vive no header da Central:** escolha de ativo e/ou tamanho renderizado; sem redesenhar o header (`h-14 sm:h-16`, `bg-[#ae1603]` preservados).
|
||||
- **Badge "Central de Conteúdos", link "Voltar à Central" e comportamento nos dois breakpoints permanecem.**
|
||||
- **Nenhuma outra página pública muda** — `CampaignPageHeader` (`/jingles`) é referência intocada, sem drive-by.
|
||||
- **O que reavaliar (hipóteses do plano de intenção):**
|
||||
- "Opções A|B|C decididas no gate": o design hi-fi decidiu — **A RECOMENDADA** (lockup oficial com recorte técnico da moldura). B (marca completa negativa) comprime o slogan na barra; C (compensar tamanho sem recorte) estoura o header. O que resta para a engenharia é só **como** implementar o recorte técnico da opção A (D1).
|
||||
- "Recorte = preparo do ativo no kit": o design entrega o recorte como **CSS (`overflow-hidden` + offsets)** sobre o PNG oficial existente — não como PNG novo commitado. Nenhum binário novo no kit.
|
||||
|
||||
## Abordagem recomendada
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
KIT["kit 1313 (fonte única)\njorge-solla-negativo.png\n1037x595, visível 790x285"] --> OWNER["ContentPiecePageHeader.tsx\núnico dono (page-local)"]
|
||||
OWNER -- "A: wrapper trimmed-lockup\nCSS overflow-hidden + offsets" --> DESK["desktop: 188x50\nimg 246px, -29/-38"]
|
||||
OWNER --> MOB["mobile: 142x39\nimg 186px, -22/-29"]
|
||||
DESK --> S1["/conteudos (catálogo)\ncom/sem peças"]
|
||||
MOB --> S1
|
||||
DESK --> S2["/conteudos/<slug>"]
|
||||
MOB --> S2
|
||||
DESK --> S3["não-encontrado\n(not-found.tsx)"]
|
||||
MOB --> S3
|
||||
REF["CampaignPageHeader (/jingles)\nreferência ~46/52px\nNÃO TOCAR"] -. "peso-alvo lado a lado" .-> S1
|
||||
```
|
||||
|
||||
**Opções consideradas (abordagem geral):** A) lockup `jorge-solla-negativo.png` com recorte técnico via CSS no componente (wrapper `overflow-hidden` com as medidas do design); B) trocar pelo ativo `marca-negativa-completa.png` do kit; C) compensar tamanho renderizado do lockup atual (aumentar `h-7`/`sm:h-9` ou `transform: scale`) sem recorte.
|
||||
**Recomendação:** **A** — é a opção recomendada do design aprovado (cenas 01/02/03), preserva a assinatura horizontal do S27, atinge ~46 px de tinta visível no peso da referência e cabe no appetite sem binário novo nem redesign.
|
||||
**Rejeitadas:** **B** porque a marca completa (nome + 1313 + slogan) comprime o slogan na barra de 64/56 px e compete verticalmente com o nome da seção — o próprio design registra a perda de leitura; **C** porque escala a moldura transparente junto: ou continua pequeno, ou estoura o `h-14`/`sm:h-16` (redesign vedado), ou distorce o lockup.
|
||||
|
||||
### D1 — Como implementar o recorte técnico da opção A (decisão central, cara de reverter)
|
||||
|
||||
**Opções:** A) CSS `overflow-hidden` com offsets no componente (wrapper `div.trimmed-lockup` 188×50 desktop / 142×39 mobile, `img` absoluta 246 px offset −29/−38 desktop e 186 px offset −22/−29 mobile, header `h-14 sm:h-16` preservado); B) asset recortado commitado no kit (novo PNG trimmed em `public/campaign-kit/` + atualização do `README.md`); C) `next/image` `fill`/`sizes` ou scale-up do lockup atual sem wrapper de recorte.
|
||||
|
||||
**Recomendação:** **A** — port fiel do design aprovado (`central-conteudos-header-logo-ui-design.html:52-73`): o mesmo PNG oficial, nenhuma segunda fonte de marca, nenhum binário novo, reversão trivial (só o componente + CSS voltam). Os offsets derivam do recorte visível medido (transparência topo 162, base 148, esquerda 123, direita 124 sobre canvas 1037×595) — documentar a derivação em comentário no componente para o próximo leitor não "recalibrar no olho".
|
||||
|
||||
**Rejeitadas:** **B** porque cria uma segunda fonte de verdade da marca fora do kit oficial: exige versionar binário + `README.md`, deriva silenciosamente a cada troca de PNG no kit e a reversão espalha (deletar asset + reeditar componente + docs). Gatilho de retorno: se o PNG oficial do kit mudar de canvas/moldura e os offsets CSS perderem a âncora, aí sim gerar o trimmed como build/preparo versionado — não agora. **C** porque `fill` sem janela de recorte replica o problema atual (a caixa continua medindo a moldura, não a tinta), e scale-up puro estoura a barra ou corta sem controle horizontal/vertical; `object-fit` sozinho não ancora o recorte 790×285 dentro de 1037×595.
|
||||
|
||||
### Componentes / mudanças
|
||||
|
||||
- **`src/components/conteudos/ContentPiecePageHeader.tsx`** (editar, `:11-22` — único dono): trocar o `Image` direto (`h-7 sm:h-9`) pelo wrapper de recorte da opção A com as duas medidas do design (desktop + `mobile`), mantendo `Link href="/"`, `aria-label`, `alt="Jorge Solla"`, `priority`, `CONTENT_PIECE_FOCUS`, badge e `backHref`/`Voltar à Central` byte a byte. Sem extrair componente compartilhado — o header é page-local (precedente `JinglePageHeader`, molde do S27).
|
||||
- **CSS do recorte:** classes co-localizadas no componente (Tailwind arbitrário ou módulo local — sem stylesheet global novo, sem classe genérica em shell do site). Valores literais do design: `188x50 / img 246px / -29/-38` desktop, `142x39 / img 186px / -22/-29` mobile. Comentário curto com a derivação (canvas 1037×595 → visível 790×285).
|
||||
- **Consumidores intocados:** `src/app/(frontend)/conteudos/(catalog)/page.tsx:99,112`, `src/app/(frontend)/conteudos/[slug]/page.tsx:82`, `src/app/(frontend)/conteudos/[slug]/not-found.tsx:16` — todas usam `ContentPiecePageHeader`; nenhuma muda.
|
||||
- **Referência intocada:** `src/components/CampaignPageHeader.tsx:20-27` — não alterar (é o peso-alvo, não o paciente).
|
||||
- **Kit intocado:** nenhum PNG novo em `public/campaign-kit/`; `public/campaign-kit/README.md` intocado; `marca-negativa-completa.png` segue só nos cards (`src/lib/cardModels.ts:141`, `src/lib/cardRender.ts:359`) — não tocar.
|
||||
- **Migration:** **sem migration** — só componente + CSS; nenhum campo/collection novo.
|
||||
- **Access / Consent:** nenhum access novo, nenhum `Consent`, nenhuma PII — header público estático; Local API/bypass e multi-collection não se aplicam (sem leitura/escrita de dados).
|
||||
- **UI:** Impeccable B — port fiel das cenas 01 (desktop A), 02 (mobile A) e 03 (peça + Voltar) do artefato aprovado; header, badge, copy e CTA preservados.
|
||||
- **Changelog + impl plan no commit:** `docs/changelog/2026-09-24-s36.md` (uma entrada curta; nunca editar o agregado/HISTORY) e este arquivo `docs/plans/central-conteudos-header-logo-impl.md` no mesmo commit.
|
||||
|
||||
### Dados → forma (se aplicável)
|
||||
|
||||
N/A — a superfície não apresenta KPI, agregado, contador ou série (a intenção declara correção de fidelidade visual; nenhum ator decide com número). Nada a modelar.
|
||||
|
||||
## Fases verificáveis
|
||||
|
||||
1. **Tracer / markup do recorte — quota ~40%:** editar `ContentPiecePageHeader` com o wrapper A (desktop + mobile); `pnpm dev` local; conferir `/conteudos`, `/conteudos/<slug>` e não-encontrado nos dois breakpoints antes de seguir. Critério: marca visível ~46 px desktop no peso da referência, header `h-14 sm:h-16` intacto, badge/Voltar inalterados.
|
||||
2. **UI (port fiel + lado a lado) — quota ~40%:** confronto lado a lado com `/jingles` (referência) em staging nos dois breakpoints; checar cena 03 (peça + "Voltar à Central"), foco visível (`CONTENT_PIECE_FOCUS` não cortado pelo `overflow-hidden`), `alt`/contraste, retina. Sem spec de header novo — cobertura via e2e/visual de staging (achado do explorador).
|
||||
3. **Gates — quota ~20%:** `pnpm gate:fast` (lint/format/typecheck/knip/cycles/unit) verde; `pnpm push` → PR `--base main`. Sem int novo (sem dados); sem manifest novo (superfícies já cobertas pelo `frontendConteudos` curado; mudança CSS-only não alarga blast radius).
|
||||
|
||||
## Testes previstos
|
||||
|
||||
- **Sem unit/int novos** — sem lógica de domínio, sem leitura/escrita, sem querystring nova; nada puro para pinar.
|
||||
- **Visual/e2e em staging (verificação viva):** `/conteudos` (catálogo com/sem peças), `/conteudos/<slug>`, não-encontrado — marca no peso da referência nos dois breakpoints, lado a lado com `/jingles`; badge e "Voltar à Central" presentes e clicáveis.
|
||||
- **Pins intocados:** `tests/unit/e2eAffectedManifest.unit.spec.ts` (sem entrada nova — CSS-only no dono já mapeado), `tests/unit/codebaseConventions.unit.spec.ts`, `src/lib/shareLink.ts`, `scripts/lib/campaignKitAssets.mjs` — todos intocados.
|
||||
|
||||
## Rabbit holes / Não escopo (engenharia)
|
||||
|
||||
- **Generalizar os headers públicos** ("padronizo `CampaignPageHeader` junto") — vira refactor de todas as páginas públicas e revisão de marca. Corte: só `ContentPiecePageHeader`.
|
||||
- **Criar lockup novo / PNG recortado no Figma ou no kit** — nasce marca paralela fora da fonte única. Corte: kit como fonte única; no máximo o recorte CSS do ativo oficial.
|
||||
- **`next.config` remote ou loader de imagem novo** — o ativo é local do kit; nada de infra de imagem.
|
||||
- **`scripts/lib/campaignKitAssets.mjs`** — tooling do kit, fora do escopo desta correção visual.
|
||||
- **Ajustar altura/espaçamento/badge do header para "caber" a marca** — redesign vedado; a menor mudança que faça a marca ler no peso certo.
|
||||
- **Mexer em copy, badge, CTA, "Voltar à Central", rotas, dados ou consentimento** — fora de escopo explícito.
|
||||
|
||||
## Riscos e mitigação
|
||||
|
||||
- **Offsets frágeis a troca do PNG no kit:** o CSS ancora no canvas atual (1037×595 → visível 790×285); se o kit republicar o PNG, o recorte desalinha. Mitigação: comentário no componente com a derivação + gatilho registrado para a opção B (asset trimmed versionado).
|
||||
- **Anel de foco cortado pelo `overflow-hidden`:** o wrapper pode clipar o `CONTENT_PIECE_FOCUS`. Mitigação: foco no `Link` externo ao wrapper (estrutura atual já permite), conferir por teclado nos dois breakpoints.
|
||||
- **`next/image` vs `img` do artefato:** o design usa `img` absoluta; o componente usa `next/image` (width/height literais). Mitigação: manter `next/image` com os mesmos `width`/`height` do canvas e aplicar largura/offset via classe — sem trocar de primitiva de imagem neste item.
|
||||
- **Retina/downscale do lockup ampliado:** ampliar a janela pode expor serrilhado. Mitigação: PNG fonte tem 1037 px de largura para janela de 246 px — sobra de resolução; conferir em tela real no gate visual.
|
||||
- **Regressão em `/jingles`/home/`/cards`:** correção page-local, mas o olho valida. Mitigação: lado a lado em staging confirma peso igual **sem** nenhuma diff fora de `/conteudos`.
|
||||
|
||||
## Aceite de engenharia
|
||||
|
||||
- [ ] Aceite de produto da intenção coberto: marca no header da Central lê nos dois breakpoints no mesmo peso visual de `/jingles` (aferido lado a lado em staging); fonte única kit 1313; correção só no header da Central; badge, "Voltar à Central" e comportamento preservados; nenhuma outra página pública muda.
|
||||
- [ ] Guardrails: sem migration, sem access/Consent/PII novo, sem escrita multi-collection; `CampaignPageHeader` e `marca-negativa-completa` nos cards intocados; nenhum binário novo no kit.
|
||||
- [ ] Invariantes AGENTS/engineering-standards: dono único editado (`ContentPiecePageHeader`, sem twin/compartilhado novo); identificadores em inglês, copy pt-BR preservada; migrations existentes intocadas.
|
||||
- [ ] Testes previstos executados: visual lado a lado em staging nas três superfícies × dois breakpoints; `pnpm gate:fast` verde; `pnpm push` via GitHub.
|
||||
- [ ] `docs/changelog/2026-09-24-s36.md` + este impl plan no mesmo commit.
|
||||
|
||||
## Decisões de engenharia
|
||||
|
||||
- **D1 — Recorte técnico da opção A:** CSS `overflow-hidden` com offsets no componente (188×50/img 246/−29/−38 desktop, 142×39/img 186/−22/−29 mobile) sobre o PNG oficial existente. Rejeitadas: asset recortado no kit (segunda fonte de marca, reversão espalhada; gatilho se o canvas oficial mudar) e `next/image fill`/scale-up sem janela (replica o problema ou estoura o header).
|
||||
- **Sem migration, sem Consent, sem access novo, sem binário novo** — registrado, não presumido.
|
||||
|
||||
## Self-score (decision-quality)
|
||||
|
||||
**Self-score decision-quality: 5/5.**
|
||||
|
||||
1. Decisão cara com Opções/Recomendação/Rejeitadas? 5/5 — D1 (CSS overflow-hidden vs asset recortado vs fill/scale-up) decide o único ponto caro de reverter, com recomendação e rejeitadas explícitas + gatilho de retorno.
|
||||
2. Cabe no appetite? 5/5 — ~0,25–0,5 dia: um componente + CSS co-localizado, sem schema/migration/binário/testes novos.
|
||||
3. Rabbit holes Teqo nomeados? 5/5 — generalizar headers, lockup novo, `next.config` remote, `campaignKitAssets.mjs`, redesign da barra, copy/badge/CTA/dados — todos com corte.
|
||||
4. Depth check (reusar o módulo profundo)? 5/5 — edita o dono único `ContentPiecePageHeader`, reusa o PNG oficial e as medidas do design aprovado; nenhum pass-through raso, nenhum compartilhado novo, referência e kit intactos.
|
||||
5. Outcome preservado + tracer cedo? 5/5 — outcome lado a lado em staging guia a fase 1; badge/Voltar/breakpoints e "nenhuma outra página muda" mapeados no aceite; fases vão do markup ao gate visual sem presumir dados.
|
||||
Média: 5/5 — ≥4/5.
|
||||
252
docs/plans/central-conteudos-header-logo-ui-design.html
Normal file
252
docs/plans/central-conteudos-header-logo-ui-design.html
Normal file
|
|
@ -0,0 +1,252 @@
|
|||
<!doctype html>
|
||||
<html lang="pt-BR" data-theme="campaign-site">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
|
||||
<title>Design — S36 · Marca no header da Central</title>
|
||||
<style type="text/tailwindcss">
|
||||
@theme {
|
||||
--font-sans: Arimo, Arial, sans-serif;
|
||||
}
|
||||
:root {
|
||||
--red: #ae1603;
|
||||
--kit-red: #e4102f;
|
||||
--blue: #184e92;
|
||||
--yellow: #ffeb00;
|
||||
--cream: #fff8f2;
|
||||
--muted: #6c615e;
|
||||
--line: rgb(0 0 0/0.12);
|
||||
--display: 'Exo 2', 'Arial Black', sans-serif;
|
||||
}
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
body {
|
||||
font-family: Arimo, Arial, sans-serif;
|
||||
}
|
||||
.display {
|
||||
font-family: var(--display);
|
||||
}
|
||||
.board {
|
||||
background: #e7e3e0;
|
||||
background-image: radial-gradient(rgb(24 78 146/0.09) 0.7px, transparent 0.7px);
|
||||
background-size: 18px 18px;
|
||||
}
|
||||
.frame {
|
||||
box-shadow: 0 22px 60px rgb(39 25 22/0.13);
|
||||
}
|
||||
.desktop {
|
||||
width: 1280px;
|
||||
}
|
||||
.phone {
|
||||
width: 390px;
|
||||
border-radius: 28px;
|
||||
}
|
||||
.scene:after {
|
||||
content: '';
|
||||
height: 1px;
|
||||
flex: 1;
|
||||
background: #cfc9c5;
|
||||
}
|
||||
.trimmed-lockup {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
width: 188px;
|
||||
height: 50px;
|
||||
}
|
||||
.trimmed-lockup img {
|
||||
position: absolute;
|
||||
width: 246px;
|
||||
max-width: none;
|
||||
left: -29px;
|
||||
top: -38px;
|
||||
}
|
||||
.trimmed-lockup.mobile {
|
||||
width: 142px;
|
||||
height: 39px;
|
||||
}
|
||||
.trimmed-lockup.mobile img {
|
||||
width: 186px;
|
||||
left: -22px;
|
||||
top: -29px;
|
||||
}
|
||||
.option {
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 14px;
|
||||
background: white;
|
||||
overflow: hidden;
|
||||
}
|
||||
.recommended {
|
||||
border: 2px solid var(--kit-red);
|
||||
box-shadow: 0 10px 26px rgb(228 16 47/0.13);
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body class="board min-h-screen text-black antialiased">
|
||||
<main class="mx-auto max-w-[1480px] space-y-14 px-4 py-12 md:px-8">
|
||||
<header class="max-w-3xl">
|
||||
<span class="rounded-full bg-[#e4102f] px-3 py-1 text-xs font-bold text-white"
|
||||
>S36 · decisão visual</span
|
||||
>
|
||||
<h1 class="display mt-4 text-4xl font-black">A marca volta a assinar a Central.</h1>
|
||||
<p class="mt-2 text-sm leading-6 text-[#6c615e]">
|
||||
Mesmo header, mesma altura e mesma copy. O gate escolhe somente o ativo e seu peso visual.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<section>
|
||||
<div class="scene mb-3 flex items-center gap-3 text-xs font-bold text-[#6c615e]">
|
||||
<span>CENA 01</span>
|
||||
<h2>Desktop 1280 · opções A e B lado a lado</h2>
|
||||
</div>
|
||||
<div class="desktop frame mx-auto overflow-hidden rounded-xl bg-[#f9faff] p-8">
|
||||
<div class="grid grid-cols-2 gap-6">
|
||||
<article class="option recommended">
|
||||
<div class="flex items-center justify-between bg-[#ae1603] px-8 h-16">
|
||||
<div class="trimmed-lockup" aria-label="Jorge Solla">
|
||||
<img src="../../public/campaign-kit/jorge-solla-negativo.png" alt="Jorge Solla" />
|
||||
</div>
|
||||
<span class="text-sm font-bold text-white">Central de Conteúdos</span>
|
||||
</div>
|
||||
<div class="p-5">
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<h3 class="font-extrabold">A · Lockup oficial com recorte técnico</h3>
|
||||
<span
|
||||
class="rounded-full bg-[#e4102f] px-2.5 py-1 text-[11px] font-black text-white"
|
||||
>RECOMENDADA</span
|
||||
>
|
||||
</div>
|
||||
<p class="mt-2 text-sm leading-6 text-[#6c615e]">
|
||||
Preserva a assinatura horizontal desenhada no S27 e remove somente a moldura
|
||||
transparente do PNG. A tinta lê em aproximadamente 46 px, no peso da referência
|
||||
pública.
|
||||
</p>
|
||||
</div>
|
||||
</article>
|
||||
<article class="option">
|
||||
<div class="flex h-16 items-center justify-between bg-[#ae1603] px-8">
|
||||
<img
|
||||
src="../../public/campaign-kit/marca-negativa-completa.png"
|
||||
class="h-[58px] w-auto object-contain"
|
||||
alt="Jorge Solla 1313 — Mais Saúde, Mais Futuro"
|
||||
/>
|
||||
<span class="text-sm font-bold text-white">Central de Conteúdos</span>
|
||||
</div>
|
||||
<div class="p-5">
|
||||
<h3 class="font-extrabold">B · Marca negativa completa</h3>
|
||||
<p class="mt-2 text-sm leading-6 text-[#6c615e]">
|
||||
Oficial e correta sobre vermelho, mas comprime nome, número e slogan na barra de
|
||||
64 px. O slogan perde leitura e a massa vertical compete com o nome da seção.
|
||||
</p>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
<div class="mt-7 rounded-xl bg-white p-6">
|
||||
<p class="text-xs font-black tracking-[.12em] text-[#e4102f]">DECISÃO RECOMENDADA</p>
|
||||
<p class="display mt-1 text-2xl font-black">
|
||||
A · manter o lockup e corrigir a caixa, não redesenhar o header.
|
||||
</p>
|
||||
<p class="mt-2 max-w-3xl text-sm leading-6 text-[#6c615e]">
|
||||
Altura do header: 64 px. Inset horizontal: 32 px dentro do conteúdo. Lockup visível:
|
||||
188 × 50 px. Badge existente: 14 px, bold. Sem novo lockup e sem alteração de cor.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<div class="scene mb-3 flex items-center gap-3 text-xs font-bold text-[#6c615e]">
|
||||
<span>CENA 02</span>
|
||||
<h2>Mobile 390 · as duas opções na barra real de 56 px</h2>
|
||||
</div>
|
||||
<div class="flex flex-wrap justify-center gap-8">
|
||||
<article class="phone frame overflow-hidden bg-white">
|
||||
<div class="flex h-14 items-center justify-between bg-[#ae1603] px-5">
|
||||
<div class="trimmed-lockup mobile">
|
||||
<img src="../../public/campaign-kit/jorge-solla-negativo.png" alt="Jorge Solla" />
|
||||
</div>
|
||||
<span class="text-white">☰</span>
|
||||
</div>
|
||||
<div class="p-5">
|
||||
<span class="rounded-full bg-[#e4102f] px-2.5 py-1 text-[10px] font-black text-white"
|
||||
>A · RECOMENDADA</span
|
||||
>
|
||||
<h3 class="display mt-4 text-2xl font-black">Central de Conteúdos</h3>
|
||||
<p class="mt-2 text-sm leading-5 text-[#6c615e]">
|
||||
A assinatura continua reconhecível sem disputar espaço com o menu.
|
||||
</p>
|
||||
</div>
|
||||
</article>
|
||||
<article class="phone frame overflow-hidden bg-white">
|
||||
<div class="flex h-14 items-center justify-between bg-[#ae1603] px-5">
|
||||
<img
|
||||
src="../../public/campaign-kit/marca-negativa-completa.png"
|
||||
class="h-[52px] w-auto object-contain"
|
||||
alt="Jorge Solla 1313 — Mais Saúde, Mais Futuro"
|
||||
/><span class="text-white">☰</span>
|
||||
</div>
|
||||
<div class="p-5">
|
||||
<span class="rounded-full border border-black/15 px-2.5 py-1 text-[10px] font-black"
|
||||
>B · ALTERNATIVA</span
|
||||
>
|
||||
<h3 class="display mt-4 text-2xl font-black">Central de Conteúdos</h3>
|
||||
<p class="mt-2 text-sm leading-5 text-[#6c615e]">
|
||||
O conjunto completo fica pequeno demais para o slogan cumprir sua função.
|
||||
</p>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<div class="scene mb-3 flex items-center gap-3 text-xs font-bold text-[#6c615e]">
|
||||
<span>CENA 03</span>
|
||||
<h2>Página da peça · “Voltar à Central” e badge preservados</h2>
|
||||
</div>
|
||||
<div class="desktop frame mx-auto overflow-hidden rounded-xl bg-white">
|
||||
<header class="flex h-16 items-center justify-between bg-[#ae1603] px-10">
|
||||
<div class="trimmed-lockup">
|
||||
<img src="../../public/campaign-kit/jorge-solla-negativo.png" alt="Jorge Solla" />
|
||||
</div>
|
||||
<a class="text-sm font-bold text-white">Voltar à Central</a>
|
||||
</header>
|
||||
<div class="mx-auto grid max-w-5xl grid-cols-[1.15fr_.85fr] gap-10 px-10 py-12">
|
||||
<div
|
||||
class="grid aspect-video place-items-center rounded-2xl bg-stone-200 text-xs font-black tracking-wide text-stone-500"
|
||||
>
|
||||
NEEDS ASSET · PREVIEW REAL DA PEÇA
|
||||
</div>
|
||||
<div>
|
||||
<span
|
||||
class="inline-flex rounded-full bg-[#eef4fb] px-2 py-1 text-[11px] font-extrabold text-[#184e92]"
|
||||
>Central de Conteúdos</span
|
||||
>
|
||||
<h3 class="display mt-3 text-3xl font-black">Título da peça publicada</h3>
|
||||
<p class="mt-3 text-sm leading-6 text-[#6c615e]">
|
||||
Descrição editorial da peça, sem alteração neste item.
|
||||
</p>
|
||||
<div class="mt-6 h-11 rounded-[10px] bg-[#ffe607]"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="phone frame mx-auto mt-8 overflow-hidden bg-white">
|
||||
<header class="flex h-14 items-center justify-between bg-[#ae1603] px-5">
|
||||
<div class="trimmed-lockup mobile">
|
||||
<img src="../../public/campaign-kit/jorge-solla-negativo.png" alt="Jorge Solla" />
|
||||
</div>
|
||||
<a class="text-xs font-bold text-white">Voltar à Central</a>
|
||||
</header>
|
||||
<div class="p-5">
|
||||
<div class="aspect-video rounded-xl bg-stone-200"></div>
|
||||
<span
|
||||
class="mt-5 inline-flex rounded-full bg-[#eef4fb] px-2 py-1 text-[11px] font-extrabold text-[#184e92]"
|
||||
>Central de Conteúdos</span
|
||||
>
|
||||
<h3 class="display mt-2 text-2xl font-black">Título da peça publicada</h3>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
99
docs/plans/central-conteudos-header-logo.md
Normal file
99
docs/plans/central-conteudos-header-logo.md
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
# S36 — Central de Conteúdos — logo do header no tamanho da marca
|
||||
|
||||
Status: rascunho
|
||||
Atualizado em: 2026-09-23
|
||||
Issue: #1301
|
||||
Priority: P2
|
||||
Impeccable: B — encaixe no header existente da Central pública (sem rota nova)
|
||||
Design UI: docs/plans/central-conteudos-header-logo-ui-design.html
|
||||
Appetite: ~0,25–0,5 dia eng; correção de fidelidade visual no header
|
||||
Responsável: —
|
||||
|
||||
## Intenção
|
||||
|
||||
No header da Central de Conteúdos pública (`/conteudos`), a marca lê muito menor do que no resto do site público — testado em staging pelo operador. O ativo oficial tem uma moldura transparente grande em volta do desenho, então a caixa do header mostra só uma fração dele: a marca fica com peso de detalhe, não de assinatura. A Central é a casa das peças de "Peça voto pra Solla 1313" e o header é a primeira coisa que o eleitor vê; a marca precisa ler no mesmo peso das outras páginas públicas, tirada do kit como fonte única (sem lockup novo, sem paleta inventada).
|
||||
|
||||
## Persona e fluxo
|
||||
|
||||
- **Persona / contexto:** eleitor/simpatizante no celular, com pressa, chegando de um link compartilhado no WhatsApp; a Central ainda não é familiar e a marca no topo é a âncora de confiança de que ele está no lugar certo.
|
||||
- **Job principal:** reconhecer de imediato que está na Central oficial de Solla 1313 e seguir para a peça.
|
||||
- **Fluxo desejado:** abre `/conteudos` → vê a marca no topo no mesmo peso das outras páginas públicas → filtra/escolhe a peça; na página da peça e no estado de não encontrado, a mesma marca com o caminho de volta.
|
||||
- **Anti-goals de produto:** não vira redesign do header (nem da Central); não cria rota nem tela nova; não troca a marca por um lockup próprio nem inventa cor/tipografia; não mexe em copy, badge ou comportamento do "Voltar à Central"; não é passada de olho nas outras páginas públicas.
|
||||
|
||||
### Esboço de fluxo (B)
|
||||
|
||||
```text
|
||||
[abre /conteudos (catálogo, peça, não encontrado)] → [header vermelho com a marca no peso das outras públicas]
|
||||
→ [segue para a peça / volta à Central]
|
||||
```
|
||||
|
||||
### Design UI (B)
|
||||
|
||||
- Design UI (gate): `docs/plans/central-conteudos-header-logo-ui-design.html` — o humano valida no gate que a marca lê no peso certo nos dois breakpoints, com a opção de ativo escolhida.
|
||||
|
||||
## Objetivo e aceite
|
||||
|
||||
- A marca no header da Central lê, nos dois breakpoints, no mesmo peso visual do header público de referência (`/jingles`) — aferido lado a lado em staging.
|
||||
- Fonte única da marca é o kit 1313 (`public/campaign-kit/`); nenhum lockup recriado, nenhuma cor ou tipografia inventada.
|
||||
- A correção vive no header da Central (escolha de ativo e/ou tamanho renderizado), sem redesenhar o header.
|
||||
- Badge "Central de Conteúdos", link "Voltar à Central" e comportamento nos dois breakpoints permanecem.
|
||||
- Nenhuma outra página pública muda (sem drive-by).
|
||||
|
||||
## Dados (intenção)
|
||||
|
||||
- **Vou apresentar dados?** Não.
|
||||
- **Decisões desbloqueadas:** N/A — correção de fidelidade visual; nenhum ator decide com número.
|
||||
- **Forma:** _adiada ao plano de implementação_ — sem restrição de produto além da referência de peso visual acima.
|
||||
|
||||
## Dados da decisão (literais)
|
||||
|
||||
- Superfícies do header: `/conteudos` (catálogo, com e sem peças publicadas), `/conteudos/<slug>` e o não encontrado da peça — todas usam `ContentPiecePageHeader`.
|
||||
- Header atual: `src/components/conteudos/ContentPiecePageHeader.tsx:12-22` — `<Image src="/campaign-kit/jorge-solla-negativo.png" ... className="h-7 w-auto object-contain sm:h-9" />`, dentro de um `div` `h-14 sm:h-16` sobre `bg-[#ae1603]`.
|
||||
- Ativo atual: canvas 1037×595; recorte visível 790×285 (transparência topo 162, base 148, esquerda 123, direita 124) → marca visível ≈13,4 px em `h-7` e ≈17,2 px em `sm:h-9`.
|
||||
- Referência de peso (`/jingles`): `src/components/CampaignPageHeader.tsx:20-27` com `marca-positiva-completa.png` (visível 552×415 no mesmo canvas 1037×595) em `h-[66px] sm:h-[74px]` → ≈46/52 px visíveis (≈3× a marca da Central).
|
||||
- O ativo negativo `jorge-solla-negativo.png` só é usado em `ContentPiecePageHeader.tsx:16`; o S27 portou fielmente o `h-9` do artefato `docs/plans/central-conteudos-publica-ui-design.html:158-164,427-433` (cenas 01/04), mas artefato+ativo juntos renderizam pequeno.
|
||||
- Dono da marca: `public/campaign-kit/README.md` (kit 1313). A pasta já tem, para fundo vermelho/escuro, a **marca completa** `marca-negativa-completa.png` (nome + 1313 + slogan; visível 552×415 no mesmo canvas, `README.md:35-37`) — ativo diferente do lockup de nome usado no header hoje; e não tem nenhuma variante **recortada** do lockup `jorge-solla-negativo.png`.
|
||||
|
||||
## Direção no codebase (hipótese)
|
||||
|
||||
- **Áreas prováveis:** `src/components/conteudos/ContentPiecePageHeader.tsx` (único componente do header da Central) e `public/campaign-kit/` (ativo/kit); rotas consumidoras em `src/app/(frontend)/conteudos/`.
|
||||
- **Precedente a olhar:** `src/components/CampaignPageHeader.tsx` (header de `/jingles`, mesmo canvas, peso-alvo) e o S27 `docs/plans/central-conteudos-publica.md`.
|
||||
- **Risco de acoplamento:** o header é page-local da Central (não é shell do site) — a correção não deve virar componente compartilhado nem alterar `CampaignPageHeader`.
|
||||
|
||||
## Dependências
|
||||
|
||||
- Nenhuma dura. Contexto: S27 (#1255) entregou a Central pública e o header.
|
||||
|
||||
## Fora de escopo
|
||||
|
||||
- Redesenho do header da Central ou da página (fica para novo item, se houver pedido).
|
||||
- Outras páginas públicas e seus headers (`/jingles`, home, `/cards`) — sem mudanças de carona.
|
||||
- Recriar lockup, paleta ou tipografia; qualquer coisa fora do kit 1313.
|
||||
- Copy, badge, CTA e comportamento do "Voltar à Central".
|
||||
- Qualquer mudança de dados, consentimento ou rotas.
|
||||
|
||||
## Rabbit holes de produto
|
||||
|
||||
- **"Já que estou no header, padronizo os outros."** Se alguém "só completar": vira refactor de todos os headers públicos e revisão de marca. **Corte neste item:** só o header da Central.
|
||||
- **"Monto um lockup novo com o ativo recortado no Figma."** Se alguém "só completar": nasce uma marca paralela fora do kit. **Corte neste item:** kit como fonte única; no máximo preparo técnico do ativo oficial (recorte do PNG existente), não desenho novo.
|
||||
- **"Ajusto o header inteiro para caber a marca."** Se alguém "só completar": muda altura, espaçamento e badge das telas. **Corte neste item:** a menor mudança que faça a marca ler no peso certo.
|
||||
|
||||
## Questões em aberto (produto)
|
||||
|
||||
- **Qual ativo/tamanho faz a marca ler no peso certo?** **Opções:** A) lockup `jorge-solla-negativo.png` com o recorte técnico da moldura transparente (preparo do ativo oficial no kit, sem redesenho); B) usar a marca completa `marca-negativa-completa.png` (nome + 1313 + slogan), que o kit destina a fundos vermelhos/escuros e tem proporção visível muito maior; C) compensar no header o tamanho renderizado do lockup atual, sem distorcer. **Recomendação:** decidir no gate com o design hi-fi mostrando A e B lado a lado (o lockup é o que o S27 desenhou; a marca completa é o ativo do kit para o fundo vermelho); C só se nenhuma das duas servir. _(assumido — validar no gate do design)_
|
||||
|
||||
## Referências
|
||||
|
||||
- Design UI (gate): `docs/plans/central-conteudos-header-logo-ui-design.html` (+ assets em `central-conteudos-header-logo-ui-design-assets/`).
|
||||
- `docs/plans/central-conteudos-publica-ui-design.html` — artefato do S27 (cenas 01/04/06/07/08: header com `h-9`).
|
||||
- `src/components/conteudos/ContentPiecePageHeader.tsx`, `src/components/CampaignPageHeader.tsx`, `public/campaign-kit/README.md`.
|
||||
- S27: `docs/plans/central-conteudos-publica.md` (Issue #1255).
|
||||
|
||||
## Self-score (shaping)
|
||||
|
||||
1. Fatia = um outcome verificável? 5/5 — a marca no peso certo, aferida lado a lado em staging.
|
||||
2. Appetite declarado e a intenção cabe nele? 5/5 — ~0,25–0,5 dia; uma escolha de ativo/tamanho.
|
||||
3. Persona + job + aceite claros (sem jargão de stack)? 4/5 — aceite fala em peso visual; a aferição exige comparação em staging.
|
||||
4. Direção no codebase é hipótese (não contrato técnico)? 5/5 — arquivos e classes são literais de estado atual/evidência, não prescrição.
|
||||
5. Zero decisões duras de engenharia no plano? 4/5 — a questão em aberto recomenda decidir no gate; a escolha final (ativo vs compensação) fica para o gate/impl.
|
||||
Média: 4,6/5 — ≥4/5.
|
||||
426
docs/plans/central-conteudos-liderancas-ui-design.html
Normal file
426
docs/plans/central-conteudos-liderancas-ui-design.html
Normal file
|
|
@ -0,0 +1,426 @@
|
|||
<!doctype html>
|
||||
<html lang="pt-BR">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
|
||||
<title>Design — S37 · Lideranças nas peças</title>
|
||||
<style type="text/tailwindcss">
|
||||
@theme {
|
||||
--font-sans: Arimo, Arial, sans-serif;
|
||||
}
|
||||
:root {
|
||||
--red: #a21c1c;
|
||||
--kit: #e4102f;
|
||||
--blue: #184e92;
|
||||
--yellow: #ffe607;
|
||||
--cream: #fff8f2;
|
||||
--muted: #6c615e;
|
||||
--line: rgb(0 0 0/0.12);
|
||||
--display: 'Exo 2', 'Arial Black', sans-serif;
|
||||
}
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.display {
|
||||
font-family: var(--display);
|
||||
}
|
||||
.board {
|
||||
background: #e7e3e0;
|
||||
background-image: radial-gradient(rgb(24 78 146/0.09) 0.7px, transparent 0.7px);
|
||||
background-size: 18px 18px;
|
||||
}
|
||||
.frame {
|
||||
box-shadow: 0 22px 60px rgb(39 25 22/0.13);
|
||||
}
|
||||
.desktop {
|
||||
width: 1280px;
|
||||
}
|
||||
.phone {
|
||||
width: 390px;
|
||||
border-radius: 28px;
|
||||
}
|
||||
.scene:after {
|
||||
content: '';
|
||||
height: 1px;
|
||||
flex: 1;
|
||||
background: #cfc9c5;
|
||||
}
|
||||
.field {
|
||||
min-height: 44px;
|
||||
border: 1px solid #d6d3d1;
|
||||
border-radius: 6px;
|
||||
background: white;
|
||||
padding: 10px 12px;
|
||||
font-size: 14px;
|
||||
}
|
||||
.label {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.chip {
|
||||
display: inline-flex;
|
||||
min-height: 36px;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 999px;
|
||||
background: white;
|
||||
padding: 6px 11px;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.active {
|
||||
border-color: rgb(24 78 146/0.35);
|
||||
background: #eef4fb;
|
||||
color: #184e92;
|
||||
}
|
||||
.tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
border-radius: 999px;
|
||||
background: #f4f4f5;
|
||||
padding: 5px 8px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
min-height: 44px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 8px;
|
||||
padding: 9px 14px;
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.primary {
|
||||
background: #c51414;
|
||||
color: white;
|
||||
}
|
||||
.catalog-card {
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 14px;
|
||||
background: white;
|
||||
box-shadow: 0 8px 24px rgb(71 19 14/0.07);
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body class="board min-h-screen text-black antialiased">
|
||||
<main class="mx-auto max-w-[1480px] space-y-14 px-4 py-12 md:px-8">
|
||||
<header class="max-w-3xl">
|
||||
<span class="rounded-full bg-[#e4102f] px-3 py-1 text-xs font-bold text-white"
|
||||
>S37 · dois recortes, uma faceta</span
|
||||
>
|
||||
<h1 class="display mt-4 text-4xl font-black">
|
||||
Quem aparece na peça fica encontrável — sem expor quem não aparece.
|
||||
</h1>
|
||||
<p class="mt-2 text-sm leading-6 text-[#6c615e]">
|
||||
A ficha separa liderança interna de figura pública; a Central pública reúne apenas os
|
||||
nomes presentes em peças publicadas.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<section>
|
||||
<div class="scene mb-3 flex items-center gap-3 text-xs font-bold text-[#6c615e]">
|
||||
<span>CENA 01</span>
|
||||
<h2>Ficha interna · desktop 1280 · os dois recortes</h2>
|
||||
</div>
|
||||
<div
|
||||
class="desktop frame mx-auto overflow-hidden rounded-xl bg-white"
|
||||
data-theme="campaign"
|
||||
>
|
||||
<header class="flex h-14 items-center justify-between border-b bg-[#fafaf9] px-6">
|
||||
<b>Campanha · Comunicação</b
|
||||
><span class="text-sm text-[#6b7280]">Central de Conteúdos</span>
|
||||
</header>
|
||||
<div class="p-8">
|
||||
<a class="text-xs font-semibold text-[#c51414]">← Conteúdos</a>
|
||||
<div class="mt-2 flex items-start justify-between">
|
||||
<div>
|
||||
<h2 class="text-xl font-semibold">Título da peça em revisão</h2>
|
||||
<div class="mt-2 flex gap-2">
|
||||
<span
|
||||
class="rounded-full bg-green-100 px-2 py-1 text-xs font-semibold text-green-800"
|
||||
>Pronto</span
|
||||
><span
|
||||
class="rounded-full bg-[#f4f4f5] px-2 py-1 text-xs font-semibold text-[#6b7280]"
|
||||
>Rascunho</span
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
<button class="btn border bg-white">Publicar</button>
|
||||
</div>
|
||||
<div class="mt-7 grid grid-cols-[300px_1fr] gap-8">
|
||||
<aside>
|
||||
<div
|
||||
class="grid aspect-video place-items-center rounded-xl bg-stone-200 text-xs font-bold text-stone-500"
|
||||
>
|
||||
NEEDS ASSET · PREVIEW REAL
|
||||
</div>
|
||||
<dl class="mt-4 space-y-2 text-xs">
|
||||
<div class="flex justify-between">
|
||||
<dt class="text-[#6b7280]">Origem</dt>
|
||||
<dd>Arquivo</dd>
|
||||
</div>
|
||||
<div class="flex justify-between">
|
||||
<dt class="text-[#6b7280]">Tipo</dt>
|
||||
<dd>Vídeo</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</aside>
|
||||
<form class="grid grid-cols-2 gap-4">
|
||||
<div class="col-span-2">
|
||||
<p class="label">Título</p>
|
||||
<div class="field mt-1">Título da peça em revisão</div>
|
||||
</div>
|
||||
<div class="col-span-2 rounded-xl border p-5">
|
||||
<div class="flex items-start justify-between gap-6">
|
||||
<div>
|
||||
<h3 class="font-semibold">Quem aparece na peça</h3>
|
||||
<p class="mt-1 text-xs leading-5 text-[#6b7280]">
|
||||
Marque somente pessoas visíveis ou participantes desta peça. A publicação
|
||||
expõe apenas o nome.
|
||||
</p>
|
||||
</div>
|
||||
<span
|
||||
class="rounded-full bg-[#fff5ed] px-2 py-1 text-[11px] font-semibold text-[#6b2d15]"
|
||||
>Curadoria humana</span
|
||||
>
|
||||
</div>
|
||||
<div class="mt-5 grid grid-cols-2 gap-5">
|
||||
<div>
|
||||
<p class="label">Lideranças da campanha</p>
|
||||
<p class="mt-1 text-xs leading-5 text-[#6b7280]">
|
||||
Busca nos registros existentes. Nenhum telefone, município ou voto vai para
|
||||
a Central pública.
|
||||
</p>
|
||||
<div class="mt-2 flex flex-wrap gap-1.5">
|
||||
<span class="tag">Nome da liderança <b>×</b></span>
|
||||
</div>
|
||||
<div class="field mt-2 flex items-center justify-between text-[#6b7280]">
|
||||
<span>Buscar liderança…</span><span>⌄</span>
|
||||
</div>
|
||||
<div class="mt-1 rounded-lg border bg-white p-1 shadow-lg">
|
||||
<div class="rounded-md bg-[#f4f4f5] px-3 py-2 text-sm">
|
||||
<b>Nome da liderança</b
|
||||
><span class="block text-xs text-[#6b7280]">Registro da campanha</span>
|
||||
</div>
|
||||
<div class="px-3 py-2 text-sm">Outra liderança de exemplo</div>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<p class="label">Figuras públicas</p>
|
||||
<p class="mt-1 text-xs leading-5 text-[#6b7280]">
|
||||
Texto curado com catálogo, no mesmo molde de Instituição.
|
||||
</p>
|
||||
<div class="mt-2 flex flex-wrap gap-1.5">
|
||||
<span class="tag">Dep. Estadual Exemplo <b>×</b></span>
|
||||
</div>
|
||||
<div class="field mt-2 flex items-center justify-between text-[#6b7280]">
|
||||
<span>Digite ou escolha uma figura pública…</span><span>⌄</span>
|
||||
</div>
|
||||
<div class="mt-1 rounded-lg border bg-white p-1 shadow-lg">
|
||||
<div class="rounded-md bg-[#f4f4f5] px-3 py-2 text-sm">
|
||||
<b>Dep. Estadual Exemplo</b
|
||||
><span class="block text-xs text-[#6b7280]"
|
||||
>Figura pública catalogada</span
|
||||
>
|
||||
</div>
|
||||
<div class="px-3 py-2 text-sm">Personalidade Exemplo</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<p class="label">Instituição</p>
|
||||
<div class="field mt-1 text-[#6b7280]">Sem instituição</div>
|
||||
</div>
|
||||
<div>
|
||||
<p class="label">Cidade</p>
|
||||
<div class="field mt-1 text-[#6b7280]">Sem cidade</div>
|
||||
</div>
|
||||
<div class="col-span-2 flex justify-end">
|
||||
<button class="btn primary">Salvar alterações</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<div class="scene mb-3 flex items-center gap-3 text-xs font-bold text-[#6c615e]">
|
||||
<span>CENA 02</span>
|
||||
<h2>Ficha interna · mobile 390 · pessoa marcada e ninguém marcado</h2>
|
||||
</div>
|
||||
<div class="flex flex-wrap justify-center gap-8">
|
||||
<div class="phone frame min-h-[760px] overflow-hidden bg-white">
|
||||
<header class="flex h-14 items-center justify-between border-b px-4">
|
||||
<b>Central de Conteúdos</b><span>☰</span>
|
||||
</header>
|
||||
<div class="p-4">
|
||||
<a class="text-xs font-semibold text-[#c51414]">← Conteúdos</a>
|
||||
<h2 class="mt-2 text-lg font-semibold">Título da peça</h2>
|
||||
<div class="mt-5 rounded-xl border p-4">
|
||||
<h3 class="font-semibold">Quem aparece na peça</h3>
|
||||
<p class="mt-1 text-xs leading-5 text-[#6b7280]">
|
||||
Somente o nome poderá aparecer no filtro público.
|
||||
</p>
|
||||
<p class="label mt-5">Lideranças da campanha</p>
|
||||
<div class="mt-2 flex">
|
||||
<span class="tag">Nome da liderança <b>×</b></span>
|
||||
</div>
|
||||
<div class="field mt-2 flex justify-between text-[#6b7280]">
|
||||
<span>Buscar liderança…</span><span>⌄</span>
|
||||
</div>
|
||||
<p class="label mt-5">Figuras públicas</p>
|
||||
<div class="mt-2 flex">
|
||||
<span class="tag">Dep. Estadual Exemplo <b>×</b></span>
|
||||
</div>
|
||||
<div class="field mt-2 flex justify-between text-[#6b7280]">
|
||||
<span>Digite ou escolha…</span><span>⌄</span>
|
||||
</div>
|
||||
</div>
|
||||
<button class="btn primary mt-5 w-full">Salvar alterações</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="phone frame min-h-[620px] overflow-hidden bg-white">
|
||||
<header class="flex h-14 items-center justify-between border-b px-4">
|
||||
<b>Central de Conteúdos</b><span>☰</span>
|
||||
</header>
|
||||
<div class="p-4">
|
||||
<a class="text-xs font-semibold text-[#c51414]">← Conteúdos</a>
|
||||
<h2 class="mt-2 text-lg font-semibold">Peça sem ninguém marcado</h2>
|
||||
<div class="mt-5 rounded-xl border p-4">
|
||||
<h3 class="font-semibold">Quem aparece na peça</h3>
|
||||
<div class="mt-4 rounded-lg bg-[#f4f4f5] p-3 text-xs leading-5 text-[#6b7280]">
|
||||
Ninguém marcado. A peça pode ser publicada normalmente e não cria nenhum nome na
|
||||
faceta “Lideranças”.
|
||||
</div>
|
||||
<p class="label mt-5">Lideranças da campanha</p>
|
||||
<div class="field mt-2 text-[#6b7280]">Buscar liderança…</div>
|
||||
<p class="label mt-5">Figuras públicas</p>
|
||||
<div class="field mt-2 text-[#6b7280]">Digite ou escolha…</div>
|
||||
</div>
|
||||
<button class="btn primary mt-5 w-full">Salvar alterações</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<div class="scene mb-3 flex items-center gap-3 text-xs font-bold text-[#6c615e]">
|
||||
<span>CENA 03</span>
|
||||
<h2>Catálogo público · faceta única “Lideranças” · desktop e mobile</h2>
|
||||
</div>
|
||||
<div class="desktop frame mx-auto overflow-hidden rounded-xl bg-white">
|
||||
<header class="flex h-16 items-center justify-between bg-[#ae1603] px-10">
|
||||
<div class="h-9 w-44 rounded bg-white/20"></div>
|
||||
<b class="text-sm text-white">Central de Conteúdos</b>
|
||||
</header>
|
||||
<div class="mx-auto max-w-6xl px-10 py-10">
|
||||
<div class="rounded-xl bg-[#fff8f2] p-4">
|
||||
<div class="h-11 rounded-[10px] border bg-white px-3 py-3 text-sm text-[#6c615e]">
|
||||
Encontre uma peça por assunto, cidade ou pessoa…
|
||||
</div>
|
||||
<div class="mt-3 flex flex-wrap gap-2">
|
||||
<span class="chip">Tipo⌄</span><span class="chip">Cidade⌄</span
|
||||
><span class="chip">Região⌄</span><span class="chip">Tema⌄</span
|
||||
><span class="chip">Instituição⌄</span>
|
||||
<details open class="relative">
|
||||
<summary class="chip list-none border-[#184e92]/35 bg-[#eef4fb] text-[#184e92]">
|
||||
Lideranças⌄
|
||||
</summary>
|
||||
<div class="absolute z-10 mt-1 w-64 rounded-xl border bg-white p-2 shadow-xl">
|
||||
<p class="px-2 py-1 text-[10px] font-black tracking-wide text-[#6c615e]">
|
||||
EM PEÇAS PUBLICADAS
|
||||
</p>
|
||||
<div class="rounded-lg bg-[#f4f4f5] px-3 py-2 text-sm font-medium">
|
||||
Nome da liderança
|
||||
</div>
|
||||
<div class="px-3 py-2 text-sm">Dep. Estadual Exemplo</div>
|
||||
<div class="px-3 py-2 text-sm">Personalidade Exemplo</div>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-24 flex items-center justify-between">
|
||||
<div>
|
||||
<h3 class="display text-2xl font-black">Peças com Nome da liderança</h3>
|
||||
<p class="mt-1 text-sm text-[#6c615e]">
|
||||
O filtro combina com cidade, tema e os demais recortes.
|
||||
</p>
|
||||
</div>
|
||||
<span class="chip active">Lideranças · Nome da liderança ×</span>
|
||||
</div>
|
||||
<div class="mt-5 grid grid-cols-3 gap-6">
|
||||
<article class="catalog-card">
|
||||
<div
|
||||
class="grid aspect-video place-items-center bg-stone-200 text-[10px] font-black text-stone-500"
|
||||
>
|
||||
NEEDS ASSET · PREVIEW REAL
|
||||
</div>
|
||||
<div class="p-4">
|
||||
<span
|
||||
class="rounded-full bg-[#eef4fb] px-2 py-1 text-[11px] font-extrabold text-[#184e92]"
|
||||
>Vídeo</span
|
||||
>
|
||||
<h4 class="mt-2 font-extrabold">Título da peça publicada</h4>
|
||||
<p class="mt-1 text-xs text-[#6c615e]">Nome da liderança · Tema</p>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
<div class="mt-7 rounded-lg border border-dashed p-4 text-xs leading-5 text-[#6c615e]">
|
||||
<b class="text-black">Regra visível do gate:</b> este menu é derivado somente das
|
||||
peças publicadas. Despublicar a última peça de um nome remove esse nome da faceta
|
||||
imediatamente. Sem contato, território, organização, status ou votos.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="phone frame mx-auto mt-8 min-h-[740px] overflow-hidden bg-white">
|
||||
<header class="flex h-14 items-center justify-between bg-[#ae1603] px-4">
|
||||
<div class="h-7 w-32 rounded bg-white/20"></div>
|
||||
<span class="text-white">☰</span>
|
||||
</header>
|
||||
<div class="p-4">
|
||||
<div class="h-11 rounded-[10px] border px-3 py-3 text-sm text-[#6c615e]">
|
||||
Busque uma pessoa…
|
||||
</div>
|
||||
<div class="mt-3 flex gap-2 overflow-hidden">
|
||||
<span class="chip shrink-0">Tipo⌄</span
|
||||
><span class="chip active shrink-0">Lideranças · Nome da liderança ×</span>
|
||||
</div>
|
||||
<div class="mt-5 rounded-xl border bg-white p-3 shadow-lg">
|
||||
<p class="px-2 py-1 text-[10px] font-black tracking-wide text-[#6c615e]">
|
||||
LIDERANÇAS · EM PEÇAS PUBLICADAS
|
||||
</p>
|
||||
<div class="rounded-lg bg-[#f4f4f5] px-3 py-3 text-sm font-medium">
|
||||
Nome da liderança
|
||||
</div>
|
||||
<div class="px-3 py-3 text-sm">Dep. Estadual Exemplo</div>
|
||||
</div>
|
||||
<article class="catalog-card mt-5">
|
||||
<div
|
||||
class="grid aspect-video place-items-center bg-stone-200 text-[10px] font-black text-stone-500"
|
||||
>
|
||||
NEEDS ASSET · PREVIEW REAL
|
||||
</div>
|
||||
<div class="p-4">
|
||||
<span
|
||||
class="rounded-full bg-[#eef4fb] px-2 py-1 text-[11px] font-extrabold text-[#184e92]"
|
||||
>Vídeo</span
|
||||
>
|
||||
<h4 class="mt-2 text-lg font-extrabold">Título da peça publicada</h4>
|
||||
<p class="mt-1 text-xs text-[#6c615e]">Nome da liderança</p>
|
||||
<button class="btn mt-4 w-full bg-[#ffe607] text-black">Compartilhar</button>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
119
docs/plans/central-conteudos-liderancas.md
Normal file
119
docs/plans/central-conteudos-liderancas.md
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
# S37 — Central de Conteúdos — lideranças que aparecem nas peças (propriedade e filtro)
|
||||
|
||||
Status: rascunho
|
||||
Atualizado em: 2026-09-23
|
||||
Issue: #1303
|
||||
Priority: P2
|
||||
Impeccable: C — propriedade nova na ficha interna (C211) + faceta nova no catálogo público (S27)
|
||||
Design UI: docs/plans/central-conteudos-liderancas-ui-design.html
|
||||
Appetite: ~2 dias eng; um outcome verificável (a peça registra quem aparece e o catálogo público filtra por isso)
|
||||
Responsável: —
|
||||
|
||||
## Intenção
|
||||
|
||||
A campanha já tem a Central de Conteúdos interna (C211), onde a assessoria cataloga as peças, e a Central pública (S27), onde o eleitor filtra por Tipo, Cidade, Região, Tema e Instituição — mas "quem aparece na peça" não existe em lugar nenhum. Numa campanha de dobradinhas, é exatamente esse o recorte que o eleitor procura: o material em que a liderança dele ou o estadual dele aparece, para repassar no grupo. A comunicação quer registrar isso na peça; o eleitor quer filtrar por isso. A decisão do humano no planejamento foi "Os dois": a peça registra as lideranças da campanha que aparecem E as figuras públicas (dobradinhas/estaduais e outras personalidades), e o catálogo público tem os dois recortes na mesma faceta `Lideranças`. O cuidado que define o item: o que é interno (liderança é PII, escopada por perfil) não pode vazar no que é público — a faceta mostra só nomes de quem aparece em peça publicada.
|
||||
|
||||
## Persona e fluxo
|
||||
|
||||
- **Persona / contexto:** dois atores. A assessoria de comunicação, na mesa, editando a ficha da peça (o mesmo gate que já edita a ficha hoje); o eleitor/liderança, no celular, na Central, procurando o material em que a referência dele aparece.
|
||||
- **Job principal:** (comunicação) registrar quem aparece na peça; (eleitor) achar a peça em que uma pessoa aparece e repassá-la.
|
||||
- **Fluxo desejado:** comunicação abre a ficha da peça → marca as lideranças da campanha que aparecem e as figuras públicas (dobradinhas/personalidades) → publica; eleitor abre `/conteudos` → filtra pela faceta `Lideranças` → vê só nomes de quem aparece em peça publicada → abre a peça e compartilha.
|
||||
- **Anti-goals de produto:** segundo cadastro de pessoa; expor qualquer dado interno de liderança; virar diretório de lideranças ou placar de aparições; página pública por pessoa; mudar o que a liderança vê hoje (leader lockdown intocado).
|
||||
|
||||
### Esboço de fluxo (C)
|
||||
|
||||
```text
|
||||
[assessoria] ficha da peça (C211)
|
||||
→ marca quem aparece: lideranças da campanha (registros de Liderança) + figuras públicas (dobradinhas/personalidades)
|
||||
→ publica a peça
|
||||
[eleitor] /conteudos → faceta `Lideranças` (os dois recortes no mesmo filtro)
|
||||
→ só nomes de quem aparece em pelo menos uma peça publicada (fail-closed)
|
||||
→ abre a peça → baixa/compartilha
|
||||
[peça despublicada] → o nome some da faceta se não houver outra peça publicada com ele
|
||||
```
|
||||
|
||||
### Design UI (C)
|
||||
|
||||
- Design UI (gate): `docs/plans/central-conteudos-liderancas-ui-design.html` (+ assets em `central-conteudos-liderancas-ui-design-assets/`) — cenas: ficha interna com os dois recortes (lideranças + figuras públicas), faceta `Lideranças` no catálogo público (mobile/desktop) e o estado de peça sem ninguém marcado.
|
||||
|
||||
## Objetivo e aceite
|
||||
|
||||
- A ficha da peça registra dois recortes de "quem aparece": (1) as lideranças da campanha — os registros de Liderança existentes, sem cadastro novo — e (2) figuras públicas (dobradinhas/estaduais e outras personalidades), em texto curado com catálogo, no molde de Instituição.
|
||||
- O catálogo público ganha a faceta `Lideranças`, unindo os dois recortes no mesmo filtro (decisão do humano: "Os dois"); os filtros continuam combinando entre si como hoje.
|
||||
- **Fail-closed de exposição:** a faceta mostra só NOMES de pessoas referenciadas por pelo menos uma peça publicada; nunca expõe liderança ou figura que não aparece em peça publicada.
|
||||
- **Nada de dado interno:** sem contato, telefone, e-mail, municípios, organizações, status ou votos (declarados/estimados) de liderança; o leader lockdown segue intocado.
|
||||
- Quem edita é quem já edita a ficha hoje (gate da assessoria de comunicação); a catalogação pode sugerir, mas nunca sobrescreve curadoria humana.
|
||||
- Os nomes marcados entram na busca por termo da Central como qualquer outro conteúdo — buscar o nome de quem aparece acha a peça.
|
||||
- Publicar/despublicar atualiza a faceta na hora: sem peça publicada com o nome, ele não aparece.
|
||||
- Guardrails: sem cadastro paralelo de pessoa (relaciona ao dono existente ou usa o molde texto+catálogo); nada novo de PII é capturado e Consent/LGPD ficam intocados — a metade "lideranças da campanha" só mostra dados quando existirem lideranças (o dado de liderança segue atrás do bloqueio LGPD de produção).
|
||||
|
||||
## Dados (intenção)
|
||||
|
||||
- **Vou apresentar dados?** Não — a faceta é uma lista de nomes; sem contagem, sem ranking, sem placar de aparições.
|
||||
- **Decisões desbloqueadas:** a comunicação decide quem aparece em cada peça; o eleitor decide qual peça procurar pelo nome de quem aparece nela.
|
||||
- **Forma:** _adiada ao plano de implementação_ — restrição de produto: só nomes de exibição (sem número, sem contagem por pessoa, sem métrica de aparições).
|
||||
|
||||
## Dados da decisão (literais)
|
||||
|
||||
- ID `S37`; slug `central-conteudos-liderancas` (arquivo `docs/plans/central-conteudos-liderancas.md`); tipo `feature`; Priority `P2`.
|
||||
- Faceta pública: rótulo `Lideranças` (uma só), unindo os dois recortes no mesmo filtro.
|
||||
- Recorte 1 — lideranças da campanha: os registros de `Liderança` existentes (dono atual; não criar cadastro de pessoa).
|
||||
- Recorte 2 — figuras públicas: dobradinhas/estaduais do roster público e outras personalidades, em texto curado com catálogo (molde de `Instituição`), semeado com os nomes das dobradinhas.
|
||||
- Regra de exposição (fail-closed): só NOMES de pessoas que aparecem em pelo menos uma peça publicada; sem peça publicada, o nome não aparece.
|
||||
- Resposta do humano no planejamento (verbatim): **"Os dois"** — a peça registra lideranças da campanha E figuras públicas, e o filtro público tem os dois recortes na mesma faceta.
|
||||
- Guardrail literal: **sem cadastro paralelo de pessoa**; sem exposição de contato/território/votos da liderança.
|
||||
|
||||
## Direção no codebase (hipótese)
|
||||
|
||||
- **Áreas prováveis:** ficha interna da peça (`src/components/campaign/content/ContentPieceForm.tsx`, `src/utilities/content/…`); contrato/filtro público (`src/lib/contentPieceCatalog.ts`, `src/components/conteudos/ContentPieceFilters.tsx`); catalogação (`src/utilities/content/contentPieceCataloging.ts`).
|
||||
- **Precedente a olhar:** `institution` — campo texto na peça (`src/collections/ContentPiece.ts:303-307`) + catálogo (`src/lib/institutionCatalog.ts`) + aliases (`src/lib/institutionNameAliases.ts`) + match na catalogação (`contentPieceCataloging.ts:181-193`); a faceta pública deriva rótulos das peças publicadas por `slugify` (`contentPieceCatalog.ts:155-184,252-269`), parâmetro `instituicao` (`:39-55,96-107`). `Speech.mentionedPeople` (`src/collections/Speech.ts:306-312`) é precedente de "pessoas citadas" por texto, mas sem filtro público — não copiar o par acervo/C200.
|
||||
- **Roster público de pessoas:** `src/lib/stateDeputyCatalog.ts` (53 dobradinhas, nome+número, público via S30).
|
||||
- **Risco de acoplamento:** `leadership` é interno e PII-bound (leitura escopada por perfil — `src/utilities/access/leaderships.ts:31-32`); a superfície pública não pode ler `leadership`, `Contact`, `campaignUser` ou `electionCandidate` nem expor campo interno — os nomes públicos derivam só das peças publicadas. A busca pública casa o texto normalizado da peça (`src/lib/contentPiece.ts:323`), então o nome precisa ser encontrável por lá. Leader lockdown intocado.
|
||||
|
||||
## Dependências
|
||||
|
||||
- C211 (peças catalogadas/publicadas) e S27 (catálogo público com facetas) entregues — dura: sem peça publicada não há nome na faceta.
|
||||
- Roster das dobradinhas (S30) como semente do recorte de figuras públicas — soft.
|
||||
- Design hi-fi aprovado no gate.
|
||||
|
||||
## Fora de escopo
|
||||
|
||||
- Cards personalizados: a escolha do estadual no estúdio (S30/S31) é do visitante, não propriedade da peça.
|
||||
- C200 (separação por pessoa no acervo / speakers em gravações, #1167) — superfície distinta; não acoplar.
|
||||
- Expor qualquer dado interno de liderança (contato, telefone, e-mail, municípios, organizações, votos declarados/estimados).
|
||||
- Mudanças de LGPD/Consent: nada novo de PII é capturado; o dado de liderança segue atrás do bloqueio LGPD de produção (a metade campanha só mostra quando houver lideranças).
|
||||
- Filtro/coluna na lista interna de peças — só se o gate pedir (ver Q(a)).
|
||||
- Página pública por pessoa, diretório/ranking de aparições, analytics de circulação (C213).
|
||||
|
||||
## Rabbit holes de produto
|
||||
|
||||
- **Cadastro paralelo de pessoa.** Se alguém "só completar": collection de "pessoas que aparecem" com nome/telefone/cidade. **Corte neste item:** liderança = registro existente; figura pública = texto curado + catálogo; nenhum cadastro novo.
|
||||
- **A faceta virar diretório de lideranças.** Se alguém "só completar": listar todas as lideranças, com município e status. **Corte neste item:** só nomes de quem aparece em peça publicada; nada de dado interno.
|
||||
- **Placar de aparições.** Se alguém "só completar": contador por pessoa, "quem aparece mais", ranking. **Corte neste item:** lista de nomes sem número.
|
||||
- **Página por pessoa.** Se alguém "só completar": `/conteudos/pessoa/<nome>` ou um hub da liderança. **Corte neste item:** uma faceta no catálogo existente; a peça continua sendo a unidade.
|
||||
- **A catalogação automática decidir por gente.** Se alguém "só completar": o pipeline preenche e sobrescreve os nomes. **Corte neste item:** sugestão só quando confiável; curadoria humana manda.
|
||||
|
||||
## Questões em aberto (produto)
|
||||
|
||||
- **Filtro só público ou também filtro/coluna na lista interna?** **Opções:** A) faceta pública (o pedido) + propriedade visível/editável na ficha interna | B) também filtro/coluna na lista interna. **Recomendação:** A — é o pedido; filtro/coluna interno só se o gate pedir. _(assumido — validar com produto)_
|
||||
- **Uma faceta unindo os dois recortes ou duas facetas?** **Opções:** A) uma faceta `Lideranças` com os dois recortes | B) `Lideranças` + `Figuras públicas`. **Recomendação:** A — o humano escolheu "Os dois" no mesmo filtro; B fica registrada como alternativa se o volume de figuras públicas justificar separar. _(assumido — validar com produto)_
|
||||
- **O recorte de figuras públicas reusa o roster das dobradinhas ou é texto com aliases?** **Opções:** A) texto curado + catálogo no molde de Instituição, semeado com os nomes das dobradinhas | B) só o roster fechado das 53 dobradinhas | C) texto livre sem catálogo. **Recomendação:** A — cobre dobradinhas e outras personalidades sem inventar cadastro; C perde o casamento de grafias. _(assumido — validar com produto)_
|
||||
- **Que nome da liderança aparece?** **Opções:** A) o nome do contato (é o título da Liderança hoje) | B) algum rótulo composto. **Recomendação:** A — só o nome; nunca telefone, e-mail ou município. _(assumido — validar com produto)_
|
||||
|
||||
## Referências
|
||||
|
||||
- GitHub Issue — a registrar (`pnpm agent:register`).
|
||||
- Design UI (gate): `docs/plans/central-conteudos-liderancas-ui-design.html` (+ assets em `central-conteudos-liderancas-ui-design-assets/`).
|
||||
- Planos irmãos: `docs/plans/central-conteudos-ingestao.md` (C211), `docs/plans/central-conteudos-publica.md` (S27), `docs/plans/cards-estadual-dobradinha.md` (S30), `docs/plans/acervo-separacao-por-pessoa.md` (C200 — fora de escopo).
|
||||
- Arquivos-pista: `src/collections/ContentPiece.ts`, `src/components/campaign/content/ContentPieceForm.tsx`, `src/lib/contentPieceCatalog.ts`, `src/components/conteudos/ContentPieceFilters.tsx`, `src/lib/institutionCatalog.ts`, `src/lib/institutionNameAliases.ts`, `src/utilities/content/contentPieceCataloging.ts`, `src/lib/stateDeputyCatalog.ts`, `src/collections/Leadership.ts`, `src/utilities/access/leaderships.ts`, `src/collections/Speech.ts`.
|
||||
- `AGENTS.md` — convenções já travadas (Contact como dono da pessoa; sem cadastro paralelo; migrations para schema).
|
||||
|
||||
## Self-score (shaping)
|
||||
|
||||
5/5 — um outcome verificável, appetite declarado e nenhuma decisão dura de engenharia.
|
||||
|
||||
- Fatia = um outcome verificável: a peça registra quem aparece e o catálogo público filtra por isso.
|
||||
- Appetite ~2 dias cabe: uma propriedade na ficha existente + uma faceta no catálogo existente, sem fluxo novo.
|
||||
- Persona + job + aceite claros, em linguagem de produto, sem jargão de stack.
|
||||
- Direção no codebase é hipótese: arquivos citados como pista, nenhum nome novo cravado.
|
||||
- Zero schema/migration/signature no plano; literais são só de produto (rótulo, recortes, regra de exposição e a resposta do humano).
|
||||
183
docs/plans/central-conteudos-link-instagram-impl.md
Normal file
183
docs/plans/central-conteudos-link-instagram-impl.md
Normal file
|
|
@ -0,0 +1,183 @@
|
|||
# Impl: C220 — Central de Conteúdos — link do Instagram do deputado baixa e cataloga a peça
|
||||
|
||||
Status: aprovado
|
||||
Atualizado em: 2026-09-24
|
||||
Issue: #1302
|
||||
Intenção: docs/plans/central-conteudos-link-instagram.md
|
||||
Appetite restante: herdado (~1,5–2 dias eng) — sem corte novo: o plano reusa o pipeline C211 e o cliente Graph API existentes; varredura, backfill, scraping e álbum de carrossel seguem fora (intenção).
|
||||
|
||||
> Modo `--auto` (work-issue): plano nasce aprovado pelo agente. Design UI do gate: `docs/plans/central-conteudos-link-instagram-ui-design.html`. Trigger de designer declarado em **D7: non-trigger** — se a execução encontrar um estado não desenhado, o designer estende o artefato ANTES do markup (não improvisar estrutura visual).
|
||||
|
||||
## Leitura da intenção
|
||||
|
||||
- **Outcome:** colar um link do próprio perfil do deputado (`@depjorgesolla`) nas formas que o browser copia resulta em peça com mídia baixada, transcrita e catalogada — igual ao envio por arquivo; quando a extração não acontecer, a ficha mostra **um dos quatro motivos literais** e a peça continua peça-link (`pronto`, nunca "Falhou", nunca em silêncio).
|
||||
- **O que NÃO negociar:**
|
||||
- Extração **só** por caminho oficial (Graph API da própria conta, `src/utilities/socialFeed/instagramFeed.ts`); nunca scraping/contorno; **mídia de terceiro nunca é baixada**; YouTube **link-only sem motivo** (a Data API não entrega arquivo).
|
||||
- Motivos **verbatim** e peça-link como resultado legítimo; `sourceUrl` canônico é a identidade (sem peça gêmea).
|
||||
- Board/feed da home **intocado**: sem cache 5 min, snapshot, kill switch, lock transacional do hook e sem `@payload-config` em `instagramFeed.ts` (`instagramFeedView.ts:44-48,96`).
|
||||
- `curatedFields` da assessoria nunca sobrescritos e **não ganha o campo de motivo**; `error` cru nunca chega à pessoa; token nunca em log.
|
||||
- Despublicar/peça-link nunca apaga arquivo nem peça; "Anexar arquivo original" segue como caminho.
|
||||
- LGPD: **sem Consent novo** (não há PII de eleitor; a peça é material de campanha).
|
||||
- **O que reavaliar (hipóteses da intenção, confirmadas ou resolvidas no código):**
|
||||
- "o parse rejeita caminho prefixado" — confirmado: `parseContentPieceLink` desestrutura `[kind, shortcode]` por posição (`src/lib/contentPiece.ts:373-386`); muda.
|
||||
- "a extração degrada em silêncio" — confirmado: 5 ramos devolvem `{media:null,caption}` sem motivo (`contentPieceLink.ts:114-155`) e o job grava `pronto/step:null/error:null` (`contentPieceJob.ts:262-299`).
|
||||
- "não há paginação" — confirmado: `parseInstagramMediaResponse` descarta `paging` (`instagramFeed.ts:148-185`) e o `limit` é capado em 50 (`:228`); o `maxResults` do C212 continua em aberto contra a API real.
|
||||
- "persistir motivo exige campo novo" — confirmado: `error` é interno e só renderiza em `falhou` (`[id]/page.tsx:175-182`; `lib/contentPiece.ts:517` mapeia `error→failureMessage` sempre) ⇒ campo novo + migration.
|
||||
- **Assumidas da intenção (recomendações A):** janela de busca paginada com limite declarado (D2); motivo **só na ficha** (D7); links prefixados pelo perfil aceitos (D3/parse).
|
||||
- Hipótese "motivo só na ficha" × design cena 3 ("Instagram · Peça-link" na lista): resolvida em D7 — motivo nunca na lista; a lista mobile ganha só o rótulo neutro desenhado.
|
||||
|
||||
## Abordagem recomendada
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
D["Dialog 'Adicionar por link'<br/>cole do próprio perfil"] --> P["parseContentPieceLink<br/>(p|reel|reels|tv · perfil prefixado · query ignorada)"]
|
||||
P --> A["action cria contentPiece<br/>processando/extraindo · sourceUrl canônico"]
|
||||
A -->|"Instagram"| J["after() → runContentPieceJob<br/>resolveContentPieceSource"]
|
||||
A -->|"YouTube"| Y["peça-link sem motivo<br/>(link-only por desenho)"]
|
||||
J --> C{"Credencial<br/>configurada?"}
|
||||
C -- "não" --> R4["motivo: sem-credencial"]
|
||||
C -- "sim" --> W{"shortcode na janela de 500<br/>(cursor · early-stop)"}
|
||||
W -- "sem match" --> R1["motivo: nao-encontrado"]
|
||||
W -- "carrossel" --> R2["motivo: carrossel"]
|
||||
W -- "imagem/vídeo/reel" --> DL["baixa media_url<br/>(teto 4 GB · sem scraping)"]
|
||||
DL -- "HTTP/transporte falhou" --> R3["motivo: indisponivel"]
|
||||
DL -- "ok" --> M["contentMedia + transcrição<br/>+ catalogação (igual ao arquivo)"]
|
||||
R1 --> F["pronto · step null · error null<br/>linkFailureReason persistido"]
|
||||
R2 --> F
|
||||
R3 --> F
|
||||
R4 --> F
|
||||
M --> OK["pronto · motivo null"]
|
||||
Y --> OK
|
||||
F --> UIF["ficha: 'Por que o arquivo não foi baixado'<br/>+ Anexar arquivo original"]
|
||||
OK --> UIO["ficha: 'Arquivo e transcrição prontos'"]
|
||||
F --> UL["lista: só 'Instagram · Peça-link'"]
|
||||
```
|
||||
|
||||
**Opções consideradas (geral):** A) paginação por cursor no dono do cliente Graph API + motivo persistido em select novo + resolução do link que devolve motivo (sem lançar) + ficha desenhada; B) scraping/oEmbed/segundo fetch ou download de terceiro; C) manter tudo como está (só forma canônica; falha = `falhou`).
|
||||
**Recomendação:** **A** — mantém um dono por mecanismo (feed Graph API, pipeline da peça, ficha), usa o seam de dependências injetáveis que o C211 já criou para o resolver (`contentPieceLink.ts:87-105`), nasce fail-closed e cabe no appetite.
|
||||
**Rejeitadas:** **B** por invariante (nunca scraping/terceiro); **C** porque não cumpre o aceite (link do perfil continua degradando) nem "motivo honesto" — e não exige schema novo justamente onde o silêncio nasce.
|
||||
|
||||
### D1 — Persistência do motivo: campo enum novo + migration
|
||||
|
||||
**Opções:** A) select novo `linkFailureReason` com 4 valores pt-BR sem acento (`nao-encontrado | carrossel | indisponivel | sem-credencial`), labels = literais verbatim, nullable/readOnly/sem default; B) `text` livre guardando o literal; C) reusar `error`.
|
||||
**Recomendação:** **A** — vocabulário fechado e fail-closed, DB restringe, a UI só mapeia label; espelha `processingStatus`/`step` (valores pt-BR + labels acentuados, precedente do C211) e preserva `error` como causa crua interna (`ContentPiece.ts:397-405`).
|
||||
**Rejeitadas:** **B** — texto livre deriva (jargão, literal torto) e a UI teria de adivinhar o motivo de volta; **C** — quebra a separação raw×produto: `error` é stderr/transporte e só renderiza em `falhou`; usá-lo num estado `pronto` confundiria os dois ciclos (e violaria "nunca com o detalhe cru").
|
||||
**Migration:** `pnpm migrate:create add_content_piece_link_failure_reason` → `20260924_<HHMMSS>_add_content_piece_link_failure_reason` (enum + coluna nullable; **sem backfill** — peça-link antiga cai no card genérico; reprocessar acervo é não escopo). `pnpm migrate` local + `pnpm generate:types` (payload-types é versionado). Migration existente nunca editada.
|
||||
|
||||
### D2 — Janela de busca: paginação por cursor no dono, sem acoplar ao board
|
||||
|
||||
**Opções:** A) dar paginação por cursor ao `loadInstagramFeed` (o dono do cliente Graph API): `maxResults` vira a **janela total** e cada página pede `limit = min(maxResults, 50)` ≤ 50, avançando por `paging.cursors.after` enquanto faltar e houver cursor; `maxResults ≤ 50` ⇒ exatamente 1 página (board/sync intactos); B) função nova no mesmo módulo (twin interno de refresh/parse); C) o resolver chamar a Graph API por conta própria.
|
||||
**Recomendação:** **A**, com janela declarada de **500 mídias** (`CONTENT_PIECE_LINK_INSTAGRAM_WINDOW = 500`, em `contentPieceLink.ts`): ~10 páginas de 50, early-stop no match; a chamada típica é **1** (a assessoria cola o post recém-publicado); 500 ≈ 1–2 anos de ritmo, bem dentro do teto de 10K da edge (C212 §Q1) e com custo máximo ≤10 chamadas por colagem. Detalhes: `parseInstagramMediaPage` (novo; mesma validação de protocolo; devolve `{ posts, nextCursor }` lendo `paging.cursors.after`; cursor ausente/malformado ⇒ para) e `parseInstagramMediaResponse` fica como wrapper (testes e `nextImageRemotePatterns`). `paging.next` é **ignorado** de propósito (leva `access_token` na URL — token nunca em log). Refresh segue o contrato atual: falha em qualquer página ⇒ um refresh e refaz a janela do zero.
|
||||
**Rejeitadas:** **B** — duas implementações do mesmo cursor/refresh/erro no mesmo dono; **C** — duplicaria auth/refresh/erro tipado e jogaria fora o seam injetável do C211.
|
||||
**Risco declarado:** se o host do Instagram Login só oferecer paginação time-based (C212 "a confirmar"), a janela efetiva cai para a 1ª página (50) e o motivo continua honesto — sem quebra; verificação viva no staging/produção (Riscos).
|
||||
|
||||
### D3 — Matching shortcode ↔ mídia (permalink)
|
||||
|
||||
**Opções:** A) identidade pelo **shortcode** (`parseContentPieceLink(post.permalink)?.shortcode === link.shortcode`); B) igualdade de `canonicalUrl` (comportamento atual, `contentPieceLink.ts:144-146`); C) comparar id numérico da mídia.
|
||||
**Recomendação:** **A** — o shortcode é a identidade declarada (`lib/contentPiece.ts:354-359`) e o kind (`p` × `reel`) é apresentação: com **B**, um link `/p/ABC/` colado para um reel nunca casa; **A** casa as duas grafias e, por casar **dentro do feed da conta própria**, é também o que garante "mídia de terceiro nunca baixada" (link de terceiro ⇒ sem match ⇒ motivo `nao-encontrado`).
|
||||
**Rejeitadas:** **B** — falso-negativo por kind; **C** — o id numérico não está no link colado.
|
||||
**Parse (muda junto):** aceitar `[kind, shortcode]` **ou** `[perfil, kind, shortcode]` (só essas duas formas), com `p|reel|reels|tv`, `www.`/`m.`, query/hash ignorados; rejeitar `/stories/` (inclusive quando `stories` for o "perfil" de um caminho forjado — primeiro segmento reservado/kind nunca é perfil), `instagr.am` e hosts fora de IG/YouTube; canônico continua `https://www.instagram.com/<kind canônico>/<shortcode>/`.
|
||||
|
||||
### D4 — Falha da extração: motivo, não `falhou` (e `!mediaUrl`)
|
||||
|
||||
**Opções:** A) falhas **do lado Instagram** (sem credencial; `loadFeed` lança; sem match na janela; carrossel; `!mediaUrl`; erro HTTP/transporte do download) devolvem `media:null` + motivo e a peça termina `pronto` (peça-link); falhas **locais** (criar `contentMedia`, exceder o teto de 4 GB, ffmpeg/transcrição) continuam lançando ⇒ `falhou` + "Reprocessar"; B) tudo vira motivo; C) manter o throw atual do download.
|
||||
**Recomendação:** **A** — cumpre "peça-link é resultado legítimo, não 'Falhou'" e deixa `falhou` só para o que o reprocessar/arquivo resolve. Para post **encontrado** mas sem `mediaUrl` (ex.: áudio protegido omite o campo), o motivo é `indisponivel` (não é carrossel; a API achou mas não entregou o arquivo) — micro-decisão registrada, reversível. Nenhum desses ramos lança: o `catch` do job (`contentPieceJob.ts:300-306`) segue reservado a falhas reais.
|
||||
**Nota de implementação:** o teto de bytes precisa ser distinguível de falha de transporte no mesmo `pipeline` — usar um erro sentinela do dono (`ContentPieceMediaTooLargeError`, `contentPieceLink.ts`) que o resolver relança; qualquer outra falha do stream vira `indisponivel`. Assim o cap continua `falhou` (retry não resolve, anexar resolve) e a rede do Instagram vira motivo honesto.
|
||||
**Rejeitadas:** **B** — mascararia falha nossa/storage como problema do Instagram e mataria o "Reprocessar"; **C** — deixa a extração falha sem motivo (o defeito que o item conserta) e converte indisponibilidade transitória em "Falhou".
|
||||
|
||||
### D5 — Token refresh
|
||||
|
||||
**Opções:** A) persistir o `refreshedAccessToken` que o `loadInstagramFeed` já devolve, via `persistInstagramAccessToken` (owner, raw SQL sem hooks), best-effort; B) ignorar (status quo: `contentPieceLink.ts:130-135` descarta); C) writer novo.
|
||||
**Recomendação:** **A** — é o mesmo helper do board, **não** é o caminho do sync (sem snapshot, kill switch, cache ou lock); evita refresh repetido a cada colagem; falha ao persistir não derruba a extração (`.catch`); token nunca vai a log (nenhuma URL com `access_token` é logada/armazenada). O UPDATE pode esperar o row lock do global se o hook do board estiver sincronizando naquele instante — é espera, não deadlock; best-effort resolve.
|
||||
**Rejeitadas:** **B** — gasta refresh à toa e pode expirar sem o board rodar; **C** — twin.
|
||||
|
||||
### D6 — Ciclo de vida do motivo (onde seta e limpa)
|
||||
|
||||
**Opções:** A) o resolver devolve `linkFailureReason` e **o job é o único que persiste**, no write final `pronto` (com `step:null/error:null`): motivo quando `!media` e origem Instagram; `null` quando há mídia, quando origem ≠ Instagram (YouTube/arquivo) ou quando não se aplica; `attachContentPieceMedia` limpa no mesmo update que grava `media` (`contentPieceUpload.ts:273-286`); o retry (`contentPieces.ts:185-195`) limpa ao reiniciar; o motivo **não** entra em `CONTENT_PIECE_CURATED_FIELDS`; B) o resolver escreve direto na linha; C) limpar só no anexo.
|
||||
**Recomendação:** **A** — um escritor (o job), coerente com "o pipeline é dono do estado"; **B** mistura I/O de resolução com estado da linha; **C** deixa motivo obsoleto quando o retry reencontra a mídia.
|
||||
**YouTube:** nunca tem motivo — o branch origem ≠ Instagram devolve `null` (link-only por desenho, coberto por teste).
|
||||
|
||||
### D7 — Superfície de UI (ficha × lista) e trigger de designer
|
||||
|
||||
**Opções:** A) motivo **só na ficha**; a lista não tem motivo, mas a card mobile ganha o rótulo neutro desenhado ("Instagram · Peça-link") derivado de `origin`+`hasFile` (sem campo novo); B) selo de motivo na lista; C) lista intocada.
|
||||
**Recomendação:** **A** — a cena 3 do design do gate desenha exatamente isso ("Instagram · Peça-link" + recomendação "a lista continua limpa; o motivo completo vive na ficha") e a pergunta em aberto da intenção era sobre o **motivo** na lista (recomendação A). O card de motivo desktop ("Motivo da peça-link") e o mobile ("Por que o arquivo não foi baixado") viram **um só** card, com o literal mobile como título — evita duas estruturas divergentes.
|
||||
**Trigger de designer: `non-trigger` (declarado).** Tudo que o código real exige já está desenhado: cena 1 (processando com 3 passos + "Buscando a mídia no perfil oficial…" + estado "Arquivo e transcrição prontos"), cena 2 (motivo + "Anexar arquivo original") e cena 3 (mobile, motivo e lista compacta). Duas **adaptações de copy** (honestidade, sem estrutura nova, registradas): (i) o card verde usa "Arquivo e transcrição prontos" só quando há transcrição, senão "Arquivo pronto" (o desenho é de um reel); (ii) o corpo não afirma "a mídia oficial foi baixada" quando o arquivo pode ter vindo do anexo. Se a execução encontrar um estado **não desenhado**, para e o designer estende o artefato antes do markup.
|
||||
**Rejeitadas:** **B** — viola "lista limpa" e polui a triagem; **C** — não implementa um elemento desenhado sem necessidade.
|
||||
|
||||
### Componentes / mudanças
|
||||
|
||||
- **`src/lib/contentPiece.ts`** (puro; dono do vocabulário): `CONTENT_PIECE_LINK_FAILURE_REASONS` + type + `contentPieceLinkFailureReasonLabels` (literais verbatim) + `isContentPieceLinkFailureReason`; `CONTENT_PIECE_LINK_LABEL = 'Peça-link'`; `parseContentPieceLink` com perfil prefixado e rejeição explícita de `stories`; `ContentPieceViewModel` ganha `linkFailureReason` + `linkFailureReasonLabel` (normalização fail-closed em `toContentPieceViewModel`, sem tocar em `failureMessage`).
|
||||
- **`src/utilities/socialFeed/instagramFeed.ts`** (dono do cliente Graph API): `parseInstagramMediaPage` (posts + cursor) e loop de cursor em `loadInstagramFeed` (`maxResults` = janela, página ≤ 50, default 1 página); `INSTAGRAM_MAX_RESULTS_CAP` vira teto **por página** (comentário); refresh/erro tipado/`signal` inalterados; snapshot/status/config **não** se tocam.
|
||||
- **`src/utilities/content/contentPieceLink.ts`** (dono da resolução): `CONTENT_PIECE_LINK_INSTAGRAM_WINDOW = 500`; retorno com `linkFailureReason`; mapeamento dos ramos (D4); download falho ⇒ `indisponivel` (sem lançar; sentinela do cap relança); persist best-effort do refresh (D5); limite de tempo do feed (30 s) para a API pendurada não segurar `processando` até o reaper; `INSTAGRAM_MAX_RESULTS_CAP` sai do import.
|
||||
- **`src/utilities/content/contentPieceJob.ts`**: write transacional final persiste `linkFailureReason` (D6); nada mais muda (transação/`req` e bypass admin já justificados em `:59-85,262-299`).
|
||||
- **`src/utilities/content/contentPieceUpload.ts`**: `attachContentPieceMedia` limpa `linkFailureReason` junto de `error: null`.
|
||||
- **`src/app/(campaign)/campanha/actions/contentPieces.ts`**: `linkFailureReason` no `contentPieceSelect` (`:42-59`); retry limpa (`:185-195`); `overrideAccess:false` + `user` preservados.
|
||||
- **`src/utilities/content/contentPiecePageData.ts`**: `linkFailureReason` **só** no `contentPieceDetailSelect` (`:47-56`) — a lista segue sem o campo (design "lista limpa").
|
||||
- **`src/collections/ContentPiece.ts`**: campo `linkFailureReason` (select, readOnly, descrição admin "Por que uma peça do Instagram ficou só como link; preenchido pelo processamento").
|
||||
- **Migration:** `20260924_<HHMMSS>_add_content_piece_link_failure_reason` (D1) + `payload-types.ts` regenerado.
|
||||
- **UI — `[id]/page.tsx` (ficha, Impeccable B, sem tela nova):** para `origin === 'instagram' && processando`: placeholder "Buscando a mídia no perfil oficial…" (enquanto `!hasFile`), caixa de progresso "Procurando a publicação no perfil oficial…" e card "Processamento da peça" com os 3 passos desenhados (Link recebido / Mídia oficial / Catalogação; estados Concluído/Em andamento/Aguardando derivados do `step` existente — `extraindo` = mídia oficial; `transcrevendo|catalogando|salvando` = catalogação); para `origin !== 'arquivo' && pronto && hasFile`: card verde "Arquivo e transcrição prontos"/"Arquivo pronto" com copy honesta; para `!hasFile && linkFailureReasonLabel`: card do motivo (título "Por que o arquivo não foi baixado", literal verbatim, "A peça continua disponível pelo link.", reusando `ContentPieceAttachFileButton`) **no lugar** do card genérico atual (`:165-173`), que permanece para peça-link sem motivo (YouTube/legado). `falhou` e demais estados ficam como estão. `ContentPieceStatusRefresher` intocado (a transição `pronto` já dispara o refresh).
|
||||
- **UI — `ContentPieceCardList.tsx`:** linha meta dos cards mobile ganha o rótulo neutro desenhado: `origin !== 'arquivo'` ⇒ prefixa a origem; `pronto && !hasFile` ⇒ "Peça-link" (sem motivo). `ContentPieceTable` fica como está (já mostra a origem).
|
||||
- **Access / Consent:** nada novo — leitura sob o gate existente (`canReadCommunicationCatalog` + access da collection); **sem Consent** (não há PII de eleitor). Nenhum helper de access muda.
|
||||
- **Changelog:** `docs/changelog/2026-09-24-c220.md` (entrada curta; nunca editar o agregado/HISTORY).
|
||||
|
||||
### Dados → forma (se aplicável)
|
||||
|
||||
N/A — não há agregado, KPI ou série; o que muda é o **estado** da peça e um rótulo. Restrição da intenção mantida: motivo em linguagem de produto (um dos quatro literais), sem código de erro, stack ou jargão de API.
|
||||
|
||||
## Fases verificáveis
|
||||
|
||||
1. **Tracer / schema+server — quota ~50%:** migration + campo + vocabulário em `lib/contentPiece.ts`; `parseContentPieceLink` prefixado (unit verde); paginação de cursor em `instagramFeed.ts` (unit verde); resolver com motivo + persist do refresh; job/attach/retry. **Tracer bullet cedo:** int do resolver com `loadFeed` fake casando `/depjorgesolla/reel/ABC/` → `contentMedia` criada, motivo `null`; e sem match → `nao-encontrado`, linha `pronto`. Só então a UI.
|
||||
2. **UI — quota ~30%:** ficha (processando com passos, sucesso, motivo) + rótulo neutro na card list; e2e do motivo (fixture, sem job).
|
||||
3. **Gates — quota ~20%:** `pnpm gate:fast` (lint + typecheck + unit); `pnpm test:int` (suíte cheia); e2e curado (`campaignSpeechAcervo`, com a seção C211 do spec); `pnpm push` via GitHub.
|
||||
|
||||
### Testes previstos
|
||||
|
||||
- **`tests/unit/contentPiece.unit.spec.ts`:** parse aceita `/depjorgesolla/reel/ABC/` e `/depjorgesolla/p/ABC/?igsh=…` com o mesmo canônico de `/reel/ABC/`; rejeita `/stories/…`, `/stories/reel/ABC/`, `instagr.am`, perfil sem kind, host fora; labels dos 4 motivos **verbatim**; `toContentPieceViewModel` mapeia motivo conhecido → literal e desconhecido → `null`, sem alterar `failureMessage`.
|
||||
- **`tests/unit/instagramFeed.unit.spec.ts`:** `parseInstagramMediaPage` (cursor presente/ausente/malformado); paginação real (2–3 páginas, `after=` na página 2, para em `maxResults`, erro na página 2 ⇒ 1 refresh e refaz a janela); `maxResults ≤ 50` ⇒ **1** chamada de mídia (board intacto); atualizar o teste do cap (`:252-258`) para pinar janela × página.
|
||||
- **`tests/int/contentPiece.int.spec.ts` — resolver (deps injetadas, sem rede):** global configurado + `loadFeed` fake + `fetchImpl` fake: match por shortcode baixa e cria `contentMedia` (motivo `null`); sem match ⇒ `nao-encontrado`; carrossel ⇒ `carrossel`; sem credencial ⇒ `sem-credencial`; `loadFeed` lançando ⇒ `indisponivel`; download HTTP 500 ⇒ `indisponivel`; download acima do teto ⇒ lança (não vira motivo).
|
||||
- **`tests/int/contentPiece.int.spec.ts` — job/collection:** `resolveSource` injetado com motivo ⇒ linha `pronto` + `linkFailureReason`; com mídia ⇒ motivo `null`; origem YouTube ⇒ motivo `null`; `attachContentPieceMedia` limpa o motivo; retry limpa ao reiniciar.
|
||||
- **e2e (benefício real, determinístico):** na seção C211 de `tests/e2e/campaignSpeechAcervo.e2e.spec.ts`, fixture peça-link com motivo (`carrossel`) ⇒ a ficha contém o literal e "Anexar arquivo original"; a lista **não** contém o literal (pina "lista limpa"). Sem depender do job assíncrono.
|
||||
- **Pins:** `tests/unit/instagramFeed.unit.spec.ts` (contrato janela/página); `scripts/lib/e2e-affected-manifest.mjs` **sem mudança** (o diff toca `src/utilities/content`, `src/components/campaign/content` e `src/lib/contentPiece` — mapeados para `campaignSpeechAcervo`; `src/utilities/socialFeed` não é prefixo de risco e cai no smoke `campaignHomeActions`).
|
||||
|
||||
## Rabbit holes / Não escopo (engenharia)
|
||||
|
||||
- **Varredura agendada/webhook/cursor próprio/backfill em massa** — item próprio (C212 §Q4); aqui só o link colado é procurado.
|
||||
- **Scraping, oEmbed, segundo fetch e download de mídia de terceiro** — permanente; o resultado é motivo honesto + anexar arquivo.
|
||||
- **Carrossel vira álbum** (baixar filhos, montar capa) — não; motivo `carrossel`.
|
||||
- **Retry de peça-link com motivo** ("Instagram indisponível" transitório): não há affordance hoje (`canRetry` só `falhou`) e o design não desenha; **gatilho:** se a assessoria pedir "tentar de novo" numa peça-link, item curto + designer.
|
||||
- **`paging.next` absoluto** (token na URL) — ignorado; só cursor. **Paginação time-based (`since/until`)** — não implementada; se for a única do host, a janela degrada para 50 com motivo honesto (item próprio se acontecer).
|
||||
- **Novo painel/tela de credencial** — `SocialFeedSettings` é o dono; falta de credencial é motivo na ficha.
|
||||
- **Motivo na lista/segundo selo/segunda tela; backfill de motivo em peças antigas; preview/poster da mídia extraída** — fora.
|
||||
- **Tocar snapshot/cache/kill switch/lock do board** — proibido; o único ponto compartilhado é o cliente `instagramFeed.ts`, com default de 1 página.
|
||||
|
||||
## Débitos do `/simplify` (deferidos com gatilho)
|
||||
|
||||
Triagem da sessão (nada registrado como Issue: nenhum `expensive_lock` ≥4):
|
||||
|
||||
- **D-1 — dono puro dos passos e do predicado "peça-link".** `processingSteps`/rótulos de design inline na ficha (`[id]/page.tsx:65-95`), predicado "peça-link" re-derivado em 4+ pontos, e `mediaStepDone = step !== 'extraindo'` dizendo "Mídia oficial: Concluído" sem mídia. **Gatilho:** próximo toque da ficha/UI de processamento (corrigir o `mediaStepDone` exigindo `hasFile` junto).
|
||||
- **D-2 — VM de linha × select da lista.** `linkFailureReason`/label sempre `null` nas linhas porque o select da lista não carrega o campo (omissão intencional por D7). **Gatilho:** a lista precisar do motivo (hoje proibido) ou o VM de linha separar-se do da ficha.
|
||||
- **D-3 — helper/restauro nos testes int.** Repetição de `withTempDir(resolveContentPieceSource(...))` e `setInstagramSettings(false)` sem restauro em `contentPiece.int.spec.ts`. **Gatilho:** próximo toque do spec (pode pegar carona no F3 do `escala-dry-pos-c211` #1267).
|
||||
- **Descartados:** wrapper `parseInstagramMediaResponse` (decisão D2: conveniência de leitura de 1 página) e a consolidação dos describes duplicados do parser (cosmético, sem risco).
|
||||
|
||||
## Riscos e mitigação
|
||||
|
||||
- **Forma da paginação no host do Instagram Login "a confirmar" (C212):** cursor ausente ⇒ 1 página e motivo honesto, sem quebra; verificação viva no staging/produção (a credencial real vive no `SocialFeedSettings` de produção; o staging pode não tê-la — registrar no runbook do token).
|
||||
- **`instagramFeed.ts` é dono compartilhado com o board:** `maxResults ≤ 50` ⇒ exatamente 1 página; testes do board (user/media/refresh/abort) passam sem mudança; o diff acorda o smoke da home no CI.
|
||||
- **Motivo obsoleto (extração posterior):** um escritor (job) + limpeza no anexo e no retry; testes int dedicados.
|
||||
- **Clobber de curadoria:** o motivo é campo de sistema, fora de `CONTENT_PIECE_CURATED_FIELDS`; o write final do job (releitura fresca + transação) segue igual.
|
||||
- **Token em log/URL:** `paging.next` ignorado; nenhuma URL com `access_token` é logada/armazenada; erros tipados não carregam URL.
|
||||
- **Janela/limite mentindo:** o literal fala "mídias recentes"; a janela é declarada no código (500) e neste plano — sem promessa de "todas as mídias".
|
||||
- **Download parcial/temp órfão:** mídia só nasce após o arquivo completo; `tempDir` removido no `finally` (`contentPieceJob.ts:307-309`).
|
||||
- **Appetite:** o maior custo é a UI da ficha; a ordem (motivo → extração → polimento de passos) deixa o aceite coberto mesmo se o polimento atrasar.
|
||||
- **CI:** diff mapeado para e2e de comunicação + smoke da home — nunca zero; rodar `gate:fast` e int local antes do push.
|
||||
|
||||
## Aceite de engenharia
|
||||
|
||||
- [ ] Aceite de produto da intenção ainda coberto: link do próprio perfil (canônico e prefixado) extrai e cataloga; janela declarada com motivo honesto além dela; os 4 motivos verbatim na ficha; peça-link nunca apagada e "Anexar arquivo original" disponível; curadoria preservada; YouTube link-only sem motivo; só caminho oficial, sem terceiro, sem scraping, token nunca em log; board intocado.
|
||||
- [ ] Invariantes AGENTS/engineering-standards: Local API com `user` + `overrideAccess: false` (bypass só com comentário já justificado no pipeline); writes novos seguem um único dono (job/attach com transação onde há multi-write; token via raw SQL do owner); Consent sem chave nova; identificadores em inglês/copy pt-BR; `lib/` não importa `utilities/`; migration nova (nada retroativo) + `pnpm migrate` + `generate:types`; `curatedFields` intocado; `sourceUrl` canônico como identidade.
|
||||
- [ ] Testes de domínio previstos (unit/int) onde access/write paths mudam; e2e do motivo (ficha mostra, lista não); pins de teste atualizados.
|
||||
- [ ] `pnpm gate:fast` verde; `pnpm test:int` verde; e2e curado verde; `pnpm push` via GitHub.
|
||||
|
||||
## Self-score
|
||||
|
||||
**Self-score decision-quality: 4/5.** (1) Decisões caras têm `Opções/Recomendação/Rejeitadas` explícitas (campo/migration, janela/paginação, matching, semântica de falha, refresh, ciclo de vida, UI); (2) cabe no appetite herdado — reusa pipeline C211, seam injetável do resolver, helpers do owner do feed e shells da ficha; (3) rabbit holes nomeados (varredura, scraping, álbum, retry de peça-link, `paging.next`, time-based, painel novo, backfill); (4) depth check: paginação fica no dono do cliente Graph API, motivo no dono do vocabulário, persistência num único escritor, attach/retry reusam os escritores existentes — sem pass-through nem twin; (5) aceite de produto intacto. Não 5/5 por duas incertezas honestly assumidas: a forma real da paginação na API (C212 "a confirmar", mitigada por degradação honesta) e o mapeamento de `!mediaUrl` para `indisponivel` (micro-decisão reversível).
|
||||
390
docs/plans/central-conteudos-link-instagram-ui-design.html
Normal file
390
docs/plans/central-conteudos-link-instagram-ui-design.html
Normal file
|
|
@ -0,0 +1,390 @@
|
|||
<!doctype html>
|
||||
<html lang="pt-BR" data-theme="campaign">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
|
||||
<title>Design — C220 · Link do Instagram</title>
|
||||
<style type="text/tailwindcss">
|
||||
@theme {
|
||||
--font-sans: Inter, Arial, sans-serif;
|
||||
--color-background: #fff;
|
||||
--color-foreground: #1c1917;
|
||||
--color-primary: #c51414;
|
||||
--color-muted: #f4f4f5;
|
||||
--color-muted-foreground: #6b7280;
|
||||
--color-border: rgb(28 25 23/0.12);
|
||||
}
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.board {
|
||||
background: #ecebea;
|
||||
background-image: radial-gradient(#d5d1cd 0.7px, transparent 0.7px);
|
||||
background-size: 18px 18px;
|
||||
}
|
||||
.frame {
|
||||
box-shadow: 0 20px 55px rgb(28 25 23/0.12);
|
||||
}
|
||||
.desktop {
|
||||
width: 1280px;
|
||||
}
|
||||
.phone {
|
||||
width: 390px;
|
||||
border-radius: 28px;
|
||||
}
|
||||
.scene:after {
|
||||
content: '';
|
||||
height: 1px;
|
||||
flex: 1;
|
||||
background: #cbc7c2;
|
||||
}
|
||||
.field {
|
||||
min-height: 44px;
|
||||
border: 1px solid #d6d3d1;
|
||||
border-radius: 6px;
|
||||
background: white;
|
||||
padding: 10px 12px;
|
||||
font-size: 14px;
|
||||
}
|
||||
.label {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
border-radius: 999px;
|
||||
padding: 3px 8px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
min-height: 44px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
border-radius: 6px;
|
||||
padding: 9px 14px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.primary {
|
||||
background: #c51414;
|
||||
color: white;
|
||||
}
|
||||
.outline {
|
||||
border: 1px solid #d6d3d1;
|
||||
background: white;
|
||||
}
|
||||
.shell {
|
||||
display: grid;
|
||||
grid-template-columns: 220px 1fr;
|
||||
}
|
||||
.side {
|
||||
background: #fafaf9;
|
||||
border-right: 1px solid rgb(28 25 23/0.12);
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body class="board min-h-screen text-[#1c1917] antialiased">
|
||||
<main class="mx-auto max-w-[1480px] space-y-14 px-4 py-12 md:px-8">
|
||||
<header class="max-w-3xl">
|
||||
<span class="rounded-full bg-[#c51414] px-3 py-1 text-xs font-bold text-white"
|
||||
>C220 · ficha existente</span
|
||||
>
|
||||
<h1 class="mt-4 text-4xl font-bold tracking-tight">O link nunca degrada em silêncio.</h1>
|
||||
<p class="mt-2 text-sm leading-6 text-[#6b7280]">
|
||||
A ficha conta o que está acontecendo, o que foi extraído e por que uma peça ficou apenas
|
||||
como link.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<section>
|
||||
<div class="scene mb-3 flex items-center gap-3 text-xs font-bold text-[#6b7280]">
|
||||
<span>CENA 01</span>
|
||||
<h2>Desktop 1280 · processando → extraída e catalogada</h2>
|
||||
</div>
|
||||
<div class="desktop frame mx-auto overflow-hidden rounded-xl bg-white">
|
||||
<div class="shell min-h-[710px]">
|
||||
<aside class="side p-5">
|
||||
<div class="h-7 w-32 rounded bg-[#c51414]"></div>
|
||||
<nav class="mt-8 space-y-2 text-sm">
|
||||
<div class="rounded-md bg-[#f5f5f4] px-3 py-2 font-semibold">Comunicação</div>
|
||||
<div class="px-3 py-2 text-[#6b7280]">Central de Conteúdos</div>
|
||||
</nav>
|
||||
</aside>
|
||||
<div class="p-8">
|
||||
<a class="text-xs font-semibold text-[#c51414]">← Conteúdos</a>
|
||||
<div class="mt-2 flex items-start justify-between">
|
||||
<div>
|
||||
<h2 class="text-xl font-semibold">Peça adicionada pelo Instagram</h2>
|
||||
<div class="mt-2 flex gap-2">
|
||||
<span class="badge bg-amber-100 text-amber-900">Processando</span
|
||||
><span class="badge bg-[#f4f4f5] text-[#6b7280]">Rascunho</span>
|
||||
</div>
|
||||
</div>
|
||||
<button class="btn outline">Publicar</button>
|
||||
</div>
|
||||
<div class="mt-7 grid grid-cols-[300px_1fr] gap-8">
|
||||
<aside>
|
||||
<div
|
||||
class="grid aspect-video place-items-center rounded-xl border bg-stone-100 text-center text-xs font-semibold text-[#6b7280]"
|
||||
>
|
||||
Buscando a mídia<br />no perfil oficial…
|
||||
</div>
|
||||
<dl class="mt-4 space-y-2 text-xs">
|
||||
<div class="flex justify-between">
|
||||
<dt class="text-[#6b7280]">Origem</dt>
|
||||
<dd>Instagram</dd>
|
||||
</div>
|
||||
<div class="flex justify-between gap-3">
|
||||
<dt class="text-[#6b7280]">Link</dt>
|
||||
<dd class="truncate text-[#c51414]">instagram.com/…/reel/ABC/</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<div class="mt-5 rounded-lg bg-[#f4f4f5] p-3">
|
||||
<div class="h-2 overflow-hidden rounded-full bg-white">
|
||||
<div class="h-full w-1/2 rounded-full bg-[#c51414]"></div>
|
||||
</div>
|
||||
<p class="mt-2 text-xs text-[#6b7280]">
|
||||
Procurando a publicação no perfil oficial…
|
||||
</p>
|
||||
</div>
|
||||
</aside>
|
||||
<div>
|
||||
<div class="rounded-xl border p-5">
|
||||
<p class="text-sm font-semibold">Processamento da peça</p>
|
||||
<ol class="mt-4 grid grid-cols-3 gap-3 text-xs">
|
||||
<li class="rounded-lg border border-green-200 bg-green-50 p-3">
|
||||
<b>1. Link recebido</b>
|
||||
<p class="mt-1 text-green-800">Concluído</p>
|
||||
</li>
|
||||
<li class="rounded-lg border border-amber-200 bg-amber-50 p-3">
|
||||
<b>2. Mídia oficial</b>
|
||||
<p class="mt-1 text-amber-900">Em andamento</p>
|
||||
</li>
|
||||
<li class="rounded-lg border bg-[#f4f4f5] p-3 text-[#6b7280]">
|
||||
<b>3. Catalogação</b>
|
||||
<p class="mt-1">Aguardando</p>
|
||||
</li>
|
||||
</ol>
|
||||
</div>
|
||||
<div class="mt-6 grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<p class="label">Título</p>
|
||||
<div class="field mt-1 text-[#9a9692]">Disponível após a catalogação</div>
|
||||
</div>
|
||||
<div>
|
||||
<p class="label">Tipo</p>
|
||||
<div class="field mt-1 text-[#9a9692]">—</div>
|
||||
</div>
|
||||
<div class="col-span-2">
|
||||
<p class="label">Transcrição / texto</p>
|
||||
<div class="mt-1 h-36 rounded-md border bg-[#fafafa]"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-8 border-t pt-8">
|
||||
<div class="flex items-center gap-3">
|
||||
<span class="badge bg-green-100 text-green-800">Pronto</span
|
||||
><b class="text-sm">Estado final — mídia extraída</b>
|
||||
</div>
|
||||
<div class="mt-4 grid grid-cols-[300px_1fr] gap-8">
|
||||
<div>
|
||||
<div
|
||||
class="grid aspect-video place-items-center rounded-xl bg-stone-200 text-[11px] font-bold text-stone-500"
|
||||
>
|
||||
NEEDS ASSET · PREVIEW REAL
|
||||
</div>
|
||||
<button class="btn outline mt-3 w-full">↓ Baixar arquivo</button>
|
||||
</div>
|
||||
<div class="rounded-xl border border-green-200 bg-green-50 p-5">
|
||||
<h3 class="font-semibold text-green-900">Arquivo e transcrição prontos</h3>
|
||||
<p class="mt-1 text-sm leading-6 text-green-900/80">
|
||||
A mídia oficial foi baixada e a ficha foi catalogada. Revise os campos antes
|
||||
de publicar.
|
||||
</p>
|
||||
<div class="mt-4 rounded-md border border-green-200 bg-white p-3 text-sm">
|
||||
“Transcrição gerada aparece aqui para revisão editorial.”
|
||||
</div>
|
||||
<button class="btn primary mt-4">Salvar alterações</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<div class="scene mb-3 flex items-center gap-3 text-xs font-bold text-[#6b7280]">
|
||||
<span>CENA 02</span>
|
||||
<h2>Peça-link · motivo honesto e caminho para anexar o original</h2>
|
||||
</div>
|
||||
<div class="desktop frame mx-auto rounded-xl bg-white p-8">
|
||||
<div class="flex items-start justify-between">
|
||||
<div>
|
||||
<a class="text-xs font-semibold text-[#c51414]">← Conteúdos</a>
|
||||
<h2 class="mt-2 text-xl font-semibold">Peça adicionada pelo Instagram</h2>
|
||||
<div class="mt-2 flex gap-2">
|
||||
<span class="badge bg-green-100 text-green-800">Pronto</span
|
||||
><span class="badge bg-[#f4f4f5] text-[#6b7280]">Rascunho</span>
|
||||
</div>
|
||||
</div>
|
||||
<button class="btn outline">Publicar</button>
|
||||
</div>
|
||||
<div class="mt-7 grid grid-cols-[300px_1fr] gap-8">
|
||||
<aside>
|
||||
<div
|
||||
class="grid aspect-video place-items-center rounded-xl border bg-stone-100 text-xs font-semibold text-[#6b7280]"
|
||||
>
|
||||
Peça-link
|
||||
</div>
|
||||
<div class="mt-5 rounded-lg border border-amber-200 bg-amber-50 p-4">
|
||||
<p class="text-xs font-semibold text-amber-950">
|
||||
A peça continua disponível pelo link
|
||||
</p>
|
||||
<p class="mt-1 text-xs leading-5 text-amber-900">
|
||||
A mídia não foi baixada. Você pode revisar a ficha ou anexar o arquivo original.
|
||||
</p>
|
||||
<button class="btn outline mt-3 w-full">⌕ Anexar arquivo original</button>
|
||||
</div>
|
||||
</aside>
|
||||
<div>
|
||||
<h3 class="text-sm font-semibold">Motivo da peça-link</h3>
|
||||
<p class="mt-1 text-xs text-[#6b7280]">
|
||||
A ficha mostra um destes quatro motivos, sem código de erro nem jargão técnico.
|
||||
</p>
|
||||
<div class="mt-4 grid grid-cols-2 gap-3 text-sm">
|
||||
<div class="rounded-lg border p-4">
|
||||
<span class="badge bg-amber-100 text-amber-900">Motivo</span>
|
||||
<p class="mt-2 font-medium">
|
||||
Link não encontrado entre as mídias recentes do perfil
|
||||
</p>
|
||||
</div>
|
||||
<div class="rounded-lg border p-4">
|
||||
<span class="badge bg-amber-100 text-amber-900">Motivo</span>
|
||||
<p class="mt-2 font-medium">Carrossel: sem arquivo único para baixar</p>
|
||||
</div>
|
||||
<div class="rounded-lg border p-4">
|
||||
<span class="badge bg-amber-100 text-amber-900">Motivo</span>
|
||||
<p class="mt-2 font-medium">Instagram indisponível no momento</p>
|
||||
</div>
|
||||
<div class="rounded-lg border p-4">
|
||||
<span class="badge bg-amber-100 text-amber-900">Motivo</span>
|
||||
<p class="mt-2 font-medium">Sem credencial do Instagram configurada</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-5 rounded-lg bg-[#f4f4f5] p-4 text-xs leading-5 text-[#6b7280]">
|
||||
Mídia de terceiro nunca é baixada. Esta peça não foi apagada e continua circulando
|
||||
pelo link.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<div class="scene mb-3 flex items-center gap-3 text-xs font-bold text-[#6b7280]">
|
||||
<span>CENA 03</span>
|
||||
<h2>Mobile 390 · estados essenciais na ficha e lista compacta</h2>
|
||||
</div>
|
||||
<div class="flex flex-wrap justify-center gap-8">
|
||||
<div class="phone frame min-h-[780px] overflow-hidden bg-white">
|
||||
<header class="flex h-14 items-center justify-between border-b px-4">
|
||||
<b>Central de Conteúdos</b><span>☰</span>
|
||||
</header>
|
||||
<div class="p-4">
|
||||
<a class="text-xs font-semibold text-[#c51414]">← Conteúdos</a>
|
||||
<h2 class="mt-2 text-lg font-semibold">Peça adicionada pelo Instagram</h2>
|
||||
<div class="mt-2 flex gap-2">
|
||||
<span class="badge bg-amber-100 text-amber-900">Processando</span
|
||||
><span class="badge bg-[#f4f4f5] text-[#6b7280]">Rascunho</span>
|
||||
</div>
|
||||
<div
|
||||
class="mt-5 grid aspect-video place-items-center rounded-xl border bg-stone-100 text-xs text-[#6b7280]"
|
||||
>
|
||||
Buscando mídia oficial…
|
||||
</div>
|
||||
<div class="mt-4 rounded-lg bg-[#f4f4f5] p-3">
|
||||
<div class="h-2 rounded-full bg-white">
|
||||
<div class="h-full w-1/2 rounded-full bg-[#c51414]"></div>
|
||||
</div>
|
||||
<p class="mt-2 text-xs text-[#6b7280]">
|
||||
Procurando a publicação no perfil oficial…
|
||||
</p>
|
||||
</div>
|
||||
<div class="mt-5 space-y-3">
|
||||
<div class="h-11 rounded-md border"></div>
|
||||
<div class="h-24 rounded-md border"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="phone frame min-h-[780px] overflow-hidden bg-white">
|
||||
<header class="flex h-14 items-center justify-between border-b px-4">
|
||||
<b>Central de Conteúdos</b><span>☰</span>
|
||||
</header>
|
||||
<div class="p-4">
|
||||
<a class="text-xs font-semibold text-[#c51414]">← Conteúdos</a>
|
||||
<h2 class="mt-2 text-lg font-semibold">Peça adicionada pelo Instagram</h2>
|
||||
<div class="mt-2 flex gap-2">
|
||||
<span class="badge bg-green-100 text-green-800">Pronto</span
|
||||
><span class="badge bg-[#f4f4f5] text-[#6b7280]">Rascunho</span>
|
||||
</div>
|
||||
<div
|
||||
class="mt-5 grid aspect-video place-items-center rounded-xl border bg-stone-100 text-xs text-[#6b7280]"
|
||||
>
|
||||
Peça-link
|
||||
</div>
|
||||
<div class="mt-4 rounded-lg border border-amber-200 bg-amber-50 p-4">
|
||||
<p class="text-xs font-semibold text-amber-950">
|
||||
Por que o arquivo não foi baixado
|
||||
</p>
|
||||
<p class="mt-2 text-sm font-medium text-amber-950">
|
||||
Carrossel: sem arquivo único para baixar
|
||||
</p>
|
||||
<p class="mt-2 text-xs leading-5 text-amber-900">
|
||||
A peça continua disponível pelo link.
|
||||
</p>
|
||||
<button class="btn outline mt-4 w-full">⌕ Anexar arquivo original</button>
|
||||
</div>
|
||||
<button class="btn primary mt-6 w-full">Salvar alterações</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="phone frame min-h-[560px] overflow-hidden bg-white">
|
||||
<header class="flex h-14 items-center justify-between border-b px-4">
|
||||
<b>Conteúdos</b><span>☰</span>
|
||||
</header>
|
||||
<div class="space-y-3 p-4">
|
||||
<article class="rounded-xl border p-4">
|
||||
<div class="flex justify-between gap-3">
|
||||
<b class="text-sm">Peça adicionada pelo Instagram</b
|
||||
><span class="badge shrink-0 bg-amber-100 text-amber-900">Processando</span>
|
||||
</div>
|
||||
<p class="mt-2 text-xs text-[#6b7280]">Instagram · Preparando a peça…</p>
|
||||
<div class="mt-3 h-2 rounded-full bg-[#f4f4f5]">
|
||||
<div class="h-full w-1/2 rounded-full bg-[#c51414]"></div>
|
||||
</div>
|
||||
<button class="btn outline mt-3 w-full">Abrir</button>
|
||||
</article>
|
||||
<article class="rounded-xl border p-4">
|
||||
<div class="flex justify-between gap-3">
|
||||
<b class="text-sm">Peça adicionada pelo Instagram</b
|
||||
><span class="badge shrink-0 bg-green-100 text-green-800">Pronto</span>
|
||||
</div>
|
||||
<p class="mt-2 text-xs text-[#6b7280]">Instagram · Peça-link</p>
|
||||
<button class="btn outline mt-3 w-full">Abrir</button>
|
||||
</article>
|
||||
<p class="px-2 text-center text-[11px] leading-4 text-[#6b7280]">
|
||||
Recomendação: a lista continua limpa; o motivo completo vive na ficha.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
112
docs/plans/central-conteudos-link-instagram.md
Normal file
112
docs/plans/central-conteudos-link-instagram.md
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
# C220 — Central de Conteúdos — link do Instagram do deputado baixa e cataloga a peça
|
||||
|
||||
Status: rascunho
|
||||
Atualizado em: 2026-09-23
|
||||
Issue: #1302
|
||||
Priority: P1
|
||||
Impeccable: B — encaixe na lista/ficha existentes do C211 (estado honesto), sem tela nova
|
||||
Design UI: docs/plans/central-conteudos-link-instagram-ui-design.html
|
||||
Appetite: ~1,5–2 dias eng; um outcome verificável — link do próprio perfil deixa de degradar em silêncio
|
||||
Responsável: —
|
||||
|
||||
## Intenção
|
||||
|
||||
A assessoria de comunicação colou na Central de Conteúdos (`/campanha/comunicacao/conteudos`) o link de uma peça do **próprio** Instagram do deputado e a peça não foi baixada nem analisada: virou uma "peça-link" em silêncio. A promessa do fluxo — decidida no gate e registrada no C212 — é que peça adicionada por link tenha a mídia extraída e catalogada quando houver caminho oficial. O caminho oficial existe (Graph API da própria conta) e o pipeline existe; o que faltou foi o link do próprio perfil ser encontrado e resolvido. Este item conserta essa quebra.
|
||||
|
||||
## Persona e fluxo
|
||||
|
||||
- **Persona / contexto:** assessoria de comunicação (`communicator`) na mesa, operando a Central, colando links das peças do perfil oficial (@depjorgesolla) que acabaram de sair.
|
||||
- **Job principal:** colar o link de uma peça do próprio Instagram e receber a peça baixada, transcrita e catalogada — como se tivesse enviado o arquivo.
|
||||
- **Fluxo desejado:** cola o link → a peça nasce "Processando" → o post é procurado no perfil oficial → achou e é extraível: arquivo baixado, transcrito e catalogado → não achou/não extraível: peça-link **com motivo honesto na ficha** → assessoria revisa/edita ou anexa o arquivo; nada é apagado.
|
||||
- **Anti-goals de produto:** não vira varredura automática do perfil; não vira tela nova nem segundo fluxo de configuração; não vira scraping/contorno; não baixa mídia de terceiro; não apaga peça-link; não encosta no board da home.
|
||||
|
||||
### Esboço de fluxo (B)
|
||||
|
||||
```text
|
||||
[Central] → "Adicionar por link" → cola link do próprio perfil
|
||||
(ex.: instagram.com/depjorgesolla/reel/ABC/ · .../reel/ABC/?igsh=… · .../p/ABC/)
|
||||
→ peça "Processando" → busca o post no perfil oficial (além das 50 mais recentes)
|
||||
→ achou + extraível: baixa o arquivo → transcreve → cataloga (igual ao envio por arquivo)
|
||||
→ não achou / não extraível: peça-link com motivo na ficha
|
||||
("Link não encontrado…" · "Carrossel…" · "Instagram indisponível…" · "Sem credencial…")
|
||||
→ revisa, edita, anexa o arquivo se quiser — a peça nunca é apagada
|
||||
[outcome: link do próprio perfil vira peça baixada e catalogada — ou falha com motivo, nunca em silêncio]
|
||||
```
|
||||
|
||||
### Design UI (B)
|
||||
|
||||
- Design UI (gate): `docs/plans/central-conteudos-link-instagram-ui-design.html`
|
||||
|
||||
## Objetivo e aceite
|
||||
|
||||
- Colar um link do próprio perfil — nas formas que o browser copia — resulta em peça com mídia baixada, transcrita e catalogada, igual ao envio por arquivo.
|
||||
- A busca pelo post colado não para na janela atual: vai para trás o suficiente para o uso real, com limite declarado; post além do limite recebe motivo honesto (não silêncio).
|
||||
- Quando a extração não acontecer, a ficha mostra o motivo em linguagem de produto (vocabulário literal abaixo). Peça-link é resultado legítimo, não "Falhou".
|
||||
- Peça-link continua fallback: circula pelo link, o arquivo original pode ser anexado e a peça nunca é apagada.
|
||||
- Curadoria preservada: campos que a assessoria editou não são sobrescritos pela catalogação.
|
||||
- **Guardrails:** extração só por caminho oficial (Graph API da própria conta) — nunca scraping/contorno; mídia de terceiro nunca é baixada; token nunca em log; o contrato do feed/board da home (cache de 5 min, snapshot, kill switch) não é reusado nem alterado; YouTube segue link-only por desenho (a Data API não entrega arquivo) — sem motivo de falha.
|
||||
|
||||
## Dados (intenção)
|
||||
|
||||
- **Vou apresentar dados?** Não — não há agregado nem KPI; o que muda é o estado da peça e o motivo visível na ficha.
|
||||
- **Decisões desbloqueadas:** N/A — a decisão da assessoria é editorial/operacional ("anexar o arquivo original?"), não numérica.
|
||||
- **Forma:** N/A — restrição: motivo em linguagem de produto, sem código de erro, stack ou jargão de API.
|
||||
|
||||
## Dados da decisão (literais)
|
||||
|
||||
- **Decisão do gate (C212, verbatim):** "Quando o assessor adiciona uma peça por link do Instagram ou Youtube, a mídia deve ser automaticamente extraída e catalogada." — com o corte do C211: **quando houver caminho oficial**.
|
||||
- **Motivos (verbatim):** "Link não encontrado entre as mídias recentes do perfil" · "Carrossel: sem arquivo único para baixar" · "Instagram indisponível no momento" · "Sem credencial do Instagram configurada".
|
||||
- **Formas de link aceitas:** `instagram.com` com `p|reel|reels|tv` + shortcode, com ou sem `www.`/`m.`, query ignorada (`?igsh=` ok) e **caminho prefixado pelo perfil** (`/depjorgesolla/reel/<shortcode>/`, `/depjorgesolla/p/<shortcode>/`); rejeitar `/stories/`, `instagr.am` e hosts fora de Instagram/YouTube (como hoje).
|
||||
- **Fallback:** peça-link permanece, com aviso na ficha; "Mídia de terceiro nunca é baixada"; o arquivo original pode ser anexado pela assessoria; a peça nunca é apagada.
|
||||
|
||||
## Direção no codebase (hipótese)
|
||||
|
||||
- **Áreas prováveis:** resolução do link `src/utilities/content/contentPieceLink.ts`; job `src/utilities/content/contentPieceJob.ts`; parse `src/lib/contentPiece.ts`; feed `src/utilities/socialFeed/instagramFeed.ts`; action `src/app/(campaign)/campanha/actions/contentPieces.ts`; lista/ficha em `src/components/campaign/content/` e `.../comunicacao/conteudos/[id]/page.tsx`.
|
||||
- **Fatos verificados (a revalidar):** hoje degradam para peça-link sem erro nem motivo — origem ≠ Instagram, parse falho, credencial ausente, `loadInstagramFeed` lançando, post fora da janela de 50, carrossel/sem `mediaUrl`; o job termina "Pronto" (`contentPieceJob.ts:278`). O parse rejeita caminho prefixado pelo perfil (`src/lib/contentPiece.ts:352-407`). Não há paginação no repo (`INSTAGRAM_MAX_RESULTS_CAP=50`). Falha depois de um match/download já vira "Falhou" com mensagem.
|
||||
- **Precedente a olhar:** `docs/plans/central-conteudos-varredura-instagram.md` (C212 §Q1/Q2/Q4 — limites e regra de terceiro) e `downloadSource` (`src/utilities/speech/speechMediaPipeline.ts`) como download remoto→mídia.
|
||||
- **Risco de acoplamento:** não reusar o caminho do sync do board (lock transacional do hook, snapshot, kill switch, cache de 5 min); o `sourceUrl` canônico é a identidade (não criar peça gêmea); `curatedFields` da assessoria não podem ser sobrescritos; nada de import que feche ciclo.
|
||||
|
||||
## Dependências
|
||||
|
||||
- **Dura: C211 (#1254)** — o fluxo de link, a ficha e o pipeline existem; este item corrige o comportamento (defeito).
|
||||
- **Soft: C212 (#1256, entregue)** — os achados (janela de 50 sem paginação, `media_url`, regra de terceiro) são a base da decisão.
|
||||
- Credencial do Instagram já governada pelo `SocialFeedSettings` (admin-only) — a ausência dela vira motivo honesto, não tela nova.
|
||||
|
||||
## Fora de escopo
|
||||
|
||||
- Varredura agendada do perfil (webhook + reconciliação + cursor próprio) — recomendação do C212 §Q4; vira item próprio se produto quiser.
|
||||
- oEmbed/embed de terceiro (C211-FOLLOWUP-OEMBED, #1263) e download/persistência de mídia de terceiro (permanente).
|
||||
- Backfill/reprocessamento em massa de peças-link antigas — item próprio, se produto quiser; "anexar arquivo" segue como caminho.
|
||||
- Montar carrossel/álbum a partir dos filhos; redesenhar feed/board da home; nova tela ou novo estado de sync.
|
||||
|
||||
## Rabbit holes de produto
|
||||
|
||||
- **"Já que vai paginar, varre o perfil inteiro".** Se alguém "só completar": webhook, agendador, cursor e painel de status. **Corte neste item:** só o link colado é procurado; a varredura é outro item (C212 §Q4).
|
||||
- **"A API não achou → scraping/yt-dlp".** Se alguém "só completar": crawler e download de terceiro. **Corte:** nunca; o resultado é motivo honesto + anexar arquivo.
|
||||
- **"Carrossel vira álbum".** Se alguém "só completar": baixar cada filho, montar álbum, inventar capa. **Corte:** carrossel fica peça-link com motivo.
|
||||
- **"Reprocessar todo o acervo".** Se alguém "só completar": job em massa sobre peças-link antigas. **Corte:** o fix vale para colagens novas; o resto é item próprio.
|
||||
- **"Consertar o token/tela de config".** Se alguém "só completar": novo painel de credencial. **Corte:** `SocialFeedSettings` já é o dono; falta de credencial é motivo na ficha.
|
||||
|
||||
## Questões em aberto (produto)
|
||||
|
||||
- **Até onde a busca pelo post deve ir para trás?** **Opções:** A) paginação limitada (tudo dentro de uma janela declarada) | B) só as N mais recentes | C) só a janela atual (50). **Recomendação:** A, com motivo honesto quando o post estiver além da janela. _(assumido — validar com produto)_
|
||||
- **O que o operador vê quando a extração falha?** **Opções:** A) motivo só na ficha | B) motivo na ficha + selo na lista. **Recomendação:** A — a lista mantém o estado atual (evita ruído novo); o detalhe é onde a decisão acontece. _(assumido — validar com produto)_
|
||||
- **Aceitar também links prefixados pelo perfil e outras grafias?** **Opções:** A) sim, as grafias que o copiar-e-colar do browser produz | B) só a forma canônica atual. **Recomendação:** A — nunca aceitar stories/terceiros; o que muda é só a grafia do próprio post. _(assumido — validar com produto)_
|
||||
|
||||
## Referências
|
||||
|
||||
- GitHub Issue — a registrar com `pnpm agent:register`.
|
||||
- Design UI (gate): `docs/plans/central-conteudos-link-instagram-ui-design.html` (+ assets em `central-conteudos-link-instagram-ui-design-assets/`)
|
||||
- Planos irmãos: `docs/plans/central-conteudos-ingestao.md` (C211) · `docs/plans/central-conteudos-varredura-instagram.md` (C212)
|
||||
- Arquivos-pista: `src/utilities/content/contentPieceLink.ts` · `src/utilities/content/contentPieceJob.ts` · `src/lib/contentPiece.ts` · `src/utilities/socialFeed/instagramFeed.ts` · `src/app/(campaign)/campanha/actions/contentPieces.ts` · `src/components/campaign/content/AddContentPieceLinkDialog.tsx` · `src/components/campaign/content/ContentPieceCardList.tsx` · `src/app/(campaign)/campanha/(app)/comunicacao/conteudos/[id]/page.tsx`
|
||||
- `AGENTS.md` — guardrails de campanha (sem scraping, sem credencial em log) e convenções de UI/nav
|
||||
|
||||
## Self-score (shaping)
|
||||
|
||||
1. Fatia = um outcome verificável? **Sim** — link do próprio perfil deixa de degradar em silêncio (baixa e cataloga, ou explica).
|
||||
2. Appetite declarado e a intenção cabe? **Sim** (~1,5–2 dias; varredura, backfill e scraping cortados).
|
||||
3. Persona + job + aceite claros sem jargão de stack? **Sim**.
|
||||
4. Direção no codebase é hipótese? **Sim** — áreas e fatos como pista, sem contrato técnico.
|
||||
5. Zero decisões duras de engenharia no plano? **Sim** — paginação, armazenamento do motivo e shape ficam no plano de implementação.
|
||||
|
||||
**Score: 5/5.**
|
||||
559
docs/plans/central-conteudos-secao-home-ui-design.html
Normal file
559
docs/plans/central-conteudos-secao-home-ui-design.html
Normal file
|
|
@ -0,0 +1,559 @@
|
|||
<!doctype html>
|
||||
<html lang="pt-BR" data-theme="campaign-site">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
|
||||
<title>Design — S39 · Central local na home</title>
|
||||
<style type="text/tailwindcss">
|
||||
@theme {
|
||||
--font-sans: Arimo, Arial, sans-serif;
|
||||
}
|
||||
:root {
|
||||
--red: #a21c1c;
|
||||
--dark: #47130e;
|
||||
--yellow: #ffe607;
|
||||
--cream: #fff8f2;
|
||||
--band: #ebe9e9;
|
||||
--surface: #f9faff;
|
||||
--muted: #6c615e;
|
||||
--line: rgb(0 0 0/0.12);
|
||||
--display: 'Exo 2', 'Arial Black', sans-serif;
|
||||
}
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.display {
|
||||
font-family: var(--display);
|
||||
}
|
||||
.board {
|
||||
background: #dedbd8;
|
||||
background-image: radial-gradient(rgb(24 78 146/0.09) 0.7px, transparent 0.7px);
|
||||
background-size: 18px 18px;
|
||||
}
|
||||
.frame {
|
||||
box-shadow: 0 22px 60px rgb(39 25 22/0.13);
|
||||
}
|
||||
.desktop {
|
||||
width: 1280px;
|
||||
}
|
||||
.phone {
|
||||
width: 390px;
|
||||
border-radius: 28px;
|
||||
}
|
||||
.scene:after {
|
||||
content: '';
|
||||
height: 1px;
|
||||
flex: 1;
|
||||
background: #c6c1bd;
|
||||
}
|
||||
.preview {
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 14px;
|
||||
background: #fff;
|
||||
box-shadow: 0 8px 24px rgb(71 19 14/0.07);
|
||||
}
|
||||
.asset {
|
||||
position: relative;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: linear-gradient(135deg, #e6e2df, #f7f5f3);
|
||||
color: #77706c;
|
||||
text-align: center;
|
||||
font-size: 10px;
|
||||
font-weight: 800;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
.tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
border-radius: 999px;
|
||||
background: #eef4fb;
|
||||
padding: 4px 8px;
|
||||
color: #184e92;
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
}
|
||||
.local {
|
||||
background: #fff3c4;
|
||||
color: #6b5100;
|
||||
}
|
||||
.cta {
|
||||
display: inline-flex;
|
||||
min-height: 48px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
border-radius: 10px;
|
||||
background: #ffe607;
|
||||
padding: 10px 18px;
|
||||
color: #171000;
|
||||
font-family: var(--display);
|
||||
font-size: 14px;
|
||||
font-weight: 900;
|
||||
box-shadow: 0 4px 0 #cfb900;
|
||||
}
|
||||
.secondary {
|
||||
display: inline-flex;
|
||||
min-height: 36px;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
border-radius: 8px;
|
||||
padding: 6px 8px;
|
||||
color: #a21c1c;
|
||||
font-size: 12px;
|
||||
font-weight: 800;
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 4px;
|
||||
}
|
||||
.surround {
|
||||
border-bottom: 1px solid var(--line);
|
||||
padding: 26px 40px;
|
||||
text-align: center;
|
||||
}
|
||||
.eyebrow {
|
||||
font-size: 12px;
|
||||
font-weight: 900;
|
||||
letter-spacing: 0.1em;
|
||||
text-transform: uppercase;
|
||||
color: #a21c1c;
|
||||
}
|
||||
.skeleton {
|
||||
background: linear-gradient(100deg, #eee 20%, #ddd 38%, #eee 56%);
|
||||
background-size: 220% 100%;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body class="board min-h-screen text-black antialiased">
|
||||
<main class="mx-auto max-w-[1480px] space-y-14 px-4 py-12 md:px-8">
|
||||
<header class="max-w-3xl">
|
||||
<span class="rounded-full bg-[#e4102f] px-3 py-1 text-xs font-bold text-white"
|
||||
>S39 · revisão do gate</span
|
||||
>
|
||||
<h1 class="display mt-4 text-4xl font-black">A peça do lugar da pessoa vem primeiro.</h1>
|
||||
<p class="mt-2 text-sm leading-6 text-[#6c615e]">
|
||||
Até três peças: município → região → recentes. Sem localização, a seção simplesmente
|
||||
mostra recentes — sem erro, prompt surpresa ou espera eterna.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<section>
|
||||
<div class="scene mb-3 flex items-center gap-3 text-xs font-bold text-[#6c615e]">
|
||||
<span>CENA 01</span>
|
||||
<h2>Localizada · desktop 1280 · município, região e complemento recente</h2>
|
||||
</div>
|
||||
<div class="desktop frame mx-auto overflow-hidden rounded-xl bg-white">
|
||||
<div class="surround bg-[#fff8f2]">
|
||||
<p class="eyebrow">Faça parte</p>
|
||||
<h3 class="display mt-1 text-2xl font-black">Mostre que você está com Solla</h3>
|
||||
<div class="mx-auto mt-4 grid max-w-3xl grid-cols-6 gap-3">
|
||||
<div class="h-20 rounded-lg bg-[#ebe9e9]"></div>
|
||||
<div class="h-20 rounded-lg bg-[#ebe9e9]"></div>
|
||||
<div class="h-20 rounded-lg bg-[#ebe9e9]"></div>
|
||||
<div class="h-20 rounded-lg bg-[#ebe9e9]"></div>
|
||||
<div class="h-20 rounded-lg bg-[#ebe9e9]"></div>
|
||||
<div class="h-20 rounded-lg bg-[#ebe9e9]"></div>
|
||||
</div>
|
||||
<p class="mt-3 text-[11px] font-bold text-[#6c615e]">
|
||||
SEÇÃO EXISTENTE · CARDS PERSONALIZÁVEIS
|
||||
</p>
|
||||
</div>
|
||||
<section class="relative overflow-hidden border-b border-black/10 bg-white px-10 py-16">
|
||||
<div class="absolute -top-24 -right-20 size-64 rounded-full bg-[#ffe607]/35"></div>
|
||||
<div class="absolute -bottom-28 -left-24 size-64 rounded-full bg-[#e4102f]/8"></div>
|
||||
<div class="relative mx-auto max-w-[1080px]">
|
||||
<div class="mx-auto max-w-2xl text-center">
|
||||
<p class="eyebrow">Central de Conteúdos</p>
|
||||
<h2 class="display mt-2 text-4xl font-black tracking-tight">
|
||||
Peça voto pra Solla 1313
|
||||
</h2>
|
||||
<p class="mx-auto mt-3 max-w-xl text-base leading-6 text-[#6c615e]">
|
||||
Comece pelo material do seu território e mande para quem você conhece.
|
||||
</p>
|
||||
<div class="mt-3 flex items-center justify-center gap-2">
|
||||
<span class="tag local">⌖ Para seu município</span
|
||||
><span class="text-[11px] text-[#6c615e]">Localização usada só nesta visita</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-9 grid grid-cols-3 gap-6">
|
||||
<article class="preview">
|
||||
<div class="asset aspect-video">NEEDS ASSET · FOTO REAL</div>
|
||||
<div class="p-4">
|
||||
<div class="flex flex-wrap gap-1">
|
||||
<span class="tag">Foto</span><span class="tag local">Do seu município</span>
|
||||
</div>
|
||||
<h3 class="mt-2 font-extrabold">Título da peça local</h3>
|
||||
<p class="mt-1 text-xs text-[#6c615e]">Seu município · Tema</p>
|
||||
<a class="mt-4 inline-block text-xs font-bold text-[#a21c1c]"
|
||||
>Ver esta peça →</a
|
||||
>
|
||||
</div>
|
||||
</article>
|
||||
<article class="preview">
|
||||
<div class="asset relative aspect-video">
|
||||
<span>NEEDS ASSET · POSTER REAL</span
|
||||
><span
|
||||
class="absolute grid size-12 place-items-center rounded-full bg-[#ffe607] text-xl text-black shadow"
|
||||
>▶</span
|
||||
><span
|
||||
class="absolute right-3 bottom-3 rounded bg-black/70 px-2 py-1 text-[10px] text-white"
|
||||
>Tocar para carregar</span
|
||||
>
|
||||
</div>
|
||||
<div class="p-4">
|
||||
<div class="flex flex-wrap gap-1">
|
||||
<span class="tag">Vídeo</span><span class="tag local">Da sua região</span>
|
||||
</div>
|
||||
<h3 class="mt-2 font-extrabold">Título da peça regional</h3>
|
||||
<p class="mt-1 text-xs text-[#6c615e]">Sua região · sem autoplay</p>
|
||||
<a class="mt-4 inline-block text-xs font-bold text-[#a21c1c]"
|
||||
>Ver esta peça →</a
|
||||
>
|
||||
</div>
|
||||
</article>
|
||||
<article class="preview">
|
||||
<div class="asset relative aspect-video">
|
||||
<span>NEEDS ASSET · CAPA REAL</span
|
||||
><span
|
||||
class="absolute grid size-12 place-items-center rounded-full bg-[#ffe607] text-xl text-black shadow"
|
||||
>▶</span
|
||||
>
|
||||
</div>
|
||||
<div class="p-4">
|
||||
<div class="flex flex-wrap gap-1">
|
||||
<span class="tag">Áudio</span><span class="tag">Mais recente</span>
|
||||
</div>
|
||||
<h3 class="mt-2 font-extrabold">Mensagem recente para compartilhar</h3>
|
||||
<p class="mt-1 text-xs text-[#6c615e]">Completa a seleção local</p>
|
||||
<a class="mt-4 inline-block text-xs font-bold text-[#a21c1c]"
|
||||
>Ver esta peça →</a
|
||||
>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
<div class="mt-9 text-center">
|
||||
<a class="cta" href="/conteudos">Ver todas as peças →</a>
|
||||
<p class="mt-3 text-xs text-[#6c615e]">
|
||||
Nenhum card personalizável entra nesta amostra.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<div class="surround bg-[#ebe9e9]">
|
||||
<p class="eyebrow">Apoie e acompanhe</p>
|
||||
<h3 class="display mt-1 text-2xl font-black">Receba as novidades da campanha</h3>
|
||||
<div class="mx-auto mt-5 h-20 max-w-2xl rounded-xl border bg-white"></div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<div class="scene mb-3 flex items-center gap-3 text-xs font-bold text-[#6c615e]">
|
||||
<span>CENA 02</span>
|
||||
<h2>Localizada · mobile 390 · recorte discreto, sem pedir GPS ao carregar</h2>
|
||||
</div>
|
||||
<div class="phone frame mx-auto overflow-hidden bg-white">
|
||||
<div class="border-b bg-[#fff8f2] px-5 py-7 text-center">
|
||||
<p class="eyebrow text-[10px]">Faça parte</p>
|
||||
<h3 class="display mt-1 text-xl font-black">Mostre que você está com Solla</h3>
|
||||
<div class="mt-4 grid grid-cols-3 gap-2">
|
||||
<div class="h-16 rounded bg-[#ebe9e9]"></div>
|
||||
<div class="h-16 rounded bg-[#ebe9e9]"></div>
|
||||
<div class="h-16 rounded bg-[#ebe9e9]"></div>
|
||||
</div>
|
||||
</div>
|
||||
<section class="relative overflow-hidden border-b px-5 py-10">
|
||||
<div class="absolute -top-16 -right-20 size-48 rounded-full bg-[#ffe607]/35"></div>
|
||||
<div class="relative text-center">
|
||||
<p class="eyebrow text-[10px]">Central de Conteúdos</p>
|
||||
<h2 class="display mt-2 text-[30px] font-black leading-[1.05]">
|
||||
Peça voto pra<br />Solla 1313
|
||||
</h2>
|
||||
<p class="mt-3 text-sm leading-5 text-[#6c615e]">
|
||||
Material do seu território para compartilhar.
|
||||
</p>
|
||||
<span class="tag local mt-3">⌖ Para seu município</span>
|
||||
</div>
|
||||
<div class="relative mt-6 space-y-4">
|
||||
<article class="preview grid grid-cols-[124px_1fr]">
|
||||
<div class="asset min-h-36">NEEDS ASSET<br />FOTO REAL</div>
|
||||
<div class="p-4 text-left">
|
||||
<span class="tag local">Do seu município</span>
|
||||
<h3 class="mt-2 text-sm font-extrabold">Título da peça local</h3>
|
||||
<a class="mt-3 block text-xs font-bold text-[#a21c1c]">Ver peça →</a>
|
||||
</div>
|
||||
</article>
|
||||
<article class="preview grid grid-cols-[124px_1fr]">
|
||||
<div class="asset relative min-h-36">
|
||||
<span>NEEDS ASSET<br />POSTER REAL</span
|
||||
><span
|
||||
class="absolute grid size-10 place-items-center rounded-full bg-[#ffe607] text-black"
|
||||
>▶</span
|
||||
>
|
||||
</div>
|
||||
<div class="p-4 text-left">
|
||||
<span class="tag local">Da sua região</span>
|
||||
<h3 class="mt-2 text-sm font-extrabold">Título da peça regional</h3>
|
||||
<p class="mt-1 text-[11px] text-[#6c615e]">Só carrega no toque</p>
|
||||
<a class="mt-3 block text-xs font-bold text-[#a21c1c]">Ver peça →</a>
|
||||
</div>
|
||||
</article>
|
||||
<article class="preview grid grid-cols-[124px_1fr]">
|
||||
<div class="asset min-h-36">NEEDS ASSET<br />CAPA REAL</div>
|
||||
<div class="p-4 text-left">
|
||||
<span class="tag">Mais recente</span>
|
||||
<h3 class="mt-2 text-sm font-extrabold">Mensagem recente</h3>
|
||||
<a class="mt-3 block text-xs font-bold text-[#a21c1c]">Ver peça →</a>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
<a class="cta relative mt-7 w-full" href="/conteudos">Ver todas as peças →</a>
|
||||
<p class="relative mt-3 text-center text-[11px] leading-4 text-[#6c615e]">
|
||||
A localização não é guardada. Cards personalizáveis ficam na seção anterior.
|
||||
</p>
|
||||
</section>
|
||||
<div class="bg-[#ebe9e9] px-5 py-8 text-center">
|
||||
<p class="eyebrow text-[10px]">Apoie e acompanhe</p>
|
||||
<h3 class="display mt-1 text-xl font-black">Receba as novidades</h3>
|
||||
<div class="mt-4 h-20 rounded-xl border bg-white"></div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<div class="scene mb-3 flex items-center gap-3 text-xs font-bold text-[#6c615e]">
|
||||
<span>CENA 03</span>
|
||||
<h2>Sem localização ou fora da Bahia · recentes, sem erro e sem insistência</h2>
|
||||
</div>
|
||||
<div class="grid gap-8 lg:grid-cols-[1fr_390px]">
|
||||
<div class="frame overflow-hidden rounded-xl bg-white">
|
||||
<section class="relative overflow-hidden px-10 py-12">
|
||||
<div class="absolute -top-24 -right-20 size-64 rounded-full bg-[#ffe607]/35"></div>
|
||||
<div class="relative">
|
||||
<div class="mx-auto max-w-2xl text-center">
|
||||
<p class="eyebrow">Central de Conteúdos</p>
|
||||
<h2 class="display mt-2 text-4xl font-black">Peça voto pra Solla 1313</h2>
|
||||
<p class="mt-3 text-base text-[#6c615e]">
|
||||
Veja as peças mais recentes e escolha uma para compartilhar.
|
||||
</p>
|
||||
<span class="tag mt-3">Seleção recente</span>
|
||||
</div>
|
||||
<div class="mt-8 grid grid-cols-3 gap-5">
|
||||
<article class="preview">
|
||||
<div class="asset aspect-video">NEEDS ASSET · PREVIEW REAL</div>
|
||||
<div class="p-4">
|
||||
<span class="tag">Foto</span>
|
||||
<h3 class="mt-2 font-extrabold">Peça recente</h3>
|
||||
</div>
|
||||
</article>
|
||||
<article class="preview">
|
||||
<div class="asset aspect-video">NEEDS ASSET · PREVIEW REAL</div>
|
||||
<div class="p-4">
|
||||
<span class="tag">Vídeo</span>
|
||||
<h3 class="mt-2 font-extrabold">Outra peça recente</h3>
|
||||
</div>
|
||||
</article>
|
||||
<article class="preview">
|
||||
<div class="asset aspect-video">NEEDS ASSET · PREVIEW REAL</div>
|
||||
<div class="p-4">
|
||||
<span class="tag">Áudio</span>
|
||||
<h3 class="mt-2 font-extrabold">Mensagem recente</h3>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
<div class="mt-8 text-center">
|
||||
<a class="cta" href="/conteudos">Ver todas as peças →</a>
|
||||
<div><button class="secondary mt-2">⌖ Usar minha localização</button></div>
|
||||
<p class="text-[11px] text-[#6c615e]">
|
||||
Opcional e secundário. A seção já funciona sem isso.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<div class="phone frame overflow-hidden bg-white">
|
||||
<section class="relative overflow-hidden px-5 py-10 text-center">
|
||||
<div class="absolute -top-16 -right-20 size-48 rounded-full bg-[#ffe607]/35"></div>
|
||||
<div class="relative">
|
||||
<p class="eyebrow text-[10px]">Central de Conteúdos</p>
|
||||
<h2 class="display mt-2 text-[30px] font-black leading-[1.05]">
|
||||
Peça voto pra<br />Solla 1313
|
||||
</h2>
|
||||
<p class="mt-3 text-sm leading-5 text-[#6c615e]">Veja as peças mais recentes.</p>
|
||||
<span class="tag mt-3">Seleção recente</span>
|
||||
<article class="preview mt-6 text-left">
|
||||
<div class="asset aspect-video">NEEDS ASSET · PREVIEW REAL</div>
|
||||
<div class="p-4">
|
||||
<span class="tag">Foto</span>
|
||||
<h3 class="mt-2 font-extrabold">Título da peça recente</h3>
|
||||
<a class="mt-3 block text-xs font-bold text-[#a21c1c]">Ver peça →</a>
|
||||
</div>
|
||||
</article>
|
||||
<a class="cta mt-6 w-full" href="/conteudos">Ver todas as peças →</a
|
||||
><button class="secondary mt-3">⌖ Usar minha localização</button>
|
||||
<p class="text-[11px] leading-4 text-[#6c615e]">
|
||||
Opcional. Sem prompt no carregamento.
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<div class="scene mb-3 flex items-center gap-3 text-xs font-bold text-[#6c615e]">
|
||||
<span>CENA 04</span>
|
||||
<h2>Resolução da localização · transitória, não bloqueia e termina em recentes</h2>
|
||||
</div>
|
||||
<div class="grid gap-6 lg:grid-cols-3">
|
||||
<article class="frame rounded-xl bg-white p-6">
|
||||
<span class="rounded-full bg-[#fff3c4] px-2 py-1 text-[10px] font-black text-[#6b5100]"
|
||||
>INSTANTE INICIAL</span
|
||||
>
|
||||
<h3 class="display mt-3 text-xl font-black">Peça voto pra Solla 1313</h3>
|
||||
<p class="mt-2 text-sm leading-5 text-[#6c615e]">
|
||||
A home já está utilizável. Só esta amostra define a melhor seleção.
|
||||
</p>
|
||||
<div class="mt-5 grid grid-cols-3 gap-2">
|
||||
<div class="skeleton aspect-video rounded-lg"></div>
|
||||
<div class="skeleton aspect-video rounded-lg"></div>
|
||||
<div class="skeleton aspect-video rounded-lg"></div>
|
||||
</div>
|
||||
<p class="mt-4 text-xs font-bold text-[#6c615e]">
|
||||
Sem modal, sem overlay e sem prompt automático.
|
||||
</p>
|
||||
</article>
|
||||
<article class="frame rounded-xl bg-white p-6">
|
||||
<span class="rounded-full bg-green-100 px-2 py-1 text-[10px] font-black text-green-800"
|
||||
>LOCALIZAÇÃO ACESSÍVEL</span
|
||||
>
|
||||
<h3 class="display mt-3 text-xl font-black">Seleção do seu território</h3>
|
||||
<p class="mt-2 text-sm leading-5 text-[#6c615e]">
|
||||
GPS já acessível; senão, recorte aproximado por IP. A interface entrega o mesmo
|
||||
resultado: município → região → recentes.
|
||||
</p>
|
||||
<div class="mt-5 flex gap-2">
|
||||
<span class="tag local">Do seu município</span
|
||||
><span class="tag local">Da sua região</span>
|
||||
</div>
|
||||
<p class="mt-5 text-xs text-[#6c615e]">
|
||||
Nada é guardado, registrado ou usado fora desta seção.
|
||||
</p>
|
||||
</article>
|
||||
<article class="frame rounded-xl bg-white p-6">
|
||||
<span class="rounded-full bg-[#eef4fb] px-2 py-1 text-[10px] font-black text-[#184e92]"
|
||||
>SEM SINAL ÚTIL</span
|
||||
>
|
||||
<h3 class="display mt-3 text-xl font-black">Seleção recente</h3>
|
||||
<p class="mt-2 text-sm leading-5 text-[#6c615e]">
|
||||
A espera termina e as peças recentes aparecem. Nenhum erro é mostrado.
|
||||
</p>
|
||||
<div class="mt-5 h-24 rounded-lg border bg-[#f9faff] p-3 text-xs text-[#6c615e]">
|
||||
Preview recente disponível
|
||||
</div>
|
||||
<p class="mt-4 text-xs font-bold text-[#184e92]">Nunca há spinner eterno.</p>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<div class="scene mb-3 flex items-center gap-3 text-xs font-bold text-[#6c615e]">
|
||||
<span>CENA 05</span>
|
||||
<h2>Uma peça publicada · sem lacunas, independentemente da localização</h2>
|
||||
</div>
|
||||
<div class="grid gap-8 lg:grid-cols-[1fr_390px]">
|
||||
<div class="frame overflow-hidden rounded-xl bg-white">
|
||||
<section class="relative overflow-hidden px-10 py-12">
|
||||
<div class="absolute -top-24 -right-20 size-64 rounded-full bg-[#ffe607]/35"></div>
|
||||
<div class="relative grid grid-cols-[1fr_360px] items-center gap-10">
|
||||
<div>
|
||||
<p class="eyebrow">Central de Conteúdos</p>
|
||||
<h2 class="display mt-2 text-4xl font-black">Peça voto pra Solla 1313</h2>
|
||||
<p class="mt-3 max-w-lg text-base leading-6 text-[#6c615e]">
|
||||
Uma peça oficial já está pronta para você compartilhar.
|
||||
</p>
|
||||
<a class="cta mt-6" href="/conteudos">Ver todas as peças →</a>
|
||||
</div>
|
||||
<article class="preview">
|
||||
<div class="asset aspect-video">NEEDS ASSET · PREVIEW REAL</div>
|
||||
<div class="p-4">
|
||||
<span class="tag">Foto</span>
|
||||
<h3 class="mt-2 font-extrabold">Título da única peça publicada</h3>
|
||||
<a class="mt-3 inline-block text-xs font-bold text-[#a21c1c]"
|
||||
>Ver esta peça →</a
|
||||
>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<div class="phone frame overflow-hidden bg-white">
|
||||
<section class="relative overflow-hidden px-5 py-10 text-center">
|
||||
<div class="absolute -top-16 -right-20 size-48 rounded-full bg-[#ffe607]/35"></div>
|
||||
<div class="relative">
|
||||
<p class="eyebrow text-[10px]">Central de Conteúdos</p>
|
||||
<h2 class="display mt-2 text-[30px] font-black leading-[1.05]">
|
||||
Peça voto pra<br />Solla 1313
|
||||
</h2>
|
||||
<p class="mt-3 text-sm leading-5 text-[#6c615e]">
|
||||
Uma peça oficial já está pronta.
|
||||
</p>
|
||||
<article class="preview mt-6 text-left">
|
||||
<div class="asset aspect-video">NEEDS ASSET · PREVIEW REAL</div>
|
||||
<div class="p-4">
|
||||
<span class="tag">Foto</span>
|
||||
<h3 class="mt-2 font-extrabold">Título da única peça publicada</h3>
|
||||
<a class="mt-3 block text-xs font-bold text-[#a21c1c]">Ver peça →</a>
|
||||
</div>
|
||||
</article>
|
||||
<a class="cta mt-6 w-full" href="/conteudos">Ver todas as peças →</a>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<div class="scene mb-3 flex items-center gap-3 text-xs font-bold text-[#6c615e]">
|
||||
<span>CENA 06</span>
|
||||
<h2>Zero peças · seção inteira ausente (fail-closed)</h2>
|
||||
</div>
|
||||
<div class="desktop frame mx-auto overflow-hidden rounded-xl bg-white">
|
||||
<div class="surround bg-[#fff8f2]">
|
||||
<p class="eyebrow">Faça parte</p>
|
||||
<h3 class="display mt-1 text-2xl font-black">Mostre que você está com Solla</h3>
|
||||
<div class="mx-auto mt-5 h-20 max-w-3xl rounded-xl bg-[#ebe9e9]"></div>
|
||||
</div>
|
||||
<div
|
||||
class="flex h-16 items-center justify-center border-b border-dashed bg-white text-xs font-bold text-[#6c615e]"
|
||||
>
|
||||
A SEÇÃO DA CENTRAL NÃO É RENDERIZADA · SEM LOCALIZAÇÃO, VAZIO OU CTA
|
||||
</div>
|
||||
<div class="surround bg-[#ebe9e9]">
|
||||
<p class="eyebrow">Apoie e acompanhe</p>
|
||||
<h3 class="display mt-1 text-2xl font-black">Receba as novidades da campanha</h3>
|
||||
<div class="mx-auto mt-5 h-20 max-w-2xl rounded-xl border bg-white"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="phone frame mx-auto mt-8 overflow-hidden bg-white">
|
||||
<div class="border-b bg-[#fff8f2] px-5 py-7 text-center">
|
||||
<p class="eyebrow text-[10px]">Faça parte</p>
|
||||
<h3 class="display mt-1 text-xl font-black">Mostre que você está com Solla</h3>
|
||||
<div class="mt-4 h-16 rounded bg-[#ebe9e9]"></div>
|
||||
</div>
|
||||
<div
|
||||
class="flex h-14 items-center justify-center border-b border-dashed text-[10px] font-bold text-[#6c615e]"
|
||||
>
|
||||
CENTRAL AUSENTE
|
||||
</div>
|
||||
<div class="bg-[#ebe9e9] px-5 py-8 text-center">
|
||||
<p class="eyebrow text-[10px]">Apoie e acompanhe</p>
|
||||
<h3 class="display mt-1 text-xl font-black">Receba as novidades</h3>
|
||||
<div class="mt-4 h-20 rounded-xl border bg-white"></div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
121
docs/plans/central-conteudos-secao-home.md
Normal file
121
docs/plans/central-conteudos-secao-home.md
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
# S39 — Home — seção divulgando a Central de Conteúdos
|
||||
|
||||
Status: rascunho
|
||||
Atualizado em: 2026-09-23
|
||||
Issue: #1305
|
||||
Priority: P1
|
||||
Impeccable: C — seção nova na home pública (superfície nova dentro de página existente)
|
||||
Design UI: docs/plans/central-conteudos-secao-home-ui-design.html
|
||||
Appetite: ~2–3 dias eng; um outcome verificável (a home leva à Central com peças do território do visitante; a seção some quando não há peça publicada)
|
||||
Responsável: —
|
||||
|
||||
## Intenção
|
||||
|
||||
A Central de Conteúdos (`/conteudos`, S27) está no ar com as peças "Peça voto pra Solla 1313", mas quem chega na home — o lugar mais visitado do site — só a descobre pelo link condicional do rodapé e pelo selo local da própria peça. Na reta final até 04/10, a home precisa empurrar o eleitor para a Central: uma seção curta que mostre peças do **território do visitante** (para ele se reconhecer e repassar) e o leve para lá. A localização é resolvida pelo próprio visitante — GPS quando acessível, senão IP —, sem guardar nada.
|
||||
|
||||
Esta seção **supersede a decisão D7 do S27** ("Descoberta (rodapé + selo; sem seção nova)", `docs/plans/central-conteudos-publica-impl.md:87-91`), que rejeitou a seção nova na home por estar fora do escopo daquele item. A reabertura é decisão de produto do dono (pedido do operador); o rodapé e o selo local do S27 permanecem como estão — este item só acrescenta a seção.
|
||||
|
||||
## Persona e fluxo
|
||||
|
||||
- **Persona / contexto:** eleitor/simpatizante que abre jorgesolla1313.com.br no celular (link no WhatsApp, busca, indicação) e quer ajudar, mas não sabe onde pegar material nem o que escrever; o que o convence é ver o material do lugar dele.
|
||||
- **Job principal:** descobrir que existe uma Central de peças oficiais de voto, reconhecer o material do seu território e chegar nela em um toque.
|
||||
- **Fluxo desejado:** rola a home → a seção resolve a localização (GPS se acessível, senão IP; sem localização, segue) → vê até 3 peças publicadas do seu município (completando com a região e, se faltar, recentes) → toca numa peça ou no CTA "Ver todas as peças" → cai em `/conteudos` → baixa/compartilha dali (fluxo do S27).
|
||||
- **Anti-goals de produto:** não é uma segunda Central nem catálogo paralelo (quem cataloga é o interno, C211); não duplica a seção S3 "Acompanhe de perto" (feed de redes/artigos) nem a seção de cards logo acima — **cards personalizáveis nunca são amostra**; não captura dado, não pede login, não guarda/loga a localização e não adiciona rastreio (analytics é C213); não re-hospeda mídia; não autoplaya áudio/vídeo; não redesenha a home.
|
||||
|
||||
### Esboço de fluxo (C)
|
||||
|
||||
```text
|
||||
[visitante na home] → a seção resolve a localização
|
||||
(GPS se acessível · senão IP no servidor · senão desconhecida — nunca guarda nem loga)
|
||||
→ até 3 peças publicadas do município do visitante
|
||||
(sem peça local: completa com a região; ainda faltando: recentes; sem localização: recentes)
|
||||
→ nunca cards personalizáveis como amostra (a seção anterior da home já os mostra)
|
||||
→ toca numa peça (mídia só no toque) ou no CTA "Ver todas as peças" → /conteudos
|
||||
[zero peças publicadas] → a seção inteira some (fail-closed)
|
||||
[localização indisponível/fora da Bahia] → recentes, sem erro e sem prompt insistente
|
||||
```
|
||||
|
||||
### Design UI (C)
|
||||
|
||||
- Design UI (gate): `docs/plans/central-conteudos-secao-home-ui-design.html` — cenas mobile/desktop da seção na home: peças do território, fallback sem localização, uma peça só, zero peças (seção ausente) e o estado de resolução da localização (sem spinner eterno). Revisão do gate: a primeira versão não tinha seleção por localização nem excluía os cards.
|
||||
|
||||
## Objetivo e aceite
|
||||
|
||||
- A home pública ganha uma seção dedicada à Central, visível só quando há peça publicada: sem peça, a seção não existe na página (fail-closed a zero, mesma condição do link do rodapé hoje).
|
||||
- **Amostra por território do visitante:** a seção mostra até 3 peças publicadas do município do visitante; se não houver peças locais suficientes, completa com a região e, ainda faltando, com as mais recentes; sem localização ou fora da Bahia, mostra as mais recentes.
|
||||
- **Localização sem rastro:** GPS só quando acessível (permissão já concedida ou affordance explícita — ver questão (a)); senão IP resolvido no servidor; **nunca persistir, logar ou setar cookie** com a localização ou o IP; nada de PII.
|
||||
- **Cards personalizáveis nunca são amostra:** a seção anterior da home (`CampaignCardsSection`) já os mostra; peças publicadas de qualquer tipo (inclusive tipo card de arquivo) podem ser amostra.
|
||||
- A seção leva à Central: CTA principal para `/conteudos` e prévia leve das peças (foto) ou só chamada de play (vídeo/áudio) — nada carrega sozinho.
|
||||
- Kill switch instantâneo: despublicar uma peça reflete na seção sem deploy (mesmo contrato de cache/tag do catálogo, `contentPieces`).
|
||||
- Sem autoplay, sem mídia pesada na abertura da home (contrato do S27); seção distinta do S3 e da seção de cards; sem rastreio novo; demais seções da home intocadas.
|
||||
- **A seção é por visitante** (localização): não pode ser servida no mesmo HTML estático compartilhado do resto da home — o executor decide o mecanismo (resolver no cliente após a localização, ou render no servidor por IP), mantendo o resto da home como está.
|
||||
- Celular primeiro: sem overflow horizontal (o e2e da home mede), usável em conexão ruim; nenhuma espera bloqueia o resto da home (a seção pode aparecer depois).
|
||||
|
||||
## Dados (intenção)
|
||||
|
||||
- **Dados: N/A** — a seção é superfície de descoberta; nenhum número, contador ou ranking. **Decisões desbloqueadas:** o visitante decide entrar na Central (e o que pegar lá); a comunicação decide o que publicar/despublicar. Nenhum dado do visitante é coletado ou guardado.
|
||||
|
||||
## Dados da decisão (literais)
|
||||
|
||||
- Item `S39`; slug `central-conteudos-secao-home`; tipo `feature`; Priority `P1`; Impeccable `C`.
|
||||
- Condição da seção: **sem peça publicada → a seção inteira não aparece** (mesma condição do link "Conteúdos" no rodapé, hoje via `hasPublishedContentPieces`).
|
||||
- CTA principal: `Ver todas as peças` → `/conteudos`.
|
||||
- Conteúdo: **até 3 peças publicadas**, na ordem de seleção **município do visitante → região → mais recentes**; sem localização/fora da Bahia → mais recentes.
|
||||
- Exclusão literal: **cards personalizáveis (os itens sintéticos dos 6 modelos) nunca entram como amostra** — a seção logo acima (`CampaignCardsSection`) já os mostra.
|
||||
- Localização: GPS só se acessível (permissão já concedida ou affordance explícita); senão IP no servidor; **proibido persistir/logar/cookiar** localização ou IP; fora da Bahia ou indisponível → recentes.
|
||||
- Sinal de IP: a viabilidade de resolver **município** pelo IP no deploy (headers do túnel Cloudflare e/ou fonte de geo-IP) é **a confirmar na implementação** — nunca estimada; se só resolver país/estado, a seleção degrada para região/recentes.
|
||||
- Convenção das seções irmãs da home: `data-home-section` — valores existentes `hero`, `proof`, `contents`, `problem`, `flags`, `story`, `sound`, `cards`, `newsletter`; a seção nova segue a convenção (valor definido no plano de implementação).
|
||||
- Cache/kill switch: mesma tag de listagem do catálogo (`contentPieces`), revalidada no publish/unpublish; a seleção por localização não entra no cache compartilhado.
|
||||
- **Supersessão:** D7 do S27 (`docs/plans/central-conteudos-publica-impl.md:87-91`), opção A (rodapé + selo; sem seção nova), rejeitava a opção B (seção nova na home). Este item reabre e adota a seção nova; rodapé e selo local do S27 permanecem.
|
||||
- Escopo do S27 intocado: filtros, busca, páginas de peça, share e mensagens de voto continuam como entregues.
|
||||
|
||||
## Direção no codebase (hipótese)
|
||||
|
||||
- **Áreas prováveis:** a home compõe seções hardcoded em `src/app/(frontend)/(home)/page.tsx:127-251`; a seção nova é um componente no molde de `JingleHomeSection` (`data-home-section="sound"`, "Ver todos" → `/jingles`) e `CampaignCardsSection` (`data-home-section="cards"`); a seleção local usa as facetas já existentes da peça (município/região, `src/lib/contentPieceCatalog.ts`) sobre a leitura pública cacheada (`src/utilities/content/contentPieceReads.ts`).
|
||||
- **Precedentes de localização a olhar:** `src/lib/municipalityProximity.ts` (ponto → município/ZE, fora da Bahia, mais próximo — puro e testado), `src/utilities/campaignGeolocation.ts` e `src/components/campaign/shared/useNearestMunicipalitySlug.ts` / `NearestMunicipalityCard.tsx` (B14, geolocalização no dashboard staff — atenção: lá resolve só entre os municípios do portfólio; aqui o universo é o catálogo inteiro), e a extração de IP do túnel em `src/utilities/content/contentEventRateLimit.ts:33-37` / `src/utilities/ai/themeSearchGuard.ts:22` (`cf-connecting-ip` → `x-forwarded-for` → `x-real-ip`).
|
||||
- **Descoberta hoje:** link condicional no rodapé (`CampaignFooter.tsx:34-37,65-67`) + selo local (`ContentPiecePageHeader.tsx:31-33`); `SiteHeader.tsx` não tem link.
|
||||
- **Risco de acoplamento:** a home é estática/cacheada — a seção por visitante não pode contaminar o cache compartilhado nem virar leitura crua pesada; não editar as seções irmãs, `/conteudos` nem o rodapé; o e2e da home mede overflow horizontal; não acoplar ao #44 PUB2 (editabilidade da home é issue separada).
|
||||
|
||||
## Dependências
|
||||
|
||||
- **C211** (peças catalogadas e publicadas) — dura, indireta: sem peça publicada a seção some (fail-closed).
|
||||
- S27 (`/conteudos` no ar) — dura: o CTA precisa do destino.
|
||||
- B14 (mecânica de geolocalização/proximidade) — soft: precedente a reusar, não dependência de entrega.
|
||||
- Design hi-fi aprovado no gate.
|
||||
|
||||
## Fora de escopo
|
||||
|
||||
- Cards personalizáveis como amostra (a seção anterior os mostra) e mudanças na `CampaignCardsSection`.
|
||||
- Guardar/logar/cookiar a localização ou o IP; analytics/UTM (C213); login/captura/PII; novo Consent.
|
||||
- Editabilidade/toggles/ordem das seções da home (#44 PUB2); mudar o rodapé, o selo local, o `SiteHeader` ou a própria `/conteudos`.
|
||||
- Redesign de qualquer outra seção da home (S3 incluída) e personalização do resto da home por localização.
|
||||
|
||||
## Rabbit holes de produto
|
||||
|
||||
- **"Já que tem localização, personaliza a home inteira".** Se alguém "só completar": hero, cards e notícias por cidade. **Corte neste item:** só a seção da Central usa a localização; o resto da home fica como está.
|
||||
- **"Guarda a cidade para a próxima visita".** Se alguém "só completar": cookie/localStorage de localização, perfil de visitante. **Corte:** nada é persistido — a resolução vale para a visita e morre nela.
|
||||
- **"Pede o GPS de novo a cada visita".** Se alguém "só completar": prompt repetido no carregamento, spinner eterno. **Corte:** GPS só quando acessível (ou affordance); indisponível → IP/recentes, sem insistir.
|
||||
- **"A seção vira uma mini-Central".** Se alguém "só completar": filtros, busca e ações de baixar/compartilhar na home. **Corte:** a seção só apresenta e leva; quem faz tudo é `/conteudos`.
|
||||
- **"Publicar para não sumir".** Se alguém "só completar": hardcode de peças para a seção nunca ficar vazia. **Corte:** fail-closed a zero é regra (kill switch); o código não publica conteúdo.
|
||||
- **"Tocar sozinho".** Se alguém "só completar": autoplay/preview animado para engajar. **Corte:** mídia só no toque, como no S27.
|
||||
|
||||
## Questões em aberto (produto)
|
||||
|
||||
- **Como obter o GPS?** **Opções:** A) prompt do navegador ao carregar a home | B) sem prompt: usa GPS só quando a permissão já estiver concedida (ou por uma affordance explícita na seção), senão IP. **Recomendação:** B — o prompt surpresa no carregamento queima confiança e a maioria nega; o IP já dá o recorte territorial na primeira visita. _(assumido — validar com produto)_
|
||||
- **Amostra local estrita ou completada?** **Opções:** A) só do município (pode mostrar menos de 3) | B) município → região → recentes | C) só recentes com selo local. **Recomendação:** B — a seção não fica vazia nem parece genérica. _(assumido — validar com produto)_
|
||||
- **Posição na home?** **Opções:** A) depois de `CampaignCardsSection`, antes da newsletter | B) junto de `CampaignContentSection` (S3). **Recomendação:** A — fecha a página com CTA de compartilhamento, mantendo cards + newsletter como bloco final de conversão. _(assumido — validar com produto)_
|
||||
- **Copy/CTA literais?** **Opções:** A) título na voz da Central ("Peça voto pra Solla 1313") + CTA `Ver todas as peças` | B) copy neutra ("Conheça a Central de Conteúdos") | C) outra. **Recomendação:** A — mesma voz do S27; copy final validada no gate/design. _(assumido — validar com produto)_
|
||||
|
||||
## Referências
|
||||
|
||||
- GitHub Issue: #1305.
|
||||
- Design UI (gate): `docs/plans/central-conteudos-secao-home-ui-design.html`.
|
||||
- `docs/plans/central-conteudos-publica.md` (S27) e `central-conteudos-publica-impl.md` (D7 superseded); `central-conteudos-publica-ui-design.html`.
|
||||
- `src/app/(frontend)/(home)/page.tsx`, `src/components/jingles/JingleHomeSection.tsx`, `src/app/(frontend)/(home)/CampaignCardsSection.tsx`, `src/utilities/content/contentPieceReads.ts`, `src/components/CampaignFooter.tsx`, `src/components/CampaignContentSection.tsx`
|
||||
- Localização: `src/lib/municipalityProximity.ts`, `src/utilities/campaignGeolocation.ts`, `src/components/campaign/shared/useNearestMunicipalitySlug.ts`, `src/utilities/content/contentEventRateLimit.ts`, `src/utilities/ai/themeSearchGuard.ts`
|
||||
- `tests/e2e/frontend.e2e.spec.ts` e `scripts/lib/e2e-affected-manifest.mjs` (manifesto de e2e afetado pela home).
|
||||
- `AGENTS-public.md` — convenções do site público (cache, kill switch, mídia).
|
||||
|
||||
## Self-score (shaping)
|
||||
|
||||
4,6/5 — (1) fatia = um outcome verificável (a home leva à Central com peças do território; a seção some sem peça); (2) appetite ~2–3 dias cabe (seção + resolução de localização + seleção, com o resto da home intocado); (3) persona/job/aceite em linguagem de produto; (4) direção no codebase é hipótese (precedentes citados como pista); (5) zero decisão dura de engenharia — o mecanismo de resolução fica no plano de implementação e a viabilidade do sinal de IP está marcada "a confirmar".
|
||||
|
|
@ -48,6 +48,13 @@ A entrega S30 ([cards-estadual-dobradinha-impl.md](cards-estadual-dobradinha-imp
|
|||
- **P8 — `identitySha256` redundante após o `toEqual`**: **descartar** — precedente idêntico no `municipalityCatalog`; o hash é o guard de regeneração do fixture.
|
||||
- **P9 — `!` em `tests/unit/cardRender.unit.spec.ts`**: **descartar** — convenção do próprio arquivo (test-only, pré-existente).
|
||||
|
||||
## Absorvidos do S34 (2026-09-24)
|
||||
|
||||
Débitos que o /simplify do S34 ([cards-colinha-arte-exata-impl.md](cards-colinha-arte-exata-impl.md)) mandou para este lote (mesma superfície):
|
||||
|
||||
- **S34-D1 — `name.toLocaleUpperCase('pt-BR')` duplicado** entre a `Linha conferida` do `CardComposer` e o nome desenhado em `renderColinhaCard`: a derivação do texto do nome entra em **F2** (função pura no dono `cardColinha.ts`), consumida pelos dois.
|
||||
- **S34-D2 — `ensureCardFont(fontFamily)` gateia o fluxo da colinha** (que desenha com o stack Arial, não com a display do site): o efeito de carga é reestruturado em **F1/F2**; hoje uma falha da fonte display derruba um fluxo que não a usa (pré-existente do S31).
|
||||
|
||||
## Rabbit holes / Não escopo
|
||||
|
||||
- Extrair o listbox compartilhado agora (P2) — três superfícies divergentes (admin/omnibox, chips de relação, estúdio público) e gatilho documentado; abstração prematura.
|
||||
|
|
|
|||
36
docs/plans/omnibox-limpar-mobile.md
Normal file
36
docs/plans/omnibox-limpar-mobile.md
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
# C221 — "Limpar" do omnibox não pode quebrar linha no mobile
|
||||
|
||||
Status: rascunho
|
||||
Atualizado em: 2026-09-24
|
||||
Issue: (a registrar)
|
||||
Priority: P3
|
||||
Impeccable: B — ajuste de encaixe do shell de filtros existente (não é fluxo novo)
|
||||
Appetite: ~2h eng (fill-in)
|
||||
|
||||
## Intenção
|
||||
|
||||
Débito capturado na crítica de design da C219 (`docs/plans/acervo-paridade-busca-filtros.md`): no mobile, quando o chip de busca do omnibox compartilhado é longo, o botão global "Limpar" (o "X" circular dentro do campo, `md:hidden`) quebra para uma linha própria e aparece órfão abaixo do chip, criando uma faixa vazia entre o campo e o seletor de modo. Reproduzido igualmente na fonte Câmara e na fonte "Gravações enviadas" — é comportamento pré-existente do `CampaignListOmnibox`, não regressão da C219.
|
||||
|
||||
Evidência: `/tmp/opencode/c219-shots/06-mobile-empty.png` (gravações) e `/tmp/opencode/c219-shots/11-mobile-camara-long-chip.png` (Câmara) na sessão da C219; o código é o cluster `flex-wrap` do campo em `src/components/campaign/shared/CampaignListOmnibox.tsx` (chips + input + botão de limpar na mesma linha flexível).
|
||||
|
||||
## Objetivo e aceite
|
||||
|
||||
- Com um chip de busca longo no mobile, o "X" de limpar permanece visualmente vinculado ao campo/chips (não quebra para uma linha órfã), em todas as listas que usam o shell.
|
||||
- Comportamento, acessibilidade (`aria-label="Limpar"`, anel de foco, região `sr-only`) e desktop intocados.
|
||||
- Sem mudança de contrato de URL/filtros.
|
||||
|
||||
## Direção no codebase (hipótese)
|
||||
|
||||
- `src/components/campaign/shared/CampaignListOmnibox.tsx` — cluster do campo (`flex min-h-10 w-full flex-wrap items-center gap-1.5 ...`) com chips, input e o botão de limpar `md:hidden`.
|
||||
- Consumidores para regressão visual: `SpeechAcervoFilters`, `RecordingAcervoFilters`, listas de municípios/apoiadores (qualquer `<form>` com `campaignListOmniboxFormClassName`).
|
||||
- Estratégias possíveis (decidir no impl): manter o botão fora do fluxo dos chips (posição absoluta no campo), agrupar chips+input num contêiner que quebra e ancorar o X na linha do input, ou limitar a largura do chip no mobile. A mais simples que preserve o layout desktop.
|
||||
|
||||
## Fora de escopo
|
||||
|
||||
- Redesenho da barra da Câmara ou dos shells de lista.
|
||||
- Mudanças nos adaptadores de omnibox por domínio.
|
||||
|
||||
## Aceite de engenharia
|
||||
|
||||
- [ ] Regressão visual mobile (390) em pelo menos uma lista de cada vertical que usa o shell.
|
||||
- [ ] Nenhuma mudança de markup/ARIA que quebre os e2e existentes das listas.
|
||||
|
|
@ -89,6 +89,8 @@
|
|||
"images:fill": "node scripts/fill-image.mjs",
|
||||
"camara:pilot": "cross-env NODE_OPTIONS=\"--no-deprecation --import=tsx/esm\" node scripts/pilot-camara-speeches.mjs",
|
||||
"camara:import": "cross-env NODE_OPTIONS=\"--no-deprecation --import=tsx/esm --import=./scripts/seed-loader.mjs\" node scripts/import-camara-speeches.mjs",
|
||||
"falas-web:import": "cross-env NODE_OPTIONS=\"--no-deprecation --import=tsx/esm --import=./scripts/seed-loader.mjs\" node scripts/import-web-speeches.mjs",
|
||||
"recordings:classify": "cross-env NODE_OPTIONS=\"--no-deprecation --import=tsx/esm --import=./scripts/seed-loader.mjs\" node scripts/backfill-recording-facets.mjs",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"typecheck:tsc6": "tsc6 --noEmit",
|
||||
"prepare": "husky",
|
||||
|
|
|
|||
162
scripts/backfill-recording-facets.mjs
Normal file
162
scripts/backfill-recording-facets.mjs
Normal file
|
|
@ -0,0 +1,162 @@
|
|||
/**
|
||||
* C219 — facet backfill of the uploaded recordings ("Gravações enviadas").
|
||||
*
|
||||
* The transcription job classifies every recording it finishes; this CLI
|
||||
* classifies the rows that already existed (and can reclassify on demand) with
|
||||
* the SAME function the job uses (`classifyRecordingFacets` → `classifySpeech`:
|
||||
* offline gazetteer + one validated LLM refinement on Deep Infra). It never
|
||||
* invents provenance: a row is only written when the classifier produced a
|
||||
* result, a `manual` curation is never touched, and the default selection is
|
||||
* exactly the rows with no `classifiedBy` (never classified).
|
||||
*
|
||||
* Idempotent: re-running skips what it already classified (default mode);
|
||||
* `--all` reclassifies everything except `manual` rows.
|
||||
*
|
||||
* The local-DB guard refuses a non-local DATABASE_URL, and any write run
|
||||
* targeting production (or a remote/override DB) additionally requires
|
||||
* `RECORDING_CLASSIFY_CONFIRM=1` (same family as `CAMARA_IMPORT_CONFIRM`).
|
||||
*
|
||||
* Usage:
|
||||
* pnpm recordings:classify --dry-run
|
||||
* pnpm recordings:classify --limit 5
|
||||
* pnpm recordings:classify
|
||||
* pnpm recordings:classify --all
|
||||
* RECORDING_CLASSIFY_CONFIRM=1 pnpm recordings:classify --all
|
||||
*/
|
||||
import { getPayload } from 'payload'
|
||||
|
||||
import { assertLocalDatabase } from './assert-local-database.mjs'
|
||||
import { dieWithLabel, isTruthyEnv, loadCliEnv, requiresWriteConfirm } from './lib/cli.mjs'
|
||||
|
||||
loadCliEnv()
|
||||
|
||||
const die = dieWithLabel('recordings:classify')
|
||||
const WRITE_CONFIRM_FLAG = 'RECORDING_CLASSIFY_CONFIRM'
|
||||
|
||||
const parseArgs = (argv) => {
|
||||
const options = { dryRun: false, all: false, limit: null }
|
||||
for (const arg of argv) {
|
||||
if (arg === '--dry-run') options.dryRun = true
|
||||
else if (arg === '--all') options.all = true
|
||||
else if (arg.startsWith('--limit=')) {
|
||||
const limit = Number(arg.slice('--limit='.length))
|
||||
if (!Number.isSafeInteger(limit) || limit <= 0) die(`--limit inválido: ${arg}`)
|
||||
options.limit = limit
|
||||
} else die(`argumento desconhecido: ${arg}`)
|
||||
}
|
||||
return options
|
||||
}
|
||||
|
||||
const options = parseArgs(process.argv.slice(2))
|
||||
|
||||
assertLocalDatabase(
|
||||
'recordings:classify',
|
||||
'A classificação escreve em `recording`; aponte DATABASE_URL para o banco local.',
|
||||
)
|
||||
|
||||
if (requiresWriteConfirm() && !isTruthyEnv(process.env[WRITE_CONFIRM_FLAG])) {
|
||||
die(
|
||||
`Este run escreve em um banco remoto/de produção. Se é isso mesmo, re-execute com:\n ${WRITE_CONFIRM_FLAG}=1 pnpm recordings:classify …`,
|
||||
)
|
||||
}
|
||||
|
||||
const config = (await import('../src/payload.config.ts')).default
|
||||
const { classifyRecordingFacets, recordingFacetWriteData } =
|
||||
await import('../src/utilities/recordings/recordingClassification.ts')
|
||||
|
||||
const payload = await getPayload({ config })
|
||||
|
||||
const where = options.all
|
||||
? { and: [{ status: { equals: 'ready' } }, { classifiedBy: { not_equals: 'manual' } }] }
|
||||
: { and: [{ status: { equals: 'ready' } }, { classifiedBy: { exists: false } }] }
|
||||
|
||||
const targets = await payload.find({
|
||||
collection: 'recording',
|
||||
where,
|
||||
depth: 0,
|
||||
limit: options.limit ?? 0,
|
||||
pagination: false,
|
||||
sort: 'createdAt',
|
||||
select: { title: true, classifiedBy: true },
|
||||
// Intentional admin bypass: the backfill CLI is a trusted actor with no session.
|
||||
overrideAccess: true,
|
||||
})
|
||||
|
||||
const report = {
|
||||
targets: targets.docs.length,
|
||||
classified: 0,
|
||||
skippedEmptyTranscript: 0,
|
||||
failed: 0,
|
||||
llmUsed: 0,
|
||||
totalTokens: 0,
|
||||
estimatedCostUsd: 0,
|
||||
}
|
||||
|
||||
console.log(
|
||||
`[recordings:classify] ${report.targets} gravação(ões) alvo${options.dryRun ? ' (dry-run)' : ''}.`,
|
||||
)
|
||||
|
||||
for (const recording of targets.docs) {
|
||||
const segments = await payload.find({
|
||||
collection: 'recordingSegment',
|
||||
where: { recording: { equals: recording.id } },
|
||||
depth: 0,
|
||||
limit: 0,
|
||||
pagination: false,
|
||||
sort: 'order',
|
||||
select: { text: true },
|
||||
// Intentional admin bypass: reconstructing the transcript the job owns.
|
||||
overrideAccess: true,
|
||||
})
|
||||
const transcript = segments.docs.map((segment) => segment.text).join(' ')
|
||||
|
||||
const classification = await classifyRecordingFacets({ payload, transcript })
|
||||
if (!classification) {
|
||||
report.skippedEmptyTranscript += 1
|
||||
console.warn(`[recordings:classify] #${recording.id} sem transcrição utilizável — pulada.`)
|
||||
continue
|
||||
}
|
||||
|
||||
if (classification.llm.used) report.llmUsed += 1
|
||||
if (classification.llm.totalTokens !== null) report.totalTokens += classification.llm.totalTokens
|
||||
if (classification.llm.estimatedCostUsd !== null) {
|
||||
report.estimatedCostUsd += classification.llm.estimatedCostUsd
|
||||
}
|
||||
|
||||
if (options.dryRun) {
|
||||
report.classified += 1
|
||||
console.log(
|
||||
`[recordings:classify] (dry-run) #${recording.id} "${recording.title}" → ` +
|
||||
`${classification.topics.join(', ') || '—'} · ${classification.classifiedBy}`,
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
try {
|
||||
await payload.update({
|
||||
collection: 'recording',
|
||||
id: recording.id,
|
||||
data: recordingFacetWriteData(classification),
|
||||
// Intentional admin bypass: the backfill CLI is a trusted actor with no session.
|
||||
overrideAccess: true,
|
||||
})
|
||||
report.classified += 1
|
||||
console.log(
|
||||
`[recordings:classify] #${recording.id} "${recording.title}" → ` +
|
||||
`${classification.topics.join(', ') || '—'} · ${classification.classifiedBy}`,
|
||||
)
|
||||
} catch (error) {
|
||||
report.failed += 1
|
||||
console.warn(
|
||||
`[recordings:classify] #${recording.id} falhou ao gravar: ` +
|
||||
`${error instanceof Error ? error.message : String(error)}`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
console.log(
|
||||
`\n[recordings:classify] alvos=${report.targets} classificadas=${report.classified} ` +
|
||||
`sem-transcrição=${report.skippedEmptyTranscript} falhas=${report.failed} ` +
|
||||
`llm=${report.llmUsed} tokens=${report.totalTokens} custo≈$${report.estimatedCostUsd.toFixed(4)}`,
|
||||
)
|
||||
process.exit(report.failed > 0 ? 1 : 0)
|
||||
|
|
@ -78,12 +78,11 @@ import {
|
|||
speechSourceKey,
|
||||
} from './lib/camaraSpeeches.mjs'
|
||||
import {
|
||||
databaseHostname,
|
||||
assertWriteConfirm,
|
||||
databaseTarget,
|
||||
dieWithLabel,
|
||||
ensureCachedDownload,
|
||||
isTruthyEnv,
|
||||
loadCliEnv,
|
||||
requiresWriteConfirm,
|
||||
} from './lib/cli.mjs'
|
||||
|
||||
loadCliEnv()
|
||||
|
|
@ -1149,14 +1148,6 @@ const runRepairLinks = async (payload, options) => {
|
|||
}
|
||||
}
|
||||
|
||||
const databaseTarget = () => {
|
||||
const url = process.env.DATABASE_URL
|
||||
const host = databaseHostname(url)
|
||||
if (host === null) return '(DATABASE_URL ausente ou inválida)'
|
||||
// `databaseHostname` only returns non-null when `new URL` already parsed.
|
||||
return `${host}${new URL(url).pathname}`
|
||||
}
|
||||
|
||||
const modeLabel = (options) => {
|
||||
if (options.coverage) return 'coverage (read-only)'
|
||||
if (options.verifyLinks !== null) return `verify-links n=${options.verifyLinks} (read-only)`
|
||||
|
|
@ -1168,21 +1159,6 @@ const modeLabel = (options) => {
|
|||
return `legislature ${options.legislature}`
|
||||
}
|
||||
|
||||
/**
|
||||
* C155 write guard: the homeserver env file sets `NODE_ENV=production` and the
|
||||
* runbook rewrites the DB host to the local proxy, so the host check alone
|
||||
* cannot see production — the explicit flag is what makes the write deliberate.
|
||||
*/
|
||||
const assertWriteAllowed = () => {
|
||||
if (!requiresWriteConfirm()) return
|
||||
if (isTruthyEnv(process.env[WRITE_CONFIRM_FLAG])) return
|
||||
die(
|
||||
`alvo de escrita não-local/produção detectado (${databaseTarget()}).\n` +
|
||||
`Confirme a intenção com:\n ${WRITE_CONFIRM_FLAG}=1 pnpm camara:import …\n` +
|
||||
`Runbook: docs/ops/teqo-1313-deploy.md §C155/§C160.`,
|
||||
)
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const options = parseArgs(process.argv.slice(2))
|
||||
if (options.help) {
|
||||
|
|
@ -1197,7 +1173,12 @@ async function main() {
|
|||
} else {
|
||||
// Confirm first: a non-local host is exactly what the flag is for; the
|
||||
// local-DB guard below still blocks a remote host without ALLOW_REMOTE_DB.
|
||||
assertWriteAllowed()
|
||||
assertWriteConfirm({
|
||||
label: 'camara:import',
|
||||
flag: WRITE_CONFIRM_FLAG,
|
||||
command: 'pnpm camara:import',
|
||||
hint: 'Runbook: docs/ops/teqo-1313-deploy.md §C155/§C160.',
|
||||
})
|
||||
assertLocalDatabase(
|
||||
'camara:import',
|
||||
'O import escreve no acervo; produção exige CAMARA_IMPORT_CONFIRM=1 (runbook §C155/§C160).',
|
||||
|
|
|
|||
240
scripts/import-web-speeches.mjs
Normal file
240
scripts/import-web-speeches.mjs
Normal file
|
|
@ -0,0 +1,240 @@
|
|||
/**
|
||||
* C215 — ingests a batch of web-speech findings (the discovery output of C218)
|
||||
* into the acervo: validate the batch → acquire the media (yt-dlp for
|
||||
* YouTube/Instagram, direct HTTP for radio/audio) → transcribe with timestamps
|
||||
* → classify → mirror the artifact privately → upsert idempotently. Re-running
|
||||
* never duplicates and never overwrites a manual facet curation; every run
|
||||
* prints and writes an honest report (found/new/updated/skipped/failures,
|
||||
* time and ASR cost).
|
||||
*
|
||||
* The report lands under `data/falas-web/reports/` (gitignored); the mirrored
|
||||
* media goes to the private collection (temp files are removed after each
|
||||
* finding). The local-DB guard refuses a non-local DATABASE_URL, and any write
|
||||
* run targeting production (or a remote/override DB) additionally requires
|
||||
* `FALAS_WEB_IMPORT_CONFIRM=1`.
|
||||
*
|
||||
* Usage:
|
||||
* pnpm falas-web:import --findings data/falas-web/lote.json
|
||||
* pnpm falas-web:import --findings lote.json --dry-run
|
||||
* pnpm falas-web:import --findings lote.json --limit 3
|
||||
* pnpm falas-web:import --findings lote.json --reprocess
|
||||
* FALAS_WEB_IMPORT_CONFIRM=1 pnpm falas-web:import --findings lote.json
|
||||
*/
|
||||
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
||||
import { dirname, join } from 'node:path'
|
||||
|
||||
import { getPayload } from 'payload'
|
||||
|
||||
import { assertLocalDatabase } from './assert-local-database.mjs'
|
||||
import { assertWriteConfirm, databaseTarget, dieWithLabel, loadCliEnv } from './lib/cli.mjs'
|
||||
import { resolveFfmpeg } from './lib/mediaBinaries.mjs'
|
||||
import {
|
||||
formatWebSpeechReport,
|
||||
planWebSpeechBatch,
|
||||
summarizePlannedActions,
|
||||
summarizeWebSpeechResults,
|
||||
webSpeechPlannedAction,
|
||||
webSpeechReportStamp,
|
||||
} from './lib/webSpeeches.mjs'
|
||||
|
||||
loadCliEnv()
|
||||
|
||||
const die = dieWithLabel('falas-web:import')
|
||||
|
||||
const config = (await import('../src/payload.config.ts')).default
|
||||
const { parseWebSpeechBatch } = await import('../src/lib/webSpeech.ts')
|
||||
const { findSpeechImportState } = await import('../src/utilities/speech/speechImport.ts')
|
||||
const { ingestWebSpeech } = await import('../src/utilities/speech/webSpeechIngest.ts')
|
||||
|
||||
const WRITE_CONFIRM_FLAG = 'FALAS_WEB_IMPORT_CONFIRM'
|
||||
const DEFAULT_OUT_DIR = 'data/falas-web'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CLI
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const parseArgs = (argv) => {
|
||||
const options = {
|
||||
findings: null,
|
||||
out: DEFAULT_OUT_DIR,
|
||||
limit: null,
|
||||
dryRun: false,
|
||||
reprocess: false,
|
||||
help: false,
|
||||
}
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const arg = argv[index]
|
||||
const value = () => {
|
||||
const next = argv[++index]
|
||||
if (next === undefined || next.startsWith('--')) die(`faltou valor para ${arg}.`)
|
||||
return next
|
||||
}
|
||||
if (arg === '--help' || arg === '-h') options.help = true
|
||||
else if (arg === '--findings') options.findings = value()
|
||||
else if (arg === '--out') options.out = value()
|
||||
else if (arg === '--limit') options.limit = Number(value())
|
||||
else if (arg === '--dry-run') options.dryRun = true
|
||||
else if (arg === '--reprocess') options.reprocess = true
|
||||
else die(`argumento desconhecido: ${arg}`)
|
||||
}
|
||||
if (options.help) return options
|
||||
if (!options.findings) die('informe --findings <arquivo.json> (veja --help).')
|
||||
if (options.limit !== null && (!Number.isInteger(options.limit) || options.limit < 1)) {
|
||||
die('--limit deve ser >= 1.')
|
||||
}
|
||||
if (options.out.includes('..')) die('--out não pode escapar do diretório do repo (sem "..").')
|
||||
return options
|
||||
}
|
||||
|
||||
const HELP = `
|
||||
Uso: pnpm falas-web:import --findings <arquivo.json> [opções]
|
||||
|
||||
O lote é o JSON da descoberta (C218): { generatedAt?, findings: [...] }.
|
||||
Cada achado: platform (youtube|instagram|radio|audio), url, publishedAt e —
|
||||
para radio|audio — mediaUrl (arquivo direto). externalId/title/channel/
|
||||
durationSeconds/thumbnailUrl são opcionais e o yt-dlp completa lacunas.
|
||||
|
||||
Opções:
|
||||
--findings <arquivo> lote de achados (obrigatório)
|
||||
--out <dir> diretório dos relatórios (default data/falas-web)
|
||||
--limit <n> processa no máximo n achados
|
||||
--dry-run planeja o lote (lê o catálogo) sem baixar nem escrever
|
||||
--reprocess refaz download/transcrição mesmo com item completo
|
||||
--help esta ajuda
|
||||
|
||||
Sucesso parcial sai com código 0 (as falhas ficam no relatório); código 1
|
||||
quando nenhum achado entrou no catálogo.
|
||||
|
||||
Escrita em alvo não-local ou com NODE_ENV=production exige
|
||||
${WRITE_CONFIRM_FLAG}=1. O binário do yt-dlp vem de YTDLP_PATH ou do PATH;
|
||||
instale com \`pipx install yt-dlp\` (o ffmpeg empacotado é usado se não houver
|
||||
no PATH).
|
||||
`
|
||||
|
||||
const writeReport = async (options, report) => {
|
||||
const reportPath = join(
|
||||
options.out,
|
||||
'reports',
|
||||
`falas-web-${webSpeechReportStamp(report.runAt)}.json`,
|
||||
)
|
||||
await mkdir(dirname(reportPath), { recursive: true })
|
||||
await writeFile(reportPath, JSON.stringify(report, null, 2))
|
||||
return reportPath
|
||||
}
|
||||
|
||||
/** The packaged ffmpeg fallback keeps the operator flow working without a system binary. */
|
||||
const ensureFfmpeg = async () => {
|
||||
if (process.env.FFMPEG_PATH?.trim()) return
|
||||
const resolved = await resolveFfmpeg({
|
||||
audio: true,
|
||||
filters: [],
|
||||
requirementsLabel: 'libmp3lame para extrair o áudio',
|
||||
})
|
||||
process.env.FFMPEG_PATH = resolved.bin
|
||||
console.log(`[falas-web:import] ffmpeg: ${resolved.bin} (${resolved.source})`)
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const options = parseArgs(process.argv.slice(2))
|
||||
if (options.help) {
|
||||
console.log(HELP)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
if (options.dryRun) {
|
||||
if (!process.env.DATABASE_URL) die('DATABASE_URL não definida; recusando continuar.')
|
||||
} else {
|
||||
assertWriteConfirm({
|
||||
label: 'falas-web:import',
|
||||
flag: WRITE_CONFIRM_FLAG,
|
||||
command: 'pnpm falas-web:import',
|
||||
})
|
||||
assertLocalDatabase(
|
||||
'falas-web:import',
|
||||
`A ingestão escreve no acervo; produção exige ${WRITE_CONFIRM_FLAG}=1.`,
|
||||
)
|
||||
}
|
||||
console.log(
|
||||
`[falas-web:import] alvo: ${databaseTarget()} | modo: ${options.dryRun ? 'dry-run (read-only)' : options.reprocess ? 'import (--reprocess)' : 'import'}`,
|
||||
)
|
||||
|
||||
const envelope = parseWebSpeechBatch(JSON.parse(await readFile(options.findings, 'utf8')))
|
||||
if (!envelope.ok) die(envelope.error)
|
||||
const plan = planWebSpeechBatch(envelope.batch.findings)
|
||||
const entries = options.limit ? plan.entries.slice(0, options.limit) : plan.entries
|
||||
if (envelope.batch.findings.length > 0 && entries.length === 0) {
|
||||
die('nenhum achado válido no lote — corrija o JSON (inválidos/duplicados no relatório).')
|
||||
}
|
||||
const runAt = new Date().toISOString()
|
||||
|
||||
const payload = await getPayload({ config })
|
||||
const startedAt = Date.now()
|
||||
|
||||
if (options.dryRun) {
|
||||
const planned = []
|
||||
for (const entry of entries) {
|
||||
const state = await findSpeechImportState(payload, entry.sourceKey)
|
||||
planned.push({
|
||||
sourceKey: entry.sourceKey,
|
||||
platform: entry.finding.platform,
|
||||
action: webSpeechPlannedAction(state, options.reprocess),
|
||||
})
|
||||
}
|
||||
const report = {
|
||||
runAt,
|
||||
mode: 'dry-run',
|
||||
batchGeneratedAt: envelope.batch.generatedAt,
|
||||
findings: envelope.batch.findings.length,
|
||||
planned: entries.length,
|
||||
invalid: plan.invalid,
|
||||
duplicates: plan.duplicates,
|
||||
plannedActions: summarizePlannedActions(planned),
|
||||
plannedEntries: planned,
|
||||
durationMs: Date.now() - startedAt,
|
||||
}
|
||||
const reportPath = await writeReport(options, report)
|
||||
for (const line of formatWebSpeechReport({ ...report, failures: [] })) console.log(line)
|
||||
console.log(`\n[falas-web:import] relatório JSON: ${reportPath}`)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
await ensureFfmpeg()
|
||||
|
||||
const results = []
|
||||
for (const entry of entries) {
|
||||
console.log(`[falas-web:import] ${entry.sourceKey}`)
|
||||
const result = await ingestWebSpeech(payload, entry.finding, { reprocess: options.reprocess })
|
||||
results.push(result)
|
||||
console.log(
|
||||
` → ${result.status}${result.stage ? ` (${result.stage})` : ''}${result.error ? `: ${result.error}` : ''}`,
|
||||
)
|
||||
}
|
||||
|
||||
const summary = summarizeWebSpeechResults(results)
|
||||
const report = {
|
||||
runAt,
|
||||
mode: 'import',
|
||||
batchGeneratedAt: envelope.batch.generatedAt,
|
||||
findings: envelope.batch.findings.length,
|
||||
planned: entries.length,
|
||||
invalid: plan.invalid,
|
||||
duplicates: plan.duplicates,
|
||||
reprocess: options.reprocess,
|
||||
...summary,
|
||||
durationMs: Date.now() - startedAt,
|
||||
}
|
||||
const reportPath = await writeReport(options, report)
|
||||
for (const line of formatWebSpeechReport(report)) console.log(line)
|
||||
console.log(`\n[falas-web:import] relatório JSON: ${reportPath}`)
|
||||
|
||||
const succeeded = summary.created + summary.updated + summary.skipped
|
||||
if (summary.failed > 0 && succeeded === 0) {
|
||||
die('nenhum achado entrou no catálogo — falhas listadas no relatório.')
|
||||
}
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(error)
|
||||
die(error?.message || String(error))
|
||||
})
|
||||
|
|
@ -216,7 +216,12 @@ export async function resolveOfficialPdfUrl(legacyUrl, { timeoutMs = 180_000, at
|
|||
throw lastError
|
||||
}
|
||||
|
||||
export const DEEPINFRA_COST_PER_MINUTE_USD = 0.00045
|
||||
/**
|
||||
* Provider price (~US$ per audio minute). The app-side owner is
|
||||
* `src/utilities/ai/deepInfraTranscribe.ts` (C215) — re-exported here so the
|
||||
* Câmara scripts and the web ingestion always report the same number.
|
||||
*/
|
||||
export { DEEPINFRA_TRANSCRIBE_COST_PER_MINUTE_USD as DEEPINFRA_COST_PER_MINUTE_USD } from '../../src/utilities/ai/deepInfraTranscribe.ts'
|
||||
|
||||
/**
|
||||
* Sends the excerpt MP4 (video/mp4 is accepted; no ffmpeg) to Deep Infra's
|
||||
|
|
|
|||
|
|
@ -194,6 +194,33 @@ export const requiresWriteConfirm = ({
|
|||
allowRemoteDb = isRemoteDbOverrideSet(),
|
||||
} = {}) => nodeEnv === 'production' || allowRemoteDb || !isLocalDatabaseUrl(databaseUrl)
|
||||
|
||||
/** Human label of the write target for the guard messages (`host/name`). */
|
||||
export const databaseTarget = () => {
|
||||
const url = process.env.DATABASE_URL
|
||||
const host = databaseHostname(url)
|
||||
if (host === null) return '(DATABASE_URL ausente ou inválida)'
|
||||
return `${host}${new URL(url).pathname}`
|
||||
}
|
||||
|
||||
/**
|
||||
* C155/C215 write guard shared by the import CLIs: a non-local/production
|
||||
* target (or the `ALLOW_REMOTE_DB` escape) refuses the run unless the command's
|
||||
* own intent flag is set. The homeserver env sets `NODE_ENV=production` and the
|
||||
* proxy rewrites the DB host, so the explicit flag is what makes the write
|
||||
* deliberate.
|
||||
*
|
||||
* @param {{ label: string, flag: string, command: string, hint?: string }} options
|
||||
*/
|
||||
export const assertWriteConfirm = ({ label, flag, command, hint = '' }) => {
|
||||
if (!requiresWriteConfirm()) return
|
||||
if (isTruthyEnv(process.env[flag])) return
|
||||
dieWithLabel(label)(
|
||||
`alvo de escrita não-local/produção detectado (${databaseTarget()}).\n` +
|
||||
`Confirme a intenção com:\n ${flag}=1 ${command} …` +
|
||||
(hint ? `\n${hint}` : ''),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Port for `next dev` (OPS40). Next's CLI resolves its port via commander's
|
||||
* `.env('PORT')` BEFORE `@next/env` loads `.env.local`, so a `PORT` written by
|
||||
|
|
|
|||
|
|
@ -47,6 +47,10 @@ export const E2E_CURATED_SPECS = [
|
|||
// and the vote share sheet are new contracts over the C211 collection
|
||||
// (curated only).
|
||||
'frontendConteudos',
|
||||
// C219 — deliberate: the recordings acervo gained its own search/facet
|
||||
// contract and the migration makes every PR of this delivery high-risk
|
||||
// (curated only).
|
||||
'campaignSpeechAcervo',
|
||||
]
|
||||
|
||||
/**
|
||||
|
|
@ -443,6 +447,10 @@ export const E2E_AFFECTED_MANIFEST = [
|
|||
'src/components/campaign/reels',
|
||||
// C199 — the uploaded recordings source and its private media owner.
|
||||
'src/components/campaign/recording',
|
||||
// C219 — the recording collection owns the facet/provenance hooks the
|
||||
// recordings list filters on (the PR is high-risk anyway; the entry keeps
|
||||
// the mapping honest for the curated/local paths).
|
||||
'src/collections/Recording.ts',
|
||||
// C211 — the Central de Conteúdos surfaces.
|
||||
'src/components/campaign/content',
|
||||
'src/utilities/speech',
|
||||
|
|
@ -454,6 +462,11 @@ export const E2E_AFFECTED_MANIFEST = [
|
|||
'src/utilities/privateMedia',
|
||||
'src/utilities/media',
|
||||
'src/lib/speech',
|
||||
// C215 — the web-speech contract, its collection and the private mirror
|
||||
// collection drive the same acervo vertical.
|
||||
'src/lib/webSpeech',
|
||||
'src/collections/Speech.ts',
|
||||
'src/collections/InternetSpeechMedia.ts',
|
||||
'src/lib/reel',
|
||||
'src/lib/recording',
|
||||
'src/lib/contentPiece',
|
||||
|
|
|
|||
149
scripts/lib/mediaBinaries.mjs
Normal file
149
scripts/lib/mediaBinaries.mjs
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
/**
|
||||
* Generic external-binary plumbing of the CLI tools: a process runner that
|
||||
* never throws, a fail-closed capability probe and the ffmpeg resolution
|
||||
* (`FFMPEG_PATH` → `ffmpeg` on PATH → the registry-packaged
|
||||
* `@ffmpeg-installer/ffmpeg` binary). Extracted from the reel composer (C196)
|
||||
* so the web-speech ingestion (C215) reuses the same owner instead of a second
|
||||
* resolver.
|
||||
*
|
||||
* Resolution order (see `docs/plans/reels-tutoriais-impl.md`, Decisão 2): the
|
||||
* packed fallback keeps the non-technical operator flow working on a
|
||||
* workstation without a system ffmpeg; the homeserver Docker build installs it
|
||||
* from npm (never from GitHub releases, which the homeserver cannot reach — see
|
||||
* the sharp override note in `pnpm-workspace.yaml`).
|
||||
*/
|
||||
|
||||
import { execFile } from 'node:child_process'
|
||||
import { promisify } from 'node:util'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
const DEFAULT_MAX_BUFFER_BYTES = 16 * 1024 * 1024
|
||||
|
||||
/**
|
||||
* @typedef {{ ok: boolean, stdout: string, stderr: string, error?: { code?: string } }} RunResult
|
||||
* @typedef {(bin: string, args: string[]) => Promise<RunResult>} RunFn
|
||||
*/
|
||||
|
||||
/**
|
||||
* Runs a process and returns the exit outcome instead of throwing.
|
||||
*
|
||||
* @type {(bin: string, args: string[]) => Promise<RunResult>}
|
||||
*/
|
||||
export const runProcess = async (bin, args) => {
|
||||
try {
|
||||
const { stdout, stderr } = await execFileAsync(bin, args, {
|
||||
maxBuffer: DEFAULT_MAX_BUFFER_BYTES,
|
||||
})
|
||||
return { ok: true, stdout, stderr }
|
||||
} catch (error) {
|
||||
return { ok: false, stdout: error.stdout ?? '', stderr: error.stderr ?? '', error }
|
||||
}
|
||||
}
|
||||
|
||||
const defaultRun = runProcess
|
||||
|
||||
const versionLine = (stdout) =>
|
||||
stdout.split('\n').find((line) => line.startsWith('ffmpeg version')) ?? ''
|
||||
|
||||
/**
|
||||
* Capability probe: the binary must run and ship every required encoder and
|
||||
* filter. Missing capabilities are reported, never assumed.
|
||||
*
|
||||
* @param {string} bin
|
||||
* @param {{ run?: RunFn, audio?: boolean, encoders?: string[], filters?: string[] }} [options]
|
||||
* @returns {Promise<{ ok: true, bin: string, version: string } | { ok: false, bin: string, reason: string }>}
|
||||
*/
|
||||
export const probeFfmpeg = async (
|
||||
bin,
|
||||
{ run = defaultRun, audio = false, encoders = [], filters = [] } = {},
|
||||
) => {
|
||||
const version = await run(bin, ['-hide_banner', '-version'])
|
||||
if (!version.ok) {
|
||||
return { ok: false, bin, reason: `não executou (${version.error?.code ?? 'erro'})` }
|
||||
}
|
||||
|
||||
const requiredEncoders = [...encoders, ...(audio ? ['libmp3lame'] : [])]
|
||||
if (requiredEncoders.length > 0) {
|
||||
const listed = await run(bin, ['-hide_banner', '-encoders'])
|
||||
const missing = requiredEncoders.filter(
|
||||
(encoder) => !listed.ok || !new RegExp(`\\b${encoder}\\b`).test(listed.stdout),
|
||||
)
|
||||
if (missing.length > 0) return { ok: false, bin, reason: `sem encoder ${missing.join(', ')}` }
|
||||
}
|
||||
|
||||
if (filters.length > 0) {
|
||||
const listed = await run(bin, ['-hide_banner', '-filters'])
|
||||
if (!listed.ok) return { ok: false, bin, reason: 'não listou filtros' }
|
||||
const missing = filters.filter((filter) => !new RegExp(`\\b${filter}\\b`).test(listed.stdout))
|
||||
if (missing.length > 0)
|
||||
return { ok: false, bin, reason: `sem filtro(s): ${missing.join(', ')}` }
|
||||
}
|
||||
|
||||
return { ok: true, bin, version: versionLine(version.stdout) }
|
||||
}
|
||||
|
||||
const FFMPEG_INSTALL_HINT =
|
||||
'Defina FFMPEG_PATH, instale o ffmpeg (ex.: `sudo apt install ffmpeg`) ou rode `pnpm install` para o binário empacotado.'
|
||||
|
||||
/**
|
||||
* Resolves the first candidate that passes the probe. Explicit `FFMPEG_PATH` is strict.
|
||||
*
|
||||
* @param {{ env?: Record<string, string | undefined>, run?: RunFn, installer?: { path?: string } | null, audio?: boolean, encoders?: string[], filters?: string[], requirementsLabel?: string, installHint?: string }} [options]
|
||||
* @returns {Promise<{ ok: true, bin: string, version: string, source: string }>}
|
||||
*/
|
||||
export const resolveFfmpeg = async ({
|
||||
env = process.env,
|
||||
run = defaultRun,
|
||||
installer,
|
||||
audio = false,
|
||||
encoders = [],
|
||||
filters = [],
|
||||
requirementsLabel = '',
|
||||
installHint = FFMPEG_INSTALL_HINT,
|
||||
} = {}) => {
|
||||
let packaged = installer
|
||||
if (packaged === undefined) {
|
||||
try {
|
||||
packaged = (await import('@ffmpeg-installer/ffmpeg')).default
|
||||
} catch {
|
||||
// The packaged binary throws on import when its platform package is
|
||||
// missing; the probe below decides, never the import.
|
||||
packaged = null
|
||||
}
|
||||
}
|
||||
const candidates = []
|
||||
const explicit = env.FFMPEG_PATH?.trim()
|
||||
if (explicit) candidates.push({ bin: explicit, source: 'FFMPEG_PATH', strict: true })
|
||||
candidates.push({ bin: 'ffmpeg', source: 'PATH', strict: false })
|
||||
if (packaged?.path) candidates.push({ bin: packaged.path, source: 'empacotado', strict: false })
|
||||
|
||||
const failures = []
|
||||
for (const candidate of candidates) {
|
||||
const probe = await probeFfmpeg(candidate.bin, { run, audio, encoders, filters })
|
||||
if (probe.ok) {
|
||||
return { ok: true, bin: probe.bin, version: probe.version, source: candidate.source }
|
||||
}
|
||||
failures.push(`${candidate.source}: ${probe.reason}`)
|
||||
if (candidate.strict) break
|
||||
}
|
||||
|
||||
const suffix = requirementsLabel ? ` (${requirementsLabel})` : ''
|
||||
throw new Error(`Nenhum ffmpeg utilizável${suffix}. ${failures.join('; ')}. ${installHint}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a process and fails with the stderr tail — never swallows the exit
|
||||
* code. Shared by the CLI tools (ffmpeg and edge-tts).
|
||||
*
|
||||
* @param {string} bin
|
||||
* @param {string[]} args
|
||||
* @param {{ run?: RunFn, label?: string }} [options]
|
||||
*/
|
||||
export const runTool = async (bin, args, { run = defaultRun, label = 'processo' } = {}) => {
|
||||
const result = await run(bin, args)
|
||||
if (!result.ok) {
|
||||
const tail = (result.stderr || result.error?.message || '').trim().slice(-400)
|
||||
throw new Error(`${label} falhou${tail ? `: ${tail}` : ''}`)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
|
@ -1,29 +1,24 @@
|
|||
/**
|
||||
* C196 — ffmpeg plumbing of the reel composer: binary resolution with a
|
||||
* fail-closed capability probe, the per-scene clip command (zoompan + burned
|
||||
* caption overlays) and the concat that stitches the scenes into `reel.mp4`.
|
||||
*
|
||||
* Resolution order (see `docs/plans/reels-tutoriais-impl.md`, Decisão 2):
|
||||
* `FFMPEG_PATH` → `ffmpeg` on PATH → the registry-packaged
|
||||
* `@ffmpeg-installer/ffmpeg` binary. The packed fallback keeps the
|
||||
* non-technical operator flow working on a workstation without a system
|
||||
* ffmpeg; the homeserver Docker build installs it from npm (never from GitHub
|
||||
* releases, which the homeserver cannot reach — see the sharp override note in
|
||||
* `pnpm-workspace.yaml`).
|
||||
* C196 — ffmpeg plumbing of the reel composer: the per-scene clip command
|
||||
* (zoompan + burned caption overlays) and the concat that stitches the scenes
|
||||
* into `reel.mp4`. The generic binary resolution/probe/runner (C215 moved them
|
||||
* to `mediaBinaries.mjs`) is re-exported here so the reel tools and their unit
|
||||
* pins keep the same import surface; the reel requirements (libx264 + the
|
||||
* composer filters, `atempo` when audio) are injected into the wrappers.
|
||||
*/
|
||||
|
||||
import { execFile } from 'node:child_process'
|
||||
import { writeFile } from 'node:fs/promises'
|
||||
import { promisify } from 'node:util'
|
||||
|
||||
import {
|
||||
probeFfmpeg as probeFfmpegBin,
|
||||
resolveFfmpeg as resolveFfmpegBin,
|
||||
runProcess,
|
||||
runTool,
|
||||
} from './mediaBinaries.mjs'
|
||||
import { NARRATION_PCM } from './reelScript.mjs'
|
||||
import { seconds } from './reelTimeline.mjs'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
const MAX_BUFFER_BYTES = 16 * 1024 * 1024
|
||||
|
||||
const REQUIRED_FILTERS = ['fade', 'overlay', 'scale', 'zoompan']
|
||||
const AUDIO_REQUIRED_ENCODER = 'libmp3lame'
|
||||
const AUDIO_REQUIRED_FILTERS = ['atempo']
|
||||
export const REEL_PRESET = 'medium'
|
||||
export const REEL_CRF = 18
|
||||
|
|
@ -38,25 +33,7 @@ export const PREVIEW_CRF = 14
|
|||
* @typedef {(bin: string, args: string[]) => Promise<{ ok: boolean, stdout: string, stderr: string, error?: { code?: string } }>} RunFn
|
||||
*/
|
||||
|
||||
/**
|
||||
* Generic process runner shared by the reel tools (ffmpeg and edge-tts): never
|
||||
* throws, returns the exit outcome.
|
||||
*
|
||||
* @type {RunFn}
|
||||
*/
|
||||
export const runProcess = async (bin, args) => {
|
||||
try {
|
||||
const { stdout, stderr } = await execFileAsync(bin, args, { maxBuffer: MAX_BUFFER_BYTES })
|
||||
return { ok: true, stdout, stderr }
|
||||
} catch (error) {
|
||||
return { ok: false, stdout: error.stdout ?? '', stderr: error.stderr ?? '', error }
|
||||
}
|
||||
}
|
||||
|
||||
const defaultRun = runProcess
|
||||
|
||||
const versionLine = (stdout) =>
|
||||
stdout.split('\n').find((line) => line.startsWith('ffmpeg version')) ?? ''
|
||||
export { runProcess, runTool }
|
||||
|
||||
/**
|
||||
* Capability probe: the binary must encode H.264 (libx264) and ship the
|
||||
|
|
@ -66,90 +43,28 @@ const versionLine = (stdout) =>
|
|||
* @param {{ run?: RunFn, audio?: boolean }} [options]
|
||||
* @returns {Promise<{ ok: true, bin: string, version: string } | { ok: false, bin: string, reason: string }>}
|
||||
*/
|
||||
export const probeFfmpeg = async (bin, { run = defaultRun, audio = false } = {}) => {
|
||||
const version = await run(bin, ['-hide_banner', '-version'])
|
||||
if (!version.ok)
|
||||
return { ok: false, bin, reason: `não executou (${version.error?.code ?? 'erro'})` }
|
||||
const encoders = await run(bin, ['-hide_banner', '-encoders'])
|
||||
if (!encoders.ok || !/\blibx264\b/.test(encoders.stdout)) {
|
||||
return { ok: false, bin, reason: 'sem encoder libx264' }
|
||||
}
|
||||
if (audio && !new RegExp(`\\b${AUDIO_REQUIRED_ENCODER}\\b`).test(encoders.stdout)) {
|
||||
return { ok: false, bin, reason: `sem encoder ${AUDIO_REQUIRED_ENCODER}` }
|
||||
}
|
||||
const filters = await run(bin, ['-hide_banner', '-filters'])
|
||||
if (!filters.ok) return { ok: false, bin, reason: 'não listou filtros' }
|
||||
const requiredFilters = audio
|
||||
? [...REQUIRED_FILTERS, ...AUDIO_REQUIRED_FILTERS]
|
||||
: REQUIRED_FILTERS
|
||||
const missing = requiredFilters.filter(
|
||||
(filter) => !new RegExp(`\\b${filter}\\b`).test(filters.stdout),
|
||||
)
|
||||
if (missing.length > 0) return { ok: false, bin, reason: `sem filtro(s): ${missing.join(', ')}` }
|
||||
return { ok: true, bin, version: versionLine(version.stdout) }
|
||||
}
|
||||
|
||||
const installHint =
|
||||
'Defina FFMPEG_PATH, instale o ffmpeg (ex.: `sudo apt install ffmpeg`) ou rode `pnpm install` para o binário empacotado.'
|
||||
export const probeFfmpeg = (bin, { audio = false, ...options } = {}) =>
|
||||
probeFfmpegBin(bin, {
|
||||
...options,
|
||||
audio,
|
||||
encoders: ['libx264'],
|
||||
filters: [...REQUIRED_FILTERS, ...(audio ? AUDIO_REQUIRED_FILTERS : [])],
|
||||
})
|
||||
|
||||
/**
|
||||
* Resolves the first candidate that passes the probe. Explicit `FFMPEG_PATH` is strict.
|
||||
* Resolves the first candidate that passes the reel probe. Explicit
|
||||
* `FFMPEG_PATH` is strict.
|
||||
*
|
||||
* @param {{ env?: Record<string, string | undefined>, run?: RunFn, installer?: { path?: string } | null, audio?: boolean }} [options]
|
||||
* @returns {Promise<{ ok: true, bin: string, version: string, source: string }>}
|
||||
*/
|
||||
export const resolveFfmpeg = async ({
|
||||
env = process.env,
|
||||
run = defaultRun,
|
||||
installer,
|
||||
audio = false,
|
||||
} = {}) => {
|
||||
let packaged = installer
|
||||
if (packaged === undefined) {
|
||||
try {
|
||||
packaged = (await import('@ffmpeg-installer/ffmpeg')).default
|
||||
} catch {
|
||||
// The packaged binary throws on import when its platform package is
|
||||
// missing; the probe below decides, never the import.
|
||||
packaged = null
|
||||
}
|
||||
}
|
||||
const candidates = []
|
||||
const explicit = env.FFMPEG_PATH?.trim()
|
||||
if (explicit) candidates.push({ bin: explicit, source: 'FFMPEG_PATH', strict: true })
|
||||
candidates.push({ bin: 'ffmpeg', source: 'PATH', strict: false })
|
||||
if (packaged?.path) candidates.push({ bin: packaged.path, source: 'empacotado', strict: false })
|
||||
const failures = []
|
||||
for (const candidate of candidates) {
|
||||
const probe = await probeFfmpeg(candidate.bin, { run, audio })
|
||||
if (probe.ok) {
|
||||
return { ok: true, bin: probe.bin, version: probe.version, source: candidate.source }
|
||||
}
|
||||
failures.push(`${candidate.source}: ${probe.reason}`)
|
||||
if (candidate.strict) break
|
||||
}
|
||||
throw new Error(
|
||||
`Nenhum ffmpeg utilizável (libx264 + filtros do reel${audio ? ' + áudio' : ''}). ${failures.join('; ')}. ${installHint}`,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a process and fails with the stderr tail — never swallows the exit
|
||||
* code. Shared by the reel tools (ffmpeg and edge-tts); `runFfmpeg` is the
|
||||
* ffmpeg-labelled alias kept for the historical call sites.
|
||||
*
|
||||
* @param {string} bin
|
||||
* @param {string[]} args
|
||||
* @param {{ run?: RunFn, label?: string }} [options]
|
||||
*/
|
||||
export const runTool = async (bin, args, { run = defaultRun, label = 'processo' } = {}) => {
|
||||
const result = await run(bin, args)
|
||||
if (!result.ok) {
|
||||
const tail = (result.stderr || result.error?.message || '').trim().slice(-400)
|
||||
throw new Error(`${label} falhou${tail ? `: ${tail}` : ''}`)
|
||||
}
|
||||
return result
|
||||
}
|
||||
export const resolveFfmpeg = (options = {}) =>
|
||||
resolveFfmpegBin({
|
||||
requirementsLabel: `libx264 + filtros do reel${options.audio ? ' + áudio' : ''}`,
|
||||
...options,
|
||||
encoders: ['libx264'],
|
||||
filters: [...REQUIRED_FILTERS, ...(options.audio ? AUDIO_REQUIRED_FILTERS : [])],
|
||||
})
|
||||
|
||||
/** @type {typeof runTool} */
|
||||
export const runFfmpeg = (bin, args, options = {}) =>
|
||||
|
|
@ -284,7 +199,7 @@ export const encodeFrames = async ({
|
|||
preset = PREVIEW_PRESET,
|
||||
crf = PREVIEW_CRF,
|
||||
writeFileImpl = writeFile,
|
||||
run = defaultRun,
|
||||
run = runProcess,
|
||||
}) => {
|
||||
await writeFileImpl(listPath, buildFrameListContent({ frames, fps }))
|
||||
await runFfmpeg(
|
||||
|
|
|
|||
|
|
@ -82,6 +82,7 @@ export const SCRIPTS_SPEC_PINNED = [
|
|||
'scripts/lib/imageResize.mjs',
|
||||
'scripts/lib/issues-panel.mjs',
|
||||
'scripts/lib/markdown-ansi.mjs',
|
||||
'scripts/lib/mediaBinaries.mjs',
|
||||
'scripts/lib/plansOnlyClosesGuard.mjs',
|
||||
'scripts/lib/playwright-e2e-args.mjs',
|
||||
'scripts/lib/portalTransparenciaEmendas.mjs',
|
||||
|
|
@ -99,6 +100,7 @@ export const SCRIPTS_SPEC_PINNED = [
|
|||
'scripts/lib/staging-test-account.mjs',
|
||||
'scripts/lib/test-affected-core.mjs',
|
||||
'scripts/lib/testing-audit-metrics-core.mjs',
|
||||
'scripts/lib/webSpeeches.mjs',
|
||||
'scripts/lib/worktree-env.mjs',
|
||||
'scripts/lib/worktree.mjs',
|
||||
'scripts/lib/wpArticles.mjs',
|
||||
|
|
|
|||
131
scripts/lib/webSpeeches.mjs
Normal file
131
scripts/lib/webSpeeches.mjs
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
/**
|
||||
* C215 — pure planning/reporting of the web-speech ingestion CLI: validate the
|
||||
* batch (one invalid finding fails only itself), dedupe by natural key, decide
|
||||
* the planned action per entry and aggregate the run report. No I/O: the unit
|
||||
* specs read this module and `import-web-speeches.mjs` is the impure shell.
|
||||
*/
|
||||
|
||||
import { formatSpeechSpan } from '../../src/lib/speechClock.ts'
|
||||
import {
|
||||
isCompleteWebSpeechState,
|
||||
parseWebSpeechFinding,
|
||||
webSpeechSourceKey,
|
||||
} from '../../src/lib/webSpeech.ts'
|
||||
|
||||
/** @typedef {import('../../src/lib/webSpeech.ts').WebSpeechFinding} WebSpeechFinding */
|
||||
/** @typedef {import('../../src/utilities/speech/webSpeechIngest.ts').WebSpeechIngestResult} WebSpeechIngestResult */
|
||||
|
||||
export { isCompleteWebSpeechState }
|
||||
|
||||
/**
|
||||
* @param {unknown[]} findings
|
||||
* @returns {{ entries: Array<{ index: number, sourceKey: string, finding: WebSpeechFinding }>, invalid: Array<{ index: number, error: string }>, duplicates: Array<{ index: number, sourceKey: string }> }}
|
||||
*/
|
||||
export const planWebSpeechBatch = (findings) => {
|
||||
const entries = []
|
||||
const invalid = []
|
||||
const duplicates = []
|
||||
const seen = new Set()
|
||||
|
||||
findings.forEach((raw, index) => {
|
||||
const parsed = parseWebSpeechFinding(raw)
|
||||
if (!parsed.ok) {
|
||||
invalid.push({ index, error: parsed.error })
|
||||
return
|
||||
}
|
||||
const sourceKey = webSpeechSourceKey(parsed.finding)
|
||||
if (seen.has(sourceKey)) {
|
||||
duplicates.push({ index, sourceKey })
|
||||
return
|
||||
}
|
||||
seen.add(sourceKey)
|
||||
entries.push({ index, sourceKey, finding: parsed.finding })
|
||||
})
|
||||
|
||||
return { entries, invalid, duplicates }
|
||||
}
|
||||
|
||||
/** What a re-run would do to an entry, from its stored state. */
|
||||
export const webSpeechPlannedAction = (state, reprocess = false) => {
|
||||
if (state === null) return 'novo'
|
||||
if (!isCompleteWebSpeechState(state)) return 'atualizado'
|
||||
return reprocess ? 'reprocessado' : 'ignorado'
|
||||
}
|
||||
|
||||
/** @param {WebSpeechIngestResult[]} results */
|
||||
export const summarizeWebSpeechResults = (results) => {
|
||||
const count = (status) => results.filter((result) => result.status === status).length
|
||||
const sum = (pick) => results.reduce((total, result) => total + (Number(pick(result)) || 0), 0)
|
||||
|
||||
return {
|
||||
created: count('created'),
|
||||
updated: count('updated'),
|
||||
skipped: count('skipped'),
|
||||
failed: count('failed'),
|
||||
asrSeconds: sum((result) => result.asrSeconds),
|
||||
asrCostUsd: sum((result) => result.asrCostUsd),
|
||||
llmCostUsd: sum((result) => result.llmCostUsd),
|
||||
failures: results
|
||||
.filter((result) => result.status === 'failed')
|
||||
.map((result) => ({
|
||||
sourceKey: result.sourceKey,
|
||||
stage: result.stage ?? null,
|
||||
error: result.error ?? null,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
/** @param {Array<{ action: string }>} planned */
|
||||
export const summarizePlannedActions = (planned) => ({
|
||||
novo: planned.filter((entry) => entry.action === 'novo').length,
|
||||
atualizado: planned.filter((entry) => entry.action === 'atualizado').length,
|
||||
ignorado: planned.filter((entry) => entry.action === 'ignorado').length,
|
||||
reprocessado: planned.filter((entry) => entry.action === 'reprocessado').length,
|
||||
})
|
||||
|
||||
const secondsLabel = (seconds) => formatSpeechSpan(Math.round(seconds))
|
||||
|
||||
/**
|
||||
* Human lines for stdout; the JSON file keeps the full report. Failures are
|
||||
* never hidden — each one names its stage and reason.
|
||||
*
|
||||
* @param {ReturnType<typeof summarizeWebSpeechResults> & { runAt: string, mode: string, findings: number, planned: number, invalid: Array<{index: number, error: string}>, duplicates: Array<{index: number, sourceKey: string}>, durationMs: number, plannedActions?: Record<string, number>|null }} report
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export const formatWebSpeechReport = (report) => {
|
||||
const label = '[falas-web:import]'
|
||||
const lines = []
|
||||
lines.push(
|
||||
`${label} achados: ${report.findings} · considerados: ${report.planned} · inválidos: ${report.invalid.length} · duplicados: ${report.duplicates.length}`,
|
||||
)
|
||||
|
||||
if (report.plannedActions) {
|
||||
const actions = report.plannedActions
|
||||
lines.push(
|
||||
`${label} plano (dry-run): novos: ${actions.novo} · atualizados: ${actions.atualizado} · ignorados: ${actions.ignorado} · reprocessados: ${actions.reprocessado}`,
|
||||
)
|
||||
} else {
|
||||
const summary = report
|
||||
lines.push(
|
||||
`${label} novos: ${summary.created} · atualizados: ${summary.updated} · ignorados: ${summary.skipped} · falhas: ${summary.failed}`,
|
||||
)
|
||||
lines.push(
|
||||
`${label} tempo: ${(report.durationMs / 1000).toFixed(1)}s · ASR: ${secondsLabel(summary.asrSeconds)} (~US$ ${summary.asrCostUsd.toFixed(4)}) · LLM: US$ ${summary.llmCostUsd.toFixed(4)}`,
|
||||
)
|
||||
}
|
||||
|
||||
for (const failure of report.invalid) {
|
||||
lines.push(`${label} inválido #${failure.index}: ${failure.error}`)
|
||||
}
|
||||
if (report.failures?.length) {
|
||||
lines.push(`${label} falhas:`)
|
||||
for (const failure of report.failures) {
|
||||
lines.push(
|
||||
` - ${failure.sourceKey} (${failure.stage ?? 'desconhecido'}): ${failure.error ?? 'erro'}`,
|
||||
)
|
||||
}
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
export const webSpeechReportStamp = (runAt) => runAt.replace(/[:.]/g, '-')
|
||||
|
|
@ -5,9 +5,11 @@ import { redirect } from 'next/navigation'
|
|||
import { getPayload } from 'payload'
|
||||
|
||||
import { AcervoSourceToggle } from '@/components/campaign/recording/AcervoSourceToggle'
|
||||
import { RecordingPersonFilter } from '@/components/campaign/recording/RecordingPersonFilter'
|
||||
import { RecordingAcervoFilters } from '@/components/campaign/recording/RecordingAcervoFilters'
|
||||
import { RecordingResultList } from '@/components/campaign/recording/RecordingResultList'
|
||||
import { RecordingSortSelect } from '@/components/campaign/recording/RecordingSortSelect'
|
||||
import { RecordingStatusRefresher } from '@/components/campaign/recording/RecordingStatusRefresher'
|
||||
import { RecordingThemeFallbackNotice } from '@/components/campaign/recording/RecordingThemeFallbackNotice'
|
||||
import { RecordingUploadDialog } from '@/components/campaign/recording/RecordingUploadDialog'
|
||||
import { CampaignListEmptyState } from '@/components/campaign/shared/CampaignListEmptyState'
|
||||
import { CampaignListFooter } from '@/components/campaign/shared/CampaignListFooter'
|
||||
|
|
@ -15,21 +17,22 @@ import {
|
|||
CampaignListPendingBoundary,
|
||||
CampaignListResults,
|
||||
} from '@/components/campaign/shared/CampaignListPending'
|
||||
import { CampaignSearchInput } from '@/components/campaign/shared/CampaignSearchInput'
|
||||
import { CampaignThemeRetryButton } from '@/components/campaign/shared/CampaignThemeRetryButton'
|
||||
import { CampaignPageShell } from '@/components/campaign/shell/CampaignPageShell'
|
||||
import { SpeechAcervoFilters } from '@/components/campaign/speech/SpeechAcervoFilters'
|
||||
import { SpeechRefineSearchButton } from '@/components/campaign/speech/SpeechRefineSearchButton'
|
||||
import { SpeechResultList } from '@/components/campaign/speech/SpeechResultList'
|
||||
import { SpeechThemeFallbackNotice } from '@/components/campaign/speech/SpeechThemeFallbackNotice'
|
||||
import { SpeechThemeRetryButton } from '@/components/campaign/speech/SpeechThemeRetryButton'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { campaignPageMetadataFromCatalog } from '@/lib/campaignPageChrome'
|
||||
import { CAMPAIGN_COMMUNICATION_ACERVO, CAMPAIGN_COMMUNICATION_CORTES } from '@/lib/campaignPaths'
|
||||
import { requireCampaignPageActor } from '@/utilities/campaignPageActor'
|
||||
import {
|
||||
buildAcervoSourceHref,
|
||||
buildRecordingFiltersKey,
|
||||
buildRecordingListHref,
|
||||
parseAcervoSource,
|
||||
recordingHasActiveFilters,
|
||||
} from '@/utilities/recordings/recordingListUrl'
|
||||
import { loadRecordingsPageData } from '@/utilities/recordings/recordingPageData'
|
||||
import { buildSpeechFiltersKey, buildSpeechListHref } from '@/utilities/speech/speechListUrl'
|
||||
|
|
@ -78,80 +81,93 @@ const AcervoHeader = ({ source }: { source: 'camara' | 'enviadas' }) => (
|
|||
</div>
|
||||
)
|
||||
|
||||
const RecordingsSearchForm = ({
|
||||
query,
|
||||
people,
|
||||
}: {
|
||||
query?: string
|
||||
people?: readonly string[]
|
||||
}) => (
|
||||
<form method="get" action={CAMPAIGN_COMMUNICATION_ACERVO} className="flex flex-col gap-1.5">
|
||||
<input type="hidden" name="source" value="enviadas" />
|
||||
{/* The "Pessoa" facet survives a new textual search. */}
|
||||
{(people ?? []).map((person) => (
|
||||
<input key={person} type="hidden" name="person" value={person} />
|
||||
))}
|
||||
{/* The shared input owns the accessible label; this is its visible twin. */}
|
||||
<p className="text-sm font-medium">Buscar nas gravações enviadas</p>
|
||||
<CampaignSearchInput
|
||||
id="recording-search"
|
||||
name="q"
|
||||
label="Buscar nas gravações enviadas"
|
||||
defaultValue={query}
|
||||
placeholder="Busque por palavra ou trecho da transcrição…"
|
||||
/>
|
||||
<button type="submit" className="sr-only">
|
||||
Buscar
|
||||
</button>
|
||||
</form>
|
||||
)
|
||||
|
||||
const RecordingsSource = ({
|
||||
data,
|
||||
}: {
|
||||
data: Awaited<ReturnType<typeof loadRecordingsPageData>>
|
||||
}) => {
|
||||
const hasSearch = Boolean(data.state.q)
|
||||
const hasPeople = (data.state.people?.length ?? 0) > 0
|
||||
const hasFilters = hasSearch || hasPeople
|
||||
const hasFilters = recordingHasActiveFilters(data.state)
|
||||
const themeMode = data.state.mode === 'tema'
|
||||
const themeActive = themeMode && data.themeApplied && !data.themeUnavailable
|
||||
|
||||
return (
|
||||
<CampaignListPendingBoundary>
|
||||
<RecordingsSearchForm query={data.state.q} people={data.state.people} />
|
||||
<RecordingAcervoFilters
|
||||
key={buildRecordingFiltersKey(data.state)}
|
||||
state={data.state}
|
||||
filterOptions={data.filterOptions}
|
||||
themeUnavailable={data.themeUnavailable}
|
||||
/>
|
||||
|
||||
<RecordingPersonFilter state={data.state} options={data.filterOptions.people} />
|
||||
{data.themeUnavailable ? <RecordingThemeFallbackNotice /> : null}
|
||||
|
||||
<RecordingStatusRefresher
|
||||
recordings={data.rows.map((row) => ({ id: row.id, status: row.status }))}
|
||||
/>
|
||||
|
||||
<CampaignListResults>
|
||||
<div className="flex flex-wrap items-end justify-between gap-3">
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold">
|
||||
{data.themeUnavailable
|
||||
? 'Resultados por termo exato'
|
||||
: themeActive
|
||||
? 'Resultados por tema'
|
||||
: 'Gravações encontradas'}
|
||||
</h2>
|
||||
{themeMode ? (
|
||||
<p className="mt-0.5 text-xs text-muted-foreground">
|
||||
{data.themeUnavailable
|
||||
? 'Comportamento atual do acervo.'
|
||||
: themeActive
|
||||
? 'Confira o indício em cada gravação antes de abrir.'
|
||||
: 'Nenhum termo relacionado foi acrescentado; mostramos a busca literal.'}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex flex-wrap items-end gap-2">
|
||||
{data.themeUnavailable ? <CampaignThemeRetryButton /> : null}
|
||||
<RecordingSortSelect state={data.state} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{data.rows.length > 0 ? (
|
||||
<RecordingResultList rows={data.rows} />
|
||||
) : (
|
||||
<CampaignListEmptyState
|
||||
className="border-solid"
|
||||
className={themeActive ? 'border-solid' : undefined}
|
||||
icon={hasFilters ? SearchIcon : VideoIcon}
|
||||
title={
|
||||
hasSearch
|
||||
? `Nenhuma gravação encontrada para "${data.state.q}"`
|
||||
: hasPeople
|
||||
? 'Nenhuma gravação encontrada com esse filtro'
|
||||
: 'Nenhuma gravação enviada ainda'
|
||||
themeActive
|
||||
? 'Nenhuma gravação encontrada para este tema'
|
||||
: data.state.q
|
||||
? `Nenhuma gravação encontrada para "${data.state.q}"`
|
||||
: hasFilters
|
||||
? 'Nenhuma gravação encontrada com esses filtros'
|
||||
: 'Nenhuma gravação enviada ainda'
|
||||
}
|
||||
description={
|
||||
hasSearch
|
||||
? 'Tente outro termo ou limpe a busca para ver todas as gravações enviadas.'
|
||||
: hasPeople
|
||||
themeActive
|
||||
? 'Não encontramos uma gravação que corresponda ao sentido desta busca com os filtros atuais. Não vamos preencher a lista com resultados pouco relacionados.'
|
||||
: hasFilters
|
||||
? 'Tente outro termo, remova filtros ou limpe a busca.'
|
||||
: 'Envie um arquivo de vídeo para acompanhar a transcrição e pesquisar o conteúdo no acervo.'
|
||||
}
|
||||
>
|
||||
{hasFilters ? (
|
||||
{themeActive ? (
|
||||
<div className="flex flex-wrap items-center justify-center gap-2">
|
||||
<Button asChild className="min-h-11">
|
||||
<Link href={buildAcervoSourceHref('enviadas')}>Limpar filtros</Link>
|
||||
</Button>
|
||||
<Button asChild variant="outline" className="min-h-11">
|
||||
<Link href={buildRecordingListHref({ ...data.state, mode: undefined }, 1)}>
|
||||
Trocar para termo exato
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
) : hasFilters ? (
|
||||
<Button asChild variant="outline" className="min-h-11">
|
||||
<Link href={buildAcervoSourceHref('enviadas')}>
|
||||
{hasPeople ? 'Limpar filtros' : 'Limpar busca'}
|
||||
</Link>
|
||||
<Link href={buildAcervoSourceHref('enviadas')}>Limpar filtros</Link>
|
||||
</Button>
|
||||
) : (
|
||||
<RecordingUploadDialog triggerLabel="Enviar gravação" />
|
||||
|
|
@ -233,7 +249,7 @@ export default async function SpeechAcervoPage({ searchParams }: SpeechAcervoPag
|
|||
: 'Nenhum termo relacionado foi acrescentado; mostramos a busca literal.'}
|
||||
</p>
|
||||
</div>
|
||||
{data.themeUnavailable ? <SpeechThemeRetryButton /> : null}
|
||||
{data.themeUnavailable ? <CampaignThemeRetryButton /> : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
|
|
|
|||
|
|
@ -18,7 +18,11 @@ import { SetCampaignPageChrome } from '@/components/campaign/shell/CampaignPageC
|
|||
import { CampaignPageShell } from '@/components/campaign/shell/CampaignPageShell'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { CAMPAIGN_COMMUNICATION_CONTEUDOS } from '@/lib/campaignPaths'
|
||||
import { contentPieceOriginLabels, contentPieceTopicLabel } from '@/lib/contentPiece'
|
||||
import {
|
||||
CONTENT_PIECE_LINK_LABEL,
|
||||
contentPieceOriginLabels,
|
||||
contentPieceTopicLabel,
|
||||
} from '@/lib/contentPiece'
|
||||
import { requireCampaignPageActor } from '@/utilities/campaignPageActor'
|
||||
import {
|
||||
ContentPieceNotFoundError,
|
||||
|
|
@ -58,6 +62,38 @@ export default async function ContentPieceDetailPage({ params }: ContentPieceDet
|
|||
])
|
||||
const { piece } = data
|
||||
|
||||
// C220 — while the official extraction runs, the ficha shows the three
|
||||
// designed steps (scene 1): the link arrived, the official media is being
|
||||
// looked up (or was found), and the cataloguing follows.
|
||||
const mediaStepDone = piece.step !== null && piece.step !== 'extraindo'
|
||||
const processingSteps =
|
||||
piece.origin === 'instagram' && piece.processingStatus === 'processando' && !piece.hasFile
|
||||
? [
|
||||
{
|
||||
label: '1. Link recebido',
|
||||
stateLabel: 'Concluído',
|
||||
className: 'rounded-lg border border-green-200 bg-green-50 p-3',
|
||||
stateClassName: 'text-green-800',
|
||||
},
|
||||
{
|
||||
label: '2. Mídia oficial',
|
||||
stateLabel: mediaStepDone ? 'Concluído' : 'Em andamento',
|
||||
className: mediaStepDone
|
||||
? 'rounded-lg border border-green-200 bg-green-50 p-3'
|
||||
: 'rounded-lg border border-amber-200 bg-amber-50 p-3',
|
||||
stateClassName: mediaStepDone ? 'text-green-800' : 'text-amber-900',
|
||||
},
|
||||
{
|
||||
label: '3. Catalogação',
|
||||
stateLabel: mediaStepDone ? 'Em andamento' : 'Aguardando',
|
||||
className: mediaStepDone
|
||||
? 'rounded-lg border border-amber-200 bg-amber-50 p-3'
|
||||
: 'rounded-lg border bg-muted p-3 text-muted-foreground',
|
||||
stateClassName: mediaStepDone ? 'text-amber-900' : '',
|
||||
},
|
||||
]
|
||||
: null
|
||||
|
||||
return (
|
||||
<CampaignPageShell aria-label="Peça da Central de Conteúdos">
|
||||
<SetCampaignPageChrome chrome={{ title: piece.title }} />
|
||||
|
|
@ -117,7 +153,11 @@ export default async function ContentPieceDetailPage({ params }: ContentPieceDet
|
|||
/>
|
||||
) : (
|
||||
<div className="grid aspect-video place-items-center p-4 text-center text-xs font-semibold text-muted-foreground">
|
||||
{piece.origin === 'arquivo' ? 'Sem arquivo' : 'Peça-link'}
|
||||
{piece.origin === 'arquivo'
|
||||
? 'Sem arquivo'
|
||||
: piece.processingStatus === 'processando'
|
||||
? 'Buscando a mídia no perfil oficial…'
|
||||
: CONTENT_PIECE_LINK_LABEL}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
|
@ -162,7 +202,20 @@ export default async function ContentPieceDetailPage({ params }: ContentPieceDet
|
|||
) : null}
|
||||
</dl>
|
||||
|
||||
{!piece.hasFile ? (
|
||||
{!piece.hasFile && piece.linkFailureReasonLabel ? (
|
||||
<div className="mt-5 rounded-lg border border-amber-200 bg-amber-50 p-4">
|
||||
<p className="text-xs font-semibold text-amber-950">
|
||||
Por que o arquivo não foi baixado
|
||||
</p>
|
||||
<p className="mt-2 text-sm font-medium text-amber-950">
|
||||
{piece.linkFailureReasonLabel}
|
||||
</p>
|
||||
<p className="mt-2 text-xs leading-5 text-amber-900">
|
||||
A peça continua disponível pelo link.
|
||||
</p>
|
||||
<ContentPieceAttachFileButton contentPieceId={piece.id} className="mt-3" />
|
||||
</div>
|
||||
) : !piece.hasFile && piece.processingStatus !== 'processando' ? (
|
||||
<div className="mt-5 rounded-lg bg-muted p-3">
|
||||
<p className="text-xs leading-5 text-muted-foreground">
|
||||
Sem mídia oficial para extrair. A peça circula pelo link; se quiser arquivar o
|
||||
|
|
@ -181,18 +234,53 @@ export default async function ContentPieceDetailPage({ params }: ContentPieceDet
|
|||
<ContentPieceRetryButton contentPieceId={piece.id} className="mt-2" />
|
||||
</div>
|
||||
) : piece.processingStatus === 'processando' ? (
|
||||
<div className="mt-5 rounded-lg bg-muted p-3">
|
||||
<p className="text-xs leading-5 text-muted-foreground">
|
||||
{piece.step === 'transcrevendo'
|
||||
? 'Transcrevendo e catalogando…'
|
||||
: 'Preparando a peça…'}{' '}
|
||||
A ficha fica disponível para revisão assim que terminar.
|
||||
</p>
|
||||
</div>
|
||||
piece.origin === 'instagram' && !piece.hasFile ? (
|
||||
<div className="mt-5 rounded-lg bg-muted p-3">
|
||||
<div className="h-2 overflow-hidden rounded-full bg-background">
|
||||
<div className="h-full w-1/2 animate-pulse rounded-full bg-primary motion-reduce:animate-none" />
|
||||
</div>
|
||||
<p className="mt-2 text-xs leading-5 text-muted-foreground">
|
||||
Procurando a publicação no perfil oficial…
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="mt-5 rounded-lg bg-muted p-3">
|
||||
<p className="text-xs leading-5 text-muted-foreground">
|
||||
{piece.step === 'transcrevendo'
|
||||
? 'Transcrevendo e catalogando…'
|
||||
: 'Preparando a peça…'}{' '}
|
||||
A ficha fica disponível para revisão assim que terminar.
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
{processingSteps ? (
|
||||
// The detailed tracker is the desktop scene; mobile keeps the
|
||||
// compact progress box in the media column (design scene 3).
|
||||
<div className="mb-6 hidden rounded-xl border p-5 md:block">
|
||||
<p className="text-sm font-semibold">Processamento da peça</p>
|
||||
<ol className="mt-4 grid grid-cols-3 gap-3 text-xs">
|
||||
{processingSteps.map((step) => (
|
||||
<li key={step.label} className={step.className}>
|
||||
<b>{step.label}</b>
|
||||
<p className={`mt-1 ${step.stateClassName}`}>{step.stateLabel}</p>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
) : piece.origin !== 'arquivo' && piece.processingStatus === 'pronto' && piece.hasFile ? (
|
||||
<div className="mb-6 rounded-xl border border-green-200 bg-green-50 p-4">
|
||||
<p className="text-sm font-semibold text-green-900">
|
||||
{piece.transcript ? 'Arquivo e transcrição prontos' : 'Arquivo pronto'}
|
||||
</p>
|
||||
<p className="mt-1 text-xs leading-5 text-green-900/80">
|
||||
A ficha foi catalogada. Revise os campos antes de publicar.
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
<ContentPieceCirculationPanel
|
||||
circulation={piece.circulation}
|
||||
isPublished={piece.isPublished}
|
||||
|
|
|
|||
|
|
@ -54,6 +54,7 @@ const contentPieceSelect = {
|
|||
pieceDate: true,
|
||||
publishedAt: true,
|
||||
error: true,
|
||||
linkFailureReason: true,
|
||||
media: true,
|
||||
curatedFields: true,
|
||||
} as const
|
||||
|
|
@ -187,7 +188,12 @@ export const retryContentPieceForActor = async (input: {
|
|||
where: {
|
||||
and: [{ id: { equals: parsed.contentPieceId } }, { processingStatus: { equals: 'falhou' } }],
|
||||
},
|
||||
data: { processingStatus: 'processando', step: 'extraindo', error: null },
|
||||
data: {
|
||||
processingStatus: 'processando',
|
||||
step: 'extraindo',
|
||||
error: null,
|
||||
linkFailureReason: null,
|
||||
},
|
||||
depth: 0,
|
||||
select: contentPieceSelect,
|
||||
user: actor,
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import {
|
|||
CONTENT_PIECE_CURATED_FIELDS,
|
||||
CONTENT_PIECE_DESCRIPTION_MAX_LENGTH,
|
||||
CONTENT_PIECE_INSTITUTION_MAX_LENGTH,
|
||||
CONTENT_PIECE_LINK_FAILURE_REASONS,
|
||||
CONTENT_PIECE_ORIGINS,
|
||||
CONTENT_PIECE_PROCESSING_STATUSES,
|
||||
CONTENT_PIECE_STATUSES,
|
||||
|
|
@ -17,6 +18,7 @@ import {
|
|||
CONTENT_PIECE_TITLE_MAX_LENGTH,
|
||||
CONTENT_PIECE_TYPES,
|
||||
contentPieceCuratedFieldLabels,
|
||||
contentPieceLinkFailureReasonLabels,
|
||||
contentPieceOriginLabels,
|
||||
contentPieceProcessingStatusLabels,
|
||||
contentPieceSearchText,
|
||||
|
|
@ -68,6 +70,10 @@ const ORIGIN_OPTIONS = CONTENT_PIECE_ORIGINS.map((value) => ({
|
|||
value,
|
||||
label: contentPieceOriginLabels[value],
|
||||
}))
|
||||
const LINK_FAILURE_REASON_OPTIONS = CONTENT_PIECE_LINK_FAILURE_REASONS.map((value) => ({
|
||||
value,
|
||||
label: contentPieceLinkFailureReasonLabels[value],
|
||||
}))
|
||||
|
||||
/**
|
||||
* The one seam with the public Central (S27): every write of a piece — the
|
||||
|
|
@ -403,6 +409,17 @@ export const ContentPiece: CollectionConfig = {
|
|||
description: 'Motivo interno da falha; nunca vai à pessoa com o detalhe cru.',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'linkFailureReason',
|
||||
type: 'select',
|
||||
label: 'Motivo da peça-link',
|
||||
options: LINK_FAILURE_REASON_OPTIONS,
|
||||
admin: {
|
||||
readOnly: true,
|
||||
description:
|
||||
'Por que uma peça do Instagram ficou só como link; preenchido pelo processamento.',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'searchText',
|
||||
type: 'textarea',
|
||||
|
|
|
|||
44
src/collections/InternetSpeechMedia.ts
Normal file
44
src/collections/InternetSpeechMedia.ts
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import type { CollectionConfig } from 'payload'
|
||||
|
||||
import { INTERNET_SPEECH_MEDIA_SLUG } from '@/lib/webSpeech'
|
||||
import { canReadSpeech, payloadAdminOnly } from '@/utilities/campaignAccess'
|
||||
|
||||
/**
|
||||
* C215 — private upload collection of a web speech's mirrored artifact (the
|
||||
* media and the optional thumbnail). Like `recordingMedia`, deliberately NOT
|
||||
* `media`: that collection is anonymous-read by contract (public pages), while
|
||||
* a third-party speech file may only be read by the communication roles. The
|
||||
* browser reaches the file through the authenticated acervo route (C216),
|
||||
* never the public `/api/media/file` proxy.
|
||||
*/
|
||||
|
||||
export const InternetSpeechMedia: CollectionConfig = {
|
||||
slug: INTERNET_SPEECH_MEDIA_SLUG,
|
||||
labels: {
|
||||
singular: 'Mídia de fala da internet',
|
||||
plural: 'Mídias de falas da internet',
|
||||
},
|
||||
admin: {
|
||||
group: 'Comunicação',
|
||||
description:
|
||||
'Arquivos privados das falas encontradas na internet (mídia espelhada e capa). Só abrem com login da campanha.',
|
||||
},
|
||||
access: {
|
||||
create: payloadAdminOnly,
|
||||
read: canReadSpeech,
|
||||
update: payloadAdminOnly,
|
||||
delete: payloadAdminOnly,
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: 'alt',
|
||||
type: 'text',
|
||||
label: 'Texto alternativo',
|
||||
required: true,
|
||||
admin: {
|
||||
description: 'Descrição do arquivo para acessibilidade.',
|
||||
},
|
||||
},
|
||||
],
|
||||
upload: true,
|
||||
}
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
import type {
|
||||
CollectionBeforeChangeHook,
|
||||
CollectionBeforeDeleteHook,
|
||||
CollectionBeforeValidateHook,
|
||||
CollectionConfig,
|
||||
|
|
@ -14,6 +15,7 @@ import {
|
|||
recordingStepLabels,
|
||||
} from '@/lib/recording'
|
||||
import { speakerNamesFromLabels } from '@/lib/recordingDiarization'
|
||||
import { SPEECH_CLASSIFICATION_SOURCES, SPEECH_SCOPES, SPEECH_TOPICS } from '@/lib/speechFacets'
|
||||
import {
|
||||
canDeleteRecording,
|
||||
canReadRecording,
|
||||
|
|
@ -67,6 +69,44 @@ const deriveSpeakerNames: CollectionBeforeValidateHook = ({ data, originalDoc })
|
|||
return data
|
||||
}
|
||||
|
||||
/**
|
||||
* C219 — the "Ano" facet is derived from the recording date the team already
|
||||
* informed (`recordedAt`), never a second hand-typed field. A recording without
|
||||
* a date honestly has no year (it stays out of the year filter).
|
||||
*/
|
||||
const deriveRecordingYear: CollectionBeforeValidateHook = ({ data, originalDoc }) => {
|
||||
if (!data) return data
|
||||
const recordedAt =
|
||||
typeof data.recordedAt === 'string' ? data.recordedAt : (originalDoc?.recordedAt ?? null)
|
||||
const year = Number(String(recordedAt ?? '').slice(0, 4))
|
||||
// Clearing the date clears the derived year too — a stale year would keep the
|
||||
// recording in an "Ano" facet the team just removed.
|
||||
data.year = Number.isInteger(year) && year > 1900 ? year : null
|
||||
return data
|
||||
}
|
||||
const FACET_FIELDS = ['topics', 'scopes', 'classifiedBy', 'mentionedMunicipalities'] as const
|
||||
|
||||
/**
|
||||
* C219 — a manual facet correction is curation: unauthenticated writes (the
|
||||
* transcription job and the backfill CLI) never overwrite it. Authenticated
|
||||
* admin edits stay free to change both the facets and the provenance.
|
||||
*/
|
||||
const preserveManualFacets: CollectionBeforeChangeHook = ({
|
||||
data,
|
||||
operation,
|
||||
originalDoc,
|
||||
req,
|
||||
}) => {
|
||||
if (!data || operation !== 'update' || originalDoc?.classifiedBy !== 'manual') return data
|
||||
if (req.user) return data
|
||||
|
||||
const next = data as Record<string, unknown>
|
||||
for (const field of FACET_FIELDS) {
|
||||
if (field in next) next[field] = originalDoc[field]
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
export const Recording: CollectionConfig = {
|
||||
slug: 'recording',
|
||||
labels: {
|
||||
|
|
@ -76,9 +116,9 @@ export const Recording: CollectionConfig = {
|
|||
admin: {
|
||||
group: 'Comunicação',
|
||||
useAsTitle: 'title',
|
||||
defaultColumns: ['title', 'recordedAt', 'status', 'durationSeconds', 'createdAt'],
|
||||
defaultColumns: ['title', 'recordedAt', 'status', 'topics', 'classifiedBy'],
|
||||
description:
|
||||
'Gravações próprias da equipe no acervo. O arquivo é privado; a transcrição é somente leitura.',
|
||||
'Gravações próprias da equipe no acervo. O arquivo é privado; a transcrição é somente leitura. Tema, alcance e municípios citados são classificados automaticamente pelo início da transcrição e podem ser corrigidos aqui (a correção vira proveniência "Manual").',
|
||||
},
|
||||
access: {
|
||||
create: canUploadRecording,
|
||||
|
|
@ -87,8 +127,8 @@ export const Recording: CollectionConfig = {
|
|||
delete: canDeleteRecording,
|
||||
},
|
||||
hooks: {
|
||||
beforeValidate: [deriveSpeakerNames],
|
||||
beforeChange: [stampCampaignCreatedBy],
|
||||
beforeValidate: [deriveSpeakerNames, deriveRecordingYear],
|
||||
beforeChange: [preserveManualFacets, stampCampaignCreatedBy],
|
||||
beforeDelete: [deleteRecordingSegments],
|
||||
},
|
||||
fields: [
|
||||
|
|
@ -108,6 +148,16 @@ export const Recording: CollectionConfig = {
|
|||
description: 'Data em que a gravação foi feita (opcional).',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'year',
|
||||
type: 'number',
|
||||
label: 'Ano',
|
||||
index: true,
|
||||
admin: {
|
||||
readOnly: true,
|
||||
description: 'Derivado da data da gravação.',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'status',
|
||||
type: 'select',
|
||||
|
|
@ -155,6 +205,47 @@ export const Recording: CollectionConfig = {
|
|||
description: 'Concatenação normalizada dos segmentos (sem acentos, minúsculas).',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'topics',
|
||||
type: 'select',
|
||||
label: 'Temas',
|
||||
hasMany: true,
|
||||
index: true,
|
||||
options: SPEECH_TOPICS.map(({ value, label }) => ({ value, label })),
|
||||
},
|
||||
{
|
||||
name: 'scopes',
|
||||
type: 'select',
|
||||
label: 'Alcance',
|
||||
hasMany: true,
|
||||
index: true,
|
||||
options: SPEECH_SCOPES.map(({ value, label }) => ({ value, label })),
|
||||
},
|
||||
{
|
||||
name: 'classifiedBy',
|
||||
type: 'select',
|
||||
label: 'Proveniência da classificação',
|
||||
// Optional on purpose: a recording from before C219 was never classified,
|
||||
// and stamping it `gazetteer` would claim a pass that never ran. Null is
|
||||
// the honest "não classificada" until the backfill CLI runs.
|
||||
index: true,
|
||||
options: SPEECH_CLASSIFICATION_SOURCES.map((value) => ({
|
||||
value,
|
||||
label: value === 'gazetteer' ? 'Gazetteer' : value === 'llm' ? 'LLM' : 'Manual',
|
||||
})),
|
||||
admin: {
|
||||
description:
|
||||
'Automática e auditável: Gazetteer (léxico), LLM (refinamento validado) ou Manual (correção humana).',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'mentionedMunicipalities',
|
||||
type: 'relationship',
|
||||
relationTo: 'municipality',
|
||||
label: 'Municípios citados',
|
||||
hasMany: true,
|
||||
index: true,
|
||||
},
|
||||
{
|
||||
name: 'speakerLabels',
|
||||
type: 'array',
|
||||
|
|
|
|||
|
|
@ -6,15 +6,20 @@ import type {
|
|||
} from 'payload'
|
||||
|
||||
import { SPEECH_CLASSIFICATION_SOURCES, SPEECH_SCOPES, SPEECH_TOPICS } from '@/lib/speechFacets'
|
||||
import { INTERNET_SPEECH_MEDIA_SLUG, WEB_SPEECH_PLATFORMS } from '@/lib/webSpeech'
|
||||
import { canReadSpeech, canUpdateSpeech, payloadAdminOnly } from '@/utilities/campaignAccess'
|
||||
|
||||
/**
|
||||
* Speech catalog (C153) — one record per Jorge Solla speech in the Câmara,
|
||||
* with the official transcript (taquigrafia), the ASR segments with timestamps
|
||||
* (speechSegment), curated facets and extracted mentions.
|
||||
* Speech catalog (C153) — one record per Jorge Solla speech: the Câmara
|
||||
* speeches with the official transcript (taquigrafia), ASR segments with
|
||||
* timestamps (speechSegment), curated facets and extracted mentions, plus the
|
||||
* web speeches (C215) mirrored from the internet with the same facets and
|
||||
* segments.
|
||||
*
|
||||
* Data provenance: Câmara open data + VOD, CC BY 4.0 — keep the credit.
|
||||
* Identity is the API speech (`sourceKey`), never the regenerable VOD URL.
|
||||
* Câmara data provenance: open data + VOD, CC BY 4.0 — keep the credit. Web
|
||||
* rows carry their own origin (platform + URL) and a private mirrored file.
|
||||
* Identity is the source (`sourceKey`): the Câmara API speech or the web
|
||||
* namespace (`web:<platform>:<externalId|url>`), never a regenerable URL.
|
||||
*/
|
||||
|
||||
const FACET_FIELDS = [
|
||||
|
|
@ -56,8 +61,22 @@ const preserveManualFacets: CollectionBeforeChangeHook = ({
|
|||
return data
|
||||
}
|
||||
|
||||
/** Segments are owned by the speech; Payload relationships do not cascade. */
|
||||
const deleteSpeechSegments: CollectionBeforeDeleteHook = async ({ id, req }) => {
|
||||
/** Speech assets are owned by the speech; Payload relationships do not cascade. */
|
||||
const deleteSpeechAssets: CollectionBeforeDeleteHook = async ({ id, req }) => {
|
||||
const speech = await req.payload.findByID({
|
||||
collection: 'speech',
|
||||
id,
|
||||
depth: 0,
|
||||
select: { mirroredMedia: true, thumbnail: true },
|
||||
req,
|
||||
// Intentional bypass: the cascade is owned by this hook; media access is the
|
||||
// acervo gate and this runs inside the authorized speech delete request.
|
||||
overrideAccess: true,
|
||||
})
|
||||
const mediaIds = [speech?.mirroredMedia, speech?.thumbnail]
|
||||
.map((media) => (typeof media === 'object' && media !== null ? media.id : media))
|
||||
.filter((mediaId): mediaId is number => typeof mediaId === 'number')
|
||||
|
||||
await req.payload.delete({
|
||||
collection: 'speechSegment',
|
||||
where: { speech: { equals: id } },
|
||||
|
|
@ -66,6 +85,15 @@ const deleteSpeechSegments: CollectionBeforeDeleteHook = async ({ id, req }) =>
|
|||
// admin-only and this runs inside the authorized speech delete request.
|
||||
overrideAccess: true,
|
||||
})
|
||||
if (mediaIds.length > 0) {
|
||||
await req.payload.delete({
|
||||
collection: INTERNET_SPEECH_MEDIA_SLUG,
|
||||
where: { id: { in: mediaIds } },
|
||||
req,
|
||||
// Intentional bypass: same cascade, now over the private mirrored files.
|
||||
overrideAccess: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export const Speech: CollectionConfig = {
|
||||
|
|
@ -77,9 +105,9 @@ export const Speech: CollectionConfig = {
|
|||
admin: {
|
||||
group: 'Comunicação',
|
||||
useAsTitle: 'speechAt',
|
||||
defaultColumns: ['speechAt', 'type', 'phase', 'topics', 'classifiedBy'],
|
||||
defaultColumns: ['speechAt', 'origin', 'platform', 'type', 'topics', 'classifiedBy'],
|
||||
description:
|
||||
'Acervo de falas do deputado na Câmara. Dados e vídeos da Câmara dos Deputados (CC BY 4.0).',
|
||||
'Acervo de falas do deputado: discursos na Câmara (CC BY 4.0) e falas publicadas na internet (mídia espelhada privada).',
|
||||
},
|
||||
access: {
|
||||
create: payloadAdminOnly,
|
||||
|
|
@ -90,7 +118,7 @@ export const Speech: CollectionConfig = {
|
|||
hooks: {
|
||||
beforeValidate: [deriveSpeechYear],
|
||||
beforeChange: [preserveManualFacets],
|
||||
beforeDelete: [deleteSpeechSegments],
|
||||
beforeDelete: [deleteSpeechAssets],
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
|
|
@ -102,7 +130,24 @@ export const Speech: CollectionConfig = {
|
|||
index: true,
|
||||
admin: {
|
||||
readOnly: true,
|
||||
description: 'Identidade da fala na API da Câmara (data/hora + tipo + fase).',
|
||||
description: 'Identidade da fala: API da Câmara ou web:<plataforma>:<id|url>.',
|
||||
},
|
||||
},
|
||||
{
|
||||
// C215 — discriminator of the catalog source. The Câmara surfaces filter
|
||||
// `camara`; the web source is served by C216 with its own list contract.
|
||||
name: 'origin',
|
||||
type: 'select',
|
||||
label: 'Origem',
|
||||
required: true,
|
||||
defaultValue: 'camara',
|
||||
index: true,
|
||||
options: [
|
||||
{ label: 'Câmara', value: 'camara' },
|
||||
{ label: 'Internet', value: 'web' },
|
||||
],
|
||||
admin: {
|
||||
description: 'Discurso da Câmara ou fala publicada na internet.',
|
||||
},
|
||||
},
|
||||
{
|
||||
|
|
@ -267,6 +312,71 @@ export const Speech: CollectionConfig = {
|
|||
label: 'VOD (baixar)',
|
||||
admin: { readOnly: true, description: 'Último link conhecido; regerável pelo VOD.' },
|
||||
},
|
||||
// C215 — web speech origin and mirrored assets (null on Câmara rows).
|
||||
{
|
||||
name: 'platform',
|
||||
type: 'select',
|
||||
label: 'Plataforma',
|
||||
index: true,
|
||||
options: WEB_SPEECH_PLATFORMS.map(({ value, label }) => ({ value, label })),
|
||||
admin: {
|
||||
description: 'Plataforma de origem da fala da internet.',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'externalId',
|
||||
type: 'text',
|
||||
label: 'Id externo',
|
||||
admin: {
|
||||
readOnly: true,
|
||||
description: 'Identificador da publicação na plataforma (quando houver).',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'sourceUrl',
|
||||
type: 'text',
|
||||
label: 'URL de origem',
|
||||
admin: {
|
||||
readOnly: true,
|
||||
description: 'Link canônico da publicação original.',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'title',
|
||||
type: 'text',
|
||||
label: 'Título',
|
||||
admin: {
|
||||
description: 'Título da publicação na plataforma.',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'channel',
|
||||
type: 'text',
|
||||
label: 'Canal/autor',
|
||||
admin: {
|
||||
description: 'Quem publicou (canal, rádio, perfil) — texto de origem, não é contato.',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'mirroredMedia',
|
||||
type: 'upload',
|
||||
relationTo: INTERNET_SPEECH_MEDIA_SLUG,
|
||||
label: 'Mídia espelhada',
|
||||
admin: {
|
||||
readOnly: true,
|
||||
description: 'Arquivo privado preservado para player, download e cortes.',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'thumbnail',
|
||||
type: 'upload',
|
||||
relationTo: INTERNET_SPEECH_MEDIA_SLUG,
|
||||
label: 'Capa',
|
||||
admin: {
|
||||
readOnly: true,
|
||||
description: 'Capa da origem quando capturada; sem ela a lista mostra placeholder.',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'topics',
|
||||
type: 'select',
|
||||
|
|
|
|||
|
|
@ -7,14 +7,16 @@ import {
|
|||
ContentPiecePublicationBadge,
|
||||
} from '@/components/campaign/content/ContentPieceStatusBadge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { contentPieceStepLabels } from '@/lib/contentPiece'
|
||||
import { CONTENT_PIECE_LINK_LABEL, contentPieceStepLabels } from '@/lib/contentPiece'
|
||||
import type { ContentPieceRowViewModel } from '@/lib/contentPieceCirculation'
|
||||
|
||||
/**
|
||||
* C211 — the Central list on mobile (approved design scenes 5): one card per
|
||||
* piece with the title + processing state, the type/publication line and the
|
||||
* single "Abrir" (or "Reprocessar" when it failed). C213 adds the piece's
|
||||
* circulation counters (2×2 grid) right above the action.
|
||||
* C211/C220 — the Central list on mobile (approved design scenes 5): one card
|
||||
* per piece with the title + processing state, the type/publication line and
|
||||
* the single "Abrir" (or "Reprocessar" when it failed). A link piece also
|
||||
* carries the neutral "Peça-link" label — the honest reason lives on the ficha,
|
||||
* never on the list (C220 D7). C213 adds the piece's circulation counters (2×2
|
||||
* grid) right above the action.
|
||||
*/
|
||||
export const ContentPieceCardList = ({
|
||||
rows,
|
||||
|
|
@ -25,49 +27,60 @@ export const ContentPieceCardList = ({
|
|||
}) => (
|
||||
<div className="flex flex-col gap-3 md:hidden">
|
||||
{rows.length === 0 && empty ? empty : null}
|
||||
{rows.map((piece) => (
|
||||
<article key={piece.id} className="rounded-xl border bg-card p-4">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<Link href={piece.detailHref} className="min-w-0 text-sm font-semibold hover:underline">
|
||||
{piece.title}
|
||||
</Link>
|
||||
<ContentPieceProcessingBadge status={piece.processingStatus} className="shrink-0" />
|
||||
</div>
|
||||
<div className="mt-1 flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
|
||||
<ContentPiecePublicationBadge status={piece.status} />
|
||||
<span>
|
||||
{[piece.typeLabel, piece.durationLabel].filter(Boolean).join(' · ')}
|
||||
{piece.cityLabel ? ` · ${piece.cityLabel}` : ''}
|
||||
</span>
|
||||
</div>
|
||||
{rows.map((piece) => {
|
||||
// A peça-link carries no honest type (the link may be a carousel) — the
|
||||
// neutral label replaces it (C220 D7, design scene 3).
|
||||
const isLinkOnly =
|
||||
piece.origin !== 'arquivo' && piece.processingStatus === 'pronto' && !piece.hasFile
|
||||
const meta = [
|
||||
piece.origin !== 'arquivo' ? piece.originLabel : null,
|
||||
isLinkOnly ? CONTENT_PIECE_LINK_LABEL : null,
|
||||
...(isLinkOnly ? [] : [piece.typeLabel, piece.durationLabel]),
|
||||
]
|
||||
return (
|
||||
<article key={piece.id} className="rounded-xl border bg-card p-4">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<Link href={piece.detailHref} className="min-w-0 text-sm font-semibold hover:underline">
|
||||
{piece.title}
|
||||
</Link>
|
||||
<ContentPieceProcessingBadge status={piece.processingStatus} className="shrink-0" />
|
||||
</div>
|
||||
<div className="mt-1 flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
|
||||
<ContentPiecePublicationBadge status={piece.status} />
|
||||
<span>
|
||||
{meta.filter(Boolean).join(' · ')}
|
||||
{piece.cityLabel ? ` · ${piece.cityLabel}` : ''}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{piece.processingStatus === 'processando' ? (
|
||||
<>
|
||||
<div className="mt-3 h-2 overflow-hidden rounded-full bg-muted">
|
||||
<div className="h-full w-1/2 animate-pulse rounded-full bg-primary motion-reduce:animate-none" />
|
||||
</div>
|
||||
<p className="mt-2 text-xs text-muted-foreground">
|
||||
{piece.step ? contentPieceStepLabels[piece.step] : 'Processando…'}
|
||||
</p>
|
||||
</>
|
||||
) : piece.processingStatus === 'falhou' && piece.failureMessage ? (
|
||||
<p className="mt-2 text-xs text-red-800">{piece.failureMessage}</p>
|
||||
) : null}
|
||||
{piece.processingStatus === 'processando' ? (
|
||||
<>
|
||||
<div className="mt-3 h-2 overflow-hidden rounded-full bg-muted">
|
||||
<div className="h-full w-1/2 animate-pulse rounded-full bg-primary motion-reduce:animate-none" />
|
||||
</div>
|
||||
<p className="mt-2 text-xs text-muted-foreground">
|
||||
{piece.step ? contentPieceStepLabels[piece.step] : 'Processando…'}
|
||||
</p>
|
||||
</>
|
||||
) : piece.processingStatus === 'falhou' && piece.failureMessage ? (
|
||||
<p className="mt-2 text-xs text-red-800">{piece.failureMessage}</p>
|
||||
) : null}
|
||||
|
||||
<ContentPieceCirculationCounters
|
||||
circulation={piece.circulation}
|
||||
isPublished={piece.isPublished}
|
||||
layout="card"
|
||||
/>
|
||||
<ContentPieceCirculationCounters
|
||||
circulation={piece.circulation}
|
||||
isPublished={piece.isPublished}
|
||||
layout="card"
|
||||
/>
|
||||
|
||||
{piece.canRetry ? (
|
||||
<ContentPieceRetryButton contentPieceId={piece.id} className="mt-3" />
|
||||
) : (
|
||||
<Button asChild variant="outline" className="mt-3 min-h-11 w-full">
|
||||
<Link href={piece.detailHref}>Abrir</Link>
|
||||
</Button>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
{piece.canRetry ? (
|
||||
<ContentPieceRetryButton contentPieceId={piece.id} className="mt-3" />
|
||||
) : (
|
||||
<Button asChild variant="outline" className="mt-3 min-h-11 w-full">
|
||||
<Link href={piece.detailHref}>Abrir</Link>
|
||||
</Button>
|
||||
)}
|
||||
</article>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
|
|
|
|||
296
src/components/campaign/recording/RecordingAcervoFilters.tsx
Normal file
296
src/components/campaign/recording/RecordingAcervoFilters.tsx
Normal file
|
|
@ -0,0 +1,296 @@
|
|||
'use client'
|
||||
|
||||
import { useMemo, useOptimistic, useState } from 'react'
|
||||
|
||||
import {
|
||||
CampaignHeaderFilterPopover,
|
||||
type CampaignHeaderFilterRow,
|
||||
} from '@/components/campaign/shared/CampaignHeaderFilterPopover'
|
||||
import {
|
||||
CampaignListOmnibox,
|
||||
campaignListOmniboxFormClassName,
|
||||
} from '@/components/campaign/shared/CampaignListOmnibox'
|
||||
import { CampaignSearchModeControl } from '@/components/campaign/shared/CampaignSearchModeControl'
|
||||
import { useCampaignListFilterNavigation } from '@/components/campaign/shared/useCampaignListFilterNavigation'
|
||||
import { selectedFilterTriggerLabel } from '@/lib/campaignListOmnibox'
|
||||
import { SPEECH_SCOPES, SPEECH_TOPICS } from '@/lib/speechFacets'
|
||||
import {
|
||||
buildRecordingListHref,
|
||||
toggleRecordingPerson,
|
||||
type RecordingFilterOptions,
|
||||
type RecordingListState,
|
||||
} from '@/utilities/recordings/recordingListUrl'
|
||||
import {
|
||||
applyRecordingOmniboxSuggestion,
|
||||
applyRecordingSearchMode,
|
||||
buildRecordingOmniboxChips,
|
||||
buildRecordingOmniboxSuggestionSeeds,
|
||||
clearRecordingOmnibox,
|
||||
filterRecordingOmniboxSuggestions,
|
||||
removeRecordingOmniboxChip,
|
||||
type RecordingOmniboxAction,
|
||||
} from '@/utilities/recordings/recordingOmnibox'
|
||||
import {
|
||||
SPEECH_DURATION_BUCKETS,
|
||||
speechDurationLabels,
|
||||
speechScopeLabels,
|
||||
speechTopicLabels,
|
||||
type SpeechSearchMode,
|
||||
} from '@/utilities/speech/speechListUrl'
|
||||
|
||||
const topicOptions = SPEECH_TOPICS.map(({ value, label }) => ({ value, label }))
|
||||
const scopeOptions = SPEECH_SCOPES.map(({ value, label }) => ({ value, label }))
|
||||
const durationOptions = SPEECH_DURATION_BUCKETS.map(({ value, label }) => ({ value, label }))
|
||||
|
||||
type FacetKey = 'years' | 'topics' | 'scopes' | 'municipalities' | 'durations' | 'people'
|
||||
|
||||
type RecordingFacet = {
|
||||
id: string
|
||||
label: string
|
||||
/** Prefix of the omnibox suggestion id (`${prefix}:${value}`). */
|
||||
prefix: string
|
||||
stateKey: FacetKey
|
||||
options: readonly { value: string; label: string }[]
|
||||
selected: readonly string[]
|
||||
labels?: Readonly<Record<string, string>>
|
||||
}
|
||||
|
||||
/**
|
||||
* C219 — the filter bar of "Gravações enviadas": same gestures as the Câmara
|
||||
* acervo (search by term or theme, year, topic, scope, cited municipality,
|
||||
* duration) plus the exclusive "Pessoa" facet. The mechanics (omnibox, chips,
|
||||
* facet popovers, pending boundary) are the shared shells; this component only
|
||||
* assembles the recordings facets. Ported from the approved hi-fi design
|
||||
* (`docs/plans/acervo-paridade-busca-filtros-ui-design.html`, scenes 01/02).
|
||||
*/
|
||||
export const RecordingAcervoFilters = ({
|
||||
state,
|
||||
filterOptions,
|
||||
themeUnavailable = false,
|
||||
}: {
|
||||
state: RecordingListState
|
||||
filterOptions: RecordingFilterOptions
|
||||
/** C219 — the theme expansion is down; the selector reflects the fallback. */
|
||||
themeUnavailable?: boolean
|
||||
}) => {
|
||||
const { navigate, isPending } = useCampaignListFilterNavigation({
|
||||
state,
|
||||
toHref: (next) => buildRecordingListHref(next, 1),
|
||||
})
|
||||
const [query, setQuery] = useState('')
|
||||
const [viewState, setOptimisticState] = useOptimistic(state)
|
||||
|
||||
const activeMode: SpeechSearchMode =
|
||||
viewState.mode === 'tema' && !themeUnavailable ? 'tema' : 'termo'
|
||||
|
||||
const municipalityLabelsById = useMemo(() => {
|
||||
const map = new Map<number, string>()
|
||||
for (const option of filterOptions.municipalities) {
|
||||
const id = Number(option.value)
|
||||
if (Number.isSafeInteger(id) && id > 0) map.set(id, option.label)
|
||||
}
|
||||
return map
|
||||
}, [filterOptions.municipalities])
|
||||
|
||||
const chips = useMemo(
|
||||
() => buildRecordingOmniboxChips({ state: viewState, municipalityLabelsById }),
|
||||
[viewState, municipalityLabelsById],
|
||||
)
|
||||
|
||||
const suggestionSeeds = useMemo(
|
||||
() =>
|
||||
buildRecordingOmniboxSuggestionSeeds({
|
||||
years: filterOptions.years,
|
||||
municipalityOptions: filterOptions.municipalities,
|
||||
personOptions: filterOptions.people,
|
||||
}),
|
||||
[filterOptions],
|
||||
)
|
||||
|
||||
const suggestions = useMemo(
|
||||
() => filterRecordingOmniboxSuggestions(suggestionSeeds, query),
|
||||
[suggestionSeeds, query],
|
||||
)
|
||||
|
||||
const runAction = (action: RecordingOmniboxAction) => {
|
||||
if (action.kind === 'clear') {
|
||||
setQuery('')
|
||||
navigate(action.state)
|
||||
return
|
||||
}
|
||||
navigate(action.state)
|
||||
}
|
||||
|
||||
const runMode = (mode: SpeechSearchMode) => {
|
||||
const next = applyRecordingSearchMode({ state: viewState, mode }).state
|
||||
setOptimisticState(next)
|
||||
navigate(next)
|
||||
}
|
||||
|
||||
const facetRows = (
|
||||
prefix: string,
|
||||
options: readonly { value: string; label: string }[],
|
||||
selected: readonly string[],
|
||||
): CampaignHeaderFilterRow[] =>
|
||||
options.map((option) => {
|
||||
const next = applyRecordingOmniboxSuggestion({
|
||||
state: viewState,
|
||||
suggestionId: `${prefix}:${option.value}`,
|
||||
}).state
|
||||
return {
|
||||
value: option.value,
|
||||
label: option.label,
|
||||
href: buildRecordingListHref(next, 1),
|
||||
selected: selected.includes(option.value),
|
||||
checkbox: true,
|
||||
onChoose: () => setOptimisticState(next),
|
||||
}
|
||||
})
|
||||
|
||||
const personRows = (): CampaignHeaderFilterRow[] =>
|
||||
filterOptions.people.map((person) => {
|
||||
const next = toggleRecordingPerson(viewState, person)
|
||||
return {
|
||||
value: person,
|
||||
label: person,
|
||||
href: buildRecordingListHref(next, 1),
|
||||
selected: (viewState.people ?? []).some(
|
||||
(selected) => selected.toLocaleLowerCase('pt-BR') === person.toLocaleLowerCase('pt-BR'),
|
||||
),
|
||||
checkbox: true,
|
||||
onChoose: () => setOptimisticState(next),
|
||||
}
|
||||
})
|
||||
|
||||
const clearFacet = (facet: FacetKey) => {
|
||||
const next: RecordingListState = { ...viewState, page: 1, [facet]: undefined }
|
||||
return { href: buildRecordingListHref(next, 1), onChoose: () => setOptimisticState(next) }
|
||||
}
|
||||
|
||||
const years = (viewState.years ?? []).map(String)
|
||||
const topics = viewState.topics ?? []
|
||||
const scopes = viewState.scopes ?? []
|
||||
const municipalities = (viewState.municipalities ?? []).map(String)
|
||||
const durations = viewState.durations ?? []
|
||||
const people = viewState.people ?? []
|
||||
|
||||
const facets: RecordingFacet[] = [
|
||||
{
|
||||
id: 'recording-filter-year',
|
||||
label: 'Ano',
|
||||
prefix: 'year',
|
||||
stateKey: 'years',
|
||||
options: filterOptions.years.map((year) => ({ value: String(year), label: String(year) })),
|
||||
selected: years,
|
||||
},
|
||||
{
|
||||
id: 'recording-filter-topic',
|
||||
label: 'Tema',
|
||||
prefix: 'topic',
|
||||
stateKey: 'topics',
|
||||
options: topicOptions,
|
||||
selected: topics,
|
||||
labels: speechTopicLabels,
|
||||
},
|
||||
{
|
||||
id: 'recording-filter-scope',
|
||||
label: 'Alcance',
|
||||
prefix: 'scope',
|
||||
stateKey: 'scopes',
|
||||
options: scopeOptions,
|
||||
selected: scopes,
|
||||
labels: speechScopeLabels,
|
||||
},
|
||||
{
|
||||
id: 'recording-filter-municipality',
|
||||
label: 'Município citado',
|
||||
prefix: 'municipality',
|
||||
stateKey: 'municipalities',
|
||||
options: filterOptions.municipalities,
|
||||
selected: municipalities,
|
||||
labels: Object.fromEntries(municipalityLabelsById),
|
||||
},
|
||||
{
|
||||
id: 'recording-filter-duration',
|
||||
label: 'Duração',
|
||||
prefix: 'duration',
|
||||
stateKey: 'durations',
|
||||
options: durationOptions,
|
||||
selected: durations,
|
||||
labels: speechDurationLabels,
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<form
|
||||
role="search"
|
||||
className={campaignListOmniboxFormClassName}
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault()
|
||||
}}
|
||||
>
|
||||
<CampaignListOmnibox
|
||||
id="recording-omnibox"
|
||||
label="Buscar nas gravações enviadas"
|
||||
placeholder="Busque por palavra, trecho ou tema da transcrição…"
|
||||
chips={chips}
|
||||
suggestions={suggestions}
|
||||
query={query}
|
||||
onQueryChange={setQuery}
|
||||
isPending={isPending}
|
||||
onSelectSuggestion={(suggestionId) => {
|
||||
runAction(applyRecordingOmniboxSuggestion({ state: viewState, suggestionId }))
|
||||
}}
|
||||
onCommitQuery={(text) => {
|
||||
runAction(
|
||||
applyRecordingOmniboxSuggestion({ state: viewState, suggestionId: `q:${text}` }),
|
||||
)
|
||||
}}
|
||||
onRemoveChip={(chipId) => {
|
||||
runAction(removeRecordingOmniboxChip({ state: viewState, chipId }))
|
||||
}}
|
||||
onClearAll={() => {
|
||||
runAction(clearRecordingOmnibox(viewState))
|
||||
}}
|
||||
/>
|
||||
|
||||
<CampaignSearchModeControl
|
||||
activeMode={activeMode}
|
||||
themeUnavailable={themeUnavailable}
|
||||
onSelect={runMode}
|
||||
relatedHint="Encontra gravações relacionadas pelo sentido."
|
||||
/>
|
||||
|
||||
<div
|
||||
role="group"
|
||||
aria-label="Filtros do acervo de gravações"
|
||||
className="mt-2 flex gap-2 overflow-x-auto pb-1 md:flex-wrap md:overflow-visible"
|
||||
>
|
||||
{facets.map((facet) => (
|
||||
<CampaignHeaderFilterPopover
|
||||
key={facet.id}
|
||||
id={facet.id}
|
||||
label={facet.label}
|
||||
triggerVariant="chip"
|
||||
triggerLabel={selectedFilterTriggerLabel(facet.label, facet.selected, facet.labels)}
|
||||
active={facet.selected.length > 0}
|
||||
closeOnChoose={false}
|
||||
optionRows={facetRows(facet.prefix, facet.options, facet.selected)}
|
||||
clear={facet.selected.length ? clearFacet(facet.stateKey) : undefined}
|
||||
/>
|
||||
))}
|
||||
<CampaignHeaderFilterPopover
|
||||
id="recording-filter-person"
|
||||
label="Pessoa"
|
||||
triggerVariant="chip"
|
||||
triggerLabel={selectedFilterTriggerLabel('Pessoa', people)}
|
||||
active={people.length > 0}
|
||||
closeOnChoose={false}
|
||||
emptyLabel="Nenhuma pessoa identificada nas gravações."
|
||||
optionRows={personRows()}
|
||||
clear={people.length ? clearFacet('people') : undefined}
|
||||
/>
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,87 +0,0 @@
|
|||
'use client'
|
||||
|
||||
import { FunnelIcon, XIcon } from 'lucide-react'
|
||||
import { useOptimistic } from 'react'
|
||||
|
||||
import {
|
||||
CampaignHeaderFilterPopover,
|
||||
type CampaignHeaderFilterRow,
|
||||
} from '@/components/campaign/shared/CampaignHeaderFilterPopover'
|
||||
import { useCampaignListFilterNavigation } from '@/components/campaign/shared/useCampaignListFilterNavigation'
|
||||
import { foldSpeakerName } from '@/lib/recordingDiarization'
|
||||
import {
|
||||
buildRecordingListHref,
|
||||
removeRecordingPerson,
|
||||
toggleRecordingPerson,
|
||||
type RecordingListState,
|
||||
} from '@/utilities/recordings/recordingListUrl'
|
||||
|
||||
const PERSON_FILTER_ID = 'recording-filter-person'
|
||||
|
||||
/**
|
||||
* C200 — the "Pessoa" facet of the uploaded recordings (design scene 3): one
|
||||
* removable chip per selected label plus the multi-select popover backed by the
|
||||
* labels actually present. Options come from the server (`speakerNames`), never
|
||||
* from a free-form directory — the label is text, not a `Contact`.
|
||||
*/
|
||||
export const RecordingPersonFilter = ({
|
||||
state,
|
||||
options,
|
||||
}: {
|
||||
state: RecordingListState
|
||||
options: readonly string[]
|
||||
}) => {
|
||||
const { navigate } = useCampaignListFilterNavigation({
|
||||
state,
|
||||
toHref: (next) => buildRecordingListHref(next, 1),
|
||||
})
|
||||
const [viewState, setOptimisticState] = useOptimistic(state)
|
||||
const selected = viewState.people ?? []
|
||||
|
||||
const optionRows: CampaignHeaderFilterRow[] = options.map((option) => {
|
||||
const next = toggleRecordingPerson(viewState, option)
|
||||
return {
|
||||
value: option,
|
||||
label: option,
|
||||
href: buildRecordingListHref(next, 1),
|
||||
selected: selected.some((person) => foldSpeakerName(person) === foldSpeakerName(option)),
|
||||
checkbox: true,
|
||||
onChoose: () => setOptimisticState(next),
|
||||
}
|
||||
})
|
||||
|
||||
const clear = {
|
||||
href: buildRecordingListHref({ ...viewState, page: 1, people: undefined }, 1),
|
||||
onChoose: () => setOptimisticState({ ...viewState, page: 1, people: undefined }),
|
||||
}
|
||||
|
||||
return (
|
||||
<div role="group" aria-label="Filtrar por pessoa" className="flex flex-wrap items-center gap-2">
|
||||
<CampaignHeaderFilterPopover
|
||||
id={PERSON_FILTER_ID}
|
||||
label="Pessoa"
|
||||
triggerVariant="chip"
|
||||
triggerLabel={selected.length > 1 ? `Pessoa: ${selected.length}` : 'Pessoa'}
|
||||
active={selected.length > 0}
|
||||
closeOnChoose={false}
|
||||
emptyLabel="Nenhuma pessoa identificada nas gravações."
|
||||
optionRows={optionRows}
|
||||
clear={selected.length ? clear : undefined}
|
||||
/>
|
||||
|
||||
{selected.map((person) => (
|
||||
<button
|
||||
key={person}
|
||||
type="button"
|
||||
className="inline-flex h-8 min-h-8 items-center gap-1.5 rounded-lg border border-input bg-white px-3 text-xs font-semibold focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
onClick={() => navigate(removeRecordingPerson(viewState, person))}
|
||||
aria-label={`Remover filtro de ${person}`}
|
||||
>
|
||||
<FunnelIcon className="size-3.5 shrink-0" aria-hidden="true" />
|
||||
<span className="max-w-56 truncate">Pessoa: {person}</span>
|
||||
<XIcon className="size-3.5 shrink-0" aria-hidden="true" />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -66,8 +66,16 @@ export const RecordingResultCard = ({ recording }: { recording: RecordingListIte
|
|||
</p>
|
||||
)}
|
||||
|
||||
{recording.matchedPersons.length > 0 ? (
|
||||
{recording.topics.length > 0 || recording.matchedPersons.length > 0 ? (
|
||||
<div className="mt-2 flex flex-wrap items-center gap-2 text-xs">
|
||||
{recording.topics.map((topic) => (
|
||||
<span
|
||||
key={topic.value}
|
||||
className="inline-flex min-h-7 items-center rounded-md bg-muted px-2 py-1 text-xs font-semibold"
|
||||
>
|
||||
{topic.label}
|
||||
</span>
|
||||
))}
|
||||
{recording.matchedPersons.map((person) => (
|
||||
<span
|
||||
key={person}
|
||||
|
|
@ -77,7 +85,9 @@ export const RecordingResultCard = ({ recording }: { recording: RecordingListIte
|
|||
{person}
|
||||
</span>
|
||||
))}
|
||||
<span className="text-muted-foreground">aparece nesta gravação</span>
|
||||
{recording.matchedPersons.length > 0 ? (
|
||||
<span className="text-muted-foreground">aparece nesta gravação</span>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
|
|
|||
51
src/components/campaign/recording/RecordingSortSelect.tsx
Normal file
51
src/components/campaign/recording/RecordingSortSelect.tsx
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
'use client'
|
||||
|
||||
import { useCampaignListFilterNavigation } from '@/components/campaign/shared/useCampaignListFilterNavigation'
|
||||
import {
|
||||
buildRecordingListHref,
|
||||
RECORDING_SORT_OPTIONS,
|
||||
recordingSortIsDuration,
|
||||
type RecordingListState,
|
||||
type RecordingSortKey,
|
||||
} from '@/utilities/recordings/recordingListUrl'
|
||||
|
||||
/**
|
||||
* C219 — the list ordering control (design scene 01): "Mais recentes" (the
|
||||
* default, never serialized) plus the two duration orders. A duration order
|
||||
* only lists rows with a measured duration, so the hint says it out loud.
|
||||
*/
|
||||
export const RecordingSortSelect = ({ state }: { state: RecordingListState }) => {
|
||||
const { navigate, isPending } = useCampaignListFilterNavigation({
|
||||
state,
|
||||
toHref: (next) => buildRecordingListHref(next, 1),
|
||||
})
|
||||
const value: RecordingSortKey = state.sort ?? 'recentes'
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-end gap-1">
|
||||
<label className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
Ordenar por
|
||||
<select
|
||||
value={value}
|
||||
disabled={isPending}
|
||||
className="min-h-10 rounded-md border border-input bg-white px-3 py-2 text-sm text-foreground disabled:opacity-70"
|
||||
onChange={(event) => {
|
||||
const next = event.target.value as RecordingSortKey
|
||||
navigate({ ...state, page: 1, sort: next === 'recentes' ? undefined : next })
|
||||
}}
|
||||
>
|
||||
{RECORDING_SORT_OPTIONS.map((option) => (
|
||||
<option key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{recordingSortIsDuration(state) ? (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Gravações sem duração aparecem apenas em Mais recentes.
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
import { TriangleAlertIcon } from 'lucide-react'
|
||||
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/Alert'
|
||||
|
||||
/**
|
||||
* C219 — the discreet fallback notice when `mode=tema` was asked on the
|
||||
* recordings source but the theme expansion was unavailable. The list below
|
||||
* shows the literal results; the notice keeps the user's request honest
|
||||
* instead of hiding the downgrade (same contract as the Câmara acervo, C192).
|
||||
*/
|
||||
export const RecordingThemeFallbackNotice = () => (
|
||||
<Alert
|
||||
variant="pending"
|
||||
data-testid="recording-theme-fallback"
|
||||
className="gap-3 border-estimate-pending/80 bg-estimate-pending/55 px-4 py-3"
|
||||
>
|
||||
<TriangleAlertIcon aria-hidden="true" />
|
||||
<AlertTitle className="text-sm font-medium">
|
||||
A busca por tema está indisponível agora.
|
||||
</AlertTitle>
|
||||
<AlertDescription className="text-xs leading-5">
|
||||
Você pediu “Por tema”. Para não interromper o trabalho, mostramos abaixo os resultados por
|
||||
termo exato.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)
|
||||
83
src/components/campaign/shared/CampaignSearchModeControl.tsx
Normal file
83
src/components/campaign/shared/CampaignSearchModeControl.tsx
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
'use client'
|
||||
|
||||
import { SparklesIcon, TriangleAlertIcon } from 'lucide-react'
|
||||
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { SpeechSearchMode } from '@/utilities/speech/speechListUrl'
|
||||
|
||||
/** C192/C219 — segmented search-mode button (mobile full width, desktop inline). */
|
||||
const modeButtonClass = (active: boolean, tone: 'termo' | 'tema'): string =>
|
||||
cn(
|
||||
'min-h-11 rounded-md px-3 text-sm md:min-h-9',
|
||||
active
|
||||
? cn(
|
||||
'bg-white font-semibold shadow-sm ring-1 ring-border',
|
||||
tone === 'tema' ? 'text-primary' : 'text-foreground',
|
||||
)
|
||||
: 'font-medium text-muted-foreground',
|
||||
)
|
||||
|
||||
/**
|
||||
* C219 — the "Termo exato | Por tema" selector shared by the two acervo
|
||||
* sources. The mechanics (mode semantics, degradation) belong to the URL
|
||||
* contract and the loader; this component only renders the choice and the
|
||||
* honest state of the theme bridge.
|
||||
*/
|
||||
export const CampaignSearchModeControl = ({
|
||||
activeMode,
|
||||
themeUnavailable = false,
|
||||
onSelect,
|
||||
relatedHint,
|
||||
}: {
|
||||
activeMode: SpeechSearchMode
|
||||
/** The theme expansion is down; the selector reflects the fallback. */
|
||||
themeUnavailable?: boolean
|
||||
onSelect: (mode: SpeechSearchMode) => void
|
||||
/** Desktop hint of the corpus ("Encontra falas relacionadas pelo sentido."). */
|
||||
relatedHint: string
|
||||
}) => (
|
||||
<div className="mt-3 flex flex-col gap-3 border-t border-border pt-3 md:flex-row md:flex-wrap md:items-center md:justify-between">
|
||||
<div className="flex w-full items-center gap-2 md:w-auto">
|
||||
<span className="hidden text-xs font-medium text-muted-foreground md:inline">Buscar por</span>
|
||||
<div
|
||||
role="group"
|
||||
aria-label="Modo de busca"
|
||||
className="grid w-full grid-cols-2 rounded-lg bg-muted p-1 md:inline-flex md:w-auto"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={activeMode === 'termo'}
|
||||
className={modeButtonClass(activeMode === 'termo', 'termo')}
|
||||
onClick={() => onSelect('termo')}
|
||||
>
|
||||
Termo exato
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={activeMode === 'tema'}
|
||||
aria-disabled={themeUnavailable || undefined}
|
||||
className={modeButtonClass(activeMode === 'tema', 'tema')}
|
||||
onClick={() => {
|
||||
if (themeUnavailable) return
|
||||
onSelect('tema')
|
||||
}}
|
||||
>
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
{themeUnavailable ? (
|
||||
<TriangleAlertIcon
|
||||
className="size-3.5 text-estimate-pending-foreground"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
) : (
|
||||
<SparklesIcon className="size-3.5" aria-hidden="true" />
|
||||
)}
|
||||
Por tema
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="hidden text-xs text-muted-foreground md:block">
|
||||
{themeUnavailable ? 'Indisponível agora; mostramos o termo exato.' : relatedHint}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
|
|
@ -5,8 +5,11 @@ import { useTransition } from 'react'
|
|||
|
||||
import { Button } from '@/components/ui/button'
|
||||
|
||||
/** C192 — re-runs the same `mode=tema` request after a degraded fallback. */
|
||||
export const SpeechThemeRetryButton = () => {
|
||||
/**
|
||||
* C192/C219 — re-runs the same `mode=tema` request after a degraded fallback.
|
||||
* Shared by both acervo sources; the notice copy stays per domain.
|
||||
*/
|
||||
export const CampaignThemeRetryButton = () => {
|
||||
const router = useRouter()
|
||||
const [isPending, startTransition] = useTransition()
|
||||
|
||||
|
|
@ -1,6 +1,5 @@
|
|||
'use client'
|
||||
|
||||
import { SparklesIcon, TriangleAlertIcon } from 'lucide-react'
|
||||
import { useMemo, useOptimistic, useState } from 'react'
|
||||
|
||||
import {
|
||||
|
|
@ -11,9 +10,10 @@ import {
|
|||
CampaignListOmnibox,
|
||||
campaignListOmniboxFormClassName,
|
||||
} from '@/components/campaign/shared/CampaignListOmnibox'
|
||||
import { CampaignSearchModeControl } from '@/components/campaign/shared/CampaignSearchModeControl'
|
||||
import { useCampaignListFilterNavigation } from '@/components/campaign/shared/useCampaignListFilterNavigation'
|
||||
import { selectedFilterTriggerLabel } from '@/lib/campaignListOmnibox'
|
||||
import { SPEECH_SCOPES, SPEECH_TOPICS } from '@/lib/speechFacets'
|
||||
import { cn } from '@/lib/utils'
|
||||
import {
|
||||
buildSpeechListHref,
|
||||
SPEECH_DURATION_BUCKETS,
|
||||
|
|
@ -53,28 +53,6 @@ type SpeechFacet = {
|
|||
labels?: Readonly<Record<string, string>>
|
||||
}
|
||||
|
||||
const selectedTriggerLabel = (
|
||||
base: string,
|
||||
values: readonly string[],
|
||||
labels?: Readonly<Record<string, string>>,
|
||||
): string => {
|
||||
if (values.length === 0) return base
|
||||
if (values.length === 1) return `${base}: ${labels?.[values[0]!] ?? values[0]}`
|
||||
return `${base}: ${values.length}`
|
||||
}
|
||||
|
||||
/** C192 — segmented search-mode button (mobile full width, desktop inline). */
|
||||
const modeButtonClass = (active: boolean, tone: 'termo' | 'tema'): string =>
|
||||
cn(
|
||||
'min-h-11 rounded-md px-3 text-sm md:min-h-9',
|
||||
active
|
||||
? cn(
|
||||
'bg-white font-semibold shadow-sm ring-1 ring-border',
|
||||
tone === 'tema' ? 'text-primary' : 'text-foreground',
|
||||
)
|
||||
: 'font-medium text-muted-foreground',
|
||||
)
|
||||
|
||||
export const SpeechAcervoFilters = ({
|
||||
state,
|
||||
filterOptions,
|
||||
|
|
@ -257,54 +235,12 @@ export const SpeechAcervoFilters = ({
|
|||
}}
|
||||
/>
|
||||
|
||||
<div className="mt-3 flex flex-col gap-3 border-t border-border pt-3 md:flex-row md:flex-wrap md:items-center md:justify-between">
|
||||
<div className="flex w-full items-center gap-2 md:w-auto">
|
||||
<span className="hidden text-xs font-medium text-muted-foreground md:inline">
|
||||
Buscar por
|
||||
</span>
|
||||
<div
|
||||
role="group"
|
||||
aria-label="Modo de busca"
|
||||
className="grid w-full grid-cols-2 rounded-lg bg-muted p-1 md:inline-flex md:w-auto"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={activeMode === 'termo'}
|
||||
className={modeButtonClass(activeMode === 'termo', 'termo')}
|
||||
onClick={() => runMode('termo')}
|
||||
>
|
||||
Termo exato
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={activeMode === 'tema'}
|
||||
aria-disabled={themeUnavailable || undefined}
|
||||
className={modeButtonClass(activeMode === 'tema', 'tema')}
|
||||
onClick={() => {
|
||||
if (themeUnavailable) return
|
||||
runMode('tema')
|
||||
}}
|
||||
>
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
{themeUnavailable ? (
|
||||
<TriangleAlertIcon
|
||||
className="size-3.5 text-estimate-pending-foreground"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
) : (
|
||||
<SparklesIcon className="size-3.5" aria-hidden="true" />
|
||||
)}
|
||||
Por tema
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="hidden text-xs text-muted-foreground md:block">
|
||||
{themeUnavailable
|
||||
? 'Indisponível agora; mostramos o termo exato.'
|
||||
: 'Encontra falas relacionadas pelo sentido.'}
|
||||
</p>
|
||||
</div>
|
||||
<CampaignSearchModeControl
|
||||
activeMode={activeMode}
|
||||
themeUnavailable={themeUnavailable}
|
||||
onSelect={runMode}
|
||||
relatedHint="Encontra falas relacionadas pelo sentido."
|
||||
/>
|
||||
|
||||
<div
|
||||
role="group"
|
||||
|
|
@ -317,7 +253,7 @@ export const SpeechAcervoFilters = ({
|
|||
id={facet.id}
|
||||
label={facet.label}
|
||||
triggerVariant="chip"
|
||||
triggerLabel={selectedTriggerLabel(facet.label, facet.selected, facet.labels)}
|
||||
triggerLabel={selectedFilterTriggerLabel(facet.label, facet.selected, facet.labels)}
|
||||
active={facet.selected.length > 0}
|
||||
closeOnChoose={false}
|
||||
optionRows={facetRows(facet.prefix, facet.options, facet.selected)}
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ import { StateDeputySelect } from '@/components/cards/StateDeputySelect'
|
|||
import { useCardCutout } from '@/components/cards/useCardCutout'
|
||||
import { DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { DrawerDescription, DrawerHeader, DrawerTitle } from '@/components/ui/Drawer'
|
||||
import { COLINHA_FONT_FAMILY, colinhaVoteRows } from '@/lib/cardColinha'
|
||||
import { COLINHA_ESTADUAL_LABEL, COLINHA_FONT_FAMILY } from '@/lib/cardColinha'
|
||||
import { TEAM_CARD_NAME_SLOT, type CardModel, type CardRect } from '@/lib/cardModels'
|
||||
import { fitCardName, type CardNameFit } from '@/lib/cardNameFit'
|
||||
import {
|
||||
|
|
@ -90,12 +90,12 @@ const STATE_DEPUTY_PREVIEW_WIDTH: Record<StateDeputyPreviewStage, string> = {
|
|||
}
|
||||
|
||||
/**
|
||||
* S31 — the colinha stages of the design gate: compact while the estadual is
|
||||
* unchosen (scene 2, 145px) and the scene 3/5 stage after the pick (405px
|
||||
* desktop, 300px mobile).
|
||||
* S31/S34 — the colinha stages of the design gate: the delivered art while the
|
||||
* estadual is unchosen (scene 1: 236px desktop / scene 2: 248px mobile) and the
|
||||
* scene 3/5 stage after the pick (405px desktop, 300px mobile).
|
||||
*/
|
||||
const COLINHA_PREVIEW_WIDTH: Record<'idle' | 'selected', string> = {
|
||||
idle: 'max-w-[9.0625rem]',
|
||||
idle: 'max-w-[15.5rem] sm:max-w-[14.75rem]',
|
||||
selected: 'max-w-[18.75rem] sm:max-w-[25.3125rem]',
|
||||
}
|
||||
|
||||
|
|
@ -194,8 +194,6 @@ export const CardComposer = ({ model, shell, fontFamily, onClose }: CardComposer
|
|||
const [loadState, setLoadState] = useState<'loading' | 'ready' | 'error'>('loading')
|
||||
const [baseImage, setBaseImage] = useState<HTMLImageElement | null>(null)
|
||||
const [overlayImage, setOverlayImage] = useState<HTMLImageElement | null>(null)
|
||||
/** S31 — the colinha brand lockup of the top box (`lockupSrc`). */
|
||||
const [lockupImage, setLockupImage] = useState<HTMLImageElement | null>(null)
|
||||
const [previewImage, setPreviewImage] = useState<HTMLImageElement | null>(null)
|
||||
const [downloadError, setDownloadError] = useState<string | null>(null)
|
||||
const [isDownloading, setIsDownloading] = useState(false)
|
||||
|
|
@ -219,6 +217,8 @@ export const CardComposer = ({ model, shell, fontFamily, onClose }: CardComposer
|
|||
const zoomInputId = useId()
|
||||
|
||||
const photoWindow = model.photoWindow
|
||||
/** S33 — the model's adjustment policy: the two team models are position-free. */
|
||||
const photoPosition = model.photoPosition ?? 'bounded'
|
||||
const isNameModel = model.kind === 'name'
|
||||
const isTeamModel = model.kind === 'team'
|
||||
const isColinhaModel = model.kind === 'colinha'
|
||||
|
|
@ -226,8 +226,6 @@ export const CardComposer = ({ model, shell, fontFamily, onClose }: CardComposer
|
|||
const selectedDeputy = selectedDeputySlug
|
||||
? (getStateDeputyCard(selectedDeputySlug) ?? null)
|
||||
: null
|
||||
/** S31 — the estadual row owns the label/case of the `Linha conferida` copy. */
|
||||
const estadualRow = colinhaVoteRows(selectedDeputy)[1]
|
||||
const deputyPairReady = selectedDeputy !== null && deputyImages?.slug === selectedDeputy.slug
|
||||
// S30 — the tone reference is the selected deputy's group art, frozen when the
|
||||
// cutout starts (switching the deputy later keeps the processed photo).
|
||||
|
|
@ -266,7 +264,6 @@ export const CardComposer = ({ model, shell, fontFamily, onClose }: CardComposer
|
|||
setLoadState('loading')
|
||||
setBaseImage(null)
|
||||
setOverlayImage(null)
|
||||
setLockupImage(null)
|
||||
setPreviewImage(null)
|
||||
|
||||
const load = async () => {
|
||||
|
|
@ -275,22 +272,18 @@ export const CardComposer = ({ model, shell, fontFamily, onClose }: CardComposer
|
|||
if (!fontReady) throw new Error('card-font-unavailable')
|
||||
// S30 — the dobradinha model loads its art pair per selection (below);
|
||||
// the static defaults stay unused so no illustrative JULIO art flashes
|
||||
// before the choice. S31 — the colinha composes the top from its three
|
||||
// official assets and never draws the tile art (`previewSrc`).
|
||||
const [image, overlay, lockup, preview] = await Promise.all([
|
||||
// before the choice. S34 — the colinha draws the approved art as the
|
||||
// base and carries no `previewSrc` (the tile falls back to `assetSrc`).
|
||||
const [image, overlay, preview] = await Promise.all([
|
||||
isStateDeputyModel ? Promise.resolve(null) : loadCardImage(model.assetSrc),
|
||||
!isStateDeputyModel && model.overlaySrc
|
||||
? loadCardImage(model.overlaySrc)
|
||||
: Promise.resolve(null),
|
||||
model.lockupSrc ? loadCardImage(model.lockupSrc) : Promise.resolve(null),
|
||||
model.previewSrc && !isColinhaModel
|
||||
? loadCardImage(model.previewSrc)
|
||||
: Promise.resolve(null),
|
||||
model.previewSrc ? loadCardImage(model.previewSrc) : Promise.resolve(null),
|
||||
])
|
||||
if (cancelled) return
|
||||
setBaseImage(image)
|
||||
setOverlayImage(overlay)
|
||||
setLockupImage(lockup)
|
||||
setPreviewImage(preview)
|
||||
setLoadState('ready')
|
||||
} catch {
|
||||
|
|
@ -307,7 +300,6 @@ export const CardComposer = ({ model, shell, fontFamily, onClose }: CardComposer
|
|||
isColinhaModel,
|
||||
model.assetSrc,
|
||||
model.overlaySrc,
|
||||
model.lockupSrc,
|
||||
model.previewSrc,
|
||||
fontFamily,
|
||||
])
|
||||
|
|
@ -356,15 +348,12 @@ export const CardComposer = ({ model, shell, fontFamily, onClose }: CardComposer
|
|||
}
|
||||
|
||||
if (isColinhaModel) {
|
||||
// S31 — the slip: official top composition + legal + the six rows; the
|
||||
// estadual row follows the shared selection and the fixed rows never
|
||||
// change. No name, photo or cutout enters this flow.
|
||||
if (!baseImage || !overlayImage || !lockupImage) return
|
||||
// S34 — the approved art is the base; only the estadual row is drawn over
|
||||
// it (or nothing, before a pick). No name, photo or cutout enters this flow.
|
||||
if (!baseImage) return
|
||||
ctx.clearRect(0, 0, model.width, model.height)
|
||||
renderColinhaCard(ctx, model, {
|
||||
group: baseImage,
|
||||
lockup: lockupImage,
|
||||
band: overlayImage,
|
||||
image: baseImage,
|
||||
deputy: selectedDeputy,
|
||||
fontFamily: COLINHA_FONT_FAMILY,
|
||||
measure: createCardMeasure(ctx, COLINHA_FONT_FAMILY, 900),
|
||||
|
|
@ -465,7 +454,6 @@ export const CardComposer = ({ model, shell, fontFamily, onClose }: CardComposer
|
|||
}, [
|
||||
baseImage,
|
||||
overlayImage,
|
||||
lockupImage,
|
||||
previewImage,
|
||||
loadState,
|
||||
isNameModel,
|
||||
|
|
@ -554,7 +542,7 @@ export const CardComposer = ({ model, shell, fontFamily, onClose }: CardComposer
|
|||
const dy = (event.clientY - drag.y) * scale
|
||||
dragRef.current = { ...drag, x: event.clientX, y: event.clientY }
|
||||
withTransform((transform, size, window) =>
|
||||
panCardPhotoTransform(transform, size, window, dx, dy),
|
||||
panCardPhotoTransform(transform, size, window, dx, dy, { position: photoPosition }),
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -564,13 +552,13 @@ export const CardComposer = ({ model, shell, fontFamily, onClose }: CardComposer
|
|||
|
||||
const panBy = (dx: number, dy: number) => {
|
||||
withTransform((transform, size, window) =>
|
||||
panCardPhotoTransform(transform, size, window, dx, dy),
|
||||
panCardPhotoTransform(transform, size, window, dx, dy, { position: photoPosition }),
|
||||
)
|
||||
}
|
||||
|
||||
const zoomTo = (zoom: number) => {
|
||||
withTransform((transform, size, window) =>
|
||||
zoomCardPhotoTransform(transform, size, window, zoom),
|
||||
zoomCardPhotoTransform(transform, size, window, zoom, undefined, { position: photoPosition }),
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -673,12 +661,13 @@ export const CardComposer = ({ model, shell, fontFamily, onClose }: CardComposer
|
|||
</p>
|
||||
) : null
|
||||
|
||||
// The drawer header defaults to centered + `shrink-0`, so a long description
|
||||
// would overflow the popup; `text-left!` + `flex-1` port the design gate
|
||||
// The dialog header takes the available row width so the close button
|
||||
// sits on the right edge (S35 design gate). The drawer header defaults to
|
||||
// centered + `shrink-0`, so `text-left!` + `flex-1` port the gate
|
||||
// (left-aligned, wrapped header) for every model in the shared composer.
|
||||
const header =
|
||||
shell === 'dialog' ? (
|
||||
<DialogHeader className="min-w-0 text-left">
|
||||
<DialogHeader className="min-w-0 flex-1 text-left">
|
||||
{eyebrowNode}
|
||||
<DialogTitle className="text-xl font-black tracking-[-0.01em] text-balance">
|
||||
{title}
|
||||
|
|
@ -708,6 +697,20 @@ export const CardComposer = ({ model, shell, fontFamily, onClose }: CardComposer
|
|||
: isTeamModel
|
||||
? TEAM_PREVIEW_WIDTH[teamPreviewStage]
|
||||
: 'max-w-[22rem]'
|
||||
/**
|
||||
* S34 designer critique (c) — the filled desktop state follows the gate's
|
||||
* scene 3 composition: the full 9:16 preview beside the controls (two-column
|
||||
* grid, wider dialog), never clipped by the footer. The empty state keeps the
|
||||
* compact dialog of scene 1. The `data-colinha-filled` attribute below is the
|
||||
* contract that widens the dialog in `CardsStudio` (`has-[[...]]`).
|
||||
*/
|
||||
const colinhaFilledDialog = isColinhaModel && shell === 'dialog' && selectedDeputy !== null
|
||||
/**
|
||||
* S34 — caps the colinha preview by the viewport so the whole 9:16 fits
|
||||
* between the dialog chrome (`max-h-[92dvh]` in `CardsStudio` minus ~224px of
|
||||
* header/footer); on tall viewports the width reaches the gate's 405px.
|
||||
*/
|
||||
const colinhaPreviewMaxHeight = 'max-h-[calc(92dvh-14rem)]'
|
||||
|
||||
const nameInputClassName = `mt-2 h-11 w-full rounded-lg bg-white px-3 text-base text-(--campaign-ink) focus-visible:ring-2 focus-visible:ring-(--pt-red) focus-visible:outline-none ${
|
||||
nameError
|
||||
|
|
@ -793,10 +796,13 @@ export const CardComposer = ({ model, shell, fontFamily, onClose }: CardComposer
|
|||
// team notice leaves the viewport by the end of the scroll.
|
||||
const bodyScrollClassName = `min-h-0 flex-1 overflow-y-auto overscroll-contain px-5 pt-4 ${
|
||||
teamBodyNotice && shell === 'drawer' ? 'pb-14' : 'pb-5'
|
||||
}`
|
||||
}${colinhaFilledDialog ? ' sm:grid sm:grid-cols-[430px_1fr] sm:items-start sm:gap-8' : ''}`
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col bg-(--background) text-(--foreground)">
|
||||
<div
|
||||
data-colinha-filled={colinhaFilledDialog ? 'true' : undefined}
|
||||
className="flex min-h-0 flex-1 flex-col bg-(--background) text-(--foreground)"
|
||||
>
|
||||
<div className="flex items-start gap-3 px-5 pt-5">
|
||||
{header}
|
||||
<button
|
||||
|
|
@ -825,7 +831,9 @@ export const CardComposer = ({ model, shell, fontFamily, onClose }: CardComposer
|
|||
) : null}
|
||||
|
||||
<div
|
||||
className={`relative mx-auto w-full ${previewWidthClassName} ${adjustable ? 'touch-none' : ''}`}
|
||||
className={`relative mx-auto w-full ${previewWidthClassName} ${adjustable ? 'touch-none' : ''}${
|
||||
colinhaFilledDialog ? ' sm:col-start-1 sm:row-start-1' : ''
|
||||
}`}
|
||||
tabIndex={adjustable ? 0 : undefined}
|
||||
role={adjustable ? 'group' : undefined}
|
||||
aria-label={adjustable ? 'Ajuste da foto' : undefined}
|
||||
|
|
@ -851,7 +859,7 @@ export const CardComposer = ({ model, shell, fontFamily, onClose }: CardComposer
|
|||
model={model}
|
||||
canvasRef={canvasRef}
|
||||
className={`mx-auto block h-auto w-auto max-w-full rounded-lg border border-(--campaign-line) shadow-sm transition-opacity ${
|
||||
isColinhaModel ? '' : 'max-h-[38dvh] '
|
||||
isColinhaModel ? `${colinhaPreviewMaxHeight} ` : 'max-h-[38dvh] '
|
||||
}${loadState === 'loading' ? 'opacity-60' : 'opacity-100'}`}
|
||||
onPointerDown={adjustable ? handlePointerDown : undefined}
|
||||
onPointerMove={adjustable ? handlePointerMove : undefined}
|
||||
|
|
@ -883,13 +891,13 @@ export const CardComposer = ({ model, shell, fontFamily, onClose }: CardComposer
|
|||
) : null}
|
||||
|
||||
{step === 'compose' && isColinhaModel ? (
|
||||
<div>
|
||||
<div className={colinhaFilledDialog ? 'sm:col-start-2 sm:row-start-1' : undefined}>
|
||||
<StateDeputySelect selected={selectedDeputy} onSelect={handleSelectDeputy} />
|
||||
{selectedDeputy ? (
|
||||
<div className="mt-4 rounded-lg bg-white p-4 ring-1 ring-(--campaign-line)">
|
||||
<p className="text-sm font-bold text-(--campaign-ink)">Linha conferida</p>
|
||||
<p className="mt-1 text-sm text-(--campaign-muted)">
|
||||
{estadualRow.officeLines.join(' ')} · {estadualRow.candidate} ·{' '}
|
||||
{COLINHA_ESTADUAL_LABEL} · {selectedDeputy.name.toLocaleUpperCase('pt-BR')} ·{' '}
|
||||
{selectedDeputy.ballotNumber}
|
||||
</p>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -6,12 +6,12 @@ import type { CardModel } from '@/lib/cardModels'
|
|||
import { cn } from '@/lib/utils'
|
||||
|
||||
/**
|
||||
* S13/S15/S31 — artwork preview of one card model, shared by the home section
|
||||
* and the `/cards` gallery. The name tile reuses the empty master with a
|
||||
* S13/S15/S31/S34 — artwork preview of one card model, shared by the home
|
||||
* section and the `/cards` gallery. The name tile reuses the empty master with a
|
||||
* `SEU NOME` preview drawn by the real composer pipeline (S14); the photo tiles
|
||||
* show the official transparent overlay above a neutral photo slot; the team
|
||||
* and colinha tiles show `previewSrc` (the filled example / the approved model
|
||||
* art) with the `NOVO` badge.
|
||||
* tiles show `previewSrc` (the filled example) and the colinha tile shows the
|
||||
* approved art itself (`assetSrc`, S34), with the `NOVO` badge.
|
||||
*/
|
||||
export const CardModelTile = ({
|
||||
model,
|
||||
|
|
|
|||
|
|
@ -82,7 +82,10 @@ export const CardsStudio = ({
|
|||
// `flex flex-col` (over the kit's `grid`) constrains the composer
|
||||
// body so its scrollable area shrinks and the CTA footer stays
|
||||
// pinned — required by the longer state-deputy selector (S30).
|
||||
className="flex max-h-[92dvh] flex-col gap-0 overflow-hidden p-0 sm:max-w-lg sm:p-0"
|
||||
// S34: the filled colinha state widens the dialog for the gate's
|
||||
// scene 3 two-column composition (the empty state stays compact);
|
||||
// `data-colinha-filled` is set by the composer (see CardComposer).
|
||||
className="flex max-h-[92dvh] flex-col gap-0 overflow-hidden p-0 sm:max-w-lg sm:p-0 has-[[data-colinha-filled]]:sm:max-w-[60rem]"
|
||||
>
|
||||
<CardComposer
|
||||
model={selectedModel}
|
||||
|
|
|
|||
|
|
@ -7,19 +7,27 @@ import { CONTENT_PIECE_FOCUS } from './contentPieceClasses'
|
|||
* S27 — the Central de Conteúdos bar (artefato: cenas 01/04/06/07/08): the
|
||||
* negative logo over the campaign red and, on a piece page, the way back to
|
||||
* the catalogue. Page-local, like the jingles header — not a site shell.
|
||||
*
|
||||
* S36 — the official lockup ships with a large transparent frame (canvas
|
||||
* 1037x595, visible ink 790x285: top 162, bottom 148, left 123, right 124),
|
||||
* so the header crops the frame with a fixed window instead of scaling the
|
||||
* whole canvas: 142x39 mobile (ink 186px, left -22 / top -29) and 188x50
|
||||
* desktop (ink 246px, left -29 / top -38), per docs/plans/central-conteudos-header-logo-ui-design.html.
|
||||
*/
|
||||
export const ContentPiecePageHeader = ({ backHref }: { backHref?: string }) => (
|
||||
<header className="bg-[#ae1603]">
|
||||
<div className="mx-auto flex h-14 w-full max-w-6xl items-center justify-between gap-3 px-5 sm:h-16 sm:px-8">
|
||||
<Link href="/" aria-label="Início — Jorge Solla 1313" className={CONTENT_PIECE_FOCUS}>
|
||||
<Image
|
||||
src="/campaign-kit/jorge-solla-negativo.png"
|
||||
alt="Jorge Solla"
|
||||
width={1037}
|
||||
height={595}
|
||||
priority
|
||||
className="h-7 w-auto object-contain sm:h-9"
|
||||
/>
|
||||
<span className="relative block h-[39px] w-[142px] shrink-0 overflow-hidden sm:h-[50px] sm:w-[188px]">
|
||||
<Image
|
||||
src="/campaign-kit/jorge-solla-negativo.png"
|
||||
alt="Jorge Solla"
|
||||
width={1037}
|
||||
height={595}
|
||||
priority
|
||||
className="absolute top-[-29px] left-[-22px] h-auto w-[186px] max-w-none sm:top-[-38px] sm:left-[-29px] sm:w-[246px]"
|
||||
/>
|
||||
</span>
|
||||
</Link>
|
||||
{backHref ? (
|
||||
<Link
|
||||
|
|
|
|||
|
|
@ -18,6 +18,21 @@ export type CampaignListOmniboxSuggestion = {
|
|||
keywords?: readonly string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* The trigger text of a facet chip: the dimension alone when nothing is
|
||||
* selected, "Ano: 2026" for one value and "Tema: 3" for several — one spelling
|
||||
* for every acervo filter bar (C154/C219).
|
||||
*/
|
||||
export const selectedFilterTriggerLabel = (
|
||||
base: string,
|
||||
values: readonly string[],
|
||||
labels?: Readonly<Record<string, string>>,
|
||||
): string => {
|
||||
if (values.length === 0) return base
|
||||
if (values.length === 1) return `${base}: ${labels?.[values[0]!] ?? values[0]}`
|
||||
return `${base}: ${values.length}`
|
||||
}
|
||||
|
||||
const omniboxQueryMatches = (
|
||||
haystack: string,
|
||||
needle: string,
|
||||
|
|
|
|||
|
|
@ -1,204 +1,78 @@
|
|||
/**
|
||||
* S31 — the pure layout of the `Minha colinha` voting slip: the six vote rows
|
||||
* (five fixed + the state deputy picked from the S30 catalog) and the pixel
|
||||
* geometry of the approved design gate (`docs/plans/cards-colinha-ui-design.html`)
|
||||
* measured at the real 1080×1920 output. No DOM and no drawing here — the
|
||||
* renderer (`renderColinhaCard` in `cardRender.ts`) consumes these constants,
|
||||
* so the model stays unit-testable with a deterministic fake.
|
||||
*
|
||||
* The gate is the canonical source of the numbers (the human-approved model
|
||||
* `modelo-colinha.jpeg` is the conference reference and the gallery tile).
|
||||
* S34 — the drawn overlay of the `Minha colinha` voting slip. The approved art
|
||||
* (`public/cards/modelo-colinha.jpeg`, the byte-for-byte 900×1600 file the human
|
||||
* delivered) is the base of the preview and the PNG; the only drawn element is
|
||||
* the state-deputy row (2nd line of the art) — the burned label wiped by a white
|
||||
* mask, the label redrawn at the left, the picked name at the right and one
|
||||
* digit per printed box. The geometry is the approved design gate
|
||||
* (`docs/plans/cards-colinha-arte-exata-ui-design.html`) measured at the real
|
||||
* 1080×1920 output (the exact 1.2× of the art); the label size was corrected by
|
||||
* the designer critique (c) to the art's printed cap height. No DOM and no
|
||||
* drawing here — the renderer (`renderColinhaCard` in `cardRender.ts`) consumes
|
||||
* these constants, so the model stays unit-testable with a deterministic fake.
|
||||
*/
|
||||
|
||||
import type { StateDeputyCatalogEntry } from './stateDeputyCatalog'
|
||||
|
||||
export type ColinhaRow = {
|
||||
/** Office label lines, e.g. `['DEPUTADO', 'FEDERAL']` (already uppercase). */
|
||||
readonly officeLines: readonly string[]
|
||||
/** Candidate display name: Title Case on the fixed rows, uppercase on the estadual. */
|
||||
readonly candidate: string
|
||||
/** One glyph per digit box, in reading order. */
|
||||
readonly digits: readonly string[]
|
||||
/** The estadual row before a deputy is picked: empty boxes + a dimmed CONFIRMA. */
|
||||
readonly empty?: boolean
|
||||
export type ColinhaRowNameFit = {
|
||||
readonly fontSize: number
|
||||
readonly text: string
|
||||
}
|
||||
|
||||
/** The five fixed choices of the slip, in the gate's order (estadual goes second). */
|
||||
export const COLINHA_FIXED_ROWS: readonly ColinhaRow[] = [
|
||||
{ officeLines: ['DEPUTADO', 'FEDERAL'], candidate: 'Jorge Solla', digits: ['1', '3', '1', '3'] },
|
||||
{ officeLines: ['SENADOR'], candidate: 'Jaques Wagner', digits: ['1', '3', '0'] },
|
||||
{ officeLines: ['SENADOR'], candidate: 'Rui Costa', digits: ['1', '3', '3'] },
|
||||
{ officeLines: ['GOVERNADOR'], candidate: 'Jerônimo', digits: ['1', '3'] },
|
||||
{ officeLines: ['PRESIDENTE'], candidate: 'Lula', digits: ['1', '3'] },
|
||||
]
|
||||
|
||||
const COLINHA_ESTADUAL_OFFICE_LINES = ['DEPUTADO', 'ESTADUAL'] as const
|
||||
export const COLINHA_ESTADUAL_PLACEHOLDER = 'Escolha abaixo'
|
||||
const COLINHA_ESTADUAL_DIGIT_COUNT = 5
|
||||
|
||||
/**
|
||||
* S31 — the slip typography of the approved gate (`Arial, Helvetica, sans-serif`,
|
||||
* the gate's card body face), not the site display family the rest of the
|
||||
* studio draws with. The designer's critique (c) fixed this as gate parity.
|
||||
* S34 — the slip typography of the approved gate: the body face of the art
|
||||
* (label at weight 400, name at 900) and the digit face (`Arial Black` first).
|
||||
* The exact heavy face of the art is not shipped in the repo (the gate marks it
|
||||
* NEEDS ASSET); the port proves the closest face side by side and the gate
|
||||
* decides composition and geometry.
|
||||
*/
|
||||
export const COLINHA_FONT_FAMILY = 'Arial, Helvetica, sans-serif'
|
||||
export const COLINHA_DIGIT_FONT_FAMILY = 'Arial Black, Arial, Helvetica, sans-serif'
|
||||
|
||||
/** The vertical legal line of the left edge (literal of the intent). */
|
||||
export const COLINHA_LEGAL_TEXT =
|
||||
'FEDERAÇÃO BRASIL DA ESPERANÇA - FE BRASIL (PT-PC DO B - PV) | CNPJ CANDIDATO: 68.430.467/0001-05'
|
||||
|
||||
/** The green seal every row carries. */
|
||||
export const COLINHA_CONFIRM_LABEL = 'CONFIRMA'
|
||||
/** The 2nd line of the art: the office label redrawn over the white mask. */
|
||||
export const COLINHA_ESTADUAL_LABEL = 'DEPUTADO ESTADUAL'
|
||||
|
||||
/**
|
||||
* The six rows in the gate's order: federal, the estadual (filled from the
|
||||
* catalog entry, or the empty placeholder), then the remaining four fixed rows.
|
||||
* S34 — pixel geometry at the 1080×1920 output, measured from the approved
|
||||
* design gate (the gate's percentages resolved against the 1080×1920 stage).
|
||||
* The mask wipes the burned label of the art and stops at the top of the five
|
||||
* printed boxes; `copy` is the right-aligned pair band and the name baseline is
|
||||
* anchored on the cap top of the name.
|
||||
*/
|
||||
export const colinhaVoteRows = (deputy: StateDeputyCatalogEntry | null): ColinhaRow[] => {
|
||||
const estadual: ColinhaRow = deputy
|
||||
? {
|
||||
officeLines: COLINHA_ESTADUAL_OFFICE_LINES,
|
||||
candidate: deputy.name.toLocaleUpperCase('pt-BR'),
|
||||
digits: [...deputy.ballotNumber],
|
||||
}
|
||||
: {
|
||||
officeLines: COLINHA_ESTADUAL_OFFICE_LINES,
|
||||
candidate: COLINHA_ESTADUAL_PLACEHOLDER,
|
||||
digits: Array.from({ length: COLINHA_ESTADUAL_DIGIT_COUNT }, () => ''),
|
||||
empty: true,
|
||||
}
|
||||
|
||||
return [COLINHA_FIXED_ROWS[0], estadual, ...COLINHA_FIXED_ROWS.slice(1)]
|
||||
}
|
||||
|
||||
/**
|
||||
* Pixel geometry at the 1080×1920 output, measured from the rendered gate. The
|
||||
* top composes the official assets (group photo, brand box, band); the body is
|
||||
* the measured CSS grid of the gate (`30% | 1fr | auto`, rows of 108).
|
||||
*/
|
||||
export const COLINHA_LAYOUT = {
|
||||
background: '#ffffff',
|
||||
top: {
|
||||
height: 710.4,
|
||||
background: '#148fc2',
|
||||
photoWidth: 1080,
|
||||
photoHeight: 1440,
|
||||
photoOffsetY: -335.62,
|
||||
lockup: {
|
||||
x: 32.4,
|
||||
y: 21.29,
|
||||
width: 529.19,
|
||||
height: 134.97,
|
||||
padding: 27,
|
||||
gradientAngleDeg: 125,
|
||||
gradientSplit: 0.52,
|
||||
gradientFrom: '#e4102f',
|
||||
gradientTo: '#184e92',
|
||||
imageWidth: 1037,
|
||||
imageHeight: 595,
|
||||
},
|
||||
band: {
|
||||
y: 504.39,
|
||||
height: 206,
|
||||
background: '#e4102f',
|
||||
sourceY: 1232.36,
|
||||
imageWidth: 1080,
|
||||
imageHeight: 1440,
|
||||
},
|
||||
},
|
||||
legal: {
|
||||
x: 7.55,
|
||||
y: 748.79,
|
||||
width: 15.66,
|
||||
height: 1132.81,
|
||||
fontSize: 15.66,
|
||||
letterSpacing: 0.31,
|
||||
color: '#333333',
|
||||
},
|
||||
body: {
|
||||
x: 51.83,
|
||||
y: 710.39,
|
||||
width: 1028.17,
|
||||
height: 1209.61,
|
||||
paddingTop: 34.56,
|
||||
paddingX: 35.64,
|
||||
paddingBottom: 32.4,
|
||||
rowGap: 34.56,
|
||||
},
|
||||
row: {
|
||||
minHeight: 108,
|
||||
officeWidthRatio: 0.3,
|
||||
columnGap: 21.6,
|
||||
},
|
||||
office: {
|
||||
fontSize: 27,
|
||||
lineHeight: 27.54,
|
||||
color: '#171717',
|
||||
},
|
||||
candidate: {
|
||||
fontSize: 26.46,
|
||||
minFontSize: 18,
|
||||
color: '#e4102f',
|
||||
gap: 9.6,
|
||||
},
|
||||
export const COLINHA_ROW_LAYOUT = {
|
||||
mask: { x: 264.6, y: 1073.28, width: 619.92, height: 55.68, fill: '#ffffff' },
|
||||
copy: { left: 290.52, top: 1084.03, width: 570.24, right: 860.76 },
|
||||
// The design gate's 2.15cqw (23.22px) sat below the art's printed labels;
|
||||
// the designer critique (c) set 26.9px so the cap height matches the 19.2px
|
||||
// of the fixed rows at weight 400.
|
||||
office: { fontSize: 26.9, weight: 400, color: '#202020' },
|
||||
name: { fontSize: 36.72, weight: 900, color: '#e4102f', letterSpacingEm: -0.04 },
|
||||
gap: 16.2,
|
||||
digit: {
|
||||
width: 59.39,
|
||||
height: 73.44,
|
||||
borderWidth: 5.94,
|
||||
radius: 6.48,
|
||||
fontSize: 46.44,
|
||||
gap: 8.1,
|
||||
borderColor: '#111111',
|
||||
color: '#141414',
|
||||
background: '#ffffff',
|
||||
emptyBorderColor: '#9a9a9a',
|
||||
emptyBackground: '#fafafa',
|
||||
},
|
||||
confirm: {
|
||||
fontSize: 21.6,
|
||||
paddingX: 21.6,
|
||||
paddingY: 17.28,
|
||||
background: '#009647',
|
||||
color: '#ffffff',
|
||||
emptyOpacity: 0.3,
|
||||
left: 279.72,
|
||||
step: 74.52,
|
||||
width: 65.88,
|
||||
height: 83.52,
|
||||
top: 1121.28,
|
||||
fontSize: 45.9,
|
||||
weight: 900,
|
||||
color: '#171717',
|
||||
},
|
||||
} as const
|
||||
|
||||
type ColinhaCandidateFit = {
|
||||
readonly fontSize: number
|
||||
readonly lines: readonly string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* S31 — the candidate shrinks inside the office column down to `minFontSize`
|
||||
* (the gate's CSS would wrap freely, but the body keeps its fixed row rhythm).
|
||||
* A name still too long at the floor wraps by word into two lines: the row
|
||||
* grows to ~101 of its 108 and the six rows never reflow.
|
||||
* S34 — the picked name shrinks on one line to fit the white mask band left of
|
||||
* the label (`maxWidth` already discounts the label and the gap), so the pair
|
||||
* never leaves the mask and the name is never cut nor wrapped. The gate's own
|
||||
* CSS keeps the pair right-aligned and lets it use the whole band (the declared
|
||||
* `copy` box is narrower than a long pair).
|
||||
*/
|
||||
export const fitColinhaCandidate = (
|
||||
export const fitColinhaRowName = (
|
||||
text: string,
|
||||
measure: (text: string, fontSize: number) => { width: number },
|
||||
maxWidth: number,
|
||||
): ColinhaCandidateFit => {
|
||||
const { fontSize: ideal, minFontSize } = COLINHA_LAYOUT.candidate
|
||||
): ColinhaRowNameFit => {
|
||||
const ideal = COLINHA_ROW_LAYOUT.name.fontSize
|
||||
const width = measure(text, ideal).width
|
||||
if (width <= maxWidth || width <= 0) return { fontSize: ideal, lines: [text] }
|
||||
if (width <= maxWidth || width <= 0) return { fontSize: ideal, text }
|
||||
|
||||
const shrunk = Math.floor((ideal * maxWidth) / width)
|
||||
if (shrunk >= minFontSize) return { fontSize: shrunk, lines: [text] }
|
||||
|
||||
const lines: string[] = []
|
||||
let current = ''
|
||||
for (const word of text.split(' ')) {
|
||||
const candidate = current ? `${current} ${word}` : word
|
||||
if (current && measure(candidate, minFontSize).width > maxWidth) {
|
||||
lines.push(current)
|
||||
current = word
|
||||
} else {
|
||||
current = candidate
|
||||
}
|
||||
}
|
||||
if (current) lines.push(current)
|
||||
|
||||
return { fontSize: minFontSize, lines: lines.length > 1 ? lines : [text] }
|
||||
return { fontSize: Math.floor((ideal * maxWidth) / width), text }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
* the home section, the `/cards` gallery and the canvas renderer share one
|
||||
* catalog (no second editor, no CMS): each entry carries the master asset, the
|
||||
* real output size in pixels and, for photo/team models, the transparent window
|
||||
* the visitor's photo must cover.
|
||||
* the photo is framed and zoomed over (fully covered under the bounded default).
|
||||
*
|
||||
* Geometry comes from the master files (pixel-measured, keep in sync with
|
||||
* `docs/plans/cards-personalizados-campanha-impl.md` and
|
||||
|
|
@ -30,6 +30,15 @@ export type CardRect = {
|
|||
height: number
|
||||
}
|
||||
|
||||
/**
|
||||
* S33 — the visitor-adjustment policy of a photo/team model. `bounded` (the
|
||||
* omitted default) pins the photo offsets so the transparent window is always
|
||||
* covered (S13/S14); `free` leaves the offsets untouched in both axes — the
|
||||
* photo may leave the frame and reveal the art behind it — while the zoom keeps
|
||||
* its `[1, 4]` range (human gate of 2026-09-24).
|
||||
*/
|
||||
export type CardPhotoPosition = 'bounded' | 'free'
|
||||
|
||||
export type CardModel = {
|
||||
id: CardModelId
|
||||
kind: CardModelKind
|
||||
|
|
@ -37,18 +46,15 @@ export type CardModel = {
|
|||
assetSrc: string
|
||||
width: number
|
||||
height: number
|
||||
/** Photo and team models: the transparent window the photo must cover. */
|
||||
/** Photo and team models: the transparent window the photo is framed over. */
|
||||
photoWindow?: CardRect
|
||||
/** Photo/team models: `free` unlocks the position clamp during the adjustment. */
|
||||
photoPosition?: CardPhotoPosition
|
||||
/** Team model: the master front overlay drawn above the cutout photo. */
|
||||
overlaySrc?: string
|
||||
/**
|
||||
* S31 — colinha model: the brand lockup of the top block, loaded besides the
|
||||
* `assetSrc` (group photo) and `overlaySrc` (band art) of the composition.
|
||||
*/
|
||||
lockupSrc?: string
|
||||
/**
|
||||
* Gallery tile art: the filled example shown by the team models before a
|
||||
* cutout is ready, and the approved model art of the colinha tile.
|
||||
* cutout is ready.
|
||||
*/
|
||||
previewSrc?: string
|
||||
/**
|
||||
|
|
@ -99,6 +105,7 @@ export const CARD_MODELS: readonly CardModel[] = [
|
|||
width: 1080,
|
||||
height: 1440,
|
||||
photoWindow: { x: 286, y: 439, width: 592, height: 577 },
|
||||
photoPosition: 'free',
|
||||
},
|
||||
{
|
||||
id: 'time-do-estadual',
|
||||
|
|
@ -115,18 +122,16 @@ export const CARD_MODELS: readonly CardModel[] = [
|
|||
width: 1080,
|
||||
height: 1440,
|
||||
photoWindow: { x: 286, y: 439, width: 592, height: 577 },
|
||||
photoPosition: 'free',
|
||||
},
|
||||
{
|
||||
id: 'minha-colinha',
|
||||
kind: 'colinha',
|
||||
label: 'Minha colinha',
|
||||
// S31 — the top block composes the official kit (group photo + brand box +
|
||||
// band); `previewSrc` is the exact approved model art of the gallery tile
|
||||
// (byte-for-byte copy) and `lockupSrc` is the brand drawn in the top box.
|
||||
assetSrc: '/cards/team-card-base.png',
|
||||
overlaySrc: '/cards/team-card-front.png',
|
||||
lockupSrc: '/campaign-kit/marca-negativa-completa.png',
|
||||
previewSrc: '/cards/modelo-colinha.jpeg',
|
||||
// S34 — the approved art delivered by the human is the base of the preview
|
||||
// and the download (drawn whole at 1.2×); the only drawn element is the
|
||||
// estadual row overlay. The gallery tile shows the same art via `assetSrc`.
|
||||
assetSrc: '/cards/modelo-colinha.jpeg',
|
||||
stateDeputyPicker: true,
|
||||
badge: 'NOVO',
|
||||
width: 1080,
|
||||
|
|
|
|||
|
|
@ -1,14 +1,19 @@
|
|||
/**
|
||||
* S13 — pure cover/pan/zoom math for the photo card models. The visitor photo
|
||||
* is drawn full-bleed under the master overlay and must always cover the
|
||||
* transparent window: `clampCardPhotoTransform` keeps the zoom inside
|
||||
* is drawn full-bleed under the master overlay and, by default, must always
|
||||
* cover the transparent window: `clampCardPhotoTransform` keeps the zoom inside
|
||||
* [1, 4] and pins the offsets so no gap can open at the window edges.
|
||||
*
|
||||
* S33 — the two team models carry `photoPosition: 'free'` (human gate of
|
||||
* 2026-09-24): their adjustment is not clamped in any axis — the photo may
|
||||
* leave the frame — while the zoom keeps its range. The policy arrives through
|
||||
* `CardPhotoClampOptions`; the omitted default is the S13 bounded behavior.
|
||||
*
|
||||
* `centerCardPhotoTransform` is the initial framing (cover on the window, not
|
||||
* on the whole card) so the face lands on the visible area of the frame.
|
||||
*/
|
||||
|
||||
import type { CardRect } from './cardModels'
|
||||
import type { CardPhotoPosition, CardRect } from './cardModels'
|
||||
|
||||
export const CARD_PHOTO_MIN_ZOOM = 1
|
||||
export const CARD_PHOTO_MAX_ZOOM = 4
|
||||
|
|
@ -37,6 +42,15 @@ export type CardPhotoTransform = {
|
|||
offsetY: number
|
||||
}
|
||||
|
||||
/**
|
||||
* S33 — the adjustment policy of the call site: `bounded` (omitted default)
|
||||
* pins the offsets so the photo covers the window; `free` keeps the offsets
|
||||
* untouched in both axes, normalizing only the zoom.
|
||||
*/
|
||||
export type CardPhotoClampOptions = {
|
||||
position?: CardPhotoPosition
|
||||
}
|
||||
|
||||
/** Alpha bounding box of a cutout photo, in source pixels. */
|
||||
export type CardAlphaBbox = {
|
||||
x: number
|
||||
|
|
@ -61,8 +75,9 @@ export const cardPhotoDrawRect = (
|
|||
transform: CardPhotoTransform,
|
||||
source: CardPhotoSize,
|
||||
window: CardRect,
|
||||
options: CardPhotoClampOptions = {},
|
||||
): CardRect => {
|
||||
const clamped = clampCardPhotoTransform(transform, source, window)
|
||||
const clamped = clampCardPhotoTransform(transform, source, window, options)
|
||||
const scale = coverScale(source, window) * clamped.zoom
|
||||
|
||||
return {
|
||||
|
|
@ -77,8 +92,13 @@ export const clampCardPhotoTransform = (
|
|||
transform: CardPhotoTransform,
|
||||
source: CardPhotoSize,
|
||||
window: CardRect,
|
||||
options: CardPhotoClampOptions = {},
|
||||
): CardPhotoTransform => {
|
||||
const zoom = clamp(transform.zoom, CARD_PHOTO_MIN_ZOOM, CARD_PHOTO_MAX_ZOOM)
|
||||
if (options.position === 'free') {
|
||||
return { zoom, offsetX: transform.offsetX, offsetY: transform.offsetY }
|
||||
}
|
||||
|
||||
const scale = coverScale(source, window) * zoom
|
||||
const width = source.width * scale
|
||||
const height = source.height * scale
|
||||
|
|
@ -149,23 +169,26 @@ export const frameCardPhotoOnBbox = (
|
|||
)
|
||||
}
|
||||
|
||||
/** Nudges the offset by a step in card pixels, clamped to the window. */
|
||||
/** Nudges the offset by a step in card pixels; clamped to the window by default. */
|
||||
export const panCardPhotoTransform = (
|
||||
transform: CardPhotoTransform,
|
||||
source: CardPhotoSize,
|
||||
window: CardRect,
|
||||
dx: number,
|
||||
dy: number,
|
||||
options: CardPhotoClampOptions = {},
|
||||
): CardPhotoTransform =>
|
||||
clampCardPhotoTransform(
|
||||
{ ...transform, offsetX: transform.offsetX + dx, offsetY: transform.offsetY + dy },
|
||||
source,
|
||||
window,
|
||||
options,
|
||||
)
|
||||
|
||||
/**
|
||||
* Rescales around a window anchor (used by the zoom control): keeps the point
|
||||
* under `anchor` stable from old to new zoom, then clamps.
|
||||
* under `anchor` stable from old to new zoom, then clamps — under the free
|
||||
* policy only the zoom is normalized.
|
||||
*/
|
||||
export const zoomCardPhotoTransform = (
|
||||
transform: CardPhotoTransform,
|
||||
|
|
@ -176,9 +199,10 @@ export const zoomCardPhotoTransform = (
|
|||
x: window.x + window.width / 2,
|
||||
y: window.y + window.height / 2,
|
||||
},
|
||||
options: CardPhotoClampOptions = {},
|
||||
): CardPhotoTransform => {
|
||||
const zoom = clamp(nextZoom, CARD_PHOTO_MIN_ZOOM, CARD_PHOTO_MAX_ZOOM)
|
||||
if (zoom === transform.zoom) return clampCardPhotoTransform(transform, source, window)
|
||||
if (zoom === transform.zoom) return clampCardPhotoTransform(transform, source, window, options)
|
||||
|
||||
const ratio = zoom / transform.zoom
|
||||
|
||||
|
|
@ -190,5 +214,6 @@ export const zoomCardPhotoTransform = (
|
|||
},
|
||||
source,
|
||||
window,
|
||||
options,
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,11 +8,10 @@
|
|||
*/
|
||||
|
||||
import {
|
||||
COLINHA_CONFIRM_LABEL,
|
||||
COLINHA_LAYOUT,
|
||||
COLINHA_LEGAL_TEXT,
|
||||
colinhaVoteRows,
|
||||
fitColinhaCandidate,
|
||||
COLINHA_DIGIT_FONT_FAMILY,
|
||||
COLINHA_ESTADUAL_LABEL,
|
||||
COLINHA_ROW_LAYOUT,
|
||||
fitColinhaRowName,
|
||||
} from './cardColinha'
|
||||
import {
|
||||
BRAND_FALLBACK_FONT,
|
||||
|
|
@ -47,6 +46,8 @@ export type CardDrawContext = {
|
|||
fillStyle: string | CanvasGradient | CanvasPattern
|
||||
textAlign: CanvasTextAlign
|
||||
textBaseline: CanvasTextBaseline
|
||||
imageSmoothingEnabled: boolean
|
||||
imageSmoothingQuality: ImageSmoothingQuality
|
||||
drawImage(image: CanvasImageSource, dx: number, dy: number, dWidth: number, dHeight: number): void
|
||||
fillRect(x: number, y: number, width: number, height: number): void
|
||||
fillText(text: string, x: number, y: number): void
|
||||
|
|
@ -289,7 +290,11 @@ export type TeamCardRenderArgs = {
|
|||
|
||||
export type TeamCardRenderResult = {
|
||||
fit: CardNameFit
|
||||
/** The clamped photo transform; `null` for the silhouette subject. */
|
||||
/**
|
||||
* The normalized photo transform (zoom always in range; S33 — the offsets
|
||||
* follow the model's `photoPosition`, so a `free` model keeps them as sent);
|
||||
* `null` for the silhouette subject.
|
||||
*/
|
||||
transform: CardPhotoTransform | null
|
||||
}
|
||||
|
||||
|
|
@ -309,9 +314,23 @@ export const renderTeamCard = (
|
|||
|
||||
let transform: CardPhotoTransform | null = null
|
||||
if (args.subject.kind === 'photo') {
|
||||
const rect = cardPhotoDrawRect(args.subject.transform, args.subject.photoSize, args.window)
|
||||
// S33 — the drawing and the returned transform follow the same policy read
|
||||
// from the model: a `free` team model never re-clamps the visitor position
|
||||
// (that would snap the photo back on the next paint).
|
||||
const options = { position: model.photoPosition ?? 'bounded' }
|
||||
const rect = cardPhotoDrawRect(
|
||||
args.subject.transform,
|
||||
args.subject.photoSize,
|
||||
args.window,
|
||||
options,
|
||||
)
|
||||
ctx.drawImage(args.subject.photo, rect.x, rect.y, rect.width, rect.height)
|
||||
transform = clampCardPhotoTransform(args.subject.transform, args.subject.photoSize, args.window)
|
||||
transform = clampCardPhotoTransform(
|
||||
args.subject.transform,
|
||||
args.subject.photoSize,
|
||||
args.window,
|
||||
options,
|
||||
)
|
||||
} else {
|
||||
drawCardVisitorSilhouette(ctx, args.window)
|
||||
}
|
||||
|
|
@ -336,256 +355,74 @@ export const renderTeamCard = (
|
|||
}
|
||||
|
||||
export type ColinhaCardRenderArgs = {
|
||||
/** Group photo of the top block (`team-card-base.png`). */
|
||||
group: CanvasImageSource
|
||||
/** Brand lockup of the top-left box (`marca-negativa-completa.png`). */
|
||||
lockup: CanvasImageSource
|
||||
/** Front art cropped to the red band (`team-card-front.png`). */
|
||||
band: CanvasImageSource
|
||||
/** The chosen state deputy; `null` draws the empty estadual row. */
|
||||
/** The approved art (`/cards/modelo-colinha.jpeg`), drawn whole at 1.2×. */
|
||||
image: CanvasImageSource
|
||||
/** The chosen state deputy; `null` leaves the art exactly as delivered. */
|
||||
deputy: StateDeputyCatalogEntry | null
|
||||
fontFamily: string
|
||||
/** The 900-weight measure the colinha draws with. */
|
||||
/** The 900-weight measure the estadual name is fitted and placed with. */
|
||||
measure: CardMeasureText
|
||||
}
|
||||
|
||||
/** The cap top of the drawn font at `fontSize` (baseline placement of the rows). */
|
||||
const capAt = (measure: CardMeasureText, fontSize: number): number =>
|
||||
measure('X', fontSize).actualBoundingBoxAscent
|
||||
|
||||
/**
|
||||
* S31 — the top block of the colinha: the group photo cover-cropped, the
|
||||
* diagonal two-color brand box with the contained lockup, and the red band
|
||||
* cropped from the official front art. Every rect comes from `COLINHA_LAYOUT`
|
||||
* (measured from the approved gate).
|
||||
*/
|
||||
const drawColinhaTop = (
|
||||
ctx: CardDrawContext,
|
||||
model: CardModel,
|
||||
args: Pick<ColinhaCardRenderArgs, 'group' | 'lockup' | 'band'>,
|
||||
): void => {
|
||||
const { top } = COLINHA_LAYOUT
|
||||
const { lockup, band } = top
|
||||
|
||||
ctx.save()
|
||||
ctx.beginPath()
|
||||
ctx.rect(0, 0, model.width, top.height)
|
||||
ctx.clip()
|
||||
|
||||
ctx.fillStyle = top.background
|
||||
ctx.fillRect(0, 0, model.width, top.height)
|
||||
ctx.drawImage(args.group, 0, top.photoOffsetY, top.photoWidth, top.photoHeight)
|
||||
|
||||
// CSS `linear-gradient(125deg, …)`: the gradient line passes through the box
|
||||
// center with the CSS length `|w·sinθ| + |h·cosθ|`.
|
||||
const angle = (lockup.gradientAngleDeg * Math.PI) / 180
|
||||
const dirX = Math.sin(angle)
|
||||
const dirY = -Math.cos(angle)
|
||||
const gradientLength = Math.abs(lockup.width * dirX) + Math.abs(lockup.height * dirY)
|
||||
const centerX = lockup.x + lockup.width / 2
|
||||
const centerY = lockup.y + lockup.height / 2
|
||||
const gradient = ctx.createLinearGradient(
|
||||
centerX - (dirX * gradientLength) / 2,
|
||||
centerY - (dirY * gradientLength) / 2,
|
||||
centerX + (dirX * gradientLength) / 2,
|
||||
centerY + (dirY * gradientLength) / 2,
|
||||
)
|
||||
gradient.addColorStop(0, lockup.gradientFrom)
|
||||
gradient.addColorStop(lockup.gradientSplit, lockup.gradientFrom)
|
||||
gradient.addColorStop(lockup.gradientSplit, lockup.gradientTo)
|
||||
gradient.addColorStop(1, lockup.gradientTo)
|
||||
|
||||
ctx.fillStyle = gradient
|
||||
ctx.fillRect(lockup.x, lockup.y, lockup.width, lockup.height)
|
||||
|
||||
// `object-fit: contain` inside the box padding (the gate's CSS resolves the
|
||||
// percentage padding against the top block, so it is already in pixels here).
|
||||
const innerX = lockup.x + lockup.padding
|
||||
const innerY = lockup.y + lockup.padding
|
||||
const innerWidth = lockup.width - lockup.padding * 2
|
||||
const innerHeight = lockup.height - lockup.padding * 2
|
||||
const lockupScale = Math.min(innerWidth / lockup.imageWidth, innerHeight / lockup.imageHeight)
|
||||
const lockupWidth = lockup.imageWidth * lockupScale
|
||||
const lockupHeight = lockup.imageHeight * lockupScale
|
||||
ctx.drawImage(
|
||||
args.lockup,
|
||||
innerX + (innerWidth - lockupWidth) / 2,
|
||||
innerY + (innerHeight - lockupHeight) / 2,
|
||||
lockupWidth,
|
||||
lockupHeight,
|
||||
)
|
||||
|
||||
ctx.save()
|
||||
ctx.beginPath()
|
||||
ctx.rect(0, band.y, model.width, band.height)
|
||||
ctx.clip()
|
||||
ctx.fillStyle = band.background
|
||||
ctx.fillRect(0, band.y, model.width, band.height)
|
||||
ctx.drawImage(args.band, 0, band.y - band.sourceY, band.imageWidth, band.imageHeight)
|
||||
ctx.restore()
|
||||
ctx.restore()
|
||||
}
|
||||
|
||||
/** S31 — the vertical legal line of the left edge (reads bottom-to-top). */
|
||||
const drawColinhaLegal = (ctx: CardDrawContext, fontFamily: string): void => {
|
||||
const { legal } = COLINHA_LAYOUT
|
||||
|
||||
ctx.save()
|
||||
ctx.translate(legal.x + legal.width / 2, legal.y + legal.height)
|
||||
ctx.rotate(-Math.PI / 2)
|
||||
ctx.font = `700 ${legal.fontSize}px ${fontFamily}`
|
||||
ctx.letterSpacing = `${legal.letterSpacing}px`
|
||||
ctx.fillStyle = legal.color
|
||||
ctx.textAlign = 'left'
|
||||
ctx.textBaseline = 'middle'
|
||||
ctx.fillText(COLINHA_LEGAL_TEXT, 0, 0)
|
||||
ctx.restore()
|
||||
}
|
||||
|
||||
/** S31 — one digit box: the border is the outer rounded rect, the fill the inner one. */
|
||||
const drawColinhaDigit = (
|
||||
ctx: CardDrawContext,
|
||||
x: number,
|
||||
y: number,
|
||||
empty: boolean,
|
||||
digit: string,
|
||||
fontFamily: string,
|
||||
): void => {
|
||||
const { digit: box } = COLINHA_LAYOUT
|
||||
|
||||
ctx.fillStyle = empty ? box.emptyBorderColor : box.borderColor
|
||||
ctx.beginPath()
|
||||
ctx.roundRect(x, y, box.width, box.height, box.radius)
|
||||
ctx.fill()
|
||||
|
||||
ctx.fillStyle = empty ? box.emptyBackground : box.background
|
||||
ctx.beginPath()
|
||||
ctx.roundRect(
|
||||
x + box.borderWidth,
|
||||
y + box.borderWidth,
|
||||
box.width - box.borderWidth * 2,
|
||||
box.height - box.borderWidth * 2,
|
||||
box.radius - box.borderWidth,
|
||||
)
|
||||
ctx.fill()
|
||||
|
||||
if (empty || !digit) return
|
||||
|
||||
ctx.fillStyle = box.color
|
||||
ctx.font = `900 ${box.fontSize}px ${fontFamily}`
|
||||
ctx.textAlign = 'center'
|
||||
ctx.textBaseline = 'middle'
|
||||
ctx.fillText(digit, x + box.width / 2, y + box.height / 2)
|
||||
}
|
||||
|
||||
/** S31 — the green `CONFIRMA` pill, right-aligned on the row. */
|
||||
const drawColinhaConfirm = (
|
||||
ctx: CardDrawContext,
|
||||
x: number,
|
||||
y: number,
|
||||
height: number,
|
||||
empty: boolean,
|
||||
fontFamily: string,
|
||||
measure: CardMeasureText,
|
||||
): void => {
|
||||
const { confirm } = COLINHA_LAYOUT
|
||||
const width = measure(COLINHA_CONFIRM_LABEL, confirm.fontSize).width + confirm.paddingX * 2
|
||||
const previousAlpha = ctx.globalAlpha
|
||||
|
||||
if (empty) ctx.globalAlpha = confirm.emptyOpacity
|
||||
|
||||
ctx.fillStyle = confirm.background
|
||||
ctx.beginPath()
|
||||
ctx.roundRect(x - width, y, width, height, height / 2)
|
||||
ctx.fill()
|
||||
|
||||
ctx.fillStyle = confirm.color
|
||||
ctx.font = `900 ${confirm.fontSize}px ${fontFamily}`
|
||||
ctx.textAlign = 'center'
|
||||
ctx.textBaseline = 'middle'
|
||||
ctx.fillText(COLINHA_CONFIRM_LABEL, x - width / 2, y + height / 2)
|
||||
|
||||
ctx.globalAlpha = previousAlpha
|
||||
}
|
||||
|
||||
/**
|
||||
* S31 — the `Minha colinha` slip: white base → top composition (official
|
||||
* assets) → vertical legal line → the six vote rows of the gate's grid
|
||||
* (`30% | 1fr | auto`, rows of 108, body centered). The estadual row comes from
|
||||
* the S30 catalog entry (or the empty placeholder); the five fixed rows are
|
||||
* template content and never change.
|
||||
* S34 — the `Minha colinha` slip: the approved art drawn whole (the 900×1600
|
||||
* JPEG scaled 1.2× to the 1080×1920 output) and, only when a state deputy is
|
||||
* picked, the 2nd line: the burned label wiped by the white mask, the label
|
||||
* redrawn at the left, the name at the right (right-aligned pair) and one digit
|
||||
* per printed box. Without a pick not a single pixel is added — the art is the
|
||||
* empty state.
|
||||
*/
|
||||
export const renderColinhaCard = (
|
||||
ctx: CardDrawContext,
|
||||
model: CardModel,
|
||||
args: ColinhaCardRenderArgs,
|
||||
): void => {
|
||||
const { body, row: rowLayout, office, candidate, digit, confirm } = COLINHA_LAYOUT
|
||||
const rows = colinhaVoteRows(args.deputy)
|
||||
ctx.imageSmoothingEnabled = true
|
||||
ctx.imageSmoothingQuality = 'high'
|
||||
ctx.drawImage(args.image, 0, 0, model.width, model.height)
|
||||
|
||||
ctx.fillStyle = COLINHA_LAYOUT.background
|
||||
ctx.fillRect(0, 0, model.width, model.height)
|
||||
const { deputy } = args
|
||||
if (!deputy) return
|
||||
|
||||
drawColinhaTop(ctx, model, args)
|
||||
drawColinhaLegal(ctx, args.fontFamily)
|
||||
const { mask, copy, office, name, gap, digit } = COLINHA_ROW_LAYOUT
|
||||
const nameText = deputy.name.toLocaleUpperCase('pt-BR')
|
||||
|
||||
const contentX = body.x + body.paddingX
|
||||
const contentWidth = body.width - body.paddingX * 2
|
||||
const contentTop = body.y + body.paddingTop
|
||||
const contentHeight = body.height - body.paddingTop - body.paddingBottom
|
||||
const rowsHeight = rows.length * rowLayout.minHeight + (rows.length - 1) * body.rowGap
|
||||
const startY = contentTop + (contentHeight - rowsHeight) / 2
|
||||
const officeWidth = contentWidth * rowLayout.officeWidthRatio
|
||||
const officeCap = capAt(args.measure, office.fontSize)
|
||||
const confirmHeight = confirm.fontSize + confirm.paddingY * 2
|
||||
// The label keeps its own face/weight; the pair (label + gap + name) is
|
||||
// right-aligned on `copy.right` and may use the whole white mask band, so the
|
||||
// name only shrinks when it would leave the mask — the gate's own CSS does
|
||||
// the same (its `nowrap` pair overflows the declared copy width to the left).
|
||||
ctx.font = `${office.weight} ${office.fontSize}px ${args.fontFamily}`
|
||||
const officeWidth = ctx.measureText(COLINHA_ESTADUAL_LABEL).width
|
||||
const nameFit = fitColinhaRowName(nameText, args.measure, copy.right - mask.x - officeWidth - gap)
|
||||
const baseline = copy.top + args.measure('X', nameFit.fontSize).actualBoundingBoxAscent
|
||||
// The label sits just left of the drawn name: measure with the same tracking.
|
||||
ctx.letterSpacing = `${name.letterSpacingEm * nameFit.fontSize}px`
|
||||
const nameWidth = args.measure(nameFit.text, nameFit.fontSize).width
|
||||
ctx.letterSpacing = '0px'
|
||||
|
||||
rows.forEach((voteRow, index) => {
|
||||
const rowY = startY + index * (rowLayout.minHeight + body.rowGap)
|
||||
const candidateFit = fitColinhaCandidate(voteRow.candidate, args.measure, officeWidth)
|
||||
const candidateCap = capAt(args.measure, candidateFit.fontSize)
|
||||
const officeHeight = voteRow.officeLines.length * office.lineHeight
|
||||
const blockHeight =
|
||||
officeHeight + candidate.gap + candidateFit.lines.length * candidateFit.fontSize
|
||||
const blockTop = rowY + (rowLayout.minHeight - blockHeight) / 2
|
||||
ctx.fillStyle = mask.fill
|
||||
ctx.fillRect(mask.x, mask.y, mask.width, mask.height)
|
||||
|
||||
ctx.fillStyle = office.color
|
||||
ctx.textAlign = 'left'
|
||||
ctx.textBaseline = 'alphabetic'
|
||||
ctx.font = `900 ${office.fontSize}px ${args.fontFamily}`
|
||||
voteRow.officeLines.forEach((line, lineIndex) => {
|
||||
ctx.fillText(line, contentX, blockTop + lineIndex * office.lineHeight + officeCap)
|
||||
})
|
||||
ctx.fillStyle = office.color
|
||||
ctx.font = `${office.weight} ${office.fontSize}px ${args.fontFamily}`
|
||||
ctx.textAlign = 'right'
|
||||
ctx.textBaseline = 'alphabetic'
|
||||
ctx.letterSpacing = '0px'
|
||||
ctx.fillText(COLINHA_ESTADUAL_LABEL, copy.right - nameWidth - gap, baseline)
|
||||
|
||||
ctx.fillStyle = candidate.color
|
||||
ctx.font = `900 ${candidateFit.fontSize}px ${args.fontFamily}`
|
||||
candidateFit.lines.forEach((line, lineIndex) => {
|
||||
ctx.fillText(
|
||||
line,
|
||||
contentX,
|
||||
blockTop + officeHeight + candidate.gap + candidateCap + lineIndex * candidateFit.fontSize,
|
||||
)
|
||||
})
|
||||
ctx.fillStyle = name.color
|
||||
ctx.font = `${name.weight} ${nameFit.fontSize}px ${args.fontFamily}`
|
||||
ctx.letterSpacing = `${name.letterSpacingEm * nameFit.fontSize}px`
|
||||
ctx.fillText(nameFit.text, copy.right, baseline)
|
||||
ctx.letterSpacing = '0px'
|
||||
|
||||
const boxY = rowY + (rowLayout.minHeight - digit.height) / 2
|
||||
voteRow.digits.forEach((glyph, digitIndex) => {
|
||||
drawColinhaDigit(
|
||||
ctx,
|
||||
contentX + officeWidth + rowLayout.columnGap + digitIndex * (digit.width + digit.gap),
|
||||
boxY,
|
||||
voteRow.empty === true,
|
||||
glyph,
|
||||
args.fontFamily,
|
||||
)
|
||||
})
|
||||
|
||||
drawColinhaConfirm(
|
||||
ctx,
|
||||
contentX + contentWidth,
|
||||
rowY + (rowLayout.minHeight - confirmHeight) / 2,
|
||||
confirmHeight,
|
||||
voteRow.empty === true,
|
||||
args.fontFamily,
|
||||
args.measure,
|
||||
)
|
||||
ctx.fillStyle = digit.color
|
||||
ctx.font = `${digit.weight} ${digit.fontSize}px ${COLINHA_DIGIT_FONT_FAMILY}`
|
||||
ctx.textAlign = 'center'
|
||||
ctx.textBaseline = 'middle'
|
||||
const centerY = digit.top + digit.height / 2
|
||||
const digits = [...deputy.ballotNumber]
|
||||
digits.forEach((glyph, index) => {
|
||||
ctx.fillText(glyph, digit.left + digit.width / 2 + index * digit.step, centerY)
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -335,6 +335,36 @@ export const contentPieceSearchText = (input: ContentPieceSearchInput): string =
|
|||
.join(' '),
|
||||
)
|
||||
|
||||
/**
|
||||
* C220 — why a piece added by link stayed a peça-link. Closed vocabulary in
|
||||
* product language (the UI only maps the label), persisted by the pipeline on
|
||||
* a `pronto` row: a peça-link is a legitimate outcome, never a failure. The
|
||||
* labels are the gate's verbatim literals.
|
||||
*/
|
||||
export const CONTENT_PIECE_LINK_FAILURE_REASONS = [
|
||||
'nao-encontrado',
|
||||
'carrossel',
|
||||
'indisponivel',
|
||||
'sem-credencial',
|
||||
] as const
|
||||
|
||||
export type ContentPieceLinkFailureReason = (typeof CONTENT_PIECE_LINK_FAILURE_REASONS)[number]
|
||||
|
||||
export const contentPieceLinkFailureReasonLabels: Record<ContentPieceLinkFailureReason, string> = {
|
||||
'nao-encontrado': 'Link não encontrado entre as mídias recentes do perfil',
|
||||
carrossel: 'Carrossel: sem arquivo único para baixar',
|
||||
indisponivel: 'Instagram indisponível no momento',
|
||||
'sem-credencial': 'Sem credencial do Instagram configurada',
|
||||
}
|
||||
|
||||
export const isContentPieceLinkFailureReason = (
|
||||
value: unknown,
|
||||
): value is ContentPieceLinkFailureReason =>
|
||||
CONTENT_PIECE_LINK_FAILURE_REASONS.includes(value as ContentPieceLinkFailureReason)
|
||||
|
||||
/** The honest name of a piece that circulates only by its platform link. */
|
||||
export const CONTENT_PIECE_LINK_LABEL = 'Peça-link'
|
||||
|
||||
type ContentPieceInstagramLink = {
|
||||
origin: 'instagram'
|
||||
canonicalUrl: string
|
||||
|
|
@ -354,8 +384,10 @@ const INSTAGRAM_KINDS = ['p', 'reel', 'reels', 'tv']
|
|||
/**
|
||||
* Normalizes an Instagram or YouTube link into its canonical form, dropping
|
||||
* tracking parameters and hash. The shortcode/video id is the identity, so two
|
||||
* pastes of the same post collapse into one `sourceUrl` (unique in the DB).
|
||||
* Returns null for any other host — the piece only accepts the two platforms.
|
||||
* pastes of the same post collapse into one `sourceUrl` (unique in the DB) —
|
||||
* including the profile-prefixed spelling the browser copies from the grid
|
||||
* (`/<profile>/reel/<shortcode>/`). Returns null for any other host — the
|
||||
* piece only accepts the two platforms.
|
||||
*/
|
||||
export const parseContentPieceLink = (raw: string | null | undefined): ContentPieceLink | null => {
|
||||
const trimmed = (raw ?? '').trim()
|
||||
|
|
@ -373,7 +405,13 @@ export const parseContentPieceLink = (raw: string | null | undefined): ContentPi
|
|||
const segments = url.pathname.split('/').filter(Boolean)
|
||||
|
||||
if (host === 'instagram.com') {
|
||||
const [kind, shortcode] = segments
|
||||
// Two accepted spellings: the canonical `/<kind>/<shortcode>/` and the one
|
||||
// the browser copies from the profile, `/<profile>/<kind>/<shortcode>/`.
|
||||
const [first, second, third] = segments
|
||||
const prefixed = segments.length === 3
|
||||
if (prefixed && (first ?? '').toLowerCase() === 'stories') return null
|
||||
const kind = prefixed ? second : first
|
||||
const shortcode = prefixed ? third : second
|
||||
if (!kind || !shortcode || !INSTAGRAM_KINDS.includes(kind.toLowerCase())) return null
|
||||
const safeShortcode = shortcode.replace(/[^A-Za-z0-9_-]/g, '')
|
||||
if (!safeShortcode) return null
|
||||
|
|
@ -434,6 +472,8 @@ export type ContentPieceViewModel = {
|
|||
pieceDateLabel: string | null
|
||||
publishedAtLabel: string | null
|
||||
failureMessage: string | null
|
||||
linkFailureReason: ContentPieceLinkFailureReason | null
|
||||
linkFailureReasonLabel: string | null
|
||||
canRetry: boolean
|
||||
isPublished: boolean
|
||||
hasFile: boolean
|
||||
|
|
@ -457,6 +497,7 @@ type ContentPieceViewRecord = {
|
|||
pieceDate?: string | null
|
||||
publishedAt?: string | null
|
||||
error?: string | null
|
||||
linkFailureReason?: string | null
|
||||
media?: number | { id: number } | null
|
||||
}
|
||||
|
||||
|
|
@ -495,6 +536,9 @@ export const toContentPieceViewModel = (record: ContentPieceViewRecord): Content
|
|||
const status = normalizedStatus(record.status)
|
||||
const origin = normalizedOrigin(record.origin)
|
||||
const hasFile = mediaIdOf(record.media) !== null
|
||||
const linkFailureReason = isContentPieceLinkFailureReason(record.linkFailureReason)
|
||||
? record.linkFailureReason
|
||||
: null
|
||||
|
||||
return {
|
||||
id: record.id,
|
||||
|
|
@ -515,6 +559,10 @@ export const toContentPieceViewModel = (record: ContentPieceViewRecord): Content
|
|||
pieceDateLabel: dateLabelOf(record.pieceDate),
|
||||
publishedAtLabel: dateLabelOf(record.publishedAt),
|
||||
failureMessage: contentPieceFailureMessage({ error: record.error, step }),
|
||||
linkFailureReason,
|
||||
linkFailureReasonLabel: linkFailureReason
|
||||
? contentPieceLinkFailureReasonLabels[linkFailureReason]
|
||||
: null,
|
||||
canRetry: canRetryContentPiece(processingStatus),
|
||||
isPublished: status === 'publicado',
|
||||
hasFile,
|
||||
|
|
|
|||
280
src/lib/webSpeech.ts
Normal file
280
src/lib/webSpeech.ts
Normal file
|
|
@ -0,0 +1,280 @@
|
|||
import { z } from 'zod'
|
||||
|
||||
/**
|
||||
* C215 — pure contract of the web-speech ingestion: the platform taxonomy, the
|
||||
* finding-batch schema the discovery (C218) hands over, the natural key
|
||||
* (`web:<platform>:<externalId|url>`) and the canonical URL normalization that
|
||||
* keeps re-runs idempotent. No I/O: the CLI, the pipeline and the tests share
|
||||
* this module.
|
||||
*/
|
||||
|
||||
export const WEB_SPEECH_PLATFORMS = [
|
||||
{ value: 'youtube', label: 'YouTube' },
|
||||
{ value: 'instagram', label: 'Instagram' },
|
||||
{ value: 'radio', label: 'Rádio' },
|
||||
{ value: 'audio', label: 'Áudio' },
|
||||
] as const
|
||||
|
||||
export type WebSpeechPlatform = (typeof WEB_SPEECH_PLATFORMS)[number]['value']
|
||||
|
||||
const WEB_SPEECH_PLATFORM_VALUES = WEB_SPEECH_PLATFORMS.map((platform) => platform.value) as [
|
||||
WebSpeechPlatform,
|
||||
...WebSpeechPlatform[],
|
||||
]
|
||||
|
||||
export const webSpeechPlatformLabel = (value: WebSpeechPlatform): string =>
|
||||
WEB_SPEECH_PLATFORMS.find((platform) => platform.value === value)?.label ?? value
|
||||
|
||||
/** Owner of the private upload collection slug (collection, config and S3). */
|
||||
export const INTERNET_SPEECH_MEDIA_SLUG = 'internetSpeechMedia' as const
|
||||
|
||||
/**
|
||||
* Platforms whose acquisition goes through yt-dlp. The others (`radio`,
|
||||
* `audio`) are direct files: the finding must carry `mediaUrl` or the item
|
||||
* fails honestly in the report — the script never guesses a page's media.
|
||||
*/
|
||||
const YTDLP_PLATFORMS: readonly WebSpeechPlatform[] = ['youtube', 'instagram']
|
||||
|
||||
export const requiresDirectMediaUrl = (platform: WebSpeechPlatform): boolean =>
|
||||
!YTDLP_PLATFORMS.includes(platform)
|
||||
|
||||
const TRACKING_PARAMS = new Set(['fbclid', 'gclid', 'igshid', 'igsh', 'si', 'feature'])
|
||||
|
||||
const isTrackingParam = (name: string): boolean =>
|
||||
TRACKING_PARAMS.has(name) || name.toLowerCase().startsWith('utm_')
|
||||
|
||||
const stripTrackingParams = (url: URL): void => {
|
||||
for (const name of [...url.searchParams.keys()]) {
|
||||
if (isTrackingParam(name)) url.searchParams.delete(name)
|
||||
}
|
||||
}
|
||||
|
||||
const withoutTrailingSlash = (pathname: string): string =>
|
||||
pathname.length > 1 && pathname.endsWith('/') ? pathname.replace(/\/+$/, '') : pathname
|
||||
|
||||
const YOUTUBE_HOSTS = new Set(['youtube.com', 'm.youtube.com', 'music.youtube.com'])
|
||||
const YOUTU_BE_HOSTS = new Set(['youtu.be'])
|
||||
|
||||
const normalizedHost = (url: URL): string => url.hostname.toLowerCase().replace(/^www\./, '')
|
||||
|
||||
const firstPathSegment = (pathname: string): string | null =>
|
||||
pathname.split('/').find((segment) => segment !== '') ?? null
|
||||
|
||||
/** Video id from any YouTube URL shape (`watch`, `shorts`, `live`, `embed`, `youtu.be`). */
|
||||
const youtubeVideoId = (url: URL): string | null => {
|
||||
const host = normalizedHost(url)
|
||||
if (YOUTU_BE_HOSTS.has(host)) return firstPathSegment(url.pathname)
|
||||
if (!YOUTUBE_HOSTS.has(host)) return null
|
||||
if (url.pathname === '/watch') return url.searchParams.get('v')
|
||||
const match = /^\/(?:shorts|live|embed)\/([^/?#]+)/.exec(url.pathname)
|
||||
return match?.[1] ?? null
|
||||
}
|
||||
|
||||
/** Shortcode + kind (`reel`/`p`/`tv`) from any Instagram post URL. */
|
||||
const instagramPost = (url: URL): { kind: string; code: string } | null => {
|
||||
if (normalizedHost(url) !== 'instagram.com') return null
|
||||
const match = /^\/(p|reel|reels|tv)\/([^/?#]+)/.exec(url.pathname)
|
||||
if (!match) return null
|
||||
return { kind: match[1] === 'reels' ? 'reel' : match[1], code: match[2] }
|
||||
}
|
||||
|
||||
const parseUrl = (raw: string): URL | null => {
|
||||
try {
|
||||
return new URL(raw.trim())
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stable URL for identity and provenance: YouTube/Instagram collapse to the
|
||||
* canonical post URL and every platform drops tracking params, the fragment
|
||||
* and a trailing slash. An unparseable URL returns trimmed as-is (the finding
|
||||
* schema validates the shape before this runs).
|
||||
*/
|
||||
export const canonicalWebSpeechUrl = (platform: WebSpeechPlatform, rawUrl: string): string => {
|
||||
const url = parseUrl(rawUrl)
|
||||
if (!url) return rawUrl.trim()
|
||||
|
||||
if (platform === 'youtube') {
|
||||
const videoId = youtubeVideoId(url)
|
||||
if (videoId) return `https://www.youtube.com/watch?v=${videoId}`
|
||||
}
|
||||
if (platform === 'instagram') {
|
||||
const post = instagramPost(url)
|
||||
if (post) return `https://www.instagram.com/${post.kind}/${post.code}/`
|
||||
}
|
||||
|
||||
url.hash = ''
|
||||
stripTrackingParams(url)
|
||||
url.hostname = url.hostname.toLowerCase()
|
||||
url.pathname = withoutTrailingSlash(url.pathname)
|
||||
return url.toString()
|
||||
}
|
||||
|
||||
/**
|
||||
* Natural key of one web speech. `externalId` wins when the discovery already
|
||||
* knows the platform id; otherwise the canonical URL is the identity — the
|
||||
* same URL always produces the same key, so re-running never duplicates.
|
||||
*/
|
||||
export const webSpeechSourceKey = ({
|
||||
platform,
|
||||
url,
|
||||
externalId,
|
||||
}: {
|
||||
platform: WebSpeechPlatform
|
||||
url: string
|
||||
externalId?: string | null
|
||||
}): string => {
|
||||
const id = externalId?.trim()
|
||||
return id ? `web:${platform}:${id}` : `web:${platform}:${canonicalWebSpeechUrl(platform, url)}`
|
||||
}
|
||||
|
||||
/** A web speech row is complete when it has both the transcript and the mirrored file. */
|
||||
export const isCompleteWebSpeechState = (
|
||||
state: { segmentCount: number; mirroredMedia: number | null } | null,
|
||||
): boolean => state !== null && state.segmentCount > 0 && state.mirroredMedia !== null
|
||||
|
||||
const PUBLISHED_AT_PATTERN = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2}))?$/
|
||||
const TIMEZONE_SUFFIX = /(?:Z|[+-]\d{2}:?\d{2})$/
|
||||
|
||||
const isValidCalendarDay = (year: string, month: string, day: string): boolean => {
|
||||
const date = new Date(Date.UTC(Number(year), Number(month) - 1, Number(day)))
|
||||
return (
|
||||
date.getUTCFullYear() === Number(year) &&
|
||||
date.getUTCMonth() === Number(month) - 1 &&
|
||||
date.getUTCDate() === Number(day)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* `speechAt` (Brasília wall-clock text, same contract as the Câmara rows) from
|
||||
* the discovery's `publishedAt` — day-only becomes midnight and an explicit
|
||||
* timezone is converted to America/Bahia. Unrecognized values return null so
|
||||
* the finding fails validation instead of inventing a date.
|
||||
*/
|
||||
export const webSpeechAtFromPublishedAt = (publishedAt: string): string | null => {
|
||||
const trimmed = publishedAt.trim()
|
||||
|
||||
if (TIMEZONE_SUFFIX.test(trimmed)) {
|
||||
const instant = new Date(trimmed)
|
||||
if (Number.isNaN(instant.getTime())) return null
|
||||
// sv-SE renders the ISO-like `YYYY-MM-DD HH:mm` for the requested zone.
|
||||
return new Intl.DateTimeFormat('sv-SE', {
|
||||
timeZone: 'America/Bahia',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
hour12: false,
|
||||
})
|
||||
.format(instant)
|
||||
.replace(' ', 'T')
|
||||
}
|
||||
|
||||
const match = PUBLISHED_AT_PATTERN.exec(trimmed)
|
||||
if (!match) return null
|
||||
const [, year, month, day, hour = '00', minute = '00'] = match
|
||||
if (!isValidCalendarDay(year, month, day)) return null
|
||||
if (Number(hour) > 23 || Number(minute) > 59) return null
|
||||
return `${year}-${month}-${day}T${hour}:${minute}`
|
||||
}
|
||||
|
||||
const MAX_TITLE_LENGTH = 300
|
||||
const MAX_CHANNEL_LENGTH = 200
|
||||
|
||||
const webSpeechFindingSchema = z
|
||||
.object({
|
||||
platform: z.enum(WEB_SPEECH_PLATFORM_VALUES, { error: 'plataforma desconhecida' }),
|
||||
url: z.string({ error: 'url obrigatória' }).trim().url('url inválida'),
|
||||
mediaUrl: z.string().trim().url('mediaUrl inválida').optional(),
|
||||
externalId: z.string().trim().min(1, 'externalId vazio').optional(),
|
||||
title: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1, 'título vazio')
|
||||
.max(MAX_TITLE_LENGTH, `título até ${MAX_TITLE_LENGTH} caracteres`)
|
||||
.optional(),
|
||||
channel: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1, 'canal vazio')
|
||||
.max(MAX_CHANNEL_LENGTH, `canal até ${MAX_CHANNEL_LENGTH} caracteres`)
|
||||
.optional(),
|
||||
publishedAt: z
|
||||
.string({ error: 'publishedAt obrigatório' })
|
||||
.trim()
|
||||
.min(4, 'publishedAt inválido'),
|
||||
durationSeconds: z
|
||||
.number({ error: 'durationSeconds inválido' })
|
||||
.finite()
|
||||
.nonnegative('durationSeconds inválido')
|
||||
.optional(),
|
||||
thumbnailUrl: z.string().trim().url('thumbnailUrl inválida').optional(),
|
||||
})
|
||||
.superRefine((finding, context) => {
|
||||
if (requiresDirectMediaUrl(finding.platform) && !finding.mediaUrl) {
|
||||
context.addIssue({
|
||||
code: 'custom',
|
||||
path: ['mediaUrl'],
|
||||
message: `Achado de ${webSpeechPlatformLabel(finding.platform)} exige mediaUrl (arquivo direto).`,
|
||||
})
|
||||
}
|
||||
if (webSpeechAtFromPublishedAt(finding.publishedAt) === null) {
|
||||
context.addIssue({
|
||||
code: 'custom',
|
||||
path: ['publishedAt'],
|
||||
message: 'publishedAt deve ser YYYY-MM-DD ou data/hora ISO.',
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
export type WebSpeechFinding = z.infer<typeof webSpeechFindingSchema>
|
||||
|
||||
export type WebSpeechFindingParseResult =
|
||||
| { ok: true; finding: WebSpeechFinding }
|
||||
| { ok: false; error: string }
|
||||
|
||||
export const parseWebSpeechFinding = (value: unknown): WebSpeechFindingParseResult => {
|
||||
const parsed = webSpeechFindingSchema.safeParse(value)
|
||||
if (parsed.success) return { ok: true, finding: parsed.data }
|
||||
const issue = parsed.error.issues[0]
|
||||
const path = issue?.path.join('.') ?? ''
|
||||
return {
|
||||
ok: false,
|
||||
error: path ? `${path}: ${issue?.message}` : (issue?.message ?? 'achado inválido'),
|
||||
}
|
||||
}
|
||||
|
||||
type WebSpeechBatch = {
|
||||
generatedAt: string | null
|
||||
findings: unknown[]
|
||||
}
|
||||
|
||||
export type WebSpeechBatchParseResult =
|
||||
| { ok: true; batch: WebSpeechBatch }
|
||||
| { ok: false; error: string }
|
||||
|
||||
/**
|
||||
* Envelope only: the findings stay raw so one invalid entry becomes a failure
|
||||
* of that entry in the report instead of killing the whole batch.
|
||||
*/
|
||||
export const parseWebSpeechBatch = (value: unknown): WebSpeechBatchParseResult => {
|
||||
const envelope = z
|
||||
.object({
|
||||
generatedAt: z.string().trim().min(1).optional(),
|
||||
findings: z.array(z.unknown()),
|
||||
})
|
||||
.safeParse(value)
|
||||
if (!envelope.success) {
|
||||
return { ok: false, error: 'lote inválido: esperado { generatedAt?, findings: [...] }.' }
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
batch: {
|
||||
generatedAt: envelope.data.generatedAt ?? null,
|
||||
findings: envelope.data.findings,
|
||||
},
|
||||
}
|
||||
}
|
||||
18696
src/migrations/20260924_040210_add_recording_facets.json
Normal file
18696
src/migrations/20260924_040210_add_recording_facets.json
Normal file
File diff suppressed because it is too large
Load diff
76
src/migrations/20260924_040210_add_recording_facets.ts
Normal file
76
src/migrations/20260924_040210_add_recording_facets.ts
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
|
||||
|
||||
/**
|
||||
* C219 — facet + provenance columns of the uploaded recordings, mirroring the
|
||||
* speech catalog (C153): `year` derived from the informed recording date,
|
||||
* `topics`/`scopes` enums, `classifiedBy` (nullable: a row from before C219 was
|
||||
* never classified) and the `mentionedMunicipalities` join. Additive only.
|
||||
*
|
||||
* The `year` backfill is deterministic SQL (never an LLM pass in a migration):
|
||||
* it derives exactly what the `deriveRecordingYear` hook derives on the next
|
||||
* write, so old rows join the "Ano" facet before the classification CLI runs.
|
||||
*/
|
||||
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
CREATE TYPE "public"."enum_recording_topics" AS ENUM('saude', 'educacao', 'cultura', 'esporte', 'seguranca-publica', 'meio-ambiente', 'economia-trabalho', 'direitos-humanos', 'infraestrutura', 'ciencia-tecnologia', 'politica-instituicoes', 'agricultura', 'habitacao-cidades', 'comunicacao-midia', 'igualdade-racial', 'mulheres-genero', 'juventude', 'pessoa-deficiencia');
|
||||
CREATE TYPE "public"."enum_recording_scopes" AS ENUM('bahia', 'brasil', 'internacional');
|
||||
CREATE TYPE "public"."enum_recording_classified_by" AS ENUM('gazetteer', 'llm', 'manual');
|
||||
CREATE TABLE "recording_topics" (
|
||||
"order" integer NOT NULL,
|
||||
"parent_id" integer NOT NULL,
|
||||
"value" "enum_recording_topics",
|
||||
"id" serial PRIMARY KEY NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE "recording_scopes" (
|
||||
"order" integer NOT NULL,
|
||||
"parent_id" integer NOT NULL,
|
||||
"value" "enum_recording_scopes",
|
||||
"id" serial PRIMARY KEY NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE "recording_rels" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"order" integer,
|
||||
"parent_id" integer NOT NULL,
|
||||
"path" varchar NOT NULL,
|
||||
"municipality_id" integer
|
||||
);
|
||||
|
||||
ALTER TABLE "recording" ADD COLUMN "year" numeric;
|
||||
ALTER TABLE "recording" ADD COLUMN "classified_by" "enum_recording_classified_by";
|
||||
ALTER TABLE "recording_topics" ADD CONSTRAINT "recording_topics_parent_fk" FOREIGN KEY ("parent_id") REFERENCES "public"."recording"("id") ON DELETE cascade ON UPDATE no action;
|
||||
ALTER TABLE "recording_scopes" ADD CONSTRAINT "recording_scopes_parent_fk" FOREIGN KEY ("parent_id") REFERENCES "public"."recording"("id") ON DELETE cascade ON UPDATE no action;
|
||||
ALTER TABLE "recording_rels" ADD CONSTRAINT "recording_rels_parent_fk" FOREIGN KEY ("parent_id") REFERENCES "public"."recording"("id") ON DELETE cascade ON UPDATE no action;
|
||||
ALTER TABLE "recording_rels" ADD CONSTRAINT "recording_rels_municipality_fk" FOREIGN KEY ("municipality_id") REFERENCES "public"."municipality"("id") ON DELETE cascade ON UPDATE no action;
|
||||
CREATE INDEX "recording_topics_order_idx" ON "recording_topics" USING btree ("order");
|
||||
CREATE INDEX "recording_topics_parent_idx" ON "recording_topics" USING btree ("parent_id");
|
||||
CREATE INDEX "recording_topics_value_idx" ON "recording_topics" USING btree ("value");
|
||||
CREATE INDEX "recording_scopes_order_idx" ON "recording_scopes" USING btree ("order");
|
||||
CREATE INDEX "recording_scopes_parent_idx" ON "recording_scopes" USING btree ("parent_id");
|
||||
CREATE INDEX "recording_scopes_value_idx" ON "recording_scopes" USING btree ("value");
|
||||
CREATE INDEX "recording_rels_order_idx" ON "recording_rels" USING btree ("order");
|
||||
CREATE INDEX "recording_rels_parent_idx" ON "recording_rels" USING btree ("parent_id");
|
||||
CREATE INDEX "recording_rels_path_idx" ON "recording_rels" USING btree ("path");
|
||||
CREATE INDEX "recording_rels_municipality_id_idx" ON "recording_rels" USING btree ("municipality_id");
|
||||
CREATE INDEX "recording_year_idx" ON "recording" USING btree ("year");
|
||||
CREATE INDEX "recording_classified_by_idx" ON "recording" USING btree ("classified_by");
|
||||
UPDATE "recording" SET "year" = EXTRACT(YEAR FROM "recorded_at") WHERE "recorded_at" IS NOT NULL;`)
|
||||
}
|
||||
|
||||
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TABLE "recording_topics" DISABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE "recording_scopes" DISABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE "recording_rels" DISABLE ROW LEVEL SECURITY;
|
||||
DROP TABLE "recording_topics" CASCADE;
|
||||
DROP TABLE "recording_scopes" CASCADE;
|
||||
DROP TABLE "recording_rels" CASCADE;
|
||||
DROP INDEX "recording_year_idx";
|
||||
DROP INDEX "recording_classified_by_idx";
|
||||
ALTER TABLE "recording" DROP COLUMN "year";
|
||||
ALTER TABLE "recording" DROP COLUMN "classified_by";
|
||||
DROP TYPE "public"."enum_recording_topics";
|
||||
DROP TYPE "public"."enum_recording_scopes";
|
||||
DROP TYPE "public"."enum_recording_classified_by";`)
|
||||
}
|
||||
18613
src/migrations/20260924_042028_add_web_speech_origin.json
Normal file
18613
src/migrations/20260924_042028_add_web_speech_origin.json
Normal file
File diff suppressed because it is too large
Load diff
71
src/migrations/20260924_042028_add_web_speech_origin.ts
Normal file
71
src/migrations/20260924_042028_add_web_speech_origin.ts
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
|
||||
|
||||
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
CREATE TYPE "public"."enum_speech_origin" AS ENUM('camara', 'web');
|
||||
CREATE TYPE "public"."enum_speech_platform" AS ENUM('youtube', 'instagram', 'radio', 'audio');
|
||||
CREATE TABLE "internet_speech_media" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"alt" varchar NOT NULL,
|
||||
"updated_at" timestamp(3) with time zone DEFAULT now() NOT NULL,
|
||||
"created_at" timestamp(3) with time zone DEFAULT now() NOT NULL,
|
||||
"url" varchar,
|
||||
"thumbnail_u_r_l" varchar,
|
||||
"filename" varchar,
|
||||
"mime_type" varchar,
|
||||
"filesize" numeric,
|
||||
"width" numeric,
|
||||
"height" numeric,
|
||||
"focal_x" numeric,
|
||||
"focal_y" numeric
|
||||
);
|
||||
|
||||
ALTER TABLE "speech" ADD COLUMN "origin" "enum_speech_origin" DEFAULT 'camara' NOT NULL;
|
||||
ALTER TABLE "speech" ADD COLUMN "platform" "enum_speech_platform";
|
||||
ALTER TABLE "speech" ADD COLUMN "external_id" varchar;
|
||||
ALTER TABLE "speech" ADD COLUMN "source_url" varchar;
|
||||
ALTER TABLE "speech" ADD COLUMN "title" varchar;
|
||||
ALTER TABLE "speech" ADD COLUMN "channel" varchar;
|
||||
ALTER TABLE "speech" ADD COLUMN "mirrored_media_id" integer;
|
||||
ALTER TABLE "speech" ADD COLUMN "thumbnail_id" integer;
|
||||
ALTER TABLE "payload_locked_documents_rels" ADD COLUMN "internet_speech_media_id" integer;
|
||||
CREATE INDEX "internet_speech_media_updated_at_idx" ON "internet_speech_media" USING btree ("updated_at");
|
||||
CREATE INDEX "internet_speech_media_created_at_idx" ON "internet_speech_media" USING btree ("created_at");
|
||||
CREATE UNIQUE INDEX "internet_speech_media_filename_idx" ON "internet_speech_media" USING btree ("filename");
|
||||
ALTER TABLE "speech" ADD CONSTRAINT "speech_mirrored_media_id_internet_speech_media_id_fk" FOREIGN KEY ("mirrored_media_id") REFERENCES "public"."internet_speech_media"("id") ON DELETE set null ON UPDATE no action;
|
||||
ALTER TABLE "speech" ADD CONSTRAINT "speech_thumbnail_id_internet_speech_media_id_fk" FOREIGN KEY ("thumbnail_id") REFERENCES "public"."internet_speech_media"("id") ON DELETE set null ON UPDATE no action;
|
||||
ALTER TABLE "payload_locked_documents_rels" ADD CONSTRAINT "payload_locked_documents_rels_internet_speech_media_fk" FOREIGN KEY ("internet_speech_media_id") REFERENCES "public"."internet_speech_media"("id") ON DELETE cascade ON UPDATE no action;
|
||||
CREATE INDEX "speech_origin_idx" ON "speech" USING btree ("origin");
|
||||
CREATE INDEX "speech_platform_idx" ON "speech" USING btree ("platform");
|
||||
CREATE INDEX "speech_mirrored_media_idx" ON "speech" USING btree ("mirrored_media_id");
|
||||
CREATE INDEX "speech_thumbnail_idx" ON "speech" USING btree ("thumbnail_id");
|
||||
CREATE INDEX "payload_locked_documents_rels_internet_speech_media_id_idx" ON "payload_locked_documents_rels" USING btree ("internet_speech_media_id");`)
|
||||
}
|
||||
|
||||
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TABLE "internet_speech_media" DISABLE ROW LEVEL SECURITY;
|
||||
DROP TABLE "internet_speech_media" CASCADE;
|
||||
ALTER TABLE "speech" DROP CONSTRAINT "speech_mirrored_media_id_internet_speech_media_id_fk";
|
||||
|
||||
ALTER TABLE "speech" DROP CONSTRAINT "speech_thumbnail_id_internet_speech_media_id_fk";
|
||||
|
||||
ALTER TABLE "payload_locked_documents_rels" DROP CONSTRAINT "payload_locked_documents_rels_internet_speech_media_fk";
|
||||
|
||||
DROP INDEX "speech_origin_idx";
|
||||
DROP INDEX "speech_platform_idx";
|
||||
DROP INDEX "speech_mirrored_media_idx";
|
||||
DROP INDEX "speech_thumbnail_idx";
|
||||
DROP INDEX "payload_locked_documents_rels_internet_speech_media_id_idx";
|
||||
ALTER TABLE "speech" DROP COLUMN "origin";
|
||||
ALTER TABLE "speech" DROP COLUMN "platform";
|
||||
ALTER TABLE "speech" DROP COLUMN "external_id";
|
||||
ALTER TABLE "speech" DROP COLUMN "source_url";
|
||||
ALTER TABLE "speech" DROP COLUMN "title";
|
||||
ALTER TABLE "speech" DROP COLUMN "channel";
|
||||
ALTER TABLE "speech" DROP COLUMN "mirrored_media_id";
|
||||
ALTER TABLE "speech" DROP COLUMN "thumbnail_id";
|
||||
ALTER TABLE "payload_locked_documents_rels" DROP COLUMN "internet_speech_media_id";
|
||||
DROP TYPE "public"."enum_speech_origin";
|
||||
DROP TYPE "public"."enum_speech_platform";`)
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,13 @@
|
|||
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
|
||||
|
||||
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
CREATE TYPE "public"."enum_content_piece_link_failure_reason" AS ENUM('nao-encontrado', 'carrossel', 'indisponivel', 'sem-credencial');
|
||||
ALTER TABLE "content_piece" ADD COLUMN "link_failure_reason" "enum_content_piece_link_failure_reason";`)
|
||||
}
|
||||
|
||||
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TABLE "content_piece" DROP COLUMN "link_failure_reason";
|
||||
DROP TYPE "public"."enum_content_piece_link_failure_reason";`)
|
||||
}
|
||||
|
|
@ -82,6 +82,9 @@ import * as migration_20260923_032714_add_content_piece from './20260923_032714_
|
|||
import * as migration_20260923_054145_add_share_link_announcement from './20260923_054145_add_share_link_announcement';
|
||||
import * as migration_20260923_172437_add_content_events from './20260923_172437_add_content_events';
|
||||
import * as migration_20260923_190414_add_content_event_variant from './20260923_190414_add_content_event_variant';
|
||||
import * as migration_20260924_040210_add_recording_facets from './20260924_040210_add_recording_facets';
|
||||
import * as migration_20260924_042028_add_web_speech_origin from './20260924_042028_add_web_speech_origin';
|
||||
import * as migration_20260924_045625_add_content_piece_link_failure_reason from './20260924_045625_add_content_piece_link_failure_reason';
|
||||
|
||||
export const migrations = [
|
||||
{
|
||||
|
|
@ -502,6 +505,21 @@ export const migrations = [
|
|||
{
|
||||
up: migration_20260923_190414_add_content_event_variant.up,
|
||||
down: migration_20260923_190414_add_content_event_variant.down,
|
||||
name: '20260923_190414_add_content_event_variant'
|
||||
name: '20260923_190414_add_content_event_variant',
|
||||
},
|
||||
{
|
||||
up: migration_20260924_040210_add_recording_facets.up,
|
||||
down: migration_20260924_040210_add_recording_facets.down,
|
||||
name: '20260924_040210_add_recording_facets'
|
||||
},
|
||||
{
|
||||
up: migration_20260924_042028_add_web_speech_origin.up,
|
||||
down: migration_20260924_042028_add_web_speech_origin.down,
|
||||
name: '20260924_042028_add_web_speech_origin'
|
||||
},
|
||||
{
|
||||
up: migration_20260924_045625_add_content_piece_link_failure_reason.up,
|
||||
down: migration_20260924_045625_add_content_piece_link_failure_reason.down,
|
||||
name: '20260924_045625_add_content_piece_link_failure_reason'
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -89,6 +89,7 @@ export interface Config {
|
|||
speech: Speech;
|
||||
speechSegment: SpeechSegment;
|
||||
speechCut: SpeechCut;
|
||||
internetSpeechMedia: InternetSpeechMedia;
|
||||
reel: Reel;
|
||||
reelMedia: ReelMedia;
|
||||
contentPiece: ContentPiece;
|
||||
|
|
@ -143,6 +144,7 @@ export interface Config {
|
|||
speech: SpeechSelect<false> | SpeechSelect<true>;
|
||||
speechSegment: SpeechSegmentSelect<false> | SpeechSegmentSelect<true>;
|
||||
speechCut: SpeechCutSelect<false> | SpeechCutSelect<true>;
|
||||
internetSpeechMedia: InternetSpeechMediaSelect<false> | InternetSpeechMediaSelect<true>;
|
||||
reel: ReelSelect<false> | ReelSelect<true>;
|
||||
reelMedia: ReelMediaSelect<false> | ReelMediaSelect<true>;
|
||||
contentPiece: ContentPieceSelect<false> | ContentPieceSelect<true>;
|
||||
|
|
@ -938,7 +940,7 @@ export interface MunicipalityUpdate {
|
|||
createdAt: string;
|
||||
}
|
||||
/**
|
||||
* Acervo de falas do deputado na Câmara. Dados e vídeos da Câmara dos Deputados (CC BY 4.0).
|
||||
* Acervo de falas do deputado: discursos na Câmara (CC BY 4.0) e falas publicadas na internet (mídia espelhada privada).
|
||||
*
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "speech".
|
||||
|
|
@ -946,9 +948,13 @@ export interface MunicipalityUpdate {
|
|||
export interface Speech {
|
||||
id: number;
|
||||
/**
|
||||
* Identidade da fala na API da Câmara (data/hora + tipo + fase).
|
||||
* Identidade da fala: API da Câmara ou web:<plataforma>:<id|url>.
|
||||
*/
|
||||
sourceKey: string;
|
||||
/**
|
||||
* Discurso da Câmara ou fala publicada na internet.
|
||||
*/
|
||||
origin: 'camara' | 'web';
|
||||
/**
|
||||
* Horário local de Brasília, como publicado pela Câmara.
|
||||
*/
|
||||
|
|
@ -988,6 +994,34 @@ export interface Speech {
|
|||
* Último link conhecido; regerável pelo VOD.
|
||||
*/
|
||||
vodDownloadUrl?: string | null;
|
||||
/**
|
||||
* Plataforma de origem da fala da internet.
|
||||
*/
|
||||
platform?: ('youtube' | 'instagram' | 'radio' | 'audio') | null;
|
||||
/**
|
||||
* Identificador da publicação na plataforma (quando houver).
|
||||
*/
|
||||
externalId?: string | null;
|
||||
/**
|
||||
* Link canônico da publicação original.
|
||||
*/
|
||||
sourceUrl?: string | null;
|
||||
/**
|
||||
* Título da publicação na plataforma.
|
||||
*/
|
||||
title?: string | null;
|
||||
/**
|
||||
* Quem publicou (canal, rádio, perfil) — texto de origem, não é contato.
|
||||
*/
|
||||
channel?: string | null;
|
||||
/**
|
||||
* Arquivo privado preservado para player, download e cortes.
|
||||
*/
|
||||
mirroredMedia?: (number | null) | InternetSpeechMedia;
|
||||
/**
|
||||
* Capa da origem quando capturada; sem ela a lista mostra placeholder.
|
||||
*/
|
||||
thumbnail?: (number | null) | InternetSpeechMedia;
|
||||
topics?:
|
||||
| (
|
||||
| 'saude'
|
||||
|
|
@ -1022,6 +1056,30 @@ export interface Speech {
|
|||
updatedAt: string;
|
||||
createdAt: string;
|
||||
}
|
||||
/**
|
||||
* Arquivos privados das falas encontradas na internet (mídia espelhada e capa). Só abrem com login da campanha.
|
||||
*
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "internetSpeechMedia".
|
||||
*/
|
||||
export interface InternetSpeechMedia {
|
||||
id: number;
|
||||
/**
|
||||
* Descrição do arquivo para acessibilidade.
|
||||
*/
|
||||
alt: string;
|
||||
updatedAt: string;
|
||||
createdAt: string;
|
||||
url?: string | null;
|
||||
thumbnailURL?: string | null;
|
||||
filename?: string | null;
|
||||
mimeType?: string | null;
|
||||
filesize?: number | null;
|
||||
width?: number | null;
|
||||
height?: number | null;
|
||||
focalX?: number | null;
|
||||
focalY?: number | null;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "speechSegment".
|
||||
|
|
@ -1240,6 +1298,10 @@ export interface ContentPiece {
|
|||
* Motivo interno da falha; nunca vai à pessoa com o detalhe cru.
|
||||
*/
|
||||
error?: string | null;
|
||||
/**
|
||||
* Por que uma peça do Instagram ficou só como link; preenchido pelo processamento.
|
||||
*/
|
||||
linkFailureReason?: ('nao-encontrado' | 'carrossel' | 'indisponivel' | 'sem-credencial') | null;
|
||||
/**
|
||||
* Título, descrição, transcrição, temas, cidade e instituição normalizados (sem acentos, minúsculas).
|
||||
*/
|
||||
|
|
@ -1300,7 +1362,7 @@ export interface ContentEvent {
|
|||
createdAt: string;
|
||||
}
|
||||
/**
|
||||
* Gravações próprias da equipe no acervo. O arquivo é privado; a transcrição é somente leitura.
|
||||
* Gravações próprias da equipe no acervo. O arquivo é privado; a transcrição é somente leitura. Tema, alcance e municípios citados são classificados automaticamente pelo início da transcrição e podem ser corrigidos aqui (a correção vira proveniência "Manual").
|
||||
*
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "recording".
|
||||
|
|
@ -1312,6 +1374,10 @@ export interface Recording {
|
|||
* Data em que a gravação foi feita (opcional).
|
||||
*/
|
||||
recordedAt?: string | null;
|
||||
/**
|
||||
* Derivado da data da gravação.
|
||||
*/
|
||||
year?: number | null;
|
||||
status: 'uploading' | 'processing' | 'ready' | 'failed';
|
||||
/**
|
||||
* Progresso honesto da transcrição em andamento.
|
||||
|
|
@ -1329,6 +1395,34 @@ export interface Recording {
|
|||
* Concatenação normalizada dos segmentos (sem acentos, minúsculas).
|
||||
*/
|
||||
searchText?: string | null;
|
||||
topics?:
|
||||
| (
|
||||
| 'saude'
|
||||
| 'educacao'
|
||||
| 'cultura'
|
||||
| 'esporte'
|
||||
| 'seguranca-publica'
|
||||
| 'meio-ambiente'
|
||||
| 'economia-trabalho'
|
||||
| 'direitos-humanos'
|
||||
| 'infraestrutura'
|
||||
| 'ciencia-tecnologia'
|
||||
| 'politica-instituicoes'
|
||||
| 'agricultura'
|
||||
| 'habitacao-cidades'
|
||||
| 'comunicacao-midia'
|
||||
| 'igualdade-racial'
|
||||
| 'mulheres-genero'
|
||||
| 'juventude'
|
||||
| 'pessoa-deficiencia'
|
||||
)[]
|
||||
| null;
|
||||
scopes?: ('bahia' | 'brasil' | 'internacional')[] | null;
|
||||
/**
|
||||
* Automática e auditável: Gazetteer (léxico), LLM (refinamento validado) ou Manual (correção humana).
|
||||
*/
|
||||
classifiedBy?: ('gazetteer' | 'llm' | 'manual') | null;
|
||||
mentionedMunicipalities?: (number | Municipality)[] | null;
|
||||
/**
|
||||
* Rótulos humanos por agrupamento acústico (chave → nome). Identificação sempre humana; o acervo nunca sugere ou infere pessoas.
|
||||
*/
|
||||
|
|
@ -2052,6 +2146,10 @@ export interface PayloadLockedDocument {
|
|||
relationTo: 'speechCut';
|
||||
value: number | SpeechCut;
|
||||
} | null)
|
||||
| ({
|
||||
relationTo: 'internetSpeechMedia';
|
||||
value: number | InternetSpeechMedia;
|
||||
} | null)
|
||||
| ({
|
||||
relationTo: 'reel';
|
||||
value: number | Reel;
|
||||
|
|
@ -2608,6 +2706,7 @@ export interface ActivitySelect<T extends boolean = true> {
|
|||
*/
|
||||
export interface SpeechSelect<T extends boolean = true> {
|
||||
sourceKey?: T;
|
||||
origin?: T;
|
||||
speechAt?: T;
|
||||
year?: T;
|
||||
legislature?: T;
|
||||
|
|
@ -2629,6 +2728,13 @@ export interface SpeechSelect<T extends boolean = true> {
|
|||
excerptTMs?: T;
|
||||
vodPlaybackUrl?: T;
|
||||
vodDownloadUrl?: T;
|
||||
platform?: T;
|
||||
externalId?: T;
|
||||
sourceUrl?: T;
|
||||
title?: T;
|
||||
channel?: T;
|
||||
mirroredMedia?: T;
|
||||
thumbnail?: T;
|
||||
topics?: T;
|
||||
scopes?: T;
|
||||
classifiedBy?: T;
|
||||
|
|
@ -2673,6 +2779,24 @@ export interface SpeechCutSelect<T extends boolean = true> {
|
|||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "internetSpeechMedia_select".
|
||||
*/
|
||||
export interface InternetSpeechMediaSelect<T extends boolean = true> {
|
||||
alt?: T;
|
||||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
url?: T;
|
||||
thumbnailURL?: T;
|
||||
filename?: T;
|
||||
mimeType?: T;
|
||||
filesize?: T;
|
||||
width?: T;
|
||||
height?: T;
|
||||
focalX?: T;
|
||||
focalY?: T;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "reel_select".
|
||||
|
|
@ -2736,6 +2860,7 @@ export interface ContentPieceSelect<T extends boolean = true> {
|
|||
processingStatus?: T;
|
||||
step?: T;
|
||||
error?: T;
|
||||
linkFailureReason?: T;
|
||||
searchText?: T;
|
||||
curatedFields?: T;
|
||||
createdBy?: T;
|
||||
|
|
@ -2779,11 +2904,16 @@ export interface ContentEventSelect<T extends boolean = true> {
|
|||
export interface RecordingSelect<T extends boolean = true> {
|
||||
title?: T;
|
||||
recordedAt?: T;
|
||||
year?: T;
|
||||
status?: T;
|
||||
step?: T;
|
||||
media?: T;
|
||||
durationSeconds?: T;
|
||||
searchText?: T;
|
||||
topics?: T;
|
||||
scopes?: T;
|
||||
classifiedBy?: T;
|
||||
mentionedMunicipalities?: T;
|
||||
speakerLabels?:
|
||||
| T
|
||||
| {
|
||||
|
|
@ -3603,6 +3733,7 @@ export interface TaskCreateCollectionExport {
|
|||
| 'speech'
|
||||
| 'speechSegment'
|
||||
| 'speechCut'
|
||||
| 'internetSpeechMedia'
|
||||
| 'reel'
|
||||
| 'reelMedia'
|
||||
| 'contentPiece'
|
||||
|
|
|
|||
|
|
@ -26,6 +26,7 @@ import { ElectionCandidate } from './collections/ElectionCandidate'
|
|||
import { ElectionCandidateVote } from './collections/ElectionCandidateVote'
|
||||
import { ElectionTally } from './collections/ElectionTally'
|
||||
import { GoogleCalendarSync } from './collections/GoogleCalendarSync'
|
||||
import { InternetSpeechMedia } from './collections/InternetSpeechMedia'
|
||||
import { Jingle } from './collections/Jingle'
|
||||
import { Leadership } from './collections/Leadership'
|
||||
import { Media } from './collections/Media'
|
||||
|
|
@ -127,6 +128,7 @@ export default buildConfig({
|
|||
Speech,
|
||||
SpeechSegment,
|
||||
SpeechCut,
|
||||
InternetSpeechMedia,
|
||||
Reel,
|
||||
ReelMedia,
|
||||
ContentPiece,
|
||||
|
|
@ -189,6 +191,8 @@ export default buildConfig({
|
|||
recordingMedia: true,
|
||||
// C211 — private content-piece files; same failure mode if omitted.
|
||||
contentMedia: true,
|
||||
// C215 — private mirrored web-speech files; same failure mode if omitted.
|
||||
internetSpeechMedia: true,
|
||||
},
|
||||
bucket: mediaStorage.bucket,
|
||||
config: {
|
||||
|
|
|
|||
|
|
@ -25,6 +25,13 @@ export const DEEPINFRA_TRANSCRIBE_URL = 'https://api.deepinfra.com/v1/openai/aud
|
|||
const DEEPINFRA_WHISPER_MODEL = 'openai/whisper-large-v3'
|
||||
const DEEPINFRA_LANGUAGE = 'pt'
|
||||
|
||||
/**
|
||||
* C215 — provider price (~US$ per audio minute, Whisper large-v3 at Deep
|
||||
* Infra) used by the ingestion report to state the ASR cost honestly. The
|
||||
* Câmara CLI keeps its own copy; this is the app-side owner.
|
||||
*/
|
||||
export const DEEPINFRA_TRANSCRIBE_COST_PER_MINUTE_USD = 0.00045
|
||||
|
||||
export type TranscribeAudioResult =
|
||||
| { ok: true; text: string }
|
||||
| { ok: false; error: string; status: number }
|
||||
|
|
|
|||
|
|
@ -15,17 +15,23 @@ const EXPAND_TIMEOUT_MS = 4000
|
|||
const MAX_OUTPUT_TOKENS = 200
|
||||
const MAX_THEME_LENGTH = 200
|
||||
|
||||
const EXPAND_SUBJECT_BY_CORPUS: Record<ThemeSearchCorpus, string> = {
|
||||
speech: 'na transcrição de falas',
|
||||
contentPiece: 'na descrição ou na transcrição de uma peça',
|
||||
recording: 'na transcrição de uma gravação enviada pela equipe',
|
||||
}
|
||||
|
||||
const expandSchemaFor = (corpus: ThemeSearchCorpus) =>
|
||||
z.object({
|
||||
terms: z
|
||||
.array(z.string())
|
||||
.describe(
|
||||
`Termos e expressões curtas (${MIN_SPEECH_THEME_TERMS} a ${MAX_SPEECH_THEME_TERMS}) que podem aparecer ${corpus === 'speech' ? 'na transcrição de falas' : 'na descrição ou na transcrição de uma peça'} sobre o tema. Lista vazia quando não houver termo confiável.`,
|
||||
`Termos e expressões curtas (${MIN_SPEECH_THEME_TERMS} a ${MAX_SPEECH_THEME_TERMS}) que podem aparecer ${EXPAND_SUBJECT_BY_CORPUS[corpus]} sobre o tema. Lista vazia quando não houver termo confiável.`,
|
||||
),
|
||||
})
|
||||
|
||||
/** The term rules are one contract; only the noun of the corpus changes. */
|
||||
const themeExpansionRules = (subject: 'discurso' | 'peça'): string =>
|
||||
const themeExpansionRules = (subject: 'discurso' | 'peça' | 'gravação'): string =>
|
||||
`Devolva de ${MIN_SPEECH_THEME_TERMS} a ${MAX_SPEECH_THEME_TERMS} termos, cada um com no máximo ${MAX_SPEECH_THEME_TERM_LENGTH} caracteres, sem explicações, ` +
|
||||
`sem pontuação extra e sem termos genéricos que apareceriam em qualquer ${subject} (ex.: "Brasil", ` +
|
||||
'"povo", "governo"). Se não houver termo confiável, devolva a lista vazia. Nunca invente fatos.'
|
||||
|
|
@ -48,14 +54,34 @@ const CONTENT_PIECE_CORPUS_PROMPT =
|
|||
themeExpansionRules('peça')
|
||||
|
||||
/**
|
||||
* S28 — the corpus a theme expansion serves: the internal speech acervo (C192)
|
||||
* and the public Central de Conteúdos (S28). The mechanism is one; only the
|
||||
* system prompt describes a different body of material and persona.
|
||||
* C219 — the third corpus: the uploaded recordings of the acervo ("Gravações
|
||||
* enviadas"), whose material is the team's own plenárias/debates rather than
|
||||
* the Câmara's speeches, so the prompt describes that body of material.
|
||||
*/
|
||||
export type ThemeSearchCorpus = 'speech' | 'contentPiece'
|
||||
const RECORDING_CORPUS_PROMPT =
|
||||
'Você ajuda a assessoria de comunicação a achar, no acervo de gravações enviadas pela equipe ' +
|
||||
'(plenárias, debates e materiais próprios do deputado Jorge Solla), trechos sobre um tema mesmo ' +
|
||||
'quando a gravação não usa as palavras exatas da busca. ' +
|
||||
'Receberá o tema digitado e deve devolver termos e expressões curtas que provavelmente aparecem ' +
|
||||
'na transcrição de uma gravação sobre esse tema — sinônimos, nomes de programas, termos técnicos ' +
|
||||
'e palavras relacionadas. Inclua a própria expressão do tema quando ela for útil. ' +
|
||||
themeExpansionRules('gravação')
|
||||
|
||||
const systemPromptFor = (corpus: ThemeSearchCorpus): string =>
|
||||
corpus === 'contentPiece' ? CONTENT_PIECE_CORPUS_PROMPT : SPEECH_CORPUS_PROMPT
|
||||
/**
|
||||
* S28/C219 — the corpus a theme expansion serves: the internal speech acervo
|
||||
* (C192), the public Central de Conteúdos (S28) and the uploaded recordings
|
||||
* (C219). The mechanism is one; only the system prompt describes a different
|
||||
* body of material and persona.
|
||||
*/
|
||||
export type ThemeSearchCorpus = 'speech' | 'contentPiece' | 'recording'
|
||||
|
||||
const SYSTEM_PROMPT_BY_CORPUS: Record<ThemeSearchCorpus, string> = {
|
||||
speech: SPEECH_CORPUS_PROMPT,
|
||||
contentPiece: CONTENT_PIECE_CORPUS_PROMPT,
|
||||
recording: RECORDING_CORPUS_PROMPT,
|
||||
}
|
||||
|
||||
const systemPromptFor = (corpus: ThemeSearchCorpus): string => SYSTEM_PROMPT_BY_CORPUS[corpus]
|
||||
|
||||
export type ThemeSearchExpansion = { terms: string[] }
|
||||
|
||||
|
|
@ -110,3 +136,7 @@ export const expandSpeechSearchTheme: SpeechThemeExpansionResolver = (theme) =>
|
|||
/** S28 — the public Central de Conteúdos expansion. */
|
||||
export const expandContentPieceSearchTheme: ThemeSearchExpansionResolver = (theme) =>
|
||||
expandSearchTheme(theme, 'contentPiece')
|
||||
|
||||
/** C219 — the uploaded recordings expansion ("Gravações enviadas"). */
|
||||
export const expandRecordingSearchTheme: ThemeSearchExpansionResolver = (theme) =>
|
||||
expandSearchTheme(theme, 'recording')
|
||||
|
|
|
|||
|
|
@ -95,7 +95,14 @@ export const findSpeechExcerpts = (ctx: AIToolContext) =>
|
|||
|
||||
const speeches = await ctx.payload.find({
|
||||
collection: 'speech',
|
||||
where: { and: terms.map((term) => ({ searchText: { like: term } })) },
|
||||
// C215 — the assistant keeps suggesting Câmara excerpts; the web
|
||||
// speeches (C216) are a different source with their own screen.
|
||||
where: {
|
||||
and: [
|
||||
{ origin: { equals: 'camara' } },
|
||||
...terms.map((term) => ({ searchText: { like: term } })),
|
||||
],
|
||||
},
|
||||
depth: 0,
|
||||
limit: SPEECH_CANDIDATE_LIMIT,
|
||||
page: 1,
|
||||
|
|
|
|||
|
|
@ -82,6 +82,21 @@ export const strictDecimalInteger = (value: string | undefined): number | undefi
|
|||
return Number.isSafeInteger(number) ? number : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Structural validation of the data-driven year facet (both acervo sources):
|
||||
* a plausible calendar year, not a closed enum.
|
||||
*/
|
||||
export const parseYearValues = (raw: string | string[] | undefined): number[] =>
|
||||
allParamValues(raw)
|
||||
.map((token) => strictDecimalInteger(token))
|
||||
.filter((year): year is number => year !== undefined && year >= 1900 && year <= 2100)
|
||||
|
||||
/** Structural validation of a municipality-id facet (positive safe integer). */
|
||||
export const parseMunicipalityValues = (raw: string | string[] | undefined): number[] =>
|
||||
allParamValues(raw)
|
||||
.map((token) => strictDecimalInteger(token))
|
||||
.filter((id): id is number => id !== undefined && id > 0)
|
||||
|
||||
export const inspectRawListParams = (
|
||||
params: RawSearchParams,
|
||||
paramNameSet: ReadonlySet<string>,
|
||||
|
|
|
|||
|
|
@ -278,6 +278,7 @@ export const runContentPieceJob = async (
|
|||
processingStatus: 'pronto',
|
||||
step: null,
|
||||
error: null,
|
||||
linkFailureReason: source.linkFailureReason,
|
||||
...(durationSeconds !== null ? { durationSeconds } : {}),
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -9,26 +9,29 @@ import {
|
|||
CONTENT_MEDIA_SLUG,
|
||||
CONTENT_PIECE_MAX_BYTES,
|
||||
parseContentPieceLink,
|
||||
type ContentPieceLinkFailureReason,
|
||||
type ContentPieceType,
|
||||
} from '@/lib/contentPiece'
|
||||
import { withPayloadTransaction } from '@/utilities/payloadTransaction'
|
||||
import {
|
||||
INSTAGRAM_MAX_RESULTS_CAP,
|
||||
isInstagramFeedConfigured,
|
||||
loadInstagramFeed,
|
||||
persistInstagramAccessToken,
|
||||
} from '@/utilities/socialFeed/instagramFeed'
|
||||
|
||||
/**
|
||||
* C211 — the official-path resolution of a piece that entered by link. There is
|
||||
* NO scraping and no oEmbed: the only extraction route is the Instagram Graph
|
||||
* API of the campaign's OWN account (listing the profile media and matching the
|
||||
* pasted permalink), exactly what the gate decided. YouTube exposes only
|
||||
* metadata through the Data API, so a YouTube piece always circulates by link.
|
||||
* C211/C220 — the official-path resolution of a piece that entered by link.
|
||||
* There is NO scraping and no oEmbed: the only extraction route is the
|
||||
* Instagram Graph API of the campaign's OWN account (listing the profile media
|
||||
* and matching the pasted shortcode), exactly what the gate decided. YouTube
|
||||
* exposes only metadata through the Data API, so a YouTube piece always
|
||||
* circulates by link and carries NO failure reason.
|
||||
*
|
||||
* A failed extraction never throws at the caller: the piece becomes a
|
||||
* peça-link (the job still catalogues the official caption when there is one).
|
||||
* A download that starts and fails DOES throw — the row is preserved and the
|
||||
* assessoria can reprocess or attach the original file.
|
||||
* Every Instagram-side failure returns a `linkFailureReason` instead of
|
||||
* throwing: the piece becomes a peça-link (`pronto`) with an honest reason on
|
||||
* the ficha — never silence, never "Falhou". Only failures the pipeline itself
|
||||
* can retry or the assessoria can solve by attaching the file (the 4 GB
|
||||
* ceiling, storage, ffmpeg) still throw.
|
||||
*/
|
||||
|
||||
export type ContentPieceSourceMedia = {
|
||||
|
|
@ -47,10 +50,39 @@ export type ContentPieceSourceResolution = {
|
|||
caption: string | null
|
||||
/** The type the official media reveals (an Instagram image is a photo). */
|
||||
suggestedType?: ContentPieceType
|
||||
/** C220 — why the piece stayed a peça-link; null when there is nothing to explain. */
|
||||
linkFailureReason: ContentPieceLinkFailureReason | null
|
||||
}
|
||||
|
||||
type FeedLoader = typeof loadInstagramFeed
|
||||
|
||||
/**
|
||||
* C220 — how far back the pasted post is searched in the official profile:
|
||||
* 10 pages of 50, with an early stop on the match. The typical paste is the
|
||||
* post that just went out (one page); the declared window covers ~1–2 years
|
||||
* and stays well under the API edge's 10K budget (C212 §Q1). A post beyond it
|
||||
* gets the honest `nao-encontrado` reason.
|
||||
*/
|
||||
export const CONTENT_PIECE_LINK_INSTAGRAM_WINDOW = 500
|
||||
|
||||
/** A hung Graph API must not hold the piece `processando` until the 1 h reaper. */
|
||||
const CONTENT_PIECE_LINK_FEED_TIMEOUT_MS = 30_000
|
||||
|
||||
/** Same deadline for the media CDN (the speech pipeline precedent is 180 s). */
|
||||
const CONTENT_PIECE_LINK_DOWNLOAD_TIMEOUT_MS = 3 * 60_000
|
||||
|
||||
/**
|
||||
* Our own ceiling, not the platform's: it must stay distinguishable from a
|
||||
* transport failure so the resolver rethrows it (`falhou`) instead of dressing
|
||||
* a policy refusal as "Instagram indisponível".
|
||||
*/
|
||||
export class ContentPieceMediaTooLargeError extends Error {
|
||||
constructor() {
|
||||
super('A mídia extraída excede o limite da Central.')
|
||||
this.name = 'ContentPieceMediaTooLargeError'
|
||||
}
|
||||
}
|
||||
|
||||
const streamResponseToFile = async ({
|
||||
response,
|
||||
destination,
|
||||
|
|
@ -66,7 +98,7 @@ const streamResponseToFile = async ({
|
|||
transform(chunk: Buffer, _encoding, callback) {
|
||||
received += chunk.length
|
||||
if (received > maxBytes) {
|
||||
callback(new Error('A mídia extraída excede o limite da Central.'))
|
||||
callback(new ContentPieceMediaTooLargeError())
|
||||
return
|
||||
}
|
||||
callback(null, chunk)
|
||||
|
|
@ -82,7 +114,8 @@ const streamResponseToFile = async ({
|
|||
/**
|
||||
* Resolves the source of one piece: the archived media when it exists,
|
||||
* otherwise the official extraction for an Instagram link, otherwise nothing
|
||||
* (peça-link). Injectable deps keep the int test free of network calls.
|
||||
* (peça-link). Injectable deps keep the int test free of network calls. Every
|
||||
* Instagram-side miss carries a `linkFailureReason` for the ficha.
|
||||
*/
|
||||
export const resolveContentPieceSource = async ({
|
||||
payload,
|
||||
|
|
@ -103,26 +136,38 @@ export const resolveContentPieceSource = async ({
|
|||
loadFeed?: FeedLoader
|
||||
fetchImpl?: (input: string, init?: RequestInit) => Promise<Response>
|
||||
}): Promise<ContentPieceSourceResolution> => {
|
||||
/** A peça-link answer: no media, optional official caption, honest reason. */
|
||||
const linkOnly = (
|
||||
linkFailureReason: ContentPieceLinkFailureReason,
|
||||
caption: string | null = null,
|
||||
): ContentPieceSourceResolution => ({
|
||||
media: null,
|
||||
localPath: null,
|
||||
caption,
|
||||
linkFailureReason,
|
||||
})
|
||||
|
||||
if (piece.media && typeof piece.media === 'object') {
|
||||
return { media: piece.media, localPath: null, caption: null }
|
||||
return { media: piece.media, localPath: null, caption: null, linkFailureReason: null }
|
||||
}
|
||||
if (piece.media) {
|
||||
// A bare id (depth 0) is not a file the pipeline can read; fail closed to
|
||||
// the link resolution instead of handing a number to the downloader.
|
||||
return { media: null, localPath: null, caption: null }
|
||||
return { media: null, localPath: null, caption: null, linkFailureReason: null }
|
||||
}
|
||||
if (piece.origin !== 'instagram' || !piece.sourceUrl) {
|
||||
return { media: null, localPath: null, caption: null }
|
||||
// YouTube (link-only by design) and uploaded files have nothing to explain.
|
||||
return { media: null, localPath: null, caption: null, linkFailureReason: null }
|
||||
}
|
||||
|
||||
const link = parseContentPieceLink(piece.sourceUrl)
|
||||
if (!link || link.origin !== 'instagram') {
|
||||
return { media: null, localPath: null, caption: null }
|
||||
return { media: null, localPath: null, caption: null, linkFailureReason: null }
|
||||
}
|
||||
|
||||
const settings = await payload.findGlobal({ slug: 'social-feed-settings', depth: 0 })
|
||||
if (!isInstagramFeedConfigured(settings)) {
|
||||
return { media: null, localPath: null, caption: null }
|
||||
return linkOnly('sem-credencial')
|
||||
}
|
||||
|
||||
let feed: Awaited<ReturnType<FeedLoader>>
|
||||
|
|
@ -130,41 +175,71 @@ export const resolveContentPieceSource = async ({
|
|||
feed = await loadFeed({
|
||||
accessToken: settings.instagramAccessToken as string,
|
||||
userId: settings.instagramUserId as string,
|
||||
maxResults: INSTAGRAM_MAX_RESULTS_CAP,
|
||||
maxResults: CONTENT_PIECE_LINK_INSTAGRAM_WINDOW,
|
||||
fetchImpl,
|
||||
signal: AbortSignal.timeout(CONTENT_PIECE_LINK_FEED_TIMEOUT_MS),
|
||||
})
|
||||
} catch {
|
||||
// Token expired, API down: fail closed to the link piece, never to an error
|
||||
// in the assessoria's face.
|
||||
return { media: null, localPath: null, caption: null }
|
||||
// Token expired, API down: the piece becomes a peça-link with the honest
|
||||
// reason, never an error in the assessoria's face.
|
||||
return linkOnly('indisponivel')
|
||||
}
|
||||
|
||||
// Canonical URLs on both sides: the shortcode is the identity and the form is
|
||||
// the same, so two spellings of the same post always match.
|
||||
const matched = feed.posts.find(
|
||||
(post) => parseContentPieceLink(post.permalink)?.canonicalUrl === link.canonicalUrl,
|
||||
)
|
||||
if (!matched) return { media: null, localPath: null, caption: null }
|
||||
if (feed.refreshedAccessToken) {
|
||||
// Best-effort: storing the refreshed token never fails the extraction, and
|
||||
// the token itself is never logged.
|
||||
await persistInstagramAccessToken(payload, feed.refreshedAccessToken).catch(() => undefined)
|
||||
}
|
||||
|
||||
// The shortcode is the identity; the kind (`p` × `reel`) is presentation, so
|
||||
// a `/p/ABC/` paste matches a reel's permalink too. Matching inside the OWN
|
||||
// profile feed is also what guarantees a third-party link never downloads.
|
||||
const matched = feed.posts.find((post) => {
|
||||
const parsed = parseContentPieceLink(post.permalink)
|
||||
return parsed?.origin === 'instagram' && parsed.shortcode === link.shortcode
|
||||
})
|
||||
if (!matched) {
|
||||
return linkOnly('nao-encontrado')
|
||||
}
|
||||
|
||||
if (matched.mediaType === 'CAROUSEL_ALBUM') {
|
||||
return linkOnly('carrossel', matched.caption)
|
||||
}
|
||||
|
||||
const extractable =
|
||||
matched.mediaType === 'IMAGE' || matched.mediaType === 'VIDEO' || matched.mediaType === 'REEL'
|
||||
if (!extractable || !matched.mediaUrl) {
|
||||
// Carousel (no single file) or a post without a media URL: the caption is
|
||||
// still official metadata the cataloguing can use.
|
||||
return { media: null, localPath: null, caption: matched.caption }
|
||||
// The API found the post but has no single file to hand over.
|
||||
return linkOnly('indisponivel', matched.caption)
|
||||
}
|
||||
|
||||
const response = await fetchImpl(matched.mediaUrl)
|
||||
if (!response.ok) throw new Error('Não foi possível baixar a mídia do Instagram.')
|
||||
let response: Response
|
||||
try {
|
||||
response = await fetchImpl(matched.mediaUrl, {
|
||||
signal: AbortSignal.timeout(CONTENT_PIECE_LINK_DOWNLOAD_TIMEOUT_MS),
|
||||
})
|
||||
} catch {
|
||||
return linkOnly('indisponivel', matched.caption)
|
||||
}
|
||||
if (!response.ok) {
|
||||
return linkOnly('indisponivel', matched.caption)
|
||||
}
|
||||
|
||||
const suggestedType: ContentPieceType = matched.mediaType === 'IMAGE' ? 'foto' : 'video'
|
||||
const extension = suggestedType === 'foto' ? 'jpg' : 'mp4'
|
||||
const localPath = `${tempDir}/instagram-${link.shortcode}.${extension}`
|
||||
await streamResponseToFile({
|
||||
response,
|
||||
destination: localPath,
|
||||
maxBytes: CONTENT_PIECE_MAX_BYTES,
|
||||
})
|
||||
try {
|
||||
await streamResponseToFile({
|
||||
response,
|
||||
destination: localPath,
|
||||
maxBytes: CONTENT_PIECE_MAX_BYTES,
|
||||
})
|
||||
} catch (error) {
|
||||
// Our ceiling is not the platform's: it stays a failure the assessoria
|
||||
// solves by attaching the file. Any other stream error is transport.
|
||||
if (error instanceof ContentPieceMediaTooLargeError) throw error
|
||||
return linkOnly('indisponivel', matched.caption)
|
||||
}
|
||||
|
||||
const media = await withPayloadTransaction(payload, async ({ req }) => {
|
||||
const created = await payload.create({
|
||||
|
|
@ -189,5 +264,5 @@ export const resolveContentPieceSource = async ({
|
|||
return created
|
||||
})
|
||||
|
||||
return { media, localPath, caption: matched.caption, suggestedType }
|
||||
return { media, localPath, caption: matched.caption, suggestedType, linkFailureReason: null }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -53,6 +53,7 @@ const contentPieceDetailSelect = {
|
|||
sourceUrl: true,
|
||||
municipality: true,
|
||||
curatedFields: true,
|
||||
linkFailureReason: true,
|
||||
} as const
|
||||
|
||||
export const ContentPieceNotFoundError = createEntityNotFoundError(
|
||||
|
|
|
|||
|
|
@ -278,6 +278,7 @@ export const attachContentPieceMedia = async ({
|
|||
processingStatus: processing ? 'processando' : 'pronto',
|
||||
...(processing ? { step: 'extraindo' } : {}),
|
||||
error: null,
|
||||
linkFailureReason: null,
|
||||
},
|
||||
depth: 0,
|
||||
user: actor,
|
||||
|
|
|
|||
63
src/utilities/media/downloadToFile.ts
Normal file
63
src/utilities/media/downloadToFile.ts
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
import 'server-only'
|
||||
|
||||
import { createWriteStream } from 'node:fs'
|
||||
import { Readable, Transform } from 'node:stream'
|
||||
import { pipeline } from 'node:stream/promises'
|
||||
import type { ReadableStream as NodeReadableStream } from 'node:stream/web'
|
||||
|
||||
/**
|
||||
* C215 — streams one public URL to a local file: the direct acquisition path
|
||||
* of radio/audio findings (yt-dlp owns the platform extractors). A non-2xx
|
||||
* answer fails before anything is written, the body is never buffered in
|
||||
* memory and both a timeout and a byte ceiling bound a stalled or oversized
|
||||
* server (a partial file is removed by the caller's temp dir).
|
||||
*/
|
||||
|
||||
/** Ceiling: hours of audio/video are the real case, 4 GiB is the guard. */
|
||||
const DOWNLOAD_MAX_BYTES = 4 * 1024 * 1024 * 1024
|
||||
const DOWNLOAD_TIMEOUT_MS = 60 * 60_000
|
||||
const TOO_LARGE_MESSAGE = 'Download excede o tamanho máximo permitido.'
|
||||
|
||||
export const downloadUrlToFile = async ({
|
||||
url,
|
||||
destinationPath,
|
||||
timeoutMs = DOWNLOAD_TIMEOUT_MS,
|
||||
maxBytes = DOWNLOAD_MAX_BYTES,
|
||||
fetchImpl = fetch,
|
||||
}: {
|
||||
url: string
|
||||
destinationPath: string
|
||||
timeoutMs?: number
|
||||
maxBytes?: number
|
||||
fetchImpl?: typeof fetch
|
||||
}): Promise<void> => {
|
||||
const response = await fetchImpl(url, {
|
||||
redirect: 'follow',
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
})
|
||||
if (!response.ok) throw new Error(`Download falhou (HTTP ${response.status}).`)
|
||||
if (!response.body) throw new Error('Download sem corpo.')
|
||||
|
||||
const declaredLength = Number(response.headers.get('content-length'))
|
||||
if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {
|
||||
throw new Error(TOO_LARGE_MESSAGE)
|
||||
}
|
||||
|
||||
let received = 0
|
||||
const ceiling = new Transform({
|
||||
transform(chunk, _encoding, callback) {
|
||||
received += chunk.length
|
||||
if (received > maxBytes) {
|
||||
callback(new Error(TOO_LARGE_MESSAGE))
|
||||
return
|
||||
}
|
||||
callback(null, chunk)
|
||||
},
|
||||
})
|
||||
|
||||
await pipeline(
|
||||
Readable.fromWeb(response.body as unknown as NodeReadableStream<Uint8Array>),
|
||||
ceiling,
|
||||
createWriteStream(destinationPath),
|
||||
)
|
||||
}
|
||||
|
|
@ -16,7 +16,12 @@ const FFMPEG_MIN_TIMEOUT_MS = 30_000
|
|||
const FFMPEG_MAX_TIMEOUT_MS = 300_000
|
||||
const FFMPEG_MAX_BUFFER_BYTES = 8 * 1024 * 1024
|
||||
|
||||
const ffmpegBinary = (): string => process.env.FFMPEG_PATH?.trim() || 'ffmpeg'
|
||||
/**
|
||||
* The resolved binary (`FFMPEG_PATH` override or `ffmpeg` on PATH). Exported
|
||||
* so callers that must tell another tool where ffmpeg lives (yt-dlp's
|
||||
* `--ffmpeg-location`, C215) read the same resolution instead of the env.
|
||||
*/
|
||||
export const ffmpegBinary = (): string => process.env.FFMPEG_PATH?.trim() || 'ffmpeg'
|
||||
|
||||
/** Last-resort copy when an error carries no message; each job names its own. */
|
||||
export const messageOf = (error: unknown, fallback: string): string =>
|
||||
|
|
|
|||
170
src/utilities/media/ytdlp.ts
Normal file
170
src/utilities/media/ytdlp.ts
Normal file
|
|
@ -0,0 +1,170 @@
|
|||
import 'server-only'
|
||||
|
||||
import { execFile } from 'node:child_process'
|
||||
|
||||
/**
|
||||
* C215 — the single owner of yt-dlp execution for the web-speech ingestion:
|
||||
* binary resolution (`YTDLP_PATH` → `yt-dlp` on PATH, fail-closed), the
|
||||
* metadata probe (`--dump-json`) and the download of one URL to a local file.
|
||||
* YouTube and Instagram only; direct radio/audio files are fetched by
|
||||
* `downloadToFile`.
|
||||
*
|
||||
* There is no packaged yt-dlp: the operator installs it and the tests inject a
|
||||
* fake through `YTDLP_PATH`. The format cap keeps the mirrored artifact enough
|
||||
* for transcription, player and cut — never the master.
|
||||
*/
|
||||
|
||||
export const YTDLP_INSTALL_HINT =
|
||||
'Instale o yt-dlp (ex.: `pipx install yt-dlp`) ou defina YTDLP_PATH.'
|
||||
|
||||
/** H.264/AAC up to 720p when available, then the best single file. */
|
||||
export const YTDLP_FORMAT = 'bv*[height<=720][vcodec^=avc1]+ba[acodec^=mp4a]/b[height<=720]/b'
|
||||
|
||||
const VERSION_TIMEOUT_MS = 30_000
|
||||
const METADATA_TIMEOUT_MS = 120_000
|
||||
const DOWNLOAD_TIMEOUT_MS = 60 * 60_000
|
||||
const MAX_BUFFER_BYTES = 16 * 1024 * 1024
|
||||
|
||||
export type YtDlpResult =
|
||||
| { ok: true; stdout: string; stderr: string }
|
||||
| {
|
||||
ok: false
|
||||
stdout: string
|
||||
stderr: string
|
||||
error?: { code?: string | number | null; message?: string }
|
||||
}
|
||||
|
||||
export type YtDlpRunner = (
|
||||
bin: string,
|
||||
args: string[],
|
||||
options?: { timeoutMs?: number },
|
||||
) => Promise<YtDlpResult>
|
||||
|
||||
const defaultRunner: YtDlpRunner = (bin, args, { timeoutMs } = {}) =>
|
||||
new Promise((resolve) => {
|
||||
execFile(
|
||||
bin,
|
||||
args,
|
||||
{ timeout: timeoutMs, maxBuffer: MAX_BUFFER_BYTES },
|
||||
(error, stdout, stderr) => {
|
||||
if (!error) {
|
||||
resolve({ ok: true, stdout: stdout ?? '', stderr: stderr ?? '' })
|
||||
return
|
||||
}
|
||||
resolve({ ok: false, stdout: stdout ?? '', stderr: stderr ?? '', error })
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
const ytDlpBinary = (env: Record<string, string | undefined> = process.env): string =>
|
||||
env.YTDLP_PATH?.trim() || 'yt-dlp'
|
||||
|
||||
export type YtDlpResolution = { ok: true; bin: string } | { ok: false; reason: string }
|
||||
|
||||
/** Probe of the resolved binary; a missing/unusable yt-dlp never degrades silently. */
|
||||
export const resolveYtDlp = async ({
|
||||
env = process.env,
|
||||
run = defaultRunner,
|
||||
}: {
|
||||
env?: Record<string, string | undefined>
|
||||
run?: YtDlpRunner
|
||||
} = {}): Promise<YtDlpResolution> => {
|
||||
const bin = ytDlpBinary(env)
|
||||
const probe = await run(bin, ['--version'], { timeoutMs: VERSION_TIMEOUT_MS })
|
||||
if (!probe.ok) {
|
||||
const code = probe.error?.code
|
||||
return {
|
||||
ok: false,
|
||||
reason: code === 'ENOENT' ? `yt-dlp não encontrado (${bin})` : `yt-dlp não executou (${bin})`,
|
||||
}
|
||||
}
|
||||
return { ok: true, bin }
|
||||
}
|
||||
|
||||
export type YtDlpMetadata = {
|
||||
externalId: string | null
|
||||
title: string | null
|
||||
channel: string | null
|
||||
durationSeconds: number | null
|
||||
thumbnailUrl: string | null
|
||||
}
|
||||
|
||||
const stringOrNull = (value: unknown): string | null =>
|
||||
typeof value === 'string' && value.trim() !== '' ? value.trim() : null
|
||||
|
||||
const positiveNumberOrNull = (value: unknown): number | null => {
|
||||
const number = Number(value)
|
||||
return Number.isFinite(number) && number > 0 ? number : null
|
||||
}
|
||||
|
||||
/** One `--dump-json` document; absent fields stay null instead of guessing. */
|
||||
export const parseYtDlpMetadata = (value: unknown): YtDlpMetadata => {
|
||||
const data = value && typeof value === 'object' ? (value as Record<string, unknown>) : {}
|
||||
return {
|
||||
externalId: stringOrNull(data.id),
|
||||
title: stringOrNull(data.title),
|
||||
channel: stringOrNull(data.channel) ?? stringOrNull(data.uploader),
|
||||
durationSeconds: positiveNumberOrNull(data.duration),
|
||||
thumbnailUrl: stringOrNull(data.thumbnail),
|
||||
}
|
||||
}
|
||||
|
||||
const stderrTail = (result: Extract<YtDlpResult, { ok: false }>): string => {
|
||||
const tail = (result.stderr || result.error?.message || '').trim().slice(-400)
|
||||
return tail ? `: ${tail}` : ''
|
||||
}
|
||||
|
||||
export const readYtDlpMetadata = async ({
|
||||
bin,
|
||||
url,
|
||||
run = defaultRunner,
|
||||
}: {
|
||||
bin: string
|
||||
url: string
|
||||
run?: YtDlpRunner
|
||||
}): Promise<YtDlpMetadata> => {
|
||||
const result = await run(
|
||||
bin,
|
||||
['--dump-json', '--no-playlist', '--no-warnings', '--skip-download', url],
|
||||
{ timeoutMs: METADATA_TIMEOUT_MS },
|
||||
)
|
||||
if (!result.ok) throw new Error(`yt-dlp não leu os metadados${stderrTail(result)}`)
|
||||
try {
|
||||
return parseYtDlpMetadata(JSON.parse(result.stdout))
|
||||
} catch {
|
||||
throw new Error('yt-dlp devolveu metadados fora do formato.')
|
||||
}
|
||||
}
|
||||
|
||||
export const downloadWithYtDlp = async ({
|
||||
bin,
|
||||
url,
|
||||
outputTemplate,
|
||||
ffmpegLocation = null,
|
||||
run = defaultRunner,
|
||||
}: {
|
||||
bin: string
|
||||
url: string
|
||||
outputTemplate: string
|
||||
ffmpegLocation?: string | null
|
||||
run?: YtDlpRunner
|
||||
}): Promise<void> => {
|
||||
const result = await run(
|
||||
bin,
|
||||
[
|
||||
'--no-playlist',
|
||||
'--no-warnings',
|
||||
'--no-progress',
|
||||
'-f',
|
||||
YTDLP_FORMAT,
|
||||
'--merge-output-format',
|
||||
'mp4',
|
||||
...(ffmpegLocation ? ['--ffmpeg-location', ffmpegLocation] : []),
|
||||
'-o',
|
||||
outputTemplate,
|
||||
url,
|
||||
],
|
||||
{ timeoutMs: DOWNLOAD_TIMEOUT_MS },
|
||||
)
|
||||
if (!result.ok) throw new Error(`yt-dlp falhou no download${stderrTail(result)}`)
|
||||
}
|
||||
97
src/utilities/recordings/recordingClassification.ts
Normal file
97
src/utilities/recordings/recordingClassification.ts
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
import 'server-only'
|
||||
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import type { MergedSpeechFacets, SpeechScope, SpeechTopic } from '@/lib/speechFacets'
|
||||
import type { SpeechFacetInput } from '@/lib/speechGazetteer'
|
||||
import type { Recording } from '@/payload-types'
|
||||
import {
|
||||
classifySpeech,
|
||||
type SpeechClassificationResult,
|
||||
} from '@/utilities/speech/speechClassifier'
|
||||
|
||||
/**
|
||||
* C219 — facet classification of one uploaded recording. Reuses the speech
|
||||
* classifier owner (`classifySpeech`: gazetteer + validated LLM refinement)
|
||||
* over the transcript the job already has in memory, so recordings gain the
|
||||
* same topic/scope/município facets with the same provenance vocabulary. The
|
||||
* classifier never throws; this wrapper is also defensive (empty transcript or
|
||||
* a database failure resolve to `null`) because the recording must still
|
||||
* become `ready` with its transcript.
|
||||
*/
|
||||
|
||||
export type RecordingFacetClassifier = (
|
||||
input: SpeechFacetInput,
|
||||
) => Promise<SpeechClassificationResult>
|
||||
|
||||
export type RecordingClassification = {
|
||||
topics: SpeechTopic[]
|
||||
scopes: SpeechScope[]
|
||||
classifiedBy: MergedSpeechFacets['classifiedBy']
|
||||
mentionedMunicipalities: number[]
|
||||
/** Provider usage of the refinement pass; the backfill CLI reports it. */
|
||||
llm: SpeechClassificationResult['llm']
|
||||
}
|
||||
|
||||
/**
|
||||
* The facet write shape, shared by the two writers (the job and the backfill
|
||||
* CLI) so a new facet field lands in one place.
|
||||
*/
|
||||
export const recordingFacetWriteData = (
|
||||
classification: RecordingClassification,
|
||||
): Pick<Recording, 'topics' | 'scopes' | 'classifiedBy' | 'mentionedMunicipalities'> => ({
|
||||
topics: classification.topics,
|
||||
scopes: classification.scopes,
|
||||
classifiedBy: classification.classifiedBy,
|
||||
mentionedMunicipalities: classification.mentionedMunicipalities,
|
||||
})
|
||||
|
||||
export const classifyRecordingFacets = async ({
|
||||
payload,
|
||||
transcript,
|
||||
classify = classifySpeech,
|
||||
}: {
|
||||
payload: Pick<Payload, 'find' | 'logger'>
|
||||
transcript: string
|
||||
classify?: RecordingFacetClassifier
|
||||
}): Promise<RecordingClassification | null> => {
|
||||
const text = transcript.trim()
|
||||
if (!text) return null
|
||||
|
||||
try {
|
||||
const { facets, llm } = await classify({ transcript: text })
|
||||
|
||||
const slugs = [...new Set(facets.municipalities.map((entry) => entry.slug))]
|
||||
const municipalities =
|
||||
slugs.length === 0
|
||||
? []
|
||||
: (
|
||||
await payload.find({
|
||||
collection: 'municipality',
|
||||
where: { slug: { in: slugs } },
|
||||
limit: slugs.length,
|
||||
depth: 0,
|
||||
select: { slug: true },
|
||||
// Intentional admin bypass: resolving gazetteer slugs against the
|
||||
// read-only município catalog (same as the speech import).
|
||||
overrideAccess: true,
|
||||
})
|
||||
).docs
|
||||
|
||||
return {
|
||||
topics: facets.topics,
|
||||
scopes: facets.scopes,
|
||||
classifiedBy: facets.classifiedBy,
|
||||
mentionedMunicipalities: municipalities.map((doc) => doc.id),
|
||||
llm,
|
||||
}
|
||||
} catch (error) {
|
||||
// Defensive: the classifier contract is "never throws"; a database failure
|
||||
// while resolving the gazetteer slugs lands here. The recording still gets
|
||||
// its transcript — but the failure is logged instead of vanishing.
|
||||
payload.logger.warn(
|
||||
`[recording-classification] falha ao classificar: ${error instanceof Error ? error.message : String(error)}`,
|
||||
)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
|
@ -39,6 +39,12 @@ import {
|
|||
type PayloadTransactionRequest,
|
||||
} from '@/utilities/payloadTransaction'
|
||||
import { downloadPrivateMediaToFile } from '@/utilities/privateMedia/privateMediaResponse'
|
||||
import {
|
||||
classifyRecordingFacets,
|
||||
recordingFacetWriteData,
|
||||
type RecordingFacetClassifier,
|
||||
} from '@/utilities/recordings/recordingClassification'
|
||||
import { classifySpeech } from '@/utilities/speech/speechClassifier'
|
||||
|
||||
/**
|
||||
* C199 — the transcription job: download the private recording, extract/split
|
||||
|
|
@ -128,6 +134,7 @@ export const runRecordingJob = async (
|
|||
recordingId: number,
|
||||
transcribe: ChunkTranscriber = deepInfraTranscribeSegments,
|
||||
diarize: SpeakerDiarizer | null = configuredSpeakerDiarizer(),
|
||||
classify: RecordingFacetClassifier = classifySpeech,
|
||||
): Promise<void> => {
|
||||
let tempDir: string | null = null
|
||||
let currentStep: RecordingStep = 'extracting'
|
||||
|
|
@ -237,6 +244,15 @@ export const runRecordingJob = async (
|
|||
}
|
||||
}
|
||||
|
||||
// C219 — facet classification runs OUTSIDE the save transaction (the LLM
|
||||
// may take a minute) and never fails the recording: a null result keeps the
|
||||
// transcript with no facets and no provenance claim.
|
||||
const classification = await classifyRecordingFacets({
|
||||
payload,
|
||||
transcript: keyedSegments.map((segment) => segment.text).join(' '),
|
||||
classify,
|
||||
})
|
||||
|
||||
await markStep('saving')
|
||||
await withPayloadTransaction(payload, async ({ req }) => {
|
||||
// Fresh reads inside the transaction: the labels a curator wrote while
|
||||
|
|
@ -310,6 +326,7 @@ export const runRecordingJob = async (
|
|||
searchText: recordingSearchText(segments),
|
||||
speakerLabels: labels,
|
||||
speakerLabelsDropped: dropped,
|
||||
...(classification ? recordingFacetWriteData(classification) : {}),
|
||||
},
|
||||
req,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,22 +1,67 @@
|
|||
/**
|
||||
* C199 — Payload `where` of the uploaded-recordings list: one textual branch
|
||||
* over the normalized `recording.searchText` (the concatenation of the
|
||||
* transcript segments). C200 adds the "Pessoa" facet: any selected label that
|
||||
* appears in the recording's derived `speakerNames`. A recording still
|
||||
* processing has no `searchText` and is honestly out of the search until the
|
||||
* transcript is saved.
|
||||
* C199/C219 — Payload `where` of the uploaded-recordings list. One textual
|
||||
* branch over the normalized `recording.searchText` (the concatenation of the
|
||||
* transcript segments), the "Pessoa" facet (any selected label present in the
|
||||
* derived `speakerNames`) and the C219 parity facets — year, topic, scope,
|
||||
* cited municipality and duration — AND-ed like the Câmara's. A duration sort
|
||||
* also gates `durationSeconds` to exist, otherwise Postgres' NULLS FIRST would
|
||||
* open "Duração (maior)" with the rows that have no duration.
|
||||
*/
|
||||
import type { Where } from 'payload'
|
||||
|
||||
import { normalizeForSearch } from '@/lib/speechSearch'
|
||||
import { collapseListWhereOrBranches } from '@/utilities/campaignListUrl'
|
||||
import type { RecordingListState } from '@/utilities/recordings/recordingListUrl'
|
||||
import {
|
||||
recordingSortIsDuration,
|
||||
type RecordingListState,
|
||||
} from '@/utilities/recordings/recordingListUrl'
|
||||
import { durationBucketWhere } from '@/utilities/speech/speechListFilters'
|
||||
|
||||
export const buildRecordingListWhere = (state: RecordingListState): Where => {
|
||||
const buildRecordingFacetWhere = (state: RecordingListState): Where[] => {
|
||||
const filters: Where[] = []
|
||||
|
||||
if (state.years?.length) filters.push({ year: { in: state.years } })
|
||||
if (state.topics?.length) filters.push({ topics: { in: state.topics } })
|
||||
if (state.scopes?.length) filters.push({ scopes: { in: state.scopes } })
|
||||
if (state.municipalities?.length) {
|
||||
filters.push({ mentionedMunicipalities: { in: state.municipalities } })
|
||||
}
|
||||
if (state.durations?.length) {
|
||||
const branch = collapseListWhereOrBranches(state.durations.map(durationBucketWhere))
|
||||
if (branch) filters.push(branch)
|
||||
}
|
||||
if (recordingSortIsDuration(state)) filters.push({ durationSeconds: { exists: true } })
|
||||
|
||||
return filters
|
||||
}
|
||||
|
||||
/**
|
||||
* The textual branch: the literal query plus (C219) every expanded theme term,
|
||||
* each matching the normalized recording text. Recordings have no official
|
||||
* keywords, so the speech `keywords` branch has no counterpart here.
|
||||
*/
|
||||
const buildRecordingTextWhere = (terms: readonly string[]): Where | undefined => {
|
||||
const branches: Where[] = []
|
||||
const seen = new Set<string>()
|
||||
|
||||
const normalized = normalizeForSearch(state.q ?? '')
|
||||
if (normalized) branches.push({ searchText: { like: normalized } })
|
||||
for (const term of terms) {
|
||||
const normalized = normalizeForSearch(term)
|
||||
if (!normalized || seen.has(normalized)) continue
|
||||
seen.add(normalized)
|
||||
branches.push({ searchText: { like: normalized } })
|
||||
}
|
||||
|
||||
return collapseListWhereOrBranches(branches)
|
||||
}
|
||||
|
||||
export const buildRecordingListWhere = (
|
||||
state: RecordingListState,
|
||||
themeTerms: readonly string[] = [],
|
||||
): Where => {
|
||||
const branches = buildRecordingFacetWhere(state)
|
||||
|
||||
const textBranch = buildRecordingTextWhere([...(state.q ? [state.q] : []), ...themeTerms])
|
||||
if (textBranch) branches.push(textBranch)
|
||||
|
||||
const peopleBranch = collapseListWhereOrBranches(
|
||||
(state.people ?? []).map((person) => ({ speakerNames: { contains: person } })),
|
||||
|
|
|
|||
|
|
@ -1,43 +1,108 @@
|
|||
/**
|
||||
* C199 — source switcher + list URL contract of the uploaded recordings. The
|
||||
* Câmara acervo keeps its own frozen contract (`speechListUrl`); the recordings
|
||||
* branch lives on the same `/campanha/comunicacao/acervo` page behind
|
||||
* `?source=enviadas` and owns its parses/serialization over the shared helpers.
|
||||
* C199/C219 — source switcher + list URL contract of the uploaded recordings.
|
||||
* The Câmara acervo keeps its own frozen contract (`speechListUrl`); the
|
||||
* recordings branch lives on the same `/campanha/comunicacao/acervo` page
|
||||
* behind `?source=enviadas` and owns its parses/serialization over the shared
|
||||
* helpers. C219 brings the parity facets — search mode, year, topic, scope,
|
||||
* cited municipality, duration and sort — reusing the Câmara taxonomy, the
|
||||
* duration buckets and the structural year/municipality parsers. The original
|
||||
* `?source=enviadas&q&person&page` deep links stay byte-identical: the new
|
||||
* params are only serialized when selected and `mode=termo`/the default sort
|
||||
* are never serialized.
|
||||
*/
|
||||
import { CAMPAIGN_COMMUNICATION_ACERVO } from '@/lib/campaignPaths'
|
||||
import { isContactSearchQueryReady } from '@/lib/contactSearchQuery'
|
||||
import { RECORDING_SPEAKER_LABEL_MAX_LENGTH } from '@/lib/recording'
|
||||
import { foldSpeakerName } from '@/lib/recordingDiarization'
|
||||
import {
|
||||
SPEECH_SCOPES,
|
||||
SPEECH_TOPICS,
|
||||
type SpeechScope,
|
||||
type SpeechTopic,
|
||||
} from '@/lib/speechFacets'
|
||||
import {
|
||||
allParamValues,
|
||||
buildListHref,
|
||||
firstValue,
|
||||
normalizedText,
|
||||
parseExhaustiveEnumParam,
|
||||
parseMunicipalityValues,
|
||||
parseYearValues,
|
||||
resolveListUrl,
|
||||
strictDecimalInteger,
|
||||
type RawSearchParams,
|
||||
} from '@/utilities/campaignListUrl'
|
||||
import {
|
||||
SPEECH_DURATION_BUCKETS,
|
||||
type SpeechDurationBucket,
|
||||
type SpeechSearchMode,
|
||||
} from '@/utilities/speech/speechListUrl'
|
||||
|
||||
export const recordingPageSize = 25
|
||||
|
||||
/** Which acervo source the page is showing. `camara` is the default. */
|
||||
export type AcervoSource = 'camara' | 'enviadas'
|
||||
|
||||
/**
|
||||
* C219 — list ordering. `recentes` is the default and never serialized (the
|
||||
* stored contract stays `-createdAt`); the duration orders only list rows with
|
||||
* a measured duration, which is why the `where` gates `durationSeconds`.
|
||||
*/
|
||||
export const RECORDING_SORT_OPTIONS = [
|
||||
{ value: 'recentes', label: 'Mais recentes' },
|
||||
{ value: 'duracao_maior', label: 'Duração (maior)' },
|
||||
{ value: 'duracao_menor', label: 'Duração (menor)' },
|
||||
] as const
|
||||
|
||||
export type RecordingSortKey = (typeof RECORDING_SORT_OPTIONS)[number]['value']
|
||||
|
||||
const ACERVO_SOURCE_PARAM = 'source'
|
||||
const ACERVO_SOURCE_ENVIADAS = 'enviadas'
|
||||
const ACERVO_PERSON_PARAM = 'person'
|
||||
|
||||
const recordingListParamNames = [ACERVO_SOURCE_PARAM, 'q', 'page', ACERVO_PERSON_PARAM] as const
|
||||
const recordingListParamNames = [
|
||||
ACERVO_SOURCE_PARAM,
|
||||
'q',
|
||||
'mode',
|
||||
'year',
|
||||
'topic',
|
||||
'scope',
|
||||
'municipality',
|
||||
'duration',
|
||||
'sort',
|
||||
ACERVO_PERSON_PARAM,
|
||||
'page',
|
||||
] as const
|
||||
const recordingListParamNameSet = new Set<string>(recordingListParamNames)
|
||||
const recordingTopicSet = new Set<string>(SPEECH_TOPICS.map(({ value }) => value))
|
||||
const recordingScopeSet = new Set<string>(SPEECH_SCOPES.map(({ value }) => value))
|
||||
const recordingDurationSet = new Set<string>(SPEECH_DURATION_BUCKETS.map(({ value }) => value))
|
||||
const recordingSortSet = new Set<string>(RECORDING_SORT_OPTIONS.map(({ value }) => value))
|
||||
|
||||
export type RecordingListState = {
|
||||
source: 'enviadas'
|
||||
page: number
|
||||
q?: string
|
||||
/** C219 — `tema` asks the semantic bridge; `termo` (default) is never stored. */
|
||||
mode?: SpeechSearchMode
|
||||
years?: number[]
|
||||
topics?: SpeechTopic[]
|
||||
scopes?: SpeechScope[]
|
||||
/** Cited municipalities (`mentionedMunicipalities`), not the uploader's. */
|
||||
municipalities?: number[]
|
||||
durations?: SpeechDurationBucket[]
|
||||
sort?: RecordingSortKey
|
||||
/** Selected "Pessoa" labels; repeated `person` params, literal text. */
|
||||
people?: string[]
|
||||
}
|
||||
|
||||
/** Server-loaded filter options (present years, cited municipalities, people). */
|
||||
export type RecordingFilterOptions = {
|
||||
people: string[]
|
||||
years: number[]
|
||||
municipalities: { value: string; label: string }[]
|
||||
}
|
||||
|
||||
/** `enviadas` only for the explicit value; anything else is the Câmara default. */
|
||||
export const parseAcervoSource = (params: RawSearchParams): AcervoSource =>
|
||||
firstValue(params[ACERVO_SOURCE_PARAM]) === ACERVO_SOURCE_ENVIADAS ? 'enviadas' : 'camara'
|
||||
|
|
@ -60,33 +125,99 @@ export const parseRecordingPeople = (raw: string | string[] | undefined): string
|
|||
return people
|
||||
}
|
||||
|
||||
/** Only `tema` is meaningful; anything else (and `termo`) means the default. */
|
||||
const parseRecordingSearchMode = (
|
||||
raw: string | string[] | undefined,
|
||||
): SpeechSearchMode | undefined => (firstValue(raw) === 'tema' ? 'tema' : undefined)
|
||||
|
||||
/** Only the non-default duration orders are meaningful; anything else is `recentes`. */
|
||||
const parseRecordingSort = (raw: string | string[] | undefined): RecordingSortKey | undefined => {
|
||||
const value = firstValue(raw)
|
||||
return value && value !== 'recentes' && recordingSortSet.has(value)
|
||||
? (value as RecordingSortKey)
|
||||
: undefined
|
||||
}
|
||||
|
||||
export const parseRecordingListParams = (params: RawSearchParams): RecordingListState => {
|
||||
const rawPage = strictDecimalInteger(firstValue(params.page))
|
||||
const rawQ = normalizedText(firstValue(params.q))
|
||||
const q = rawQ && isContactSearchQueryReady(rawQ) ? rawQ : undefined
|
||||
const mode = parseRecordingSearchMode(params.mode)
|
||||
const years = parseYearValues(params.year)
|
||||
const topics = parseExhaustiveEnumParam<SpeechTopic>(params.topic, recordingTopicSet)
|
||||
const scopes = parseExhaustiveEnumParam<SpeechScope>(params.scope, recordingScopeSet)
|
||||
const municipalities = parseMunicipalityValues(params.municipality)
|
||||
const durations = parseExhaustiveEnumParam<SpeechDurationBucket>(
|
||||
params.duration,
|
||||
recordingDurationSet,
|
||||
)
|
||||
const sort = parseRecordingSort(params.sort)
|
||||
const people = parseRecordingPeople(params[ACERVO_PERSON_PARAM])
|
||||
|
||||
return {
|
||||
source: 'enviadas',
|
||||
page: rawPage ?? 1,
|
||||
...(q ? { q } : {}),
|
||||
...(mode ? { mode } : {}),
|
||||
...(years.length ? { years } : {}),
|
||||
...(topics.length ? { topics } : {}),
|
||||
...(scopes.length ? { scopes } : {}),
|
||||
...(municipalities.length ? { municipalities } : {}),
|
||||
...(durations.length ? { durations } : {}),
|
||||
...(sort ? { sort } : {}),
|
||||
...(people.length > 0 ? { people } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
const recordingListSearchParams = (
|
||||
const recordingListStateToRawParams = (
|
||||
state: RecordingListState,
|
||||
page = state.page,
|
||||
): RawSearchParams => ({
|
||||
[ACERVO_SOURCE_PARAM]: ACERVO_SOURCE_ENVIADAS,
|
||||
page: String(page),
|
||||
q: state.q,
|
||||
mode: state.mode,
|
||||
year: state.years?.map(String),
|
||||
topic: state.topics,
|
||||
scope: state.scopes,
|
||||
municipality: state.municipalities?.map(String),
|
||||
duration: state.durations,
|
||||
sort: state.sort,
|
||||
[ACERVO_PERSON_PARAM]: state.people,
|
||||
})
|
||||
|
||||
/** Expects already-canonical state (from parse or a rule-preserving toggle). */
|
||||
const serializeCanonicalRecordingListSearchParams = (
|
||||
canonicalState: RecordingListState,
|
||||
): URLSearchParams => {
|
||||
const params = new URLSearchParams()
|
||||
// `source=enviadas` is always serialized — it is what selects the source.
|
||||
params.set(ACERVO_SOURCE_PARAM, ACERVO_SOURCE_ENVIADAS)
|
||||
if (state.q) params.set('q', state.q)
|
||||
for (const person of state.people ?? []) params.append(ACERVO_PERSON_PARAM, person)
|
||||
if (page > 1) params.set('page', String(page))
|
||||
if (canonicalState.q) params.set('q', canonicalState.q)
|
||||
// `termo` is the default and never serialized; `tema` only makes sense with a
|
||||
// query, so a theme param without `q` canonicalizes away.
|
||||
if (canonicalState.mode === 'tema' && canonicalState.q) params.set('mode', 'tema')
|
||||
for (const year of canonicalState.years ?? []) params.append('year', String(year))
|
||||
for (const topic of canonicalState.topics ?? []) params.append('topic', topic)
|
||||
for (const scope of canonicalState.scopes ?? []) params.append('scope', scope)
|
||||
for (const municipality of canonicalState.municipalities ?? []) {
|
||||
params.append('municipality', String(municipality))
|
||||
}
|
||||
for (const duration of canonicalState.durations ?? []) params.append('duration', duration)
|
||||
// `recentes` is the default and never serialized.
|
||||
if (canonicalState.sort && canonicalState.sort !== 'recentes') {
|
||||
params.set('sort', canonicalState.sort)
|
||||
}
|
||||
for (const person of canonicalState.people ?? []) params.append(ACERVO_PERSON_PARAM, person)
|
||||
if (canonicalState.page > 1) params.set('page', String(canonicalState.page))
|
||||
return params
|
||||
}
|
||||
|
||||
const recordingListSearchParams = (state: RecordingListState, page = state.page): URLSearchParams =>
|
||||
serializeCanonicalRecordingListSearchParams(
|
||||
parseRecordingListParams(recordingListStateToRawParams(state, page)),
|
||||
)
|
||||
|
||||
/** The URL of one "Pessoa" facet option with `person` toggled (page resets). */
|
||||
export const toggleRecordingPerson = (
|
||||
state: RecordingListState,
|
||||
|
|
@ -114,6 +245,47 @@ export const removeRecordingPerson = (
|
|||
export const buildRecordingListHref = (state: RecordingListState, page: number): string =>
|
||||
buildListHref(state, recordingListSearchParams, CAMPAIGN_COMMUNICATION_ACERVO, page)
|
||||
|
||||
/**
|
||||
* C219 — the canonical query drives the filter bar remount (`key`), exactly
|
||||
* like `buildSpeechFiltersKey`, so optimistic state resets when the URL
|
||||
* changes.
|
||||
*/
|
||||
export const buildRecordingFiltersKey = (state: RecordingListState): string =>
|
||||
recordingListSearchParams(state).toString()
|
||||
|
||||
/** Payload sort order of the list: the default keeps the stored `-createdAt`. */
|
||||
export const recordingSortOrder = (state: RecordingListState): string => {
|
||||
switch (state.sort) {
|
||||
case 'duracao_maior':
|
||||
return '-durationSeconds'
|
||||
case 'duracao_menor':
|
||||
return 'durationSeconds'
|
||||
default:
|
||||
return '-createdAt'
|
||||
}
|
||||
}
|
||||
|
||||
/** Duration orders only make sense over rows with a measured duration. */
|
||||
export const recordingSortIsDuration = (state: RecordingListState): boolean =>
|
||||
state.sort === 'duracao_maior' || state.sort === 'duracao_menor'
|
||||
|
||||
/**
|
||||
* C219 — whether the actor narrowed the list (query/mode or any facet). The
|
||||
* empty state uses it to tell "no recording was ever sent" from "the filters
|
||||
* hid everything"; pagination is not a filter.
|
||||
*/
|
||||
export const recordingHasActiveFilters = (state: RecordingListState): boolean =>
|
||||
Boolean(
|
||||
state.q ||
|
||||
state.mode ||
|
||||
state.years?.length ||
|
||||
state.topics?.length ||
|
||||
state.scopes?.length ||
|
||||
state.municipalities?.length ||
|
||||
state.durations?.length ||
|
||||
state.people?.length,
|
||||
)
|
||||
|
||||
/** Toggle hrefs of the source switcher (the Câmara side is the bare acervo). */
|
||||
export const buildAcervoSourceHref = (source: AcervoSource): string =>
|
||||
source === 'enviadas'
|
||||
|
|
|
|||
286
src/utilities/recordings/recordingOmnibox.ts
Normal file
286
src/utilities/recordings/recordingOmnibox.ts
Normal file
|
|
@ -0,0 +1,286 @@
|
|||
/**
|
||||
* C219 — recordings acervo omnibox adapter. Pure / client-safe: builds the
|
||||
* active chips, the suggestion seeds (facet constants plus server-loaded
|
||||
* years/municipalities/people) and the toggle/remove/clear actions over the
|
||||
* URL state, mirroring `speechOmnibox` on the same shared helpers. "Pessoa"
|
||||
* reuses the case-insensitive dedupe owned by the recordings URL contract.
|
||||
*/
|
||||
import {
|
||||
createOmniboxSuggestionSeed,
|
||||
filterOmniboxSuggestionSeeds,
|
||||
type CampaignListOmniboxChip,
|
||||
type CampaignListOmniboxSuggestion,
|
||||
} from '@/lib/campaignListOmnibox'
|
||||
import {
|
||||
SPEECH_SCOPES,
|
||||
SPEECH_TOPICS,
|
||||
type SpeechScope,
|
||||
type SpeechTopic,
|
||||
} from '@/lib/speechFacets'
|
||||
import {
|
||||
removeRecordingPerson,
|
||||
toggleRecordingPerson,
|
||||
type RecordingListState,
|
||||
} from '@/utilities/recordings/recordingListUrl'
|
||||
import {
|
||||
SPEECH_DURATION_BUCKETS,
|
||||
speechDurationLabels,
|
||||
speechScopeLabels,
|
||||
speechTopicLabels,
|
||||
type SpeechDurationBucket,
|
||||
type SpeechSearchMode,
|
||||
} from '@/utilities/speech/speechListUrl'
|
||||
|
||||
export type RecordingFilterOption = {
|
||||
value: string
|
||||
label: string
|
||||
}
|
||||
|
||||
const MUNICIPALITY_CHIP_LABEL = 'Município citado'
|
||||
|
||||
export type RecordingOmniboxAction =
|
||||
| { kind: 'url'; state: RecordingListState }
|
||||
| { kind: 'clear'; state: RecordingListState }
|
||||
|
||||
const chipLabel = (dimension: string, value: string): string => `${dimension}: ${value}`
|
||||
|
||||
const withPageReset = (state: RecordingListState): RecordingListState => ({ ...state, page: 1 })
|
||||
|
||||
const toggleValue = <T>(values: T[] | undefined, value: T): T[] | undefined => {
|
||||
const current = values ?? []
|
||||
const next = current.includes(value)
|
||||
? current.filter((item) => item !== value)
|
||||
: [...current, value]
|
||||
return next.length ? next : undefined
|
||||
}
|
||||
|
||||
const removeValue = <T>(values: T[] | undefined, value: T): T[] | undefined => {
|
||||
const next = (values ?? []).filter((item) => item !== value)
|
||||
return next.length ? next : undefined
|
||||
}
|
||||
|
||||
const chipPrefix = (chipId: string): { key: string; value: string } => {
|
||||
const separator = chipId.indexOf(':')
|
||||
if (separator === -1) return { key: chipId, value: '' }
|
||||
return { key: chipId.slice(0, separator), value: chipId.slice(separator + 1) }
|
||||
}
|
||||
|
||||
type FacetMutation = 'toggle' | 'remove'
|
||||
|
||||
/**
|
||||
* ONE facet mutation for both omnibox actions: `toggle` (selecting a
|
||||
* suggestion) and `remove` (dropping a chip) differ only in the values
|
||||
* operation. Returns null when the id carries an invalid numeric value.
|
||||
*/
|
||||
const mutateFacet = (
|
||||
state: RecordingListState,
|
||||
key: string,
|
||||
value: string,
|
||||
mode: FacetMutation,
|
||||
): RecordingListState | null => {
|
||||
const mutate = mode === 'toggle' ? toggleValue : removeValue
|
||||
switch (key) {
|
||||
case 'year': {
|
||||
const year = Number(value)
|
||||
if (!Number.isSafeInteger(year)) return null
|
||||
return { ...state, years: mutate(state.years, year) }
|
||||
}
|
||||
case 'topic':
|
||||
return { ...state, topics: mutate(state.topics, value as SpeechTopic) }
|
||||
case 'scope':
|
||||
return { ...state, scopes: mutate(state.scopes, value as SpeechScope) }
|
||||
case 'municipality': {
|
||||
const municipality = Number(value)
|
||||
if (!Number.isSafeInteger(municipality)) return null
|
||||
return { ...state, municipalities: mutate(state.municipalities, municipality) }
|
||||
}
|
||||
case 'duration':
|
||||
return { ...state, durations: mutate(state.durations, value as SpeechDurationBucket) }
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export const buildRecordingOmniboxChips = ({
|
||||
state,
|
||||
municipalityLabelsById,
|
||||
}: {
|
||||
state: RecordingListState
|
||||
municipalityLabelsById: ReadonlyMap<number, string>
|
||||
}): CampaignListOmniboxChip[] => {
|
||||
const chips: CampaignListOmniboxChip[] = []
|
||||
|
||||
if (state.q) chips.push({ id: 'q', label: chipLabel('Busca', state.q) })
|
||||
for (const year of state.years ?? []) {
|
||||
chips.push({ id: `year:${year}`, label: chipLabel('Ano', String(year)) })
|
||||
}
|
||||
for (const topic of state.topics ?? []) {
|
||||
chips.push({ id: `topic:${topic}`, label: chipLabel('Tema', speechTopicLabels[topic]) })
|
||||
}
|
||||
for (const scope of state.scopes ?? []) {
|
||||
chips.push({ id: `scope:${scope}`, label: chipLabel('Alcance', speechScopeLabels[scope]) })
|
||||
}
|
||||
for (const municipality of state.municipalities ?? []) {
|
||||
chips.push({
|
||||
id: `municipality:${municipality}`,
|
||||
label: chipLabel(
|
||||
MUNICIPALITY_CHIP_LABEL,
|
||||
municipalityLabelsById.get(municipality) ?? `Município #${municipality}`,
|
||||
),
|
||||
})
|
||||
}
|
||||
for (const duration of state.durations ?? []) {
|
||||
chips.push({
|
||||
id: `duration:${duration}`,
|
||||
label: chipLabel('Duração', speechDurationLabels[duration]),
|
||||
})
|
||||
}
|
||||
for (const person of state.people ?? []) {
|
||||
chips.push({ id: `person:${person}`, label: chipLabel('Pessoa', person) })
|
||||
}
|
||||
|
||||
return chips
|
||||
}
|
||||
|
||||
export const buildRecordingOmniboxSuggestionSeeds = ({
|
||||
years,
|
||||
municipalityOptions,
|
||||
personOptions,
|
||||
}: {
|
||||
years: readonly number[]
|
||||
municipalityOptions: readonly RecordingFilterOption[]
|
||||
personOptions: readonly string[]
|
||||
}) => {
|
||||
const seeds = []
|
||||
|
||||
for (const { value, label } of SPEECH_TOPICS) {
|
||||
seeds.push(
|
||||
createOmniboxSuggestionSeed(
|
||||
{ id: `topic:${value}`, group: 'Tema', label, keywords: ['tema'] },
|
||||
{ emptyQueryVisible: true },
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
for (const { value, label } of SPEECH_SCOPES) {
|
||||
seeds.push(
|
||||
createOmniboxSuggestionSeed(
|
||||
{ id: `scope:${value}`, group: 'Alcance', label, keywords: ['alcance'] },
|
||||
{ emptyQueryVisible: true },
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
for (const { value, label } of SPEECH_DURATION_BUCKETS) {
|
||||
seeds.push(
|
||||
createOmniboxSuggestionSeed(
|
||||
{ id: `duration:${value}`, group: 'Duração', label, keywords: ['duracao', 'tempo'] },
|
||||
{ emptyQueryVisible: true },
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
for (const year of years) {
|
||||
seeds.push(
|
||||
createOmniboxSuggestionSeed({
|
||||
id: `year:${year}`,
|
||||
group: 'Ano',
|
||||
label: String(year),
|
||||
keywords: ['ano'],
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
for (const option of municipalityOptions) {
|
||||
seeds.push(
|
||||
createOmniboxSuggestionSeed({
|
||||
id: `municipality:${option.value}`,
|
||||
group: MUNICIPALITY_CHIP_LABEL,
|
||||
label: option.label,
|
||||
keywords: ['municipio', 'cidade', 'citado'],
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
for (const person of personOptions) {
|
||||
seeds.push(
|
||||
createOmniboxSuggestionSeed({
|
||||
id: `person:${person}`,
|
||||
group: 'Pessoa',
|
||||
label: person,
|
||||
keywords: ['pessoa', 'falante'],
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
return seeds
|
||||
}
|
||||
|
||||
export const filterRecordingOmniboxSuggestions = (
|
||||
seeds: ReturnType<typeof buildRecordingOmniboxSuggestionSeeds>,
|
||||
query: string,
|
||||
): CampaignListOmniboxSuggestion[] => filterOmniboxSuggestionSeeds(seeds, query)
|
||||
|
||||
export const applyRecordingOmniboxSuggestion = ({
|
||||
state,
|
||||
suggestionId,
|
||||
}: {
|
||||
state: RecordingListState
|
||||
suggestionId: string
|
||||
}): RecordingOmniboxAction => {
|
||||
if (suggestionId.startsWith('q:')) {
|
||||
const q = suggestionId.slice(2).trim()
|
||||
return { kind: 'url', state: withPageReset({ ...state, q: q || undefined }) }
|
||||
}
|
||||
|
||||
const { key, value } = chipPrefix(suggestionId)
|
||||
if (key === 'person') {
|
||||
return { kind: 'url', state: toggleRecordingPerson(withPageReset(state), value) }
|
||||
}
|
||||
|
||||
const next = mutateFacet(withPageReset(state), key, value, 'toggle')
|
||||
return { kind: 'url', state: next ?? state }
|
||||
}
|
||||
|
||||
export const removeRecordingOmniboxChip = ({
|
||||
state,
|
||||
chipId,
|
||||
}: {
|
||||
state: RecordingListState
|
||||
chipId: string
|
||||
}): RecordingOmniboxAction => {
|
||||
// Dropping the query also drops the theme mode: a theme without a query has
|
||||
// nothing to expand.
|
||||
if (chipId === 'q') {
|
||||
return { kind: 'url', state: withPageReset({ ...state, q: undefined, mode: undefined }) }
|
||||
}
|
||||
|
||||
const { key, value } = chipPrefix(chipId)
|
||||
if (key === 'person') {
|
||||
return { kind: 'url', state: removeRecordingPerson(withPageReset(state), value) }
|
||||
}
|
||||
|
||||
const next = mutateFacet(withPageReset(state), key, value, 'remove')
|
||||
return { kind: 'url', state: next ?? state }
|
||||
}
|
||||
|
||||
/**
|
||||
* C219 — the search mode toggle. `tema` only sticks with a query; `termo`
|
||||
* (the default) clears the param so the URL stays canonical and shareable.
|
||||
*/
|
||||
export const applyRecordingSearchMode = ({
|
||||
state,
|
||||
mode,
|
||||
}: {
|
||||
state: RecordingListState
|
||||
mode: SpeechSearchMode
|
||||
}): RecordingOmniboxAction => ({
|
||||
kind: 'url',
|
||||
state: withPageReset({ ...state, mode: mode === 'tema' && state.q ? 'tema' : undefined }),
|
||||
})
|
||||
|
||||
/** Clearing keeps `source=enviadas` — it is what selects this source. */
|
||||
export const clearRecordingOmnibox = (_state: RecordingListState): RecordingOmniboxAction => ({
|
||||
kind: 'clear',
|
||||
state: { source: 'enviadas', page: 1 },
|
||||
})
|
||||
|
|
@ -2,15 +2,24 @@ import 'server-only'
|
|||
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import { canReadCommunicationCatalog } from '@/lib/campaignRoles'
|
||||
import { foldSpeakerName } from '@/lib/recordingDiarization'
|
||||
import { RECORDING_NOT_FOUND_MESSAGE } from '@/lib/schemas/recording'
|
||||
import { normalizeForSearch } from '@/lib/speechSearch'
|
||||
import type { CampaignUser } from '@/payload-types'
|
||||
import {
|
||||
expandRecordingSearchTheme,
|
||||
type ThemeSearchExpansionResolver,
|
||||
} from '@/utilities/ai/expandSpeechSearchTheme'
|
||||
import { collapseListWhereOrBranches } from '@/utilities/campaignListUrl'
|
||||
import { createEntityNotFoundError } from '@/utilities/entityNotFound'
|
||||
import { loadMunicipalityLabelsByIds } from '@/utilities/loadNamesByIds'
|
||||
import { buildRecordingListWhere } from '@/utilities/recordings/recordingListFilters'
|
||||
import {
|
||||
recordingPageSize,
|
||||
recordingSortOrder,
|
||||
resolveRecordingListUrl,
|
||||
type RecordingFilterOptions,
|
||||
type RecordingListState,
|
||||
} from '@/utilities/recordings/recordingListUrl'
|
||||
import {
|
||||
|
|
@ -35,6 +44,8 @@ const recordingListSelect = {
|
|||
recordedAt: true,
|
||||
durationSeconds: true,
|
||||
speakerNames: true,
|
||||
// C219 — the card's topic chip; the facet itself is not displayed.
|
||||
topics: true,
|
||||
} as const
|
||||
|
||||
const recordingDetailSelect = {
|
||||
|
|
@ -63,17 +74,12 @@ const toSegmentRecord = (segment: {
|
|||
speakerKey: segment.speakerKey ?? null,
|
||||
})
|
||||
|
||||
/** C200 — the options the "Pessoa" facet offers. */
|
||||
export type RecordingFilterOptions = {
|
||||
people: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* C200 — distinct labels across the recordings the actor can read: the facet
|
||||
* only ever lists what is reachable, and the derived `speakerNames` column is
|
||||
* the single source. Small acervo now; if the list grows past a few thousand
|
||||
* rows this becomes a `SELECT DISTINCT` (registered as a revisit trigger in the
|
||||
* impl plan).
|
||||
* C200/C219 — distinct labels/years/cited municipalities across the
|
||||
* recordings the actor can read: a facet only ever lists what is reachable,
|
||||
* and the derived columns are the single source. Municipality labels resolve
|
||||
* through the justified `loadMunicipalityLabelsByIds` bypass — the ids come
|
||||
* from recordings the actor was already authorized to read.
|
||||
*/
|
||||
export const loadRecordingFilterOptions = async (
|
||||
payload: Payload,
|
||||
|
|
@ -84,13 +90,15 @@ export const loadRecordingFilterOptions = async (
|
|||
depth: 0,
|
||||
limit: 0,
|
||||
pagination: false,
|
||||
select: { speakerNames: true },
|
||||
select: { speakerNames: true, year: true, mentionedMunicipalities: true },
|
||||
user,
|
||||
overrideAccess: false,
|
||||
})
|
||||
|
||||
const people: string[] = []
|
||||
const seen = new Set<string>()
|
||||
const years = new Set<number>()
|
||||
const municipalityIds = new Set<number>()
|
||||
for (const recording of result.docs) {
|
||||
for (const name of recording.speakerNames ?? []) {
|
||||
const trimmed = name.trim()
|
||||
|
|
@ -99,35 +107,56 @@ export const loadRecordingFilterOptions = async (
|
|||
seen.add(folded)
|
||||
people.push(trimmed)
|
||||
}
|
||||
if (typeof recording.year === 'number') years.add(recording.year)
|
||||
for (const value of recording.mentionedMunicipalities ?? []) {
|
||||
municipalityIds.add(typeof value === 'number' ? value : value.id)
|
||||
}
|
||||
}
|
||||
|
||||
return { people: people.sort((left, right) => left.localeCompare(right, 'pt-BR')) }
|
||||
const labels = await loadMunicipalityLabelsByIds(payload, [...municipalityIds])
|
||||
const municipalities = [...municipalityIds]
|
||||
.flatMap((id) => {
|
||||
const entry = labels.get(id)
|
||||
return entry ? [{ value: String(id), label: entry.name }] : []
|
||||
})
|
||||
.sort((left, right) => left.label.localeCompare(right.label, 'pt-BR'))
|
||||
|
||||
return {
|
||||
people: people.sort((left, right) => left.localeCompare(right, 'pt-BR')),
|
||||
years: [...years].sort((left, right) => right - left),
|
||||
municipalities,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The excerpt segment of each listed recording: ONE matching segment per row
|
||||
* (the search runs `LIKE` on the joined `recording.searchText`, so a page of
|
||||
* hour-long recordings never pays for all of its segments). The rows whose
|
||||
* query only matches across the junction of two segments fall back together in
|
||||
* a single batched query, so a result never renders without an excerpt.
|
||||
* hour-long recordings never pays for all of its segments). C219 passes the
|
||||
* literal query plus every expanded theme term, so a theme result still gets
|
||||
* the passage that surfaced it. The rows whose query only matches across the
|
||||
* junction of two segments fall back together in a single batched query, so a
|
||||
* result never renders without an excerpt.
|
||||
*/
|
||||
const loadMatchedSegments = async (
|
||||
payload: Payload,
|
||||
user: CampaignUser,
|
||||
recordingIds: readonly number[],
|
||||
q: string,
|
||||
terms: readonly string[],
|
||||
): Promise<Map<number, RecordingSegmentRecord[]>> => {
|
||||
const byRecording = new Map<number, RecordingSegmentRecord[]>()
|
||||
const normalized = normalizeForSearch(q)
|
||||
if (!normalized || recordingIds.length === 0) return byRecording
|
||||
const normalizedTerms = [
|
||||
...new Set(terms.map((term) => normalizeForSearch(term)).filter((term) => term.length > 0)),
|
||||
]
|
||||
const textBranch = collapseListWhereOrBranches(
|
||||
normalizedTerms.map((term) => ({ searchText: { like: term } })),
|
||||
)
|
||||
if (!textBranch || recordingIds.length === 0) return byRecording
|
||||
|
||||
await Promise.all(
|
||||
recordingIds.map(async (recordingId) => {
|
||||
const match = await payload.find({
|
||||
collection: 'recordingSegment',
|
||||
where: {
|
||||
and: [{ recording: { equals: recordingId } }, { searchText: { like: normalized } }],
|
||||
},
|
||||
where: { and: [{ recording: { equals: recordingId } }, textBranch] },
|
||||
depth: 0,
|
||||
limit: 1,
|
||||
pagination: false,
|
||||
|
|
@ -172,25 +201,44 @@ export type RecordingsPageData = {
|
|||
redirectHref?: string
|
||||
totalDocs: number
|
||||
totalPages: number
|
||||
/**
|
||||
* C219 — true when the actor asked for `mode=tema` but the expansion
|
||||
* mechanism was unavailable; the page shows the discreet fallback notice.
|
||||
*/
|
||||
themeUnavailable: boolean
|
||||
/** C219 — true when the expansion actually contributed terms. */
|
||||
themeApplied: boolean
|
||||
}
|
||||
|
||||
export const loadRecordingsPageData = async (
|
||||
payload: Payload,
|
||||
user: CampaignUser,
|
||||
searchParams: Promise<RecordingListSearchParams> | RecordingListSearchParams,
|
||||
expandTheme: ThemeSearchExpansionResolver = expandRecordingSearchTheme,
|
||||
): Promise<RecordingsPageData> => {
|
||||
const rawSearchParams = await searchParams
|
||||
const canonicalUrl = resolveRecordingListUrl(rawSearchParams)
|
||||
const state = canonicalUrl.state
|
||||
|
||||
// C219 — only expand for an actor who may read the catalog (the `find` below
|
||||
// is still the final, fail-closed barrier) and only with a query.
|
||||
const themeRequested = state.mode === 'tema' && Boolean(state.q)
|
||||
let themeTerms: readonly string[] = []
|
||||
let themeUnavailable = false
|
||||
if (themeRequested && canReadCommunicationCatalog(user.role)) {
|
||||
const expansion = await expandTheme(state.q ?? '')
|
||||
if (expansion) themeTerms = expansion.terms
|
||||
else themeUnavailable = true
|
||||
}
|
||||
|
||||
const [result, filterOptions] = await Promise.all([
|
||||
payload.find({
|
||||
collection: 'recording',
|
||||
depth: 0,
|
||||
limit: recordingPageSize,
|
||||
page: state.page,
|
||||
sort: '-createdAt',
|
||||
where: buildRecordingListWhere(state),
|
||||
sort: recordingSortOrder(state),
|
||||
where: buildRecordingListWhere(state, themeTerms),
|
||||
select: recordingListSelect,
|
||||
user,
|
||||
overrideAccess: false,
|
||||
|
|
@ -200,12 +248,13 @@ export const loadRecordingsPageData = async (
|
|||
|
||||
const resolvedUrl = resolveRecordingListUrl(rawSearchParams, result.totalPages)
|
||||
const recordings = result.docs
|
||||
const segmentsByRecording = state.q
|
||||
const matchedTerms = [...(state.q ? [state.q] : []), ...themeTerms]
|
||||
const segmentsByRecording = matchedTerms.length
|
||||
? await loadMatchedSegments(
|
||||
payload,
|
||||
user,
|
||||
recordings.map((recording) => recording.id),
|
||||
state.q,
|
||||
matchedTerms,
|
||||
)
|
||||
: new Map<number, RecordingSegmentRecord[]>()
|
||||
|
||||
|
|
@ -215,6 +264,7 @@ export const loadRecordingsPageData = async (
|
|||
recording,
|
||||
matchedSegments: segmentsByRecording.get(recording.id) ?? [],
|
||||
query: state.q,
|
||||
themeTerms,
|
||||
people: state.people,
|
||||
}),
|
||||
),
|
||||
|
|
@ -223,6 +273,8 @@ export const loadRecordingsPageData = async (
|
|||
redirectHref: resolvedUrl.redirectHref ?? canonicalUrl.redirectHref,
|
||||
totalDocs: result.totalDocs,
|
||||
totalPages: result.totalPages,
|
||||
themeUnavailable,
|
||||
themeApplied: themeTerms.length > 0,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import {
|
|||
} from '@/lib/recording'
|
||||
import { recordingSpeakerDefaultLabel, speakerNameMatches } from '@/lib/recordingDiarization'
|
||||
import { formatSpeechClock } from '@/lib/speechClock'
|
||||
import type { SpeechTopic } from '@/lib/speechFacets'
|
||||
import {
|
||||
buildHighlightedExcerpt,
|
||||
pickMatchingSegment,
|
||||
|
|
@ -18,6 +19,7 @@ import {
|
|||
type SpeechHighlightedExcerpt,
|
||||
type SpeechHighlightPart,
|
||||
} from '@/lib/speechHighlight'
|
||||
import { speechTopicLabels } from '@/utilities/speech/speechListUrl'
|
||||
|
||||
/** The segment shape the recording detail transcript renders. */
|
||||
export type RecordingSegmentRecord = {
|
||||
|
|
@ -40,6 +42,8 @@ type RecordingBaseRecord = {
|
|||
export type RecordingListRecord = RecordingBaseRecord & {
|
||||
/** C200 — derived distinct labels; drives the card chip under a "Pessoa" filter. */
|
||||
speakerNames?: string[] | null
|
||||
/** C219 — classified topics; the card shows them as chips. */
|
||||
topics?: SpeechTopic[] | null
|
||||
}
|
||||
|
||||
export type RecordingDetailRecord = RecordingBaseRecord & {
|
||||
|
|
@ -55,6 +59,8 @@ export type RecordingListItemViewModel = RecordingViewModel & {
|
|||
excerpt: SpeechHighlightedExcerpt | null
|
||||
/** Selected "Pessoa" labels that this recording indeed contains. */
|
||||
matchedPersons: string[]
|
||||
/** C219 — classified topics with their pt-BR labels (card chips). */
|
||||
topics: { value: SpeechTopic; label: string }[]
|
||||
/**
|
||||
* Detail link that seeks the player to the matching segment when the search
|
||||
* found one (`?t=`), carrying the term for transcript highlighting (`?q=`).
|
||||
|
|
@ -148,6 +154,24 @@ const withSeek = (href: string, segment: RecordingSegmentRecord | undefined, que
|
|||
return queryString ? `${href}?${queryString}` : href
|
||||
}
|
||||
|
||||
/**
|
||||
* C219 — the first expanded theme term that actually surfaced this recording:
|
||||
* the passage that carries it, preferred for the excerpt so a theme result
|
||||
* shows why it appeared. Returns undefined when no theme term applies.
|
||||
*/
|
||||
const pickThemeSegment = (
|
||||
segments: readonly RecordingSegmentRecord[],
|
||||
themeTerms: readonly string[],
|
||||
): { term: string; segment: RecordingSegmentRecord } | undefined => {
|
||||
for (const term of themeTerms) {
|
||||
const trimmed = term.trim()
|
||||
if (!trimmed) continue
|
||||
const segment = pickMatchingSegment(segments, trimmed)
|
||||
if (segment) return { term: trimmed, segment }
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* List item of one recording. The excerpt only exists for a `ready` row and a
|
||||
* search term; the status cards of the other three states carry their own copy
|
||||
|
|
@ -157,20 +181,31 @@ export const toRecordingListItemViewModel = ({
|
|||
recording,
|
||||
matchedSegments,
|
||||
query,
|
||||
themeTerms = [],
|
||||
people,
|
||||
}: {
|
||||
recording: RecordingListRecord
|
||||
/** Segments that matched the query (or the row's first one as fallback). */
|
||||
matchedSegments: readonly RecordingSegmentRecord[]
|
||||
query?: string
|
||||
/** C219 — expanded theme terms; empty in the literal search. */
|
||||
themeTerms?: readonly string[]
|
||||
/** C200 — the selected "Pessoa" labels of the list state. */
|
||||
people?: readonly string[]
|
||||
}): RecordingListItemViewModel => {
|
||||
const base = toRecordingViewModel(recording)
|
||||
const isReady = base.status === 'ready'
|
||||
const q = query?.trim()
|
||||
const segment = isReady && q ? pickMatchingSegment(matchedSegments, q) : undefined
|
||||
const excerpt = segment ? buildHighlightedExcerpt(segment.text, q ?? '') : null
|
||||
const themeMatch = isReady ? pickThemeSegment(matchedSegments, themeTerms) : undefined
|
||||
const segment =
|
||||
themeMatch?.segment ?? (isReady && q ? pickMatchingSegment(matchedSegments, q) : undefined)
|
||||
// The theme passage highlights the whole phrase as one band (the per-term
|
||||
// split would break it into pieces), mirroring the speech acervo (C192).
|
||||
const excerpt = themeMatch
|
||||
? buildHighlightedExcerpt(themeMatch.segment.text, themeMatch.term, { phrase: true })
|
||||
: segment
|
||||
? buildHighlightedExcerpt(segment.text, q ?? '')
|
||||
: null
|
||||
const speakerNames = recording.speakerNames ?? []
|
||||
|
||||
return {
|
||||
|
|
@ -179,6 +214,7 @@ export const toRecordingListItemViewModel = ({
|
|||
matchedPersons: (people ?? []).filter((person) =>
|
||||
speakerNames.some((name) => speakerNameMatches(name, person)),
|
||||
),
|
||||
topics: (recording.topics ?? []).map((value) => ({ value, label: speechTopicLabels[value] })),
|
||||
watchHref: withSeek(base.detailHref, segment, q),
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import type { Payload } from 'payload'
|
|||
|
||||
const INSTAGRAM_API_BASE_URL = process.env.INSTAGRAM_API_BASE_URL ?? 'https://graph.instagram.com'
|
||||
|
||||
/** Page ceiling of one `/media` call: `maxResults` beyond it walks cursors. */
|
||||
export const INSTAGRAM_MAX_RESULTS_CAP = 50
|
||||
|
||||
type InstagramMediaType = 'IMAGE' | 'VIDEO' | 'REEL' | 'CAROUSEL_ALBUM'
|
||||
|
|
@ -138,14 +139,39 @@ export const pickInstagramThumbnail = (item: {
|
|||
}
|
||||
|
||||
/**
|
||||
* Parses a `/media` response into posts. Throws on a protocol-level violation
|
||||
* (no `data` array); individual malformed items are skipped, but an item
|
||||
* without an id, a timestamp or a permalink is dropped — it could not be
|
||||
* placed in the recency merge nor opened on the platform. A null caption is
|
||||
* kept: captionless posts (e.g. grid mosaics) still show with a fallback
|
||||
* title so the assessoria can exclude them item by item.
|
||||
* Hard ceiling of pages one feed load may walk (defensive): the Graph API
|
||||
* returns `limit` items per page, so a 500-media window needs 10 — 20 covers
|
||||
* it with room, and a pathological API that always answers a cursor cannot
|
||||
* loop forever.
|
||||
*/
|
||||
export const parseInstagramMediaResponse = (json: unknown): InstagramPost[] => {
|
||||
const INSTAGRAM_MAX_MEDIA_PAGES = 20
|
||||
|
||||
export type InstagramMediaPage = {
|
||||
posts: InstagramPost[]
|
||||
/** Cursor of the next page; undefined when the API did not offer one. */
|
||||
nextCursor?: string
|
||||
}
|
||||
|
||||
const nextCursorFrom = (json: unknown): string | undefined => {
|
||||
const paging = (json as { paging?: unknown }).paging
|
||||
if (!paging || typeof paging !== 'object') return undefined
|
||||
const cursors = (paging as { cursors?: unknown }).cursors
|
||||
if (!cursors || typeof cursors !== 'object') return undefined
|
||||
const after = (cursors as { after?: unknown }).after
|
||||
return typeof after === 'string' && after ? after : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses one `/media` page into posts plus the cursor of the next page. Throws
|
||||
* on a protocol-level violation (no `data` array); individual malformed items
|
||||
* are skipped, but an item without an id, a timestamp or a permalink is
|
||||
* dropped — it could not be placed in the recency merge nor opened on the
|
||||
* platform. A null caption is kept: captionless posts (e.g. grid mosaics)
|
||||
* still show with a fallback title so the assessoria can exclude them item by
|
||||
* item. Only the cursor is read from `paging`; `paging.next` (which carries
|
||||
* the access token in its URL) is deliberately ignored.
|
||||
*/
|
||||
export const parseInstagramMediaPage = (json: unknown): InstagramMediaPage => {
|
||||
if (!json || typeof json !== 'object') {
|
||||
throw new Error('Resposta de mídia do Instagram inválida')
|
||||
}
|
||||
|
|
@ -181,9 +207,13 @@ export const parseInstagramMediaResponse = (json: unknown): InstagramPost[] => {
|
|||
thumbnailUrl: pickInstagramThumbnail(rawItem),
|
||||
})
|
||||
}
|
||||
return posts
|
||||
return { posts, nextCursor: nextCursorFrom(json) }
|
||||
}
|
||||
|
||||
/** Posts of one `/media` page — the one-page convenience for non-paginating readers. */
|
||||
export const parseInstagramMediaResponse = (json: unknown): InstagramPost[] =>
|
||||
parseInstagramMediaPage(json).posts
|
||||
|
||||
/**
|
||||
* Keeps only the posts whose ids are not excluded, in API order (newest
|
||||
* first), capped at `maxItems`. The board skips an excluded post — it never
|
||||
|
|
@ -200,11 +230,15 @@ const jsonFrom = async (response: Response): Promise<unknown> => response.json()
|
|||
/**
|
||||
* Fetches the username and the latest media of a Business/Creator profile:
|
||||
* `GET /{userId}` for the username, then `GET /{userId}/media` for the posts
|
||||
* (permalink, caption, thumbnail, timestamp). On any failure it attempts one
|
||||
* token refresh (`refresh_access_token` — only mints/refreshes Instagram
|
||||
* Login tokens; page tokens from Facebook Login error out and the caller
|
||||
* falls back to the snapshot) and retries once. Throws when the retry also
|
||||
* fails so the cached wrapper can fail closed.
|
||||
* (permalink, caption, thumbnail, timestamp). `maxResults` is the TOTAL window
|
||||
* of posts: up to `INSTAGRAM_MAX_RESULTS_CAP` per page, walking the
|
||||
* `paging.cursors.after` cursor while the window is not filled — so a caller
|
||||
* asking for 50 makes exactly one call (the board's contract is untouched) and
|
||||
* a deeper window is an explicit opt-in. On any failure it attempts one token
|
||||
* refresh (`refresh_access_token` — only mints/refreshes Instagram Login
|
||||
* tokens; page tokens from Facebook Login error out and the caller falls back
|
||||
* to the snapshot) and retries once. Throws when the retry also fails so the
|
||||
* cached wrapper can fail closed.
|
||||
*/
|
||||
export const loadInstagramFeed = async ({
|
||||
accessToken,
|
||||
|
|
@ -223,17 +257,30 @@ export const loadInstagramFeed = async ({
|
|||
const userJson = (await jsonFrom(userResponse)) as { username?: unknown }
|
||||
const username = typeof userJson.username === 'string' ? userJson.username : null
|
||||
|
||||
const mediaParams = new URLSearchParams({
|
||||
fields: MEDIA_FIELDS,
|
||||
limit: String(Math.min(Math.max(maxResults, 1), INSTAGRAM_MAX_RESULTS_CAP)),
|
||||
access_token: token,
|
||||
})
|
||||
const mediaResponse = await fetchImpl(`${baseUrl}/${userId}/media?${mediaParams}`, { signal })
|
||||
if (!mediaResponse.ok) {
|
||||
throw await apiErrorFrom(mediaResponse)
|
||||
const pageSize = Math.min(Math.max(maxResults, 1), INSTAGRAM_MAX_RESULTS_CAP)
|
||||
const posts: InstagramPost[] = []
|
||||
let after: string | undefined
|
||||
for (let page = 0; page < INSTAGRAM_MAX_MEDIA_PAGES; page += 1) {
|
||||
const mediaParams = new URLSearchParams({
|
||||
fields: MEDIA_FIELDS,
|
||||
limit: String(pageSize),
|
||||
access_token: token,
|
||||
})
|
||||
if (after) mediaParams.set('after', after)
|
||||
const mediaResponse = await fetchImpl(`${baseUrl}/${userId}/media?${mediaParams}`, {
|
||||
signal,
|
||||
})
|
||||
if (!mediaResponse.ok) {
|
||||
throw await apiErrorFrom(mediaResponse)
|
||||
}
|
||||
|
||||
const parsed = parseInstagramMediaPage(await jsonFrom(mediaResponse))
|
||||
posts.push(...parsed.posts)
|
||||
if (posts.length >= maxResults || !parsed.nextCursor) break
|
||||
after = parsed.nextCursor
|
||||
}
|
||||
|
||||
return { username, posts: parseInstagramMediaResponse(await jsonFrom(mediaResponse)) }
|
||||
return { username, posts: posts.slice(0, maxResults) }
|
||||
}
|
||||
|
||||
try {
|
||||
|
|
|
|||
|
|
@ -45,6 +45,7 @@ const COVERAGE_QUERY = sql`
|
|||
)) AS "with_segments",
|
||||
COUNT(*) FILTER (WHERE s."audio_id" IS NULL AND s."youtube_url" IS NOT NULL) AS "fallback_youtube"
|
||||
FROM "speech" s
|
||||
WHERE s."origin" = 'camara'
|
||||
GROUP BY s."legislature"
|
||||
ORDER BY s."legislature" NULLS LAST
|
||||
`
|
||||
|
|
|
|||
|
|
@ -5,13 +5,22 @@ import type { Payload, RequiredDataFromCollectionSlug } from 'payload'
|
|||
import type { MergedSpeechFacets } from '@/lib/speechFacets'
|
||||
import { normalizeForSearch } from '@/lib/speechSearch'
|
||||
import type { Speech } from '@/payload-types'
|
||||
import { withPayloadTransaction } from '@/utilities/payloadTransaction'
|
||||
import {
|
||||
withPayloadTransaction,
|
||||
type PayloadTransactionRequest,
|
||||
} from '@/utilities/payloadTransaction'
|
||||
|
||||
/**
|
||||
* Idempotent persistence of one imported speech (C153). Identity is
|
||||
* `sourceKey`; metadata is refreshed on every run, segments are replaced only
|
||||
* when the caller supplies them, and a `manual` facet curation is never
|
||||
* overwritten. Everything runs in one transaction on the Payload session.
|
||||
*
|
||||
* C215 — the same owner persists the web speeches: the optional origin fields
|
||||
* (`origin: 'web'`, platform, canonical URL, title, channel and the mirrored
|
||||
* media) travel in the bundle. The web pipeline already holds a transaction
|
||||
* (media upload + upsert) and passes it via `options.req`; the Câmara path
|
||||
* passes nothing and keeps opening its own.
|
||||
*/
|
||||
|
||||
type SpeechSegmentInput = {
|
||||
|
|
@ -42,6 +51,15 @@ export type SpeechImportBundle = {
|
|||
excerptTMs: number | null
|
||||
vodPlaybackUrl: string | null
|
||||
vodDownloadUrl: string | null
|
||||
/** C215 — web origin metadata (undefined on the Câmara path). */
|
||||
origin?: Speech['origin']
|
||||
platform?: Speech['platform']
|
||||
externalId?: string | null
|
||||
sourceUrl?: string | null
|
||||
title?: string | null
|
||||
channel?: string | null
|
||||
mirroredMedia?: number | null
|
||||
thumbnail?: number | null
|
||||
/** Undefined preserves the stored facets (e.g. a run that skipped classification). */
|
||||
facets?: MergedSpeechFacets
|
||||
/** Undefined preserves the stored segments (e.g. `--skip-transcribe`). */
|
||||
|
|
@ -60,6 +78,12 @@ export type SpeechImportState = {
|
|||
summary: string | null
|
||||
officialTranscript: string | null
|
||||
officialTextUrl: string | null
|
||||
origin: Speech['origin']
|
||||
platform: Speech['platform'] | null
|
||||
externalId: string | null
|
||||
sourceUrl: string | null
|
||||
mirroredMedia: number | null
|
||||
thumbnail: number | null
|
||||
}
|
||||
|
||||
export type SpeechUpsertCounts = {
|
||||
|
|
@ -69,6 +93,10 @@ export type SpeechUpsertCounts = {
|
|||
manualFacetsPreserved: boolean
|
||||
}
|
||||
|
||||
/** Depth-0 upload relations arrive as the id; normalize for the state contract. */
|
||||
const mediaIdOf = (media: Speech['mirroredMedia']): number | null =>
|
||||
typeof media === 'object' && media !== null ? media.id : (media ?? null)
|
||||
|
||||
/** Current stored state of one speech, for the importer's skip decisions. */
|
||||
export const findSpeechImportState = async (
|
||||
payload: Payload,
|
||||
|
|
@ -89,6 +117,12 @@ export const findSpeechImportState = async (
|
|||
summary: true,
|
||||
officialTranscript: true,
|
||||
officialTextUrl: true,
|
||||
origin: true,
|
||||
platform: true,
|
||||
externalId: true,
|
||||
sourceUrl: true,
|
||||
mirroredMedia: true,
|
||||
thumbnail: true,
|
||||
},
|
||||
// Intentional bypass: the import CLI is a trusted actor with no session.
|
||||
overrideAccess: true,
|
||||
|
|
@ -115,152 +149,189 @@ export const findSpeechImportState = async (
|
|||
summary: speech.summary ?? null,
|
||||
officialTranscript: speech.officialTranscript ?? null,
|
||||
officialTextUrl: speech.officialTextUrl ?? null,
|
||||
origin: speech.origin,
|
||||
platform: speech.platform ?? null,
|
||||
externalId: speech.externalId ?? null,
|
||||
sourceUrl: speech.sourceUrl ?? null,
|
||||
mirroredMedia: mediaIdOf(speech.mirroredMedia),
|
||||
thumbnail: mediaIdOf(speech.thumbnail),
|
||||
}
|
||||
}
|
||||
|
||||
type SpeechWriteData = RequiredDataFromCollectionSlug<'speech'>
|
||||
|
||||
const metadataData = (
|
||||
bundle: SpeechImportBundle,
|
||||
): Omit<SpeechWriteData, 'sourceKey' | 'classifiedBy' | 'searchText'> => ({
|
||||
speechAt: bundle.speechAt,
|
||||
year: bundle.year,
|
||||
legislature: bundle.legislature,
|
||||
type: bundle.type,
|
||||
phase: bundle.phase,
|
||||
durationSeconds: bundle.durationSeconds,
|
||||
summary: bundle.summary,
|
||||
officialTranscript: bundle.officialTranscript,
|
||||
officialTextUrl: bundle.officialTextUrl,
|
||||
keywords: bundle.keywords,
|
||||
eventId: bundle.eventId,
|
||||
eventType: bundle.eventType,
|
||||
eventStartAt: bundle.eventStartAt,
|
||||
eventEndAt: bundle.eventEndAt,
|
||||
youtubeUrl: bundle.youtubeUrl,
|
||||
presidingOfficer: bundle.presidingOfficer,
|
||||
audioId: bundle.audioId,
|
||||
excerptTMs: bundle.excerptTMs,
|
||||
vodPlaybackUrl: bundle.vodPlaybackUrl,
|
||||
vodDownloadUrl: bundle.vodDownloadUrl,
|
||||
})
|
||||
type SpeechMetadataData = Omit<SpeechWriteData, 'sourceKey' | 'classifiedBy' | 'searchText'>
|
||||
|
||||
export const upsertSpeechBundle = async (
|
||||
const metadataData = (bundle: SpeechImportBundle): SpeechMetadataData => {
|
||||
const data: SpeechMetadataData = {
|
||||
origin: bundle.origin ?? 'camara',
|
||||
speechAt: bundle.speechAt,
|
||||
year: bundle.year,
|
||||
legislature: bundle.legislature,
|
||||
type: bundle.type,
|
||||
phase: bundle.phase,
|
||||
durationSeconds: bundle.durationSeconds,
|
||||
summary: bundle.summary,
|
||||
officialTranscript: bundle.officialTranscript,
|
||||
officialTextUrl: bundle.officialTextUrl,
|
||||
keywords: bundle.keywords,
|
||||
eventId: bundle.eventId,
|
||||
eventType: bundle.eventType,
|
||||
eventStartAt: bundle.eventStartAt,
|
||||
eventEndAt: bundle.eventEndAt,
|
||||
youtubeUrl: bundle.youtubeUrl,
|
||||
presidingOfficer: bundle.presidingOfficer,
|
||||
audioId: bundle.audioId,
|
||||
excerptTMs: bundle.excerptTMs,
|
||||
vodPlaybackUrl: bundle.vodPlaybackUrl,
|
||||
vodDownloadUrl: bundle.vodDownloadUrl,
|
||||
}
|
||||
|
||||
// Web-origin fields travel only when the caller supplied them: the Câmara
|
||||
// bundle omits them and Payload leaves the stored values untouched.
|
||||
if (bundle.platform !== undefined) data.platform = bundle.platform
|
||||
if (bundle.externalId !== undefined) data.externalId = bundle.externalId
|
||||
if (bundle.sourceUrl !== undefined) data.sourceUrl = bundle.sourceUrl
|
||||
if (bundle.title !== undefined) data.title = bundle.title
|
||||
if (bundle.channel !== undefined) data.channel = bundle.channel
|
||||
if (bundle.mirroredMedia !== undefined) data.mirroredMedia = bundle.mirroredMedia
|
||||
if (bundle.thumbnail !== undefined) data.thumbnail = bundle.thumbnail
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
export type SpeechUpsertOptions = {
|
||||
/** Existing transaction to ride (C215 media upload + upsert); absent opens one. */
|
||||
req?: PayloadTransactionRequest
|
||||
}
|
||||
|
||||
const upsertSpeechBundleInTransaction = async (
|
||||
payload: Payload,
|
||||
bundle: SpeechImportBundle,
|
||||
): Promise<SpeechUpsertCounts> =>
|
||||
withPayloadTransaction(payload, async ({ req }) => {
|
||||
const found = await payload.find({
|
||||
req: PayloadTransactionRequest,
|
||||
): Promise<SpeechUpsertCounts> => {
|
||||
const found = await payload.find({
|
||||
collection: 'speech',
|
||||
where: { sourceKey: { equals: bundle.sourceKey } },
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
select: { id: true, classifiedBy: true },
|
||||
req,
|
||||
// Intentional bypass: the import CLI is a trusted actor with no session.
|
||||
overrideAccess: true,
|
||||
})
|
||||
const current = found.docs[0]
|
||||
const manualFacetsPreserved = current?.classifiedBy === 'manual'
|
||||
|
||||
// C154 — the speech-level search text mirrors the segments and is owned by
|
||||
// this bundle: `segments: undefined` (skip/ASR failure) preserves whatever
|
||||
// is stored, exactly like the segments themselves.
|
||||
const segmentSearchText =
|
||||
bundle.segments === undefined
|
||||
? undefined
|
||||
: normalizeForSearch(bundle.segments.map((segment) => segment.text).join(' '))
|
||||
|
||||
const metadata = metadataData(bundle)
|
||||
const facets: Partial<SpeechWriteData> = {}
|
||||
if (bundle.facets && !manualFacetsPreserved) {
|
||||
const municipalitySlugs = bundle.facets.municipalities.map((entry) => entry.slug)
|
||||
const municipalities =
|
||||
municipalitySlugs.length === 0
|
||||
? []
|
||||
: (
|
||||
await payload.find({
|
||||
collection: 'municipality',
|
||||
where: { slug: { in: municipalitySlugs } },
|
||||
limit: municipalitySlugs.length,
|
||||
depth: 0,
|
||||
select: { slug: true },
|
||||
req,
|
||||
// Intentional bypass: resolving gazetteer slugs inside the import transaction.
|
||||
overrideAccess: true,
|
||||
})
|
||||
).docs
|
||||
facets.topics = bundle.facets.topics
|
||||
facets.scopes = bundle.facets.scopes
|
||||
facets.classifiedBy = bundle.facets.classifiedBy
|
||||
facets.mentionedMunicipalities = municipalities.map((doc) => doc.id)
|
||||
facets.mentionedPeople = bundle.facets.people
|
||||
facets.mentionedPrograms = bundle.facets.programs
|
||||
facets.mentionedProjects = bundle.facets.projects
|
||||
}
|
||||
const data = { ...metadata, ...facets }
|
||||
|
||||
let speechId: number
|
||||
let created = false
|
||||
if (current) {
|
||||
await payload.update({
|
||||
collection: 'speech',
|
||||
where: { sourceKey: { equals: bundle.sourceKey } },
|
||||
limit: 1,
|
||||
id: current.id,
|
||||
data: segmentSearchText === undefined ? data : { ...data, searchText: segmentSearchText },
|
||||
depth: 0,
|
||||
select: { id: true, classifiedBy: true },
|
||||
req,
|
||||
// Intentional bypass: the import CLI is a trusted actor with no session.
|
||||
overrideAccess: true,
|
||||
})
|
||||
const current = found.docs[0]
|
||||
const manualFacetsPreserved = current?.classifiedBy === 'manual'
|
||||
speechId = current.id
|
||||
} else {
|
||||
const speech = await payload.create({
|
||||
collection: 'speech',
|
||||
data: {
|
||||
sourceKey: bundle.sourceKey,
|
||||
classifiedBy: bundle.facets?.classifiedBy ?? 'gazetteer',
|
||||
searchText: segmentSearchText ?? '',
|
||||
...data,
|
||||
},
|
||||
depth: 0,
|
||||
req,
|
||||
// Intentional bypass: the import CLI is a trusted actor with no session.
|
||||
overrideAccess: true,
|
||||
})
|
||||
speechId = speech.id
|
||||
created = true
|
||||
}
|
||||
|
||||
// C154 — the speech-level search text mirrors the segments and is owned by
|
||||
// this bundle: `segments: undefined` (skip/ASR failure) preserves whatever
|
||||
// is stored, exactly like the segments themselves.
|
||||
const segmentSearchText =
|
||||
bundle.segments === undefined
|
||||
? undefined
|
||||
: normalizeForSearch(bundle.segments.map((segment) => segment.text).join(' '))
|
||||
let segmentsInserted = 0
|
||||
let segmentsDeleted = 0
|
||||
if (bundle.segments !== undefined) {
|
||||
const removed = await payload.delete({
|
||||
collection: 'speechSegment',
|
||||
where: { speech: { equals: speechId } },
|
||||
req,
|
||||
// Intentional bypass: replacing segments owned by the speech being imported.
|
||||
overrideAccess: true,
|
||||
})
|
||||
segmentsDeleted = removed.docs.length
|
||||
|
||||
const metadata = metadataData(bundle)
|
||||
const facets: Partial<SpeechWriteData> = {}
|
||||
if (bundle.facets && !manualFacetsPreserved) {
|
||||
const municipalitySlugs = bundle.facets.municipalities.map((entry) => entry.slug)
|
||||
const municipalities =
|
||||
municipalitySlugs.length === 0
|
||||
? []
|
||||
: (
|
||||
await payload.find({
|
||||
collection: 'municipality',
|
||||
where: { slug: { in: municipalitySlugs } },
|
||||
limit: municipalitySlugs.length,
|
||||
depth: 0,
|
||||
select: { slug: true },
|
||||
req,
|
||||
// Intentional bypass: resolving gazetteer slugs inside the import transaction.
|
||||
overrideAccess: true,
|
||||
})
|
||||
).docs
|
||||
facets.topics = bundle.facets.topics
|
||||
facets.scopes = bundle.facets.scopes
|
||||
facets.classifiedBy = bundle.facets.classifiedBy
|
||||
facets.mentionedMunicipalities = municipalities.map((doc) => doc.id)
|
||||
facets.mentionedPeople = bundle.facets.people
|
||||
facets.mentionedPrograms = bundle.facets.programs
|
||||
facets.mentionedProjects = bundle.facets.projects
|
||||
}
|
||||
const data = { ...metadata, ...facets }
|
||||
|
||||
let speechId: number
|
||||
let created = false
|
||||
if (current) {
|
||||
await payload.update({
|
||||
collection: 'speech',
|
||||
id: current.id,
|
||||
data: segmentSearchText === undefined ? data : { ...data, searchText: segmentSearchText },
|
||||
depth: 0,
|
||||
req,
|
||||
// Intentional bypass: the import CLI is a trusted actor with no session.
|
||||
overrideAccess: true,
|
||||
})
|
||||
speechId = current.id
|
||||
} else {
|
||||
const speech = await payload.create({
|
||||
collection: 'speech',
|
||||
data: {
|
||||
sourceKey: bundle.sourceKey,
|
||||
classifiedBy: bundle.facets?.classifiedBy ?? 'gazetteer',
|
||||
searchText: segmentSearchText ?? '',
|
||||
...data,
|
||||
},
|
||||
depth: 0,
|
||||
req,
|
||||
// Intentional bypass: the import CLI is a trusted actor with no session.
|
||||
overrideAccess: true,
|
||||
})
|
||||
speechId = speech.id
|
||||
created = true
|
||||
}
|
||||
|
||||
let segmentsInserted = 0
|
||||
let segmentsDeleted = 0
|
||||
if (bundle.segments !== undefined) {
|
||||
const removed = await payload.delete({
|
||||
for (const [index, segment] of bundle.segments.entries()) {
|
||||
await payload.create({
|
||||
collection: 'speechSegment',
|
||||
where: { speech: { equals: speechId } },
|
||||
data: {
|
||||
speech: speechId,
|
||||
order: index + 1,
|
||||
startSeconds: segment.startSeconds,
|
||||
endSeconds: segment.endSeconds,
|
||||
text: segment.text,
|
||||
searchText: normalizeForSearch(segment.text),
|
||||
},
|
||||
req,
|
||||
// Intentional bypass: replacing segments owned by the speech being imported.
|
||||
// Intentional bypass: the import CLI is a trusted actor with no session.
|
||||
overrideAccess: true,
|
||||
})
|
||||
segmentsDeleted = removed.docs.length
|
||||
|
||||
for (const [index, segment] of bundle.segments.entries()) {
|
||||
await payload.create({
|
||||
collection: 'speechSegment',
|
||||
data: {
|
||||
speech: speechId,
|
||||
order: index + 1,
|
||||
startSeconds: segment.startSeconds,
|
||||
endSeconds: segment.endSeconds,
|
||||
text: segment.text,
|
||||
searchText: normalizeForSearch(segment.text),
|
||||
},
|
||||
req,
|
||||
// Intentional bypass: the import CLI is a trusted actor with no session.
|
||||
overrideAccess: true,
|
||||
})
|
||||
segmentsInserted += 1
|
||||
}
|
||||
segmentsInserted += 1
|
||||
}
|
||||
}
|
||||
|
||||
return { created, segmentsInserted, segmentsDeleted, manualFacetsPreserved }
|
||||
})
|
||||
return { created, segmentsInserted, segmentsDeleted, manualFacetsPreserved }
|
||||
}
|
||||
|
||||
export const upsertSpeechBundle = async (
|
||||
payload: Payload,
|
||||
bundle: SpeechImportBundle,
|
||||
options: SpeechUpsertOptions = {},
|
||||
): Promise<SpeechUpsertCounts> => {
|
||||
if (options.req) return upsertSpeechBundleInTransaction(payload, bundle, options.req)
|
||||
return withPayloadTransaction(payload, ({ req }) =>
|
||||
upsertSpeechBundleInTransaction(payload, bundle, req),
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,7 +13,11 @@ import type { SpeechDurationBucket, SpeechListState } from '@/utilities/speech/s
|
|||
const DURATION_MEDIA_MIN_SECONDS = 120
|
||||
const DURATION_LONGA_MIN_SECONDS = 300
|
||||
|
||||
const durationBucketWhere = (bucket: SpeechDurationBucket): Where => {
|
||||
/**
|
||||
* The ONE duration-bucket predicate of the acervo: the recordings list (C219)
|
||||
* reuses it so the buckets can never diverge between the two sources.
|
||||
*/
|
||||
export const durationBucketWhere = (bucket: SpeechDurationBucket): Where => {
|
||||
switch (bucket) {
|
||||
case 'curta':
|
||||
return { durationSeconds: { less_than: DURATION_MEDIA_MIN_SECONDS } }
|
||||
|
|
@ -32,7 +36,9 @@ const durationBucketWhere = (bucket: SpeechDurationBucket): Where => {
|
|||
}
|
||||
|
||||
const buildSpeechFacetWhere = (state: SpeechListState): Where[] => {
|
||||
const filters: Where[] = []
|
||||
// C215 — this contract is the Câmara list: the web speeches share the table
|
||||
// but are served by their own source (C216), never mixed here.
|
||||
const filters: Where[] = [{ origin: { equals: 'camara' } }]
|
||||
|
||||
if (state.years?.length) filters.push({ year: { in: state.years } })
|
||||
if (state.topics?.length) filters.push({ topics: { in: state.topics } })
|
||||
|
|
|
|||
|
|
@ -19,6 +19,8 @@ import {
|
|||
firstValue,
|
||||
normalizedText,
|
||||
parseExhaustiveEnumParam,
|
||||
parseMunicipalityValues,
|
||||
parseYearValues,
|
||||
resolveListUrl,
|
||||
strictDecimalInteger,
|
||||
type RawSearchParams,
|
||||
|
|
@ -95,16 +97,6 @@ const speechScopeSet = new Set<string>(SPEECH_SCOPES.map(({ value }) => value))
|
|||
const speechDurationSet = new Set<string>(SPEECH_DURATION_BUCKETS.map(({ value }) => value))
|
||||
const MAX_PHASE_LENGTH = 80
|
||||
|
||||
const parseYearValues = (raw: string | string[] | undefined): number[] =>
|
||||
allParamValues(raw)
|
||||
.map((token) => strictDecimalInteger(token))
|
||||
.filter((year): year is number => year !== undefined && year >= 1900 && year <= 2100)
|
||||
|
||||
const parseMunicipalityValues = (raw: string | string[] | undefined): number[] =>
|
||||
allParamValues(raw)
|
||||
.map((token) => strictDecimalInteger(token))
|
||||
.filter((id): id is number => id !== undefined && id > 0)
|
||||
|
||||
/** Only `tema` is meaningful; anything else (and `termo`) means the default. */
|
||||
const parseSpeechSearchMode = (raw: string | string[] | undefined): SpeechSearchMode | undefined =>
|
||||
firstValue(raw) === 'tema' ? 'tema' : undefined
|
||||
|
|
|
|||
|
|
@ -91,6 +91,9 @@ const loadSpeechFilterOptions = async (
|
|||
depth: 0,
|
||||
limit: 0,
|
||||
pagination: false,
|
||||
// C215 — options are the Câmara catalog's; the web source (C216) builds
|
||||
// its own options from its rows.
|
||||
where: { origin: { equals: 'camara' } },
|
||||
select: { year: true, phase: true, mentionedMunicipalities: true },
|
||||
user,
|
||||
overrideAccess: false,
|
||||
|
|
|
|||
514
src/utilities/speech/webSpeechIngest.ts
Normal file
514
src/utilities/speech/webSpeechIngest.ts
Normal file
|
|
@ -0,0 +1,514 @@
|
|||
import 'server-only'
|
||||
|
||||
import { mkdtemp, readdir, readFile, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import {
|
||||
buildRecordingAudioFfmpegArgs,
|
||||
mergeChunkTranscriptions,
|
||||
RECORDING_AUDIO_CHUNK_SECONDS,
|
||||
type RecordingChunkTranscription,
|
||||
type RecordingTranscriptSegment,
|
||||
} from '@/lib/recordingTranscription'
|
||||
import type { SpeechFacetInput } from '@/lib/speechGazetteer'
|
||||
import {
|
||||
canonicalWebSpeechUrl,
|
||||
INTERNET_SPEECH_MEDIA_SLUG,
|
||||
isCompleteWebSpeechState,
|
||||
requiresDirectMediaUrl,
|
||||
webSpeechAtFromPublishedAt,
|
||||
webSpeechPlatformLabel,
|
||||
webSpeechSourceKey,
|
||||
type WebSpeechFinding,
|
||||
} from '@/lib/webSpeech'
|
||||
import {
|
||||
DEEPINFRA_TRANSCRIBE_COST_PER_MINUTE_USD,
|
||||
deepInfraTranscribeSegments,
|
||||
type TranscribeSegmentsResult,
|
||||
} from '@/utilities/ai/deepInfraTranscribe'
|
||||
import { downloadUrlToFile } from '@/utilities/media/downloadToFile'
|
||||
import { ffmpegBinary, messageOf, runFfmpeg } from '@/utilities/media/ffmpeg'
|
||||
import {
|
||||
downloadWithYtDlp,
|
||||
readYtDlpMetadata,
|
||||
resolveYtDlp,
|
||||
YTDLP_INSTALL_HINT,
|
||||
type YtDlpMetadata,
|
||||
} from '@/utilities/media/ytdlp'
|
||||
import { withPayloadTransaction } from '@/utilities/payloadTransaction'
|
||||
import {
|
||||
classifySpeech,
|
||||
type SpeechClassificationResult,
|
||||
} from '@/utilities/speech/speechClassifier'
|
||||
import {
|
||||
findSpeechImportState,
|
||||
upsertSpeechBundle,
|
||||
type SpeechImportBundle,
|
||||
} from '@/utilities/speech/speechImport'
|
||||
|
||||
/**
|
||||
* C215 — one web speech end to end: acquire the media (yt-dlp or direct HTTP),
|
||||
* transcribe with timestamps (the C199 chunk owner), classify (the C153 owner),
|
||||
* mirror the artifact in the private collection and upsert idempotently (the
|
||||
* Câmara import owner). Every dependency is injectable so the int specs run
|
||||
* offline; the CLI is the only caller.
|
||||
*/
|
||||
|
||||
/** Audio extraction has no duration to scale the timeout from; 30 min is ample. */
|
||||
const FFMPEG_TIMEOUT_MS = 30 * 60_000
|
||||
const ACQUISITION_FAILURE = 'Não foi possível baixar a mídia da fala.'
|
||||
const TRANSCRIPTION_FAILURE = 'Não foi possível transcrever a fala.'
|
||||
const MEDIA_FAILURE = 'Não foi possível guardar a mídia da fala.'
|
||||
const CLASSIFICATION_FAILURE = 'Não foi possível classificar a fala.'
|
||||
|
||||
type WebSpeechIngestStatus = 'created' | 'updated' | 'skipped' | 'failed'
|
||||
type WebSpeechIngestStage =
|
||||
| 'validation'
|
||||
| 'acquisition'
|
||||
| 'transcription'
|
||||
| 'classification'
|
||||
| 'media'
|
||||
| 'upsert'
|
||||
|
||||
export type WebSpeechIngestResult = {
|
||||
sourceKey: string
|
||||
status: WebSpeechIngestStatus
|
||||
stage: WebSpeechIngestStage | null
|
||||
error: string | null
|
||||
asrSeconds: number
|
||||
asrCostUsd: number
|
||||
llmCostUsd: number | null
|
||||
}
|
||||
|
||||
type WebSpeechAcquisition = {
|
||||
/** Produced file inside the temp dir, extension included. */
|
||||
fileName: string
|
||||
metadata: YtDlpMetadata | null
|
||||
}
|
||||
|
||||
export type WebSpeechAcquirer = (
|
||||
finding: WebSpeechFinding,
|
||||
tempDir: string,
|
||||
) => Promise<WebSpeechAcquisition>
|
||||
|
||||
export type WebSpeechTranscriber = (
|
||||
file: Blob,
|
||||
options?: { filename?: string },
|
||||
) => Promise<TranscribeSegmentsResult>
|
||||
|
||||
export type WebSpeechClassifier = (input: SpeechFacetInput) => Promise<SpeechClassificationResult>
|
||||
|
||||
export type WebSpeechIngestDeps = {
|
||||
acquire?: WebSpeechAcquirer
|
||||
transcribe?: WebSpeechTranscriber
|
||||
classify?: WebSpeechClassifier
|
||||
runFfmpeg?: typeof runFfmpeg
|
||||
downloadThumbnail?: (url: string, destinationPath: string) => Promise<void>
|
||||
}
|
||||
|
||||
class WebSpeechIngestError extends Error {
|
||||
readonly stage: WebSpeechIngestStage
|
||||
|
||||
constructor(stage: WebSpeechIngestStage, message: string) {
|
||||
super(message)
|
||||
this.stage = stage
|
||||
}
|
||||
}
|
||||
|
||||
const extensionOf = (url: string, fallback: string): string => {
|
||||
try {
|
||||
const name = new URL(url).pathname.split('/').pop() ?? ''
|
||||
const index = name.lastIndexOf('.')
|
||||
const extension = index >= 0 ? name.slice(index).toLowerCase() : ''
|
||||
return /^\.[a-z0-9]{1,5}$/.test(extension) ? extension : fallback
|
||||
} catch {
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
|
||||
/** yt-dlp for YouTube/Instagram; direct mediaUrl for radio/audio. */
|
||||
const defaultAcquire: WebSpeechAcquirer = async (finding, tempDir) => {
|
||||
if (requiresDirectMediaUrl(finding.platform)) {
|
||||
if (!finding.mediaUrl) throw new Error('Achado sem mediaUrl.')
|
||||
const fileName = `source${extensionOf(finding.mediaUrl, '.mp3')}`
|
||||
await downloadUrlToFile({ url: finding.mediaUrl, destinationPath: join(tempDir, fileName) })
|
||||
return { fileName, metadata: null }
|
||||
}
|
||||
|
||||
const resolved = await resolveYtDlp()
|
||||
if (!resolved.ok) throw new Error(`${resolved.reason}. ${YTDLP_INSTALL_HINT}`)
|
||||
|
||||
const metadata = await readYtDlpMetadata({ bin: resolved.bin, url: finding.url })
|
||||
await downloadWithYtDlp({
|
||||
bin: resolved.bin,
|
||||
url: finding.url,
|
||||
outputTemplate: join(tempDir, 'source.%(ext)s'),
|
||||
ffmpegLocation: ffmpegBinary(),
|
||||
})
|
||||
const fileName = (await readdir(tempDir)).find((name) => name.startsWith('source.'))
|
||||
if (!fileName) throw new Error('yt-dlp não produziu arquivo.')
|
||||
return { fileName, metadata }
|
||||
}
|
||||
|
||||
type BundleMetadata = {
|
||||
title?: string | null
|
||||
channel?: string | null
|
||||
externalId?: string | null
|
||||
durationSeconds?: number | null
|
||||
}
|
||||
|
||||
/**
|
||||
* The web bundle: Câmara-only fields stay null (no legislature, no VOD, no
|
||||
* official transcript) and the web metadata travels only when known —
|
||||
* `undefined` preserves the stored value on a metadata refresh.
|
||||
*/
|
||||
const baseBundle = (
|
||||
finding: WebSpeechFinding,
|
||||
sourceKey: string,
|
||||
speechAt: string,
|
||||
metadata: BundleMetadata,
|
||||
): SpeechImportBundle => ({
|
||||
sourceKey,
|
||||
origin: 'web',
|
||||
platform: finding.platform,
|
||||
externalId: metadata.externalId,
|
||||
sourceUrl: canonicalWebSpeechUrl(finding.platform, finding.url),
|
||||
title: metadata.title,
|
||||
channel: metadata.channel,
|
||||
speechAt,
|
||||
year: Number(speechAt.slice(0, 4)),
|
||||
legislature: null,
|
||||
type: null,
|
||||
phase: null,
|
||||
durationSeconds: metadata.durationSeconds ?? null,
|
||||
summary: null,
|
||||
officialTranscript: null,
|
||||
officialTextUrl: null,
|
||||
keywords: [],
|
||||
eventId: null,
|
||||
eventType: null,
|
||||
eventStartAt: null,
|
||||
eventEndAt: null,
|
||||
youtubeUrl: null,
|
||||
presidingOfficer: null,
|
||||
audioId: null,
|
||||
excerptTMs: null,
|
||||
vodPlaybackUrl: null,
|
||||
vodDownloadUrl: null,
|
||||
})
|
||||
|
||||
const emptyResult = (
|
||||
sourceKey: string,
|
||||
status: WebSpeechIngestStatus,
|
||||
stage: WebSpeechIngestStage | null,
|
||||
error: string | null,
|
||||
): WebSpeechIngestResult => ({
|
||||
sourceKey,
|
||||
status,
|
||||
stage,
|
||||
error,
|
||||
asrSeconds: 0,
|
||||
asrCostUsd: 0,
|
||||
llmCostUsd: null,
|
||||
})
|
||||
|
||||
type ExtractedTranscript = {
|
||||
segments: RecordingTranscriptSegment[]
|
||||
durationSeconds: number | null
|
||||
asrSeconds: number
|
||||
}
|
||||
|
||||
/** Extract → chunk → transcribe → merge (the C199 owners, relative offsets). */
|
||||
const extractTranscript = async ({
|
||||
ffmpeg,
|
||||
transcribe,
|
||||
inputPath,
|
||||
tempDir,
|
||||
declaredDuration,
|
||||
}: {
|
||||
ffmpeg: typeof runFfmpeg
|
||||
transcribe: WebSpeechTranscriber
|
||||
inputPath: string
|
||||
tempDir: string
|
||||
declaredDuration: number | null
|
||||
}): Promise<ExtractedTranscript> => {
|
||||
const outputPattern = join(tempDir, 'chunk-%03d.mp3')
|
||||
await ffmpeg(
|
||||
buildRecordingAudioFfmpegArgs({ inputPath, outputPattern }),
|
||||
declaredDuration ?? 0,
|
||||
TRANSCRIPTION_FAILURE,
|
||||
FFMPEG_TIMEOUT_MS,
|
||||
)
|
||||
const chunkFiles = (await readdir(tempDir)).filter((name) => /^chunk-\d+\.mp3$/.test(name)).sort()
|
||||
if (chunkFiles.length === 0) throw new Error(TRANSCRIPTION_FAILURE)
|
||||
|
||||
const chunks: RecordingChunkTranscription[] = []
|
||||
let asrSeconds = 0
|
||||
let measuredDuration = 0
|
||||
for (const [index, chunkFile] of chunkFiles.entries()) {
|
||||
const bytes = await readFile(join(tempDir, chunkFile))
|
||||
const result = await transcribe(new Blob([bytes], { type: 'audio/mpeg' }), {
|
||||
filename: chunkFile,
|
||||
})
|
||||
if (!result.ok) throw new Error(result.error)
|
||||
chunks.push({
|
||||
offsetSeconds: index * RECORDING_AUDIO_CHUNK_SECONDS,
|
||||
segments: result.segments,
|
||||
})
|
||||
asrSeconds += result.durationSeconds ?? RECORDING_AUDIO_CHUNK_SECONDS
|
||||
if (result.durationSeconds !== null) measuredDuration += result.durationSeconds
|
||||
}
|
||||
|
||||
const segments = mergeChunkTranscriptions(chunks)
|
||||
if (segments.length === 0) throw new Error(TRANSCRIPTION_FAILURE)
|
||||
|
||||
// Only measured data (or the declared duration / the last segment end) —
|
||||
// never the chunk count as a duration.
|
||||
const lastSegmentEnd = segments.at(-1)?.endSeconds
|
||||
const durationSeconds =
|
||||
measuredDuration > 0
|
||||
? Math.round(measuredDuration)
|
||||
: (declaredDuration ?? (lastSegmentEnd !== undefined ? Math.round(lastSegmentEnd) : null))
|
||||
|
||||
return { segments, durationSeconds, asrSeconds }
|
||||
}
|
||||
|
||||
/**
|
||||
* The artifact and the speech in ONE transaction (`req` threaded through the
|
||||
* upload and the upsert). Throws `WebSpeechIngestError('media')`; the caller
|
||||
* owns the best-effort cleanup of a thumbnail created before the failure.
|
||||
*/
|
||||
const persistIngestedSpeech = async ({
|
||||
payload,
|
||||
finding,
|
||||
sourceKey,
|
||||
speechAt,
|
||||
metadata,
|
||||
facets,
|
||||
segments,
|
||||
durationSeconds,
|
||||
inputPath,
|
||||
thumbnail,
|
||||
}: {
|
||||
payload: Payload
|
||||
finding: WebSpeechFinding
|
||||
sourceKey: string
|
||||
speechAt: string
|
||||
metadata: { title: string | null; channel: string | null; externalId: string | null }
|
||||
facets: SpeechClassificationResult['facets']
|
||||
segments: RecordingTranscriptSegment[]
|
||||
durationSeconds: number | null
|
||||
inputPath: string
|
||||
thumbnail: number | null
|
||||
}): Promise<void> => {
|
||||
const alt = `${webSpeechPlatformLabel(finding.platform)} — ${metadata.title ?? speechAt}`
|
||||
|
||||
try {
|
||||
await withPayloadTransaction(payload, async ({ req }) => {
|
||||
const media = await payload.create({
|
||||
collection: INTERNET_SPEECH_MEDIA_SLUG,
|
||||
data: { alt },
|
||||
filePath: inputPath,
|
||||
req,
|
||||
// Intentional bypass: the ingestion CLI is a trusted actor with no session.
|
||||
overrideAccess: true,
|
||||
})
|
||||
|
||||
await upsertSpeechBundle(
|
||||
payload,
|
||||
{
|
||||
...baseBundle(finding, sourceKey, speechAt, { ...metadata, durationSeconds }),
|
||||
facets,
|
||||
segments: segments.map((segment) => ({
|
||||
startSeconds: segment.startSeconds,
|
||||
endSeconds: segment.endSeconds,
|
||||
text: segment.text,
|
||||
})),
|
||||
mirroredMedia: media.id,
|
||||
thumbnail,
|
||||
},
|
||||
{ req },
|
||||
)
|
||||
})
|
||||
} catch (error) {
|
||||
throw new WebSpeechIngestError('media', messageOf(error, MEDIA_FAILURE))
|
||||
}
|
||||
}
|
||||
|
||||
export const ingestWebSpeech = async (
|
||||
payload: Payload,
|
||||
finding: WebSpeechFinding,
|
||||
{ reprocess = false, deps = {} }: { reprocess?: boolean; deps?: WebSpeechIngestDeps } = {},
|
||||
): Promise<WebSpeechIngestResult> => {
|
||||
const sourceKey = webSpeechSourceKey(finding)
|
||||
const speechAt = webSpeechAtFromPublishedAt(finding.publishedAt)
|
||||
if (!speechAt)
|
||||
return emptyResult(sourceKey, 'failed', 'validation', 'Data de publicação inválida.')
|
||||
|
||||
const acquire = deps.acquire ?? defaultAcquire
|
||||
const transcribe = deps.transcribe ?? deepInfraTranscribeSegments
|
||||
const classify = deps.classify ?? classifySpeech
|
||||
const ffmpeg = deps.runFfmpeg ?? runFfmpeg
|
||||
const downloadThumbnail =
|
||||
deps.downloadThumbnail ??
|
||||
((url, destinationPath) => downloadUrlToFile({ url, destinationPath }))
|
||||
|
||||
let asrSeconds = 0
|
||||
let tempDir: string | null = null
|
||||
|
||||
try {
|
||||
const state = await findSpeechImportState(payload, sourceKey)
|
||||
|
||||
if (isCompleteWebSpeechState(state) && !reprocess) {
|
||||
// Complete row: refresh only the metadata the finding brought (undefined
|
||||
// preserves the stored values); never re-download or re-transcribe.
|
||||
await upsertSpeechBundle(
|
||||
payload,
|
||||
baseBundle(finding, sourceKey, speechAt, {
|
||||
title: finding.title,
|
||||
channel: finding.channel,
|
||||
externalId: finding.externalId,
|
||||
durationSeconds: finding.durationSeconds ?? state?.durationSeconds ?? undefined,
|
||||
}),
|
||||
)
|
||||
return emptyResult(sourceKey, 'skipped', null, null)
|
||||
}
|
||||
|
||||
tempDir = await mkdtemp(join(tmpdir(), 'web-speech-'))
|
||||
let acquisition: WebSpeechAcquisition
|
||||
try {
|
||||
acquisition = await acquire(finding, tempDir)
|
||||
} catch (error) {
|
||||
throw new WebSpeechIngestError('acquisition', messageOf(error, ACQUISITION_FAILURE))
|
||||
}
|
||||
|
||||
const inputPath = join(tempDir, acquisition.fileName)
|
||||
const metadata = acquisition.metadata
|
||||
const title = finding.title ?? metadata?.title ?? null
|
||||
const channel = finding.channel ?? metadata?.channel ?? null
|
||||
const externalId = finding.externalId ?? metadata?.externalId ?? null
|
||||
const declaredDuration = finding.durationSeconds ?? metadata?.durationSeconds ?? null
|
||||
const thumbnailUrl = finding.thumbnailUrl ?? metadata?.thumbnailUrl ?? null
|
||||
|
||||
let extracted: ExtractedTranscript
|
||||
try {
|
||||
extracted = await extractTranscript({
|
||||
ffmpeg,
|
||||
transcribe,
|
||||
inputPath,
|
||||
tempDir,
|
||||
declaredDuration,
|
||||
})
|
||||
} catch (error) {
|
||||
throw new WebSpeechIngestError('transcription', messageOf(error, TRANSCRIPTION_FAILURE))
|
||||
}
|
||||
asrSeconds = extracted.asrSeconds
|
||||
|
||||
let classification: SpeechClassificationResult
|
||||
try {
|
||||
classification = await classify({
|
||||
transcript: extracted.segments.map((segment) => segment.text).join(' '),
|
||||
summary: title,
|
||||
keywords: [],
|
||||
})
|
||||
} catch (error) {
|
||||
throw new WebSpeechIngestError('classification', messageOf(error, CLASSIFICATION_FAILURE))
|
||||
}
|
||||
|
||||
// Thumbnail is best effort and lives OUTSIDE the main transaction: a broken
|
||||
// image (or a failed upload) must never lose the speech.
|
||||
let thumbnailId: number | null = null
|
||||
if (thumbnailUrl) {
|
||||
try {
|
||||
const destination = join(tempDir, `thumbnail${extensionOf(thumbnailUrl, '.jpg')}`)
|
||||
await downloadThumbnail(thumbnailUrl, destination)
|
||||
const thumbnail = await payload.create({
|
||||
collection: INTERNET_SPEECH_MEDIA_SLUG,
|
||||
data: { alt: `Capa — ${title ?? speechAt}` },
|
||||
filePath: destination,
|
||||
// Intentional bypass: the ingestion CLI is a trusted actor with no session.
|
||||
overrideAccess: true,
|
||||
})
|
||||
thumbnailId = thumbnail.id
|
||||
} catch {
|
||||
thumbnailId = null
|
||||
}
|
||||
}
|
||||
|
||||
const previousThumbnail = state?.thumbnail ?? null
|
||||
const previousMediaIds = [
|
||||
...(typeof state?.mirroredMedia === 'number' ? [state.mirroredMedia] : []),
|
||||
// Only a replaced thumbnail is deleted; keeping it is the fallback when
|
||||
// the new download failed.
|
||||
...(thumbnailId !== null && typeof previousThumbnail === 'number' ? [previousThumbnail] : []),
|
||||
]
|
||||
|
||||
try {
|
||||
await persistIngestedSpeech({
|
||||
payload,
|
||||
finding,
|
||||
sourceKey,
|
||||
speechAt,
|
||||
metadata: { title, channel, externalId },
|
||||
facets: classification.facets,
|
||||
segments: extracted.segments,
|
||||
durationSeconds: extracted.durationSeconds,
|
||||
inputPath,
|
||||
thumbnail: thumbnailId ?? previousThumbnail,
|
||||
})
|
||||
} catch (error) {
|
||||
if (thumbnailId !== null) {
|
||||
await payload
|
||||
.delete({
|
||||
collection: INTERNET_SPEECH_MEDIA_SLUG,
|
||||
id: thumbnailId,
|
||||
// Intentional bypass: the pipeline cleans up the file it just created.
|
||||
overrideAccess: true,
|
||||
})
|
||||
.catch(() => undefined)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
|
||||
// Replaced artifacts are removed best effort: an orphan object in the
|
||||
// private bucket is harmless, a leaked row is not.
|
||||
if (previousMediaIds.length > 0) {
|
||||
await payload
|
||||
.delete({
|
||||
collection: INTERNET_SPEECH_MEDIA_SLUG,
|
||||
where: { id: { in: previousMediaIds } },
|
||||
// Intentional bypass: the pipeline replaces the files it owns.
|
||||
overrideAccess: true,
|
||||
})
|
||||
.catch(() => undefined)
|
||||
}
|
||||
|
||||
return {
|
||||
sourceKey,
|
||||
status: state ? 'updated' : 'created',
|
||||
stage: null,
|
||||
error: null,
|
||||
asrSeconds,
|
||||
asrCostUsd: (asrSeconds * DEEPINFRA_TRANSCRIBE_COST_PER_MINUTE_USD) / 60,
|
||||
llmCostUsd: classification.llm.estimatedCostUsd,
|
||||
}
|
||||
} catch (error) {
|
||||
const asrCostUsd = (asrSeconds * DEEPINFRA_TRANSCRIBE_COST_PER_MINUTE_USD) / 60
|
||||
if (error instanceof WebSpeechIngestError) {
|
||||
return {
|
||||
...emptyResult(sourceKey, 'failed', error.stage, error.message),
|
||||
asrSeconds,
|
||||
asrCostUsd,
|
||||
}
|
||||
}
|
||||
return {
|
||||
...emptyResult(sourceKey, 'failed', null, messageOf(error, 'Falha na ingestão da fala.')),
|
||||
asrSeconds,
|
||||
asrCostUsd,
|
||||
}
|
||||
} finally {
|
||||
if (tempDir) await rm(tempDir, { recursive: true, force: true }).catch(() => undefined)
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue