mirror of
https://github.com/fsolla/teqo.git
synced 2026-12-01 12:03:06 +00:00
Compare commits
8 commits
ca843fb4bb
...
0a8b0774d3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0a8b0774d3 | ||
|
|
8d61b4183f | ||
|
|
33a1d10c09 | ||
|
|
94d1ca3364 | ||
|
|
f2b5ec0e5c | ||
|
|
90768be1cf | ||
|
|
cd4942d9e2 | ||
|
|
77e7b0efde |
87 changed files with 29272 additions and 2031 deletions
|
|
@ -6,13 +6,17 @@ The public album over the private archive (`archivePhoto`, C231/C232): **only `p
|
|||
|
||||
The album global `photoAlbum` holds the two product knobs: `published` (kill switch — **only `false` closes**; an absent row means the schema default `true`) and `removalChannelUrl` (the visible "é você nesta foto? peça a remoção" channel, never invented in code). Publishing the album or approving a photo **requires a valid channel** (fail-closed guard in the global and in the collection); the album has no `loading.tsx` on purpose — a Suspense boundary would turn the closed album's `notFound()` into a `200`. The "Fotos" discovery link in `CampaignFooter` appears while there are approved photos (and always on `/fotos` itself).
|
||||
|
||||
## Selfie search (`/fotos/encontre`) — C234
|
||||
## Selfie search (`/fotos/encontre`) — C234/C242
|
||||
|
||||
The visitor's photo never leaves their device: the browser runs the face-api nets locally (models served same-origin from `/fotos/modelos`, copied by `scripts/copy-face-vision-assets.mjs` in prebuild/predev/Docker) and posts only the 128-float descriptor to `POST /api/fotos/selfie` (`{ vector, intent: 'search' | 'leave-index' }`, JSON ≤4 KB, same-origin, rate-limited 20/10 min per hashed IP with its own key namespace). The answer is a list of **approved** photos (`{ ok, found, photos }`), never a score, a percentage or a third-party name — the view model (`src/lib/faceSearch.ts` `toFaceSearchPhotoView`) has no such fields by shape. Recusals: 400 body, 403 origin, 429 throttle, 404 when `photoAlbum.published === false` or `selfieSearchEnabled !== true`, 503 when the query Consent is missing.
|
||||
The visitor's photo never leaves their device: the browser runs the face-api nets locally (models served same-origin from `/fotos/modelos`, copied by `scripts/copy-face-vision-assets.mjs` in prebuild/predev/Docker) and posts only the 128-float descriptor to `POST /api/fotos/selfie` (`{ vector, intent: 'search' | 'leave-index' }`, JSON ≤4 KB, same-origin, rate-limited 20/10 min per hashed IP with its own key namespace). The answer is a list of **approved** photos (`{ ok, found, photos }`), never a score, a percentage or a third-party name — the view model (`src/lib/faceSearch.ts` `toFaceSearchPhotoView`) has no such fields by shape. Recusals: 400 body, 403 origin, 429 throttle, 404 when `photoAlbum.published === false` or `selfieSearchEnabled !== true`, 503 when either Consent is missing. Since C243 the public homepage carries a conditional discovery section (`SelfieSearchHomeSection`) that only presents and links — no capture/engine there.
|
||||
|
||||
**The index is A/C by gate decision (PR #1370): only people who adhered and consented are searchable; there is no anonymous face index of the archive (that is option B, gated on DPIA + legal review).** Enrollment and indexing are ops-only CLIs (`pnpm faces:enroll`, `pnpm faces:index --apply|--verify`), run from the maintenance service with the same write guards as C231/C232 (`TEQO_ENV`, `FACE_*_CONFIRM=1`, mirrored `S3_*`). The batch computes descriptors transiently and persists only the photo↔subject links (`faceSubject.matchedPhotos`) plus the `archivePhoto.faces.checkedKey` marker (model + each subject's `enrolledAt`, so the batch's own writes never invalidate it). The CLI engine (`scripts/lib/faceEngine.mjs`) loads the same nets from `node_modules`; a model change invalidates the index (re-enroll + `--refresh`).
|
||||
**The index is scope B (owner decision, 2026-10-01, supersedes the A/C gate of PR #1370): an anonymous descriptor index of the approved archive, so ANY visitor can find themselves.** The batch (`pnpm faces:index --apply|--verify`, maintenance service with the C231/C232 write guards) downloads each approved photo, detects faces with the same engine and persists identity-free rows in `archivePhotoFace` (photo + 128-float vector + model); `archivePhoto.faces.checkedKey` stores only the model, so a model change marks everything stale. There is no enrollment and no per-person consent: the `Consent` rows are the visitor's query consent and the public index notice. The rows die with the public status — the collection hooks purge them when a photo stops being `approved` or is deleted (plus the FK `ON DELETE CASCADE`) — and the answer always intersects with the C233 approved read. The CLI engine (`scripts/lib/faceEngine.mjs`) loads the same nets from `node_modules`.
|
||||
|
||||
Both sides are **fail-closed**: `selfieSearchEnabled` defaults to `false`, and the two Consent keys (`busca-selfie-fotos` for the query, `busca-selfie-indice` for enrollment, in `src/lib/campaignConsentKeys.ts`) are never seeded — without the admin row with the exact key the page renders the closed state and the API refuses. Editing the enrollment text makes every subject ineligible until re-consent (`consentHash` snapshot). Opt-out is self-service ("Minha presença" → face match removes the vector and the links, status `removed`); photo takedown keeps using `photoAlbum.removalChannelUrl`. E2E builds stub the engine with `NEXT_PUBLIC_FACE_SEARCH_STUB=1` (`window.__faceSearchStub`); the real engine is exercised by the CLI canary and manually. Runbook: `docs/ops/teqo-1313-deploy.md` §C234.
|
||||
Both sides are **fail-closed**: `selfieSearchEnabled` defaults to `false`; the two Consent keys (`busca-selfie-fotos` query consent, `busca-selfie-indice` public index notice, in `src/lib/campaignConsentKeys.ts`) are provisioned by `pnpm seed:face-consents` from the texts versioned in `scripts/lib/faceConsentTexts.mjs` — without both admin rows the page renders the closed state and the API refuses. Opt-out is self-service ("Minha presença" → face match deletes the matching descriptors, so the face stops answering); photo takedown keeps using `photoAlbum.removalChannelUrl`. Opening the surface also requires approving the archive (`pnpm archive:publish`, bulk `draft → approved`, never touching `removed`). E2E builds stub the engine with `NEXT_PUBLIC_FACE_SEARCH_STUB=1` (`window.__faceSearchStub`); the real engine is exercised by the CLI canary and manually. Runbook: `docs/ops/teqo-1313-deploy.md` §C242.
|
||||
|
||||
## Home Plenária section (S44)
|
||||
|
||||
The campaign home carries a section for the Plenária da Vitória right after the hero. It is driven by **one fixed share link** (`SHARE_LINK_HOME_SECTION_SLUG = 'plenaria-vitoria'`, `src/lib/shareLinkHomeSection.ts`) — no CMS field, no migration: the link itself remains the owner of the title, description, image, date and destination pool. `loadShareLinkHomeSection` (`src/utilities/shareLinkReads.ts`) reads it under the same cached `shareLinks` tag as the announcement page (unpublish pulls the section without a deploy) and fails closed: no published link, no valid `startsAt`, or `now >= endsAt` (else `startsAt` + 2h) → the section is absent from the HTML. While the window is open the client island (`ShareLinkHomeSection`) renders the invitation — image + the S29 agenda, **never an entry button**; once a destination is on air the poll (shared hook `useShareLinkLiveTarget`, activation-only, 30s, paused on hidden tabs) swaps the image for the official `youtube-nocookie` player (video id derived from the link's pre-registered YouTube destination) and the entry CTA takes the agenda's place, always pointing to `/plenaria-vitoria` (never the raw Meet/YouTube URL) with the label by host (`Entrar na plenária` on Meet, `Assistir no YouTube` on YouTube). The island also hides itself at the exact window close, covering open tabs over the ISR-stale HTML. No data collection, no Consent, no PII.
|
||||
|
||||
## Posts & Tags (news / publications)
|
||||
|
||||
|
|
|
|||
|
|
@ -294,6 +294,8 @@ This file is the living owner of Teqo's visual decisions — a working document,
|
|||
|
||||
**Multi-media content gallery (C240, 2026-10-01).** A public piece with multiple media uses one stable stage plus position (“N de M”), previous/next controls, and a horizontally scrollable thumbnail strip; never shrink every thumbnail to force the whole set on screen. Download belongs to the selected media, while the single primary action shares the official source post — do not offer an ambiguous “download all” or make media-sharing compete with the source link. Partial arrival is an internal neutral processing state; the public gallery appears only when the complete set is ready. This keeps the action model honest across image-only, mixed video, and large carousels without inventing a second album product.
|
||||
|
||||
**Public light-surface focus separation (C243, 2026-10-01).** When the campaign-yellow focus outline sits on a cream, white, or yellow-tinted public surface, keep the 3px yellow signal but add a dark blue outer separator. Yellow alone does not separate reliably from these backgrounds; the second edge preserves the archive's established focus identity while making keyboard location unmistakable without turning blue into a competing action color.
|
||||
|
||||
How rules change:
|
||||
|
||||
- **Decide, then update the owner.** When a better pattern wins — anti-slop review (`design-taste-frontend` / `gpt-taste`), a reference study (`awesome-design-md`), a redesign pass (`redesign-existing-projects`), or implementation judgment — update this file in the **same change** and say why. A pattern that only lives in code or in an agent's head is drift, not design.
|
||||
|
|
|
|||
|
|
@ -14,6 +14,8 @@ CI (`ci-pr.yml`) is a **single sequential job `checks`** (OPS62 X1): guards →
|
|||
|
||||
**Local e2e (OPS72 — skill step, discretionary):** before push, run the e2e specs you created + the same affected surface — `pnpm test:e2e:affected` runs `e2e-affected.mjs` against `origin/main`, migrates/seeds, then `pnpm test:e2e` with the selected specs (full suite on high-risk diffs). High-risk diffs diverge from PR CI by design: the PR runs no e2e (selected only, never full) and the local mirror runs the full suite. Forward extra Playwright args after `--` for a narrowed repro. Opt into production mode with `E2E_PROD=1 pnpm test:e2e:affected` (CI and prod mode serve the production build via `pnpm start`; plain local runs use `pnpm dev` — dev-mode flakes like cold-compile timeouts and dev-only console warnings do not reproduce in prod mode).
|
||||
|
||||
**Calendar day-cell clicks (miss #55, 2026-10-01):** click a calendar day cell through its stable contract — `calendarDaySelector(civilDate)` → `[data-day="DD/MM/YYYY"]` (`tests/e2e/helpers/agendaPeriodLabels.ts`) — never through the accessible name. date-fns formats the label as `"d de mês de ano"`, which is a substring of `"1d…"/"2d… de mês de ano"` in the same grid, and Playwright's name matcher is substring + case-insensitive by default: `"2 de outubro de 2026"` resolves to days 2, 12 and 22 (strict mode violation). The bug is date-dependent — it only fires when the target lands on day 01–09 of the month (the C104 spec picks today + 1). The `e2eNavigationConventions` unit guard fails the build on name-based day clicks.
|
||||
|
||||
**Navigation discipline in e2e (miss #54, 2026-07-30):** `page.goto` is for cold loads and URL contracts (deep links, redirects, legacy params); when the scenario is _continuity inside the authenticated shell_ — especially after a heavy list route — navigate in-shell instead (sidebar links, buttons, form submits), the way the user does. Never fire two `page.goto` back-to-back with nothing settling the first navigation (an `await expect(...)`, `waitForURL`, or interaction): the second aborts the first's in-flight RSC fetch (`net::ERR_ABORTED`, measured in `campaignSavedFilters`). The `e2eNavigationConventions` unit guard fails the build on unsettled goto pairs. Two sibling rules of the same family: wait for **interactive state** before clicking dynamic controls — `toBeVisible` proves SSR paint, not hydration (pre-hydration clicks no-op silently; `checkRadixWhenHydrated` is the precedent, P3-C class) — and gate WebAuthn ceremonies on `expectCampaignBiometricsReady` before the island's one-shot probe runs (miss #53). **Dev-mode caveat (closed 2026-08-10, P4-L/OPS30):** `campaignLeaderships`' chip-cell spec was failing deterministically under `pnpm dev` before B34 rewrote it; with the OPS30 prewarm/login hardening it ran ×3 green in dev + ×1 `E2E_PROD=1` (evidence in TECH-DEBT).
|
||||
|
||||
## Minimal test database (`pnpm db:seed:minimal`)
|
||||
|
|
|
|||
1
docs/changelog/2026-10-01-c242-c243.md
Normal file
1
docs/changelog/2026-10-01-c242-c243.md
Normal file
|
|
@ -0,0 +1 @@
|
|||
**C242/C243 — busca por selfie aberta a qualquer visitante (escopo B) + seção na homepage (2026-10-01):** o C234 entregou a busca **fechada** e no escopo A/C (só quem era inscrito pela assessoria se achava); por decisão do dono na sessão de 2026-10-01, com aval jurídico declarado, o escopo do gate (PR #1370) foi reaberto para **B**: o índice passa a ser **anônimo** — descritores 128-d extraídos dos rostos das fotos **aprovadas** do acervo, persistidos sem nome e sem vínculo com pessoa na collection nova `archivePhotoFace` (`admin.hidden`, admin-only), para que **qualquer visitante** encontre as próprias fotos. O enrollment A/C morre (collection `faceSubject`, `pnpm faces:enroll` e a adesão por pessoa foram removidos; migration `20261001_040904_add_archive_photo_face` cria a tabela nova com FK `ON DELETE CASCADE`, dropa a antiga — 0 linhas em produção — e o gerador reordenado à mão para o `CASCADE` do drop não engolir o `DROP CONSTRAINT`). O lote `pnpm faces:index` agora **persiste** os descritores (transação por foto substitui as linhas + marker `faces.checkedKey` = modelo); desaprovar/remover/deletar foto apaga os descritores nos hooks da collection (e o FK cobre SQL direto); o endpoint `POST /api/fotos/selfie` casa o vetor da consulta contra o índice carregado em memória (TTL 60 s, `Float32Array`, teto defensivo) e devolve só a interseção com o read aprovado do C233 — sem score, sem nome de terceiro; `leave-index` apaga os descritores que casarem (opt-out de fato). **Fail-closed mantido:** `selfieSearchEnabled` segue `false`, e os dois Consentimentos continuam obrigatórios — `busca-selfie-fotos` (consentimento da consulta, reescrito) e `busca-selfie-indice` (reclassificado como **aviso público do índice**, sem `consentHash`/elegibilidade por pessoa), com os textos versionados em `scripts/lib/faceConsentTexts.mjs` e provisionados por `pnpm seed:face-consents` (guarda `TEQO_ENV`/`FACE_CONSENT_SEED_CONFIRM`); a página exige os dois e mostra o aviso completo em `<details>`. Ops ganhou `pnpm archive:publish` (lote `draft → approved`, nunca toca `removed`, exige canal de remoção válido, guardas + recibo) para as 6.492 fotos nunca publicadas; o runbook §C242 documenta a abertura na ordem (canal → consentimentos → lote → indexação → flag) e o rollback. **C243:** a homepage pública ganha a seção condicional `SelfieSearchHomeSection` (design hi-fi `docs/plans/busca-selfie-secao-home-ui-design.html`, cenas 390/1280) entre a Central e a newsletter — só apresenta e linka (sem engine/captura/fotos/contadores na home), renderizada apenas com álbum publicado + flag + fotos aprovadas (fail-closed: fechada não deixa CTA morto). Copy do fluxo/entrada atualizada para o escopo B (o artefato `busca-fotos-por-selfie-ui-design.html` foi estendido pelo `designer`, que também atualizou `DESIGN.md` §7). Provas: unit 456 arquivos/5.050 testes verdes (novos: `findFaceDescriptorPhotoIds`, planos dos CLIs, textos de consentimento, gating da home), int full verde 109 arquivos/1.075 testes (índice/purges/endpoint/opt-out/rate limit), e2e `frontendFotosSelfie` atualizado (descritores em vez de subjects; opt-out por linhas; seção da home aberta/fechada). Pendente de ops (pós-deploy): canal de remoção, `seed:face-consents --apply`, `archive:publish --apply` + bust da tag, `faces:index --apply` e a flag. Planos: `docs/plans/busca-selfie-escopo-b.md`/`-impl.md` e `docs/plans/busca-selfie-secao-home.md`/`-impl.md`.
|
||||
|
|
@ -0,0 +1 @@
|
|||
**Fix CI — clique no dia do calendário pelo nome acessível derrubava o verify do deploy (C104, miss #55) (2026-10-01):** o `verify` do deploy ficou vermelho em 2026-10-01 (runs `36816518055` e `36820002374`; Issue #1406, auto-unblock) porque o e2e do C104 clicava a célula de término com `getByRole('button', { name: '2 de Outubro de 2026' })` e o matcher de nome do Playwright é substring + case-insensitive: o nome acessível real do react-day-picker pt-BR ("sexta-feira, 2 de outubro de 2026") casa também com os dias 12 e 22 do mesmo grid — `strict mode violation ... resolved to 3 elements` nas 3 tentativas. A classe só dispara quando hoje + 1 cai em dia 01–09, por isso passou desde o C134 (commit `fe0a7999`), que removeu a data fixa do C104 mas manteve o clique pelo nome; a primeira detecção (#1401) foi fechada sem PR de fix. O run vermelho segurava a lane e os merges seguintes tiveram o deploy preflight-skipped (`77e7b0ef`, `cd4942d9`) — deploy do main bloqueado, sem impacto em produção (o `verify` roda antes de publicar). O fix troca o clique pelo contrato estável do Calendar, `calendarDaySelector(civilDate)` → `[data-day="DD/MM/YYYY"]` (novo helper em `tests/e2e/helpers/agendaPeriodLabels.ts`, aditivo), e adiciona o guard miss #55 no `e2eNavigationConventions`, que varre todos os `tests/e2e/**/*.e2e.spec.ts` e falha o build em clique de célula de dia por nome (mais o teste do contrato zero-padded), além do parágrafo de convenção no `docs/TESTING.md`; sem mudança de schema/produto. Provas: repro local falha sem o fix com o mesmo strict mode violation, o guard falha com o spec antigo (offender `tests/e2e/campaignActivity.e2e.spec.ts:355`), e2e C104 1 passed (1.4m, dev) e `pnpm gate:fast` verde (458 arquivos / 5.071 testes; os 7 flaky do run passaram no retry, sem relação causal com o diff). PR #1407; a confirmação é o `verify` verde no deploy pós-merge e produção depende do approve humano (não aprovado por esta sessão).
|
||||
1
docs/changelog/2026-10-01-s44.md
Normal file
1
docs/changelog/2026-10-01-s44.md
Normal file
|
|
@ -0,0 +1 @@
|
|||
**S44 — Home: seção da Plenária da Vitória (divulgação e acesso) (2026-10-01):** a home pública ganha a seção da Plenária da Vitória logo depois do hero, dirigida por **um share link fixo** (`SHARE_LINK_HOME_SECTION_SLUG = 'plenaria-vitoria'`, `src/lib/shareLinkHomeSection.ts`) — sem campo/global novo, sem migration: o link continua dono de título, descrição, imagem, data e destinos. `loadShareLinkHomeSection` (`src/utilities/shareLinkReads.ts`) lê sob a mesma tag cacheada `shareLinks` do anúncio (despublicar tira a seção sem deploy) e **falha fechado**: sem link publicado, sem `startsAt` válido ou `agora >= endsAt` (senão `startsAt` + 2h, mesma convenção do S29) → `null`, a seção não existe no HTML; a ilha também se esconde no instante exato do fim da janela (timeout único, re-arma acima do teto do `setTimeout`), cobrindo abas abertas sobre o HTML ISR defasado. A ilha `ShareLinkHomeSection` porta o artefato `docs/plans/secao-home-plenaria-da-vitoria-ui-design.html` (cenas 01–06): **pré-live** = imagem quadrada + data/hora da Bahia + `Online` + **`Adicionar à agenda`** (a agenda do S29; `ShareLinkAgendaMenu` ganhou `triggerClassName` para o gatilho amarelo do gate, com as classes novas no vocabulário de `menuControls.ts`), **sem botão de entrada**; **ao vivo** = a imagem dá lugar ao embed oficial `youtube-nocookie` (id derivado do destino YouTube pré-cadastrado do link, `resolveShareLinkYoutubeVideoId` puro com validação de id) e o CTA de entrada assume o lugar da agenda com rótulo por host (`Entrar na plenária` no Meet, `Assistir no YouTube` no YouTube, fallback `Entrar` — `resolveShareLinkLiveActionLabel`) e href **sempre `/plenaria-vitoria`** (nunca a URL crua); sem destino YouTube o bloco degrada para a imagem (e para coluna única sem imagem). O estado ao vivo já vem resolvido do read cacheado no server (sem flash de agenda para quem chega durante a transmissão) e o poll do S29 foi extraído para o hook único `useShareLinkLiveTarget` (30 s, só ativa, pausa em aba oculta), consumido pelo anúncio e pela seção sem mudança de comportamento. `formatBahiaEventDayLabel`/`formatBahiaEventTimeLabel` nascem em `lib/campaignTime.ts` (o headline do anúncio passa a compor as duas, saída intacta). O débito D3 do S39 foi resolvido (3º spec bateu o gatilho): o poll do HTML ISR virou `tests/helpers/homeIsr.ts`, com rewiring de `frontend`/`frontendConteudos`, e o manifesto ganhou `src/app/(frontend)/(home)` no entry do `frontendShareLink`. Sem Consent/PII/coleta; a página `/plenaria-vitoria`, o cadastro do link, a rota `[type]` e as demais seções ficam intocados. Provas: `pnpm gate:fast` verde (459 arquivos/5.093 testes; novos unit de `shareLinkHomeSection` (11), da extração do vídeo em `shareLink` e do gating no skeleton do `campaignHome`); int `shareLink` 28 verdes (loader novo: publicado + janela futura, expirado, sem data, despublicado e pré-live); e2e `frontendShareLink` 8/8 (describe S44 novo — seção após o hero, agenda sem entrada, troca Meet→YouTube sem reload via poll, estado ao vivo já no HTML do server pelo caminho REST, kill switch e janela fechada/reaberta — com o S29 intacto), `frontendConteudos` 12/12 e `frontend` 42/42 (helper rewiring). Design hi-fi certificado pelo `designer` (tier `openai/gpt-5.6-sol`) contra o artefato `docs/plans/secao-home-plenaria-da-vitoria-ui-design.html`, após uma rodada de ajustes (linha herdada do `h2` global, padding fora do `max-w`, margens do mobile, `(horário da Bahia)` inline no mobile e o popover da agenda fiel ao artefato: largura do gatilho no mobile, `sideOffset` 8, sombra e subtítulos de 11 px). Planos: `docs/plans/secao-home-plenaria-da-vitoria.md`/`-impl.md`.
|
||||
|
|
@ -1452,64 +1452,76 @@ Rollback: a migration `add_archive_photo_catalog` é aditiva; o rollback funcion
|
|||
é limpar o grupo `catalog`/`curatedFields` no admin. Reexecutar nunca duplica nem
|
||||
sobrescreve curadoria.
|
||||
|
||||
## C234 — busca por selfie no álbum público
|
||||
## C242 — busca por selfie aberta (índice anônimo do acervo)
|
||||
|
||||
A busca por selfie (`/fotos/encontre` + `POST /api/fotos/selfie`) nasce
|
||||
**fechada**: a flag `photoAlbum.selfieSearchEnabled` é `false` por default e o
|
||||
fluxo só abre com o **Consent de consulta** (`busca-selfie-fotos`) configurado
|
||||
no admin — sem ele a página mostra o estado fail-closed e a API recusa (503).
|
||||
O índice é A/C (decisão do gate, PR #1370): só rostos de pessoas que aderiram
|
||||
entram; não existe índice anônimo do acervo. A selfie nunca sai do aparelho do
|
||||
visitante (o navegador envia só o vetor 128-d).
|
||||
A busca por selfie (`/fotos/encontre` + `POST /api/fotos/selfie`) cobre **qualquer
|
||||
visitante**: o índice é anônimo (foto + descritor 128-d em `archivePhotoFace`),
|
||||
sem nome, sem vínculo com pessoa e sem adesão prévia. A selfie nunca sai do
|
||||
aparelho do visitante (o navegador envia só o vetor). A flag
|
||||
`photoAlbum.selfieSearchEnabled` nasce `false` e é o kill switch imediato.
|
||||
|
||||
### Abertura (depois do aval jurídico/DPIA registrado)
|
||||
### Abertura (ordem obrigatória)
|
||||
|
||||
1. No admin (`/admin`), crie os dois Consentimentos com as chaves exatas:
|
||||
`busca-selfie-fotos` (consulta, texto mostrado no fluxo) e
|
||||
`busca-selfie-indice` (adesão, assinado com a pessoa no enrollment). Sem os
|
||||
dois, o fluxo não abre / ninguém é elegível.
|
||||
2. Inscreva cada pessoa que aderiu (selfie com **um** rosto, com a pessoa
|
||||
presente e o consentimento assinado). Rode no homeserver, no serviço de
|
||||
manutenção do alvo (o engine roda local, sem endpoint externo):
|
||||
1. **Canal de remoção** no admin (`/admin` → Configurações → Álbum de fotos):
|
||||
`https://` ou `mailto:` válido. Sem ele o álbum não publica e o lote de
|
||||
aprovação recusa.
|
||||
2. **Consentimentos** (textos versionados em `scripts/lib/faceConsentTexts.mjs`):
|
||||
no serviço de manutenção do alvo, com o env file do stack:
|
||||
```bash
|
||||
cd ~/stack
|
||||
# plano (dry-run: detecta o rosto e resolve o consentimento; não grava)
|
||||
docker compose --profile maintenance run --rm -v /srv/face-selfies:/app/data/face-selfies:ro -v /srv/face-reports:/app/data/face/reports teqo-1313-migrate pnpm faces:enroll --label "<nome interno>" --selfie /app/data/face-selfies/<arquivo>.jpg
|
||||
# grava (exige TEQO_ENV=production e FACE_ENROLL_CONFIRM=1):
|
||||
docker compose --profile maintenance run --rm -e TEQO_ENV=production -e FACE_ENROLL_CONFIRM=1 -v /srv/face-selfies:/app/data/face-selfies:ro -v /srv/face-reports:/app/data/face-reports teqo-1313-migrate pnpm faces:enroll --label "<nome interno>" --selfie /app/data/face-selfies/<arquivo>.jpg --apply
|
||||
docker compose --profile maintenance run --rm \
|
||||
-e TEQO_ENV=production -e FACE_CONSENT_SEED_CONFIRM=1 \
|
||||
teqo-1313-migrate pnpm seed:face-consents --apply
|
||||
```
|
||||
3. Indexe o acervo aprovado para os inscritos (canário primeiro):
|
||||
(dry-run sem `--apply` mostra o estado; o guard exige `TEQO_ENV` casando o
|
||||
banco exato.)
|
||||
3. **Aprovar o acervo** (drafts → approved; `removed` nunca é tocado):
|
||||
```bash
|
||||
docker compose --profile maintenance run --rm -e TEQO_ENV=production -e FACE_INDEX_CONFIRM=1 -v /srv/face-reports:/app/data/face/reports teqo-1313-migrate pnpm faces:index --apply --limit 20
|
||||
# sem --limit processa todas as aprovadas; adicionar/reenrolar alguém
|
||||
# muda a revisão e a próxima execução reprocessa tudo (~6,5k fotos).
|
||||
docker compose --profile maintenance run --rm teqo-1313-migrate pnpm faces:index --verify # inventário read-only; sai 1 com pendências
|
||||
docker compose --profile maintenance run --rm \
|
||||
-e TEQO_ENV=production -e ARCHIVE_PUBLISH_CONFIRM=1 \
|
||||
teqo-1313-migrate pnpm archive:publish --apply
|
||||
# canário: --limit 20
|
||||
```
|
||||
4. Só então ligue `Busca por selfie` no global **Álbum de fotos** (admin). O
|
||||
kill switch é imediato (sem deploy); desligar fecha a página (404) e a API.
|
||||
Ao fim, buste a tag pública em um processo que a possui (o write do CLI não
|
||||
revalida o servidor Next):
|
||||
```bash
|
||||
curl -X POST "https://jorgesolla1313.com.br/api/revalidate?tag=archivePhotos" \
|
||||
-H "x-revalidate-secret: $REVALIDATE_SECRET"
|
||||
```
|
||||
4. **Indexar** (horas; o engine roda local no maintenance, sem endpoint externo):
|
||||
```bash
|
||||
docker compose --profile maintenance run --rm \
|
||||
-e TEQO_ENV=production -e FACE_INDEX_CONFIRM=1 \
|
||||
-v /srv/face-reports:/app/data/face/reports \
|
||||
teqo-1313-migrate pnpm faces:index --apply --limit 20 # canário
|
||||
docker compose --profile maintenance run --rm \
|
||||
-e TEQO_ENV=production -e FACE_INDEX_CONFIRM=1 \
|
||||
-v /srv/face-reports:/app/data/face/reports \
|
||||
teqo-1313-migrate pnpm faces:index --apply # lote completo
|
||||
docker compose --profile maintenance run --rm \
|
||||
-v /srv/face-reports:/app/data/face/reports \
|
||||
teqo-1313-migrate pnpm faces:index --verify # read-only; sai 1 com pendências
|
||||
```
|
||||
O resultado no site aparece em até ~60 s (cache em memória do índice).
|
||||
5. **Ligar** `Busca por selfie` no global Álbum de fotos (admin). Sem deploy;
|
||||
desligar fecha a página (404), a API e a seção da home imediatamente.
|
||||
|
||||
### Remoção e re-consentimento
|
||||
### Remoção e privacidade
|
||||
|
||||
- **Sair do índice**: a própria pessoa usa "Minha presença" no fluxo (selfie
|
||||
confere o vínculo; o vetor e os links são apagados e o status vira
|
||||
`removed`). O pedido de **remoção de foto** continua no canal do álbum.
|
||||
- **Texto do Consent editado**: os inscritos ficam inelegíveis até
|
||||
re-consentimento (o `consentHash` do enrollment é comparado com o texto
|
||||
vigente) — re-rode `faces:enroll --subject <id>` com a pessoa.
|
||||
- **Troca de modelo do engine**: `FACE_SEARCH_MODEL` muda ⇒ o índice inteiro
|
||||
fica stale; re-inscreva (`--subject`) e rode `faces:index --refresh`.
|
||||
- **Rollback**: desligue a flag; a migration `add_face_subject` é aditiva
|
||||
(tabela `face_subject`, colunas `faces_*` em `archive_photo` e
|
||||
`selfie_search_enabled` no global). Nada do acervo público muda.
|
||||
- **Sair do índice**: a própria pessoa usa “Minha presença” no fluxo (selfie
|
||||
confere; os descritores correspondentes são apagados e o rosto deixa de ser
|
||||
encontrado). O pedido de **remoção de foto** continua no canal do álbum.
|
||||
- **Desaprovar/remover foto**: os descritores daquela foto são apagados pelos
|
||||
hooks da collection (e o read aprovado nunca os mostra).
|
||||
- **Rollback**: desligue a flag; a migration `add_archive_photo_face` é aditiva,
|
||||
exceto o drop da `face_subject` (tabela vazia em produção).
|
||||
|
||||
### Guardas e recibos
|
||||
|
||||
`--apply` exige `TEQO_ENV` casando o banco exato, `FACE_ENROLL_CONFIRM=1` /
|
||||
`FACE_INDEX_CONFIRM=1` fora do dev local e as quatro `S3_*` (mídia espelhada);
|
||||
`ALLOW_REMOTE_DB` é recusado. Recibos JSON em `data/face/reports/` (nunca
|
||||
levam vetor nem bytes de imagem). O engine carrega os mesmos modelos do
|
||||
navegador de `node_modules`; a cópia same-origin para o browser é artefato de
|
||||
build (`scripts/copy-face-vision-assets.mjs`).
|
||||
`--apply` exige `TEQO_ENV` casando o banco exato e a flag de confirmação do
|
||||
comando (`FACE_INDEX_CONFIRM`/`ARCHIVE_PUBLISH_CONFIRM`/`FACE_CONSENT_SEED_CONFIRM`),
|
||||
mais as quatro `S3_*` quando a mídia for remota (indexação). Recibos JSON em
|
||||
`data/face/reports/` e `data/archive/reports/` (nunca levam vetor nem bytes).
|
||||
|
||||
## C230-followup — importação do Instagram para a Central de Conteúdos
|
||||
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@
|
|||
<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 — C234 · Busca de fotos por selfie</title>
|
||||
<title>Design — C234/C242 · Busca de fotos por selfie</title>
|
||||
<style type="text/tailwindcss">
|
||||
@theme inline {
|
||||
--font-sans: Inter, Arimo, ui-sans-serif, system-ui, sans-serif;
|
||||
|
|
@ -225,28 +225,29 @@
|
|||
<header class="max-w-3xl">
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<span class="rounded-full bg-[#e4102f] px-3 py-1 text-xs font-extrabold text-white"
|
||||
>C234 · gate hi-fi</span
|
||||
>C234 + C242 · gate hi-fi</span
|
||||
><span class="rounded-full border border-border bg-white px-3 py-1 text-xs font-bold"
|
||||
>Fluxo sensível · LGPD fail-closed</span
|
||||
><span
|
||||
class="rounded-full border border-[#184e92]/20 bg-[#eef4fb] px-3 py-1 text-xs font-extrabold text-[#184e92]"
|
||||
>Estendido para a execução · 27 set 2026</span
|
||||
>Escopo B · 01 out 2026</span
|
||||
>
|
||||
</div>
|
||||
<h1 class="display mt-4 text-3xl font-black tracking-[-.03em]">
|
||||
Encontre você nas fotos — privado, explícito e sem placar de semelhança
|
||||
</h1>
|
||||
<p class="mt-2 max-w-2xl text-sm leading-6 text-muted-foreground">
|
||||
A pessoa parte do álbum, entende o uso de biometria, escolhe a própria selfie e recebe
|
||||
apenas fotos públicas aprovadas em que aparece. A selfie permanece no dispositivo.
|
||||
Qualquer visitante pode partir do álbum, entender o uso de biometria, escolher a própria
|
||||
selfie e receber apenas fotos públicas aprovadas em que aparece. A selfie permanece no
|
||||
dispositivo e é possível sair do índice.
|
||||
</p>
|
||||
<div class="mt-5 rounded-xl border border-[#184e92]/15 bg-[#f9faff] p-4 text-sm leading-6">
|
||||
<p class="font-extrabold text-[#184e92]">Deltas de execução desta revisão</p>
|
||||
<p class="font-extrabold text-[#184e92]">Delta de produto desta revisão · C242</p>
|
||||
<p class="mt-1 text-muted-foreground">
|
||||
A entrada agora respeita o hero e a grade reais do C233; o fluxo é uma página própria em
|
||||
<b class="text-foreground">/fotos/encontre</b>; resultado, vazio A/C, falhas do
|
||||
processamento e opt-out sem reconhecimento ganham estados explícitos. Cenas revisadas
|
||||
mantêm o número aprovado e recebem selo azul; cenas novas começam em 09.
|
||||
O índice deixa de depender de adesão prévia por pessoa: ele cobre os rostos do acervo
|
||||
público aprovado, sem nomes ou vínculo com cadastro. O aviso público do índice aparece
|
||||
antes da autorização de consulta; “Minha presença” permite retirar o próprio rosto a
|
||||
qualquer momento. As cenas sem delta visual permanecem intactas.
|
||||
</p>
|
||||
</div>
|
||||
</header>
|
||||
|
|
@ -259,7 +260,7 @@
|
|||
<section aria-labelledby="s1">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<p class="text-xs font-extrabold tracking-[.08em] text-[#e4102f] uppercase">Cena 01</p>
|
||||
<span class="revision-badge">Revisada · C234 execução</span>
|
||||
<span class="revision-badge">Revisada · C242 escopo B</span>
|
||||
</div>
|
||||
<h2 id="s1" class="display mt-1 text-xl font-black">
|
||||
Entrada real na /fotos · flag ligada
|
||||
|
|
@ -317,8 +318,8 @@
|
|||
<div>
|
||||
<h3 class="display text-xl font-black">Encontre você nas fotos</h3>
|
||||
<p class="mt-1 text-sm leading-6 text-muted-foreground">
|
||||
Use uma selfie sua. A imagem não sai deste dispositivo e a busca cobre quem
|
||||
autorizou participar do índice.
|
||||
Use uma selfie sua. A imagem não sai deste dispositivo. A busca cobre o acervo
|
||||
público aprovado, e você pode retirar seu rosto do índice.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -393,7 +394,8 @@
|
|||
<div>
|
||||
<h3 class="display text-lg font-black">Encontre você nas fotos</h3>
|
||||
<p class="mt-1 text-xs leading-5 text-muted-foreground">
|
||||
Sua selfie fica neste aparelho. A busca é para quem aderiu ao índice.
|
||||
Sua selfie fica neste aparelho. A busca cobre o acervo público aprovado, e
|
||||
você pode sair do índice.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -447,7 +449,7 @@
|
|||
<section aria-labelledby="s2">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<p class="text-xs font-extrabold tracking-[.08em] text-[#e4102f] uppercase">Cena 02</p>
|
||||
<span class="revision-badge">Revisada · página /fotos/encontre</span>
|
||||
<span class="revision-badge">Revisada · C242 aviso + consulta</span>
|
||||
</div>
|
||||
<h2 id="s2" class="display mt-1 text-xl font-black">
|
||||
Desktop ~1280 · aviso e consentimento na página própria, não em modal
|
||||
|
|
@ -491,10 +493,30 @@
|
|||
Sua face é um dado biométrico sensível
|
||||
</h3>
|
||||
<p class="mt-3 text-sm leading-6 text-muted-foreground">
|
||||
Com sua autorização, comparamos a sua selfie com o índice formado por pessoas que
|
||||
autorizaram participar, para mostrar somente fotos públicas aprovadas em que você
|
||||
aparece.
|
||||
Com sua autorização, usamos a sua selfie somente nesta consulta para procurar você
|
||||
no índice biométrico anônimo do acervo público aprovado.
|
||||
</p>
|
||||
<div class="mt-5 rounded-xl border border-[#184e92]/20 bg-[#eef4fb] p-4">
|
||||
<div class="flex items-start gap-3">
|
||||
<svg class="icon mt-0.5 shrink-0 text-[#184e92]"><use href="#shield" /></svg>
|
||||
<div>
|
||||
<p class="text-sm font-extrabold text-[#143c70]">
|
||||
Aviso público sobre o índice de fotos
|
||||
</p>
|
||||
<p class="mt-1 text-sm leading-6 text-[#365472]">
|
||||
Rostos presentes nas fotos públicas aprovadas compõem um índice sem nomes e
|
||||
sem vínculo com cadastros de pessoas. Ele serve apenas para localizar as
|
||||
próprias fotos. Você pode retirar seu rosto do índice a qualquer momento em
|
||||
“Minha presença”.
|
||||
</p>
|
||||
<a
|
||||
href="#"
|
||||
class="focus-ring mt-2 inline-flex min-h-11 items-center text-sm font-extrabold text-[#184e92] underline underline-offset-4"
|
||||
>Ler o aviso completo do índice</a
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-5 grid gap-3 rounded-xl bg-[#f9faff] p-4 text-sm">
|
||||
<div class="flex gap-3">
|
||||
<svg class="icon mt-0.5 shrink-0 text-[#184e92]"><use href="#device" /></svg>
|
||||
|
|
@ -508,10 +530,9 @@
|
|||
<div class="flex gap-3">
|
||||
<svg class="icon mt-0.5 shrink-0 text-[#184e92]"><use href="#lock" /></svg>
|
||||
<p>
|
||||
<b>Você pode desistir e pedir remoção.</b><br /><span
|
||||
class="text-muted-foreground"
|
||||
>O resultado não mostra nomes de terceiros nem percentual de
|
||||
semelhança.</span
|
||||
<b>Você mantém o controle.</b><br /><span class="text-muted-foreground"
|
||||
>Saia do índice quando quiser. O resultado não mostra nomes de terceiros nem
|
||||
percentual de semelhança.</span
|
||||
>
|
||||
</p>
|
||||
</div>
|
||||
|
|
@ -522,8 +543,8 @@
|
|||
class="mt-0.5 grid size-5 shrink-0 place-items-center rounded border-2 border-[#184e92] bg-[#184e92] text-white"
|
||||
><svg class="icon size-3.5"><use href="#check" /></svg></span
|
||||
><span
|
||||
>Li e autorizo o uso temporário da minha biometria facial para procurar a mim
|
||||
mesmo neste álbum.</span
|
||||
>Li o aviso e autorizo o uso da minha selfie e da minha biometria somente nesta
|
||||
consulta para procurar a mim mesmo no álbum.</span
|
||||
></label
|
||||
>
|
||||
<p class="mt-3 text-xs leading-5 text-muted-foreground">
|
||||
|
|
@ -542,6 +563,15 @@
|
|||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="mt-4 max-w-3xl rounded-xl border border-[#184e92]/15 bg-[#f9faff] p-4 text-xs leading-5 text-muted-foreground"
|
||||
>
|
||||
<b class="text-foreground">Contrato de conteúdo:</b> o bloco azul é o aviso público
|
||||
<code class="font-bold text-[#184e92]">busca-selfie-indice</code>, não um consentimento de
|
||||
adesão ao índice. A caixa abaixo autoriza apenas o uso da própria selfie e biometria na
|
||||
consulta atual (<code class="font-bold text-[#184e92]">busca-selfie-fotos</code>). Sem
|
||||
qualquer um dos dois textos, vale a Cena 07.
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- CENA 03 -->
|
||||
|
|
@ -799,7 +829,7 @@
|
|||
<section aria-labelledby="s6">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<p class="text-xs font-extrabold tracking-[.08em] text-[#e4102f] uppercase">Cena 06</p>
|
||||
<span class="revision-badge">Revisada · índice A/C</span>
|
||||
<span class="revision-badge">Revisada · escopo B</span>
|
||||
</div>
|
||||
<h2 id="s6" class="display mt-1 text-xl font-black">
|
||||
Mobile ~390 · vazio honesto, sem “parecidos”
|
||||
|
|
@ -818,8 +848,8 @@
|
|||
</div>
|
||||
<h3 class="display mt-5 text-2xl font-black">Não encontramos fotos suas</h3>
|
||||
<p class="mt-2 max-w-[310px] text-sm leading-6 text-muted-foreground">
|
||||
Esta busca funciona para quem autorizou participar do índice. Também pode não haver
|
||||
uma foto sua entre os registros públicos aprovados.
|
||||
Pode não haver uma foto sua entre os registros públicos aprovados, ou seu rosto pode
|
||||
já ter sido retirado do índice.
|
||||
</p>
|
||||
<p class="mt-3 text-sm font-bold">
|
||||
Não mostramos pessoas parecidas nem tentamos adivinhar quem você é.
|
||||
|
|
@ -836,7 +866,7 @@
|
|||
<section aria-labelledby="s7">
|
||||
<p class="text-xs font-extrabold tracking-[.08em] text-[#e4102f] uppercase">Cena 07</p>
|
||||
<h2 id="s7" class="display mt-1 text-xl font-black">
|
||||
Fail-closed · consentimento não configurado, fluxo indisponível
|
||||
Fail-closed · aviso ou consentimento não configurado, fluxo indisponível
|
||||
</h2>
|
||||
<div class="stage mt-4 max-w-[920px] rounded-2xl border border-border bg-white p-8 sm:p-12">
|
||||
<div class="rounded-2xl border border-amber-300 bg-amber-50 px-6 py-10 text-center">
|
||||
|
|
@ -852,8 +882,8 @@
|
|||
A busca por selfie está indisponível
|
||||
</h3>
|
||||
<p class="mx-auto mt-3 max-w-lg text-sm leading-6 text-amber-900">
|
||||
O texto de consentimento necessário ainda não está configurado. Por segurança, não
|
||||
podemos receber nem processar sua selfie agora.
|
||||
O aviso público do índice ou o consentimento da consulta não está configurado. Por
|
||||
segurança, não podemos receber nem processar sua selfie agora.
|
||||
</p>
|
||||
<p class="mx-auto mt-3 max-w-lg text-sm font-bold text-amber-950">
|
||||
Nenhuma imagem foi capturada ou enviada.
|
||||
|
|
@ -869,10 +899,10 @@
|
|||
<section aria-labelledby="s8">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<p class="text-xs font-extrabold tracking-[.08em] text-[#e4102f] uppercase">Cena 08</p>
|
||||
<span class="revision-badge">Revisada · opt-out self-service</span>
|
||||
<span class="revision-badge">Revisada · C242 saída do índice</span>
|
||||
</div>
|
||||
<h2 id="s8" class="display mt-1 text-xl font-black">
|
||||
Mobile ~390 · opt-out e pedido de remoção com confirmação
|
||||
Mobile ~390 · saída do índice a qualquer momento, com confirmação e sucesso
|
||||
</h2>
|
||||
<div class="mt-4 flex flex-wrap items-start gap-8">
|
||||
<div class="stage w-[390px] overflow-hidden rounded-[30px] border border-border bg-white">
|
||||
|
|
@ -885,10 +915,11 @@
|
|||
<p class="text-xs font-black tracking-[.08em] text-[#184e92] uppercase">
|
||||
Privacidade
|
||||
</p>
|
||||
<h3 class="display mt-1 text-2xl font-black">Você decide se quer aparecer</h3>
|
||||
<h3 class="display mt-1 text-2xl font-black">Você controla sua presença no índice</h3>
|
||||
<p class="mt-2 text-sm leading-6 text-muted-foreground">
|
||||
Para sair do índice, confirme sua identidade com uma selfie. Para retirar uma foto
|
||||
pública, use o canal da equipe responsável pelo acervo.
|
||||
Seu rosto pode fazer parte do índice anônimo por aparecer no acervo aprovado. Para
|
||||
retirá-lo, use uma selfie sua. Para retirar uma foto pública, fale com a equipe do
|
||||
acervo.
|
||||
</p>
|
||||
<label class="mt-5 flex gap-3 rounded-xl border-2 border-[#184e92] bg-[#f9faff] p-4"
|
||||
><span
|
||||
|
|
@ -897,7 +928,8 @@
|
|||
><span
|
||||
><b class="text-sm">Sair do índice de busca</b
|
||||
><small class="mt-1 block text-xs leading-5 text-muted-foreground"
|
||||
>Seu rosto deixa de ser usado para localizar fotos por selfie.</small
|
||||
>Apaga do índice as referências biométricas que correspondem ao seu
|
||||
rosto.</small
|
||||
></span
|
||||
></label
|
||||
>
|
||||
|
|
@ -931,8 +963,8 @@
|
|||
</div>
|
||||
<h3 class="display mt-4 text-xl font-black">Confirmar saída do índice?</h3>
|
||||
<p class="mt-2 text-sm leading-6 text-muted-foreground">
|
||||
Vamos reconhecer você neste aparelho e, se houver correspondência, retirar sua
|
||||
presença do índice de busca.
|
||||
Vamos processar sua selfie neste aparelho e, se houver correspondência, apagar do
|
||||
índice as referências biométricas do seu rosto. A selfie não será enviada.
|
||||
</p>
|
||||
<button
|
||||
class="mt-6 flex min-h-11 w-full items-center justify-center rounded-[10px] bg-[#b42318] px-4 text-sm font-extrabold text-white"
|
||||
|
|
@ -944,6 +976,34 @@
|
|||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="stage w-[390px] overflow-hidden rounded-[30px] border border-border bg-white">
|
||||
<header class="flex h-14 items-center justify-between bg-[#ae1603] px-4 text-white">
|
||||
<span class="w-[18px]"></span><span class="text-sm font-bold">Minha presença</span
|
||||
><span class="w-[18px]"></span>
|
||||
</header>
|
||||
<div class="flex min-h-[635px] flex-col items-center justify-center px-6 text-center">
|
||||
<div class="grid size-14 place-items-center rounded-full bg-[#eef4fb] text-[#184e92]">
|
||||
<svg class="icon size-7"><use href="#shield" /></svg>
|
||||
</div>
|
||||
<h3 class="display mt-5 text-2xl font-black">Pronto — seu rosto saiu do índice</h3>
|
||||
<p class="mt-3 max-w-[315px] text-sm leading-6 text-muted-foreground">
|
||||
Apagamos as referências biométricas que correspondiam ao seu rosto. Ele deixa de ser
|
||||
encontrado pela busca por selfie.
|
||||
</p>
|
||||
<p class="mt-3 max-w-[315px] text-sm font-bold">
|
||||
As fotos públicas continuam no álbum. Para retirar uma foto específica, use o canal
|
||||
da equipe responsável pelo acervo.
|
||||
</p>
|
||||
<a href="#" class="primary mt-7 w-full">Voltar ao álbum</a>
|
||||
<a
|
||||
href="#"
|
||||
data-source="photoAlbum.removalChannelUrl"
|
||||
class="focus-ring mt-4 inline-flex min-h-11 items-center text-sm font-extrabold text-[#184e92] underline underline-offset-4"
|
||||
>Pedir remoção de uma foto</a
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
|
@ -1140,8 +1200,8 @@
|
|||
</div>
|
||||
<h3 class="display mt-5 text-2xl font-black">Não encontramos sua presença no índice</h3>
|
||||
<p class="mt-3 max-w-[310px] text-sm leading-6 text-muted-foreground">
|
||||
Não foi possível reconhecer uma participação sua no índice com esta selfie. Nenhuma
|
||||
alteração foi feita.
|
||||
Não encontramos no índice referências biométricas que correspondam ao seu rosto com
|
||||
esta selfie. Nenhuma alteração foi feita.
|
||||
</p>
|
||||
<button class="primary mt-7 w-full">Tentar outra selfie</button>
|
||||
<div class="mt-6 w-full border-t border-border pt-5">
|
||||
|
|
|
|||
126
docs/plans/busca-selfie-escopo-b-impl.md
Normal file
126
docs/plans/busca-selfie-escopo-b-impl.md
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
# Impl: C242 — Busca por selfie aberta a qualquer visitante (escopo B)
|
||||
|
||||
Status: aprovado (decisão do dono na sessão, 2026-10-01) — hard-stops humanos registrados (migração de schema, contrato público, Consent/LGPD)
|
||||
Atualizado em: 2026-10-01
|
||||
Issue: — (worktree `work/43`, sem claim)
|
||||
Intenção: docs/plans/busca-selfie-escopo-b.md
|
||||
Design UI (gate): docs/plans/busca-fotos-por-selfie-ui-design.html (estendido no C243; aqui só copy/estados)
|
||||
Appetite restante: herdado (~2–3 dias eng + ops de publicação/indexação) — índice biométrico **anônimo** do acervo aprovado, sem enrollment e sem cadastro de pessoa.
|
||||
|
||||
## Leitura da intenção
|
||||
|
||||
- **Outcome:** qualquer visitante com rosto em foto aprovada se encontra; sem aviso/consentimento/flag, nada abre; sem score/nomes; opt-out e remoção funcionam; foto desaprovada sai na hora.
|
||||
- **O que NÃO negociar:**
|
||||
- Fail-closed de Consent/LGPD: sem as duas linhas de Consent com as chaves exatas, o endpoint recusa (503) e a página mostra o estado fechado.
|
||||
- A selfie nunca sai do dispositivo (vetor-only), sem score, sem nome de terceiro, sem retenção.
|
||||
- Resultado = interseção com `getApprovedArchivePhotoItems()` (draft/removida nunca).
|
||||
- Kill switch `photoAlbum.selfieSearchEnabled` e `photoAlbum.published` valem no servidor.
|
||||
- Sem vínculo com `Contact`/leadership; o índice não vira cadastro de pessoas.
|
||||
- **O que reavaliar (achados do reconhecimento):**
|
||||
- O índice A/C persiste **só os vínculos** `matchedPhotos` por subject; os descritores do acervo são transitórios (`faceSubjectPhotoIndex.ts:28-44`). B exige persistir descritores por foto — collection nova.
|
||||
- `findFaceMatch` casa a consulta contra **subjects elegíveis** (`faceSearch.ts:101-128`); B casa a consulta contra **descritores do acervo**.
|
||||
- O marker `faces.checkedKey` hoje resume modelo + revisões de subjects (`faceSubjectPhotoIndex.ts:111-120`); em B resume só o modelo.
|
||||
- `deriveArchivePhotoCatalogIndex` já ignora writes do lote via `context.faceIndex` (`ArchivePhoto.ts:168-172`) — manter.
|
||||
- Produção verificada 2026-10-01: `archive_photo` 0 aprovadas / 6.492 draft; `face_subject` 0; 0 consentimentos; flag default off; `photo_album` sem linha (defaults: published=true, selfie=false, sem canal de remoção).
|
||||
|
||||
## Abordagem recomendada
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph OPS["Ops — CLI"]
|
||||
PUB["pnpm archive:publish --apply\naprova drafts em lote"] --> APR[("archivePhoto\napproved")]
|
||||
IDX["pnpm faces:index --apply"] --> DLD["downloadPrivateMediaToFile + sharp ≤1024px"]
|
||||
DLD --> NODE["engine node-wasm (face-api)"]
|
||||
NODE --> ROW[("archivePhotoFace\nphoto · vector 128d · model")]
|
||||
APR --> IDX
|
||||
CANAL["canal de remoção no global"] --> PUB
|
||||
end
|
||||
subgraph PUB2["Público"]
|
||||
ALB["/fotos + seção da home (C243)"] --> ENC["/fotos/encontre\nflag + aviso + consentimento"]
|
||||
ENC --> BRW["engine on-device · selfie NÃO sai"]
|
||||
BRW -- "vetor 128d ≤4KB" --> API["POST /api/fotos/selfie"]
|
||||
API --> CACHE["índice de descritores em memória (TTL 60s)"]
|
||||
CACHE --> APR2["getApprovedArchivePhotoItems ∩ matches\nsem nomes · sem score · ≤60"]
|
||||
API -- "leave-index" --> DEL["apaga descritores do rosto"]
|
||||
UNAP["desaprovar/remover foto"] --> PURGE["hook apaga descritores da foto"]
|
||||
end
|
||||
```
|
||||
|
||||
**Opções consideradas (índice B):**
|
||||
A) collection `archivePhotoFace` (1 linha/rosto, `json` 128 floats) + ranking em memória com cache curto; B) coluna json no próprio `archivePhoto`; C) pgvector/serviço externo.
|
||||
**Recomendação:** **A** — segue o precedente C229 (`speechEmbedding` jsonb + ranking em memória), isola PII biométrica da ficha pública, permite apagar por rosto/foto e não exige extensão de banco (o Postgres do homeserver é vanilla; C229 rejeitou pgvector).
|
||||
**Rejeitadas:** **B** porque carregaria ~6,5k documentos com vetores a cada scan e misturaria biometria na ficha do acervo; **C** porque troca imagem do Postgres/instala extensão por ganho marginal na escala atual (~dezenas de milhares de rostos).
|
||||
|
||||
### Componentes / mudanças
|
||||
|
||||
**Schema**
|
||||
|
||||
- **`src/collections/ArchivePhotoFace.ts`** (novo): slug `archivePhotoFace`, labels “Rosto no índice”/“Rostos no índice”, grupo `Comunicação`, `admin.hidden: true` (dado de máquina; sem UI), access `payloadAdminOnly` nas quatro operações. Campos: `photo` (relationship → `archivePhoto`, required, index), `model` (text, required, index), `vector` (json, hidden, readOnly), `detectedAt` (date, readOnly). Sem hooks.
|
||||
- **`src/payload.config.ts`**: registrar a collection; remover `FaceSubject`.
|
||||
- **`src/collections/FaceSubject.ts`**: **deletar**.
|
||||
- **Migration `add_archive_photo_face`** (gerada + revisada à mão): cria `archive_photo_face` (+ FK para `archive_photo` com `ON DELETE CASCADE` e índice por `photo`), dropa `face_subject`, `face_subject_rels`, `enum_face_subject_status` (0 linhas em produção). Nunca editar migrations antigas.
|
||||
- **`src/collections/ArchivePhoto.ts`**: hook novo `afterChange` que apaga descritores quando a foto deixa de ser `approved` (e `afterDelete` equivalente); o batch continua marcando `faces.checkedAt/checkedKey` com `context.faceIndex`.
|
||||
|
||||
**Contrato puro (`src/lib/faceSearch.ts`, editar)**
|
||||
|
||||
- Manter descritor/modelo/threshold/intents/view model/stub.
|
||||
- Novo `findFaceDescriptorMatch({ vector, descriptors, model })` → melhores `photoIds` distintos sob o threshold (nunca devolve distância).
|
||||
- Remover `findFaceMatch`/`faceSubjectIsEligible`/`FaceSearchSubject` (sem subjects).
|
||||
|
||||
**Índice (novo domínio `src/utilities/faceIndex/`, substitui `faceSubjects/`)**
|
||||
|
||||
- `faceDescriptorIndex.ts` (`server-only`): `listArchivePhotoFaceIndexQueue({ payload, refresh, limit })` (aprovadas + marker), `indexArchivePhotoFaces({ payload, item, indexKey, analyze })` — baixa/prepara/analisa e, em uma transação, **substitui** os descritores da foto e grava o marker `sha256(model)`. Falha por foto é resultado, nunca throw (estágios download/image/analyze/write).
|
||||
- `faceDescriptorReads.ts` (`server-only`): `loadFaceDescriptorIndex(payload)` com cache em memória (TTL 60 s, `Float32Array` por descritor, cap defensivo documentado) e `deleteFaceDescriptorMatches({ payload, vector, model })` para o opt-out; leitura direta (sem cache) no delete para o opt-out valer na hora.
|
||||
- Deletar `src/utilities/faceSubjects/*` e `scripts/enroll-face-subject.mjs`; remover `faces:enroll` do `package.json`; ajustar `scripts/copy-face-vision-assets.mjs` só se referenciar o CLI (não referencia).
|
||||
|
||||
**Endpoint (`src/app/(frontend)/api/fotos/selfie/route.ts`, editar)**
|
||||
|
||||
- Mesmas recusas (400 body, 403 origin, 404 flag/álbum, 429 rate, 503 consent) — muda o miolo: exige os dois Consents (`busca-selfie-fotos` consulta + `busca-selfie-indice` aviso); match contra `loadFaceDescriptorIndex`; `leave-index` apaga os descritores que casarem; resposta `getApprovedArchivePhotoItems ∩ photoIds` (≤60, `toFaceSearchPhotoView`).
|
||||
- Página `/fotos/encontre`: passa a exigir/consumir também o aviso (renderiza o texto do aviso + texto do consentimento) e mantém o estado fechado sem qualquer um dos dois; `/fotos` mostra a entrada quando flag + aprovadas (e aviso/consentimento configurados).
|
||||
|
||||
**Copy/estados (porta do design estendido no C243)**
|
||||
|
||||
- `SelfieSearchEntry`: “a busca cobre quem autorizou participar do índice” → cobre o acervo aprovado, com saída do índice.
|
||||
- `SelfieSearchFlow`: textos de consentimento/aviso e o estado de “Minha presença” (o vetor/descritores do rosto são apagados do índice).
|
||||
|
||||
**CLI de publicação (novo `scripts/publish-archive-photos.mjs`, guardas C231/C232)**
|
||||
|
||||
- Dry-run default; `--apply` exige `ARCHIVE_PUBLISH_CONFIRM=1`, `TEQO_ENV` casando o banco e as 4 `S3_*`; `--limit`, `--refresh`; nunca toca `removed`; exige `removalChannelUrl` válido (o guard da collection reforça); recibo JSON em `data/archive/reports/`; ao fim, instrui/deposita o bust da tag `archivePhotos` via `POST /api/revalidate` (writes fora do processo Next não revalidam sozinhos).
|
||||
- `package.json`: script `archive:publish`.
|
||||
|
||||
**Testes**
|
||||
|
||||
- Unit: `faceSearch` (match por descritores, threshold estrito, sem score), parser do CLI de publicação, plan/CLI do índice.
|
||||
- Int: `faceSearchApi` (busca sem subject, opt-out, flag/álbum/Consents, rate limit, 404/503) e `faceDescriptorIndex` (substituição por foto, purge em desaprovação/delete, marker).
|
||||
- E2e: `frontendFotosSelfie` (semear descritores via fixture em vez de subject; fluxo completo com stub), seção da home (C243).
|
||||
- Fixtures/helpers: `tests/helpers/faceIntFixtures.ts` reescrito para descritores; ownership de `archivePhotoFace`.
|
||||
|
||||
**Ops (runbook §C234 reescrito)**
|
||||
|
||||
1. Admin: criar os dois Consentimentos (textos da entrega) e o canal de remoção no global Álbum de fotos.
|
||||
2. `pnpm archive:publish --apply` (6.492) + bust da tag; conferir `/fotos`.
|
||||
3. `pnpm faces:index --apply` (horas; canário `--limit 20` antes) + `--verify`.
|
||||
4. Ligar `Busca por selfie`; conferir `/fotos/encontre` e a seção da home.
|
||||
Rollback: desligar a flag; migration do índice é aditiva exceto o drop do `face_subject` (vazio).
|
||||
|
||||
**Docs**
|
||||
|
||||
- `AGENTS-public.md` (contrato `/fotos/encontre` reescrito para escopo B), `docs/ops/teqo-1313-deploy.md` §C234, `docs/changelog/<data>-c240-c241.md`, planos atualizados (C234 ganha nota de superação).
|
||||
|
||||
## Riscos
|
||||
|
||||
- **Falso positivo do threshold** mostra foto de outra pessoa — mitigado por threshold conservador, canário e calibração no runbook; sem score na UI.
|
||||
- **Custo do lote** (~6,5k detecções) — ops em background no homeserver; retomável pelo marker.
|
||||
- **Descrição/volume do índice em memória** — `Float32Array`, TTL curto e cap documentado; degrada para vazio honesto se o índice não carregar.
|
||||
- **Migração destrutiva** do `face_subject` (vazio em produção; staging/local com dados de teste podem perder linhas — aceitável e registrado).
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] Collection + migration + purge hooks + types
|
||||
- [ ] Domínio `faceIndex` (batch/reads/delete) + CLI `faces:index` novo + remoção do enrollment
|
||||
- [ ] Endpoint + páginas fail-closed (consulta + aviso)
|
||||
- [ ] CLI `archive:publish` + script
|
||||
- [ ] Copy/estados do fluxo e da entrada `/fotos` (porta do design)
|
||||
- [ ] Testes unit/int/e2e + fixtures
|
||||
- [ ] Docs (AGENTS-public, runbook, changelog, planos)
|
||||
- [ ] Ops: consentimentos, canal, lote, indexação, flag
|
||||
92
docs/plans/busca-selfie-escopo-b.md
Normal file
92
docs/plans/busca-selfie-escopo-b.md
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
# C242 — Busca por selfie aberta a qualquer visitante (escopo B)
|
||||
|
||||
Status: aprovado (decisão do dono na sessão, 2026-10-01)
|
||||
Atualizado em: 2026-10-01
|
||||
Issue: — (worktree `work/43`, sem claim)
|
||||
Priority: P1
|
||||
Impeccable: C — superfície pública de biometria (muda o escopo do índice facial do C234)
|
||||
Design UI: docs/plans/busca-fotos-por-selfie-ui-design.html (estender no C243; esta fatia muda copy/estados do fluxo, não a gramática visual)
|
||||
Appetite: ~2–3 dias eng + ops de publicação/indexação; um outcome verificável — **qualquer visitante** encontra no acervo público aprovado as fotos em que aparece, sem que a selfie saia do aparelho e sem score
|
||||
Responsável: —
|
||||
|
||||
## Intenção
|
||||
|
||||
O C234 entregou a busca por selfie **fechada por padrão** e no escopo A/C: só quem foi inscrito pela assessoria (`pnpm faces:enroll`, consentimento assinado) entra no índice; um visitante comum nunca se encontra. O dono decidiu (2026-10-01), com aval jurídico declarado na sessão, **reabrir o escopo do gate (PR #1370) para B**: indexar os rostos presentes no acervo público aprovado, anonimamente (sem nome, sem vínculo com pessoa), para que **qualquer visitante** consiga se achar. A base de fotos também nunca foi publicada (6.492 drafts, 0 aprovadas) — sem isso não há o que buscar —, então a fatia inclui a publicação em lote do acervo e a indexação.
|
||||
|
||||
O que muda de conceito: o índice deixa de ser "adesão de pessoas" e passa a ser **índice biométrico anônimo do acervo aprovado**, com transparência pública (aviso), remoção a pedido (opt-out por selfie + canal de remoção de foto) e kill switch imediato. O enrollment por CLI e a collection `faceSubject` ficam obsoletos e são removidos (editar o dono, não criar gêmeo).
|
||||
|
||||
## Persona e fluxo
|
||||
|
||||
- **Persona / contexto:** visitante que foi a um evento com Solla, no celular, sem conta na campanha.
|
||||
- **Job principal:** encontrar, entre as fotos públicas aprovadas, as que eu apareço.
|
||||
- **Fluxo desejado:** abre `/fotos` (ou a seção da home) → toca "Encontre você nas fotos" → lê o aviso (biometria/LGPD + como sair do índice) e consente com o uso da própria selfie → tira/envia uma selfie → o reconhecimento roda no dispositivo (a selfie não sobe) → vê só as fotos aprovadas em que aparece, sem nome de terceiros e sem score → a qualquer momento pede para sair do índice (selfie de novo → o rosto deixa de ser encontrado) e/ou despublica uma foto pelo canal de remoção.
|
||||
- **Anti-goals de produto:** não é vigilância nem CRM de rostos; não nomeia nem identifica terceiros; não cruza com `Contact`/leadership; não oferece busca por outra pessoa; não abre sem aviso/consentimento configurados; não retém a selfie.
|
||||
|
||||
## Objetivo e aceite
|
||||
|
||||
- Com o aviso e o consentimento de consulta configurados e a flag ligada, **qualquer visitante** que apareça em foto aprovada recebe a lista dessas fotos.
|
||||
- Sem aviso/consentimento configurado (ou flag desligada), o fluxo recusa com linguagem clara — nunca meio aberto, nem na UI nem no servidor.
|
||||
- Nenhum rastro da selfie no servidor: o browser envia só o vetor 128-d; nenhuma imagem, nenhum score, nenhum nome de terceiro.
|
||||
- Nenhuma foto draft/removida no resultado; desaprovar uma foto a tira da busca imediatamente (por construção: o resultado cruza o índice com o read aprovado do C233, e os descritores da foto são apagados na desaprovação/remoção).
|
||||
- Opt-out funciona: "Minha presença" com a selfie apaga os descritores daquele rosto do índice e ele deixa de ser encontrado; o pedido de remoção de foto continua no canal do álbum.
|
||||
- O índice cobre só o acervo **aprovado** e só o modelo vigente; trocar o modelo invalida a revisão e o próximo lote reprocessa.
|
||||
- Antiabuso: rate limit anônimo (20/10 min por IP hasheado), same-origin, body ≤4 KB.
|
||||
- **Guardrails:** Consent/LGPD fail-closed (aviso + consentimento de consulta são o gate); sem cruzamento com `Contact`/leadership; a biometria não vira cadastro de pessoa.
|
||||
|
||||
## Dados (intenção)
|
||||
|
||||
- **Vou apresentar dados?** Não — o resultado é "quais fotos", nunca "quão parecido". Score/percentual é anti-goal explícito do dono.
|
||||
- **Decisões desbloqueadas:** N/A — a escolha do visitante ("essa foto é minha, quero guardar/compartilhar") é qualitativa.
|
||||
- **Forma:** N/A — **sem score/percentual** de semelhança em nenhum estado; a única saída é a lista de fotos.
|
||||
|
||||
## Dados da decisão (literais)
|
||||
|
||||
- **Escopo do índice — decisão do dono (2026-10-01): B.** Indexa os rostos do acervo público aprovado, anonimamente; a resposta é só sobre a própria pessoa consultante. O DPIA/aval jurídico foi **declarado aprovado pelo dono na sessão** ("o jurídico aprovou; qualquer coisa ajeitamos ou tiramos do ar depois"); o fail-closed de configuração (aviso + consentimento) permanece no código.
|
||||
- **Textos:** os dois Consentimentos (`busca-selfie-fotos` de consulta e `busca-selfie-indice`, reclassificado como **aviso público do índice**) são redigidos nesta entrega e configurados no admin antes da abertura; nada abre sem eles.
|
||||
- **Selfie nunca sai do dispositivo:** o browser roda o engine e envia só o vetor; sem upload, sem galeria, sem retenção.
|
||||
- **Resposta mínima:** só fotos aprovadas em que a pessoa consultante aparece; nunca "outras pessoas parecidas", nunca nome de terceiro, nunca score.
|
||||
- **Remoção:** opt-out por selfie apaga os descritores do rosto no índice; foto específica sai pelo canal de remoção do álbum (`photoAlbum.removalChannelUrl`, obrigatório).
|
||||
- **Publicação do acervo:** as 6.492 fotos draft são aprovadas em lote (decisão do dono, 2026-10-01), com guardas de ops; `removed` nunca é reaprovada por lote.
|
||||
- **Enrollment A/C morre:** `faceSubject`, `pnpm faces:enroll` e a adesão por pessoa são removidos; a chave `busca-selfie-indice` passa a nomear o aviso do índice.
|
||||
|
||||
## Direção no codebase (hipótese)
|
||||
|
||||
- **Áreas prováveis:** `src/collections/ArchivePhoto.ts` (grupo `faces` existente), collection nova do índice (`archivePhotoFace`), `src/utilities/faceSubjects/*` (reescrito como domínio `faceIndex`), `src/lib/faceSearch.ts` (match por descritor do acervo), `src/app/(frontend)/api/fotos/selfie/route.ts`, `scripts/index-archive-faces.mjs` (+ novo CLI de publicação), migration.
|
||||
- **Precedente a olhar:** C229 (`speechEmbeddingIndex.ts`/`speechEmbedding` — índice vetorial em jsonb com ranking em memória), `archivePhotoReads.ts` (read público aprovado + tag), `withPayloadTransaction`, guardas de CLI do C231/C232, `revalidateRequest` (`/api/revalidate` para writes fora do processo Next).
|
||||
- **Risco de acoplamento:** a busca hoje resolve `faceSubject`; remover a collection exige migração destrutiva (tabela vazia em produção — verificado: 0 linhas) e atualização de testes/fixtures; o endpoint e o e2e mudam de "seed de subject" para "seed de descritores".
|
||||
|
||||
## Dependências
|
||||
|
||||
- Duras: C231/C232/C233 (acervo, catalogação, álbum público) — entregues.
|
||||
- Duras de produto: aval jurídico/DPIA — **declarado aprovado pelo dono na sessão de 2026-10-01**; registrar no changelog.
|
||||
- Soft: C243 (seção na home) consome o estado "busca aberta" daqui.
|
||||
|
||||
## Fora de escopo
|
||||
|
||||
- Identificação/nomeação de terceiros; diretório de rostos; busca por outra pessoa; indexação de vídeo; API pública de reconhecimento.
|
||||
- Retenção de selfie/imagem; score; galeria.
|
||||
- Curadoria foto a foto do acervo (o lote publica tudo, com canal de remoção).
|
||||
|
||||
## Rabbit holes de produto
|
||||
|
||||
- **"Só completar" indexando vídeo/gravações.** **Corte:** só fotos aprovadas do acervo.
|
||||
- **"Só completar" nomeando quem aparece.** **Corte:** nunca nome inferido de rosto; `catalog.people` continua vindo só do catálogo curado e por texto.
|
||||
- **"Só completar" com score/"match 87%".** **Corte:** sem número em nenhum estado.
|
||||
- **"Só completar" guardando a selfie.** **Corte:** vetor-only, sem retenção.
|
||||
|
||||
## Questões em aberto (produto)
|
||||
|
||||
- **Calibração do threshold (0.45) para índice anônimo:** risco assimétrico muda (falso positivo mostra foto de outra pessoa). **Recomendação:** manter 0.45 no v1 e calibrar com o canário/amostra no runbook; número nunca aparece na UI.
|
||||
- **Quem atende a fila de remoção de foto:** comunicação/assessoria, como no C233 (canal de remoção já é dela).
|
||||
|
||||
## Referências
|
||||
|
||||
- `docs/plans/busca-fotos-por-selfie.md` (C234, escopo A/C — decisão superada por este item)
|
||||
- `docs/plans/busca-fotos-por-selfie-impl.md` (dono técnico a editar)
|
||||
- `docs/plans/album-fotos-publico-busca.md` (C233 — álbum e canal de remoção)
|
||||
- `docs/ops/teqo-1313-deploy.md` §C234 (runbook a reescrever)
|
||||
- `docs/changelog/2026-09-27-c234.md` (entrega anterior)
|
||||
|
||||
## Self-score (shaping)
|
||||
|
||||
5/5 — (1) fatia = um outcome verificável (qualquer visitante se acha no acervo aprovado; sem configuração, recusa); (2) appetite comporta schema + CLI + endpoint + remoção + ops, sem pesquisa nova; (3) persona, job e aceite verificáveis; (4) direção no codebase com precedentes nomeados; (5) decisões duras (escopo/legal) tomadas pelo dono e registradas.
|
||||
35
docs/plans/busca-selfie-secao-home-impl.md
Normal file
35
docs/plans/busca-selfie-secao-home-impl.md
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
# Impl: C243 — Seção da busca por selfie na homepage pública
|
||||
|
||||
Status: aprovado (decisão do dono na sessão, 2026-10-01)
|
||||
Atualizado em: 2026-10-01
|
||||
Issue: — (worktree `work/43`, sem claim)
|
||||
Intenção: docs/plans/busca-selfie-secao-home.md
|
||||
Design UI (gate): docs/plans/busca-selfie-secao-home-ui-design.html
|
||||
Appetite restante: herdado (~0,5–1 dia eng) — uma seção condicional na home, sem engine.
|
||||
|
||||
## Leitura da intenção
|
||||
|
||||
- **Outcome:** visitante descobre a busca na home e chega a `/fotos/encontre`; fechada, a seção não aparece (sem CTA morto).
|
||||
- **O que NÃO negociar:** sem captura/engine na home; sem promessa de "todas as fotos"/score; mobile-first; nada de fotos do acervo renderizadas na home; gate só com reads cacheados.
|
||||
|
||||
## Abordagem recomendada
|
||||
|
||||
**Opções consideradas (gate):** A) gating por `photoAlbum` cacheado (published + flag) + `hasPublishedArchivePhotos()` (também cacheado); B) leitura live dos Consents para o gate (mais exato, quebra a estaticidade/ISR da home).
|
||||
**Recomendação:** **A** — a home mantém os reads cacheados; flag desligada já esconde a seção, e a combinação flag ligada + Consent ausente (misconfiguração) cai no estado fechado honesto da página de destino, nunca em 404 (a página `/fotos/encontre` existe nesse caso).
|
||||
**Rejeitadas:** **B** porque uma leitura live de Consent por request transformaria a homepage (hoje estática com ISR por tags) em dinâmica sem ganho de segurança material — o servidor da busca é o gate real.
|
||||
|
||||
### Componentes / mudanças
|
||||
|
||||
- **`src/components/fotos/SelfieSearchHomeSection.tsx`** (novo): porta classe-a-classe de `docs/plans/busca-selfie-secao-home-ui-design.html`; título, explicação curta (selfie não sai do aparelho; acervo aprovado; saída do índice) e CTAs (`Encontre você nas fotos` → `/fotos/encontre`; link secundário `Ver o álbum` → `/fotos`).
|
||||
- **`src/app/(frontend)/(home)/page.tsx`**: somar `photoAlbum` (via `getCachedGlobal`) ao `Promise.all`; renderizar a seção quando `published !== false && selfieSearchEnabled === true && showFotos` (mesmo `showFotos` já lido de `hasPublishedArchivePhotos`).
|
||||
- **`src/components/fotos/SelfieSearchEntry.tsx`** (C242, ajuste de copy): atualizar o texto do escopo B quando o design estendido definir os literais.
|
||||
- **Testes:** e2e da home (seção ausente com flag off/álbum fechado; presente com flag on + fotos aprovadas; CTA leva à página da busca) no spec existente de fotos/selfie ou no de frontend, seguindo o manifest curado; unit de gating se extrair predicado puro.
|
||||
- **Docs:** changelog conjunto C242/C243; `AGENTS-public.md` ganha a seção.
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] Design hi-fi aprovado (agente `designer`) gravado no disco
|
||||
- [ ] Componente + composição na home + gating
|
||||
- [ ] Copy da entrada `/fotos` alinhada ao escopo B
|
||||
- [ ] Testes (unit/e2e) e manifest
|
||||
- [ ] Docs/changelog
|
||||
481
docs/plans/busca-selfie-secao-home-ui-design.html
Normal file
481
docs/plans/busca-selfie-secao-home-ui-design.html
Normal file
|
|
@ -0,0 +1,481 @@
|
|||
<!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" />
|
||||
<meta name="theme-color" content="#fff8f2" />
|
||||
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
|
||||
<title>Design — C243 · Busca por selfie na homepage</title>
|
||||
<style type="text/tailwindcss">
|
||||
@theme inline {
|
||||
--font-sans: Inter, Arimo, ui-sans-serif, system-ui, sans-serif;
|
||||
}
|
||||
|
||||
[data-theme='campaign-site'] {
|
||||
--pt-red: #a21c1c;
|
||||
--pt-red-dark: #47130e;
|
||||
--pt-yellow: #ffe607;
|
||||
--campaign-cream: #fff8f2;
|
||||
--campaign-ink: #000000;
|
||||
--campaign-muted: #6c615e;
|
||||
--campaign-surface: #f9faff;
|
||||
--campaign-band: #ebe9e9;
|
||||
--campaign-line: rgb(0 0 0 / 12%);
|
||||
--campaign-content-inset: clamp(20px, calc(25.36vw - 79.64px), 180px);
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: Inter, Arimo, ui-sans-serif, system-ui, sans-serif;
|
||||
}
|
||||
|
||||
.display {
|
||||
font-family: 'Exo 2', Inter, ui-sans-serif, system-ui, sans-serif;
|
||||
}
|
||||
|
||||
.campaign-section-eyebrow {
|
||||
font-size: clamp(10px, calc(0.32vw + 8.75px), 12px);
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
.campaign-section-title {
|
||||
font-size: clamp(28px, calc(1.15vw + 23px), 38px);
|
||||
line-height: 1.02;
|
||||
}
|
||||
|
||||
.campaign-section-copy {
|
||||
font-size: clamp(15px, calc(0.32vw + 13.75px), 17px);
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.stage {
|
||||
box-shadow: 0 24px 80px rgb(32 27 26 / 15%);
|
||||
}
|
||||
|
||||
.archive-focus:focus-visible {
|
||||
outline: 3px solid var(--pt-yellow);
|
||||
outline-offset: 3px;
|
||||
box-shadow: 0 0 0 6px rgb(24 78 146 / 72%);
|
||||
}
|
||||
|
||||
.primary-action {
|
||||
display: inline-flex;
|
||||
min-height: 44px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
border-radius: 10px;
|
||||
background: var(--pt-red);
|
||||
padding: 10px 16px;
|
||||
color: white;
|
||||
font-family: 'Exo 2', Inter, ui-sans-serif, system-ui, sans-serif;
|
||||
font-size: 14px;
|
||||
font-weight: 800;
|
||||
text-decoration: none;
|
||||
box-shadow: 0 4px 0 #7f1616;
|
||||
transition:
|
||||
transform 150ms ease-out,
|
||||
box-shadow 150ms ease-out;
|
||||
}
|
||||
|
||||
.primary-action:hover {
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.primary-action:active {
|
||||
transform: translateY(2px);
|
||||
box-shadow: 0 2px 0 #7f1616;
|
||||
}
|
||||
|
||||
.secondary-link {
|
||||
display: inline-flex;
|
||||
min-height: 44px;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
border-radius: 4px;
|
||||
color: var(--pt-red);
|
||||
font-size: 14px;
|
||||
font-weight: 800;
|
||||
text-decoration-line: underline;
|
||||
text-decoration-thickness: 1px;
|
||||
text-underline-offset: 4px;
|
||||
}
|
||||
|
||||
.secondary-link:hover {
|
||||
color: #741414;
|
||||
text-decoration-thickness: 2px;
|
||||
}
|
||||
|
||||
a {
|
||||
touch-action: manipulation;
|
||||
-webkit-tap-highlight-color: rgb(162 28 28 / 18%);
|
||||
}
|
||||
|
||||
.assurance-mark {
|
||||
background:
|
||||
radial-gradient(circle at 76% 18%, rgb(255 230 7 / 66%) 0 8%, transparent 8.5%),
|
||||
linear-gradient(145deg, #f9faff 0%, #eef4fb 100%);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.primary-action {
|
||||
transition: none;
|
||||
}
|
||||
|
||||
.primary-action:hover,
|
||||
.primary-action:active {
|
||||
transform: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 64rem) {
|
||||
[data-theme='campaign-site'] {
|
||||
--campaign-content-inset: max(180px, calc((100vw - 1152px) / 2 + 32px));
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body class="min-h-screen bg-[#efeeec] text-[#201b1a] antialiased">
|
||||
<svg class="absolute size-0 overflow-hidden" aria-hidden="true">
|
||||
<symbol id="spark" viewBox="0 0 24 24">
|
||||
<path d="m12 3-1.7 4.6L6 9.3l4.3 1.7 1.7 4.7 1.7-4.7L18 9.3l-4.3-1.7L12 3Z" />
|
||||
<path d="m19 14-.9 2.1L16 17l2.1.9L19 20l.9-2.1L22 17l-2.1-.9L19 14Z" />
|
||||
</symbol>
|
||||
<symbol id="device" viewBox="0 0 24 24">
|
||||
<rect x="5" y="2" width="14" height="20" rx="2" />
|
||||
<path d="M9 18h6" />
|
||||
</symbol>
|
||||
<symbol id="images" viewBox="0 0 24 24">
|
||||
<path d="m16 5 3 3M4 9V5a2 2 0 0 1 2-2h9l5 5v10a2 2 0 0 1-2 2h-4" />
|
||||
<rect x="2" y="11" width="12" height="10" rx="2" />
|
||||
<circle cx="6" cy="15" r="1" />
|
||||
<path d="m4 19 3-3 5 5" />
|
||||
</symbol>
|
||||
<symbol id="shield" viewBox="0 0 24 24">
|
||||
<path d="M20 13c0 5-3.5 7.5-8 9-4.5-1.5-8-4-8-9V5l8-3 8 3v8Z" />
|
||||
<path d="m9 12 2 2 4-4" />
|
||||
</symbol>
|
||||
<symbol id="arrow" viewBox="0 0 24 24"><path d="m9 18 6-6-6-6" /></symbol>
|
||||
<symbol id="check" viewBox="0 0 24 24"><path d="m5 12 4 4L19 6" /></symbol>
|
||||
</svg>
|
||||
|
||||
<main class="mx-auto flex max-w-[1480px] flex-col gap-14 px-4 py-10 md:px-8">
|
||||
<header class="max-w-4xl">
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<span class="rounded-full bg-[#a21c1c] px-3 py-1 text-xs font-extrabold text-white"
|
||||
>C243 · gate hi-fi</span
|
||||
>
|
||||
<span class="rounded-full border border-black/10 bg-white px-3 py-1 text-xs font-bold"
|
||||
>Homepage pública · aberta</span
|
||||
>
|
||||
<span
|
||||
class="rounded-full border border-[#184e92]/20 bg-[#eef4fb] px-3 py-1 text-xs font-extrabold text-[#184e92]"
|
||||
>Sem selfie, engine, fotos ou contadores na home</span
|
||||
>
|
||||
</div>
|
||||
<h1 class="display mt-4 text-3xl font-black tracking-[-0.03em]">
|
||||
A home apresenta a busca; a experiência sensível começa só em /fotos/encontre
|
||||
</h1>
|
||||
<p class="mt-2 max-w-3xl text-sm leading-6 text-[#6c615e]">
|
||||
Seção condicional, mobile-first, com uma ação dominante. Ela herda a gramática de bandas,
|
||||
inset e hierarquia da home e usa o azul do álbum apenas para explicar proteção e controle.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<section aria-labelledby="desktop-title">
|
||||
<p class="text-xs font-extrabold tracking-[0.1em] text-[#a21c1c] uppercase">
|
||||
Cena 01 · 1280
|
||||
</p>
|
||||
<h2 id="desktop-title" class="display mt-1 text-xl font-black">
|
||||
Entre a Central de Conteúdos e a newsletter
|
||||
</h2>
|
||||
<p class="mt-2 max-w-3xl text-sm leading-6 text-[#6c615e]">
|
||||
A banda creme interrompe o catálogo branco sem competir com a newsletter cinza. O texto
|
||||
explica o suficiente para uma decisão informada; o aviso completo e a autorização ficam na
|
||||
página da busca.
|
||||
</p>
|
||||
|
||||
<div class="stage mt-4 overflow-x-auto rounded-2xl border border-black/10 bg-white">
|
||||
<div class="min-w-[1280px] bg-white">
|
||||
<div
|
||||
aria-hidden="true"
|
||||
class="flex h-20 items-center justify-center border-b border-black/10 bg-white text-xs font-bold tracking-[0.08em] text-black/45 uppercase"
|
||||
>
|
||||
fim da seção · Central de Conteúdos
|
||||
</div>
|
||||
|
||||
<!-- Port classe-a-classe: section border-b bg-(--campaign-cream); container
|
||||
max-w-[1160px] px-5 sm:px-8 lg:px-10 py-12 lg:py-16. -->
|
||||
<section
|
||||
aria-labelledby="selfie-home-desktop-title"
|
||||
class="relative overflow-hidden border-b border-(--campaign-line) bg-(--campaign-cream)"
|
||||
>
|
||||
<div
|
||||
aria-hidden="true"
|
||||
class="pointer-events-none absolute -top-24 -right-20 size-64 rounded-full bg-(--pt-yellow)/45"
|
||||
></div>
|
||||
<div
|
||||
aria-hidden="true"
|
||||
class="pointer-events-none absolute -bottom-32 left-[36%] size-64 rounded-full bg-(--pt-red)/8"
|
||||
></div>
|
||||
|
||||
<div
|
||||
class="relative mx-auto grid w-full max-w-[1160px] grid-cols-[minmax(0,1.1fr)_minmax(360px,.9fr)] items-center gap-16 px-10 py-16"
|
||||
>
|
||||
<div class="max-w-[620px]">
|
||||
<p
|
||||
class="campaign-section-eyebrow m-0 font-black tracking-[0.1em] text-(--pt-red) uppercase"
|
||||
>
|
||||
Fotos da nossa caminhada
|
||||
</p>
|
||||
<h2
|
||||
id="selfie-home-desktop-title"
|
||||
class="campaign-section-title display m-0 mt-2 max-w-[560px] border-0 p-0 font-black tracking-[-0.03em] text-balance"
|
||||
>
|
||||
Encontre você nas fotos
|
||||
</h2>
|
||||
<p class="campaign-section-copy mt-4 max-w-[600px] text-(--campaign-muted)">
|
||||
Use uma selfie sua na página da busca para procurar, entre as fotos públicas
|
||||
aprovadas, aquelas em que você aparece.
|
||||
</p>
|
||||
|
||||
<div class="mt-5 flex max-w-[610px] items-start gap-3 text-sm leading-6">
|
||||
<div
|
||||
class="mt-0.5 grid size-9 shrink-0 place-items-center rounded-xl bg-[#184e92] text-white"
|
||||
>
|
||||
<svg aria-hidden="true" class="size-4 fill-none stroke-current stroke-2">
|
||||
<use href="#shield" />
|
||||
</svg>
|
||||
</div>
|
||||
<p class="m-0 text-[#365472]">
|
||||
<b class="text-[#143c70]">A selfie não sai do seu aparelho.</b> A busca cobre
|
||||
o índice anônimo do acervo aprovado, e você pode retirar seu rosto quando
|
||||
quiser.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="mt-7 flex flex-wrap items-center gap-x-6 gap-y-2">
|
||||
<a href="/fotos/encontre" class="primary-action archive-focus">
|
||||
Encontrar minhas fotos
|
||||
<svg aria-hidden="true" class="size-4 fill-none stroke-current stroke-2">
|
||||
<use href="#arrow" />
|
||||
</svg>
|
||||
</a>
|
||||
<a href="/fotos" class="secondary-link archive-focus">
|
||||
Ver o álbum
|
||||
<svg aria-hidden="true" class="size-4 fill-none stroke-current stroke-2">
|
||||
<use href="#arrow" />
|
||||
</svg>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="assurance-mark relative overflow-hidden rounded-2xl border border-[#184e92]/15 p-6"
|
||||
>
|
||||
<div
|
||||
aria-hidden="true"
|
||||
class="absolute top-5 right-5 grid size-12 place-items-center rounded-full bg-white text-[#184e92] shadow-[0_8px_28px_rgb(24_78_146/12%)]"
|
||||
>
|
||||
<svg aria-hidden="true" class="size-6 fill-none stroke-current stroke-2">
|
||||
<use href="#spark" />
|
||||
</svg>
|
||||
</div>
|
||||
<p class="display max-w-[250px] text-xl leading-tight font-black text-[#143c70]">
|
||||
Sua imagem fica com você. O controle também.
|
||||
</p>
|
||||
<ul class="mt-7 grid list-none gap-0 p-0">
|
||||
<li class="flex items-center gap-3 border-t border-[#184e92]/12 py-4">
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
class="size-5 shrink-0 fill-none stroke-[#184e92] stroke-2"
|
||||
>
|
||||
<use href="#device" />
|
||||
</svg>
|
||||
<span class="text-sm font-bold text-[#143c70]"
|
||||
>Processamento no aparelho</span
|
||||
>
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
class="ml-auto size-4 fill-none stroke-[#184e92] stroke-2"
|
||||
>
|
||||
<use href="#check" />
|
||||
</svg>
|
||||
</li>
|
||||
<li class="flex items-center gap-3 border-t border-[#184e92]/12 py-4">
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
class="size-5 shrink-0 fill-none stroke-[#184e92] stroke-2"
|
||||
>
|
||||
<use href="#images" />
|
||||
</svg>
|
||||
<span class="text-sm font-bold text-[#143c70]"
|
||||
>Só o acervo público aprovado</span
|
||||
>
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
class="ml-auto size-4 fill-none stroke-[#184e92] stroke-2"
|
||||
>
|
||||
<use href="#check" />
|
||||
</svg>
|
||||
</li>
|
||||
<li class="flex items-center gap-3 border-y border-[#184e92]/12 py-4">
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
class="size-5 shrink-0 fill-none stroke-[#184e92] stroke-2"
|
||||
>
|
||||
<use href="#shield" />
|
||||
</svg>
|
||||
<span class="text-sm font-bold text-[#143c70]"
|
||||
>Saída do índice a qualquer momento</span
|
||||
>
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
class="ml-auto size-4 fill-none stroke-[#184e92] stroke-2"
|
||||
>
|
||||
<use href="#check" />
|
||||
</svg>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="border-b border-black/10 bg-(--campaign-band) px-10 py-10 text-center">
|
||||
<p
|
||||
class="campaign-section-eyebrow font-black tracking-[0.1em] text-(--pt-red) uppercase"
|
||||
>
|
||||
Apoie e acompanhe
|
||||
</p>
|
||||
<p class="display mt-1 text-2xl font-black">Receba as novidades da campanha</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section aria-labelledby="mobile-title">
|
||||
<p class="text-xs font-extrabold tracking-[0.1em] text-[#a21c1c] uppercase">
|
||||
Cena 02 · 390
|
||||
</p>
|
||||
<h2 id="mobile-title" class="display mt-1 text-xl font-black">
|
||||
Mobile-first · uma ação dominante, sem simular captura
|
||||
</h2>
|
||||
|
||||
<div
|
||||
class="stage mt-4 w-[390px] overflow-hidden rounded-[30px] border border-black/10 bg-white"
|
||||
>
|
||||
<div
|
||||
aria-hidden="true"
|
||||
class="flex h-16 items-center justify-center border-b border-black/10 bg-white text-[10px] font-bold tracking-[0.08em] text-black/40 uppercase"
|
||||
>
|
||||
fim da Central de Conteúdos
|
||||
</div>
|
||||
|
||||
<section
|
||||
aria-labelledby="selfie-home-mobile-title"
|
||||
class="relative overflow-hidden border-b border-(--campaign-line) bg-(--campaign-cream)"
|
||||
>
|
||||
<div
|
||||
aria-hidden="true"
|
||||
class="pointer-events-none absolute -top-14 -right-14 size-40 rounded-full bg-(--pt-yellow)/45"
|
||||
></div>
|
||||
<div class="relative px-5 py-12">
|
||||
<p
|
||||
class="campaign-section-eyebrow m-0 font-black tracking-[0.1em] text-(--pt-red) uppercase"
|
||||
>
|
||||
Fotos da nossa caminhada
|
||||
</p>
|
||||
<h2
|
||||
id="selfie-home-mobile-title"
|
||||
class="display m-0 mt-2 max-w-[320px] border-0 p-0 text-[30px] leading-[1.02] font-black tracking-[-0.03em] text-balance"
|
||||
>
|
||||
Encontre você nas fotos
|
||||
</h2>
|
||||
<p class="mt-4 text-[15px] leading-6 text-(--campaign-muted)">
|
||||
Use uma selfie sua na página da busca para procurar as fotos públicas aprovadas em
|
||||
que você aparece.
|
||||
</p>
|
||||
|
||||
<div class="assurance-mark mt-6 rounded-2xl border border-[#184e92]/15 p-4">
|
||||
<div class="flex items-start gap-3">
|
||||
<div
|
||||
class="grid size-10 shrink-0 place-items-center rounded-xl bg-[#184e92] text-white"
|
||||
>
|
||||
<svg aria-hidden="true" class="size-5 fill-none stroke-current stroke-2">
|
||||
<use href="#shield" />
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-sm font-extrabold text-[#143c70]">Sua selfie fica no aparelho</p>
|
||||
<p class="mt-1 text-xs leading-5 text-[#365472]">
|
||||
A selfie não sai deste aparelho. A busca cobre o acervo aprovado, e você pode
|
||||
retirar seu rosto do índice quando quiser.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<a href="/fotos/encontre" class="primary-action archive-focus mt-6 w-full">
|
||||
Encontrar minhas fotos
|
||||
<svg aria-hidden="true" class="size-4 fill-none stroke-current stroke-2">
|
||||
<use href="#arrow" />
|
||||
</svg>
|
||||
</a>
|
||||
<a href="/fotos" class="secondary-link archive-focus mt-2 w-full justify-center">
|
||||
Ver o álbum
|
||||
<svg aria-hidden="true" class="size-4 fill-none stroke-current stroke-2">
|
||||
<use href="#arrow" />
|
||||
</svg>
|
||||
</a>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="bg-(--campaign-band) px-5 py-9 text-center">
|
||||
<p
|
||||
class="campaign-section-eyebrow font-black tracking-[0.1em] text-(--pt-red) uppercase"
|
||||
>
|
||||
Apoie e acompanhe
|
||||
</p>
|
||||
<p class="display mt-1 text-[22px] leading-tight font-black">
|
||||
Receba as novidades da campanha
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section
|
||||
aria-labelledby="rules-title"
|
||||
class="max-w-4xl rounded-2xl border border-black/10 bg-white p-6"
|
||||
>
|
||||
<p class="text-xs font-extrabold tracking-[0.1em] text-[#a21c1c] uppercase">
|
||||
Contrato do port
|
||||
</p>
|
||||
<h2 id="rules-title" class="display mt-1 text-xl font-black">Estados e acessibilidade</h2>
|
||||
<ul class="mt-4 grid list-none gap-3 p-0 text-sm leading-6 text-[#6c615e] sm:grid-cols-2">
|
||||
<li class="rounded-xl bg-[#f9faff] p-4">
|
||||
<b class="text-[#201b1a]">Fechada:</b> a seção inteira não é renderizada quando a flag,
|
||||
o álbum publicado ou as fotos aprovadas não liberam a busca. Não há placeholder, aviso
|
||||
nem CTA morto; Central de Conteúdos e newsletter se encostam pelo ritmo normal.
|
||||
</li>
|
||||
<li class="rounded-xl bg-[#f9faff] p-4">
|
||||
<b class="text-[#201b1a]">Hierarquia:</b> o título da seção é <code>h2</code>; há um
|
||||
único CTA preenchido. “Ver o álbum” permanece secundário, textual e com alvo mínimo de
|
||||
44 px.
|
||||
</li>
|
||||
<li class="rounded-xl bg-[#f9faff] p-4">
|
||||
<b class="text-[#201b1a]">Foco:</b> ambos os links usam o foco amarelo de 3 px do álbum,
|
||||
com offset de 3 px e separação azul externa para permanecer visível sobre creme,
|
||||
vermelho e branco.
|
||||
</li>
|
||||
<li class="rounded-xl bg-[#f9faff] p-4">
|
||||
<b class="text-[#201b1a]">Movimento:</b> só o CTA reage ao hover/press; em
|
||||
<code>prefers-reduced-motion: reduce</code>, transição e deslocamento são removidos.
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
76
docs/plans/busca-selfie-secao-home.md
Normal file
76
docs/plans/busca-selfie-secao-home.md
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
# C243 — Seção da busca por selfie na homepage pública
|
||||
|
||||
Status: aprovado (decisão do dono na sessão, 2026-10-01)
|
||||
Atualizado em: 2026-10-01
|
||||
Issue: — (worktree `work/43`, sem claim)
|
||||
Priority: P2
|
||||
Impeccable: C — seção nova na homepage pública (descoberta da busca por selfie)
|
||||
Design UI: docs/plans/busca-selfie-secao-home-ui-design.html
|
||||
Appetite: ~0,5–1 dia eng — **uma seção da home que apresenta e leva à busca por selfie**, sem duplicar a superfície do álbum
|
||||
Responsável: —
|
||||
|
||||
## Intenção
|
||||
|
||||
Com o C242 abrindo a busca por selfie a qualquer visitante, a homepage pública passa a ter uma porta para ela. Hoje a busca só é descoberta dentro de `/fotos` (banda da cena 01); o dono pediu (2026-10-01) **seção própria na homepage**, que aparece quando a busca está aberta e leva direto a `/fotos/encontre`.
|
||||
|
||||
A seção é descoberta, não uma segunda busca: nada de captura de selfie na home (o engine pesado roda só na página da busca, como hoje). Copy e visual seguem a gramática das seções da home e o aviso de biometria/LGPD aparece de forma honesta.
|
||||
|
||||
## Persona e fluxo
|
||||
|
||||
- **Persona / contexto:** visitante na home da campanha, no celular, que viu Solla num evento e não sabe que existe um álbum pesquisável.
|
||||
- **Job principal:** saber que dá para me encontrar nas fotos do mandato e chegar lá.
|
||||
- **Fluxo desejado:** rola a home → encontra a seção "Encontre você nas fotos" com explicação curta (selfie não sai do aparelho; acervo aprovado; dá para sair do índice) → toca o CTA → chega em `/fotos/encontre`.
|
||||
- **Anti-goals de produto:** não captura selfie na home; não lista pessoas; não promete "todas as fotos"; não vira carrossel de fotos com PII; não aparece fechada/quebrada.
|
||||
|
||||
## Objetivo e aceite
|
||||
|
||||
- A seção aparece na home **somente quando a busca está aberta** (flag `selfieSearchEnabled`, álbum publicado e fotos aprovadas) — fail-closed: nenhum CTA morto/404 enquanto fechada.
|
||||
- O CTA leva a `/fotos/encontre`; a seção tem título, explicação curta e um link secundário para o álbum (`/fotos`).
|
||||
- Mobile-first (390) e desktop (1280) fiéis ao design hi-fi aprovado; acessibilidade: heading na hierarquia da página, foco visível, contraste, `prefers-reduced-motion`.
|
||||
- Nenhum texto que prometa identificação de terceiros ou score; o aviso de biometria é o mesmo contrato do C242.
|
||||
|
||||
## Dados (intenção)
|
||||
|
||||
- **Vou apresentar dados?** Não.
|
||||
- **Forma:** N/A — sem números, sem contadores, sem "X fotos" (o acervo muda).
|
||||
|
||||
## Dados da decisão (literais)
|
||||
|
||||
- **Comportamento quando fechada — decisão do dono (2026-10-01):** "aparece quando aberta, mas já é pra abrir" → a seção é renderizada condicionada ao estado aberto e a abertura é feita na mesma entrega (ops do C242).
|
||||
- **Sem captura na home:** o engine de face não é carregado na homepage (peso ~7 MB de modelos + wasm); a home só apresenta e linka.
|
||||
- **Posição:** a definir no design hi-fi, entre as seções de conteúdo existentes (recomendação da engenharia: depois de `ContentPieceHomeSection`, antes da newsletter), sem quebrar o ritmo/altura das seções atuais.
|
||||
|
||||
## Direção no codebase (hipótese)
|
||||
|
||||
- **Áreas prováveis:** `src/app/(frontend)/(home)/page.tsx` (composição + gating), componente novo em `src/components/fotos/`, classes/tokens `campaign-section-*` de `styles.css` e os padrões de seção da home (`JingleHomeSection`, `ContentPieceHomeSection`, `CampaignCardsSection`).
|
||||
- **Precedente a olhar:** `SelfieSearchEntry.tsx` (banda do C234 em `/fotos`), `ContentPieceHomeSection.tsx` (seção condicional), `hasPublishedArchivePhotos` (flag cacheada) + `getCachedGlobal('photoAlbum')` (kill switches com tag própria).
|
||||
- **Risco de acoplamento:** a home usa reads cacheados (ISR/tag); a seção não pode introduzir leitura live de Consent (perda de estaticidade). Gatear por flag global + fotos aprovadas (ambos cacheados e revalidados no admin); misconfiguração de Consent cai no estado fechado da página de destino, nunca em 404.
|
||||
|
||||
## Dependências
|
||||
|
||||
- Duras: C242 (busca aberta a qualquer visitante) — a seção só faz sentido com ela.
|
||||
- Soft: nenhuma.
|
||||
|
||||
## Fora de escopo
|
||||
|
||||
- Captura/engine na home; carrossel de fotos; contadores; personalização por visitante.
|
||||
- Mudar a `/fotos` ou o fluxo de `/fotos/encontre` além da copy/porta do C242.
|
||||
|
||||
## Rabbit holes de produto
|
||||
|
||||
- **"Só completar" com prévia de fotos na home.** **Corte:** a home não renderiza fotos do acervo (PII + peso); só a banda de convite.
|
||||
- **"Só completar" com captura inline.** **Corte:** engine só em `/fotos/encontre`.
|
||||
|
||||
## Questões em aberto (produto)
|
||||
|
||||
- Nenhuma bloqueante; posição final e composição ficam no design hi-fi (gate visual).
|
||||
|
||||
## Referências
|
||||
|
||||
- `docs/plans/busca-fotos-por-selfie.md` (C234 — artefato de design a estender)
|
||||
- `docs/plans/busca-selfie-escopo-b.md` (C242 — dono do estado "aberta")
|
||||
- `src/components/fotos/SelfieSearchEntry.tsx` · `src/app/(frontend)/(home)/page.tsx`
|
||||
|
||||
## Self-score (shaping)
|
||||
|
||||
5/5 — (1) fatia = um outcome verificável (visitante descobre e chega à busca quando aberta; fechada não aparece); (2) appetite pequeno comporta design + componente + testes; (3) persona/job/aceite verificáveis; (4) direção no codebase com precedentes; (5) decisões duras (comportamento e captura) tomadas e registradas.
|
||||
1127
docs/plans/central-conteudos-cards-verticais-ui-design.html
Normal file
1127
docs/plans/central-conteudos-cards-verticais-ui-design.html
Normal file
File diff suppressed because it is too large
Load diff
125
docs/plans/central-conteudos-cards-verticais.md
Normal file
125
docs/plans/central-conteudos-cards-verticais.md
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
# S45 — Central de Conteúdos — cards verticais no catálogo e na seção da home
|
||||
|
||||
Status: rascunho
|
||||
Atualizado em: 2026-10-01
|
||||
Issue: #1410
|
||||
Priority: P1
|
||||
Impeccable: B — encaixe no slot/card existente, sem rota ou tela nova
|
||||
Design UI: docs/plans/central-conteudos-cards-verticais-ui-design.html
|
||||
Appetite: ~1–2 dias eng; um outcome verificável — o vertical aparece inteiro e o horizontal também, no catálogo e na seção da home
|
||||
Responsável: —
|
||||
|
||||
## Intenção
|
||||
|
||||
A Central de Conteúdos (`/conteudos`) tem 281 peças publicadas, quase todas vindas do Instagram: Reels em 9:16 e fotos de feed em 4:5. São justamente as formas verticais que o eleitor reconhece e repassa. Mas os cards do board foram desenhados para mídia horizontal — o slot é `aspect-video` (16:9) em todas as superfícies —, então o enquadramento vertical é cortado no `object-cover` e o board parece uma parede de thumbs horizontais, todos iguais.
|
||||
|
||||
O pedido é corrigir o enquadramento na Central e na seção dela na home (S39/S42): o card passa a apresentar a peça na forma em que ela respira — vertical é o padrão do board e nunca é cortado; peça genuinamente horizontal aparece inteira, em letterbox na superfície neutra, nunca esticada nem cortada. O board fica honesto: dá para reconhecer o Reel e a foto antes de decidir assistir ou baixar.
|
||||
|
||||
## Persona e fluxo
|
||||
|
||||
- **Persona / contexto:** eleitor/simpatizante no celular, chegando por link do WhatsApp ou rolando a home; reconhece o material pelo formato (Reel, foto de feed) e decide o que assistir, baixar ou repassar.
|
||||
- **Job principal:** reconhecer a peça no formato em que ela foi feita, sem enquadramento cortado que a descaracterize, e escolher o que consumir.
|
||||
- **Fluxo desejado:** abre `/conteudos` (ou passa pela seção da home) → vê cada peça na forma real: Reel em 9:16, foto em 4:5, arte de modelo vertical; peça horizontal inteira em letterbox → reconhece e escolhe → toca para reproduzir/baixar como hoje → no detalhe, se a página entrar no escopo, o mesmo enquadramento (coerência card→detalhe).
|
||||
- **Anti-goals de produto:** não é redesenho da Central nem da home; não cria rota, tela, player ou galeria; não mexe em filtros, busca, ações, kill switch ou copy; não carrega mídia sozinha; não vira masonry nem grade de altura variável; não puxa dimensão real de mídia (migration/ffprobe) nesta fatia.
|
||||
|
||||
### Esboço de fluxo (B)
|
||||
|
||||
```text
|
||||
[visitante no celular] → /conteudos (ou seção da Central na home)
|
||||
→ card da peça na forma em que ela respira
|
||||
├─ vertical (Reel 9:16 · foto 4:5 · arte de modelo S38 vertical)
|
||||
│ → enquadramento inteiro, nunca cortado
|
||||
├─ horizontal genuíno → peça inteira em letterbox na superfície neutra
|
||||
│ → nunca esticado, nunca cortado
|
||||
└─ áudio/texto/link → forma decidida pela coerência do board (sem enquadramento a preservar)
|
||||
→ itens sintéticos de modelo do S38 seguem a mesma grade (convite para /cards intacto)
|
||||
→ toque reproduz/baixa como hoje (mídia só no toque)
|
||||
[se a página da peça entrar no escopo] → /conteudos/<slug> com o mesmo enquadramento do card
|
||||
[peça despublicada] → some como hoje (kill switch intacto)
|
||||
```
|
||||
|
||||
### Design UI (B)
|
||||
|
||||
- Design UI (gate): `docs/plans/central-conteudos-cards-verticais-ui-design.html` — cenas do catálogo e da seção da home em ~390 e ~1280: card full vertical (vídeo 9:16, foto 4:5), compacto de foto, item de modelo S38 vertical, peça horizontal em letterbox e a grade sem overflow.
|
||||
|
||||
## Objetivo e aceite
|
||||
|
||||
- No catálogo `/conteudos` e na seção da Central na home, peça vertical aparece no enquadramento vertical recomendado, **nunca cortada** — Reel (9:16) e foto/carrossel (4:5) preservam o que o autor enquadrou.
|
||||
- Peça genuinamente horizontal aparece **inteira**, em letterbox na superfície neutra — nunca esticada nem cortada; o board deixa de ser uma parede de thumbs 16:9.
|
||||
- Os itens sintéticos de modelo do S38, que dividem a mesma grade, ganham arte vertical para a coerência do board — **sem mudar a semântica de convite para `/cards`** (seguem itens, não peças, sem cromo de mídia).
|
||||
- Guardrails: sem rota/tela nova; mídia continua só no toque (sem autoplay); reprodução, download, compartilhar, filtros, busca e copy intocados; kill switch instantâneo intocado; sem analytics nem PII nova; **nenhuma migration/schema/ffprobe decidido aqui** — v1 decide a forma pelo tipo, não pela dimensão real da mídia.
|
||||
- Celular primeiro: nenhum overflow horizontal novo (o e2e mede ≤1 px a 390) e nenhuma mídia pesada antecipada.
|
||||
- **Decidido no gate:** incluir também a página da peça (`ContentPieceDetail`) no mesmo enquadramento, pela coerência card→detalhe — nada de Issue sucessora.
|
||||
- Demais seções da home, shell/nav e ficha interna intocados.
|
||||
|
||||
## Dados (intenção)
|
||||
|
||||
- **Vou apresentar dados?** Não — é enquadramento visual, não número: nenhum contador, série, ranking ou métrica nova.
|
||||
- **Decisões desbloqueadas:** o eleitor reconhece a peça no formato real e decide o que consumir; a comunicação passa a ler o board como ele foi publicado (Reel × foto × horizontal). A contagem de circulação segue no mecanismo anônimo existente (C213), sem métrica nova.
|
||||
- **Forma:** _adiada ao plano de implementação_ — aqui só a restrição de produto: o formato apresentado é o da própria peça, nunca um recorte inventado.
|
||||
|
||||
## Dados da decisão (literais)
|
||||
|
||||
- Item `S45`; slug `central-conteudos-cards-verticais`; tipo `feature`; Priority `P1`; Impeccable `B` ("encaixe no slot/card existente, sem rota ou tela nova" — mesmo enquadramento de classe do C226); model `deepseek/deepseek-flash`.
|
||||
- Superfícies no escopo: (1) catálogo `/conteudos` — cards de peça full (video/audio/link) e compacto (foto/texto), **e** os itens sintéticos de modelo do S38 que compartilham a mesma grade (coerência do board, sem mudar a semântica de convite para `/cards`); (2) seção da home S39/S42 (`ContentPieceHomeCard`, thumb mobile de 124px e bloco `sm+`).
|
||||
- Regra de produto central: o card apresenta a peça na forma em que ela respira — **vertical é o padrão do board; o enquadramento de peça vertical nunca é cortado**. Peças genuinamente horizontais aparecem inteiras (**letterbox na superfície neutra**), nunca esticadas nem cortadas.
|
||||
- Formas recomendadas (o designer decide o número final no artefato): vídeo/Reel → **9:16**; foto/carrossel → **4:5**; arte dos itens de modelo S38 → **vertical**; áudio/texto/link não têm enquadramento a preservar — o designer decide a forma pela coerência do board.
|
||||
- Sem dado de orientação/dimensão no item público hoje: a v1 decide a forma **pelo tipo**, não pela dimensão real da mídia; se o designer/impl optar por forma adaptativa por dimensão real, isso é decisão de implementação, **não requisito de produto**.
|
||||
- Decisão do gate: incluir também o palco da página da peça (`ContentPieceDetail`) no mesmo item, pela coerência card→detalhe (`docs/plans/central-conteudos-cards-verticais-ui-design.html`, cena 05).
|
||||
- **Supersessão explícita:** a decisão D5 do C226 ("o slot é 16:9 nas três superfícies", `docs/plans/central-conteudos-preview-frame-video-impl.md:91`) fica **revogada na parte do 16:9**.
|
||||
- Relação **#1399 C240** (carrossel como conteúdo de primeira classe, `in-progress`, plano+design commitados, ainda sem código): reescreve os MESMOS arquivos (`contentPieceCatalog.ts`, `ContentPieceCard/Media/Detail`, catálogo/página pública) e seu design usa stage `aspect-video`. S45 **não roda em paralelo com C240** — o registrador grava `serializes: []` e a ordem fica **sem fixação** (decisão do gate): o executor coordena no claim; quem rodar depois porta sobre a base do outro (o design do C240 se ajusta ao palco vertical se o S45 vier primeiro).
|
||||
- Relação **#1358 C228** (P3, aberto): é só cromo do mesmo slot (play 68px, acentos, badge) e o body manda fechá-lo antes de mexer no `ContentPieceMedia`. Para o S45, **C228 não bloqueia** (cromo ≠ ratio); o executor deve saber que ele existe e não puxar o cromo para dentro desta fatia.
|
||||
- Fora de escopo (literal): galeria multi-mídia do C240; cromo do C228; imagem OG; filtros/busca/ações/kill switch/copy; ficha interna da assessoria; acervo/outras verticais; redesenho do shell/nav/home além do card da seção.
|
||||
|
||||
## Direção no codebase (hipótese)
|
||||
|
||||
- **Cards hoje:** `ContentPieceCard.tsx:99-129` compacto (foto/texto/outro) com thumb `h-24 w-32`; `:132-162` card full com `ContentPieceMedia className="aspect-video"` (`:143`). `ContentPieceCatalog.tsx:47-53` divide large (video/audio/link) vs compact (image/text/other); grids `sm:grid-cols-2 lg:grid-cols-3` (`:67`) e `sm:grid-cols-2` (`:79`). `ContentPieceHomeCard.tsx:74-87`: mobile `grid-cols-[124px_1fr]`, mídia `aspect-video self-start` (`:86`); `ContentPieceHomeBoard.tsx:241-245` grade `sm:grid-cols-2 lg:grid-cols-3`. `ContentCatalogCardItem.tsx:23-58,68-109`: arte `min-h-40 sm:aspect-video` (`:26`) e `grid-cols-[128px_1fr] sm:block` (`:75`).
|
||||
- **Slot de mídia:** `ContentPieceMedia.tsx:110-126` — o slot não tem aspecto próprio; o host passa a classe. Imagem `object-cover` (`:190`), frame de vídeo `object-cover` (`:277`), vídeo em play `object-contain` (`:235`). Usado por catálogo, card da home e página da peça (`ContentPieceDetail.tsx:53-61`, slot `aspect-video` em `:60`).
|
||||
- **Sem dado de orientação:** `ContentPiecePublicItem` (`contentPieceCatalog.ts:364-404`) não tem width/height; `ContentPiecePublicFile` (`:406-411`) só id/path/mimeType/downloadFilename; `mediaOf` (`:672-680`) descarta `url/thumbnailURL/width/height`. O DB tem dims só para imagem (`src/payload-types.ts:1398-1399`; sharp em `payload.config.ts:188`), mas o VM descarta; vídeo não tem dims em lugar nenhum (sem ffprobe). O frame do C226 preserva o aspecto com ffmpeg `scale=640:-2` (`contentPieceFrame.ts:102`) e o VM só expõe `framePath` (`contentPieceCatalog.ts:757-763`), nunca dims.
|
||||
- **Precedentes visuais verticais:** `CampaignStorySection.tsx:50-52` (`aspect-[9/16]`, `max-w-[420px] lg:max-w-[300px]`); reels internos `ReelLibraryCard.tsx:13`/`ReelPlayer.tsx:12,26` (`aspect-[9/16]`); home S3 `CampaignContentCard.tsx:16-17,44` (`coverAspect 'video'|'square'`); `/fotos` `ArchivePhotoCard.tsx:37` (`aspect-square sm:aspect-[4/3]`); `/cards` `CardModelTile.tsx:16,44-45` usa spacer in-flow (bug WebKit com aspect-ratio); modelos verticais em `cardModels.ts:90-161` (1080×1440, 1000×1440, 1080×1920).
|
||||
- **Evidência do volume:** 281 peças publicadas, todas Instagram (`docs/changelog/2026-10-01-c230-prune.md:1`); Reels = vídeo e feed = foto pelo MIME (`contentPiece.ts:248-264`); stories nunca entram (C230). Não há medição de proporção vertical×horizontal no repo.
|
||||
- **Testes a respeitar:** `tests/e2e/frontendConteudos.e2e.spec.ts` (contagens `article[data-content-piece]`, frame antes/depois do play `:342,360`, seção da home `:745-805`, overflow ≤1 em 390, bounding boxes `:908-912`; frame stubado 320×180 `:212-224`); units `contentPieceMedia.unit.spec.tsx`, `contentPieceHomeSelection.unit.spec.ts:84-108` (pina keys da projeção lean — não engordar), `contentPieceCatalog.unit.spec.ts`; manifesto e2e já cobre `components/conteudos`/`(home)`/`conteudos` (`scripts/lib/e2e-affected-manifest.mjs:170-201`).
|
||||
- **Risco de acoplamento:** o slot `ContentPieceMedia` é compartilhado (catálogo, home, detalhe) — o ratio vale para os hosts atuais e futuros; C240 reescreve os mesmos arquivos; os bounding boxes do e2e e o frame stub 320×180 podem acusar a mudança de ratio; não editar as seções irmãs da home.
|
||||
|
||||
## Dependências
|
||||
|
||||
- Nenhuma dura — catálogo (S27/S28), itens de modelo (S38), seção da home (S39/S42) e frame do C226 já estão no repo.
|
||||
- **#1399 C240** — relação registrada acima: serializa (ordem sem fixação; coordenação no claim); sem código ainda. **#1358 C228** — não bloqueia (cromo ≠ ratio); ciência do executor.
|
||||
- Design UI aprovado no gate.
|
||||
|
||||
## Fora de escopo
|
||||
|
||||
- Galeria multi-mídia do C240 e a promoção de carrossel a conteúdo de primeira classe.
|
||||
- Cromo do C228 (play 68px, acentos radiais, badge, sombra) e qualquer polimento visual do slot.
|
||||
- Imagem OG; filtros, busca, ações, kill switch e copy; ficha interna da assessoria.
|
||||
- Acervo de falas e outras verticais internas; redesenho do shell/nav/home além do card da seção.
|
||||
- Forma adaptativa por dimensão real de mídia (migration/ffprobe) e qualquer mudança de schema.
|
||||
|
||||
## Rabbit holes de produto
|
||||
|
||||
- **"Já que verticaliza, redesenha a Central inteira".** Se alguém "só completar": novo board, nova hierarquia, header, filtros. **Corte neste item:** só o enquadramento dos cards e a grade existentes.
|
||||
- **"Masonry/altura variável por peça".** Se alguém "só completar": layout novo, colunas quebradas, e2e de overflow refeito. **Corte:** grade atual, uma forma por tipo de peça.
|
||||
- **"Detecta a dimensão de toda mídia agora".** Se alguém "só completar": migration de width/height, ffprobe no acervo, backfill. **Corte:** v1 decide pelo tipo; adaptativa é decisão de implementação futura, não requisito.
|
||||
- **"Cover em tudo para o board ficar uniforme".** Se alguém "só completar": corta o vertical para preencher o slot e destrói o pedido. **Corte:** vertical inteiro; horizontal em letterbox.
|
||||
- **"Autoplay no card para aproveitar o formato".** Se alguém "só completar": vídeo carregando no board, quebra do contrato do S27. **Corte:** mídia só no toque, como hoje.
|
||||
|
||||
## Questões em aberto (produto)
|
||||
|
||||
- **Forma por tipo ou adaptativa pela dimensão real da mídia?** **Decidido no gate:** **A** — por tipo na v1 (vídeo 9:16, foto 4:5, arte de modelo 3:4); adaptativa por dimensão real vira decisão de implementação posterior, sem migration/ffprobe nesta fatia.
|
||||
- **Foto compacta continua linha ou vira card vertical cheio?** **Decidido no gate:** **A** — mantém a linha compacta e corrige o enquadramento do thumb (96×120, 4:5), preservando a leitura de varredura do board.
|
||||
- **A página da peça entra no mesmo item?** **Decidido no gate:** **A** — sim, `ContentPieceDetail` com o mesmo palco vertical (coerência card→detalhe; cena 05 do artefato).
|
||||
- **Onde ficam as ações no card vertical?** **Decidido no gate:** **A** — abaixo da mídia, como hoje; mantém os alvos de toque do S27.
|
||||
- **Áudio e link ficam verticais ou largos?** **Decidido no gate:** **B** — permanecem largos (não há enquadramento a preservar); decisão fechada no artefato.
|
||||
|
||||
## Referências
|
||||
|
||||
- GitHub Issue — a registrar (`pnpm agent:register`).
|
||||
- Design UI (gate): `docs/plans/central-conteudos-cards-verticais-ui-design.html`.
|
||||
- Planos irmãos: `central-conteudos-publica.md` (S27) · `central-conteudos-cards-no-catalogo.md` (S38) · `central-conteudos-secao-home.md` (S39) · `central-conteudos-secao-home-share-filtro.md` (S42) · `central-conteudos-preview-frame-video.md` e `-impl.md:91` (C226, D5 superseded na parte do 16:9) · `central-conteudos-carrossel.md` (C240, #1399).
|
||||
- Arquivos-pista: `src/components/conteudos/ContentPieceCard.tsx:99-162` · `ContentPieceCatalog.tsx:47-79` · `ContentPieceHomeCard.tsx:74-87` · `ContentPieceHomeBoard.tsx:241-245` · `ContentCatalogCardItem.tsx:23-109` · `ContentPieceMedia.tsx:110-277` · `ContentPieceDetail.tsx:53-61` · `src/lib/contentPieceCatalog.ts:364-411,672-680,757-763` · `src/components/campaign/.../CardModelTile.tsx:16,44-45` e `src/lib/cardModels.ts:90-161`.
|
||||
- Testes: `tests/e2e/frontendConteudos.e2e.spec.ts:212-224,342,360,745-805,908-912` · units de `contentPieceMedia`/`contentPieceHomeSelection`/`contentPieceCatalog` · `scripts/lib/e2e-affected-manifest.mjs:170-201`.
|
||||
- `AGENTS-public.md` — convenções do site público (mídia, cache, kill switch).
|
||||
|
||||
## Self-score (shaping)
|
||||
|
||||
**5/5** — (1) fatia = um outcome verificável (vertical inteiro, horizontal em letterbox, no catálogo e na home); (2) appetite ~1–2 dias cabe: enquadramento no slot/cards existentes, sem rota, tela ou migração; (3) persona/job/aceite em linguagem de produto, com a regra central e os guardrails; (4) direção no codebase é hipótese, com achados e precedentes citados como pista; (5) zero decisão dura de engenharia — sem schema/migration/ffprobe, com as cinco dúvidas de produto posicionadas e as relações C240/C228 registradas.
|
||||
1335
docs/plans/home-colinha-estadual-ui-design.html
Normal file
1335
docs/plans/home-colinha-estadual-ui-design.html
Normal file
File diff suppressed because it is too large
Load diff
127
docs/plans/home-colinha-estadual.md
Normal file
127
docs/plans/home-colinha-estadual.md
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
# Home — escolher o estadual da dobradinha, montar e compartilhar a colinha
|
||||
|
||||
Status: rascunho
|
||||
Atualizado em: 2026-10-01
|
||||
Issue: #1404
|
||||
Priority: P1
|
||||
Impeccable: B — seção nova na home com seletor próprio e reuso da folha de compartilhamento
|
||||
Design UI: docs/plans/home-colinha-estadual-ui-design.html
|
||||
Appetite: ~1,5–2 dias eng; um outcome verificável (o visitante sai da home com a colinha do estadual — PNG e mensagem — e o link reabre a mesma colinha)
|
||||
Responsável: —
|
||||
|
||||
## Intenção
|
||||
|
||||
Na reta final até 04/10, quem já está com Solla no grupo de WhatsApp precisa da colinha certa: o número do deputado estadual da dobradinha do seu território. A colinha já existe dentro do estúdio de cards (modelo `Minha colinha`, S31/S34) e a escolha do estadual vive dentro do composer — quem chega pela home não descobre que isso existe nem tem um caminho de um toque até o estadual dele. Este item dá à home uma seção própria: a lista dos estaduais com busca e card (foto, nome, número), a colinha montada no mesmo editor e o compartilhamento no mesmo idioma da Central de Conteúdos. É uma porta de entrada nova para o mesmo produto, não um segundo estúdio.
|
||||
|
||||
A campanha tem as dobradinhas na plataforma (`stateDeputy`) e o material de divulgação da Plenária da Vitória (54 dobradinhas, foto + card). A home mostra só quem casa nas duas pontas — quem não tem número/foto não aparece (fail-closed), porque a base não tem número de urna e nada é inventado.
|
||||
|
||||
## Persona e fluxo
|
||||
|
||||
- **Persona / contexto:** militante/eleitor no celular, grupo de WhatsApp aberto, já decidido no 1313, querendo o número do estadual da dobradinha do seu município — chegou pela home ou recebeu um link.
|
||||
- **Job principal:** achar o seu estadual, sair com a colinha pronta (PNG + mensagem) e mandar para o grupo sem cadastro, sem digitar e sem errar o número.
|
||||
- **Fluxo desejado:** rola a home até a seção nova (ou abre o link direto recebido) → a prévia da colinha já aparece na própria seção com `Baixar` e `Compartilhar` sempre disponíveis → digita o nome na busca e escolhe o estadual (desktop: rolagem vertical da lista; mobile: carrossel horizontal de uma linha) → a prévia atualiza na hora com a linha do estadual preenchida → baixa o PNG 1080×1920 → compartilha no WhatsApp (mensagem editável + link) ou manda o PNG pela folha do aparelho (Instagram e afins) → quem recebe o link cai na mesma seção com a colinha daquele estadual. **Sem escolha, a colinha é válida:** sai só com as cinco linhas fixas e o link sem `?estadual=`.
|
||||
- **Anti-goals de produto:** segundo estúdio/editor; diálogo de montagem separado (a prévia é embutida); mini-CMS de dobradinhas; ranking/placar de estaduais; paginação/“carregar mais”; página por estadual nesta fatia; PII, cadastro, upload ou foto do visitante; envio automático ou destinatário; qualquer métrica nova.
|
||||
|
||||
### Esboço de fluxo (B)
|
||||
|
||||
```text
|
||||
[home: nova seção (ou link direto /?estadual=<slug>#colinha)]
|
||||
→ prévia da colinha SEMPRE visível na seção + Baixar/Compartilhar SEMPRE habilitados
|
||||
→ busca "meu estadual" → lista com cards (foto · nome · número)
|
||||
desktop: grade em rolagem vertical (sem paginação) · mobile: carrossel horizontal de uma linha
|
||||
→ escolhe (opcional) → a prévia atualiza na hora com a linha do estadual preenchida
|
||||
→ baixa o PNG 1080×1920 (sem escolha: só as cinco linhas fixas)
|
||||
→ compartilha: WhatsApp (mensagem editável + link) · folha nativa com o PNG (senão baixa) · copiar link
|
||||
→ quem recebe o link cai na mesma seção com a colinha daquele estadual
|
||||
[candidato sem material oficial / slug desconhecido] → não aparece na lista / cai no estado normal (fail-closed)
|
||||
```
|
||||
|
||||
### Design UI (B)
|
||||
|
||||
- Design UI (gate): `docs/plans/home-colinha-estadual-ui-design.html` (+ assets em `home-colinha-estadual-ui-design-assets/`) — cenas: seção com busca, lista (desktop em rolagem vertical; mobile em carrossel horizontal de uma linha) e a **prévia da colinha embutida** nos dois estados (sem estadual = cinco linhas fixas; com estadual = linha preenchida), busca ativa/estado vazio, chegada pelo link direto (prévia já preenchida, sem diálogo), folha de compartilhamento e o recorte de candidato sem material (não aparece na lista); ~390 e ~1280. Posição da seção na home (sugestão: logo depois da seção `#cards`, antes da Central) entra na cena do fluxo para validação no gate.
|
||||
|
||||
## Objetivo e aceite
|
||||
|
||||
- A home ganha a seção âncora (`#colinha`) com busca de estadual; cada card mostra foto, nome e número; a lista é a interseção plataforma × material — sem material oficial, o estadual não aparece, nunca com número/foto inventados.
|
||||
- A **prévia da colinha vive na própria seção** e é o estado inicial: sem nenhum estadual escolhido ela mostra só as cinco linhas fixas; escolhido um card, a linha `DEPUTADO ESTADUAL` preenche na hora e as cinco linhas fixas ficam intocadas. Não há diálogo de montagem separado.
|
||||
- `Baixar o PNG` e `Compartilhar` ficam **sempre habilitados**, com ou sem estadual escolhido; sem escolha, o PNG sai com as cinco linhas fixas e o compartilhamento usa a mensagem/link sem o estadual.
|
||||
- O download é o mesmo PNG 1080×1920 do estúdio — mesmo render, um só editor; nenhuma segunda via de geração.
|
||||
- Navegação da lista **sem paginação**: no desktop os cards rolam verticalmente (grade na própria página, todos alcançáveis); no mobile são **um carrossel de uma linha** com rolagem horizontal — nenhum botão de página/“carregar mais”.
|
||||
- Compartilhar usa a mesma folha/vocabulário: WhatsApp com mensagem editável + link, folha nativa do aparelho com o PNG gerado (fallback: baixar o PNG) e copiar link; sem destinatário e sem envio automático.
|
||||
- O link direto `/?estadual=<slug>#colinha` reabre a seção com aquele estadual pré-selecionado e a prévia já preenchida; sem `?estadual` o link abre a seção no estado sem escolha; slug desconhecido ou sem material cai no estado normal, sem erro.
|
||||
- Sem PII, sem login, sem upload e sem `Consent` novo; a nota de privacidade do estúdio continua verdadeira e a foto do visitante não entra aqui.
|
||||
- Sem candidato com material, a seção continua útil: a lista mostra o estado vazio e a colinha (sem estadual) segue baixável/compartilhável; sem overflow horizontal fora do carrossel mobile.
|
||||
|
||||
## Dados (intenção)
|
||||
|
||||
- **Vou apresentar dados?** Não.
|
||||
- **Decisões desbloqueadas:** N/A — nenhuma decisão nova; a leitura de uso segue sendo a do contador anônimo existente (S32) se o download for o mesmo, sem evento novo.
|
||||
- **Forma:** _adiada ao plano de implementação_ — restrição de produto: nenhuma métrica/superfície de dados nasce aqui.
|
||||
|
||||
## Dados da decisão (literais)
|
||||
|
||||
- Item `S43`; slug `home-colinha-estadual` (arquivo `docs/plans/home-colinha-estadual.md`); tipo `feature`; Priority `P1`; Impeccable `B — seção nova na home com seletor próprio e reuso da folha de compartilhamento`; Design UI `docs/plans/home-colinha-estadual-ui-design.html`.
|
||||
- Fonte da lista: dobradinhas da plataforma (`stateDeputy`), **excluindo** registros cujo nome contenha "apagar" (case-insensitive; convenção da equipe para marcar registros a remover); a lista exibida é a **interseção** com quem tem material oficial (foto + número).
|
||||
- Material da Plenária da Vitória (origem fora do repo; o repo recebe só derivativos otimizados, convenção S30): `/home/fsolla/Downloads/CARDS-PLENARIA-DA-VITORIA/<Nome> - card.png`, `/home/fsolla/Downloads/DOBRADINHAS-ORGANIZADAS/<Nome>/foto.png` e a lista `/home/fsolla/Downloads/DOBRADINHAS-ORGANIZADAS/LISTA-DOBRADINHAS.txt` — 54 dobradinhas.
|
||||
- Descompasso conhecido a resolver no cruzamento (mapa explícito e versionado, nunca casamento por semelhança em tempo de render): `Dr. Armando` tem material e não tem entrada no catálogo S30; `Marlenne` (material) ≠ `Marlene do Sindicato` (catálogo); `Radiovaldo Costa` (material) ≠ `Radiovaldo` (catálogo).
|
||||
- Colinha: model id `minha-colinha`; saída PNG 1080×1920; as cinco linhas fixas já contratadas (S31/S34) ficam intocadas — só a linha `DEPUTADO ESTADUAL <nome de urna> — <5 dígitos>` é preenchida. **Dois estados válidos:** sem estadual (a prévia/PNG sai só com as cinco linhas fixas) e com estadual (linha preenchida).
|
||||
- Navegação da lista: **desktop = rolagem vertical** (grade que flui na página; sem paginação); **mobile = carrossel horizontal de uma linha** (todos os estaduais alcançáveis por rolagem lateral); nunca paginação/“carregar mais”.
|
||||
- Link direto: `/?estadual=<slug>#colinha` (com estadual) e `/#colinha` (sem estadual); sem rota nova nesta fatia; slug desconhecido/sem material cai no estado normal da seção, sem erro.
|
||||
- Copy da mensagem (assumida — validar com produto): com estadual `Montei minha colinha: [NOME] [NÚMERO] para deputado estadual, com Jorge Solla 1313. Monte a sua: [link]`; **sem estadual** `Montei minha colinha de votação com Jorge Solla 1313. Monte a sua: [link]`; alternativa com estadual `Colinha pronta: 1313 para deputado federal e [NÚMERO] para estadual. Monte a sua: [link]`.
|
||||
- Share: WhatsApp com a mensagem editável + link; Instagram/outros pela folha nativa do aparelho com o PNG gerado (fallback: baixar o PNG); copiar link — sem destinatário e sem envio automático; nenhum canal novo.
|
||||
- Sem PII, sem login, sem upload, sem `Consent` novo; a foto do card é do candidato (asset do site), a do visitante não entra neste fluxo.
|
||||
|
||||
## Direção no codebase (hipótese)
|
||||
|
||||
- **Áreas prováveis:** nova seção na home (`src/app/(frontend)/(home)/page.tsx`) no padrão server → ilha client da S39/S42 (`ContentPieceHomeSection` → `ContentPieceHomeBoard`); o funil de cards em `src/components/cards/` (`CardComposer`, `StateDeputySelect`, `cardCanvas`); a folha de share em `src/components/conteudos/ContentPieceShareSheet.tsx`; catálogo no formato de `src/lib/stateDeputyCatalog.ts` (pista, não necessariamente o dono da nova lista); geração do cruzamento com precedentes `scripts/build-state-deputy-card-assets.mjs` e `scripts/regenerate-municipality-catalog-snapshot.mjs`.
|
||||
- **Precedente a olhar:** S39/S42 (seção na home + folha de compartilhar), S27 (`ContentPieceShareSheet`), S30/S31/S34 (catálogo, seletor e colinha), S32/C213 (contador anônimo).
|
||||
- **Risco de acoplamento:** o estúdio tem UM editor — a seção só abre o mesmo fluxo, nunca um render/download paralelo; a folha é o único mecanismo de share; diretório novo sem entrada no `scripts/lib/e2e-affected-manifest.mjs` falha fechado (`unmapped-risk`).
|
||||
|
||||
## Dependências
|
||||
|
||||
- S30 (#1271), S31 (#1272) e S34 (#1298) entregues — catálogo, seletor e colinha reusados.
|
||||
- Material da Plenária da Vitória disponível fora do repo (paths acima); sem ele não há foto/número novos.
|
||||
- Design hi-fi aprovado no gate. Soft: S32/C213 (contador anônimo) — se o download for o mesmo, nada muda.
|
||||
|
||||
## Fora de escopo
|
||||
|
||||
- Segundo editor/estúdio; **diálogo/step separado para montar a colinha** (a prévia é embutida na seção e atualiza na escolha); mudar os modelos existentes ou o conteúdo das cinco linhas fixas; mexer na seção `#cards` ou em `/cards`.
|
||||
- Paginação, “carregar mais” ou qualquer corte da lista; rota/página por estadual com metadata própria (`/colinha/<slug>`) — item próprio se o preview social do link medir.
|
||||
- Mini-CMS/collection/toggle novo para dobradinhas (salvo se a Questão 1 mudar).
|
||||
- Ranking, força, prioridade, contagem por estadual ou qualquer métrica nova; A4/impressão.
|
||||
- PII/cadastro/foto do visitante/upload; novos canais de compartilhamento.
|
||||
|
||||
## Rabbit holes de produto
|
||||
|
||||
- **"Já que tem seção, mostra o estúdio inteiro".** Se alguém "só completar": galeria dos seis modelos e busca de tudo na home. **Corte neste item:** só a colinha; a lista e a prévia vivem na seção.
|
||||
- **"Escolher o estadual vira obrigatório".** Se alguém "só completar": `Baixar`/`Compartilhar` desabilitados até escolher. **Corte neste item:** sem estadual é estado válido — a colinha sai com as cinco linhas fixas e o link sem `?estadual=`.
|
||||
- **"A lista vira mini-CMS/ranking".** Se alguém "só completar": prioridade, força eleitoral, ordenação por votos. **Corte neste item:** ordem estável do material, sem métrica; curadoria continua na plataforma.
|
||||
- **"Lista longa pede paginação".** Se alguém "só completar": páginas ou “carregar mais” cortam os 54. **Corte neste item:** rolagem vertical no desktop e carrossel horizontal no mobile — a lista inteira sempre alcançável.
|
||||
- **"Completar quem não tem material".** Se alguém "só completar": aproximar número de outra fonte ou usar foto genérica. **Corte neste item:** fail-closed — sem foto+número oficiais, o estadual não aparece.
|
||||
- **"Segundo mecanismo de compartilhar".** Se alguém "só completar": folha própria com mensagem divergente. **Corte neste item:** a folha existente é o único mecanismo.
|
||||
- **"Prometer anexo no WhatsApp".** Se alguém "só completar": dizer que o PNG vai junto no `wa.me` (não vai). **Corte neste item:** WhatsApp = mensagem + link; o PNG vai pela folha nativa ou pelo download.
|
||||
|
||||
## Questões em aberto (produto)
|
||||
|
||||
- **Qual a fonte da verdade da lista cruzada?** **Opções:** A) a plataforma segue a fonte de quem é dobradinha (filtro "apagar") e foto/número vêm do material, com o cruzamento gerado e versionado | B) número e foto viram campos preenchidos na plataforma (+ publicação para o site) | C) lista digitada à mão no site. **Recomendação:** A — ninguém cadastra duas vezes e a curadoria fica no mapa versionado; B vira item próprio se a equipe quiser operar a lista sem deploy. _(assumido — validar com produto)_
|
||||
- **Link direto nesta fatia?** **Opções:** A) `/?estadual=<slug>#colinha` na home, sem rota nova | B) `/colinha/<slug>` com título/descrição por estadual (preview melhor no link compartilhado, nova URL pública). **Recomendação:** A agora; B vira item próprio se o preview social do link for pedido. _(assumido — validar com produto)_
|
||||
- **Qual copy da mensagem?** **Opções:** A) com estadual `Montei minha colinha: [NOME] [NÚMERO] para deputado estadual, com Jorge Solla 1313. Monte a sua: [link]` (sem estadual cai no literal sem nome/número) | B) `Colinha pronta: 1313 para deputado federal e [NÚMERO] para estadual. Monte a sua: [link]`. **Recomendação:** A — nomeia o estadual e chama a montagem. _(assumido — validar com produto)_
|
||||
- **Se a lista cruzada vier vazia, a seção aparece?** **Opções:** A) sim — busca com estado vazio e a colinha (sem estadual) seguem baixável/compartilhável | B) não aparece (kill switch do rascunho anterior). **Recomendação:** A — “Baixar/Compartilhar sempre disponíveis” e a colinha sem estadual é estado válido. _(assumido — validar com produto)_
|
||||
|
||||
## Referências
|
||||
|
||||
- GitHub Issue: #1404.
|
||||
- Design UI (gate): `docs/plans/home-colinha-estadual-ui-design.html` (+ assets em `home-colinha-estadual-ui-design-assets/`).
|
||||
- `docs/plans/cards-estadual-dobradinha.md` (S30), `cards-colinha.md` (S31), `cards-colinha-arte-exata.md` (S34), `cards-analytics.md` (S32); `central-conteudos-secao-home-share-filtro.md` (S42 — seção na home + folha de share).
|
||||
- `src/components/cards/StateDeputySelect.tsx`, `CardComposer.tsx`, `cardCanvas.ts`, `src/lib/stateDeputyCatalog.ts`, `cardRender.ts`/`cardColinha.ts`; `src/components/conteudos/ContentPieceShareSheet.tsx`, `ContentPieceHomeSection.tsx`; `src/app/(frontend)/(home)/page.tsx`; `scripts/lib/e2e-affected-manifest.mjs`.
|
||||
- Material externo: `/home/fsolla/Downloads/CARDS-PLENARIA-DA-VITORIA/`, `/home/fsolla/Downloads/DOBRADINHAS-ORGANIZADAS/` (54 dobradinhas; `LISTA-DOBRADINHAS.txt`).
|
||||
|
||||
## Self-score (shaping)
|
||||
|
||||
1. Fatia = um outcome verificável? 5/5 — o visitante escolhe o estadual na home e sai com a colinha (PNG + share); o link reabre a mesma colinha.
|
||||
2. Appetite declarado e a intenção cabe nele? 4/5 — ~1,5–2 dias: seção nova + lista cruzada versionada, reusando editor e folha existentes; o cruzamento plataforma×material é o delta.
|
||||
3. Persona + job + aceite claros (sem jargão de stack)? 5/5 — fluxo em linguagem de eleitor, reta final de eleição.
|
||||
4. Direção no codebase é hipótese (não contrato técnico)? 5/5 — arquivos e paths são pista do estado atual; nenhuma schema/signature prescrita.
|
||||
5. Zero decisões duras de engenharia no plano? 4/5 — materialização do cruzamento e forma do link direto ficam nas questões abertas; a escolha final é da implementação.
|
||||
|
||||
Média: 4,6/5 — ≥4/5.
|
||||
141
docs/plans/secao-home-plenaria-da-vitoria-impl.md
Normal file
141
docs/plans/secao-home-plenaria-da-vitoria-impl.md
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
# Impl: S44 — Home — seção da Plenária da Vitória (divulgação e acesso)
|
||||
|
||||
Status: aprovado
|
||||
Atualizado em: 2026-10-01
|
||||
Issue: #1408
|
||||
Intenção: docs/plans/secao-home-plenaria-da-vitoria.md
|
||||
Design UI (gate): docs/plans/secao-home-plenaria-da-vitoria-ui-design.html
|
||||
Appetite restante: herdado (~0,5–1 dia eng) — uma seção condicional na home, sem migration.
|
||||
|
||||
## Leitura da intenção
|
||||
|
||||
- **Outcome:** a home divulga a Plenária da Vitória logo depois do hero e leva a `/plenaria-vitoria` em um toque — pré-live mostra o convite (imagem + data/hora da Bahia + `Adicionar à agenda`, sem botão de entrada); ao vivo troca a imagem pelo embed oficial do YouTube e o CTA de entrada assume (`Entrar na plenária` no Meet, `Assistir no YouTube` no YouTube); despublicada ou expirada a seção inteira some (fail-closed), sem deploy.
|
||||
- **O que NÃO negociar:** o CTA nunca aponta para a URL crua do Meet/YouTube (sempre `/{slug}`); a agenda é a do S29 (`ShareLinkAgendaMenu`), sem mecanismo novo; sem player próprio (embed oficial); sem campo/global/CMS novo nesta fatia; sem coleta/RSVP/rastreio; nada do cadastro do link, da página `/plenaria-vitoria`, das seções irmãs ou do redesenho da home; mobile 390 sem overflow; um único CTA primário por estado.
|
||||
- **O que reavaliar:** (1) a intenção cogita "a seção acompanha o no ar como o anúncio do S29" — o poll de 30 s está **inline** em `ShareLinkAnnouncement` (`ShareLinkAnnouncement.tsx:51-88`); copiá-lo criaria dois donos do mesmo contrato (D3). (2) A intenção não fixa o que fazer quando não há destino YouTube pré-cadastrado: sem embed, degrada para a imagem e, sem imagem, coluna única (D4). (3) O watch do e2e da home pina a ordem das seções condicionais de forma agnóstica (`frontend.e2e.spec.ts:1778-1796`) — a seção nova é mais uma condicional; a posição exata fica no spec dono (D10).
|
||||
|
||||
## Abordagem recomendada
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph server["Server · home ISR (tag shareLinks)"]
|
||||
read["loadShareLinkHomeSection('plenaria-vitoria')<br/>read cacheado + canonical + buildView"]
|
||||
gate{"published e agora < fim?<br/>(endsAt | startsAt+2h)"}
|
||||
absent["seção ausente no HTML"]
|
||||
data["{ view, initialLive }"]
|
||||
end
|
||||
subgraph client["Client · ilha da seção (SSR do próprio client component)"]
|
||||
sec["ShareLinkHomeSection"]
|
||||
timeout["timeout único de expiração → some"]
|
||||
hook["useShareLinkLiveTarget(slug, initialLive)<br/>30 s · só ativa · pausa em aba oculta"]
|
||||
pre["pré-live: imagem + Adicionar à agenda"]
|
||||
meet["Meet no ar: embed YouTube + 'Entrar na plenária' → /plenaria-vitoria"]
|
||||
yt["YouTube no ar: embed + 'Assistir no YouTube' → /plenaria-vitoria"]
|
||||
end
|
||||
read --> gate
|
||||
gate -- "não" --> absent
|
||||
gate -- "sim" --> data --> sec
|
||||
sec --> timeout
|
||||
sec --> hook
|
||||
hook -- null --> pre
|
||||
hook -- "live.href host = meet.google.com" --> meet
|
||||
hook -- "live.href host = youtube" --> yt
|
||||
```
|
||||
|
||||
**Opções consideradas:** A) server decide a visibilidade com o read cacheado e renderiza a ilha client com `initialLive` já resolvido; B) wrapper server + ilha só do swap (server pré-live sempre); C) seção 100% client que busca tudo no browser.
|
||||
**Recomendação:** **A** — a home continua estática/ISR (read sob a tag `shareLinks`, o kill switch já busta), o HTML pré-live sai no server sem JS, e o destino no ar é resolvido no mesmo read cacheado, sem flash de agenda para quem chega durante a live.
|
||||
**Rejeitadas:** **B** porque em cada visita ao vivo o HTML chegaria pré-live e o refetch imediato trocaria o estado, piscando a agenda antes do embed (o visitante novo é justamente o caso da reta final); **C** porque sem JS a seção sumiria e o fail-closed deixaria de ser HTML do servidor, além de expor a leitura ao browser.
|
||||
|
||||
### Componentes / mudanças
|
||||
|
||||
- **`src/lib/shareLinkHomeSection.ts` (novo, puro/client-safe):**
|
||||
- `SHARE_LINK_HOME_SECTION_SLUG = 'plenaria-vitoria'` (o slug fixo do contrato);
|
||||
- `ShareLinkHomeSectionView = ShareLinkAnnouncementView & { expiresAt: number; youtubeVideoId: string | null }`;
|
||||
- `buildShareLinkHomeSectionView({ link, imageUrl, canonicalUrl, nowMs })` → `ShareLinkHomeSectionView | null`: janela via `resolveCalendarEventWindow(link.startsAt, link.endsAt)`; sem `startsAt` válido ou `nowMs >= end` → `null`; delega `buildShareLinkAnnouncementView` (alt/location/eventLabel) e acrescenta `expiresAt` (epoch ms) + `youtubeVideoId`;
|
||||
- `resolveShareLinkLiveActionLabel(live)` → `meet.google.com` = "Entrar na plenária"; youtube/youtu.be = "Assistir no YouTube"; fallback "Entrar" (host via `new URL`, nunca o label do cadastro);
|
||||
- não importa `@/utilities/**` (regra do ESLint para `src/lib`); tipos de `@/lib/shareLink`.
|
||||
- **`src/lib/shareLink.ts`:** `resolveShareLinkYoutubeVideoId(destinations)` — varre o pool pré-cadastrado, aceita `youtu.be/<id>`, `watch?v=`, `/live/`, `/embed/`, `/shorts/`, valida o id (`^[A-Za-z0-9_-]{11}$`) e devolve o primeiro | `null`; sem I/O.
|
||||
- **`src/lib/campaignTime.ts`:** `formatBahiaEventDayLabel(iso)` (`sexta, 2 de outubro`) e `formatBahiaEventTimeLabel(iso)` (`18h`/`18h30`); `formatBahiaEventDateLabel` passa a compor as duas, mantendo a saída atual intacta (pin em `shareLinkAnnouncement.unit.spec.ts:26`).
|
||||
- **`src/utilities/shareLinkReads.ts`:** `loadShareLinkHomeSection(slug)` — server-only: `getCachedPublishedShareLinkBySlug(slug)()` (tag `shareLinks`; draft nunca sai), imagem no proxy same-origin (`typeof link.image === 'object' ? link.image.url : null`), `resolveShareLinkCanonicalUrl(slug)` e `buildShareLinkHomeSectionView({ …, nowMs: Date.now() })`; devolve `{ view, initialLive: resolveLiveShareLinkDestination(link.destinations) } | null`.
|
||||
- **`src/components/shareLink/useShareLinkLiveTarget.ts` (novo, `'use client'`):** extrai o poll inline do anúncio com assinatura `useShareLinkLiveTarget(slug, initial = null)`; mesmo contrato: refetch imediato, `setInterval` 30 s só com aba visível, `visibilitychange`, guard `cancelled`, igualdade por `href`/`label`, resposta `target: null` nunca limpa o estado. Comportamento do anúncio idêntico (`initial` null).
|
||||
- **`src/components/shareLink/ShareLinkAnnouncement.tsx`:** passa a consumir o hook (`useShareLinkLiveTarget(view.slug)`), removendo o efeito local — sem mudança visual/comportamental.
|
||||
- **`src/components/shareLink/ShareLinkAgendaMenu.tsx`:** prop opcional `triggerClassName` (default `SECONDARY_ACTION`) para o gatilho amarelo primário do artefato; popover, rows e `.ics` intactos.
|
||||
- **`src/components/shareLink/menuControls.ts`:** classes do CTA primário da home (o `PRIMARY_ACTION` do anúncio portado como vocabulário compartilhado + `SAFE_FOCUS`); o anúncio não muda.
|
||||
- **`src/components/shareLink/ShareLinkHomeSection.tsx` (novo, `'use client'`):** porta classe-a-classe a `.event-section` do artefato (cena 01–06): eyebrow com ponto (`aria-live="polite"` na troca de estado), h2, descrição, grid de metas com ícones lucide (dia · `18h` + "horário da Bahia" · "Online"), bloco de ação (pré-live: `ShareLinkAgendaMenu` com o gatilho amarelo; ao vivo: `<iframe src="https://www.youtube-nocookie.com/embed/<id>?playsinline=1&rel=0" loading="lazy" title=…>` + CTA `resolveShareLinkLiveActionLabel(live)` → `shareLinkPath(view.slug)`, sem `target="_blank"`), figura quadrada com `next/image fill` (ao vivo vira `aspect-video` com o iframe; sem imagem → sem figura), blobs decorativos `aria-hidden`, ordem mobile/desktop do artefato via grid explícito, `data-home-section="plenaria"`. Estado local: `hidden` por expiração (timeout único; no mount, se já expirado, o efeito esconde imediatamente sem mismatch de hidratação) + `live` do hook (`initialLive`).
|
||||
- **`src/app/(frontend)/(home)/page.tsx`:** `loadShareLinkHomeSection(SHARE_LINK_HOME_SECTION_SLUG)` entra no `Promise.all` (`page.tsx:128`) e a seção renderiza condicional logo após `<CampaignHero />` (`page.tsx:144`), antes da prova (`data-home-section="proof"`).
|
||||
- **Migration:** sem migration (nenhuma collection/global muda).
|
||||
- **Access / Consent:** sem escrita, sem PII, sem Consent novo; o gate é o `published: true` do read cacheado (fail-closed).
|
||||
- **UI:** Impeccable C com gate aprovado — port classe a classe das cenas 01–06, mobile (390) primeiro, inspeção em 1280; shape→craft→critique→polish; crítica final antes do push.
|
||||
|
||||
### Dados → forma (se aplicável)
|
||||
|
||||
Não aplicável — a intenção fixa **Dados: N/A** (nenhuma métrica nova). A única "forma" é a separação dia × hora no grid de metas do artefato, servida pelos dois formatadores puros (D7); rejeitados: countdown, contador, percentual ou qualquer número inventado numa superfície de convite.
|
||||
|
||||
## Decisões de engenharia
|
||||
|
||||
1. **Visibilidade/expiração — A) server decide no render; poll e timeout cobrem a borda.** Opções: A | B (TTL/revalidate próprio na home) | C (campo/global novo de destaque) | D (datas fixas no código). Recomendação: **A** — read cacheado do slug fixo (`plenaria-vitoria`), sem link publicado → `null`; janela por `resolveCalendarEventWindow` (fallback 2 h), sem `startsAt` válido ou `agora >= fim` → `null`. O client esconde no instante exato da expiração (timeout único) para abas abertas/HTML ISR defasado; o kill switch (despublicar) já busta a tag. Rejeitadas: **B** (muda o contrato de cache da home por um evento de um dia), **C** (migration por algo que dura um dia) e **D** (hardcode de datas).
|
||||
2. **Estado inicial ao vivo — A) server resolve o destino do read cacheado e passa `initialLive`.** Recomendação: **A** — quem chega durante a live já recebe o embed/CTA no HTML, sem flash de agenda. O poll mantém o contrato do S29 (só ativa, 30 s, pausa em aba oculta, guard por href/label). Rejeitadas: **B** (server sempre pré-live e refetch imediato trocando — flash exatamente para o visitante novo da reta final).
|
||||
3. **Poll único — A) extrair o hook `useShareLinkLiveTarget(slug, initial = null)`.** Recomendação: **A** — o anúncio (S29) e a home passam a ter um dono só do contrato de ativação; o anúncio chama sem `initial` e mantém o comportamento atual bit a bit. Rejeitadas: **B** (duplicar o poll na home — dois donos do mesmo contrato, deriva garantida).
|
||||
4. **Embed — A) vídeo derivado do destino YouTube pré-cadastrado.** Recomendação: **A** — `resolveShareLinkYoutubeVideoId(destinations)` puro aceita os formatos usuais e valida o id; embed `youtube-nocookie` (convenção de `CampaignStorySection.tsx:55`), `loading="lazy"`, sem autoplay, `title` acessível. Sem destino YouTube → sem embed (cai para a imagem; sem imagem, coluna única). Rejeitadas: **B** (hardcodar o id do vídeo) e **C** (player próprio).
|
||||
5. **CTA de entrada — A) rótulo pelo host do destino no ar; href sempre o path canônico.** Recomendação: **A** — `resolveShareLinkLiveActionLabel` decide Meet/YouTube/fallback pelo host; href sempre `shareLinkPath(view.slug)` (`/plenaria-vitoria`), sem `target="_blank"`. Rejeitadas: **B** (usar `live.href` direto — expõe a URL crua) e **C** (decidir pelo label do cadastro — o host é mais robusto a renomeação de rótulo).
|
||||
6. **Agenda pré-live — A) reusar a `ShareLinkAgendaMenu` com `triggerClassName`.** Recomendação: **A** — o menu S29 ganha a prop opcional (default `SECONDARY_ACTION`) para o gatilho amarelo primário do gate; classes novas do CTA da home entram no vocabulário de `menuControls.ts`, reusando `SAFE_FOCUS`. Rejeitadas: **B** (duplicar o popover/menu na home) e **C** (manter o gatilho secundário branco — divergiria do gate).
|
||||
7. **Formatação — A) separar dia e hora em `campaignTime.ts`.** Recomendação: **A** — novas funções puras `formatBahiaEventDayLabel` e `formatBahiaEventTimeLabel`; `formatBahiaEventDateLabel` compõe as duas sem mudar a saída atual (o anúncio do S29 segue coberto pelo unit existente). Rejeitadas: **B** (split de string do `eventLabel` — quebra frágil) e **C** (terceiro módulo de data — o dono da formatação Bahia já existe).
|
||||
8. **View — A) `buildShareLinkHomeSectionView` delegando ao view model do anúncio.** Recomendação: **A** — reusa alt/location/eventLabel de `buildShareLinkAnnouncementView` e acrescenta `expiresAt` + `youtubeVideoId`; `null` quando expirado. `loadShareLinkHomeSection(slug)` em `shareLinkReads.ts` orquestra read cacheado + canonical + view (e devolve `initialLive`). Rejeitadas: **B** (shape próprio duplicando o view model) e **C** (orquestração inline no `page.tsx` — a home não deve conhecer o read/canonical).
|
||||
9. **Componente — A) ilha `'use client'` SSR-ada, dona do estado.** Recomendação: **A** — porta classe a classe o `.event-section` do artefato; com JS desligado o HTML pré-live continua completo (o server renderiza o client component) e o timeout de expiração/poll vivem um lugar só. Renderizada logo após `<CampaignHero />`, condicional ao loader. Rejeitadas: **B** (server wrapper + ilha só do swap — fragmenta o dono do estado/expiração).
|
||||
10. **Testes — A) unit primeiro, int na fronteira do loader, e2e no spec dono com o helper de poll extraído.** Recomendação: **A** — unit (`tests/unit/shareLinkHomeSection.unit.spec.ts`): builder visível/expirado/sem janela, extração do vídeo, rótulo do CTA e labels Bahia novos; unit do hook se barato. Int (estender `tests/int/shareLink.int.spec.ts`): `loadShareLinkHomeSection` com publicado + janela futura → view com `youtubeVideoId`; expirado → `null`; despublicado → `null`; sem `startsAt` → `null`. E2e: novo describe "S44" em `tests/e2e/frontendShareLink.e2e.spec.ts` (spec dona do shareLink; o manifesto já a acorda) — (a) cria `plenaria-vitoria` via REST com mídia e destinos Meet+YouTube, `startsAt` futuro, `mode: announcement`, published; poll do HTML converge, a seção aparece logo após o hero (ordem hero→plenaria→proof), agenda presente e sem link de entrada; flag live via SQL (sem revalidar a tag) + `visibilitychange` → iframe `youtube-nocookie` + `Entrar na plenária` href `/plenaria-vitoria` sem reload; troca para YouTube → `Assistir no YouTube`; kill switch via REST (`published: false`) → HTML converge ausente; (b) janela expirada (`startsAt` passado > 2 h) → ausente; patch `endsAt` futuro → presente (borda dos dois lados). Overflow 390 ≤ 1 px; limpeza no `afterAll` com a infra existente (`createdShareLinkIds`/`createdMediaIds`). **D3 do débito do S39** (extrair o poll do HTML ISR para `tests/helpers/`) tem o gatilho batido (3º spec): unificar `waitForHomeHTML` (`frontend.e2e.spec.ts:777`) e `waitForHomeSection` (`frontendConteudos.e2e.spec.ts:242`) num helper e rewiring os dois specs; se a extração mostrar atrito, manter local e registrar o débito reavaliado. Rejeitadas: **B** (spec e2e nova — 2ª infra de seed do mesmo contrato) e **C** (e2e com `page.clock` para a expiração client — a borda é o predicado unit-testado do builder; clock no e2e é flake).
|
||||
11. **Docs — A) contrato no `AGENTS-public.md` + changelog + este impl plan.** Recomendação: **A** — `AGENTS-public.md` ganha a seção da home (slug fixo, estados, fail-closed, kill switch, sem migration/Consent); `docs/changelog/2026-10-01-s44.md`; o impl plan entra no commit.
|
||||
|
||||
## Fases verificáveis
|
||||
|
||||
1. **Tracer — puros + leitura (~0,25 dia).** `src/lib/shareLinkHomeSection.ts` (`SHARE_LINK_HOME_SECTION_SLUG`, builder, rótulo do CTA), `resolveShareLinkYoutubeVideoId` em `shareLink.ts`, os dois formatadores em `campaignTime.ts`, `loadShareLinkHomeSection` em `shareLinkReads.ts`; `tests/unit/shareLinkHomeSection.unit.spec.ts` + casos novos em `tests/int/shareLink.int.spec.ts`. Verificação: `pnpm test tests/unit/shareLinkHomeSection.unit.spec.ts tests/int/shareLink.int.spec.ts` e `pnpm gate:fast`.
|
||||
2. **UI (~0,5 dia).** Hook `useShareLinkLiveTarget` + rewire do `ShareLinkAnnouncement`; `triggerClassName` na agenda; classes novas em `menuControls.ts`; `ShareLinkHomeSection`; fiação em `page.tsx`; unit do hook (se barato). Verificação: `pnpm gate:fast`; inspeção 390/1280 contra as cenas 01–06 (sem overflow; pré-live sem entrada; ao vivo sem agenda).
|
||||
3. **E2e + gates (~0,25–0,5 dia).** Extrair `tests/helpers/<homePoll>.ts` e rewiring `frontend.e2e.spec.ts` + `frontendConteudos.e2e.spec.ts`; describe "S44" em `frontendShareLink.e2e.spec.ts`; manifesto — acrescentar `src/app/(frontend)/(home)` ao entry do `frontendShareLink` (mesmo racional do S39: a página é a única fiação da seção, e um diff só dela deve acordar o spec dono). Verificação: `pnpm test:e2e:affected` (ou `pnpm test:e2e --no-deps --project=frontendShareLink`, `--project=frontend`, `--project=frontendConteudos`); `pnpm gate:fast`; push via `pnpm push`.
|
||||
|
||||
## Rabbit holes / Não escopo (engenharia)
|
||||
|
||||
- Countdown, contador, compartilhar dentro da seção, carrossel/agenda de próximos eventos, CMS de eventos (a lista de eventos é outro produto).
|
||||
- Campo/global "destaque na home", migration, Consent novo, collection nova.
|
||||
- CTA para URL crua do Meet/YouTube; `target="_blank"`; player próprio; autoplay com som; segundo poll/endpoint/rota; leitura live (não cacheada) no server da home.
|
||||
- Tocar o cadastro do `ShareLink`, a rota `[type]`, a página `/plenaria-vitoria`, o `ShareLinkAnnouncement` além da extração do hook, as seções irmãs da home ou o `SiteHeader`/rodapé.
|
||||
- Spec e2e nova, `page.clock`, screenshot/visual regression da home, dedupe do slug duplicado `plenaria-da-vitoria` (ops).
|
||||
|
||||
## Riscos e mitigação
|
||||
|
||||
- **Duplicata `plenaria-da-vitoria` (id 5) segue em produção:** fora deste item (ops); a home lê apenas o slug fixo `plenaria-vitoria`.
|
||||
- **ISR/HTML defasado:** o kill switch busta a tag `shareLinks`; a expiração é coberta pelo timeout no client e o e2e converge por poll do HTML do server antes de navegar.
|
||||
- **Dev Fast Refresh no primeiro compile da rota de poll:** o e2e aquece `GET /api/share-link/<slug>/live` antes do `goto` (precedente S29, `frontendShareLink.e2e.spec.ts:438-442`).
|
||||
- **Concorrência em prod (4 workers):** o pin de ordem do `frontend` permanece agnóstico da seção condicional (o `frontendShareLink` pode publicar `plenaria-vitoria` em paralelo); a ordem exata hero→plenaria→proof é pinada no describe S44.
|
||||
- **Slug fixo no banco de teste:** o describe S44 é serial e único dono do slug; o `beforeAll` remove resíduo de runs abortados e o `afterAll` limpa com a infra existente.
|
||||
- **Sem imagem e/ou sem destino YouTube:** o componente precisa renderizar sem figura e sem embed (coluna única) sem quebrar o grid do artefato; coberto no unit do builder e na inspeção das cenas.
|
||||
- **Hidratação/expiração:** estado inicial visível e efeito que esconde no mount quando `Date.now() >= expiresAt` (sem mismatch); timer único limpo no unmount; sem `page.clock`.
|
||||
- **Segurança do embed:** iframe só existe com id validado (`^[A-Za-z0-9_-]{11}$`) do destino pré-cadastrado; URL nunca vem do estado no ar em texto cru.
|
||||
|
||||
## Débitos
|
||||
|
||||
- **D3 do S39 — resolvido aqui:** a extração do poll do HTML ISR para `tests/helpers/` é passo da fase 3 (o 3º spec bateu o gatilho). Se a extração mostrar atrito real, manter local e registrar o débito reavaliado no changelog.
|
||||
- **Dedupe do slug duplicado em produção** — ops, fora deste item (registrado na intenção).
|
||||
- **Copy do dia da semana ("sexta" vs `Intl` pt-BR "sexta-feira")** — validar no port contra o gate; se divergir, ajustar a copy no artefato, nunca a saída do formatador (o anúncio do S29 precisa continuar idêntico).
|
||||
|
||||
### Débitos da revisão (simplify) — explicitamente fora / adiado com gatilho
|
||||
|
||||
- **Já resolvido no simplify (não reabrir):** exports mortos (knip); twin do `YOUTUBE_VIDEO_ID_PATTERN` (dono único em `lib/shareLink`, importado por `utilities/socialFeed/excludedItems`); listas de hosts YouTube unificadas; CTA desktop/mobile em `LiveEntryAction`; rename `ShareLinkHomeSectionData`; type do mock no unit da home; mensagem do helper de ISR com o erro original; import do slug no e2e; e2e do estado ao vivo já no HTML do server (caminho `initialLive`); e o describe int S44 aninhado no describe dono (o `afterAll` passou a limpar as linhas — provado com duas execuções).
|
||||
- **Adiado com gatilho — S2:** ao expirar, o timer esconde a seção mas o hook segue pollando (30 s) até o unmount, e `expired` não volta a `false` se `view.expiresAt` mudar num refresh RSC (hoje a home não re-renderiza a seção no cliente). Gatilho: a seção ganhar refresh dinâmico no cliente (revalidate/refresh RSC) ou o `/api/share-link/<slug>/live` passar a ter custo/rate relevante — aí parar o poll com `expired` (flag `enabled`/desmontar a ilha).
|
||||
- **Descartado — S1:** `eventLabel` segue no view da home de propósito — `buildShareLinkHomeSectionView` reusa `buildShareLinkAnnouncementView` (D8); shape próprio foi rejeitado. Revisitar só se o payload ganhar um 2º campo inútil.
|
||||
- **Descartado — S3:** os `cleanup()`/resets dentro do `it` isolam renders múltiplos do mesmo teste; o `afterEach` cobre a fronteira entre testes — não duplicam.
|
||||
- **Descartado — S4:** `Entrar` é o fail-safe do host desconhecido; sem caso de produto. Rótulo novo só com host novo real.
|
||||
|
||||
## Aceite de engenharia
|
||||
|
||||
- [ ] Aceite de produto da intenção ainda coberto: seção só enquanto publicado e não expirado; pré-live imagem + `Adicionar à agenda` sem entrada; ao vivo embed + CTA por host sempre → `/plenaria-vitoria`; troca sem reload; kill switch sem deploy; demais seções intocadas; 390 sem overflow; acessível e sem autoplay com som; sem coleta.
|
||||
- [ ] Invariantes AGENTS/engineering-standards: `src/lib` sem importar `@/utilities/**`; client importa de server só `import type`; sem migration; sem Consent novo; sem PII; copy pt-BR / identificadores em inglês.
|
||||
- [ ] Testes de domínio previstos: unit do builder/vídeo/CTA/labels (+ hook se barato); int do `loadShareLinkHomeSection`; e2e S44 no spec dono; helper de poll extraído e specs rewired.
|
||||
- [ ] Gates: `pnpm gate:fast`; e2e afetado (`frontendShareLink`, `frontend`, `frontendConteudos`); `pnpm push`.
|
||||
|
||||
## Self-score decision-quality
|
||||
|
||||
4,5/5.
|
||||
|
||||
1. **Decisões caras com rejeitadas (5/5):** visibilidade/cache, estado inicial, ownership do poll, embed, CTA/href, agenda, formatação, view model, componente, testes e docs têm Opções + Recomendação + rejeitadas explícitas (D1–D11).
|
||||
2. **Cabe no appetite herdado (4,5/5):** sem schema/API nova; 1 módulo puro, 1 loader, 1 hook extraído, 1 componente e extensões de specs — o custo concentra-se na UI e no e2e, dentro de ~0,5–1 dia.
|
||||
3. **Rabbit holes nomeados (5/5):** countdown, CMS de eventos, campo/global/migration, URL crua, player próprio, segundo poll, spec e2e nova, `page.clock`, dedupe.
|
||||
4. **Depth check (4,5/5):** reusa o read cacheado + tag `shareLinks`, o view model do anúncio, `resolveCalendarEventWindow`, a agenda S29, o vocabulário de `menuControls` e a infra e2e; extrai o poll do dono existente em vez de duplicar.
|
||||
5. **Intenção preservada (5/5):** outcome intacto; as reavaliações (sem destino YouTube, helper de poll e o pin agnóstico) são delegadas/antecipadas pela própria intenção e não mudam produto.
|
||||
1408
docs/plans/secao-home-plenaria-da-vitoria-ui-design.html
Normal file
1408
docs/plans/secao-home-plenaria-da-vitoria-ui-design.html
Normal file
File diff suppressed because it is too large
Load diff
106
docs/plans/secao-home-plenaria-da-vitoria.md
Normal file
106
docs/plans/secao-home-plenaria-da-vitoria.md
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
# S44 — Home — seção da Plenária da Vitória (divulgação e acesso)
|
||||
|
||||
Status: rascunho
|
||||
Atualizado em: 2026-10-01
|
||||
Issue: #1408
|
||||
Priority: P1
|
||||
Impeccable: C — seção nova na home pública (superfície nova dentro de página existente)
|
||||
Design UI: docs/plans/secao-home-plenaria-da-vitoria-ui-design.html
|
||||
Appetite: ~0,5–1 dia eng; um outcome verificável (a home divulga a plenária e leva ao link em um toque)
|
||||
Responsável: —
|
||||
|
||||
## Intenção
|
||||
|
||||
A Plenária da Vitória acontece **amanhã, sexta 02/10/2026, às 18h (horário da Bahia), online** — e a home, a superfície mais visitada do site, não a anuncia. Hoje o convite só circula pelo link no WhatsApp; quem chega ao site não fica sabendo. Na reta final até 04/10, a home precisa empurrar esse encontro: uma seção curta que mostra o convite e leva ao link em um toque.
|
||||
|
||||
O evento já existe na produção como link de compartilhamento publicado (`/plenaria-vitoria`, modo anúncio). A seção **reflete o estado do link**: antes de ir ao ar, mostra o convite (imagem + dados do evento) e o botão **Adicionar à agenda** — a mesma agenda do link (Google Agenda + arquivo `.ics`, S29), sem botão de entrada; quando a equipe marca um destino no ar, a imagem de divulgação dá lugar ao **embed da live do YouTube** e o botão de entrada aparece — `Entrar na plenária` quando o destino ativo é o Google Meet, `Assistir no YouTube` quando é o YouTube. Quem decide o destino continua sendo o próprio link, sem deploy na home.
|
||||
|
||||
## Persona e fluxo
|
||||
|
||||
- **Persona / contexto:** simpatizante/militância abrindo o site no celular (link no WhatsApp, busca, indicação), a dois dias da eleição; quer saber onde se encontrar com o time e entrar rápido.
|
||||
- **Job principal:** ver o convite da plenária e entrar nela em um toque, sem procurar link.
|
||||
- **Fluxo desejado:** rola a home → vê a seção com título, data/hora da Bahia, "Online", descrição e imagem (pré-live: botão **Adicionar à agenda**, sem botão de entrada) → adiciona o evento na agenda em um toque (Google Agenda ou `.ics`) → quando a equipe marca um destino no ar, a seção troca sozinha a imagem pelo embed da live e o botão de entrada assume o lugar do de agenda → toca (`Entrar na plenária` no Meet, `Assistir no YouTube` no YouTube) → cai em `/plenaria-vitoria`, que leva ao destino no ar.
|
||||
- **Anti-goals de produto:** não é segunda página de anúncio (compartilhar continua no link; a seção **reusa a agenda do próprio link**, não cria mecanismo novo nem menu próprio de agenda); não é agenda pública nem carrossel de eventos; o botão de entrada nunca aponta direto para a URL do Meet/YouTube (sempre via `/{slug}`); não é player próprio (o ao vivo é o embed oficial do YouTube); não cria botão de entrada antes de haver destino no ar; não coleta dado/RSVP; não duplica seções existentes; não redesenha a home; não cria campo de CMS/destaque genérico nesta fatia.
|
||||
|
||||
### Esboço de fluxo (C)
|
||||
|
||||
```text
|
||||
[visitante na home] → seção "Plenária da Vitória"
|
||||
(título · data/hora Bahia · "Online" · descrição)
|
||||
→ pré-live (nenhum destino no ar): imagem de divulgação + botão "Adicionar à agenda"
|
||||
(Google Agenda · arquivo .ics — a agenda do S29, sem mecanismo novo)
|
||||
→ equipe marca um destino no ar (sem deploy na home):
|
||||
├─ destino Google Meet → embed da live do YouTube + botão "Entrar na plenária" → /plenaria-vitoria → Meet
|
||||
└─ destino YouTube → embed da live do YouTube + botão "Assistir no YouTube" → /plenaria-vitoria → YouTube
|
||||
(a seção acompanha a troca sem recarregar, como a página de anúncio do S29)
|
||||
[link despublicado ou evento expirado] → a seção inteira some (fail-closed)
|
||||
```
|
||||
|
||||
### Design UI (C)
|
||||
|
||||
- Design UI (gate): `docs/plans/secao-home-plenaria-da-vitoria-ui-design.html` — cenas mobile/desktop da seção nos três estados (pré-live com `Adicionar à agenda` e sem botão de entrada; ao vivo no Meet; ao vivo no YouTube com embed) e o estado ausente (despublicado/expirado).
|
||||
|
||||
## Objetivo e aceite
|
||||
|
||||
- A home pública ganha uma seção dedicada à Plenária da Vitória, visível **só enquanto o link estiver publicado e o evento não tiver expirado**: despublicada ou expirada, a seção não existe na página (fail-closed, sem promo velha).
|
||||
- **Pré-live (nenhum destino no ar):** a seção mostra o convite — título, descrição, data/hora da Bahia, "Online" e a imagem de divulgação — com o botão **Adicionar à agenda** (Google Agenda + arquivo `.ics`, a mesma agenda do link no S29 — sem segundo mecanismo) e **sem botão de entrada** (não há para onde entrar).
|
||||
- **Ao vivo:** com um destino marcado no ar, a imagem de divulgação dá lugar ao **embed da live do YouTube** (player oficial, nunca player próprio) e o botão de entrada assume o lugar do de agenda: `Entrar na plenária` quando o destino no ar é o Google Meet; `Assistir no YouTube` quando é o YouTube.
|
||||
- **A seção acompanha o "no ar" sem recarregar** (mesmo contrato de ativação da página de anúncio do S29), sem deploy; o botão sempre leva a `/plenaria-vitoria`, que resolve o destino no ar — nunca à URL crua do Meet/YouTube.
|
||||
- Kill switch sem deploy: despublicar o link esconde a seção; demais seções da home intocadas.
|
||||
- Celular primeiro, sem overflow horizontal (o e2e da home mede); acessível (contraste, foco visível, botão operável por teclado); o embed não autoplaya com som.
|
||||
- Sem coleta: nenhum dado/RSVP, nenhum rastreio novo.
|
||||
|
||||
## Dados (intenção)
|
||||
|
||||
- **Dados: N/A** — nenhuma métrica nova; a seção divulga um evento. **Decisões desbloqueadas:** o visitante decide entrar na plenária; a comunicação decide publicar/despublicar o link. Nada do visitante é coletado.
|
||||
|
||||
## Dados da decisão (literais)
|
||||
|
||||
- Evento em produção (link publicado): id `4`; slug `plenaria-vitoria`; caminho canônico `/plenaria-vitoria`; título `Plenária da Vitória`; modo `announcement`; `published: true`; `startsAt` `2026-10-02 21:00:00+00` (**sexta, 02/10/2026, 18h horário da Bahia**); `endsAt` vazio; local `Online`; imagem media id `171` (alt `Plenária da Vitória 1313`).
|
||||
- Descrição (verbatim): "O time de Jorge Solla se encontra antes da vitória. Chama seu grupo para o 1313 e vamos juntos! ❤️"
|
||||
- Destinos pré-cadastrados (nenhum ao vivo ainda): `Google Meet` → `https://meet.google.com/fyz-rurx-biv`; `Youtube` → `https://www.youtube.com/live/77bUgl7cvQ8`.
|
||||
- Duplicata em produção: id `5`, slug `plenaria-da-vitoria`, mesmo conteúdo — dedupe é ops, fora deste item; esta entrega usa `plenaria-vitoria`.
|
||||
- Estados da seção: **pré-live** (nenhum destino no ar) = imagem de divulgação + botão `Adicionar à agenda` (sem botão de entrada); **ao vivo no Meet** = embed da live do YouTube + botão `Entrar na plenária`; **ao vivo no YouTube** = embed da live + botão `Assistir no YouTube`.
|
||||
- Agenda do pré-live: as duas opções já contratadas no S29 — Google Agenda (link preenchido com o evento) e arquivo `/{slug}/evento.ics` (`/plenaria-vitoria/evento.ics`); sem data (`startsAt`) a agenda não aparece.
|
||||
- Embed do ao vivo (YouTube): vídeo `77bUgl7cvQ8` → player `https://www.youtube.com/embed/77bUgl7cvQ8` (o embed usa o destino do YouTube pré-cadastrado do link).
|
||||
- Botão sempre para `/plenaria-vitoria` (nunca a URL crua do Meet/YouTube); rótulo segue o destino no ar.
|
||||
- Regra de visibilidade: visível só se publicado E agora < `endsAt` (quando preenchido; senão `startsAt` + 2h — mesma convenção de duração do anúncio do S29); fora disso, não renderiza. _(assumido — validar com produto)_
|
||||
|
||||
## Direção no codebase (hipótese)
|
||||
|
||||
- **Áreas prováveis:** a home compõe seções em `src/app/(frontend)/(home)/page.tsx`; a leitura cacheada de share link (`src/utilities/shareLinkReads.ts`) e o anúncio (`src/components/shareLink/ShareLinkAnnouncement.tsx`, com o poll de ativação a cada ~30 s) mostram os dados/estados; a agenda já existe (`src/components/shareLink/ShareLinkAgendaMenu.tsx` — Google Agenda + `.ics`); o estado "no ar" sem recarregar já tem endpoint próprio (`src/app/(frontend)/api/share-link/[slug]/live/route.ts`, `{ target: { href, label } | null }`); a rota do link é `src/app/(frontend)/[type]/page.tsx`; estilos de seção em `src/app/(frontend)/styles.css`.
|
||||
- **Precedentes a olhar:** `docs/plans/central-conteudos-secao-home.md` (S39 — seção nova na home, fail-closed a zero), `docs/plans/link-compartilhamento-destino-trocavel-anuncio.md` (S29 — modo anúncio, duração default 2h), `docs/plans/jingles-radio-homepage.md`.
|
||||
- **Risco de acoplamento:** a home é estática/cacheada (leitura por tag da coleção de share links); não editar o cadastro do link, a página do anúncio nem as seções irmãs; o e2e da home verifica a ordem das seções; escrita direta no banco não busta o cache (só o admin revalida).
|
||||
|
||||
## Dependências
|
||||
|
||||
- Nenhuma (S19/S29 já entregues). Design hi-fi aprovado no gate.
|
||||
|
||||
## Fora de escopo
|
||||
|
||||
- Duplicata id `5` (`plenaria-da-vitoria`) — dedupe é ops.
|
||||
- Mecanismo genérico de destaque/agenda de eventos (a agenda desta seção é a do próprio link, S29); countdown; compartilhar dentro da seção.
|
||||
- Edições no cadastro do share link (`/plenaria-vitoria` e destinos ficam como estão).
|
||||
|
||||
## Rabbit holes de produto
|
||||
|
||||
- **"Já que tem seção, vira agenda".** Se alguém "só completar": carrossel de próximos eventos, CMS de eventos. **Corte neste item:** uma seção, um evento — a lista de eventos é outro produto.
|
||||
- **"Cria campo de destaque por evento".** Se alguém "só completar": campo novo + migration para algo que dura um dia. **Corte:** slug fixo + `published` (questão 1, opção A).
|
||||
- **"Linka direto ao destino para funcionar mais rápido".** Se alguém "só completar": Meet/YouTube no CTA. **Corte:** CTA sempre para `/{slug}`; a troca de destino é do link, sem deploy.
|
||||
- **"Põe um countdown para urgência".** Se alguém "só completar": relógio regressivo, animação. **Corte:** data/hora no texto basta; urgência é da reta final, não de widget.
|
||||
|
||||
## Questões em aberto (produto)
|
||||
|
||||
- **Qual a fonte da seção?** **Opções:** A) slug fixo em código + `published` | B) campo "destaque na home" no share link (exige migration) | C) global da home com link digitado. **Recomendação:** A — entrega hoje, sem migration; o link já é o dono do dado. _(assumido — validar com produto)_
|
||||
- **Como expira?** **Opções:** A) automática: `endsAt` quando houver, senão `startsAt` + 2h, mais kill switch de despublicar | B) só despublicar manualmente | C) datas fixas no código. **Recomendação:** A — sem risco de promo velha; B como rede de segurança. _(assumido — validar com produto)_
|
||||
- **Onde fica na home?** **Opções:** A) logo após o hero | B) depois de "Acompanhe de perto" | C) antes da newsletter. **Recomendação:** A — máxima visibilidade na reta final; a seção some sozinha depois. _(assumido — validar com produto)_
|
||||
- **Quando o embed da live entra?** **Opções:** A) com qualquer destino no ar — usa o destino do YouTube pré-cadastrado no link (recomendação, literal do pedido: "se a live já estiver começado, mostrar a live acontecendo") | B) só quando o destino no ar é o YouTube. _(assumido — validar com produto)_
|
||||
- **A seção tem algum clique além da agenda antes do ao vivo?** **Opções:** A) não — pré-live é convite + `Adicionar à agenda`, sem link implícito nem título/imagem clicáveis (recomendação, mantém uma ação só) | B) título/imagem também clicáveis para `/plenaria-vitoria`. _(assumido — validar com produto)_
|
||||
- **O botão de agenda some quando a live começa?** **Opções:** A) sim — o botão de entrada assume o lugar (recomendação: agenda é inútil depois que começou; um CTA primário por estado) | B) coexiste como ação secundária ao lado de `Entrar`/`Assistir`. _(assumido — validar com produto)_
|
||||
|
||||
## Referências
|
||||
|
||||
- GitHub Issue: #1408.
|
||||
- Design UI (gate): `docs/plans/secao-home-plenaria-da-vitoria-ui-design.html`.
|
||||
- `src/app/(frontend)/(home)/page.tsx`, `src/utilities/shareLinkReads.ts`, `src/components/shareLink/ShareLinkAnnouncement.tsx`, `src/app/(frontend)/[type]/page.tsx`
|
||||
- `tests/e2e/frontendShareLink.e2e.spec.ts`, `tests/e2e/frontend.e2e.spec.ts` (ordem das seções da home); `docs/plans/central-conteudos-secao-home.md` (S39), `docs/plans/link-compartilhamento-destino-trocavel-anuncio.md` (S29), `docs/plans/jingles-radio-homepage.md`.
|
||||
89
docs/postmortems/2026-10-01-e2e-c104-calendar-day-locator.md
Normal file
89
docs/postmortems/2026-10-01-e2e-c104-calendar-day-locator.md
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
# Post-mortem: clique no dia do calendário pelo nome acessível derruba o verify do deploy
|
||||
|
||||
> Template do `/bug-fix`. Preencha com fatos apurados; o que não for apurado fica "não apurado" — nunca invente.
|
||||
|
||||
## Registro
|
||||
|
||||
| Campo | Valor |
|
||||
| ------------------- | ---------------------------------------------------------------------------------------------------------- |
|
||||
| Data do post-mortem | 2026-10-01 |
|
||||
| Severidade | alta (bloqueou o deploy do main; CI vermelho — sem impacto em produção, o `verify` roda antes de publicar) |
|
||||
| Ambiente | CI (job `verify` do Deploy no GitHub Actions) |
|
||||
| Issue(s) | #1406 (auto-unblock; não fechar — o wrapper cuida) + #1401 (primeira detecção, fechada sem fix) |
|
||||
| PR do fix | #1407 |
|
||||
| Detectado por | CI (deploy run vermelho) / wrapper auto-unblock |
|
||||
|
||||
## Timeline
|
||||
|
||||
| Momento | Data/hora | Evento |
|
||||
| ----------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Início provável | 2026-08-09 | C104 (`ea700e31`) criou o picker de término com data fixa (`/17 de agosto de 2026/`). |
|
||||
| Fragilidade latente | 2026-08-13 | C134 (commit `fe0a7999`) passou a derivar hoje + 1, mas manteve o clique pelo nome acessível — a fragilidade só dispara quando hoje + 1 cai em dia 01–09 do mês. |
|
||||
| Detecção 1 | 2026-10-01 04:44–05:02 UTC | run `36816518055` (commit `20d3781e`, docs(C240), docs-only), job `verify`, passo "E2E tests (full suite, single job, 4 workers)" falhou: C104 falhou nas 3 tentativas (mesmo strict mode violation); 2 failed (C104 + `campaignSpeechAcervo` C222, que não reapareceu no run seguinte), 3 flaky, 326 passed. Issue #1401 aberta (single-flight) e fechada em 2026-10-01T15:38:43Z sem PR de fix. |
|
||||
| Detecção 2 / do disparo | 2026-10-01 ~15:40 / 16:08 UTC | run `36820002374` (commit `ca843fb4`, attempt 2 ~15:40Z), passo do `verify` falhou às 16:08Z: C104 falhou nas 3 tentativas; 1 failed, 7 flaky, 323 passed. Issue #1406 aberta (auto-unblock). |
|
||||
| Bloqueio do deploy | 2026-10-01 | O run vermelho segurava a lane; os deploys de `77e7b0ef` (run `36886280567`) e `cd4942d9` (run `36887968057`) foram preflight-skipped. |
|
||||
| Correção implementada | 2026-10-01 | Worktree `fix/falha-do-job-verify-do-deploy-github-actions-desbloqueie`. |
|
||||
| Correção mergeada | a preencher | PR #1407 aberto (Ready, auto-merge armado); merge a preencher. |
|
||||
| Deploy | a preencher | a preencher. |
|
||||
| Verificado em prod | não se aplica | Bug de CI/teste; o comportamento público não muda. A confirmação é o `verify` verde no run de deploy pós-merge; produção depende do approve humano (não aprovado por esta sessão). |
|
||||
|
||||
## O bug
|
||||
|
||||
O passo de e2e full do `verify` falhava deterministicamente no teste `[campaign] › tests/e2e/campaignActivity.e2e.spec.ts › Agenda — calendário operacional › cria compromisso "Todo o dia" no slot, sem horário e com faixa no calendário (C104)`: ao abrir o date picker de "Término" e clicar no dia de hoje + 1, o Playwright abortava com `strict mode violation: ... getByRole('button', { name: '2 de Outubro de 2026' }) resolved to 3 elements` (dias 02, 12 e 22 de outubro). O CI ficou vermelho no run de 2026-10-01 e os merges seguintes tiveram o deploy preflight-skipped — o deploy do main ficou bloqueado. Nenhum impacto em produção: o `verify` roda antes de publicar. **Sintoma — não a causa.**
|
||||
|
||||
## Causa-raiz
|
||||
|
||||
Origem `file:line` pré-fix: `tests/e2e/campaignActivity.e2e.spec.ts:355` (`endPicker.getByRole('button', { name: endDayLabel }).click()`), com `endDayLabel` montado em `:352` ("2 de Outubro de 2026") a partir de `civilDatePlusDays(formatBahiaCivilDate(new Date()), 1)` (`:348`).
|
||||
|
||||
O accessible name real do botão vem do react-day-picker com locale pt-BR: `"sexta-feira, 2 de outubro de 2026"` (date-fns `PPPP`); `src/components/ui/Calendar.tsx:167` também expõe `data-day="02/10/2026"`. O matcher de nome do Playwright é substring + case-insensitive por default; `"2 de outubro de 2026"` é substring de `"12 de outubro de 2026"` e `"22 de outubro de 2026"` (mesmo grid). `exact: true` não serve (o nome tem o dia da semana). O bug só dispara quando hoje + 1 cai em dia 01–09; em outubro/2026 caiu em 02.
|
||||
|
||||
### 5 whys
|
||||
|
||||
1. Por que o `verify` quebrou? Porque o clique usou o nome acessível.
|
||||
2. Por que o teste clicava pelo nome? Porque herdou esse clique do C104 original e o manteve no C134, que só trocou a data fixa por hoje + 1.
|
||||
3. Por que o locator não usou o contrato estável? Porque `data-day` já existia no Calendar, mas não havia helper que o montasse — role + name parecia o locator "semântico" correto.
|
||||
4. Por que passou nos runs anteriores? Porque a fragilidade é dependente do calendário (só dias 1–9) e o alvo caiu nessa faixa apenas em 2026-10-02.
|
||||
5. Por que nenhuma camada a montante pegou? Porque unit/int não veem locators de DOM e o e2e de PR é `selected` (OPS72) — a classe só é pega no verify full do deploy.
|
||||
|
||||
## Correção
|
||||
|
||||
Sem mudança de schema/produto — o defeito era do locator do spec:
|
||||
|
||||
- `tests/e2e/helpers/agendaPeriodLabels.ts:46`: novo helper `calendarDaySelector(civilDate)` → `[data-day="DD/MM/YYYY"]` (o contrato do `Calendar.tsx:167`), aditivo (funções existentes intocadas).
|
||||
- `tests/e2e/campaignActivity.e2e.spec.ts:357`: o C104 clica `endPicker.locator(calendarDaySelector(endCivilDate))`; comentário atualizado.
|
||||
- `tests/unit/e2eNavigationConventions.unit.spec.ts:96`: guard miss #55 que varre todos os `tests/e2e/**/*.e2e.spec.ts` e falha o build em clique de célula de dia por nome (`*DayLabel` ou literais/templates com " de " e ano), + teste do contrato do helper (zero-padded) em `:119`.
|
||||
- `docs/TESTING.md:17`: parágrafo "Calendar day-cell clicks (miss #55)", ao lado do miss #54.
|
||||
|
||||
Resolve a causa: o clique passa a mirar o atributo de contrato (inequívoco por construção) em vez do texto, e a suposição antiga ("clicar pelo nome é seguro") deixa de ser aceita sem falhar um teste.
|
||||
|
||||
## Verificação
|
||||
|
||||
- Sem o fix: repro local em dev (`env -u CI pnpm test:e2e --no-deps --project=campaign -g "Todo o dia"`) falhou exatamente com o strict mode violation (3 elementos: data-day 02/10, 12/10, 22/10) em 2026-10-01; no CI falhou nas 3 tentativas (runs `36816518055` e `36820002374`).
|
||||
- Guard de regressão: com o spec antigo (stash) a suíte `tests/unit/e2eNavigationConventions.unit.spec.ts` falha com offender `tests/e2e/campaignActivity.e2e.spec.ts:355`; com o fix, 4 passed.
|
||||
- Com o fix: e2e C104 1 passed (1.4m, dev); `pnpm gate:fast` verde (eslint `--max-warnings=0`, `tsc --noEmit`, unit 458 arquivos / 5.071 testes).
|
||||
- Flaky do run `36820002374` (7, todos passaram no retry; sem relação causal com o diff): `frontendShareLink` (kill-switch, 404 pós-republish), `campaignAgendaGoogleSync` (500 `POST /campanha/agenda`), `campaignBottomNav` (clique não navegou), `campaignMunicipalities` (apoiador não visível), `campaignPeople` (filtro não aplicado na URL), `campaignTerritoriesHttp` (cleanup com transação abortada), `frontendJingles` (404 de mídia). O run `36816518055` teve 3 flaky.
|
||||
- CI: a preencher (PR).
|
||||
- Prod: não se aplica (bug de CI/teste).
|
||||
|
||||
## Prevenção
|
||||
|
||||
| Estratégia | Custo | Estado |
|
||||
| ------------------------------------------------------------------------------------------------------ | ------ | ------------------------------------------ |
|
||||
| Helper `calendarDaySelector` como contrato único para clicar célula de dia | barata | implementada neste PR |
|
||||
| Guard miss #55 no `e2eNavigationConventions` (varre specs futuros e auto-testa o contrato zero-padded) | barata | implementada neste PR |
|
||||
| Doc em `docs/TESTING.md` ("Calendar day-cell clicks (miss #55)") | barata | implementada neste PR |
|
||||
| Page Object/helper de calendário completo | cara | documentada — não implementada neste fluxo |
|
||||
| Lint AST para locators (hoje o guard é regex por linha) | cara | documentada — não implementada neste fluxo |
|
||||
| `failOnFlakyTests`/quarentena (hoje `retries: 2` sem `failOnFlakyTests`, `playwright.config.ts:119`) | cara | documentada — não implementada neste fluxo |
|
||||
| Estabilizar os flaky listados (causas próprias) | cara | documentada — não implementada neste fluxo |
|
||||
|
||||
**Estratégia implementada:** os cliques de célula de dia passam a usar um contrato único (`data-day` via helper), um guard de convenção varre todos os specs e falha o build no padrão antigo (e auto-testa o contrato), e a convenção está documentada no `docs/TESTING.md`. A varredura não achou outro spec com o mesmo padrão.
|
||||
|
||||
**Estratégia documentada (cara):** Page Object/helper de calendário completo; lint AST para locators; `failOnFlakyTests`/quarentena (`playwright.config.ts:119` roda `retries: 2` sem `failOnFlakyTests`); e estabilizar os flaky listados, que têm causas próprias e ficam como débito separado.
|
||||
|
||||
## Lições
|
||||
|
||||
- Locator "semântico" por texto pode ser menos estável que um atributo de contrato; `data-day` já existia e não foi usado.
|
||||
- O C134 removeu o hardcode de data mas manteve o matcher dependente do calendário: remover a data fixa não basta se o locator continua ambíguo.
|
||||
- O e2e de PR é `selected` (OPS72) e o verify full do deploy é o primeiro a pegar a classe — por isso o vermelho só apareceu no deploy.
|
||||
- A falha de hoje degradou o CI por ~11h e bloqueou a lane: a segunda detecção (#1406) ocorreu porque a primeira (#1401) foi fechada sem PR de fix (a decisão da primeira sessão é não apurada).
|
||||
|
|
@ -39,8 +39,9 @@
|
|||
"content:instagram:withdraw": "cross-env NODE_OPTIONS=\"--no-deprecation --import=tsx/esm --import=./scripts/seed-loader.mjs\" node scripts/withdraw-instagram-content.mjs",
|
||||
"content:instagram:prune": "cross-env NODE_OPTIONS=\"--no-deprecation --import=tsx/esm --import=./scripts/seed-loader.mjs\" node scripts/prune-instagram-content.mjs",
|
||||
"archive:catalog": "cross-env NODE_OPTIONS=\"--no-deprecation --import=tsx/esm --import=./scripts/seed-loader.mjs\" node scripts/catalog-archive-photos.mjs",
|
||||
"faces:enroll": "cross-env NODE_OPTIONS=\"--no-deprecation --import=tsx/esm --import=./scripts/seed-loader.mjs\" node scripts/enroll-face-subject.mjs",
|
||||
"faces:index": "cross-env NODE_OPTIONS=\"--no-deprecation --import=tsx/esm --import=./scripts/seed-loader.mjs\" node scripts/index-archive-faces.mjs",
|
||||
"archive:publish": "cross-env NODE_OPTIONS=\"--no-deprecation --import=tsx/esm --import=./scripts/seed-loader.mjs\" node scripts/publish-archive-photos.mjs",
|
||||
"seed:face-consents": "cross-env NODE_OPTIONS=\"--no-deprecation --import=tsx/esm --import=./scripts/seed-loader.mjs\" node scripts/seed-face-consents.mjs",
|
||||
"db:seed:minimal": "cross-env NODE_OPTIONS=\"--no-deprecation --import=tsx/esm --import=./scripts/seed-loader.mjs\" node scripts/seed-minimal.mjs",
|
||||
"campaign:staging:test-account": "cross-env NODE_OPTIONS=\"--no-deprecation --import=tsx/esm --import=./scripts/seed-loader.mjs\" node scripts/bootstrap-staging-test-account.mjs",
|
||||
"db:check:push-chain": "node scripts/check-push-chain.mjs",
|
||||
|
|
|
|||
|
|
@ -1,224 +0,0 @@
|
|||
/**
|
||||
* C234 — enrolls one person in the selfie-search index (A/C scope of the gate,
|
||||
* PR #1370): the assessoria runs this WITH the person, after the signed
|
||||
* adherence consent, and the row is the only place a consented descriptor
|
||||
* exists. The selfie is read from disk, the descriptor is computed locally by
|
||||
* the same face-api nets the browser runs (only ONE face is accepted) and the
|
||||
* image is never stored or uploaded anywhere.
|
||||
*
|
||||
* Modes:
|
||||
* pnpm faces:enroll --label "<nome>" --selfie <arquivo>
|
||||
* plan/dry-run (default) — detects the face,
|
||||
* resolves the consent and reports; no write
|
||||
* pnpm faces:enroll ... --apply writes the faceSubject row; requires
|
||||
* FACE_ENROLL_CONFIRM=1 outside local dev and
|
||||
* the declared TEQO_ENV matching the database
|
||||
*
|
||||
* Options: --subject <id> (re-enrollment: replaces the descriptor, advances
|
||||
* `enrolledAt` and clears the derived links), --out <dir> (receipts, default
|
||||
* `data/face`), --help.
|
||||
*
|
||||
* Guards: fails closed when the index Consent (stable key) is not configured,
|
||||
* when the selfie has 0 or more than 1 detectable face, and on a non-local
|
||||
* target without the intent flag + declared environment. The receipt never
|
||||
* carries the descriptor nor the image.
|
||||
*/
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
|
||||
import { getPayload } from 'payload'
|
||||
|
||||
import { FACE_INDEX_CONSENT_KEY } from '../src/lib/campaignConsentKeys.ts'
|
||||
import { FACE_SEARCH_MODEL } from '../src/lib/faceSearch.ts'
|
||||
|
||||
import {
|
||||
TEQO_ENV_DATABASE_BY_ENV,
|
||||
assertEnvironmentDatabaseTarget,
|
||||
assertWriteConfirm,
|
||||
databaseTarget,
|
||||
dieWithLabel,
|
||||
loadCliEnv,
|
||||
writeRepoFile,
|
||||
} from './lib/cli.mjs'
|
||||
import { createNodeFaceEngine } from './lib/faceEngine.mjs'
|
||||
import {
|
||||
FACE_ENROLL_DEFAULT_OUT_DIR,
|
||||
faceEnrollReportStamp,
|
||||
formatFaceEnrollReport,
|
||||
parseFaceEnrollCliArgs,
|
||||
} from './lib/faceEnrollPlan.mjs'
|
||||
|
||||
loadCliEnv()
|
||||
|
||||
const die = dieWithLabel('faces:enroll')
|
||||
|
||||
const WRITE_CONFIRM_FLAG = 'FACE_ENROLL_CONFIRM'
|
||||
|
||||
const envLines = Object.entries(TEQO_ENV_DATABASE_BY_ENV)
|
||||
.map(([environment, database]) => `${environment} (${database})`)
|
||||
.join(' | ')
|
||||
|
||||
const HELP = `
|
||||
Uso: pnpm faces:enroll --label "<nome>" --selfie <arquivo> [opções]
|
||||
|
||||
Inscreve uma pessoa no índice da busca por selfie (/fotos/encontre). A selfie é
|
||||
lida do disco e processada localmente (mesmos modelos do navegador): exatamente
|
||||
1 rosto é exigido. O vetor fica no servidor; a imagem nunca é guardada.
|
||||
|
||||
Modos:
|
||||
(sem flag) plano/dry-run — detecta o rosto e resolve o consentimento; sem escrita
|
||||
--apply grava a pessoa no índice (exige ${WRITE_CONFIRM_FLAG}=1 fora do dev local)
|
||||
|
||||
Opções:
|
||||
--label <nome> nome interno da pessoa (nunca aparece no site)
|
||||
--selfie <arquivo> foto com um único rosto
|
||||
--subject <id> re-enrollment: substitui o vetor e limpa os vínculos derivados
|
||||
--out <dir> diretório dos recibos (default ${FACE_ENROLL_DEFAULT_OUT_DIR})
|
||||
--help esta ajuda
|
||||
|
||||
Ambiente:
|
||||
DATABASE_URL alvo (obrigatório em todos os modos)
|
||||
|
||||
--apply em alvo não-local/produção exige ${WRITE_CONFIRM_FLAG}=1 e TEQO_ENV=${envLines}
|
||||
casando o banco exato. O consentimento de adesão (chave ${FACE_INDEX_CONSENT_KEY}) precisa
|
||||
existir no admin; sem ele o fluxo falha fechado.
|
||||
`
|
||||
|
||||
const writeReport = async (options, report, suffix = '') => {
|
||||
const stamp = faceEnrollReportStamp(report.runAt)
|
||||
const relativePath = join(options.out, 'reports', `face-enroll-${stamp}${suffix}.json`)
|
||||
const body = JSON.stringify(report, null, 2)
|
||||
await writeRepoFile({
|
||||
label: 'faces:enroll',
|
||||
root: process.cwd(),
|
||||
relativePath,
|
||||
body,
|
||||
})
|
||||
return join(process.cwd(), relativePath)
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const options = parseFaceEnrollCliArgs(process.argv.slice(2))
|
||||
if (options.help) {
|
||||
console.log(HELP)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
if (!process.env.DATABASE_URL) die('DATABASE_URL não definida; recusando continuar.')
|
||||
|
||||
const mode = options.apply ? 'apply' : 'plan'
|
||||
const runAt = new Date().toISOString()
|
||||
const startedAt = Date.now()
|
||||
console.log(`[faces:enroll] alvo: ${databaseTarget()} | modo: ${mode}`)
|
||||
|
||||
if (mode === 'apply') {
|
||||
assertWriteConfirm({
|
||||
label: 'faces:enroll',
|
||||
flag: WRITE_CONFIRM_FLAG,
|
||||
command: 'pnpm faces:enroll --label "<nome>" --selfie <arquivo> --apply',
|
||||
})
|
||||
assertEnvironmentDatabaseTarget()
|
||||
}
|
||||
|
||||
try {
|
||||
// Readability probe only: the bytes are decoded by `prepareFaceImage`
|
||||
// below; this gives the operator a friendly refusal before the engine.
|
||||
await readFile(options.selfie)
|
||||
} catch (error) {
|
||||
die(`não foi possível ler a selfie ${options.selfie}: ${error?.message ?? error}`)
|
||||
}
|
||||
|
||||
const engine = await createNodeFaceEngine(process.cwd()).catch((error) => {
|
||||
die(error.message)
|
||||
})
|
||||
|
||||
const { prepareFaceImage } =
|
||||
await import('../src/utilities/faceSubjects/faceSubjectPhotoIndex.ts')
|
||||
let descriptors
|
||||
try {
|
||||
descriptors = await engine.detectPixels(await prepareFaceImage(options.selfie))
|
||||
} catch (error) {
|
||||
die(`engine falhou ao processar a selfie: ${error?.message ?? error}`)
|
||||
}
|
||||
|
||||
const baseReport = {
|
||||
runAt,
|
||||
mode,
|
||||
target: databaseTarget(),
|
||||
model: FACE_SEARCH_MODEL,
|
||||
label: options.label.trim(),
|
||||
subjectId: options.subject,
|
||||
subjectAction: null,
|
||||
faceCount: descriptors.length,
|
||||
allowed: descriptors.length === 1,
|
||||
reason:
|
||||
descriptors.length === 1
|
||||
? null
|
||||
: descriptors.length === 0
|
||||
? 'nenhum rosto detectado — use uma selfie nítida, de frente e bem iluminada'
|
||||
: 'mais de um rosto na selfie — use uma foto com apenas uma pessoa',
|
||||
consentKey: FACE_INDEX_CONSENT_KEY,
|
||||
consentHash: null,
|
||||
durationMs: 0,
|
||||
}
|
||||
|
||||
if (!baseReport.allowed) {
|
||||
const report = { ...baseReport, durationMs: Date.now() - startedAt }
|
||||
const reportPath = await writeReport(options, report)
|
||||
for (const line of formatFaceEnrollReport(report)) console.log(line)
|
||||
console.log(`\n[faces:enroll] recibo JSON: ${reportPath}`)
|
||||
die('enrollment recusado — detalhe no recibo acima.')
|
||||
}
|
||||
|
||||
const config = (await import('../src/payload.config.ts')).default
|
||||
const payload = await getPayload({ config })
|
||||
const { getConsentByKey } = await import('../src/utilities/campaignConsent.ts')
|
||||
const consent = await getConsentByKey(payload, FACE_INDEX_CONSENT_KEY)
|
||||
if (!consent) {
|
||||
const report = { ...baseReport, durationMs: Date.now() - startedAt }
|
||||
await writeReport(options, report)
|
||||
for (const line of formatFaceEnrollReport(report)) console.log(line)
|
||||
die(
|
||||
`consentimento de adesão não configurado (chave ${FACE_INDEX_CONSENT_KEY}) — o fluxo falha fechado.`,
|
||||
)
|
||||
}
|
||||
|
||||
const consentHash = consent.contentHash
|
||||
if (mode === 'plan') {
|
||||
const report = {
|
||||
...baseReport,
|
||||
consentHash,
|
||||
durationMs: Date.now() - startedAt,
|
||||
}
|
||||
const reportPath = await writeReport(options, report)
|
||||
for (const line of formatFaceEnrollReport(report)) console.log(line)
|
||||
console.log(`\n[faces:enroll] recibo JSON: ${reportPath}`)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const { enrollFaceSubject } =
|
||||
await import('../src/utilities/faceSubjects/faceSubjectEnrollment.ts')
|
||||
const enrolled = await enrollFaceSubject({
|
||||
payload,
|
||||
label: baseReport.label,
|
||||
descriptor: descriptors[0],
|
||||
consent: { id: consent.id, contentHash: consentHash },
|
||||
subjectId: options.subject,
|
||||
})
|
||||
|
||||
const report = {
|
||||
...baseReport,
|
||||
subjectId: enrolled.id,
|
||||
subjectAction: enrolled.created ? 'created' : 'updated',
|
||||
consentHash,
|
||||
durationMs: Date.now() - startedAt,
|
||||
}
|
||||
const reportPath = await writeReport(options, report)
|
||||
for (const line of formatFaceEnrollReport(report)) console.log(line)
|
||||
console.log(`\n[faces:enroll] recibo JSON: ${reportPath}`)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
die(error?.message || String(error))
|
||||
})
|
||||
|
|
@ -1,11 +1,9 @@
|
|||
/**
|
||||
* C234 — indexes the approved photo archive for the selfie search: each photo
|
||||
* C242 — indexes the approved photo archive for the selfie search: each photo
|
||||
* is downloaded from the private storage, prepared small and handed to the SAME
|
||||
* face-api engine the browser runs; the descriptors are compared against the
|
||||
* enrolled subjects and thrown away — only the photo↔subject links and the
|
||||
* photo's revision marker are persisted (A/C scope of the gate, PR #1370: no
|
||||
* anonymous face index anywhere). Adding/re-enrolling a subject changes the
|
||||
* revision, so the next run reprocesses every approved photo.
|
||||
* face-api engine the browser runs; the descriptors of every detected face are
|
||||
* PERSISTED as anonymous rows in `archivePhotoFace` (scope B, decision of
|
||||
* 2026-10-01: any visitor can find themselves; no identity, no score).
|
||||
*
|
||||
* Modes:
|
||||
* pnpm faces:index plan/dry-run (default) — the queue; no engine, no write
|
||||
|
|
@ -13,7 +11,7 @@
|
|||
* FACE_INDEX_CONFIRM=1 outside local dev, the
|
||||
* declared TEQO_ENV and the complete S3_* set
|
||||
* when the target media is remote
|
||||
* pnpm faces:index --verify read-only inventory (indexed/stale/consent)
|
||||
* pnpm faces:index --verify read-only inventory (indexed/stale/descriptors)
|
||||
*
|
||||
* Options: --limit <n> (canary), --refresh (ignores the marker), --out <dir>
|
||||
* (receipts, default `data/face`), --help.
|
||||
|
|
@ -25,7 +23,6 @@ import { join } from 'node:path'
|
|||
|
||||
import { getPayload } from 'payload'
|
||||
|
||||
import { FACE_INDEX_CONSENT_KEY } from '../src/lib/campaignConsentKeys.ts'
|
||||
import { FACE_SEARCH_MODEL } from '../src/lib/faceSearch.ts'
|
||||
|
||||
import {
|
||||
|
|
@ -63,14 +60,14 @@ const HELP = `
|
|||
Uso: pnpm faces:index [opções]
|
||||
|
||||
Indexa as fotos APROVADAS do acervo para a busca por selfie: por foto, detecta
|
||||
os rostos com os mesmos modelos do navegador, compara com os descritores das
|
||||
pessoas inscritas e grava só os vínculos (foto ↔ pessoa) + a revisão da foto.
|
||||
Os descritores dos rostos do acervo são descartados — não existe índice anônimo.
|
||||
os rostos com os mesmos modelos do navegador e grava os descritores como linhas
|
||||
anônimas (foto + vetor + modelo) em archivePhotoFace. Não há nome nem vínculo
|
||||
com pessoa; a busca responde só com fotos.
|
||||
|
||||
Modos (mutuamente exclusivos; o default é o plano):
|
||||
(sem flag) plano/dry-run — fila e revisão; sem engine nem escrita
|
||||
--apply processa a fila (engine local + escrita transacional)
|
||||
--verify inventário read-only (indexadas/desatualizadas/consentimento)
|
||||
--verify inventário read-only (indexadas/desatualizadas/rostos)
|
||||
|
||||
Opções:
|
||||
--limit <n> --apply: processa no máximo n fotos (canário)
|
||||
|
|
@ -130,24 +127,22 @@ async function main() {
|
|||
|
||||
const config = (await import('../src/payload.config.ts')).default
|
||||
const { listArchivePhotoFaceIndexQueue, indexArchivePhotoFaces } =
|
||||
await import('../src/utilities/faceSubjects/faceSubjectPhotoIndex.ts')
|
||||
const { listFaceSubjects } = await import('../src/utilities/faceSubjects/faceSubjectReads.ts')
|
||||
const { getConsentByKey } = await import('../src/utilities/campaignConsent.ts')
|
||||
await import('../src/utilities/faceIndex/faceDescriptorIndex.ts')
|
||||
|
||||
const payload = await getPayload({ config })
|
||||
const startedAt = Date.now()
|
||||
|
||||
if (mode === 'verify') {
|
||||
const [queue, subjects, consent] = await Promise.all([
|
||||
const [queue, descriptors] = await Promise.all([
|
||||
listArchivePhotoFaceIndexQueue({ payload }),
|
||||
listFaceSubjects(payload),
|
||||
getConsentByKey(payload, FACE_INDEX_CONSENT_KEY),
|
||||
payload.count({
|
||||
collection: 'archivePhotoFace',
|
||||
where: { model: { equals: FACE_SEARCH_MODEL } },
|
||||
// Intentional bypass: the batch CLI is a trusted operator with no session.
|
||||
overrideAccess: true,
|
||||
}),
|
||||
])
|
||||
const inventory = summarizeFaceIndexInventory({
|
||||
queue,
|
||||
subjects,
|
||||
currentConsentHash: consent?.contentHash ?? null,
|
||||
})
|
||||
const inventory = summarizeFaceIndexInventory({ queue, descriptors: descriptors.totalDocs })
|
||||
const report = {
|
||||
runAt,
|
||||
mode,
|
||||
|
|
@ -160,21 +155,9 @@ async function main() {
|
|||
for (const line of formatFaceIndexInventory(inventory, FACE_SEARCH_MODEL)) console.log(line)
|
||||
console.log(`\n[faces:index] recibo JSON: ${reportPath}`)
|
||||
|
||||
const problems = []
|
||||
if (!consent) {
|
||||
problems.push(
|
||||
`consentimento de adesão ausente (chave ${FACE_INDEX_CONSENT_KEY}) — a busca responde vazio para todos`,
|
||||
)
|
||||
}
|
||||
if (inventory.staleConsentSubjects > 0) {
|
||||
problems.push(
|
||||
`${inventory.staleConsentSubjects} sujeito(s) com consentimento vencido — re-consentir e re-enrollar`,
|
||||
)
|
||||
}
|
||||
if (inventory.stale > 0) {
|
||||
problems.push(`${inventory.stale} foto(s) desatualizada(s) — rode o --apply`)
|
||||
die(`${inventory.stale} foto(s) desatualizada(s) — rode o --apply`)
|
||||
}
|
||||
if (problems.length > 0) die(problems.join('; '))
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
|
|
@ -194,10 +177,9 @@ async function main() {
|
|||
indexKey: queue.indexKey,
|
||||
totalApproved: queue.totalApproved,
|
||||
stale: queue.stale,
|
||||
eligibleSubjects: queue.eligibleSubjects,
|
||||
items: queue.items.length,
|
||||
},
|
||||
summary: { indexed: 0, failed: 0, linkedPhotos: 0, linksBySubject: [], failures: [] },
|
||||
summary: { indexed: 0, failed: 0, descriptors: 0, failures: [] },
|
||||
preview: queue.items.slice(0, options.limit ?? 20).map((item) => ({ photoId: item.id })),
|
||||
durationMs: Date.now() - startedAt,
|
||||
}
|
||||
|
|
@ -207,10 +189,9 @@ async function main() {
|
|||
process.exit(0)
|
||||
}
|
||||
|
||||
if (queue.eligibleSubjects === 0) {
|
||||
die(
|
||||
'nenhuma pessoa elegível no índice — rode o faces:enroll antes (o lote não tem o que procurar).',
|
||||
)
|
||||
if (queue.items.length === 0) {
|
||||
console.log('[faces:index] nada a fazer — todas as fotos aprovadas estão na revisão atual.')
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const engine = await createNodeFaceEngine(process.cwd()).catch((error) => {
|
||||
|
|
@ -229,8 +210,8 @@ async function main() {
|
|||
const detail =
|
||||
result.status === 'failed'
|
||||
? ` [${result.stage}]: ${result.error}`
|
||||
: result.matchedSubjects.length > 0
|
||||
? ` → ${result.matchedSubjects.length} vínculo(s)`
|
||||
: result.descriptorCount > 0
|
||||
? ` → ${result.descriptorCount} rosto(s)`
|
||||
: ''
|
||||
console.log(`[faces:index] ${result.status}${detail} foto ${item.id}`)
|
||||
}
|
||||
|
|
@ -245,7 +226,6 @@ async function main() {
|
|||
indexKey: queue.indexKey,
|
||||
totalApproved: queue.totalApproved,
|
||||
stale: queue.stale,
|
||||
eligibleSubjects: queue.eligibleSubjects,
|
||||
items: queue.items.length,
|
||||
},
|
||||
summary,
|
||||
|
|
|
|||
83
scripts/lib/archivePublishPlan.mjs
Normal file
83
scripts/lib/archivePublishPlan.mjs
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
/**
|
||||
* C242 — pure planning/reporting of `pnpm archive:publish`: the argv parser,
|
||||
* the run summary and the human lines + JSON receipt. No I/O of its own, so the
|
||||
* unit spec drives it with fakes.
|
||||
*/
|
||||
|
||||
const USAGE = 'uso: `pnpm archive:publish [--apply] [--limit <n>] [--out <dir>]`'
|
||||
|
||||
export const ARCHIVE_PUBLISH_DEFAULT_OUT_DIR = 'data/archive'
|
||||
|
||||
export const archivePublishReportStamp = (runAt) => String(runAt).replace(/[:.]/g, '-')
|
||||
|
||||
/**
|
||||
* @param {string[]} [argv]
|
||||
* @returns {{ apply: boolean, limit: number | null, out: string, help: boolean }}
|
||||
*/
|
||||
export const parseArchivePublishCliArgs = (argv = process.argv.slice(2)) => {
|
||||
const options = { apply: false, limit: null, out: ARCHIVE_PUBLISH_DEFAULT_OUT_DIR, 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('--')) {
|
||||
throw new Error(`faltou valor para ${arg} — ${USAGE}.`)
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
if (arg === '--help' || arg === '-h') options.help = true
|
||||
else if (arg === '--apply') options.apply = true
|
||||
else if (arg === '--limit') options.limit = Number(value())
|
||||
else if (arg === '--out') options.out = value()
|
||||
else throw new Error(`argumento desconhecido: ${arg} — ${USAGE}.`)
|
||||
}
|
||||
|
||||
if (options.help) return options
|
||||
if (options.limit !== null && (!Number.isSafeInteger(options.limit) || options.limit < 1)) {
|
||||
throw new Error('--limit deve ser >= 1.')
|
||||
}
|
||||
if (options.out.split(/[\\/]/).includes('..')) {
|
||||
throw new Error('--out não pode escapar do diretório do repo (sem "..").')
|
||||
}
|
||||
return options
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Array<{ photoId: number, status: string, error?: string | null }>} results
|
||||
*/
|
||||
export const summarizeArchivePublishResults = (results) => {
|
||||
const failures = []
|
||||
let approved = 0
|
||||
let failed = 0
|
||||
|
||||
for (const result of results) {
|
||||
if (result.status === 'approved') approved += 1
|
||||
else {
|
||||
failed += 1
|
||||
failures.push({ photoId: result.photoId, error: result.error ?? null })
|
||||
}
|
||||
}
|
||||
|
||||
return { approved, failed, failures }
|
||||
}
|
||||
|
||||
export const formatArchivePublishReport = (report) => {
|
||||
const lines = [
|
||||
`[archive:publish] modo: ${report.mode} | alvo: ${report.target}`,
|
||||
`[archive:publish] drafts elegíveis: ${report.queue.totalDrafts}`,
|
||||
]
|
||||
|
||||
if (report.mode !== 'plan') {
|
||||
lines.push(
|
||||
`[archive:publish] aprovadas: ${report.summary.approved} | falharam: ${report.summary.failed}`,
|
||||
)
|
||||
}
|
||||
|
||||
for (const failure of report.summary?.failures ?? []) {
|
||||
lines.push(`[archive:publish] ✗ foto ${failure.photoId}: ${failure.error}`)
|
||||
}
|
||||
|
||||
return lines
|
||||
}
|
||||
|
|
@ -113,6 +113,9 @@ export const E2E_AFFECTED_MANIFEST = [
|
|||
'src/components/ShareLinkRedirect.tsx',
|
||||
'src/components/shareLink',
|
||||
'src/app/(frontend)/api/share-link',
|
||||
// S44 — the home page is the only wiring of the Plenária section; a diff
|
||||
// there alone must still wake the spec that owns the section.
|
||||
'src/app/(frontend)/(home)',
|
||||
],
|
||||
specs: ['frontendShareLink'],
|
||||
},
|
||||
|
|
@ -228,15 +231,15 @@ export const E2E_AFFECTED_MANIFEST = [
|
|||
specs: ['frontendFotos', 'frontendFotosSelfie'],
|
||||
},
|
||||
{
|
||||
// C234 — the selfie search: the `/fotos/encontre` page (already matched by
|
||||
// the C233 prefix above), the anonymous descriptor endpoint, the consented
|
||||
// subjects and the bounded-body/rate-limit owners it shares. The migration
|
||||
// makes every PR of this delivery high-risk (curated only).
|
||||
// C242 — the selfie search: the `/fotos/encontre` page (already matched by
|
||||
// the C233 prefix above), the anonymous descriptor endpoint, the anonymous
|
||||
// photo-face index and the bounded-body/rate-limit owners it shares. The
|
||||
// migration makes every PR of this delivery high-risk (curated only).
|
||||
prefixes: [
|
||||
'src/app/(frontend)/api/fotos',
|
||||
'src/lib/faceSearch.ts',
|
||||
'src/utilities/faceSubjects',
|
||||
'src/collections/FaceSubject.ts',
|
||||
'src/utilities/faceIndex',
|
||||
'src/collections/ArchivePhotoFace.ts',
|
||||
'src/collections/Consent.ts',
|
||||
'src/utilities/campaignConsent.ts',
|
||||
'src/lib/campaignConsentKeys.ts',
|
||||
|
|
|
|||
52
scripts/lib/faceConsentTexts.mjs
Normal file
52
scripts/lib/faceConsentTexts.mjs
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
/**
|
||||
* C242 — the legal texts the selfie search resolves by stable key, versioned in
|
||||
* the repo so the delivery that opens the surface owns what the visitor reads:
|
||||
*
|
||||
* - `busca-selfie-fotos` is the QUERY consent: authorizes the use of the
|
||||
* visitor's own selfie/biometrics for this one search, on device.
|
||||
* - `busca-selfie-indice` is the PUBLIC NOTICE of the anonymous archive index
|
||||
* (scope B): transparency about the descriptor index over approved photos
|
||||
* and the self-service opt-out. It is not an enrollment consent — nobody is
|
||||
* individually enrolled.
|
||||
*
|
||||
* Both are written to the `consent` collection by `pnpm seed:face-consents`
|
||||
* (create-if-missing, idempotent, guarded); editing a text here and re-running
|
||||
* updates the row (versioned by Payload).
|
||||
*/
|
||||
|
||||
/** Builds the Lexical root of a Consent text from plain paragraphs. */
|
||||
export const buildConsentRichText = (paragraphs) => ({
|
||||
root: {
|
||||
type: 'root',
|
||||
children: paragraphs.map((text) => ({
|
||||
type: 'paragraph',
|
||||
children: [{ type: 'text', text, version: 1 }],
|
||||
direction: null,
|
||||
format: '',
|
||||
indent: 0,
|
||||
version: 1,
|
||||
})),
|
||||
direction: null,
|
||||
format: '',
|
||||
indent: 0,
|
||||
version: 1,
|
||||
},
|
||||
})
|
||||
|
||||
export const FACE_SEARCH_CONSENT_PARAGRAPHS = [
|
||||
'Autorizo, de forma livre, informada e específica, o uso da minha selfie e dos dados biométricos faciais dela extraídos exclusivamente para esta consulta: procurar, entre as fotos públicas aprovadas do acervo do mandato de Jorge Solla, aquelas em que eu apareço.',
|
||||
'O reconhecimento acontece no meu próprio aparelho. A imagem da selfie não é enviada nem armazenada; ao servidor é enviado apenas o vetor matemático necessário para a comparação, que é descartado ao fim da consulta e não fica guardado.',
|
||||
'Estou ciente de que o resultado não mostra nomes de terceiros e não informa grau de semelhança. A busca pode não encontrar fotos, e posso interrompê-la a qualquer momento.',
|
||||
'A base legal é o consentimento específico para dados pessoais sensíveis (art. 11, I, da LGPD). Posso retirar este consentimento a qualquer momento, sem custo, pelo próprio fluxo ou pelos canais do mandato — a retirada não afeta o que já foi realizado.',
|
||||
'Controlador: campanha Jorge Solla 1313. Mais detalhes na Política de Privacidade do site.',
|
||||
]
|
||||
|
||||
export const FACE_INDEX_CONSENT_PARAGRAPHS = [
|
||||
'Aviso público sobre o índice de fotos: as fotos públicas aprovadas do acervo podem conter rostos de várias pessoas. Para que cada pessoa encontre as próprias fotos pela busca por selfie, o sistema mantém um índice biométrico anônimo — vetores matemáticos extraídos dos rostos presentes nessas fotos, sem nome, sem vínculo com cadastro de pessoas e sem qualquer identificação de quem aparece.',
|
||||
'O índice serve apenas para localizar as fotos da própria pessoa que faz a busca. Ele nunca é usado para identificar, nomear ou listar terceiros, e nunca cruza os dados biométricos com contatos, lideranças ou apoiadores.',
|
||||
'Qualquer pessoa pode retirar seu rosto do índice a qualquer momento, sem custo: use a opção “Minha presença” na página da busca e siga as instruções. A retirada apaga do índice as referências biométricas correspondentes, e o rosto deixa de ser encontrado.',
|
||||
'Para pedir a remoção de uma foto específica, use o canal indicado no álbum público. Fotos que não estejam aprovadas para o público não fazem parte do índice.',
|
||||
]
|
||||
|
||||
export const FACE_SEARCH_CONSENT_TEXT = buildConsentRichText(FACE_SEARCH_CONSENT_PARAGRAPHS)
|
||||
export const FACE_INDEX_CONSENT_TEXT = buildConsentRichText(FACE_INDEX_CONSENT_PARAGRAPHS)
|
||||
|
|
@ -1,91 +0,0 @@
|
|||
/**
|
||||
* C234 — pure planning/reporting of `pnpm faces:enroll`: the argv parser and
|
||||
* the human lines + JSON receipt of the enrollment. No I/O of its own — the
|
||||
* engine, the Consent resolution and the Payload write arrive as parameters,
|
||||
* so the unit spec drives everything with fakes.
|
||||
*/
|
||||
|
||||
const USAGE =
|
||||
'uso: `pnpm faces:enroll --label "<nome>" --selfie <arquivo> [--subject <id>] [--apply]`'
|
||||
|
||||
export const FACE_ENROLL_DEFAULT_OUT_DIR = 'data/face'
|
||||
|
||||
export const faceEnrollReportStamp = (runAt) => String(runAt).replace(/[:.]/g, '-')
|
||||
|
||||
/**
|
||||
* `pnpm faces:enroll` argv parser — pure, so the unit spec pins it (the CLI
|
||||
* owns the exit and the help text). The default mode is the plan/dry-run;
|
||||
* `--label` and `--selfie` are required in both modes so the plan shows the
|
||||
* real operation, not an abstract one.
|
||||
*
|
||||
* @param {string[]} [argv]
|
||||
* @returns {{ apply: boolean, label: string | null, selfie: string | null, subject: number | null, out: string, help: boolean }}
|
||||
*/
|
||||
export const parseFaceEnrollCliArgs = (argv = process.argv.slice(2)) => {
|
||||
const options = {
|
||||
apply: false,
|
||||
label: null,
|
||||
selfie: null,
|
||||
subject: null,
|
||||
out: FACE_ENROLL_DEFAULT_OUT_DIR,
|
||||
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('--')) {
|
||||
throw new Error(`faltou valor para ${arg} — ${USAGE}.`)
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
if (arg === '--help' || arg === '-h') options.help = true
|
||||
else if (arg === '--apply') options.apply = true
|
||||
else if (arg === '--label') options.label = value()
|
||||
else if (arg === '--selfie') options.selfie = value()
|
||||
else if (arg === '--subject') options.subject = Number(value())
|
||||
else if (arg === '--out') options.out = value()
|
||||
else throw new Error(`argumento desconhecido: ${arg} — ${USAGE}.`)
|
||||
}
|
||||
|
||||
if (options.help) return options
|
||||
if (!options.label?.trim()) throw new Error(`--label é obrigatório — ${USAGE}.`)
|
||||
if (!options.selfie?.trim()) throw new Error(`--selfie é obrigatório — ${USAGE}.`)
|
||||
if (options.subject !== null && (!Number.isSafeInteger(options.subject) || options.subject < 1)) {
|
||||
throw new Error('--subject deve ser um id >= 1.')
|
||||
}
|
||||
if (options.out.split(/[\\/]/).includes('..')) {
|
||||
throw new Error('--out não pode escapar do diretório do repo (sem "..").')
|
||||
}
|
||||
return options
|
||||
}
|
||||
|
||||
/**
|
||||
* The receipt + human lines of one enrollment: what was detected (face count —
|
||||
* never the descriptor), the subject row and the consent snapshot. A refusal
|
||||
* (0 or >1 faces) is a report with `allowed: false` and its reason.
|
||||
*
|
||||
* @param {{ runAt: string, mode: string, target: string, model: string, label: string, subjectId: number | null, subjectAction: 'created' | 'updated' | null, faceCount: number, allowed: boolean, reason?: string | null, consentKey: string, consentHash: string | null, durationMs: number }} report
|
||||
*/
|
||||
export const formatFaceEnrollReport = (report) => {
|
||||
const lines = [
|
||||
`[faces:enroll] modo: ${report.mode} | alvo: ${report.target} | modelo: ${report.model}`,
|
||||
`[faces:enroll] selfie: ${report.faceCount} rosto(s) detectado(s)`,
|
||||
]
|
||||
if (!report.allowed) {
|
||||
lines.push(`[faces:enroll] RECUSADO: ${report.reason ?? 'selfie fora do contrato'}`)
|
||||
return lines
|
||||
}
|
||||
if (report.subjectAction === null) {
|
||||
lines.push(`[faces:enroll] plano: ${report.label} (nada gravado; confirme com --apply)`)
|
||||
return lines
|
||||
}
|
||||
lines.push(
|
||||
`[faces:enroll] ${report.subjectAction === 'created' ? 'criada' : 'atualizada'}: #${report.subjectId} (${report.label})`,
|
||||
`[faces:enroll] consentimento: ${report.consentKey} · hash ${report.consentHash ?? '(ausente)'}`,
|
||||
`[faces:enroll] próximo passo: pnpm faces:index --apply (reprocessa as fotos aprovadas)`,
|
||||
)
|
||||
return lines
|
||||
}
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
/**
|
||||
* C234 — pure planning/reporting of `pnpm faces:index`: the argv parser, the
|
||||
* C242 — pure planning/reporting of `pnpm faces:index`: the argv parser, the
|
||||
* run summary, the `--verify` inventory and the human lines + JSON receipt. No
|
||||
* I/O of its own — the queue, the subjects and the results arrive as
|
||||
* I/O of its own — the queue, the descriptor counts and the results arrive as
|
||||
* parameters, so the unit spec drives everything with fakes.
|
||||
*/
|
||||
|
||||
|
|
@ -61,24 +61,21 @@ export const parseFaceIndexCliArgs = (argv = process.argv.slice(2)) => {
|
|||
}
|
||||
|
||||
/**
|
||||
* Aggregates one apply run: photos indexed (and how many subjects each linked),
|
||||
* Aggregates one apply run: photos indexed (and how many faces each stored),
|
||||
* photos refused by the engine/IO with stage+reason.
|
||||
*
|
||||
* @param {Array<{ photoId: number, status: string, matchedSubjects?: number[], stage?: string | null, error?: string | null }>} results
|
||||
* @param {Array<{ photoId: number, status: string, descriptorCount?: number, stage?: string | null, error?: string | null }>} results
|
||||
*/
|
||||
export const summarizeFaceIndexResults = (results) => {
|
||||
const linkedBySubject = new Map()
|
||||
const failures = []
|
||||
let indexed = 0
|
||||
let failed = 0
|
||||
let linkedPhotos = 0
|
||||
let descriptors = 0
|
||||
|
||||
for (const result of results) {
|
||||
if (result.status === 'indexed') {
|
||||
indexed += 1
|
||||
const matched = result.matchedSubjects ?? []
|
||||
if (matched.length > 0) linkedPhotos += 1
|
||||
for (const id of matched) linkedBySubject.set(id, (linkedBySubject.get(id) ?? 0) + 1)
|
||||
descriptors += result.descriptorCount ?? 0
|
||||
} else if (result.status === 'failed') {
|
||||
failed += 1
|
||||
failures.push({
|
||||
|
|
@ -89,48 +86,23 @@ export const summarizeFaceIndexResults = (results) => {
|
|||
}
|
||||
}
|
||||
|
||||
return {
|
||||
indexed,
|
||||
failed,
|
||||
linkedPhotos,
|
||||
linksBySubject: [...linkedBySubject.entries()]
|
||||
.sort((a, b) => a[0] - b[0])
|
||||
.map(([subjectId, photos]) => ({ subjectId, photos })),
|
||||
failures,
|
||||
}
|
||||
return { indexed, failed, descriptors, failures }
|
||||
}
|
||||
|
||||
/**
|
||||
* The `--verify` inventory: the honest gap is `stale` — approved photos whose
|
||||
* marker is not the current index revision (new enrollment, new model or never
|
||||
* indexed). Consent-edited subjects are reported separately: the query already
|
||||
* fails closed on them, but the operator must see they need re-consent.
|
||||
* marker is not the current index revision (never indexed or a model change).
|
||||
* `descriptors` is the stored face count of the current model.
|
||||
*
|
||||
* @param {{ queue: { indexKey: string, eligibleSubjects: number, totalApproved: number, stale: number }, subjects: Array<{ id: number, status: string | null, model: string | null, consentHash: string | null, matchedPhotoIds: number[] }>, currentConsentHash: string | null }} input
|
||||
* @param {{ queue: { indexKey: string, totalApproved: number, stale: number }, descriptors: number }} input
|
||||
*/
|
||||
export const summarizeFaceIndexInventory = ({ queue, subjects, currentConsentHash }) => {
|
||||
const active = subjects.filter((subject) => subject.status === 'active')
|
||||
const staleConsent = active.filter((subject) => subject.consentHash !== currentConsentHash)
|
||||
const linksBySubject = subjects
|
||||
.filter((subject) => subject.matchedPhotoIds.length > 0)
|
||||
.map((subject) => ({ subjectId: subject.id, photos: subject.matchedPhotoIds.length }))
|
||||
.sort((a, b) => a.subjectId - b.subjectId)
|
||||
|
||||
return {
|
||||
indexKey: queue.indexKey,
|
||||
totalApproved: queue.totalApproved,
|
||||
indexed: Math.max(0, queue.totalApproved - queue.stale),
|
||||
stale: queue.stale,
|
||||
// The eligibility predicate belongs to the batch owner; the inventory just
|
||||
// reports its count (a corrupted vector never counts as eligible).
|
||||
eligibleSubjects: queue.eligibleSubjects,
|
||||
activeSubjects: active.length,
|
||||
removedSubjects: subjects.length - active.length,
|
||||
staleConsentSubjects: staleConsent.length,
|
||||
linkedPhotos: linksBySubject.reduce((sum, link) => sum + link.photos, 0),
|
||||
linksBySubject,
|
||||
}
|
||||
}
|
||||
export const summarizeFaceIndexInventory = ({ queue, descriptors }) => ({
|
||||
indexKey: queue.indexKey,
|
||||
totalApproved: queue.totalApproved,
|
||||
indexed: Math.max(0, queue.totalApproved - queue.stale),
|
||||
stale: queue.stale,
|
||||
descriptors,
|
||||
})
|
||||
|
||||
/** One line per counted state of the inventory (pt-BR, operator-facing). */
|
||||
export const formatFaceIndexInventory = (inventory, model) => [
|
||||
|
|
@ -138,28 +110,20 @@ export const formatFaceIndexInventory = (inventory, model) => [
|
|||
`[faces:index] fotos aprovadas: ${inventory.totalApproved}`,
|
||||
`[faces:index] indexadas na revisão atual: ${inventory.indexed}`,
|
||||
`[faces:index] desatualizadas (a processar): ${inventory.stale}`,
|
||||
`[faces:index] sujeitos: ${inventory.activeSubjects} ativo(s), ${inventory.removedSubjects} removido(s), ${inventory.eligibleSubjects} elegível(is)`,
|
||||
`[faces:index] sujeitos com consentimento vencido (inelegíveis até re-consentir): ${inventory.staleConsentSubjects}`,
|
||||
`[faces:index] vínculos foto↔sujeito: ${inventory.linkedPhotos}`,
|
||||
...inventory.linksBySubject.map(
|
||||
(link) => `[faces:index] sujeito #${link.subjectId}: ${link.photos} foto(s)`,
|
||||
),
|
||||
`[faces:index] rostos no índice (modelo atual): ${inventory.descriptors}`,
|
||||
]
|
||||
|
||||
/** The receipt + human lines of one plan/apply run. */
|
||||
export const formatFaceIndexReport = (report) => {
|
||||
const lines = [
|
||||
`[faces:index] modo: ${report.mode} | alvo: ${report.target} | modelo: ${report.model}`,
|
||||
`[faces:index] fila: ${report.queue.items} foto(s) a processar (aprovadas: ${report.queue.totalApproved} | sujeitos elegíveis: ${report.queue.eligibleSubjects})`,
|
||||
`[faces:index] fila: ${report.queue.items} foto(s) a processar (aprovadas: ${report.queue.totalApproved})`,
|
||||
]
|
||||
|
||||
if (report.mode !== 'plan') {
|
||||
lines.push(
|
||||
`[faces:index] processadas: ${report.summary.indexed} | vinculadas a alguém: ${report.summary.linkedPhotos} | falharam: ${report.summary.failed}`,
|
||||
`[faces:index] processadas: ${report.summary.indexed} | rostos indexados: ${report.summary.descriptors} | falharam: ${report.summary.failed}`,
|
||||
)
|
||||
for (const link of report.summary.linksBySubject) {
|
||||
lines.push(`[faces:index] sujeito #${link.subjectId}: ${link.photos} foto(s)`)
|
||||
}
|
||||
}
|
||||
|
||||
for (const failure of report.summary?.failures ?? []) {
|
||||
|
|
|
|||
|
|
@ -44,6 +44,7 @@ export const SCRIPTS_SPEC_PINNED = [
|
|||
'scripts/lib/agent-session.mjs',
|
||||
'scripts/lib/ansi.mjs',
|
||||
'scripts/lib/archiveCatalogPlan.mjs',
|
||||
'scripts/lib/archivePublishPlan.mjs',
|
||||
'scripts/lib/archiveVisionApi.mjs',
|
||||
'scripts/lib/auto-unblock.mjs',
|
||||
'scripts/lib/briefingContent.mjs',
|
||||
|
|
@ -78,7 +79,7 @@ export const SCRIPTS_SPEC_PINNED = [
|
|||
'scripts/lib/dossieResearch.mjs',
|
||||
'scripts/lib/dossieUnit.mjs',
|
||||
'scripts/lib/e2e-affected-manifest.mjs',
|
||||
'scripts/lib/faceEnrollPlan.mjs',
|
||||
'scripts/lib/faceConsentTexts.mjs',
|
||||
'scripts/lib/faceIndexPlan.mjs',
|
||||
'scripts/lib/flickrApi.mjs',
|
||||
'scripts/lib/flickrPlan.mjs',
|
||||
|
|
|
|||
213
scripts/publish-archive-photos.mjs
Normal file
213
scripts/publish-archive-photos.mjs
Normal file
|
|
@ -0,0 +1,213 @@
|
|||
/**
|
||||
* C242 — publishes the photo archive in bulk: every `draft` photo becomes
|
||||
* `approved` so the public album (/fotos, C233) and the selfie search (C234/
|
||||
* C242) have what to show. The curation act is explicitly human and bulk
|
||||
* (decision of the owner, 2026-10-01); `removed` is NEVER touched — a takedown
|
||||
* stays a takedown.
|
||||
*
|
||||
* Modes:
|
||||
* pnpm archive:publish plan/dry-run (default) — the eligible queue; no write
|
||||
* pnpm archive:publish --apply approves the drafts; requires
|
||||
* ARCHIVE_PUBLISH_CONFIRM=1 outside local dev
|
||||
* and the declared TEQO_ENV matching the
|
||||
* exact database
|
||||
*
|
||||
* Options: --limit <n> (canary), --out <dir> (receipts, default `data/archive`),
|
||||
* --help.
|
||||
*
|
||||
* Preconditions enforced fail-closed: the album global must have a valid
|
||||
* removal channel configured (the same guard the per-photo approval uses) —
|
||||
* a public photo always carries the takedown path.
|
||||
*
|
||||
* Runbook (after --apply, bust the public cache from a process that owns it):
|
||||
* curl -X POST "https://jorgesolla1313.com.br/api/revalidate?tag=archivePhotos" \
|
||||
* -H "x-revalidate-secret: $REVALIDATE_SECRET"
|
||||
*/
|
||||
import { join } from 'node:path'
|
||||
|
||||
import { getPayload } from 'payload'
|
||||
|
||||
import { isArchivePhotoRemovalChannelUrl } from '../src/lib/archivePhotoCatalog.ts'
|
||||
|
||||
import {
|
||||
ARCHIVE_PUBLISH_DEFAULT_OUT_DIR,
|
||||
archivePublishReportStamp,
|
||||
formatArchivePublishReport,
|
||||
parseArchivePublishCliArgs,
|
||||
summarizeArchivePublishResults,
|
||||
} from './lib/archivePublishPlan.mjs'
|
||||
import {
|
||||
TEQO_ENV_DATABASE_BY_ENV,
|
||||
assertEnvironmentDatabaseTarget,
|
||||
assertWriteConfirm,
|
||||
databaseTarget,
|
||||
dieWithLabel,
|
||||
loadCliEnv,
|
||||
writeRepoFile,
|
||||
} from './lib/cli.mjs'
|
||||
|
||||
loadCliEnv()
|
||||
|
||||
const die = dieWithLabel('archive:publish')
|
||||
|
||||
const WRITE_CONFIRM_FLAG = 'ARCHIVE_PUBLISH_CONFIRM'
|
||||
const PAGE_SIZE = 200
|
||||
|
||||
const envLines = Object.entries(TEQO_ENV_DATABASE_BY_ENV)
|
||||
.map(([environment, database]) => `${environment} (${database})`)
|
||||
.join(' | ')
|
||||
|
||||
const HELP = `
|
||||
Uso: pnpm archive:publish [opções]
|
||||
|
||||
Aprova em lote as fotos DRAFT do acervo (publicationStatus: draft → approved),
|
||||
para o álbum público e a busca por selfie. Fotos "removed" nunca são tocadas.
|
||||
|
||||
Modos:
|
||||
(sem flag) plano/dry-run — fila elegível; sem escrita
|
||||
--apply aprova os drafts (exige ${WRITE_CONFIRM_FLAG}=1 fora do dev local)
|
||||
|
||||
Opções:
|
||||
--limit <n> processa no máximo n fotos (canário)
|
||||
--out <dir> diretório dos recibos (default ${ARCHIVE_PUBLISH_DEFAULT_OUT_DIR})
|
||||
--help esta ajuda
|
||||
|
||||
Ambiente:
|
||||
DATABASE_URL alvo (obrigatório em todos os modos)
|
||||
|
||||
--apply em alvo não-local/produção exige ${WRITE_CONFIRM_FLAG}=1 e TEQO_ENV=${envLines}
|
||||
casando o banco exato. O plano é read-only.
|
||||
`
|
||||
|
||||
const writeReport = async (options, report, suffix = '') => {
|
||||
const stamp = archivePublishReportStamp(report.runAt)
|
||||
const relativePath = join(options.out, 'reports', `archive-publish-${stamp}${suffix}.json`)
|
||||
await writeRepoFile({
|
||||
label: 'archive:publish',
|
||||
root: process.cwd(),
|
||||
relativePath,
|
||||
body: JSON.stringify(report, null, 2),
|
||||
})
|
||||
return join(process.cwd(), relativePath)
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const options = parseArchivePublishCliArgs(process.argv.slice(2))
|
||||
if (options.help) {
|
||||
console.log(HELP)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
if (!process.env.DATABASE_URL) die('DATABASE_URL não definida; recusando continuar.')
|
||||
|
||||
const mode = options.apply ? 'apply' : 'plan'
|
||||
const runAt = new Date().toISOString()
|
||||
console.log(`[archive:publish] alvo: ${databaseTarget()} | modo: ${mode}`)
|
||||
|
||||
if (mode === 'apply') {
|
||||
assertWriteConfirm({
|
||||
label: 'archive:publish',
|
||||
flag: WRITE_CONFIRM_FLAG,
|
||||
command: 'pnpm archive:publish --apply',
|
||||
})
|
||||
assertEnvironmentDatabaseTarget()
|
||||
}
|
||||
|
||||
const config = (await import('../src/payload.config.ts')).default
|
||||
const payload = await getPayload({ config })
|
||||
const startedAt = Date.now()
|
||||
|
||||
const album = await payload
|
||||
.findGlobal({ slug: 'photoAlbum', depth: 0, overrideAccess: true })
|
||||
.catch(() => null)
|
||||
if (!isArchivePhotoRemovalChannelUrl(album?.removalChannelUrl)) {
|
||||
die(
|
||||
'canal de remoção não configurado no global Álbum de fotos — aprove pelo admin antes do lote (a foto pública sempre carrega o caminho de remoção).',
|
||||
)
|
||||
}
|
||||
|
||||
const drafts = await payload.find({
|
||||
collection: 'archivePhoto',
|
||||
where: { publicationStatus: { equals: 'draft' } },
|
||||
sort: ['id'],
|
||||
depth: 0,
|
||||
limit: 0,
|
||||
pagination: false,
|
||||
select: { id: true },
|
||||
// Intentional bypass: the publish CLI is a trusted operator with no session.
|
||||
overrideAccess: true,
|
||||
})
|
||||
const queue = options.limit ? drafts.docs.slice(0, options.limit) : drafts.docs
|
||||
|
||||
if (mode === 'plan') {
|
||||
const report = {
|
||||
runAt,
|
||||
mode,
|
||||
target: databaseTarget(),
|
||||
queue: { totalDrafts: drafts.docs.length, items: queue.length },
|
||||
summary: { approved: 0, failed: 0, failures: [] },
|
||||
preview: queue.slice(0, 20).map((doc) => ({ photoId: doc.id })),
|
||||
durationMs: Date.now() - startedAt,
|
||||
}
|
||||
const reportPath = await writeReport(options, report)
|
||||
for (const line of formatArchivePublishReport(report)) console.log(line)
|
||||
console.log(`\n[archive:publish] recibo JSON: ${reportPath}`)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
if (queue.length === 0) {
|
||||
console.log('[archive:publish] nada a fazer — nenhuma foto draft elegível.')
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const results = []
|
||||
for (let index = 0; index < queue.length; index += 1) {
|
||||
const photo = queue[index]
|
||||
try {
|
||||
await payload.update({
|
||||
collection: 'archivePhoto',
|
||||
id: photo.id,
|
||||
data: { publicationStatus: 'approved' },
|
||||
depth: 0,
|
||||
// Intentional bypass: same trusted operator.
|
||||
overrideAccess: true,
|
||||
})
|
||||
results.push({ photoId: photo.id, status: 'approved' })
|
||||
} catch (error) {
|
||||
results.push({
|
||||
photoId: photo.id,
|
||||
status: 'failed',
|
||||
error: error?.message ?? String(error),
|
||||
})
|
||||
}
|
||||
|
||||
if ((index + 1) % PAGE_SIZE === 0) {
|
||||
console.log(`[archive:publish] … ${index + 1}/${queue.length}`)
|
||||
}
|
||||
}
|
||||
|
||||
const summary = summarizeArchivePublishResults(results)
|
||||
const report = {
|
||||
runAt,
|
||||
mode,
|
||||
target: databaseTarget(),
|
||||
queue: { totalDrafts: drafts.docs.length, items: queue.length },
|
||||
summary,
|
||||
durationMs: Date.now() - startedAt,
|
||||
}
|
||||
const reportPath = await writeReport(options, report)
|
||||
for (const line of formatArchivePublishReport(report)) console.log(line)
|
||||
console.log(
|
||||
'\n[archive:publish] lembre de bustar a tag pública (processo Next): curl -X POST "https://jorgesolla1313.com.br/api/revalidate?tag=archivePhotos" -H "x-revalidate-secret: $REVALIDATE_SECRET"',
|
||||
)
|
||||
console.log(`[archive:publish] recibo JSON: ${reportPath}`)
|
||||
|
||||
if (summary.approved === 0 && results.length > 0) {
|
||||
die('nenhuma foto foi aprovada — falhas listadas no recibo.')
|
||||
}
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
die(error?.message || String(error))
|
||||
})
|
||||
159
scripts/seed-face-consents.mjs
Normal file
159
scripts/seed-face-consents.mjs
Normal file
|
|
@ -0,0 +1,159 @@
|
|||
/**
|
||||
* C242 — provisions the two Consent texts of the selfie search by their stable
|
||||
* keys (`busca-selfie-fotos` query consent, `busca-selfie-indice` public index
|
||||
* notice). Idempotent: creates the row when missing, updates the text when the
|
||||
* repo text changed (Payload versions the consent).
|
||||
*
|
||||
* Modes:
|
||||
* pnpm seed:face-consents plan/dry-run (default) — shows the state; no write
|
||||
* pnpm seed:face-consents --apply upserts the texts; requires
|
||||
* FACE_CONSENT_SEED_CONFIRM=1 outside local dev
|
||||
* and the declared TEQO_ENV matching the
|
||||
* exact database
|
||||
*
|
||||
* The texts are versioned in `scripts/lib/faceConsentTexts.mjs` — the delivery
|
||||
* that opens the surface owns what the visitor reads.
|
||||
*/
|
||||
import { getPayload } from 'payload'
|
||||
|
||||
import { FACE_INDEX_CONSENT_KEY, FACE_SEARCH_CONSENT_KEY } from '../src/lib/campaignConsentKeys.ts'
|
||||
|
||||
import {
|
||||
TEQO_ENV_DATABASE_BY_ENV,
|
||||
assertEnvironmentDatabaseTarget,
|
||||
assertWriteConfirm,
|
||||
databaseTarget,
|
||||
dieWithLabel,
|
||||
loadCliEnv,
|
||||
} from './lib/cli.mjs'
|
||||
import {
|
||||
FACE_INDEX_CONSENT_PARAGRAPHS,
|
||||
FACE_INDEX_CONSENT_TEXT,
|
||||
FACE_SEARCH_CONSENT_PARAGRAPHS,
|
||||
FACE_SEARCH_CONSENT_TEXT,
|
||||
} from './lib/faceConsentTexts.mjs'
|
||||
|
||||
loadCliEnv()
|
||||
|
||||
const die = dieWithLabel('seed:face-consents')
|
||||
const WRITE_CONFIRM_FLAG = 'FACE_CONSENT_SEED_CONFIRM'
|
||||
|
||||
const envLines = Object.entries(TEQO_ENV_DATABASE_BY_ENV)
|
||||
.map(([environment, database]) => `${environment} (${database})`)
|
||||
.join(' | ')
|
||||
|
||||
const HELP = `
|
||||
Uso: pnpm seed:face-consents [opções]
|
||||
|
||||
Cria/atualiza os dois Consentimentos da busca por selfie:
|
||||
${FACE_SEARCH_CONSENT_KEY} consentimento da consulta (selfie + biometria)
|
||||
${FACE_INDEX_CONSENT_KEY} aviso público do índice anônimo do acervo
|
||||
|
||||
Modos:
|
||||
(sem flag) plano/dry-run — estado atual e prévia dos textos; sem escrita
|
||||
--apply grava os textos (exige ${WRITE_CONFIRM_FLAG}=1 fora do dev local)
|
||||
|
||||
Ambiente:
|
||||
DATABASE_URL alvo (obrigatório em todos os modos)
|
||||
|
||||
--apply em alvo não-local/produção exige ${WRITE_CONFIRM_FLAG}=1 e TEQO_ENV=${envLines}
|
||||
casando o banco exato. O plano é read-only.
|
||||
`
|
||||
|
||||
const upsertConsent = async (payload, key, text) => {
|
||||
const existing = await payload.find({
|
||||
collection: 'consent',
|
||||
where: { key: { equals: key } },
|
||||
depth: 0,
|
||||
limit: 1,
|
||||
overrideAccess: true,
|
||||
})
|
||||
const found = existing.docs[0]
|
||||
if (found) {
|
||||
await payload.update({
|
||||
collection: 'consent',
|
||||
id: found.id,
|
||||
data: { text },
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
})
|
||||
return { id: found.id, action: 'updated' }
|
||||
}
|
||||
|
||||
const created = await payload.create({
|
||||
collection: 'consent',
|
||||
data: { key, text },
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
})
|
||||
return { id: created.id, action: 'created' }
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const argv = process.argv.slice(2)
|
||||
if (argv.includes('--help') || argv.includes('-h')) {
|
||||
console.log(HELP)
|
||||
process.exit(0)
|
||||
}
|
||||
const unknown = argv.find((arg) => arg !== '--apply')
|
||||
if (unknown) die(`argumento desconhecido: ${unknown} — uso: pnpm seed:face-consents [--apply].`)
|
||||
|
||||
const apply = argv.includes('--apply')
|
||||
if (!process.env.DATABASE_URL) die('DATABASE_URL não definida; recusando continuar.')
|
||||
|
||||
console.log(`[seed:face-consents] alvo: ${databaseTarget()} | modo: ${apply ? 'apply' : 'plan'}`)
|
||||
|
||||
if (apply) {
|
||||
assertWriteConfirm({
|
||||
label: 'seed:face-consents',
|
||||
flag: WRITE_CONFIRM_FLAG,
|
||||
command: 'pnpm seed:face-consents --apply',
|
||||
})
|
||||
assertEnvironmentDatabaseTarget()
|
||||
}
|
||||
|
||||
const config = (await import('../src/payload.config.ts')).default
|
||||
const payload = await getPayload({ config })
|
||||
|
||||
const entries = [
|
||||
{
|
||||
key: FACE_SEARCH_CONSENT_KEY,
|
||||
text: FACE_SEARCH_CONSENT_TEXT,
|
||||
paragraphs: FACE_SEARCH_CONSENT_PARAGRAPHS,
|
||||
},
|
||||
{
|
||||
key: FACE_INDEX_CONSENT_KEY,
|
||||
text: FACE_INDEX_CONSENT_TEXT,
|
||||
paragraphs: FACE_INDEX_CONSENT_PARAGRAPHS,
|
||||
},
|
||||
]
|
||||
|
||||
for (const entry of entries) {
|
||||
const existing = await payload.find({
|
||||
collection: 'consent',
|
||||
where: { key: { equals: entry.key } },
|
||||
depth: 0,
|
||||
limit: 1,
|
||||
overrideAccess: true,
|
||||
})
|
||||
const state = existing.docs[0] ? `existe (#${existing.docs[0].id})` : 'ausente'
|
||||
console.log(
|
||||
`[seed:face-consents] ${entry.key}: ${state} | texto com ${entry.paragraphs.length} parágrafo(s)`,
|
||||
)
|
||||
|
||||
if (!apply) continue
|
||||
const result = await upsertConsent(payload, entry.key, entry.text)
|
||||
console.log(`[seed:face-consents] ${entry.key}: ${result.action} (#${result.id})`)
|
||||
}
|
||||
|
||||
if (!apply) {
|
||||
console.log('\n[seed:face-consents] dry-run — use --apply para gravar.')
|
||||
process.exit(0)
|
||||
}
|
||||
console.log('\n[seed:face-consents] OK — Consentimentos da busca por selfie provisionados.')
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
die(error?.message || String(error))
|
||||
})
|
||||
|
|
@ -6,11 +6,16 @@ import { CampaignHero } from '@/components/CampaignHero'
|
|||
import { CampaignProblemCard } from '@/components/CampaignProblemCard'
|
||||
import { CampaignStorySection } from '@/components/CampaignStorySection'
|
||||
import { ContentPieceHomeSection } from '@/components/conteudos/ContentPieceHomeSection'
|
||||
import { SelfieSearchHomeSection } from '@/components/fotos/SelfieSearchHomeSection'
|
||||
import { JingleHomeSection } from '@/components/jingles/JingleHomeSection'
|
||||
import { ShareLinkHomeSection } from '@/components/shareLink/ShareLinkHomeSection'
|
||||
import { SHARE_LINK_HOME_SECTION_SLUG } from '@/lib/shareLinkHomeSection'
|
||||
import { hasPublishedArchivePhotos } from '@/utilities/archivePhotos/archivePhotoReads'
|
||||
import { getCampaignHomeMetaPixelId } from '@/utilities/campaignHomeTracking'
|
||||
import { getPublishedContentPieceItems } from '@/utilities/content/contentPieceReads'
|
||||
import { getCachedGlobal } from '@/utilities/globalReads'
|
||||
import { getPublishedJingleItems } from '@/utilities/jingleReads'
|
||||
import { loadShareLinkHomeSection } from '@/utilities/shareLinkReads'
|
||||
import type { ReactNode } from 'react'
|
||||
import { CampaignCardsSection } from './CampaignCardsSection'
|
||||
import { CampaignNewsletterSection } from './CampaignNewsletterSection'
|
||||
|
|
@ -123,19 +128,32 @@ export default async function HomePage() {
|
|||
// S27/S39 — one cached listing (tag `contentPieces`) feeds both the discovery
|
||||
// flag of the footer and the home sample; zero pieces hides both (fail-closed).
|
||||
// C233 — the same contract for the "Fotos" discovery flag (tag `archivePhotos`).
|
||||
const [pixelId, jingles, contentPieces, showFotos] = await Promise.all([
|
||||
// S44 — the Plenária section reads one published share link under the
|
||||
// `shareLinks` tag; unpublished or past the event window, the section is
|
||||
// absent from the HTML (fail-closed, kill switch without a deploy).
|
||||
const [pixelId, jingles, contentPieces, showFotos, album, plenaria] = await Promise.all([
|
||||
getCampaignHomeMetaPixelId(),
|
||||
getPublishedJingleItems(),
|
||||
getPublishedContentPieceItems(),
|
||||
hasPublishedArchivePhotos(),
|
||||
getCachedGlobal('photoAlbum')(),
|
||||
loadShareLinkHomeSection(SHARE_LINK_HOME_SECTION_SLUG),
|
||||
])
|
||||
const homeJingles = jingles.slice(0, 3)
|
||||
// C243 — the discovery section only exists while the selfie search is open
|
||||
// (album published + own flag + approved photos); closed leaves no dead CTA.
|
||||
const showSelfieSearch =
|
||||
album.published !== false && album.selfieSearchEnabled === true && showFotos
|
||||
|
||||
return (
|
||||
<>
|
||||
<main className="w-full bg-white text-black">
|
||||
<CampaignHero />
|
||||
|
||||
{plenaria ? (
|
||||
<ShareLinkHomeSection view={plenaria.view} initialLive={plenaria.initialLive} />
|
||||
) : null}
|
||||
|
||||
<section
|
||||
aria-label="Experiência e atuação parlamentar"
|
||||
data-home-section="proof"
|
||||
|
|
@ -255,6 +273,7 @@ export default async function HomePage() {
|
|||
<JingleHomeSection jingles={homeJingles} showAll={jingles.length > homeJingles.length} />
|
||||
<CampaignCardsSection />
|
||||
{contentPieces.length > 0 ? <ContentPieceHomeSection items={contentPieces} /> : null}
|
||||
{showSelfieSearch ? <SelfieSearchHomeSection /> : null}
|
||||
<CampaignNewsletterSection pixelId={pixelId ?? undefined} />
|
||||
</main>
|
||||
|
||||
|
|
|
|||
|
|
@ -3,12 +3,7 @@ import { NextResponse } from 'next/server'
|
|||
import { getPayload } from 'payload'
|
||||
|
||||
import { FACE_INDEX_CONSENT_KEY, FACE_SEARCH_CONSENT_KEY } from '@/lib/campaignConsentKeys'
|
||||
import {
|
||||
FACE_SEARCH_MODEL,
|
||||
FACE_SEARCH_RESULT_LIMIT,
|
||||
findFaceMatch,
|
||||
toFaceSearchPhotoView,
|
||||
} from '@/lib/faceSearch'
|
||||
import { FACE_SEARCH_RESULT_LIMIT, toFaceSearchPhotoView } from '@/lib/faceSearch'
|
||||
import { faceSearchRequestSchema } from '@/lib/schemas/faceSearch'
|
||||
import { getApprovedArchivePhotoItems } from '@/utilities/archivePhotos/archivePhotoReads'
|
||||
import { readBoundedRequestBody } from '@/utilities/boundedRequestBody'
|
||||
|
|
@ -17,28 +12,31 @@ import {
|
|||
checkContentEventRateLimit,
|
||||
contentEventClientKey,
|
||||
} from '@/utilities/content/contentEventRateLimit'
|
||||
import { removeFaceSubjectFromIndex } from '@/utilities/faceSubjects/faceSubjectEnrollment'
|
||||
import {
|
||||
getFaceSubjectMatchedPhotoIds,
|
||||
listSearchableFaceSubjects,
|
||||
} from '@/utilities/faceSubjects/faceSubjectReads'
|
||||
deleteFaceDescriptorMatches,
|
||||
findMatchedFacePhotoIds,
|
||||
loadFaceDescriptorIndex,
|
||||
} from '@/utilities/faceIndex/faceDescriptorReads'
|
||||
import { isSameOriginRequest } from '@/utilities/sameOriginRequest'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
/**
|
||||
* C234 — the anonymous endpoint of the selfie search. The browser computes the
|
||||
* face descriptor ON DEVICE (the selfie image never reaches this server) and
|
||||
* sends only the 128-float vector plus the intent; the answer is a list of
|
||||
* approved photos, never a score and never a third-party name.
|
||||
* C242 — the anonymous endpoint of the selfie search (scope B: the anonymous
|
||||
* descriptor index of the approved archive, decision of 2026-10-01). The
|
||||
* browser computes the face descriptor ON DEVICE (the selfie image never
|
||||
* reaches this server) and sends only the 128-float vector plus the intent; the
|
||||
* answer is a list of approved photos, never a score and never a third-party
|
||||
* name.
|
||||
*
|
||||
* Fail-closed in layers: same-origin, bounded body, strict schema, a budget
|
||||
* much stricter than the beacon's (the endpoint answers a membership oracle),
|
||||
* the album's `selfieSearchEnabled` kill switch AND the query Consent resolved
|
||||
* server-side — the page closing is convenience, this is the gate. Scope A/C
|
||||
* of the gate (PR #1370): only subjects enrolled with consent answer; the
|
||||
* anonymous archive index (B) does not exist. `leave-index` is authorized by
|
||||
* the matched descriptor itself.
|
||||
* the album's `selfieSearchEnabled` kill switch AND both configured Consents
|
||||
* resolved server-side — the query consent (`busca-selfie-fotos`, accepted by
|
||||
* the visitor) and the public index notice (`busca-selfie-indice`, the
|
||||
* transparency document of the anonymous index). `leave-index` is authorized
|
||||
* by the matched descriptor itself and erases the person's faces from the
|
||||
* index.
|
||||
*/
|
||||
|
||||
const NO_STORE = { 'Cache-Control': 'no-store' } as const
|
||||
|
|
@ -79,45 +77,33 @@ export const POST = async (request: Request): Promise<NextResponse> => {
|
|||
}
|
||||
|
||||
const payload = await getPayload({ config })
|
||||
// Direct read (no cache): the kill switch and the consent must be the state
|
||||
// Direct read (no cache): the kill switch and the consents must be the state
|
||||
// of this moment — the endpoint is the gate, the page is convenience. The
|
||||
// album global's read access is public by contract, so no bypass is needed.
|
||||
const [album, searchConsent] = await Promise.all([
|
||||
const [album, searchConsent, indexNotice] = await Promise.all([
|
||||
payload.findGlobal({ slug: 'photoAlbum', depth: 0 }).catch(() => null),
|
||||
getConsentByKey(payload, FACE_SEARCH_CONSENT_KEY),
|
||||
getConsentByKey(payload, FACE_INDEX_CONSENT_KEY),
|
||||
])
|
||||
|
||||
if (album?.published === false || album?.selfieSearchEnabled !== true) {
|
||||
return jsonResponse({ ok: false, error: 'closed' }, 404)
|
||||
}
|
||||
if (!searchConsent) return jsonResponse({ ok: false, error: 'consent' }, 503)
|
||||
|
||||
const [subjects, indexConsent] = await Promise.all([
|
||||
listSearchableFaceSubjects(payload),
|
||||
getConsentByKey(payload, FACE_INDEX_CONSENT_KEY),
|
||||
])
|
||||
|
||||
const match = indexConsent
|
||||
? findFaceMatch({
|
||||
vector: parsed.data.vector,
|
||||
subjects,
|
||||
model: FACE_SEARCH_MODEL,
|
||||
consentHash: indexConsent.contentHash,
|
||||
})
|
||||
: null
|
||||
if (!searchConsent || !indexNotice) return jsonResponse({ ok: false, error: 'consent' }, 503)
|
||||
|
||||
if (parsed.data.intent === 'leave-index') {
|
||||
if (!match) return jsonResponse({ ok: true, removed: false })
|
||||
await removeFaceSubjectFromIndex({ payload, id: match.id })
|
||||
return jsonResponse({ ok: true, removed: true })
|
||||
const removedFaces = await deleteFaceDescriptorMatches({
|
||||
payload,
|
||||
vector: parsed.data.vector,
|
||||
})
|
||||
return jsonResponse({ ok: true, removed: removedFaces > 0 })
|
||||
}
|
||||
|
||||
if (!match) return jsonResponse({ ok: true, found: false })
|
||||
const index = await loadFaceDescriptorIndex(payload)
|
||||
const matchedIds = findMatchedFacePhotoIds({ vector: parsed.data.vector, entries: index })
|
||||
if (matchedIds.length === 0) return jsonResponse({ ok: true, found: false })
|
||||
|
||||
const [matchedIds, approved] = await Promise.all([
|
||||
getFaceSubjectMatchedPhotoIds(payload, match.id),
|
||||
getApprovedArchivePhotoItems(),
|
||||
])
|
||||
const approved = await getApprovedArchivePhotoItems()
|
||||
const linked = new Set(matchedIds)
|
||||
const photos = approved
|
||||
.filter((item) => linked.has(item.id))
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ import {
|
|||
ARCHIVE_PHOTO_ALBUM_ENTRY_PATH,
|
||||
ARCHIVE_PHOTO_ALBUM_PATH,
|
||||
} from '@/lib/archivePhotoPublicCatalog'
|
||||
import { FACE_SEARCH_CONSENT_KEY } from '@/lib/campaignConsentKeys'
|
||||
import { FACE_INDEX_CONSENT_KEY, FACE_SEARCH_CONSENT_KEY } from '@/lib/campaignConsentKeys'
|
||||
import { getConsentByKey } from '@/utilities/campaignConsent'
|
||||
import { hasPublishedContentPieces } from '@/utilities/content/contentPieceReads'
|
||||
import { getCachedGlobal } from '@/utilities/globalReads'
|
||||
|
|
@ -79,7 +79,10 @@ export default async function FotosEncontrePage() {
|
|||
if (album.published === false || album.selfieSearchEnabled !== true) notFound()
|
||||
|
||||
const payload = await getPayload({ config })
|
||||
const consent = await getConsentByKey(payload, FACE_SEARCH_CONSENT_KEY)
|
||||
const [consent, indexNotice] = await Promise.all([
|
||||
getConsentByKey(payload, FACE_SEARCH_CONSENT_KEY),
|
||||
getConsentByKey(payload, FACE_INDEX_CONSENT_KEY),
|
||||
])
|
||||
const removalChannelUrl = isArchivePhotoRemovalChannelUrl(album.removalChannelUrl)
|
||||
? album.removalChannelUrl.trim()
|
||||
: null
|
||||
|
|
@ -98,9 +101,10 @@ export default async function FotosEncontrePage() {
|
|||
</Link>
|
||||
</nav>
|
||||
</div>
|
||||
{consent ? (
|
||||
{consent && indexNotice ? (
|
||||
<SelfieSearchFlow
|
||||
consentText={<ConsentText data={consent.text} />}
|
||||
noticeText={<ConsentText data={indexNotice.text} />}
|
||||
removalChannelUrl={removalChannelUrl}
|
||||
/>
|
||||
) : (
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ import {
|
|||
import { SPEECH_TOPICS } from '@/lib/speechFacets'
|
||||
import { canReadArchivePhoto, payloadAdminOnly } from '@/utilities/campaignAccess'
|
||||
import { revalidateArchivePhotosListing } from '@/utilities/documents'
|
||||
import { purgeFaceDescriptorsForPhoto } from '@/utilities/faceIndex/faceDescriptorIndex'
|
||||
|
||||
/**
|
||||
* C231 — private upload collection of the Flickr photo archive: the ORIGINAL
|
||||
|
|
@ -282,6 +283,24 @@ const revalidateArchivePhotosListingAfterDelete: CollectionAfterDeleteHook = ({
|
|||
return doc
|
||||
}
|
||||
|
||||
/**
|
||||
* C242 — a photo that stops being `approved` cannot keep answering the selfie
|
||||
* search: the anonymous descriptor rows die with the public status (and on
|
||||
* deletion), the same fail-closed spirit of the C233 read. The FK cascade
|
||||
* covers direct SQL deletes; this covers the Local API lifecycle.
|
||||
*/
|
||||
const purgeFaceDescriptorsAfterChange: CollectionAfterChangeHook = async ({ doc, req }) => {
|
||||
if (doc.publicationStatus !== 'approved') {
|
||||
await purgeFaceDescriptorsForPhoto({ payload: req.payload, photoId: doc.id, req })
|
||||
}
|
||||
return doc
|
||||
}
|
||||
|
||||
const purgeFaceDescriptorsAfterDelete: CollectionAfterDeleteHook = async ({ doc, req }) => {
|
||||
await purgeFaceDescriptorsForPhoto({ payload: req.payload, photoId: doc.id, req })
|
||||
return doc
|
||||
}
|
||||
|
||||
/**
|
||||
* C234 — the batch state of the selfie-search index (`pnpm faces:index`). The
|
||||
* `checkedKey` is what lets the batch skip a photo honestly: it summarizes the
|
||||
|
|
@ -346,8 +365,8 @@ export const ArchivePhoto: CollectionConfig = {
|
|||
},
|
||||
hooks: {
|
||||
beforeValidate: [deriveArchivePhotoCatalogIndex, requireRemovalChannelForApproval],
|
||||
afterChange: [revalidateArchivePhotosListingAfterChange],
|
||||
afterDelete: [revalidateArchivePhotosListingAfterDelete],
|
||||
afterChange: [revalidateArchivePhotosListingAfterChange, purgeFaceDescriptorsAfterChange],
|
||||
afterDelete: [revalidateArchivePhotosListingAfterDelete, purgeFaceDescriptorsAfterDelete],
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
|
|
|
|||
79
src/collections/ArchivePhotoFace.ts
Normal file
79
src/collections/ArchivePhotoFace.ts
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
import type { CollectionConfig } from 'payload'
|
||||
|
||||
import { payloadAdminOnly } from '@/utilities/campaignAccess'
|
||||
|
||||
/**
|
||||
* C242 — one detected face of an APPROVED archive photo: the anonymous index
|
||||
* that lets any visitor find themselves (scope B of the gate, decision of
|
||||
* 2026-10-01; supersedes the A/C `faceSubject` enrollment). The row carries no
|
||||
* identity, no link to `Contact`/leadership and no name — only the photo it was
|
||||
* found in, the 128-float descriptor and the model that produced it.
|
||||
*
|
||||
* Machine-only data: no admin surface (`admin.hidden`), admin-only access, and
|
||||
* the descriptor never leaves the server. Written exclusively by the
|
||||
* `pnpm faces:index` batch (trusted operator, `overrideAccess`), deleted by the
|
||||
* opt-out (`leave-index` matches the person's own descriptor) and by the photo
|
||||
* lifecycle hooks on unapproval/deletion. A photo that is not `approved` must
|
||||
* never have rows here.
|
||||
*/
|
||||
export const ArchivePhotoFace: CollectionConfig = {
|
||||
slug: 'archivePhotoFace',
|
||||
labels: {
|
||||
singular: 'Rosto no índice',
|
||||
plural: 'Rostos no índice',
|
||||
},
|
||||
admin: {
|
||||
group: 'Comunicação',
|
||||
hidden: true,
|
||||
description:
|
||||
'Índice facial anônimo do acervo público aprovado (C242). Operado pela CLI faces:index; o descriptor nunca é exposto.',
|
||||
},
|
||||
access: {
|
||||
create: payloadAdminOnly,
|
||||
read: payloadAdminOnly,
|
||||
update: payloadAdminOnly,
|
||||
delete: payloadAdminOnly,
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: 'photo',
|
||||
type: 'relationship',
|
||||
relationTo: 'archivePhoto',
|
||||
label: 'Foto',
|
||||
required: true,
|
||||
index: true,
|
||||
admin: {
|
||||
description: 'Foto aprovada em que o rosto foi detectado.',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'model',
|
||||
type: 'text',
|
||||
label: 'Modelo',
|
||||
required: true,
|
||||
index: true,
|
||||
admin: {
|
||||
readOnly: true,
|
||||
description:
|
||||
'Modelo do descriptor (troca de modelo invalida a revisão e o lote reprocessa).',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'detectedAt',
|
||||
type: 'date',
|
||||
label: 'Detectado em',
|
||||
admin: {
|
||||
readOnly: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'vector',
|
||||
type: 'json',
|
||||
label: 'Descriptor',
|
||||
admin: {
|
||||
hidden: true,
|
||||
readOnly: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
|
|
@ -22,7 +22,6 @@ const blockConsentDeletionWithReferences: CollectionBeforeDeleteHook = async ({
|
|||
leaderships,
|
||||
supporters,
|
||||
voteSupporters,
|
||||
faceSubjects,
|
||||
] = await Promise.all([
|
||||
req.payload.count({
|
||||
collection: 'subscription',
|
||||
|
|
@ -66,14 +65,6 @@ const blockConsentDeletionWithReferences: CollectionBeforeDeleteHook = async ({
|
|||
overrideAccess: true,
|
||||
req,
|
||||
}),
|
||||
// C234 — face-subject references: intentional access bypass like every
|
||||
// count above (the hook must see every reference to decide).
|
||||
req.payload.count({
|
||||
collection: 'faceSubject',
|
||||
where: { consent: { equals: id } },
|
||||
overrideAccess: true,
|
||||
req,
|
||||
}),
|
||||
])
|
||||
|
||||
const references: Array<[number, string]> = [
|
||||
|
|
@ -84,7 +75,6 @@ const blockConsentDeletionWithReferences: CollectionBeforeDeleteHook = async ({
|
|||
[leaderships.totalDocs, 'lideranças'],
|
||||
[supporters.totalDocs, 'apoiadores'],
|
||||
[voteSupporters.totalDocs, 'apoiadores (intenção de voto)'],
|
||||
[faceSubjects.totalDocs, 'pessoas no índice de busca por selfie'],
|
||||
]
|
||||
const used = references.filter(([count]) => count > 0)
|
||||
if (used.length === 0) return
|
||||
|
|
|
|||
|
|
@ -1,135 +0,0 @@
|
|||
import type { CollectionConfig } from 'payload'
|
||||
|
||||
import { payloadAdminOnly } from '@/utilities/campaignAccess'
|
||||
|
||||
/**
|
||||
* C234 — one person who ADHERED to the selfie search index (A/C scope of the
|
||||
* gate, PR #1370): the enrollment is an ops act of the assessoria with the
|
||||
* person (signed consent, `pnpm faces:enroll`), never self-service and never
|
||||
* inferred from the archive.
|
||||
*
|
||||
* This is not a people registry: it has no link to `Contact`/leadership, no
|
||||
* public read and no surface of its own — it exists to (a) hold the consented
|
||||
* descriptor that lets the person find themselves and (b) carry the audit
|
||||
* trail of the adherence (`consent` + `consentHash` + `model` + status). The
|
||||
* descriptor is written only by the CLI and never leaves the server; the
|
||||
* matched photos are a derived link the batch replaces on every run. A
|
||||
* `removed` subject keeps its row (the attendance record) but not the vector.
|
||||
*/
|
||||
export const FaceSubject: CollectionConfig = {
|
||||
slug: 'faceSubject',
|
||||
labels: {
|
||||
singular: 'Pessoa no índice facial',
|
||||
plural: 'Pessoas no índice facial',
|
||||
},
|
||||
admin: {
|
||||
group: 'Comunicação',
|
||||
description:
|
||||
'Pessoas que consentiram entrar no índice da busca por selfie (/fotos/encontre). Operado pela CLI faces:enroll/faces:index; a remoção é registrada no status.',
|
||||
useAsTitle: 'label',
|
||||
defaultColumns: ['label', 'status', 'model', 'removedAt'],
|
||||
},
|
||||
access: {
|
||||
create: payloadAdminOnly,
|
||||
read: payloadAdminOnly,
|
||||
update: payloadAdminOnly,
|
||||
delete: payloadAdminOnly,
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: 'label',
|
||||
type: 'text',
|
||||
label: 'Nome (interno)',
|
||||
required: true,
|
||||
admin: {
|
||||
description: 'Como a assessoria identifica a pessoa; nunca aparece no site.',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'consent',
|
||||
type: 'relationship',
|
||||
relationTo: 'consent',
|
||||
label: 'Consentimento (adesão)',
|
||||
required: true,
|
||||
index: true,
|
||||
admin: {
|
||||
description: 'O Consent da adesão ao índice (chave estável busca-selfie-indice).',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'consentHash',
|
||||
type: 'text',
|
||||
label: 'Hash do consentimento',
|
||||
admin: {
|
||||
readOnly: true,
|
||||
description:
|
||||
'Snapshot do texto aceito no enrollment; se o texto mudar, a pessoa fica inelegível até re-consentir.',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'model',
|
||||
type: 'text',
|
||||
label: 'Modelo',
|
||||
admin: {
|
||||
readOnly: true,
|
||||
description: 'Modelo do descriptor (troca de modelo invalida o índice: re-enrollment).',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'enrolledAt',
|
||||
type: 'date',
|
||||
label: 'Inscrita em',
|
||||
admin: {
|
||||
readOnly: true,
|
||||
description:
|
||||
'Muda a cada enrollment/re-enrollment; é o que marca o lote como stale (o updated_at muda também quando o lote escreve os vínculos).',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'vector',
|
||||
type: 'json',
|
||||
label: 'Descriptor',
|
||||
admin: {
|
||||
hidden: true,
|
||||
readOnly: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'status',
|
||||
type: 'select',
|
||||
label: 'Status',
|
||||
required: true,
|
||||
index: true,
|
||||
defaultValue: 'active',
|
||||
options: [
|
||||
{ label: 'Ativa', value: 'active' },
|
||||
{ label: 'Removida do índice', value: 'removed' },
|
||||
],
|
||||
admin: {
|
||||
description:
|
||||
'Removida: pedido de saída atendido — o vetor é apagado e a pessoa deixa de ser encontrada.',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'removedAt',
|
||||
type: 'date',
|
||||
label: 'Removida em',
|
||||
admin: {
|
||||
readOnly: true,
|
||||
description: 'Data do atendimento da saída do índice.',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'matchedPhotos',
|
||||
type: 'relationship',
|
||||
relationTo: 'archivePhoto',
|
||||
hasMany: true,
|
||||
label: 'Fotos vinculadas',
|
||||
admin: {
|
||||
readOnly: true,
|
||||
description:
|
||||
'Derivado do lote (pnpm faces:index): fotos aprovadas em que o descriptor foi encontrado.',
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
|
|
@ -24,11 +24,12 @@ export const SelfieSearchEntry = () => (
|
|||
</h2>
|
||||
<p className="mt-1 text-sm leading-6 text-(--campaign-muted)">
|
||||
<span className="sm:hidden">
|
||||
Sua selfie fica neste aparelho. A busca é para quem aderiu ao índice.
|
||||
Sua selfie fica neste aparelho. A busca cobre o acervo público aprovado, e você pode
|
||||
sair do índice.
|
||||
</span>
|
||||
<span className="hidden sm:inline">
|
||||
Use uma selfie sua. A imagem não sai deste dispositivo e a busca cobre quem autorizou
|
||||
participar do índice.
|
||||
Use uma selfie sua. A imagem não sai deste dispositivo. A busca cobre o acervo público
|
||||
aprovado, e você pode retirar seu rosto do índice.
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -72,9 +72,11 @@ const STEP_SHELL = 'mx-auto w-full max-w-[650px]'
|
|||
*/
|
||||
export const SelfieSearchFlow = ({
|
||||
consentText,
|
||||
noticeText,
|
||||
removalChannelUrl,
|
||||
}: {
|
||||
consentText: ReactNode
|
||||
noticeText: ReactNode
|
||||
removalChannelUrl: string | null
|
||||
}) => {
|
||||
const [step, setStep] = useState<FlowStep>({ kind: 'consent' })
|
||||
|
|
@ -234,8 +236,34 @@ export const SelfieSearchFlow = ({
|
|||
>
|
||||
Sua face é um dado biométrico sensível
|
||||
</h2>
|
||||
<div className="mt-3 max-h-72 overflow-y-auto rounded-xl border border-(--campaign-line) bg-(--campaign-cream) p-4 text-sm leading-6 text-(--campaign-muted)">
|
||||
{consentText}
|
||||
<div className="mt-3 text-sm leading-6 text-(--campaign-muted)">{consentText}</div>
|
||||
<div className="mt-4 rounded-xl border border-[#184e92]/20 bg-[#eef4fb] p-4 text-sm leading-6">
|
||||
<div className="flex items-start gap-3">
|
||||
<ShieldCheck
|
||||
aria-hidden="true"
|
||||
className="mt-0.5 size-[18px] shrink-0 text-[#184e92]"
|
||||
strokeWidth={2}
|
||||
/>
|
||||
<div>
|
||||
<b className="text-[#184e92]">Aviso público sobre o índice de fotos</b>
|
||||
<p className="mt-1 text-(--campaign-muted)">
|
||||
Rostos presentes nas fotos públicas aprovadas compõem um índice sem nomes e sem
|
||||
vínculo com cadastros de pessoas. Ele serve apenas para localizar as próprias
|
||||
fotos. Você pode retirar seu rosto do índice a qualquer momento em “Minha
|
||||
presença”.
|
||||
</p>
|
||||
<details className="mt-1">
|
||||
<summary
|
||||
className={`inline-flex min-h-11 cursor-pointer items-center text-sm font-extrabold text-[#184e92] underline underline-offset-4 ${ARCHIVE_PHOTO_FOCUS}`}
|
||||
>
|
||||
Ler o aviso completo do índice
|
||||
</summary>
|
||||
<div className="mt-2 max-h-60 overflow-y-auto rounded-lg border border-(--campaign-line) bg-white p-3 text-(--campaign-muted)">
|
||||
{noticeText}
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-5 grid gap-3 rounded-xl bg-[#f9faff] p-4 text-sm">
|
||||
<div className="flex gap-3">
|
||||
|
|
@ -251,10 +279,11 @@ export const SelfieSearchFlow = ({
|
|||
<div className="flex gap-3">
|
||||
<ShieldCheck aria-hidden="true" className="mt-0.5 size-4 shrink-0 text-[#184e92]" />
|
||||
<p>
|
||||
<b>Você pode desistir e pedir remoção.</b>
|
||||
<b>Você mantém o controle.</b>
|
||||
<br />
|
||||
<span className="text-(--campaign-muted)">
|
||||
O resultado não mostra nomes de terceiros nem percentual de semelhança.
|
||||
Saia do índice quando quiser. O resultado não mostra nomes de terceiros nem
|
||||
percentual de semelhança.
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
|
|
@ -267,8 +296,8 @@ export const SelfieSearchFlow = ({
|
|||
className="mt-0.5 size-5 shrink-0 accent-[#184e92]"
|
||||
/>
|
||||
<span>
|
||||
Li e autorizo o uso temporário da minha biometria facial para procurar a mim mesmo
|
||||
neste álbum.
|
||||
Li o aviso e autorizo o uso da minha selfie e da minha biometria somente nesta
|
||||
consulta para procurar a mim mesmo no álbum.
|
||||
</span>
|
||||
</label>
|
||||
<p className="mt-3 text-xs leading-5 text-(--campaign-muted)">
|
||||
|
|
@ -456,7 +485,7 @@ export const SelfieSearchFlow = ({
|
|||
<FlowStateCard
|
||||
icon={<ImageIcon aria-hidden="true" className="size-7" strokeWidth={2} />}
|
||||
title="Não encontramos fotos suas"
|
||||
body="Esta busca funciona para quem autorizou participar do índice. Também pode não haver uma foto sua entre os registros públicos aprovados."
|
||||
body="Pode não haver uma foto sua entre os registros públicos aprovados, ou seu rosto pode já ter sido retirado do índice."
|
||||
note="Não mostramos pessoas parecidas nem tentamos adivinhar quem você é."
|
||||
action={
|
||||
<button
|
||||
|
|
@ -513,24 +542,28 @@ export const SelfieSearchFlow = ({
|
|||
id="selfie-presence-title"
|
||||
className="mt-1 border-0 pb-0 font-[family-name:var(--font-exo2)] text-2xl font-black"
|
||||
>
|
||||
Você decide se quer aparecer
|
||||
Você controla sua presença no índice
|
||||
</h2>
|
||||
<p className="mt-2 text-sm leading-6 text-(--campaign-muted)">
|
||||
Para sair do índice, confirme sua identidade com uma selfie. Para retirar uma foto
|
||||
pública, use o canal da equipe responsável pelo acervo.
|
||||
Seu rosto pode fazer parte do índice anônimo por aparecer no acervo aprovado. Para
|
||||
retirá-lo, use uma selfie sua. Para retirar uma foto pública, fale com a equipe do
|
||||
acervo.
|
||||
</p>
|
||||
<div className="mt-5 flex gap-3 rounded-xl border-2 border-[#184e92] bg-[#f9faff] p-4">
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="mt-0.5 size-5 shrink-0 rounded-full border-[5px] border-[#184e92]"
|
||||
<label className="mt-5 flex cursor-pointer gap-3 rounded-xl border-2 border-[#184e92] bg-[#f9faff] p-4">
|
||||
<input
|
||||
type="radio"
|
||||
name="presence-action"
|
||||
value="leave-index"
|
||||
defaultChecked
|
||||
className="mt-0.5 size-5 shrink-0 accent-[#184e92]"
|
||||
/>
|
||||
<span>
|
||||
<b className="text-sm">Sair do índice de busca</b>
|
||||
<small className="mt-1 block text-xs leading-5 text-(--campaign-muted)">
|
||||
Seu rosto deixa de ser usado para localizar fotos por selfie.
|
||||
Apaga do índice as referências biométricas que correspondem ao seu rosto.
|
||||
</small>
|
||||
</span>
|
||||
</div>
|
||||
</label>
|
||||
{removalChannelUrl ? (
|
||||
<a
|
||||
href={removalChannelUrl}
|
||||
|
|
@ -565,9 +598,9 @@ export const SelfieSearchFlow = ({
|
|||
{step.kind === 'removed' ? (
|
||||
<FlowStateCard
|
||||
icon={<ShieldCheck aria-hidden="true" className="size-7" strokeWidth={2} />}
|
||||
title="Pronto — você saiu do índice"
|
||||
body="Seu rosto deixou de ser usado para localizar fotos por selfie e o vetor foi apagado."
|
||||
note="Se quiser voltar a participar, fale com a equipe responsável pelo acervo."
|
||||
title="Pronto — seu rosto saiu do índice"
|
||||
body="Apagamos as referências biométricas que correspondiam ao seu rosto. Ele deixa de ser encontrado pela busca por selfie."
|
||||
note="As fotos públicas continuam no álbum. Para retirar uma foto específica, use o canal da equipe responsável pelo acervo."
|
||||
action={
|
||||
<Link
|
||||
href={ARCHIVE_PHOTO_ALBUM_PATH}
|
||||
|
|
@ -576,6 +609,16 @@ export const SelfieSearchFlow = ({
|
|||
Voltar ao álbum
|
||||
</Link>
|
||||
}
|
||||
secondary={
|
||||
removalChannelUrl ? (
|
||||
<a
|
||||
href={removalChannelUrl}
|
||||
className={`mt-3 inline-flex min-h-11 items-center text-sm font-extrabold text-[#184e92] underline underline-offset-4 ${ARCHIVE_PHOTO_FOCUS}`}
|
||||
>
|
||||
Pedir remoção de uma foto
|
||||
</a>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
|
|
@ -583,7 +626,7 @@ export const SelfieSearchFlow = ({
|
|||
<FlowStateCard
|
||||
icon={<ShieldCheck aria-hidden="true" className="size-7" strokeWidth={2} />}
|
||||
title="Não encontramos sua presença no índice"
|
||||
body="Não foi possível reconhecer uma participação sua no índice com esta selfie. Nenhuma alteração foi feita."
|
||||
body="Não encontramos no índice referências biométricas que correspondam ao seu rosto com esta selfie. Nenhuma alteração foi feita."
|
||||
action={
|
||||
<button
|
||||
type="button"
|
||||
|
|
@ -594,7 +637,7 @@ export const SelfieSearchFlow = ({
|
|||
</button>
|
||||
}
|
||||
secondary={
|
||||
<>
|
||||
<div className="mt-6 w-full border-t border-(--campaign-line) pt-5">
|
||||
<p className="text-sm leading-6 text-(--campaign-muted)">
|
||||
Quer retirar uma foto pública mesmo assim?
|
||||
</p>
|
||||
|
|
@ -606,10 +649,13 @@ export const SelfieSearchFlow = ({
|
|||
Pedir remoção de uma foto
|
||||
</a>
|
||||
) : null}
|
||||
<Link href={ARCHIVE_PHOTO_ALBUM_PATH} className={`${STATE_LINK} mt-4`}>
|
||||
<Link
|
||||
href={ARCHIVE_PHOTO_ALBUM_PATH}
|
||||
className={`mt-4 inline-flex min-h-11 items-center text-sm font-bold text-(--campaign-muted) ${ARCHIVE_PHOTO_FOCUS}`}
|
||||
>
|
||||
Voltar ao álbum
|
||||
</Link>
|
||||
</>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
|
|
@ -862,8 +908,8 @@ const LeaveConfirmDialog = ({
|
|||
Confirmar saída do índice?
|
||||
</h2>
|
||||
<p className="mt-2 text-sm leading-6 text-(--campaign-muted)">
|
||||
Vamos reconhecer você neste aparelho e, se houver correspondência, retirar sua presença do
|
||||
índice de busca.
|
||||
Vamos processar sua selfie neste aparelho e, se houver correspondência, apagar do índice
|
||||
as referências biométricas do seu rosto. A selfie não será enviada.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
|
|
|
|||
153
src/components/fotos/SelfieSearchHomeSection.tsx
Normal file
153
src/components/fotos/SelfieSearchHomeSection.tsx
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
import { Check, ChevronRight, Images, ShieldCheck, Smartphone, Sparkles } from 'lucide-react'
|
||||
import Link from 'next/link'
|
||||
|
||||
import {
|
||||
ARCHIVE_PHOTO_ALBUM_ENTRY_PATH,
|
||||
ARCHIVE_PHOTO_ALBUM_PATH,
|
||||
} from '@/lib/archivePhotoPublicCatalog'
|
||||
|
||||
import { ARCHIVE_PHOTO_FOCUS, ARCHIVE_PHOTO_PRIMARY_BUTTON } from './archivePhotoClasses'
|
||||
|
||||
/** `.assurance-mark` of the artifact: azure surface with the yellow radial glow. */
|
||||
const ASSURANCE_SURFACE =
|
||||
'rounded-2xl border border-[#184e92]/15 bg-[radial-gradient(circle_at_76%_18%,rgb(255_230_7/66%)_0_8%,transparent_8.5%),linear-gradient(145deg,#f9faff_0%,#eef4fb_100%)]'
|
||||
|
||||
/**
|
||||
* C243 — the selfie-search section of the public campaign homepage (artefato:
|
||||
* `busca-selfie-secao-home-ui-design.html`, cenas 01/02). It only presents and
|
||||
* links: no selfie capture, no engine, no archive photos and no counters on the
|
||||
* home — the sensitive experience starts at `/fotos/encontre`. Rendered by the
|
||||
* homepage only while the search is open (album published + flag +
|
||||
* approved photos), so a closed search leaves no dead CTA.
|
||||
*/
|
||||
const ASSURANCE_ITEMS = [
|
||||
{ icon: Smartphone, label: 'Processamento no aparelho' },
|
||||
{ icon: Images, label: 'Só o acervo público aprovado' },
|
||||
{ icon: ShieldCheck, label: 'Saída do índice a qualquer momento' },
|
||||
] as const
|
||||
|
||||
export const SelfieSearchHomeSection = () => (
|
||||
<section
|
||||
aria-labelledby="selfie-home-title"
|
||||
data-home-section="selfie-search"
|
||||
className="relative overflow-hidden border-b border-(--campaign-line) bg-(--campaign-cream)"
|
||||
>
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="pointer-events-none absolute -top-14 -right-14 size-40 rounded-full bg-(--pt-yellow)/45 sm:-top-24 sm:-right-20 sm:size-64"
|
||||
/>
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="pointer-events-none absolute -bottom-32 left-[36%] hidden size-64 rounded-full bg-(--pt-red)/8 sm:block"
|
||||
/>
|
||||
|
||||
<div className="relative mx-auto grid w-full max-w-[1160px] grid-cols-1 items-center gap-8 px-5 py-12 sm:px-10 sm:py-16 lg:grid-cols-[minmax(0,1.1fr)_minmax(360px,.9fr)] lg:gap-16">
|
||||
<div className="max-w-[620px]">
|
||||
<p className="campaign-section-eyebrow m-0 font-black tracking-[0.1em] text-(--pt-red) uppercase">
|
||||
Fotos da nossa caminhada
|
||||
</p>
|
||||
<h2
|
||||
id="selfie-home-title"
|
||||
className="campaign-section-title display m-0 mt-2 max-w-[560px] border-0 p-0 text-[30px]! leading-[1.02]! font-black tracking-[-0.03em] text-balance lg:text-[38px]!"
|
||||
>
|
||||
Encontre você nas fotos
|
||||
</h2>
|
||||
<p className="campaign-section-copy mt-4 max-w-[600px] text-(--campaign-muted)">
|
||||
<span className="sm:hidden">
|
||||
Use uma selfie sua na página da busca para procurar as fotos públicas aprovadas em que
|
||||
você aparece.
|
||||
</span>
|
||||
<span className="hidden sm:inline">
|
||||
Use uma selfie sua na página da busca para procurar, entre as fotos públicas aprovadas,
|
||||
aquelas em que você aparece.
|
||||
</span>
|
||||
</p>
|
||||
|
||||
<div className="mt-5 hidden max-w-[610px] items-start gap-3 text-sm leading-6 sm:flex">
|
||||
<span className="mt-0.5 grid size-9 shrink-0 place-items-center rounded-xl bg-[#184e92] text-white">
|
||||
<ShieldCheck aria-hidden="true" className="size-4" strokeWidth={2} />
|
||||
</span>
|
||||
<p className="m-0 text-[#365472]">
|
||||
<b className="text-[#143c70]">A selfie não sai do seu aparelho.</b> A busca cobre o
|
||||
índice anônimo do acervo aprovado, e você pode retirar seu rosto quando quiser.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 hidden flex-wrap items-center gap-x-6 gap-y-2 sm:flex">
|
||||
<Link
|
||||
href={ARCHIVE_PHOTO_ALBUM_ENTRY_PATH}
|
||||
className={`${ARCHIVE_PHOTO_PRIMARY_BUTTON} shrink-0`}
|
||||
>
|
||||
Encontrar minhas fotos
|
||||
<ChevronRight aria-hidden="true" className="size-4" />
|
||||
</Link>
|
||||
<Link
|
||||
href={ARCHIVE_PHOTO_ALBUM_PATH}
|
||||
className={`inline-flex min-h-11 items-center justify-center gap-1.5 rounded-md px-2 text-sm font-extrabold text-(--pt-red) underline underline-offset-4 hover:text-[#741414] ${ARCHIVE_PHOTO_FOCUS}`}
|
||||
>
|
||||
Ver o álbum
|
||||
<ChevronRight aria-hidden="true" className="size-4" />
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className={`mt-6 p-4 sm:hidden ${ASSURANCE_SURFACE}`}>
|
||||
<div className="flex items-start gap-3">
|
||||
<span className="grid size-10 shrink-0 place-items-center rounded-xl bg-[#184e92] text-white">
|
||||
<ShieldCheck aria-hidden="true" className="size-5" strokeWidth={2} />
|
||||
</span>
|
||||
<div>
|
||||
<p className="text-sm font-extrabold text-[#143c70]">Sua selfie fica no aparelho</p>
|
||||
<p className="mt-1 text-xs leading-5 text-[#365472]">
|
||||
A selfie não sai deste aparelho. A busca cobre o acervo aprovado, e você pode
|
||||
retirar seu rosto do índice quando quiser.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 grid gap-2 sm:mt-0 sm:hidden">
|
||||
<Link
|
||||
href={ARCHIVE_PHOTO_ALBUM_ENTRY_PATH}
|
||||
className={`${ARCHIVE_PHOTO_PRIMARY_BUTTON} w-full`}
|
||||
>
|
||||
Encontrar minhas fotos
|
||||
<ChevronRight aria-hidden="true" className="size-4" />
|
||||
</Link>
|
||||
<Link
|
||||
href={ARCHIVE_PHOTO_ALBUM_PATH}
|
||||
className={`inline-flex min-h-11 w-full items-center justify-center gap-1.5 rounded-md px-2 text-sm font-extrabold text-(--pt-red) underline underline-offset-4 hover:text-[#741414] ${ARCHIVE_PHOTO_FOCUS}`}
|
||||
>
|
||||
Ver o álbum
|
||||
<ChevronRight aria-hidden="true" className="size-4" />
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={`relative hidden overflow-hidden p-6 lg:block ${ASSURANCE_SURFACE}`}>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="absolute top-5 right-5 grid size-12 place-items-center rounded-full bg-white text-[#184e92] shadow-[0_8px_28px_rgb(24_78_146/12%)]"
|
||||
>
|
||||
<Sparkles aria-hidden="true" className="size-6" strokeWidth={2} />
|
||||
</span>
|
||||
<p className="max-w-[250px] font-[family-name:var(--font-exo2)] text-xl leading-tight font-black text-[#143c70]">
|
||||
Sua imagem fica com você. O controle também.
|
||||
</p>
|
||||
<ul className="mt-7 grid list-none gap-0 p-0">
|
||||
{ASSURANCE_ITEMS.map(({ icon: Icon, label }, index) => (
|
||||
<li
|
||||
key={label}
|
||||
className={`flex items-center gap-3 border-[#184e92]/12 py-4 ${
|
||||
index === ASSURANCE_ITEMS.length - 1 ? 'border-y' : 'border-t'
|
||||
}`}
|
||||
>
|
||||
<Icon aria-hidden="true" className="size-5 shrink-0 text-[#184e92]" strokeWidth={2} />
|
||||
<span className="text-sm font-bold text-[#143c70]">{label}</span>
|
||||
<Check aria-hidden="true" className="ml-auto size-4 text-[#184e92]" strokeWidth={2} />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
|
|
@ -3,7 +3,7 @@ import { cn } from '@/lib/utils'
|
|||
/** Shared class contracts of the public photo album (artefato C233, cenas 01–07). */
|
||||
|
||||
export const ARCHIVE_PHOTO_FOCUS =
|
||||
'focus-visible:outline-[3px] focus-visible:outline-offset-[3px] focus-visible:outline-(--pt-yellow)'
|
||||
'focus-visible:outline-[3px] focus-visible:outline-offset-[3px] focus-visible:outline-(--pt-yellow) focus-visible:shadow-[0_0_0_6px_rgb(24_78_146/72%)]'
|
||||
|
||||
export const ARCHIVE_PHOTO_CHIP = cn(
|
||||
'inline-flex min-h-11 items-center gap-1.5 rounded-full border border-(--campaign-line) bg-white px-3 text-xs font-bold text-black',
|
||||
|
|
|
|||
|
|
@ -16,6 +16,12 @@ type ShareLinkAgendaMenuProps = {
|
|||
canonicalUrl: string | null
|
||||
startsAt: string | null
|
||||
endsAt: string | null
|
||||
/**
|
||||
* S44 — the home section's agenda is the primary action (yellow CTA), while
|
||||
* the announcement page keeps the secondary outline. Default preserves the
|
||||
* S29 look.
|
||||
*/
|
||||
triggerClassName?: string
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -31,6 +37,7 @@ export const ShareLinkAgendaMenu = ({
|
|||
canonicalUrl,
|
||||
startsAt,
|
||||
endsAt,
|
||||
triggerClassName = SECONDARY_ACTION,
|
||||
}: ShareLinkAgendaMenuProps) => {
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
|
|
@ -49,13 +56,20 @@ export const ShareLinkAgendaMenu = ({
|
|||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<button type="button" className={SECONDARY_ACTION}>
|
||||
<button type="button" className={triggerClassName}>
|
||||
<CalendarPlusIcon className="size-4" aria-hidden="true" />
|
||||
Adicionar à agenda
|
||||
{open ? <ChevronDownIcon className="size-4" aria-hidden="true" /> : null}
|
||||
</button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent align="center" className={MENU_POPOVER} aria-label="Opções de agenda">
|
||||
<PopoverContent
|
||||
align="center"
|
||||
side="bottom"
|
||||
sideOffset={8}
|
||||
collisionPadding={12}
|
||||
className={MENU_POPOVER}
|
||||
aria-label="Opções de agenda"
|
||||
>
|
||||
<a
|
||||
href={googleUrl}
|
||||
target="_blank"
|
||||
|
|
@ -71,7 +85,9 @@ export const ShareLinkAgendaMenu = ({
|
|||
</span>
|
||||
<span>
|
||||
Google Agenda
|
||||
<small className="block font-normal text-black/45">Abrir evento preenchido</small>
|
||||
<small className="mt-0.5 block text-[11px] font-normal text-black/45">
|
||||
Abrir evento preenchido
|
||||
</small>
|
||||
</span>
|
||||
</a>
|
||||
<a
|
||||
|
|
@ -83,7 +99,9 @@ export const ShareLinkAgendaMenu = ({
|
|||
<CalendarPlusIcon className="size-5 flex-none text-(--pt-red)" aria-hidden="true" />
|
||||
<span>
|
||||
Baixar arquivo .ics
|
||||
<small className="block font-normal text-black/45">Apple, Outlook e desktop</small>
|
||||
<small className="mt-0.5 block text-[11px] font-normal text-black/45">
|
||||
Apple, Outlook e desktop
|
||||
</small>
|
||||
</span>
|
||||
</a>
|
||||
</PopoverContent>
|
||||
|
|
|
|||
|
|
@ -2,19 +2,16 @@
|
|||
|
||||
import { CalendarIcon, ExternalLinkIcon, MapPinIcon, VideoIcon } from 'lucide-react'
|
||||
import Image from 'next/image'
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
import { CampaignFooter } from '@/components/CampaignFooter'
|
||||
import { CampaignPageHeader } from '@/components/CampaignPageHeader'
|
||||
import { SAFE_FOCUS } from '@/components/shareLink/menuControls'
|
||||
import { ShareLinkAgendaMenu } from '@/components/shareLink/ShareLinkAgendaMenu'
|
||||
import { ShareLinkShareMenu } from '@/components/shareLink/ShareLinkShareMenu'
|
||||
import type { ShareLinkLiveTarget } from '@/lib/shareLink'
|
||||
import { useShareLinkLiveTarget } from '@/components/shareLink/useShareLinkLiveTarget'
|
||||
import type { ShareLinkAnnouncementView } from '@/lib/shareLinkAnnouncement'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const POLL_INTERVAL_MS = 30_000
|
||||
|
||||
const PRIMARY_ACTION = cn(
|
||||
'inline-flex min-h-14 w-full items-center justify-center gap-2.5 rounded-[10px] bg-(--pt-yellow) px-4',
|
||||
'font-[family-name:var(--font-exo2)] text-lg font-black text-(--pt-yellow-ink) no-underline',
|
||||
|
|
@ -44,49 +41,10 @@ export const ShareLinkAnnouncement = ({
|
|||
showJingles?: boolean
|
||||
showFotos?: boolean
|
||||
}) => {
|
||||
const [live, setLive] = useState<ShareLinkLiveTarget | null>(null)
|
||||
const live = useShareLinkLiveTarget(view.slug)
|
||||
const isLive = live !== null
|
||||
const hasEventDetails = Boolean(view.eventLabel || view.location)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
|
||||
const refetch = async () => {
|
||||
try {
|
||||
const response = await fetch(`/api/share-link/${encodeURIComponent(view.slug)}/live`, {
|
||||
cache: 'no-store',
|
||||
})
|
||||
if (!response.ok) return
|
||||
const { target } = (await response.json()) as { target: ShareLinkLiveTarget | null }
|
||||
if (cancelled || !target) return
|
||||
setLive((current) =>
|
||||
current?.href === target.href && current?.label === target.label ? current : target,
|
||||
)
|
||||
} catch {
|
||||
// A transient failure is a lost tick: the next poll retries.
|
||||
}
|
||||
}
|
||||
|
||||
// Read immediately: the server render may be a cached pre-broadcast page
|
||||
// that is already out of date.
|
||||
void refetch()
|
||||
|
||||
const interval = setInterval(() => {
|
||||
if (document.visibilityState === 'visible') void refetch()
|
||||
}, POLL_INTERVAL_MS)
|
||||
|
||||
const handleVisibility = () => {
|
||||
if (document.visibilityState === 'visible') void refetch()
|
||||
}
|
||||
document.addEventListener('visibilitychange', handleVisibility)
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
clearInterval(interval)
|
||||
document.removeEventListener('visibilitychange', handleVisibility)
|
||||
}
|
||||
}, [view.slug])
|
||||
|
||||
return (
|
||||
<div data-theme="campaign-site" className="flex min-h-full flex-col bg-(--campaign-cream)">
|
||||
<CampaignPageHeader badge={isLive ? 'Ao vivo' : 'Atividade online'} />
|
||||
|
|
|
|||
259
src/components/shareLink/ShareLinkHomeSection.tsx
Normal file
259
src/components/shareLink/ShareLinkHomeSection.tsx
Normal file
|
|
@ -0,0 +1,259 @@
|
|||
'use client'
|
||||
|
||||
import { ArrowRightIcon, CalendarIcon, ClockIcon, VideoIcon } from 'lucide-react'
|
||||
import Image from 'next/image'
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
import { ShareLinkAgendaMenu } from '@/components/shareLink/ShareLinkAgendaMenu'
|
||||
import { SHARE_LINK_HOME_PRIMARY_ACTION } from '@/components/shareLink/menuControls'
|
||||
import { useShareLinkLiveTarget } from '@/components/shareLink/useShareLinkLiveTarget'
|
||||
import { formatBahiaEventDayLabel, formatBahiaEventTimeLabel } from '@/lib/campaignTime'
|
||||
import { shareLinkPath, type ShareLinkLiveTarget } from '@/lib/shareLink'
|
||||
import {
|
||||
resolveShareLinkLiveActionLabel,
|
||||
type ShareLinkHomeSectionView,
|
||||
} from '@/lib/shareLinkHomeSection'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const META_ITEM =
|
||||
'flex min-w-0 items-center gap-[11px] py-2.5 text-sm leading-[1.2] font-extrabold text-[#211b19] lg:py-0'
|
||||
const META_ICON =
|
||||
'grid size-9 flex-none place-items-center rounded-[10px] bg-[rgb(162_28_28/9%)] text-(--pt-red)'
|
||||
|
||||
// `setTimeout` clamps delays above this (Node/browser) and fires immediately;
|
||||
// a far-future `endsAt` re-arms instead of hiding the section on mount.
|
||||
const MAX_TIMER_MS = 2_147_483_647
|
||||
|
||||
/** The single live entry action (the desktop/mobile variants differ only in placement). */
|
||||
const LiveEntryAction = ({
|
||||
slug,
|
||||
label,
|
||||
className,
|
||||
}: {
|
||||
slug: string
|
||||
label: string
|
||||
className: string
|
||||
}) => (
|
||||
<a href={shareLinkPath(slug)} className={cn(SHARE_LINK_HOME_PRIMARY_ACTION, className)}>
|
||||
{label}
|
||||
<ArrowRightIcon className="size-[19px]" strokeWidth={2.25} aria-hidden="true" />
|
||||
</a>
|
||||
)
|
||||
|
||||
/**
|
||||
* S44 — the home section that announces the Plenária da Vitória (design
|
||||
* artefato `secao-home-plenaria-da-vitoria-ui-design.html`, cenas 01–06).
|
||||
* Before the broadcast it shows the invitation (image, Bahia date/time and the
|
||||
* S29 agenda, never an entry button); once a destination is on air the image
|
||||
* gives way to the official YouTube player and the entry CTA takes the agenda's
|
||||
* place, always pointing to the link's canonical path. The section hides
|
||||
* itself the moment the event window closes (open tabs), on top of the
|
||||
* server-side fail-closed gate (unpublished or expired → absent from the HTML).
|
||||
*/
|
||||
export const ShareLinkHomeSection = ({
|
||||
view,
|
||||
initialLive,
|
||||
}: {
|
||||
view: ShareLinkHomeSectionView
|
||||
initialLive: ShareLinkLiveTarget | null
|
||||
}) => {
|
||||
const live = useShareLinkLiveTarget(view.slug, initialLive)
|
||||
const [expired, setExpired] = useState(false)
|
||||
const isLive = live !== null
|
||||
|
||||
useEffect(() => {
|
||||
let timer: ReturnType<typeof setTimeout>
|
||||
|
||||
const schedule = () => {
|
||||
const remaining = view.expiresAt - Date.now()
|
||||
if (remaining <= 0) {
|
||||
timer = setTimeout(() => setExpired(true), 0)
|
||||
return
|
||||
}
|
||||
timer = setTimeout(schedule, Math.min(remaining, MAX_TIMER_MS))
|
||||
}
|
||||
|
||||
schedule()
|
||||
return () => clearTimeout(timer)
|
||||
}, [view.expiresAt])
|
||||
|
||||
if (expired) return null
|
||||
|
||||
const dayLabel = view.startsAt ? formatBahiaEventDayLabel(view.startsAt) : ''
|
||||
const timeLabel = view.startsAt ? formatBahiaEventTimeLabel(view.startsAt) : ''
|
||||
const entryLabel = live ? resolveShareLinkLiveActionLabel(live) : null
|
||||
|
||||
const figure =
|
||||
isLive && view.youtubeVideoId ? (
|
||||
<figure className="m-0 mt-6 lg:col-start-2 lg:mt-0">
|
||||
<div className="relative aspect-video w-full overflow-hidden rounded-[18px] border border-black/10 bg-black shadow-[0_18px_46px_rgb(71_19_14/18%)]">
|
||||
<iframe
|
||||
src={`https://www.youtube-nocookie.com/embed/${view.youtubeVideoId}?playsinline=1&rel=0`}
|
||||
title={`Ao vivo: ${view.title}`}
|
||||
loading="lazy"
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
|
||||
allowFullScreen
|
||||
className="absolute inset-0 h-full w-full border-0"
|
||||
/>
|
||||
</div>
|
||||
</figure>
|
||||
) : view.imageUrl ? (
|
||||
<figure className="m-0 mt-7 lg:col-start-2 lg:mt-0">
|
||||
<div className="relative aspect-square w-full overflow-hidden rounded-[18px] border border-[rgb(71_19_14/18%)] bg-[#eee9e4] shadow-[0_18px_46px_rgb(71_19_14/10%)]">
|
||||
<Image
|
||||
src={view.imageUrl}
|
||||
alt={view.imageAlt}
|
||||
fill
|
||||
sizes="(min-width: 1024px) 390px, 100vw"
|
||||
className="object-cover"
|
||||
/>
|
||||
</div>
|
||||
</figure>
|
||||
) : null
|
||||
|
||||
return (
|
||||
<section
|
||||
aria-labelledby="plenaria-title"
|
||||
data-home-section="plenaria"
|
||||
className="relative isolate overflow-hidden border-b border-(--campaign-line) bg-(--campaign-cream) px-5 py-9 sm:px-8 lg:px-16 lg:py-14"
|
||||
>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="pointer-events-none absolute -top-[170px] -right-[108px] -z-10 size-[420px] rounded-full bg-(--pt-yellow) opacity-30"
|
||||
/>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="pointer-events-none absolute -bottom-[230px] -left-[190px] -z-10 size-[390px] rounded-full bg-[#184e92] opacity-[0.055]"
|
||||
/>
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
'mx-auto grid max-w-[1152px] gap-0 lg:items-center',
|
||||
isLive
|
||||
? 'lg:grid-cols-[minmax(0,1fr)_470px] lg:gap-14'
|
||||
: 'lg:grid-cols-[minmax(0,1fr)_390px] lg:gap-16',
|
||||
)}
|
||||
>
|
||||
<div className={cn(isLive ? undefined : 'lg:max-w-[610px]')}>
|
||||
<p
|
||||
aria-live="polite"
|
||||
className={cn(
|
||||
'm-0 flex items-center gap-[9px] font-[family-name:var(--font-exo2)] font-black text-(--pt-red) uppercase',
|
||||
isLive
|
||||
? 'text-[10px] tracking-[0.08em] lg:text-[11px]'
|
||||
: 'text-[10px] tracking-[0.11em] lg:text-[12px]',
|
||||
)}
|
||||
>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
'flex-none rounded-full bg-(--pt-red) shadow-[0_0_0_5px_rgb(162_28_28/10%)]',
|
||||
isLive ? 'size-2' : 'size-[9px]',
|
||||
)}
|
||||
/>
|
||||
{isLive ? 'Ao vivo agora' : 'Encontro online'}
|
||||
</p>
|
||||
|
||||
<h2
|
||||
id="plenaria-title"
|
||||
className={cn(
|
||||
'border-0 pb-0 font-[family-name:var(--font-exo2)] font-black tracking-[-0.04em] text-(--campaign-ink)',
|
||||
isLive
|
||||
? 'mt-3 text-[34px] leading-none lg:mt-4 lg:text-[43px]'
|
||||
: 'mt-3 text-[36px] leading-[0.98] lg:mt-4 lg:text-[48px]',
|
||||
)}
|
||||
>
|
||||
{view.title}
|
||||
</h2>
|
||||
|
||||
<p
|
||||
className={cn(
|
||||
'text-black/72',
|
||||
isLive
|
||||
? 'mt-4 text-[14px] leading-6 lg:max-w-[560px] lg:text-[17px] lg:leading-[1.55]'
|
||||
: 'mt-4 text-[15px] leading-6 lg:mt-5 lg:max-w-[590px] lg:text-[18px] lg:leading-[1.55]',
|
||||
)}
|
||||
>
|
||||
{view.description}
|
||||
</p>
|
||||
|
||||
{isLive ? (
|
||||
<>
|
||||
<div className="mt-5 grid gap-1 border-y border-(--campaign-line) py-3 text-xs font-extrabold lg:hidden">
|
||||
<span>
|
||||
{dayLabel} · {timeLabel}
|
||||
</span>
|
||||
<span>
|
||||
{view.location ? `horário da Bahia · ${view.location}` : 'horário da Bahia'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-6 hidden flex-wrap gap-x-5 gap-y-2 border-y border-(--campaign-line) py-4 text-sm font-extrabold lg:flex">
|
||||
<span>{dayLabel}</span>
|
||||
<span>{timeLabel} (horário da Bahia)</span>
|
||||
{view.location ? <span>{view.location}</span> : null}
|
||||
</div>
|
||||
{entryLabel ? (
|
||||
<LiveEntryAction
|
||||
slug={view.slug}
|
||||
label={entryLabel}
|
||||
className="mt-6 hidden lg:mt-7 lg:inline-flex"
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="mt-6 grid border-y border-(--campaign-line) py-2 lg:mt-7 lg:grid-cols-3 lg:py-4">
|
||||
<div className={cn(META_ITEM, 'lg:border-r lg:border-black/10 lg:pr-4')}>
|
||||
<span className={META_ICON} aria-hidden="true">
|
||||
<CalendarIcon className="size-5" strokeWidth={2} />
|
||||
</span>
|
||||
<span>{dayLabel}</span>
|
||||
</div>
|
||||
<div className={cn(META_ITEM, 'lg:border-r lg:border-black/10 lg:px-4')}>
|
||||
<span className={META_ICON} aria-hidden="true">
|
||||
<ClockIcon className="size-5" strokeWidth={2} />
|
||||
</span>
|
||||
<span>
|
||||
{timeLabel}
|
||||
<small className="mt-0.5 hidden text-[10px] font-semibold text-black/55 lg:block">
|
||||
horário da Bahia
|
||||
</small>
|
||||
<span className="lg:hidden"> (horário da Bahia)</span>
|
||||
</span>
|
||||
</div>
|
||||
{view.location ? (
|
||||
<div className={cn(META_ITEM, 'lg:pl-4')}>
|
||||
<span className={META_ICON} aria-hidden="true">
|
||||
<VideoIcon className="size-5" strokeWidth={2} />
|
||||
</span>
|
||||
<span>{view.location}</span>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="mt-6 w-full lg:mt-7 lg:w-[270px]">
|
||||
<ShareLinkAgendaMenu
|
||||
slug={view.slug}
|
||||
title={view.title}
|
||||
description={view.description}
|
||||
location={view.location}
|
||||
canonicalUrl={view.canonicalUrl}
|
||||
startsAt={view.startsAt}
|
||||
endsAt={view.endsAt}
|
||||
triggerClassName={cn(SHARE_LINK_HOME_PRIMARY_ACTION, 'w-full')}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{figure}
|
||||
|
||||
{/* Mobile keeps the artifact order (player before the entry CTA); the
|
||||
desktop CTA lives inside the left column, right after the meta. */}
|
||||
{entryLabel ? (
|
||||
<LiveEntryAction slug={view.slug} label={entryLabel} className="mt-6 w-full lg:hidden" />
|
||||
) : null}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
|
@ -15,9 +15,26 @@ export const SECONDARY_ACTION = cn(
|
|||
SAFE_FOCUS,
|
||||
)
|
||||
|
||||
/**
|
||||
* S44 — the home section's single primary action (design artefato
|
||||
* `secao-home-plenaria-da-vitoria-ui-design.html`, `.primary-action`): the
|
||||
* yellow CTA is both the agenda trigger before the broadcast and the entry
|
||||
* link while on air. The announcement page keeps its own CTA constant.
|
||||
*/
|
||||
export const SHARE_LINK_HOME_PRIMARY_ACTION = cn(
|
||||
'inline-flex min-h-[54px] items-center justify-center gap-2.5 rounded-[10px] bg-(--pt-yellow) px-5 py-3',
|
||||
'font-[family-name:var(--font-exo2)] text-[17px] leading-none font-black text-(--pt-yellow-ink) no-underline',
|
||||
'shadow-[0_5px_0_#cfb900,0_10px_22px_rgb(0_0_0/12%)]',
|
||||
'transition-[transform,filter] duration-[180ms] ease-out hover:brightness-[0.97] hover:-translate-y-px',
|
||||
'active:translate-y-[3px] active:shadow-[0_2px_0_#cfb900,0_5px_12px_rgb(0_0_0/10%)] motion-reduce:transition-none',
|
||||
'focus-visible:outline-[3px] focus-visible:outline-offset-4 focus-visible:outline-(--pt-yellow)',
|
||||
'focus-visible:shadow-[0_0_0_2px_var(--pt-red-dark),0_5px_0_#cfb900,0_10px_22px_rgb(0_0_0/12%)]',
|
||||
)
|
||||
|
||||
export const MENU_ROW = cn(
|
||||
'flex min-h-11 w-full items-center gap-2.5 rounded-[7px] px-2.5 py-2 text-left text-sm font-semibold text-[#211b19] no-underline',
|
||||
'transition-colors hover:bg-(--campaign-band) focus-visible:bg-(--campaign-band) focus-visible:outline-none motion-reduce:transition-none',
|
||||
)
|
||||
|
||||
export const MENU_POPOVER = 'w-[270px] rounded-[10px] border border-black/10 p-1'
|
||||
export const MENU_POPOVER =
|
||||
'w-[270px] max-lg:w-(--radix-popover-trigger-width) rounded-[10px] border border-black/10 p-1 shadow-[0_14px_34px_rgb(71_19_14/15%)]'
|
||||
|
|
|
|||
64
src/components/shareLink/useShareLinkLiveTarget.ts
Normal file
64
src/components/shareLink/useShareLinkLiveTarget.ts
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
import type { ShareLinkLiveTarget } from '@/lib/shareLink'
|
||||
|
||||
const POLL_INTERVAL_MS = 30_000
|
||||
|
||||
/**
|
||||
* S29/S44 — the fresh "no ar" read behind the share-link surfaces. It polls
|
||||
* the route handler every 30s (paused on hidden tabs), refetches immediately on
|
||||
* mount/wake, and only ever ACTIVATES: a `target: null` answer never clears the
|
||||
* state, so an already-open page keeps the destination it saw (the kill switch
|
||||
* is the link's `published` flag, handled by the server read). `initial` seeds
|
||||
* the server-resolved state (the home section renders live in the HTML for
|
||||
* whoever arrives during the broadcast).
|
||||
*/
|
||||
export const useShareLinkLiveTarget = (
|
||||
slug: string,
|
||||
initial: ShareLinkLiveTarget | null = null,
|
||||
): ShareLinkLiveTarget | null => {
|
||||
const [live, setLive] = useState<ShareLinkLiveTarget | null>(initial)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
|
||||
const refetch = async () => {
|
||||
try {
|
||||
const response = await fetch(`/api/share-link/${encodeURIComponent(slug)}/live`, {
|
||||
cache: 'no-store',
|
||||
})
|
||||
if (!response.ok) return
|
||||
const { target } = (await response.json()) as { target: ShareLinkLiveTarget | null }
|
||||
if (cancelled || !target) return
|
||||
setLive((current) =>
|
||||
current?.href === target.href && current?.label === target.label ? current : target,
|
||||
)
|
||||
} catch {
|
||||
// A transient failure is a lost tick: the next poll retries.
|
||||
}
|
||||
}
|
||||
|
||||
// Read immediately: the server render may be a cached pre-broadcast page
|
||||
// that is already out of date.
|
||||
void refetch()
|
||||
|
||||
const interval = setInterval(() => {
|
||||
if (document.visibilityState === 'visible') void refetch()
|
||||
}, POLL_INTERVAL_MS)
|
||||
|
||||
const handleVisibility = () => {
|
||||
if (document.visibilityState === 'visible') void refetch()
|
||||
}
|
||||
document.addEventListener('visibilitychange', handleVisibility)
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
clearInterval(interval)
|
||||
document.removeEventListener('visibilitychange', handleVisibility)
|
||||
}
|
||||
}, [slug])
|
||||
|
||||
return live
|
||||
}
|
||||
|
|
@ -30,14 +30,15 @@ export const CAMPAIGN_PUSH_CONSENT_MISSING_MESSAGE =
|
|||
'Consentimento de notificações push ainda não configurado.'
|
||||
|
||||
/**
|
||||
* C234 — the public selfie search on the photo album. Two keys because the
|
||||
* two biometric uses are distinct: `FACE_SEARCH_CONSENT_KEY` is the temporary
|
||||
* use of the querying person's face to find themselves in the album (the
|
||||
* vector is discarded with the request), while `FACE_INDEX_CONSENT_KEY` is
|
||||
* the enrollment in the search index (the vector is stored until removal).
|
||||
* Both fail closed: without the Consent row with the exact key the flow is
|
||||
* closed, and editing the text invalidates every enrolled subject until
|
||||
* re-consent.
|
||||
* C242 — the public selfie search on the photo album (scope B: the anonymous
|
||||
* descriptor index of the approved archive). Two keys because the two
|
||||
* biometric documents are distinct: `FACE_SEARCH_CONSENT_KEY` is the visitor's
|
||||
* consent for the temporary use of their own face in this query (the vector is
|
||||
* discarded with the request), while `FACE_INDEX_CONSENT_KEY` is the PUBLIC
|
||||
* NOTICE of the anonymous archive index (transparency + self-service opt-out;
|
||||
* there is no per-person enrollment). Both fail closed: without the Consent row
|
||||
* with the exact key the flow is closed, and the texts are versioned in
|
||||
* `scripts/lib/faceConsentTexts.mjs` (provisioned by `pnpm seed:face-consents`).
|
||||
*/
|
||||
export const FACE_SEARCH_CONSENT_KEY = 'busca-selfie-fotos'
|
||||
export const FACE_INDEX_CONSENT_KEY = 'busca-selfie-indice'
|
||||
|
|
|
|||
|
|
@ -136,18 +136,40 @@ const bahiaEventTimeFormatter = new Intl.DateTimeFormat('pt-BR', {
|
|||
})
|
||||
|
||||
/**
|
||||
* S29 — the announcement headline date, e.g. `Sábado, 3 de outubro · 19h`.
|
||||
* Minutes only when they are not `00`; the timezone is always Bahia, never
|
||||
* the visitor's. Empty string for an unparsable instant (callers fall back to
|
||||
* hiding the date).
|
||||
* S29/S44 — the event day in Bahia civil time, e.g. `sexta-feira, 2 de
|
||||
* outubro`. Lowercase on purpose: the callers decide the capitalization
|
||||
* (the announcement headline capitalizes; the home meta row does not). Empty
|
||||
* string for an unparsable instant (callers fall back to hiding the date).
|
||||
*/
|
||||
export const formatBahiaEventDateLabel = (iso: string): string => {
|
||||
export const formatBahiaEventDayLabel = (iso: string): string => {
|
||||
const date = new Date(iso)
|
||||
if (Number.isNaN(date.getTime())) return ''
|
||||
|
||||
return bahiaEventDayFormatter.format(date)
|
||||
}
|
||||
|
||||
/**
|
||||
* S29/S44 — the event time in Bahia civil time, e.g. `18h` (minutes only when
|
||||
* they are not `00`; `18h30`). Empty string for an unparsable instant.
|
||||
*/
|
||||
export const formatBahiaEventTimeLabel = (iso: string): string => {
|
||||
const date = new Date(iso)
|
||||
if (Number.isNaN(date.getTime())) return ''
|
||||
|
||||
const day = bahiaEventDayFormatter.format(date)
|
||||
const [hour, minute] = bahiaEventTimeFormatter.format(date).split(':')
|
||||
const time = minute === '00' ? `${hour}h` : `${hour}h${minute}`
|
||||
return minute === '00' ? `${hour}h` : `${hour}h${minute}`
|
||||
}
|
||||
|
||||
/**
|
||||
* S29 — the announcement headline date, e.g. `Sábado, 3 de outubro · 19h`.
|
||||
* The timezone is always Bahia, never the visitor's. Empty string for an
|
||||
* unparsable instant (callers fall back to hiding the date).
|
||||
*/
|
||||
export const formatBahiaEventDateLabel = (iso: string): string => {
|
||||
const day = formatBahiaEventDayLabel(iso)
|
||||
const time = formatBahiaEventTimeLabel(iso)
|
||||
if (!day || !time) return ''
|
||||
|
||||
const capitalizedDay = day.charAt(0).toUpperCase() + day.slice(1)
|
||||
|
||||
return `${capitalizedDay} · ${time}`
|
||||
|
|
|
|||
|
|
@ -1,25 +1,26 @@
|
|||
/**
|
||||
* C234 — pure contract of the selfie search over the public photo album.
|
||||
* C242 — pure contract of the selfie search over the public photo album
|
||||
* (scope B: the anonymous descriptor index of the approved archive, decision
|
||||
* of 2026-10-01, supersedes the A/C enrollment of C234).
|
||||
*
|
||||
* The visitor's face descriptor is computed on their own device (the selfie
|
||||
* never leaves it); the server only ever sees the 128-float vector and answers
|
||||
* with photos, never with a score. This module owns the wire vocabulary (the
|
||||
* descriptor length, the model id, the intents), the distance math, the
|
||||
* eligibility of an enrolled subject (active + current model + current consent
|
||||
* hash — fail-closed on any of the three), the result view model (which by
|
||||
* SHAPE cannot carry a similarity number or a third-party name) and the
|
||||
* deterministic stub the e2e build uses in place of the engine.
|
||||
* descriptor length, the model id, the intents), the distance math, the match
|
||||
* over photo descriptors (which by SHAPE cannot carry a similarity number),
|
||||
* the result view model (no third-party names) and the deterministic stub the
|
||||
* e2e build uses in place of the engine.
|
||||
*
|
||||
* Scope lock of the gate (PR #1370): only consented/indexed faces exist in the
|
||||
* index (A/C); the anonymous-archive index (B) is out. The vector of the
|
||||
* visitor is never persisted — it lives in the request only.
|
||||
* The anonymous photo descriptors live in `archivePhotoFace` (photo-level, no
|
||||
* identity); a match never resolves a person — only photos. The visitor's
|
||||
* vector is never persisted: it lives in the request only.
|
||||
*/
|
||||
import type { ArchivePhotoPublicItem } from '@/lib/archivePhotoPublicCatalog'
|
||||
|
||||
/** face-api's faceRecognitionNet descriptor (128 floats, euclidean space). */
|
||||
export const FACE_SEARCH_DESCRIPTOR_LENGTH = 128
|
||||
|
||||
/** The engine+model the enrolled vectors belong to — a match across models is void. */
|
||||
/** The engine+model the indexed vectors belong to — a match across models is void. */
|
||||
export const FACE_SEARCH_MODEL = 'face-api@1.7.15/faceRecognitionNet'
|
||||
|
||||
/**
|
||||
|
|
@ -61,8 +62,11 @@ export const readFaceVector = (value: unknown): number[] | null => {
|
|||
return vector
|
||||
}
|
||||
|
||||
/** Euclidean distance of same-length descriptors; a length mismatch is never a match. */
|
||||
export const faceEuclideanDistance = (a: readonly number[], b: readonly number[]): number => {
|
||||
/**
|
||||
* Euclidean distance of same-length descriptors; a length mismatch is never a
|
||||
* match. Accepts typed arrays so the cached index can stay in `Float32Array`.
|
||||
*/
|
||||
export const faceEuclideanDistance = (a: ArrayLike<number>, b: ArrayLike<number>): number => {
|
||||
if (a.length !== b.length || a.length === 0) return Number.POSITIVE_INFINITY
|
||||
|
||||
let sum = 0
|
||||
|
|
@ -73,58 +77,37 @@ export const faceEuclideanDistance = (a: readonly number[], b: readonly number[]
|
|||
return Math.sqrt(sum)
|
||||
}
|
||||
|
||||
export type FaceSearchSubject = {
|
||||
id: number
|
||||
status?: string | null
|
||||
model?: string | null
|
||||
consentHash?: string | null
|
||||
vector?: unknown
|
||||
/**
|
||||
* One indexed face of the approved archive: the photo it was found in and its
|
||||
* descriptor. The row has no identity by construction — this is the scope B
|
||||
* (anonymous) contract.
|
||||
*/
|
||||
export type FaceDescriptorEntry = {
|
||||
photoId: number
|
||||
vector: ArrayLike<number>
|
||||
}
|
||||
|
||||
/**
|
||||
* A subject only answers while it is `active`, was enrolled with the model the
|
||||
* query belongs to and its consent snapshot is still the configured text
|
||||
* (editing the Consent text invalidates every enrolled descriptor until the
|
||||
* person is re-consented — fail-closed).
|
||||
* The distinct photo ids with at least one indexed face strictly under
|
||||
* `maxDistance` from the query vector, in the order the photos appear in the
|
||||
* index. `FACE_SEARCH_MAX_DISTANCE` is the only threshold: no caller ever
|
||||
* receives a distance or a score.
|
||||
*/
|
||||
export const faceSubjectIsEligible = (
|
||||
subject: FaceSearchSubject,
|
||||
{ model, consentHash }: { model: string; consentHash: string },
|
||||
): boolean =>
|
||||
subject.status === 'active' && subject.model === model && subject.consentHash === consentHash
|
||||
export const findFaceDescriptorPhotoIds = (
|
||||
vector: ArrayLike<number>,
|
||||
descriptors: readonly FaceDescriptorEntry[],
|
||||
): number[] => {
|
||||
const matched: number[] = []
|
||||
const seen = new Set<number>()
|
||||
|
||||
/**
|
||||
* The best eligible subject strictly under `maxDistance`, or null. Subject
|
||||
* order breaks nothing: the comparison is strict, so only a closer subject
|
||||
* replaces the current best.
|
||||
*/
|
||||
export const findFaceMatch = ({
|
||||
vector,
|
||||
subjects,
|
||||
model,
|
||||
consentHash,
|
||||
}: {
|
||||
vector: readonly number[]
|
||||
subjects: readonly FaceSearchSubject[]
|
||||
model: string
|
||||
consentHash: string
|
||||
}): FaceSearchSubject | null => {
|
||||
let best: FaceSearchSubject | null = null
|
||||
let bestDistance = FACE_SEARCH_MAX_DISTANCE
|
||||
|
||||
for (const subject of subjects) {
|
||||
if (!faceSubjectIsEligible(subject, { model, consentHash })) continue
|
||||
const candidate = readFaceVector(subject.vector)
|
||||
if (!candidate) continue
|
||||
|
||||
const distance = faceEuclideanDistance(vector, candidate)
|
||||
if (distance < bestDistance) {
|
||||
bestDistance = distance
|
||||
best = subject
|
||||
}
|
||||
for (const entry of descriptors) {
|
||||
if (seen.has(entry.photoId)) continue
|
||||
if (faceEuclideanDistance(vector, entry.vector) >= FACE_SEARCH_MAX_DISTANCE) continue
|
||||
seen.add(entry.photoId)
|
||||
matched.push(entry.photoId)
|
||||
}
|
||||
|
||||
return best
|
||||
return matched
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -165,7 +148,7 @@ export const toFaceSearchPhotoView = (item: ArchivePhotoPublicItem): FaceSearchP
|
|||
/**
|
||||
* Deterministic stand-in for the on-device engine (`NEXT_PUBLIC_FACE_SEARCH_STUB=1`,
|
||||
* e2e builds only): the same bytes always derive the same descriptor, so the
|
||||
* spec can seed a subject whose vector equals the fixture's without ever
|
||||
* spec can seed an indexed face whose vector equals the fixture's without ever
|
||||
* loading a model. Never used outside the stub seam.
|
||||
*/
|
||||
export const faceStubDescriptorFromBytes = (bytes: Uint8Array): number[] => {
|
||||
|
|
|
|||
|
|
@ -87,6 +87,61 @@ export const resolveLiveShareLinkDestination = (
|
|||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* The single owner of the YouTube id contract (11 chars), shared with the
|
||||
* campaign social-feed exclusion validator (`utilities/socialFeed/excludedItems`).
|
||||
*/
|
||||
export const YOUTUBE_VIDEO_ID_PATTERN = /^[A-Za-z0-9_-]{11}$/
|
||||
|
||||
/** Hosts that serve YouTube videos (embed/watch), `www.` stripped by the caller. */
|
||||
export const YOUTUBE_HOSTS = ['youtube.com', 'm.youtube.com', 'youtube-nocookie.com'] as const
|
||||
|
||||
const resolveYoutubeVideoIdFromUrl = (value: string): string | null => {
|
||||
const url = normalizeAbsoluteHttpUrl(value)
|
||||
if (!url) return null
|
||||
|
||||
const parsed = new URL(url)
|
||||
const host = parsed.hostname.replace(/^www\./, '')
|
||||
|
||||
if (host === 'youtu.be') {
|
||||
const [id] = parsed.pathname.slice(1).split('/')
|
||||
return id && YOUTUBE_VIDEO_ID_PATTERN.test(id) ? id : null
|
||||
}
|
||||
|
||||
if (!(YOUTUBE_HOSTS as readonly string[]).includes(host)) return null
|
||||
|
||||
if (parsed.pathname === '/watch') {
|
||||
const id = parsed.searchParams.get('v')
|
||||
return id && YOUTUBE_VIDEO_ID_PATTERN.test(id) ? id : null
|
||||
}
|
||||
|
||||
const match = parsed.pathname.match(/^\/(?:live|embed|shorts)\/([^/?#]+)/)
|
||||
const id = match?.[1]
|
||||
return id && YOUTUBE_VIDEO_ID_PATTERN.test(id) ? id : null
|
||||
}
|
||||
|
||||
/**
|
||||
* S44 — the official player of the home section embeds the link's
|
||||
* pre-registered YouTube destination (the campaign's own live), independent of
|
||||
* which destination is on air. Accepts the usual public shapes
|
||||
* (`youtu.be/<id>`, `watch?v=`, `/live/`, `/embed/`, `/shorts/`); the id must
|
||||
* look like a real one (11 chars) — anything else fails closed to `null` and
|
||||
* the section renders without the player.
|
||||
*/
|
||||
export const resolveShareLinkYoutubeVideoId = (
|
||||
destinations: ShareLinkDestinationLike[] | null | undefined,
|
||||
): string | null => {
|
||||
if (!destinations?.length) return null
|
||||
|
||||
for (const destination of destinations) {
|
||||
const url = typeof destination?.url === 'string' ? destination.url : ''
|
||||
const id = resolveYoutubeVideoIdFromUrl(url)
|
||||
if (id) return id
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/** Public path contract: a single root segment (`jorgesolla1313.com.br/<slug>`). */
|
||||
export const shareLinkPath = (slug: string): string => `/${slug}`
|
||||
|
||||
|
|
|
|||
82
src/lib/shareLinkHomeSection.ts
Normal file
82
src/lib/shareLinkHomeSection.ts
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
import { resolveCalendarEventWindow } from '@/lib/calendarEvent'
|
||||
import {
|
||||
normalizeAbsoluteHttpUrl,
|
||||
resolveShareLinkYoutubeVideoId,
|
||||
YOUTUBE_HOSTS,
|
||||
type ShareLinkDestinationLike,
|
||||
type ShareLinkLiveTarget,
|
||||
} from '@/lib/shareLink'
|
||||
import {
|
||||
buildShareLinkAnnouncementView,
|
||||
type ShareLinkAnnouncementSource,
|
||||
type ShareLinkAnnouncementView,
|
||||
} from '@/lib/shareLinkAnnouncement'
|
||||
|
||||
/**
|
||||
* S44 — the pure contract of the home section that announces the Plenária da
|
||||
* Vitória. The section reflects the state of one fixed share link: while the
|
||||
* event window is open it renders the announcement view (image + agenda before
|
||||
* the broadcast; YouTube embed + entry CTA while on air), and it disappears
|
||||
* (fail-closed) once the link is unpublished or the window closes. No Payload
|
||||
* import here — the server read orchestrates and hands over a serializable view.
|
||||
*/
|
||||
|
||||
export const SHARE_LINK_HOME_SECTION_SLUG = 'plenaria-vitoria'
|
||||
|
||||
export type ShareLinkHomeSectionSource = ShareLinkAnnouncementSource & {
|
||||
destinations?: ShareLinkDestinationLike[] | null
|
||||
}
|
||||
|
||||
export type ShareLinkHomeSectionView = ShareLinkAnnouncementView & {
|
||||
/** Epoch ms when the event window closes (`endsAt`, else `startsAt` + 2h). */
|
||||
expiresAt: number
|
||||
/** Video id of the link's pre-registered YouTube destination, when there is one. */
|
||||
youtubeVideoId: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* The visibility window is the S29 calendar window (the same 2h fallback
|
||||
* duration): no valid `startsAt` means no event window, and a closed window
|
||||
* hides the section entirely — never a stale promo.
|
||||
*/
|
||||
export const buildShareLinkHomeSectionView = ({
|
||||
link,
|
||||
imageUrl,
|
||||
canonicalUrl,
|
||||
nowMs,
|
||||
}: {
|
||||
link: ShareLinkHomeSectionSource
|
||||
imageUrl: string | null
|
||||
canonicalUrl: string | null
|
||||
nowMs: number
|
||||
}): ShareLinkHomeSectionView | null => {
|
||||
const window = resolveCalendarEventWindow(link.startsAt, link.endsAt)
|
||||
if (!window || nowMs >= window.end.getTime()) return null
|
||||
|
||||
return {
|
||||
...buildShareLinkAnnouncementView({ link, imageUrl, canonicalUrl }),
|
||||
expiresAt: window.end.getTime(),
|
||||
youtubeVideoId: resolveShareLinkYoutubeVideoId(link.destinations),
|
||||
}
|
||||
}
|
||||
|
||||
const MEET_HOST = 'meet.google.com'
|
||||
|
||||
/**
|
||||
* S44 — the entry CTA label follows the destination on air (design gate): the
|
||||
* Google Meet is "Entrar na plenária", the YouTube is "Assistir no YouTube".
|
||||
* The host is the source of truth (a relabeled destination never mislabels the
|
||||
* button); anything else falls back to the S29 generic "Entrar".
|
||||
*/
|
||||
export const resolveShareLinkLiveActionLabel = (target: ShareLinkLiveTarget): string => {
|
||||
const url = normalizeAbsoluteHttpUrl(target.href)
|
||||
if (!url) return 'Entrar'
|
||||
|
||||
const host = new URL(url).hostname.replace(/^www\./, '')
|
||||
if (host === MEET_HOST) return 'Entrar na plenária'
|
||||
if (host === 'youtu.be' || (YOUTUBE_HOSTS as readonly string[]).includes(host)) {
|
||||
return 'Assistir no YouTube'
|
||||
}
|
||||
|
||||
return 'Entrar'
|
||||
}
|
||||
20625
src/migrations/20261001_040904_add_archive_photo_face.json
Normal file
20625
src/migrations/20261001_040904_add_archive_photo_face.json
Normal file
File diff suppressed because it is too large
Load diff
77
src/migrations/20261001_040904_add_archive_photo_face.ts
Normal file
77
src/migrations/20261001_040904_add_archive_photo_face.ts
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
|
||||
|
||||
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
CREATE TABLE "archive_photo_face" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"photo_id" integer NOT NULL,
|
||||
"model" varchar NOT NULL,
|
||||
"detected_at" timestamp(3) with time zone,
|
||||
"vector" jsonb,
|
||||
"updated_at" timestamp(3) with time zone DEFAULT now() NOT NULL,
|
||||
"created_at" timestamp(3) with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
|
||||
ALTER TABLE "face_subject" DISABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE "face_subject_rels" DISABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE "payload_locked_documents_rels" DROP CONSTRAINT "payload_locked_documents_rels_face_subject_fk";
|
||||
DROP INDEX "payload_locked_documents_rels_face_subject_id_idx";
|
||||
DROP TABLE "face_subject" CASCADE;
|
||||
DROP TABLE "face_subject_rels" CASCADE;
|
||||
ALTER TABLE "payload_locked_documents_rels" ADD COLUMN "archive_photo_face_id" integer;
|
||||
ALTER TABLE "archive_photo_face" ADD CONSTRAINT "archive_photo_face_photo_id_archive_photo_id_fk" FOREIGN KEY ("photo_id") REFERENCES "public"."archive_photo"("id") ON DELETE cascade ON UPDATE no action;
|
||||
CREATE INDEX "archive_photo_face_photo_idx" ON "archive_photo_face" USING btree ("photo_id");
|
||||
CREATE INDEX "archive_photo_face_model_idx" ON "archive_photo_face" USING btree ("model");
|
||||
CREATE INDEX "archive_photo_face_updated_at_idx" ON "archive_photo_face" USING btree ("updated_at");
|
||||
CREATE INDEX "archive_photo_face_created_at_idx" ON "archive_photo_face" USING btree ("created_at");
|
||||
ALTER TABLE "payload_locked_documents_rels" ADD CONSTRAINT "payload_locked_documents_rels_archive_photo_face_fk" FOREIGN KEY ("archive_photo_face_id") REFERENCES "public"."archive_photo_face"("id") ON DELETE cascade ON UPDATE no action;
|
||||
CREATE INDEX "payload_locked_documents_rels_archive_photo_face_id_idx" ON "payload_locked_documents_rels" USING btree ("archive_photo_face_id");
|
||||
ALTER TABLE "payload_locked_documents_rels" DROP COLUMN "face_subject_id";
|
||||
DROP TYPE "public"."enum_face_subject_status";`)
|
||||
}
|
||||
|
||||
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
CREATE TYPE "public"."enum_face_subject_status" AS ENUM('active', 'removed');
|
||||
CREATE TABLE "face_subject" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"label" varchar NOT NULL,
|
||||
"consent_id" integer NOT NULL,
|
||||
"consent_hash" varchar,
|
||||
"model" varchar,
|
||||
"enrolled_at" timestamp(3) with time zone,
|
||||
"vector" jsonb,
|
||||
"status" "enum_face_subject_status" DEFAULT 'active' NOT NULL,
|
||||
"removed_at" timestamp(3) with time zone,
|
||||
"updated_at" timestamp(3) with time zone DEFAULT now() NOT NULL,
|
||||
"created_at" timestamp(3) with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE "face_subject_rels" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"order" integer,
|
||||
"parent_id" integer NOT NULL,
|
||||
"path" varchar NOT NULL,
|
||||
"archive_photo_id" integer
|
||||
);
|
||||
|
||||
ALTER TABLE "archive_photo_face" DISABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE "payload_locked_documents_rels" DROP CONSTRAINT "payload_locked_documents_rels_archive_photo_face_fk";
|
||||
DROP INDEX "payload_locked_documents_rels_archive_photo_face_id_idx";
|
||||
DROP TABLE "archive_photo_face" CASCADE;
|
||||
ALTER TABLE "payload_locked_documents_rels" ADD COLUMN "face_subject_id" integer;
|
||||
ALTER TABLE "face_subject" ADD CONSTRAINT "face_subject_consent_id_consent_id_fk" FOREIGN KEY ("consent_id") REFERENCES "public"."consent"("id") ON DELETE set null ON UPDATE no action;
|
||||
ALTER TABLE "face_subject_rels" ADD CONSTRAINT "face_subject_rels_parent_fk" FOREIGN KEY ("parent_id") REFERENCES "public"."face_subject"("id") ON DELETE cascade ON UPDATE no action;
|
||||
ALTER TABLE "face_subject_rels" ADD CONSTRAINT "face_subject_rels_archive_photo_fk" FOREIGN KEY ("archive_photo_id") REFERENCES "public"."archive_photo"("id") ON DELETE cascade ON UPDATE no action;
|
||||
CREATE INDEX "face_subject_consent_idx" ON "face_subject" USING btree ("consent_id");
|
||||
CREATE INDEX "face_subject_status_idx" ON "face_subject" USING btree ("status");
|
||||
CREATE INDEX "face_subject_updated_at_idx" ON "face_subject" USING btree ("updated_at");
|
||||
CREATE INDEX "face_subject_created_at_idx" ON "face_subject" USING btree ("created_at");
|
||||
CREATE INDEX "face_subject_rels_order_idx" ON "face_subject_rels" USING btree ("order");
|
||||
CREATE INDEX "face_subject_rels_parent_idx" ON "face_subject_rels" USING btree ("parent_id");
|
||||
CREATE INDEX "face_subject_rels_path_idx" ON "face_subject_rels" USING btree ("path");
|
||||
CREATE INDEX "face_subject_rels_archive_photo_id_idx" ON "face_subject_rels" USING btree ("archive_photo_id");
|
||||
ALTER TABLE "payload_locked_documents_rels" ADD CONSTRAINT "payload_locked_documents_rels_face_subject_fk" FOREIGN KEY ("face_subject_id") REFERENCES "public"."face_subject"("id") ON DELETE cascade ON UPDATE no action;
|
||||
CREATE INDEX "payload_locked_documents_rels_face_subject_id_idx" ON "payload_locked_documents_rels" USING btree ("face_subject_id");
|
||||
ALTER TABLE "payload_locked_documents_rels" DROP COLUMN "archive_photo_face_id";`)
|
||||
}
|
||||
|
|
@ -91,6 +91,7 @@ import * as migration_20260926_062039_add_archive_photo from './20260926_062039_
|
|||
import * as migration_20260926_132106_add_archive_photo_catalog from './20260926_132106_add_archive_photo_catalog';
|
||||
import * as migration_20260926_163248_add_archive_photo_publication from './20260926_163248_add_archive_photo_publication';
|
||||
import * as migration_20260927_193954_add_face_subject from './20260927_193954_add_face_subject';
|
||||
import * as migration_20261001_040904_add_archive_photo_face from './20261001_040904_add_archive_photo_face';
|
||||
|
||||
export const migrations = [
|
||||
{
|
||||
|
|
@ -556,6 +557,11 @@ export const migrations = [
|
|||
{
|
||||
up: migration_20260927_193954_add_face_subject.up,
|
||||
down: migration_20260927_193954_add_face_subject.down,
|
||||
name: '20260927_193954_add_face_subject'
|
||||
name: '20260927_193954_add_face_subject',
|
||||
},
|
||||
{
|
||||
up: migration_20261001_040904_add_archive_photo_face.up,
|
||||
down: migration_20261001_040904_add_archive_photo_face.down,
|
||||
name: '20261001_040904_add_archive_photo_face'
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -96,7 +96,7 @@ export interface Config {
|
|||
contentPiece: ContentPiece;
|
||||
contentMedia: ContentMedia;
|
||||
archivePhoto: ArchivePhoto;
|
||||
faceSubject: FaceSubject;
|
||||
archivePhotoFace: ArchivePhotoFace;
|
||||
contentEvent: ContentEvent;
|
||||
recording: Recording;
|
||||
recordingMedia: RecordingMedia;
|
||||
|
|
@ -154,7 +154,7 @@ export interface Config {
|
|||
contentPiece: ContentPieceSelect<false> | ContentPieceSelect<true>;
|
||||
contentMedia: ContentMediaSelect<false> | ContentMediaSelect<true>;
|
||||
archivePhoto: ArchivePhotoSelect<false> | ArchivePhotoSelect<true>;
|
||||
faceSubject: FaceSubjectSelect<false> | FaceSubjectSelect<true>;
|
||||
archivePhotoFace: ArchivePhotoFaceSelect<false> | ArchivePhotoFaceSelect<true>;
|
||||
contentEvent: ContentEventSelect<false> | ContentEventSelect<true>;
|
||||
recording: RecordingSelect<false> | RecordingSelect<true>;
|
||||
recordingMedia: RecordingMediaSelect<false> | RecordingMediaSelect<true>;
|
||||
|
|
@ -1585,33 +1585,22 @@ export interface ArchivePhoto {
|
|||
focalY?: number | null;
|
||||
}
|
||||
/**
|
||||
* Pessoas que consentiram entrar no índice da busca por selfie (/fotos/encontre). Operado pela CLI faces:enroll/faces:index; a remoção é registrada no status.
|
||||
* Índice facial anônimo do acervo público aprovado (C242). Operado pela CLI faces:index; o descriptor nunca é exposto.
|
||||
*
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "faceSubject".
|
||||
* via the `definition` "archivePhotoFace".
|
||||
*/
|
||||
export interface FaceSubject {
|
||||
export interface ArchivePhotoFace {
|
||||
id: number;
|
||||
/**
|
||||
* Como a assessoria identifica a pessoa; nunca aparece no site.
|
||||
* Foto aprovada em que o rosto foi detectado.
|
||||
*/
|
||||
label: string;
|
||||
photo: number | ArchivePhoto;
|
||||
/**
|
||||
* O Consent da adesão ao índice (chave estável busca-selfie-indice).
|
||||
* Modelo do descriptor (troca de modelo invalida a revisão e o lote reprocessa).
|
||||
*/
|
||||
consent: number | Consent;
|
||||
/**
|
||||
* Snapshot do texto aceito no enrollment; se o texto mudar, a pessoa fica inelegível até re-consentir.
|
||||
*/
|
||||
consentHash?: string | null;
|
||||
/**
|
||||
* Modelo do descriptor (troca de modelo invalida o índice: re-enrollment).
|
||||
*/
|
||||
model?: string | null;
|
||||
/**
|
||||
* Muda a cada enrollment/re-enrollment; é o que marca o lote como stale (o updated_at muda também quando o lote escreve os vínculos).
|
||||
*/
|
||||
enrolledAt?: string | null;
|
||||
model: string;
|
||||
detectedAt?: string | null;
|
||||
vector?:
|
||||
| {
|
||||
[k: string]: unknown;
|
||||
|
|
@ -1621,18 +1610,6 @@ export interface FaceSubject {
|
|||
| number
|
||||
| boolean
|
||||
| null;
|
||||
/**
|
||||
* Removida: pedido de saída atendido — o vetor é apagado e a pessoa deixa de ser encontrada.
|
||||
*/
|
||||
status: 'active' | 'removed';
|
||||
/**
|
||||
* Data do atendimento da saída do índice.
|
||||
*/
|
||||
removedAt?: string | null;
|
||||
/**
|
||||
* Derivado do lote (pnpm faces:index): fotos aprovadas em que o descriptor foi encontrado.
|
||||
*/
|
||||
matchedPhotos?: (number | ArchivePhoto)[] | null;
|
||||
updatedAt: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
|
@ -2471,8 +2448,8 @@ export interface PayloadLockedDocument {
|
|||
value: number | ArchivePhoto;
|
||||
} | null)
|
||||
| ({
|
||||
relationTo: 'faceSubject';
|
||||
value: number | FaceSubject;
|
||||
relationTo: 'archivePhotoFace';
|
||||
value: number | ArchivePhotoFace;
|
||||
} | null)
|
||||
| ({
|
||||
relationTo: 'contentEvent';
|
||||
|
|
@ -3286,18 +3263,13 @@ export interface ArchivePhotoSelect<T extends boolean = true> {
|
|||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "faceSubject_select".
|
||||
* via the `definition` "archivePhotoFace_select".
|
||||
*/
|
||||
export interface FaceSubjectSelect<T extends boolean = true> {
|
||||
label?: T;
|
||||
consent?: T;
|
||||
consentHash?: T;
|
||||
export interface ArchivePhotoFaceSelect<T extends boolean = true> {
|
||||
photo?: T;
|
||||
model?: T;
|
||||
enrolledAt?: T;
|
||||
detectedAt?: T;
|
||||
vector?: T;
|
||||
status?: T;
|
||||
removedAt?: T;
|
||||
matchedPhotos?: T;
|
||||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
}
|
||||
|
|
@ -4191,7 +4163,7 @@ export interface TaskCreateCollectionExport {
|
|||
| 'contentPiece'
|
||||
| 'contentMedia'
|
||||
| 'archivePhoto'
|
||||
| 'faceSubject'
|
||||
| 'archivePhotoFace'
|
||||
| 'contentEvent'
|
||||
| 'recording'
|
||||
| 'recordingMedia'
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ import { pt } from 'payload/i18n/pt'
|
|||
import { Activity } from './collections/Activity'
|
||||
import { AllocationDecision } from './collections/AllocationDecision'
|
||||
import { ArchivePhoto } from './collections/ArchivePhoto'
|
||||
import { ArchivePhotoFace } from './collections/ArchivePhotoFace'
|
||||
import { CalendarFeed } from './collections/CalendarFeed'
|
||||
import { CampaignDemand } from './collections/CampaignDemand'
|
||||
import { CampaignInvite } from './collections/CampaignInvite'
|
||||
|
|
@ -26,7 +27,6 @@ import { ContentPiece } from './collections/ContentPiece'
|
|||
import { ElectionCandidate } from './collections/ElectionCandidate'
|
||||
import { ElectionCandidateVote } from './collections/ElectionCandidateVote'
|
||||
import { ElectionTally } from './collections/ElectionTally'
|
||||
import { FaceSubject } from './collections/FaceSubject'
|
||||
import { GoogleCalendarSync } from './collections/GoogleCalendarSync'
|
||||
import { InternetSpeechMedia } from './collections/InternetSpeechMedia'
|
||||
import { Jingle } from './collections/Jingle'
|
||||
|
|
@ -140,7 +140,7 @@ export default buildConfig({
|
|||
ContentPiece,
|
||||
ContentMedia,
|
||||
ArchivePhoto,
|
||||
FaceSubject,
|
||||
ArchivePhotoFace,
|
||||
ContentEvent,
|
||||
Recording,
|
||||
RecordingMedia,
|
||||
|
|
|
|||
|
|
@ -1,23 +1,13 @@
|
|||
import 'server-only'
|
||||
|
||||
import { createHash } from 'node:crypto'
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import type { Payload } from 'payload'
|
||||
import type { Payload, PayloadRequest } from 'payload'
|
||||
import sharp from 'sharp'
|
||||
|
||||
import { ARCHIVE_PHOTO_SLUG } from '@/lib/archivePhoto'
|
||||
import {
|
||||
FACE_SEARCH_MAX_DISTANCE,
|
||||
FACE_SEARCH_MODEL,
|
||||
faceEuclideanDistance,
|
||||
readFaceVector,
|
||||
} from '@/lib/faceSearch'
|
||||
import {
|
||||
listFaceSubjects,
|
||||
type FaceSubjectSummary,
|
||||
} from '@/utilities/faceSubjects/faceSubjectReads'
|
||||
import { FACE_SEARCH_MODEL, readFaceVector } from '@/lib/faceSearch'
|
||||
import { messageOf } from '@/utilities/media/ffmpeg'
|
||||
import { withPayloadTransaction } from '@/utilities/payloadTransaction'
|
||||
import {
|
||||
|
|
@ -26,18 +16,19 @@ import {
|
|||
} from '@/utilities/privateMedia/privateMediaResponse'
|
||||
|
||||
/**
|
||||
* C234 — the batch index of the selfie search (`pnpm faces:index`). For every
|
||||
* approved photo it downloads the private original, prepares a small RGB image
|
||||
* and asks the INJECTED analyzer (the same face-api engine the browser runs)
|
||||
* for the descriptors of every face. The descriptors are TRANSIENT — they are
|
||||
* compared against the enrolled subjects and thrown away; only the
|
||||
* photo↔subject links are persisted, inside one transaction per photo. That is
|
||||
* the A/C line of the gate: there is no anonymous face index anywhere.
|
||||
* C242 — the batch owner of the anonymous face index (`pnpm faces:index`). For
|
||||
* every approved photo it downloads the private original, prepares a small RGB
|
||||
* image and asks the INJECTED analyzer (the same face-api engine the browser
|
||||
* runs) for the descriptors of every face; the descriptors are PERSISTED as
|
||||
* identity-free rows in `archivePhotoFace` (scope B, decision of 2026-10-01:
|
||||
* any visitor can find themselves). One photo's rows are replaced atomically —
|
||||
* never merged with a previous revision.
|
||||
*
|
||||
* Skipping is honest by construction: the photo's `faces.checkedKey` records
|
||||
* the model plus the enrollment revision (`enrolledAt`) of every eligible
|
||||
* subject, so a new/updated/removed subject invalidates every photo and the
|
||||
* next run recomputes — while the batch's own writes never change the key.
|
||||
* the model that produced the stored descriptors, so a model change marks every
|
||||
* photo stale and the next run recomputes. The batch's own writes never change
|
||||
* the key (`context.faceIndex` skips the catalog derivation and the marker
|
||||
* write does not read it back).
|
||||
*
|
||||
* A failure of one photo is returned, never thrown: nothing is written, the
|
||||
* next run retries it and the receipt names the stage.
|
||||
|
|
@ -46,7 +37,7 @@ import {
|
|||
/** Long edge sent to the engine; the original never leaves the archive. */
|
||||
const IMAGE_MAX_EDGE = 1024
|
||||
|
||||
export type ArchivePhotoFaceImage = {
|
||||
type ArchivePhotoFaceImage = {
|
||||
pixels: Buffer
|
||||
width: number
|
||||
height: number
|
||||
|
|
@ -57,10 +48,10 @@ export type ArchivePhotoFaceAnalyzer = (image: ArchivePhotoFaceImage) => Promise
|
|||
|
||||
/**
|
||||
* Decodes any stored image (EXIF-rotated, alpha flattened, ≤1024px raw RGB) —
|
||||
* the exact input both the batch and the enrollment CLI hand to the engine, so
|
||||
* the exact input both the batch and the browser compute descriptors over, so
|
||||
* the selfie and the archive enter the same space.
|
||||
*/
|
||||
export const prepareFaceImage = async (filePath: string): Promise<ArchivePhotoFaceImage> => {
|
||||
const prepareFaceImage = async (filePath: string): Promise<ArchivePhotoFaceImage> => {
|
||||
const prepared = await sharp(filePath)
|
||||
.rotate()
|
||||
.resize({ width: IMAGE_MAX_EDGE, height: IMAGE_MAX_EDGE, fit: 'inside' })
|
||||
|
|
@ -80,8 +71,6 @@ export type ArchivePhotoFaceIndexItem = {
|
|||
export type ArchivePhotoFaceIndexQueue = {
|
||||
/** The revision every processed photo is stamped with. */
|
||||
indexKey: string
|
||||
/** Subjects the batch will look for (`active` + current model + vector). */
|
||||
eligibleSubjects: number
|
||||
totalApproved: number
|
||||
/** Approved photos whose `faces.checkedKey` is not the current revision. */
|
||||
stale: number
|
||||
|
|
@ -90,39 +79,17 @@ export type ArchivePhotoFaceIndexQueue = {
|
|||
}
|
||||
|
||||
export type ArchivePhotoFaceIndexResult =
|
||||
| { status: 'indexed'; matchedSubjects: number[] }
|
||||
| { status: 'indexed'; descriptorCount: number }
|
||||
| {
|
||||
status: 'failed'
|
||||
stage: 'download' | 'image' | 'analyze' | 'write'
|
||||
error: string
|
||||
}
|
||||
|
||||
const isIndexableSubject = (subject: FaceSubjectSummary): boolean =>
|
||||
subject.status === 'active' &&
|
||||
subject.model === FACE_SEARCH_MODEL &&
|
||||
readFaceVector(subject.vector) !== null
|
||||
|
||||
/**
|
||||
* The revision stamped on each processed photo: the model plus the enrollment
|
||||
* revision of every indexable subject. Deliberately ignores `updatedAt` (the
|
||||
* batch writes `matchedPhotos`, which would bump it and make every photo stale
|
||||
* forever) and ignores removed/stale subjects (they are not searched).
|
||||
*/
|
||||
const facePhotoIndexKey = (subjects: readonly FaceSubjectSummary[]): string => {
|
||||
const revisions = subjects
|
||||
.filter(isIndexableSubject)
|
||||
.map((subject) => `${subject.id}:${subject.enrolledAt ?? ''}`)
|
||||
.sort()
|
||||
|
||||
return createHash('sha256')
|
||||
.update([FACE_SEARCH_MODEL, ...revisions].join('\n'))
|
||||
.digest('hex')
|
||||
}
|
||||
|
||||
/**
|
||||
* The batch queue: the approved photos with their marker, the subjects that
|
||||
* will be searched, and the revision to stamp. `refresh` ignores the marker;
|
||||
* `limit` caps only the returned work list (the counts stay true).
|
||||
* The batch queue: the approved photos with their marker and the revision to
|
||||
* stamp. `refresh` ignores the marker; `limit` caps only the returned work list
|
||||
* (the counts stay true).
|
||||
*/
|
||||
export const listArchivePhotoFaceIndexQueue = async ({
|
||||
payload,
|
||||
|
|
@ -133,8 +100,7 @@ export const listArchivePhotoFaceIndexQueue = async ({
|
|||
refresh?: boolean
|
||||
limit?: number
|
||||
}): Promise<ArchivePhotoFaceIndexQueue> => {
|
||||
const subjects = await listFaceSubjects(payload)
|
||||
const indexKey = facePhotoIndexKey(subjects)
|
||||
const indexKey = FACE_SEARCH_MODEL
|
||||
|
||||
const photos = await payload.find({
|
||||
collection: ARCHIVE_PHOTO_SLUG,
|
||||
|
|
@ -157,7 +123,6 @@ export const listArchivePhotoFaceIndexQueue = async ({
|
|||
|
||||
return {
|
||||
indexKey,
|
||||
eligibleSubjects: subjects.filter(isIndexableSubject).length,
|
||||
totalApproved: photos.docs.length,
|
||||
stale: staleRows.length,
|
||||
items: limit && limit > 0 ? staleRows.slice(0, limit) : staleRows,
|
||||
|
|
@ -165,10 +130,9 @@ export const listArchivePhotoFaceIndexQueue = async ({
|
|||
}
|
||||
|
||||
/**
|
||||
* One photo: download → prepare → analyze → transactional link update + marker.
|
||||
* The fresh subject read happens INSIDE the transaction, so an enrollment that
|
||||
* lands mid-run is respected (the photo is simply reprocessed by the changed
|
||||
* key on a later run).
|
||||
* One photo: download → prepare → analyze → transactional descriptor replace +
|
||||
* marker. The rows of the previous revision are deleted inside the same
|
||||
* transaction, so a query never sees a half-replaced photo.
|
||||
*/
|
||||
export const indexArchivePhotoFaces = async ({
|
||||
payload,
|
||||
|
|
@ -214,13 +178,13 @@ export const indexArchivePhotoFaces = async ({
|
|||
}
|
||||
|
||||
try {
|
||||
const matchedSubjects = await writeArchivePhotoFaceMatches({
|
||||
const descriptorCount = await writeArchivePhotoFaceDescriptors({
|
||||
payload,
|
||||
photoId: item.id,
|
||||
descriptors,
|
||||
indexKey,
|
||||
})
|
||||
return { status: 'indexed', matchedSubjects }
|
||||
return { status: 'indexed', descriptorCount }
|
||||
} catch (error) {
|
||||
return { status: 'failed', stage: 'write', error: messageOf(error, 'erro desconhecido') }
|
||||
}
|
||||
|
|
@ -230,11 +194,12 @@ export const indexArchivePhotoFaces = async ({
|
|||
}
|
||||
|
||||
/**
|
||||
* Replaces the links of one photo for every eligible subject and stamps the
|
||||
* marker — one transaction with a fresh read, so a concurrent enrollment or
|
||||
* takedown never meets a half-written state.
|
||||
* Replaces the descriptor rows of one photo and stamps the marker — one
|
||||
* transaction, so a concurrent takedown or search never meets a half-written
|
||||
* photo. Invalid descriptors are dropped (fail-closed) instead of poisoning the
|
||||
* index.
|
||||
*/
|
||||
const writeArchivePhotoFaceMatches = async ({
|
||||
export const writeArchivePhotoFaceDescriptors = async ({
|
||||
payload,
|
||||
photoId,
|
||||
descriptors,
|
||||
|
|
@ -242,35 +207,35 @@ const writeArchivePhotoFaceMatches = async ({
|
|||
}: {
|
||||
payload: Payload
|
||||
photoId: number
|
||||
descriptors: number[][]
|
||||
descriptors: readonly number[][]
|
||||
indexKey: string
|
||||
}): Promise<number[]> =>
|
||||
withPayloadTransaction(payload, async ({ req }) => {
|
||||
const subjects = await listFaceSubjects(payload, req)
|
||||
const matchedSubjects: number[] = []
|
||||
}): Promise<number> => {
|
||||
const vectors = descriptors
|
||||
.map((descriptor) => readFaceVector(descriptor))
|
||||
.filter((vector): vector is number[] => vector !== null)
|
||||
|
||||
for (const subject of subjects) {
|
||||
if (!isIndexableSubject(subject)) continue
|
||||
const write = async (writeReq?: { transactionID?: number | string }) => {
|
||||
await payload.delete({
|
||||
collection: 'archivePhotoFace',
|
||||
where: { photo: { equals: photoId } },
|
||||
depth: 0,
|
||||
req: writeReq,
|
||||
// Intentional bypass: the batch CLI is a trusted operator with no session.
|
||||
overrideAccess: true,
|
||||
})
|
||||
|
||||
const vector = readFaceVector(subject.vector)
|
||||
if (!vector) continue
|
||||
const matched = descriptors.some(
|
||||
(descriptor) => faceEuclideanDistance(descriptor, vector) < FACE_SEARCH_MAX_DISTANCE,
|
||||
)
|
||||
const linked = subject.matchedPhotoIds.includes(photoId)
|
||||
if (matched) matchedSubjects.push(subject.id)
|
||||
if (matched === linked) continue
|
||||
|
||||
const next = matched
|
||||
? [...subject.matchedPhotoIds, photoId]
|
||||
: subject.matchedPhotoIds.filter((id) => id !== photoId)
|
||||
await payload.update({
|
||||
collection: 'faceSubject',
|
||||
id: subject.id,
|
||||
data: { matchedPhotos: next },
|
||||
for (const vector of vectors) {
|
||||
await payload.create({
|
||||
collection: 'archivePhotoFace',
|
||||
data: {
|
||||
photo: photoId,
|
||||
model: indexKey,
|
||||
detectedAt: new Date().toISOString(),
|
||||
vector,
|
||||
},
|
||||
depth: 0,
|
||||
req,
|
||||
// Intentional bypass: the batch CLI is a trusted operator with no session.
|
||||
req: writeReq,
|
||||
// Intentional bypass: same trusted operator.
|
||||
overrideAccess: true,
|
||||
})
|
||||
}
|
||||
|
|
@ -280,11 +245,39 @@ const writeArchivePhotoFaceMatches = async ({
|
|||
id: photoId,
|
||||
data: { faces: { checkedAt: new Date().toISOString(), checkedKey: indexKey } },
|
||||
depth: 0,
|
||||
req,
|
||||
req: writeReq,
|
||||
context: { faceIndex: true },
|
||||
// Intentional bypass: the batch CLI is a trusted operator with no session.
|
||||
// Intentional bypass: same trusted operator.
|
||||
overrideAccess: true,
|
||||
})
|
||||
}
|
||||
|
||||
return matchedSubjects
|
||||
return withPayloadTransaction(payload, async ({ req }) => {
|
||||
await write(req)
|
||||
return vectors.length
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Purges every descriptor row of one photo. Called by the photo lifecycle hooks
|
||||
* when a photo stops being `approved` (unapproval/removal) and on deletion — the
|
||||
* DB-level FK cascade covers direct SQL deletes, this covers the Local API path.
|
||||
*/
|
||||
export const purgeFaceDescriptorsForPhoto = async ({
|
||||
payload,
|
||||
photoId,
|
||||
req,
|
||||
}: {
|
||||
payload: Payload
|
||||
photoId: number
|
||||
req?: PayloadRequest
|
||||
}): Promise<void> => {
|
||||
await payload.delete({
|
||||
collection: 'archivePhotoFace',
|
||||
where: { photo: { equals: photoId } },
|
||||
depth: 0,
|
||||
req,
|
||||
// Intentional bypass: lifecycle maintenance, never an actor-bound write.
|
||||
overrideAccess: true,
|
||||
})
|
||||
}
|
||||
158
src/utilities/faceIndex/faceDescriptorReads.ts
Normal file
158
src/utilities/faceIndex/faceDescriptorReads.ts
Normal file
|
|
@ -0,0 +1,158 @@
|
|||
import 'server-only'
|
||||
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import {
|
||||
FACE_SEARCH_MAX_DISTANCE,
|
||||
FACE_SEARCH_MODEL,
|
||||
faceEuclideanDistance,
|
||||
findFaceDescriptorPhotoIds,
|
||||
readFaceVector,
|
||||
type FaceDescriptorEntry,
|
||||
} from '@/lib/faceSearch'
|
||||
|
||||
/**
|
||||
* C242 — reads of the anonymous face index. The collection is admin-only and
|
||||
* machine-written, so every read is the Local API without a user (the same
|
||||
* anonymous-read bypass precedent as `archivePhotoReads`): the SELECTOR is the
|
||||
* search request itself, never an actor.
|
||||
*
|
||||
* The full set is loaded once per short window into an in-process cache
|
||||
* (`Float32Array` descriptors): the ranking is exact and linear — no pgvector
|
||||
* (C229 precedent) — and the TTL keeps an opt-out or a new index run visible
|
||||
* without a deploy. The opt-out path never uses the cache: it re-reads and
|
||||
* deletes in the same pass, because "leave-index" must take effect immediately.
|
||||
*/
|
||||
|
||||
/** How long a loaded index answers before a re-read; short on purpose. */
|
||||
const INDEX_CACHE_TTL_MS = 60_000
|
||||
|
||||
/**
|
||||
* Defensive ceiling: the flat cache costs ~600 bytes per face, so half a
|
||||
* million faces would be ~300 MB. Past the cap the search fails closed rather
|
||||
* than answering from a truncated index. The real archive (~6.5k photos) sits
|
||||
* orders of magnitude below it.
|
||||
*/
|
||||
const MAX_INDEXED_DESCRIPTORS = 300_000
|
||||
|
||||
type FaceDescriptorCache = {
|
||||
loadedAt: number
|
||||
entries: FaceDescriptorEntry[]
|
||||
}
|
||||
|
||||
let descriptorCache: FaceDescriptorCache | null = null
|
||||
|
||||
/** Test seam: a fresh read after a fixture write in the same process. */
|
||||
export const invalidateFaceDescriptorIndex = (): void => {
|
||||
descriptorCache = null
|
||||
}
|
||||
|
||||
const relationId = (value: unknown): number | null => {
|
||||
if (typeof value === 'number') return value
|
||||
if (value && typeof value === 'object' && 'id' in value && typeof value.id === 'number') {
|
||||
return value.id
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const loadFaceDescriptorIndexFromDb = async (payload: Payload): Promise<FaceDescriptorEntry[]> => {
|
||||
const result = await payload.find({
|
||||
collection: 'archivePhotoFace',
|
||||
where: { model: { equals: FACE_SEARCH_MODEL } },
|
||||
depth: 0,
|
||||
limit: 0,
|
||||
pagination: false,
|
||||
select: { photo: true, vector: true },
|
||||
// Intentional bypass: the search endpoint answers anonymous requests and
|
||||
// the selector is the consent-gated query itself, never an actor.
|
||||
overrideAccess: true,
|
||||
})
|
||||
|
||||
if (result.docs.length > MAX_INDEXED_DESCRIPTORS) {
|
||||
throw new Error(
|
||||
`Índice facial acima do teto defensivo (${result.docs.length} > ${MAX_INDEXED_DESCRIPTORS}).`,
|
||||
)
|
||||
}
|
||||
|
||||
const entries: FaceDescriptorEntry[] = []
|
||||
for (const doc of result.docs) {
|
||||
const photoId = relationId(doc.photo)
|
||||
const vector = readFaceVector(doc.vector)
|
||||
if (photoId === null || vector === null) continue
|
||||
entries.push({ photoId, vector: Float32Array.from(vector) })
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
/** The current index, from the short-lived in-process cache when fresh. */
|
||||
export const loadFaceDescriptorIndex = async (payload: Payload): Promise<FaceDescriptorEntry[]> => {
|
||||
const now = Date.now()
|
||||
if (descriptorCache && now - descriptorCache.loadedAt < INDEX_CACHE_TTL_MS) {
|
||||
return descriptorCache.entries
|
||||
}
|
||||
|
||||
const entries = await loadFaceDescriptorIndexFromDb(payload)
|
||||
descriptorCache = { loadedAt: now, entries }
|
||||
return entries
|
||||
}
|
||||
|
||||
/**
|
||||
* The distinct approved-photo ids the query vector matches, in index order.
|
||||
* Pure math on the loaded index; the caller intersects with the approved album
|
||||
* read (draft/removed never leave this function as a result).
|
||||
*/
|
||||
export const findMatchedFacePhotoIds = ({
|
||||
vector,
|
||||
entries,
|
||||
}: {
|
||||
vector: ArrayLike<number>
|
||||
entries: readonly FaceDescriptorEntry[]
|
||||
}): number[] => findFaceDescriptorPhotoIds(vector, entries)
|
||||
|
||||
/**
|
||||
* Opt-out ("leave-index"): the person's own descriptor is the authorization —
|
||||
* every indexed face under the threshold is deleted and the person stops being
|
||||
* found. Reads and deletes in one pass, never from the cache; returns how many
|
||||
* faces were erased (never which photos: the answer is not a score nor a list
|
||||
* of third-party places).
|
||||
*/
|
||||
export const deleteFaceDescriptorMatches = async ({
|
||||
payload,
|
||||
vector,
|
||||
}: {
|
||||
payload: Payload
|
||||
vector: ArrayLike<number>
|
||||
}): Promise<number> => {
|
||||
const result = await payload.find({
|
||||
collection: 'archivePhotoFace',
|
||||
where: { model: { equals: FACE_SEARCH_MODEL } },
|
||||
depth: 0,
|
||||
limit: 0,
|
||||
pagination: false,
|
||||
select: { vector: true },
|
||||
// Intentional bypass: same anonymous-request rationale as the load above;
|
||||
// the deletion itself is authorized by the matched descriptor.
|
||||
overrideAccess: true,
|
||||
})
|
||||
|
||||
const matchedIds: number[] = []
|
||||
for (const doc of result.docs) {
|
||||
const stored = readFaceVector(doc.vector)
|
||||
if (!stored) continue
|
||||
if (faceEuclideanDistance(vector, stored) < FACE_SEARCH_MAX_DISTANCE) {
|
||||
matchedIds.push(doc.id)
|
||||
}
|
||||
}
|
||||
if (matchedIds.length === 0) return 0
|
||||
|
||||
await payload.delete({
|
||||
collection: 'archivePhotoFace',
|
||||
where: { id: { in: matchedIds } },
|
||||
depth: 0,
|
||||
// Intentional bypass: the search endpoint is anonymous and the removal is
|
||||
// authorized by the matched descriptor, never by a session.
|
||||
overrideAccess: true,
|
||||
})
|
||||
invalidateFaceDescriptorIndex()
|
||||
return matchedIds.length
|
||||
}
|
||||
|
|
@ -1,102 +0,0 @@
|
|||
import 'server-only'
|
||||
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import { FACE_SEARCH_MODEL, readFaceVector } from '@/lib/faceSearch'
|
||||
|
||||
/**
|
||||
* C234 — writes of the subject lifecycle: enrollment (one row per person who
|
||||
* adhered to the search index — A/C scope of the gate) and the removal that
|
||||
* serves the person's own opt-out. Enrollment is called only by
|
||||
* `pnpm faces:enroll`, after the CLI has proven the selfie has exactly one
|
||||
* detectable face and resolved the enrollment Consent by its stable key; the
|
||||
* removal is called by the search endpoint after the request's descriptor
|
||||
* matched the subject (the face IS the authentication). Neither path takes the
|
||||
* descriptor from any other source and the row is never public.
|
||||
*
|
||||
* Re-enrollment (`subjectId`) replaces the descriptor, refreshes the consent
|
||||
* snapshot and clears the derived links: the previous matches belong to the
|
||||
* previous descriptor and must never survive it. `enrolledAt` also advances —
|
||||
* it is the batch's staleness key, so the next `faces:index` recomputes.
|
||||
*/
|
||||
export type FaceSubjectEnrollmentInput = {
|
||||
payload: Payload
|
||||
label: string
|
||||
descriptor: readonly number[]
|
||||
consent: { id: number; contentHash: string }
|
||||
subjectId?: number | null
|
||||
}
|
||||
|
||||
export type FaceSubjectEnrollment = {
|
||||
id: number
|
||||
created: boolean
|
||||
}
|
||||
|
||||
export const enrollFaceSubject = async ({
|
||||
payload,
|
||||
label,
|
||||
descriptor,
|
||||
consent,
|
||||
subjectId,
|
||||
}: FaceSubjectEnrollmentInput): Promise<FaceSubjectEnrollment> => {
|
||||
const vector = readFaceVector(descriptor)
|
||||
if (!vector) throw new Error('Descriptor inválido para enrollment.')
|
||||
|
||||
const data = {
|
||||
label,
|
||||
consent: consent.id,
|
||||
consentHash: consent.contentHash,
|
||||
model: FACE_SEARCH_MODEL,
|
||||
vector,
|
||||
enrolledAt: new Date().toISOString(),
|
||||
status: 'active' as const,
|
||||
removedAt: null,
|
||||
matchedPhotos: [] as number[],
|
||||
}
|
||||
|
||||
// Intentional bypass: the enrollment CLI is a trusted operator with no
|
||||
// session; the descriptor is validated above and never crosses the wire.
|
||||
const common = { depth: 0 as const, overrideAccess: true }
|
||||
|
||||
if (subjectId != null) {
|
||||
const updated = await payload.update({
|
||||
collection: 'faceSubject',
|
||||
id: subjectId,
|
||||
data,
|
||||
...common,
|
||||
})
|
||||
return { id: updated.id, created: false }
|
||||
}
|
||||
|
||||
const created = await payload.create({ collection: 'faceSubject', data, ...common })
|
||||
return { id: created.id, created: true }
|
||||
}
|
||||
|
||||
/**
|
||||
* Opt-out: the subject stops answering (the query checks `status`) and stops
|
||||
* holding biometrics (the vector and the derived links are erased). The row
|
||||
* itself stays as the attendance record. One row, one update — atomic by
|
||||
* itself, no transaction needed.
|
||||
*/
|
||||
export const removeFaceSubjectFromIndex = async ({
|
||||
payload,
|
||||
id,
|
||||
}: {
|
||||
payload: Payload
|
||||
id: number
|
||||
}): Promise<void> => {
|
||||
await payload.update({
|
||||
collection: 'faceSubject',
|
||||
id,
|
||||
data: {
|
||||
status: 'removed',
|
||||
vector: null,
|
||||
removedAt: new Date().toISOString(),
|
||||
matchedPhotos: [],
|
||||
},
|
||||
depth: 0,
|
||||
// Intentional bypass: the search endpoint is anonymous and the removal is
|
||||
// authorized by the matched descriptor, never by a session.
|
||||
overrideAccess: true,
|
||||
})
|
||||
}
|
||||
|
|
@ -1,136 +0,0 @@
|
|||
import 'server-only'
|
||||
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import type { FaceSearchSubject } from '@/lib/faceSearch'
|
||||
|
||||
/**
|
||||
* C234 — server reads of the enrolled subjects behind the selfie search. The
|
||||
* collection is admin-only, so every read here is the Local API without a user
|
||||
* (the documented anonymous-read bypass, same precedent as
|
||||
* `archivePhotoReads`): the SELECTOR is the search request itself, never an
|
||||
* actor. The rows are few (one per adhered person) and the search must see the
|
||||
* live state — no cache, so an opt-out stops answering immediately.
|
||||
*/
|
||||
|
||||
/** A relationship value at depth 0 is the id; tolerate the populated shape. */
|
||||
const relationIds = (value: unknown): number[] => {
|
||||
if (!Array.isArray(value)) return []
|
||||
|
||||
const ids: number[] = []
|
||||
for (const entry of value) {
|
||||
if (typeof entry === 'number') {
|
||||
ids.push(entry)
|
||||
continue
|
||||
}
|
||||
if (entry && typeof entry === 'object' && 'id' in entry && typeof entry.id === 'number') {
|
||||
ids.push(entry.id)
|
||||
}
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
export type FaceSubjectSummary = {
|
||||
id: number
|
||||
status: string | null
|
||||
model: string | null
|
||||
consentHash: string | null
|
||||
enrolledAt: string | null
|
||||
vector: unknown
|
||||
matchedPhotoIds: number[]
|
||||
}
|
||||
|
||||
type FaceSubjectDoc = {
|
||||
id: number
|
||||
status?: string | null
|
||||
model?: string | null
|
||||
consentHash?: string | null
|
||||
enrolledAt?: string | null
|
||||
vector?: unknown
|
||||
matchedPhotos?: unknown
|
||||
}
|
||||
|
||||
const toSummary = (doc: FaceSubjectDoc): FaceSubjectSummary => ({
|
||||
id: doc.id,
|
||||
status: doc.status ?? null,
|
||||
model: doc.model ?? null,
|
||||
consentHash: doc.consentHash ?? null,
|
||||
enrolledAt: doc.enrolledAt ?? null,
|
||||
vector: doc.vector,
|
||||
matchedPhotoIds: relationIds(doc.matchedPhotos),
|
||||
})
|
||||
|
||||
const faceSubjectSelect = {
|
||||
status: true,
|
||||
model: true,
|
||||
consentHash: true,
|
||||
enrolledAt: true,
|
||||
vector: true,
|
||||
matchedPhotos: true,
|
||||
} as const
|
||||
|
||||
/** Every subject (any status) — the CLI inventory and the batch's fresh read. */
|
||||
export const listFaceSubjects = async (
|
||||
payload: Payload,
|
||||
req?: { transactionID?: number | string },
|
||||
): Promise<FaceSubjectSummary[]> => {
|
||||
const result = await payload.find({
|
||||
collection: 'faceSubject',
|
||||
sort: ['id'],
|
||||
depth: 0,
|
||||
limit: 0,
|
||||
pagination: false,
|
||||
select: faceSubjectSelect,
|
||||
// Intentional bypass: subjects are admin-only configuration and both the
|
||||
// search (anonymous request) and the CLI (no session) must read them.
|
||||
overrideAccess: true,
|
||||
req,
|
||||
})
|
||||
|
||||
return result.docs.map((doc) => toSummary(doc as FaceSubjectDoc))
|
||||
}
|
||||
|
||||
/** Active subjects only — the candidate set of one search. */
|
||||
export const listSearchableFaceSubjects = async (
|
||||
payload: Payload,
|
||||
): Promise<FaceSearchSubject[]> => {
|
||||
const result = await payload.find({
|
||||
collection: 'faceSubject',
|
||||
where: { status: { equals: 'active' } },
|
||||
sort: ['id'],
|
||||
depth: 0,
|
||||
limit: 0,
|
||||
pagination: false,
|
||||
select: { status: true, model: true, consentHash: true, vector: true },
|
||||
// Intentional bypass: the search endpoint answers anonymous requests and
|
||||
// the selector is the consent-gated query itself, never an actor.
|
||||
overrideAccess: true,
|
||||
})
|
||||
|
||||
return result.docs.map((doc) => ({
|
||||
id: doc.id,
|
||||
status: doc.status ?? null,
|
||||
model: doc.model ?? null,
|
||||
consentHash: doc.consentHash ?? null,
|
||||
vector: doc.vector,
|
||||
}))
|
||||
}
|
||||
|
||||
/** The approved photos linked to one subject (the search answer). */
|
||||
export const getFaceSubjectMatchedPhotoIds = async (
|
||||
payload: Payload,
|
||||
id: number,
|
||||
): Promise<number[]> => {
|
||||
const doc = await payload
|
||||
.findByID({
|
||||
collection: 'faceSubject',
|
||||
id,
|
||||
depth: 0,
|
||||
select: { matchedPhotos: true },
|
||||
// Intentional bypass: same anonymous-read rationale as the list above.
|
||||
overrideAccess: true,
|
||||
})
|
||||
.catch(() => null)
|
||||
|
||||
return relationIds((doc as FaceSubjectDoc | null)?.matchedPhotos)
|
||||
}
|
||||
|
|
@ -6,6 +6,10 @@ import {
|
|||
shareLinkPath,
|
||||
type ShareLinkLiveTarget,
|
||||
} from '@/lib/shareLink'
|
||||
import {
|
||||
buildShareLinkHomeSectionView,
|
||||
type ShareLinkHomeSectionView,
|
||||
} from '@/lib/shareLinkHomeSection'
|
||||
import { getCollectionListingTag } from '@/utilities/documents'
|
||||
import { getCachedGlobal } from '@/utilities/globalReads'
|
||||
import { resolveOgImage } from '@/utilities/ogImageReads'
|
||||
|
|
@ -50,6 +54,38 @@ export const getCachedPublishedShareLinkBySlug = (slug: string, depth = 1) =>
|
|||
},
|
||||
)
|
||||
|
||||
export type ShareLinkHomeSectionData = {
|
||||
view: ShareLinkHomeSectionView
|
||||
initialLive: ShareLinkLiveTarget | null
|
||||
}
|
||||
|
||||
/**
|
||||
* S44 — the home section read: the same cached listing read as the announcement
|
||||
* page (tag `shareLinks`, so unpublishing pulls the section without a deploy),
|
||||
* plus the canonical URL the agenda needs and the destination already on air
|
||||
* (so a visitor arriving during the live gets the embed/CTA in the HTML). The
|
||||
* event window decides visibility here — a closed window (or a missing start)
|
||||
* returns `null` and the home never renders the section.
|
||||
*/
|
||||
export const loadShareLinkHomeSection = async (
|
||||
slug: string,
|
||||
): Promise<ShareLinkHomeSectionData | null> => {
|
||||
const link = await getCachedPublishedShareLinkBySlug(slug, 1)()
|
||||
if (!link) return null
|
||||
|
||||
const image = typeof link.image === 'object' ? link.image : null
|
||||
const canonicalUrl = await resolveShareLinkCanonicalUrl(slug)
|
||||
const view = buildShareLinkHomeSectionView({
|
||||
link,
|
||||
imageUrl: image?.url ?? null,
|
||||
canonicalUrl: canonicalUrl ?? null,
|
||||
nowMs: Date.now(),
|
||||
})
|
||||
if (!view) return null
|
||||
|
||||
return { view, initialLive: resolveLiveShareLinkDestination(link.destinations) }
|
||||
}
|
||||
|
||||
export const resolveShareLinkCanonicalUrl = async (slug: string): Promise<string | undefined> => {
|
||||
const globalMetadata = await getCachedGlobal('metadata')()
|
||||
const { siteUrl } = resolveSiteMetadata(globalMetadata)
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
import { YOUTUBE_VIDEO_ID_PATTERN } from '@/lib/shareLink'
|
||||
|
||||
/**
|
||||
* Validation for `socialFeedSettings.excludedItems[].itemId` (the campaign home
|
||||
* content board's manual exclusion list). The field is an array row: Payload
|
||||
|
|
@ -5,9 +7,8 @@
|
|||
* validate must read the platform from `siblingData` (the previous
|
||||
* `validate` read `data.platform`, which is the whole document and therefore
|
||||
* always `undefined` — dead code that never validated anything in production).
|
||||
* The YouTube id contract itself lives in `lib/shareLink` (single owner).
|
||||
*/
|
||||
export const YOUTUBE_VIDEO_ID_PATTERN = /^[A-Za-z0-9_-]{11}$/
|
||||
|
||||
export const validateExcludedItemId = (
|
||||
value: string | null | undefined,
|
||||
siblingData?: { platform?: string },
|
||||
|
|
|
|||
|
|
@ -1,7 +1,12 @@
|
|||
import { formatBahiaCivilDate, parseBahiaDateTimeInput } from '../../src/lib/campaignTime.js'
|
||||
import { hookFilledCreateData } from '../../src/utilities/hookFilledData.js'
|
||||
import { campaignPageChrome, expect, test } from './fixtures/campaignE2EFixtures.js'
|
||||
import { civilDatePlusDays, dayLabelFor, ptBrMonthNames } from './helpers/agendaPeriodLabels.js'
|
||||
import {
|
||||
calendarDaySelector,
|
||||
civilDatePlusDays,
|
||||
dayLabelFor,
|
||||
ptBrMonthNames,
|
||||
} from './helpers/agendaPeriodLabels.js'
|
||||
|
||||
/**
|
||||
* Agenda prologue shared by every journey in this file: opens the agenda
|
||||
|
|
@ -342,17 +347,14 @@ test.describe('Agenda — calendário operacional', () => {
|
|||
// Multi-day: the end picker lands on a later day, always +1 from today:
|
||||
// the target stays inside the picker's visible grid (an inside day, or
|
||||
// day 1 of the next month as an outside day) — no hardcoded dates (C134).
|
||||
// The button label is date-fns pt-BR "PPPP" ("sexta-feira, 14 de agosto
|
||||
// de 2026"): day without leading zero, month in lowercase — the string
|
||||
// name matcher is case-insensitive, the day number is not.
|
||||
const [endYear, endMonth, endDay] = civilDatePlusDays(
|
||||
formatBahiaCivilDate(new Date()),
|
||||
1,
|
||||
).split('-')
|
||||
const endDayLabel = `${Number(endDay)} de ${ptBrMonthNames[Number(endMonth) - 1]} de ${endYear}`
|
||||
// The cell is clicked by its `data-day` contract, not by the accessible
|
||||
// name: "d de mês de ano" is a substring of "1d…"/"2d… de mês de ano"
|
||||
// and name matching would resolve to several cells (C104 miss #55).
|
||||
const endCivilDate = civilDatePlusDays(formatBahiaCivilDate(new Date()), 1)
|
||||
const [endYear, endMonth, endDay] = endCivilDate.split('-')
|
||||
await page.getByRole('button', { name: 'Término', exact: true }).click()
|
||||
const endPicker = page.locator('[data-slot="popover-content"][data-state="open"]').last()
|
||||
await endPicker.getByRole('button', { name: endDayLabel }).click()
|
||||
await endPicker.locator(calendarDaySelector(endCivilDate)).click()
|
||||
await page.keyboard.press('Escape')
|
||||
await expect(page.getByRole('button', { name: 'Término', exact: true })).toHaveText(
|
||||
`${endDay}/${endMonth}/${endYear}`,
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { COLINHA_ROW_LAYOUT } from '@/lib/cardColinha'
|
|||
import { TEAM_CARD_NAME_BANNER } from '@/lib/cardModels'
|
||||
|
||||
import { adminHeaders } from '../helpers/adminApi'
|
||||
import { waitForHomeHTML, waitForHomeSection } from '../helpers/homeIsr'
|
||||
import { seedTestUser } from '../helpers/seedUser'
|
||||
import { instagramStubUrlFor, youtubeStubUrlFor } from '../helpers/socialStub'
|
||||
import { expect, test } from './fixtures/e2eTest'
|
||||
|
|
@ -768,43 +769,14 @@ test.describe('Campaign home content section', () => {
|
|||
return doc
|
||||
}
|
||||
|
||||
// ISR serves the stale page while it regenerates after a revalidateTag
|
||||
// (slower under the parallel suite), and a navigation that lands on it never
|
||||
// refreshes its DOM. Poll the server HTML positively until it converges to
|
||||
// the expected substring state (section presence or actual content, e.g.
|
||||
// video titles); the navigation that follows then always lands on the fresh
|
||||
// page. 12 attempts preserves the S1 convergence budget.
|
||||
const waitForHomeHTML = async (
|
||||
request: APIRequestContext,
|
||||
includes: string[],
|
||||
excludes: string[] = [],
|
||||
attempts = 12,
|
||||
) => {
|
||||
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
||||
const response = await request.get(`${baseURL}/`).catch(() => undefined)
|
||||
if (response?.ok()) {
|
||||
const html = await response.text()
|
||||
const allIncluded = includes.every((needle) => html.includes(needle))
|
||||
const anyExcluded = excludes.some((needle) => html.includes(needle))
|
||||
if (allIncluded && !anyExcluded) return
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 1_000))
|
||||
}
|
||||
throw new Error(
|
||||
`A home não convergiu após ${attempts}s (includes: ${includes.join(', ')}, excludes: ${excludes.join(', ')}).`,
|
||||
)
|
||||
}
|
||||
|
||||
// S39/S44 — the ISR poll lives in `tests/helpers/homeIsr.ts` (shared by the
|
||||
// specs that own home sections); this spec keeps the `contents` specialization.
|
||||
const waitForHomeSectionState = async (
|
||||
request: APIRequestContext,
|
||||
expected: 'present' | 'absent',
|
||||
attempts = 12,
|
||||
) => {
|
||||
if (expected === 'present') {
|
||||
await waitForHomeHTML(request, ['data-home-section="contents"'], [], attempts)
|
||||
} else {
|
||||
await waitForHomeHTML(request, [], ['data-home-section="contents"'], attempts)
|
||||
}
|
||||
await waitForHomeSection(request, baseURL, 'contents', expected, attempts)
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -1159,6 +1131,7 @@ test.describe('Campaign home content section', () => {
|
|||
try {
|
||||
await waitForHomeHTML(
|
||||
request,
|
||||
baseURL,
|
||||
['E2e Vídeo em destaque', 'E2e Artigo no mix'],
|
||||
['E2e Vídeo excluído'],
|
||||
)
|
||||
|
|
@ -1242,6 +1215,7 @@ test.describe('Campaign home content section', () => {
|
|||
// section (page never breaks, no error shown).
|
||||
await waitForHomeHTML(
|
||||
request,
|
||||
baseURL,
|
||||
['E2e Artigo fallback', 'YouTube →'],
|
||||
['E2e Vídeo em destaque'],
|
||||
)
|
||||
|
|
@ -1278,7 +1252,7 @@ test.describe('Campaign home content section', () => {
|
|||
|
||||
try {
|
||||
// Live fetch succeeds and persists the raw snapshot.
|
||||
await waitForHomeHTML(request, ['E2e Vídeo em destaque'], ['E2e Vídeo excluído'])
|
||||
await waitForHomeHTML(request, baseURL, ['E2e Vídeo em destaque'], ['E2e Vídeo excluído'])
|
||||
await gotoHomeFresh(page)
|
||||
await expect(page.getByRole('link', { name: /E2e Vídeo em destaque/ }).first()).toBeVisible()
|
||||
await page.goto('about:blank')
|
||||
|
|
@ -1298,6 +1272,7 @@ test.describe('Campaign home content section', () => {
|
|||
})
|
||||
await waitForHomeHTML(
|
||||
request,
|
||||
baseURL,
|
||||
['E2e Vídeo em destaque', 'E2e Vídeo de caravana'],
|
||||
['E2e Vídeo de entrevista'],
|
||||
)
|
||||
|
|
@ -1311,7 +1286,7 @@ test.describe('Campaign home content section', () => {
|
|||
// API back: the live feed returns with the original cap.
|
||||
await setYouTubeStubState(request, 'ok')
|
||||
await updateSocialFeedSettings(request, headers, baseSettings)
|
||||
await waitForHomeHTML(request, ['E2e Vídeo de entrevista'], ['E2e Vídeo excluído'])
|
||||
await waitForHomeHTML(request, baseURL, ['E2e Vídeo de entrevista'], ['E2e Vídeo excluído'])
|
||||
await gotoHomeFresh(page)
|
||||
await expect(page.getByText('E2e Vídeo de entrevista').first()).toBeVisible()
|
||||
await page.goto('about:blank')
|
||||
|
|
@ -1364,6 +1339,7 @@ test.describe('Campaign home content section', () => {
|
|||
try {
|
||||
await waitForHomeHTML(
|
||||
request,
|
||||
baseURL,
|
||||
['E2e Post do muro', 'E2e Artigo no mix IG'],
|
||||
['E2e Post de grade', 'YouTube →'],
|
||||
)
|
||||
|
|
@ -1464,6 +1440,7 @@ test.describe('Campaign home content section', () => {
|
|||
// breaks, no error shown).
|
||||
await waitForHomeHTML(
|
||||
request,
|
||||
baseURL,
|
||||
['E2e Artigo fallback IG'],
|
||||
['E2e Post do muro', 'Seguir no Instagram'],
|
||||
)
|
||||
|
|
@ -1506,7 +1483,7 @@ test.describe('Campaign home content section', () => {
|
|||
|
||||
try {
|
||||
// Live fetch succeeds and persists the raw snapshot (with the username).
|
||||
await waitForHomeHTML(request, ['E2e Post do muro'], ['E2e Post de grade'])
|
||||
await waitForHomeHTML(request, baseURL, ['E2e Post do muro'], ['E2e Post de grade'])
|
||||
await gotoHomeFresh(page)
|
||||
await expect(page.getByRole('link', { name: /E2e Post do muro/ }).first()).toBeVisible()
|
||||
await page.goto('about:blank')
|
||||
|
|
@ -1527,6 +1504,7 @@ test.describe('Campaign home content section', () => {
|
|||
})
|
||||
await waitForHomeHTML(
|
||||
request,
|
||||
baseURL,
|
||||
['E2e Post do muro', 'E2e Reel da caravana', 'Seguir no Instagram'],
|
||||
['Publicação no Instagram'],
|
||||
)
|
||||
|
|
@ -1541,7 +1519,7 @@ test.describe('Campaign home content section', () => {
|
|||
// API back: the live feed returns with the original cap.
|
||||
await setInstagramStubState(request, 'ok')
|
||||
await updateSocialFeedSettings(request, headers, baseSettings)
|
||||
await waitForHomeHTML(request, ['Publicação no Instagram'], ['E2e Post de grade'])
|
||||
await waitForHomeHTML(request, baseURL, ['Publicação no Instagram'], ['E2e Post de grade'])
|
||||
await gotoHomeFresh(page)
|
||||
await expect(page.getByText('Publicação no Instagram').first()).toBeVisible()
|
||||
await page.goto('about:blank')
|
||||
|
|
@ -1595,6 +1573,7 @@ test.describe('Campaign home content section', () => {
|
|||
// section lives on.
|
||||
await waitForHomeHTML(
|
||||
request,
|
||||
baseURL,
|
||||
['E2e Artigo kill switch'],
|
||||
['E2e Vídeo em destaque', 'YouTube →', 'E2e Post do muro', 'Seguir no Instagram'],
|
||||
)
|
||||
|
|
@ -1658,7 +1637,11 @@ test.describe('Campaign home content section', () => {
|
|||
await context.grantPermissions(['clipboard-read', 'clipboard-write'])
|
||||
|
||||
try {
|
||||
await waitForHomeHTML(request, [articleTitle, 'E2e Vídeo em destaque', 'E2e Post do muro'])
|
||||
await waitForHomeHTML(request, baseURL, [
|
||||
articleTitle,
|
||||
'E2e Vídeo em destaque',
|
||||
'E2e Post do muro',
|
||||
])
|
||||
await page.setViewportSize({ width: 1280, height: 900 })
|
||||
await gotoHomeFresh(page)
|
||||
const section = page.locator('[data-home-section="contents"]')
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import { getMunicipalityCatalogEntry } from '../../src/lib/municipalityCatalog.j
|
|||
import { slugify } from '../../src/lib/slug.js'
|
||||
import { adminHeaders } from '../helpers/adminApi'
|
||||
import { interiorPointOf } from '../helpers/featureBounds'
|
||||
import { waitForHomeSection } from '../helpers/homeIsr'
|
||||
import { seedTestUser } from '../helpers/seedUser'
|
||||
import { expect, test } from './fixtures/e2eTest'
|
||||
|
||||
|
|
@ -234,28 +235,6 @@ const waitForSettledPage = async (page: Page) => {
|
|||
await page.waitForFunction(() => document.querySelectorAll('div[id^="S:"]').length === 0)
|
||||
}
|
||||
|
||||
/**
|
||||
* S39 — the home is ISR and the section is gated by the same listing tag as the
|
||||
* catalogue; poll the server HTML until the kill switch converged (the
|
||||
* navigation that follows always lands on the fresh page).
|
||||
*/
|
||||
const waitForHomeSection = async (
|
||||
request: APIRequestContext,
|
||||
expected: 'present' | 'absent',
|
||||
attempts = 12,
|
||||
) => {
|
||||
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
||||
const response = await request.get(`${BASE_URL}/`).catch(() => undefined)
|
||||
if (response?.ok()) {
|
||||
const html = await response.text()
|
||||
const present = html.includes('data-home-section="content-pieces"')
|
||||
if ((expected === 'present') === present) return
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 1_000))
|
||||
}
|
||||
throw new Error(`A seção da Central não convergiu para "${expected}" em ${attempts}s.`)
|
||||
}
|
||||
|
||||
test.describe.configure({ mode: 'serial' })
|
||||
|
||||
// C226 — the still of a video piece is asked for before the play and answers
|
||||
|
|
@ -740,7 +719,7 @@ test.describe('Frontend Central de Conteúdos (S27)', () => {
|
|||
await createPiece(request, headers, { title: photoTitle, type: 'foto' })
|
||||
await createPiece(request, headers, { title: videoTitle, type: 'video' })
|
||||
|
||||
await waitForHomeSection(request, 'present')
|
||||
await waitForHomeSection(request, BASE_URL, 'content-pieces', 'present')
|
||||
|
||||
await page.setViewportSize({ width: 390, height: 844 })
|
||||
await page.goto(`/?e2e=${Date.now()}`)
|
||||
|
|
@ -805,7 +784,7 @@ test.describe('Frontend Central de Conteúdos (S27)', () => {
|
|||
expect(overflow).toBeLessThanOrEqual(1)
|
||||
|
||||
await unpublishEveryPiece(request, headers)
|
||||
await waitForHomeSection(request, 'absent')
|
||||
await waitForHomeSection(request, BASE_URL, 'content-pieces', 'absent')
|
||||
await page.goto(`/?e2e=${Date.now()}`)
|
||||
await expect(page.locator('[data-home-section="content-pieces"]')).toHaveCount(0)
|
||||
})
|
||||
|
|
@ -838,7 +817,7 @@ test.describe('Frontend Central de Conteúdos (S27)', () => {
|
|||
|
||||
const title = `Peça de Feira de Santana ${uniqueMarker()}`
|
||||
await createPiece(request, headers, { title, type: 'foto', municipality: municipality.id })
|
||||
await waitForHomeSection(request, 'present')
|
||||
await waitForHomeSection(request, BASE_URL, 'content-pieces', 'present')
|
||||
|
||||
await context.grantPermissions(['geolocation'])
|
||||
await context.setGeolocation({ latitude: point.lat, longitude: point.lng })
|
||||
|
|
|
|||
|
|
@ -8,24 +8,24 @@ import {
|
|||
FACE_SEARCH_CONSENT_KEY,
|
||||
} from '../../src/lib/campaignConsentKeys.js'
|
||||
import { FACE_SEARCH_MODEL, faceStubDescriptorFromBytes } from '../../src/lib/faceSearch.js'
|
||||
import { hashConsentContent } from '../../src/utilities/consentContentHash.js'
|
||||
import { adminHeaders } from '../helpers/adminApi'
|
||||
import { seedTestUser } from '../helpers/seedUser'
|
||||
import { waitForStreamSettled } from './fixtures/campaignE2EFixtures'
|
||||
import { expect, test } from './fixtures/e2eTest'
|
||||
|
||||
/**
|
||||
* C234 — the selfie search over real HTTP: the entry gated by the album flag,
|
||||
* the Consent fail-closed, the A/C answer (only the enrolled subject's approved
|
||||
* photos, never a third-party name), the honest empty and the opt-out by
|
||||
* matched descriptor. The engine is the deterministic stub
|
||||
* (`NEXT_PUBLIC_FACE_SEARCH_STUB=1`): the fixture bytes derive the descriptor
|
||||
* the seeded subject carries, so no model is ever downloaded.
|
||||
* C242 — the selfie search over real HTTP: the entry gated by the album flag,
|
||||
* the Consent fail-closed, the scope B answer (anonymous descriptors of
|
||||
* approved photos only, never a third-party name), the honest empty, the
|
||||
* opt-out by matched descriptor and the homepage discovery section (C243). The
|
||||
* engine is the deterministic stub (`NEXT_PUBLIC_FACE_SEARCH_STUB=1`): the
|
||||
* fixture bytes derive the descriptor the seeded face rows carry, so no model
|
||||
* is ever downloaded.
|
||||
*
|
||||
* Rows are seeded through the deployed REST API (admin session) so the server
|
||||
* process runs the real hooks. Serial: this spec owns its faceSubject/Consent
|
||||
* rows and flips the same `photoAlbum` global as the C233 spec (the project
|
||||
* depends on `frontendFotos`).
|
||||
* process runs the real hooks. Serial: this spec owns its archivePhotoFace/
|
||||
* Consent rows and flips the same `photoAlbum` global as the C233 spec (the
|
||||
* project depends on `frontendFotos`).
|
||||
*/
|
||||
|
||||
const BASE_URL = process.env.PLAYWRIGHT_BASE_URL ?? 'http://localhost:3000'
|
||||
|
|
@ -34,7 +34,6 @@ const REMOVAL_CHANNEL = 'https://example.org/acervo/remocao'
|
|||
type Headers = Record<string, string>
|
||||
|
||||
const createdPhotoIds: number[] = []
|
||||
const createdSubjectIds: number[] = []
|
||||
const createdConsentKeys = new Set<string>()
|
||||
|
||||
const uniqueMarker = () => randomUUID().slice(0, 8)
|
||||
|
|
@ -134,38 +133,36 @@ const ensureConsent = async (
|
|||
return { id: doc.id, text: doc.text }
|
||||
}
|
||||
|
||||
const createSubject = async (
|
||||
/** One anonymous descriptor row, exactly like the batch writes it. */
|
||||
const createFaceRow = async (
|
||||
request: APIRequestContext,
|
||||
headers: Headers,
|
||||
data: { vector: number[]; consentId: number; consentHash: string; matchedPhotos: number[] },
|
||||
data: { photo: number; vector: number[] },
|
||||
): Promise<number> => {
|
||||
const response = await request.post(`${BASE_URL}/api/faceSubject`, {
|
||||
const response = await request.post(`${BASE_URL}/api/archivePhotoFace`, {
|
||||
headers,
|
||||
data: {
|
||||
label: `Pessoa de teste ${uniqueMarker()}`,
|
||||
consent: data.consentId,
|
||||
consentHash: data.consentHash,
|
||||
photo: data.photo,
|
||||
model: FACE_SEARCH_MODEL,
|
||||
detectedAt: new Date().toISOString(),
|
||||
vector: data.vector,
|
||||
enrolledAt: new Date().toISOString(),
|
||||
status: 'active',
|
||||
matchedPhotos: data.matchedPhotos,
|
||||
},
|
||||
})
|
||||
expect(response.ok(), await response.text()).toBeTruthy()
|
||||
const id = ((await response.json()) as { doc: { id: number } }).doc.id
|
||||
createdSubjectIds.push(id)
|
||||
return id
|
||||
return ((await response.json()) as { doc: { id: number } }).doc.id
|
||||
}
|
||||
|
||||
const faceSubjectById = async (
|
||||
const faceRowsOf = async (
|
||||
request: APIRequestContext,
|
||||
headers: Headers,
|
||||
id: number,
|
||||
): Promise<{ status: string; vector: unknown }> => {
|
||||
const response = await request.get(`${BASE_URL}/api/faceSubject/${id}?depth=0`, { headers })
|
||||
photoId: number,
|
||||
): Promise<number> => {
|
||||
const response = await request.get(
|
||||
`${BASE_URL}/api/archivePhotoFace?limit=0&depth=0&where[photo][equals]=${photoId}`,
|
||||
{ headers },
|
||||
)
|
||||
expect(response.ok(), await response.text()).toBeTruthy()
|
||||
return (await response.json()) as { status: string; vector: unknown }
|
||||
return ((await response.json()) as { totalDocs: number }).totalDocs
|
||||
}
|
||||
|
||||
/** Consent card → pick screen with the given fixture, ready for the primary action. */
|
||||
|
|
@ -183,11 +180,8 @@ const reachPickWithFixture = async (
|
|||
|
||||
test.describe.configure({ mode: 'serial' })
|
||||
|
||||
test.describe('Frontend busca por selfie (C234)', () => {
|
||||
test.describe('Frontend busca por selfie (C242)', () => {
|
||||
let headers: Headers
|
||||
let indexConsent: { id: number; text: unknown }
|
||||
let indexConsentHash: string
|
||||
let subjectId: number
|
||||
let linkedPhoto: number
|
||||
let draftLinkedPhoto: number
|
||||
let otherPhoto: number
|
||||
|
|
@ -213,8 +207,7 @@ test.describe('Frontend busca por selfie (C234)', () => {
|
|||
selfieB.buffer = await jpegWithFill('77')
|
||||
|
||||
await ensureConsent(request, headers, FACE_SEARCH_CONSENT_KEY)
|
||||
indexConsent = await ensureConsent(request, headers, FACE_INDEX_CONSENT_KEY)
|
||||
indexConsentHash = hashConsentContent(indexConsent.text)
|
||||
await ensureConsent(request, headers, FACE_INDEX_CONSENT_KEY)
|
||||
|
||||
await setAlbum(request, headers, {
|
||||
published: true,
|
||||
|
|
@ -230,22 +223,16 @@ test.describe('Frontend busca por selfie (C234)', () => {
|
|||
data: { publicationStatus: 'draft' },
|
||||
})
|
||||
|
||||
subjectId = await createSubject(request, headers, {
|
||||
vector: faceStubDescriptorFromBytes(new Uint8Array(selfieA.buffer)),
|
||||
consentId: indexConsent.id,
|
||||
consentHash: indexConsentHash,
|
||||
matchedPhotos: [linkedPhoto, draftLinkedPhoto],
|
||||
})
|
||||
const descriptor = faceStubDescriptorFromBytes(new Uint8Array(selfieA.buffer))
|
||||
await createFaceRow(request, headers, { photo: linkedPhoto, vector: descriptor })
|
||||
// The draft row is seeded by hand on purpose: the search must intersect
|
||||
// the index with the approved public read and never surface it.
|
||||
await createFaceRow(request, headers, { photo: draftLinkedPhoto, vector: descriptor })
|
||||
})
|
||||
|
||||
test.afterAll(async ({ request }) => {
|
||||
const cleanupHeaders = await adminHeaders(request, BASE_URL).catch(() => null)
|
||||
if (cleanupHeaders) {
|
||||
for (const id of createdSubjectIds.splice(0)) {
|
||||
await request
|
||||
.delete(`${BASE_URL}/api/faceSubject/${id}`, { headers: cleanupHeaders })
|
||||
.catch(() => undefined)
|
||||
}
|
||||
for (const id of createdPhotoIds.splice(0)) {
|
||||
await request
|
||||
.delete(`${BASE_URL}/api/archivePhoto/${id}`, { headers: cleanupHeaders })
|
||||
|
|
@ -295,6 +282,23 @@ test.describe('Frontend busca por selfie (C234)', () => {
|
|||
await expect(primary).toBeEnabled()
|
||||
})
|
||||
|
||||
test('shows the discovery section on the homepage while the search is open (C243)', async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.goto('/')
|
||||
await waitForStreamSettled(page)
|
||||
|
||||
const section = page.getByRole('region', { name: 'Encontre você nas fotos' })
|
||||
await expect(section).toBeVisible()
|
||||
await expect(
|
||||
section.getByRole('link', { name: 'Encontrar minhas fotos' }).first(),
|
||||
).toHaveAttribute('href', '/fotos/encontre')
|
||||
await expect(section.getByRole('link', { name: 'Ver o álbum' }).first()).toHaveAttribute(
|
||||
'href',
|
||||
'/fotos',
|
||||
)
|
||||
})
|
||||
|
||||
test('finds only the approved photos of the matched subject, without third-party names', async ({
|
||||
page,
|
||||
}) => {
|
||||
|
|
@ -373,11 +377,13 @@ test.describe('Frontend busca por selfie (C234)', () => {
|
|||
|
||||
await expect(page.getByRole('heading', { name: 'Confirmar saída do índice?' })).toBeVisible()
|
||||
await page.getByRole('button', { name: 'Confirmar saída do índice' }).click()
|
||||
await expect(page.getByRole('heading', { name: 'Pronto — você saiu do índice' })).toBeVisible()
|
||||
await expect(
|
||||
page.getByRole('heading', { name: 'Pronto — seu rosto saiu do índice' }),
|
||||
).toBeVisible()
|
||||
|
||||
const subject = await faceSubjectById(request, headers, subjectId)
|
||||
expect(subject.status).toBe('removed')
|
||||
expect(subject.vector).toBeNull()
|
||||
// The person's face rows are gone from the index (the search stops
|
||||
// answering); the photos themselves stay in the album.
|
||||
expect(await faceRowsOf(request, headers, linkedPhoto)).toBe(0)
|
||||
})
|
||||
|
||||
test('fails the engine honestly when the local processing breaks', async ({ page }) => {
|
||||
|
|
@ -429,6 +435,11 @@ test.describe('Frontend busca por selfie (C234)', () => {
|
|||
await waitForStreamSettled(page)
|
||||
await expect(page.getByRole('link', { name: 'Começar busca por selfie' })).toHaveCount(0)
|
||||
|
||||
// C243 — closed leaves no dead CTA on the homepage either.
|
||||
await page.goto('/')
|
||||
await waitForStreamSettled(page)
|
||||
await expect(page.getByRole('region', { name: 'Encontre você nas fotos' })).toHaveCount(0)
|
||||
|
||||
// Through the API context on purpose: the browser would log the
|
||||
// document's own 404 and trip the console-error guard (same choice as
|
||||
// the C233 kill-switch test).
|
||||
|
|
|
|||
|
|
@ -10,7 +10,9 @@ import {
|
|||
formatBahiaEventDateLabel,
|
||||
parseBahiaDateTimeInput,
|
||||
} from '../../src/lib/campaignTime.js'
|
||||
import { SHARE_LINK_HOME_SECTION_SLUG } from '../../src/lib/shareLinkHomeSection.js'
|
||||
import { adminHeaders } from '../helpers/adminApi'
|
||||
import { waitForHomeHTML, waitForHomeSection } from '../helpers/homeIsr'
|
||||
import { metaContent } from '../helpers/metaContent'
|
||||
import { seedTestUser } from '../helpers/seedUser'
|
||||
import { expect, test } from './fixtures/e2eTest'
|
||||
|
|
@ -485,3 +487,196 @@ test.describe('Frontend share-link announcement (S29)', () => {
|
|||
}
|
||||
})
|
||||
})
|
||||
|
||||
test.describe('Frontend home Plenária section (S44)', () => {
|
||||
// The home section reads one FIXED slug (`plenaria-vitoria`), so this
|
||||
// describe is the only owner of those rows and runs serially — the other
|
||||
// specs keep their unique-slug fixtures untouched.
|
||||
test.describe.configure({ mode: 'serial' })
|
||||
|
||||
const HOME_SECTION_SLUG = SHARE_LINK_HOME_SECTION_SLUG
|
||||
const YOUTUBE_VIDEO_ID = '77bUgl7cvQ8'
|
||||
|
||||
test.beforeAll(async () => {
|
||||
await seedTestUser()
|
||||
})
|
||||
|
||||
const shareLinkIdsBySlug = async (
|
||||
request: APIRequestContext,
|
||||
headers: Record<string, string>,
|
||||
slug: string,
|
||||
): Promise<number[]> => {
|
||||
const response = await request.get(
|
||||
`${BASE_URL}/api/shareLink?where[slug][equals]=${encodeURIComponent(slug)}&limit=10&depth=0`,
|
||||
{ headers },
|
||||
)
|
||||
expect(response.ok(), await response.text()).toBeTruthy()
|
||||
const { docs } = (await response.json()) as { docs: Array<{ id: number }> }
|
||||
return docs.map((doc) => doc.id)
|
||||
}
|
||||
|
||||
/** Deletes any residue of the fixed slug (aborted runs) before each flow. */
|
||||
const resetHomeSectionLink = async (
|
||||
request: APIRequestContext,
|
||||
headers: Record<string, string>,
|
||||
) => {
|
||||
for (const id of await shareLinkIdsBySlug(request, headers, HOME_SECTION_SLUG)) {
|
||||
await request.delete(`${BASE_URL}/api/shareLink/${id}`, { headers })
|
||||
const index = createdShareLinkIds.indexOf(id)
|
||||
if (index >= 0) createdShareLinkIds.splice(index, 1)
|
||||
}
|
||||
}
|
||||
|
||||
const createHomeSectionLink = async (
|
||||
request: APIRequestContext,
|
||||
headers: Record<string, string>,
|
||||
overrides: Partial<ShareLinkInput> = {},
|
||||
): Promise<number> => {
|
||||
const image =
|
||||
overrides.image ?? (await createMedia(request, headers, 'Plenária da Vitória 1313'))
|
||||
return createShareLink(request, headers, {
|
||||
title: 'Plenária da Vitória',
|
||||
slug: HOME_SECTION_SLUG,
|
||||
destinations: [
|
||||
{ label: 'Google Meet', url: 'https://meet.google.com/fyz-rurx-biv' },
|
||||
{ label: 'Youtube', url: `https://www.youtube.com/live/${YOUTUBE_VIDEO_ID}` },
|
||||
],
|
||||
description: 'O time de Jorge Solla se encontra antes da vitória.',
|
||||
published: true,
|
||||
mode: 'announcement',
|
||||
startsAt: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
|
||||
location: 'Online',
|
||||
image,
|
||||
...overrides,
|
||||
})
|
||||
}
|
||||
|
||||
test('announces the plenária after the hero, swaps to the live player and hides on unpublish', async ({
|
||||
page,
|
||||
request,
|
||||
}) => {
|
||||
const headers = await adminHeaders(request, BASE_URL)
|
||||
await resetHomeSectionLink(request, headers)
|
||||
const id = await createHomeSectionLink(request, headers)
|
||||
|
||||
// Warm the poll route before the browser mounts it (the S29 dev-mode Fast
|
||||
// Refresh caveat: the first compile of the route reloads the open page).
|
||||
await request.get(`${BASE_URL}/api/share-link/${HOME_SECTION_SLUG}/live`)
|
||||
await waitForHomeSection(request, BASE_URL, 'plenaria', 'present')
|
||||
|
||||
await page.setViewportSize({ width: 390, height: 844 })
|
||||
await page.goto(`/?e2e=${Date.now()}`)
|
||||
|
||||
const section = page.locator('[data-home-section="plenaria"]')
|
||||
await expect(section).toBeVisible()
|
||||
|
||||
// S44 — immediately after the hero, before the proof strip.
|
||||
const order = await page
|
||||
.locator('[data-home-section]')
|
||||
.evaluateAll((sections) => sections.map((s) => s.getAttribute('data-home-section')))
|
||||
expect(order.indexOf('plenaria')).toBe(order.indexOf('hero') + 1)
|
||||
expect(order.indexOf('plenaria')).toBeLessThan(order.indexOf('proof'))
|
||||
|
||||
// Pré-live: the invitation with the S29 agenda and no entry button.
|
||||
await expect(section.getByRole('heading', { name: 'Plenária da Vitória' })).toBeVisible()
|
||||
await expect(section.getByText('Encontro online')).toBeVisible()
|
||||
await expect(
|
||||
section.getByText('O time de Jorge Solla se encontra antes da vitória.'),
|
||||
).toBeVisible()
|
||||
// Mobile inlines the timezone next to the time (the desktop keeps the small).
|
||||
await expect(section.getByText('(horário da Bahia)')).toBeVisible()
|
||||
await expect(section.getByText('Online', { exact: true })).toBeVisible()
|
||||
await expect(section.getByRole('link', { name: 'Assistir no YouTube' })).toHaveCount(0)
|
||||
await expect(section.getByRole('link', { name: 'Entrar na plenária' })).toHaveCount(0)
|
||||
|
||||
await section.getByRole('button', { name: 'Adicionar à agenda' }).click()
|
||||
// The popover is portaled to the body, outside the section subtree.
|
||||
await expect(page.getByRole('link', { name: /Google Agenda/ })).toHaveAttribute(
|
||||
'href',
|
||||
/calendar\.google\.com/,
|
||||
)
|
||||
await expect(page.getByRole('link', { name: /Baixar arquivo \.ics/ })).toHaveAttribute(
|
||||
'href',
|
||||
`/${HOME_SECTION_SLUG}/evento.ics`,
|
||||
)
|
||||
await page.keyboard.press('Escape')
|
||||
|
||||
const overflow = await page.evaluate(() => {
|
||||
const container = document.querySelector<HTMLElement>('[data-theme="campaign-site"]')
|
||||
return container ? container.scrollWidth - container.clientWidth : 0
|
||||
})
|
||||
expect(overflow).toBeLessThanOrEqual(1)
|
||||
|
||||
// The team flags the Meet on air through the test database (the poll
|
||||
// contract; the REST path would revalidate and race the open page).
|
||||
await flagLiveDestination(id, 'Google Meet')
|
||||
await page.evaluate(() => document.dispatchEvent(new Event('visibilitychange')))
|
||||
|
||||
await expect(section.getByText('Ao vivo agora')).toBeVisible({ timeout: 20_000 })
|
||||
await expect(section.getByRole('link', { name: 'Entrar na plenária' })).toHaveAttribute(
|
||||
'href',
|
||||
`/${HOME_SECTION_SLUG}`,
|
||||
)
|
||||
await expect(
|
||||
section.locator(`iframe[src*="youtube-nocookie.com/embed/${YOUTUBE_VIDEO_ID}"]`),
|
||||
).toBeAttached()
|
||||
await expect(section.getByRole('button', { name: 'Adicionar à agenda' })).toHaveCount(0)
|
||||
|
||||
// The YouTube takes over: only the label changes; the href stays canonical.
|
||||
await flagLiveDestination(id, 'Youtube')
|
||||
await page.evaluate(() => document.dispatchEvent(new Event('visibilitychange')))
|
||||
await expect(section.getByRole('link', { name: 'Assistir no YouTube' })).toHaveAttribute(
|
||||
'href',
|
||||
`/${HOME_SECTION_SLUG}`,
|
||||
)
|
||||
|
||||
// The same state written through the admin REST API (the collection hook
|
||||
// path) lands in the server HTML: whoever arrives now gets the live state
|
||||
// on first paint, without waiting for the poll.
|
||||
await setShareLinkDestinations(request, headers, id, [
|
||||
{ label: 'Google Meet', url: 'https://meet.google.com/fyz-rurx-biv' },
|
||||
{ label: 'Youtube', url: `https://www.youtube.com/live/${YOUTUBE_VIDEO_ID}`, live: true },
|
||||
])
|
||||
await waitForHomeHTML(request, BASE_URL, [
|
||||
'data-home-section="plenaria"',
|
||||
'Assistir no YouTube',
|
||||
])
|
||||
await page.goto(`/?e2e=${Date.now()}`)
|
||||
await expect(
|
||||
page
|
||||
.locator('[data-home-section="plenaria"]')
|
||||
.getByRole('link', { name: 'Assistir no YouTube' }),
|
||||
).toBeVisible()
|
||||
|
||||
// Kill switch: unpublishing the link pulls the section without a deploy.
|
||||
await setShareLinkPublished(request, headers, id, false)
|
||||
await waitForHomeSection(request, BASE_URL, 'plenaria', 'absent')
|
||||
await page.goto(`/?e2e=${Date.now()}`)
|
||||
await expect(page.locator('[data-home-section="plenaria"]')).toHaveCount(0)
|
||||
})
|
||||
|
||||
test('hides the section when the event window is closed and brings it back when it opens', async ({
|
||||
page,
|
||||
request,
|
||||
}) => {
|
||||
const headers = await adminHeaders(request, BASE_URL)
|
||||
await resetHomeSectionLink(request, headers)
|
||||
const id = await createHomeSectionLink(request, headers, {
|
||||
startsAt: new Date(Date.now() - 3 * 60 * 60 * 1000).toISOString(),
|
||||
})
|
||||
|
||||
// startsAt + 2h already passed: the section is absent from the HTML.
|
||||
await waitForHomeSection(request, BASE_URL, 'plenaria', 'absent')
|
||||
await page.goto(`/?e2e=${Date.now()}`)
|
||||
await expect(page.locator('[data-home-section="plenaria"]')).toHaveCount(0)
|
||||
|
||||
// Reopening the window (an end in the future) brings the section back.
|
||||
const endsAt = new Date(Date.now() + 60 * 60 * 1000).toISOString()
|
||||
const response = await request.patch(`${BASE_URL}/api/shareLink/${id}`, {
|
||||
headers,
|
||||
data: { endsAt },
|
||||
})
|
||||
expect(response.ok(), await response.text()).toBeTruthy()
|
||||
await waitForHomeSection(request, BASE_URL, 'plenaria', 'present')
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -36,6 +36,18 @@ const ptBrWeekdays = [
|
|||
export const dayLabelFor = (civilDate: string): string =>
|
||||
`${Number(civilDate.slice(8, 10))} ${ptBrMonthNames[Number(civilDate.slice(5, 7)) - 1]}`
|
||||
|
||||
/**
|
||||
* "[data-day=\"DD/MM/YYYY\"]" — the Calendar day cell's stable contract
|
||||
* (`Calendar.tsx` DayButton formats the civil date with the pt-BR locale).
|
||||
* Click day cells through this selector, never through the accessible name:
|
||||
* "2 de outubro de 2026" is a substring of "12…"/"22 de outubro de 2026",
|
||||
* so name matching resolves to several cells (strict mode violation).
|
||||
*/
|
||||
export const calendarDaySelector = (civilDate: string): string => {
|
||||
const [year, month, day] = civilDate.split('-')
|
||||
return `[data-day="${day}/${month}/${year}"]`
|
||||
}
|
||||
|
||||
export const civilDatePlusDays = (civilDate: string, days: number): string => {
|
||||
const [year, month, day] = civilDate.split('-').map(Number)
|
||||
const date = new Date(Date.UTC(year, month - 1, day + days))
|
||||
|
|
|
|||
|
|
@ -5,25 +5,21 @@ import { join } from 'node:path'
|
|||
import type { Payload } from 'payload'
|
||||
|
||||
import { ARCHIVE_PHOTO_SLUG, type ArchivePhotoImport } from '@/lib/archivePhoto'
|
||||
import { FACE_INDEX_CONSENT_KEY } from '@/lib/campaignConsentKeys'
|
||||
import { FACE_SEARCH_DESCRIPTOR_LENGTH } from '@/lib/faceSearch'
|
||||
import { getConsentByKey } from '@/utilities/campaignConsent'
|
||||
import { enrollFaceSubject } from '@/utilities/faceSubjects/faceSubjectEnrollment'
|
||||
import { FACE_SEARCH_DESCRIPTOR_LENGTH, FACE_SEARCH_MODEL } from '@/lib/faceSearch'
|
||||
import { writeArchivePhotoFaceDescriptors } from '@/utilities/faceIndex/faceDescriptorIndex'
|
||||
import { ingestArchivePhoto } from '@/utilities/flickr/archivePhotoIngest'
|
||||
|
||||
import { ARCHIVE_PHOTO_JPEG_BYTES } from './archivePhotoFixture'
|
||||
|
||||
/**
|
||||
* C234 — the fixtures shared by the face-search int specs (subject/index and
|
||||
* the API): the file-backed archive photo over the real Payload test database
|
||||
* and the enrolled subject. The two spec files serialize on the same lease
|
||||
* because the index revision is derived state over EVERY enrolled subject — an
|
||||
* enrollment in the sibling spec changes the key and would legitimately mark
|
||||
* photos stale mid-assertion.
|
||||
* C242 — the fixtures shared by the face-search int specs: the file-backed
|
||||
* archive photo over the real Payload test database and the indexed face rows
|
||||
* (scope B: anonymous descriptors, no subjects). The specs serialize on the
|
||||
* same lease because the in-process descriptor cache is derived state.
|
||||
*/
|
||||
export const FACE_SPECS_LEASE_KEY = 'c234-face-specs'
|
||||
export const FACE_INDEX_LEASE_KEY = 'c234-face-index-consent'
|
||||
export const FACE_SEARCH_LEASE_KEY = 'c234-face-search-consent'
|
||||
export const FACE_SPECS_LEASE_KEY = 'c240-face-specs'
|
||||
export const FACE_INDEX_LEASE_KEY = 'c240-face-index-consent'
|
||||
export const FACE_SEARCH_LEASE_KEY = 'c240-face-search-consent'
|
||||
|
||||
export const faceTestVector = (value: number): number[] =>
|
||||
Array.from({ length: FACE_SEARCH_DESCRIPTOR_LENGTH }, () => value)
|
||||
|
|
@ -86,27 +82,24 @@ export const createFaceTestPhoto = async ({
|
|||
return { id: created.id, flickrId }
|
||||
}
|
||||
|
||||
/** Enrolls a subject with the current index Consent resolved by stable key. */
|
||||
export const enrollFaceTestSubject = async ({
|
||||
/**
|
||||
* Seeds the descriptor rows of one photo exactly like the batch does (rows +
|
||||
* marker, one transaction). `model` lets a spec pin the old-model contract.
|
||||
*/
|
||||
export const indexFaceTestPhoto = async ({
|
||||
payload,
|
||||
label,
|
||||
vector,
|
||||
trackedSubjectIds,
|
||||
photoId,
|
||||
descriptors,
|
||||
model = FACE_SEARCH_MODEL,
|
||||
}: {
|
||||
payload: Payload
|
||||
label: string
|
||||
vector: number[]
|
||||
trackedSubjectIds: Set<number>
|
||||
}): Promise<number> => {
|
||||
const consent = await getConsentByKey(payload, FACE_INDEX_CONSENT_KEY)
|
||||
if (!consent) throw new Error('index consent not configured')
|
||||
|
||||
const enrolled = await enrollFaceSubject({
|
||||
photoId: number
|
||||
descriptors: number[][]
|
||||
model?: string
|
||||
}): Promise<number> =>
|
||||
writeArchivePhotoFaceDescriptors({
|
||||
payload,
|
||||
label,
|
||||
descriptor: vector,
|
||||
consent: { id: consent.id, contentHash: consent.contentHash },
|
||||
photoId,
|
||||
descriptors,
|
||||
indexKey: model,
|
||||
})
|
||||
trackedSubjectIds.add(enrolled.id)
|
||||
return enrolled.id
|
||||
}
|
||||
|
|
|
|||
57
tests/helpers/homeIsr.ts
Normal file
57
tests/helpers/homeIsr.ts
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
import type { APIRequestContext } from '@playwright/test'
|
||||
|
||||
/**
|
||||
* S39/S44 — the shared ISR poll of the specs that own home sections. The home
|
||||
* is served stale while it regenerates after a `revalidateTag` (slower under
|
||||
* the parallel suite), and a navigation that lands on the stale body never
|
||||
* refreshes its DOM. Poll the server HTML positively until it converges to the
|
||||
* expected state; the navigation that follows then always lands on the fresh
|
||||
* page. 12 attempts preserves the S1 convergence budget.
|
||||
*/
|
||||
export const waitForHomeHTML = async (
|
||||
request: APIRequestContext,
|
||||
baseUrl: string,
|
||||
includes: string[],
|
||||
excludes: string[] = [],
|
||||
attempts = 12,
|
||||
): Promise<void> => {
|
||||
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
||||
const response = await request.get(`${baseUrl}/`).catch(() => undefined)
|
||||
if (response?.ok()) {
|
||||
const html = await response.text()
|
||||
const allIncluded = includes.every((needle) => html.includes(needle))
|
||||
const anyExcluded = excludes.some((needle) => html.includes(needle))
|
||||
if (allIncluded && !anyExcluded) return
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 1_000))
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`A home não convergiu após ${attempts}s (includes: ${includes.join(', ')}, excludes: ${excludes.join(', ')}).`,
|
||||
)
|
||||
}
|
||||
|
||||
/** The kill-switch/section-presence specialization of the HTML poll above. */
|
||||
export const waitForHomeSection = async (
|
||||
request: APIRequestContext,
|
||||
baseUrl: string,
|
||||
section: string,
|
||||
expected: 'present' | 'absent',
|
||||
attempts = 12,
|
||||
): Promise<void> => {
|
||||
const needle = `data-home-section="${section}"`
|
||||
|
||||
try {
|
||||
await waitForHomeHTML(
|
||||
request,
|
||||
baseUrl,
|
||||
expected === 'present' ? [needle] : [],
|
||||
expected === 'present' ? [] : [needle],
|
||||
attempts,
|
||||
)
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`A seção "${section}" da home não convergiu para "${expected}" em ${attempts}s (${(error as Error).message}).`,
|
||||
)
|
||||
}
|
||||
}
|
||||
247
tests/int/faceDescriptorIndex.int.spec.ts
Normal file
247
tests/int/faceDescriptorIndex.int.spec.ts
Normal file
|
|
@ -0,0 +1,247 @@
|
|||
// @vitest-environment node
|
||||
|
||||
import { rm } from 'node:fs/promises'
|
||||
import type { Payload } from 'payload'
|
||||
import { getPayload } from 'payload'
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
vi.mock('next/cache', () => ({
|
||||
revalidatePath: () => undefined,
|
||||
revalidateTag: vi.fn(),
|
||||
unstable_cache: (fn: unknown) => fn,
|
||||
}))
|
||||
|
||||
import { ARCHIVE_PHOTO_SLUG } from '@/lib/archivePhoto'
|
||||
import { FACE_SEARCH_MODEL } from '@/lib/faceSearch'
|
||||
import config from '@/payload.config'
|
||||
import {
|
||||
indexArchivePhotoFaces,
|
||||
listArchivePhotoFaceIndexQueue,
|
||||
purgeFaceDescriptorsForPhoto,
|
||||
writeArchivePhotoFaceDescriptors,
|
||||
} from '@/utilities/faceIndex/faceDescriptorIndex'
|
||||
|
||||
import { installCampaignFixtures } from '../helpers/campaignFixtures'
|
||||
import {
|
||||
createFaceTestPhoto,
|
||||
FACE_SPECS_LEASE_KEY,
|
||||
faceTestVector,
|
||||
} from '../helpers/faceIntFixtures'
|
||||
import {
|
||||
acquireTestDatabaseLease,
|
||||
PHOTO_ALBUM_LEASE_KEY,
|
||||
withExclusiveTestDatabaseLease,
|
||||
} from '../helpers/testDatabaseLease'
|
||||
|
||||
// C242 — the anonymous index boundary over the real Payload `teqo_test`: the
|
||||
// batch's transactional descriptor replacement, the marker that makes the run
|
||||
// resumable and the purges that keep draft/removed photos out of the search.
|
||||
|
||||
let payload: Payload
|
||||
const createdFlickrIds = new Set<string>()
|
||||
const tempDirs: string[] = []
|
||||
|
||||
installCampaignFixtures({
|
||||
getPayload: () => payload,
|
||||
setPayload: (nextPayload) => {
|
||||
payload = nextPayload
|
||||
},
|
||||
})
|
||||
|
||||
const CHANNEL = 'https://jorge.solla.example.org/remocao'
|
||||
|
||||
const createPhoto = (approved: boolean) =>
|
||||
createFaceTestPhoto({
|
||||
payload,
|
||||
approved,
|
||||
prefix: 'c240',
|
||||
trackedFlickrIds: createdFlickrIds,
|
||||
tempDirs,
|
||||
})
|
||||
|
||||
const faceRowsOf = async (photoId: number): Promise<number> => {
|
||||
const result = await payload.count({
|
||||
collection: 'archivePhotoFace',
|
||||
where: { photo: { equals: photoId } },
|
||||
overrideAccess: true,
|
||||
})
|
||||
return result.totalDocs
|
||||
}
|
||||
|
||||
const markerOf = async (
|
||||
id: number,
|
||||
): Promise<{ checkedAt?: string | null; checkedKey?: string | null }> => {
|
||||
const doc = await payload.findByID({
|
||||
collection: ARCHIVE_PHOTO_SLUG,
|
||||
id,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
})
|
||||
return doc.faces ?? {}
|
||||
}
|
||||
|
||||
const queueItem = async (
|
||||
id: number,
|
||||
refresh = false,
|
||||
): Promise<
|
||||
Awaited<ReturnType<typeof listArchivePhotoFaceIndexQueue>>['items'][number] | undefined
|
||||
> => {
|
||||
const queue = await listArchivePhotoFaceIndexQueue({ payload, refresh })
|
||||
return queue.items.find((item) => item.id === id)
|
||||
}
|
||||
|
||||
describe('anonymous face descriptor index (C242)', () => {
|
||||
let specsLease: Awaited<ReturnType<typeof acquireTestDatabaseLease>>
|
||||
|
||||
beforeAll(async () => {
|
||||
payload = await getPayload({ config: await config })
|
||||
specsLease = await acquireTestDatabaseLease(payload, FACE_SPECS_LEASE_KEY)
|
||||
await withExclusiveTestDatabaseLease(payload, PHOTO_ALBUM_LEASE_KEY, () =>
|
||||
payload.updateGlobal({
|
||||
slug: 'photoAlbum',
|
||||
data: { published: true, removalChannelUrl: CHANNEL, selfieSearchEnabled: false },
|
||||
overrideAccess: true,
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
for (const flickrId of createdFlickrIds) {
|
||||
await payload.delete({
|
||||
collection: ARCHIVE_PHOTO_SLUG,
|
||||
where: { flickrId: { equals: flickrId } },
|
||||
overrideAccess: true,
|
||||
})
|
||||
}
|
||||
await Promise.all(tempDirs.map((dir) => rm(dir, { recursive: true, force: true })))
|
||||
await specsLease.release()
|
||||
})
|
||||
|
||||
it('lists only approved photos as stale and stamps the marker after indexing', async () => {
|
||||
const approved = await createPhoto(true)
|
||||
await createPhoto(false)
|
||||
|
||||
const before = await queueItem(approved.id)
|
||||
expect(before).toBeDefined()
|
||||
expect(before?.checkedKey).toBeNull()
|
||||
|
||||
const queue = await listArchivePhotoFaceIndexQueue({ payload, refresh: true })
|
||||
const result = await indexArchivePhotoFaces({
|
||||
payload,
|
||||
item: queue.items.find((item) => item.id === approved.id)!,
|
||||
indexKey: queue.indexKey,
|
||||
analyze: async () => [faceTestVector(0), faceTestVector(0.1)],
|
||||
})
|
||||
expect(result).toEqual({ status: 'indexed', descriptorCount: 2 })
|
||||
expect(await faceRowsOf(approved.id)).toBe(2)
|
||||
|
||||
const marker = await markerOf(approved.id)
|
||||
expect(marker.checkedKey).toBe(FACE_SEARCH_MODEL)
|
||||
expect(typeof marker.checkedAt).toBe('string')
|
||||
|
||||
// The marker makes the next run a no-op for this photo.
|
||||
expect(await queueItem(approved.id)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('replaces the rows of a photo on re-index instead of merging revisions', async () => {
|
||||
const photo = await createPhoto(true)
|
||||
const queue = await listArchivePhotoFaceIndexQueue({ payload, refresh: true })
|
||||
const item = queue.items.find((entry) => entry.id === photo.id)!
|
||||
|
||||
await indexArchivePhotoFaces({
|
||||
payload,
|
||||
item,
|
||||
indexKey: queue.indexKey,
|
||||
analyze: async () => [faceTestVector(0), faceTestVector(0.2), faceTestVector(0.3)],
|
||||
})
|
||||
expect(await faceRowsOf(photo.id)).toBe(3)
|
||||
|
||||
await indexArchivePhotoFaces({
|
||||
payload,
|
||||
item,
|
||||
indexKey: queue.indexKey,
|
||||
analyze: async () => [faceTestVector(0.4)],
|
||||
})
|
||||
expect(await faceRowsOf(photo.id)).toBe(1)
|
||||
})
|
||||
|
||||
it('drops malformed descriptors (fail-closed) and still stamps the marker', async () => {
|
||||
const photo = await createPhoto(true)
|
||||
const written = await writeArchivePhotoFaceDescriptors({
|
||||
payload,
|
||||
photoId: photo.id,
|
||||
descriptors: [
|
||||
[1, 2, 3],
|
||||
[Number.NaN, ...faceTestVector(0).slice(1)],
|
||||
],
|
||||
indexKey: FACE_SEARCH_MODEL,
|
||||
})
|
||||
expect(written).toBe(0)
|
||||
expect(await faceRowsOf(photo.id)).toBe(0)
|
||||
expect((await markerOf(photo.id)).checkedKey).toBe(FACE_SEARCH_MODEL)
|
||||
expect(await queueItem(photo.id)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('purges the descriptor rows when the photo stops being approved', async () => {
|
||||
const photo = await createPhoto(true)
|
||||
const queue = await listArchivePhotoFaceIndexQueue({ payload, refresh: true })
|
||||
await indexArchivePhotoFaces({
|
||||
payload,
|
||||
item: queue.items.find((item) => item.id === photo.id)!,
|
||||
indexKey: queue.indexKey,
|
||||
analyze: async () => [faceTestVector(0)],
|
||||
})
|
||||
expect(await faceRowsOf(photo.id)).toBe(1)
|
||||
|
||||
await payload.update({
|
||||
collection: ARCHIVE_PHOTO_SLUG,
|
||||
id: photo.id,
|
||||
data: { publicationStatus: 'removed' },
|
||||
overrideAccess: true,
|
||||
})
|
||||
expect(await faceRowsOf(photo.id)).toBe(0)
|
||||
expect(await queueItem(photo.id, true)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('purges the descriptor rows on deletion and on the explicit maintenance call', async () => {
|
||||
const photo = await createPhoto(true)
|
||||
await writeArchivePhotoFaceDescriptors({
|
||||
payload,
|
||||
photoId: photo.id,
|
||||
descriptors: [faceTestVector(0.5)],
|
||||
indexKey: FACE_SEARCH_MODEL,
|
||||
})
|
||||
expect(await faceRowsOf(photo.id)).toBe(1)
|
||||
|
||||
await purgeFaceDescriptorsForPhoto({ payload, photoId: photo.id })
|
||||
expect(await faceRowsOf(photo.id)).toBe(0)
|
||||
|
||||
await writeArchivePhotoFaceDescriptors({
|
||||
payload,
|
||||
photoId: photo.id,
|
||||
descriptors: [faceTestVector(0.5)],
|
||||
indexKey: FACE_SEARCH_MODEL,
|
||||
})
|
||||
await payload.delete({ collection: ARCHIVE_PHOTO_SLUG, id: photo.id, overrideAccess: true })
|
||||
const orphans = await payload.count({
|
||||
collection: 'archivePhotoFace',
|
||||
where: { photo: { equals: photo.id } },
|
||||
overrideAccess: true,
|
||||
})
|
||||
expect(orphans.totalDocs).toBe(0)
|
||||
})
|
||||
|
||||
it('reports an indexed photo with zero faces honestly', async () => {
|
||||
const photo = await createPhoto(true)
|
||||
const queue = await listArchivePhotoFaceIndexQueue({ payload, refresh: true })
|
||||
const result = await indexArchivePhotoFaces({
|
||||
payload,
|
||||
item: queue.items.find((item) => item.id === photo.id)!,
|
||||
indexKey: queue.indexKey,
|
||||
analyze: async () => [],
|
||||
})
|
||||
expect(result).toEqual({ status: 'indexed', descriptorCount: 0 })
|
||||
expect(await faceRowsOf(photo.id)).toBe(0)
|
||||
expect((await markerOf(photo.id)).checkedKey).toBe(FACE_SEARCH_MODEL)
|
||||
})
|
||||
})
|
||||
|
|
@ -14,21 +14,18 @@ vi.mock('next/cache', () => ({
|
|||
import { POST as postSelfie } from '@/app/(frontend)/api/fotos/selfie/route'
|
||||
import { ARCHIVE_PHOTO_SLUG } from '@/lib/archivePhoto'
|
||||
import { FACE_INDEX_CONSENT_KEY, FACE_SEARCH_CONSENT_KEY } from '@/lib/campaignConsentKeys'
|
||||
import { FACE_SEARCH_MODEL } from '@/lib/faceSearch'
|
||||
import config from '@/payload.config'
|
||||
import { removeFaceSubjectFromIndex } from '@/utilities/faceSubjects/faceSubjectEnrollment'
|
||||
import {
|
||||
indexArchivePhotoFaces,
|
||||
listArchivePhotoFaceIndexQueue,
|
||||
} from '@/utilities/faceSubjects/faceSubjectPhotoIndex'
|
||||
import { invalidateFaceDescriptorIndex } from '@/utilities/faceIndex/faceDescriptorReads'
|
||||
|
||||
import { installCampaignFixtures } from '../helpers/campaignFixtures'
|
||||
import {
|
||||
createFaceTestPhoto,
|
||||
enrollFaceTestSubject,
|
||||
FACE_INDEX_LEASE_KEY,
|
||||
FACE_SEARCH_LEASE_KEY,
|
||||
FACE_SPECS_LEASE_KEY,
|
||||
faceTestVector,
|
||||
indexFaceTestPhoto,
|
||||
} from '../helpers/faceIntFixtures'
|
||||
import {
|
||||
acquireTestDatabaseLease,
|
||||
|
|
@ -37,14 +34,14 @@ import {
|
|||
withExclusiveTestDatabaseLease,
|
||||
} from '../helpers/testDatabaseLease'
|
||||
|
||||
// C234 — the anonymous selfie endpoint over the real Payload `teqo_test`:
|
||||
// the kill switch and the Consent fail-closed layers, the A/C answer (only
|
||||
// enrolled subjects, only approved photos, never a score or a third-party
|
||||
// name), the opt-out by matched descriptor and the anonymous anti-abuse.
|
||||
// C242 — the anonymous selfie endpoint over the real Payload `teqo_test`:
|
||||
// the kill switch and the two Consent fail-closed layers, the scope B answer
|
||||
// (anonymous descriptors of approved photos only, never a score or a
|
||||
// third-party name), the opt-out by matched descriptor and the anonymous
|
||||
// anti-abuse.
|
||||
|
||||
let payload: Payload
|
||||
const createdFlickrIds = new Set<string>()
|
||||
const createdSubjectIds = new Set<number>()
|
||||
const tempDirs: string[] = []
|
||||
|
||||
installCampaignFixtures({
|
||||
|
|
@ -60,25 +57,11 @@ const createPhoto = (approved: boolean) =>
|
|||
createFaceTestPhoto({
|
||||
payload,
|
||||
approved,
|
||||
prefix: 'c234-api',
|
||||
prefix: 'c240-api',
|
||||
trackedFlickrIds: createdFlickrIds,
|
||||
tempDirs,
|
||||
})
|
||||
|
||||
const enrollFixtureSubject = (label: string, vector: number[]) =>
|
||||
enrollFaceTestSubject({ payload, label, vector, trackedSubjectIds: createdSubjectIds })
|
||||
|
||||
const indexPhotoForSubject = async (photoId: number, vector: number[]): Promise<void> => {
|
||||
const queue = await listArchivePhotoFaceIndexQueue({ payload, refresh: true })
|
||||
const result = await indexArchivePhotoFaces({
|
||||
payload,
|
||||
item: queue.items.find((item) => item.id === photoId)!,
|
||||
indexKey: queue.indexKey,
|
||||
analyze: async () => [vector],
|
||||
})
|
||||
if (result.status !== 'indexed') throw new Error(`index fixture failed: ${result.status}`)
|
||||
}
|
||||
|
||||
const setSelfieSearchEnabled = async (enabled: boolean): Promise<void> => {
|
||||
await withExclusiveTestDatabaseLease(payload, PHOTO_ALBUM_LEASE_KEY, () =>
|
||||
payload.updateGlobal({
|
||||
|
|
@ -98,7 +81,7 @@ const post = (body: unknown, headers: Record<string, string> = {}): Promise<Resp
|
|||
}),
|
||||
)
|
||||
|
||||
describe('selfie search endpoint (C234)', () => {
|
||||
describe('selfie search endpoint (C242)', () => {
|
||||
let specsLease: Awaited<ReturnType<typeof acquireTestDatabaseLease>>
|
||||
|
||||
beforeAll(async () => {
|
||||
|
|
@ -123,10 +106,8 @@ describe('selfie search endpoint (C234)', () => {
|
|||
overrideAccess: true,
|
||||
})
|
||||
}
|
||||
for (const id of createdSubjectIds) {
|
||||
await payload.delete({ collection: 'faceSubject', id, overrideAccess: true })
|
||||
}
|
||||
await setSelfieSearchEnabled(false)
|
||||
invalidateFaceDescriptorIndex()
|
||||
await Promise.all(tempDirs.map((dir) => rm(dir, { recursive: true, force: true })))
|
||||
await specsLease.release()
|
||||
})
|
||||
|
|
@ -165,43 +146,51 @@ describe('selfie search endpoint (C234)', () => {
|
|||
await setSelfieSearchEnabled(false)
|
||||
})
|
||||
|
||||
it('fails closed (503) while the query Consent is not configured', async () => {
|
||||
it('fails closed (503) while either Consent is not configured', async () => {
|
||||
await setSelfieSearchEnabled(true)
|
||||
try {
|
||||
// The C234 specs lease already serializes every writer of this key, so
|
||||
// the absence window is exclusive by construction.
|
||||
await payload.delete({
|
||||
collection: 'consent',
|
||||
where: { key: { equals: FACE_SEARCH_CONSENT_KEY } },
|
||||
overrideAccess: true,
|
||||
})
|
||||
const response = await post({ vector: faceTestVector(0), intent: 'search' })
|
||||
expect(response.status).toBe(503)
|
||||
await expect(response.json()).resolves.toEqual({ ok: false, error: 'consent' })
|
||||
} finally {
|
||||
const withoutQuery = await post({ vector: faceTestVector(0), intent: 'search' })
|
||||
expect(withoutQuery.status).toBe(503)
|
||||
await expect(withoutQuery.json()).resolves.toEqual({ ok: false, error: 'consent' })
|
||||
|
||||
await ensureLeasedConsent(payload, {
|
||||
consentKey: FACE_SEARCH_CONSENT_KEY,
|
||||
leaseKey: FACE_SEARCH_LEASE_KEY,
|
||||
})
|
||||
await payload.delete({
|
||||
collection: 'consent',
|
||||
where: { key: { equals: FACE_INDEX_CONSENT_KEY } },
|
||||
overrideAccess: true,
|
||||
})
|
||||
const withoutNotice = await post({ vector: faceTestVector(0), intent: 'search' })
|
||||
expect(withoutNotice.status).toBe(503)
|
||||
} finally {
|
||||
await ensureLeasedConsent(payload, {
|
||||
consentKey: FACE_INDEX_CONSENT_KEY,
|
||||
leaseKey: FACE_INDEX_LEASE_KEY,
|
||||
})
|
||||
await setSelfieSearchEnabled(false)
|
||||
}
|
||||
})
|
||||
|
||||
it('returns only the approved photos of the matched subject, without names or score', async () => {
|
||||
it('returns only the approved photos with a matching face, without names or score', async () => {
|
||||
const vector = faceTestVector(0)
|
||||
const subject = await enrollFixtureSubject('Pessoa encontrada', vector)
|
||||
const approved = await createPhoto(true)
|
||||
const draft = await createPhoto(false)
|
||||
await indexPhotoForSubject(approved.id, vector)
|
||||
|
||||
// A draft linked by hand must never surface: the endpoint intersects the
|
||||
// subject's links with the approved public read.
|
||||
await payload.update({
|
||||
collection: 'faceSubject',
|
||||
id: subject,
|
||||
data: { matchedPhotos: [approved.id, draft.id] },
|
||||
await indexFaceTestPhoto({ payload, photoId: approved.id, descriptors: [vector] })
|
||||
// A draft with descriptor rows by hand must never surface: the endpoint
|
||||
// intersects the index with the approved public read.
|
||||
await payload.create({
|
||||
collection: 'archivePhotoFace',
|
||||
data: { photo: draft.id, model: FACE_SEARCH_MODEL, vector },
|
||||
overrideAccess: true,
|
||||
})
|
||||
invalidateFaceDescriptorIndex()
|
||||
|
||||
await setSelfieSearchEnabled(true)
|
||||
const response = await post({ vector, intent: 'search' })
|
||||
|
|
@ -217,19 +206,18 @@ describe('selfie search endpoint (C234)', () => {
|
|||
expect(body.photos.map((photo) => photo.id)).toEqual([approved.id])
|
||||
expect(JSON.stringify(body)).not.toMatch(/"people"|"score"|"distance"|"similarity"/i)
|
||||
|
||||
// A face nobody enrolled in the index gets the honest empty answer.
|
||||
// A face nobody has in the index gets the honest empty answer.
|
||||
const stranger = await post({ vector: faceTestVector(1), intent: 'search' })
|
||||
await expect(stranger.json()).resolves.toEqual({ ok: true, found: false })
|
||||
|
||||
await setSelfieSearchEnabled(false)
|
||||
await removeFaceSubjectFromIndex({ payload, id: subject })
|
||||
})
|
||||
|
||||
it('serves the opt-out by matched descriptor and stops answering afterwards', async () => {
|
||||
const vector = faceTestVector(0.25)
|
||||
const subject = await enrollFixtureSubject('Sai pelo endpoint', vector)
|
||||
const approved = await createPhoto(true)
|
||||
await indexPhotoForSubject(approved.id, vector)
|
||||
await indexFaceTestPhoto({ payload, photoId: approved.id, descriptors: [vector] })
|
||||
invalidateFaceDescriptorIndex()
|
||||
|
||||
await setSelfieSearchEnabled(true)
|
||||
const before = await post({ vector, intent: 'search' })
|
||||
|
|
@ -238,14 +226,12 @@ describe('selfie search endpoint (C234)', () => {
|
|||
const leave = await post({ vector, intent: 'leave-index' })
|
||||
await expect(leave.json()).resolves.toEqual({ ok: true, removed: true })
|
||||
|
||||
const stored = await payload.findByID({
|
||||
collection: 'faceSubject',
|
||||
id: subject,
|
||||
depth: 0,
|
||||
const rows = await payload.count({
|
||||
collection: 'archivePhotoFace',
|
||||
where: { photo: { equals: approved.id } },
|
||||
overrideAccess: true,
|
||||
})
|
||||
expect(stored.status).toBe('removed')
|
||||
expect(stored.vector).toBeNull()
|
||||
expect(rows.totalDocs).toBe(0)
|
||||
|
||||
const after = await post({ vector, intent: 'search' })
|
||||
await expect(after.json()).resolves.toEqual({ ok: true, found: false })
|
||||
|
|
@ -270,13 +256,14 @@ describe('selfie search endpoint (C234)', () => {
|
|||
|
||||
it('keeps the model contract: only the current model can match', async () => {
|
||||
const vector = faceTestVector(0.75)
|
||||
const subject = await enrollFixtureSubject('Modelo trocado', vector)
|
||||
await payload.update({
|
||||
collection: 'faceSubject',
|
||||
id: subject,
|
||||
data: { model: 'outro-modelo@0' },
|
||||
overrideAccess: true,
|
||||
const approved = await createPhoto(true)
|
||||
await indexFaceTestPhoto({
|
||||
payload,
|
||||
photoId: approved.id,
|
||||
descriptors: [vector],
|
||||
model: 'outro-modelo@0',
|
||||
})
|
||||
invalidateFaceDescriptorIndex()
|
||||
|
||||
await setSelfieSearchEnabled(true)
|
||||
const response = await post({ vector, intent: 'search' })
|
||||
|
|
|
|||
|
|
@ -1,249 +0,0 @@
|
|||
// @vitest-environment node
|
||||
|
||||
import { rm } from 'node:fs/promises'
|
||||
import type { Payload } from 'payload'
|
||||
import { getPayload } from 'payload'
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
vi.mock('next/cache', () => ({
|
||||
revalidatePath: () => undefined,
|
||||
revalidateTag: vi.fn(),
|
||||
unstable_cache: (fn: unknown) => fn,
|
||||
}))
|
||||
|
||||
import { ARCHIVE_PHOTO_SLUG } from '@/lib/archivePhoto'
|
||||
import { FACE_INDEX_CONSENT_KEY } from '@/lib/campaignConsentKeys'
|
||||
import { FACE_SEARCH_DESCRIPTOR_LENGTH, FACE_SEARCH_MODEL } from '@/lib/faceSearch'
|
||||
import config from '@/payload.config'
|
||||
import { getConsentByKey } from '@/utilities/campaignConsent'
|
||||
import { removeFaceSubjectFromIndex } from '@/utilities/faceSubjects/faceSubjectEnrollment'
|
||||
import {
|
||||
indexArchivePhotoFaces,
|
||||
listArchivePhotoFaceIndexQueue,
|
||||
} from '@/utilities/faceSubjects/faceSubjectPhotoIndex'
|
||||
import {
|
||||
getFaceSubjectMatchedPhotoIds,
|
||||
listSearchableFaceSubjects,
|
||||
} from '@/utilities/faceSubjects/faceSubjectReads'
|
||||
|
||||
import { installCampaignFixtures } from '../helpers/campaignFixtures'
|
||||
import {
|
||||
createFaceTestPhoto,
|
||||
enrollFaceTestSubject,
|
||||
FACE_INDEX_LEASE_KEY,
|
||||
FACE_SPECS_LEASE_KEY,
|
||||
faceTestVector,
|
||||
} from '../helpers/faceIntFixtures'
|
||||
import {
|
||||
acquireTestDatabaseLease,
|
||||
ensureLeasedConsent,
|
||||
PHOTO_ALBUM_LEASE_KEY,
|
||||
withExclusiveTestDatabaseLease,
|
||||
} from '../helpers/testDatabaseLease'
|
||||
|
||||
// C234 — the subject/index boundary over the real Payload `teqo_test`: the
|
||||
// enrollment write, the batch's transactional link replacement, the marker
|
||||
// that makes the run resumable, the opt-out that erases the descriptor and the
|
||||
// A/C rule that only enrolled subjects are ever searched.
|
||||
|
||||
let payload: Payload
|
||||
const createdFlickrIds = new Set<string>()
|
||||
const createdSubjectIds = new Set<number>()
|
||||
const tempDirs: string[] = []
|
||||
|
||||
installCampaignFixtures({
|
||||
getPayload: () => payload,
|
||||
setPayload: (nextPayload) => {
|
||||
payload = nextPayload
|
||||
},
|
||||
})
|
||||
|
||||
const CHANNEL = 'https://jorge.solla.example.org/remocao'
|
||||
|
||||
const createApprovedPhoto = () =>
|
||||
createFaceTestPhoto({
|
||||
payload,
|
||||
approved: true,
|
||||
prefix: 'c234',
|
||||
trackedFlickrIds: createdFlickrIds,
|
||||
tempDirs,
|
||||
})
|
||||
|
||||
const enrollFixtureSubject = (label: string, vector: number[]) =>
|
||||
enrollFaceTestSubject({ payload, label, vector, trackedSubjectIds: createdSubjectIds })
|
||||
|
||||
const markerOf = async (
|
||||
id: number,
|
||||
): Promise<{ checkedAt?: string | null; checkedKey?: string | null }> => {
|
||||
const doc = await payload.findByID({
|
||||
collection: ARCHIVE_PHOTO_SLUG,
|
||||
id,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
})
|
||||
return doc.faces ?? {}
|
||||
}
|
||||
|
||||
describe('face subject enrollment and archive index (C234)', () => {
|
||||
let specsLease: Awaited<ReturnType<typeof acquireTestDatabaseLease>>
|
||||
|
||||
beforeAll(async () => {
|
||||
payload = await getPayload({ config: await config })
|
||||
specsLease = await acquireTestDatabaseLease(payload, FACE_SPECS_LEASE_KEY)
|
||||
await ensureLeasedConsent(payload, {
|
||||
consentKey: FACE_INDEX_CONSENT_KEY,
|
||||
leaseKey: FACE_INDEX_LEASE_KEY,
|
||||
})
|
||||
await withExclusiveTestDatabaseLease(payload, PHOTO_ALBUM_LEASE_KEY, () =>
|
||||
payload.updateGlobal({
|
||||
slug: 'photoAlbum',
|
||||
data: { published: true, removalChannelUrl: CHANNEL },
|
||||
overrideAccess: true,
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
for (const flickrId of createdFlickrIds) {
|
||||
await payload.delete({
|
||||
collection: ARCHIVE_PHOTO_SLUG,
|
||||
where: { flickrId: { equals: flickrId } },
|
||||
overrideAccess: true,
|
||||
})
|
||||
}
|
||||
for (const id of createdSubjectIds) {
|
||||
await payload.delete({ collection: 'faceSubject', id, overrideAccess: true })
|
||||
}
|
||||
await Promise.all(tempDirs.map((dir) => rm(dir, { recursive: true, force: true })))
|
||||
await specsLease.release()
|
||||
})
|
||||
|
||||
it('enrolls a subject with the current model and consent snapshot', async () => {
|
||||
const consent = await getConsentByKey(payload, FACE_INDEX_CONSENT_KEY)
|
||||
const id = await enrollFixtureSubject('Pessoa de teste', faceTestVector(0))
|
||||
|
||||
const stored = await payload.findByID({
|
||||
collection: 'faceSubject',
|
||||
id,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
})
|
||||
expect(stored.status).toBe('active')
|
||||
expect(stored.model).toBe(FACE_SEARCH_MODEL)
|
||||
expect(stored.consentHash).toBe(consent?.contentHash)
|
||||
expect(stored.vector).toHaveLength(FACE_SEARCH_DESCRIPTOR_LENGTH)
|
||||
expect(stored.enrolledAt).toBeTruthy()
|
||||
|
||||
const searchable = await listSearchableFaceSubjects(payload)
|
||||
expect(searchable.map((subject) => subject.id)).toContain(id)
|
||||
})
|
||||
|
||||
it('links an approved photo to the enrolled subject and stamps the marker', async () => {
|
||||
const owner = await enrollFixtureSubject('Dona da foto', faceTestVector(0))
|
||||
const photo = await createApprovedPhoto()
|
||||
|
||||
const queue = await listArchivePhotoFaceIndexQueue({ payload })
|
||||
expect(queue.eligibleSubjects).toBeGreaterThanOrEqual(1)
|
||||
expect(queue.items.map((item) => item.id)).toContain(photo.id)
|
||||
|
||||
const result = await indexArchivePhotoFaces({
|
||||
payload,
|
||||
item: queue.items.find((item) => item.id === photo.id)!,
|
||||
indexKey: queue.indexKey,
|
||||
analyze: async () => [faceTestVector(0)],
|
||||
})
|
||||
expect(result).toEqual({ status: 'indexed', matchedSubjects: expect.arrayContaining([owner]) })
|
||||
expect(await getFaceSubjectMatchedPhotoIds(payload, owner)).toContain(photo.id)
|
||||
|
||||
const marker = await markerOf(photo.id)
|
||||
expect(marker.checkedKey).toBe(queue.indexKey)
|
||||
expect(marker.checkedAt).toBeTruthy()
|
||||
|
||||
// The marker now spares the photo on the next run.
|
||||
const nextQueue = await listArchivePhotoFaceIndexQueue({ payload })
|
||||
expect(nextQueue.items.map((item) => item.id)).not.toContain(photo.id)
|
||||
const refreshed = await listArchivePhotoFaceIndexQueue({ payload, refresh: true })
|
||||
expect(refreshed.items.map((item) => item.id)).toContain(photo.id)
|
||||
})
|
||||
|
||||
it('removes a link that stopped matching and re-adds it when the face matches again', async () => {
|
||||
const subject = await enrollFixtureSubject('Rosto mutável', faceTestVector(0))
|
||||
const photo = await createApprovedPhoto()
|
||||
const queue = await listArchivePhotoFaceIndexQueue({ payload, refresh: true })
|
||||
|
||||
const indexed = await indexArchivePhotoFaces({
|
||||
payload,
|
||||
item: queue.items.find((item) => item.id === photo.id)!,
|
||||
indexKey: queue.indexKey,
|
||||
analyze: async () => [faceTestVector(0)],
|
||||
})
|
||||
expect(indexed.status).toBe('indexed')
|
||||
expect(await getFaceSubjectMatchedPhotoIds(payload, subject)).toContain(photo.id)
|
||||
|
||||
const removed = await indexArchivePhotoFaces({
|
||||
payload,
|
||||
item: queue.items.find((item) => item.id === photo.id)!,
|
||||
indexKey: queue.indexKey,
|
||||
analyze: async () => [faceTestVector(1)],
|
||||
})
|
||||
expect(removed.status).toBe('indexed')
|
||||
expect(await getFaceSubjectMatchedPhotoIds(payload, subject)).not.toContain(photo.id)
|
||||
|
||||
await indexArchivePhotoFaces({
|
||||
payload,
|
||||
item: queue.items.find((item) => item.id === photo.id)!,
|
||||
indexKey: queue.indexKey,
|
||||
analyze: async () => [faceTestVector(0)],
|
||||
})
|
||||
expect(await getFaceSubjectMatchedPhotoIds(payload, subject)).toContain(photo.id)
|
||||
})
|
||||
|
||||
it('changes the index key on a new enrollment so every photo is reprocessed', async () => {
|
||||
const queue = await listArchivePhotoFaceIndexQueue({ payload })
|
||||
await enrollFixtureSubject('Nova adesão', faceTestVector(0.5))
|
||||
const nextQueue = await listArchivePhotoFaceIndexQueue({ payload })
|
||||
expect(nextQueue.indexKey).not.toBe(queue.indexKey)
|
||||
})
|
||||
|
||||
it('erases the descriptor and the links on opt-out', async () => {
|
||||
const subject = await enrollFixtureSubject('Sai do índice', faceTestVector(0))
|
||||
const photo = await createApprovedPhoto()
|
||||
const queue = await listArchivePhotoFaceIndexQueue({ payload, refresh: true })
|
||||
await indexArchivePhotoFaces({
|
||||
payload,
|
||||
item: queue.items.find((item) => item.id === photo.id)!,
|
||||
indexKey: queue.indexKey,
|
||||
analyze: async () => [faceTestVector(0)],
|
||||
})
|
||||
expect(await getFaceSubjectMatchedPhotoIds(payload, subject)).toContain(photo.id)
|
||||
|
||||
await removeFaceSubjectFromIndex({ payload, id: subject })
|
||||
|
||||
const stored = await payload.findByID({
|
||||
collection: 'faceSubject',
|
||||
id: subject,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
})
|
||||
expect(stored.status).toBe('removed')
|
||||
expect(stored.vector).toBeNull()
|
||||
expect(stored.removedAt).toBeTruthy()
|
||||
expect(await getFaceSubjectMatchedPhotoIds(payload, subject)).toEqual([])
|
||||
|
||||
const searchable = await listSearchableFaceSubjects(payload)
|
||||
expect(searchable.map((candidate) => candidate.id)).not.toContain(subject)
|
||||
})
|
||||
|
||||
it('fails a photo with no stored file instead of writing a link', async () => {
|
||||
const subject = await enrollFixtureSubject('Sem arquivo', faceTestVector(0))
|
||||
const queue = await listArchivePhotoFaceIndexQueue({ payload, refresh: true })
|
||||
const result = await indexArchivePhotoFaces({
|
||||
payload,
|
||||
item: { id: 999_999_999, filename: null, checkedKey: null },
|
||||
indexKey: queue.indexKey,
|
||||
analyze: async () => [faceTestVector(0)],
|
||||
})
|
||||
expect(result).toEqual({ status: 'failed', stage: 'download', error: expect.any(String) })
|
||||
expect(await getFaceSubjectMatchedPhotoIds(payload, subject)).toEqual([])
|
||||
})
|
||||
})
|
||||
|
|
@ -49,6 +49,7 @@ import config from '@/payload.config'
|
|||
import {
|
||||
getCachedPublishedShareLinkBySlug,
|
||||
loadPublishedShareLinkLiveTarget,
|
||||
loadShareLinkHomeSection,
|
||||
resolveShareLinkCanonicalUrl,
|
||||
resolveShareLinkOgImageUrl,
|
||||
} from '@/utilities/shareLinkReads'
|
||||
|
|
@ -450,4 +451,86 @@ describe('shareLink', () => {
|
|||
'https://site.test/api/media/file/site-default.png',
|
||||
)
|
||||
})
|
||||
|
||||
describe('loadShareLinkHomeSection (S44)', () => {
|
||||
const startsInAnHour = () => new Date(Date.now() + 60 * 60 * 1000).toISOString()
|
||||
|
||||
beforeEach(() => {
|
||||
getCachedGlobalMock.mockReturnValue(async () => ({ URL: 'https://canonical.example/' }))
|
||||
})
|
||||
|
||||
it('builds the home view with the on-air destination and the YouTube player id', async () => {
|
||||
const startsAt = startsInAnHour()
|
||||
await createShareLink({
|
||||
title: 'Plenária da Vitória',
|
||||
slug: 'home-section-s44',
|
||||
description: 'Encontro online.',
|
||||
mode: 'announcement',
|
||||
published: true,
|
||||
startsAt,
|
||||
location: 'Online',
|
||||
destinations: [
|
||||
{ label: 'Google Meet', url: 'https://meet.google.com/abc-defg-hij', live: true },
|
||||
{ label: 'Youtube', url: 'https://www.youtube.com/live/77bUgl7cvQ8' },
|
||||
],
|
||||
})
|
||||
|
||||
const section = await loadShareLinkHomeSection('home-section-s44')
|
||||
expect(section?.initialLive).toEqual({
|
||||
href: 'https://meet.google.com/abc-defg-hij',
|
||||
label: 'Google Meet',
|
||||
})
|
||||
expect(section?.view.youtubeVideoId).toBe('77bUgl7cvQ8')
|
||||
expect(section?.view.canonicalUrl).toBe('https://canonical.example/home-section-s44')
|
||||
expect(section?.view.expiresAt).toBe(Date.parse(startsAt) + 2 * 60 * 60 * 1000)
|
||||
expect(section?.view.location).toBe('Online')
|
||||
})
|
||||
|
||||
it('fails closed for an expired window, a missing start or an unpublished link', async () => {
|
||||
await createShareLink({
|
||||
title: 'Expirada',
|
||||
slug: 'home-section-expirada-s44',
|
||||
description: 'x',
|
||||
mode: 'announcement',
|
||||
published: true,
|
||||
startsAt: new Date(Date.now() - 3 * 60 * 60 * 1000).toISOString(),
|
||||
})
|
||||
await createShareLink({
|
||||
title: 'Sem data',
|
||||
slug: 'home-section-sem-data-s44',
|
||||
description: 'x',
|
||||
mode: 'announcement',
|
||||
published: true,
|
||||
})
|
||||
await createShareLink({
|
||||
title: 'Rascunho',
|
||||
slug: 'home-section-rascunho-s44',
|
||||
description: 'x',
|
||||
mode: 'announcement',
|
||||
published: false,
|
||||
startsAt: startsInAnHour(),
|
||||
})
|
||||
|
||||
expect(await loadShareLinkHomeSection('home-section-expirada-s44')).toBeNull()
|
||||
expect(await loadShareLinkHomeSection('home-section-sem-data-s44')).toBeNull()
|
||||
expect(await loadShareLinkHomeSection('home-section-rascunho-s44')).toBeNull()
|
||||
expect(await loadShareLinkHomeSection('home-section-inexistente-s44')).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps the section pre-live while no destination is on air', async () => {
|
||||
await createShareLink({
|
||||
title: 'Pré-live',
|
||||
slug: 'home-section-pre-s44',
|
||||
description: 'x',
|
||||
mode: 'announcement',
|
||||
published: true,
|
||||
startsAt: startsInAnHour(),
|
||||
destinations: [{ label: 'Google Meet', url: 'https://meet.google.com/abc-defg-hij' }],
|
||||
})
|
||||
|
||||
const section = await loadShareLinkHomeSection('home-section-pre-s44')
|
||||
expect(section?.initialLive).toBeNull()
|
||||
expect(section?.view.youtubeVideoId).toBeNull()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
|
|
|||
77
tests/unit/archivePublishPlan.unit.spec.ts
Normal file
77
tests/unit/archivePublishPlan.unit.spec.ts
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
// @vitest-environment node
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
ARCHIVE_PUBLISH_DEFAULT_OUT_DIR,
|
||||
archivePublishReportStamp,
|
||||
formatArchivePublishReport,
|
||||
parseArchivePublishCliArgs,
|
||||
summarizeArchivePublishResults,
|
||||
} from '../../scripts/lib/archivePublishPlan.mjs'
|
||||
|
||||
// C242 — the pure parser/summary of `pnpm archive:publish`: the dry-run default
|
||||
// and the honest per-photo failure accounting of the bulk approval.
|
||||
|
||||
describe('parseArchivePublishCliArgs', () => {
|
||||
it('defaults to the dry-run and parses the options', () => {
|
||||
expect(parseArchivePublishCliArgs([])).toEqual({
|
||||
apply: false,
|
||||
limit: null,
|
||||
out: ARCHIVE_PUBLISH_DEFAULT_OUT_DIR,
|
||||
help: false,
|
||||
})
|
||||
|
||||
const apply = parseArchivePublishCliArgs(['--apply', '--limit', '20', '--out', 'x'])
|
||||
expect(apply.apply).toBe(true)
|
||||
expect(apply.limit).toBe(20)
|
||||
expect(apply.out).toBe('x')
|
||||
expect(parseArchivePublishCliArgs(['--help']).help).toBe(true)
|
||||
})
|
||||
|
||||
it('fails closed on a bad limit, escaping out and unknown args', () => {
|
||||
expect(() => parseArchivePublishCliArgs(['--limit', '0'])).toThrow(/--limit/)
|
||||
expect(() => parseArchivePublishCliArgs(['--limit', 'x'])).toThrow(/--limit/)
|
||||
expect(() => parseArchivePublishCliArgs(['--out', '../etc'])).toThrow(/--out/)
|
||||
expect(() => parseArchivePublishCliArgs(['--apply=1'])).toThrow(/argumento desconhecido/)
|
||||
expect(() => parseArchivePublishCliArgs(['--limit'])).toThrow(/faltou valor/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('summarizeArchivePublishResults', () => {
|
||||
it('counts approvals and lists failures with the reason', () => {
|
||||
const summary = summarizeArchivePublishResults([
|
||||
{ photoId: 1, status: 'approved' },
|
||||
{ photoId: 2, status: 'approved' },
|
||||
{ photoId: 3, status: 'failed', error: 'canal ausente' },
|
||||
])
|
||||
|
||||
expect(summary.approved).toBe(2)
|
||||
expect(summary.failed).toBe(1)
|
||||
expect(summary.failures).toEqual([{ photoId: 3, error: 'canal ausente' }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatting', () => {
|
||||
it('stamps the receipt name and prints the apply summary', () => {
|
||||
expect(archivePublishReportStamp('2026-10-01T04:09:04.123Z')).toBe('2026-10-01T04-09-04-123Z')
|
||||
|
||||
const plan = formatArchivePublishReport({
|
||||
mode: 'plan',
|
||||
target: 'host/db',
|
||||
queue: { totalDrafts: 6492, items: 6492 },
|
||||
summary: { approved: 0, failed: 0, failures: [] },
|
||||
}).join('\n')
|
||||
expect(plan).toContain('modo: plan')
|
||||
expect(plan).toContain('drafts elegíveis: 6492')
|
||||
|
||||
const apply = formatArchivePublishReport({
|
||||
mode: 'apply',
|
||||
target: 'host/db',
|
||||
queue: { totalDrafts: 10, items: 3 },
|
||||
summary: { approved: 2, failed: 1, failures: [{ photoId: 7, error: 'sem arquivo' }] },
|
||||
}).join('\n')
|
||||
expect(apply).toContain('aprovadas: 2 | falharam: 1')
|
||||
expect(apply).toContain('✗ foto 7: sem arquivo')
|
||||
})
|
||||
})
|
||||
|
|
@ -3,6 +3,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
|
|||
|
||||
import HomePage from '@/app/(frontend)/(home)/page'
|
||||
import { toContentPiecePublicItem, type ContentPiecePublicItem } from '@/lib/contentPieceCatalog'
|
||||
import type { ShareLinkHomeSectionData } from '@/utilities/shareLinkReads'
|
||||
|
||||
const pieceItem = toContentPiecePublicItem({
|
||||
id: 1,
|
||||
|
|
@ -64,11 +65,36 @@ vi.mock('@/utilities/content/contentPieceReads', () => ({
|
|||
getPublishedContentPieceItems: async () => contentPieces.items,
|
||||
}))
|
||||
|
||||
// C233 — the footer's "Fotos" discovery flag reads the approved archive photos
|
||||
// through the Payload DB; the unit env has no database and the real listing is
|
||||
// e2e-covered (frontendFotos.e2e.spec.ts).
|
||||
// C233/C243 — the footer's "Fotos" discovery flag and the selfie-search section
|
||||
// read the approved archive photos and the photoAlbum global through the
|
||||
// Payload DB; the unit env has no database and the real gate is e2e-covered
|
||||
// (frontendFotosSelfie.e2e.spec.ts).
|
||||
const homePhotoAlbum = vi.hoisted(() => ({
|
||||
hasPhotos: false,
|
||||
selfieSearchEnabled: false,
|
||||
published: true,
|
||||
}))
|
||||
|
||||
vi.mock('@/utilities/archivePhotos/archivePhotoReads', () => ({
|
||||
hasPublishedArchivePhotos: async () => false,
|
||||
hasPublishedArchivePhotos: async () => homePhotoAlbum.hasPhotos,
|
||||
}))
|
||||
|
||||
vi.mock('@/utilities/globalReads', () => ({
|
||||
getCachedGlobal: () => async () => ({
|
||||
published: homePhotoAlbum.published,
|
||||
selfieSearchEnabled: homePhotoAlbum.selfieSearchEnabled,
|
||||
}),
|
||||
}))
|
||||
|
||||
// S44 — the Plenária section reads the fixed share link through the Payload DB
|
||||
// (cached under the shareLinks tag); the unit env has no database, and the real
|
||||
// window gate/swap behavior is e2e-covered (frontendShareLink.e2e.spec.ts).
|
||||
const homeShareLink = vi.hoisted(() => ({
|
||||
section: null as ShareLinkHomeSectionData | null,
|
||||
}))
|
||||
|
||||
vi.mock('@/utilities/shareLinkReads', () => ({
|
||||
loadShareLinkHomeSection: async () => homeShareLink.section,
|
||||
}))
|
||||
|
||||
// S14 — the card section renders the client studio island (next/font local
|
||||
|
|
@ -84,6 +110,10 @@ vi.mock('@/components/cards/CardsStudio', () => ({
|
|||
|
||||
afterEach(() => {
|
||||
contentPieces.items = []
|
||||
homePhotoAlbum.hasPhotos = false
|
||||
homePhotoAlbum.selfieSearchEnabled = false
|
||||
homePhotoAlbum.published = true
|
||||
homeShareLink.section = null
|
||||
cleanup()
|
||||
})
|
||||
|
||||
|
|
@ -144,4 +174,63 @@ describe('Campaign home', () => {
|
|||
expect(screen.queryByRole('heading', { name: 'Peça voto pra Solla 1313' })).toBeNull()
|
||||
expect(screen.queryByRole('link', { name: /Ver todas as peças/ })).toBeNull()
|
||||
})
|
||||
|
||||
it('mostra a seção da busca por selfie só quando a busca está aberta (C243, fail-closed)', async () => {
|
||||
homePhotoAlbum.hasPhotos = true
|
||||
homePhotoAlbum.selfieSearchEnabled = true
|
||||
render(await HomePage())
|
||||
|
||||
expect(screen.getByRole('heading', { name: 'Encontre você nas fotos' })).toBeTruthy()
|
||||
const ctas = screen.getAllByRole('link', { name: /Encontrar minhas fotos/ })
|
||||
expect(ctas.length).toBeGreaterThan(0)
|
||||
for (const cta of ctas) expect(cta.getAttribute('href')).toBe('/fotos/encontre')
|
||||
|
||||
cleanup()
|
||||
|
||||
homePhotoAlbum.selfieSearchEnabled = false
|
||||
render(await HomePage())
|
||||
expect(screen.queryByRole('heading', { name: 'Encontre você nas fotos' })).toBeNull()
|
||||
|
||||
cleanup()
|
||||
|
||||
// Flag on but no approved photo is still closed: no dead CTA.
|
||||
homePhotoAlbum.selfieSearchEnabled = true
|
||||
homePhotoAlbum.hasPhotos = false
|
||||
render(await HomePage())
|
||||
expect(screen.queryByRole('heading', { name: 'Encontre você nas fotos' })).toBeNull()
|
||||
})
|
||||
|
||||
it('mostra a seção da Plenária só com o link publicado na janela (S44, fail-closed)', async () => {
|
||||
const startsAt = new Date(Date.now() + 60 * 60 * 1000).toISOString()
|
||||
homeShareLink.section = {
|
||||
view: {
|
||||
slug: 'plenaria-vitoria',
|
||||
title: 'Plenária da Vitória',
|
||||
description: 'O time de Jorge Solla se encontra antes da vitória.',
|
||||
imageUrl: null,
|
||||
imageAlt: 'Plenária da Vitória',
|
||||
eventLabel: 'Sexta-feira, 2 de outubro · 18h',
|
||||
location: 'Online',
|
||||
startsAt,
|
||||
endsAt: null,
|
||||
canonicalUrl: 'https://jorgesolla1313.com.br/plenaria-vitoria',
|
||||
expiresAt: Date.parse(startsAt) + 2 * 60 * 60 * 1000,
|
||||
youtubeVideoId: null,
|
||||
},
|
||||
initialLive: null,
|
||||
}
|
||||
render(await HomePage())
|
||||
|
||||
expect(screen.getByRole('heading', { name: 'Plenária da Vitória' })).toBeTruthy()
|
||||
// Pré-live: the S29 agenda is the only action — never an entry button.
|
||||
expect(screen.getByRole('button', { name: 'Adicionar à agenda' })).toBeTruthy()
|
||||
expect(
|
||||
screen.queryByRole('link', { name: /Entrar na plenária|Assistir no YouTube/ }),
|
||||
).toBeNull()
|
||||
|
||||
cleanup()
|
||||
homeShareLink.section = null
|
||||
render(await HomePage())
|
||||
expect(screen.queryByRole('heading', { name: 'Plenária da Vitória' })).toBeNull()
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -2,6 +2,8 @@ import { readdirSync, readFileSync } from 'node:fs'
|
|||
import { relative, resolve } from 'node:path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { calendarDaySelector } from '../e2e/helpers/agendaPeriodLabels.js'
|
||||
|
||||
// Miss #54 (2026-07-30): a `page.goto` fired while the previous heavy RSC
|
||||
// navigation was still in flight aborted with `net::ERR_ABORTED`
|
||||
// (campaignSavedFilters, prod build). `goto` stays legal for cold loads and
|
||||
|
|
@ -84,3 +86,37 @@ describe('e2e WebAuthn virtual authenticator (miss #53)', () => {
|
|||
).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
// Miss #55 (2026-10-01): the C104 e2e clicked the calendar's end-day cell with
|
||||
// `getByRole('button', { name: '2 de Outubro de 2026' })`. The accessible name
|
||||
// ("sexta-feira, 2 de outubro de 2026") is a longer string and Playwright's
|
||||
// name matcher is substring + case-insensitive by default, so days 12 and 22
|
||||
// in the same grid matched too — a strict mode violation that only fired when
|
||||
// "today + 1" landed on a single-digit day of the month (2026-10-02).
|
||||
const AMBIGUOUS_DAY_NAME =
|
||||
/getByRole\('button',\s*\{\s*name:\s*(?:[A-Za-z_]*DayLabel\b|`[^`]*\bde\b[^`]*\$\{|"[^"]*\bde\b[^"]*20\d\d[^"]*"|'[^']*\bde\b[^']*20\d\d[^']*')/
|
||||
|
||||
describe('e2e calendar day-cell locator (miss #55)', () => {
|
||||
it('clicks calendar days through the data-day contract, never the date name', () => {
|
||||
const offenders: string[] = []
|
||||
|
||||
for (const file of specFiles) {
|
||||
const lines = readFileSync(file, 'utf8').split('\n')
|
||||
for (const [index, line] of lines.entries()) {
|
||||
if (AMBIGUOUS_DAY_NAME.test(line)) {
|
||||
offenders.push(`${relative(process.cwd(), file)}:${index + 1}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
expect(
|
||||
offenders,
|
||||
"click the day cell via calendarDaySelector ('[data-day=\"DD/MM/YYYY\"]') — the accessible name 'd de mês de ano' also matches 1d/2d (miss #55)",
|
||||
).toEqual([])
|
||||
})
|
||||
|
||||
it('builds the pt-BR data-day selector with a zero-padded day and month', () => {
|
||||
expect(calendarDaySelector('2026-10-02')).toBe('[data-day="02/10/2026"]')
|
||||
expect(calendarDaySelector('2026-01-31')).toBe('[data-day="31/01/2026"]')
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -5,12 +5,12 @@ import { join } from 'node:path'
|
|||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
// C234 — the write guards of the two face CLIs, exercised as subprocesses:
|
||||
// C242 — the write guards of the face/publish CLIs, exercised as subprocesses:
|
||||
// every refusal must happen before any engine call or DB connection.
|
||||
|
||||
const repoRoot = process.cwd()
|
||||
const enrollScript = join(repoRoot, 'scripts', 'enroll-face-subject.mjs')
|
||||
const indexScript = join(repoRoot, 'scripts', 'index-archive-faces.mjs')
|
||||
const publishScript = join(repoRoot, 'scripts', 'publish-archive-photos.mjs')
|
||||
|
||||
const run = (scriptPath: string, args: string[], env: Record<string, string> = {}) =>
|
||||
spawnSync(process.execPath, [scriptPath, ...args], {
|
||||
|
|
@ -26,8 +26,8 @@ const run = (scriptPath: string, args: string[], env: Record<string, string> = {
|
|||
PAYLOAD_SECRET: 'test-secret',
|
||||
TEQO_ENV: '',
|
||||
ALLOW_REMOTE_DB: '',
|
||||
FACE_ENROLL_CONFIRM: '',
|
||||
FACE_INDEX_CONFIRM: '',
|
||||
ARCHIVE_PUBLISH_CONFIRM: '',
|
||||
S3_BUCKET: '',
|
||||
S3_ENDPOINT: '',
|
||||
S3_ACCESS_KEY_ID: '',
|
||||
|
|
@ -44,53 +44,7 @@ const withS3 = {
|
|||
S3_SECRET_ACCESS_KEY: 'secret',
|
||||
}
|
||||
|
||||
describe('faces:enroll write guards (C234)', () => {
|
||||
const enrollArgs = ['--label', 'Pessoa', '--selfie', '/tmp/nao-existe-234.jpg', '--apply']
|
||||
|
||||
it('prints the help even without a database', () => {
|
||||
const result = run(enrollScript, ['--help'], { DATABASE_URL: '' })
|
||||
|
||||
expect(result.status).toBe(0)
|
||||
expect(result.stdout).toContain('FACE_ENROLL_CONFIRM')
|
||||
expect(result.stdout).toContain('busca-selfie-indice')
|
||||
})
|
||||
|
||||
it('refuses --apply on a production target without the intent flag', () => {
|
||||
const result = run(enrollScript, enrollArgs)
|
||||
|
||||
expect(result.status).toBe(1)
|
||||
expect(output(result)).toContain('FACE_ENROLL_CONFIRM=1')
|
||||
})
|
||||
|
||||
it('requires the declared TEQO_ENV once the intent flag is set', () => {
|
||||
const result = run(enrollScript, enrollArgs, { FACE_ENROLL_CONFIRM: '1' })
|
||||
|
||||
expect(result.status).toBe(1)
|
||||
expect(output(result)).toContain('TEQO_ENV')
|
||||
})
|
||||
|
||||
it('refuses a target database that does not match the declared environment', () => {
|
||||
const result = run(enrollScript, enrollArgs, {
|
||||
FACE_ENROLL_CONFIRM: '1',
|
||||
TEQO_ENV: 'staging',
|
||||
})
|
||||
|
||||
expect(result.status).toBe(1)
|
||||
expect(output(result)).toContain('≠ "teqo_staging"')
|
||||
})
|
||||
|
||||
it('passes the guards and refuses a missing selfie before the engine/DB', () => {
|
||||
const result = run(enrollScript, enrollArgs, {
|
||||
FACE_ENROLL_CONFIRM: '1',
|
||||
TEQO_ENV: 'production',
|
||||
})
|
||||
|
||||
expect(result.status).toBe(1)
|
||||
expect(output(result)).toContain('não foi possível ler a selfie')
|
||||
})
|
||||
})
|
||||
|
||||
describe('faces:index write guards (C234)', () => {
|
||||
describe('faces:index write guards (C242)', () => {
|
||||
it('prints the help even without a database', () => {
|
||||
const result = run(indexScript, ['--help'], { DATABASE_URL: '' })
|
||||
|
||||
|
|
@ -138,3 +92,37 @@ describe('faces:index write guards (C234)', () => {
|
|||
expect(output(result)).not.toContain('TEQO_ENV=')
|
||||
}, 30_000)
|
||||
})
|
||||
|
||||
describe('archive:publish write guards (C242)', () => {
|
||||
it('prints the help even without a database', () => {
|
||||
const result = run(publishScript, ['--help'], { DATABASE_URL: '' })
|
||||
|
||||
expect(result.status).toBe(0)
|
||||
expect(result.stdout).toContain('ARCHIVE_PUBLISH_CONFIRM')
|
||||
expect(result.stdout).toContain('--limit')
|
||||
})
|
||||
|
||||
it('refuses --apply on a production target without the intent flag', () => {
|
||||
const result = run(publishScript, ['--apply'])
|
||||
|
||||
expect(result.status).toBe(1)
|
||||
expect(output(result)).toContain('ARCHIVE_PUBLISH_CONFIRM=1')
|
||||
})
|
||||
|
||||
it('requires the declared TEQO_ENV once the intent flag is set', () => {
|
||||
const result = run(publishScript, ['--apply'], { ARCHIVE_PUBLISH_CONFIRM: '1' })
|
||||
|
||||
expect(result.status).toBe(1)
|
||||
expect(output(result)).toContain('TEQO_ENV')
|
||||
})
|
||||
|
||||
it('refuses a target database that does not match the declared environment', () => {
|
||||
const result = run(publishScript, ['--apply'], {
|
||||
ARCHIVE_PUBLISH_CONFIRM: '1',
|
||||
TEQO_ENV: 'staging',
|
||||
})
|
||||
|
||||
expect(result.status).toBe(1)
|
||||
expect(output(result)).toContain('≠ "teqo_staging"')
|
||||
})
|
||||
})
|
||||
|
|
|
|||
60
tests/unit/faceConsentTexts.unit.spec.ts
Normal file
60
tests/unit/faceConsentTexts.unit.spec.ts
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
// @vitest-environment node
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
buildConsentRichText,
|
||||
FACE_INDEX_CONSENT_PARAGRAPHS,
|
||||
FACE_INDEX_CONSENT_TEXT,
|
||||
FACE_SEARCH_CONSENT_PARAGRAPHS,
|
||||
FACE_SEARCH_CONSENT_TEXT,
|
||||
} from '../../scripts/lib/faceConsentTexts.mjs'
|
||||
|
||||
// C242 — the versioned legal texts of the selfie search: the Lexical shape the
|
||||
// Consent collection stores and the honest content the visitor reads.
|
||||
|
||||
describe('buildConsentRichText', () => {
|
||||
it('builds the Lexical root with one paragraph per text', () => {
|
||||
const rich = buildConsentRichText(['Um.', 'Dois.'])
|
||||
|
||||
expect(rich.root.type).toBe('root')
|
||||
expect(rich.root.children).toHaveLength(2)
|
||||
expect(rich.root.children[0].children[0].text).toBe('Um.')
|
||||
expect(rich.root.children[1].children[0].text).toBe('Dois.')
|
||||
})
|
||||
|
||||
it('produces an empty root for no paragraphs (fail-closed content)', () => {
|
||||
expect(buildConsentRichText([]).root.children).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
const flatten = (text: unknown): string =>
|
||||
(text as { root: { children: { children: { text: string }[] }[] } }).root.children
|
||||
.map((paragraph) => paragraph.children.map((child) => child.text).join(''))
|
||||
.join('\n')
|
||||
|
||||
describe('face consent texts', () => {
|
||||
it('has substantive paragraphs in both texts', () => {
|
||||
expect(FACE_SEARCH_CONSENT_PARAGRAPHS.length).toBeGreaterThanOrEqual(4)
|
||||
expect(FACE_INDEX_CONSENT_PARAGRAPHS.length).toBeGreaterThanOrEqual(4)
|
||||
for (const paragraph of [...FACE_SEARCH_CONSENT_PARAGRAPHS, ...FACE_INDEX_CONSENT_PARAGRAPHS]) {
|
||||
expect(paragraph.trim().length).toBeGreaterThan(40)
|
||||
}
|
||||
})
|
||||
|
||||
it('states the on-device processing and the LGPD basis in the query consent', () => {
|
||||
const text = flatten(FACE_SEARCH_CONSENT_TEXT)
|
||||
expect(text).toMatch(/aparelho/i)
|
||||
expect(text).toMatch(/não é enviada nem armazenada/i)
|
||||
expect(text).toMatch(/LGPD/)
|
||||
expect(text).toMatch(/retirar este consentimento/i)
|
||||
})
|
||||
|
||||
it('states the anonymous index and the self-service opt-out in the notice', () => {
|
||||
const text = flatten(FACE_INDEX_CONSENT_TEXT)
|
||||
expect(text).toMatch(/índice biométrico anônimo/i)
|
||||
expect(text).toMatch(/sem nome/i)
|
||||
expect(text).toMatch(/Minha presença/)
|
||||
expect(text).toMatch(/remoção de uma foto/i)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,128 +0,0 @@
|
|||
// @vitest-environment node
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
FACE_ENROLL_DEFAULT_OUT_DIR,
|
||||
faceEnrollReportStamp,
|
||||
formatFaceEnrollReport,
|
||||
parseFaceEnrollCliArgs,
|
||||
} from '../../scripts/lib/faceEnrollPlan.mjs'
|
||||
|
||||
// C234 — the pure parser/report of `pnpm faces:enroll`: every refusal happens
|
||||
// before any engine call or DB connection, and the human lines never carry the
|
||||
// descriptor.
|
||||
|
||||
describe('parseFaceEnrollCliArgs', () => {
|
||||
it('defaults to the dry-run with the standard receipt dir', () => {
|
||||
const options = parseFaceEnrollCliArgs(['--label', 'Pessoa', '--selfie', '/tmp/selfie.jpg'])
|
||||
expect(options).toEqual({
|
||||
apply: false,
|
||||
label: 'Pessoa',
|
||||
selfie: '/tmp/selfie.jpg',
|
||||
subject: null,
|
||||
out: FACE_ENROLL_DEFAULT_OUT_DIR,
|
||||
help: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('parses --apply, --subject, --out and --help', () => {
|
||||
const options = parseFaceEnrollCliArgs([
|
||||
'--apply',
|
||||
'--label',
|
||||
' Pessoa ',
|
||||
'--selfie',
|
||||
'/tmp/selfie.jpg',
|
||||
'--subject',
|
||||
'7',
|
||||
'--out',
|
||||
'data/outro',
|
||||
])
|
||||
expect(options.apply).toBe(true)
|
||||
expect(options.label).toBe(' Pessoa ')
|
||||
expect(options.subject).toBe(7)
|
||||
expect(options.out).toBe('data/outro')
|
||||
|
||||
expect(parseFaceEnrollCliArgs(['--help']).help).toBe(true)
|
||||
})
|
||||
|
||||
it('fails closed on missing label/selfie, bad subject and unknown args', () => {
|
||||
expect(() => parseFaceEnrollCliArgs(['--selfie', '/tmp/a.jpg'])).toThrow(/--label/)
|
||||
expect(() => parseFaceEnrollCliArgs(['--label', 'Pessoa'])).toThrow(/--selfie/)
|
||||
expect(() => parseFaceEnrollCliArgs(['--label', ' ', '--selfie', '/tmp/a.jpg'])).toThrow(
|
||||
/--label/,
|
||||
)
|
||||
expect(() =>
|
||||
parseFaceEnrollCliArgs(['--label', 'P', '--selfie', '/tmp/a.jpg', '--subject', '0']),
|
||||
).toThrow(/--subject/)
|
||||
expect(() =>
|
||||
parseFaceEnrollCliArgs(['--label', 'P', '--selfie', '/tmp/a.jpg', '--nope']),
|
||||
).toThrow(/argumento desconhecido/)
|
||||
expect(() => parseFaceEnrollCliArgs(['--label'])).toThrow(/faltou valor/)
|
||||
expect(() =>
|
||||
parseFaceEnrollCliArgs(['--label', 'P', '--selfie', '/tmp/a.jpg', '--out', '../etc']),
|
||||
).toThrow(/--out/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('faceEnrollReportStamp', () => {
|
||||
it('is filesystem-safe', () => {
|
||||
expect(faceEnrollReportStamp('2026-09-27T16:42:01.123Z')).toBe('2026-09-27T16-42-01-123Z')
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatFaceEnrollReport', () => {
|
||||
const base = {
|
||||
runAt: '2026-09-27T16:42:01.123Z',
|
||||
mode: 'apply',
|
||||
target: '127.0.0.1/teqo_wt234',
|
||||
model: 'face-api@1.7.15/faceRecognitionNet',
|
||||
label: 'Pessoa',
|
||||
subjectId: 3,
|
||||
subjectAction: 'created' as const,
|
||||
faceCount: 1,
|
||||
allowed: true,
|
||||
reason: null,
|
||||
consentKey: 'busca-selfie-indice',
|
||||
consentHash: 'abc',
|
||||
durationMs: 10,
|
||||
}
|
||||
|
||||
it('reports the enrollment without ever mentioning a descriptor', () => {
|
||||
const lines = formatFaceEnrollReport(base)
|
||||
const text = lines.join('\n')
|
||||
|
||||
expect(text).toContain('criada: #3 (Pessoa)')
|
||||
expect(text).toContain('busca-selfie-indice')
|
||||
expect(text).toContain('pnpm faces:index --apply')
|
||||
expect(text).not.toMatch(/descriptor|vetor|vector/i)
|
||||
})
|
||||
|
||||
it('shows the dry-run as a plan, never as a write', () => {
|
||||
const lines = formatFaceEnrollReport({
|
||||
...base,
|
||||
mode: 'plan',
|
||||
subjectAction: null,
|
||||
subjectId: null,
|
||||
})
|
||||
const text = lines.join('\n')
|
||||
|
||||
expect(text).toContain('plano: Pessoa (nada gravado')
|
||||
expect(text).not.toContain('criada')
|
||||
})
|
||||
|
||||
it('shows the refusal reason and no subject line', () => {
|
||||
const lines = formatFaceEnrollReport({
|
||||
...base,
|
||||
allowed: false,
|
||||
subjectId: null,
|
||||
subjectAction: null,
|
||||
faceCount: 2,
|
||||
reason: 'mais de um rosto na selfie',
|
||||
})
|
||||
const text = lines.join('\n')
|
||||
|
||||
expect(text).toContain('RECUSADO: mais de um rosto na selfie')
|
||||
expect(text).not.toContain('criada')
|
||||
})
|
||||
})
|
||||
|
|
@ -12,8 +12,8 @@ import {
|
|||
summarizeFaceIndexResults,
|
||||
} from '../../scripts/lib/faceIndexPlan.mjs'
|
||||
|
||||
// C234 — the pure parser/summaries of `pnpm faces:index`: the honest staleness
|
||||
// accounting and the operator-facing lines.
|
||||
// C242 — the pure parser/summaries of `pnpm faces:index`: the honest staleness
|
||||
// accounting (scope B: descriptors, not subjects) and the operator-facing lines.
|
||||
|
||||
describe('parseFaceIndexCliArgs', () => {
|
||||
it('defaults to the dry-run and parses the modes', () => {
|
||||
|
|
@ -47,82 +47,43 @@ describe('parseFaceIndexCliArgs', () => {
|
|||
})
|
||||
|
||||
describe('summarizeFaceIndexResults', () => {
|
||||
it('counts indexed/linked/failed and aggregates links per subject', () => {
|
||||
it('counts indexed photos, stored descriptors and failures with the stage', () => {
|
||||
const summary = summarizeFaceIndexResults([
|
||||
{ photoId: 1, status: 'indexed', matchedSubjects: [3, 4] },
|
||||
{ photoId: 2, status: 'indexed', matchedSubjects: [3] },
|
||||
{ photoId: 3, status: 'indexed', matchedSubjects: [] },
|
||||
{ photoId: 1, status: 'indexed', descriptorCount: 3 },
|
||||
{ photoId: 2, status: 'indexed', descriptorCount: 0 },
|
||||
{ photoId: 3, status: 'indexed', descriptorCount: 1 },
|
||||
{ photoId: 4, status: 'failed', stage: 'download', error: 'sem arquivo' },
|
||||
])
|
||||
|
||||
expect(summary.indexed).toBe(3)
|
||||
expect(summary.descriptors).toBe(4)
|
||||
expect(summary.failed).toBe(1)
|
||||
expect(summary.linkedPhotos).toBe(2)
|
||||
expect(summary.linksBySubject).toEqual([
|
||||
{ subjectId: 3, photos: 2 },
|
||||
{ subjectId: 4, photos: 1 },
|
||||
])
|
||||
expect(summary.failures).toEqual([{ photoId: 4, stage: 'download', error: 'sem arquivo' }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('summarizeFaceIndexInventory', () => {
|
||||
const queue = { indexKey: 'k', eligibleSubjects: 2, totalApproved: 10, stale: 4 }
|
||||
const subjects = [
|
||||
{
|
||||
id: 1,
|
||||
status: 'active',
|
||||
model: 'face-api@1.7.15/faceRecognitionNet',
|
||||
consentHash: 'hash-atual',
|
||||
vector: [0],
|
||||
matchedPhotoIds: [1, 2],
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
status: 'active',
|
||||
model: 'face-api@1.7.15/faceRecognitionNet',
|
||||
consentHash: 'hash-antigo',
|
||||
vector: [0],
|
||||
matchedPhotoIds: [],
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
status: 'removed',
|
||||
model: 'face-api@1.7.15/faceRecognitionNet',
|
||||
consentHash: 'hash-atual',
|
||||
vector: null,
|
||||
matchedPhotoIds: [],
|
||||
},
|
||||
]
|
||||
|
||||
it('derives the honest gap, the consent staleness and the links breakdown', () => {
|
||||
it('derives the honest gap and the stored descriptor count', () => {
|
||||
const inventory = summarizeFaceIndexInventory({
|
||||
queue,
|
||||
subjects,
|
||||
currentConsentHash: 'hash-atual',
|
||||
queue: { indexKey: 'face-api@1.7.15/faceRecognitionNet', totalApproved: 10, stale: 4 },
|
||||
descriptors: 23,
|
||||
})
|
||||
|
||||
expect(inventory).toEqual({
|
||||
indexKey: 'k',
|
||||
indexKey: 'face-api@1.7.15/faceRecognitionNet',
|
||||
totalApproved: 10,
|
||||
indexed: 6,
|
||||
stale: 4,
|
||||
eligibleSubjects: 2,
|
||||
activeSubjects: 2,
|
||||
removedSubjects: 1,
|
||||
staleConsentSubjects: 1,
|
||||
linkedPhotos: 2,
|
||||
linksBySubject: [{ subjectId: 1, photos: 2 }],
|
||||
descriptors: 23,
|
||||
})
|
||||
})
|
||||
|
||||
it('treats a missing current consent as stale for everyone', () => {
|
||||
it('never reports a negative indexed count', () => {
|
||||
const inventory = summarizeFaceIndexInventory({
|
||||
queue,
|
||||
subjects,
|
||||
currentConsentHash: null,
|
||||
queue: { indexKey: 'k', totalApproved: 2, stale: 5 },
|
||||
descriptors: 0,
|
||||
})
|
||||
expect(inventory.staleConsentSubjects).toBe(2)
|
||||
expect(inventory.indexed).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
|
|
@ -136,20 +97,14 @@ describe('formatting', () => {
|
|||
totalApproved: 10,
|
||||
indexed: 6,
|
||||
stale: 4,
|
||||
eligibleSubjects: 2,
|
||||
activeSubjects: 2,
|
||||
removedSubjects: 1,
|
||||
staleConsentSubjects: 1,
|
||||
linkedPhotos: 2,
|
||||
linksBySubject: [{ subjectId: 1, photos: 2 }],
|
||||
descriptors: 23,
|
||||
},
|
||||
'face-api@1.7.15/faceRecognitionNet',
|
||||
)
|
||||
const text = lines.join('\n')
|
||||
expect(text).toContain('fotos aprovadas: 10')
|
||||
expect(text).toContain('desatualizadas (a processar): 4')
|
||||
expect(text).toContain('consentimento vencido')
|
||||
expect(text).toContain('sujeito #1: 2 foto(s)')
|
||||
expect(text).toContain('rostos no índice (modelo atual): 23')
|
||||
})
|
||||
|
||||
it('prints the apply summary with failures', () => {
|
||||
|
|
@ -157,20 +112,18 @@ describe('formatting', () => {
|
|||
mode: 'apply',
|
||||
target: 'host/db',
|
||||
model: 'face-api@1.7.15/faceRecognitionNet',
|
||||
queue: { items: 3, totalApproved: 10, eligibleSubjects: 1 },
|
||||
queue: { items: 3, totalApproved: 10 },
|
||||
summary: {
|
||||
indexed: 2,
|
||||
failed: 1,
|
||||
linkedPhotos: 1,
|
||||
linksBySubject: [{ subjectId: 3, photos: 1 }],
|
||||
descriptors: 5,
|
||||
failures: [{ photoId: 4, stage: 'analyze', error: 'engine fora' }],
|
||||
},
|
||||
}
|
||||
const text = formatFaceIndexReport(report).join('\n')
|
||||
|
||||
expect(text).toContain('modo: apply')
|
||||
expect(text).toContain('processadas: 2 | vinculadas a alguém: 1 | falharam: 1')
|
||||
expect(text).toContain('sujeito #3: 1 foto(s)')
|
||||
expect(text).toContain('processadas: 2 | rostos indexados: 5 | falharam: 1')
|
||||
expect(text).toContain('✗ foto 4 [analyze]: engine fora')
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -6,39 +6,20 @@ import type { ArchivePhotoPublicItem } from '@/lib/archivePhotoPublicCatalog'
|
|||
import {
|
||||
FACE_SEARCH_DESCRIPTOR_LENGTH,
|
||||
FACE_SEARCH_MAX_DISTANCE,
|
||||
FACE_SEARCH_MODEL,
|
||||
faceEuclideanDistance,
|
||||
faceStubDescriptorFromBytes,
|
||||
faceSubjectIsEligible,
|
||||
findFaceMatch,
|
||||
findFaceDescriptorPhotoIds,
|
||||
readFaceVector,
|
||||
toFaceSearchPhotoView,
|
||||
} from '@/lib/faceSearch'
|
||||
|
||||
// C234 — the pure contract of the selfie search: vector validation, the
|
||||
// euclidean math, the eligibility of an enrolled subject and the result view
|
||||
// model that by shape cannot carry a score or a third-party name.
|
||||
// C242 — the pure contract of the selfie search: vector validation, the
|
||||
// euclidean math, the anonymous descriptor match (which by shape cannot carry a
|
||||
// score or a third-party name) and the result view model.
|
||||
|
||||
const vectorOf = (value: number, length = FACE_SEARCH_DESCRIPTOR_LENGTH): number[] =>
|
||||
Array.from({ length }, () => value)
|
||||
|
||||
const subjectOf = (
|
||||
overrides: Partial<{
|
||||
id: number
|
||||
status: string
|
||||
model: string
|
||||
consentHash: string | null
|
||||
vector: unknown
|
||||
}> = {},
|
||||
) => ({
|
||||
id: 1,
|
||||
status: 'active',
|
||||
model: FACE_SEARCH_MODEL,
|
||||
consentHash: 'hash-atual',
|
||||
vector: vectorOf(0),
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('readFaceVector', () => {
|
||||
it('accepts exactly the descriptor length of finite numbers', () => {
|
||||
expect(readFaceVector(vectorOf(0.25))).toHaveLength(FACE_SEARCH_DESCRIPTOR_LENGTH)
|
||||
|
|
@ -67,60 +48,41 @@ describe('faceEuclideanDistance', () => {
|
|||
})
|
||||
})
|
||||
|
||||
describe('faceSubjectIsEligible', () => {
|
||||
const current = { model: FACE_SEARCH_MODEL, consentHash: 'hash-atual' }
|
||||
|
||||
it('requires active status, the current model and the current consent hash', () => {
|
||||
expect(faceSubjectIsEligible(subjectOf(), current)).toBe(true)
|
||||
expect(faceSubjectIsEligible(subjectOf({ status: 'removed' }), current)).toBe(false)
|
||||
expect(faceSubjectIsEligible(subjectOf({ model: 'outro-modelo' }), current)).toBe(false)
|
||||
expect(faceSubjectIsEligible(subjectOf({ consentHash: 'hash-antigo' }), current)).toBe(false)
|
||||
expect(faceSubjectIsEligible(subjectOf({ consentHash: null }), current)).toBe(false)
|
||||
describe('findFaceDescriptorPhotoIds', () => {
|
||||
const near = (photoId: number, delta = 0.1) => ({
|
||||
photoId,
|
||||
vector: [...vectorOf(0).slice(1), delta],
|
||||
})
|
||||
})
|
||||
|
||||
describe('findFaceMatch', () => {
|
||||
const current = { model: FACE_SEARCH_MODEL, consentHash: 'hash-atual' }
|
||||
|
||||
it('returns the closest eligible subject strictly under the threshold', () => {
|
||||
const far = subjectOf({ id: 1, vector: [...vectorOf(0).slice(1), 1] })
|
||||
const near = subjectOf({ id: 2, vector: [...vectorOf(0).slice(1), 0.1] })
|
||||
const match = findFaceMatch({
|
||||
vector: vectorOf(0),
|
||||
subjects: [far, near],
|
||||
...current,
|
||||
})
|
||||
expect(match?.id).toBe(2)
|
||||
const far = (photoId: number, delta = FACE_SEARCH_MAX_DISTANCE + 1) => ({
|
||||
photoId,
|
||||
vector: [...vectorOf(0).slice(1), delta],
|
||||
})
|
||||
|
||||
it('ignores ineligible subjects and subjects with a malformed vector', () => {
|
||||
const removed = subjectOf({ id: 1, status: 'removed', vector: vectorOf(0) })
|
||||
const staleModel = subjectOf({ id: 2, model: 'outro', vector: vectorOf(0) })
|
||||
const staleConsent = subjectOf({ id: 3, consentHash: 'antigo', vector: vectorOf(0) })
|
||||
const broken = subjectOf({ id: 4, vector: [1, 2, 3] })
|
||||
const eligible = subjectOf({ id: 5, vector: vectorOf(0) })
|
||||
|
||||
const match = findFaceMatch({
|
||||
vector: vectorOf(0),
|
||||
subjects: [removed, staleModel, staleConsent, broken, eligible],
|
||||
...current,
|
||||
})
|
||||
expect(match?.id).toBe(5)
|
||||
it('returns the distinct photo ids with a face under the threshold', () => {
|
||||
const ids = findFaceDescriptorPhotoIds(vectorOf(0), [
|
||||
near(7),
|
||||
near(7, 0.2),
|
||||
near(9, 0.3),
|
||||
far(11),
|
||||
])
|
||||
expect(ids).toEqual([7, 9])
|
||||
})
|
||||
|
||||
it('never matches at or beyond the threshold and answers null when nothing is close', () => {
|
||||
const atThreshold = subjectOf({
|
||||
id: 1,
|
||||
vector: [...vectorOf(0).slice(1), FACE_SEARCH_MAX_DISTANCE],
|
||||
})
|
||||
expect(findFaceMatch({ vector: vectorOf(0), subjects: [atThreshold], ...current })).toBeNull()
|
||||
it('never matches at or beyond the threshold and answers empty when nothing is close', () => {
|
||||
expect(
|
||||
findFaceDescriptorPhotoIds(vectorOf(0), [
|
||||
{ photoId: 1, vector: [...vectorOf(0).slice(1), FACE_SEARCH_MAX_DISTANCE] },
|
||||
]),
|
||||
).toEqual([])
|
||||
expect(findFaceDescriptorPhotoIds(vectorOf(0), [far(2)])).toEqual([])
|
||||
expect(findFaceDescriptorPhotoIds(vectorOf(0), [])).toEqual([])
|
||||
})
|
||||
|
||||
const far = subjectOf({
|
||||
id: 2,
|
||||
vector: [...vectorOf(0).slice(1), FACE_SEARCH_MAX_DISTANCE + 1],
|
||||
})
|
||||
expect(findFaceMatch({ vector: vectorOf(0), subjects: [far], ...current })).toBeNull()
|
||||
expect(findFaceMatch({ vector: vectorOf(0), subjects: [], ...current })).toBeNull()
|
||||
it('accepts Float32Array descriptors (the in-process cache shape)', () => {
|
||||
const ids = findFaceDescriptorPhotoIds(vectorOf(0), [
|
||||
{ photoId: 3, vector: Float32Array.from(near(3).vector) },
|
||||
])
|
||||
expect(ids).toEqual([3])
|
||||
})
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import {
|
|||
normalizeShareLinkDescription,
|
||||
resolveLiveShareLinkDestination,
|
||||
resolveShareLinkMode,
|
||||
resolveShareLinkYoutubeVideoId,
|
||||
SHARE_LINK_MODES,
|
||||
SHARE_LINK_RESERVED_SLUGS,
|
||||
SHARE_LINK_SLUG_PATTERN,
|
||||
|
|
@ -137,6 +138,48 @@ describe('resolveLiveShareLinkDestination (S29)', () => {
|
|||
})
|
||||
})
|
||||
|
||||
describe('resolveShareLinkYoutubeVideoId (S44)', () => {
|
||||
it.each([
|
||||
'https://www.youtube.com/live/77bUgl7cvQ8',
|
||||
'https://youtube.com/live/77bUgl7cvQ8?feature=share',
|
||||
'https://youtu.be/77bUgl7cvQ8',
|
||||
'https://www.youtube.com/watch?v=77bUgl7cvQ8',
|
||||
'https://m.youtube.com/watch?v=77bUgl7cvQ8&t=10s',
|
||||
'https://www.youtube.com/embed/77bUgl7cvQ8',
|
||||
'https://www.youtube-nocookie.com/embed/77bUgl7cvQ8',
|
||||
'https://www.youtube.com/shorts/77bUgl7cvQ8',
|
||||
])('extracts the id from %s', (url) => {
|
||||
expect(resolveShareLinkYoutubeVideoId([{ label: 'YouTube', url }])).toBe('77bUgl7cvQ8')
|
||||
})
|
||||
|
||||
it('skips invalid rows and picks the first valid YouTube destination', () => {
|
||||
expect(
|
||||
resolveShareLinkYoutubeVideoId([
|
||||
{ label: 'Meet', url: 'https://meet.google.com/abc-defg-hij' },
|
||||
{ label: 'YouTube', url: 'https://www.youtube.com/live/77bUgl7cvQ8' },
|
||||
{ label: 'Outro', url: 'https://youtu.be/AAAAAAAAAAA' },
|
||||
]),
|
||||
).toBe('77bUgl7cvQ8')
|
||||
})
|
||||
|
||||
it('fails closed without a valid YouTube id', () => {
|
||||
expect(resolveShareLinkYoutubeVideoId(null)).toBeNull()
|
||||
expect(resolveShareLinkYoutubeVideoId([])).toBeNull()
|
||||
expect(
|
||||
resolveShareLinkYoutubeVideoId([{ label: 'Meet', url: 'https://meet.google.com/x' }]),
|
||||
).toBeNull()
|
||||
expect(
|
||||
resolveShareLinkYoutubeVideoId([{ label: 'Y', url: 'https://youtu.be/curto' }]),
|
||||
).toBeNull()
|
||||
expect(resolveShareLinkYoutubeVideoId([{ label: 'Y', url: 'javascript:alert(1)' }])).toBeNull()
|
||||
expect(
|
||||
resolveShareLinkYoutubeVideoId([
|
||||
{ label: 'Y', url: 'https://notyoutube.com/live/77bUgl7cvQ8' },
|
||||
]),
|
||||
).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('shareLink ics contract (S29)', () => {
|
||||
it('hangs the download off the slug namespace', () => {
|
||||
expect(shareLinkIcsPath('plenaria-saude')).toBe('/plenaria-saude/evento.ics')
|
||||
|
|
|
|||
120
tests/unit/shareLinkHomeSection.unit.spec.ts
Normal file
120
tests/unit/shareLinkHomeSection.unit.spec.ts
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { formatBahiaEventDayLabel, formatBahiaEventTimeLabel } from '@/lib/campaignTime'
|
||||
import {
|
||||
buildShareLinkHomeSectionView,
|
||||
resolveShareLinkLiveActionLabel,
|
||||
SHARE_LINK_HOME_SECTION_SLUG,
|
||||
} from '@/lib/shareLinkHomeSection'
|
||||
|
||||
const STARTS_AT = '2026-10-02T21:00:00.000Z'
|
||||
const ENDS_AT = '2026-10-03T00:00:00.000Z'
|
||||
const BEFORE_END = Date.parse('2026-10-02T22:00:00.000Z')
|
||||
|
||||
const baseLink = {
|
||||
slug: SHARE_LINK_HOME_SECTION_SLUG,
|
||||
title: 'Plenária da Vitória',
|
||||
description: 'O time de Jorge Solla se encontra antes da vitória.',
|
||||
startsAt: STARTS_AT,
|
||||
location: 'Online',
|
||||
destinations: [
|
||||
{ label: 'Google Meet', url: 'https://meet.google.com/fyz-rurx-biv' },
|
||||
{ label: 'Youtube', url: 'https://www.youtube.com/live/77bUgl7cvQ8' },
|
||||
],
|
||||
}
|
||||
|
||||
describe('buildShareLinkHomeSectionView (S44)', () => {
|
||||
it('builds the serializable view while the event window is open', () => {
|
||||
const view = buildShareLinkHomeSectionView({
|
||||
link: { ...baseLink, image: { alt: 'Plenária da Vitória 1313' } },
|
||||
imageUrl: '/api/media/file/plenaria.jpg',
|
||||
canonicalUrl: 'https://jorgesolla1313.com.br/plenaria-vitoria',
|
||||
nowMs: BEFORE_END,
|
||||
})
|
||||
|
||||
expect(view).toEqual({
|
||||
slug: 'plenaria-vitoria',
|
||||
title: 'Plenária da Vitória',
|
||||
description: 'O time de Jorge Solla se encontra antes da vitória.',
|
||||
imageUrl: '/api/media/file/plenaria.jpg',
|
||||
imageAlt: 'Plenária da Vitória 1313',
|
||||
eventLabel: 'Sexta-feira, 2 de outubro · 18h',
|
||||
location: 'Online',
|
||||
startsAt: STARTS_AT,
|
||||
endsAt: null,
|
||||
canonicalUrl: 'https://jorgesolla1313.com.br/plenaria-vitoria',
|
||||
expiresAt: Date.parse('2026-10-02T23:00:00.000Z'),
|
||||
youtubeVideoId: '77bUgl7cvQ8',
|
||||
})
|
||||
})
|
||||
|
||||
it('honors a configured end and drops the section at the exact close', () => {
|
||||
const view = buildShareLinkHomeSectionView({
|
||||
link: { ...baseLink, endsAt: ENDS_AT },
|
||||
imageUrl: null,
|
||||
canonicalUrl: null,
|
||||
nowMs: Date.parse(ENDS_AT) - 1,
|
||||
})
|
||||
expect(view?.expiresAt).toBe(Date.parse(ENDS_AT))
|
||||
|
||||
expect(
|
||||
buildShareLinkHomeSectionView({
|
||||
link: { ...baseLink, endsAt: ENDS_AT },
|
||||
imageUrl: null,
|
||||
canonicalUrl: null,
|
||||
nowMs: Date.parse(ENDS_AT),
|
||||
}),
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('fails closed without a valid event window', () => {
|
||||
const args = { imageUrl: null, canonicalUrl: null, nowMs: BEFORE_END }
|
||||
expect(
|
||||
buildShareLinkHomeSectionView({ ...args, link: { ...baseLink, startsAt: null } }),
|
||||
).toBeNull()
|
||||
expect(
|
||||
buildShareLinkHomeSectionView({ ...args, link: { ...baseLink, startsAt: 'lixo' } }),
|
||||
).toBeNull()
|
||||
expect(
|
||||
buildShareLinkHomeSectionView({
|
||||
...args,
|
||||
link: { ...baseLink, startsAt: '2026-09-30T21:00:00.000Z' },
|
||||
}),
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('renders without the player when there is no YouTube destination', () => {
|
||||
const view = buildShareLinkHomeSectionView({
|
||||
link: { ...baseLink, destinations: [{ label: 'Meet', url: 'https://meet.google.com/x' }] },
|
||||
imageUrl: null,
|
||||
canonicalUrl: null,
|
||||
nowMs: BEFORE_END,
|
||||
})
|
||||
expect(view?.youtubeVideoId).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveShareLinkLiveActionLabel (S44)', () => {
|
||||
it.each([
|
||||
['https://meet.google.com/fyz-rurx-biv', 'Entrar na plenária'],
|
||||
['https://www.youtube.com/live/77bUgl7cvQ8', 'Assistir no YouTube'],
|
||||
['https://youtu.be/77bUgl7cvQ8', 'Assistir no YouTube'],
|
||||
['https://zoom.us/j/123', 'Entrar'],
|
||||
['javascript:alert(1)', 'Entrar'],
|
||||
])('labels %s', (href, label) => {
|
||||
expect(resolveShareLinkLiveActionLabel({ href, label: 'Destino' })).toBe(label)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Bahia event labels (S44)', () => {
|
||||
it('splits the day and the time for the home meta row', () => {
|
||||
expect(formatBahiaEventDayLabel(STARTS_AT)).toBe('sexta-feira, 2 de outubro')
|
||||
expect(formatBahiaEventTimeLabel(STARTS_AT)).toBe('18h')
|
||||
expect(formatBahiaEventTimeLabel('2026-10-02T21:30:00.000Z')).toBe('18h30')
|
||||
})
|
||||
|
||||
it('returns an empty string for an unparsable instant', () => {
|
||||
expect(formatBahiaEventDayLabel('lixo')).toBe('')
|
||||
expect(formatBahiaEventTimeLabel('lixo')).toBe('')
|
||||
})
|
||||
})
|
||||
|
|
@ -1,7 +1,5 @@
|
|||
import {
|
||||
validateExcludedItemId,
|
||||
YOUTUBE_VIDEO_ID_PATTERN,
|
||||
} from '@/utilities/socialFeed/excludedItems'
|
||||
import { YOUTUBE_VIDEO_ID_PATTERN } from '@/lib/shareLink'
|
||||
import { validateExcludedItemId } from '@/utilities/socialFeed/excludedItems'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
describe('validateExcludedItemId', () => {
|
||||
|
|
|
|||
Loading…
Reference in a new issue