Compare commits

...

13 commits

Author SHA1 Message Date
Francisco Solla
b03b7bd969 feat(OPS103): staging no homeserver com verify único e aprovações separadas (Closes #968) 2026-09-12 22:48:22 -03:00
Francisco Solla
907b9ba96b refactor(OPS102): fixes do /simplify — comentários vivos alinhados, pin do exit 0 com mais dentes, runbook/changelog precisos 2026-09-12 21:32:28 -03:00
Francisco Solla
c9bd627de4 fix(OPS102): deploy manual roda até o fim mesmo com main à frente (remove guards de stale run) (Closes #962) 2026-09-12 21:32:28 -03:00
Francisco Solla
8e0366d3ba feat(S14): cards personalizados — ajustes de fidelidade e experiência
A home abre o mesmo compositor do /cards ali mesmo (dialog no desktop,
drawer no mobile) e perde o CTA: os três modelos viram botões e nada
navega. A seção sobe para imediatamente antes da captura de novidades.
O nome no card e no tile alinha à esquerda com o SOU (x=213) via leftX
+ drawCardName extraído; o tile passa a desenhar SEU NOME com o próprio
pipeline real (canvas transparente sobre a base). Modal sem o vão
interno (p-0 sm:p-0) e ajuda legível no tema campaign-site
(--muted-foreground). Remove a variante link e o cardModelHref sem call
site. Unit atualizado (+ drawCardName) e e2e com alinhamento por pixel;
sem migration, sem PII em rede.
2026-09-12 21:01:15 -03:00
Francisco Solla
7990c79b3e refactor(campaign): C150 — simplify (catch/sessão do picker, leitura única, webcal morto) + changelog e débito C156 2026-09-12 21:01:12 -03:00
Francisco Solla
cc6d2abd04 feat(campaign): C150 — calendário principal escolhido pelo candidato/coordenador + inscrição de staff no Google (Closes #935) 2026-09-12 21:01:12 -03:00
Francisco Solla
677dbbf0ea docs(plans): registra OPS103 — staging no homeserver com verify único e aprovações separadas 2026-09-12 20:55:07 -03:00
Francisco Solla
fa6933c1cd feat(C152): piloto da fonte de vídeos e transcrição minutada da Câmara
Spike de viabilidade da fonte (sem DB/Payload): script + lib pura + unit tests; 3 discursos (55ª/56ª/57ª) processados ponta a ponta com segmentos ASR; relatório em docs/research/.
2026-09-12 20:43:36 -03:00
Francisco Solla
6d676609cd feat(C151): marca atividade como evento público
Adiciona o checkbox publicEvent ("Evento público", default false, indexado)
à collection activity para registrar a intenção de expor o compromisso na
futura agenda pública do site — sem consumo agora e sem mudar agenda, lista,
detalhe ou o espelho do Google.

- Activity.ts: campo checkbox + snapshot do guard de liderança
- zod/formData/view model do form + ActivityOverlay (ao lado de "Todo o dia")
- migration add_activity_public_event + types regenerados
- unit (overlay), int (parse/persistência/reabertura) e e2e (roundtrip)
2026-09-12 20:28:59 -03:00
Francisco Solla
bf4a4d9807 docs(plans): registra OPS102 — deploy manual roda até o fim mesmo com main à frente 2026-09-12 20:13:52 -03:00
Francisco Solla
1ff755a8ad docs(plans): registra S14 — cards personalizados: ajustes de fidelidade e experiência 2026-09-12 19:52:54 -03:00
Francisco Solla
e29fb8df1d test(int): C149 — isola o advisory lock do harness e2e (vitest fora do processo Playwright) 2026-09-12 19:49:24 -03:00
Francisco Solla
d9b778b269 feat(campaign): C149 — botão Conectar com o Google (OAuth) substitui a configuração manual da service account (Closes #934) 2026-09-12 19:49:24 -03:00
99 changed files with 36054 additions and 537 deletions

View file

@ -14,8 +14,9 @@ PAYLOAD_SECRET=YOUR_SECRET_HERE
# (dev/test). The bucket stays PRIVATE: the app proxies the files through its
# /media/file route (the plugin streams each object from Garage), so no public
# bucket/DNS is needed. Production: S3_BUCKET=teqo-media,
# S3_ENDPOINT=http://100.119.220.31:3900 (tailnet do homeserver). Dev may use its
# own bucket — never share the production bucket across environments.
# S3_ENDPOINT=http://100.119.220.31:3900 (tailnet do homeserver). Staging
# (OPS103) has its own bucket `teqo-media-staging` — never share the
# production bucket across environments.
S3_BUCKET=
S3_ENDPOINT=
S3_REGION=garage
@ -65,3 +66,13 @@ DEEPINFRA_API_KEY=YOUR_DEEPINFRA_API_KEY_HERE
# collection. Absent/malformed → the agenda shows "não configurado" and the
# mirror stays off — the Teqo agenda never depends on this.
GOOGLE_CALENDAR_SERVICE_ACCOUNT_KEY=
# C149 — Google OAuth client pair for the "Conectar com o Google" button. Create
# a "Web application" OAuth client in the same GCP project, register the
# redirect URIs (`<public site>/campanha/agenda/google-oauth/callback`, plus the
# local dev origin) and publish the app to production (unverified is fine for
# internal use) so the refresh token does not expire in ~7 days. Absent → the
# dialog falls back to the service-account runbook and the mirror keeps working
# via `GOOGLE_CALENDAR_SERVICE_ACCOUNT_KEY`.
GOOGLE_CALENDAR_OAUTH_CLIENT_ID=
GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET=

View file

@ -1,28 +1,45 @@
# Manual production deploy (OPS71 — GitHub Actions). `workflow_dispatch`
# only: there is NO automatic main verifier anymore (ci.yml eliminated in the
# gate 2026-08-19) — publishing is a deliberate operator act, and this
# workflow runs the FULL suite (no scope skips, e2e included) before the
# deploy job touches the homeserver.
# Manual deploy (OPS71 — GitHub Actions; staging + production since OPS103).
# `workflow_dispatch` only: there is NO automatic main verifier anymore
# (ci.yml eliminated in the gate 2026-08-19) — publishing is a deliberate
# operator act, and this workflow runs the FULL suite (no scope skips, e2e
# included) before any deploy job touches the homeserver.
#
# TWO jobs, same workflow:
# verify — ubuntu-latest (hosted): full cascade (guards for PR contracts are
# left out — they gate PRs, not production).
# deploy — needs: [verify], runs-on [self-hosted, homeserver]: the GitHub
# self-hosted runner ON the homeserver executes
# scripts/deploy-homeserver.sh LOCALLY (no SSH; outbound-only
# runner, works behind the Cloudflare tunnel). The hosted job
# never reaches the homeserver; the self-hosted job never counts
# hosted minutes.
# THREE jobs, same workflow (OPS103):
# verify — ubuntu-latest (hosted): full cascade (guards for PR
# contracts are left out — they gate PRs, not
# production). Untouched by OPS103; it verifies the
# COMMIT once for both environments.
# deploy-staging — needs: [verify], environment: staging (no reviewer:
# the dispatch itself is the deliberate act). Runs the
# same script with TEQO_ENV=staging (teqo-staging,
# 127.0.0.1:1314).
# deploy-production — needs: [deploy-staging], environment: production
# (required reviewer fsolla, configured in the repo).
# A red staging fail-closes production. Same script,
# TEQO_ENV=production (teqo-1313, 127.0.0.1:1313).
#
# The production build CANNOT leave the homeserver (migrate pre-build on the
# prod DB — OPS66 — and the compose network / local registry localhost:5000),
# which is exactly why the hosted job only verifies and the self-hosted job
# only builds + deploys. Deploy is idempotent ("already deployed" guard in
# deploy-homeserver.sh) and serialized by flock on the homeserver.
# Both deploy jobs run on the GitHub self-hosted runner ON the homeserver
# (labels self-hosted + homeserver): the script executes locally — no SSH
# hop, no workstation involvement. Deliberately wired ONLY here (manual
# dispatch), never in ci-pr.yml: a self-hosted job is code execution on the
# production machine, and only an explicit dispatch with the full verify
# suite green can reach it. The hosted job never reaches the homeserver; the
# self-hosted job never counts hosted minutes.
#
# The `deploy` job fetches the repo from github.com (public) — TEQO_REPO_URL
# in deploy-homeserver.sh now defaults there; the script's HEAD guard only
# deploys when the dispatched SHA is main's HEAD (a stale dispatch skips).
# The environment-specific builds CANNOT leave the homeserver (migrate
# pre-build on the env DB — OPS66 — and the compose network / local registry
# localhost:5000), which is exactly why the hosted job only verifies and the
# self-hosted jobs only build + deploy. Deploy is idempotent ("already
# deployed" guard in deploy-homeserver.sh) and serialized by flock per
# environment; the `concurrency` group below serializes the two shared
# homeserver compose/workspace consumers across runs without cancelling an
# in-flight deploy (the staged `needs` chain already serializes them inside
# one run).
#
# The deploy jobs fetch the repo from github.com (public) — TEQO_REPO_URL in
# deploy-homeserver.sh now defaults there; the script runs to completion for
# the dispatched SHA even if main advances during verify (OPS102 — publishing
# is a deliberate operator act).
name: Deploy (manual)
@ -141,18 +158,54 @@ jobs:
NEXT_PUBLIC_SITE_URL: https://feed.e2e.teqo.test
run: pnpm test:e2e
deploy:
name: deploy homeserver (teqo-1313)
# OPS53 + OPS71. Runs on the GitHub self-hosted runner ON the homeserver
# (labels self-hosted + homeserver): the script executes locally — no SSH
# hop, no workstation involvement. Deliberately wired ONLY here (manual
# dispatch), never in ci-pr.yml: a self-hosted job is code execution on
# the production machine, and only an explicit dispatch with the full
# verify suite green can reach it.
deploy-staging:
name: deploy staging (teqo-staging)
# OPS103: same SHA, same verify, own environment — no reviewer (the
# manual dispatch is the deliberate act); production is the approval that
# matters. The `main` guard makes a dispatch from a branch/tag a no-op
# for deploys (the runbook's dispatch ref is always `main`).
needs: [verify]
if: needs.verify.result == 'success'
if: needs.verify.result == 'success' && github.ref == 'refs/heads/main'
environment: staging
runs-on: [self-hosted, homeserver]
timeout-minutes: 60
concurrency:
# Shared homeserver compose/workspace: never two deploys at once across
# runs. The staged needs chain serializes them within one run. `queue:
# max`: the default single-slot queue cancels a previously pending
# deploy when a new dispatch arrives, even with cancel-in-progress
# false — deploys must wait their turn (OPS102: run to completion).
group: deploy-homeserver
cancel-in-progress: false
queue: max
env:
TEQO_ENV: staging
steps:
- uses: actions/checkout@v5
- name: Deploy teqo-staging on the homeserver
run: bash scripts/deploy-homeserver.sh "$GITHUB_SHA"
deploy-production:
name: deploy production (teqo-1313)
# OPS53 + OPS71 + OPS103. Runs on the GitHub self-hosted runner ON the
# homeserver (labels self-hosted + homeserver): the script executes
# locally — no SSH hop, no workstation involvement. Deliberately wired
# ONLY here (manual dispatch), never in ci-pr.yml: a self-hosted job is
# code execution on the production machine, and only an explicit dispatch
# with the full verify suite green can reach it. `needs: [deploy-staging]`
# makes a red staging fail-close production; the environment `production`
# (required reviewer, configured in the repo) is the approval gate.
needs: [deploy-staging]
if: needs.deploy-staging.result == 'success' && github.ref == 'refs/heads/main'
environment: production
runs-on: [self-hosted, homeserver]
timeout-minutes: 60
concurrency:
group: deploy-homeserver
cancel-in-progress: false
queue: max
env:
TEQO_ENV: production
steps:
- uses: actions/checkout@v5
- name: Deploy teqo-1313 on the homeserver

2
.gitignore vendored
View file

@ -73,6 +73,8 @@ next-env.d.ts
/data/demographics/
# AI fill masters (pnpm images:fill — regenerable drafts, never commit)
/data/ai-fill/
# Câmara pilot media/JSON cache (pnpm camara:pilot — VOD MP4 + report, never commit)
/data/camara/
# Local-only sensitive material (agents may read; never commit content)
/private/**

View file

@ -2,7 +2,7 @@
## Deploy & CI
Production is self-hosted on the homeserver (`jorgesolla1313.com.br`, behind the Cloudflare tunnel; container/database `teqo-1313`/`teqo_1313`). **There is no Vercel deploy anymore** — the Vercel deploy job, `vercel-promote.yml`, the Vercel scripts/`vercel.json` and the `VERCEL_*` repo secrets were removed in OPS50 (2026-08-17). **CI/PR/deploy AND the ISSUE TRACKER live on GitHub (OPS71 + OPS76, 2026-08-21)** (`github.com/fsolla/teqo/issues` — labels, claims, `pnpm issue`/`agent:*` and the post-merge flips talk to the GitHub API; GitHub is the single host). The PR CI (`ci-pr.yml`, job único `checks` — OPS62) runs the same cascade as always (guards → lint → format → typecheck → knip → cycles → unit → int → build → e2e selected/afetado, skips via `ci-scope.mjs`); its check-run `CI (PR) / checks` is the required check of `main`. **There is NO main verifier (`ci.yml`) anymore**: publishing is a **manual `workflow_dispatch`** (`.github/workflows/deploy.yml`) with two jobs — `verify` (hosted `ubuntu-latest`, suíte **full** incl. e2e full) → `deploy` (`needs: [verify]`, `runs-on: [self-hosted, homeserver]`): the GitHub self-hosted runner ON the homeserver executes `scripts/deploy-homeserver.sh` **locally** (no SSH; outbound-only runner, works behind the tunnel; the hosted job never touches the homeserver). The remote Docker deployment is gone; the production container runs the monolith directly. The Docker Compose file is used ONLY for local dev databases. The `run-deploy.yml` (OPS38/OPS46) was deleted in OPS71. There is no `run-deploy.yml` or equivalent in GitHub Actions — deploy is `deploy.yml` only.
Production is self-hosted on the homeserver (`jorgesolla1313.com.br`, behind the Cloudflare tunnel; container/database `teqo-1313`/`teqo_1313`). **There is no Vercel deploy anymore** — the Vercel deploy job, `vercel-promote.yml`, the Vercel scripts/`vercel.json` and the `VERCEL_*` repo secrets were removed in OPS50 (2026-08-17). **CI/PR/deploy AND the ISSUE TRACKER live on GitHub (OPS71 + OPS76, 2026-08-21)** (`github.com/fsolla/teqo/issues` — labels, claims, `pnpm issue`/`agent:*` and the post-merge flips talk to the GitHub API; GitHub is the single host). The PR CI (`ci-pr.yml`, job único `checks` — OPS62) runs the same cascade as always (guards → lint → format → typecheck → knip → cycles → unit → int → build → e2e selected/afetado, skips via `ci-scope.mjs`); its check-run `CI (PR) / checks` is the required check of `main`. **There is NO main verifier (`ci.yml`) anymore**: publishing is a **manual `workflow_dispatch`** (`.github/workflows/deploy.yml`) with three jobs — `verify` (hosted `ubuntu-latest`, suíte **full** incl. e2e full, rodado uma vez por commit) → `deploy-staging` (`environment: staging`, OPS103) → `deploy-production` (`environment: production` com required reviewer, `needs: [deploy-staging]`): the GitHub self-hosted runner ON the homeserver executes `scripts/deploy-homeserver.sh` **locally** (no SSH; outbound-only runner, works behind the tunnel; the hosted job never touches the homeserver). O script é único e parametrizado por `TEQO_ENV` (`production` default intocado; `staging` = `teqo-staging`/`teqo_staging`/`~/stack/teqo-staging.env`/`127.0.0.1:1314`, bucket `teqo-media-staging`; envs de staging só no homeserver, nunca como GitHub secrets; staging não é indexável). The remote Docker deployment is gone; the production container runs the monolith directly. The Docker Compose file is used ONLY for local dev databases. The `run-deploy.yml` (OPS38/OPS46) was deleted in OPS71. There is no `run-deploy.yml` or equivalent in GitHub Actions — deploy is `deploy.yml` only.
**Guarding `pnpm push` (OPS24+):** every PR push goes through `scripts/git-push.mjs`, which runs `ensure-repo-deps` (install + Husky in worktrees — OPS51), then `gate:push` (the pre-push hook), which chains `gate:ci` — a serialized mirror of the CI `checks` job (**without e2e**: OPS72 moved e2e to an explicit skill step) — plus the `docs-guards` (changelog entries additions-only + frozen HISTORY snapshot + uncommitted regenerable aggregate — OPS63/OPS85; conflict markers; the rewrite escape stays in CI only). The hook blocks `git push` on failure; escape: `git push --no-verify` (WIP only). There is no YAML `push` gate — the hook is the gate. **CI red on your PR is yours**, even pre-existing or infra — "out of feature scope" is not a stop condition (policy "Dono do PR, dono do CI" in `docs/AGENT-OPS.md`).
@ -22,6 +22,6 @@ Production is self-hosted on the homeserver (`jorgesolla1313.com.br`, behind the
- Never run `knip --fix` blind: when knip's module graph is incomplete (it still cannot load `payload.config.ts` — ledgered as P3), `--fix` deletes exports that migrations/tests still reference. Verify each removal (e.g. `git grep -w <symbol>`) before deleting.
- Run gate commands bare — never piped (`pnpm test | tail` swallows the exit code, and a real failure was masked exactly this way during Pass 2). Large outputs are captured by the terminal; read them from there.
4. Scan every edited runtime source file with Aikido and resolve new findings before handoff. Do not expand hardening work into unrelated pre-existing findings without an explicit scope change.
5. Review production environment variables and migration SQL before deploy; `pnpm build` applies pending migrations to the deployed database automatically. **`NEXT_PUBLIC_SITE_URL` (ex.: `https://jorgesolla1313.com.br`) é obrigatória em Production** — sem ela, `getCampaignInviteBaseURL()` lança em runtime e o fluxo de convites/webauthn/link de import da agenda falha com mensagem genérica (C98, 2026-08-09: produção ficou sem a env e "gerar link" do feed quebrava; o preview tinha a de stage).
5. Review production environment variables and migration SQL before deploy; `pnpm build` applies pending migrations to the deployed database automatically. **`NEXT_PUBLIC_SITE_URL` (ex.: `https://jorgesolla1313.com.br`) é obrigatória em Production** — sem ela, `getCampaignInviteBaseURL()` lança em runtime e o fluxo de convites/webauthn/link de import da agenda falha com mensagem genérica (C98, 2026-08-09: produção ficou sem a env e "gerar link" do feed quebrava; o preview tinha a de stage). Em staging (OPS103) a env carrega `https://staging.jorgesolla1313.com.br` — o mesmo fail-closed vale e a origem `staging.` também desliga o index (`robots.ts` + metadata).
6. **Mandatory production blocker:** do not insert real leadership/support data or enable invites until electoral counsel documents the LGPD art. 11 basis, approves the specific versioned consent text, and an admin creates it with exactly `Consent.key = 'lideranca-autopreenchimento'`. The app intentionally fails closed when this key is absent.
7. **Remodel deploy (historical — applied to production 2026-07-23):** the destructive remodel chain (`20260721_020109_remodel_municipalities` → `20260723_200000_remodel_municipalities` + `20260723_202000_reconcile_municipality_remodel`) already ran in production via the Vercel build: campaign vertical reset, 435 municípios seeded, public-site data untouched. Treat any future destructive migration the same way — review its SQL before the first production build that includes it.

File diff suppressed because one or more lines are too long

View file

@ -4,18 +4,19 @@ Uma página. Norte: simplicidade (GitHub = tracker E Actions — OPS76), agente
## Ambientes de dados (test ladder — nunca misturar)
| Ambiente | Conteúdo | Quem usa |
| ------------------------------------------- | ------------------------------------------------------------ | -------------------------------------------- |
| **Mínimo** (`teqo_test` local / service CI) | schema migrado + `pnpm db:seed:minimal` (sintético, sem PII) | agentes, Cursor Cloud, CI |
| **Prod** (`teqo_1313`, homeserver) | real | job `deploy` do `deploy.yml` (OPS53 + OPS71) |
| Ambiente | Conteúdo | Quem usa |
| ------------------------------------------- | ------------------------------------------------------------ | --------------------------------------------------------------------------------------------- |
| **Mínimo** (`teqo_test` local / service CI) | schema migrado + `pnpm db:seed:minimal` (sintético, sem PII) | agentes, Cursor Cloud, CI |
| **Staging** (`teqo_staging`, homeserver) | sintético (`db:seed:minimal`) | job `deploy-staging` do `deploy.yml` (OPS103); inspeção humana antes da aprovação de produção |
| **Prod** (`teqo_1313`, homeserver) | real | job `deploy-production` do `deploy.yml` (OPS53 + OPS71 + OPS103) |
Agentes **nunca** recebem `DATABASE_URL` de prod e nunca setam `ALLOW_REMOTE_DB`. Não há mais smoke `stage` / `ALLOW_STAGE_TEST_DB` / `ci-stage.yml`.
Agentes **nunca** recebem `DATABASE_URL` de prod/staging e nunca setam `ALLOW_REMOTE_DB`. Não há mais smoke `stage` / `ALLOW_STAGE_TEST_DB` / `ci-stage.yml` — o staging da OPS103 é **alvo de promoção de um SHA de `main`** (dispatch manual → staging → aprovação → produção), nunca destino de PR.
## Fluxo
```text
claim → feature branch → PR --base main (GitHub) → CI PR green (cascade + skips) → auto-merge nativo em main (rebase)
main → (opcional, deliberado) workflow_dispatch deploy.yml → verify full suite verde → job deploy no homeserver (OPS53)
main → (opcional, deliberado) workflow_dispatch deploy.yml → verify full suite verde → deploy-staging → aprovação do environment production → deploy-production (OPS53 + OPS103)
```
**Skills:** `plan-issue` (intenção + Issues) → `work-issue` (humano: Issue já claimada → impl plan → confirmação → execução) ou `agent-work-issue` (pool: já claimada → impl plan → execução sem pausa) → `/simplify` → `capture-review-debts` → PR `--base main` (GitHub) → `project-status`. `docs/roadmap.md` = legado congelado; fonte canônica = Issues do GitHub (`github.com/fsolla/teqo/issues`).
@ -75,14 +76,14 @@ Arquivos de "lista" que N agentes escrevem em paralelo (plans, migrações, cata
## CI por alvo (GitHub Actions, OPS71)
| Workflow | Trigger | Banco | Passos |
| ------------------------------------ | --------------------------------------------------------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ci-pr.yml` | PR → `main` (same-repo) | 1× service Postgres 17 | Job único `checks` sequencial (OPS62 X1): guards → lint→format→typecheck→knip→cycles→unit→int→build→e2e; skips via `ci-scope.mjs` (step `scope`); **fail-fast estrutural** — step vermelho interrompe o job, o run falha; `concurrency` nativo cancela o run em push novo; e2e **apenas blast radius** — `selected` ou, em high-risk, o conjunto `curated` (nunca `full` — OPS72/OPS86); área de risco sem mapping falha `unmapped-risk`; unit/int `changed` com seleção vazia cai em full (`vitest-changed-or-full.mjs`) — em 1 processo com `PLAYWRIGHT_WORKERS=4`; 1 service `postgres-int` (localhost:5432) com **`pnpm db:reset`** (drop→migrate→seed:minimal) entre int e build/e2e (OPS88 — substitui o 2º container); fork-PR excluída no `if:` do job (repo público — não queima minutes) |
| `deploy.yml` | **`workflow_dispatch` manual** | 1× service Postgres 17 | **Dois jobs:** `verify` (hosted, suíte **full** sem skips — lint→format→typecheck→knip→cycles→unit→int→`db:reset`→build `.next-e2e`→e2e full; OPS88: um build só, o default saiu) → `deploy` (`needs: [verify]`, `runs-on: [self-hosted, homeserver]`) executa `scripts/deploy-homeserver.sh <sha>` **localmente** no homeserver (sem SSH; idempotente; HEAD guard; flock; migrator→migrate→runner→rollout→smoke) |
| `issue-done-on-main-merge.yml` | PR merged → `main` (same-repo) + **dispatch manual (recovery)** | — | `Closes`/`Fixes` → `done` + `in-prod` + **close** **no GitHub** (token `GITHUB_TOKEN`; body do PR via `PR_BODY` do evento GitHub — no dispatch, busca via `gh` com o mesmo contrato: merged + main + same-repo) |
| `plan-issue-ready-on-main-merge.yml` | PR merged → `main` (same-repo) + **dispatch manual (recovery)** | — | `Related #N` aguardando plano → `ready` **no GitHub** (OPS18; soft-skip; mesmo token) |
| `agent-pr-ready-automerge.yml` | PR same-repo → `main` (open/sync/…) | — | Safety net via `github-pr-automerge.mjs` (plain Node, REST+GraphQL): draft `cursor/*` → Ready (PATCH); arm `enablePullRequestAutoMerge` (rebase) **com o `AUTOMERGE_PAT`** (fail-closed — nunca o `GITHUB_TOKEN` nativo, cujo merge como `github-actions[bot]` não cria runs no `closed`; OPS71-FLIP) — o **servidor** espera o required check `CI (PR) / checks` (o OPS64 "rollup pode mentir" é estrutural aqui: job único posta um check-run honesto); draft não-`cursor/*` = veto, skip |
| `archive-cursor-agent.yml` | dispatch manual (ops) | — | Helper: cancela run + arquiva um agente Cursor Cloud (`CURSOR_API_KEY`) — **dormente (OPS65)** como o pool |
| Workflow | Trigger | Banco | Passos |
| ------------------------------------ | --------------------------------------------------------------- | ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ci-pr.yml` | PR → `main` (same-repo) | 1× service Postgres 17 | Job único `checks` sequencial (OPS62 X1): guards → lint→format→typecheck→knip→cycles→unit→int→build→e2e; skips via `ci-scope.mjs` (step `scope`); **fail-fast estrutural** — step vermelho interrompe o job, o run falha; `concurrency` nativo cancela o run em push novo; e2e **apenas blast radius** — `selected` ou, em high-risk, o conjunto `curated` (nunca `full` — OPS72/OPS86); área de risco sem mapping falha `unmapped-risk`; unit/int `changed` com seleção vazia cai em full (`vitest-changed-or-full.mjs`) — em 1 processo com `PLAYWRIGHT_WORKERS=4`; 1 service `postgres-int` (localhost:5432) com **`pnpm db:reset`** (drop→migrate→seed:minimal) entre int e build/e2e (OPS88 — substitui o 2º container); fork-PR excluída no `if:` do job (repo público — não queima minutes) |
| `deploy.yml` | **`workflow_dispatch` manual** | 1× service Postgres 17 | **Três jobs (OPS103):** `verify` (hosted, suíte **full** sem skips — lint→format→typecheck→knip→cycles→unit→int→`db:reset`→build `.next-e2e`→e2e full; OPS88: um build só, o default saiu) → `deploy-staging` (`needs: [verify]`, `environment: staging`, `TEQO_ENV=staging`) → `deploy-production` (`needs: [deploy-staging]`, `environment: production` com required reviewer, `TEQO_ENV=production`); ambos os deploys rodam em `runs-on: [self-hosted, homeserver]` e executam `scripts/deploy-homeserver.sh <sha>` **localmente** no homeserver (sem SSH; roda até o fim com o SHA do dispatch mesmo se `main` andar durante o verify — OPS102; idempotente; um `flock` compartilhado + `concurrency: deploy-homeserver` com `queue: max`; migrator→migrate→runner→rollout→smoke) — staging vermelho fail-closa produção |
| `issue-done-on-main-merge.yml` | PR merged → `main` (same-repo) + **dispatch manual (recovery)** | — | `Closes`/`Fixes` → `done` + `in-prod` + **close** **no GitHub** (token `GITHUB_TOKEN`; body do PR via `PR_BODY` do evento GitHub — no dispatch, busca via `gh` com o mesmo contrato: merged + main + same-repo) |
| `plan-issue-ready-on-main-merge.yml` | PR merged → `main` (same-repo) + **dispatch manual (recovery)** | — | `Related #N` aguardando plano → `ready` **no GitHub** (OPS18; soft-skip; mesmo token) |
| `agent-pr-ready-automerge.yml` | PR same-repo → `main` (open/sync/…) | — | Safety net via `github-pr-automerge.mjs` (plain Node, REST+GraphQL): draft `cursor/*` → Ready (PATCH); arm `enablePullRequestAutoMerge` (rebase) **com o `AUTOMERGE_PAT`** (fail-closed — nunca o `GITHUB_TOKEN` nativo, cujo merge como `github-actions[bot]` não cria runs no `closed`; OPS71-FLIP) — o **servidor** espera o required check `CI (PR) / checks` (o OPS64 "rollup pode mentir" é estrutural aqui: job único posta um check-run honesto); draft não-`cursor/*` = veto, skip |
| `archive-cursor-agent.yml` | dispatch manual (ops) | — | Helper: cancela run + arquiva um agente Cursor Cloud (`CURSOR_API_KEY`) — **dormente (OPS65)** como o pool |
`agent-pool.yml` foi **removido no OPS65** (pool dormente; o tick `*/10` custava 144 `pnpm install`/dia na workstation). O verificador de main (`ci.yml`) foi **eliminado no OPS71** (gate 2026-08-19): só o `verify` do dispatch manual roda a suíte full.
@ -107,7 +108,7 @@ O flip `issue-done`/`plan-issue-ready` roda no `pull_request: closed` do PR no G
Branch protection de `main` no **GitHub** (aplicada no cutover do OPS71, via `pnpm configure:branch-protection`): required check `CI (PR) / checks` (a UI exibe workflow/job; o **literal de match é `checks`** — o GitHub casa pelo nome do check-run — pin ao vivo PR #742), `strict=false`, 0 reviews, `enforce_admins: true` (nem admin mergea com CI vermelho — mesmo invariante do rule-based Forgejo). O auto-merge nativo espera esse mesmo check antes de mergear; a regra no servidor é o gate real de qualquer caminho de merge, inclusive API manual. Reaplicar/consertar drift: `pnpm configure:branch-protection` (idempotente).
Deploy (OPS53 + OPS71): **manual** via `workflow_dispatch` no `deploy.yml` — o job `verify` (hosted, suíte full incl. e2e full) roda **antes** do job `deploy` (`needs: [verify]`), que executa `scripts/deploy-homeserver.sh <sha>` no runner self-hosted do GitHub **no homeserver** (conecta outbound ao GitHub — funciona atrás do Cloudflare tunnel; o hosted nunca toca o homeserver; o self-hosted não conta minutos hosted). O script: HEAD guard (`TEQO_REPO_URL` — default `https://github.com/fsolla/teqo.git`, público) → flock → guard "already deployed" (revision do container) → build do migrator (BuildKit, secrets de `~/stack/teqo-1313.env`) → push/tag em `localhost:5000` → swap dos tags no compose (backup) → **migrations** (`teqo-1313-migrate` — antes do build do runner, OPS66) → build do runner (contra o banco JÁ migrado) → rollout → healthcheck → smoke. Falha = job vermelho; nada é publicado pela metade. Runbook (rollback, falhas conhecidas): `docs/ops/teqo-1313-deploy.md`. O deploy Vercel foi removido no OPS50; o verificador automático de main foi eliminado no OPS71 — se um dia o merge em main quiser rede de regressão, o `ci.yml` volta com 1 linha de trigger (sem deploy).
Deploy (OPS53 + OPS71 + OPS103): **manual** via `workflow_dispatch` no `deploy.yml` — o job `verify` (hosted, suíte full incl. e2e full, **intocado** — verifica o commit uma vez) roda **antes** dos deploys: `deploy-staging` (`environment: staging`, sem reviewer) e então `deploy-production` (`needs: [deploy-staging]`, `environment: production` com required reviewer; staging vermelho nunca deixa produção rodar). Os dois executam `scripts/deploy-homeserver.sh <sha>` no runner self-hosted do GitHub **no homeserver** (conecta outbound ao GitHub — funciona atrás do Cloudflare tunnel; o hosted nunca toca o homeserver; o self-hosted não conta minutos hosted), parametrizado por `TEQO_ENV` (`production` default intocado; `staging` = `teqo-staging`/`teqo_staging`/`~/stack/teqo-staging.env`/`127.0.0.1:1314`). O script: flock por ambiente → guard "already deployed" (revision do container do ambiente) → build do migrator (BuildKit, secrets do env file do ambiente) → push/tag em `localhost:5000` → swap dos tags no compose (backup; sed ancorado ao serviço do ambiente) → **migrations** (`teqo-1313-migrate`/`teqo-staging-migrate` — antes do build do runner, OPS66) → build do runner (contra o banco JÁ migrado) → rollout → healthcheck → smoke. Desde a OPS102 o deploy roda até o fim com o SHA do dispatch mesmo se `main` avançar durante o verify (o antigo guard de stale run era da era automática); o único verde sem build é o "already deployed", que prova que o container já roda o SHA. Falha = job vermelho; nada é publicado pela metade. Runbook (rollback, falhas conhecidas, bootstrap do staging): `docs/ops/teqo-1313-deploy.md`. O deploy Vercel foi removido no OPS50; o verificador automático de main foi eliminado no OPS71 — se um dia o merge em main quiser rede de regressão, o `ci.yml` volta com 1 linha de trigger (sem deploy).
## Cursor Cloud

View file

@ -0,0 +1 @@
**Botão "Conectar com o Google" na agenda substitui a configuração manual da service account (2026-09-12):** ativar o espelho Google Calendar (C114/C115) exigia cerimônia de engenharia — criar service account no GCP, baixar JSON, base64 numa env e compartilhar o calendário; agora candidato ou coordenação clica **Conectar com o Google** no diálogo do espelho e autoriza uma única concessão (Authorization Code + `access_type=offline` + `prompt=consent`) para o calendário da campanha. O refresh token é gravado na própria collection `googleCalendarSync` (5 campos `oauth*`, `oauthRefreshToken` com `read: false` — inalcançável por qualquer caminho de usuário, como o segredo do webhook); a migration `20260912_052226_add_google_calendar_oauth_connection` é aditiva/nullable e o schema continua com `push: false`. O motor resolve a credencial por `readGoogleCalendarAuth` (OAuth vence quando há token + client env; service account segue fallback intacto) e o client ganhou a união `GoogleCalendarAuth` (refresh_token grant) mantendo os 6 métodos e o retry de 401. A conexão tem exatamente três estados derivados (`conectado | erro | não configurado`): `invalid_grant` vira `error` com reconexão em um clique (`GoogleCalendarAuthError` → `oauthErrorPatchFor`, pinado em unit), e o sucesso limpa o erro — falha do Google nunca corrompe o Teqo. O handshake usa escopos mínimos (`calendar.events` + `calendar.calendarlist.readonly`, validados na concessão para o consent granular não conectar sem permissão de escrita), `state` HMAC-SHA256 single-use de 10min amarrado ao usuário (cookie `campaign-google-oauth-state`, padrão WebAuthn), callback GET fora do `(app)` com redirect sempre na URL pública (`getCampaignInviteBaseURL()` — nada de localhost atrás do túnel) e re-checagem do papel fresco. Desconectar limpa a conexão no Teqo e orienta revogar o app no Google. UI: card de conexão no `GoogleCalendarSyncDialog` (Conectar/Reconectar/Desconectar; advisor vê sem botões; leader lockdown intocado) com o runbook antigo só quando o client OAuth não está configurado no servidor. Duas envs novas (`GOOGLE_CALENDAR_OAUTH_CLIENT_ID`/`_SECRET`) documentadas no `.env.example` e no runbook `docs/ops/teqo-1313-deploy.md` (criar o OAuth client Web application, registrar os redirect URIs e publicar o app unverified para o token não expirar em 7 dias) — **pré-requisito de deploy: setá-las em `~/stack/teqo-1313.env`**. Verificação: unit full 2716 passed, int full 722 passed (os specs da família Google agora serializam por advisory lock — a collection é singleton e a corrida entre arquivos paralelos sumiu), e2e `campaignAgendaGoogleSync` 9/9 local incluindo o botão de consent, typecheck/lint/format/knip/cycles verdes. Débitos deferidos com gatilho no impl plan (`docs/plans/c149-conectar-google-oauth-impl.md`): extrair o cookie assinado compartilhado no 4º site, cifrar o refresh token em repouso se compliance exigir, e a constraint única do singleton para o C150.

View file

@ -0,0 +1 @@
**Calendário principal da campanha escolhido na própria agenda e inscrição de staff no Google com um clique (2026-09-12):** escolher qual calendário Google espelhava a agenda era operação de admin do Payload; agora o candidato/coordenação lista os calendários da conta conectada (C149) direto em `/campanha/agenda` e escolhe o principal. O `GoogleCalendarClient` ganhou `listCalendars` (`calendarList.list` com `minAccessRole=writer`, paginação por `nextPageToken`, `deleted` filtrado, `summary` caindo para o id), OAuth-only por desenho (a lista do service account não contém os calendários compartilhados). O picker novo (`GoogleCalendarPickerDialog`, Dialog desktop/Drawer mobile, mesmo chrome C94/C148) lista ao vivo a cada abertura com estados loading/erro/vazio/retry, marca o "em uso" e só confirma quando a seleção muda; o chrome da agenda é dono dos dois overlays (um por vez — sem Radix/vaul aninhados). A escrita do `calendarId` virou action manager-only + utility `setCampaignPrimaryCalendarId`: o id é **validado server-side contra a lista viva** da conta conectada antes do system write com bypass (`canSetGoogleCalendarSyncConfigField` segue admin-only como escape hatch do Painel — a superfície REST do campaignUser nunca escreve id arbitrário); trocar o calendário dispara o hook D7 e o motor re-concilia no novo, sem backfill nem limpeza no antigo (design C114). `invalid_grant` na listagem grava `oauthErrorAt/oauthError` e o card deriva `error`/Reconectar (mesma classificação do motor). O one-click "Adicionar ao meu Google Calendar" usa o literal `calendar.google.com/calendar/r?cid=<calendarId URL-encoded>` — âncora no header para staff (rótulo no desktop, ícone com `aria-label` no mobile) e dentro do diálogo; o caminho manual "Por URL"/Apple Calendar/Outlook passou a exibir a URL iCal pública do calendário, e o feed ICS filtrado (`CalendarFeedDialog`) ficou intocado. Advisor vê o one-click mas não o seletor (copy "escolhido por candidato ou coordenação"); leader lockdown intocado. Sem migration. Verificação: unit 290 files/2775 passed, int 81 files/728 passed (spec novo `googleCalendarPrimaryCalendarAction` cobre papel, id fora da lista, record do auth error e o D7 com `listEvents(novoId)`), e2e `campaignAgendaGoogleSync` 11/11 (synced com seletor + one-click + URL iCal, advisor sem seletor, one-click mobile), `campaignActivity`+`campaignAgendaFeed` 10/10, gate:ci completo (lint/format/typecheck/knip/cycles/build). Débito registrado: **C156** (#965, `docs/plans/escala-dry-pos-c150.md`) — o gatilho do C148 disparou (4º modal com o mesmo corpo rolável): extrair o shell responsivo compartilhado dos diálogos; copy única do one-click absorvida como fase cortável e as máquinas de estado picker/sync deferidas com gatilho.

View file

@ -0,0 +1 @@
**C151 — Atividade: marcar evento como público (2026-09-12):** o staff agora marca/desmarca "Evento público" no modal de atividade (criar e editar), uma flag durável e consultável que registra a INTENÇÃO de expor o compromisso na futura agenda pública do site — a exposição em si é item PUB posterior. Campo `publicEvent` (checkbox, default `false`, indexado) na collection `activity` existente, com o mesmo padrão de `deputyPresent`/`allDay`; migration `20260912_224719_add_activity_public_event`. O parser de FormData, o zod de entrada, o `ActivityFormViewModel`/`activityFormSelect` e o `ActivityOverlay` (checkbox ao lado de "Todo o dia", default desmarcado, volta correto ao reabrir) acompanham o campo; o snapshot do guard de liderança em `Activity.ts` inclui a flag (defesa em profundidade). Nada no site público, na agenda, na lista, no detalhe ou no espelho do Google (C114) muda: `publicEvent` fica fora de `SYNC_RELEVANT_ACTIVITY_FIELDS` e dos selects de agenda/lista/detalhe, sem filtro/badge novo. Testes: unit do overlay (render, submit e prefill), int de parse e persistência/reabertura, e o e2e `campaignActivity` cobre marcar→salvar→reabrir. Plano: `docs/plans/c151-atividade-evento-publico-impl.md`.

View file

@ -0,0 +1 @@
**C152 — Piloto da fonte: vídeos e transcrição minutada de discursos da Câmara (2026-09-12):** spike de viabilidade da fonte do acervo de falas, sem DB/Payload/collection/migration. Novo `scripts/pilot-camara-speeches.mjs` (orquestra: API de discursos → evento do dia → trechos por orador na página do evento → poll assíncrono de `video-sob-demanda` → download do MP4 → Deep Infra Whisper large-v3) + `scripts/lib/camaraSpeeches.mjs` (lógica pura: parser das âncoras, matching orador/horário, offset YouTube, normalização de segmentos) com 17 unit tests; script `pnpm camara:pilot`; cache de mídia/JSON em `data/camara/` (novo no `.gitignore`). 3 discursos (55ª/2016, 56ª/2021, 57ª/2023) processados ponta a ponta com transcrição segmentada (`start`/`end`/`text`) — o endpoint compat `verbose_json` aceita o MP4 direto, sem ffmpeg, e devolve segmentos. Achados registrados em `docs/research/piloto-fonte-videos-camara.md`: link do VOD é determinístico/regerável (persistir `evento`+`idAudio`+`trecho`, não a URL); trechos por orador existem de 2015 em diante (54ª não cobre); casamento discurso↔evento é por data/hora (`uriEvento` vazio); página de trecho responde 400 anti-crawl. Custo medido US$ 0,0006–0,0021 por discurso. Sem migration, sem access/Consent; destrava C153/C154/C155.

View file

@ -0,0 +1 @@
**OPS102 — Deploy manual roda até o fim mesmo com `main` à frente (2026-09-12):** o guard de stale run nasceu na era automática (OPS53): `scripts/deploy-homeserver.sh` comparava `git ls-remote … refs/heads/main` com o SHA do job (pré e pós-`flock`) e abortava com `fatal "stale run"`. Desde a OPS71 o publish é um `workflow_dispatch` deliberado — se alguém mergeasse em `main` durante os ~50 min do `verify`, o job `deploy` morria mesmo com o dispatch legítimo. O fix remove os dois blocos (o `flock` e o guard "already deployed" ficam; o único verde sem build segue sendo o que prova que o container já roda o SHA) e realinha o registro vivo: comentários do script e do `deploy.yml`, fluxo e tabela "Falhas conhecidas" do runbook (`docs/ops/teqo-1313-deploy.md` — a linha do antigo "stale run" vira o risco aceito de dispatch fora de ordem, com gatilho de revisita) e `docs/AGENT-OPS.md`. `tests/unit/deployScript.unit.spec.ts` passa a pinar o contrato novo: ausência de `git ls-remote`/`refs/heads/main`/`stale run` (pins de ausência com RED comprovado contra o script anterior), único `exit 0` = "already deployed" (anti-falso-verde #953) e `flock` preservado. Sem migration, sem UI, sem access/Consent. Verificação: `pnpm gate:fast` verde; e2e não afetado (diff sem superfície runtime). Aceite final humano pós-merge: dispatch manual do `deploy.yml`.

View file

@ -0,0 +1 @@
**OPS103 — Staging no homeserver com verify único e aprovações separadas (2026-09-12):** o repo ganhou um alvo real e descartável entre o banco mínimo do CI e a produção. Um único `workflow_dispatch` do `deploy.yml` roda o `verify` (hosted, suíte **full** incl. e2e — **intocado**: verifica o commit, não o alvo) uma vez e gateia **três jobs**: `verify` → `deploy-staging` (`environment: staging`, sem reviewer; `TEQO_ENV=staging`) → `deploy-production` (`needs: [deploy-staging]`, `environment: production` com required reviewer — staging vermelho nunca deixa produção rodar; `TEQO_ENV=production`). Os dois deploys rodam no runner self-hosted do homeserver e executam o **mesmo** `scripts/deploy-homeserver.sh`, agora parametrizado por `TEQO_ENV` (mapa no topo; produção default byte-for-byte a de antes: `teqo-1313`/`teqo-1313-migrate`/`~/stack/teqo-1313.env`/127.0.0.1:1313/`localhost:5000/teqo-1313(-migrator):$SHA`; staging: `teqo-staging`/`teqo-staging-migrate`/`~/stack/teqo-staging.env`/127.0.0.1:1314/bucket `teqo-media-staging`/proxy de build próprio; `TEQO_ENV` inválido fail-closed, mapa `readonly` contra retargeting pelos env files). Sem script gêmeo: o sed de imagens é ancorado ao repo do ambiente e o label `org.opencontainers.image.revision` passa a ser trocado por **range do bloco do serviço** (um replace global carimbaria o SHA de um ambiente no serviço do outro e o guard "already deployed" leria revision mentirosa); a ordem migrator→migrate→runner (OPS66), o rollback por ambiente, o healthcheck e o smoke (`http://localhost:1314` no staging) seguem idênticos. Os dois deploys compartilham o compose/workspace/registry do homeserver, então entram no mesmo `concurrency: deploy-homeserver` (`cancel-in-progress: false`, `queue: max` — o default de fila cancelaria um pending a cada dispatch novo) e num único `flock` compartilhado (locks por ambiente deixariam staging e produção buildar/swapar concorrentemente; o lock também cobre invocação manual, que não passa pelo concurrency). Staging é noindex no repo (`src/lib/siteEnvironment.ts` + `src/app/robots.ts` + metadata do layout — hostname `staging.` desliga index em qualquer alvo) e usa seed sintético, nunca PII. Pins: `tests/unit/deployScript.unit.spec.ts` (defaults de produção + mapa de staging + sed ancorado + único `exit 0`; a ordem OPS66 passou a ancorar em `--profile maintenance run --rm`/último `up -d`), `tests/unit/ciSkipInvariants.unit.spec.ts` (os três jobs, environments, `needs`, guard `main`, concurrency) e `tests/unit/siteEnvironment.unit.spec.ts` (predicado + wiring do noindex). Docs vivos: runbook `docs/ops/teqo-1313-deploy.md` (fluxo, tabela staging×produção, bootstrap manual do homeserver — DB, env file, serviços no compose, bucket, tunnel/DNS, environments e migrate+seed — e limites explícitos: WebAuthn/OAuth/Resend/e2e não são validados), `docs/AGENT-OPS.md` (ladder de ambientes e workflow), `AGENTS.md`/`AGENTS-infra.md` e `.env.example` (bucket `teqo-media-staging`). Sem migration, sem UI, sem access/Consent. Verificação: `pnpm gate:fast` verde (unit 292 arquivos/2810 testes); e2e local da mesma superfície (`frontend`, 25 testes) verde; `/robots.txt` confirmado no build (rota estática). Aceite final humano pós-merge: bootstrap ops no homeserver + dispatch real (staging verde → inspeção → aprovação → produção no mesmo SHA).

View file

@ -0,0 +1 @@
**S14 — cards personalizados: ajustes de fidelidade e experiência (2026-09-12):** refinamento do funil entregue no S13, sem fluxo novo. A home passa a abrir o MESMO compositor ali mesmo: a seção `Faça parte / Mostre que você está com Solla` renderiza a ilha `CardsStudio` (modal no desktop, drawer no mobile), os três tiles viraram botões e o CTA `Criar meu card` saiu; nada navega e fechar devolve à seção (foco de volta ao tile). A seção subiu para imediatamente antes de `Receba as novidades da campanha` (depois de `Nossa história`), mantendo a captura de contato como último bloco de conversão. O nome no card gerado agora alinha à esquerda com a linha `#SOU` (borda x=213 no canvas de 1080) em uma e duas linhas, com o fit de tamanho/quebra intocado: `NAME_CARD_SLOT.centerX` virou `leftX` e o desenho do nome foi extraído de `renderNameCard` para um `drawCardName` puro (`textAlign='left'`), reusado pelo tile do modelo de nome — que deixou de ser um placeholder HTML em Exo2 e passou a desenhar `SEU NOME` com o mesmo pipeline real (fit + `drawCardName`) num canvas transparente sobre a base otimizada, então o tile não pode divergir do resultado. No compositor, o vão interno de 32px do dialog sumiu (`p-0 sm:p-0` no call site; o `sm:p-8` base sobrevivia ao twMerge) preservando borda fina e raio, e o texto de ajuda `Arraste para posicionar e use os controles para aproximar ou ajustar.` ficou legível nos dois shells via `--muted-foreground: var(--campaign-muted)` no tema `campaign-site` (~6:1 sobre branco; antes herdava o near-white do `:root`). Limpeza: a variante `link` do `CardModelGallery` e o helper `cardModelHref` saíram (sem call site). `/cards` e o deep-link `?model=` seguem intactos; sem migration, sem Payload/Consent, sem PII em rede. Unit de `cardModels`/`cardRender` atualizado (+ `drawCardName`) e e2e do spec `frontend` reescrito: ordem da home, tiles-botão, compositor abrindo sem navegar, alinhamento à esquerda conferido por pixel na faixa do nome (card e tile), além dos fluxos canônicos de `/cards`, `?model=` e download PNG. Plano: `docs/plans/cards-personalizados-ajustes-impl.md`.

View file

@ -1,62 +1,147 @@
# Runbook: deploy do site 1313 no homeserver (OPS53 + OPS71 — dispatch manual)
# Runbook: deploy do site 1313 no homeserver (OPS53 + OPS71 + OPS103 — dispatch manual)
O deploy de produção é uma **action manual** (`workflow_dispatch` no GitHub
Actions, `.github/workflows/deploy.yml`): mergir em `main` **não** publica
nada. O operador dispara o deploy quando decide publicar; antes de tocar o
homeserver, o job `verify` (hosted) roda a suíte **full** (incl. e2e full).
O deploy é uma **action manual** (`workflow_dispatch` no GitHub Actions,
`.github/workflows/deploy.yml`): mergir em `main` **não** publica nada. O
operador dispara o deploy quando decide publicar; antes de tocar o homeserver,
o job `verify` (hosted) roda a suíte **full** (incl. e2e full) **uma vez** e
gateia os dois alvos: `deploy-staging` → aprovação do environment `production`
→ `deploy-production` (OPS103).
## Gatilho e fluxo
1. GitHub → Actions → **Deploy (manual)** → Run workflow (ref: `main`).
2. Job `verify` (hosted `ubuntu-latest`, ~50 min): suíte full sem skips —
check-test-locations → lint → format → typecheck → knip → cycles → unit →
int (migrate+seed nos services) → build → e2e full.
3. Se `verify` verde, o job `deploy` (`needs: [verify]`,
`runs-on: [self-hosted, homeserver]`) roda no **runner do GitHub instalado
no homeserver** e executa `scripts/deploy-homeserver.sh <sha>` **localmente**
(sem SSH; o runner conecta outbound ao GitHub — funciona atrás do
Cloudflare tunnel; o hosted nunca toca o homeserver; o self-hosted não
conta minutos hosted).
4. O script, no **homeserver**: guarda de HEAD (`git ls-remote` de
`TEQO_REPO_URL` — default `https://github.com/fsolla/teqo.git`, público —
== SHA do job, senão "stale run" skip) → `flock` (serializa) → guard
"already deployed" (revision do container rodando) → **build do migrator**
(o estágio migrator não roda `next build` — builda mesmo contra o schema
antigo; BuildKit, secrets do `~/stack/teqo-1313.env`) → push do migrator em
`localhost:5000` (tag **qualificada de registry** — INF13: a única ref que o
compose referencia) → swap dos tags de imagem no
`~/stack/docker-compose.yml` (backup antes; sed idempotente aceita as formas
antiga e qualificada e escreve sempre a qualificada) → **migrations**
(`docker compose --profile maintenance run --rm teqo-1313-migrate </dev/null`,
já com a imagem do SHA novo) → **build do runner** (contra o banco JÁ
migrado — o `next build` da geração estática lê o schema novo, OPS66;
`--network host` com proxy socat `teqo-1313-build-proxy` na `stack_default`
para alcançar o `postgres`; o proxy é criado idempotentemente pelo script)
→ push do runner (tag qualificada de registry) → `docker compose up -d teqo-1313` → healthcheck →
smoke (`/`, `/campanha/login`, `/admin`, barreira 307, WebAuthn
login-options, `api/revalidate` com o secret real).
5. Falha = job vermelho; nada é publicado pela metade (rollback automático
após o swap).
int (migrate+seed nos services) → build → e2e full. **Intocado pela
OPS103**: verifica o commit, não o alvo.
3. Se `verify` verde, o job `deploy-staging` (`needs: [verify]`,
`environment: staging`, sem reviewer) roda no runner self-hosted e executa
`TEQO_ENV=staging bash scripts/deploy-homeserver.sh <sha>` — publica o SHA
em `staging.jorgesolla1313.com.br` (container `teqo-staging`,
`127.0.0.1:1314`).
4. Com staging verde, o job `deploy-production` (`needs: [deploy-staging]`,
`environment: production`) **aguarda a aprovação do reviewer** e então
executa `TEQO_ENV=production bash scripts/deploy-homeserver.sh <sha>` —
publica o **mesmo SHA** em produção (`teqo-1313`, `127.0.0.1:1313`).
Staging vermelho = produção nunca roda; a corrida entre os dois é
serializada pela `concurrency: deploy-homeserver`.
5. O script, no **homeserver**: `flock` único (compose, workspace e registry
são compartilhados — um deploy por vez no host; o `concurrency` do
workflow serializa os runs e o lock cobre invocação manual; desde a OPS102
o run vai até o fim com o SHA do dispatch mesmo se `main` avançar durante o
verify; o workspace é clonado/atualizado de `TEQO_REPO_URL` — default
`https://github.com/fsolla/teqo.git`, público) →
guard "already deployed" (revision do container do ambiente) → **build do
migrator** (o estágio migrator não roda `next build` — builda mesmo contra o
schema antigo; BuildKit, secrets do env file do ambiente) → push do migrator
em `localhost:5000` (tag **qualificada de registry** — INF13: a única ref
que o compose referencia) → swap dos tags de imagem no
`~/stack/docker-compose.yml` (backup antes; sed ancorado ao serviço do
ambiente — a linha do outro ambiente não é tocada) → **migrations**
(`docker compose --profile maintenance run --rm teqo-<env>-migrate
</dev/null`, já com a imagem do SHA novo) → **build do runner** (contra o
banco JÁ migrado — o `next build` da geração estática lê o schema novo,
OPS66; `--network host` com proxy socat por ambiente na `stack_default` para
alcançar o `postgres`; o proxy é criado idempotentemente pelo script) →
push do runner (tag qualificada de registry) → `docker compose up -d
teqo-<env>` → healthcheck → smoke (`/`, `/campanha/login`, `/admin`,
barreira 307, WebAuthn login-options, `api/revalidate` com o secret real do
ambiente).
6. Falha = job vermelho; nada é publicado pela metade (rollback automático
após o swap, **só do ambiente que falhou**).
**Primeiro deploy (verificação ao vivo):** depois do cutover OPS71, dispare o
deploy manual e confira no log do job `deploy` o `set-url` do workspace
(origem Forgejo → GitHub), o `deployed_sha` lido do container e o guard
"already deployed" num segundo dispatch do mesmo SHA.
deploy manual e confira no log do job `deploy-production` o `set-url` do
workspace (origem Forgejo → GitHub), o `deployed_sha` lido do container e o
guard "already deployed" num segundo dispatch do mesmo SHA. Na OPS103, o
caminho de estreia é o mesmo dispatch: staging primeiro (bootstrap abaixo),
inspeção humana, aprovação, produção.
## Onde roda cada coisa
| Máquina | Papel |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **GitHub hosted** (ubuntu) | CI de PR (`ci-pr.yml`, job `checks`) e job `verify` do `deploy.yml` (suíte full). Nunca toca o homeserver. |
| **homeserver** (8c/16GB) | todo o stack (`~/stack/docker-compose.yml`): postgres `teqo_1313`, forgejo, registry `localhost:5000`, cloudflared, `teqo-1313` na 127.0.0.1:1313; **runner self-hosted do GitHub** (labels `self-hosted`, `homeserver`; instalado 2026-08-19 — Issue #113 OPS71-INFRA; `~/actions-runner` v2.336.0, systemd user `actions.runner.fsolla-teqo.teqo-1313-runner.service` — `systemctl --user status/restart`); workspace `~/teqo-deploy` (clone de `github.com/fsolla/teqo`, público) |
| **workstation** | dev/agentes apenas — o runner do Forgejo foi **desligado** no cutover (o schedule do `ci.yml` antigo não tem mais razão; religar é reversível) |
| Máquina | Papel |
| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **GitHub hosted** (ubuntu) | CI de PR (`ci-pr.yml`, job `checks`) e job `verify` do `deploy.yml` (suíte full). Nunca toca o homeserver. |
| **homeserver** (8c/16GB) | todo o stack (`~/stack/docker-compose.yml`): postgres `teqo_1313`, forgejo, registry `localhost:5000`, cloudflared, `teqo-1313` na 127.0.0.1:1313 e `teqo-staging` na 127.0.0.1:1314 (OPS103; DB `teqo_staging`, env `~/stack/teqo-staging.env`, bucket `teqo-media-staging`); **runner self-hosted do GitHub** (labels `self-hosted`, `homeserver`; instalado 2026-08-19 — Issue #113 OPS71-INFRA; `~/actions-runner` v2.336.0, systemd user `actions.runner.fsolla-teqo.teqo-1313-runner.service` — `systemctl --user status/restart`); workspace `~/teqo-deploy` (clone de `github.com/fsolla/teqo`, público) |
| **workstation** | dev/agentes apenas — o runner do Forgejo foi **desligado** no cutover (o schedule do `ci.yml` antigo não tem mais razão; religar é reversível) |
Segredos **não** ficam no GitHub: o script sourceia `~/stack/teqo-1313.env` e
Segredos **não** ficam no GitHub: o script sourceia o env file do ambiente
(`~/stack/teqo-1313.env` em produção, `~/stack/teqo-staging.env` em staging) e
`~/stack/.env` (chmod 600) no próprio homeserver. O repo GitHub é público — o
clone do workspace não precisa de credencial. No GitHub ficam apenas os
secrets de integração: `FORGEJO_API_TOKEN` (flips pós-merge) e
`CURSOR_API_KEY` (archive helper, dormente).
## Staging (OPS103)
Alvo real e descartável para validar o SHA (migração/build/rollout/smoke) antes
de produção. Mesmo dispatch, mesmo `verify`, mesmo script — o que muda é
`TEQO_ENV=staging` e o environment `staging` (sem reviewer; a aprovação que
importa é a de `production`).
| Item | Staging | Produção |
| ----------- | ------------------------------------------------------------------------------ | ------------------------------------------ |
| Container | `teqo-staging` (127.0.0.1:1314) | `teqo-1313` (127.0.0.1:1313) |
| Migrator | `teqo-staging-migrate` | `teqo-1313-migrate` |
| DB | `teqo_staging` | `teqo_1313` |
| Env file | `~/stack/teqo-staging.env` | `~/stack/teqo-1313.env` |
| Imagens | `localhost:5000/teqo-staging(-migrator):$SHA` | `localhost:5000/teqo-1313(-migrator):$SHA` |
| Bucket | `teqo-media-staging` | `teqo-media` |
| URL | `https://staging.jorgesolla1313.com.br` (noindex) | `https://jorgesolla1313.com.br` |
| Build proxy | `teqo-staging-build-proxy` (127.0.0.1:5434) | `teqo-1313-build-proxy` (127.0.0.1:5433) |
| Lock | `/tmp/teqo-deploy.lock` (compartilhado — compose/workspace/registry são um só) | idem |
### Bootstrap do homeserver (uma vez, manual — fora do repo)
1. **DB:** criar `teqo_staging` no Postgres do stack
(`docker compose exec postgres createdb -U teqo teqo_staging`).
2. **Env file:** `~/stack/teqo-staging.env` (chmod 600) com `DATABASE_URL`
apontando para `teqo_staging`, `PAYLOAD_SECRET` próprio,
`NEXT_PUBLIC_SITE_URL=https://staging.jorgesolla1313.com.br`,
`REVALIDATE_SECRET` próprio e `S3_*` do bucket `teqo-media-staging`.
3. **Compose:** adicionar `teqo-staging` e `teqo-staging-migrate` ao
`~/stack/docker-compose.yml`, espelhando os serviços de produção
(`pull_policy: never`, label `org.opencontainers.image.revision` **por
serviço**, healthcheck, `extra_hosts: host-gateway`) e a porta
`127.0.0.1:1314`.
4. **Bucket:** criar `teqo-media-staging` no Garage com key própria — nunca
reutilizar a key/bucket de produção.
5. **Tunnel/DNS:** ingress `staging.jorgesolla1313.com.br` →
`http://localhost:1314` no cloudflared + DNS no Cloudflare. Opcional
(defesa em profundidade): header `X-Robots-Tag: noindex` no ingress — o
noindex versionado (robots.ts + metadata, OPS103) já cobre crawlers.
6. **GitHub Environments:** criar `staging` (sem reviewer) e `production`
(required reviewer `fsolla`) em Settings → Environments — **antes do
primeiro dispatch** (environment `production` sem reviewer é fail-open).
7. **Migrate + seed sintético (antes do primeiro dispatch):** no homeserver,
com o workspace em `~/teqo-deploy`, criar o proxy de staging manualmente
(o deploy também cria, idempotente), migrar e semear. O guard local passa
porque o alvo é `127.0.0.1` — **sem** `ALLOW_REMOTE_DB`:
```bash
ssh homeserver
cd ~/teqo-deploy && pnpm install
docker inspect teqo-staging-build-proxy >/dev/null 2>&1 || docker run -d \
--name teqo-staging-build-proxy --network stack_default \
--restart unless-stopped -p 127.0.0.1:5434:5434 \
alpine/socat TCP-LISTEN:5434,fork TCP:postgres:5432
set -a; source ~/stack/teqo-staging.env; set +a
export DATABASE_URL="${DATABASE_URL/@postgres:5432/@127.0.0.1:5434}"
pnpm migrate
pnpm db:seed:minimal
```
Nunca copiar dados de produção (PII/LGPD): o seed mínimo é sintético.
### Limites do staging (o que ele NÃO valida)
- e2e automatizado (o full continua no `verify`, que valida o commit);
- carga, caos, multi-região;
- integrações origin-bound sem configuração própria: WebAuthn/passkeys,
Google OAuth e envio de e-mail (Resend). "Staging verde" ≠ "produção
garantida" — é validação de migração/build/rollout/smoke + inspeção humana;
- dados são sintéticos; nunca PII real.
## Cutover OPS71 (passos manuais, ordem)
1. Remotes locais (config compartilhada pelos worktrees):
@ -96,7 +181,10 @@ history (`git revert` do PR da remoção, ou clone do main congelado do Forgejo)
A imagem anterior **não** fica mais local após a limpeza pós-deploy (INF3/F2:
`docker builder prune` + remoção das tags locais antigas, exceto o SHA em uso)
— o registry `localhost:5000` **nunca deleta** e é a fonte do rollback. O
compose anterior fica em `~/stack/docker-compose.yml.pre-<sha-do-deploy-que-falhou>`.
compose anterior fica em `~/stack/docker-compose.yml.pre-<sha-do-deploy-que-falhou>`
(um por deploy; como o staging roda antes no mesmo SHA, o backup de produção é
o compose já com a linha do staging — o restore devolve o arquivo inteiro, o
que é o correto).
```bash
ssh homeserver
@ -116,6 +204,11 @@ docker pull localhost:5000/teqo-1313:<sha-anterior>
docker compose up -d teqo-1313
```
Para **staging**, o mesmo procedimento com as identidades do ambiente
(`teqo-staging`, `localhost:5000/teqo-staging:<sha-anterior>`,
`docker compose up -d teqo-staging`) — o rollback de um ambiente não toca o
container do outro (só restaura as linhas de imagem do arquivo compartilhado).
**Caveat:** uma migration de schema aplicada no passo de migrate **não** é
desfeita pelo rollback (Payload é append-only). Código velho sobre schema novo
pode se comportar mal — o caminho primário minimiza essa janela (migrate só
@ -129,18 +222,19 @@ a correção se re-mergeia e o próximo deploy completo publica.
| Sintoma | Causa | Tratamento |
| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Job verde sem deploy ("stale run") | Push mais novo venceu; o dispatch apontava um SHA que não é mais o HEAD do main do GitHub | Nada a fazer — dispatch novo no main atual |
| Prod regride para um SHA antigo após re-dispatch fora de ordem | O `flock` serializa mas não ordena; o "already deployed" não pega revision diferente | Não re-dispatchar SHA antigo; se acontecer, re-dispatchar o `main` atual (rollback manual disponível na seção Rollback). Revisitar se o deploy ganhar frequência/automação ou se uma regressão fora-de-ordem acontecer |
| Job verde sem deploy ("already deployed") | O container rodando já tem a revision do SHA do job (ex.: `workflow_dispatch` duplicado da mesma HEAD) | Nada a fazer — o site já roda esse SHA. Forçar rebuild da MESMA HEAD não é suportado via dispatch: edite o tag da imagem no compose (`image: localhost:5000/teqo-1313:<sha>-rebuild`) e `docker compose up -d`, ou espere um commit novo |
| Job `deploy` nunca roda / runner offline | Runner self-hosted do homeserver não instalado ou parado (passo manual do cutover OPS71) | Instalar/religar o runner (labels `self-hosted`, `homeserver`); os PRs e o `verify` não dependem dele — só o deploy |
| Job de deploy nunca roda / runner offline | Runner self-hosted do homeserver não instalado ou parado (passo manual do cutover OPS71) | Instalar/religar o runner (labels `self-hosted`, `homeserver`); os PRs e o `verify` não dependem dele — só os deploys |
| Deploy dispara mas o job `verify` falha | Regressão real na suíte full | Corrigir e re-dispatchar — o homeserver nunca é tocado |
| `No such image` ao recriar o container fora de deploy (ex.: `compose up -d` pós-reboot/migração) | O compose referenciava uma tag local bare (`teqo-1313:<sha>`) que desapareceu sem recriação (achado INF8/INF13, 24/08: só restava a ref do registry) | Corrigido no INF13: o compose passa a referenciar a tag **qualificada** (`localhost:5000/teqo-1313:<sha>`) a partir do primeiro deploy pós-fix — até lá, produção ainda roda o compose bare (recrie o alias via `docker tag` se necessário). Recovery geral: `docker pull localhost:5000/teqo-1313:<sha>` (+ `docker tag` se o compose em uso tiver tag bare) e `docker compose up -d` |
| Deploy para logo após o migrate ("Done." e nada mais, EXIT=0) | `docker compose run` anexa stdin por padrão — o container consome o resto do script; o bash chega a EOF e termina sem rodar o rollout | O script já usa `< /dev/null` no `run --rm` do migrate (não remover); sintoma visto 2026-08-17 no primeiro deploy |
| Build falha: `network mode "stack_default" not supported by buildkit` | BuildKit (drivers docker e docker-container) recusa rede bridge custom no `--network` | O script builda com `--network host` + proxy socat `teqo-1313-build-proxy` (na `stack_default`, publicado em 127.0.0.1:5433, criado idempotentemente com `restart: unless-stopped`) + `DATABASE_URL` reescrita para o loopback |
| Build falha: `network mode "stack_default" not supported by buildkit` | BuildKit (drivers docker e docker-container) recusa rede bridge custom no `--network` | O script builda com `--network host` + proxy socat do ambiente (prod `teqo-1313-build-proxy` em 127.0.0.1:5433; staging `teqo-staging-build-proxy` em 127.0.0.1:5434, na `stack_default`, criado idempotentemente com `restart: unless-stopped`) + `DATABASE_URL` reescrita para o loopback |
| Build OOM no homeserver | Laptop 8c/16GB com o stack ativo (~12GB livres medidos) | Re-dispatch; se recorrente, item futuro: build na workstation com túnel |
| Build do runner falha: `relation "..." does not exist` no `next build` | Migration nova criou tabela lida em geração estática. Pré-OPS66 a ordem era build→migrate e o deploy morria aqui para sempre (incidente 2026-08-18, S2) | Pós-OPS66 não deve ocorrer: migrate roda antes do build do runner. Se reaparecer, confira no log se o passo migrate rodou; recovery manual: `docker build --target migrator` + `docker run --rm --network stack_default --env-file ~/stack/teqo-1313.env localhost:5000/teqo-1313-migrator:<sha>` e re-dispatch do workflow |
| Workspace clone sem o SHA novo | O workspace antigo apontava para o Forgejo local (pré-OPS71) e o fetch não achou o SHA | O script agora re-aponta `origin` para `TEQO_REPO_URL` (idempotente) antes do fetch — se ainda falhar, `git -C ~/teqo-deploy remote -v` e corrigir manualmente |
| Migrate falha | Drift/erro de schema | Job vermelho; site segue no container antigo; corrigir e re-mergear |
| Smoke falha pós-up | Regressão de runtime | Rollback automático (restore + `up -d`) + job vermelho; investigar |
| `deploy-staging` falha cedo (`teqo-staging.env`/serviço ausente) | Bootstrap do staging incompleto (DB, env file, serviços no compose ou environment `staging`) | Rodar o bootstrap da seção Staging; produção nunca é tocada (staging vermelho fail-closa o job `deploy-production`) |
## Backup passivo no Forgejo (OPS76-FOLLOWUP, 2026-08-21)
@ -165,15 +259,40 @@ automaticamente — **não serve push, não recebe PRs, é somente leitura**.
## Segurança (decisão deliberada)
- O job `deploy` usa `runs-on: [self-hosted, homeserver]` — executa como o
usuário do runner no homeserver. Está **apenas** no `deploy.yml`
(dispatch manual), nunca no `ci-pr.yml`; o hosted (`verify`) não tem acesso
ao homeserver e o self-hosted não recebe secrets de produção (as envs vivem
no próprio homeserver). `main` só anda por PR mergeado com CI verde; o
deploy só roda com `verify` full verde. Fork-PRs não rodam CI (same-repo
gate + setting do repo).
- Os jobs `deploy-staging`/`deploy-production` usam
`runs-on: [self-hosted, homeserver]` — executam como o usuário do runner no
homeserver. Estão **apenas** no `deploy.yml` (dispatch manual), nunca no
`ci-pr.yml`; o hosted (`verify`) não tem acesso ao homeserver e o self-hosted
não recebe secrets de produção (as envs vivem no próprio homeserver,
inclusive as de staging — nunca como GitHub secrets). `main` só anda por PR
mergeado com CI verde; o deploy só roda com `verify` full verde. Fork-PRs
não rodam CI (same-repo gate + setting do repo).
- Segredos nunca ecoados: sem `set -x`, senhas via `--password-stdin` /
build-secrets; envs só no homeserver.
- Staging sem PII real (seed sintético), bucket/DB/env próprios e noindex —
nunca compartilha credencial, bucket ou dados com produção.
## C149 — Google OAuth da agenda (envs novas + GCP)
O botão **"Conectar com o Google"** da agenda usa um OAuth client do GCP. Sem
as envs, o diálogo cai no runbook antigo da service account — que segue como
fallback e não foi removida por esta entrega.
1. No GCP (mesmo projeto da service account), crie um OAuth client **Web
application** com os redirect URIs:
- `https://jorgesolla1313.com.br/campanha/agenda/google-oauth/callback`
- `http://localhost:<porta>/campanha/agenda/google-oauth/callback` (dev)
2. Publique o app em produção — **unverified** é aceito (uso interno). Em
"Testing" o refresh token expira em ~7 dias e o estado vira `erro` na UI.
3. Adicione ao `~/stack/teqo-1313.env` (homeserver, chmod 600):
`GOOGLE_CALENDAR_OAUTH_CLIENT_ID` e `GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET`.
4. Deploy normal (`workflow_dispatch` do `deploy.yml`). O callback monta o
redirect a partir de `NEXT_PUBLIC_SITE_URL` — precisa bater exatamente com
o URI registrado no passo 1.
Desconectar no Teqo apaga o refresh token daquele lado; para revogar o acesso
de fato, revogue o app em `myaccount.google.com/permissions` (a UI orienta o
passo).
## OPS79 — última migração da plataforma antiga → nova (vertical campanha)
@ -313,8 +432,9 @@ Não há escrita; "rollback" = rodar de novo (idempotente, read-only).
## Referências
- `scripts/deploy-homeserver.sh` — o script (fonte da verdade do fluxo)
- `.github/workflows/deploy.yml` — verify → deploy
- `scripts/deploy-homeserver.sh` — o script (fonte da verdade do fluxo; parametrizado por `TEQO_ENV`)
- `.github/workflows/deploy.yml` — verify → deploy-staging → deploy-production (OPS103)
- `docs/plans/ops53-ci-deploy-homeserver*.md` — intenção e decisões (era Forgejo)
- `docs/plans/ops71-ci-github-actions-tracker-forgejo*.md` — o cutover
- `docs/plans/ops103-staging-homeserver*.md` — staging com verify único e aprovações separadas
- infra-solla: `STATE.md`, `plano-infra-final.md` §"Arquitetura de deploy"

View file

@ -0,0 +1,175 @@
# Impl: C149 — Google Calendar: botão Conectar Google (OAuth) substitui a configuração manual de service account
Status: em execução
Atualizado em: 2026-09-12
Issue: #934
Intenção: docs/plans/c149-conectar-google-oauth.md
Appetite restante: ~2 dias eng (herdado)
## Leitura da intenção
- **Outcome:** candidato/coordenador conecta a conta Google do calendário da campanha com um clique (consent), sem criar service account nem colar JSON; o estado da conexão é honesto (`conectado | erro | não configurado`), erro de token reconecta em um clique e o Teqo segue SoT.
- **Não negociar:** escopos mínimos literais (`calendar.events` + `calendar.calendarlist.readonly`); exatamente três estados, derivados, nunca armazenados; `GOOGLE_CALENDAR_SERVICE_ACCOUNT_KEY` preservada como fallback (não renomear/remover); token sobrevive sem re-consentimento semanal; não é OAuth por pessoa (anti-goal C114); motor de reconciliação intocado; callback sempre na URL pública (`getCampaignInviteBaseURL()`); token nunca em log; armazenamento fail-closed (sem conexão → sem sync, sem crash); leader lockdown intocado.
- **Reavaliar:** app unverified exige publicar em produção no GCP para o refresh token não expirar em ~7 dias (decisão de ops, D14); armazenamento do refresh token em texto puro é débito consciente com gatilho de revisão (D1); advisor vê o card sem botões (assumido com produto); a escrita de `calendarId` continua admin-only e será aberta no C150.
## Abordagem recomendada
```mermaid
flowchart LR
subgraph UI["Agenda /campanha/agenda"]
CARD["GoogleCalendarSyncDialog<br/>card de conexão (3 estados)"]
end
CARD -->|startGoogleCalendarOAuth| ACT[server action]
ACT -->|state assinado HMAC| COOKIE[(cookie campaign<br/>TTL 10min, single-use)]
ACT -->|authorizeUrl| GOOG[accounts.google.com<br/>consent]
GOOG -->|code + state| CB[callback GET<br/>fora do app]
COOKIE -->|verifica state| CB
CB -->|troca code| TOK[oauth2 token endpoint]
TOK -->|refresh_token| DB[(googleCalendarSync<br/>oauthRefreshToken)]
CB -->|302 /campanha/agenda| CARD
SYNC[runCampaignCalendarSync] -->|readGoogleCalendarAuth| DB
SYNC -->|Bearer access token| GCAL[Google Calendar API]
SA[GOOGLE_CALENDAR_SERVICE_ACCOUNT_KEY] -.fallback quando sem OAuth.-> SYNC
CARD -->|disconnectGoogleCalendarOAuth| ACT2[server action]
ACT2 -->|limpa conexão| DB
```
**Opções consideradas:** A) Authorization Code + rota de callback própria com state assinado em cookie | B) fluxo out-of-band (device/código colado) | C) manter service account e melhorar só o runbook.
**Recomendação:** A — reusa o precedente de cerimônia fora do `(app)` (WebAuthn) e o resolvedor de URL pública (`getCampaignInviteBaseURL`), entrega o consent de um clique e isola o callback para teste; B troca "um clique" por "copiar e colar código" e não tem precedente; C não entrega o outcome pedido pelo dono.
**Rejeitadas:** B porque adiciona atrito e uma superfície de erro nova; C porque é exatamente a cerimônia que o pedido manda remover.
### Componentes / mudanças
- **`src/collections/GoogleCalendarSync.ts`** — cinco campos novos (D1): `oauthRefreshToken` (text, `read: canReadGoogleCalendarSyncIdentityField`, `create/update: canSetGoogleCalendarSyncSystemField`), `oauthScope` (text), `oauthConnectedAt` (date), `oauthErrorAt` (date), `oauthError` (textarea); labels/admin `readOnly` em pt-BR; `admin.defaultColumns` inalterado.
- **`src/utilities/access/googleCalendarSync.ts`** — `canManageGoogleCalendarConnection(actor)` (delega a `isCampaignUnrestricted`); novos campos usam os helpers existentes (`canSetGoogleCalendarSyncSystemField`, `canReadGoogleCalendarSyncIdentityField`).
- **`src/migrations/<timestamp>_add_google_calendar_oauth_connection.{ts,json}` + `index.ts`** — migração aditiva (colunas nullable), gerada com `pnpm migrate:create add_google_calendar_oauth_connection`; `src/payload-types.ts` regenerado (`pnpm generate:types`).
- **`src/lib/googleCalendarOAuth.ts`** (novo, puro) — `GOOGLE_CALENDAR_OAUTH_SCOPES`, `GOOGLE_CALENDAR_OAUTH_CALLBACK_PATH`, `GOOGLE_CALENDAR_OAUTH_AUTHORIZE_ENDPOINT`, `buildGoogleCalendarOAuthAuthorizeUrl({ clientId, redirectUri, state })` com `access_type=offline`, `prompt=consent`, `response_type=code`.
- **`src/utilities/googleCalendarOAuth.ts`** (novo, server-only, sem importar `googleCalendarSync`) — `readGoogleCalendarOAuthCredentials()` (fail-closed), `buildGoogleCalendarOAuthRedirectUri()` (via `getCampaignInviteBaseURL()`), `storeGoogleCalendarOAuthState(state, userId)` / `readGoogleCalendarOAuthState(state)` / `clearGoogleCalendarOAuthState()` (HMAC `PAYLOAD_SECRET`, payload state+userId+exp, TTL 10min, httpOnly/lax, path `/campanha`, single-use), `exchangeGoogleCalendarOAuthCode(code, fetchImpl?)` → `{ refreshToken, scope }` ou erro tipado com mensagem segura (sem corpo/token).
- **`src/utilities/googleCalendarClient.ts`** — `GoogleCalendarAuth = { kind: 'service-account'; credentials } | { kind: 'oauth'; refreshToken; clientId; clientSecret }`; `createGoogleCalendarClient(auth, ...)` mantém os 6 métodos e o cache em memória; `requestAccessToken` ganha o branch `grant_type=refresh_token`; novo `GoogleCalendarAuthError` APENAS para `invalid_grant` (refresh token revogado/expirado — o caso reconectável; `invalid_client`/5xx seguem `GoogleCalendarApiError`, pois reconectar não conserta); `buildServiceAccountAssertion` preservado para testes.
- **`src/utilities/googleCalendarSync.ts`** — `readGoogleCalendarAuth(config)` (OAuth se refresh token + env; senão SA; senão `null`); `GoogleCalendarConnectionState = 'connected' | 'error' | 'not-configured'` + `deriveGoogleCalendarConnectionState`; `GoogleCalendarSyncView` ganha `connection`, `oauthAvailable`, `oauthConnectedAt`, `oauthError`; `loadGoogleCalendarSyncConfig` passa a "row com `calendarId` vence, senão qualquer row" (D11); helpers `recordGoogleCalendarOAuthConnection`, `recordGoogleCalendarOAuthError`, `clearGoogleCalendarOAuthConnection`; `runCampaignCalendarSync` resolve a auth pelo config, limpa `oauthError*` no sucesso e grava `oauthErrorAt/oauthError` no catch de `GoogleCalendarAuthError`.
- **`src/app/(campaign)/campanha/actions/googleCalendarSync.ts`** — `startGoogleCalendarOAuth()` (valida `reloadUnrestrictedActor`, exige env, cria o row singleton se ausente com admin bypass, grava state cookie, devolve `{ ok, authorizeUrl }`) e `disconnectGoogleCalendarOAuth()` (limpa token/scope/datas/erro; sem revoke remoto; sem pass de sync); `GoogleCalendarSyncActionResult` ganha `canManageConnection` e os campos de conexão; `failure()` atualizado.
- **`src/app/(campaign)/campanha/agenda/google-oauth/callback/route.ts`** (novo, fora do `(app)`, `dynamic = 'force-dynamic'`) — GET: lê `code/state/error`, verifica e queima o state cookie, re-checa papel fresco, troca o code, grava a conexão, roda pass de sync se houver `calendarId` e responde `NextResponse.redirect` 302 para `/campanha/agenda`; `access_denied` não grava erro; falha de troca grava `oauthError` e redireciona (sem query param).
- **`src/components/campaign/activity/GoogleCalendarSyncDialog.tsx`** — card de conexão por estado (badge, Conectar/Reconectar/Desconectar, nota do fallback SA, nota para não-manager, runbook admin só quando `!oauthAvailable`); props novas `onStartOAuth`, `onDisconnect`, `canManageConnection`.
- **`src/components/campaign/activity/AgendaGoogleSyncChrome.tsx`** — callbacks `onStartOAuth`/`onDisconnect` repassados; pill existente intocada.
- **`src/app/(campaign)/campanha/(app)/agenda/page.tsx`** — passa as server actions novas ao chrome.
- **`scripts/lib/e2e-affected-manifest.mjs`** — entry nova mapeando `src/utilities/googleCalendarSync.ts`, `googleCalendarSyncHooks.ts`, `googleCalendarClient.ts`, `googleCalendarOAuth.ts`, `src/lib/googleCalendarOAuth.ts`, `GoogleCalendarSyncDialog.tsx`, `AgendaGoogleSyncChrome.tsx` e `src/app/(campaign)/campanha/agenda/google-oauth` ao spec `campaignAgendaGoogleSync`.
- **`playwright.config.ts`** — `GOOGLE_CALENDAR_OAUTH_CLIENT_ID`/`_SECRET` dummy no `webServer.env` (botão visível no e2e).
- **`tests/e2e/campaignAgendaGoogleSync.e2e.spec.ts`** — estados com OAuth: botão, URL de consent interceptada, conectado e erro.
- **`.env.example` + `docs/ops/teqo-1313-deploy.md`** — as duas envs e o runbook GCP (D14).
- **Testes:** `tests/unit/googleCalendarOAuth.unit.spec.ts` (novo), extensões em `googleCalendarClient.unit.spec.ts`, `googleCalendarSync.unit.spec.ts`, `googleCalendarSyncDialog.unit.spec.tsx`, `agendaGoogleSyncChrome.unit.spec.tsx`, `tests/int/googleCalendarSync.int.spec.ts`, `tests/int/googleCalendarSyncAction.int.spec.ts`; allowlist top-level de `tests/unit/codebaseConventions.unit.spec.ts` ganha `googleCalendarOAuth.ts`.
### Dados → forma
Estado da conexão é **derivado** (nunca armazenado), função de `oauthRefreshToken`, `oauthConnectedAt` e `oauthErrorAt`:
| refresh token | erro mais novo que a conexão | estado | UI |
| ------------- | ----------------------------------------------------------- | ---------------- | ------------------------------------------------------------------- |
| não | não | `not-configured` | "Não configurado" + Conectar (se `oauthAvailable`) ou runbook admin |
| sim ou não | sim (`oauthErrorAt > oauthConnectedAt`, inclui sem conexão) | `error` | "Erro na conexão" + Reconectar + Desconectar |
| sim | não | `connected` | "Conectado" + Desconectar |
`oauthAvailable` (env do client presente) é ortogonal ao estado e decide botão vs. runbook. `oauthScope`, `oauthConnectedAt` e `oauthError` são apenas informativos/derivados; o token nunca cruza a fronteira da view.
## Decisões de engenharia (decisão + por quê + rejeitadas; só as caras de reverter)
1. **Armazenamento na própria `googleCalendarSync` (D1):** campos novos na collection que já é dona do estado do espelho; sem collection twin. Texto puro com precedente (`SocialFeedSettings.instagramAccessToken`, `pushChannelSecret`), `read: false` no token e nunca logar. **Rejeitadas:** AES-GCM (sem precedente no repo, rotação de chave e o DB comprometido já é game over) — vira débito com gatilho de revisão; collection nova (twin).
2. **Credenciais do app OAuth em env (D2):** `GOOGLE_CALENDAR_OAUTH_CLIENT_ID`/`_SECRET`; redirect URI sempre derivado de `getCampaignInviteBaseURL()` + `/campanha/agenda/google-oauth/callback`. **Rejeitadas:** client no DB (não é per-campanha); override de redirect por env (risco de localhost vazar).
3. **Transporte por união de auth (D3):** `GoogleCalendarAuth` com SA (JWT assertion, comportamento atual) e OAuth (refresh_token grant) na mesma superfície de 6 métodos, mesmo cache e mesmo retry de 401; `GoogleCalendarAuthError` separa conexão quebrada (`invalid_grant`, reconectável) de erro de API/config (`invalid_client`, 5xx → pausa). **Rejeitadas:** segundo client OAuth paralelo; tratar todo erro de token como auth error (invalid_client viraria "reconecte" sem conserto).
4. **Resolução e limpeza no motor (D4):** `readGoogleCalendarAuth` prefere OAuth quando há refresh token + env, senão SA, senão `null`; sucesso limpa `oauthError*`, `GoogleCalendarAuthError` grava `oauthErrorAt/oauthError` além de `lastError`/paused. **Rejeitada:** fallback silencioso para SA com token quebrado (mascararia o erro e tornaria o estado `error` inalcançável com SA configurada).
5. **Estado derivado (D5):** `'connected' | 'error' | 'not-configured'` como função pura dos campos, nunca coluna nova. **Rejeitadas:** armazenar o estado (drift); quarto estado intermediário.
6. **Papéis (D6):** conectar/desconectar = `isCampaignUnrestricted` via `canManageGoogleCalendarConnection`, enforcement com `reloadUnrestrictedActor` na action; advisor vê o card sem botões; leader não vê a agenda. **Rejeitadas:** advisor conectar (credencial global); liberar por `canUpdateGoogleCalendarSync` (staff inteiro).
7. **Fluxo: action de start + callback GET com state em cookie (D7):** `startGoogleCalendarOAuth` devolve `authorizeUrl` e o client navega; callback valida state (HMAC, TTL 10min, single-use, bound ao userId), re-checa papel fresco, troca o code e responde 302. **Rejeitadas:** searchParam/hash para aviso pós-callback (a canonicalização de `resolveActivityAgendaUrl` come parâmetros desconhecidos); rota GET de start (menos testável e sem precedente); revogação remota no disconnect.
8. **Desconectar limpa só o Teqo (D8):** remove refresh token/scope/datas/erro com admin bypass e orienta revogar no Google; sem pass de sync automático (o próximo trigger cai no fallback SA, se houver). **Rejeitada:** chamar `/revoke` no Google (fora do literal da intenção).
9. **Módulos (D9):** puro em `src/lib/googleCalendarOAuth.ts`, server-only em `src/utilities/googleCalendarOAuth.ts` (sem importar `googleCalendarSync` para não criar ciclo), record/clear e resolução no `googleCalendarSync.ts`, client no `googleCalendarClient.ts`; registrar o novo top-level na allowlist. **Rejeitadas:** um módulo único misturando puro/server; lógica OAuth dentro do client.
10. **UI (D10):** card de conexão dentro do `GoogleCalendarSyncDialog`; pill existente e motor intocados; runbook admin só quando `!oauthAvailable`. **Rejeitadas:** diálogo novo; mexer na pill de status do espelho.
11. **Loader singleton (D11):** "row com `calendarId` vence; senão qualquer row" para o row da conexão não ficar escondido pelo filtro atual. **Rejeitada:** manter o filtro e criar row só no primeiro sync (a conexão ficaria invisível).
12. **Manifest e2e (D12):** entry do domínio Google Calendar → `campaignAgendaGoogleSync`, fechando o gap pré-existente. **Rejeitada:** confiar só no fallback de smoke (o spec não rodaria no PR).
13. **E2E determinístico (D13):** envs dummy no webServer; estados conectado/erro com `lastSuccessAt` futuro para não disparar auto-retry; consent assertado com `page.route('https://accounts.google.com/**')`. **Rejeitada:** consent real (rede/flake).
14. **Ops documentado, sem código (D14):** OAuth client "Web application" no GCP com redirect URIs (prod + dev), escopos, app **publicado em produção (unverified)** para o refresh token não expirar em 7 dias; envs em `~/stack/teqo-1313.env`; aviso de app não verificado aceito (decisão de produto A).
## Fases verificáveis
1. **Tracer/schema + server (~55%, ≈1,1 dia)**
- Campos + access + `pnpm migrate:create add_google_calendar_oauth_connection` + `pnpm migrate` + `pnpm generate:types`.
- `src/lib/googleCalendarOAuth.ts` e `src/utilities/googleCalendarOAuth.ts` com unit (URL, escopos, state TTL/single-use, env fail-closed, exchange sem token em mensagem).
- Auth union + `GoogleCalendarAuthError` no client com unit (SA inalterado, refresh grant, 401 re-mint).
- `readGoogleCalendarAuth`, derivação do estado, loader D11, record/clear, sucesso limpa erro, catch de `GoogleCalendarAuthError`; unit/int do sync atualizados.
- Actions start/disconnect + `canManageGoogleCalendarConnection`; int com mock de `campaignActionContext` (padrão de `googleCalendarSyncAction.int.spec.ts`).
- Allowlist top-level de `codebaseConventions` registrada. Gate: `pnpm gate:fast`.
2. **Callback + UI + e2e + docs (~35%, ≈0,7 dia)**
- Callback route (state, papel fresco, exchange, grava, pass se `calendarId`, 302).
- Dialog/chrome/page; unit de dialog/chrome; copy pt-BR dos três estados + orientação de revogar no Google.
- e2e: envs no `playwright.config.ts`, spec com botão/consent/conectado/erro, entry no manifest.
- `.env.example` + runbook em `docs/ops/teqo-1313-deploy.md`. Gate: `pnpm test:e2e:affected` (deve incluir `campaignAgendaGoogleSync`).
3. **Gates finais (~10%, ≈0,2 dia)**
- `pnpm gate:fast`; e2e afetado local (`pnpm test:e2e:affected`); `pnpm push`.
## Rabbit holes / Não escopo (engenharia)
- **Criptografar o refresh token no DB (AES-GCM/keyring):** débito registrado com gatilho (rotação de chave/requisito de compliance); não entra.
- **Chamar `/revoke` no Google ao desconectar:** só orientação na UI (literal da intenção).
- **Listar/escolher calendário:** C150; aqui só a conexão.
- **Verificação completa do app Google / auditoria:** ops, fora.
- **Aposentar/migrar a service account:** fora; segue fallback.
- **Watchdog de expiração do refresh token / cron:** fora; o erro aparece no próximo pass e a UI oferece Reconectar.
- **Módulo genérico de envs:** fora; `process.env` direto como no resto do repo.
- **Rate limiting nas rotas OAuth:** fora; state + TTL bastam para este escopo.
- **Motor de reconciliação, janela, locks, hooks C114/C122:** intocados.
- **Aviso pós-callback via searchParam/hash:** rejeitado; redirect simples para `/campanha/agenda`.
- **OAuth por pessoa / agenda pessoal:** anti-goal C114.
## Riscos e mitigação
- **Refresh token expira em ~7 dias (app unverified em testing):** D14 publica o app em produção (unverified) no GCP; se expirar, estado vira `error` e Reconectar resolve. Risco residual aceito (produto A).
- **Localhost vazando no redirect atrás do túnel:** redirect URI sempre de `getCampaignInviteBaseURL()` (prod exige HTTPS DNS); unit pin do path do callback; e2e asserta `redirect_uri` público.
- **CSRF/replay do callback:** state HMAC `PAYLOAD_SECRET` com TTL 10min, single-use (queimado antes da troca) e binding ao userId; papel re-checado fresco.
- **Token em log:** exchange não loga corpo; mensagens usam status/código seguros; `oauthRefreshToken` com `read: false`; unit garante ausência de token/code na mensagem de erro.
- **Falha do Google corromper dados:** Teqo SoT; `GoogleCalendarAuthError` só grava `oauthError*`/paused; int cobre `invalid_grant` sem apagar/duplicar eventos.
- **OAuth quebrado sem fallback SA:** decisão consciente (D4); a UI expõe erro + Reconectar e o runbook explica.
- **Upsert do row/corrida:** start cria o singleton com admin bypass; única escrita concorrente é o callback; sem lock novo.
- **Migration em prod:** aditiva/nullable, aplicada pelo deploy (`pnpm build` roda `payload migrate`); sem backfill; baseline intocada.
- **`unmapped-risk` no CI:** `src/utilities/access` já é mapeado; a entry nova do domínio Google entra no mesmo PR — falhar fechado é o comportamento desejado.
- **Auto-retry em erro de conexão:** uma tentativa por load da agenda (sem hammer); falha rápida no token endpoint.
## Qualidade da decisão
**Auto-avaliação: 4/5** — as decisões já vêm fechadas e ancoradas em achados concretos (rotas de cerimônia fora do `(app)`, cookie HMAC do WebAuthn, precedente de credencial no DB, canonicalização da agenda, gap do manifest), e o caminho crítico é testável sem tocar o Google. Perde 1 ponto por dependências fora do código: o refresh token de app unverified é uma promessa de ops (publicar em produção no GCP) e o e2e não exercita consent real, então a prova de produção fica no smoke manual pós-deploy; o armazenamento em texto puro é débito aceito com gatilho, não resolvido.
## Aceite de engenharia
- [ ] Botão "Conectar com o Google" no card da agenda para candidato/coordenador; advisor vê o card sem botões; leader sem agenda (lockdown intocado).
- [ ] Estados exatamente `conectado | erro | não configurado`, derivados de `oauthRefreshToken`/`oauthConnectedAt`/`oauthErrorAt`.
- [ ] Erro de token (`invalid_grant`) mostra Reconectar em um clique; `access_denied` não grava erro.
- [ ] Callback atrás do túnel usa a URL pública (`getCampaignInviteBaseURL()`); sem localhost em produção.
- [ ] Token nunca em log; `oauthRefreshToken` com `read: false`; exchange sem corpo em erro.
- [ ] Fail-closed: sem auth → `runCampaignCalendarSync` retorna cedo, sem crash e sem sync.
- [ ] Desconectar limpa a conexão no Teqo e orienta revogar no Google; sem pass de sync automático.
- [ ] Service account segue como fallback; `GOOGLE_CALENDAR_SERVICE_ACCOUNT_KEY` não renomeada/removida.
- [ ] Escopos literais `calendar.events` + `calendar.calendarlist.readonly`; `access_type=offline` + `prompt=consent`.
- [ ] Migration nova aplicada local + `payload-types.ts` regenerado; nenhuma migration antiga editada.
- [ ] `pnpm gate:fast` verde; `pnpm test:e2e:affected` inclui `campaignAgendaGoogleSync` (manifest atualizado) e passa local.
- [ ] `.env.example` e runbook de ops (GCP, envs, app publicado unverified) documentados.
## Execução — desvios e decisões emergentes (2026-09-12)
- **Classificação do `invalid_grant` virou helper puro** (`oauthErrorPatchFor` em `googleCalendarSync.ts`, pinado em unit): o catch do motor é I/O-bound e o int de motor com row configurado colidia com os specs C114 paralelos. O comportamento é o mesmo; a prova ficou no unit.
- **Escopos concedidos são validados no exchange**: consent granular permite desmarcar `calendar.events`; sem a checagem o card diria "Conectado" e o sync falharia 403 sem caminho de reconexão.
- **Callback só grava `oauthError` quando o EXCHANGE falha** (papel recusado/env ausente não sujam o estado de uma conexão sadia; um erro transitório se auto-cura no próximo pass bem-sucedido, que limpa o campo).
- **Suíte int dos specs Google serializada por advisory lock** (`GOOGLE_CALENDAR_SYNC_LOCK_KEY` + `serializeSpecWithAdvisoryLock` em `tests/helpers/advisoryLock.ts`): a collection é singleton e o loader "row configurado vence" fazia specs paralelos lerem o doc um do outro. A serialização elimina a dependência de `retry` da família.
- **Specs novos não criam rows configurados** (só connection-only) e limpam tokens em rows compartilhados sem deletá-los; o pass do callback é mockado no spec de actions (o motor tem spec próprio).
- **`.env.example` + runbook C149 em `docs/ops/teqo-1313-deploy.md`** documentam o OAuth client, os redirect URIs e a publicação unverified.
## Débitos (triage do /simplify)
| ID | Achado | Score | Tipo | Destino |
| --- | -------------------------------------------------------------------- | ----- | ------------- | -------------------------------------------------------------------------------------------------------------------------- |
| S1 | Cookie HMAC — 3ª cópia (`googleCalendarOAuth` vs WebAuthn vs import) | 3 | defer_trigger | Defer: extrair `signedCampaignCookie` no 4º cookie assinado ou no próximo toque de um dos três |
| S2 | Refresh token OAuth em texto puro no DB | 3 | defer_trigger | Defer: cifrar em repouso quando compliance/counsel exigir (o campo já é `read: false` e o precedente do repo é texto puro) |
| S3 | Upsert do singleton sem constraint única | 2 | defer_trigger | Defer para **C150** (dono do `calendarId`): decidir constraint se twins virarem risco real |
| S4 | Helper de env dos testes duplicado em 3 specs | 2 | cheap_polish | Descartado (barato, local; os specs estão verdes) |
| S5 | `docToView` com 3 flags posicionais | 1 | cheap_polish | Descartado (cosmético) |
- **Já resolvido no simplify (não reabrir):** índice em `oauthConnectedAt` removido; `failure()` sem diagnóstico falso; copy do card ajustada; `Date.parse` na derivação; guarda do `parseAccessToken`; validação de escopo concedido; prefixo morto do manifest; callback grava erro só do exchange; `runAction` no dialog; classify puro `oauthErrorPatchFor`; serialização int.
- **Explicitamente fora:** criptografia do refresh token agora; revogação remota no Google (só orientação); rate limiting nas rotas OAuth; verificação completa do app Google; aposentadoria da service account.

View file

@ -0,0 +1,163 @@
# Impl: C150 — Agenda: calendário principal escolhido pelo candidato/coordenador + inscrição de staff no Google
Status: em execução
Atualizado em: 2026-09-12
Issue: #935
Intenção: docs/plans/c150-calendario-principal-e-inscricao-staff.md
Appetite restante: ~1,5–2 dias eng (herdado)
## Leitura da intenção
- **Outcome:** na própria agenda (`/campanha/agenda`), o candidato/coordenador lista os calendários da conta Google conectada (C149) e escolhe o calendário principal da campanha — create/edit passam a espelhar nele; um staff adiciona a agenda ao Google pessoal com um clique, sem copiar link nem "Por URL". O recorte filtrado segue no feed ICS atual.
- **O que NÃO negociar:** leader lockdown (nem vê as ações); Teqo segue SoT; um calendário principal só (nada de N espelhos); motor C114/C115 não muda de modelo; falha do Google não derruba a agenda (estado do sync visível); admin do Payload continua como escape hatch; o fluxo do recorte ICS (`CalendarFeedDialog`) fica intocado; OAuth por pessoa e backfill do calendário antigo são anti-goals.
- **O que reavaliar (divergências registradas no plano):**
- A "Direção no codebase" sugeria abrir `canSetGoogleCalendarSyncConfigField` a candidato/coordenador. **Rejeitado** (D2): a escrita passa por action de manager + utility system write com validação "id pertence à lista viva da conta conectada"; o campo segue admin-only.
- O bullet de e2e do explorador propõe interceptar `oauth2.googleapis.com/token` e `www.googleapis.com/calendar/v3/...` com `page.route`. **Impossível** (D7): `page.route` só vê o tráfego do browser; a listagem roda no processo Next (server action). O caminho feliz lista/escolhe fica no int com stub client; o e2e cobre os contratos do browser.
- O rascunho UI desenha o botão mobile full-width; o cluster do top bar não suporta isso — adaptado para ícone + `aria-label` (D6).
- A cena de "confirmação da inscrição" do rascunho não é implementável (o Google não chama de volta); fora de escopo (não escopo de engenharia).
## Abordagem recomendada
```mermaid
flowchart LR
subgraph UI["Agenda /campanha/agenda"]
CHROME["AgendaGoogleSyncChrome<br/>(dono dos 2 diálogos)"]
SYNC["GoogleCalendarSyncDialog<br/>card de conexão"]
PICKER["GoogleCalendarPickerDialog"]
ADD["Adicionar ao meu Google Calendar<br/>(âncora target=_blank no header)"]
end
CHROME --> SYNC
SYNC -->|"manager + connected:<br/>Escolher/Trocar calendário"| PICKER
PICKER -->|listGoogleCalendars| A1[server action]
PICKER -->|chooseGoogleCalendar| A2[server action]
A1 --> U1["listGoogleCalendarPickerOptions"]
A2 --> U2["setCampaignPrimaryCalendarId"]
U1 --> CL["GoogleCalendarClient.listCalendars<br/>GET /users/me/calendarList?minAccessRole=writer"]
U2 --> CL
U2 -->|"valida id na lista viva"| DB[("googleCalendarSync.calendarId<br/>system write overrideAccess")]
DB -->|"config hook D7"| ENG["runCampaignCalendarSync<br/>re-concilia no novo calendário"]
CHROME --> ADD
ADD -->|href| GOOG["calendar.google.com/calendar/r?cid=calendarId"]
U1 -. GoogleCalendarAuthError .-> ERR["recordGoogleCalendarOAuthError<br/>card deriva error/Reconectar"]
U2 -. GoogleCalendarAuthError .-> ERR
```
**Opções consideradas:** A) listagem no client + actions de manager com validação viva + picker como diálogo próprio + literal `cid=<calendarId>` | B) abrir `canSetGoogleCalendarSyncConfigField` a `isCampaignUnrestricted` (hipótese da intenção) | C) armazenar nome/summary do calendário e fazer o picker a partir do banco.
**Recomendação:** A — mantém o motor e o modelo de dados intocados, concentra a nova escrita num utility com bypass e validação server-side (mesmo padrão de `recordGoogleCalendarOAuthConnection`), e entrega os dois outcomes com um componente de diálogo novo e zero migration. B abriria escrita crua de id arbitrário pela superfície REST do `campaignUser` sem a validação "pertence à conta conectada"; C exige migration e sofre drift quando o calendário é renomeado no Google.
**Rejeitadas:** B porque o enforcement de papel não substitui a validação de pertencimento (e o admin deve seguir funcionando como escape hatch); C porque a lista é viva e o "em uso" deriva de `state.calendarId` sem persistir nada.
### Componentes / mudanças
**Server**
- **`GoogleCalendarClient.listCalendars`** (`src/utilities/googleCalendarClient.ts`): método novo na superfície existente (mesmo `apiFetch`, mesmo cache de token, mesmo retry de 401, mesmo timeout de 15s). `GET {base}/users/me/calendarList` com `minAccessRole=writer`, `showHidden=true`, `maxResults=250`, `fields=items(id,summary,primary,deleted),nextPageToken` e loop de `pageToken`; filtra `deleted`; `summary` cai para o `id` quando ausente. Tipo novo `GoogleCalendarListEntry = { id: string; summary: string; primary: boolean }`. `CALENDAR_LIST_PAGE_SIZE = 250`.
- **`listGoogleCalendarPickerOptions(payload, options?: { client?: GoogleCalendarClient })`** (`src/utilities/googleCalendarSync.ts`): carrega a row (`loadGoogleCalendarSyncConfig`), resolve `readGoogleCalendarAuth` e **exige `auth.kind === 'oauth'`**; cria o client (ou usa `options.client`) e devolve `{ ok: true; calendars } | { ok: false; reason: 'not-connected' | 'auth-error' | 'api-error'; message }`. Em `GoogleCalendarAuthError`, grava `recordGoogleCalendarOAuthError` e devolve `reason: 'auth-error'` com a mensagem do erro (já segura, pt-BR). `GoogleCalendarPickerOption = GoogleCalendarListEntry` (alias, sem twin de shape).
- **`setCampaignPrimaryCalendarId(payload, calendarId, options?)`** (mesmo arquivo): reusa `listGoogleCalendarPickerOptions` (inclusive o record de auth error), exige que `calendarId` esteja na lista viva (`not-listed` quando não está), no-op quando já é o atual, e escreve com `payload.update({ collection: 'googleCalendarSync', id, data: { calendarId }, depth: 0, overrideAccess: true })` — o hook `googleCalendarSyncConfigHook` (D7) dispara `runCampaignCalendarSync` no novo calendário. Nunca cria row (a row conectada existe; sem row → `not-connected`).
- **Actions** (`src/app/(campaign)/campanha/actions/googleCalendarSync.ts`, mesmo padrão manual try/catch — sem `runCampaignFormAction`/zod):
- `listGoogleCalendars(): Promise<GoogleCalendarListActionResult>` — `loadConnectionManager` (candidate/coordinator) + utility; falha de papel devolve `{ ok: false, message: GOOGLE_CALENDAR_PRIMARY_MANAGER_ONLY_MESSAGE }`.
- `chooseGoogleCalendar(calendarId: string): Promise<GoogleCalendarSyncActionResult>` — `loadConnectionManager`; valida `typeof calendarId === 'string'` com tamanho sano; utility; sucesso devolve `{ ok: true, canManageConnection: true, ...withLinks(await readGoogleCalendarSyncView(payload)) }` (mesmo shape das outras actions); falha devolve `failure(message, true)`.
- Tipos/mensagens novos: `GoogleCalendarPickerOption`, `GoogleCalendarListActionResult = { ok: true; calendars } | { ok: false; message }`, `GOOGLE_CALENDAR_PRIMARY_MANAGER_ONLY_MESSAGE`, `GOOGLE_CALENDAR_PICKER_NOT_CONNECTED_MESSAGE`, `GOOGLE_CALENDAR_PICKER_NOT_LISTED_MESSAGE`, `GOOGLE_CALENDAR_PICKER_LIST_FAILED_MESSAGE`.
- **`buildGoogleCalendarAddLink`** (`src/lib/googleCalendarLink.ts`): `cid=${encodeURIComponent(calendarId)}` (literal da intenção); `buildGoogleCalendarWebcalUrl` e `buildGoogleCalendarPublicIcalUrl` permanecem exportados/intocados (Apple/Outlook). Atualizar o doc-comment do módulo (o `cid` não é mais a URL webcal).
- **Migration:** **nenhuma** — `payload-types.ts` intocado. Débito S3 (constraint singleton) adiado de novo (D3).
**UI (Impeccable B — encaixe na agenda; shell/dialog existentes)**
- **`GoogleCalendarPickerDialog.tsx`** (novo, `src/components/campaign/activity/`): Dialog desktop / Drawer mobile com o mesmo chrome do `GoogleCalendarSyncDialog` (header/scroll-body/footer). Props `{ open, onOpenChange, currentCalendarId, onListCalendars, onChooseCalendar }`. Estados `loading | error | empty | ready` com "Tentar de novo"; lista de opções com `summary`, marca "em uso" quando `id === currentCalendarId` e hint "principal da conta" quando `primary`; seleção local; rodapé "Cancelar" / "Escolher calendário" (desabilitado sem seleção, sem mudança ou busy).
- **`GoogleCalendarSyncDialog.tsx`**: prop nova `onOpenPicker: () => void`; no bloco `connected` (manager) botão "Escolher calendário principal" (ou "Trocar calendário principal" quando `state.calendarId`); non-manager vê a copy "O calendário principal da campanha é escolhido por candidato ou coordenação." (substitui "escolhido na configuração do Painel"); o `content` de `status === 'not-configured' && connection === 'connected'` passa a apontar para o botão (manager) / informar a escolha do núcleo (non-manager); bloco manual: input vira `buildGoogleCalendarPublicIcalUrl(state.calendarId)` (label "URL pública do calendário (Por URL, Apple Calendar e Outlook)") + âncora one-click "Adicionar ao meu Google Calendar" (`state.addLink`); instruções "Por URL" passam a casar com o input.
- **`AgendaGoogleSyncChrome.tsx`**: props novas `onListCalendars`, `onChooseCalendar`; estado `pickerOpen`; `openPicker` fecha o diálogo do espelho e abre o picker (overlays não empilham — ver D5), `onOpenChange(false)` do picker reabre o do espelho; `handleChooseCalendar` chama a action e `setState(result)` no sucesso; registra `SetCampaignHeaderAction id="google-calendar-add"` com a âncora one-click quando `state.addLink` existe (desktop com rótulo `hidden md:inline-flex`, mobile ícone `md:hidden` com `aria-label`/`title` "Adicionar ao meu Google Calendar"); pill e auto-retry intocados; FAB continua abrindo o diálogo do espelho.
- **`agenda/page.tsx`**: injeta as duas actions novas no chrome (`listGoogleCalendars`, `chooseGoogleCalendar`) junto das 5 atuais.
- **`scripts/lib/e2e-affected-manifest.mjs`**: adicionar `src/lib/googleCalendarLink.ts` e `src/app/(campaign)/campanha/actions/googleCalendarSync.ts` à entry C149 do domínio → `campaignAgendaGoogleSync`.
### Dados → forma
Não se aplica como apresentação de dado do Teqo (nenhuma leitura nova; a intenção adiou a forma). O único dado apresentado é a lista viva da conta Google, com shape mínimo `{ id, summary, primary }` e "em uso" derivado de `state.calendarId` — sem persistência. Forma escolhida: lista de opções (radio-like) com o calendário atual marcado; **rejeitadas:** select/combobox (esconde o contexto do "em uso" e o estado vazio), armazenar `summary` (D3), lista cacheada (D1).
## Decisões de engenharia (decisão + por quê + rejeitadas; só as caras de reverter)
1. **Listagem como método novo do client, OAuth-only na borda (D1).** `listCalendars()` entra na superfície do `GoogleCalendarClient` (transporte fino) e a exigência de OAuth fica no utility (`auth.kind !== 'oauth'` → `not-connected`). Params `minAccessRole=writer` + `showHidden=true` + paginação + filtro `deleted`. **Opções:** A) método no client + enforcement no utility | B) método restrito ao branch OAuth do tipo union | C) listar via service account. **Recomendação: A** — o client já é agnóstico de auth (SA/OAuth) e a autorização é concern do domínio; B bifurca o tipo sem ganho; C não enxerga os calendários compartilhados (a `calendarList` do SA só contém os dele). **Rejeitadas:** `showHidden=false` (o default — o calendário criado pela operação pode estar desmarcado no Google e sumir do picker, justamente o que o usuário quer escolher); cache da lista/summary na row (migration + drift, D3); `syncToken` incremental (complexidade sem ganho para uma lista de dezenas de itens).
2. **Escrita do `calendarId`: action de manager + utility system write com validação viva (D2).** `chooseGoogleCalendar` → `setCampaignPrimaryCalendarId` com `overrideAccess: true`, validando que o id está na lista viva (`minAccessRole=writer`) da conta conectada. **Opções:** A) action + utility com bypass | B) abrir `canSetGoogleCalendarSyncConfigField` a `isCampaignUnrestricted` (hipótese da intenção) | C) novo field access por papel. **Recomendação: A** — a superfície REST do `campaignUser` nunca escreve id arbitrário; a validação de pertencimento roda server-side e o write segue o padrão C149; o admin continua podendo configurar direto no Painel (escape hatch). **Rejeitadas:** B porque field access não valida valor nem roda o record de auth error (e abriria `calendarId` cru ao REST); C porque fragmenta o enforcement sem cobrir a validação. **Divergência da intenção registrada:** o outcome (escolher sem admin) é preservado; o caminho é outro.
3. **Sem migration; lista viva (D3).** Nenhum campo novo; o picker marca "em uso" por `state.calendarId`. **Opções:** A) não armazenar | B) `calendarSummary` na row. **Recomendação: A** — zero schema e zero drift. **Rejeitadas:** B (migration cosmética + summary desatualizado quando o calendário é renomeado no Google). **S3 (constraint singleton):** adiado de novo; o C150 não cria rows (só atualiza a row conectada), então o risco de twins segue teórico — gatilho de revisitação: qualquer caminho novo que crie row ou twins observados em prod; sem coluna natural de singleton, a constraint exigiria migration hand-written.
4. **Erro de auth na listagem grava o estado de conexão (D4).** `GoogleCalendarAuthError` → `recordGoogleCalendarOAuthError` + falha `reason: 'auth-error'`. **Opções:** A) gravar só `invalid_grant` | B) não gravar | C) gravar qualquer erro. **Recomendação: A** — mesma classificação do motor (C149 D4): `invalid_grant` é reconectável e o card deriva `error`/Reconectar; o picker é outro consumidor da mesma credencial. **Rejeitadas:** B (card diria "Conectado" enquanto o picker falha — estado desonesto); C (`invalid_client`/5xx não se consertam reconectando). Residual aceito: o badge do card atualiza no próximo read de view; a mensagem do picker já instrui "Reconecte a conta".
5. **Picker como diálogo próprio; chrome dono dos dois; sem empilhar overlays (D5).** Novo `GoogleCalendarPickerDialog` (Dialog/Drawer, mesmo chrome), aberto a partir do card de conexão para manager com `connection === 'connected'`. O chrome fecha o diálogo do espelho ao abrir o picker e o reabre quando o picker fecha — um overlay por vez (Radix/vaul aninhados têm scroll-lock/focus frágeis no mobile). **Opções:** A) diálogo próprio com troca de overlay | B) lista expansível dentro do `GoogleCalendarSyncDialog` | C) rota/página nova. **Recomendação: A** — o picker tem ciclo próprio (loading/erro/vazio/retry) e o diálogo do espelho já é denso; o chrome já é dono do estado (padrão C148). **Rejeitadas:** B (duas máquinas de estado num modal cheio); C (cerimônia e rota nova sem URL pública a proteger); empilhar os dois overlays (risco de focus/scroll no mobile).
6. **One-click com `cid=<calendarId>` + reconciliação do bloco manual (D6).** `buildGoogleCalendarAddLink` passa a `https://calendar.google.com/calendar/r?cid=${encodeURIComponent(calendarId)}`; header ganha a âncora (desktop com rótulo, mobile ícone + `aria-label`); o input do diálogo passa a `buildGoogleCalendarPublicIcalUrl(calendarId)` (o "Por URL" e Apple/Outlook assinam a URL iCal pública) + âncora one-click dentro do diálogo; `CalendarFeedDialog` (recorte ICS) intocado. **Opções:** A) literal da intenção + input iCal público | B) manter webcal no `cid` | C) dois inputs. **Recomendação: A** — o fluxo de adicionar calendário do Google interpreta `cid` como id do calendário; as instruções "Por URL" atuais já estavam desalinhadas com o `cid` webcal (o input antigo não era a URL iCal pública); Apple/Outlook continuam servidos pela URL iCal. **Rejeitadas:** B (infiel ao literal); C (mais chrome que o menor ajuste); remover o bloco manual (quebraria Apple/Outlook e o "copie e envie"); um-clique para o recorte ICS (anti-goal da intenção).
7. **E2E sem interceptar fetch do servidor (D7 — emenda ao bullet do explorador).** `page.route` intercepta só o tráfego do browser; a listagem roda na server action (processo Next). **Opções:** A) e2e cobre contratos do browser (href do one-click, ausência para advisor, ícone mobile, botão do manager) + caminho feliz lista/escolhe no int com stub | B) env de base URL do Google para teste | C) semear refresh token real e chamar o Google. **Recomendação: A** — determinístico e sem rede (mesma doutrina C114/C149); o int prova a validação viva e o D7 com `listEvents(novoId)`. **Rejeitadas:** B (superfície de produção — base URL do Google por env — existindo só por teste); C (flake de rede/credencial dummy no CI).
8. **Seam de teste por injeção de client nas utilities (D8).** `listGoogleCalendarPickerOptions`/`setCampaignPrimaryCalendarId` aceitam `options.client?: GoogleCalendarClient` (precedente `runCampaignCalendarSync.options.client`); o int novo mocka `@/utilities/googleCalendarClient` (stub com `listCalendars`/`listEvents` gravando o `calendarId`) e `campaignActionContext`, serializado por `serializeGoogleCalendarSyncSpec()`. **Opções:** A) injeção de client | B) mock global de `fetch` | C) só o fake credential (falha no JWT). **Recomendação: A** — prova direta da rejeição de id fora da lista e da reconciliação no novo calendário; C não prova qual calendário foi usado. **Rejeitadas:** B (o action não injeta `fetchImpl`; mockar `fetch` global vaza para o resto do spec).
9. **Manifest cobre o literal e as actions (D9).** Adicionar `src/lib/googleCalendarLink.ts` e `src/app/(campaign)/campanha/actions/googleCalendarSync.ts` à entry C149 → `campaignAgendaGoogleSync`. **Rejeitada:** confiar no smoke fallback (o literal do link e as actions não acordariam o spec da agenda).
## Fases verificáveis
1. **Tracer/servidor (~50%, ≈0,8–1 dia)**
- `listCalendars` no client + unit em `tests/unit/googleCalendarClient.unit.spec.ts` (params `minAccessRole=writer`/`showHidden=true`, paginação por `nextPageToken`, filtro `deleted`, fallback do summary, retry de 401, `invalid_grant` → `GoogleCalendarAuthError`).
- Utilities `listGoogleCalendarPickerOptions`/`setCampaignPrimaryCalendarId` + actions `listGoogleCalendars`/`chooseGoogleCalendar` + tipos/mensagens.
- Int novo `tests/int/googleCalendarPrimaryCalendarAction.int.spec.ts` (mocks do client e do contexto + advisory lock): advisor recusado; lista para coordinator; `invalid_grant` grava `oauthErrorAt/oauthError`; id fora da lista rejeitado sem write; id listado escreve `calendarId` e o hook D7 reconcilia no novo (`listEvents` chamado com o novo id); no-op quando já é o atual.
- Gate: `pnpm gate:fast`.
2. **UI + links (~35%, ≈0,6 dia)**
- `buildGoogleCalendarAddLink` literal + pins (`tests/unit/googleCalendarLink.unit.spec.ts`, e2e do input).
- `GoogleCalendarPickerDialog` novo + `tests/unit/googleCalendarPickerDialog.unit.spec.tsx` (loading/erro/vazio/lista, "em uso", confirmar desabilitado sem mudança, escolha chama o callback).
- `GoogleCalendarSyncDialog` (botão/copy/iCal público/âncora) + `tests/unit/googleCalendarSyncDialog.unit.spec.tsx`; `AgendaGoogleSyncChrome` (estado dos dois diálogos + header add) + `tests/unit/agendaGoogleSyncChrome.unit.spec.tsx`; `page.tsx` injeta as actions.
- Gate: `pnpm gate:fast`.
3. **E2E + manifest + gates (~15%, ≈0,3 dia)**
- `tests/e2e/campaignAgendaGoogleSync.e2e.spec.ts`: href do one-click com `cid=<calendarId>` e `target=_blank`; advisor sem o botão + copy; manager com "Trocar calendário principal"; mobile com o ícone (`aria-label`); input do diálogo com a URL iCal pública.
- Manifest (D9). Gate: `pnpm gate:fast`; `pnpm test:e2e:affected` (deve incluir `campaignAgendaGoogleSync`); `pnpm push`.
**Cortes se o appetite estourar (nesta ordem):** (1) hint "principal da conta" e polish do picker; (2) âncora one-click dentro do diálogo (mantém header + input iCal); (3) asserção mobile no e2e (unit cobre o ícone); (4) `fields` no request da listagem. **Nunca cortar:** a validação do id na lista viva (D2), o record do auth error (D4) e o int do D7.
## Rabbit holes / Não escopo (engenharia)
- **Backfill/limpeza do calendário abandonado:** trocar `calendarId` reusa a reconciliação D7 e o calendário antigo fica congelado (design C114 D7, provado em `tests/int/googleCalendarSync.int.spec.ts:396-418`); nenhum retro-cleanup.
- **Limpar `calendarId` no disconnect:** C149 intocado; gatilho de revisitação — suporte observar "reconectei outra conta e o espelho pausou"; a UI do picker já lida (nenhum item "em uso") e o manager reescolhe.
- **Estado de confirmação pós-one-click** ("Agenda adicionada"): o Google não chama de volta; a cena do rascunho não é implementável.
- **One-click para o recorte ICS / feed externo:** anti-goal (cid infiel); `CalendarFeedDialog` fica como está.
- **OAuth por pessoa, N calendários, calendário por assessor:** anti-goals C114/intenção.
- **Cache da lista/summary, `syncToken` incremental:** D1/D3.
- **Constraint singleton (S3):** adiada de novo (D3), com gatilho.
- **Env de base URL do Google para teste:** D7.
- **Mexer no motor C114/C115** (snapshot pino, canal push, janela, locks) e no `GoogleCalendarSyncDialog` além dos blocos descritos: fora.
- **Rate limiting na listagem:** manager-only e aberta por gesto; sem superfície nova de abuso.
## Riscos e mitigação
- **Listagem pode segurar o diálogo (token + N páginas, cada hop 15s):** o picker tem estado de loading e "Tentar de novo"; `REQUEST_TIMEOUT_MS` existente limita cada hop; ação de manager, sem caminho crítico da agenda.
- **Calendário some entre a listagem e a escolha:** `setCampaignPrimaryCalendarId` re-lista e rejeita (`not-listed`); a mensagem pede atualizar a lista.
- **`invalid_grant` no meio do fluxo:** a listagem grava o erro de conexão; o picker mostra a mensagem e o card deriva `error`/Reconectar no próximo read (residual documentado em D4).
- **Crowding do header desktop** (pill + rótulo longo + import + IA + sino): rótulo com `shrink-0`/`whitespace-nowrap`; encurtar a copy ou esconder o rótulo em `md` (cheap polish) se a inspeção visual acusar.
- **Overlays empilhados no mobile:** evitado por desenho (D5) — o picker substitui o diálogo do espelho enquanto aberto.
- **E2E da agenda é serial e compartilha a row singleton:** os seeds novos usam `lastSuccessAt` futuro (imune a `lastErrorAt` de specs paralelas) e nunca disparam action contra o Google; sem refresh token real nos seeds que abrem o picker (o botão não é clicado no e2e).
- **Sem rede no e2e:** o caminho feliz lista/escolhe é int com stub; a prova de produção fica no smoke manual pós-deploy (mesma doutrina C149).
- **`buildGoogleCalendarPublicIcalUrl` passa a ser usado** (era export não consumido em `src`): sem impacto; knip já tolerava.
- **`unmapped-risk` no CI:** as mudanças tocam `src/utilities/access`? Não — o access fica intocado (D2); o manifest entra no mesmo PR.
## Qualidade da decisão
**Auto-avaliação: 4/5** — todas as decisões caras (listagem, escrita do `calendarId`, schema, auth error, UI, literal do link, estratégia de teste) têm recomendação e rejeitadas ancoradas em achados concretos (union de auth C149, precedente de system write, hook D7, pins de teste, manifest); o appetite cabe (~1,7–1,9 dia) e o depth check reusa client/utility/action/dialog/hook existentes, criando só o componente de picker (ciclo de estados próprio). Perde 1 ponto porque o caminho feliz da listagem real (shape do Google, `showHidden`, paginação) só é provado por unit/int com stub — sem e2e de rede (D7) —, então a verificação contra o Google real fica no smoke pós-deploy.
## Execução — desvios e decisões emergentes (2026-09-12)
- **`buildGoogleCalendarWebcalUrl` removido:** o plano previa mantê-la para Apple/Outlook, mas o diálogo serve esse caminho com a URL iCal pública (HTTPS); o export ficou morto e saiu no simplify.
- **Validação do id e leitura única:** `resolveGoogleCalendarPickerClient` dobrado em `loadWritableGoogleCalendars`, que recebe o doc já carregado — a escolha faz uma leitura da row, não duas.
- **Picker sem roles ARIA de radio:** a lista usa botões com `aria-pressed` (roving tabindex/owned-children não valem a cerimônia); a seleção fica desabilitada durante a escolha e há guarda de sessão (`sessionRef`) contra corrida de close/reopen.
- **Catch explícito no picker:** listagem/escolha rejeitadas (sessão expirada/serialização) caem em erro com "Tentar de novo" — nunca spinner infinito.
## Débitos (triage do /simplify)
| ID | Achado | Score | Tipo | Destino |
| --- | -------------------------------------------------------------- | ----- | ------------- | ------------------------------------------------------------------------------------------------------------- |
| S1 | 3ª cópia do chrome responsivo Dialog/Drawer (Picker/Sync/Feed) | 3 | cheap_polish | Registrado: **C156** (#965) — `docs/plans/escala-dry-pos-c150.md` (o gatilho do C148 disparou com o 4º modal) |
| S2 | Copy "Adicionar ao meu Google Calendar" duplicada | 2 | cheap_polish | Absorvido como F3 cortável do C156 |
| S3 | Máquinas de estado semelhantes Picker/Sync | 2 | defer_trigger | Defer no plano do C156: 3º diálogo com a mesma máquina busy/erro/ação |
- **Já resolvido no simplify (não reabrir):** guarda de sessão/catch do picker; `CalendarOption`; envelope `applyState` no chrome; `addLink` derivado no diálogo; webcal morto; leitura única da row; flag `changed` removida; roles ARIA.
- **Explicitamente fora:** copy única fora do C156; máquinas de estado unificadas; shell do `ActivityOverlay`.
## Aceite de engenharia
- [ ] Aceite de produto da intenção ainda coberto: candidato/coordenador escolhe o calendário principal na agenda; create/edit espelham nele; staff adiciona a agenda ao Google com um clique; recorte ICS intocado; admin do Payload segue escape hatch.
- [ ] Invariantes AGENTS/engineering-standards: `leader` sem agenda; escrita system com `overrideAccess` justificado e papel checado na action; identificadores em inglês, copy pt-BR; sem migration (nenhuma antiga editada).
- [ ] `calendarId` só é escrito após validação de que o id está na lista viva da conta conectada (`minAccessRole=writer`); `canSetGoogleCalendarSyncConfigField` segue admin-only.
- [ ] Trocar o calendário dispara a reconciliação D7 no novo calendário (int prova `listEvents(novoId)`); nenhum backfill/limpeza no calendário antigo.
- [ ] `GoogleCalendarAuthError` na listagem/escolha grava `oauthErrorAt/oauthError` e o card deriva `error`/Reconectar; `invalid_client`/5xx não sujam a conexão.
- [ ] `buildGoogleCalendarAddLink` = `cid=<calendarId URL-encoded>`; âncora de header (desktop com rótulo, mobile ícone + `aria-label`) visível só com `addLink`; diálogo mantém URL iCal pública para "Por URL"/Apple/Outlook.
- [ ] Testes previstos verdes: unit do client/link/picker/sync dialog/chrome; int novo das actions (papel, id fora da lista, write + D7); e2e `campaignAgendaGoogleSync` estendido (href, advisor, manager, mobile).
- [ ] `pnpm gate:fast` verde; `pnpm test:e2e:affected` inclui `campaignAgendaGoogleSync` (manifest cobre `googleCalendarLink.ts` e `actions/googleCalendarSync.ts`) e passa local; `pnpm push`.

View file

@ -0,0 +1,116 @@
# Impl: Atividade: marcar evento como público (base para exposição no site)
Status: aprovado
Atualizado em: 2026-09-12
Issue: #936
Intenção: docs/plans/c151-atividade-evento-publico.md
Appetite restante: herdado (~0,5 dia eng) — cabe sem corte.
## Leitura da intenção
- **Outcome:** o staff marca/desmarca "Evento público" no modal de atividade; a marcação é
durável, volta correta ao reabrir e fica consultável — sem nenhuma tela mudar de comportamento.
- **O que NÃO negociar:** exposição pública é item futuro (PUB), nada no `(frontend)`; sem filtro/badge
na lista; sem collection paralela; `leader` segue lockdown (não vê o campo); o espelho do Google
(C114) não é influenciado em v1.
- **O que reavaliar:** a hipótese do plano de intenção ("a marcação vive na atividade existente")
confirma-se — nenhuma surpresa de acoplamento na exploração.
## Abordagem recomendada
```mermaid
flowchart LR
O[ActivityOverlay<br/>checkbox publicEvent] -->|FormData| P[parseSharedActivityFormData]
P --> Z[activityCreate/UpdateSchema]
Z --> A[create/updateActivityRecord]
A --> C[collection activity<br/>publicEvent checkbox]
C -->|migration| DB[(activity.public_event)]
A -.nao inclui.-> G[sync Google C114]
```
**Opções consideradas:** A) campo boolean na `activity` existente (draft) | B) collection/entidade
"evento público" separada | C) global/config paralela.
**Recomendação:** A — a intenção fixa a flag na atividade existente; é um checkbox de negócio, indexado,
sem access especial (quem edita a atividade marca).
**Rejeitadas:** B porque duplica cadastro e cria divergência de dados (anti-goal explícito da intenção);
C porque não há escopo por item — a flag é por atividade.
### Componentes / mudanças
- **`publicEvent`** (`src/collections/Activity.ts`): `type: 'checkbox'`, `label: 'Evento público'`,
`defaultValue: false`, `index: true`, `admin.description` "Quando marcado, este evento poderá ser
publicado no site do candidato (futuro)." — espelha `deputyPresent`/`allDay` (sem `access` de field:
qualquer staff com linha pode marcar).
- **`activityStaffFieldSnapshot`** (`src/collections/Activity.ts`): incluir
`publicEvent: Boolean(doc.publicEvent)` no snapshot do guard de liderança — mantém a defesa em
profundidade (liderança, se algum dia alcançar o write path, não marca campo de staff). Access
`canReadActivity`/`canUpdateActivity` já negam `leader`; isto é só cinto de segurança barato.
- **`src/lib/schemas/activity.ts`**: adicionar `publicEvent: z.boolean().optional()` em
`activityFieldsSchema` (herdado por create/update `.partial()`).
- **`src/utilities/activityFormData.ts`**: `publicEvent: checkboxFormValue(formData, 'publicEvent')`
em `parseSharedActivityFormData` — sem isso o checkbox é silenciosamente descartado no submit.
- **`src/utilities/activityViewModels.ts`**: `ActivityFormViewModel.publicEvent: boolean` +
`activityFormSelect.publicEvent` + `toActivityFormViewModel`. **Não** tocar em
agenda/list/detail selects/view models (nada de badge/coluna/consumo novo).
- **`src/components/campaign/activity/ActivityOverlay.tsx`**: checkbox "Evento público" na
`scheduleSection`, logo após "Todo o dia" (posição do rascunho UI aprovado), `name="publicEvent"`,
`defaultChecked={isEdit ? editDraft?.publicEvent : false}`, `aria-label="Evento público"`.
- **Migration:** `pnpm migrate:create add_activity_public_event` — copia exata do precedente
`20260810_010844_add_activity_all_day` (`ADD COLUMN "public_event" boolean DEFAULT false` +
índice btree `activity_public_event_idx`). Depois `pnpm generate:types` (`src/payload-types.ts`).
- **Google Calendar (C114):** `SYNC_RELEVANT_ACTIVITY_FIELDS` **não** recebe `publicEvent` — decisão
v1 da intenção; editar só a flag não re-dispara sync nem carimba `lastMirroredChangeAt`.
- **UI:** Impeccable B (encaixe no modal). Reusa `Checkbox` + `Field` do próprio overlay; sem seção
nova, sem shell novo. Shape já aprovado no rascunho `c151-atividade-evento-publico-ui-draft.html`.
### Dados → forma (se aplicável)
- Não aplicável: nenhuma superfície de dados neste item (a intenção já decidiu "não apresentar dados").
## Fases verificáveis
1. **Tracer schema+server** — campo + migration + zod + parser + select/view model do form;
int test prova persistência e reabertura (`loadActivityEditDraftRecord` devolve `publicEvent`).
2. **UI** — checkbox no `scheduleSection`; unit test do overlay (render no create e no edit, submit
manda `publicEvent=on` só quando marcado).
3. **Gates** — `pnpm gate:fast`; `pnpm test` (unit+int) na entrega; push via `pnpm push`.
## Rabbit holes / Não escopo (engenharia)
- Expor no site público, agenda pública, SEO ou share kit (item PUB futuro).
- Badge/coluna/filtro na lista de atividades, na agenda ou no detalhe.
- Ligar a flag ao espelho do Google (C114) — decidido fora em v1.
- Tornar `publicEvent` system field (`canSetActivitySystemField`) ou restricted access — não pedido.
- Marcação em lote / spreadsheet mode.
## Riscos e mitigação
- **Risco:** checkbox silenciosamente descartado no submit se o parser/zod não acompanhar. **Mitigação:**
unit test do overlay + int test de parse/persistência.
- **Risco:** a flag vazar para abas/visões como comportamento novo. **Mitigação:** mudanças restritas a
form select/view model; nenhum agenda/list/detail select alterado.
- **Risco:** migration sem regenerar tipos → erro de `tsc`. **Mitigação:** `migrate:create` +
`generate:types` + `pnpm typecheck` no gate.
## Débitos triados (simplify)
- **Já resolvido:** o `migrate:create` arrastou drift de `supporter_import_batch.actor_id`
(snapshot stale dos hand-written 20260824) com `down` rollback-inseguro — removido, a migration
só mexe em `public_event`; changelog da entrega criado; racional C126 do `farFuture` no int;
status do plano finalizado.
- **Descartado (YAGNI):** índice parcial em vez de btree pleno para um boolean de 2 valores — sem
medição que justifique; a intenção pediu "indexado" e o precedente `all_day` usa btree pleno.
- **Defer (gatilho):** extrair um `OverlayCheckboxField` local para os três checkboxes idênticos do
overlay (`deputyPresent`/`allDay`/`publicEvent`) — só quando um 4º checkbox ou mudança real de UX
no bloco justificar.
- **Defer (gatilho):** teste de regressão pinando `publicEvent` fora de `SYNC_RELEVANT_ACTIVITY_FIELDS`
e dos selects de agenda/lista — hoje a type honesty (view models sem o campo) cobre agenda/lista/
detalhe; adicionar o pin quando o item PUB ligar a flag a um consumidor.
## Aceite de engenharia
- [x] Aceite de produto da intenção ainda coberto (marca/desmarca, durável, reabre correto, nada muda)
- [x] Invariantes AGENTS/engineering-standards (leader lockdown, copy pt-BR/identificadores EN)
- [x] Testes de domínio previstos (unit do overlay + int de persistência/parse + e2e de roundtrip)

View file

@ -0,0 +1,176 @@
# Impl: Cards personalizados: ajustes de fidelidade e experiência (S14)
Status: em execução
Atualizado em: 2026-09-12
Issue: #959
Intenção: docs/plans/cards-personalizados-ajustes.md
Appetite restante: herdado — ~1–1,5 dia eng (3 fases somam ≤1,5 dia; sem migration)
## Leitura da intenção
- **Outcome:** o visitante vê a seção `Mostre que você está com Solla` na home, toca num dos três modelos e o MESMO compositor do `/cards` abre ali mesmo (modal no desktop, drawer no mobile), sem navegar; o nome no card gerado alinha à esquerda com a linha `SOU` (borda x≈213, em 1 e 2 linhas, sem corte), o tile do modelo de nome mostra o resultado real da string, a moldura do modal encosta no conteúdo, a ajuda fica legível e a seção passa a ficar imediatamente antes da captura de novidades — sem conta e sem que nome/foto saiam do aparelho.
- **O que NÃO negociar:**
- **Um único editor.** A home abre a ilha `CardsStudio`/`CardComposer` existente; nenhum segundo compositor, nenhum estado duplicado (anti-goal "dois fluxos de criação" da intenção).
- **100% client-side e sem PII em rede/analytics.** Nome/foto processados no aparelho; sem upload, persistência, collection/global/migration/Consent novo.
- **`/cards` e o deep-link `/cards?model=<id>` intactos** como rota canônica (o gate manteve a rota; só o comportamento da home muda).
- **Arte-mestre intocada** e geometria do mestre preservada: borda esquerda x≈213 (canvas 1080), tinta ≤714px, cap 106, Brexter 700, fill `#ffec01`.
- **Copy literais** da intenção preservados (`Mostre que você está com Solla`, `SEU NOME`, `Arraste para posicionar e use os controles para aproximar ou ajustar.`).
- **As demais seções da home não mudam** — e o fit do nome (tamanho/quebra atuais) permanece; a entrega só muda o alinhamento.
- **O que reavaliar (hipóteses da intenção / rascunho):**
- **Ordem literal do rascunho.** `… → Acompanhe de perto → cards → Receba as novidades` não existe no código: "Acompanhe de perto" é `CampaignContentSection` (`data-home-section="contents"`) e está no começo da home (`page.tsx:142`), antes de problem/flags/story. O aceite operativo é "cards imediatamente antes de Receba as novidades" → mover `<CampaignCardsSection />` para entre `CampaignStorySection` e `CampaignNewsletterSection`. **Divergência registrada para o gate humano** (decisão 2).
- **Tile em HTML com Brexter.** Não se sustenta: `SEU NOME` tem avanço de 6,7em e, no cap ideal (corpo 151,43px), mede ~1014px — não cabe em `maxInkWidth` 714; o fit real encolhe a string (corpo 106 → cap ~74). Um placeholder HTML com `font-size` calibrado valeria só para essa string e mentiria a geometria.
- **Home RSC com tiles-link.** Deixa de valer: a home renderiza a ilha client e os tiles viram botões; a variante `link` do `CardModelGallery` e o helper `cardModelHref` ficam sem call site.
## Abordagem recomendada
```mermaid
flowchart LR
HOME["Home · CampaignCardsSection (RSC)<br/>Brexter variable · sem CTA"] --> STUDIO["CardsStudio (ilha client única)"]
ROUTE["/cards · /cards?model=id (inalterado)"] --> STUDIO
STUDIO --> GALLERY["CardModelGallery (select)<br/>3 tiles-botão"]
GALLERY --> TILE["CardModelTile<br/>next/image + CardNameTileName"]
GALLERY -->|"toque"| SHELL{"viewport abaixo de 768px?"}
SHELL -->|"não"| DIALOG["Dialog · p-0 sm:p-0"]
SHELL -->|"sim"| DRAWER["Drawer · sem vão base"]
DIALOG --> COMPOSER["CardComposer (editor único)"]
DRAWER --> COMPOSER
COMPOSER --> FIT["cardNameFit (inalterado)"]
FIT --> DRAW["drawCardName · textAlign='left' · x=leftX (213)"]
DRAW --> PREVIEW["prévia no canvas"]
PREVIEW --> PNG["Baixar PNG no aparelho"]
TILE -.->|"mesmo fit + drawCardName"| DRAW
COPY["CARD_NAME_TILE_PLACEHOLDER = 'SEU NOME'"] -.-> TILE
TOKEN["--muted-foreground = --campaign-muted"] -.-> DIALOG
```
**Opções consideradas:** A) ajustar no dono — a home renderiza a ilha existente, a geometria do nome vira `leftX` + `drawCardName` reusado pelo canvas do tile, o contraste vira token do tema e o vão é corrigido no call site do dialog | B) criar superfície/editor próprios na home | C) manter o CTA e o link para `/cards`, ajustando só o resto.
**Recomendação:** A — um único editor (estado e comportamento idênticos), cada correção no módulo que já é dono do concern (renderer puro, token do tema, seção da home, call site do dialog) e o menor blast radius possível.
**Rejeitadas:** B porque é o rabbit hole "segundo editor" da intenção — dois estados divergem e qualquer ajuste futuro passa a valer em dobro; C porque contraria a decisão do gate de 2026-09-12 (o modelo abre o compositor ali mesmo e o CTA `Criar meu card` sai).
### Decisões de engenharia
1. **Home abre o mesmo compositor (ilha única; CTA removido).**
Opções: A) `CampaignCardsSection` continua RSC e renderiza a ilha client `CardsStudio` (`fontFamily={brexterBold.style.fontFamily}` + `brexterBold.variable` na section) e o CTA `Criar meu card` é removido | B) criar um compositor próprio na home (estado/shell novos) | C) manter o CTA e o link para `/cards` (status quo).
Recomendação: A — a home e `/cards` são o mesmo funil; a ilha já é dona de `selectedId`/`open`, das cascas `ui/dialog`/`ui/Drawer` e do editor único; `focusSelectedTile` já varre `[data-card-model-tile]` visível e funciona na home, então o retorno de foco ao fechar não muda.
Rejeitadas: B porque dois editores divergem (o rabbit hole "dois fluxos de criação" da intenção); C porque o gate decidiu que o modelo abre o compositor ali mesmo e que o CTA sai.
Consequências: a variante `link` do `CardModelGallery` e o helper `cardModelHref` ficam sem call site → **removidos no mesmo PR** (knip trata export morto como ERROR; só a home e um unit usavam); `Link` sai de `CampaignCardsSection`/`CardModelGallery`; o unit de `cardModelHref` sai junto. A rota `/cards` e o `?model=` permanecem intocados (a page segue passando `fontFamily` e sanitizando o param). O comentário S13 da seção é atualizado (posição e comportamento).
2. **Ordem da home — cards imediatamente antes da newsletter.**
Opções: A) mover `<CampaignCardsSection />` para entre `<CampaignStorySection />` e `<CampaignNewsletterSection … />` | B) mover também `CampaignContentSection` para colar em cards (satisfazer a ordem literal do rascunho) | C) manter no fim da página (depois da newsletter) e só trocar o gatilho.
Recomendação: A — satisfaz o aceite operativo (cards imediatamente antes da captura; a captura segue como último bloco de conversão) sem tocar nas demais seções.
Rejeitadas: B porque "as demais seções da home não mudam" é guardrail da intenção e mover "Acompanhe de perto" do topo para o fim é redesenho de home, fora do appetite; C porque contraria o gate e o aceite "antes de Receba as novidades".
> **Divergência para o gate humano:** o rascunho UI mostra "Acompanhe de perto" colado antes dos cards, mas no código real essa seção é `CampaignContentSection` e vive no começo da página; a ordem implementada é `… → story → cards → newsletter → rodapé`. Se o humano quiser a ordem literal do rascunho, mover `CampaignContentSection` é outro item (não este).
> Pins: o e2e deixa de exigir `cards = newsletter + 1` e passa a exigir `newsletter = cards + 1` **e** `cards = story + 1`.
3. **Alinhamento à esquerda — geometria no dado e desenho extraído.**
Opções: A) trocar `NAME_CARD_SLOT.centerX: 570` por `leftX: 213` e extrair de `renderNameCard` um `drawCardName(ctx, { fit, fontFamily, slot? })` puro que desenha SÓ o nome (1 e 2 linhas) com `textAlign='left'` em `slot.leftX`; `renderNameCard` passa a chamar `drawCardName` | B) manter `centerX` e derivar `leftX = centerX − maxInkWidth/2` no render | C) alinhar só a 1ª linha à esquerda e manter o bloco de 2 linhas centrado.
Recomendação: A — o dado do mestre é a borda (213 = 570 − 714/2, a borda esquerda do mestre), não o centro; `drawCardName` fica reusável pelo tile sem duplicar geometria.
Rejeitadas: B porque a borda vira derivada ambígua (se o fit/`maxInkWidth` mudar, a borda muda em silêncio); C porque o aceite exige borda esquerda nas duas linhas (o bloco de 2 linhas mantém a mesma lógica vertical atual, mas ambas as linhas partem de `leftX`).
Consequências: o fit NÃO muda (largura/quebra/min cap intactos em `cardNameFit`); `renderNameCard` = base → fit → `drawCardName`; `drawCardName` não desenha nada quando `!fit.ok` (nunca corta). O comentário do slot registra a borda esquerda x=213 e a tinta ≤714 (`[213..927]`).
4. **Tile fiel via o próprio renderizador (canvas transparente sobre o `next/image`).**
Opções: A) o tile do modelo de nome vira base `next/image` (como hoje) + overlay canvas client `CardNameTileName` que espera `ensureCardFont`, roda `fitCardName('SEU NOME', createCardMeasure(ctx, fontFamily))` e chama `drawCardName` | B) manter placeholder HTML com Brexter e `font-size` em cqw calibrado pelo cap ratio | C) canvas desenhando a base inteira no tile (sem `next/image`).
Recomendação: A — mesma geometria do resultado por construção (mesmo fit, mesmo slot, mesma cor), sem constantes de métrica de fonte no CSS e sem re-baixar a base (o canvas é transparente).
Rejeitadas: B porque exigiria codificar métricas da fonte (cap ratio/avanços) e replicar o fit no CSS — e o número em cqw só vale para `SEU NOME` (a string encolhe no fit real, então um cap fixo mentiria); C porque re-baixa 427KB no tile e perde o `next/image` otimizado/lazy.
Consequências: `fontFamily` desce `CardsStudio → CardModelGallery → CardModelTile`; `containerType`, `font-size: 11.5cqw`, `tracking-[-0.02em]` e `--font-exo2` saem do placeholder; o literal `SEU NOME` vira `CARD_NAME_TILE_PLACEHOLDER` em `cardCopy.ts`; o canvas é decorativo (`aria-hidden`, o botão já tem `aria-label`). **Consequência visual registrada:** `SEU NOME` aparece com cap ~74 (o corpo 106 que o fit escolhe para caber nos 714px), não com o cap 106 do exemplo `FULANO` do mestre — é o resultado real da string, que é o que o aceite pede. Se a fonte não carregar, o overlay fica vazio (nunca medir/desenhar com fallback, que mentiria a geometria).
5. **Vão do modal — corrigir no call site.**
Opções: A) `p-0 sm:p-0` no `className` do `DialogContent` em `CardsStudio.tsx` (precedente `PetitionSuccessDialog.tsx:46`) | B) mexer no `ui/dialog.tsx` base (remover/reordenar o `sm:p-8`) | C) compensar o padding no `CardComposer` com margens negativas.
Recomendação: A — o `sm:p-8` base sobrevive ao `p-0` do call site porque o twMerge só remove a variante sem breakpoint; `sm:p-0` vence e o vão some preservando borda fina e raio.
Rejeitadas: B porque atinge todos os dialogs do app (admin/campanha) que dependem de `p-6 sm:p-8` — fora do appetite; C porque é hack de layout que quebra se o padding base mudar.
Consequências: `DrawerContent` não tem padding base (nada a fazer no mobile); o `CardComposer` já traz `px-5` próprios no header/body/footer.
6. **Contraste da ajuda — token do tema, não band-aid.**
Opções: A) definir `--muted-foreground: var(--campaign-muted)` dentro de `[data-theme='campaign-site']` (`styles.css`) | B) className local `text-(--campaign-muted)` nos dois `DialogDescription`/`DrawerDescription` do `CardComposer` | C) criar um tema novo para o funil de cards.
Recomendação: A — o tema é claro (fundo branco) e hoje herda o `--muted-foreground` near-white do `:root` (pensado para o dark); `--campaign-muted: #6c615e` já existe no tema e tem ~6:1 sobre branco (≥4.5:1); conserta os dois shells de uma vez e qualquer uso futuro de `muted-foreground` no tema (o portal re-aplica `data-theme="campaign-site"`, então herda o token).
Rejeitadas: B porque é band-aid — deixa a raiz (o próximo `muted-foreground` no tema volta a ser ilegível); C porque é tema paralelo sem necessidade.
Verificação: grep não encontra outro `text-muted-foreground` no subtree `campaign-site` hoje → mudança sem regressão.
7. **Testes — atualizar o harness existente.**
Opções: A) atualizar os pins de `cardModels`/`cardRender`, adicionar o unit do `drawCardName` e reescrever o describe de cards no spec `frontend` (home nova + asserção de alinhamento por pixel), mantendo `/cards`/`?model=`/download | B) criar um spec e2e novo + `testMatch` + manifest.
Recomendação: A — o projeto `frontend` já coleta o describe e o manifest já mapeia `src/components/cards`/`src/lib/card` → `frontend` (S13); menor blast radius, mesma cobertura de fluxo.
Rejeitadas: B porque muda config + manifest + pins por nenhum ganho (é o mesmo funil).
Cobertura unit: `cardModels` pina `leftX: 213` (e perde o teste de `cardModelHref`); `cardRender` pina `x = leftX`/`textAlign = 'left'` e ganha um `describe('drawCardName')` — (a) desenha só texto (nenhum `drawImage`), na borda; (b) 2 linhas, ambas em `leftX`, baselines dentro da banda; (c) `fit.ok === false` não desenha; `cardNameFit` fica intocado.
Cobertura e2e (describe renomeado para `Cards personalizados (S14)`): home com `newsletter = cards + 1` e `cards = story + 1`; 3 tiles-botão e ausência do link `Criar meu card`; clique em `Moldura quadrada` abre o diálogo **sem navegar** (URL segue `/`) e `Escape` fecha devolvendo o foco ao tile; fluxo de `/cards`/`?model=` e download PNG mantidos; asserção de alinhamento no canvas do nome (menor x com pixel amarelo na faixa y[430..535] em ~[205..240]; centralizado para `João` começaria >280) e, se barato, a mesma varredura no canvas do tile (`section#cards canvas`).
Manifest/prewarm: **sem mudança** (prefixos `src/components/cards`/`src/lib/card` e `/cards` no prewarm já existem).
8. **Changelog e higiene.**
- `docs/changelog/2026-09-12-s14-cards-personalizados-ajustes.md` (OPS85): entrada curta do funil (home abre o compositor, alinhamento, tile fiel, vão, contraste, ordem).
- Sem migration; sem Payload/Consent; 100% client-side; nenhuma PII em rede.
- `codebase-map.mdc` não precisa mudar (a linha de `src/components/cards/` já cobre o estúdio e não há módulo movido).
### Componentes / mudanças
- **`src/lib/cardModels.ts`** (editar): `NAME_CARD_SLOT.centerX: 570` → `leftX: 213`; comentário do mestre atualizado (borda esquerda, tinta ≤714 em `[213..927]`); remover `cardModelHref` (sem call site).
- **`src/lib/cardRender.ts`** (editar): extrair `drawCardName(ctx, { fit, fontFamily, slot? })` puro (só o nome; `textAlign='left'`; 1 linha na baseline `capTop + capHeight`; 2 linhas no mesmo cálculo vertical de hoje, ambas em `slot.leftX`; `!fit.ok` → nada); `renderNameCard` passa a delegar o desenho.
- **`src/components/cards/cardCopy.ts`** (editar): `CARD_NAME_TILE_PLACEHOLDER = 'SEU NOME'`.
- **`src/components/cards/CardNameTileName.tsx`** (novo, client): canvas transparente `absolute inset-0 h-full w-full` (dimensões intrínsecas do modelo); efeito com `ensureCardFont(fontFamily)` → `fitCardName(CARD_NAME_TILE_PLACEHOLDER, createCardMeasure(ctx, fontFamily))` → `drawCardName`; cleanup cancela; `aria-hidden`.
- **`src/components/cards/CardModelTile.tsx`** (editar): remover o placeholder HTML (e `containerType`/`11.5cqw`/`tracking`/`--font-exo2`); renderizar `<CardNameTileName model={model} fontFamily={fontFamily} />` sobre o `next/image`; nova prop `fontFamily: string`.
- **`src/components/cards/CardModelGallery.tsx`** (editar): select-only — remover `variant`/`Link`/`cardModelHref`; manter `selectedId`/`onSelect`, os dois tracks (grid/peek) e `data-card-model-tile`; repassar `fontFamily` ao tile.
- **`src/components/cards/CardsStudio.tsx`** (editar): repassar `fontFamily` ao gallery; `DialogContent` com `p-0 sm:p-0` (mantém `gap-0`, `max-h-[92dvh]`, `overflow-hidden`, `sm:max-w-lg`).
- **`src/app/(frontend)/(home)/CampaignCardsSection.tsx`** (editar): importa `brexterBold` (`variable` na section + `style.fontFamily` no estúdio), renderiza `<CardsStudio fontFamily={…} />`, remove o bloco do CTA e o import de `Link`; atualiza o comentário S13 (antes da captura, abre o compositor).
- **`src/app/(frontend)/(home)/page.tsx`** (editar): mover `<CampaignCardsSection />` para entre `<CampaignStorySection />` e `<CampaignNewsletterSection … />`.
- **`src/app/(frontend)/styles.css`** (editar): `--muted-foreground: var(--campaign-muted)` no bloco `[data-theme='campaign-site']`.
- **`tests/unit/cardModels.unit.spec.ts`** (editar): pin `leftX`; remover o teste/import de `cardModelHref`.
- **`tests/unit/cardRender.unit.spec.ts`** (editar): pins de `leftX`/`textAlign='left'` + `describe('drawCardName')`.
- **`tests/e2e/frontend.e2e.spec.ts`** (editar): describe S14 com home/ordem/botões/sem-navegação/foco/alinhamento e os fluxos canônicos mantidos.
- **`docs/changelog/2026-09-12-s14-cards-personalizados-ajustes.md`** (novo).
- **Migration:** sem migration — nenhuma collection/global/field toca o schema; `push:false` intocado.
- **Access / Consent:** não se aplica — nenhuma superfície Payload; nenhum dado pessoal trafega; sem chave nova de Consent.
- **UI:** Impeccable C — craft/critique/polish dos seis ajustes sobre os shells existentes (`ui/dialog`, `ui/Drawer`, `useIsMobileMeasured`); sem componente de UI novo além do canvas do tile; alvos ≥44px e foco visível preservados.
### Dados → forma (se aplicável)
Não se aplica (data-presentation Q3): nenhum KPI, mapa ou série. A única "forma" é a geometria do próprio card (definida pelas artes-mestre); nome/foto são insumos locais da imagem, nunca dados apresentados ou coletados.
## Fases verificáveis
1. **Fidelidade do nome (núcleo + tile)** — quota ~0,5 dia. `leftX` + `drawCardName` + units; `CardNameTileName` + `CARD_NAME_TILE_PLACEHOLDER`; `CardModelGallery` select-only e remoção de `cardModelHref`/variante link; thread do `fontFamily`.
Prova: `pnpm gate:fast` verde; unit pinando borda esquerda nas 1 e 2 linhas; no craft, o tile do modelo de nome desenha `SEU NOME` com a mesma geometria do card (x=213) e o card com `João` mantém cap 106.
2. **Experiência (home + modal + contraste)** — quota ~0,5 dia. `CampaignCardsSection` renderiza a ilha e perde o CTA; ordem nova em `page.tsx`; `p-0 sm:p-0`; token de contraste.
Prova: home abre o compositor sem navegar (URL `/`); fechar volta à seção; a captura de novidades fica imediatamente depois dos cards; ajuda legível nos dois shells (contraste ~6:1).
3. **Gates + e2e + changelog** — quota ~0,5 dia. Describe e2e reescrito (ordem, botões, sem navegação, foco, alinhamento por pixel, `/cards`/`?model=`/download); changelog; `pnpm gate:fast`; e2e local do describe (`pnpm test:e2e --no-deps -- tests/e2e/frontend.e2e.spec.ts -g "Cards personalizados"`); `pnpm push`.
## Rabbit holes / Não escopo (engenharia)
- Não criar segundo editor/estado na home: a ilha `CardsStudio`/`CardComposer` é a única.
- Não mexer em `ui/dialog.tsx`/`ui/Drawer.tsx` para o vão (atinge o app inteiro) nem criar tema novo para o contraste.
- Não redesenhar as artes-mestre nem recalibrar o fit (`cardNameFit` intocado; `SEU NOME` encolhe porque é o resultado real da string).
- Não remover `/cards` nem quebrar o deep-link `?model=`.
- Não usar canvas para desenhar a base no tile (perde `next/image` otimizado/lazy).
- Não mover outras seções da home: a divergência da ordem literal vai ao gate, não vira redesenho.
- Não adicionar CMS/catálogo dinâmico, share social, analytics de uso ou métricas de clique.
- Não testar pixel no jsdom (unit usa ctx fake); a fidelidade é provada no e2e/craft.
## Triagem pós-simplify (capture-review-debts, 2026-09-12)
**Já resolvido no simplify/critique (não reabrir):** duplicação da varredura de pixel amarelo nos dois testes e2e (helper `readCardNameBand`/`expectCardNameLeftAligned` extraído); prop `priority` morta no `CardModelTile` (removida); tipo inline do `drawCardName` (`CardNameDrawArgs`); rename `CardNameTileName` → `CardNameTileCanvas`; prefixo de comentário `S13/S14`; estado a11y anunciado 2× (sufixo `(selecionado)` removido, `aria-pressed` fica); comentário impreciso do `brexterBold.variable`; `toHaveURL(/\/$/)` fraco no e2e da home (pathname pinado).
**Explicitamente fora / descartado:** falha do `pnpm exec knip` ao carregar `src/payload.config.ts` neste ambiente — pré-existente em `main` (reproduzida no checkout principal), fora do diff; achados visuais do design-vision (desalinhamento SOU×nome, alt ausente, foco ausente, padding no modal, falta de CTA no drawer) refutados por medição objetiva (nome minX 217 vs borda SOU 213; tiles decorativos com `aria-label` no botão; input com `focus-visible` e 16px; `p-0 sm:p-0` é o aceite; `Cancelar`/`Criar meu card` visíveis a 44px). Nada a registrar.
## Riscos e mitigação
- **Divergência da ordem literal do rascunho:** registrada na decisão 2 e no PR para o gate humano; o e2e pina o aceite operativo (`newsletter = cards + 1`). Mover `CampaignContentSection` seria outro item, fora do appetite.
- **Fonte não pronta no canvas do tile:** `ensureCardFont` antes de medir/desenhar; enquanto isso o tile mostra só a base; nunca medir com fallback (a geometria mentiria).
- **Export morto após a home virar botões:** `cardModelHref`/variante `link` saem no mesmo PR; `pnpm knip` acusa se sobrar algo.
- **Token de contraste vazando para outra superfície `campaign-site`:** grep confirma que não há outro `text-muted-foreground` no subtree; o token é o da casa e o tema é claro.
- **E2E de pixel flaky:** usar a mesma máscara amarela do teste existente e tolerância larga (x≤240; centralizado para `João` começaria >280); `expect.poll` espera o draw e o `ensureCardFont`.
- **`sm:p-0` não vencer o `sm:p-8` base:** twMerge remove a classe base de mesma variante; validar visualmente no craft (precedente `PetitionSuccessDialog` faz exatamente isso).
- **Peso novo na home:** o canvas do tile dispara `document.fonts.load` da Brexter (~38KB) quando a seção monta; aceito pela intenção (tile fiel), `preload:false` mantido e o arquivo é o mesmo do funil (cacheável).
- **Foco ao fechar na home:** `focusSelectedTile` já varre o tile visível — o da home é o próprio gatilho; o e2e cobre.
- **Regressão do fluxo canônico:** os testes de `/cards`, `?model=` e download permanecem; só o teste da home muda.
## Aceite de engenharia
- [ ] Aceite de produto da intenção coberto: home abre o compositor no lugar (modal desktop/drawer mobile) sem navegar e fecha de volta à seção; CTA removido; nome alinhado à esquerda (x≈213) em 1 e 2 linhas sem corte; tile fiel via o próprio renderizador; seção imediatamente antes da newsletter; modal sem vão; ajuda ≥4.5:1; `/cards` e `?model=` intactos; um único editor.
- [ ] Invariantes AGENTS/engineering-standards: sem schema/migration/Payload/Consent; nenhuma PII em rede/analytics; `src/lib` puro (sem Next/DOM); copy pt-BR / identificadores em inglês; sem `as never`; knip sem órfãos; `pnpm gate:fast` + `pnpm push` verdes.
- [ ] Testes de domínio previstos: unit dos módulos puros atualizado (`leftX`/`drawCardName`) e e2e no spec `frontend` reescrito com alinhamento por pixel; **int não se aplica** — não há Payload/DB/access nem escrita multi-collection neste fluxo (100% client-side + assets estáticos).
## Self-score decision-quality: 5/5
1. **Decisões caras com rejeitadas:** ilha única na home, ordem, geometria/desenho (`leftX`/`drawCardName`), tile fiel, vão do modal, contraste, harness de teste e changelog — todas com Opções/Recomendação/Rejeitadas e consequências.
2. **Cabe no appetite:** 3 fases somam ≤1,5 dia, sem migration, sem infra nova; a fidelidade do nome (maior risco) vem primeiro.
3. **Rabbit holes nomeados:** segundo editor, mexer nos shells base, redesenho das artes/fit, mover outras seções da home, CMS/share/analytics, teste de pixel no jsdom.
4. **Depth check:** reusa `CardsStudio`/`CardComposer`/`ui/dialog`/`ui/Drawer`/`ensureCardFont`/`createCardMeasure`/tema; `drawCardName` é extraído do próprio `renderNameCard` (sem módulo novo) e o placeholder vai para o `cardCopy` existente.
5. **Intenção preservada:** aceite de produto intacto; a única divergência (ordem literal do rascunho) está explicitada e é levada ao gate humano.

View file

@ -0,0 +1,325 @@
<!doctype html>
<html lang="pt-BR">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
<title>UI draft — S14 · Cards personalizados: ajustes de fidelidade e experiência</title>
</head>
<body class="bg-zinc-950 text-zinc-100 antialiased">
<main class="mx-auto max-w-[1400px] px-6 py-10">
<h1 class="text-lg font-semibold">
S14 · Cards personalizados — ajustes de fidelidade e experiência
</h1>
<p class="mt-2 max-w-4xl text-sm leading-6 text-zinc-400">
Visitante da home pública, principalmente no celular. O compositor passa a abrir na própria
home (sem navegar para <code>/cards</code>) e o CTA da home sai — tocar num modelo já abre a
criação; o nome fica alinhado à esquerda com o "SOU" no card e no tile; a seção muda de
posição; o modal perde o vão interno e o texto de ajuda ganha contraste. Cenas estáticas em
cinza neutro com um único acento indigo. Arte real omitida — este rascunho valida interface,
não redesenha os arquivos oficiais.
</p>
<div
class="mt-4 inline-flex min-h-9 items-center border border-zinc-700 bg-zinc-900 px-3 text-xs font-semibold text-zinc-300"
>
GEOMETRIA DO NOME · borda esquerda x≈213/1080 · tinta ≤714px · cap 106px · Brexter 700 ·
#ffec01
</div>
<!-- Cena 1: home desktop, nova ordem + compositor aberto -->
<section class="mt-12">
<h2 class="text-xs font-semibold tracking-wider text-zinc-500 uppercase">
Cena 1 · Home desktop — nova ordem + compositor aberto no lugar
</h2>
<p class="mt-1 text-xs text-zinc-500">
A seção "Mostre que você está com Solla" sobe para antes de "Receba as novidades da
campanha" (mantém a captura como último bloco). Tocar num modelo abre o modal sobre a
home; a URL não muda e a rolagem fica onde está. Sem CTA: os três modelos são o único
gatilho.
</p>
<div
class="relative mt-4 w-full max-w-[1160px] overflow-hidden border border-zinc-700 bg-white text-zinc-950"
>
<!-- bandas de contexto, na ordem -->
<div class="border-b border-zinc-200 bg-zinc-100 px-10 py-6">
<p class="text-[10px] font-bold tracking-wider text-zinc-400 uppercase">Hero</p>
<div class="mt-2 h-4 w-64 bg-zinc-300"></div>
<div class="mt-2 h-3 w-40 bg-zinc-200"></div>
</div>
<div class="border-b border-zinc-200 px-10 py-4">
<p class="text-[10px] font-bold tracking-wider text-zinc-400 uppercase">
Prova (números)
</p>
<div class="mt-2 grid grid-cols-3 gap-6">
<div class="h-3 bg-zinc-200"></div>
<div class="h-3 bg-zinc-200"></div>
<div class="h-3 bg-zinc-200"></div>
</div>
</div>
<div class="border-b border-zinc-200 bg-zinc-50 px-10 py-4">
<p class="text-[10px] font-bold tracking-wider text-zinc-400 uppercase">
Últimas notícias
</p>
<div class="mt-2 grid grid-cols-4 gap-3">
<div class="h-10 bg-zinc-200"></div>
<div class="h-10 bg-zinc-200"></div>
<div class="h-10 bg-zinc-200"></div>
<div class="h-10 bg-zinc-200"></div>
</div>
</div>
<div class="border-b border-zinc-200 bg-zinc-100 px-10 py-4">
<p class="text-[10px] font-bold tracking-wider text-zinc-400 uppercase">
Por que essa eleição importa
</p>
<div class="mt-2 h-3 w-80 bg-zinc-300"></div>
</div>
<div class="border-b border-zinc-200 px-10 py-4">
<p class="text-[10px] font-bold tracking-wider text-zinc-400 uppercase">
Nossa caminhada
</p>
<div class="mt-2 grid grid-cols-3 gap-3">
<div class="h-8 bg-zinc-200"></div>
<div class="h-8 bg-zinc-200"></div>
<div class="h-8 bg-zinc-200"></div>
</div>
</div>
<div class="border-b border-zinc-200 bg-zinc-50 px-10 py-4">
<p class="text-[10px] font-bold tracking-wider text-zinc-400 uppercase">
Acompanhe de perto
</p>
<div class="mt-2 grid grid-cols-4 gap-3">
<div class="h-8 bg-zinc-200"></div>
<div class="h-8 bg-zinc-200"></div>
<div class="h-8 bg-zinc-200"></div>
<div class="h-8 bg-zinc-200"></div>
</div>
</div>
<!-- seção de cards, agora aqui -->
<div class="border-y-2 border-indigo-500 bg-zinc-100 px-10 py-6">
<p class="text-[10px] font-bold tracking-wider text-indigo-600 uppercase">
Faça parte · nova posição
</p>
<div class="mt-2 grid grid-cols-[1fr_1.4fr] items-center gap-10">
<div>
<div class="h-4 w-56 bg-zinc-400"></div>
<div class="mt-2 h-3 w-72 bg-zinc-300"></div>
<p class="mt-4 text-[11px] font-semibold text-zinc-500">
Sem CTA — tocar num modelo abre o compositor
</p>
</div>
<div class="grid grid-cols-3 gap-3">
<div class="flex h-24 flex-col border border-zinc-400 bg-zinc-200">
<div class="m-1 h-3 w-14 self-start bg-zinc-400"></div>
<div class="mx-1 h-2 w-20 bg-zinc-300"></div>
<div class="mx-1 mt-1 h-2 w-12 bg-zinc-300"></div>
</div>
<div class="h-24 border border-zinc-400 bg-zinc-300"></div>
<div class="h-24 border border-zinc-400 bg-zinc-300"></div>
</div>
</div>
</div>
<div class="border-b border-zinc-200 bg-zinc-50 px-10 py-4">
<p class="text-[10px] font-bold tracking-wider text-zinc-400 uppercase">
Receba as novidades da campanha
</p>
<div class="mt-2 h-8 w-72 border border-zinc-300 bg-white"></div>
</div>
<div class="bg-zinc-100 px-10 py-4">
<p class="text-[10px] font-bold tracking-wider text-zinc-400 uppercase">Rodapé</p>
</div>
<!-- modal sobre a home -->
<div class="absolute inset-0 bg-zinc-950/50">
<div
class="absolute top-1/2 left-1/2 w-[420px] -translate-x-1/2 -translate-y-1/2 border border-zinc-400 bg-white p-0 text-zinc-950 shadow-xl"
>
<div class="flex items-start gap-3 px-5 pt-5">
<div>
<p class="text-base font-black">Personalize com seu nome</p>
</div>
<span class="ml-auto text-lg leading-none text-zinc-500">×</span>
</div>
<div class="px-5 pt-4 pb-5">
<div class="mx-auto flex h-56 w-40 flex-col border border-zinc-300 bg-zinc-200 p-3">
<div class="h-4 w-16 bg-zinc-400"></div>
<div class="mt-2 h-5 w-32 bg-zinc-500"></div>
<div class="mt-3 h-3 w-24 self-center bg-zinc-400"></div>
<div class="mt-auto h-4 w-28 self-center bg-zinc-500"></div>
</div>
<p class="mt-4 text-sm font-bold text-zinc-950">Seu nome</p>
<div class="mt-2 h-10 border border-zinc-300 bg-white"></div>
<p class="mt-2 text-xs text-zinc-600">
Use seu primeiro nome ou o nome pelo qual as pessoas conhecem você.
</p>
</div>
<div class="flex gap-3 border-t border-zinc-300 px-5 py-4">
<div
class="flex h-10 flex-1 items-center justify-center border border-zinc-300 text-xs font-bold"
>
Cancelar
</div>
<div
class="flex h-10 flex-1 items-center justify-center bg-indigo-600 text-xs font-bold text-white"
>
Criar meu card
</div>
</div>
</div>
</div>
</div>
<p class="mt-2 text-xs text-zinc-500">
Nota: o modal abre sobre a home e fecha de volta à seção; nenhuma navegação.
</p>
</section>
<!-- Cena 2: mobile com drawer -->
<section class="mt-12">
<h2 class="text-xs font-semibold tracking-wider text-zinc-500 uppercase">
Cena 2 · Home mobile (~390px) — drawer do compositor
</h2>
<p class="mt-1 text-xs text-zinc-500">
Mesma ilha, casca inferior; fechar devolve à seção sem perder a posição de rolagem.
</p>
<div class="mt-4 w-[390px] overflow-hidden border border-zinc-700 bg-white text-zinc-950">
<div class="border-b border-zinc-200 bg-zinc-100 px-5 py-4">
<p class="text-[10px] font-bold tracking-wider text-zinc-400 uppercase">
Acompanhe de perto
</p>
<div class="mt-2 h-8 bg-zinc-200"></div>
</div>
<div class="border-y-2 border-indigo-500 px-5 py-5">
<p class="text-[10px] font-bold tracking-wider text-indigo-600 uppercase">Faça parte</p>
<div class="mt-2 h-4 w-48 bg-zinc-400"></div>
<div class="mt-2 h-3 w-64 bg-zinc-300"></div>
<div class="mt-4 flex snap-x gap-3 overflow-hidden">
<div
class="flex h-40 w-[78%] shrink-0 flex-col border border-zinc-400 bg-zinc-200 p-2"
>
<div class="h-3 w-14 bg-zinc-400"></div>
<div class="mt-1 h-4 w-24 bg-zinc-500"></div>
<div class="mt-2 h-2 w-16 bg-zinc-400"></div>
</div>
<div class="h-40 w-[78%] shrink-0 border border-zinc-400 bg-zinc-300"></div>
</div>
<p class="mt-3 text-[11px] font-semibold text-zinc-500">
Sem CTA — tocar num modelo abre o drawer
</p>
</div>
<div class="relative h-72 bg-zinc-950/50">
<div class="absolute inset-x-0 bottom-0 border-t border-zinc-400 bg-white">
<div class="mx-auto mt-2 h-1 w-10 rounded-full bg-zinc-300"></div>
<div class="flex items-start gap-3 px-5 pt-4">
<p class="text-base font-black">Enquadre sua foto</p>
<span class="ml-auto text-lg leading-none text-zinc-500">×</span>
</div>
<div class="px-5 pt-3 pb-4">
<p class="text-sm text-zinc-700">
Arraste para posicionar e use os controles para aproximar ou ajustar.
</p>
<div class="mx-auto mt-3 h-32 w-32 border border-zinc-300 bg-zinc-200"></div>
<div class="mt-3 flex gap-3">
<div class="h-10 flex-1 border border-zinc-300"></div>
<div class="h-10 flex-1 bg-indigo-600"></div>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- Cena 3: fidelidade do tile de nome -->
<section class="mt-12">
<h2 class="text-xs font-semibold tracking-wider text-zinc-500 uppercase">
Cena 3 · Tile do modelo de nome — fiel ao resultado
</h2>
<p class="mt-1 text-xs text-zinc-500">
O tile passa a repetir a geometria do card real: nome na mesma borda esquerda do "SOU",
fonte display em peso forte, maior, na cor de destaque. Arte real omitida.
</p>
<div class="mt-4 flex flex-wrap items-start gap-8">
<div>
<p class="text-xs font-semibold text-zinc-400">Hoje — centralizado e menor</p>
<div class="mt-2 flex h-64 w-48 flex-col border border-zinc-600 bg-zinc-200 p-4">
<div class="h-4 w-16 bg-zinc-400"></div>
<div class="mt-3 h-4 w-32 self-center bg-zinc-500"></div>
<div class="mt-6 h-3 w-24 self-center bg-zinc-400"></div>
<div class="mt-auto h-4 w-28 bg-zinc-500"></div>
</div>
</div>
<div>
<p class="text-xs font-semibold text-indigo-400">
Proposto — alinhado à esquerda com "SOU"
</p>
<div class="mt-2 flex h-64 w-48 flex-col border border-indigo-500 bg-zinc-200 p-4">
<div class="h-4 w-16 bg-zinc-400"></div>
<div class="mt-3 h-6 w-36 bg-zinc-600"></div>
<div class="mt-6 h-3 w-24 self-center bg-zinc-400"></div>
<div class="mt-auto h-4 w-28 bg-zinc-500"></div>
</div>
<p class="mt-2 max-w-48 text-[11px] leading-4 text-zinc-500">
Exemplo literal: <span class="font-semibold text-zinc-300">SEU NOME</span> · borda
esquerda igual à do "SOU" · Brexter 700 · #ffec01
</p>
</div>
</div>
</section>
<!-- Cena 4: modal enxuto + ajuda legível -->
<section class="mt-12">
<h2 class="text-xs font-semibold tracking-wider text-zinc-500 uppercase">
Cena 4 · Compositor de foto — moldura enxuta e ajuda legível
</h2>
<p class="mt-1 text-xs text-zinc-500">
Sem o vão interno de 32px: o conteúdo encosta na moldura com o respiro próprio do
componente. A ajuda usa cinza escuro com contraste ≥ 4.5:1 sobre branco.
</p>
<div class="mt-4 flex flex-wrap items-start gap-8">
<div>
<p class="text-xs font-semibold text-zinc-400">
Hoje — vão interno grande + ajuda clara
</p>
<div class="mt-2 w-[380px] border border-zinc-600 bg-white p-8 text-zinc-950">
<p class="text-sm font-bold">Enquadre sua foto</p>
<p class="mt-1 text-sm text-zinc-300">
Arraste para posicionar e use os controles para aproximar ou ajustar.
</p>
<div class="mx-auto mt-4 h-40 w-40 border border-zinc-300 bg-zinc-200"></div>
<div class="mt-4 flex gap-3">
<div class="h-10 flex-1 border border-zinc-300"></div>
<div class="h-10 flex-1 bg-indigo-600"></div>
</div>
</div>
</div>
<div>
<p class="text-xs font-semibold text-indigo-400">Proposto — encostado + ajuda escura</p>
<div class="mt-2 w-[380px] border border-indigo-500 bg-white p-0 text-zinc-950">
<div class="px-5 pt-5">
<p class="text-sm font-bold">Enquadre sua foto</p>
<p class="mt-1 text-sm text-zinc-700">
Arraste para posicionar e use os controles para aproximar ou ajustar.
</p>
</div>
<div class="px-5 pt-3 pb-5">
<div class="mx-auto h-40 w-40 border border-zinc-300 bg-zinc-200"></div>
</div>
<div class="flex gap-3 border-t border-zinc-200 px-5 py-4">
<div class="h-10 flex-1 border border-zinc-300"></div>
<div class="h-10 flex-1 bg-indigo-600"></div>
</div>
</div>
<p class="mt-2 max-w-80 text-[11px] leading-4 text-zinc-500">
Moldura: borda fina e raio preservados; só o padding base de 32px do desktop é
neutralizado.
</p>
</div>
</div>
</section>
</main>
</body>
</html>

View file

@ -0,0 +1,112 @@
# Cards personalizados: ajustes de fidelidade e experiência (S14)
Status: rascunho
Atualizado em: 2026-09-12
Issue: #959
Priority: P1
Model: composer-2.5
Impeccable: C — ajustes de fidelidade e interação no funil público de cards (home + compositor)
Rascunho UI: docs/plans/cards-personalizados-ajustes-ui-draft.html
Appetite: ~1–1,5 dia eng; seis ajustes verificáveis no funil já entregue, sem fluxo novo
Responsável: —
## Intenção
O S13 (#941) entregou o funil de cards e está em produção: a seção `Mostre que você está com Solla` na home e o compositor em `/cards`. O humano revisou o funil e pediu seis ajustes de fidelidade e experiência: o modelo da home deve abrir o compositor ali mesmo; o nome no card gerado deve alinhar à esquerda com a linha `SOU`; o tile do modelo de nome deve ser fiel ao resultado real; a seção precisa de uma posição melhor na home; a moldura do modal tem um vão interno grande demais; e o texto de ajuda está ilegível por baixo contraste.
É um refinamento do que já existe — nenhum modelo, rota ou mecanismo novo. A promessa ao visitante continua a mesma: mostrar apoio com a identidade oficial, sem conta e sem que nome ou foto saiam do aparelho.
**Decisões do humano (2026-09-12, gate):** a home passa a abrir o MESMO compositor de `/cards` (modal no desktop, drawer no mobile), mantendo a pessoa na homepage; o CTA `Criar meu card` da home é removido — os três modelos passam a ser o único gatilho. Isso reverte deliberadamente a decisão do gate do S13 de que `/cards` seria a única superfície de edição; o anti-goal "dois fluxos de criação" permanece — há um único editor, não dois.
## Persona e fluxo
- **Persona / contexto:** visitante do site, geralmente no celular, que quer manifestar apoio e publicar uma imagem com a identidade da campanha.
- **Job principal:** criar um card pessoal com aparência oficial em poucos passos, sem sair de onde está nem entregar dados.
- **Fluxo desejado:** vê a seção na home → toca em um modelo → o compositor abre ali mesmo (modal no desktop, drawer no mobile) → personaliza e confere → gera e baixa o PNG → fecha e continua na home. Quem chega direto em `/cards` (ou por link `?model=`) mantém o fluxo canônico.
- **Anti-goals de produto:** virar editor gráfico completo, galeria, rede social, cadastro de apoiador, segundo editor ou novo canal de coleta de dados.
### Esboço de fluxo (C)
```text
[home: seção "Mostre que você está com Solla"]
→ [toca num modelo]
→ [modal desktop | drawer mobile — compositor aberto na home]
→ [personalizar + conferir] → [card pronto] → [baixar PNG] → [fechar → continua na home]
(caminho canônico preservado: /cards e /cards?model=<id>)
```
### Rascunho UI (C)
- Rascunho UI (gate): `docs/plans/cards-personalizados-ajustes-ui-draft.html`
- Cenas: home com o compositor aberto em desktop e mobile, tile de nome fiel ao resultado, modal sem vão interno, ajuda legível e a nova ordem das seções.
## Objetivo e aceite
- Tocar em um modelo na home abre o compositor ali mesmo, sem navegar; a pessoa permanece na homepage e, ao fechar, volta à seção.
- O CTA `Criar meu card` sai da seção da home: os três modelos são o único gatilho e abrem o compositor ali mesmo.
- O nome no card gerado fica alinhado à esquerda com a linha `SOU` (borda x≈213), em uma e duas linhas, sem cortar texto; o ajuste de tamanho/quebra atual permanece.
- O tile do modelo de nome reproduz o resultado real: mesma borda esquerda do `SOU`, fonte `Brexter 700`, mesma relação de tamanho/cap height e cor `#ffec01`, com `SEU NOME` como exemplo.
- A seção é reposicionada na ordem da home: imediatamente antes de `Receba as novidades da campanha` e depois de `Acompanhe de perto`, mantendo a captura de contato como último bloco de conversão.
- A moldura do modal do compositor encosta no conteúdo (sem o vão interno atual), preservando borda fina e raio.
- O texto de ajuda `Arraste para posicionar e use os controles para aproximar ou ajustar.` fica legível nos dois shells (contraste ≥ 4.5:1 sobre branco).
- Guardrails: nome e foto continuam 100% no aparelho (sem PII em rede/analytics, sem persistência); arte-mestre intocada; `/cards` e o deep-link `/cards?model=<id>` seguem funcionando; um único editor; as demais seções da home não mudam.
## Dados (intenção)
- **Vou apresentar dados?** Não.
- **Decisões desbloqueadas:** N/A — esta entrega não apresenta métricas nem dados para uma decisão operacional.
- **Forma:** _adiada ao plano de implementação_ — nome e foto seguem insumos locais da imagem; nenhum conteúdo pessoal entra em analytics.
## Dados da decisão (literais)
- ID reservado: `S14`; Tipo: `feature`; Priority proposta: `P1`; Model: `composer-2.5`.
- Frase de ajuda literal: `Arraste para posicionar e use os controles para aproximar ou ajustar.`
- Placeholder literal do tile: `SEU NOME`.
- Geometria-mestre do nome: borda esquerda x≈213 (canvas de 1080 de largura), tinta máxima 714px, cap height 106px, fill `#ffec01`, fonte `Brexter 700`.
- Tokens de contraste: `--campaign-muted: #6c615e`, `--campaign-ink: #000000`.
- Rota canônica preservada: `/cards` e deep-link `/cards?model=<id>`.
- Seção na home: `id="cards"`, `data-home-section="cards"`, título `Mostre que você está com Solla`; o CTA `Criar meu card` é removido da home (os modelos são o único gatilho).
- Nova ordem da home (decidida no gate): `… → Acompanhe de perto → cards → Receba as novidades da campanha → rodapé`.
- Arquivos-mestre de referência: `/home/fsolla/Documentos/cards/eu-sou-solla/template-to-com-solla-site.jpg.jpeg` (preenchido) e `/home/fsolla/Documentos/cards/eu-sou-solla/template-to-com-solla-site-sem-o-nome.jpg.jpeg` (base).
## Direção no codebase (hipótese)
- **Áreas prováveis:** seção e ordem da home em `src/app/(frontend)/(home)/`, componentes e catálogo em `src/components/cards/`, geometria/render em `src/lib/card*`, tokens em `src/app/(frontend)/styles.css`.
- **Precedente a olhar:** o próprio S13 (`docs/plans/cards-personalizados-campanha.md` + `-impl.md`); `CardsStudio`/`CardComposer` para reusar a ilha na home sem duplicar editor; `CardModelTile`/`NAME_CARD_SLOT` para a fidelidade do tile.
- **Risco de acoplamento:** o vão do modal nasce da classe base `sm:p-8` sobrevivendo ao override `p-0` (twMerge só remove a variante sem breakpoint); o contraste da ajuda vem de `DialogDescription`/`DrawerDescription` usarem `text-muted-foreground`, que `[data-theme='campaign-site']` não redefine (cai no near-white do `:root`). Resolver no menor blast radius, sem criar tema paralelo.
## Dependências
- Nenhuma.
## Fora de escopo
- Novos modelos, CMS de modelos ou métricas de uso.
- Redesenho das demais seções da home ou da página `/cards`.
- Remover `/cards` ou quebrar o deep-link `?model=`.
- Compartilhamento direto em redes sociais.
- Alterar as artes-mestre (compor por cima, nunca redesenhar).
## Rabbit holes de produto
- **Segundo editor na home.** Se alguém "só completar": nasce um compositor próprio na home e os comportamentos divergem. **Corte neste item:** a home abre o mesmo compositor, com o mesmo estado e a mesma ilha de edição.
- **Redesenhar o modal inteiro.** Se alguém "só completar": vira repaginação do compositor. **Corte neste item:** corrigir o vão da moldura e o contraste da ajuda, sem mudar estrutura.
- **Trocar a arte para "melhorar" a fidelidade.** Se alguém "só completar": a arte oficial é reeditada. **Corte neste item:** o resultado segue a arte-mestre; o ajuste é do desenho/tile.
- **Medir fidelidade "no olho".** Se alguém "só completar": aproximação visual vira critério. **Corte neste item:** usar a geometria do mestre (borda x≈213, tinta 714, cap 106, Brexter 700, `#ffec01`).
## Questões em aberto (produto)
- **Onde a seção entra na home?** **Decidido no gate (2026-09-12): antes de `Receba as novidades da campanha` e depois de `Acompanhe de perto`** — mantém a captura de contato como último bloco de conversão.
- **O que faz o CTA `Criar meu card` da home?** **Decidido no gate (2026-09-12): o CTA é removido da home** — tocar num modelo já abre o compositor de criação; a seção fica só com os três modelos como gatilho.
- **`/cards` continua existindo?** **Decidido no gate (2026-09-12): sim**, como página canônica e deep-link; a mudança é só o comportamento da home.
## Referências
- GitHub Issue #941 (S13, entregue)
- `docs/plans/cards-personalizados-campanha.md` e `docs/plans/cards-personalizados-campanha-impl.md`
- `docs/changelog/2026-09-12-s13-cards-personalizados.md`
- Rascunho UI (gate): `docs/plans/cards-personalizados-ajustes-ui-draft.html`
- `src/app/(frontend)/(home)/CampaignCardsSection.tsx`, `src/app/(frontend)/(home)/page.tsx`, `src/app/(frontend)/(home)/cards/page.tsx`
- `src/components/cards/{CardsStudio,CardComposer,CardModelGallery,CardModelTile}.tsx`, `src/lib/{cardModels,cardNameFit,cardRender}.ts`
- `src/app/(frontend)/styles.css` e `src/app/(frontend)/fonts.ts`
- `AGENTS.md` e `AGENTS-public.md`

View file

@ -0,0 +1,125 @@
# Escala e DRY pós-C150 (shell responsivo dos diálogos da agenda)
Status: rascunho
Atualizado em: 2026-09-12
Item do roadmap: fill-in de engenharia (Trilha C, pós-C150) — sem linha nova no roadmap
Issue: C156 (registrada por `agent:register`)
Priority: P3
Impeccable: B — encaixe estrutural sem pixel novo; paridade de DOM/`data-slot` é o aceite (sem critique visual)
Appetite: ~0,5–1 dia eng (fill-in)
Responsável: —
## Contexto
O C150 (#935) entregou o `GoogleCalendarPickerDialog` — a **3ª cópia** do chrome responsivo
Dialog/Drawer da agenda. O C148 (#933, entregue 2026-09-12) considerou e **rejeitou** a extração
(Opção C) para 3 call sites, com gatilho explícito: _"4º modal da agenda com o mesmo corpo
rolável, ou adoção do padrão por outro domínio"_ ([c148-modais-agenda-desktop-impl.md](c148-modais-agenda-desktop-impl.md),
Decisão C). Com o picker, há **4** modais com `data-slot="dialog-scroll-body"` (ActivityOverlay,
Sync, Feed, Picker) — **o gatilho disparou** (mesmo precedente do E10+: _"o gatilho disparou, e é por
isso que este lote existe em vez de mais uma linha adiada"_).
Três deles — `GoogleCalendarSyncDialog`, `CalendarFeedDialog` e `GoogleCalendarPickerDialog` — têm
chrome **idêntico** exceto `max-w` e conteúdo do rodapé: desktop
`DialogContent flex max-h-[calc(100dvh-2rem)] flex-col gap-0 overflow-hidden p-0 sm:max-w-xl sm:p-0`
- header `shrink-0 border-b px-6 py-4 pr-12 text-left` + corpo
`min-h-0 flex-1 overflow-y-auto overscroll-contain px-6 py-4` + rodapé `shrink-0 border-t px-6 py-4`;
mobile `DrawerContent max-h-[85vh]` + corpo rolável com as ações dentro + `DrawerFooter` com Fechar.
Evidência (linhas atuais, pós-simplify): picker `src/components/campaign/activity/GoogleCalendarPickerDialog.tsx`,
sync `GoogleCalendarSyncDialog.tsx`, feed `CalendarFeedDialog.tsx:214-260`; ActivityOverlay `:448`.
**Já resolvido no simplify (não reabrir):** picker com guarda de sessão (`sessionRef`/`reloadCount`),
catch de promise rejeitada e status de erro, `CalendarOption` extraído, retry com `useCallback`,
seleção desabilitada durante a escolha e copy da descrição corrigida; chrome com o envelope
`applyState` compartilhado pelos 4 handlers; sync dialog com `runAction` e `addLink` derivado
localmente; `buildGoogleCalendarWebcalUrl` morto removido; `resolveGoogleCalendarPickerClient`
dobrado em `loadWritableGoogleCalendars` e flag `changed` removida.
## Objetivos
- Um `CampaignResponsiveDialog` em `src/components/campaign/shared/`, dono do contrato responsivo
(Dialog desktop com header/body/footer; Drawer mobile com ações no corpo + Fechar no
`DrawerFooter`) — a divergência mobile/desktop deixa de estar triplicada.
- Sync/Feed/Picker compõem o shell com DOM e classes **idênticos** aos de hoje (paridade pinada
pelos units/e2e existentes).
- F3 (cortável): fonte única da copy do one-click em `src` (chrome + dialog); testes seguem com literais.
- Guardrails: sem migration/schema/access/Consent; `ui/dialog.tsx` e os demais consumidores
intocados; ActivityOverlay fora; comportamento e estado inalterados.
## Decisões travadas
- **Escopo: só os 3 homogêneos; ActivityOverlay fora.** O overlay usa `p-0` + cards com `<form>`
envolvendo header/body/footer, `sm:max-w-3xl` e mobile como sheet (não Drawer); incluí-lo exigiria
modos/wrappers que transformariam o shell num config pass-through — exatamente o que o C148
rejeitou. **Rejeitadas:** shell paramétrico para os 4 (YAGNI/config); manter a 4ª cópia.
- **Props de forma, não `variant` genérico:** `{ title, description, children, actions?, size: 'lg' | 'xl', footerClassName? }`;
ações no corpo no mobile e no rodapé fixo no desktop (a regra que o C148 conquistou). Picker = `lg`;
sync/feed = `xl`. **Rejeitadas:** cada dialog montar os dois ramos (mantém a cópia);
`asChild`/render-prop (cerimônia sem volatilidade).
- **Paridade como aceite, não redesign:** classes e `data-slot` preservados; se um unit exigir edição
de asserção estrutural, parar e reavaliar.
- **F3 só se F1/F2 não estourarem** (cortável sem perda do objetivo principal).
## Fases
1. **F1 — shell + picker (tracer, ~50%).** Criar `CampaignResponsiveDialog`; migrar o
`GoogleCalendarPickerDialog` (call site mais novo, com unit próprio). Gate: unit do picker verde +
inspeção visual mobile/desktop.
2. **F2 — sync + feed (~35%).** Mesmo diff mecânico. Gate: units `googleCalendarSyncDialog`/
`calendarFeedDialog` verdes sem edição das asserções estruturais.
3. **F3 — copy única do one-click (cortável, ~5%).** Exportar a label consumida por
`AgendaGoogleSyncChrome` e `GoogleCalendarSyncDialog`; literais permanecem nos testes/e2e.
4. **F4 — gates (~10%, não cortável).** `pnpm gate:fast`; e2e afetados (`campaignAgendaGoogleSync`,
`campaignAgendaFeed`, `campaignActivity`); changelog.
## Rabbit holes / Não escopo
- Não tocar `ui/dialog.tsx` nem os outros consumidores (C148).
- Não incluir `ActivityOverlay` (form/cards/mobile sheet) — gatilho: 2º overlay de form com o mesmo formato.
- Não unificar os breakpoints (`useNarrowMeasured(640)` do overlay vs `useIsMobile()` 768) — C148.
- Não unificar as máquinas de estado picker/sync (S3) — domínios distintos (lista+escolha × ciclo de sync).
- Não mudar copy (fora F3), lógica, estado, nem o `DrawerFooter`/nested sheet.
- Não redesenhar: zero pixel novo; classes idênticas.
## Riscos e mitigação
- **Regressão mobile por recomposição:** paridade de DOM; units/e2e mobile (C103/C94/C114) verdes;
diff por dialog.
- **twMerge/variantes `sm:`** (lição C148): o shell espelha as variantes e preserva `p-0`; asserções
são de `data-slot`/estrutura, não de classe.
- **Rodapé condicional** (sync não renderiza quando vazio; feed sempre; picker condicional): `actions?`
— footer só com `actions`; sync passa `errorNotice` junto das ações.
- **Testes acoplados ao shell:** asserções existentes são estruturais; edição delas = sinal de mudança
de comportamento → parar.
## Explicitamente fora
- **S3 — máquinas de estado picker/sync:** deferido — não é duplicação exata (ciclos de domínio
distintos; D5 do C150 escolheu diálogos separados). Gatilho: 3º diálogo com a mesma máquina busy/erro/ação.
- **S2 standalone:** absorvido como F3 (cortável); se cortada, gatilho: 3ª superfície consumindo a label.
- **ActivityOverlay na extração:** fora (heterogêneo) — gatilho acima.
- **`ui/dialog.tsx` / unificação de breakpoint:** decisões do C148, não reabrir.
- Achados cosméticos dos revisores aplicados no simplify — não reabrir.
## Aceite de engenharia
- [ ] Os 3 diálogos compõem `CampaignResponsiveDialog`; nenhuma cópia do chrome trio resta
(`grep` por `sm:max-w-xl` + `dialog-scroll-body` só no shell).
- [ ] DOM mobile idêntico (ações no corpo + `DrawerFooter` Fechar) e desktop com rodapé fixo;
units/e2e atuais verdes sem edição de asserção estrutural.
- [ ] `pnpm gate:fast` verde; e2e afetados rodados; changelog.
- [ ] Sem migration/access/Consent; `ui/dialog.tsx` intacto.
## Self-score (decision-quality)
| Critério | Nota | Justificativa |
| ---------------------------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------ |
| Decisões caras têm rejeitadas? | 4/5 | Escopo (trio vs 4) e forma do shell com rejeitadas explícitas; demais decisões são baratas. |
| Cabe no appetite? | 5/5 | 1 componente + 3 migrações mecânicas + testes; sem schema. |
| Rabbit holes nomeados? | 5/5 | Overlay, breakpoints, máquinas de estado, base global, copy fora de F3. |
| Depth check: reusa shells/helpers? | 4/5 | O shell encapsula o contrato responsivo conquistado no C148; não é pass-through para o trio (é para o overlay, que fica fora). |
| Intenção permanece satisfeita? | 5/5 | Refactor sem pixel/comportamento novo; paridade pinada por testes. |
**Total: 4,6/5 (gate ≥4).**

View file

@ -0,0 +1,115 @@
# Impl: OPS102 — Deploy manual roda até o fim mesmo com main à frente (sem guard de stale run)
Status: em execução
Atualizado em: 2026-09-12
Issue: #962
Intenção: docs/plans/ops102-deploy-manual-sem-stale-guard.md
Appetite restante: herdado (~0,5 dia eng; sem migration, sem UI, sem schema — remoção de ~8 linhas no script, reescrita de 2 specs unit, 4 docs vivas + changelog)
## Leitura da intenção
- **Outcome:** um `workflow_dispatch` do `deploy.yml` completa o deploy do SHA do run mesmo que `main` avance durante os ~50 min do `verify` — sem "stale run" abortando. Sem falso verde: job verde = SHA publicado (build + rollout + smoke) ou container já o rodava ("already deployed") — nunca skip silencioso.
- **O que NÃO negociar:** o guard "already deployed" (`scripts/deploy-homeserver.sh:70-74`) permanece intacto; nenhum caminho verde sem deploy; nenhum mecanismo novo anti-out-of-order; `verify`/build/ordem migrator→migrate→runner/rollback/smoke intocados; `workflow_dispatch`-only intacto; histórico (postmortem #953, changelogs, `CHANGELOG-AGENTS-HISTORY.md`, planos ops53/65/66/71/103) não é editado.
- **O que reavaliar:** nada de produto — a questão em aberto da intenção já está decidida (Recomendação A: documentar o risco, não engenhar). Em engenharia, duas escolhas baratas: a forma exata dos pins unitários (Decisão 2) e o texto da linha de risco out-of-order na tabela "Falhas conhecidas" (Decisão 3).
## Abordagem recomendada
```mermaid
flowchart TD
A["workflow_dispatch (operador escolhe o SHA)"] --> B["verify hosted: suíte full (~50 min)<br/>main pode avançar no meio"]
B --> C["deploy job: bash scripts/deploy-homeserver.sh $GITHUB_SHA"]
C --> D["flock: serializa dispatches (l.54-55)"]
D --> E{"container já roda a revision do SHA? (l.70-74)"}
E -- sim --> F["'already deployed' → exit 0<br/>ÚNICO verde sem build"]
E -- não --> G["migrator build → migrate → runner build → rollout → smoke"]
G --> H["deploy completo do SHA do run<br/>mesmo com main à frente (OPS102)"]
F -. "removidos: guards pré/pós-flock (l.49-52, l.57-60)" .-> D
```
**Opções consideradas:** A | B | C por decisão, abaixo.
**Recomendação:** **A + A/B + A** — remover os dois guards de stale run (Decisão 1); pins unitários negativos + positivo do "already deployed" + pin do único `exit 0` (Decisão 2); atualizar runbook/AGENT-OPS e registrar o risco out-of-order na tabela "Falhas conhecidas" (Decisão 3). Cada mudança fica no dono do contrato (script, spec, docs vivas) sem criar superfície nova.
**Rejeitadas:** manter os guards como warn ou condicionados (Decisão 1: B/C); remover os testes e confiar no e2e (Decisão 2: C); só apagar as menções das docs (Decisão 3: B).
### Decisão 1 — destino dos guards de stale run
- **Opções:** A) remover os dois blocos (`l.49-52` pré-flock e `l.57-60` pós-flock); B) torná-los não-fatais (warn); C) mantê-los condicionados ao gatilho (`workflow_dispatch`).
- **Recomendação:** **A — remover.** A premissa do guard era o deploy automático (OPS53): `main` andava sozinho e publicar SHA velho era errado. Desde a OPS71 o dispatch é ato humano deliberado e o `ciSkipInvariants.unit.spec.ts:111-115` pina que o workflow é `workflow_dispatch`-only — a comparação com o HEAD do `main` deixou de significar algo.
- **Rejeitadas:** B porque um warning em job verde é ruído sem ação (e mantém um `git ls-remote` por deploy + a leitura errada de que `main` importa); C porque o workflow **já é só** `workflow_dispatch`, então a condição seria sempre verdadeira — é A com código morto e um round-trip a mais ao remoto.
### Decisão 2 — como pinar o contrato novo nos unit tests
- **Opções:** A) pins negativos (`not.toContain('stale run' / 'git ls-remote' / 'refs/heads/main')`) + manter o pin positivo do "already deployed"; B) pin positivo do fluxo novo (`toContain('already deployed')` + `not.toContain('stale run')`); C) remover os testes e confiar no e2e.
- **Recomendação:** **A+B combinados** — reescrever as specs `l.19-23` e `l.25-30` como contrato negativo com comentário de intenção (o guard OPS53 só faz sentido em deploy automático; reintroduzi-lo deve falhar), **manter intacta** a spec `l.32-38` ("already deployed") e adicionar dois pins que dão dentes à remoção: (i) o **único `exit 0`** do script é o do "already deployed" (não existe mais nenhum caminho de skip verde — regressão do #953); (ii) o `flock` permanece (anti over-deletion).
- **Rejeitadas:** C porque o e2e **não roda o script de deploy** (nenhum spec de e2e o exercita; o `deploy.yml` não é disparado no CI de PR) — seria trocar a única rede por nenhuma; B sozinho porque `not.toContain('stale run')` prova ausência de string, não ausência de outro caminho de falso verde — o pin do `exit 0` único cobre a classe.
### Decisão 3 — documentação viva
- **Opções:** A) atualizar runbook + AGENT-OPS e adicionar a linha de risco out-of-order na tabela "Falhas conhecidas"; B) só remover as menções ao guard; C) deixar como está (registro histórico).
- **Recomendação:** **A** — o runbook e o AGENT-OPS são docs **vivas** (fonte de operação); a remoção do guard muda o fluxo, então o texto muda junto, e o risco de dispatch fora de ordem (SHA antigo re-dispatchado depois de um deploy mais novo) fica explícito com gatilho de revisita (Recomendação A da questão em aberto da intenção).
- **Rejeitadas:** B porque apaga o fluxo sem dar a leitura nova ao operador (e perde o contexto do #953); C porque o histórico é `docs/changelog/` + `docs/postmortems/` + `HISTORY` (intocados) — runbook/AGENT-OPS não são registro congelado.
### Componentes / mudanças
- **`scripts/deploy-homeserver.sh`** (dono do fluxo):
- Remover o bloco pré-flock `l.49-52` e o bloco pós-flock `l.57-60` (a comparação `git ls-remote … refs/heads/main` + os dois `fatal "stale run…"`). O `awk` some junto, sem órfãos.
- Renomear o cabeçalho `# --- guards ---` (`l.47`) para algo como `# --- serialization (flock) ---`, já que o único bloco restante ali é o `flock` (`l.54-55`).
- Header de fluxo `l.11-12`: remover "HEAD guard (only the current main HEAD deploys; a stale run FAILS the job — never a false green…)" e começar em "flock serialization -> workspace fetch at <sha> -> …".
- Comentário do `set-url` `l.96-98`: "so the HEAD guard and the fetch compare against the repo…" → "so the fetch targets the repo that actually received the merge" (o `TEQO_REPO_URL` continua usado por clone/set-url/fetch — não remover).
- **Preservar sem tocar:** `flock` `l.54-55`; bloco de idempotência "already deployed" `l.62-74` (inclui o `exit 0`); `say`/`fatal` (usados no resto do script).
- **`.github/workflows/deploy.yml`:** atualizar o comentário `l.23-25` ("the script's HEAD guard only deploys when the dispatched SHA is main's HEAD (a stale dispatch skips)") para "the script deploys the dispatched SHA to the end even if main advances during verify (OPS102 — deliberate dispatch; idempotency is the 'already deployed' guard)". Nada mais muda: `on: workflow_dispatch` (l.29-30), `needs/if/runs-on` e a invocação `l.159` (`bash scripts/deploy-homeserver.sh "$GITHUB_SHA"`) ficam intactos.
- **`tests/unit/deployScript.unit.spec.ts`:** reescrever as specs `l.19-23` e `l.25-30` conforme Decisão 2; manter a spec `l.32-38` ("already deployed", `docker inspect` + `$running_rev` + `"$running_rev" = "$SHA"`); o restante do arquivo (BuildKit, proxy, ordem OPS66, smoke, secrets, Dockerfile) não muda. `ciSkipInvariants.unit.spec.ts` **não muda** (já pina só `workflow_dispatch:` + ausência de `push`/`schedule`).
- **`docs/ops/teqo-1313-deploy.md`:**
- Fluxo passo 4 (`l.20-22`): "guarda de HEAD (`git ls-remote` de `TEQO_REPO_URL` … senão 'stale run' skip) → `flock`" → "`flock` (serializa dispatches) → guard 'already deployed'"; manter a menção a `TEQO_REPO_URL` como origem do clone/atualização do workspace (a info não se perde).
- Tabela "Falhas conhecidas" (`l.132`): trocar a linha "Job verde sem deploy ('stale run')" por **"Dispatch fora de ordem (SHA antigo re-dispatchado depois de um deploy mais novo)"** | causa: o `flock` serializa mas não ordena; o "already deployed" não pega revision diferente | tratamento: não re-dispatchar SHA antigo; se acontecer, re-dispatchar o `main` atual (rollback manual disponível na seção Rollback). Gatilho para revisitar: deploy mais frequente/automatizado ou regressão real. A linha `l.133` ("already deployed") permanece.
- **`docs/AGENT-OPS.md`:** `l.81` — remover `HEAD guard;` da descrição do `deploy.yml`; `l.110` — trocar "O script: HEAD guard (`TEQO_REPO_URL` — default …, público) → flock → guard 'already deployed' …" por "O script: flock → guard 'already deployed' …", acrescentando que o deploy roda até o fim com o SHA do dispatch mesmo se `main` andar durante o verify (OPS102).
- **`docs/changelog/2026-09-12-ops102.md`** (novo): UMA entrada curta no padrão AGENTS; nunca editar o agregado nem o HISTORY.
- **Migration:** nenhuma. **Access/Consent:** N/A (não toca Payload). **UI:** Impeccable A — N/A (sem UI).
### Dados → forma
N/A (sem UI).
## Fases verificáveis
1. **Script + workflow (remoção + comentários).** Remover os dois blocos de stale run, ajustar header de fluxo, comentário do `set-url` e comentário do `deploy.yml`. Verificações: `bash -n scripts/deploy-homeserver.sh`; `git diff` revisado mostrando `flock` e "already deployed" intactos e só comentários além dos guards removidos; `grep -n 'stale run\|git ls-remote\|refs/heads/main' scripts/deploy-homeserver.sh` vazio.
2. **Unit tests.** Reescrever as duas specs + adicionar os pins do `exit 0` único e do `flock`; manter a spec do "already deployed". Verificações: `pnpm test:unit -- tests/unit/deployScript.unit.spec.ts` verde. Prova de valor (RED barata): rodar a spec reescrita contra o script pré-remoção (ex.: `git stash` do diff da Fase 1) e ver `not.toContain('stale run')` falhar — o pin tem dentes.
3. **Docs vivas + changelog.** Runbook (fluxo + linha out-of-order), AGENT-OPS (`l.81`, `l.110`), entrada `docs/changelog/2026-09-12-ops102.md`. Verificação: `grep -rn 'stale run\|HEAD guard' scripts/ .github/ docs/ops/ docs/AGENT-OPS.md` vazio (fora de `docs/plans/`, `docs/changelog/`, `docs/postmortems/`, `docs/CHANGELOG-AGENTS-HISTORY.md` — histórico intocável).
4. **Gates + entrega.** `pnpm gate:fast` verde (lint/format/typecheck/unit); `pnpm push` (gate:push = gate:ci — o PR toca `tests/unit`, então a seleção roda a spec alterada); PR com `Closes #962`, base `main`, auto-merge armado. **Aceite final (humano, pós-merge):** dispatch manual do `deploy.yml` → `verify` verde → job `deploy` concluído publicando a revision do SHA do run; idealmente com `main` andando durante o verify (natural se houver merge concorrente) para exercitar o cenário ao vivo — a prova determinística do contrato fica nos pins.
## Rabbit holes / Não escopo (engenharia)
- **Não adicionar mecanismo de ordenação/anti-out-of-order** (recusar SHA não-descendente, fila ordenada, timestamp): decisão explícita da intenção — o `flock` serializa e a fila natural do verify ordena; o risco vai documentado com gatilho.
- **Não refatorar o miolo do script** (`flock`, migrator→migrate→runner, rollback, smoke, cleanup): o pipeline acabou de ser recuperado (#952/#953) e o appetite não cobre; tocar só os guards e os comentários.
- **Não reintroduzir verifier automático de `main`** nem deploy automático; não mexer no `verify`.
- **Não editar histórico:** `docs/postmortems/2026-09-12-deploy-build-importmap.md`, `docs/changelog/2026-09-12-*`, `docs/CHANGELOG-AGENTS-HISTORY.md`, planos `ops53`/`ops65`/`ops66`/`ops71`/`ops103` (menções ao guard ali são registro).
- **Não mexer no guard "already deployed"** nem no `ciSkipInvariants` (não muda).
- **Não transformar o pin negativo em dogma:** `not.toContain('git ls-remote')` pina o contrato **atual** (dispatch deliberado); o comentário no spec diz que, se um dia um verifier automático voltar, é ali que o contrato se reavalia — sem abrir porta para skip verde.
## Riscos e mitigação
- **Regressão do falso verde #953** (verde sem deploy): mitigação = pin negativo explícito + pin do **único `exit 0`** (só o "already deployed", que prova que o container roda o SHA) + manutenção do pin positivo do bloco `l.32-38`; não existe mais nenhum caminho de skip silencioso.
- **Over-deletion na remoção** (levar `flock`/already-deployed junto): mitigação = diff focado na Fase 1 + pins positivos de `flock` e "already deployed" no mesmo spec + `bash -n`.
- **Dispatch fora de ordem pode regredir prod** (SHA antigo re-dispatchado após deploy mais novo): aceito e documentado na tabela "Falhas conhecidas" com gatilho de revisita; fora de escopo por decisão (não engenhar agora).
- **Drift de docs** (menção órfã a "HEAD guard"/"stale run"): mitigação = grep da Fase 3 e revisão do PR.
- **O verify do `deploy.yml` não é exercitado no CI de PR:** mitigação = `bash -n` + pins unitários; a prova ao vivo é o dispatch manual pós-merge (aceite final humano).
## Aceite de engenharia
- [ ] `scripts/deploy-homeserver.sh` sem os dois blocos de stale run (pré e pós-flock) e sem menção a HEAD guard nos comentários (header de fluxo e `set-url`); `flock` e "already deployed" intactos
- [ ] `.github/workflows/deploy.yml` com comentário atualizado; `workflow_dispatch`-only intacto (`ciSkipInvariants` verde sem mudanças); invocação `l.159` intocada
- [ ] `tests/unit/deployScript.unit.spec.ts`: pins negativos + `exit 0` único + `flock` verdes, comprovadamente RED contra o script pré-remoção; spec "already deployed" (`l.32-38`) preservada
- [ ] Runbook (fluxo `l.20-22` + linha out-of-order em "Falhas conhecidas") e `docs/AGENT-OPS.md` (`l.81`, `l.110`) alinhados; grep de drift vazio fora do histórico
- [ ] `docs/changelog/2026-09-12-ops102.md` criado; agregado/HISTORY/históricos intocados
- [ ] `pnpm gate:fast` verde; `pnpm push` verde; PR `Closes #962` base `main`
- [ ] (humano, pós-merge) dispatch manual do `deploy.yml`: `verify` verde + job `deploy` concluído com a revision do SHA do run — critério final da Issue
---
### Self-score de decision-quality: 4/5
- **Decisões caras têm rejeitadas?** ✓ — as 3 decisões têm opções nomeadas e rejeitadas com razão de morte (warn/condicional, confiar no e2e, só apagar docs).
- **Cabe no appetite?** ✓ — ~0,5 dia: remover ~8 linhas, reescrever 2 specs, ajustar 4 docs vivas + changelog; sem migration/UI/schema.
- **Rabbit holes nomeados?** ✓ — out-of-order, refactor do script, verifier automático, histórico, dogma do pin.
- **Depth check?** ✓ — nenhum módulo/utilitário novo; edita o dono de cada contrato (script, spec, runbook, AGENT-OPS), sem pass-through.
- **Intenção satisfeita?** ✓ — dispatch roda até o fim com o SHA do run; único verde sem build é o "already deployed"; registro vivo alinhado.
- **Não dou 5 porque** — o cenário ao vivo (main andando durante o verify) não é reproduzível deterministicamente no CI: a prova fica nos pins + no próximo dispatch manual pós-merge, e o risco out-of-order é aceito sem mecanismo por decisão documentada (não por omissão).

View file

@ -0,0 +1,104 @@
# OPS102 — Deploy manual roda até o fim mesmo com main à frente (sem guard de stale run)
Status: rascunho
Atualizado em: 2026-09-12
Issue: #962
Priority: P1
Impeccable: A — N/A sem UI
Rascunho UI: N/A — sem UI
Appetite: ~0,5 dia eng; um outcome verificável
Responsável: —
## Intenção
O deploy manual falha quando o HEAD do `main` anda depois do momento em que a action foi disparada: _"Looks like the manual deploy flow fails when the main head is ahead of the moment when the action was deployed. That made sense when it was automatic, but now that it is manual, it should run til the end, even when main moves."_
O guard de stale run nasceu na era automática (OPS53): `main` andava sozinho e publicar um SHA velho era errado. A OPS71 tornou o deploy um `workflow_dispatch` deliberado — o operador escolhe o SHA —, mas o guard ficou: hoje, se alguém mergeia em `main` durante os ~50 min do `verify`, o job `deploy` morre com "stale run" mesmo com o dispatch legítimo. A premissa caducou; o dispatch manual deve rodar até o fim com o SHA do run.
## Persona e fluxo
- **Persona / contexto:** operador do deploy — humano que dispara o workflow no GitHub Actions depois de mergear algo que precisa ir a prod; espera ~50 min de `verify` e mais o build no homeserver, hoje torcendo para `main` não andar nesse meio tempo.
- **Job principal:** publicar o SHA que ele deliberadamente escolheu, sem ser sabotado por merges alheios no meio do verify.
- **Fluxo desejado:** dispara o deploy → `verify` roda a suíte full → o job `deploy` publica o SHA do run até o fim, mesmo se `main` avançou no meio → vê verde só porque prod de fato roda o SHA; num re-dispatch do mesmo SHA, vê "already deployed" e nada é reconstruído.
- **Anti-goals de produto:** não voltar a ser deploy automático; não criar mecanismo novo de ordenação de dispatches; não voltar ao falso verde do #953 (skip silencioso com job verde e prod no build velho).
## Objetivo e aceite
- Um dispatch manual do `deploy.yml` completa o deploy do SHA do run mesmo que `main` avance durante o verify — sem "stale run" abortando.
- Sem falso verde: job verde = o SHA do run foi de fato publicado (build + rollout + smoke) ou o container já o rodava ("already deployed") — nunca skip silencioso.
- O guard "already deployed" permanece: container já roda a revision do SHA → no-op verde.
- Nenhum mecanismo novo anti-out-of-order entra neste item.
- Registro vivo alinhado: comentários do workflow/script, runbook (fluxo + "Falhas conhecidas") e `AGENT-OPS` deixam de descrever o guard removido; as specs unitárias pinam o contrato novo sem perder o pin do "already deployed".
## Dados (intenção)
- **Vou apresentar dados?** Não — item de infraestrutura de deploy; sem superfície de dados de produto e sem métrica que desbloqueie decisão.
- **Decisões desbloqueadas:** N/A — nenhuma escolha de produto depende de dado aqui.
- **Forma:** N/A — nada a apresentar.
## Dados da decisão (literais)
- ID reservado: **OPS102**; kind **chore**; sem UI (Impeccable A).
- Gatilho: `workflow_dispatch` manual do `.github/workflows/deploy.yml` — o operador escolhe o SHA; não há verifier automático de `main` (OPS71).
- Remover de `scripts/deploy-homeserver.sh` os dois guards de stale run. Pré-flock (l.49–52):
```bash
main_head="$(git ls-remote "$TEQO_REPO_URL" refs/heads/main | awk '{print $1}')"
if [ "$main_head" != "$SHA" ]; then
fatal "stale run: main is $main_head, job deploys $SHA — refusing to deploy an outdated SHA"
fi
```
- Pós-flock (l.57–60): a mesma comparação, com `fatal "stale run after lock: main is $main_head, job deploys $SHA — refusing to deploy an outdated SHA"`. O comentário de fluxo l.11–12 ("HEAD guard … stale run FAILS the job") deixa de valer e é atualizado.
- Preservar o guard "already deployed" (l.70–74) — permanece intacto:
```bash
running_rev="$(docker inspect -f '{{index .Config.Labels "org.opencontainers.image.revision"}}' teqo-1313 2>/dev/null || true)"
if [ -n "$running_rev" ] && [ "$running_rev" = "$SHA" ]; then
say "already deployed: teqo-1313 runs $SHA — nothing to do"
exit 0
fi
```
- `.github/workflows/deploy.yml`: atualizar o comentário l.23–25 ("HEAD guard only deploys when the dispatched SHA is main's HEAD (a stale dispatch skips)"); a invocação do job `deploy` (l.159, `bash scripts/deploy-homeserver.sh "$GITHUB_SHA"`) não muda.
- `tests/unit/deployScript.unit.spec.ts`: as specs l.19–23 e l.25–30 (pinam `fatal "stale run` 2× e a ausência de `say "stale run`) passam a pinar o contrato novo (deploya o SHA do dispatch mesmo com `main` à frente); a spec l.32–38 ("already deployed") permanece. `ciSkipInvariants.unit.spec.ts` (pina só `workflow_dispatch:`) não muda.
- `docs/ops/teqo-1313-deploy.md`: atualizar o fluxo (l.20–22) e a linha "Job verde sem deploy ('stale run')" da tabela "Falhas conhecidas" (l.132); `docs/AGENT-OPS.md` l.81 e l.110 citam "HEAD guard" — atualizar.
- Histórico intocável: `docs/postmortems/2026-09-12-deploy-build-importmap.md` e os `docs/changelog/2026-09-12-*` são registro — a entrega escreve uma entrada nova `docs/changelog/<data>-ops102.md`, nunca edita os existentes.
## Direção no codebase (hipótese)
- **Áreas prováveis:** `scripts/deploy-homeserver.sh` (guards + comentário de fluxo), `.github/workflows/deploy.yml` (comentário HEAD), `tests/unit/deployScript.unit.spec.ts`, `docs/ops/teqo-1313-deploy.md`, `docs/AGENT-OPS.md`.
- **Precedente a olhar:** OPS65 (guard "already deployed" — o no-op idempotente que fica), OPS66/OPS71 (dispatch manual e build-after-migrate — contratos que não mudam), #953/#952 (o fix recente que tornou o stale run `fatal`; agora reverte-se só a parte que a era manual tornou obsoleta).
- **Risco de acoplamento:** o miolo do script (flock, migrator→migrate→runner, rollback, smoke) não muda; remover o guard não é licença para refatorar o pipeline nem para enfraquecer os pins de segurança existentes.
## Dependências
- Nenhuma. Histórico: #953 (tornou o stale run fatal) e #952 (mesmo postmortem) já estão em `main`; OPS65, OPS66, OPS71 e OPS99 ficam intactos.
## Fora de escopo
- Qualquer mecanismo novo de ordenação/anti-out-of-order de dispatches (o `flock` serializa; a fila natural do verify ordena) — risco declarado, não feature.
- Reintroduzir verifier automático de `main` ou deploy automático.
- Mudar o `verify`, o build da imagem, a ordem migrator→migrate→runner, rollback ou smoke.
- Editar postmortem/changelog históricos.
## Rabbit holes de produto
- **"Já que o guard saiu, qualquer SHA pode."** Se a remoção virar licença para dispatchar SHA velho/arbitrário, a regressão por fora-de-ordem deixa de ser teórica. **Corte neste item:** a remoção é sobre `main` avançar durante o verify, não sobre ignorar ordem; nenhum guard novo entra, mas o risco fica escrito no runbook.
- **"Aproveitar e enxugar o script."** Refatorar flock/migrate/build/rollback de passagem explode o appetite e arrisca o pipeline recém-recuperado. **Corte:** tocar só os guards e a documentação viva.
- **"Pôr um guard de ordem no lugar."** Substituir o stale run por outro mecanismo (fila ordenada, comparação de timestamp, recusa de SHA não-descendente) é a tentação simétrica. **Corte:** não — dispatch é ato humano deliberado e raro; a decisão é explicitamente não adicionar mecanismo.
## Questões em aberto (produto)
- **Dispatch duplicado fora de ordem pode regredir prod?** Um SHA antigo re-dispatchado depois de um deploy mais novo regride prod: o `flock` serializa mas não ordena, e o "already deployed" não pega revision diferente. **Opções:** A) não adicionar mecanismo agora — dispatch é ato humano deliberado e raro e a fila natural do verify ordena os dispatches; B) adicionar guard de ordem (recusar SHA não-descendente do que roda); C) restringir o dispatch na UI ao SHA atual. **Recomendação:** A, deixando o risco explícito na tabela "Falhas conhecidas" com o gatilho para revisitar — se o deploy ganhar frequência/automação, ou se uma regressão fora-de-ordem acontecer de fato. _(assumido — validar com produto)_
## Referências
- GitHub Issue #962
- `scripts/deploy-homeserver.sh` — guards atuais (l.49–52, l.57–60), "already deployed" (l.70–74), comentário de fluxo (l.11–12)
- `.github/workflows/deploy.yml` — comentário HEAD (l.23–25) e job `deploy` (l.159)
- `tests/unit/deployScript.unit.spec.ts` — pins do stale run (l.19–30) e do "already deployed" (l.32–38)
- `docs/ops/teqo-1313-deploy.md` — fluxo (l.20–22) e "Falhas conhecidas" (l.132)
- `docs/postmortems/2026-09-12-deploy-build-importmap.md` — falso verde e contexto do #953
- `docs/AGENT-OPS.md` (l.81, l.110) — menções ao "HEAD guard"
- `docs/plans/ops53-ci-deploy-homeserver.md` / `…-impl.md` — origem do guard (era automática); `docs/plans/ops65-ci-main-janela-30min-e-matar-pool-impl.md` — origem do "already deployed"

View file

@ -0,0 +1,131 @@
# Impl: OPS103 — Staging no homeserver com verify único e aprovações separadas
Status: aprovado
Atualizado em: 2026-09-12
Issue: #968
Intenção: docs/plans/ops103-staging-homeserver.md
Appetite restante: herdado (~2–3 dias eng no repo + bootstrap ops no homeserver; sem migration, sem schema, sem UI)
## Leitura da intenção
- **Outcome:** um dispatch único do `deploy.yml` roda o `verify` uma vez e gateia `deploy-staging` → `deploy-production`; produção só depois de staging verde e do environment `production` aprovado; o mesmo script parametrizado por ambiente executa os dois deploys sem mudar os defaults de produção.
- **O que NÃO negociar:** `verify` intocado; runner self-hosted só nos deploys (nunca no PR CI); envs de staging só no homeserver (nunca GitHub secrets); staging sem PII real, não indexável, bucket `teqo-media-staging` próprio; ordem migrator→migrate→runner (OPS66) e rollback por ambiente; `workflow_dispatch`-only; produção `teqo-1313`/`teqo_1313`/`~/stack/teqo-1313.env`/1313 intocados.
- **O que reavaliar:** a intenção fala em environments `deploy-staging`/`deploy-production` — os nomes reais no GitHub são `staging` e `production`; e "serviços no compose `~/stack`" implica um único `docker-compose.yml` compartilhado, o que muda a decisão de lock (Decisão 2) e exige sed ancorado por serviço (Decisão 4).
## Abordagem recomendada
```mermaid
flowchart LR
D["workflow_dispatch (main)"] --> V["verify hosted — suíte full (intocado)"]
V -->|success| S["deploy-staging<br/>environment: staging · TEQO_ENV=staging"]
S -->|success| P["deploy-production<br/>environment: production (reviewer) · TEQO_ENV=production"]
S -->|fail| X["produção nunca roda (fail-closed)"]
S -. "bash deploy-homeserver.sh $GITHUB_SHA" .-> R["script único parametrizado"]
P -. idem .-> R
R --> F["migrator build → migrate → runner build → rollout → smoke (por ambiente, OPS66)"]
```
**Opções consideradas:** decisões A/B/C abaixo.
**Recomendação:** parametrizar o script por env vars com defaults de produção (D1); locks por ambiente + `concurrency` de grupo único nos jobs de deploy (D2); dois jobs explícitos com `environment:` + `TEQO_ENV` por job (D3); sed ancorado por serviço (imagens) e por range (label de revision) (D4); noindex via `robots.ts` + metadata condicionados à URL de staging (D5); pins estendendo os specs donos (D6).
**Rejeitadas:** por decisão.
### Decisão 1 — como parametrizar o script
- **Opções:** A) env vars com defaults de produção, derivadas num mapa `case "${TEQO_ENV:-production}"` no topo; B) flags CLI `--env staging` (default produção); C) dois scripts (proibido pela intenção); D) env vars sem defaults.
- **Recomendação:** **A** — `bash scripts/deploy-homeserver.sh "$SHA"` continua idêntico em produção (defaults atuais preservados) e o workflow passa `TEQO_ENV` por job. Mapa: `TEQO_CONTAINER`, `TEQO_MIGRATE_SERVICE`, `TEQO_ENV_FILE`, `TEQO_IMAGE_REPO` (+ `TEQO_REGISTRY=localhost:5000`), `TEQO_BUILD_PROXY`, `TEQO_BUILD_PROXY_PORT`, `TEQO_SMOKE_BASE`, `TEQO_LOCK`; `STACK_DIR`/`WORKSPACE_DIR`/`TEQO_REPO_URL` seguem compartilhados. `TEQO_ENV` inválido → `fatal` (fail-closed). O nome do DB não entra no script (vive no env file).
- **Rejeitadas:** B porque muda a invocação canônica (pins e runbook) por uma ergonomia que o `env:` do job já resolve; C porque a intenção proíbe gêmeo; D porque quebra produção (nenhum default).
### Decisão 2 — serialização entre ambientes
- **Opções:** A) um `flock` compartilhado (`/tmp/teqo-deploy.lock`) + `concurrency: {group: deploy-homeserver, cancel-in-progress: false, queue: max}` nos dois jobs de deploy; B) um lock por ambiente; C) só `concurrency`.
- **Recomendação:** **A** — o `docker-compose.yml` de `~/stack`, o workspace `~/teqo-deploy` e o registry `localhost:5000` são compartilhados: o swap/rollback de um ambiente reescreve o arquivo que o outro usa, e dois builds concorrentes estouram o homeserver 8c/16GB (OOM já documentado no runbook). O lock único serializa os deploys inclusive na invocação manual no host (que não passa pelo `concurrency`); a `concurrency` com `queue: max` enfileira runs em vez de cancelar o pending (o default `single` cancela um pending a cada dispatch novo, mesmo com `cancel-in-progress: false` — descoberto na revisão do /simplify) e não bloqueia o `verify` hosted de um run novo.
- **Rejeitadas:** B porque locks por ambiente não protegem os recursos compartilhados (a razão de existirem) e a independência não é um requisito — os deploys já se encadeiam por `needs`; C porque deixaria a invocação manual sem serialização.
- **Revisão /simplify (2026-09-12):** a versão inicial do plano previa lock por ambiente; os revisores apontaram a corrida no compose/workspace compartilhado e o cancelamento de pending do `queue: single` — corrigido para lock único + `queue: max`.
### Decisão 3 — como o workflow passa o ambiente
- **Opções:** A) dois jobs explícitos — `deploy-staging` (`environment: staging`, `TEQO_ENV: staging`) e `deploy-production` (`environment: production`, `needs: [deploy-staging]`, `TEQO_ENV: production`), ambos com guard `github.ref == 'refs/heads/main'` e `verify` intocado; B) manter o job `deploy` de produção e adicionar só o `deploy-staging`; C) input `environment` no dispatch ou workflow por ambiente.
- **Recomendação:** **A** — simetria entre alvos irmãos; o gate de aprovação fica no environment (ortogonal ao `TEQO_ENV` que o script lê) e o `needs` encadeia fail-closed. Reviewer obrigatório só em `production` (config do repo, não do YAML; bootstrap cria os dois environments).
- **Rejeitadas:** B porque um job chamado `deploy` que na verdade é produção e outro qualificado confunde runbook/pins; C porque um input permitiria pular staging ou escolher alvo (viola o aceite) e workflow por ambiente duplicaria o `verify` — o ponto da intenção.
### Decisão 4 — sed do compose compartilhado
- **Opções:** A) padrões derivados por ambiente (`TEQO_REGISTRY`/`TEQO_IMAGE_REPO`, migrator antes do runner) e o label `org.opencontainers.image.revision` trocado por range ancorado ao bloco do serviço (`/^ $TEQO_CONTAINER:/,/^ [A-Za-z0-9_-]+:/`); B) manter o sed global atual; C) editar YAML com `yq`/python.
- **Recomendação:** **A** — sem o range, um deploy de staging carimbaria o label de revision do serviço de produção (o guard "already deployed" leria um SHA mentiroso). Os `grep -q` pós-swap passam a checar `image: $TEQO_REGISTRY/$TEQO_IMAGE_REPO(-migrator):$SHA`; o bootstrap exige labels por serviço, sem âncora YAML.
- **Rejeitadas:** B porque corrompe o label do outro ambiente; C porque adiciona dependência ao host por um ganho que sed ancorado entrega.
### Decisão 5 — onde vive o noindex de staging
- **Opções:** A) `src/app/robots.ts` (mapeia `/robots.txt`; Next 15 só reconhece metadata route files na raiz do app dir — route group não entra no match) + `robots` do metadata do layout condicionados por `src/lib/siteEnvironment.ts` (hostname começa com `staging.`); B) só header `X-Robots-Tag` no tunnel Cloudflare; C) nada (sem links públicos).
- **Recomendação:** **A** — versionado, testável em unit e efetivo para crawlers que respeitam robots/metadata; o header no tunnel fica como defesa em profundidade opcional no bootstrap (documentado no runbook). A URL de staging é a identidade que o build já carrega (`NEXT_PUBLIC_SITE_URL`), então não há env nova para esquecer (fail-closed: qualquer host `staging.*` desindexa).
- **Rejeitadas:** B porque vive fora do repo (não testável/versionado) e não cobre acesso direto à origem; C porque o aceite exige "não indexável".
### Decisão 6 — pins
- **Opções:** A) estender `tests/unit/deployScript.unit.spec.ts` (defaults de produção idênticos, mapa de staging, sed ancorado, env inválido fail-closed) e `tests/unit/ciSkipInvariants.unit.spec.ts` (dois jobs, environments, `needs`, `TEQO_ENV`, guard de main); B) novo spec só do workflow; C) sem pins.
- **Recomendação:** **A** — cada spec fica no dono do contrato que já pina (script/workflow), em unit puro (leitura do arquivo). O pin de ordem OPS66 passa a ancorar em marcadores estáveis (`--profile maintenance run --rm`, `lastIndexOf('docker compose up -d')`), porque `indexOf('teqo-1313-migrate')` passaria a achar o mapa no topo.
- **Rejeitadas:** B porque espalha o contrato do mesmo workflow em dois donos; C porque a única rede do script é unit (nenhum e2e o exercita).
### Componentes / mudanças
- **`scripts/deploy-homeserver.sh`** (dono do fluxo): mapa `TEQO_ENV` no topo; toda ocorrência de `teqo-1313`/porta/lock/proxy/smoke/cleanup vira variável; sed de imagens ancorado; revision por range; produção default idêntica.
- **`.github/workflows/deploy.yml`**: header comentado; `verify` intocado; `deploy` renomeado para `deploy-production` + novo `deploy-staging`, com `environment`, `TEQO_ENV`, `needs`, guard de `main` e `concurrency`.
- **`src/lib/siteEnvironment.ts`** (novo): `isStagingSiteUrl(url)` puro + `isStagingSite()` (lê `NEXT_PUBLIC_SITE_URL`).
- **`src/app/robots.ts`** (novo — raiz do app dir, exigência do Next 15 para metadata routes) + **`src/app/(frontend)/layout.tsx`**: `disallow: /` e `index:false` quando staging.
- **Testes**: os dois specs acima + `tests/unit/siteEnvironment.unit.spec.ts` (predicado + pin de que robots/layout consomem o helper).
- **Docs**: `docs/ops/teqo-1313-deploy.md` (seção Staging + bootstrap + limites), `docs/AGENT-OPS.md` (ladder e linha do `deploy.yml`), `AGENTS.md`/`AGENTS-infra.md`, `.env.example` (bucket `teqo-media-staging`), `docs/changelog/<data>-ops103.md`.
- **Migration:** nenhuma. **Access/Consent:** N/A (não toca Payload). **UI:** Impeccable A — robots/metadata não é UI visual.
### Dados → forma
N/A (sem UI).
## Fases verificáveis
1. **Script + spec (RED primeiro):** mapa por ambiente, sed ancorado, proxy/lock/smoke/cleanup parametrizados; atualizar `deployScript.unit.spec.ts` (mapa de staging e ordem OPS66 falham antes do refactor). Verificação: `bash -n scripts/deploy-homeserver.sh`; `pnpm test:unit -- tests/unit/deployScript.unit.spec.ts` verde.
2. **Workflow + pin:** `deploy-staging`/`deploy-production` com environments/`needs`/guard/`concurrency`; estender `ciSkipInvariants.unit.spec.ts`. Verificação: unit verde + `pnpm lint`.
3. **noindex:** helper + `robots.ts` + metadata do layout + spec. Verificação: `pnpm test:unit -- tests/unit/siteEnvironment.unit.spec.ts`.
4. **Docs + changelog:** runbook (fluxo, identidades, bootstrap, limites), AGENT-OPS, AGENTS, `.env.example`, entrada de changelog.
5. **Gates** — `pnpm gate:fast`; push via `pnpm push`; PR `Closes #968` base `main`.
6. **Aceite humano pós-merge (bootstrap ops, fora do repo):** criar DB `teqo_staging`, serviços no compose `~/stack`, `~/stack/teqo-staging.env`, bucket Garage `teqo-media-staging`, ingress/DNS `staging.jorgesolla1313.com.br`, environments `staging`/`production` (reviewer `fsolla`); migrate+seed iniciais (proxy 5434 + `pnpm db:seed:minimal` — passa no guard local via `127.0.0.1`, sem `ALLOW_REMOTE_DB`) antes do 1º dispatch; dispatch → staging em `:1314` → inspeção → aprovação → prod no mesmo SHA; `curl https://staging.jorgesolla1313.com.br/robots.txt` = `Disallow: /`.
## Rabbit holes / Não escopo (engenharia)
- e2e contra staging, branch `stage`/PR-to-stage, preview por PR, cópia de dados de prod (fora de escopo da intenção).
- Segundo workflow/script, proxy/compose gêmeo por ambiente, lock único global, `NEXT_PUBLIC_SITE_ENV` nova.
- GitHub secrets para staging; envs fora do homeserver; runner self-hosted fora do deploy; tocar o `verify`.
- Refatorar o miolo do script além da parametrização (ordem OPS66, rollback, guard "already deployed", BuildKit) — o único default que muda é o derivado.
- `yq`/python para editar YAML; validar WebAuthn/OAuth/Resend no staging (limites documentados no runbook).
## Explicitamente fora (triage pós-simplify, 2026-09-12)
Achados dos revisores estruturais/qualidade que **não** viraram Issue nova — decisão autônoma do ator `work-issue` pela triage do `capture-review-debts`, sem editar a Issue #968 (in-progress):
| ID | Achado | Destino | Racional / gatilho |
| --- | -------------------------------------------------------------------------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| A | noindex fail-open: `staging.*` é heurística de hostname; URL ausente/malformada indexa | defer | D5 escolheu a URL como identidade do build (sem env nova); o bootstrap exige a env. Gatilho: staging mudar para domínio sem prefixo `staging.` ou crawler indexar |
| B | pins do compose swap são textuais (sem harness de fixture) | defer | Prova manual com fixture na sessão + pins de contrato. Gatilho: próxima mudança na lógica de sed/swap |
| C | `.` do registry não escapado em ERE (`localhost:5000`) | descartar | Comportamento idêntico ao pré-OPS103; registry controlado por ops — cosmético |
| D | sem e2e de `/robots.txt` | defer | Unit chama `robots()` comportamentalmente; e2e provaria wiring do Next. Gatilho: e2e passar a tocar metadata route |
| E | gate de aprovação de produção vive só no environment (config do repo, fora do YAML) | defer | D3 decidiu reviewer no repo, não no YAML; runbook documenta que environment sem reviewer é fail-open. Gatilho: environment `production` perder o reviewer ou deploy sem aprovação |
| F | staging pode subir vazio se o seed do bootstrap (passo 7) for pulado | defer | Runbook exige migrate+seed antes do 1º dispatch. Gatilho: 1º dispatch real de staging — se subir vazio, seed vira passo do deploy |
## Riscos e mitigação
- **Regressão silenciosa no deploy de produção** (script parametrizado): defaults prod pinados no unit + `bash -n` + prova RED + o staging do mesmo dispatch exercita o mesmo caminho antes de produção.
- **Sed tocando a linha/label do outro ambiente:** padrões ancorados por `TEQO_IMAGE_REPO` + range do label + `grep -q` pós-swap + backup/rollback; bootstrap exige labels por serviço sem âncora YAML.
- **Runs concorrentes** (compose/workspace/build compartilhados): `concurrency: deploy-homeserver` sem cancel + locks por ambiente; risco residual aceito — aprovação de produção segura o slot e o operador dispara um run por vez.
- **Staging indexável ou com PII:** robots + metadata condicionados à URL; bucket/DB/env próprios; seed sintético; checklist de bootstrap marca reviewer do `production` antes do 1º dispatch (environment sem reviewer é fail-open e vira critério de aceite).
- **Custo/OOM no homeserver** (2 builds por ambiente, 4 por dispatch): serialização, idempotência e cleanup pós-deploy por ambiente; re-dispatch se OOM.
- **Drift de docs/runbook:** grep de menções a `deploy`/`teqo-1313` nas docs vivas na Fase 4 + revisão do PR.
## Aceite de engenharia
- [ ] Aceite de produto da intenção ainda coberto
- [ ] Invariantes AGENTS/engineering-standards
- [ ] Testes de domínio previstos (unit/int) onde access/write paths mudam — aqui: unit do script, do wiring do workflow e do noindex; sem access/Consent
- [ ] `bash scripts/deploy-homeserver.sh "$SHA"` idêntico em produção (defaults e único `exit 0` preservados); staging mapeado e `TEQO_ENV` inválido fail-closed
- [ ] `deploy.yml`: `verify` intocado; dois deploys com `environment: staging`/`production`, `needs`, `TEQO_ENV` e guard `main`; pin novo no `ciSkipInvariants`
- [ ] Staging noindex (robots + metadata) testado; produção com `index:true` inalterado
- [ ] Runbook/AGENT-OPS/AGENTS/`.env.example` alinhados; changelog criado; PR `Closes #968`
- [ ] (humano) bootstrap ops + dispatch real: staging verde → aprovação → produção no mesmo SHA; staging não indexável

View file

@ -0,0 +1,98 @@
# OPS103 — Staging no homeserver com verify único e aprovações separadas
Status: rascunho
Atualizado em: 2026-09-12
Issue: #968
Priority: P1
Impeccable: A — N/A sem UI
Rascunho UI: N/A — sem UI
Appetite: ~2–3 dias eng no repo + bootstrap ops no homeserver
Responsável: —
## Intenção
_"Lets set up a staging environment. What would be the best way to do it? Can we use the same verify step for both staging and prod environment deploys? But approve each deploy separately?"_
Hoje o repo tem só dois alvos: o banco mínimo sintético (CI/PR) e produção. Uma migration só encontra o schema real no deploy de produção — o defeito de build/rollout/migração é descoberto no alvo mais caro. O staging no homeserver dá um alvo real e descartável (mesmo SHA, mesma stack, banco e bucket próprios) antes de produção.
A resposta ao "best way": sim, o `verify` é do **commit**, não do alvo — fica intocado e gateia os dois deploys num único `workflow_dispatch`; o que muda entre ambientes é o deploy. A separação de aprovações vem dos GitHub Environments: `deploy-staging` e `deploy-production` com gates independentes, e produção só depois de staging verde.
## Persona e fluxo
- **Persona / contexto:** operador do deploy (o mesmo humano de OPS102), decidindo publicar um SHA e esperando ~50 min de `verify`.
- **Job principal:** validar o SHA num ambiente real antes de aprovar produção, sem rodar o verify duas vezes.
- **Fluxo desejado:** dispatch do `deploy.yml` em `main` → `verify` full → `deploy-staging` sobe o SHA em `staging.jorgesolla1313.com.br` → humano inspeciona site/login/migração aplicada → aprova o environment `production` → `deploy-production` publica o mesmo SHA em produção. Staging vermelho = produção nunca roda.
- **Anti-goals de produto:** não é deploy automático; não é branch/PR `stage` (precedente morto); não é um segundo pipeline ou script gêmeo; não substitui o `verify`; não é ambiente com PII real.
## Objetivo e aceite
- Um único dispatch do `deploy.yml` roda o `verify` (intocado) uma vez e gateia os dois deploys: `verify` → `deploy-staging` → `deploy-production`.
- Aprovações separadas por GitHub Environments: cada deploy tem seu próprio environment; produção só roda com o `production` aprovado e depois de staging verde (`needs`).
- O mesmo script parametrizado por ambiente executa os dois deploys (edit-the-owner, sem gêmeo); invocação e defaults atuais de produção não mudam.
- Migração validada em staging antes de tocar produção: em cada ambiente a ordem migrator→migrate→runner (OPS66) é preservada.
- Falha em staging é fail-closed para produção e faz rollback só do staging.
- Guardrails: staging nunca recebe PII real; staging não é indexável; envs de staging vivem no homeserver, nunca como GitHub secrets; runner self-hosted só no deploy (nunca no PR CI); build próprio por ambiente (mesmo SHA, imagens e `NEXT_PUBLIC_SITE_URL` de cada alvo); bucket próprio.
- Runbook e docs vivos descrevem o fluxo de staging e o bootstrap ops do homeserver.
## Dados (intenção)
- **Vou apresentar dados?** Não — item de infraestrutura de deploy; sem superfície de dados de produto.
- **Decisões desbloqueadas:** operador decide promover um SHA a produção depois de vê-lo rodando em staging.
- **Forma:** N/A — nada a apresentar.
## Dados da decisão (literais)
- ID reservado: **OPS103**; kind **chore**; sem UI (Impeccable A); slug `ops103-staging-homeserver`.
- `.github/workflows/deploy.yml`: `verify` (hosted, full, intocado) → `deploy-staging` (`environment: staging`) → `deploy-production` (`environment: production`, required reviewer `fsolla`, `needs: [deploy-staging]`); ambos os deploys restritos à branch `main`.
- Identidades de staging (novas): container/serviço `teqo-staging`, migrator `teqo-staging-migrate`, DB `teqo_staging`, env `~/stack/teqo-staging.env`, porta `127.0.0.1:1314`, imagens `localhost:5000/teqo-staging:$SHA` e `localhost:5000/teqo-staging-migrator:$SHA`.
- Produção intocada: `teqo-1313`/`teqo-1313-migrate`, DB `teqo_1313`, `~/stack/teqo-1313.env`, `127.0.0.1:1313`, imagens `localhost:5000/teqo-1313(-migrator):$SHA` — defaults atuais do script.
- `scripts/deploy-homeserver.sh`: script único parametrizado por ambiente (env file, container/serviço, DB, proxy, tags, compose, base do smoke); sem script gêmeo.
- URL pública: `https://staging.jorgesolla1313.com.br` atrás do mesmo Cloudflare tunnel (ingress novo), `NEXT_PUBLIC_SITE_URL` de staging; `noindex` (robots).
- Mídia: bucket próprio `teqo-media-staging` — nunca compartilhar o bucket de produção (`.env.example`: "never share the production bucket across environments").
- Dados de staging: sintéticos (`db:seed:minimal`/demo); PII real de apoiadores nunca entra (LGPD). Cópia de prod sem PII fica como opção futura.
- Bootstrap do homeserver (DB `teqo_staging`, serviços no compose `~/stack`, env file, bucket no Garage, ingress/DNS do tunnel) é trabalho OPS fora do repo, executado na aceitação e documentado no runbook — o executor do item não faz infra a partir do código.
- Dependência dura: OPS102 (#962) remove o guard de stale run; sem ele o deploy de produção aborta quando `main` anda durante a janela longa de promoção (verify + staging + inspeção + aprovação + prod).
## Direção no codebase (hipótese)
- **Áreas prováveis:** `.github/workflows/deploy.yml` (jobs + environments), `scripts/deploy-homeserver.sh` (parametrização), `tests/unit/deployScript.unit.spec.ts` e `tests/unit/ciSkipInvariants.unit.spec.ts` (pins), `docs/ops/teqo-1313-deploy.md` (runbook), `docs/AGENT-OPS.md` + `AGENTS-infra.md`/`AGENTS.md` (ladder de ambientes), `.env.example` (nota do bucket de staging).
- **Precedente a olhar:** OPS53/OPS71 (script + dispatch manual), OPS66 (build-after-migrate), OPS65 ("already deployed"), OPS102 (#962, stale guard).
- **Risco de acoplamento:** não criar script/workflow gêmeo; não tocar defaults de produção; runner self-hosted continua exclusivo do deploy; nenhuma credencial nova no GitHub.
## Dependências
- OPS102 (#962) — dura: sem a remoção do stale run, a janela de promoção ultrapassa o guard e o deploy de produção falha quando `main` anda.
- Nenhuma outra.
## Fora de escopo
- e2e automatizado contra staging (o full continua no `verify`); carga, caos, multi-região.
- Branch `stage` / PR-to-stage / promote git — precedente morto (removido 2026-08-01); não ressuscitar.
- Cópia de dados de produção para staging (opção futura, com revisão LGPD).
- Preview environment por PR.
- Compartilhar DB, bucket ou imagem entre ambientes.
## Rabbit holes de produto
- **"Staging vira um segundo pipeline."** Duplicar workflow/script "para não mexer em produção" cria drift silencioso entre ambientes. **Corte neste item:** um workflow, um script, um parâmetro.
- **"Staging com dados reais é mais útil."** Cópia de prod carrega PII de apoiadores para um ambiente novo. **Corte:** sintético no v1; cópia anonimizada só como item futuro com revisão LGPD.
- **"Já que tem staging, todo PR vai pra lá."** Recria o fluxo branch `stage`/PR-to-stage que o repo matou. **Corte:** staging é alvo de promoção de um SHA de `main`, não destino de PR.
- **"Aproveitar e cobrir e2e/integrações externas no staging."** WebAuthn/OAuth/Resend são origin-bound e exigem configuração própria; transformar staging em espelho de prod explode o appetite. **Corte:** staging valida migração/build/rollout/smoke/inspeção; o resto fica explícito como não-validado.
## Questões em aberto (produto)
- **Staging tem reviewer próprio ou o dispatch é a aprovação?** **Opções:** A) sem reviewer no environment `staging` — o dispatch manual já é ato deliberado, e a aprovação que importa é a de produção; B) reviewer `fsolla` também no staging. **Recomendação:** A, com reviewer obrigatório só em `production`; revisitar se o staging passar a receber dados menos descartáveis. _(assumido — validar com produto)_
- **Dados do staging: sintético ou cópia sem PII?** **Opções:** A) sintético (`db:seed:minimal` + demo) no v1; B) cópia de prod com scrub de PII desde já; C) snapshot congelado sem PII. **Recomendação:** A — o objetivo é validar migração/build/rollout, que não depende da forma dos dados reais; B vira item futuro quando um bug concreto exigir volume/forma de produção. _(assumido — validar com produto)_
- **Domínio público ou só localhost?** **Opções:** A) `https://staging.jorgesolla1313.com.br` atrás do mesmo tunnel, com noindex; B) apenas localhost no homeserver (acesso por túnel/SSH), sem DNS. **Recomendação:** A — inspeção humana no browser e o comportamento real do tunnel fazem parte do valor; noindex + ausência de links públicos controlam a exposição. _(assumido — validar com produto)_
- **O que o staging NÃO valida?** **Opções:** A) assumir explicitamente: e2e automatizado, carga e integrações origin-bound (WebAuthn/passkeys, Google OAuth, Resend) sem configuração própria de staging; B) tentar cobrir e2e contra staging. **Recomendação:** A — e2e continua no `verify` (que valida o commit, não o alvo); documentar os limites no runbook para ninguém confundir "staging verde" com "produção garantida". _(assumido — validar com produto)_
## Referências
- GitHub Issue #962 (OPS102 — dependência)
- `docs/plans/ops102-deploy-manual-sem-stale-guard.md` — a dependência dura
- `.github/workflows/deploy.yml` — `verify` (l.40–142) e `deploy` (l.144–159); nenhum workflow usa `environment:` hoje
- `scripts/deploy-homeserver.sh` — hardcodes a parametrizar (env files l.79–80, container l.70/72/179/196/209/214/250/261, proxy l.122–127/137, tags l.152–160/168–169/202–203, compose l.164–171, smoke l.223–234, cleanup l.252)
- `tests/unit/deployScript.unit.spec.ts` e `tests/unit/ciSkipInvariants.unit.spec.ts` — pins do script e do deploy manual-only
- `docs/ops/teqo-1313-deploy.md` — runbook (zero menção a staging); `docs/AGENT-OPS.md` l.7–12 (ladder de 2 ambientes), l.80–81, l.100, l.110; `AGENTS-infra.md` l.5, l.25
- `.env.example` l.14–23 — "never share the production bucket across environments"; `src/utilities/mediaStorage.ts` — fail-closed das 4 envs S3
- `docs/plans/paradigma-agentes-paralelos.md` l.135–185 — precedente morto de `environment: stage` + `STAGE_DATABASE_URL` (não ressuscitar)

View file

@ -0,0 +1,127 @@
# Impl: Piloto da fonte: vídeos e transcrição minutada de um discurso da Câmara
Status: executado
Atualizado em: 2026-09-12
Issue: #954
Intenção: docs/plans/piloto-fonte-videos-camara.md
Appetite restante: herdado (~1 dia)
## Leitura da intenção
- **Outcome:** 2–3 discursos de legislaturas diferentes processados ponta a ponta (evento → trecho do orador → MP4 do VOD → transcrição com segmentos `início/fim/texto`), com relatório curto que responde as 4 incógnitas e mede custos/tempos. Nada em banco de produção; artefatos fora do git; o relatório commitado é o entregável durável.
- **O que NÃO negociar:** sem DB/Payload/collection/migration e sem `assertLocalDatabase`; 2–3 discursos (nunca o acervo); nenhuma mídia/HTML/JSON bruto commitado; crédito CC BY 4.0 no relatório e marca-d'água intocada; identificadores em inglês, strings pt-BR.
- **O que reavaliar (achados ao vivo que contradizem a intenção):**
1. `video-sob-demanda` **não é GET síncrono** — é _poll de geração assíncrona_ que devolve `{estado}` (`PRONTO|INDISPONIVEL|…`); o front polla a cada 3s por até ~2min e recarrega a página quando `PRONTO`. O plano trata como máquina de estados com backoff/limite, não como download direto.
2. A página de trecho (`?a=…&t=…`) respondeu **400 "Acesso via bot não permitido"** a UA de curl — há anti-crawl; exige UA de browser e talvez `crawl=no`/cookies. O caminho de evidência principal passa a ser a **página do evento** (âncoras server-rendered com `a`/`t`), que respondeu 200.
3. `uriEvento` vem **vazio** nos discursos 2023–2024 e `urlVideo`/`urlAudio` são nulos → o casamento discurso↔evento é **por data/hora**, não por id direto.
## Abordagem recomendada
```mermaid
flowchart LR
S[discurso 178857<br/>GET /deputados/.../discursos] --> E[evento do dia<br/>GET /eventos dataInicio=dataFim]
E --> P[página do evento<br/>âncoras ?a=&t= server-rendered]
P --> V[video-sob-demanda?idAudio=&trecho=<br/>poll estado]
V -->|PRONTO| M[MP4 do trecho]
M --> T[Deep Infra Whisper large-v3<br/>compat verbose_json]
T --> R[segmentos start/end/text + tempos/custos]
P -.->|sem trecho / sessão antiga| Y[YouTube urlRegistro<br/>offset = t/1000 − startTimestamp]
```
**Opções consideradas:**
- **A — CLI fino commitado: `scripts/pilot-camara-speeches.mjs` (orquestra I/O) + `scripts/lib/camaraSpeeches.mjs` (lógica pura), cache em `data/camara/` (gitignored), relatório em `docs/research/`.** **Recomendada.**
- **B — Scratch/one-off fora do repo (curl + um notebook descartável).** Rejeitada: sem evidência reproduzível, sem unit tests das regras (poll, offset, parser) e sem base para C153; contraria o espírito de "piloto documentado".
- **C — Estender `scripts/recover-media.mjs`.** Rejeitada: aquele script é acoplado a DB/S3/`assertLocalDatabase`; domínio errado, arrastaria Payload para o piloto.
**Recomendação: A** — o problema é um spike de fonte com regras puras e testáveis (parser das âncoras, montador de URL do VOD, offset YouTube, normalização dos segmentos), então o custo baixo de um módulo puro + script de orquestração já entrega os dois artefatos duráveis do piloto (código unit-testado + relatório) sem tocar o app.
**Decisões CARAS (cada uma com opções/recomendação/rejeitadas):**
- **(a) Áudio sem ffmpeg.** **A)** enviar o **arquivo do trecho VOD (MP4 curto) direto** ao Whisper multipart — o provedor faz o demux; o trecho é a fala do orador, curto, provavelmente abaixo do limite de tamanho. **B)** exigir `ffmpeg` local para extrair WAV. **C)** baixar áudio da sessão inteira no YouTube via lib. **Recomendação: A** — ffmpeg está ausente do repo e do Dockerfile (`apk add libc6-compat` só), B adiciona dependência de sistema e C adiciona dep pesada + sessão inteira. **Medir no piloto:** o Deep Infra aceita `video/mp4` no multipart e qual o tamanho do `linkParaDownload` (critério: transcrição 200 com segmentos para o trecho; se rejeitar o container, registrar o formato aceito e cair para B como pré-requisito manual _do piloto_, sem mudar repo/Dockerfile).
- **(b) Segmentos Deep Infra: compat vs nativo.** **A)** compat `POST /v1/openai/audio/transcriptions` com `model=openai/whisper-large-v3`, `language=pt`, `response_format=verbose_json` (+ `timestamp_granularities[]=segment`), shape `segments[{start,end,text}]`. **B)** nativo `/v1/inference/…` com `chunk_level: segment`. **C)** reusar `src/utilities/ai/deepInfraTranscribe.ts`. **Recomendação: A se devolver segmentos; B como fallback; C rejeitada** — o wrapper atual devolve só `{text}`, é `server-only` TS (exigiria tsx) e não expõe timestamps. **Medir no piloto:** presença de `segments[].start`/`.end` no compat (critério: ≥1 segmento com `start` e `end` numéricos); senão B com o mesmo critério.
- **(c) Local dos artefatos.** **A)** `data/camara/` no repo + entrada explícita `/data/camara/` no `.gitignore`. **B)** fora do repo (`/tmp`, `$HOME`). **C)** `private/`. **Recomendação: A** — não existe `/data/` global no `.gitignore` (só `/data/tse/`, `/data/geometries/`, `/data/ai-fill/`, `/data/encode/`, `/data/poster-candidates/`), então um `data/camara/` novo **vazaria sem entrada explícita**; A mantém os caminhos do script/relatório estáveis e reproduzíveis. B quebra reprodutibilidade; C é para material sensível.
- **(d) Trechos: parser HTML vs API.** **A)** parsear a **página do evento** server-rendered (âncoras `?a=<idAudio>&t=<epoch ms>&trechosOrador=&crawl=no`). **B)** engenharia reversa de endpoint JSON interno de trechos. **C)** página `Resultado.asp?txtCodigo=` (áudio, sem vídeo). **Recomendação: A** — não há API de trechos; a página do evento é a superfície observada (200, ~878 KB) e a que carrega `a`/`t`; B é não-documentado e frágil; C não dá vídeo. **Medir no piloto:** parser extrai ≥1 trecho do orador-alvo (critério: nome normalizado bate e `t` é epoch ms plausível).
- **(e) Escopo de teste.** Unit puro sobre `scripts/lib/camaraSpeeches.mjs` (sem rede): `parseEventExcerpts(html)`, `buildVodUrl(eventId, audioId, t)`, `parseVodStatus(json)`, `youtubeOffsetSeconds(tMs, startTimestamp)`, `selectSpeechEvent(events, speech)`, `matchExcerpt(excerpts, speech)`, `normalizeTranscription(json)`. **Recomendação: só unit** — é spike de rede; int/e2e não têm alvo local. Fixture sintética pequena inline no spec (não commitar HTML bruto da Câmara).
### Componentes / mudanças
- `scripts/pilot-camara-speeches.mjs` (novo, top-level): orquestra fetch (`AbortSignal.timeout`, UA de browser por constante), poll do VOD com backoff/limite, download cacheado, transcrição, impressão do relatório. Importa `dieWithLabel`/`loadCliEnv` de `scripts/lib/cli.mjs` (não re-espelha `die`/dotenv/`sha256`; não chama `assertLocalDatabase`). Flags: `--speech`, `--legislature`, `--out`, `--help`.
- `scripts/lib/camaraSpeeches.mjs` (novo, puro): os 7 helpers acima. **Deve ser importado pelo script** (knip acusa `scripts/lib/*.mjs` órfão).
- `tests/unit/camaraSpeeches.unit.spec.ts` (novo, `// @vitest-environment node`, import relativo do `.mjs`).
- `package.json`: atalho `"camara:pilot": "node scripts/pilot-camara-speeches.mjs"` (`.mjs` puro roda node seco — sem `tsx`).
- `.gitignore`: `/data/camara/`.
- `docs/research/piloto-fonte-videos-camara.md` (relatório, commitado) e `docs/changelog/2026-09-12-c152.md` (curto).
### Dados → forma (N/A)
Não há superfície de produto — é spike de engenharia. A "forma" é o relatório: por discurso, uma tabela `evento · trecho(a,t) · estado VOD · bytes MP4 · segmentos(start/end/text)` + bloco de custos/tempos; sem UI, sem collection.
## Fases verificáveis
1. **Tracer recente (quota ~0,35 dia).** Um discurso 2023–2024: listar discursos (`GET /deputados/178857/discursos`, ler `X-Total-Count`), casar o evento por data (`GET /eventos?dataInicio=&dataFim=`), buscar as âncoras na página do evento, chamar `video-sob-demanda`, pollar até `PRONTO`, baixar o MP4 do trecho, transcrever no compat com `verbose_json`. Junto: esqueleto do script, `/data/camara/` no `.gitignore`, `package.json`. **Pronto quando:** o console imprime os segmentos `start/end/text` de 1 discurso e os tempos de download/transcrição. Responde (parcial) incógnitas 1 e 3.
2. **Discurso antigo 55ª/56ª (2011–2015) (quota ~0,3 dia).** Repetir o fluxo; se a página do evento não tiver trecho do orador, exercitar o fallback YouTube (`urlRegistro` + `offset = t/1000 − startTimestamp`). **Pronto quando:** 2–3 discursos de legislaturas diferentes processados, com o casamento discurso↔evento↔trecho (ou o motivo de não casar) registrado. Responde incógnitas 2 e 4.
3. **Fallbacks e permanência (quota ~0,2 dia).** Re-resolver o mesmo trecho do tracer após intervalo para checar permanência do link; tentar o endpoint nativo se o compat não trouxer `start/end`; tratar o 400 anti-crawl (UA de browser + `crawl=no`/cookies) e registrar o resultado. **Pronto quando:** as 4 incógnitas têm resposta com evidência ou "medir no piloto" com critério explícito.
4. **Fechamento (quota ~0,15 dia).** Unit tests do módulo puro; relatório `docs/research/piloto-fonte-videos-camara.md` com as 4 respostas, custos/tempos e fallback por incógnita; changelog. **Pronto quando:** lint + typecheck + `pnpm test:unit` verdes e nenhum artefato de mídia no `git status`.
## Rabbit holes / Não escopo (engenharia)
- **Crawler resiliente genérico** (retry framework, cookie jar, headless browser): não — fetch direcionado com UA e timeout; se o anti-crawl bloquear, registrar como incógnita residual.
- **Instalar/embutir ffmpeg** no repo/Dockerfile: não — envio direto do MP4 (decisão a); ffmpeg, se necessário, é pré-requisito manual do piloto e fica documentado, sem tocar a imagem.
- **Refatorar `ensureCachedDownload` para streaming / criar `createWriteStream`/`pipeline`:** não — o trecho é curto; buffer em memória (padrão atual de `recover-media.mjs:233` e `electionResultsZip.ts:63`).
- **Criar client/collection/tipos da Câmara em `src/`:** não — fica em `scripts/`; C153 é que modela o acervo.
- **Baixar os 45/99 discursos ou a sessão inteira:** não — 2–3 discursos.
- **Commitar mídia/HTML/JSON bruto:** não — só relatório + código + testes; mídia em `data/camara/` gitignored.
- **Knip trap:** não criar `scripts/lib/camaraSpeeches.mjs` sem importá-lo no script.
## Riscos e mitigação
- **VOD nunca chega a `PRONTO` / expira.** Poll com backoff e teto (~3s × até 2min, com limite explícito), capturando o JSON cru do cache; fallback YouTube quando houver `urlRegistro`; senão registrar "sem vídeo" para o discurso.
- **400 anti-crawl na página de trecho/paginação.** Usar UA de browser + `crawl=no`; caminho principal continua sendo as âncoras da página do evento (200) + o JSON do VOD por `idAudio`/`t`, que não dependem da página de trecho.
- **Compat sem timestamp / provedor rejeita MP4.** Fallback nativo (`chunk_level`); normalizador aceita os dois shapes; se rejeitar o container, decidir ffmpeg manual só para o piloto e registrar.
- **Sessão antiga sem trecho por orador.** Fallback YouTube com offset; sem `urlRegistro`, resposta da incógnita 2 = "não cobre" com a evidência da contagem de âncoras.
- **Casamento ambíguo** (vários eventos no dia; nome do orador divergente). Casar por data normalizada + nome normalizado + `t` mais próximo de `dataHoraInicio`; logar candidatos e, se ainda ambíguo, registrar no relatório.
- **Vazamento de mídia no git.** Entrada explícita `/data/camara/` + checagem de que todo caminho de escrita está sob a raiz do cache antes de gravar; `git status` limpo é aceite.
- **Chave ausente.** `DEEPINFRA_API_KEY` é lida via `loadCliEnv`; ausente → `dieWithLabel` com mensagem pt-BR (a execução ao vivo já tem a chave no env).
- **Estouro de appetite.** Teto rígido de 3 discursos e trechos curtos; custo é ~US$ 0,00045/min, desprezível vs. tempo de busca/poll.
## Aceite de engenharia
- [x] `scripts/pilot-camara-speeches.mjs` roda com node seco e imprime, por discurso: evento, `a`/`t` do trecho, `estado` do VOD, caminho/bytes do MP4 e segmentos `start/end/text`.
- [x] 2–3 discursos de legislaturas diferentes processados ponta a ponta.
- [x] Lógica pura em `scripts/lib/camaraSpeeches.mjs`, importada pelo script (knip) e coberta por `tests/unit/camaraSpeeches.unit.spec.ts` (`// @vitest-environment node`).
- [x] Sem `assertLocalDatabase`, sem Payload/DB/collection/migration; sem re-spell de `die`/`sha256`/dotenv/`LOCAL_HOSTS`; `dieWithLabel` importado de `scripts/lib/cli.mjs`.
- [x] `data/camara/` fora do git via entrada explícita no `.gitignore`; nenhuma mídia/HTML/JSON bruto commitado.
- [x] `docs/research/piloto-fonte-videos-camara.md` commitado: as 4 incógnitas respondidas (com evidência ou critério de "medir no piloto"), custos/tempos e fallback por incógnita, crédito CC BY 4.0.
- [x] `docs/changelog/2026-09-12-c152.md` criado.
- [x] `pnpm lint`, `pnpm typecheck` e `pnpm test:unit` verdes.
## Débitos (triage pós-simplify)
Nenhum achado dos dois revisores virou Issue: é spike, os achados eram baixos/médios e ou foram resolvidos na sessão, ou ficam como gatilho para C153. Isso evita poluir o backlog (ver `capture-review-debts`).
**Já resolvido no simplify (não reabrir):**
- `youtubeOffsetSeconds` era export especulativo sem call site → removido (a fórmula fica documentada no relatório; C153 liga o fallback).
- `normalizeTranscription` convertia `duration: null` em `0` (`Number(null) === 0`) → guard `typeof number`.
- Uma exceção de rede/Deep Infra derrubava o run e não gravava o JSON → `processSpeech` agora captura e registra em `failures[]`.
- `--skip-download` dizia resolver o VOD mas pulava o `resolveVod` → agora resolve e registra; help corrigido.
- `--out` aceitava `..` sem guard → fail-closed adicionado.
- `chunk` do parser podia capturar o card do próximo trecho → fatiado até a próxima âncora.
- `matchExcerpt` casava qualquer orador com `speaker` vazio → guard de string vazia.
- `headers` redundante, validação de presença de valor nos args, cast do teste, duração do `--skip-download`.
**Adiado com gatilho (C153):**
- **Parser de âncoras ancorado na ordem de atributos/query literal** (`scripts/lib/camaraSpeeches.mjs`): qualquer reordenação do HTML da Câmara quebra silenciosamente (retorna `[]`). Gatilho: quando C153 montar o import robusto, usar seleção estrutural + teste com HTML real versionado.
- **Fallback YouTube** (`urlRegistro` + offset `t/1000 − startTimestamp`): registrado no relatório e no `report.youtube`, mas não calculado (o `startTimestamp` do VOD não vem na API). Gatilho: C153, se o acervo precisar cobrir eventos sem trecho.
**Explicitamente fora / descartado:** duplicação `fileExists`/`readFile` vs cache interno de `ensureCachedDownload` (score 1–2); builders de URL inline no driver (nit de consistência); `includes` do match de orador (leniência intencional no piloto).
### Self-score decision-quality
1. **Fidelidade ao outcome e anti-goals — 5/5:** cada fase fecha um pedaço do aceite (2–3 discursos, 4 incógnitas); os guardrails (sem DB, sem acervo, mídia fora do git) viram itens de aceite verificáveis.
2. **Decisões caras com opções/recomendação/rejeitadas — 5/5:** (a) áudio sem ffmpeg, (b) compat vs nativo, (c) local dos artefatos, (d) parser vs API, (e) escopo de teste — todas deliberadas com rejeitadas explícitas.
3. **Fases verificáveis e tracer primeiro — 4/5:** tracer já exercita o caminho mais arriscado (poll do VOD + transcrição com segmentos); quota estimada, sem baseline histórico do repo para calibrar (daí o 4).
4. **Incerteza tratada com critério mensurável — 5/5:** os dois pontos contraditórios ao vivo (VOD assíncrono, anti-crawl) foram incorporados; cada incógnita tem "medir no piloto" com critério objetivo.
5. **Aderência ao codebase e convenções — 5/5:** reusa `scripts/lib/cli.mjs` sem duplicar helpers, respeita os guards de `codebaseConventions`/`scriptCliConventions`, o knip de `scripts/lib`, o formato `.mjs` puro e o padrão de relatório em `docs/research/`.

View file

@ -48,3 +48,12 @@ Mesmo método (literatura → personas → entrevistas sintéticas em subagents
| [`roteiro-entrevista-emendas-responsavel-real.md`](roteiro-entrevista-emendas-responsavel-real.md) | Roteiro Mom Test da sessão real com a pessoa do gabinete que mantém a planilha de emendas (artefato-first; não é auditoria) | **aguardando agendamento** |
**Limitação metodológica (ciclo 3):** as quatro personas bebem do MESMO compêndio — convergência é consistência de leitura, não evidência independente; o que informa é a divergência entre lentes de papel. Exceção parcial: a persona 4 ancora os campos [R] na entrevista real de 2026-07-23 (`docs/CUSTOMER.md`). **Nada entra no roadmap nem vira código antes da validação com a pessoa real do gabinete — inclusive a criação das verticais `/mandato` e `/comunicacao`.** O eixo B do compêndio não é parecer jurídico; qualquer registro novo da camada política passa pelo advogado antes de existir.
## Piloto de fonte — acervo de falas da Câmara (C152, 2026-09-12)
Viabilidade da fonte do acervo de falas (Issue #954): 2–3 discursos de legislaturas diferentes processados ponta a ponta (evento → trecho → VOD → transcrição ASR com segmentos). Não é discovery de produto — é relatório de engenharia que destrava C153/C154/C155.
| Artefato | O quê | Status |
| ----------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | -------------------- |
| [`piloto-fonte-videos-camara.md`](piloto-fonte-videos-camara.md) | Respostas às 4 incógnitas da fonte (permanência do link, trechos em 55ª/56ª, segmentos Deep Infra, casamento antigo), custos e fallbacks | concluído 2026-09-12 |
| [`piloto-fonte-videos-camara-impl.md`](../plans/piloto-fonte-videos-camara-impl.md) | Plano de implementação do piloto (script + lib pura + unit tests) | executado |

View file

@ -0,0 +1,106 @@
# Piloto da fonte: vídeos e transcrição minutada de discursos da Câmara
Status: concluído — piloto de viabilidade
Atualizado em: 2026-09-12
Issue: [#954](https://github.com/fsolla/teqo/issues/954) (C152)
Intenção: [`docs/plans/piloto-fonte-videos-camara.md`](../plans/piloto-fonte-videos-camara.md)
Impl: [`docs/plans/piloto-fonte-videos-camara-impl.md`](../plans/piloto-fonte-videos-camara-impl.md)
Script: [`scripts/pilot-camara-speeches.mjs`](../../scripts/pilot-camara-speeches.mjs) + [`scripts/lib/camaraSpeeches.mjs`](../../scripts/lib/camaraSpeeches.mjs)
Relatório de engenharia: responde as quatro incógnitas que decidem o desenho do acervo de falas (C153) antes de modelar banco, import e tela. **Nada foi escrito em banco**; mídia e JSON ficam em `data/camara/` (gitignored).
## Como reproduzir
```bash
# requer DEEPINFRA_API_KEY no .env.local ou no env do processo
pnpm camara:pilot --legislature 57 --limit 1
pnpm camara:pilot --date 2016-03-10 --skip-transcribe # só resolve o VOD
```
O script escolhe o discurso, casa o evento do dia, acha o trecho do orador na página do evento, polla a geração assíncrona do VOD, baixa o MP4 e transcreve com segmentos. Os artefatos vão para `data/camara/` (MP4 + `pilot-report.json`).
## Discursos processados ponta a ponta
| Legislatura | Discurso | Sessão | Trecho do orador | VOD | MP4 | ASR (segmentos) | Custo ASR |
| ----------- | ---------------- | ---------------------------------- | ---------------------------------- | --------------- | ------- | --------------- | ------------ |
| 57ª (2023) | 2023-02-07T17:28 | Sessão Deliberativa (evento 67091) | `a=558641` `t=1675801808560` 17:30 | PRONTO, 1 poll | 20,3 MB | 43 (252,0 s) | ~US$ 0,00189 |
| 56ª (2021) | 2021-02-24T16:16 | Outro Evento (evento 60430) | `a=545023` `t=1614194341593` 16:19 | PRONTO, 1 poll | 22,9 MB | 62 (284,0 s) | ~US$ 0,00213 |
| 55ª (2016) | 2016-03-10T09:28 | Sessão Deliberativa (evento 43106) | `a=55709` `t=1457612936930` 09:28 | PRONTO, 2 polls | 4,4 MB | 16 (83,1 s) | ~US$ 0,00062 |
| 54ª (2013) | 2013-09-04T15:45 | Comissão Geral "Mais Médicos" | **não há** (0 âncoras de trecho) | — | — | — | — |
O `tipoDiscurso`/`faseEvento` vêm da API de discursos; o trecho, da página do evento.
## As quatro incógnitas
### 1. Os links de vídeo por discurso são permanentes?
**Não existe link por discurso**: `urlVideo` e `urlAudio` vêm nulos e `uriEvento` vem vazio na API de discursos. O vídeo é derivado em duas etapas:
- `GET https://www.camara.leg.br/evento-legislativo/{evento}/video-sob-demanda?idAudio={a}&trecho={t}` devolve `{ estado, video }` — **geração assíncrona** no servidor de VOD (`GERANDO` → `PRONTO`), não um download síncrono. O primeiro request de um trecho novo pode levar ~30 s e retorna `GERANDO`; os seguintes (a cada ~5 s) retornam `PRONTO` em 1–2 polls.
- Quando `PRONTO`, o `video.linkParaDownload` aponta para `https://vod.camara.leg.br/vod/download?p=<hash>.mp4`, que respondeu **200 sem cookie nem sessão** (2026-09-12).
**Evidência de permanência:** o mesmo `<hash>` foi devolvido em requests separados por >15 min (2023: `a7b49fbccf69a58965f8f25377fe9a97`; 2016: `2c102e9a69704b5e7edb780f934000a2`), e o MP4 baixou consistentemente. **Recomendação:** tratar o link como **regerável e determinístico**, não como asset imutável — persistir `evento`+`idAudio`+`trecho` e re-resolver via `video-sob-demanda` quando precisar baixar de novo. Um teste de permanência de longa duração (semanas) não foi feito.
### 2. Sessões antigas (2011–2015) têm trechos por orador?
**Depende da legislatura.** A página do evento lista os trechos por orador (âncoras server-rendered com `a`/`t`) e o Solla aparece:
- **55ª (2016)** e **56ª (2021)**: sim — 248 e 262 âncoras na página, com o trecho do Solla (1:21 e 4:40).
- **54ª (2011–2015)**: não. O único discurso do período na API (Comissão Geral "Mais Médicos", 2013-09-04) não tem trecho: a página do evento 33397 tem **0 âncoras** e nenhuma menção ao orador — e o evento também não tem `urlRegistro` (YouTube), então não há nem fallback.
O volume do período também é praticamente nulo para este deputado (1 discurso em 2011–2015, contra 362/414/234 em 55ª/56ª/57ª, conforme a pesquisa do planejamento). **Conclusão:** a cobertura útil começa em 2015; C153/C155 não devem contar com 54ª.
### 3. A transcrição via Deep Infra devolve segmentos com minutagem?
**Sim, no endpoint compatível, e sem ffmpeg.** Funcionou de primeira:
```
POST https://api.deepinfra.com/v1/openai/audio/transcriptions
model=openai/whisper-large-v3 language=pt
response_format=verbose_json timestamp_granularities[]=segment
file=<o próprio MP4 do trecho, video/mp4>
→ { text, language: "pt", duration, segments: [{ start, end, text }, …] }
```
Retornou `segments[]` com `start`/`end` numéricos nos três discursos (43/62/16 segmentos) e **aceitou o MP4 direto** — o container de vídeo não precisa de extração de áudio. O endpoint nativo (`chunk_level`) e a instalação de `ffmpeg` **não foram necessários** (o repo e a imagem não têm ffmpeg). O `deepInfraTranscribe.ts` do app não serve: é `server-only`, devolve só `{ text }` e não expõe timestamps.
### 4. O casamento discurso ↔ evento ↔ trecho funciona em anos antigos?
**Sim, por data/hora.** Como `uriEvento` vem vazio, o casamento é: discurso → eventos do mesmo dia (ordenados por proximidade do horário) → âncoras da página do evento → trecho cujo `titulo` normalizado bate com o orador e cujo horário é o mais próximo. Funcionou em 55ª/56ª/57ª. A única falha foi o caso de 2013, explicada por ausência de trecho (não por erro de casamento).
**Custo do casamento:** quando o dia não tem trecho, o script varre todos os eventos do dia até achar — em 2013 foram ~44 páginas de evento (~50 s). C153 deve priorizar os tipos `Sessão Deliberativa`/`Breves Comunicações` e abortar cedo em vez de varrer tudo.
## Custos e tempos medidos
- **Transcrição (Deep Infra, whisper-large-v3):** US$ 0,00045/min. Medido: US$ 0,00062 (1:21), US$ 0,00189 (4:02), US$ 0,00213 (4:40). Para o acervo 54ª–57ª (≈1.011 discursos, ~4 min médios ≈ 67 h) a ordem de grandeza é **~US$ 1,80** — irrelevante.
- **Tempo de transcrição:** ~11–19 s por trecho de 1–5 min (≈4–5× tempo real); o upload de ~20 MB é o que domina.
- **Geração do VOD:** 1–2 polls (~5–35 s na primeira vez de cada trecho).
- **Download do MP4:** ~3 s para ~20 MB.
- **Ponta a ponta por discurso:** ~35–40 s (incluindo busca de evento e transcrição).
## Fallbacks recomendados (por incógnita)
1. **Link/permanência:** não persistir a URL do MP4; persistir `evento`+`idAudio`+`trecho` e re-resolver por `video-sob-demanda`. Se `INDISPONIVEL`, cair para o YouTube do evento com offset `t/1000 − startTimestamp` (`urlRegistro`); sem `urlRegistro`, marcar "sem vídeo".
2. **Sessão sem trecho:** idem acima; em 2011–2015 a resposta é "não cobre" (documentado, não é falha).
3. **Segmentos ASR:** compat `verbose_json` funcionou; fallback raro = endpoint nativo (`chunk_level: segment`); último recurso = extrair áudio com `ffmpeg` (não foi preciso).
4. **Casamento ambíguo:** usar `faseEvento`/tipo do discurso e validar o nome normalizado; limitar a varredura a tipos de sessão relevantes.
## Limitações e armadilhas observadas
- **Anti-crawl:** a URL de trecho `?a=…&t=…&trechosOrador=&crawl=no` responde **400 "Acesso via bot não permitido"** a User-Agent de curl. O caminho que funciona é a página do evento (200, UA de browser) + o JSON de `video-sob-demanda`; não foi preciso copiar cookies.
- **Conteúdo inicial do recorte:** o MP4 do trecho começa alguns segundos antes do orador (captura o fim da fala anterior). Para citar com precisão, recortar pelo `start` do primeiro segmento ASR após o início real, ou cruzar com o horário do trecho.
- **Data/hora sem timezone:** as datas da API e o `horario` do trecho são hora local de Brasília; o casamento foi feito por hora-do-dia, sem conversão.
- **Sem espelhamento de mídia:** os vídeos continuam servidos pela Câmara (C154/C155).
- **Licença:** as transmissões de atividades legislativas da Câmara são **CC BY 4.0**; crédito obrigatório e marca-d'água intocada.
## Recomendações para C153
- Modelar o discurso com `evento`+`idAudio`+`trecho` (chave natural) e re-resolver o MP4 sob demanda, nunca guardar a URL do VOD como identidade.
- Reusar a lógica pura de `scripts/lib/camaraSpeeches.mjs` (parser de âncoras, matching, offset YouTube, normalização de segmentos) no import idempotente.
- Assumir cobertura de trecho **2015+**; tratar 54ª como vazia.
- Priorizar tipos de sessão e cachear a página do evento para não varrer dezenas de páginas por dia.
- A transcrição oficial (taquigrafia) + segmentos ASR (minutagem) convivem: o texto oficial é a leitura; o ASR dá os `start/end`.
## Crédito
Vídeos e dados da Câmara dos Deputados — [dadosabertos.camara.leg.br](https://dadosabertos.camara.leg.br) e [camara.leg.br](https://www.camara.leg.br), licença CC BY 4.0.

View file

@ -81,6 +81,7 @@
"test:unit": "cross-env NODE_OPTIONS=--no-deprecation DATABASE_URL=postgresql://invalid:invalid@127.0.0.1:1/unit_tests_must_not_connect vitest run --config ./vitest.unit.config.mts",
"images:resize": "node scripts/resize-images.mjs",
"images:fill": "node scripts/fill-image.mjs",
"camara:pilot": "node scripts/pilot-camara-speeches.mjs",
"typecheck": "tsc --noEmit",
"typecheck:tsc6": "tsc6 --noEmit",
"prepare": "husky",

View file

@ -228,6 +228,17 @@ export default defineConfig({
* e2e states stay deterministic (see `googleCalendarTestKey.ts`).
*/
[GOOGLE_CALENDAR_SERVICE_ACCOUNT_KEY_ENV_NAME]: GOOGLE_CALENDAR_TEST_KEY,
/*
* C149 — dummy OAuth client pair so the agenda dialog offers the
* "Conectar com o Google" button (the view derives `oauthAvailable`).
* No spec seeds a refresh token on the shared sync row except with a
* far-future success, and the button test intercepts the navigation
* to Google — no request ever leaves the runner for oauth2.
*/
GOOGLE_CALENDAR_OAUTH_CLIENT_ID:
process.env.GOOGLE_CALENDAR_OAUTH_CLIENT_ID ?? 'e2e-client-id.apps.googleusercontent.com',
GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET:
process.env.GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET ?? 'e2e-client-secret',
// Keep e2e artifacts outside `.next`: a concurrent development server
// owns that entire directory and may clear nested production bundles.
NEXT_DIST_DIR: process.env.NEXT_DIST_DIR ?? '.next-e2e',

View file

@ -1,19 +1,30 @@
#!/usr/bin/env bash
#
# Deploy teqo-1313 to the homeserver (OPS53).
# Deploy teqo-1313 (production) or teqo-staging to the homeserver (OPS53,
# parameterized by OPS103).
#
# OPS71: runs ON the homeserver via the GitHub self-hosted runner (deploy job
# OPS71: runs ON the homeserver via the GitHub self-hosted runner (deploy jobs
# of .github/workflows/deploy.yml):
# bash scripts/deploy-homeserver.sh <commit-sha>
# (The Forgejo-era invocation `ssh homeserver "bash -s -- <sha>" < script`
# is gone — no SSH hop, no workstation involvement.)
#
# Flow: HEAD guard (only the current main HEAD deploys; a stale run FAILS the
# job — never a false green with prod left on the old image) -> flock
# serialization -> workspace fetch at <sha> -> docker login (local registry)
# -> build of the MIGRATOR stage (it never runs `next build`, so it builds
# even against the old schema) -> push of the migrator (registry-qualified
# tag — INF13: the ONLY ref the compose references) -> compose image-tag swap
# OPS103: one script, both environments — `TEQO_ENV=production` (default,
# byte-for-byte the pre-OPS103 behavior) and `TEQO_ENV=staging`. Each
# environment owns its container/service, env file, image repo, build-proxy
# port, smoke base and lock; the compose file, workspace and registry stay
# shared. An unknown TEQO_ENV fails closed before anything is touched.
#
# OPS102: a manual dispatch runs to the end with its SHA even if main advances
# during verify (the old stale-run guard belonged to the automatic era); the
# only early green is the idempotency guard, which proves the SHA is already
# running.
#
# Flow: flock serialization -> workspace fetch at <sha> -> docker login
# (local registry) -> build of the MIGRATOR stage (it never runs `next
# build`, so it builds even against the old schema) -> push of the migrator
# (registry-qualified tag — INF13: the ONLY ref the compose references) ->
# compose image-tag swap
# (with backup) -> migrate via the maintenance service
# (BEFORE the runner build — static generation reads the NEW schema, OPS66)
# -> build of the runner stage (BuildKit secrets, compose network) ->
@ -31,10 +42,16 @@
set -euo pipefail
SHA="${1:?usage: deploy-homeserver.sh <commit-sha>}"
TEQO_ENV="${TEQO_ENV:-production}"
TEQO_REPO_URL="${TEQO_REPO_URL:-https://github.com/fsolla/teqo.git}"
STACK_DIR="${STACK_DIR:-$HOME/stack}"
WORKSPACE_DIR="${WORKSPACE_DIR:-$HOME/teqo-deploy}"
DEPLOY_LOCK="${DEPLOY_LOCK:-/tmp/teqo-1313-deploy.lock}"
TEQO_REGISTRY="${TEQO_REGISTRY:-localhost:5000}"
# ONE lock for both environments: the compose file, the workspace and the
# local registry are shared, so staging and production must never build or
# swap concurrently (the workflow's job-level concurrency serializes the
# runs; this lock also covers manual invocations on the host).
DEPLOY_LOCK="${DEPLOY_LOCK:-/tmp/teqo-deploy.lock}"
say() { printf '[deploy] %s\n' "$*"; }
@ -44,46 +61,70 @@ fatal() {
exit 1
}
# --- guards ------------------------------------------------------------
# --- environment map (OPS103) -------------------------------------------
# Production values are the pre-OPS103 literals: the canonical invocation
# `bash scripts/deploy-homeserver.sh <sha>` (no TEQO_ENV) behaves exactly as
# before. The workflow passes TEQO_ENV per deploy job. The DB name is NOT
# here — it lives inside each environment's env file. `readonly` keeps the
# env files (sourced below) from silently retargeting the deploy.
main_head="$(git ls-remote "$TEQO_REPO_URL" refs/heads/main | awk '{print $1}')"
if [ "$main_head" != "$SHA" ]; then
fatal "stale run: main is $main_head, job deploys $SHA — refusing to deploy an outdated SHA"
fi
case "$TEQO_ENV" in
production)
TEQO_CONTAINER=teqo-1313
TEQO_MIGRATE_SERVICE=teqo-1313-migrate
TEQO_ENV_FILE="$STACK_DIR/teqo-1313.env"
TEQO_IMAGE_REPO=teqo-1313
TEQO_BUILD_PROXY=teqo-1313-build-proxy
TEQO_BUILD_PROXY_PORT=5433
TEQO_SMOKE_BASE=http://localhost:1313
;;
staging)
TEQO_CONTAINER=teqo-staging
TEQO_MIGRATE_SERVICE=teqo-staging-migrate
TEQO_ENV_FILE="$STACK_DIR/teqo-staging.env"
TEQO_IMAGE_REPO=teqo-staging
TEQO_BUILD_PROXY=teqo-staging-build-proxy
TEQO_BUILD_PROXY_PORT=5434
TEQO_SMOKE_BASE=http://localhost:1314
;;
*)
fatal "unknown TEQO_ENV '$TEQO_ENV' (expected production or staging)"
;;
esac
readonly TEQO_CONTAINER TEQO_MIGRATE_SERVICE TEQO_ENV_FILE TEQO_IMAGE_REPO
readonly TEQO_BUILD_PROXY TEQO_BUILD_PROXY_PORT TEQO_SMOKE_BASE DEPLOY_LOCK
# --- serialization (flock) ----------------------------------------------
exec 9>"$DEPLOY_LOCK"
flock -w 3600 9 || fatal "another deploy holds $DEPLOY_LOCK"
main_head="$(git ls-remote "$TEQO_REPO_URL" refs/heads/main | awk '{print $1}')"
if [ "$main_head" != "$SHA" ]; then
fatal "stale run after lock: main is $main_head, job deploys $SHA — refusing to deploy an outdated SHA"
fi
# --- idempotency (OPS65) ------------------------------------------------
# A 30-min main window can re-deliver a SHA the cluster already runs (e.g. a
# duplicate workflow_dispatch): rebuilding it is a ~15 min no-op. The truth
# A duplicate workflow_dispatch can re-deliver a SHA the cluster already runs:
# rebuilding it is a ~15 min no-op. The truth
# is the RUNNING container's revision label — the compose file can lie after
# a failed rollback (it is swapped before the rollout and restored best-
# effort). A container without the label (or down) counts as "not deployed":
# the deploy proceeds (safe direction — it rebuilds).
running_rev="$(docker inspect -f '{{index .Config.Labels "org.opencontainers.image.revision"}}' teqo-1313 2>/dev/null || true)"
running_rev="$(docker inspect -f '{{index .Config.Labels "org.opencontainers.image.revision"}}' "$TEQO_CONTAINER" 2>/dev/null || true)"
if [ -n "$running_rev" ] && [ "$running_rev" = "$SHA" ]; then
say "already deployed: teqo-1313 runs $SHA — nothing to do"
say "already deployed: $TEQO_CONTAINER runs $SHA — nothing to do"
exit 0
fi
# --- secrets (sourced locally, never echoed) ----------------------------
set -a
. "$STACK_DIR/teqo-1313.env"
. "$TEQO_ENV_FILE"
. "$STACK_DIR/.env"
set +a
: "${DATABASE_URL:?teqo-1313.env is missing DATABASE_URL}"
: "${PAYLOAD_SECRET:?teqo-1313.env is missing PAYLOAD_SECRET}"
: "${NEXT_PUBLIC_SITE_URL:?teqo-1313.env is missing NEXT_PUBLIC_SITE_URL}"
: "${REVALIDATE_SECRET:?teqo-1313.env is missing REVALIDATE_SECRET}"
: "${DATABASE_URL:?$TEQO_ENV_FILE is missing DATABASE_URL}"
: "${PAYLOAD_SECRET:?$TEQO_ENV_FILE is missing PAYLOAD_SECRET}"
: "${NEXT_PUBLIC_SITE_URL:?$TEQO_ENV_FILE is missing NEXT_PUBLIC_SITE_URL}"
: "${REVALIDATE_SECRET:?$TEQO_ENV_FILE is missing REVALIDATE_SECRET}"
: "${REGISTRY_USER:?stack/.env is missing REGISTRY_USER}"
: "${REGISTRY_PASSWORD:?stack/.env is missing REGISTRY_PASSWORD}"
@ -94,8 +135,8 @@ if [ ! -d "$WORKSPACE_DIR/.git" ]; then
git clone "$TEQO_REPO_URL" "$WORKSPACE_DIR"
else
# OPS71: the pre-cutover clone pointed at the local Forgejo — re-point
# idempotently so the HEAD guard and the fetch compare against the repo
# that actually received the merge.
# idempotently so the fetch targets the repo that actually received the
# merge.
current_url="$(git -C "$WORKSPACE_DIR" remote get-url origin 2>/dev/null || true)"
if [ -n "$current_url" ] && [ "$current_url" != "$TEQO_REPO_URL" ]; then
say "updating workspace origin: $current_url → $TEQO_REPO_URL"
@ -108,23 +149,25 @@ say "workspace at $SHA"
# --- registry -----------------------------------------------------------
say "logging into local registry localhost:5000"
echo "$REGISTRY_PASSWORD" | docker login localhost:5000 --username "$REGISTRY_USER" --password-stdin >/dev/null
say "logging into local registry $TEQO_REGISTRY"
echo "$REGISTRY_PASSWORD" | docker login "$TEQO_REGISTRY" --username "$REGISTRY_USER" --password-stdin >/dev/null
# --- build --------------------------------------------------------------
# BuildKit rejects a custom bridge network on `--network`, so the build runs
# with `--network host`; the prod DB (only reachable inside stack_default) is
# with `--network host`; the env DB (only reachable inside stack_default) is
# proxied to the host loopback by a one-off socat container on the compose
# network, and DATABASE_URL is rewritten to that endpoint. The proxy is
# idempotent and survives reboots (restart: unless-stopped).
# idempotent and survives reboots (restart: unless-stopped). Each
# environment publishes its own loopback port (TEQO_BUILD_PROXY_PORT) so the
# two proxies never collide.
ensure_db_proxy() {
if ! docker inspect teqo-1313-build-proxy >/dev/null 2>&1; then
docker run -d --name teqo-1313-build-proxy \
if ! docker inspect "$TEQO_BUILD_PROXY" >/dev/null 2>&1; then
docker run -d --name "$TEQO_BUILD_PROXY" \
--network stack_default \
--restart unless-stopped \
-p 127.0.0.1:5433:5433 \
alpine/socat TCP-LISTEN:5433,fork TCP:postgres:5432 >/dev/null
-p "127.0.0.1:$TEQO_BUILD_PROXY_PORT:$TEQO_BUILD_PROXY_PORT" \
alpine/socat "TCP-LISTEN:$TEQO_BUILD_PROXY_PORT,fork TCP:postgres:5432" >/dev/null
fi
}
@ -134,7 +177,7 @@ build_image() {
ensure_db_proxy
# The build's DATABASE_URL points at the loopback proxy; the outer env
# keeps the original value and nothing is echoed.
local build_db_url="${DATABASE_URL/@postgres:5432/@127.0.0.1:5433}"
local build_db_url="${DATABASE_URL/@postgres:5432/@127.0.0.1:$TEQO_BUILD_PROXY_PORT}"
DATABASE_URL="$build_db_url" DOCKER_BUILDKIT=1 docker build \
--network host \
--build-arg "NEXT_PUBLIC_SITE_URL=$NEXT_PUBLIC_SITE_URL" \
@ -149,34 +192,47 @@ cd "$WORKSPACE_DIR"
# The migrator stage never runs `next build`, so it builds fine against the
# OLD schema — unlike the runner, whose static generation reads Payload data
# and therefore needs the migrations applied first (OPS66).
build_image migrator "localhost:5000/teqo-1313-migrator:$SHA"
build_image migrator "$TEQO_REGISTRY/$TEQO_IMAGE_REPO-migrator:$SHA"
# INF13: the compose references REGISTRY-QUALIFIED tags
# (`localhost:5000/teqo-1313(-migrator):<sha>`) with pull_policy: never — the
# exact name every build produces, so the ref the compose needs can never go
# missing (the old bare `teqo-1313:<sha>` alias was a second local-only ref
# that nothing recreated once lost — homeserver incident 24/08, `No such
# image` on recreate).
docker push "localhost:5000/teqo-1313-migrator:$SHA"
# (`$TEQO_REGISTRY/$TEQO_IMAGE_REPO(-migrator):<sha>`) with pull_policy: never
# — the exact name every build produces, so the ref the compose needs can
# never go missing (the old bare `teqo-1313:<sha>` alias was a second
# local-only ref that nothing recreated once lost — homeserver incident
# 24/08, `No such image` on recreate).
docker push "$TEQO_REGISTRY/$TEQO_IMAGE_REPO-migrator:$SHA"
# --- compose swap (backup first; failures from here roll back) ----------
compose="$STACK_DIR/docker-compose.yml"
backup="$compose.pre-$SHA"
cp "$compose" "$backup"
# Image lines: the env-specific repo names cannot touch the other
# environment's services (the migrator pattern runs first; `teqo-1313:`
# never matches `teqo-1313-migrator:`).
sed -i -E \
-e "s|image: (localhost:5000/)?teqo-1313-migrator:[0-9a-f]+|image: localhost:5000/teqo-1313-migrator:$SHA|g" \
-e "s|image: (localhost:5000/)?teqo-1313:[0-9a-f]+|image: localhost:5000/teqo-1313:$SHA|g" \
-e "s|org.opencontainers.image.revision: [0-9a-f]+|org.opencontainers.image.revision: $SHA|g" \
-e "s|image: ($TEQO_REGISTRY/)?$TEQO_IMAGE_REPO-migrator:[0-9a-f]+|image: $TEQO_REGISTRY/$TEQO_IMAGE_REPO-migrator:$SHA|g" \
-e "s|image: ($TEQO_REGISTRY/)?$TEQO_IMAGE_REPO:[0-9a-f]+|image: $TEQO_REGISTRY/$TEQO_IMAGE_REPO:$SHA|g" \
"$compose"
grep -q "image: localhost:5000/teqo-1313:$SHA" "$compose" || fatal "compose swap failed (runner image)"
grep -q "image: localhost:5000/teqo-1313-migrator:$SHA" "$compose" || fatal "compose swap failed (migrator image)"
# Revision label: it lives INSIDE the service block, so a bare global
# replace would stamp THIS env's SHA onto the other environment's service —
# and the "already deployed" guard would read a lying revision. The sed
# range starts at the service key and ends at the next two-space key (the
# next service); keys inside a service are indented four spaces. The range
# is then re-read to fail closed when the service has no revision label
# (a silent no-op would disable the idempotency guard for this env).
label_range="/^ $TEQO_CONTAINER:/,/^ [A-Za-z0-9_.-]+:/"
sed -i -E -e "$label_range s|org.opencontainers.image.revision: [0-9a-f]+|org.opencontainers.image.revision: $SHA|" "$compose"
sed -n -e "$label_range p" "$compose" | grep -q "org.opencontainers.image.revision: $SHA" \
|| fatal "compose swap failed (revision label of $TEQO_CONTAINER)"
grep -q "image: $TEQO_REGISTRY/$TEQO_IMAGE_REPO:$SHA" "$compose" || fatal "compose swap failed (runner image)"
grep -q "image: $TEQO_REGISTRY/$TEQO_IMAGE_REPO-migrator:$SHA" "$compose" || fatal "compose swap failed (migrator image)"
rollback() {
trap - ERR
say "FAILED: $* — restoring previous compose and image"
cp "$backup" "$compose" 2>/dev/null || true
( cd "$STACK_DIR" && docker compose up -d teqo-1313 ) 2>/dev/null || true
( cd "$STACK_DIR" && docker compose up -d "$TEQO_CONTAINER" ) 2>/dev/null || true
exit 1
}
trap 'rollback "unexpected failure"' ERR
@ -186,32 +242,32 @@ trap 'rollback "unexpected failure"' ERR
# migration that creates a table a static route reads would otherwise
# deadlock the deploy (build fails -> migrate never runs -> build fails...).
# The migrator image above is already swapped into the compose, so this
# maintenance service runs the migrations of the NEW sha against prod.
# maintenance service runs the migrations of the NEW sha against the env DB.
cd "$STACK_DIR"
say "applying pending migrations (maintenance service teqo-1313-migrate)"
say "applying pending migrations (maintenance service $TEQO_MIGRATE_SERVICE)"
# `< /dev/null`: `compose run` attaches stdin by default; the container would
# consume the rest of the script piped into `bash -s` (bash then hits EOF and
# exits right after the migrate step, skipping the rollout).
docker compose --profile maintenance run --rm teqo-1313-migrate </dev/null || rollback "migrations failed"
docker compose --profile maintenance run --rm "$TEQO_MIGRATE_SERVICE" </dev/null || rollback "migrations failed"
# --- runner build (against the migrated schema) --------------------------
cd "$WORKSPACE_DIR"
say "building runner"
build_image runner "localhost:5000/teqo-1313:$SHA"
docker push "localhost:5000/teqo-1313:$SHA"
build_image runner "$TEQO_REGISTRY/$TEQO_IMAGE_REPO:$SHA"
docker push "$TEQO_REGISTRY/$TEQO_IMAGE_REPO:$SHA"
# --- rollout ------------------------------------------------------------
cd "$STACK_DIR"
say "rolling out teqo-1313"
docker compose up -d teqo-1313 || rollback "compose up failed"
say "rolling out $TEQO_CONTAINER"
docker compose up -d "$TEQO_CONTAINER" || rollback "compose up failed"
say "waiting for the healthcheck to go healthy"
health="starting"
for _ in $(seq 1 30); do
health="$(docker inspect -f '{{.State.Health.Status}}' teqo-1313 2>/dev/null || true)"
health="$(docker inspect -f '{{.State.Health.Status}}' "$TEQO_CONTAINER" 2>/dev/null || true)"
[ "$health" = "healthy" ] && break
[ "$health" = "unhealthy" ] && break
sleep 10
@ -220,7 +276,7 @@ done
# --- smoke --------------------------------------------------------------
base="http://localhost:1313"
base="$TEQO_SMOKE_BASE"
smoke_fail() { rollback "smoke: $*"; }
curl -fsS -o /dev/null "$base/" || smoke_fail "GET /"
@ -247,9 +303,9 @@ echo "$body" | grep -q '"revalidated":true' || smoke_fail "POST /api/revalidate
say "post-deploy cleanup: build cache + tags locais antigas"
docker builder prune -f >/dev/null 2>&1 || true
in_use_id="$(docker inspect -f '{{.Image}}' teqo-1313 2>/dev/null || true)"
in_use_id="$(docker inspect -f '{{.Image}}' "$TEQO_CONTAINER" 2>/dev/null || true)"
if [ -n "$in_use_id" ]; then
for img in $(docker images --format '{{.Repository}}:{{.Tag}}' | grep -E '^(localhost:5000/)?teqo-1313(-migrator)?:' || true); do
for img in $(docker images --format '{{.Repository}}:{{.Tag}}' | grep -E "^($TEQO_REGISTRY/)?$TEQO_IMAGE_REPO(-migrator)?:" || true); do
img_id="$(docker image inspect -f '{{.Id}}' "$img" 2>/dev/null || true)"
[ -n "$img_id" ] && [ "$img_id" = "$in_use_id" ] && continue
docker rmi "$img" >/dev/null 2>&1 || true
@ -258,4 +314,4 @@ else
say "cleanup: container sem image ID — mantendo imagens locais"
fi
say "deploy of $SHA complete: $(docker inspect -f '{{.Image}}' teqo-1313)"
say "deploy of $SHA complete: $(docker inspect -f '{{.Image}}' "$TEQO_CONTAINER")"

View file

@ -0,0 +1,239 @@
/**
* Pure derivation for the C152 pilot (`scripts/pilot-camara-speeches.mjs`):
* matching a Câmara speech to its legislative event and to the speaker's video
* excerpt, plus normalizing the VOD status and the Deep Infra transcription.
*
* No I/O here — the CLI threads fetch/download/transcribe through these
* decisions, so the fragile rules (HTML anchors, time-of-day matching, epoch
* offsets, provider shapes) are unit-tested without network.
*/
/** Câmara's open-data deputy id for Jorge Solla (used by the pilot). */
export const SOLLA_DEPUTY_ID = 178857
/** Browser-like UA — the trecho/evento pages answer 400 "Acesso via bot" to curl. */
export const CAMARA_USER_AGENT =
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36'
/** Deep Infra OpenAI-compatible transcription endpoint (returns segments with `verbose_json`). */
export const DEEPINFRA_TRANSCRIBE_URL = 'https://api.deepinfra.com/v1/openai/audio/transcriptions'
/** Whisper large-v3 on Deep Infra — US$ 0,00045/audio minute. */
export const DEEPINFRA_WHISPER_MODEL = 'openai/whisper-large-v3'
/** Legislature → inclusive date range (year of the first and last session). */
export const LEGISLATURE_RANGES = {
54: ['2011-01-01', '2015-01-31'],
55: ['2015-02-01', '2019-01-31'],
56: ['2019-02-01', '2023-01-31'],
57: ['2023-02-01', '2027-01-31'],
}
const stripAccents = (value) => value.normalize('NFD').replace(/[\u0300-\u036f]/g, '')
/**
* Canonical form of a speaker name for comparison: NFD-stripped, uppercase,
* punctuation dropped, whitespace collapsed. `Jorge Solla` → `JORGE SOLLA`.
*
* @param {string} name
* @returns {string}
*/
export const normalizeSpeakerName = (name) =>
stripAccents(String(name ?? ''))
.toUpperCase()
.replace(/[^A-Z0-9 ]+/g, ' ')
.replace(/\s+/g, ' ')
.trim()
/**
* `HH:MM` / `HH:MM:SS` → seconds of day, or null when unparseable.
*
* @param {string} clock
* @returns {number | null}
*/
export const clockToSeconds = (clock) => {
const match = /^(\d{1,2}):(\d{2})(?::(\d{2}))?$/.exec(String(clock ?? '').trim())
if (!match) return null
const hours = Number(match[1])
const minutes = Number(match[2])
const seconds = Number(match[3] ?? '0')
if (hours > 23 || minutes > 59 || seconds > 59) return null
return hours * 3600 + minutes * 60 + seconds
}
/**
* Time-of-day (seconds) of a naive local datetime (`2023-02-07T17:28`).
* Returns null when the value has no `T`-time part.
*
* @param {string} iso
* @returns {number | null}
*/
export const speechTimeOfDaySeconds = (iso) => clockToSeconds(String(iso ?? '').slice(11, 19))
/** `YYYY-MM-DD` prefix of a naive datetime. */
export const speechDate = (iso) => String(iso ?? '').slice(0, 10)
const integerOrNull = (value) => {
const n = Number(value)
return Number.isInteger(n) && n > 0 ? n : null
}
/**
* Parses the speaker-excerpt anchors of an event page. The page renders one
* `<a id="link-trecho-video" href="…/{eventId}?a=<idAudio>&t=<epochms>…"
* class="chamada__link-trecho" titulo="<SPEAKER>">` per excerpt, followed by
* the speaker card (`chamada__cargo`, `chamada__info-video-hora`,
* `chamada__info-video-duracao`). Returns `[]` when the event has no excerpts
* (old/committee sessions, or an unexpected layout).
*
* @param {string} html
* @param {number | string} eventId
* @returns {Array<{ audioId: number, tMs: number, speaker: string, party: string | null, startTime: string | null, duration: string | null }>}
*/
export const parseEventExcerpts = (html, eventId) => {
const page = String(html ?? '')
const escapedId = String(eventId).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const anchor = new RegExp(
`href="https://www\\.camara\\.leg\\.br/evento-legislativo/${escapedId}\\?a&#x3D;(\\d+)&amp;t&#x3D;(\\d+)&trechosOrador=&crawl=no"[^>]*class="chamada__link-trecho"[^>]*titulo="([^"]*)"`,
'g',
)
const excerpts = []
let match
while ((match = anchor.exec(page)) !== null) {
const audioId = integerOrNull(match[1])
const tMs = integerOrNull(match[2])
if (audioId === null || tMs === null) continue
const boundary = page.indexOf('id="link-trecho-video"', match.index + 1)
const end = boundary === -1 ? match.index + 4000 : Math.min(boundary, match.index + 4000)
const chunk = page.slice(match.index, end)
const afterDash = (text) => text.split(' - ').slice(1).join(' - ').trim() || null
const startRaw = /class="chamada__info-video-hora">([^<]*)<\/span>/.exec(chunk)?.[1]
const durationRaw = /class="chamada__info-video-duracao">([^<]*)<\/span>/.exec(chunk)?.[1]
excerpts.push({
audioId,
tMs,
speaker: match[3].trim(),
party: /class="chamada__cargo">([^<]*)<\/span>/.exec(chunk)?.[1]?.trim() ?? null,
startTime: startRaw ? afterDash(startRaw) : null,
duration: durationRaw ? afterDash(durationRaw) : null,
})
}
return excerpts
}
/** The async VOD-generation status URL for one excerpt. */
export const buildVodUrl = (eventId, audioId, tMs) =>
`https://www.camara.leg.br/evento-legislativo/${eventId}/video-sob-demanda?idAudio=${audioId}&trecho=${tMs}`
/**
* Normalizes the `video-sob-demanda` JSON (`{ estado, video }`). `state` is
* `GERANDO` while the server transcodes, `PRONTO` when the MP4 exists,
* `INDISPONIVEL` when there is none.
*
* @param {unknown} json
* @returns {{ state: string, video: { title: string | null, subtitle: string | null, duration: string | null, clock: string | null, downloadUrl: string | null, playbackUrl: string | null } | null }}
*/
export const parseVodStatus = (json) => {
const data = json && typeof json === 'object' ? json : {}
const estado = typeof data.estado === 'string' ? data.estado : 'DESCONHECIDO'
const raw = data.video && typeof data.video === 'object' ? data.video : null
const pick = (key) => (typeof raw?.[key] === 'string' ? raw[key] : null)
return {
state: estado,
video: raw
? {
title: pick('titulo'),
subtitle: pick('subtitulo'),
duration: pick('duracao'),
clock: pick('horario'),
downloadUrl: pick('linkParaDownload'),
playbackUrl: pick('linkParaReproducao'),
}
: null,
}
}
/**
* Events of the speech's date, nearest-first by start time. The open-data
* `uriEvento` comes empty, so the event is inferred from the date/time.
*
* @param {Array<{ id: number, dataHoraInicio?: string, descricaoTipo?: string, urlRegistro?: string | null }>} events
* @param {string} speechIso
* @returns {Array<{ id: number, dataHoraInicio?: string, descricaoTipo?: string, urlRegistro?: string | null }>}
*/
export const selectSpeechEvents = (events, speechIso) => {
const date = speechDate(speechIso)
const target = Date.parse(speechIso)
return (Array.isArray(events) ? events : [])
.filter((event) => speechDate(event?.dataHoraInicio) === date)
.sort((a, b) => {
const da = Math.abs(Date.parse(a.dataHoraInicio) - target)
const db = Math.abs(Date.parse(b.dataHoraInicio) - target)
return da - db
})
}
/**
* Picks the speaker's excerpt nearest in time-of-day to the speech. Returns
* null when the speaker is empty or does not appear on the page. Excerpts
* without a clock lose to ones with a clock.
*
* @param {ReturnType<typeof parseEventExcerpts>} excerpts
* @param {string} speechIso
* @param {string} speaker
* @returns {(ReturnType<typeof parseEventExcerpts>[number]) | null}
*/
export const matchExcerpt = (excerpts, speechIso, speaker) => {
const wanted = normalizeSpeakerName(speaker)
if (wanted === '') return null
const bySpeaker = (Array.isArray(excerpts) ? excerpts : []).filter((excerpt) =>
normalizeSpeakerName(excerpt?.speaker).includes(wanted),
)
if (bySpeaker.length === 0) return null
const target = speechTimeOfDaySeconds(speechIso)
if (target === null) return bySpeaker[0]
const delta = (excerpt) => {
const start = clockToSeconds(excerpt.startTime)
return start === null ? Number.POSITIVE_INFINITY : Math.abs(start - target)
}
return bySpeaker.reduce((best, current) => (delta(current) < delta(best) ? current : best))
}
/**
* Normalizes a Deep Infra transcription response. Accepts the OpenAI-compat
* shape (`segments[{start,end,text}]`) and the native whisper shape
* (`chunks[{timestamp:[start,end],text}]`). Invalid entries are dropped.
*
* @param {unknown} json
* @returns {{ text: string, language: string | null, duration: number | null, segments: Array<{ start: number, end: number, text: string }> }}
*/
export const normalizeTranscription = (json) => {
const data = json && typeof json === 'object' ? json : {}
const rawSegments = Array.isArray(data.segments)
? data.segments
: Array.isArray(data.chunks)
? data.chunks
: []
const segments = rawSegments
.map((segment) => {
const timestamps = Array.isArray(segment?.timestamp) ? segment.timestamp : null
const rawStart = segment?.start ?? timestamps?.[0]
const rawEnd = segment?.end ?? timestamps?.[1]
const start = rawStart === null || rawStart === undefined ? Number.NaN : Number(rawStart)
const end = rawEnd === null || rawEnd === undefined ? Number.NaN : Number(rawEnd)
const text = typeof segment?.text === 'string' ? segment.text.trim() : ''
return { start, end, text }
})
.filter(
(segment) =>
Number.isFinite(segment.start) && Number.isFinite(segment.end) && segment.text !== '',
)
return {
text: typeof data.text === 'string' ? data.text.trim() : segments.map((s) => s.text).join(' '),
language: typeof data.language === 'string' ? data.language : null,
duration:
typeof data.duration === 'number' && Number.isFinite(data.duration) ? data.duration : null,
segments,
}
}

View file

@ -111,6 +111,28 @@ export const E2E_AFFECTED_MANIFEST = [
// iCal feed dialog. A change there must wake all three surfaces.
specs: ['campaignActivity', 'campaignAgendaGoogleSync', 'campaignAgendaFeed'],
},
{
// C149 — the Google Calendar OAuth connection surface. The engine/client
// utilities live top-level (not under `src/utilities/activity`), and the
// callback route sits OUTSIDE `(app)` — without this entry a diff to them
// would only wake the home smoke, leaving the mirror spec unrun.
// C150 — the one-click link builder and the campaign actions (picker +
// choose) join the same domain entry.
prefixes: [
'src/utilities/googleCalendarSync.ts',
'src/utilities/googleCalendarSyncHooks.ts',
'src/utilities/googleCalendarClient.ts',
'src/utilities/googleCalendarOAuth.ts',
'src/lib/googleCalendarOAuth.ts',
'src/lib/googleCalendarLink.ts',
'src/components/campaign/activity/AgendaGoogleSyncChrome',
'src/components/campaign/activity/GoogleCalendarSyncDialog',
'src/components/campaign/activity/GoogleCalendarPickerDialog',
'src/app/(campaign)/campanha/actions/googleCalendarSync.ts',
'src/app/(campaign)/campanha/agenda/google-oauth',
],
specs: ['campaignAgendaGoogleSync'],
},
{
prefixes: [
`${CAMPAIGN_APP}/liderancas`,

View file

@ -0,0 +1,423 @@
/**
* C152 pilot: processes 2–3 Câmara speeches end-to-end to de-risk the "acervo
* de falas" source before C153 models it. No DB, no Payload, no collection —
* this is a disposable-data spike whose durable outputs are the pure module
* (`scripts/lib/camaraSpeeches.mjs`), its unit tests and the viability report
* (`docs/research/piloto-fonte-videos-camara.md`).
*
* Flow per speech: open-data discursos → event on that date → speaker excerpt
* on the event page (server-rendered `a`/`t` anchors) → `video-sob-demanda`
* poll (async VOD transcoding) → MP4 download → Deep Infra Whisper large-v3
* (OpenAI-compat `verbose_json`, segments with start/end) → report.
*
* Media/JSON artifacts land under `data/camara/` (gitignored), never in git.
*
* Usage:
* pnpm camara:pilot --legislature 57 --limit 1
* pnpm camara:pilot --date 2016-03-10
* pnpm camara:pilot --legislature 56 --skip-transcribe
*/
import { access, mkdir, readFile, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import {
CAMARA_USER_AGENT,
DEEPINFRA_TRANSCRIBE_URL,
DEEPINFRA_WHISPER_MODEL,
LEGISLATURE_RANGES,
SOLLA_DEPUTY_ID,
buildVodUrl,
matchExcerpt,
normalizeTranscription,
parseEventExcerpts,
parseVodStatus,
selectSpeechEvents,
} from './lib/camaraSpeeches.mjs'
import { dieWithLabel, ensureCachedDownload, loadCliEnv } from './lib/cli.mjs'
loadCliEnv()
const die = dieWithLabel('camara:pilot')
const DEEPINFRA_COST_PER_MINUTE_USD = 0.00045
const VOD_POLL_INTERVAL_MS = 5_000
const VOD_POLL_MAX_ATTEMPTS = 40
const DEFAULT_OUT_DIR = 'data/camara'
// ---------------------------------------------------------------------------
// CLI
// ---------------------------------------------------------------------------
const parseArgs = (argv) => {
const options = {
legislature: null,
date: null,
limit: 1,
speaker: 'Jorge Solla',
out: DEFAULT_OUT_DIR,
skipTranscribe: false,
skipDownload: false,
help: false,
}
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i]
const value = () => {
const next = argv[++i]
if (next === undefined || next.startsWith('--')) die(`faltou valor para ${arg}.`)
return next
}
if (arg === '--help' || arg === '-h') options.help = true
else if (arg === '--skip-transcribe') options.skipTranscribe = true
else if (arg === '--skip-download') options.skipDownload = true
else if (arg === '--legislature') options.legislature = Number(value())
else if (arg === '--date') options.date = value()
else if (arg === '--limit') options.limit = Number(value())
else if (arg === '--speaker') options.speaker = value()
else if (arg === '--out') options.out = value()
else die(`argumento desconhecido: ${arg}`)
}
if (!options.help && !options.date && !LEGISLATURE_RANGES[options.legislature]) {
die('informe --legislature <54|55|56|57> ou --date <YYYY-MM-DD> (veja --help).')
}
if (!options.help && options.date && !/^\d{4}-\d{2}-\d{2}$/.test(options.date)) {
die('--date deve ser YYYY-MM-DD.')
}
if (!Number.isInteger(options.limit) || options.limit < 1) die('--limit deve ser >= 1.')
if (!options.help && options.out.includes('..')) {
die('--out não pode escapar do diretório do repo (sem "..").')
}
return options
}
const HELP = `
Uso: pnpm camara:pilot [--legislature 54|55|56|57] [--date YYYY-MM-DD] [opções]
Opções:
--legislature <n> 54|55|56|57 (range de datas; ignorado se --date)
--date <YYYY-MM-DD> discursos de um único dia (sobrepõe --legislature)
--limit <n> quantos discursos processar (default 1)
--speaker <nome> nome do orador a casar no evento (default "Jorge Solla")
--out <dir> diretório de cache/artefatos (default data/camara)
--skip-download não baixa o MP4 (resolve e registra o VOD)
--skip-transcribe não chama a Deep Infra
--help esta ajuda
`
// ---------------------------------------------------------------------------
// HTTP helpers
// ---------------------------------------------------------------------------
const camaraHeaders = { 'User-Agent': CAMARA_USER_AGENT, Accept: 'application/json' }
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
async function fetchOnce(url, { timeoutMs = 30_000, headers = camaraHeaders } = {}) {
const response = await fetch(url, { headers, signal: AbortSignal.timeout(timeoutMs) })
if (!response.ok) throw new Error(`HTTP ${response.status} em ${url}`)
return response
}
/** The Câmara API drops connections now and then — bounded retry for GETs. */
async function getText(url, { attempts = 3, ...options } = {}) {
let lastError
for (let attempt = 1; attempt <= attempts; attempt += 1) {
try {
return await (await fetchOnce(url, options)).text()
} catch (error) {
lastError = error
if (attempt < attempts) await sleep(2_000)
}
}
throw lastError
}
const getJson = async (url, options) => JSON.parse(await getText(url, options))
// ---------------------------------------------------------------------------
// Pipeline steps
// ---------------------------------------------------------------------------
const speechesUrl = (deputyId, from, to) =>
`https://dadosabertos.camara.leg.br/api/v2/deputados/${deputyId}/discursos` +
`?dataInicio=${from}&dataFim=${to}&itens=100&ordenarPor=dataHoraInicio&ordem=ASC`
const eventsUrl = (date) =>
`https://dadosabertos.camara.leg.br/api/v2/eventos?dataInicio=${date}&dataFim=${date}&itens=100`
const eventPageUrl = (eventId) => `https://www.camara.leg.br/evento-legislativo/${eventId}`
const fileExists = async (path) => {
try {
await access(path)
return true
} catch {
return false
}
}
const resolveRange = (options) => {
if (options.date) return { from: options.date, to: options.date }
const [from, to] = LEGISLATURE_RANGES[options.legislature]
return { from, to }
}
/** Polls the async VOD generation until PRONTO (or gives up). */
async function resolveVod(eventId, excerpt) {
const url = buildVodUrl(eventId, excerpt.audioId, excerpt.tMs)
let lastStatus = null
for (let attempt = 1; attempt <= VOD_POLL_MAX_ATTEMPTS; attempt += 1) {
const status = parseVodStatus(await getJson(url, { timeoutMs: 60_000 }))
lastStatus = status
if (status.state === 'PRONTO') return { url, status, attempts: attempt }
if (status.state === 'INDISPONIVEL') return { url, status, attempts: attempt }
await sleep(VOD_POLL_INTERVAL_MS)
}
return { url, status: lastStatus, attempts: VOD_POLL_MAX_ATTEMPTS }
}
const downloadToBuffer = async (url) => {
let lastError
for (let attempt = 1; attempt <= 3; attempt += 1) {
try {
const response = await fetchOnce(url, {
timeoutMs: 120_000,
headers: { 'User-Agent': CAMARA_USER_AGENT },
})
return Buffer.from(await response.arrayBuffer())
} catch (error) {
lastError = error
if (attempt < 3) await sleep(3_000)
}
}
throw lastError
}
async function transcribe(mp4Buffer) {
const apiKey = process.env.DEEPINFRA_API_KEY
if (!apiKey) die('DEEPINFRA_API_KEY ausente — configure no .env.local ou no env do processo.')
const form = new FormData()
form.append('file', new Blob([mp4Buffer], { type: 'video/mp4' }), 'trecho.mp4')
form.append('model', DEEPINFRA_WHISPER_MODEL)
form.append('language', 'pt')
form.append('response_format', 'verbose_json')
form.append('timestamp_granularities[]', 'segment')
const startedAt = Date.now()
const response = await fetch(DEEPINFRA_TRANSCRIBE_URL, {
method: 'POST',
headers: { Authorization: `Bearer ${apiKey}` },
body: form,
signal: AbortSignal.timeout(600_000),
})
if (!response.ok) {
throw new Error(`Deep Infra HTTP ${response.status}: ${(await response.text()).slice(0, 300)}`)
}
return {
transcription: normalizeTranscription(await response.json()),
elapsedMs: Date.now() - startedAt,
}
}
// ---------------------------------------------------------------------------
// Per-speech orchestration
// ---------------------------------------------------------------------------
async function processSpeech(speech, options) {
const report = {
speechAt: speech.dataHoraInicio,
type: speech.tipoDiscurso,
phase: speech.faseEvento?.titulo ?? null,
summary: speech.sumario ?? null,
officialTranscriptChars: (speech.transcricao ?? '').length,
oficialKeywords: (speech.keywords ?? '').split(/[\r\n]+/).filter(Boolean).length,
event: null,
eventUrl: null,
youtube: null,
excerpt: null,
vodState: null,
vodUrl: null,
vodAttempts: null,
downloadUrl: null,
mp4: null,
transcription: null,
failures: [],
}
try {
const date = speech.dataHoraInicio.slice(0, 10)
const events = (await getJson(eventsUrl(date))).dados ?? []
const candidates = selectSpeechEvents(events, speech.dataHoraInicio)
if (candidates.length === 0) {
report.failures.push(`nenhum evento em ${date}`)
return report
}
for (const event of candidates) {
const html = await getText(eventPageUrl(event.id), { timeoutMs: 60_000 })
const excerpt = matchExcerpt(
parseEventExcerpts(html, event.id),
speech.dataHoraInicio,
options.speaker,
)
if (!excerpt) continue
report.event = {
id: event.id,
type: event.descricaoTipo,
start: event.dataHoraInicio,
status: event.situacao,
}
report.eventUrl = eventPageUrl(event.id)
report.youtube = event.urlRegistro || null
report.excerpt = excerpt
break
}
if (!report.excerpt) {
report.failures.push(`trecho de "${options.speaker}" não encontrado no(s) evento(s) do dia`)
return report
}
const cacheKey = `${report.event.id}-${report.excerpt.audioId}-${report.excerpt.tMs}`
const cachePath = join(options.out, `${cacheKey}.mp4`)
if (await fileExists(cachePath)) {
report.mp4 = { path: cachePath, bytes: (await readFile(cachePath)).length, cached: true }
} else {
const vod = await resolveVod(report.event.id, report.excerpt)
report.vodState = vod.status.state
report.vodUrl = vod.url
report.vodAttempts = vod.attempts
report.downloadUrl = vod.status.video?.downloadUrl ?? null
if (report.vodState !== 'PRONTO' || !report.downloadUrl) {
report.failures.push(`VOD não ficou PRONTO (estado=${report.vodState})`)
return report
}
if (!options.skipDownload) {
const cached = await ensureCachedDownload({
label: 'camara:pilot',
key: cacheKey,
url: report.downloadUrl,
ext: 'mp4',
cacheDir: options.out,
download: downloadToBuffer,
})
report.mp4 = {
path: join(options.out, `${cacheKey}.mp4`),
bytes: cached.buffer.length,
sha256: cached.hash,
cached: false,
}
}
}
if (!options.skipTranscribe && report.mp4) {
const buffer = await readFile(report.mp4.path)
const { transcription, elapsedMs } = await transcribe(buffer)
const estimatedCostUsd = transcription.duration
? (transcription.duration / 60) * DEEPINFRA_COST_PER_MINUTE_USD
: null
report.transcription = {
language: transcription.language,
durationSeconds: transcription.duration,
segmentCount: transcription.segments.length,
firstSegment: transcription.segments[0] ?? null,
lastSegment: transcription.segments.at(-1) ?? null,
textPreview: transcription.text.slice(0, 300),
elapsedMs,
estimatedCostUsd,
}
}
} catch (error) {
report.failures.push(error?.message || String(error))
}
return report
}
// ---------------------------------------------------------------------------
// Report
// ---------------------------------------------------------------------------
const seconds = (ms) => `${(ms / 1000).toFixed(1)}s`
function printReport(reports) {
console.log('\n=== Relatório do piloto C152 ===')
for (const report of reports) {
console.log(`\n• discurso ${report.speechAt} — ${report.type ?? '?'} (${report.phase ?? '?'})`)
console.log(` resumo: ${(report.summary ?? '').slice(0, 90)}`)
console.log(
` transcrição oficial: ${report.officialTranscriptChars} chars | keywords: ${report.oficialKeywords}`,
)
if (report.event) {
console.log(
` evento: ${report.event.id} ${report.event.type} @ ${report.event.start} (${report.event.status})`,
)
console.log(` página: ${report.eventUrl}`)
console.log(` youtube: ${report.youtube ?? '—'}`)
}
if (report.excerpt) {
console.log(
` trecho: a=${report.excerpt.audioId} t=${report.excerpt.tMs} ` +
`${report.excerpt.speaker} ${report.excerpt.party ?? ''} ` +
`${report.excerpt.startTime ?? '?'} ${report.excerpt.duration ?? '?'}`,
)
}
if (report.vodState) console.log(` VOD: ${report.vodState} após ${report.vodAttempts} poll(s)`)
if (report.downloadUrl) console.log(` download: ${report.downloadUrl}`)
if (report.mp4)
console.log(` MP4: ${report.mp4.path} (${(report.mp4.bytes / 1e6).toFixed(1)} MB)`)
if (report.transcription) {
const t = report.transcription
console.log(
` ASR: ${t.segmentCount} segmentos | ${t.durationSeconds?.toFixed(1) ?? '?'}s | ` +
`${seconds(t.elapsedMs)} | ~US$ ${t.estimatedCostUsd?.toFixed(5) ?? '?'}`,
)
if (t.firstSegment)
console.log(
` primeiro: [${t.firstSegment.start}s–${t.firstSegment.end}s] ${t.firstSegment.text}`,
)
if (t.lastSegment)
console.log(
` último: [${t.lastSegment.start}s–${t.lastSegment.end}s] ${t.lastSegment.text}`,
)
}
if (report.failures.length > 0) console.log(` FALHAS: ${report.failures.join(' | ')}`)
}
const ok = reports.filter((r) => r.transcription?.segmentCount > 0).length
console.log(`\nResultado: ${ok}/${reports.length} discurso(s) com transcrição segmentada.`)
}
// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------
async function main() {
const options = parseArgs(process.argv.slice(2))
if (options.help) {
console.log(HELP)
process.exit(0)
}
const { from, to } = resolveRange(options)
console.log(
`[camara:pilot] deputado ${SOLLA_DEPUTY_ID} | ${from}..${to} | speaker "${options.speaker}"`,
)
const speeches = (await getJson(speechesUrl(SOLLA_DEPUTY_ID, from, to))).dados ?? []
const targets = speeches
.filter((s) => (s.transcricao ?? '').trim() !== '')
.slice(0, options.limit)
if (targets.length === 0) die(`nenhum discurso com transcrição em ${from}..${to}.`)
const reports = []
for (const speech of targets) {
reports.push(await processSpeech(speech, options))
}
printReport(reports)
const reportPath = join(options.out, 'pilot-report.json')
await mkdir(options.out, { recursive: true })
await writeFile(reportPath, JSON.stringify(reports, null, 2))
console.log(`\n[camara:pilot] relatório JSON: ${reportPath}`)
}
main().catch((error) => die(error?.message || String(error)))

View file

@ -8,9 +8,13 @@ import {
revokeCalendarFeed,
} from '@/app/(campaign)/campanha/actions/calendarFeed'
import {
chooseGoogleCalendar,
disconnectGoogleCalendarOAuth,
getGoogleCalendarSyncState,
listGoogleCalendars,
runGoogleCalendarSyncNow,
setGoogleCalendarSyncDisabled,
startGoogleCalendarOAuth,
} from '@/app/(campaign)/campanha/actions/googleCalendarSync'
import { ActivityAgenda } from '@/components/campaign/activity/ActivityAgenda'
import { ActivityAgendaFilters } from '@/components/campaign/activity/ActivityAgendaFilters'
@ -102,6 +106,22 @@ export default async function AgendaPage({ searchParams }: AgendaPageProps) {
'use server'
return setGoogleCalendarSyncDisabled(disabled)
}}
onStartOAuth={async () => {
'use server'
return startGoogleCalendarOAuth()
}}
onDisconnect={async () => {
'use server'
return disconnectGoogleCalendarOAuth()
}}
onListCalendars={async () => {
'use server'
return listGoogleCalendars()
}}
onChooseCalendar={async (calendarId) => {
'use server'
return chooseGoogleCalendar(calendarId)
}}
/>
<CampaignListPendingBoundary>

View file

@ -1,14 +1,31 @@
'use server'
import { randomBytes } from 'node:crypto'
import type { CampaignUser } from '@/payload-types'
import type { Payload } from 'payload'
import { buildGoogleCalendarAddLink } from '@/lib/googleCalendarLink'
import { getCampaignActionContext, reloadStaffActor } from '@/utilities/campaignActionContext'
import { buildGoogleCalendarOAuthAuthorizeUrl } from '@/lib/googleCalendarOAuth'
import { canManageGoogleCalendarConnection } from '@/utilities/access/googleCalendarSync'
import {
getCampaignActionContext,
reloadCampaignActor,
reloadStaffActor,
} from '@/utilities/campaignActionContext'
import {
buildGoogleCalendarOAuthRedirectUri,
readGoogleCalendarOAuthCredentials,
storeGoogleCalendarOAuthState,
} from '@/utilities/googleCalendarOAuth'
import {
clearGoogleCalendarOAuthConnection,
listGoogleCalendarPickerOptions,
loadGoogleCalendarSyncConfig,
readGoogleCalendarSyncView,
runCampaignCalendarSync,
setCampaignPrimaryCalendarId,
type GoogleCalendarPickerOption,
type GoogleCalendarSyncView,
} from '@/utilities/googleCalendarSync'
@ -16,21 +33,48 @@ const GOOGLE_CALENDAR_SYNC_STAFF_ONLY_MESSAGE =
'Apenas a equipe da campanha pode gerenciar a sincronização com o Google.'
const GOOGLE_CALENDAR_SYNC_FAILED_MESSAGE =
'Não foi possível atualizar o estado da sincronização com o Google.'
const GOOGLE_CALENDAR_OAUTH_MANAGER_ONLY_MESSAGE =
'Apenas candidato ou coordenação pode conectar ou desconectar a conta Google da campanha.'
const GOOGLE_CALENDAR_OAUTH_UNAVAILABLE_MESSAGE =
'A conexão com o Google ainda não está configurada no servidor. Fale com a equipe técnica.'
const GOOGLE_CALENDAR_PRIMARY_MANAGER_ONLY_MESSAGE =
'Apenas candidato ou coordenação pode escolher o calendário principal da campanha.'
const GOOGLE_CALENDAR_PRIMARY_INVALID_MESSAGE = 'Calendário inválido.'
export type GoogleCalendarSyncActionResult = {
ok: boolean
message?: string
/** C149 — the actor may connect/disconnect (candidate or coordinator). */
canManageConnection: boolean
} & GoogleCalendarSyncView & { addLink: string | null }
const withLinks = (view: GoogleCalendarSyncView): Omit<GoogleCalendarSyncActionResult, 'ok'> => ({
export type GoogleCalendarListActionResult =
| { ok: true; calendars: GoogleCalendarPickerOption[] }
| { ok: false; message: string }
export type GoogleCalendarOAuthStartResult =
| { ok: true; authorizeUrl: string }
| { ok: false; message: string }
const withLinks = (
view: GoogleCalendarSyncView,
): Omit<GoogleCalendarSyncActionResult, 'ok' | 'canManageConnection'> => ({
...view,
addLink: view.calendarId ? buildGoogleCalendarAddLink(view.calendarId) : null,
})
const failure = (message: string): GoogleCalendarSyncActionResult => ({
const failure = (
message: string,
canManageConnection: boolean,
): GoogleCalendarSyncActionResult => ({
ok: false,
message,
canManageConnection,
status: 'not-configured',
connection: 'not-configured',
oauthAvailable: false,
oauthConnectedAt: null,
oauthError: null,
calendarId: null,
lastSyncedAt: null,
lastSuccessAt: null,
@ -44,16 +88,33 @@ const failure = (message: string): GoogleCalendarSyncActionResult => ({
const requireStaff = async (payload: Payload, actor: CampaignUser): Promise<CampaignUser> =>
reloadStaffActor(payload, actor, GOOGLE_CALENDAR_SYNC_STAFF_ONLY_MESSAGE)
/**
* C149 — reloads the actor and returns them only when they may manage the
* connection (candidate/coordinator). The role check runs on the fresh
* document; `null` means "refused", never "not loaded".
*/
const loadConnectionManager = async (
payload: Payload,
actor: CampaignUser,
): Promise<CampaignUser | null> => {
const currentActor = await reloadCampaignActor(payload, actor)
return canManageGoogleCalendarConnection(currentActor) ? currentActor : null
}
/** Read model for the agenda pill/dialog — status derived, never stored. */
export const getGoogleCalendarSyncState = async (): Promise<GoogleCalendarSyncActionResult> => {
const { payload, actor } = await getCampaignActionContext()
try {
await requireStaff(payload, actor)
return { ok: true, ...withLinks(await readGoogleCalendarSyncView(payload)) }
const currentActor = await requireStaff(payload, actor)
return {
ok: true,
canManageConnection: canManageGoogleCalendarConnection(currentActor),
...withLinks(await readGoogleCalendarSyncView(payload)),
}
} catch (error) {
console.error('getGoogleCalendarSyncState failed', error)
return failure(GOOGLE_CALENDAR_SYNC_FAILED_MESSAGE)
return failure(GOOGLE_CALENDAR_SYNC_FAILED_MESSAGE, canManageGoogleCalendarConnection(actor))
}
}
@ -62,12 +123,16 @@ export const runGoogleCalendarSyncNow = async (): Promise<GoogleCalendarSyncActi
const { payload, actor } = await getCampaignActionContext()
try {
await requireStaff(payload, actor)
const currentActor = await requireStaff(payload, actor)
await runCampaignCalendarSync(payload, { reason: 'manual' })
return { ok: true, ...withLinks(await readGoogleCalendarSyncView(payload)) }
return {
ok: true,
canManageConnection: canManageGoogleCalendarConnection(currentActor),
...withLinks(await readGoogleCalendarSyncView(payload)),
}
} catch (error) {
console.error('runGoogleCalendarSyncNow failed', error)
return failure(GOOGLE_CALENDAR_SYNC_FAILED_MESSAGE)
return failure(GOOGLE_CALENDAR_SYNC_FAILED_MESSAGE, canManageGoogleCalendarConnection(actor))
}
}
@ -90,9 +155,143 @@ export const setGoogleCalendarSyncDisabled = async (
overrideAccess: false,
})
}
return { ok: true, ...withLinks(await readGoogleCalendarSyncView(payload)) }
return {
ok: true,
canManageConnection: canManageGoogleCalendarConnection(currentActor),
...withLinks(await readGoogleCalendarSyncView(payload)),
}
} catch (error) {
console.error('setGoogleCalendarSyncDisabled failed', error)
return failure(GOOGLE_CALENDAR_SYNC_FAILED_MESSAGE)
return failure(GOOGLE_CALENDAR_SYNC_FAILED_MESSAGE, canManageGoogleCalendarConnection(actor))
}
}
/**
* C150 — lists the calendars of the OAuth-connected account for the primary
* calendar picker. Candidate/coordinator only (the picker is a nucleus
* decision); a Google failure maps to a safe message and never throws.
*/
export const listGoogleCalendars = async (): Promise<GoogleCalendarListActionResult> => {
const { payload, actor } = await getCampaignActionContext()
try {
if (!(await loadConnectionManager(payload, actor))) {
return { ok: false, message: GOOGLE_CALENDAR_PRIMARY_MANAGER_ONLY_MESSAGE }
}
const result = await listGoogleCalendarPickerOptions(payload)
if (!result.ok) return { ok: false, message: result.message }
return { ok: true, calendars: result.calendars }
} catch (error) {
console.error('listGoogleCalendars failed', error)
return { ok: false, message: GOOGLE_CALENDAR_SYNC_FAILED_MESSAGE }
}
}
/**
* C150 — sets the campaign's primary calendar from the picker. The utility
* validates the id against the connected account's live writable list and the
* `afterChange` config hook (D7) reconciles the mirror into the new calendar.
*/
export const chooseGoogleCalendar = async (
calendarId: string,
): Promise<GoogleCalendarSyncActionResult> => {
const { payload, actor } = await getCampaignActionContext()
try {
const currentActor = await loadConnectionManager(payload, actor)
if (!currentActor) return failure(GOOGLE_CALENDAR_PRIMARY_MANAGER_ONLY_MESSAGE, false)
if (typeof calendarId !== 'string' || calendarId.length === 0 || calendarId.length > 1024) {
return failure(GOOGLE_CALENDAR_PRIMARY_INVALID_MESSAGE, true)
}
const result = await setCampaignPrimaryCalendarId(payload, calendarId)
if (!result.ok) return failure(result.message, true)
return {
ok: true,
canManageConnection: true,
...withLinks(await readGoogleCalendarSyncView(payload)),
}
} catch (error) {
console.error('chooseGoogleCalendar failed', error)
return failure(GOOGLE_CALENDAR_SYNC_FAILED_MESSAGE, canManageGoogleCalendarConnection(actor))
}
}
/**
* C149 — starts the OAuth handshake: validates the manager role, ensures the
* singleton connection row exists, stores the signed single-use `state` cookie
* and returns the Google consent URL for the client to navigate to. The
* authorize URL is built from the canonical public origin (never the request),
* so a callback behind the Cloudflare tunnel cannot leak localhost.
*/
export const startGoogleCalendarOAuth = async (): Promise<GoogleCalendarOAuthStartResult> => {
const { payload, actor } = await getCampaignActionContext()
try {
if (!(await loadConnectionManager(payload, actor))) {
return { ok: false, message: GOOGLE_CALENDAR_OAUTH_MANAGER_ONLY_MESSAGE }
}
const credentials = readGoogleCalendarOAuthCredentials()
if (!credentials) {
return { ok: false, message: GOOGLE_CALENDAR_OAUTH_UNAVAILABLE_MESSAGE }
}
// Resolved BEFORE any write: a missing canonical origin throws here and
// must not leave a stray connection row behind.
const redirectUri = buildGoogleCalendarOAuthRedirectUri()
// The connection may exist before any calendar is chosen (C150 picks it).
// Payload's Local API without `user` needs the explicit admin bypass; the
// role check above is the authorization for this system write.
const doc = await loadGoogleCalendarSyncConfig(payload)
if (!doc) {
await payload.create({
collection: 'googleCalendarSync',
data: {},
depth: 0,
overrideAccess: true,
})
}
const state = randomBytes(32).toString('base64url')
await storeGoogleCalendarOAuthState(state, actor.id)
return {
ok: true,
authorizeUrl: buildGoogleCalendarOAuthAuthorizeUrl({
clientId: credentials.clientId,
redirectUri,
state,
}),
}
} catch (error) {
console.error('startGoogleCalendarOAuth failed', error)
return { ok: false, message: GOOGLE_CALENDAR_SYNC_FAILED_MESSAGE }
}
}
/**
* C149 — disconnects the OAuth account from the Teqo: drops the refresh token
* and the connection state. The UI guides revoking the app access on the
* Google account; the service account, when configured, takes over on the next
* trigger.
*/
export const disconnectGoogleCalendarOAuth = async (): Promise<GoogleCalendarSyncActionResult> => {
const { payload, actor } = await getCampaignActionContext()
try {
const currentActor = await loadConnectionManager(payload, actor)
if (!currentActor) {
return failure(GOOGLE_CALENDAR_OAUTH_MANAGER_ONLY_MESSAGE, false)
}
await clearGoogleCalendarOAuthConnection(payload)
return {
ok: true,
canManageConnection: true,
...withLinks(await readGoogleCalendarSyncView(payload)),
}
} catch (error) {
console.error('disconnectGoogleCalendarOAuth failed', error)
return failure(GOOGLE_CALENDAR_SYNC_FAILED_MESSAGE, canManageGoogleCalendarConnection(actor))
}
}

View file

@ -0,0 +1,127 @@
import config from '@payload-config'
import { NextResponse, type NextRequest } from 'next/server'
import { getPayload } from 'payload'
import { canManageGoogleCalendarConnection } from '@/utilities/access/googleCalendarSync'
import { getCampaignInviteBaseURL } from '@/utilities/campaignInviteOrigin'
import {
buildGoogleCalendarOAuthRedirectUri,
clearGoogleCalendarOAuthState,
exchangeGoogleCalendarOAuthCode,
GoogleCalendarOAuthError,
readGoogleCalendarOAuthCredentials,
readGoogleCalendarOAuthState,
} from '@/utilities/googleCalendarOAuth'
import {
loadGoogleCalendarSyncConfig,
recordGoogleCalendarOAuthConnection,
recordGoogleCalendarOAuthError,
runCampaignCalendarSync,
} from '@/utilities/googleCalendarSync'
/**
* C149 — the OAuth callback registered in the GCP client. Google returns the
* browser here after consent with `code + state` (or `error` when the user
* denies). It lives OUTSIDE `(app)` on purpose: it is a ceremony route like
* the WebAuthn ones, authenticated by the signed single-use state cookie and
* not by a page session.
*
* The exchange is the only step that matters — the refresh token lands on the
* singleton `googleCalendarSync` row and the derived connection state becomes
* `connected`; a failure records `oauthError` so the UI offers reconnect. The
* browser always ends on `/campanha/agenda` (no query param): the agenda page
* canonicalizes unknown params away, so the state itself is the feedback.
*/
export const dynamic = 'force-dynamic'
/** The code exchange plus (when a calendar is configured) a full sync pass. */
export const maxDuration = 60
const AGENDA_PATH = '/campanha/agenda'
const agendaRedirect = (request: NextRequest): NextResponse => {
try {
return NextResponse.redirect(new URL(AGENDA_PATH, getCampaignInviteBaseURL()))
} catch {
// Only reachable when NEXT_PUBLIC_SITE_URL is missing in production —
// still send the user back to the page instead of a dead end.
return NextResponse.redirect(new URL(AGENDA_PATH, request.nextUrl.origin))
}
}
export const GET = async (request: NextRequest): Promise<NextResponse> => {
const payload = await getPayload({ config })
const searchParams = request.nextUrl.searchParams
const providedState = searchParams.get('state') ?? ''
const errorParam = searchParams.get('error')
const code = searchParams.get('code')
try {
// `access_denied` is the user saying no — not an error to surface, and
// there is no code to exchange.
if (errorParam || !code) {
return agendaRedirect(request)
}
const state = await readGoogleCalendarOAuthState(providedState)
// Burn before the exchange: a captured callback cannot be replayed even
// if the exchange itself fails.
await clearGoogleCalendarOAuthState()
// Re-check the role against the FRESH document: the consent navigation
// may have outlived a downgrade. The signed state binds the actor; the
// role check is what authorizes the system write below. Intentional admin
// bypass on the reload (the fresh-role read is the trusted check).
const actor = await payload.findByID({
collection: 'campaignUser',
id: state.userId,
depth: 0,
overrideAccess: true,
})
if (!canManageGoogleCalendarConnection(actor)) {
throw new GoogleCalendarOAuthError(
'Apenas candidato ou coordenação pode conectar a conta Google da campanha.',
)
}
const credentials = readGoogleCalendarOAuthCredentials()
if (!credentials) {
throw new GoogleCalendarOAuthError('A conexão com o Google não está configurada no servidor.')
}
// Only an EXCHANGE failure flips the connection state to `error` — a
// refused role or a missing client env leaves the stored connection
// untouched (the engine clears a transient exchange error on the next
// successful pass with the previous token).
const tokens = await exchangeGoogleCalendarOAuthCode({
code,
redirectUri: buildGoogleCalendarOAuthRedirectUri(),
credentials,
}).catch(async (error: unknown) => {
if (error instanceof GoogleCalendarOAuthError) {
await recordGoogleCalendarOAuthError(payload, error.message).catch(() => {})
}
throw error
})
await recordGoogleCalendarOAuthConnection(payload, {
refreshToken: tokens.refreshToken,
scope: tokens.scope,
})
const doc = await loadGoogleCalendarSyncConfig(payload)
if (doc?.calendarId) {
await runCampaignCalendarSync(payload, { reason: 'config-change' })
}
return agendaRedirect(request)
} catch (error) {
const message =
error instanceof Error ? error.message : 'Erro desconhecido ao conectar com o Google.'
payload.logger.error(`[GoogleCalendarSync] Callback OAuth falhou: ${message}`)
return agendaRedirect(request)
} finally {
await clearGoogleCalendarOAuthState().catch(() => {})
}
}

View file

@ -1,19 +1,20 @@
import Link from 'next/link'
import { CardModelGallery } from '@/components/cards/CardModelGallery'
import { brexterBold } from '@/app/(frontend)/fonts'
import { CardsStudio } from '@/components/cards/CardsStudio'
/**
* S13 — the home invitation to the card funnel: short copy + the three model
* tiles, positioned after the newsletter capture (which stays the first
* conversion of the page end) and before the footer. Each tile deep-links into
* `/cards` with its model selected; the general CTA opens the plain catalog.
* S14 — the home invitation to the card funnel: short copy + the three model
* tiles, positioned right before the newsletter capture (which stays the last
* conversion block). Tapping a tile opens the SAME composer island used by
* `/cards` right here (dialog on desktop, drawer on mobile) — no navigation and
* no separate CTA. `brexterBold.variable` includes the display face in the page
* so the name-tile canvas (family passed as a prop) can load it.
*/
export const CampaignCardsSection = () => (
<section
id="cards"
aria-labelledby="cards-title"
data-home-section="cards"
className="border-b border-(--campaign-line) bg-(--campaign-cream)"
className={`border-b border-(--campaign-line) bg-(--campaign-cream) ${brexterBold.variable}`}
>
<div className="mx-auto w-full max-w-[1160px] px-5 py-12 sm:px-8 lg:px-10 lg:py-16">
<div className="mx-auto max-w-2xl text-center">
@ -32,16 +33,7 @@ export const CampaignCardsSection = () => (
</p>
</div>
<CardModelGallery variant="link" ariaLabel="Modelos de card" />
<div className="mt-8 text-center">
<Link
href="/cards"
className="inline-flex min-h-12 w-full items-center justify-center rounded-lg bg-(--pt-red) px-6 text-sm font-extrabold text-white transition hover:brightness-95 focus-visible:ring-2 focus-visible:ring-(--pt-red) focus-visible:ring-offset-2 focus-visible:outline-none sm:w-auto"
>
Criar meu card
</Link>
</div>
<CardsStudio fontFamily={brexterBold.style.fontFamily} />
</div>
</section>
)

View file

@ -236,8 +236,8 @@ export default async function HomePage() {
</section>
<CampaignStorySection />
<CampaignNewsletterSection pixelId={pixelId ?? undefined} />
<CampaignCardsSection />
<CampaignNewsletterSection pixelId={pixelId ?? undefined} />
</main>
<CampaignFooter />

View file

@ -1,5 +1,6 @@
import { RefreshRouteOnSave } from '@/components/RefreshRouteOnSave'
import { ThemeProvider } from '@/components/ThemeProvider'
import { isStagingSite } from '@/lib/siteEnvironment'
import { getCachedDocumentById } from '@/utilities/documentReads'
import { getCachedGlobal } from '@/utilities/globalReads'
import { resolveSiteMetadata } from '@/utilities/seo'
@ -37,10 +38,7 @@ export async function generateMetadata(): Promise<Metadata> {
],
creator: 'Francisco Solla',
publisher: 'Teqo',
robots: {
index: true,
follow: true,
},
robots: isStagingSite() ? { index: false, follow: false } : { index: true, follow: true },
openGraph: {
type: 'website',
locale: 'pt-BR',

View file

@ -175,6 +175,11 @@ body,
--campaign-cream: #fff8f2;
--campaign-ink: #000000;
--campaign-muted: #6c615e;
/* S14 — the campaign theme is light: the near-white `--muted-foreground`
inherited from `:root` (built for the dark pages) is illegible on white.
Point it at the campaign gray (~6:1) so generic descriptions — e.g. the
card composer help text — read correctly in dialogs/drawers. */
--muted-foreground: var(--campaign-muted);
--campaign-surface: #f9faff;
--campaign-band: #ebe9e9;
--campaign-line: rgb(0 0 0 / 12%);

20
src/app/robots.ts Normal file
View file

@ -0,0 +1,20 @@
import type { MetadataRoute } from 'next'
import { isStagingSite } from '@/lib/siteEnvironment'
/**
* Staging is a throwaway validation target — it must never be indexed
* (OPS103). Production keeps the allow-all behavior it had implicitly (there
* was no robots.txt before OPS103).
*/
export default function robots(): MetadataRoute.Robots {
if (isStagingSite()) {
return {
rules: { userAgent: '*', disallow: '/' },
}
}
return {
rules: { userAgent: '*', allow: '/' },
}
}

View file

@ -57,6 +57,7 @@ const activityStaffFieldSnapshot = (doc: Record<string, unknown>) => ({
municipality: relationshipId(doc.municipality),
locality: trimmedText(doc.locality),
deputyPresent: Boolean(doc.deputyPresent),
publicEvent: Boolean(doc.publicEvent),
organizations: relationshipIds(doc.organizations),
responsible: JSON.stringify(
parseActivityResponsibleEntries(doc.responsible)
@ -514,6 +515,21 @@ export const Activity: CollectionConfig = {
description: 'Compromisso que ocupa um ou mais dias inteiros, sem horário.',
},
},
{
// C151 — marks a staff intent to expose this activity as a public event
// in the candidate's website (a future PUB item). The flag is durable and
// consultable; nothing consumes it yet and it does not affect the agenda,
// the list, or the Google Calendar mirror.
name: 'publicEvent',
type: 'checkbox',
label: 'Evento público',
defaultValue: false,
index: true,
admin: {
description:
'Quando marcado, este evento poderá ser publicado no site do candidato (futuro).',
},
},
{
name: 'startAt',
type: 'date',

View file

@ -18,6 +18,12 @@ import { googleCalendarSyncConfigHook } from '@/utilities/googleCalendarSyncHook
* account private key never lives here — it is `GOOGLE_CALENDAR_SERVICE_ACCOUNT_KEY`
* in the environment. Changing `calendarId` (or re-enabling) re-runs the full
* reconciliation automatically via `googleCalendarSyncConfigHook` (D7).
*
* C149 — the same row also holds the OAuth connection (refresh token + state)
* created by the "Conectar com o Google" button. The refresh token is
* system-only and unreadable by every user path (`read: false`), exactly like
* the push-channel secret; the engine reads it with the admin bypass. The
* service account remains the fallback while no OAuth connection exists.
*/
export const GoogleCalendarSync: CollectionConfig = {
slug: 'googleCalendarSync',
@ -60,6 +66,64 @@ export const GoogleCalendarSync: CollectionConfig = {
'O calendarId do calendário "Agenda da Campanha" na conta Google da campanha (ex.: c_…@group.calendar.google.com). O calendário precisa estar público no link e a service account com permissão de edição.',
},
},
{
name: 'oauthRefreshToken',
type: 'text',
label: 'Token de atualização (OAuth)',
access: {
create: canSetGoogleCalendarSyncSystemField,
read: canReadGoogleCalendarSyncIdentityField,
update: canSetGoogleCalendarSyncSystemField,
},
admin: {
readOnly: true,
description:
'Credencial da conexão OAuth com a conta Google da campanha. Preenchida pelo callback do botão "Conectar com o Google"; nunca é exibida.',
},
},
{
name: 'oauthScope',
type: 'text',
label: 'Escopos concedidos (OAuth)',
access: {
create: canSetGoogleCalendarSyncSystemField,
update: canSetGoogleCalendarSyncSystemField,
},
admin: {
readOnly: true,
description: 'Escopos que o Google devolveu na conexão (diagnóstico).',
},
},
{
name: 'oauthConnectedAt',
type: 'date',
label: 'Conta Google conectada em',
access: {
create: canSetGoogleCalendarSyncSystemField,
update: canSetGoogleCalendarSyncSystemField,
},
admin: { readOnly: true },
},
{
name: 'oauthErrorAt',
type: 'date',
label: 'Último erro de conexão (OAuth)',
access: {
create: canSetGoogleCalendarSyncSystemField,
update: canSetGoogleCalendarSyncSystemField,
},
admin: { readOnly: true },
},
{
name: 'oauthError',
type: 'textarea',
label: 'Mensagem do último erro de conexão (OAuth)',
access: {
create: canSetGoogleCalendarSyncSystemField,
update: canSetGoogleCalendarSyncSystemField,
},
admin: { readOnly: true },
},
{
name: 'disabledAt',
type: 'date',

View file

@ -352,6 +352,20 @@ const ActivityOverlayForm = ({
<span>Todo o dia</span>
</Field>
<Field
orientation="horizontal"
className={
sheet ? 'min-h-11 gap-2 rounded-none border-0 px-0' : 'min-h-11 rounded-lg border p-3'
}
>
<Checkbox
name="publicEvent"
defaultChecked={isEdit ? editDraft?.publicEvent : false}
aria-label="Evento público"
/>
<span>Evento público</span>
</Field>
{sheet ? startEndFields : <div className="grid gap-3 sm:grid-cols-2">{startEndFields}</div>}
</>
)

View file

@ -2,16 +2,32 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import type { GoogleCalendarSyncActionResult } from '@/app/(campaign)/campanha/actions/googleCalendarSync'
import { CalendarPlusIcon } from 'lucide-react'
import type {
GoogleCalendarListActionResult,
GoogleCalendarOAuthStartResult,
GoogleCalendarSyncActionResult,
} from '@/app/(campaign)/campanha/actions/googleCalendarSync'
import { GoogleCalendarPickerDialog } from '@/components/campaign/activity/GoogleCalendarPickerDialog'
import { GoogleCalendarSyncDialog } from '@/components/campaign/activity/GoogleCalendarSyncDialog'
import { SetCampaignHeaderAction } from '@/components/campaign/shell/CampaignPageChromeContext'
import { useBridgedQuickAction } from '@/components/campaign/shell/CampaignQuickActionContext'
import { Button } from '@/components/ui/button'
import type { GoogleCalendarSyncStatus } from '@/utilities/googleCalendarSync'
type AgendaGoogleSyncChromeProps = {
initialState: GoogleCalendarSyncActionResult
onSyncNow: () => Promise<GoogleCalendarSyncActionResult>
onSetDisabled: (disabled: boolean) => Promise<GoogleCalendarSyncActionResult>
/** C149 — starts the OAuth handshake; the dialog navigates to the consent URL. */
onStartOAuth: () => Promise<GoogleCalendarOAuthStartResult>
/** C149 — drops the OAuth connection from the Teqo. */
onDisconnect: () => Promise<GoogleCalendarSyncActionResult>
/** C150 — lists the connected account's writable calendars (picker). */
onListCalendars: () => Promise<GoogleCalendarListActionResult>
/** C150 — sets the campaign's primary calendar. */
onChooseCalendar: (calendarId: string) => Promise<GoogleCalendarSyncActionResult>
}
const PILL_COPY: Record<
@ -40,18 +56,30 @@ const PILL_COPY: Record<
},
}
const ADD_TO_GOOGLE_LABEL = 'Adicionar ao meu Google Calendar'
/**
* C114 — agenda page → app chrome bridge for the Google Calendar mirror
* (same pattern as AgendaFeedChrome/C94): the status pill registers in the
* desktop header cluster (after "Link de import"), the mobile FAB opens the
* same dialog, and a paused mirror auto-retries once on mount.
*
* C150 — the chrome also owns the primary-calendar picker (one overlay at a
* time: opening the picker closes the mirror dialog and closing it brings the
* dialog back) and registers the one-click "add to my Google Calendar" link
* for every staff member as soon as a primary calendar exists.
*/
export const AgendaGoogleSyncChrome = ({
initialState,
onSyncNow,
onSetDisabled,
onStartOAuth,
onDisconnect,
onListCalendars,
onChooseCalendar,
}: AgendaGoogleSyncChromeProps) => {
const [open, setOpen] = useState(false)
const [pickerOpen, setPickerOpen] = useState(false)
const [state, setState] = useState(initialState)
const autoRetriedRef = useRef(false)
@ -59,13 +87,17 @@ export const AgendaGoogleSyncChrome = ({
useBridgedQuickAction('openGoogleCalendarSync', openSync)
// "Re-tenta sem ação manual": a paused mirror tries once when the agenda
// page loads (the staff is operating — the natural retry moment).
const handleSyncNow = useCallback(async () => {
const result = await onSyncNow()
// Shared envelope: every action result that succeeded becomes the rendered
// state; failures are left for the caller's UI to surface.
const applyState = useCallback(async (run: () => Promise<GoogleCalendarSyncActionResult>) => {
const result = await run()
if (result.ok) setState(result)
return result
}, [onSyncNow])
}, [])
// "Re-tenta sem ação manual": a paused mirror tries once when the agenda
// page loads (the staff is operating — the natural retry moment).
const handleSyncNow = useCallback(() => applyState(onSyncNow), [applyState, onSyncNow])
useEffect(() => {
if (state.status === 'paused' && !autoRetriedRef.current) {
@ -75,12 +107,28 @@ export const AgendaGoogleSyncChrome = ({
}, [state.status, handleSyncNow])
const handleSetDisabled = useCallback(
async (disabled: boolean) => {
const result = await onSetDisabled(disabled)
if (result.ok) setState(result)
return result
},
[onSetDisabled],
(disabled: boolean) => applyState(() => onSetDisabled(disabled)),
[applyState, onSetDisabled],
)
// C149 — the connection card follows the disconnect without a page reload.
const handleDisconnect = useCallback(() => applyState(onDisconnect), [applyState, onDisconnect])
// C150 — one overlay at a time: the picker replaces the mirror dialog while
// open (nested Radix/vaul overlays have fragile focus/scroll on mobile).
const openPicker = useCallback(() => {
setOpen(false)
setPickerOpen(true)
}, [])
const handlePickerOpenChange = useCallback((next: boolean) => {
setPickerOpen(next)
if (!next) setOpen(true)
}, [])
const handleChooseCalendar = useCallback(
(calendarId: string) => applyState(() => onChooseCalendar(calendarId)),
[applyState, onChooseCalendar],
)
const pill = useMemo(() => {
@ -99,9 +147,41 @@ export const AgendaGoogleSyncChrome = ({
)
}, [state.status, openSync])
const addToGoogle = useMemo(() => {
if (!state.addLink) return null
return (
<>
<Button asChild size="sm" className="hidden shrink-0 whitespace-nowrap md:inline-flex">
<a
href={state.addLink}
target="_blank"
rel="noopener noreferrer"
aria-label={ADD_TO_GOOGLE_LABEL}
>
<CalendarPlusIcon className="mr-2 size-4" aria-hidden />
{ADD_TO_GOOGLE_LABEL}
</a>
</Button>
<Button
asChild
variant="ghost"
size="icon"
className="size-11 shrink-0 md:hidden"
aria-label={ADD_TO_GOOGLE_LABEL}
title={ADD_TO_GOOGLE_LABEL}
>
<a href={state.addLink} target="_blank" rel="noopener noreferrer">
<CalendarPlusIcon className="size-5" aria-hidden />
</a>
</Button>
</>
)
}, [state.addLink])
return (
<>
<SetCampaignHeaderAction id="google-calendar-sync">{pill}</SetCampaignHeaderAction>
<SetCampaignHeaderAction id="google-calendar-add">{addToGoogle}</SetCampaignHeaderAction>
<GoogleCalendarSyncDialog
open={open}
@ -109,6 +189,17 @@ export const AgendaGoogleSyncChrome = ({
state={state}
onSyncNow={handleSyncNow}
onSetDisabled={handleSetDisabled}
onStartOAuth={onStartOAuth}
onDisconnect={handleDisconnect}
onOpenPicker={openPicker}
/>
<GoogleCalendarPickerDialog
open={pickerOpen}
onOpenChange={handlePickerOpenChange}
currentCalendarId={state.calendarId}
onListCalendars={onListCalendars}
onChooseCalendar={handleChooseCalendar}
/>
</>
)

View file

@ -0,0 +1,288 @@
'use client'
import { useCallback, useEffect, useRef, useState } from 'react'
import { RefreshCwIcon } from 'lucide-react'
import type {
GoogleCalendarListActionResult,
GoogleCalendarSyncActionResult,
} from '@/app/(campaign)/campanha/actions/googleCalendarSync'
import { Button } from '@/components/ui/button'
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import {
Drawer,
DrawerCloseButton,
DrawerContent,
DrawerDescription,
DrawerFooter,
DrawerHeader,
DrawerTitle,
} from '@/components/ui/Drawer'
import { useIsMobile } from '@/hooks/use-mobile'
import { cn } from '@/lib/utils'
import type { GoogleCalendarPickerOption } from '@/utilities/googleCalendarSync'
type GoogleCalendarPickerDialogProps = {
open: boolean
onOpenChange: (open: boolean) => void
/** The calendar currently in use, marked and preselected. */
currentCalendarId: string | null
onListCalendars: () => Promise<GoogleCalendarListActionResult>
onChooseCalendar: (calendarId: string) => Promise<GoogleCalendarSyncActionResult>
}
type PickerListStatus = 'loading' | 'error' | 'ready'
const TITLE = 'Calendário principal da campanha'
const DESCRIPTION = 'Atividades criadas e editadas no Teqo espelham no calendário escolhido.'
const LIST_FAILED_MESSAGE = 'Não foi possível listar os calendários agora.'
const CalendarOption = ({
calendar,
isSelected,
isCurrent,
disabled,
onSelect,
}: {
calendar: GoogleCalendarPickerOption
isSelected: boolean
isCurrent: boolean
disabled: boolean
onSelect: () => void
}) => (
<button
type="button"
aria-pressed={isSelected}
onClick={onSelect}
disabled={disabled}
className={cn(
'flex w-full items-center gap-3 rounded-lg border p-3 text-left transition-colors focus-visible:outline-none focus-visible:ring-3 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-60',
isSelected ? 'border-primary bg-primary/5' : 'border-border hover:bg-muted',
)}
>
<span
className={cn(
'flex h-4 w-4 shrink-0 items-center justify-center rounded-full border',
isSelected ? 'border-primary' : 'border-muted-foreground',
)}
aria-hidden
>
{isSelected ? <span className="h-2 w-2 rounded-full bg-primary" /> : null}
</span>
<span className="min-w-0 flex-1">
<span className="block truncate text-sm">{calendar.summary}</span>
{calendar.primary ? (
<span className="block text-xs text-muted-foreground">Calendário principal da conta</span>
) : null}
</span>
{isCurrent ? <span className="shrink-0 text-xs text-muted-foreground">em uso</span> : null}
</button>
)
/**
* C150 — primary-calendar picker. The list is fetched live from the connected
* Google account on every open (the account's calendars can change under us);
* only candidate/coordination reach this dialog (the trigger is gated in the
* sync dialog) and the server action re-validates both the role and the
* calendar membership before writing.
*/
export const GoogleCalendarPickerDialog = ({
open,
onOpenChange,
currentCalendarId,
onListCalendars,
onChooseCalendar,
}: GoogleCalendarPickerDialogProps) => {
const isMobile = useIsMobile()
const [status, setStatus] = useState<PickerListStatus>('loading')
const [calendars, setCalendars] = useState<GoogleCalendarPickerOption[]>([])
const [listError, setListError] = useState<string | null>(null)
const [selectedId, setSelectedId] = useState<string | null>(null)
const [chooseError, setChooseError] = useState<string | null>(null)
const [isChoosing, setIsChoosing] = useState(false)
const [reloadCount, setReloadCount] = useState(0)
// A session is one open→close cycle: results from a previous session never
// apply to the next one (a choose in flight when the picker is closed and
// reopened must not close/relabel the new session).
const sessionRef = useRef(0)
useEffect(() => {
if (!open) return
const session = ++sessionRef.current
let cancelled = false
const isStale = () => cancelled || session !== sessionRef.current
setStatus('loading')
setCalendars([])
setSelectedId(null)
setListError(null)
setChooseError(null)
setIsChoosing(false)
void onListCalendars()
.then((result) => {
if (isStale()) return
if (result.ok) {
setCalendars(result.calendars)
setSelectedId(currentCalendarId)
setStatus('ready')
} else {
setListError(result.message)
setStatus('error')
}
})
.catch(() => {
if (isStale()) return
setListError(LIST_FAILED_MESSAGE)
setStatus('error')
})
return () => {
cancelled = true
}
}, [open, reloadCount, onListCalendars, currentCalendarId])
const retryList = useCallback(() => setReloadCount((value) => value + 1), [])
const handleChoose = async () => {
if (!selectedId || selectedId === currentCalendarId || isChoosing) return
const session = sessionRef.current
setIsChoosing(true)
setChooseError(null)
try {
const result = await onChooseCalendar(selectedId)
if (session !== sessionRef.current) return
if (result.ok) {
onOpenChange(false)
} else {
setChooseError(result.message ?? 'Não foi possível escolher o calendário.')
}
} catch {
if (session !== sessionRef.current) return
setChooseError('Não foi possível escolher o calendário agora.')
} finally {
if (session === sessionRef.current) setIsChoosing(false)
}
}
const listContent =
status === 'loading' ? (
<p className="flex items-center gap-2 text-sm text-muted-foreground" aria-live="polite">
<RefreshCwIcon className="h-4 w-4 animate-spin" aria-hidden />
Carregando calendários...
</p>
) : status === 'error' ? (
<div className="space-y-3">
<p role="alert" className="text-sm text-red-600">
{listError}
</p>
<Button type="button" variant="outline" onClick={retryList}>
Tentar de novo
</Button>
</div>
) : calendars.length === 0 ? (
<div className="space-y-3">
<p className="text-sm text-muted-foreground">
Nenhum calendário com permissão de edição nesta conta Google.
</p>
<Button type="button" variant="outline" onClick={retryList}>
Atualizar lista
</Button>
</div>
) : (
<ul aria-label="Calendários da conta Google conectada" className="space-y-2">
{calendars.map((calendar) => (
<li key={calendar.id}>
<CalendarOption
calendar={calendar}
isSelected={selectedId === calendar.id}
isCurrent={currentCalendarId === calendar.id}
disabled={isChoosing}
onSelect={() => setSelectedId(calendar.id)}
/>
</li>
))}
</ul>
)
const chooseErrorNotice = chooseError ? (
<p role="alert" className="text-sm text-red-600">
{chooseError}
</p>
) : null
const actions =
status === 'ready' && calendars.length > 0 ? (
<div className="flex flex-col gap-3">
{chooseErrorNotice}
<div className="flex justify-end gap-2">
<Button
type="button"
variant="outline"
onClick={() => onOpenChange(false)}
disabled={isChoosing}
>
Cancelar
</Button>
<Button
type="button"
onClick={() => void handleChoose()}
disabled={!selectedId || selectedId === currentCalendarId || isChoosing}
>
{isChoosing ? 'Escolhendo...' : 'Escolher calendário'}
</Button>
</div>
</div>
) : null
if (isMobile) {
return (
<Drawer open={open} onOpenChange={onOpenChange} showSwipeHandle>
<DrawerContent className="max-h-[85vh]">
<DrawerHeader className="text-left">
<DrawerTitle>{TITLE}</DrawerTitle>
<DrawerDescription>{DESCRIPTION}</DrawerDescription>
</DrawerHeader>
<div className="overflow-y-auto px-4 pb-2">
<div className="space-y-4">
{listContent}
{actions}
</div>
</div>
<DrawerFooter className="border-t">
<DrawerCloseButton className="w-full">Fechar</DrawerCloseButton>
</DrawerFooter>
</DrawerContent>
</Drawer>
)
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="flex max-h-[calc(100dvh-2rem)] flex-col gap-0 overflow-hidden p-0 sm:max-w-lg sm:p-0">
<DialogHeader className="shrink-0 border-b px-6 py-4 pr-12 text-left">
<DialogTitle>{TITLE}</DialogTitle>
<DialogDescription>{DESCRIPTION}</DialogDescription>
</DialogHeader>
<div
data-slot="dialog-scroll-body"
className="min-h-0 flex-1 overflow-y-auto overscroll-contain px-6 py-4"
>
{listContent}
</div>
{actions ? (
<div data-slot="dialog-footer" className="shrink-0 border-t px-6 py-4">
{actions}
</div>
) : null}
</DialogContent>
</Dialog>
)
}

View file

@ -4,7 +4,10 @@ import { useState } from 'react'
import { CopyIcon, ExternalLinkIcon, RefreshCwIcon } from 'lucide-react'
import type { GoogleCalendarSyncActionResult } from '@/app/(campaign)/campanha/actions/googleCalendarSync'
import type {
GoogleCalendarOAuthStartResult,
GoogleCalendarSyncActionResult,
} from '@/app/(campaign)/campanha/actions/googleCalendarSync'
import { Button } from '@/components/ui/button'
import {
Dialog,
@ -25,6 +28,11 @@ import {
import { Input } from '@/components/ui/input'
import { useIsMobile } from '@/hooks/use-mobile'
import { formatBahiaDateTimeLabel } from '@/lib/campaignTime'
import {
buildGoogleCalendarAddLink,
buildGoogleCalendarPublicIcalUrl,
} from '@/lib/googleCalendarLink'
import type { GoogleCalendarConnectionStatus } from '@/utilities/googleCalendarSync'
type GoogleCalendarSyncDialogProps = {
open: boolean
@ -32,6 +40,12 @@ type GoogleCalendarSyncDialogProps = {
state: GoogleCalendarSyncActionResult
onSyncNow: () => Promise<GoogleCalendarSyncActionResult>
onSetDisabled: (disabled: boolean) => Promise<GoogleCalendarSyncActionResult>
/** C149 — starts the OAuth handshake; the caller navigates to the returned URL. */
onStartOAuth: () => Promise<GoogleCalendarOAuthStartResult>
/** C149 — drops the OAuth connection from the Teqo. */
onDisconnect: () => Promise<GoogleCalendarSyncActionResult>
/** C150 — opens the primary-calendar picker (candidate/coordination only). */
onOpenPicker: () => void
}
const NOT_CONFIGURED_RUNBOOK: readonly string[] = [
@ -41,11 +55,32 @@ const NOT_CONFIGURED_RUNBOOK: readonly string[] = [
'Um administrador configura o ID do calendário no Painel e a chave da service account nas variáveis de ambiente.',
]
const CONNECTION_BADGE: Record<
GoogleCalendarConnectionStatus,
{ label: string; className: string }
> = {
connected: {
label: 'Conectado',
className: 'border-green-300 bg-green-50 text-green-700',
},
error: {
label: 'Erro',
className: 'border-amber-300 bg-amber-50 text-amber-700',
},
'not-configured': {
label: 'Não configurado',
className: 'border-border text-muted-foreground',
},
}
const copyIcon = <CopyIcon className="h-4 w-4" />
/**
* C114 — Google Calendar mirror dialog (estados da jornada do canvas:
* não configurado / sincronizado / pausado / desativado). Bottom sheet on
* C114/C115/C149 — Google Calendar mirror dialog. The OAuth connection card
* (C149) leads every state: `não configurado` offers the one-click connect
* (or the admin runbook when the server has no OAuth client), `conectado`
* offers reconnect/disconnect and `erro` offers the reconnect path. The
* mirror-state blocks (C114/C115) stay below, untouched. Bottom sheet on
* mobile, dialog on desktop — same chrome as the iCal feed dialog (C94).
*/
export const GoogleCalendarSyncDialog = ({
@ -54,6 +89,9 @@ export const GoogleCalendarSyncDialog = ({
state,
onSyncNow,
onSetDisabled,
onStartOAuth,
onDisconnect,
onOpenPicker,
}: GoogleCalendarSyncDialogProps) => {
const isMobile = useIsMobile()
const [isBusy, setIsBusy] = useState(false)
@ -65,67 +103,95 @@ export const GoogleCalendarSyncDialog = ({
setActionError(null)
}
// C150 — the one-click button and the manual path ("Por URL", Apple
// Calendar, Outlook) are both derived from the configured calendar.
const addLink = state.calendarId ? buildGoogleCalendarAddLink(state.calendarId) : null
const icalUrl = state.calendarId ? buildGoogleCalendarPublicIcalUrl(state.calendarId) : null
const handleCopy = async () => {
if (!state.addLink) return
await navigator.clipboard.writeText(state.addLink)
if (!icalUrl) return
await navigator.clipboard.writeText(icalUrl)
setCopied(true)
setTimeout(() => setCopied(false), 2000)
}
const handleSyncNow = async () => {
if (isBusy) return
/**
* Shared busy/error envelope: every card action maps a failed result to the
* same `actionError` line and never leaves the buttons stuck in busy.
*/
const runAction = async <T extends { ok: boolean; message?: string }>(
run: () => Promise<T>,
fallbackMessage: string,
): Promise<T | null> => {
if (isBusy) return null
setIsBusy(true)
setActionError(null)
try {
const result = await onSyncNow()
if (!result.ok) setActionError(result.message ?? 'Não foi possível sincronizar.')
const result = await run()
if (!result.ok) setActionError(result.message ?? fallbackMessage)
return result
} finally {
setIsBusy(false)
}
}
const handleSetDisabled = async (disabled: boolean) => {
if (isBusy) return
setIsBusy(true)
setActionError(null)
try {
const result = await onSetDisabled(disabled)
if (!result.ok) setActionError(result.message ?? 'Não foi possível atualizar.')
} finally {
setIsBusy(false)
}
const handleSyncNow = () => runAction(onSyncNow, 'Não foi possível sincronizar.')
const handleSetDisabled = (disabled: boolean) =>
runAction(() => onSetDisabled(disabled), 'Não foi possível atualizar.')
const handleStartOAuth = async () => {
const result = await runAction(onStartOAuth, 'Não foi possível iniciar a conexão.')
if (result?.ok) window.location.assign(result.authorizeUrl)
}
const linkBlock = state.addLink ? (
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="google-calendar-link">
Link do calendário (copie e envie à equipe)
</label>
<div className="flex gap-2">
<Input
id="google-calendar-link"
value={state.addLink}
readOnly
className="font-mono text-xs"
/>
<Button
type="button"
variant="outline"
size="icon"
onClick={handleCopy}
aria-label="Copiar link"
>
{copyIcon}
const handleDisconnect = () => runAction(onDisconnect, 'Não foi possível desconectar.')
const linkBlock = addLink ? (
<div className="space-y-3">
<div className="space-y-2">
<p className="text-sm font-medium">Adicionar ao meu Google Calendar</p>
<Button asChild className="w-full sm:w-auto">
<a href={addLink} target="_blank" rel="noopener noreferrer">
<ExternalLinkIcon className="mr-2 h-4 w-4" />
Adicionar ao meu Google Calendar
</a>
</Button>
</div>
{copied && (
<p className="text-xs text-green-600" aria-live="polite">
Link copiado!
<p className="text-xs text-muted-foreground">
O Google abre com o calendário da campanha pronto para assinar — vale para o computador e
o celular.
</p>
)}
<p className="text-xs text-muted-foreground">
Quem segue o calendário recebe aviso conforme as próprias configurações do Google.
</p>
</div>
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="google-calendar-link">
URL pública do calendário (Por URL, Apple Calendar e Outlook)
</label>
<div className="flex gap-2">
<Input
id="google-calendar-link"
value={icalUrl ?? ''}
readOnly
className="font-mono text-xs"
/>
<Button
type="button"
variant="outline"
size="icon"
onClick={handleCopy}
aria-label="Copiar link"
>
{copyIcon}
</Button>
</div>
{copied && (
<p className="text-xs text-green-600" aria-live="polite">
Link copiado!
</p>
)}
<p className="text-xs text-muted-foreground">
Quem segue o calendário recebe aviso conforme as próprias configurações do Google.
</p>
</div>
</div>
) : null
@ -183,16 +249,51 @@ export const GoogleCalendarSyncDialog = ({
</Button>
)
let content: React.ReactNode
let actions: React.ReactNode = null
const connectionActions = state.canManageConnection ? (
<div className="flex flex-wrap items-center gap-2">
{state.connection === 'connected' ? (
<Button
type="button"
variant="outline"
onClick={() => void handleStartOAuth()}
disabled={isBusy}
>
Reconectar com o Google
</Button>
) : (
<Button
type="button"
onClick={() => void handleStartOAuth()}
disabled={isBusy || !state.oauthAvailable}
>
<ExternalLinkIcon className="mr-2 h-4 w-4" />
{state.connection === 'error' ? 'Reconectar com o Google' : 'Conectar com o Google'}
</Button>
)}
{state.connection !== 'not-configured' ? (
<Button
type="button"
variant="outline"
onClick={() => void handleDisconnect()}
disabled={isBusy}
>
Desconectar
</Button>
) : null}
</div>
) : (
<p className="text-xs text-muted-foreground">
Somente candidato ou coordenação pode conectar ou desconectar a conta Google da campanha.
</p>
)
if (state.status === 'not-configured') {
content = (
const oauthUnavailableBlock =
state.connection === 'not-configured' && !state.oauthAvailable ? (
<div className="rounded-lg border border-amber-300 bg-amber-50 p-4 text-sm">
<p className="mb-2 font-medium text-amber-900">Ainda não configurado</p>
<p className="text-amber-800">
O Teqo segue 100% funcional — a agenda do Teqo nunca depende do Google. Para ativar o
espelho, um administrador precisa concluir a configuração:
O Teqo segue 100% funcional — a agenda do Teqo nunca depende do Google. Um administrador
pode concluir a configuração manual:
</p>
<ol className="mt-2 list-inside list-decimal space-y-1 text-amber-800">
{NOT_CONFIGURED_RUNBOOK.map((step) => (
@ -200,7 +301,133 @@ export const GoogleCalendarSyncDialog = ({
))}
</ol>
</div>
)
) : null
const connectionBlock = (
<div className="rounded-lg border border-border p-4">
<div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
<div>
<h3 className="text-sm font-semibold">Google Calendar</h3>
{state.connection === 'not-configured' ? (
<p className="mt-1 text-sm text-muted-foreground">
Conecte a conta Google do calendário da campanha para gerenciar o espelho por ela.
{state.status !== 'not-configured'
? ' O espelho segue ativo pela configuração manual (service account).'
: ''}
</p>
) : state.connection === 'connected' ? (
<p className="mt-1 text-sm text-muted-foreground">
O espelho usa a conta Google conectada para escrever os compromissos no calendário da
campanha.
</p>
) : (
<p className="mt-1 text-sm text-muted-foreground">
A conexão com o Google precisa ser refeita.
</p>
)}
</div>
<span
className={`self-start rounded-full border px-3 py-1 text-xs font-medium ${CONNECTION_BADGE[state.connection].className}`}
>
{CONNECTION_BADGE[state.connection].label}
</span>
</div>
{state.connection === 'not-configured' ? (
<div className="mt-4 space-y-3">
{oauthUnavailableBlock ?? (
<div className="rounded-md border border-dashed border-border p-4">
<p className="text-sm text-muted-foreground">
Você será levado à tela de consentimento do Google para autorizar o Teqo a gerenciar
o calendário da campanha.
</p>
<div className="mt-3">{connectionActions}</div>
</div>
)}
<p className="text-xs text-muted-foreground">
A configuração manual por service account continua disponível como fallback técnico.
</p>
</div>
) : null}
{state.connection === 'connected' ? (
<div className="mt-4 space-y-3">
<p className="text-sm text-muted-foreground">
{state.oauthConnectedAt
? `Conta Google conectada em ${formatBahiaDateTimeLabel(state.oauthConnectedAt)}.`
: 'Conta Google conectada.'}
</p>
<div className="rounded-md border border-dashed border-border p-4">
<p className="text-sm font-medium">Calendário principal da campanha</p>
{state.canManageConnection ? (
<>
<p className="mt-1 text-sm text-muted-foreground">
{state.calendarId
? 'O espelho escreve neste calendário:'
: 'Nenhum calendário escolhido ainda — o espelho fica parado até a escolha.'}
</p>
{state.calendarId ? (
<p className="mt-1 break-all font-mono text-xs text-muted-foreground">
{state.calendarId}
</p>
) : null}
<Button
type="button"
variant="outline"
className="mt-3"
onClick={onOpenPicker}
disabled={isBusy}
>
{state.calendarId
? 'Trocar calendário principal'
: 'Escolher calendário principal'}
</Button>
</>
) : (
<p className="mt-1 text-sm text-muted-foreground">
O calendário principal é escolhido por candidato ou coordenação.
</p>
)}
</div>
{connectionActions}
<p className="text-xs text-muted-foreground">
Desconectar revoga o acesso do Teqo; depois, revogue o app nas configurações de
segurança da conta Google.
</p>
</div>
) : null}
{state.connection === 'error' ? (
<div className="mt-4 space-y-3">
<div className="rounded-md border border-amber-300 bg-amber-50 p-4 text-sm">
<p className="font-medium text-amber-900">Erro de conexão com o Google</p>
<p className="mt-1 text-amber-800">
{state.oauthError ??
'Não foi possível renovar o acesso. O Teqo continua sendo a fonte da verdade — nada foi perdido.'}
</p>
<p className="mt-2 text-xs text-amber-700">
Reconecte com a mesma conta Google do calendário da campanha. Se a conta mudou,
desconecte antes e conecte novamente.
</p>
</div>
{connectionActions}
</div>
) : null}
</div>
)
let content: React.ReactNode
let actions: React.ReactNode = null
if (state.status === 'not-configured') {
content =
state.connection === 'connected' ? (
<p className="rounded-lg bg-muted p-3 text-sm text-muted-foreground">
{state.canManageConnection
? 'Escolha o calendário principal para a agenda começar a espelhar no Google.'
: 'O calendário principal da campanha é escolhido por candidato ou coordenação.'}
</p>
) : null
} else if (state.status === 'disabled') {
content = (
<div className="rounded-lg bg-muted p-4 text-sm text-muted-foreground">
@ -280,6 +507,14 @@ export const GoogleCalendarSyncDialog = ({
</p>
) : null
// C149 — the connection card leads every state; the mirror blocks stay below.
const body = (
<>
{connectionBlock}
{content}
</>
)
const description =
'Compromissos do Teqo refletem no calendário Google compartilhado em minutos, e edições feitas nele voltam para o Teqo. Quem segue recebe aviso conforme as próprias configurações.'
@ -298,7 +533,7 @@ export const GoogleCalendarSyncDialog = ({
</DrawerHeader>
<div className="overflow-y-auto px-4 pb-2">
<div className="space-y-4">
{content}
{body}
{errorNotice}
{actions}
</div>
@ -322,7 +557,7 @@ export const GoogleCalendarSyncDialog = ({
data-slot="dialog-scroll-body"
className="min-h-0 flex-1 overflow-y-auto overscroll-contain px-6 py-4"
>
<div className="space-y-4">{content}</div>
<div className="space-y-4">{body}</div>
</div>
{errorNotice || actions ? (
<div data-slot="dialog-footer" className="shrink-0 space-y-3 border-t px-6 py-4">

View file

@ -1,64 +1,45 @@
import Link from 'next/link'
import { CardModelTile } from '@/components/cards/CardModelTile'
import { CARD_MODELS, cardModelHref, type CardModel, type CardModelId } from '@/lib/cardModels'
import { CARD_MODELS, type CardModel, type CardModelId } from '@/lib/cardModels'
type CardModelGalleryProps = {
variant: 'link' | 'select'
ariaLabel: string
fontFamily: string
selectedId?: CardModelId | null
onSelect?: (id: CardModelId) => void
onSelect: (id: CardModelId) => void
}
const tileClassName =
'group flex h-full w-full flex-col rounded-xl text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-(--pt-red) focus-visible:ring-offset-2 focus-visible:ring-offset-(--campaign-cream)'
/**
* S13 — the three models side by side on desktop and a one-item-with-peek
* snap track on mobile. `link` renders deep links (home funnel), `select`
* renders buttons for the `/cards` studio; both come from the same catalog.
* S14 — the three models side by side on desktop and a one-item-with-peek snap
* track on mobile, as buttons for the studio island: selecting a tile opens the
* single composer in place (home or `/cards`). Both tracks come from the same
* catalog (S13).
*/
export const CardModelGallery = ({
variant,
ariaLabel,
fontFamily,
selectedId = null,
onSelect,
}: CardModelGalleryProps) => {
const renderItem = (model: CardModel) => {
const selected = variant === 'select' && selectedId === model.id
const content = (
<>
<CardModelTile model={model} selected={selected} />
const selected = selectedId === model.id
return (
<button
type="button"
aria-pressed={selected}
aria-label={model.label}
data-card-model-tile={model.id}
onClick={() => onSelect(model.id)}
className={tileClassName}
>
<CardModelTile model={model} fontFamily={fontFamily} selected={selected} />
<span className="mt-auto block pt-3 text-center text-sm font-bold text-(--campaign-ink) sm:text-base">
{model.label}
</span>
</>
)
if (variant === 'select') {
return (
<button
type="button"
aria-pressed={selected}
aria-label={`${model.label}${selected ? ' (selecionado)' : ''}`}
data-card-model-tile={model.id}
onClick={() => onSelect?.(model.id)}
className={tileClassName}
>
{content}
</button>
)
}
return (
<Link
href={cardModelHref(model.id)}
aria-label={`${model.label} — criar meu card`}
data-card-model-tile={model.id}
className={tileClassName}
>
{content}
</Link>
</button>
)
}

View file

@ -1,23 +1,24 @@
import { CheckIcon, UserRoundIcon } from 'lucide-react'
import Image from 'next/image'
import { NAME_CARD_SLOT, type CardModel } from '@/lib/cardModels'
import { CardNameTileCanvas } from '@/components/cards/CardNameTileCanvas'
import type { CardModel } from '@/lib/cardModels'
import { cn } from '@/lib/utils'
/**
* S13 — artwork preview of one card model, shared by the home section and the
* `/cards` gallery. The name tile reuses the empty master with an HTML
* `SEU NOME` placeholder (the real name is only drawn by the canvas); the photo
* tiles show the official transparent overlay above a neutral photo slot.
* `/cards` gallery. The name tile reuses the empty master with a `SEU NOME`
* preview drawn by the real composer pipeline (S14); the photo tiles show the
* official transparent overlay above a neutral photo slot.
*/
export const CardModelTile = ({
model,
fontFamily,
selected = false,
priority = false,
}: {
model: CardModel
fontFamily: string
selected?: boolean
priority?: boolean
}) => (
<span
className={cn(
@ -26,7 +27,7 @@ export const CardModelTile = ({
? 'border-(--pt-red) ring-2 ring-(--pt-red)'
: 'border-(--campaign-line) group-hover:-translate-y-0.5 group-hover:shadow-lg',
)}
style={{ aspectRatio: `${model.width} / ${model.height}`, containerType: 'inline-size' }}
style={{ aspectRatio: `${model.width} / ${model.height}` }}
>
{model.kind === 'photo' ? (
<>
@ -52,25 +53,11 @@ export const CardModelTile = ({
src={model.assetSrc}
alt=""
fill
priority={priority}
sizes="(min-width: 1024px) 340px, 78vw"
className="object-cover"
/>
{model.kind === 'name' ? (
<span
aria-hidden="true"
className="absolute -translate-x-1/2 font-[family-name:var(--font-exo2)] leading-none font-black tracking-[-0.02em]"
style={{
left: `${(NAME_CARD_SLOT.centerX / model.width) * 100}%`,
top: `${(NAME_CARD_SLOT.capTop / model.height) * 100}%`,
fontSize: '11.5cqw',
color: NAME_CARD_SLOT.fill,
}}
>
SEU NOME
</span>
) : null}
{model.kind === 'name' ? <CardNameTileCanvas model={model} fontFamily={fontFamily} /> : null}
{selected ? (
<span className="absolute top-3 right-3 inline-flex size-7 items-center justify-center rounded-full bg-(--pt-red) text-white shadow-md">

View file

@ -0,0 +1,58 @@
'use client'
import { useEffect, useRef } from 'react'
import { ensureCardFont } from '@/components/cards/cardCanvas'
import { CARD_NAME_TILE_PLACEHOLDER } from '@/components/cards/cardCopy'
import type { CardModel } from '@/lib/cardModels'
import { fitCardName } from '@/lib/cardNameFit'
import { createCardMeasure, drawCardName } from '@/lib/cardRender'
/**
* S14 — the name-model tile preview: a transparent canvas over the base image
* that draws `SEU NOME` with the exact composer pipeline (same fit, same slot,
* same left border), so the tile cannot drift from the generated card. Draws
* only after the real font loads — measuring with the fallback would lie.
*/
export const CardNameTileCanvas = ({
model,
fontFamily,
}: {
model: CardModel
fontFamily: string
}) => {
const canvasRef = useRef<HTMLCanvasElement>(null)
useEffect(() => {
let cancelled = false
const draw = async () => {
const fontReady = await ensureCardFont(fontFamily)
if (!fontReady || cancelled) return
const ctx = canvasRef.current?.getContext('2d')
if (!ctx) return
const fit = fitCardName(CARD_NAME_TILE_PLACEHOLDER, createCardMeasure(ctx, fontFamily))
if (!fit.ok) return
ctx.clearRect(0, 0, model.width, model.height)
drawCardName(ctx, { fit, fontFamily })
}
void draw()
return () => {
cancelled = true
}
}, [model.width, model.height, fontFamily])
return (
<canvas
ref={canvasRef}
width={model.width}
height={model.height}
aria-hidden="true"
className="absolute inset-0 h-full w-full"
/>
)
}

View file

@ -10,10 +10,13 @@ import { useIsMobileMeasured } from '@/hooks/use-mobile'
import { getCardModel, type CardModelId } from '@/lib/cardModels'
/**
* S13 — the `/cards` studio island: owns which model is selected and whether
* the composer is open, renders the catalog and mounts the single editor in a
* S13 — the card studio island: owns which model is selected and whether the
* composer is open, renders the catalog and mounts the single editor in a
* centered dialog (desktop) or a bottom drawer (mobile). Closing returns to the
* catalog with the selection kept; the URL is only read, never rewritten.
*
* S14 — the home section renders this same island (no second editor): tiles are
* buttons everywhere and opening the composer never navigates.
*/
export const CardsStudio = ({
initialModelId,
@ -33,9 +36,9 @@ export const CardsStudio = ({
setOpen(true)
}
// Radix restores focus to the element that opened the dialog, but the home
// tile that deep-linked here is unmounted after navigation. Send focus back
// to the catalog tile of the selected model instead (visible list only).
// Radix restores focus to the element that opened the dialog; send it back to
// the catalog tile of the selected model (visible list only) so home and
// `/cards` share the same focus return.
const focusSelectedTile = () => {
if (!selectedId) return
const tiles = document.querySelectorAll<HTMLElement>(`[data-card-model-tile="${selectedId}"]`)
@ -46,8 +49,8 @@ export const CardsStudio = ({
return (
<div>
<CardModelGallery
variant="select"
ariaLabel="Modelos de card"
fontFamily={fontFamily}
selectedId={selectedId}
onSelect={handleSelect}
/>
@ -76,7 +79,7 @@ export const CardsStudio = ({
event.preventDefault()
focusSelectedTile()
}}
className="max-h-[92dvh] gap-0 overflow-hidden p-0 sm:max-w-lg"
className="max-h-[92dvh] gap-0 overflow-hidden p-0 sm:max-w-lg sm:p-0"
>
<CardComposer
model={selectedModel}

View file

@ -6,3 +6,9 @@
export const CARD_PRIVACY_NOTE =
'Seu nome e sua foto são processados apenas no seu aparelho e não são enviados para nós.'
export const CARD_PHOTO_PRIVACY_NOTE = 'Sua foto fica neste aparelho e não é enviada para nós.'
/**
* S14 — example name of the name-model tile. Drawn by the real composer
* pipeline over the base image (same fit and left border as the generated card).
*/
export const CARD_NAME_TILE_PLACEHOLDER = 'SEU NOME'

View file

@ -64,12 +64,14 @@ export const CARD_MODELS: readonly CardModel[] = [
/**
* Name model slot, pixel-measured from the filled master (`FULANO` example):
* glyph cap band tops at y=430 with a 106px cap height, ink spans x[213..926]
* (714px) centered at x≈570 — not at the canvas center. The visitor's name is
* the only thing drawn over the base; the fixed lines already live in the art.
* the `#SOU` line and the visitor's name share the same left border at x=213
* (S14 — the name is left-aligned, not centered); the cap band tops at y=430
* with a 106px cap height and the master's ink spans x[214..925] (712px), so a
* fitted name never crosses 714px. The visitor's name is the only thing drawn
* over the base; the fixed lines already live in the art.
*/
export const NAME_CARD_SLOT = {
centerX: 570,
leftX: 213,
capTop: 430,
capHeight: 106,
maxInkWidth: 714,
@ -86,5 +88,3 @@ export const isCardModelId = (value: unknown): value is CardModelId =>
export const getCardModel = (id: CardModelId): CardModel | undefined =>
CARD_MODELS.find((model) => model.id === id)
export const cardModelHref = (id: CardModelId): string => `/cards?model=${id}`

View file

@ -56,6 +56,40 @@ export type NameCardRenderArgs = {
slot?: CardNameSlot
}
export type CardNameDrawArgs = {
fit: Extract<CardNameFit, { ok: true }>
fontFamily: string
slot?: CardNameSlot
}
/**
* S14 — draws only the fitted name (no base image) so the home tile preview
* reuses the exact composer geometry. `fit.ok` is the caller's contract: a
* failed fit never draws (names are never cut silently).
*/
export const drawCardName = (ctx: CardDrawContext, args: CardNameDrawArgs): void => {
const slot = args.slot ?? NAME_CARD_SLOT
const { fit } = args
ctx.font = `700 ${fit.fontSize}px ${args.fontFamily}`
ctx.fillStyle = slot.fill
ctx.textAlign = 'left'
ctx.textBaseline = 'alphabetic'
if (fit.lines.length === 1) {
ctx.fillText(fit.lines[0], slot.leftX, slot.capTop + fit.capHeight)
return
}
const availableHeight = slot.maxBlockBottom - slot.capTop
const blockHeight = fit.lineHeight + fit.capHeight
const blockTop = slot.capTop + Math.max(0, (availableHeight - blockHeight) / 2)
fit.lines.forEach((line, index) => {
ctx.fillText(line, slot.leftX, blockTop + fit.capHeight + index * fit.lineHeight)
})
}
export const renderNameCard = (
ctx: CardDrawContext,
model: CardModel,
@ -67,23 +101,7 @@ export const renderNameCard = (
const fit = fitCardName(args.name, args.measure, slot)
if (!fit.ok) return fit
ctx.font = `700 ${fit.fontSize}px ${args.fontFamily}`
ctx.fillStyle = slot.fill
ctx.textAlign = 'center'
ctx.textBaseline = 'alphabetic'
if (fit.lines.length === 1) {
ctx.fillText(fit.lines[0], slot.centerX, slot.capTop + fit.capHeight)
return fit
}
const availableHeight = slot.maxBlockBottom - slot.capTop
const blockHeight = fit.lineHeight + fit.capHeight
const blockTop = slot.capTop + Math.max(0, (availableHeight - blockHeight) / 2)
fit.lines.forEach((line, index) => {
ctx.fillText(line, slot.centerX, blockTop + fit.capHeight + index * fit.lineHeight)
})
drawCardName(ctx, { fit, fontFamily: args.fontFamily, slot })
return fit
}

View file

@ -1,13 +1,13 @@
/**
* C114 — public "add this calendar" links for the campaign's shared Google
* calendar. The calendar itself is created in the campaign's Google account
* (never by a service account — Google's recommendation) and shared publicly
* by link (ops runbook); these URLs are what the team receives:
* C114/C150 — public "add this calendar" links for the campaign's shared
* Google calendar. The calendar itself is created in the campaign's Google
* account (never by a service account — Google's recommendation) and shared
* publicly by link (ops runbook); these URLs are what the team receives:
*
* - Google Calendar: the `cid` webcal URL (the established add-by-URL flow the
* iCal feed dialog already uses, `calendar/r/settings/addbyurl`).
* - Apple Calendar / Outlook: subscribe straight to the webcal URL the Google
* calendar exposes for public calendars.
* - Google Calendar: the `cid` calendarId (C150) — Google opens the calendar
* ready to subscribe, no "add by URL" step.
* - Google Calendar "add by URL", Apple Calendar and Outlook: the public iCal
* URL of the same calendar (manual path).
*
* Both require the calendar to be public in the owner's sharing settings —
* the link IS the credential, same model as the iCal feed secret.
@ -15,14 +15,10 @@
const GOOGLE_CALENDAR_ADD_BASE = 'https://calendar.google.com/calendar/r'
const GOOGLE_CALENDAR_ICAL_BASE = 'https://calendar.google.com/calendar/ical'
export const buildGoogleCalendarWebcalUrl = (calendarId: string): string =>
`webcal://calendar.google.com/calendar/ical/${encodeURIComponent(calendarId)}/public/basic.ics`
/** C150 — the one-click add link: `cid` carries the calendar id itself. */
export const buildGoogleCalendarAddLink = (calendarId: string): string =>
`${GOOGLE_CALENDAR_ADD_BASE}?cid=${encodeURIComponent(calendarId)}`
export const buildGoogleCalendarAddLink = (calendarId: string): string => {
const webcal = buildGoogleCalendarWebcalUrl(calendarId)
return `${GOOGLE_CALENDAR_ADD_BASE}?cid=${encodeURIComponent(webcal)}`
}
/** The public iCal URL of the shared calendar — same `cid` target, plain HTTPS. */
/** The public iCal URL of the shared calendar — the manual "add by URL" target. */
export const buildGoogleCalendarPublicIcalUrl = (calendarId: string): string =>
`${GOOGLE_CALENDAR_ICAL_BASE}/${encodeURIComponent(calendarId)}/public/basic.ics`

View file

@ -0,0 +1,48 @@
/**
* C149 — pure pieces of the campaign's Google OAuth handshake. The authorize
* URL is request-independent (client id + redirect uri + state are passed in),
* so it lives in `lib/` and is unit-tested without a server. Nothing here is
* secret: the client id is public in the consent URL and the state is
* generated per attempt by the caller.
*/
const GOOGLE_CALENDAR_OAUTH_AUTHORIZE_ENDPOINT = 'https://accounts.google.com/o/oauth2/v2/auth'
/** Where Google returns the browser after consent (also registered in the GCP client). */
export const GOOGLE_CALENDAR_OAUTH_CALLBACK_PATH = '/campanha/agenda/google-oauth/callback'
/**
* The minimum scopes (C149 literal): `calendar.events` is what the mirror
* needs to write, `calendar.calendarlist.readonly` is what C150's picker
* needs to list the account's calendars. Nothing beyond.
*/
export const GOOGLE_CALENDAR_OAUTH_SCOPES = [
'https://www.googleapis.com/auth/calendar.events',
'https://www.googleapis.com/auth/calendar.calendarlist.readonly',
] as const
type GoogleCalendarOAuthAuthorizeUrlInput = {
clientId: string
redirectUri: string
state: string
}
export const buildGoogleCalendarOAuthAuthorizeUrl = ({
clientId,
redirectUri,
state,
}: GoogleCalendarOAuthAuthorizeUrlInput): string => {
const params = new URLSearchParams({
client_id: clientId,
redirect_uri: redirectUri,
response_type: 'code',
scope: GOOGLE_CALENDAR_OAUTH_SCOPES.join(' '),
// `offline` + `consent` are what make Google return a refresh token that
// survives without weekly re-consent (the hard product constraint); the
// explicit `prompt` also guarantees a fresh token on reconnect.
access_type: 'offline',
prompt: 'consent',
state,
})
return `${GOOGLE_CALENDAR_OAUTH_AUTHORIZE_ENDPOINT}?${params.toString()}`
}

View file

@ -133,6 +133,7 @@ const activityFieldsSchema = z.object({
description: trimmedOptionalText(4000),
deputyPresent: z.boolean().optional(),
allDay: z.boolean().optional(),
publicEvent: z.boolean().optional(),
startAt: z.string().datetime().optional().nullable(),
endAt: z.string().datetime().optional().nullable(),
municipality: positiveRelationshipId,

View file

@ -0,0 +1,25 @@
/**
* Staging detection for the public site (OPS103).
*
* Staging runs the same build with
* `NEXT_PUBLIC_SITE_URL=https://staging.jorgesolla1313.com.br` — anything
* served under a `staging.` hostname must stay out of search indexes.
* Client-safe: no Payload/Next imports; `isStagingSite` reads the public
* origin that the build already carries.
*/
/** Whether a public origin belongs to a staging deployment. */
export function isStagingSiteUrl(url: string | null | undefined): boolean {
if (!url) return false
try {
return new URL(url).hostname.startsWith('staging.')
} catch {
return false
}
}
/** Whether THIS build is the staging deployment (reads the public origin). */
export function isStagingSite(): boolean {
return isStagingSiteUrl(process.env.NEXT_PUBLIC_SITE_URL)
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,27 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
/**
* C149 — `googleCalendarSync` gains the OAuth connection fields (C149). The
* generated migration also re-emitted the already-applied
* `supporter_import_batch.actor_id DROP NOT NULL` statement
* (applied by `20260824_010000_make_supporter_import_batch_actor_nullable`);
* it was removed by hand so the apply does not fail on a duplicate change —
* same drift handled in the C114 migration.
*/
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "google_calendar_sync" ADD COLUMN "oauth_refresh_token" varchar;
ALTER TABLE "google_calendar_sync" ADD COLUMN "oauth_scope" varchar;
ALTER TABLE "google_calendar_sync" ADD COLUMN "oauth_connected_at" timestamp(3) with time zone;
ALTER TABLE "google_calendar_sync" ADD COLUMN "oauth_error_at" timestamp(3) with time zone;
ALTER TABLE "google_calendar_sync" ADD COLUMN "oauth_error" varchar;`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "google_calendar_sync" DROP COLUMN "oauth_refresh_token";
ALTER TABLE "google_calendar_sync" DROP COLUMN "oauth_scope";
ALTER TABLE "google_calendar_sync" DROP COLUMN "oauth_connected_at";
ALTER TABLE "google_calendar_sync" DROP COLUMN "oauth_error_at";
ALTER TABLE "google_calendar_sync" DROP COLUMN "oauth_error";`)
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,13 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "activity" ADD COLUMN "public_event" boolean DEFAULT false;
CREATE INDEX "activity_public_event_idx" ON "activity" USING btree ("public_event");`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
DROP INDEX "activity_public_event_idx";
ALTER TABLE "activity" DROP COLUMN "public_event";`)
}

View file

@ -64,6 +64,8 @@ import * as migration_20260820_003426_add_instagram_sync_status from './20260820
import * as migration_20260823_161905_add_municipality_update_deliberation from './20260823_161905_add_municipality_update_deliberation';
import * as migration_20260824_000000_reconcile_allocation_decision_rationale_nullable from './20260824_000000_reconcile_allocation_decision_rationale_nullable';
import * as migration_20260824_010000_make_supporter_import_batch_actor_nullable from './20260824_010000_make_supporter_import_batch_actor_nullable';
import * as migration_20260912_052226_add_google_calendar_oauth_connection from './20260912_052226_add_google_calendar_oauth_connection';
import * as migration_20260912_224719_add_activity_public_event from './20260912_224719_add_activity_public_event';
export const migrations = [
{
@ -384,16 +386,26 @@ export const migrations = [
{
up: migration_20260823_161905_add_municipality_update_deliberation.up,
down: migration_20260823_161905_add_municipality_update_deliberation.down,
name: '20260823_161905_add_municipality_update_deliberation'
name: '20260823_161905_add_municipality_update_deliberation',
},
{
up: migration_20260824_000000_reconcile_allocation_decision_rationale_nullable.up,
down: migration_20260824_000000_reconcile_allocation_decision_rationale_nullable.down,
name: '20260824_000000_reconcile_allocation_decision_rationale_nullable'
name: '20260824_000000_reconcile_allocation_decision_rationale_nullable',
},
{
up: migration_20260824_010000_make_supporter_import_batch_actor_nullable.up,
down: migration_20260824_010000_make_supporter_import_batch_actor_nullable.down,
name: '20260824_010000_make_supporter_import_batch_actor_nullable'
name: '20260824_010000_make_supporter_import_batch_actor_nullable',
},
{
up: migration_20260912_052226_add_google_calendar_oauth_connection.up,
down: migration_20260912_052226_add_google_calendar_oauth_connection.down,
name: '20260912_052226_add_google_calendar_oauth_connection'
},
{
up: migration_20260912_224719_add_activity_public_event.up,
down: migration_20260912_224719_add_activity_public_event.down,
name: '20260912_224719_add_activity_public_event'
},
];

View file

@ -776,6 +776,10 @@ export interface Activity {
* Compromisso que ocupa um ou mais dias inteiros, sem horário.
*/
allDay?: boolean | null;
/**
* Quando marcado, este evento poderá ser publicado no site do candidato (futuro).
*/
publicEvent?: boolean | null;
startAt?: string | null;
endAt?: string | null;
municipality: number | Municipality;
@ -940,6 +944,17 @@ export interface GoogleCalendarSync {
* O calendarId do calendário "Agenda da Campanha" na conta Google da campanha (ex.: c_…@group.calendar.google.com). O calendário precisa estar público no link e a service account com permissão de edição.
*/
calendarId?: string | null;
/**
* Credencial da conexão OAuth com a conta Google da campanha. Preenchida pelo callback do botão "Conectar com o Google"; nunca é exibida.
*/
oauthRefreshToken?: string | null;
/**
* Escopos que o Google devolveu na conexão (diagnóstico).
*/
oauthScope?: string | null;
oauthConnectedAt?: string | null;
oauthErrorAt?: string | null;
oauthError?: string | null;
/**
* Enquanto preenchido, o Teqo não escreve no Google.
*/
@ -1904,6 +1919,7 @@ export interface ActivitySelect<T extends boolean = true> {
description?: T;
deputyPresent?: T;
allDay?: T;
publicEvent?: T;
startAt?: T;
endAt?: T;
municipality?: T;
@ -1959,6 +1975,11 @@ export interface CalendarFeedSelect<T extends boolean = true> {
*/
export interface GoogleCalendarSyncSelect<T extends boolean = true> {
calendarId?: T;
oauthRefreshToken?: T;
oauthScope?: T;
oauthConnectedAt?: T;
oauthErrorAt?: T;
oauthError?: T;
disabledAt?: T;
lastSyncedAt?: T;
lastSuccessAt?: T;

View file

@ -3,8 +3,10 @@ import type { Access, FieldAccess } from 'payload'
import {
getFreshCampaignUser,
isCampaignStaff,
isCampaignUnrestricted,
isPayloadAdmin,
payloadAdminOnly,
type CampaignActor,
} from '@/utilities/access/shared'
/**
@ -53,3 +55,13 @@ export const canSetGoogleCalendarSyncSystemField: FieldAccess = () => false
* hand out full push-forging authority to any staff member.
*/
export const canReadGoogleCalendarSyncIdentityField: FieldAccess = () => false
/**
* C149 — connecting/disconnecting the campaign's Google account is a core
* decision over a credential that belongs to the whole campaign: candidate or
* coordinator only (advisor reads the state but never holds the token; leader
* never reaches the agenda). Enforced at the action layer with the freshly
* reloaded actor — same pattern as the other campaign actions.
*/
export const canManageGoogleCalendarConnection = (user: CampaignActor): boolean =>
isCampaignUnrestricted(user)

View file

@ -163,6 +163,7 @@ const parseSharedActivityFormData = (formData: FormData) => {
description: optionalFormText(formData, 'description'),
deputyPresent: checkboxFormValue(formData, 'deputyPresent'),
allDay,
publicEvent: checkboxFormValue(formData, 'publicEvent'),
startAt: parseScheduleFormField(formData, 'startAt', allDay),
endAt: parseScheduleFormField(formData, 'endAt', allDay),
municipality: requiredRelationshipFormValue(formData, 'municipality'),

View file

@ -228,6 +228,7 @@ export const activityFormSelect = {
description: true,
deputyPresent: true,
allDay: true,
publicEvent: true,
startAt: true,
endAt: true,
municipality: true,
@ -253,6 +254,7 @@ export type ActivityFormViewModel = {
description: string | null
deputyPresent: boolean
allDay: boolean
publicEvent: boolean
startAt: string | null
endAt: string | null
municipalityId: number | null
@ -274,6 +276,7 @@ export const toActivityFormViewModel = (activity: Activity): ActivityFormViewMod
description: activity.description ?? null,
deputyPresent: Boolean(activity.deputyPresent),
allDay: Boolean(activity.allDay),
publicEvent: Boolean(activity.publicEvent),
startAt: activity.startAt ?? null,
endAt: activity.endAt ?? null,
municipalityId: relationshipId(activity.municipality),

View file

@ -5,8 +5,10 @@ import { importPKCS8, SignJWT } from 'jose'
import type { GoogleRemoteEvent } from '@/lib/googleCalendarEventMapping'
/**
* C114 — thin Calendar API v3 client authenticated as the campaign's service
* account (JWT assertion → OAuth2 token → REST). Only the four event endpoints
* C114 — thin Calendar API v3 client authenticated either as the campaign's
* service account (JWT assertion → OAuth2 token → REST) or — C149 — with the
* OAuth refresh token granted by the "Conectar com o Google" consent
* (refresh_token grant → access token → REST). Only the four event endpoints
* the reconciliation engine needs; the token is cached per runtime instance
* and re-minted on 401. The `fetch` implementation is injectable so tests can
* stub the transport without network.
@ -19,6 +21,8 @@ const GOOGLE_CALENDAR_API_BASE = 'https://www.googleapis.com/calendar/v3'
const GOOGLE_TOKEN_TTL_SECONDS = 3600
const TOKEN_REFRESH_LEAD_SECONDS = 60
const MAX_LIST_PAGE_SIZE = 2500
/** calendarList caps `maxResults` at 250 (unlike events). */
const CALENDAR_LIST_PAGE_SIZE = 250
/**
* Every outbound call carries a hard timeout so a hanging Google never holds
* the activity write path (the afterChange hook awaits the sync) — Teqo's
@ -29,11 +33,27 @@ export const REQUEST_TIMEOUT_MS = 15_000
export type { GoogleRemoteEvent } from '@/lib/googleCalendarEventMapping'
export type GoogleCalendarCredentials = {
export type GoogleCalendarServiceAccountCredentials = {
clientEmail: string
privateKey: string
}
/** C149 — the connection created by the OAuth consent (refresh token + app pair). */
type GoogleCalendarOAuthCredentials = {
clientId: string
clientSecret: string
refreshToken: string
}
/**
* How the client authenticates. The engine resolves OAuth first (when the
* campaign connected an account) and falls back to the service account —
* `googleCalendarSync.readGoogleCalendarAuth`.
*/
export type GoogleCalendarAuth =
| { kind: 'service-account'; credentials: GoogleCalendarServiceAccountCredentials }
| { kind: 'oauth'; credentials: GoogleCalendarOAuthCredentials }
/** Typed transport failure — safe message, never echoes credentials or bodies. */
export class GoogleCalendarApiError extends Error {
readonly status: number
@ -45,7 +65,36 @@ export class GoogleCalendarApiError extends Error {
}
}
/**
* C149 — the OAuth connection is dead (`invalid_grant`: the refresh token was
* revoked or expired). Reconnectable by the user, unlike an API/config error:
* the engine records it as the connection `error` state that offers
* "Reconectar" in one click.
*/
export class GoogleCalendarAuthError extends Error {
constructor(message: string) {
super(message)
this.name = 'GoogleCalendarAuthError'
}
}
/**
* C150 — one entry of the connected account's calendar list, reduced to what
* the picker renders. `summary` falls back to the id when Google omits it.
*/
export type GoogleCalendarListEntry = {
id: string
summary: string
primary: boolean
}
export type GoogleCalendarClient = {
/**
* C150 — the calendars the connected account can WRITE to (`minAccessRole=writer`),
* for the campaign's primary-calendar picker. The mirror only works on a
* calendar the account owns/edits, so read-only subscriptions never show up.
*/
listCalendars: () => Promise<GoogleCalendarListEntry[]>
listEvents: (
calendarId: string,
range: { timeMin: string; timeMax: string },
@ -76,7 +125,7 @@ export type FetchLike = typeof fetch
* for tests — `createGoogleCalendarClient` mints and exchanges it internally.
*/
export const buildServiceAccountAssertion = async (
credentials: GoogleCalendarCredentials,
credentials: GoogleCalendarServiceAccountCredentials,
nowSeconds: number,
): Promise<string> => {
const key = await importPKCS8(credentials.privateKey, 'RS256')
@ -89,8 +138,18 @@ export const buildServiceAccountAssertion = async (
.sign(key)
}
/** Reads the token endpoint's error code without ever surfacing the body. */
const readOAuthErrorCode = async (response: Response): Promise<string | null> => {
try {
const body = (await response.json()) as { error?: unknown }
return typeof body.error === 'string' ? body.error : null
} catch {
return null
}
}
export const createGoogleCalendarClient = (
credentials: GoogleCalendarCredentials,
auth: GoogleCalendarAuth,
fetchImpl: FetchLike = fetch,
hookSignal?: AbortSignal,
): GoogleCalendarClient => {
@ -101,7 +160,29 @@ export const createGoogleCalendarClient = (
return hookSignal ? AbortSignal.any([hookSignal, perHop]) : perHop
}
const requestAccessToken = async (): Promise<string> => {
const parseAccessToken = async (response: Response): Promise<string> => {
const body = (await response.json().catch(() => null)) as {
access_token?: unknown
expires_in?: unknown
} | null
const accessToken = typeof body?.access_token === 'string' ? body.access_token : ''
if (!accessToken) {
throw new GoogleCalendarApiError('Resposta de autenticação do Google sem token.', 502)
}
const expiresIn =
typeof body?.expires_in === 'number' && Number.isFinite(body.expires_in)
? body.expires_in
: GOOGLE_TOKEN_TTL_SECONDS
cachedToken = {
value: accessToken,
expiresAtMs: Date.now() + expiresIn * 1000,
}
return cachedToken.value
}
const requestServiceAccountAccessToken = async (
credentials: GoogleCalendarServiceAccountCredentials,
): Promise<string> => {
const nowSeconds = Math.floor(Date.now() / 1000)
const assertion = await buildServiceAccountAssertion(credentials, nowSeconds)
@ -120,19 +201,46 @@ export const createGoogleCalendarClient = (
response.status,
)
}
const body = (await response.json()) as { access_token?: string; expires_in?: number }
if (!body.access_token) {
throw new GoogleCalendarApiError('Resposta de autenticação do Google sem token.', 502)
}
cachedToken = {
value: body.access_token,
expiresAtMs: Date.now() + (body.expires_in ?? GOOGLE_TOKEN_TTL_SECONDS) * 1000,
}
return cachedToken.value
return parseAccessToken(response)
}
const requestOAuthAccessToken = async (
credentials: GoogleCalendarOAuthCredentials,
): Promise<string> => {
const response = await fetchImpl(GOOGLE_TOKEN_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: credentials.refreshToken,
client_id: credentials.clientId,
client_secret: credentials.clientSecret,
}).toString(),
signal: requestSignal(),
})
if (!response.ok) {
// `invalid_grant` is the user-fixable case (token revoked/expired) and
// becomes the reconnectable auth error. `invalid_client` (our app
// credential is wrong) and transient failures stay API errors: telling
// the user to reconnect would not fix them.
if ((await readOAuthErrorCode(response)) === 'invalid_grant') {
throw new GoogleCalendarAuthError(
'A conexão com o Google expirou ou foi revogada. Reconecte a conta.',
)
}
throw new GoogleCalendarApiError(
`Não foi possível autenticar no Google (HTTP ${response.status}).`,
response.status,
)
}
return parseAccessToken(response)
}
const requestAccessToken = (): Promise<string> =>
auth.kind === 'oauth'
? requestOAuthAccessToken(auth.credentials)
: requestServiceAccountAccessToken(auth.credentials)
const getAccessToken = async (): Promise<string> => {
if (cachedToken && cachedToken.expiresAtMs > Date.now() + TOKEN_REFRESH_LEAD_SECONDS * 1000) {
return cachedToken.value
@ -171,6 +279,42 @@ export const createGoogleCalendarClient = (
.map((part) => `/${encodeURIComponent(part)}`)
.join('')}`
const listCalendars: GoogleCalendarClient['listCalendars'] = async () => {
const calendars: GoogleCalendarListEntry[] = []
let pageToken: string | undefined
do {
const params = new URLSearchParams({
minAccessRole: 'writer',
// A calendar the operation hid in the Google sidebar is still a valid
// mirror target — hiding is a UI preference, not a permission.
showHidden: 'true',
maxResults: String(CALENDAR_LIST_PAGE_SIZE),
fields: 'items(id,summary,primary,deleted),nextPageToken',
})
if (pageToken) params.set('pageToken', pageToken)
const response = await apiFetch(`${GOOGLE_CALENDAR_API_BASE}/users/me/calendarList?${params}`)
const body = (await response.json()) as {
items?: Array<{ id?: unknown; summary?: unknown; primary?: unknown; deleted?: unknown }>
nextPageToken?: string
}
for (const item of body.items ?? []) {
// Deleted calendars linger in the list until Google purges them.
if (typeof item.id !== 'string' || item.id.length === 0 || item.deleted === true) continue
calendars.push({
id: item.id,
summary:
typeof item.summary === 'string' && item.summary.length > 0 ? item.summary : item.id,
primary: item.primary === true,
})
}
pageToken = body.nextPageToken
} while (pageToken)
return calendars
}
const listEvents: GoogleCalendarClient['listEvents'] = async (calendarId, range) => {
const events: GoogleRemoteEvent[] = []
let pageToken: string | undefined
@ -267,5 +411,13 @@ export const createGoogleCalendarClient = (
}
}
return { listEvents, insertEvent, updateEvent, deleteEvent, watchEvents, stopChannel }
return {
listCalendars,
listEvents,
insertEvent,
updateEvent,
deleteEvent,
watchEvents,
stopChannel,
}
}

View file

@ -0,0 +1,212 @@
import 'server-only'
import { cookies } from 'next/headers'
import { createHmac, timingSafeEqual } from 'node:crypto'
import {
GOOGLE_CALENDAR_OAUTH_CALLBACK_PATH,
GOOGLE_CALENDAR_OAUTH_SCOPES,
} from '@/lib/googleCalendarOAuth'
import { getCampaignInviteBaseURL } from '@/utilities/campaignInviteOrigin'
/**
* C149 — the server side of the campaign's Google OAuth handshake: the client
* credential pair (env), the public redirect URI, the signed single-use
* `state` cookie and the authorization-code exchange.
*
* No token ever crosses this module's messages: the exchange reads only
* `refresh_token`/`scope` and fails with a safe, fixed pt-BR message — the
* response body is never echoed and never logged.
*/
export const GOOGLE_CALENDAR_OAUTH_CLIENT_ID_ENV = 'GOOGLE_CALENDAR_OAUTH_CLIENT_ID'
export const GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET_ENV = 'GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET'
const GOOGLE_TOKEN_ENDPOINT = 'https://oauth2.googleapis.com/token'
const STATE_COOKIE_NAME = 'campaign-google-oauth-state'
const STATE_COOKIE_PATH = '/campanha'
const STATE_TTL_MS = 10 * 60 * 1000
const REQUEST_TIMEOUT_MS = 15_000
export type GoogleCalendarOAuthClientCredentials = {
clientId: string
clientSecret: string
}
/**
* Reads the OAuth client pair from the environment. Fail-closed: a partial or
* absent pair disables the connect button (the view exposes `oauthAvailable`)
* without breaking the service-account fallback. Never logs the values.
*/
export const readGoogleCalendarOAuthCredentials =
(): GoogleCalendarOAuthClientCredentials | null => {
const clientId = process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_ID_ENV]?.trim()
const clientSecret = process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET_ENV]?.trim()
if (!clientId || !clientSecret) return null
return { clientId, clientSecret }
}
/**
* The redirect URI registered in the GCP OAuth client. Always the canonical
* public origin (production requires `NEXT_PUBLIC_SITE_URL`), never the
* request URL — so a callback behind the Cloudflare tunnel cannot leak
* localhost into the redirect.
*/
export const buildGoogleCalendarOAuthRedirectUri = (): string =>
`${getCampaignInviteBaseURL()}${GOOGLE_CALENDAR_OAUTH_CALLBACK_PATH}`
export class GoogleCalendarOAuthError extends Error {
constructor(message: string) {
super(message)
this.name = 'GoogleCalendarOAuthError'
}
}
const GOOGLE_CALENDAR_OAUTH_STATE_EXPIRED_MESSAGE =
'A conexão com o Google expirou. Tente conectar novamente.'
const getSecret = (): string => {
const secret = process.env.PAYLOAD_SECRET
if (!secret) throw new Error('PAYLOAD_SECRET não configurado para o state do OAuth.')
return secret
}
const signature = (state: string, userId: string, expiresAt: number): Buffer =>
createHmac('sha256', getSecret()).update(`${state}.${userId}.${expiresAt}`).digest()
const cookieOptions = (maxAge: number) => ({
httpOnly: true,
maxAge,
path: STATE_COOKIE_PATH,
sameSite: 'lax' as const,
secure: process.env.NODE_ENV === 'production',
})
/**
* Stores the signed, time-boxed `state` — the CSRF/replay guard of the
* handshake, bound to the campaign user that started it (precedent:
* `campaignWebAuthnChallenge`).
*/
export const storeGoogleCalendarOAuthState = async (
state: string,
userId: number,
): Promise<void> => {
const expiresAt = Date.now() + STATE_TTL_MS
const sig = signature(state, String(userId), expiresAt).toString('base64url')
const cookieStore = await cookies()
cookieStore.set(
STATE_COOKIE_NAME,
`${state}.${userId}.${expiresAt}.${sig}`,
cookieOptions(Math.ceil(STATE_TTL_MS / 1000)),
)
}
/**
* Verifies the cookie against the `state` Google echoed back and returns the
* user that started the flow. Anything wrong (missing, malformed, stale,
* forged, mismatched) is the same event from the user's side.
*/
export const readGoogleCalendarOAuthState = async (
providedState: string,
): Promise<{ userId: number }> => {
const cookieStore = await cookies()
const raw = cookieStore.get(STATE_COOKIE_NAME)?.value
const invalid = () => new GoogleCalendarOAuthError(GOOGLE_CALENDAR_OAUTH_STATE_EXPIRED_MESSAGE)
if (!raw) throw invalid()
const [state, userIdText, expiresAtText, sig, ...rest] = raw.split('.')
if (!state || !userIdText || !expiresAtText || !sig || rest.length > 0) throw invalid()
const expiresAt = Number(expiresAtText)
if (!Number.isSafeInteger(expiresAt) || expiresAt <= Date.now()) throw invalid()
const expected = signature(state, userIdText, expiresAt)
const provided = Buffer.from(sig, 'base64url')
if (expected.length !== provided.length || !timingSafeEqual(expected, provided)) throw invalid()
if (state !== providedState) throw invalid()
const userId = Number(userIdText)
if (!Number.isSafeInteger(userId) || userId <= 0) throw invalid()
return { userId }
}
/** Burns the state so a captured callback cannot be replayed. */
export const clearGoogleCalendarOAuthState = async (): Promise<void> => {
const cookieStore = await cookies()
cookieStore.set(STATE_COOKIE_NAME, '', cookieOptions(0))
}
export type GoogleCalendarOAuthTokens = {
refreshToken: string
scope: string | null
}
/**
* Exchanges the authorization code for the long-lived refresh token. The
* response body is never echoed or logged: a non-OK answer collapses to a
* fixed safe message, and a body without `refresh_token` tells the user to
* remove the app access and try again (the case where Google does not reissue
* a token for an already-granted consent).
*/
export const exchangeGoogleCalendarOAuthCode = async ({
code,
redirectUri,
credentials,
fetchImpl = fetch,
}: {
code: string
redirectUri: string
credentials: GoogleCalendarOAuthClientCredentials
fetchImpl?: typeof fetch
}): Promise<GoogleCalendarOAuthTokens> => {
let response: Response
try {
response = await fetchImpl(GOOGLE_TOKEN_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
code,
client_id: credentials.clientId,
client_secret: credentials.clientSecret,
redirect_uri: redirectUri,
}).toString(),
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
})
} catch {
throw new GoogleCalendarOAuthError('Não foi possível falar com o Google. Tente novamente.')
}
if (!response.ok) {
throw new GoogleCalendarOAuthError('O Google recusou a autorização. Tente conectar novamente.')
}
const body = (await response.json().catch(() => null)) as {
refresh_token?: unknown
scope?: unknown
} | null
const refreshToken = typeof body?.refresh_token === 'string' ? body.refresh_token : ''
if (!refreshToken) {
throw new GoogleCalendarOAuthError(
'O Google não devolveu um token de atualização. Remova o acesso do Teqo na sua conta Google e tente conectar de novo.',
)
}
const scope = typeof body?.scope === 'string' ? body.scope : null
// Granular consent lets the user uncheck a scope: without `calendar.events`
// the mirror would connect and then fail every pass with 403 — fail the
// handshake instead, which lands on the reconnect path.
if (scope) {
const granted = new Set(scope.split(' ').filter(Boolean))
if (GOOGLE_CALENDAR_OAUTH_SCOPES.some((required) => !granted.has(required))) {
throw new GoogleCalendarOAuthError(
'A autorização não inclui todas as permissões necessárias. Conecte novamente e aceite o acesso completo.',
)
}
}
return { refreshToken, scope }
}

View file

@ -32,9 +32,16 @@ import { getCampaignInviteBaseURL } from '@/utilities/campaignInviteOrigin'
import {
createGoogleCalendarClient,
GoogleCalendarApiError,
GoogleCalendarAuthError,
type GoogleCalendarAuth,
type GoogleCalendarClient,
type GoogleCalendarCredentials,
type GoogleCalendarListEntry,
type GoogleCalendarServiceAccountCredentials,
} from '@/utilities/googleCalendarClient'
import {
readGoogleCalendarOAuthCredentials,
type GoogleCalendarOAuthClientCredentials,
} from '@/utilities/googleCalendarOAuth'
/**
* C114+C115 — the campaign↔Google calendar reconciliation engine.
@ -57,6 +64,12 @@ import {
* trigger also lazily ensures the push channel (D5). The engine NEVER throws
* into the caller — failures land in the state fields and the status derives
* to `paused`; the channel itself is best-effort and never pauses the mirror.
*
* C149 — the credential is now resolved by `readGoogleCalendarAuth`: the OAuth
* connection (refresh token stored on the config row) wins when present and
* the service account remains the fallback. A dead OAuth connection
* (`GoogleCalendarAuthError`) additionally records `oauthError`, which derives
* the connection `error` state that offers reconnect in one click.
*/
export const GOOGLE_CALENDAR_SERVICE_ACCOUNT_KEY_ENV = 'GOOGLE_CALENDAR_SERVICE_ACCOUNT_KEY'
@ -111,8 +124,16 @@ const SYNC_RELEVANT_ACTIVITY_FIELDS = [
export type GoogleCalendarSyncStatus = 'not-configured' | 'disabled' | 'synced' | 'paused'
export type GoogleCalendarConnectionStatus = 'connected' | 'error' | 'not-configured'
export type GoogleCalendarSyncView = {
status: GoogleCalendarSyncStatus
/** C149 — state of the OAuth connection (derived, never stored). */
connection: GoogleCalendarConnectionStatus
/** C149 — the OAuth client env is present, so the connect button can work. */
oauthAvailable: boolean
oauthConnectedAt: string | null
oauthError: string | null
calendarId: string | null
lastSyncedAt: string | null
lastSuccessAt: string | null
@ -142,43 +163,92 @@ export const deriveGoogleCalendarSyncStatus = (input: {
return 'synced'
}
/**
* C149 — pure derivation of the connection state (the intent's literal
* `conectado | erro | não configurado`). An auth error newer than the last
* connection wins (including before any successful connection); a token
* without a newer error is connected; anything else is not configured. The
* state is never stored — reconnect clears the error fields and the state
* recovers by construction.
*/
export const deriveGoogleCalendarConnectionStatus = (input: {
hasRefreshToken: boolean
oauthConnectedAt?: string | null
oauthErrorAt?: string | null
}): GoogleCalendarConnectionStatus => {
// Timestamps are compared as instants, not strings: a value persisted with
// a UTC offset (admin edit, fixture) would invert a lexical comparison.
const errorAt = input.oauthErrorAt ? Date.parse(input.oauthErrorAt) : Number.NaN
const connectedAt = input.oauthConnectedAt ? Date.parse(input.oauthConnectedAt) : Number.NaN
if (!Number.isNaN(errorAt) && (Number.isNaN(connectedAt) || errorAt > connectedAt)) {
return 'error'
}
return input.hasRefreshToken ? 'connected' : 'not-configured'
}
/**
* Reads the service account credential from the environment (base64 of the
* Google Cloud JSON key). Fail-closed: malformed/absent → null, which
* disables the sync entirely without breaking anything else.
*/
export const readGoogleServiceAccountCredentials = (): GoogleCalendarCredentials | null => {
const raw = process.env[GOOGLE_CALENDAR_SERVICE_ACCOUNT_KEY_ENV]
if (!raw) {
// Note: this function is called without payload context, so we use console.warn
// In production, this warning will appear in server logs
console.warn(
`[GoogleCalendarSync] ${GOOGLE_CALENDAR_SERVICE_ACCOUNT_KEY_ENV} não está definido no ambiente.`,
)
export const readGoogleServiceAccountCredentials =
(): GoogleCalendarServiceAccountCredentials | null => {
const raw = process.env[GOOGLE_CALENDAR_SERVICE_ACCOUNT_KEY_ENV]
if (!raw) {
// Note: this function is called without payload context, so we use console.warn
// In production, this warning will appear in server logs
console.warn(
`[GoogleCalendarSync] ${GOOGLE_CALENDAR_SERVICE_ACCOUNT_KEY_ENV} não está definido no ambiente.`,
)
return null
}
try {
const parsed = JSON.parse(Buffer.from(raw, 'base64').toString('utf8')) as Record<
string,
unknown
>
if (
typeof parsed.client_email === 'string' &&
typeof parsed.private_key === 'string' &&
parsed.private_key.length > 0
) {
return { clientEmail: parsed.client_email, privateKey: parsed.private_key }
}
console.warn(
`[GoogleCalendarSync] ${GOOGLE_CALENDAR_SERVICE_ACCOUNT_KEY_ENV} está malformado: client_email ou private_key ausente/vazio.`,
)
} catch {
console.warn(
`[GoogleCalendarSync] ${GOOGLE_CALENDAR_SERVICE_ACCOUNT_KEY_ENV} não é base64 válido ou JSON inválido.`,
)
}
return null
}
try {
const parsed = JSON.parse(Buffer.from(raw, 'base64').toString('utf8')) as Record<
string,
unknown
>
if (
typeof parsed.client_email === 'string' &&
typeof parsed.private_key === 'string' &&
parsed.private_key.length > 0
) {
return { clientEmail: parsed.client_email, privateKey: parsed.private_key }
/**
* C149 — resolves the credential the engine uses. The OAuth connection (when
* a refresh token is stored AND the client env is present) wins over the
* service account, which stays as the technical fallback. `null` means no
* credential at all — the fail-closed state that skips the sync.
*/
export const readGoogleCalendarAuth = (
doc: GoogleCalendarSyncDoc | null,
oauthClient: GoogleCalendarOAuthClientCredentials | null = readGoogleCalendarOAuthCredentials(),
): GoogleCalendarAuth | null => {
if (doc?.oauthRefreshToken && oauthClient) {
return {
kind: 'oauth',
credentials: {
clientId: oauthClient.clientId,
clientSecret: oauthClient.clientSecret,
refreshToken: doc.oauthRefreshToken,
},
}
console.warn(
`[GoogleCalendarSync] ${GOOGLE_CALENDAR_SERVICE_ACCOUNT_KEY_ENV} está malformado: client_email ou private_key ausente/vazio.`,
)
} catch {
console.warn(
`[GoogleCalendarSync] ${GOOGLE_CALENDAR_SERVICE_ACCOUNT_KEY_ENV} não é base64 válido ou JSON inválido.`,
)
}
return null
const serviceAccount = readGoogleServiceAccountCredentials()
return serviceAccount ? { kind: 'service-account', credentials: serviceAccount } : null
}
export const loadGoogleCalendarSyncConfig = async (
@ -187,26 +257,31 @@ export const loadGoogleCalendarSyncConfig = async (
): Promise<GoogleCalendarSyncDoc | null> => {
// Intentional admin bypass: config/state of the mirror is read by the
// engine and the agenda pill for any staff — access is enforced at the
// action layer, never per-read. The configured row wins: a stray empty
// row (staff can no longer create one, but legacy rows may exist) must
// never shadow the operational calendar (single-row invariant). The
// webhook route and the engine rely on this bypass for the channel
// identity fields, which no user path may read.
// action layer, never per-read. The webhook route and the engine rely on
// this bypass for the channel identity fields, which no user path may read.
//
// C149 — single-row read with a preference: the configured row (calendarId
// present) wins, and when none is configured the connection-only row is
// returned (fresh setup: the OAuth connection exists before C150 picks the
// calendar). The collection holds one row operationally; legacy extra docs
// must never shadow the operational calendar — same intentional admin bypass.
const result = await payload.find({
collection: 'googleCalendarSync',
limit: 1,
limit: 0,
pagination: false,
depth: 0,
where: { calendarId: { exists: true } },
sort: 'createdAt',
overrideAccess: true,
req,
})
return result.docs[0] ?? null
const docs = result.docs
return docs.find((doc) => Boolean(doc.calendarId)) ?? docs[0] ?? null
}
const docToView = (
doc: GoogleCalendarSyncDoc | null,
hasCredential: boolean,
oauthAvailable: boolean,
): GoogleCalendarSyncView => ({
status: deriveGoogleCalendarSyncStatus({
hasCredential,
@ -215,6 +290,14 @@ const docToView = (
lastSuccessAt: doc?.lastSuccessAt ?? null,
lastErrorAt: doc?.lastErrorAt ?? null,
}),
connection: deriveGoogleCalendarConnectionStatus({
hasRefreshToken: Boolean(doc?.oauthRefreshToken),
oauthConnectedAt: doc?.oauthConnectedAt ?? null,
oauthErrorAt: doc?.oauthErrorAt ?? null,
}),
oauthAvailable,
oauthConnectedAt: doc?.oauthConnectedAt ?? null,
oauthError: doc?.oauthError ?? null,
calendarId: doc?.calendarId ?? null,
lastSyncedAt: doc?.lastSyncedAt ?? null,
lastSuccessAt: doc?.lastSuccessAt ?? null,
@ -228,11 +311,9 @@ const docToView = (
export const readGoogleCalendarSyncView = async (
payload: Payload,
): Promise<GoogleCalendarSyncView> => {
const [doc, credentials] = await Promise.all([
loadGoogleCalendarSyncConfig(payload),
readGoogleServiceAccountCredentials(),
])
return docToView(doc, credentials !== null)
const doc = await loadGoogleCalendarSyncConfig(payload)
const oauthClient = readGoogleCalendarOAuthCredentials()
return docToView(doc, readGoogleCalendarAuth(doc, oauthClient) !== null, oauthClient !== null)
}
/**
@ -638,6 +719,8 @@ type SyncStatePatch = Partial<
| 'lastSuccessAt'
| 'lastErrorAt'
| 'lastError'
| 'oauthErrorAt'
| 'oauthError'
| 'pushChannelId'
| 'pushChannelResourceId'
| 'pushChannelExpiresAt'
@ -720,6 +803,209 @@ export const recordGoogleCalendarSyncError = async (
await recordSyncState(payload, undefined, { lastErrorAt: at, lastError: message.slice(0, 500) })
}
/**
* C149 — persists the OAuth connection (the callback calls this after a
* successful code exchange). Creates the singleton connection row when the
* start action did not (fresh setup); clears every error field so the derived
* connection state recovers to `connected` by construction. The refresh token
* is system state, written with the admin bypass, and never returned here.
*/
export const recordGoogleCalendarOAuthConnection = async (
payload: Payload,
data: { refreshToken: string; scope: string | null },
req?: PayloadRequest,
): Promise<void> => {
const at = new Date().toISOString()
const patch = {
oauthRefreshToken: data.refreshToken,
oauthScope: data.scope,
oauthConnectedAt: at,
oauthErrorAt: null,
oauthError: null,
}
const doc = await loadGoogleCalendarSyncConfig(payload, req)
if (doc) {
await payload.update({
collection: 'googleCalendarSync',
id: doc.id,
data: patch,
depth: 0,
// Intentional admin bypass: the connection is system state, unreadable
// by user paths; the caller checks the actor before getting here.
overrideAccess: true,
req,
})
return
}
await payload.create({
collection: 'googleCalendarSync',
data: patch,
depth: 0,
// Intentional admin bypass: same rationale as above.
overrideAccess: true,
req,
})
}
/**
* C149 — records a failed handshake (code exchange) so the UI shows the
* connection `error` with the reconnect path. Never throws into the callback:
* the failure is already being surfaced by the redirect.
*/
export const recordGoogleCalendarOAuthError = async (
payload: Payload,
message: string,
): Promise<void> => {
const doc = await loadGoogleCalendarSyncConfig(payload)
if (!doc) return // nothing to record onto — the start action creates the row
const at = new Date().toISOString()
await payload.update({
collection: 'googleCalendarSync',
id: doc.id,
data: { oauthErrorAt: at, oauthError: message.slice(0, 500) },
depth: 0,
// Intentional admin bypass: connection state is system-only.
overrideAccess: true,
})
}
/**
* C149 — disconnect: drops the OAuth connection from the Teqo (the UI guides
* revoking the app access on the Google account). The service account, when
* configured, takes over on the next trigger — no sync pass is forced here.
*/
export const clearGoogleCalendarOAuthConnection = async (payload: Payload): Promise<void> => {
const doc = await loadGoogleCalendarSyncConfig(payload)
if (!doc) return
await payload.update({
collection: 'googleCalendarSync',
id: doc.id,
data: {
oauthRefreshToken: null,
oauthScope: null,
oauthConnectedAt: null,
oauthErrorAt: null,
oauthError: null,
},
depth: 0,
// Intentional admin bypass: the disconnect action checks the actor.
overrideAccess: true,
})
}
/** C150 — one calendar option of the primary-calendar picker. */
export type GoogleCalendarPickerOption = GoogleCalendarListEntry
export type GoogleCalendarPickerListResult =
| { ok: true; calendars: GoogleCalendarPickerOption[] }
| { ok: false; reason: 'not-connected' | 'auth-error' | 'api-error'; message: string }
export type GoogleCalendarPrimaryCalendarResult =
| { ok: true; calendarId: string }
| {
ok: false
reason: 'not-connected' | 'auth-error' | 'api-error' | 'not-listed'
message: string
}
const GOOGLE_CALENDAR_PICKER_NOT_CONNECTED_MESSAGE =
'Conecte a conta Google da campanha para listar e escolher o calendário principal.'
const GOOGLE_CALENDAR_PICKER_LIST_FAILED_MESSAGE =
'Não foi possível listar os calendários do Google agora. Tente de novo.'
const GOOGLE_CALENDAR_PICKER_NOT_LISTED_MESSAGE =
'O calendário escolhido não está mais disponível na conta Google conectada. Atualize a lista e escolha de novo.'
/**
* C150 — lists the calendars the connected account can WRITE to. The service
* account is deliberately refused: its own calendar list does not contain the
* calendars shared with it, so it cannot back a picker (the connection is the
* C149 hard dependency of this surface). A dead OAuth connection is recorded
* on the row (same classification as the engine) so the card derives `error`
* and offers Reconnect; every other failure is a transient API error.
*/
const loadWritableGoogleCalendars = async (
payload: Payload,
doc: GoogleCalendarSyncDoc | null,
client?: GoogleCalendarClient,
): Promise<GoogleCalendarPickerListResult> => {
const auth = readGoogleCalendarAuth(doc)
if (auth?.kind !== 'oauth') {
return {
ok: false,
reason: 'not-connected',
message: GOOGLE_CALENDAR_PICKER_NOT_CONNECTED_MESSAGE,
}
}
try {
return {
ok: true,
calendars: await (client ?? createGoogleCalendarClient(auth)).listCalendars(),
}
} catch (error) {
if (error instanceof GoogleCalendarAuthError) {
await recordGoogleCalendarOAuthError(payload, error.message)
return { ok: false, reason: 'auth-error', message: error.message }
}
return { ok: false, reason: 'api-error', message: GOOGLE_CALENDAR_PICKER_LIST_FAILED_MESSAGE }
}
}
/** The read model of the picker: the connected account's writable calendars. */
export const listGoogleCalendarPickerOptions = async (
payload: Payload,
options?: { client?: GoogleCalendarClient },
): Promise<GoogleCalendarPickerListResult> =>
loadWritableGoogleCalendars(payload, await loadGoogleCalendarSyncConfig(payload), options?.client)
/**
* C150 — sets the campaign's primary calendar (`calendarId`), the one the
* mirror writes to. The id is validated server-side against the connected
* account's LIVE writable list before the write, so the campaign surface can
* never point the mirror at an arbitrary string (the Payload admin keeps that
* escape hatch through the field's admin-only access). The write uses the
* admin bypass by design: the caller (campaign action) authorizes the actor
* and this utility owns the value validation. The `afterChange` config hook
* (D7) reconciles the mirror into the new calendar; the old one is left as-is
* (design C114 D7 — no backfill, no retro-cleanup).
*/
export const setCampaignPrimaryCalendarId = async (
payload: Payload,
calendarId: string,
options?: { client?: GoogleCalendarClient },
): Promise<GoogleCalendarPrimaryCalendarResult> => {
const doc = await loadGoogleCalendarSyncConfig(payload)
if (!doc) {
return {
ok: false,
reason: 'not-connected',
message: GOOGLE_CALENDAR_PICKER_NOT_CONNECTED_MESSAGE,
}
}
if (doc.calendarId === calendarId) return { ok: true, calendarId }
const listed = await loadWritableGoogleCalendars(payload, doc, options?.client)
if (!listed.ok) return listed
if (!listed.calendars.some((calendar) => calendar.id === calendarId)) {
return { ok: false, reason: 'not-listed', message: GOOGLE_CALENDAR_PICKER_NOT_LISTED_MESSAGE }
}
await payload.update({
collection: 'googleCalendarSync',
id: doc.id,
data: { calendarId },
depth: 0,
// Intentional admin bypass: `calendarId` is admin-only at the field level;
// the campaign path is authorized at the action and validated above.
overrideAccess: true,
})
return { ok: true, calendarId }
}
/** The push-channel webhook address; the URL secret IS the credential. */
const buildPushChannelAddress = (secret: string): string | null => {
try {
@ -827,6 +1113,20 @@ const ensureGoogleCalendarPushChannel = async (
}
}
/**
* C149 — pure classification for the engine's catch: only a dead OAuth
* connection (`GoogleCalendarAuthError`, i.e. `invalid_grant`) also flips the
* connection to `error`; every other failure stays `paused` without touching
* the connection. Exported for the unit pin (the engine catch is I/O-bound).
*/
export const oauthErrorPatchFor = (
error: unknown,
at: string,
): Pick<GoogleCalendarSyncDoc, 'oauthErrorAt' | 'oauthError'> | null =>
error instanceof GoogleCalendarAuthError
? { oauthErrorAt: at, oauthError: error.message.slice(0, 500) }
: null
export type CampaignCalendarSyncOutcome = SyncCounts & {
status: GoogleCalendarSyncStatus
at: string
@ -853,20 +1153,20 @@ export const runCampaignCalendarSync = async (
payload: Payload,
options: CampaignCalendarSyncOptions,
): Promise<CampaignCalendarSyncOutcome> => {
const credentials = readGoogleServiceAccountCredentials()
const config = await loadGoogleCalendarSyncConfig(payload, options.req)
const auth = readGoogleCalendarAuth(config)
const at = new Date().toISOString()
if (!credentials || !config?.calendarId || config.disabledAt) {
if (!auth || !config?.calendarId || config.disabledAt) {
const status = deriveGoogleCalendarSyncStatus({
hasCredential: credentials !== null,
hasCredential: auth !== null,
calendarId: config?.calendarId ?? null,
disabledAt: config?.disabledAt ?? null,
lastSuccessAt: config?.lastSuccessAt ?? null,
lastErrorAt: config?.lastErrorAt ?? null,
})
payload.logger.warn(
`[GoogleCalendarSync] Sincronização ignorada: credentialsPresent=${credentials !== null}, calendarId=${config?.calendarId ?? 'null'}, disabledAt=${config?.disabledAt ?? 'null'}, status=${status}`,
`[GoogleCalendarSync] Sincronização ignorada: credentialsPresent=${auth !== null}, calendarId=${config?.calendarId ?? 'null'}, disabledAt=${config?.disabledAt ?? 'null'}, status=${status}`,
)
return {
status,
@ -882,8 +1182,7 @@ export const runCampaignCalendarSync = async (
// the hook `signal` is not plumbed into that instance — the stub must be
// created with its own signal. Production hooks never inject a client, so
// the `??` branch covers the row-lock path.
const client =
options.client ?? createGoogleCalendarClient(credentials, undefined, options.signal)
const client = options.client ?? createGoogleCalendarClient(auth, undefined, options.signal)
try {
if (!options.skipChannelEnsure) {
@ -897,17 +1196,28 @@ export const runCampaignCalendarSync = async (
options.activityWhere,
config,
)
await recordSyncState(payload, options.req, { lastSyncedAt: at, lastSuccessAt: at })
// C149 — a successful pass also clears a previous OAuth error: the
// connection state recovers to `connected` without a manual reconnect.
await recordSyncState(payload, options.req, {
lastSyncedAt: at,
lastSuccessAt: at,
oauthErrorAt: null,
oauthError: null,
})
return { status: 'synced', ...counts, at }
} catch (error) {
const message =
error instanceof Error ? error.message : 'Erro desconhecido ao sincronizar com o Google.'
payload.logger.error(`[GoogleCalendarSync] Erro durante a sincronização: ${message}`)
await recordSyncState(payload, options.req, {
const patch: SyncStatePatch = {
lastSyncedAt: at,
lastErrorAt: at,
lastError: message.slice(0, 500),
})
}
// C149 — a dead OAuth connection (`invalid_grant`) additionally flips the
// derived connection state to `error`, which offers reconnect in one click.
Object.assign(patch, oauthErrorPatchFor(error, at) ?? {})
await recordSyncState(payload, options.req, patch)
return { status: 'paused', created: 0, updated: 0, deleted: 0, reverseEdits: 0, at }
}
}

View file

@ -412,6 +412,8 @@ test.describe('Agenda — calendário operacional', () => {
// regression): saving must actually persist.
await editModal.getByLabel('Hora de Término').selectOption('15')
await editModal.getByLabel('Local (opcional)').fill(newLocality)
// C151 — the public-event intent is marked in the same save.
await editModal.getByLabel('Evento público').click()
await editModal.getByRole('button', { name: 'Salvar alterações' }).click()
// Save closes the overlay, never navigates; the calendar reflects the edit.
@ -426,6 +428,8 @@ test.describe('Agenda — calendário operacional', () => {
await page.getByText(title, { exact: true }).first().click()
const detailModal = page.getByRole('dialog', { name: 'Editar atividade' })
await expect(detailModal.getByLabel('Título *')).toBeVisible({ timeout: 30_000 })
// C151 — the mark survives the save and comes back on reopening the overlay.
await expect(detailModal.getByLabel('Evento público')).toHaveAttribute('aria-checked', 'true')
await detailModal.getByRole('link', { name: 'Ver detalhes' }).click()
await expect(page).toHaveURL(/\/campanha\/atividades\/[^/?]+(?:\?tab=overview)?$/, {
timeout: 30_000,

View file

@ -49,7 +49,7 @@ const seedSyncConfig = (
})
test.describe('Agenda — sincronização Google (C114/C122)', () => {
test('staff vê a pill "não configurado" e o diálogo explica o passo de operação', async ({
test('staff vê a pill "não configurado" e o diálogo oferece conectar (C149)', async ({
campaign,
page,
}) => {
@ -67,9 +67,57 @@ test.describe('Agenda — sincronização Google (C114/C122)', () => {
const dialog = syncDialog(page)
await expect(dialog).toBeVisible()
await expect(dialog.getByText('Ainda não configurado')).toBeVisible()
// O runbook de operação aparece (a ativação depende da conta Google da campanha).
await expect(dialog.getByText(/service account do Teqo/)).toBeVisible()
// C149: sem conexão, o card oferece o botão de conectar (o client OAuth
// dummy está no webServer) e mantém a service account como fallback.
await expect(dialog.getByText('Não configurado')).toBeVisible()
await expect(dialog.getByRole('button', { name: 'Conectar com o Google' })).toBeVisible()
await expect(dialog.getByText(/service account continua disponível/)).toBeVisible()
})
test('o botão Conectar leva ao consent do Google com os escopos mínimos (C149)', async ({
campaign,
page,
}) => {
const { fixtures } = campaign
const coordinator = await fixtures.createCampaignUser('coordinator')
// Row owned by the fixture: the start action UPDATES it (the connection
// row may exist before any calendar is chosen) instead of creating a row
// the cleanup would not track.
await fixtures.payload.create({
collection: 'googleCalendarSync',
data: {},
depth: 0,
overrideAccess: true,
})
await campaign.login(page, coordinator.email!, coordinator.password)
await page.goto(`${campaign.baseURL}/campanha/agenda`)
// The click navigates the browser to accounts.google.com — intercept so
// the assertion observes the URL Google would receive, with no network.
await page.route('https://accounts.google.com/**', (route) =>
route.fulfill({ status: 200, contentType: 'text/html', body: '<title>consent</title>' }),
)
const pill = page.getByRole('button', { name: 'Google: não configurado' })
await expect(pill).toBeVisible({ timeout: 15_000 })
await pill.click()
const dialog = syncDialog(page)
await expect(dialog).toBeVisible()
await dialog.getByRole('button', { name: 'Conectar com o Google' }).click()
await expect.poll(() => page.url()).toContain('accounts.google.com/o/oauth2/v2/auth')
const url = new URL(page.url())
expect(url.searchParams.get('access_type')).toBe('offline')
expect(url.searchParams.get('prompt')).toBe('consent')
expect(url.searchParams.get('response_type')).toBe('code')
expect(url.searchParams.get('scope')).toBe(
'https://www.googleapis.com/auth/calendar.events https://www.googleapis.com/auth/calendar.calendarlist.readonly',
)
expect(url.searchParams.get('state')).toBeTruthy()
const redirectUri = new URL(url.searchParams.get('redirect_uri') as string)
expect(redirectUri.pathname).toBe('/campanha/agenda/google-oauth/callback')
})
test('estado disabled: pill, aviso de desativação e Reativar re-sincroniza (D7)', async ({
@ -135,7 +183,7 @@ test.describe('Agenda — sincronização Google (C114/C122)', () => {
)
})
test('estado synced: pill, link do calendário com copiar e instruções', async ({
test('estado synced: pill, link do calendário, seletor principal e one-click (C150)', async ({
campaign,
page,
}) => {
@ -143,14 +191,26 @@ test.describe('Agenda — sincronização Google (C114/C122)', () => {
const coordinator = await fixtures.createCampaignUser('coordinator')
// lastSuccessAt no futuro: imune a lastErrorAt gravado por hooks de specs
// paralelas (a derivação só volta a synced enquanto erro não for mais novo).
// O refresh token seedado dá o estado `connected` (o client OAuth dummy
// está no webServer) — necessário para o seletor de calendário principal.
await seedSyncConfig(fixtures, {
lastSyncedAt: FAR_FUTURE,
lastSuccessAt: FAR_FUTURE,
oauthRefreshToken: 'c150-e2e-refresh',
oauthConnectedAt: '2026-08-01T10:00:00.000Z',
})
await campaign.login(page, coordinator.email!, coordinator.password)
await page.goto(`${campaign.baseURL}/campanha/agenda`)
// C150 — o one-click do header aparece para staff quando há calendário.
const headerAdd = page.locator('a[aria-label="Adicionar ao meu Google Calendar"]:visible')
await expect(headerAdd).toBeVisible({ timeout: 15_000 })
await expect(headerAdd).toHaveAttribute(
'href',
`https://calendar.google.com/calendar/r?cid=${encodeURIComponent(CALENDAR_ID)}`,
)
const pill = page.getByRole('button', { name: 'Google: sincronizado' })
await expect(pill).toBeVisible({ timeout: 15_000 })
await pill.click()
@ -160,12 +220,20 @@ test.describe('Agenda — sincronização Google (C114/C122)', () => {
await expect(
dialog.getByText(/Sincronizado — as mudanças da agenda já refletiram/),
).toBeVisible()
// O link de adição vem do calendarId seedado (webcal → cid) + copiar + instruções.
const linkInput = dialog.getByLabel('Link do calendário (copie e envie à equipe)')
await expect(linkInput).toHaveValue(
`https://calendar.google.com/calendar/r?cid=${encodeURIComponent(
`webcal://calendar.google.com/calendar/ical/${encodeURIComponent(CALENDAR_ID)}/public/basic.ics`,
)}`,
// C150 — o seletor do calendário principal (manager + conexão ativa).
await expect(dialog.getByRole('button', { name: 'Trocar calendário principal' })).toBeVisible()
// O one-click no diálogo e a URL iCal pública para o caminho manual.
await expect(
dialog.getByRole('link', { name: 'Adicionar ao meu Google Calendar' }),
).toHaveAttribute(
'href',
`https://calendar.google.com/calendar/r?cid=${encodeURIComponent(CALENDAR_ID)}`,
)
const icalInput = dialog.getByLabel(
'URL pública do calendário (Por URL, Apple Calendar e Outlook)',
)
await expect(icalInput).toHaveValue(
`https://calendar.google.com/calendar/ical/${encodeURIComponent(CALENDAR_ID)}/public/basic.ics`,
)
await expect(dialog.getByRole('button', { name: 'Copiar link' })).toBeVisible()
await expect(dialog.getByText(/Como adicionar ao Google Calendar:/)).toBeVisible()
@ -187,6 +255,35 @@ test.describe('Agenda — sincronização Google (C114/C122)', () => {
await expect(dialog.getByRole('button', { name: 'Sincronizar agora' })).toBeVisible()
})
test('advisor vê o one-click mas não o seletor de calendário (C150)', async ({
campaign,
page,
}) => {
const { fixtures } = campaign
const advisor = await fixtures.createCampaignUser('advisor')
await seedSyncConfig(fixtures, {
lastSyncedAt: FAR_FUTURE,
lastSuccessAt: FAR_FUTURE,
oauthRefreshToken: 'c150-e2e-refresh-advisor',
oauthConnectedAt: '2026-08-01T10:00:00.000Z',
})
await campaign.login(page, advisor.email!, advisor.password)
await page.goto(`${campaign.baseURL}/campanha/agenda`)
const headerAdd = page.locator('a[aria-label="Adicionar ao meu Google Calendar"]:visible')
await expect(headerAdd).toBeVisible({ timeout: 15_000 })
const pill = page.getByRole('button', { name: 'Google: sincronizado' })
await expect(pill).toBeVisible({ timeout: 15_000 })
await pill.click()
const dialog = syncDialog(page)
await expect(dialog).toBeVisible()
await expect(dialog.getByRole('button', { name: /calendário principal/ })).toHaveCount(0)
await expect(dialog.getByText(/escolhido por candidato ou coordenação/)).toBeVisible()
})
test.describe('mobile (FAB)', () => {
test.use({ viewport: { width: 390, height: 844 } })
@ -212,7 +309,32 @@ test.describe('Agenda — sincronização Google (C114/C122)', () => {
const sheet = syncDialog(page)
await expect(sheet).toBeVisible({ timeout: 15_000 })
await expect(sheet.getByText('Ainda não configurado')).toBeVisible()
await expect(sheet.getByText('Não configurado')).toBeVisible()
await expect(sheet.getByRole('button', { name: 'Conectar com o Google' })).toBeVisible()
})
test('o one-click do header aparece no mobile com calendário principal (C150)', async ({
campaign,
page,
}) => {
const { fixtures } = campaign
const coordinator = await fixtures.createCampaignUser('coordinator')
await seedSyncConfig(fixtures, {
lastSyncedAt: FAR_FUTURE,
lastSuccessAt: FAR_FUTURE,
})
await campaign.login(page, coordinator.email!, coordinator.password)
await page.goto(`${campaign.baseURL}/campanha/agenda`)
// O cluster do top bar não suporta botão full-width (adaptação do
// rascunho): no mobile o one-click é o ícone com aria-label.
const addLink = page.locator('a[aria-label="Adicionar ao meu Google Calendar"]:visible')
await expect(addLink).toBeVisible({ timeout: 15_000 })
await expect(addLink).toHaveAttribute(
'href',
`https://calendar.google.com/calendar/r?cid=${encodeURIComponent(CALENDAR_ID)}`,
)
})
})

View file

@ -38,6 +38,41 @@ const swipeLeft = async (
await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] })
}
/**
* S14 — scans the name band (y[420..540]) of a card canvas: yellow pixel count
* and leftmost x. The base masters have no yellow in this band, so the scan
* sees only the drawn name.
*/
const readCardNameBand = (canvas: Locator) =>
canvas.evaluate((element) => {
const node = element as HTMLCanvasElement
const ctx = node.getContext('2d')
if (!ctx) return { yellow: 0, minX: node.width }
const band = ctx.getImageData(0, 420, node.width, 120).data
let yellow = 0
let minX = node.width
for (let index = 0; index < band.length; index += 4) {
if (band[index] > 230 && band[index + 1] > 200 && band[index + 2] < 80) {
yellow += 1
const x = (index / 4) % node.width
if (x < minX) minX = x
}
}
return { yellow, minX }
})
/** S14 — the name starts on the `SOU` left border (x≈213 at 1080), not centered. */
const expectCardNameLeftAligned = async (canvas: Locator) => {
await expect
.poll(async () => {
const { yellow, minX } = await readCardNameBand(canvas)
return yellow > 1000 && minX >= 205 && minX <= 245
})
.toBe(true)
}
test.describe('Frontend', () => {
test('can go on homepage', async ({ page }) => {
await page.goto('/')
@ -1656,8 +1691,8 @@ test.describe('Campaign home content section', () => {
})
})
test.describe('Cards personalizados (S13)', () => {
test('home invites to the card funnel right after the newsletter capture', async ({ page }) => {
test.describe('Cards personalizados (S14)', () => {
test('home opens the composer in place right before the newsletter capture', async ({ page }) => {
await page.goto('/')
const order = await page
@ -1665,19 +1700,28 @@ test.describe('Cards personalizados (S13)', () => {
.evaluateAll((sections) =>
sections.map((section) => section.getAttribute('data-home-section')),
)
expect(order.indexOf('cards')).toBe(order.indexOf('newsletter') + 1)
expect(order.indexOf('cards')).toBe(order.indexOf('story') + 1)
expect(order.indexOf('cards')).toBe(order.indexOf('newsletter') - 1)
const section = page.locator('section#cards')
await expect(
section.getByRole('heading', { name: 'Mostre que você está com Solla' }),
).toBeVisible()
// S14 — the CTA is gone: the three models are the only trigger.
await expect(section.getByRole('link', { name: 'Criar meu card' })).toHaveCount(0)
for (const model of ['eu-sou-solla', 'perfil-quadrado', 'perfil-retangular']) {
await expect(section.locator(`a[href="/cards?model=${model}"]`).first()).toBeAttached()
await expect(section.locator(`[data-card-model-tile="${model}"]`).first()).toBeAttached()
}
const trigger = section.getByRole('link', { name: /Moldura quadrada/ })
// S14 — the name tile reproduces the real result: `SEU NOME` drawn by the
// composer pipeline, left-aligned with the `SOU` border (x≈213 at 1080).
const nameTileCanvas = section.locator('[data-card-model-tile="eu-sou-solla"] canvas').first()
await expectCardNameLeftAligned(nameTileCanvas)
const trigger = section.getByRole('button', { name: /Moldura quadrada/ })
await trigger.click()
await expect(page).toHaveURL(/\/cards\?model=perfil-quadrado$/)
// No navigation: the same composer island opens over the home.
expect(new URL(page.url()).pathname).toBe('/')
const dialog = page.getByRole('dialog')
await expect(dialog.getByRole('heading', { name: 'Enquadre sua foto' })).toBeVisible()
await page.keyboard.press('Escape')
@ -1705,19 +1749,9 @@ test.describe('Cards personalizados (S13)', () => {
const canvas = dialog.locator('canvas')
await expect(canvas).toHaveAttribute('width', '1080')
await expect(canvas).toHaveAttribute('height', '1440')
await expect
.poll(() =>
canvas.evaluate((element) => {
const node = element as HTMLCanvasElement
const band = node.getContext('2d')!.getImageData(0, 420, node.width, 120).data
let yellow = 0
for (let index = 0; index < band.length; index += 4) {
if (band[index] > 230 && band[index + 1] > 200 && band[index + 2] < 80) yellow += 1
}
return yellow
}),
)
.toBeGreaterThan(1000)
// S14 — the name is drawn on the `SOU` left border (x≈213 at 1080), not
// centered: a centered `João` would start past x=350.
await expectCardNameLeftAligned(canvas)
await primary.click()
await expect(dialog.getByText('Seu card está pronto para compartilhar.')).toBeVisible()

View file

@ -12,6 +12,19 @@ import { assertTestDatabase } from './assertTestDatabase'
*/
export const ADMIN_LOGIN_LOCK_KEY = 727_001
/**
* C149 — `googleCalendarSync` is a SINGLETON row, and the int suite runs files
* in parallel against one database: several google specs create/pick/delete
* configured rows concurrently, and the loader's "configured row wins"
* preference then resolves to ANOTHER file's row (channel/count assertions
* read the wrong doc, snapshots land on a row being deleted). Serialize the
* whole google calendar family for the duration of each file with
* `serializeGoogleCalendarSyncSpec` (`tests/helpers/googleCalendarSyncLock.ts`
* — the vitest hooks live there so this module stays loadable by Playwright
* fixtures, which must never pull `vitest` into the e2e process).
*/
export const GOOGLE_CALENDAR_SYNC_LOCK_KEY = 727_002
/**
* Runs `fn` while holding a Postgres advisory lock.
*
@ -33,3 +46,20 @@ export const withAdvisoryLock = async <T>(key: number, fn: () => Promise<T>): Pr
await client.end().catch(() => {})
}
}
/**
* Acquires the lock on a dedicated connection and returns the release
* function. The caller owns the lifetime (a spec file holds it between its
* `beforeAll` and `afterAll`); a crashed worker drops the connection and the
* lock is released by Postgres.
*/
export const acquireAdvisoryLock = async (key: number): Promise<() => Promise<void>> => {
assertTestDatabase(process.env.DATABASE_URL)
const client = new Client({ connectionString: process.env.DATABASE_URL })
await client.connect()
await client.query('SELECT pg_advisory_lock($1)', [key])
return async () => {
await client.query('SELECT pg_advisory_unlock($1)', [key]).catch(() => {})
await client.end().catch(() => {})
}
}

View file

@ -0,0 +1,29 @@
import { afterAll, beforeAll } from 'vitest'
import { acquireAdvisoryLock, GOOGLE_CALENDAR_SYNC_LOCK_KEY } from './advisoryLock'
/**
* C149 — holds the google-calendar advisory lock for the WHOLE spec file
* (`beforeAll` acquires on a dedicated connection, `afterAll` releases it).
* Call at the top level of every int spec that touches the singleton
* `googleCalendarSync` row so parallel files cannot read/write each other's
* configured row.
*
* This module imports vitest hooks ON PURPOSE and must only be imported by
* int specs: `tests/helpers/advisoryLock.ts` is also loaded by Playwright
* fixtures, and pulling `vitest` into the e2e process breaks its matchers
* (`Cannot redefine property: Symbol($$jest-matchers-object)`).
*/
export const serializeGoogleCalendarSyncSpec = (): void => {
let release: (() => Promise<void>) | null = null
beforeAll(async () => {
release = await acquireAdvisoryLock(GOOGLE_CALENDAR_SYNC_LOCK_KEY)
}, 60_000)
afterAll(async () => {
if (!release) return
await release()
release = null
})
}

View file

@ -647,6 +647,57 @@ describe('activity domain', () => {
expect(parsed.endAt).toBe(allDayEndInstant('2026-08-12'))
})
it('parses the public event flag from the activity form (C151)', () => {
const formData = new FormData()
formData.set('title', 'Comício público')
formData.set('status', 'confirmado')
formData.set('municipality', '1')
formData.set('tagsJson', '[]')
formData.set('demandsJson', '[]')
// Unchecked checkbox is absent from FormData — parses as false.
expect(parseActivityCreateFormData(formData).publicEvent).toBe(false)
formData.set('publicEvent', 'on')
expect(parseActivityCreateFormData(formData).publicEvent).toBe(true)
})
it('persists the public event flag and returns it when reopening the overlay (C151)', async () => {
const fixtures = campaignFixtures()
const coordinator = await fixtures.createCampaignUser('coordinator')
const [markedMunicipality, ordinaryMunicipality] = await Promise.all([
fixtures.getMunicipality(),
fixtures.getMunicipality(),
])
// Far-future startAt keeps these rows OUTSIDE the Google sync engine's
// 90/365-day scan window, avoiding the C126 parallel-flake class.
const farFuture = new Date(Date.now() + 400 * 86_400_000).toISOString()
const marked = await createActivityRecord(payload, coordinator, {
...validActivityInput(markedMunicipality.id),
title: fixtures.value('Evento público marcado'),
startAt: farFuture,
publicEvent: true,
})
fixtures.own('activity', marked.id)
const ordinary = await createActivityRecord(payload, coordinator, {
...validActivityInput(ordinaryMunicipality.id),
title: fixtures.value('Atividade interna'),
startAt: farFuture,
})
fixtures.own('activity', ordinary.id)
expect(marked.publicEvent).toBe(true)
expect(ordinary.publicEvent).toBe(false)
expect((await loadActivityEditDraftRecord(payload, coordinator, marked.id)).publicEvent).toBe(
true,
)
expect((await loadActivityEditDraftRecord(payload, coordinator, ordinary.id)).publicEvent).toBe(
false,
)
})
it('loads only accessible events matching the agenda range and filters', async () => {
const fixtures = campaignFixtures()
const advisor = await fixtures.createCampaignUser('advisor')

View file

@ -8,11 +8,14 @@ import { loadGoogleCalendarSyncConfig } from '@/utilities/googleCalendarSync'
import { hookFilledCreateData } from '@/utilities/hookFilledData'
import { installCampaignFixtures } from '../helpers/campaignFixtures'
import { serializeGoogleCalendarSyncSpec } from '../helpers/googleCalendarSyncLock'
import {
createSlowGoogleFetch,
withValidGoogleCalendarCredential,
} from '../helpers/googleCalendarTestKey'
serializeGoogleCalendarSyncSpec()
let payload: Payload
const campaignFixtures = installCampaignFixtures({
getPayload: () => payload,

View file

@ -0,0 +1,166 @@
// @vitest-environment node
//
// C149 — the OAuth connection stored on the singleton `googleCalendarSync`
// row: recording, error state, disconnect, view/loader derivation. The int
// suite runs files in parallel against ONE shared database, so this file only
// creates CONNECTION-ONLY rows (no `calendarId`): the singleton loader prefers
// a configured row, which means these rows can never shadow the engine specs'
// configured row. Rows this file created are tracked and deleted; a token that
// landed on a shared row (the loader's preference) is cleared, never deleted.
import { getPayload, type Payload } from 'payload'
import { afterEach, beforeAll, describe, expect, it } from 'vitest'
import config from '@/payload.config'
import {
GOOGLE_CALENDAR_OAUTH_CLIENT_ID_ENV,
GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET_ENV,
} from '@/utilities/googleCalendarOAuth'
import {
clearGoogleCalendarOAuthConnection,
loadGoogleCalendarSyncConfig,
readGoogleCalendarSyncView,
recordGoogleCalendarOAuthConnection,
recordGoogleCalendarOAuthError,
} from '@/utilities/googleCalendarSync'
import { serializeGoogleCalendarSyncSpec } from '../helpers/googleCalendarSyncLock'
serializeGoogleCalendarSyncSpec()
let payload: Payload
/** Sets/restores the OAuth client pair around a callback — restored on failure too. */
const withGoogleCalendarOAuthClient = async <T>(run: () => Promise<T>): Promise<T> => {
const previous = {
id: process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_ID_ENV],
secret: process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET_ENV],
}
process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_ID_ENV] = 'test-client-id'
process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET_ENV] = 'test-client-secret'
try {
return await run()
} finally {
if (previous.id === undefined) delete process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_ID_ENV]
else process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_ID_ENV] = previous.id
if (previous.secret === undefined) delete process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET_ENV]
else process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET_ENV] = previous.secret
}
}
describe('C149 — OAuth connection on the googleCalendarSync row', () => {
beforeAll(async () => {
payload = await getPayload({ config: await config })
})
const ownedIds = new Set<number>()
afterEach(async () => {
// Clear connection fields this file wrote wherever they landed — the
// loader may have picked a row created by a sibling spec, and that row
// must not be deleted from under it.
const touched = await payload.find({
collection: 'googleCalendarSync',
where: { oauthRefreshToken: { like: 'c149-conn%' } },
depth: 0,
pagination: false,
overrideAccess: true,
})
for (const doc of touched.docs) {
if (ownedIds.has(doc.id)) continue
await payload.update({
collection: 'googleCalendarSync',
id: doc.id,
data: {
oauthRefreshToken: null,
oauthScope: null,
oauthConnectedAt: null,
oauthErrorAt: null,
oauthError: null,
},
depth: 0,
overrideAccess: true,
})
}
for (const id of ownedIds) {
await payload.delete({ collection: 'googleCalendarSync', id, overrideAccess: true })
}
ownedIds.clear()
})
const createConnectionRow = async (data: Record<string, unknown> = {}) => {
const doc = await payload.create({
collection: 'googleCalendarSync',
data,
depth: 0,
overrideAccess: true,
})
ownedIds.add(doc.id)
return doc
}
it('records the connection (create when no row exists) and clears previous errors', async () => {
await createConnectionRow({ oauthErrorAt: '2026-08-11T10:00:00.000Z', oauthError: 'antigo' })
await recordGoogleCalendarOAuthConnection(payload, {
refreshToken: 'c149-conn-create',
scope: 'scope-a scope-b',
})
const doc = await loadGoogleCalendarSyncConfig(payload)
expect(doc?.oauthRefreshToken).toBe('c149-conn-create')
expect(doc?.oauthScope).toBe('scope-a scope-b')
expect(doc?.oauthConnectedAt).toBeTruthy()
expect(doc?.oauthErrorAt).toBeNull()
expect(doc?.oauthError).toBeNull()
})
it('records the auth error and clears the whole connection on disconnect', async () => {
await createConnectionRow({ oauthRefreshToken: 'c149-conn-disconnect' })
await recordGoogleCalendarOAuthError(payload, 'A conexão com o Google expirou.')
let doc = await loadGoogleCalendarSyncConfig(payload)
expect(doc?.oauthError).toBe('A conexão com o Google expirou.')
expect(doc?.oauthErrorAt).toBeTruthy()
await clearGoogleCalendarOAuthConnection(payload)
doc = await loadGoogleCalendarSyncConfig(payload)
expect(doc?.oauthRefreshToken).toBeNull()
expect(doc?.oauthScope).toBeNull()
expect(doc?.oauthConnectedAt).toBeNull()
expect(doc?.oauthErrorAt).toBeNull()
expect(doc?.oauthError).toBeNull()
})
it('derives the connection view (connected → error) and oauthAvailable from the env', async () => {
await createConnectionRow({ oauthRefreshToken: 'c149-conn-view' })
await withGoogleCalendarOAuthClient(async () => {
const connected = await readGoogleCalendarSyncView(payload)
expect(connected.connection).toBe('connected')
expect(connected.oauthAvailable).toBe(true)
await recordGoogleCalendarOAuthError(payload, 'Token revogado.')
const broken = await readGoogleCalendarSyncView(payload)
expect(broken.connection).toBe('error')
expect(broken.oauthError).toBe('Token revogado.')
})
})
it('finds a connection-only row even without a calendarId (fresh setup)', async () => {
const row = await createConnectionRow({ oauthRefreshToken: 'c149-conn-loader' })
const loaded = await loadGoogleCalendarSyncConfig(payload)
// A configured sibling (parallel spec) legitimately wins the singleton
// preference; without one, the connection-only row is the row.
if (loaded?.calendarId) {
expect(loaded.id).not.toBe(row.id)
} else {
expect(loaded?.id).toBe(row.id)
}
expect(row.calendarId ?? null).toBeNull()
})
})

View file

@ -0,0 +1,290 @@
// @vitest-environment node
//
// C149 — the OAuth handshake boundary: the start action (role + state cookie
// + authorize URL) and the callback route (state validation, role re-check,
// code exchange, connection recording). `next/headers` is mocked with an
// in-memory cookie jar so the real signing/verification runs; `fetch` is
// stubbed at the token endpoint so no request leaves the process. Session
// resolution is mocked (the pattern of googleCalendarSyncAction.int.spec.ts);
// everything else — Payload access, the engine hooks, the DB — runs for real.
import { NextRequest } from 'next/server'
import { getPayload, type Payload } from 'payload'
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
import config from '@/payload.config'
const { cookieJar } = vi.hoisted(() => ({ cookieJar: new Map<string, string>() }))
vi.mock('next/headers', () => ({
cookies: async () => ({
get: (name: string) => (cookieJar.has(name) ? { name, value: cookieJar.get(name) } : undefined),
set: (name: string, value: string) => {
cookieJar.set(name, value)
},
}),
headers: async () => new Headers(),
}))
vi.mock('@/utilities/campaignActionContext', async (importOriginal) => {
const original = await importOriginal<typeof import('@/utilities/campaignActionContext')>()
return { ...original, getCampaignActionContext: vi.fn() }
})
// The callback's follow-up reconciliation is not this spec's subject (the
// engine has its own file) and, against the shared singleton, a full pass
// would write snapshots onto whichever row the loader picked — including a
// parallel spec's. Stub only that call; every other export stays real.
vi.mock('@/utilities/googleCalendarSync', async (importOriginal) => {
const original = await importOriginal<typeof import('@/utilities/googleCalendarSync')>()
return { ...original, runCampaignCalendarSync: vi.fn() }
})
import {
disconnectGoogleCalendarOAuth,
startGoogleCalendarOAuth,
} from '@/app/(campaign)/campanha/actions/googleCalendarSync'
import { GET as googleOAuthCallback } from '@/app/(campaign)/campanha/agenda/google-oauth/callback/route'
import { getCampaignActionContext } from '@/utilities/campaignActionContext'
import {
GOOGLE_CALENDAR_OAUTH_CLIENT_ID_ENV,
GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET_ENV,
} from '@/utilities/googleCalendarOAuth'
import { recordGoogleCalendarOAuthConnection } from '@/utilities/googleCalendarSync'
import { installCampaignFixtures } from '../helpers/campaignFixtures'
import { serializeGoogleCalendarSyncSpec } from '../helpers/googleCalendarSyncLock'
serializeGoogleCalendarSyncSpec()
let payload: Payload
const campaignFixtures = installCampaignFixtures({
getPayload: () => payload,
setPayload: (nextPayload) => {
payload = nextPayload
},
})
const mockedGetContext = vi.mocked(getCampaignActionContext)
const OAUTH_ENV_KEYS = [
GOOGLE_CALENDAR_OAUTH_CLIENT_ID_ENV,
GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET_ENV,
] as const
const originalEnv = new Map(OAUTH_ENV_KEYS.map((key) => [key, process.env[key]]))
const setOAuthClientEnv = (): void => {
process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_ID_ENV] = 'test-client-id'
process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET_ENV] = 'test-client-secret'
}
const restoreEnv = (): void => {
for (const key of OAUTH_ENV_KEYS) {
const value = originalEnv.get(key)
if (value === undefined) delete process.env[key]
else process.env[key] = value
}
}
/**
* Token endpoint + an empty calendar API, so the callback's follow-up pass
* completes without network regardless of which row the loader picked.
*/
const googleFetchStub = (refreshToken: string): typeof fetch =>
(async (input: RequestInfo | URL) => {
const url = String(input)
if (url === 'https://oauth2.googleapis.com/token') {
return new Response(
JSON.stringify({
access_token: 'access-token',
refresh_token: refreshToken,
scope:
'https://www.googleapis.com/auth/calendar.events https://www.googleapis.com/auth/calendar.calendarlist.readonly',
}),
{ status: 200, headers: { 'Content-Type': 'application/json' } },
)
}
if (url.includes('/events/watch')) {
return new Response(
JSON.stringify({ id: 'watch-1', resourceId: 'resource-1', expiration: null }),
{ status: 200, headers: { 'Content-Type': 'application/json' } },
)
}
if (url.includes('/channels/stop')) return new Response(null, { status: 204 })
if (url.includes('/calendar/v3/')) {
return new Response(JSON.stringify({ items: [] }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}
throw new Error(`Unexpected fetch to ${url}`)
}) as typeof fetch
const callbackRequest = (params: Record<string, string>): NextRequest =>
new NextRequest(
`http://localhost:3000/campanha/agenda/google-oauth/callback?${new URLSearchParams(params).toString()}`,
)
const rowsWithToken = (token: string) =>
payload.find({
collection: 'googleCalendarSync',
where: { oauthRefreshToken: { equals: token } },
depth: 0,
overrideAccess: true,
})
describe('C149 — OAuth actions and callback', () => {
beforeAll(async () => {
payload = await getPayload({ config: await config })
})
afterEach(async () => {
restoreEnv()
cookieJar.clear()
vi.unstubAllGlobals()
vi.clearAllMocks()
// The connection may have landed on a parallel spec's row (the loader
// prefers a configured row): clear the fields, never delete that row.
const touched = await payload.find({
collection: 'googleCalendarSync',
where: { oauthRefreshToken: { like: 'c149-refresh%' } },
depth: 0,
pagination: false,
overrideAccess: true,
})
for (const doc of touched.docs) {
await payload.update({
collection: 'googleCalendarSync',
id: doc.id,
data: {
oauthRefreshToken: null,
oauthScope: null,
oauthConnectedAt: null,
oauthErrorAt: null,
oauthError: null,
},
depth: 0,
overrideAccess: true,
})
}
// Empty rows (no calendar, no token) are only produced by this file's
// start attempts — safe to delete.
const emptyRows = await payload.find({
collection: 'googleCalendarSync',
where: {
and: [{ calendarId: { exists: false } }, { oauthRefreshToken: { exists: false } }],
},
depth: 0,
pagination: false,
overrideAccess: true,
})
for (const doc of emptyRows.docs) {
await payload.delete({ collection: 'googleCalendarSync', id: doc.id, overrideAccess: true })
}
})
afterAll(() => {
restoreEnv()
})
it('start (coordinator) returns the consent URL and the callback records the connection', async () => {
const coordinator = await campaignFixtures().createCampaignUser('coordinator')
mockedGetContext.mockResolvedValue({ payload, actor: coordinator })
setOAuthClientEnv()
const start = await startGoogleCalendarOAuth()
expect(start.ok).toBe(true)
if (!start.ok) throw new Error('start must succeed')
const authorizeUrl = new URL(start.authorizeUrl)
expect(`${authorizeUrl.origin}${authorizeUrl.pathname}`).toBe(
'https://accounts.google.com/o/oauth2/v2/auth',
)
expect(authorizeUrl.searchParams.get('access_type')).toBe('offline')
expect(authorizeUrl.searchParams.get('prompt')).toBe('consent')
expect(authorizeUrl.searchParams.get('redirect_uri')).toMatch(
/\/campanha\/agenda\/google-oauth\/callback$/,
)
const state = authorizeUrl.searchParams.get('state')
expect(state).toBeTruthy()
expect(cookieJar.has('campaign-google-oauth-state')).toBe(true)
const refreshToken = 'c149-refresh-callback-success'
vi.stubGlobal('fetch', googleFetchStub(refreshToken))
const response = await googleOAuthCallback(
callbackRequest({ code: 'code-1', state: state as string }),
)
expect(response.status).toBe(307)
expect(response.headers.get('location')).toContain('/campanha/agenda')
const rows = await rowsWithToken(refreshToken)
expect(rows.docs).toHaveLength(1)
expect(rows.docs[0]?.oauthConnectedAt).toBeTruthy()
// The state cookie is single-use.
expect(cookieJar.get('campaign-google-oauth-state')).toBe('')
})
it('start refuses an advisor without writing anything', async () => {
const advisor = await campaignFixtures().createCampaignUser('advisor')
mockedGetContext.mockResolvedValue({ payload, actor: advisor })
setOAuthClientEnv()
const start = await startGoogleCalendarOAuth()
expect(start.ok).toBe(false)
if (start.ok) throw new Error('start must be refused')
expect(start.message).toContain('candidato ou coordenação')
expect(cookieJar.has('campaign-google-oauth-state')).toBe(false)
})
it('start fails closed when the OAuth client env is missing', async () => {
const coordinator = await campaignFixtures().createCampaignUser('coordinator')
mockedGetContext.mockResolvedValue({ payload, actor: coordinator })
delete process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_ID_ENV]
delete process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET_ENV]
const start = await startGoogleCalendarOAuth()
expect(start.ok).toBe(false)
if (start.ok) throw new Error('start must fail')
expect(start.message).toContain('não está configurada no servidor')
})
it('callback refuses an invalid state without recording anything', async () => {
const coordinator = await campaignFixtures().createCampaignUser('coordinator')
mockedGetContext.mockResolvedValue({ payload, actor: coordinator })
setOAuthClientEnv()
vi.stubGlobal('fetch', googleFetchStub('c149-refresh-should-not-exist'))
const response = await googleOAuthCallback(
callbackRequest({ code: 'code-1', state: 'forged-state' }),
)
expect(response.status).toBe(307)
expect((await rowsWithToken('c149-refresh-should-not-exist')).docs).toHaveLength(0)
})
it('callback treats access_denied as a silent redirect', async () => {
const response = await googleOAuthCallback(callbackRequest({ error: 'access_denied' }))
expect(response.status).toBe(307)
expect(response.headers.get('location')).toContain('/campanha/agenda')
})
it('disconnect clears the stored connection', async () => {
const coordinator = await campaignFixtures().createCampaignUser('coordinator')
mockedGetContext.mockResolvedValue({ payload, actor: coordinator })
setOAuthClientEnv()
const refreshToken = 'c149-refresh-disconnect'
await recordGoogleCalendarOAuthConnection(payload, { refreshToken, scope: null })
expect((await rowsWithToken(refreshToken)).docs).toHaveLength(1)
const result = await disconnectGoogleCalendarOAuth()
expect(result.ok).toBe(true)
expect((await rowsWithToken(refreshToken)).docs).toHaveLength(0)
})
})

View file

@ -0,0 +1,270 @@
// @vitest-environment node
//
// C150 — the primary-calendar picker actions. Session resolution is mocked
// (`getCampaignActionContext`), like the sibling action specs; everything else
// — Payload access, the config afterChange hook (D7) and the DB — runs for
// real. The Google client factory is mocked so the listing/validation is
// deterministic: the picker must refuse an id that is not in the connected
// account's LIVE writable list, and choosing a listed one must write
// `calendarId` and reconcile the mirror into it.
import { getPayload, type Payload } from 'payload'
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
vi.mock('@/utilities/campaignActionContext', async (importOriginal) => {
const original = await importOriginal<typeof import('@/utilities/campaignActionContext')>()
return { ...original, getCampaignActionContext: vi.fn() }
})
vi.mock('@/utilities/googleCalendarClient', async (importOriginal) => {
const original = await importOriginal<typeof import('@/utilities/googleCalendarClient')>()
return { ...original, createGoogleCalendarClient: vi.fn() }
})
import {
chooseGoogleCalendar,
listGoogleCalendars,
} from '@/app/(campaign)/campanha/actions/googleCalendarSync'
import config from '@/payload.config'
import { getCampaignActionContext } from '@/utilities/campaignActionContext'
import {
createGoogleCalendarClient,
GoogleCalendarAuthError,
type GoogleCalendarClient,
type GoogleRemoteEvent,
} from '@/utilities/googleCalendarClient'
import {
GOOGLE_CALENDAR_OAUTH_CLIENT_ID_ENV,
GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET_ENV,
} from '@/utilities/googleCalendarOAuth'
import { loadGoogleCalendarSyncConfig } from '@/utilities/googleCalendarSync'
import { installCampaignFixtures } from '../helpers/campaignFixtures'
import { serializeGoogleCalendarSyncSpec } from '../helpers/googleCalendarSyncLock'
serializeGoogleCalendarSyncSpec()
let payload: Payload
const campaignFixtures = installCampaignFixtures({
getPayload: () => payload,
setPayload: (nextPayload) => {
payload = nextPayload
},
})
const mockedGetContext = vi.mocked(getCampaignActionContext)
const mockedCreateClient = vi.mocked(createGoogleCalendarClient)
const OAUTH_ENV_KEYS = [
GOOGLE_CALENDAR_OAUTH_CLIENT_ID_ENV,
GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET_ENV,
] as const
const originalEnv = new Map(OAUTH_ENV_KEYS.map((key) => [key, process.env[key]]))
const setOAuthClientEnv = (): void => {
process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_ID_ENV] = 'test-client-id'
process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET_ENV] = 'test-client-secret'
}
const restoreEnv = (): void => {
for (const key of OAUTH_ENV_KEYS) {
const value = originalEnv.get(key)
if (value === undefined) delete process.env[key]
else process.env[key] = value
}
}
const CALENDAR_A = 'c_campanha_a@group.calendar.google.com'
const CALENDAR_B = 'c_campanha_b@group.calendar.google.com'
type StubClient = {
client: GoogleCalendarClient
listCalendars: ReturnType<typeof vi.fn>
listEvents: ReturnType<typeof vi.fn>
}
const createStubClient = (): StubClient => {
const listCalendars = vi.fn(async () => [
{ id: CALENDAR_A, summary: 'Agenda da Campanha', primary: false },
{ id: CALENDAR_B, summary: 'Meu calendário', primary: true },
])
const listEvents = vi.fn(
async (_calendarId: string, _range: { timeMin: string; timeMax: string }) =>
[] as GoogleRemoteEvent[],
)
const client: GoogleCalendarClient = {
listCalendars,
listEvents,
insertEvent: vi.fn(async () => {}),
updateEvent: vi.fn(async () => {}),
deleteEvent: vi.fn(async () => {}),
watchEvents: vi.fn(async () => ({
id: 'watch-1',
resourceId: 'resource-1',
expiration: null,
})),
stopChannel: vi.fn(async () => {}),
}
return { client, listCalendars, listEvents }
}
describe('C150 — primary calendar picker actions', () => {
beforeAll(async () => {
payload = await getPayload({ config: await config })
})
let ownedConfigId: number | null = null
afterEach(async () => {
restoreEnv()
if (ownedConfigId !== null) {
// Scoped to OUR row: the sibling Google specs share the test DB and
// their own config lifecycle must not be robbed by this file's cleanup.
await payload.delete({
collection: 'googleCalendarSync',
id: ownedConfigId,
overrideAccess: true,
})
ownedConfigId = null
}
mockedGetContext.mockReset()
mockedCreateClient.mockReset()
})
afterAll(() => {
restoreEnv()
})
const installActor = async (role: 'coordinator' | 'advisor'): Promise<void> => {
const actor = await campaignFixtures().createCampaignUser(role)
mockedGetContext.mockResolvedValue({ payload, actor })
}
const createConnectedConfig = async (calendarId: string | null = null) => {
const doc = await payload.create({
collection: 'googleCalendarSync',
data: {
calendarId,
oauthRefreshToken: 'c150-refresh-token',
oauthConnectedAt: new Date().toISOString(),
},
depth: 0,
overrideAccess: true,
})
ownedConfigId = doc.id
return doc
}
it('refuses an advisor on list and choose without touching the row', async () => {
await installActor('advisor')
await createConnectedConfig(CALENDAR_A)
setOAuthClientEnv()
const list = await listGoogleCalendars()
expect(list.ok).toBe(false)
if (list.ok) throw new Error('list must be refused')
expect(list.message).toContain('candidato ou coordenação')
const choose = await chooseGoogleCalendar(CALENDAR_B)
expect(choose.ok).toBe(false)
expect(choose.message).toContain('candidato ou coordenação')
const doc = await loadGoogleCalendarSyncConfig(payload)
expect(doc?.calendarId).toBe(CALENDAR_A)
expect(mockedCreateClient).not.toHaveBeenCalled()
})
it('lists the writable calendars of the connected account for a coordinator', async () => {
await installActor('coordinator')
await createConnectedConfig()
setOAuthClientEnv()
const stub = createStubClient()
mockedCreateClient.mockReturnValue(stub.client)
const result = await listGoogleCalendars()
expect(result.ok).toBe(true)
if (!result.ok) throw new Error('list must succeed')
expect(result.calendars).toEqual([
{ id: CALENDAR_A, summary: 'Agenda da Campanha', primary: false },
{ id: CALENDAR_B, summary: 'Meu calendário', primary: true },
])
expect(mockedCreateClient).toHaveBeenCalledTimes(1)
})
it('records a dead OAuth connection and surfaces it as an auth error', async () => {
await installActor('coordinator')
await createConnectedConfig()
setOAuthClientEnv()
const stub = createStubClient()
stub.listCalendars.mockRejectedValue(
new GoogleCalendarAuthError('A conexão com o Google expirou ou foi revogada. Reconecte.'),
)
mockedCreateClient.mockReturnValue(stub.client)
const result = await listGoogleCalendars()
expect(result.ok).toBe(false)
if (result.ok) throw new Error('list must fail')
expect(result.message).toContain('Reconecte')
const doc = await loadGoogleCalendarSyncConfig(payload)
expect(doc?.oauthErrorAt).toBeTruthy()
expect(doc?.oauthError).toContain('Reconecte')
})
it('rejects an id outside the live writable list without writing', async () => {
await installActor('coordinator')
await createConnectedConfig(CALENDAR_A)
setOAuthClientEnv()
const stub = createStubClient()
stub.listCalendars.mockResolvedValue([
{ id: CALENDAR_A, summary: 'Agenda da Campanha', primary: false },
])
mockedCreateClient.mockReturnValue(stub.client)
const result = await chooseGoogleCalendar(CALENDAR_B)
expect(result.ok).toBe(false)
expect(result.message).toContain('não está mais disponível')
const doc = await loadGoogleCalendarSyncConfig(payload)
expect(doc?.calendarId).toBe(CALENDAR_A)
})
it('writes a listed calendar and reconciles the mirror into it (D7)', async () => {
await installActor('coordinator')
await createConnectedConfig(CALENDAR_A)
setOAuthClientEnv()
const stub = createStubClient()
mockedCreateClient.mockReturnValue(stub.client)
const result = await chooseGoogleCalendar(CALENDAR_B)
expect(result.ok).toBe(true)
expect(result.calendarId).toBe(CALENDAR_B)
expect(result.addLink).toBe(
`https://calendar.google.com/calendar/r?cid=${encodeURIComponent(CALENDAR_B)}`,
)
const doc = await loadGoogleCalendarSyncConfig(payload)
expect(doc?.calendarId).toBe(CALENDAR_B)
// The config afterChange hook (D7) ran a pass against the NEW calendar and
// succeeded with the stub transport.
expect(stub.listEvents).toHaveBeenCalled()
expect(stub.listEvents.mock.calls[0][0]).toBe(CALENDAR_B)
expect(doc?.lastSuccessAt).toBeTruthy()
})
it('keeps the current calendar as a no-op without listing', async () => {
await installActor('coordinator')
await createConnectedConfig(CALENDAR_A)
setOAuthClientEnv()
const stub = createStubClient()
mockedCreateClient.mockReturnValue(stub.client)
const result = await chooseGoogleCalendar(CALENDAR_A)
expect(result.ok).toBe(true)
expect(result.calendarId).toBe(CALENDAR_A)
expect(stub.listCalendars).not.toHaveBeenCalled()
expect(stub.listEvents).not.toHaveBeenCalled()
})
})

View file

@ -38,8 +38,11 @@ import {
import { hookFilledCreateData } from '@/utilities/hookFilledData'
import { installCampaignFixtures } from '../helpers/campaignFixtures'
import { serializeGoogleCalendarSyncSpec } from '../helpers/googleCalendarSyncLock'
import { withGoogleCalendarTestCredential } from '../helpers/googleCalendarTestKey'
serializeGoogleCalendarSyncSpec()
let payload: Payload
const campaignFixtures = installCampaignFixtures({
getPayload: () => payload,
@ -50,6 +53,8 @@ const campaignFixtures = installCampaignFixtures({
/** In-memory Google calendar stub — list/insert/update/delete over an array. */
const createStubClient = (store: GoogleRemoteEvent[] = []): GoogleCalendarClient => ({
// C150 — the picker lists calendars; the engine never calls this.
listCalendars: async () => [],
listEvents: async (_calendarId, range) =>
store.filter((event) => {
const start = event.start?.dateTime ?? event.start?.date ?? ''

View file

@ -11,6 +11,7 @@ import config from '@/payload.config'
import { loadGoogleCalendarSyncConfig } from '@/utilities/googleCalendarSync'
import { installCampaignFixtures } from '../helpers/campaignFixtures'
import { serializeGoogleCalendarSyncSpec } from '../helpers/googleCalendarSyncLock'
import { withGoogleCalendarTestCredential } from '../helpers/googleCalendarTestKey'
/**
@ -30,6 +31,8 @@ vi.mock('@/utilities/campaignActionContext', async (importOriginal) => {
import { getCampaignActionContext, reloadStaffActor } from '@/utilities/campaignActionContext'
serializeGoogleCalendarSyncSpec()
let payload: Payload
const campaignFixtures = installCampaignFixtures({
getPayload: () => payload,

View file

@ -49,6 +49,7 @@ const EDIT_VIEW_MODEL: ActivityFormViewModel = {
description: 'Panfletagem no centro histórico',
deputyPresent: true,
allDay: false,
publicEvent: true,
startAt: '2026-08-07T16:00:00.000Z',
endAt: '2026-08-07T17:00:00.000Z',
municipalityId: 12,
@ -170,6 +171,7 @@ describe('ActivityOverlay — criação (modal central)', () => {
expect(screen.getByText('Demandas')).toBeTruthy()
expect(screen.getByLabelText('Descrição')).toBeTruthy()
expect(screen.getByLabelText('Deputado presente')).toBeTruthy()
expect(screen.getByLabelText('Evento público')).toBeTruthy()
expect(screen.getByRole('combobox', { name: /Organizações apoiadoras/ })).toBeTruthy()
})
@ -218,6 +220,7 @@ describe('ActivityOverlay — criação (modal central)', () => {
target: { value: 'Café da manhã com lideranças' },
})
fireEvent.click(screen.getByLabelText('Deputado presente'))
fireEvent.click(screen.getByLabelText('Evento público'))
fireEvent.change(screen.getByRole('combobox', { name: 'Minuto de Término' }), {
target: { value: '45' },
})
@ -232,6 +235,7 @@ describe('ActivityOverlay — criação (modal central)', () => {
expect(formData.get('locality')).toBe('Centro histórico')
expect(formData.get('description')).toBe('Café da manhã com lideranças')
expect(formData.get('deputyPresent')).toBe('on')
expect(formData.get('publicEvent')).toBe('on')
expect(formData.get('status')).toBe('confirmado')
expect(formData.get('allDay')).toBeNull()
expect(formData.get('id')).toBeNull()
@ -365,6 +369,7 @@ describe('ActivityOverlay — edição (modal central)', () => {
expect((screen.getByLabelText('Descrição') as HTMLInputElement).value).toBe(
'Panfletagem no centro histórico',
)
expect(screen.getByLabelText('Evento público').getAttribute('aria-checked')).toBe('true')
expect((screen.getByLabelText('Título *') as HTMLInputElement).readOnly).toBe(true)
expect(screen.getByText('Comício')).toBeTruthy()
expect(screen.getByRole('link', { name: 'Ver detalhes' }).getAttribute('href')).toBe(
@ -380,6 +385,7 @@ describe('ActivityOverlay — edição (modal central)', () => {
const formData = mocks.updateOverlay.mock.calls[0][0] as FormData
expect(formData.get('id')).toBe('42')
expect(formData.get('title')).toBe('Comício na feira')
expect(formData.get('publicEvent')).toBe('on')
expect(formData.get('startAt')).toBe('2026-08-07T13:00')
expect(formData.get('endAt')).toBe('2026-08-07T14:30')
expect(onSaved).toHaveBeenCalledTimes(1)

View file

@ -1,7 +1,10 @@
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import type { GoogleCalendarSyncActionResult } from '@/app/(campaign)/campanha/actions/googleCalendarSync'
import type {
GoogleCalendarOAuthStartResult,
GoogleCalendarSyncActionResult,
} from '@/app/(campaign)/campanha/actions/googleCalendarSync'
import { AgendaGoogleSyncChrome } from '@/components/campaign/activity/AgendaGoogleSyncChrome'
import {
CampaignPageChromeProvider,
@ -23,6 +26,11 @@ import { stubMatchMedia } from '../helpers/matchMedia'
const stateFor = (status: GoogleCalendarSyncStatus): GoogleCalendarSyncActionResult => ({
ok: true,
canManageConnection: true,
connection: status === 'not-configured' ? 'not-configured' : 'connected',
oauthAvailable: true,
oauthConnectedAt: status === 'not-configured' ? null : '2026-08-01T10:00:00.000Z',
oauthError: null,
status,
calendarId: status === 'not-configured' ? null : 'c_campanha@group.calendar.google.com',
lastSyncedAt: status === 'synced' || status === 'paused' ? '2026-08-11T10:00:00.000Z' : null,
@ -31,7 +39,10 @@ const stateFor = (status: GoogleCalendarSyncStatus): GoogleCalendarSyncActionRes
lastError: status === 'paused' ? 'Google fora do ar (simulado)' : null,
pushChannelExpiresAt: null,
pushChannelError: null,
addLink: status === 'not-configured' ? null : 'https://calendar.google.com/calendar/r?cid=webcal',
addLink:
status === 'not-configured'
? null
: 'https://calendar.google.com/calendar/r?cid=c_campanha%40group.calendar.google.com',
})
const PILL_LABELS: Record<GoogleCalendarSyncStatus, string> = {
@ -43,7 +54,12 @@ const PILL_LABELS: Record<GoogleCalendarSyncStatus, string> = {
const HeaderActionsProbe = () => {
const actions = useCampaignHeaderActions()
return <>{actions['google-calendar-sync'] ?? null}</>
return (
<>
{actions['google-calendar-sync'] ?? null}
{actions['google-calendar-add'] ?? null}
</>
)
}
const renderChrome = ({
@ -51,9 +67,11 @@ const renderChrome = ({
// Status-consistent default: a paused mount's auto-retry resolves back to
// the same state, so the label assertions never race the retry's setState.
onSyncNow = vi.fn(async () => stateFor(status)),
onChooseCalendar,
}: {
status: GoogleCalendarSyncStatus
onSyncNow?: () => Promise<GoogleCalendarSyncActionResult>
onChooseCalendar?: (calendarId: string) => Promise<GoogleCalendarSyncActionResult>
}) =>
render(
<CampaignPageChromeProvider role="coordinator">
@ -62,6 +80,29 @@ const renderChrome = ({
initialState={stateFor(status)}
onSyncNow={onSyncNow}
onSetDisabled={vi.fn(async () => stateFor('disabled'))}
onStartOAuth={vi.fn(
async (): Promise<GoogleCalendarOAuthStartResult> => ({
ok: true,
authorizeUrl: 'https://accounts.google.com/',
}),
)}
onDisconnect={vi.fn(async () => stateFor('not-configured'))}
onListCalendars={vi.fn(async () => ({
ok: true as const,
calendars: [
{
id: 'c_campanha@group.calendar.google.com',
summary: 'Agenda da Campanha',
primary: false,
},
{
id: 'c_pessoal@group.calendar.google.com',
summary: 'Meu calendário',
primary: true,
},
],
}))}
onChooseCalendar={onChooseCalendar ?? vi.fn(async () => stateFor('synced'))}
/>
<HeaderActionsProbe />
</CampaignQuickActionContextProvider>
@ -139,4 +180,67 @@ describe('AgendaGoogleSyncChrome (S14)', () => {
)
expect(onSyncNow).toHaveBeenCalledTimes(1)
})
it('registers the one-click add link when a primary calendar is set (C150)', () => {
renderChrome({ status: 'synced' })
const links = screen.getAllByRole('link', { name: 'Adicionar ao meu Google Calendar' })
expect(links).toHaveLength(2)
for (const link of links) {
expect(link.getAttribute('href')).toBe(
'https://calendar.google.com/calendar/r?cid=c_campanha%40group.calendar.google.com',
)
}
})
it('hides the one-click add link without a primary calendar (C150)', () => {
renderChrome({ status: 'not-configured' })
expect(screen.queryByRole('link', { name: 'Adicionar ao meu Google Calendar' })).toBeNull()
})
it('opens the picker from the sync dialog and returns to it on close (C150)', async () => {
renderChrome({ status: 'synced' })
fireEvent.click(screen.getByRole('button', { name: /^Google:/ }))
const syncDialog = screen.getByRole('dialog', { name: /Agenda da Campanha no Google/ })
fireEvent.click(within(syncDialog).getByRole('button', { name: 'Trocar calendário principal' }))
const picker = await screen.findByRole('dialog', {
name: /Calendário principal da campanha/,
})
expect(within(picker).getByText('Agenda da Campanha')).toBeTruthy()
expect(within(picker).getByText('em uso')).toBeTruthy()
fireEvent.click(within(picker).getByRole('button', { name: 'Cancelar' }))
expect(screen.getByRole('dialog', { name: /Agenda da Campanha no Google/ })).toBeTruthy()
})
it('chooses a calendar and refreshes the one-click link (C150)', async () => {
const chosen: GoogleCalendarSyncActionResult = {
...stateFor('synced'),
calendarId: 'c_pessoal@group.calendar.google.com',
addLink: 'https://calendar.google.com/calendar/r?cid=c_pessoal%40group.calendar.google.com',
}
const onChooseCalendar = vi.fn(async () => chosen)
renderChrome({ status: 'synced', onChooseCalendar })
fireEvent.click(screen.getByRole('button', { name: /^Google:/ }))
fireEvent.click(screen.getByRole('button', { name: 'Trocar calendário principal' }))
const picker = await screen.findByRole('dialog', {
name: /Calendário principal da campanha/,
})
fireEvent.click(within(picker).getByRole('button', { name: /Meu calendário/ }))
fireEvent.click(within(picker).getByRole('button', { name: 'Escolher calendário' }))
await waitFor(() => expect(onChooseCalendar).toHaveBeenCalledTimes(1))
expect(onChooseCalendar).toHaveBeenCalledWith('c_pessoal@group.calendar.google.com')
await waitFor(() =>
expect(
screen
.getAllByRole('link', { name: 'Adicionar ao meu Google Calendar' })[0]
.getAttribute('href'),
).toBe('https://calendar.google.com/calendar/r?cid=c_pessoal%40group.calendar.google.com'),
)
})
})

View file

@ -0,0 +1,312 @@
// @vitest-environment node
import { describe, expect, it } from 'vitest'
import {
buildVodUrl,
clockToSeconds,
matchExcerpt,
normalizeSpeakerName,
normalizeTranscription,
parseEventExcerpts,
parseVodStatus,
selectSpeechEvents,
speechDate,
speechTimeOfDaySeconds,
} from '../../scripts/lib/camaraSpeeches.mjs'
const excerptHtml = (
eventId: number,
{
audioId,
tMs,
speaker,
party,
startTime,
duration,
}: {
audioId: number
tMs: number
speaker: string
party: string
startTime: string
duration: string
},
) => `
<article class="g-chamada">
<a id="link-trecho-video" href="https://www.camara.leg.br/evento-legislativo/${eventId}?a&#x3D;${audioId}&amp;t&#x3D;${tMs}&trechosOrador=&crawl=no" class="chamada__link-trecho" titulo="${speaker}">
<div class="l-chamada-conteudo">
<h4 class="g-chamada__titulo"><b>${speaker}</b></h4>
<span class="chamada__cargo">${party}</span>
<div class="chamada__info-video">
<span class="chamada__info-video-hora">Horário - ${startTime}</span>
<br><span class="chamada__info-video-duracao">Duração - ${duration}</span>
</div>
</div>
</a>
</article>`
describe('normalizeSpeakerName', () => {
it('strips accents, case and punctuation', () => {
expect(normalizeSpeakerName(' Jorge Solla ')).toBe('JORGE SOLLA')
expect(normalizeSpeakerName('José Ação')).toBe('JOSE ACAO')
expect(normalizeSpeakerName('')).toBe('')
})
})
describe('clock helpers', () => {
it('parses HH:MM and HH:MM:SS', () => {
expect(clockToSeconds('17:30')).toBe(63000)
expect(clockToSeconds('09:28:15')).toBe(34095)
expect(clockToSeconds('24:00')).toBeNull()
expect(clockToSeconds('abc')).toBeNull()
})
it('extracts time-of-day and date from a naive datetime', () => {
expect(speechTimeOfDaySeconds('2023-02-07T17:28')).toBe(62880)
expect(speechTimeOfDaySeconds('2023-02-07')).toBeNull()
expect(speechDate('2023-02-07T17:28')).toBe('2023-02-07')
})
})
describe('parseEventExcerpts', () => {
it('reads the speaker anchors with card metadata', () => {
const html = [
excerptHtml(67091, {
audioId: 558641,
tMs: 1675801808560,
speaker: 'JORGE SOLLA',
party: 'DEPUTADO (PT-BA)',
startTime: '17:30',
duration: '0h04\'07"',
}),
excerptHtml(67091, {
audioId: 558641,
tMs: 1675792829010,
speaker: 'POMPEO DE MATTOS',
party: 'DEPUTADO (PDT-RS)',
startTime: '21:22',
duration: '0h04\'03"',
}),
].join('\n')
expect(parseEventExcerpts(html, 67091)).toEqual([
{
audioId: 558641,
tMs: 1675801808560,
speaker: 'JORGE SOLLA',
party: 'DEPUTADO (PT-BA)',
startTime: '17:30',
duration: '0h04\'07"',
},
{
audioId: 558641,
tMs: 1675792829010,
speaker: 'POMPEO DE MATTOS',
party: 'DEPUTADO (PDT-RS)',
startTime: '21:22',
duration: '0h04\'03"',
},
])
})
it('returns [] when the page has no excerpt anchors or the event id differs', () => {
const html = excerptHtml(111, {
audioId: 5,
tMs: 1000,
speaker: 'X',
party: 'Y',
startTime: '10:00',
duration: '0h01\'00"',
})
expect(parseEventExcerpts(html, 67091)).toEqual([])
expect(parseEventExcerpts('', 67091)).toEqual([])
})
it('degrades card metadata to null when the spans are missing', () => {
const html =
'<a id="link-trecho-video" href="https://www.camara.leg.br/evento-legislativo/67091?a&#x3D;5&amp;t&#x3D;1000&trechosOrador=&crawl=no" class="chamada__link-trecho" titulo="JORGE SOLLA">x</a>'
expect(parseEventExcerpts(html, 67091)).toEqual([
{
audioId: 5,
tMs: 1000,
speaker: 'JORGE SOLLA',
party: null,
startTime: null,
duration: null,
},
])
})
})
describe('buildVodUrl', () => {
it('targets the async VOD endpoint with audio id and excerpt epoch', () => {
expect(buildVodUrl(67091, 558641, 1675801808560)).toBe(
'https://www.camara.leg.br/evento-legislativo/67091/video-sob-demanda?idAudio=558641&trecho=1675801808560',
)
})
})
describe('parseVodStatus', () => {
it('normalizes the PRONTO payload', () => {
expect(
parseVodStatus({
estado: 'PRONTO',
video: {
titulo: 'Jorge Solla',
subtitulo: 'DEPUTADO (PT-BA)',
duracao: '0:04:07',
horario: "17h30'08''",
linkParaDownload: 'https://vod.camara.leg.br/vod/download?p=abc.mp4',
linkParaReproducao: 'https://vod.camara.leg.br/videos/abc.mp4',
},
}),
).toEqual({
state: 'PRONTO',
video: {
title: 'Jorge Solla',
subtitle: 'DEPUTADO (PT-BA)',
duration: '0:04:07',
clock: "17h30'08''",
downloadUrl: 'https://vod.camara.leg.br/vod/download?p=abc.mp4',
playbackUrl: 'https://vod.camara.leg.br/videos/abc.mp4',
},
})
})
it('handles GERANDO/INDISPONIVEL and malformed input', () => {
expect(parseVodStatus({ estado: 'GERANDO', video: null })).toEqual({
state: 'GERANDO',
video: null,
})
expect(parseVodStatus({ estado: 'INDISPONIVEL', video: null })).toEqual({
state: 'INDISPONIVEL',
video: null,
})
expect(parseVodStatus(null)).toEqual({ state: 'DESCONHECIDO', video: null })
})
})
describe('selectSpeechEvents', () => {
const events: Array<{ id: number; dataHoraInicio: string }> = [
{ id: 1, dataHoraInicio: '2023-02-07T15:00' },
{ id: 2, dataHoraInicio: '2023-02-07T20:00' },
{ id: 3, dataHoraInicio: '2023-02-08T15:00' },
]
it('keeps only the speech date and sorts nearest-first', () => {
const selected = selectSpeechEvents(events, '2023-02-07T17:28')
expect(selected.map((e) => e.id)).toEqual([1, 2])
})
it('is empty when nothing matches the date', () => {
expect(selectSpeechEvents(events, '2020-01-01T10:00')).toEqual([])
})
})
describe('matchExcerpt', () => {
const excerpts = [
{
audioId: 1,
tMs: 100,
speaker: 'JORGE SOLLA',
party: 'DEPUTADO (PT-BA)',
startTime: '09:28',
duration: null,
},
{
audioId: 2,
tMs: 200,
speaker: 'JORGE SOLLA',
party: 'DEPUTADO (PT-BA)',
startTime: '17:30',
duration: null,
},
{
audioId: 3,
tMs: 300,
speaker: 'OUTRO',
party: null,
startTime: '09:00',
duration: null,
},
]
it('picks the speaker excerpt nearest the speech time (accent-insensitive)', () => {
expect(matchExcerpt(excerpts, '2016-03-10T09:28', 'Jorge Solla')?.audioId).toBe(1)
expect(matchExcerpt(excerpts, '2023-02-07T17:28', 'Jorge Solla')?.audioId).toBe(2)
})
it('returns null when the speaker is absent or empty', () => {
expect(matchExcerpt(excerpts, '2016-03-10T09:28', 'Fulano de Tal')).toBeNull()
expect(matchExcerpt(excerpts, '2016-03-10T09:28', '')).toBeNull()
})
it('prefers an excerpt with a clock over one without', () => {
const withMissing = [
{ audioId: 9, tMs: 1, speaker: 'JORGE SOLLA', party: null, startTime: null, duration: null },
...excerpts,
]
expect(matchExcerpt(withMissing, '2016-03-10T09:28', 'Jorge Solla')?.audioId).toBe(1)
})
})
describe('normalizeTranscription', () => {
it('accepts the OpenAI-compat segments shape', () => {
expect(
normalizeTranscription({
text: 'olá mundo',
language: 'pt',
duration: 12.5,
segments: [
{ start: 0, end: 2.7, text: ' olá' },
{ start: 2.91, end: 4.1, text: ' mundo' },
],
}),
).toEqual({
text: 'olá mundo',
language: 'pt',
duration: 12.5,
segments: [
{ start: 0, end: 2.7, text: 'olá' },
{ start: 2.91, end: 4.1, text: 'mundo' },
],
})
})
it('accepts the native chunks shape and drops invalid entries', () => {
const result = normalizeTranscription({
chunks: [
{ timestamp: [0, 1.5], text: 'a' },
{ timestamp: [null, null], text: 'lixo' },
{ timestamp: [2, 3], text: '' },
],
language: 'pt',
})
expect(result.segments).toEqual([{ start: 0, end: 1.5, text: 'a' }])
expect(result.text).toBe('a')
})
it('degrades on malformed input', () => {
expect(normalizeTranscription(null)).toEqual({
text: '',
language: null,
duration: null,
segments: [],
})
})
it('keeps a missing duration as null instead of 0', () => {
expect(normalizeTranscription({ duration: null, segments: [] }).duration).toBeNull()
expect(normalizeTranscription({ duration: '', segments: [] }).duration).toBeNull()
expect(normalizeTranscription({ duration: 12, segments: [] }).duration).toBe(12)
})
it('prefers segments over chunks when both are present', () => {
const result = normalizeTranscription({
segments: [{ start: 0, end: 1, text: 'seg' }],
chunks: [{ timestamp: [2, 3], text: 'chunk' }],
})
expect(result.segments).toEqual([{ start: 0, end: 1, text: 'seg' }])
})
})

View file

@ -35,6 +35,17 @@ vi.mock('@/utilities/campaignHomeTracking', () => ({
getCampaignHomeMetaPixelId: async () => null,
}))
// S14 — the card section renders the client studio island (next/font local
// face + matchMedia + canvas); its behavior is e2e-covered, so the unit
// skeleton mocks both the face module and the island.
vi.mock('@/app/(frontend)/fonts', () => ({
brexterBold: { variable: 'font-brexter-mock', style: { fontFamily: 'Brexter' } },
}))
vi.mock('@/components/cards/CardsStudio', () => ({
CardsStudio: () => null,
}))
afterEach(cleanup)
describe('Campaign home', () => {
@ -51,6 +62,7 @@ describe('Campaign home', () => {
name: /Junto com o trabalhador e do lado de quem mais precisa, sempre/i,
}),
).toBeTruthy()
expect(screen.getByRole('heading', { name: /Mostre que você está com Solla/i })).toBeTruthy()
expect(screen.getByRole('heading', { name: /Receba as novidades da campanha/i })).toBeTruthy()
expect(screen.getByText(/CNPJ: 68\.430\.467\/0001-05/)).toBeTruthy()
})

View file

@ -1,12 +1,6 @@
import { describe, expect, it } from 'vitest'
import {
CARD_MODELS,
NAME_CARD_SLOT,
cardModelHref,
getCardModel,
isCardModelId,
} from '@/lib/cardModels'
import { CARD_MODELS, NAME_CARD_SLOT, getCardModel, isCardModelId } from '@/lib/cardModels'
describe('card model catalog (S13)', () => {
it('exposes the three shipped models with unique ids', () => {
@ -56,7 +50,7 @@ describe('card model catalog (S13)', () => {
it('guards the name slot geometry measured from the filled master', () => {
expect(NAME_CARD_SLOT).toMatchObject({
centerX: 570,
leftX: 213,
capTop: 430,
capHeight: 106,
maxInkWidth: 714,
@ -71,8 +65,4 @@ describe('card model catalog (S13)', () => {
expect(isCardModelId(['perfil-quadrado'])).toBe(false)
expect(isCardModelId(undefined)).toBe(false)
})
it('builds the deep-link used by the home tiles', () => {
expect(cardModelHref('perfil-quadrado')).toBe('/cards?model=perfil-quadrado')
})
})

View file

@ -1,9 +1,11 @@
import { describe, expect, it } from 'vitest'
import { NAME_CARD_SLOT, getCardModel, type CardRect } from '@/lib/cardModels'
import { fitCardName } from '@/lib/cardNameFit'
import { centerCardPhotoTransform, type CardPhotoSize } from '@/lib/cardPhotoTransform'
import {
createCardMeasure,
drawCardName,
renderNameCard,
renderPhotoCard,
type CardDrawContext,
@ -49,7 +51,7 @@ const nameModel = getCardModel('eu-sou-solla')!
const squareModel = getCardModel('perfil-quadrado')!
describe('renderNameCard', () => {
it('draws the master base first and then the centered name', () => {
it('draws the master base first and then the name on the left border', () => {
const { ctx, drawCalls, textCalls } = createFakeContext()
const image = { id: 'base' } as unknown as CanvasImageSource
const fit = renderNameCard(ctx, nameModel, {
@ -63,10 +65,10 @@ describe('renderNameCard', () => {
expect(drawCalls).toEqual([{ image, dx: 0, dy: 0, dw: 1080, dh: 1440 }])
expect(textCalls).toHaveLength(1)
expect(textCalls[0]!.text).toBe('JOÃO')
expect(textCalls[0]!.x).toBe(NAME_CARD_SLOT.centerX)
expect(textCalls[0]!.x).toBe(NAME_CARD_SLOT.leftX)
expect(textCalls[0]!.y).toBeCloseTo(NAME_CARD_SLOT.capTop + NAME_CARD_SLOT.capHeight, 5)
expect(ctx.fillStyle).toBe(NAME_CARD_SLOT.fill)
expect(ctx.textAlign).toBe('center')
expect(ctx.textAlign).toBe('left')
})
it('wraps long names into two lines with baselines inside the free band', () => {
@ -99,6 +101,38 @@ describe('renderNameCard', () => {
})
})
describe('drawCardName', () => {
it('draws only the fitted name (no base) on the left border', () => {
const { ctx, drawCalls, textCalls } = createFakeContext()
const fit = fitCardName('João', createCardMeasure(ctx, 'Brexter'))
expect(fit.ok).toBe(true)
if (!fit.ok) return
drawCardName(ctx, { fit, fontFamily: 'Brexter' })
expect(drawCalls).toHaveLength(0)
expect(textCalls).toEqual([
{ text: 'JOÃO', x: NAME_CARD_SLOT.leftX, y: NAME_CARD_SLOT.capTop + fit.capHeight },
])
expect(ctx.textAlign).toBe('left')
expect(ctx.fillStyle).toBe(NAME_CARD_SLOT.fill)
})
it('left-aligns both wrapped lines inside the free band', () => {
const { ctx, textCalls } = createFakeContext()
const fit = fitCardName('Jorge Solla da Bahia', createCardMeasure(ctx, 'Brexter'))
expect(fit.ok).toBe(true)
if (!fit.ok) return
drawCardName(ctx, { fit, fontFamily: 'Brexter' })
expect(textCalls.map((call) => call.text)).toEqual(['JORGE SOLLA', 'DA BAHIA'])
expect(textCalls.every((call) => call.x === NAME_CARD_SLOT.leftX)).toBe(true)
expect(textCalls[0]!.y).toBeLessThan(textCalls[1]!.y)
expect(textCalls[1]!.y).toBeLessThanOrEqual(NAME_CARD_SLOT.maxBlockBottom)
})
})
describe('renderPhotoCard', () => {
it('draws the photo full-bleed under the official overlay', () => {
const { ctx, drawCalls } = createFakeContext()

View file

@ -121,6 +121,34 @@ describe('ciSkipInvariants', () => {
expect(ciPr).not.toContain('ci-classify-production.mjs')
})
it('deploy.yml chains verify → deploy-staging → deploy-production with separate environments (OPS103)', () => {
// One dispatch, one verify, two separately approved deploys. The gate is
// the GitHub Environment (reviewer on production, configured in the repo —
// not in this YAML); the chain is needs-based so a red staging fail-closes
// production. Comments are stripped first: the header prose also mentions
// these keys, and it must never satisfy the pin.
const raw = readFileSync(join(repoRoot, '.github/workflows/deploy.yml'), 'utf8')
const deploy = raw
.split('\n')
.filter((line) => !line.trimStart().startsWith('#'))
.join('\n')
expect(deploy).toContain(' deploy-staging:')
expect(deploy).toContain(' deploy-production:')
expect(deploy).toContain(' environment: staging')
expect(deploy).toContain(' environment: production')
expect(deploy).toContain(' needs: [deploy-staging]')
expect(deploy).toContain(' TEQO_ENV: staging')
expect(deploy).toContain(' TEQO_ENV: production')
expect(deploy).toContain("github.ref == 'refs/heads/main'")
expect(deploy).toContain("needs.deploy-staging.result == 'success'")
// Deploys share the homeserver compose/workspace: serialize them across
// runs without cancelling an in-flight deploy, and queue (never cancel) a
// previously pending one (`queue: max`).
expect(deploy).toContain(' group: deploy-homeserver')
expect(deploy).toContain(' cancel-in-progress: false')
expect(deploy).toContain(' queue: max')
})
it('every campaign domain dir is covered by the e2e affected manifest', () => {
const componentDirs = readdirSync(join(repoRoot, 'src/components/campaign'), {
withFileTypes: true,

View file

@ -417,6 +417,9 @@ describe('src/utilities top-level is pinned', () => {
// C114 — Google Calendar mirror: activity/config hooks (separate module so
// the engine is mockable at the import boundary in tests).
'googleCalendarSyncHooks.ts',
// C149 — Google Calendar OAuth: env client pair, signed single-use state
// cookie and the authorization-code exchange (server-only).
'googleCalendarOAuth.ts',
'campaignAuth.ts',
'campaignBiometricsPrompt.ts',
'campaignColumnVisibilityCookie.ts',

View file

@ -16,17 +16,24 @@ describe('scripts/deploy-homeserver.sh (OPS53 deploy pipeline)', () => {
expect(() => execFileSync('bash', ['-n', scriptPath], { stdio: 'pipe' })).not.toThrow()
})
it('guards against stale runs: only the current main HEAD deploys', () => {
expect(script).toContain('git ls-remote')
expect(script).toContain('refs/heads/main')
expect(script).toContain('stale run')
it('deploys the dispatched SHA to the end even when main advanced during verify (OPS102)', () => {
// OPS53's stale-run guard assumed an automatic deploy; since OPS71 the
// dispatch is a deliberate operator act — the run must complete with the
// SHA it started with. Reintroducing a main-HEAD comparison must fail here.
expect(script).not.toContain('stale run')
expect(script).not.toContain('git ls-remote')
expect(script).not.toContain('refs/heads/main')
})
it('fails the run when main advanced during verify — no silent false success', () => {
// The skip used to `exit 0`, so GitHub reported a green deploy that never
// happened while prod stayed on an older image (2026-09-12 incident).
expect(script).not.toMatch(/say "stale run/)
expect(script.match(/fatal "stale run/g) ?? []).toHaveLength(2)
it('never exits green without deploying: the only early exit 0 is "already deployed"', () => {
// #953: the stale-run skip used to `exit 0` — a green deploy that never
// happened while prod stayed on an older image.
expect(script.match(/\bexit 0\b/g) ?? []).toHaveLength(1)
})
it('keeps flock serialization after removing the HEAD guards (OPS102)', () => {
expect(script).toContain('exec 9>"$DEPLOY_LOCK"')
expect(script).toContain('flock -w 3600 9')
})
it('skips idempotently when the running container already runs the SHA (OPS65)', () => {
@ -43,14 +50,14 @@ describe('scripts/deploy-homeserver.sh (OPS53 deploy pipeline)', () => {
expect(script).toContain('id=payload_secret,env=PAYLOAD_SECRET')
})
it('reaches the prod DB from the build (loopback proxy on the compose network)', () => {
it('reaches the env DB from the build (loopback proxy on the compose network)', () => {
// BuildKit rejects `--network <bridge>`; the build uses --network host and
// a socat proxy (on stack_default, published on the host loopback) with a
// rewritten DATABASE_URL.
// rewritten DATABASE_URL. OPS103 parameterized the proxy per environment.
expect(script).toContain('--network host')
expect(script).toContain('teqo-1313-build-proxy')
expect(script).toContain('$TEQO_BUILD_PROXY')
expect(script).toContain('TCP:postgres:5432')
expect(script).toContain('127.0.0.1:5433')
expect(script).toContain('$TEQO_BUILD_PROXY_PORT')
})
it('applies migrations BEFORE the runner build — static generation reads the new schema (OPS66)', () => {
@ -59,14 +66,16 @@ describe('scripts/deploy-homeserver.sh (OPS53 deploy pipeline)', () => {
// failed again). The migrator stage never runs `next build`, so it must
// build first; the compose swap feeds the new migrator image to the
// maintenance service; then migrate runs; only then the runner builds
// against the migrated DB.
// against the migrated DB. OPS103 anchors the markers on the invocation
// itself (the raw `teqo-1313-migrate` literal now appears first in the
// environment map at the top of the script).
const migratorBuildIndex = script.indexOf('build_image migrator')
const swapIndex = script.indexOf('compose swap')
const migrateIndex = script.indexOf('teqo-1313-migrate')
const migrateIndex = script.indexOf('--profile maintenance run --rm')
const runnerBuildIndex = script.indexOf('build_image runner')
// The rollback helper also contains a `compose up -d` (before the migrate
// step); the REAL rollout is the last occurrence.
const upIndex = script.lastIndexOf('docker compose up -d teqo-1313')
const upIndex = script.lastIndexOf('docker compose up -d "$TEQO_CONTAINER"')
for (const i of [migratorBuildIndex, swapIndex, migrateIndex, runnerBuildIndex, upIndex]) {
expect(i).toBeGreaterThan(-1)
}
@ -147,3 +156,84 @@ describe('scripts/deploy-homeserver.sh (OPS53 deploy pipeline)', () => {
expect(builderStage).not.toContain('pnpm exec payload generate:importmap')
})
})
describe('scripts/deploy-homeserver.sh environment parameterization (OPS103)', () => {
const productionBlock = script.slice(
script.indexOf(' production)'),
script.indexOf(' staging)'),
)
const stagingBlock = script.slice(script.indexOf(' staging)'), script.indexOf(' *)'))
const fallbackBlock = script.slice(script.indexOf(' *)'), script.indexOf('esac'))
it('defaults to production with the exact pre-OPS103 identities', () => {
// The canonical invocation `bash scripts/deploy-homeserver.sh <sha>` (no
// env) must keep deploying production with the same names and ports as
// before — a drift here is a production regression.
expect(script).toContain('TEQO_ENV="${TEQO_ENV:-production}"')
expect(productionBlock).toContain('TEQO_CONTAINER=teqo-1313')
expect(productionBlock).toContain('TEQO_MIGRATE_SERVICE=teqo-1313-migrate')
expect(productionBlock).toContain('teqo-1313.env')
expect(productionBlock).toContain('TEQO_IMAGE_REPO=teqo-1313')
expect(productionBlock).toContain('TEQO_BUILD_PROXY=teqo-1313-build-proxy')
expect(productionBlock).toContain('TEQO_BUILD_PROXY_PORT=5433')
expect(productionBlock).toContain('TEQO_SMOKE_BASE=http://localhost:1313')
})
it('maps the staging identities (container, service, env file, ports)', () => {
expect(stagingBlock).toContain('TEQO_CONTAINER=teqo-staging')
expect(stagingBlock).toContain('TEQO_MIGRATE_SERVICE=teqo-staging-migrate')
expect(stagingBlock).toContain('teqo-staging.env')
expect(stagingBlock).toContain('TEQO_IMAGE_REPO=teqo-staging')
expect(stagingBlock).toContain('TEQO_BUILD_PROXY=teqo-staging-build-proxy')
expect(stagingBlock).toContain('TEQO_BUILD_PROXY_PORT=5434')
expect(stagingBlock).toContain('TEQO_SMOKE_BASE=http://localhost:1314')
})
it('serializes both environments on ONE shared lock (compose/workspace are shared)', () => {
// Per-env locks would let staging and production build/swap concurrently
// on the same workspace and compose file (the workflow concurrency does
// not cover manual invocations on the host).
expect(script).toContain('DEPLOY_LOCK="${DEPLOY_LOCK:-/tmp/teqo-deploy.lock}"')
expect(script).not.toContain('/tmp/teqo-1313-deploy.lock')
expect(script).not.toContain('/tmp/teqo-staging-deploy.lock')
})
it('fails closed on an unknown TEQO_ENV (case fallback, before any deploy step)', () => {
expect(fallbackBlock).toContain('fatal "unknown TEQO_ENV')
expect(script.indexOf('fatal "unknown TEQO_ENV')).toBeLessThan(script.indexOf('exec 9>'))
})
it('freezes the derived env map against env-file retargeting (readonly)', () => {
expect(script).toContain(
'readonly TEQO_CONTAINER TEQO_MIGRATE_SERVICE TEQO_ENV_FILE TEQO_IMAGE_REPO',
)
expect(script).toContain(
'readonly TEQO_BUILD_PROXY TEQO_BUILD_PROXY_PORT TEQO_SMOKE_BASE DEPLOY_LOCK',
)
// The env files are sourced after the map; a readonly assignment error
// aborts the deploy (fail-closed) instead of silently switching targets.
const readonlyIndex = script.indexOf('readonly TEQO_CONTAINER')
const sourceIndex = script.indexOf('. "$TEQO_ENV_FILE"')
expect(readonlyIndex).toBeGreaterThan(-1)
expect(readonlyIndex).toBeLessThan(sourceIndex)
})
it('parameterizes image refs, migrate service, rollout, healthcheck and cleanup', () => {
expect(script).toContain('$TEQO_REGISTRY/$TEQO_IMAGE_REPO-migrator:$SHA')
expect(script).toContain('$TEQO_REGISTRY/$TEQO_IMAGE_REPO:$SHA')
expect(script).toContain('run --rm "$TEQO_MIGRATE_SERVICE"')
expect(script).toContain('docker compose up -d "$TEQO_CONTAINER"')
expect(script).toContain('\'{{.State.Health.Status}}\' "$TEQO_CONTAINER"')
expect(script).toContain('grep -E "^($TEQO_REGISTRY/)?$TEQO_IMAGE_REPO(-migrator)?:"')
})
it('anchors the revision-label sed to the service block (never stamps the other env)', () => {
// A bare global replace would stamp THIS env's SHA onto the other
// environment's service, and the "already deployed" guard would read a
// lying revision. The range is re-read afterwards to fail closed when the
// service block has no label (a silent no-op would disable the guard).
expect(script).toContain('label_range="/^ $TEQO_CONTAINER:/,/^ [A-Za-z0-9_.-]+:/"')
expect(script).not.toContain('-e "s|org.opencontainers.image.revision')
expect(script).toContain('grep -q "org.opencontainers.image.revision: $SHA"')
})
})

View file

@ -8,12 +8,14 @@ import {
createGoogleCalendarClient,
GOOGLE_CALENDAR_SCOPE,
GoogleCalendarApiError,
GoogleCalendarAuthError,
type FetchLike,
type GoogleCalendarCredentials,
type GoogleCalendarAuth,
type GoogleCalendarServiceAccountCredentials,
} from '@/utilities/googleCalendarClient'
describe('buildServiceAccountAssertion', () => {
let credentials: GoogleCalendarCredentials
let credentials: GoogleCalendarServiceAccountCredentials
let publicKeyPem: string
beforeAll(async () => {
@ -38,7 +40,8 @@ describe('buildServiceAccountAssertion', () => {
})
describe('createGoogleCalendarClient', () => {
let credentials: GoogleCalendarCredentials
let credentials: GoogleCalendarServiceAccountCredentials
let serviceAccountAuth: GoogleCalendarAuth
beforeAll(async () => {
// The token endpoint is stubbed, but the client still SIGNS the JWT
@ -48,8 +51,18 @@ describe('createGoogleCalendarClient', () => {
clientEmail: 'teqo-sa@projeto.iam.gserviceaccount.com',
privateKey: await exportPKCS8(privateKey),
}
serviceAccountAuth = { kind: 'service-account', credentials }
})
const oauthAuth: GoogleCalendarAuth = {
kind: 'oauth',
credentials: {
clientId: 'client-id.apps.googleusercontent.com',
clientSecret: 'client-secret',
refreshToken: 'refresh-token',
},
}
const calendarId = 'c_abc@group.calendar.google.com'
/** Minimal fake transport: token endpoint + calendar REST in memory. */
@ -112,7 +125,7 @@ describe('createGoogleCalendarClient', () => {
it('inserts with the deterministic id, bearer auth and JSON body', async () => {
const { fetchImpl, calls, events } = stubTransport()
const client = createGoogleCalendarClient(credentials, fetchImpl)
const client = createGoogleCalendarClient(serviceAccountAuth, fetchImpl)
await client.insertEvent(calendarId, { id: 'teqo1a', summary: 'S', description: 'D' })
@ -125,7 +138,7 @@ describe('createGoogleCalendarClient', () => {
it('lists with the window params and pagination', async () => {
const { fetchImpl, calls } = stubTransport()
const client = createGoogleCalendarClient(credentials, fetchImpl)
const client = createGoogleCalendarClient(serviceAccountAuth, fetchImpl)
await client.listEvents(calendarId, {
timeMin: '2026-01-01T00:00:00Z',
@ -138,6 +151,69 @@ describe('createGoogleCalendarClient', () => {
expect(listCall?.url).toContain('maxResults=2500')
})
it('lists writable calendars with pagination, hiding deleted and falling back the summary (C150)', async () => {
const pages: Record<string, { items: Array<Record<string, unknown>>; nextPageToken?: string }> =
{
'': {
items: [
{ id: 'primary-id', summary: 'Conta da campanha', primary: true, accessRole: 'owner' },
{ id: 'campaign-id', summary: 'Agenda da Campanha', accessRole: 'writer' },
{ id: 'no-summary-id' },
{ id: 'deleted-id', summary: 'Antiga', deleted: true },
],
nextPageToken: 'page-2',
},
'page-2': {
items: [{ id: 'second-page-id', summary: 'Segunda página' }],
},
}
const calls: string[] = []
const fetchImpl: FetchLike = (async (input: RequestInfo | URL) => {
const url = String(input)
if (url === 'https://oauth2.googleapis.com/token') {
return new Response(JSON.stringify({ access_token: 'token-1', expires_in: 3600 }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}
calls.push(url)
const pageToken = new URL(url).searchParams.get('pageToken') ?? ''
return new Response(JSON.stringify(pages[pageToken]), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}) as FetchLike
const client = createGoogleCalendarClient(oauthAuth, fetchImpl)
const calendars = await client.listCalendars()
expect(calendars).toEqual([
{ id: 'primary-id', summary: 'Conta da campanha', primary: true },
{ id: 'campaign-id', summary: 'Agenda da Campanha', primary: false },
{ id: 'no-summary-id', summary: 'no-summary-id', primary: false },
{ id: 'second-page-id', summary: 'Segunda página', primary: false },
])
expect(calls).toHaveLength(2)
const first = new URL(calls[0])
expect(first.pathname).toBe('/calendar/v3/users/me/calendarList')
expect(first.searchParams.get('minAccessRole')).toBe('writer')
expect(first.searchParams.get('showHidden')).toBe('true')
expect(first.searchParams.get('maxResults')).toBe('250')
expect(first.searchParams.get('fields')).toBe('items(id,summary,primary,deleted),nextPageToken')
expect(new URL(calls[1]).searchParams.get('pageToken')).toBe('page-2')
})
it('maps invalid_grant on the calendar list to GoogleCalendarAuthError (C150)', async () => {
const fetchImpl: FetchLike = (async () =>
new Response(JSON.stringify({ error: 'invalid_grant' }), {
status: 400,
headers: { 'Content-Type': 'application/json' },
})) as FetchLike
const client = createGoogleCalendarClient(oauthAuth, fetchImpl)
await expect(client.listCalendars()).rejects.toBeInstanceOf(GoogleCalendarAuthError)
})
it('re-mints the token once on a 401 and retries the call', async () => {
let calendarCalls = 0
const fetchImpl: FetchLike = (async (input: RequestInfo | URL, _init?: RequestInit) => {
@ -158,7 +234,7 @@ describe('createGoogleCalendarClient', () => {
})
}) as FetchLike
const client = createGoogleCalendarClient(credentials, fetchImpl)
const client = createGoogleCalendarClient(serviceAccountAuth, fetchImpl)
const events = await client.listEvents(calendarId, {
timeMin: '2026-01-01T00:00:00Z',
timeMax: '2026-12-31T00:00:00Z',
@ -177,9 +253,79 @@ describe('createGoogleCalendarClient', () => {
return new Response('ok', { status: 200 })
}) as FetchLike
const client = createGoogleCalendarClient(credentials, fetchImpl)
const client = createGoogleCalendarClient(serviceAccountAuth, fetchImpl)
await expect(
client.listEvents(calendarId, { timeMin: 'a', timeMax: 'b' }),
).rejects.toBeInstanceOf(GoogleCalendarApiError)
})
it('mints an access token with the OAuth refresh grant (C149)', async () => {
const { fetchImpl, calls } = stubTransport()
const client = createGoogleCalendarClient(oauthAuth, fetchImpl)
await client.listEvents(calendarId, { timeMin: 'a', timeMax: 'b' })
const tokenCall = calls.find((call) => call.url === 'https://oauth2.googleapis.com/token')
const params = new URLSearchParams(tokenCall?.body)
expect(params.get('grant_type')).toBe('refresh_token')
expect(params.get('refresh_token')).toBe('refresh-token')
expect(params.get('client_id')).toBe('client-id.apps.googleusercontent.com')
expect(params.get('client_secret')).toBe('client-secret')
const listCall = calls.find((call) => call.method === 'GET')
expect(listCall?.auth).toBe('Bearer token-1')
})
it('maps invalid_grant to GoogleCalendarAuthError (reconnectable)', async () => {
const fetchImpl: FetchLike = (async () =>
new Response(JSON.stringify({ error: 'invalid_grant' }), {
status: 400,
headers: { 'Content-Type': 'application/json' },
})) as FetchLike
const client = createGoogleCalendarClient(oauthAuth, fetchImpl)
await expect(
client.listEvents(calendarId, { timeMin: 'a', timeMax: 'b' }),
).rejects.toBeInstanceOf(GoogleCalendarAuthError)
})
it('keeps invalid_client as an API error (reconnect would not fix it)', async () => {
const fetchImpl: FetchLike = (async () =>
new Response(JSON.stringify({ error: 'invalid_client' }), {
status: 401,
headers: { 'Content-Type': 'application/json' },
})) as FetchLike
const client = createGoogleCalendarClient(oauthAuth, fetchImpl)
await expect(
client.listEvents(calendarId, { timeMin: 'a', timeMax: 'b' }),
).rejects.toBeInstanceOf(GoogleCalendarApiError)
})
it('re-mints the OAuth token once on a 401 and retries the call', async () => {
let calendarCalls = 0
let tokenRequests = 0
const fetchImpl: FetchLike = (async (input: RequestInfo | URL) => {
const url = String(input)
if (url === 'https://oauth2.googleapis.com/token') {
tokenRequests += 1
return new Response(
JSON.stringify({ access_token: `oauth-token-${tokenRequests}`, expires_in: 3600 }),
{ status: 200, headers: { 'Content-Type': 'application/json' } },
)
}
calendarCalls += 1
if (calendarCalls === 1) return new Response('unauthorized', { status: 401 })
return new Response(JSON.stringify({ items: [] }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}) as FetchLike
const client = createGoogleCalendarClient(oauthAuth, fetchImpl)
const events = await client.listEvents(calendarId, { timeMin: 'a', timeMax: 'b' })
expect(events).toEqual([])
expect(calendarCalls).toBe(2)
expect(tokenRequests).toBe(2)
})
})

View file

@ -3,22 +3,15 @@ import { describe, expect, it } from 'vitest'
import {
buildGoogleCalendarAddLink,
buildGoogleCalendarPublicIcalUrl,
buildGoogleCalendarWebcalUrl,
} from '@/lib/googleCalendarLink'
describe('googleCalendarLink', () => {
const calendarId = 'c_abc123@group.calendar.google.com'
it('builds the webcal subscription URL Apple/Outlook consume', () => {
expect(buildGoogleCalendarWebcalUrl(calendarId)).toBe(
'webcal://calendar.google.com/calendar/ical/c_abc123%40group.calendar.google.com/public/basic.ics',
)
})
it('builds the Google add-by-URL link with the webcal URL as cid', () => {
it('builds the one-click Google add link with the calendarId as cid (C150)', () => {
const link = buildGoogleCalendarAddLink(calendarId)
expect(link).toBe(
'https://calendar.google.com/calendar/r?cid=webcal%3A%2F%2Fcalendar.google.com%2Fcalendar%2Fical%2Fc_abc123%2540group.calendar.google.com%2Fpublic%2Fbasic.ics',
'https://calendar.google.com/calendar/r?cid=c_abc123%40group.calendar.google.com',
)
})

View file

@ -0,0 +1,195 @@
// @vitest-environment node
import { afterEach, describe, expect, it } from 'vitest'
import {
buildGoogleCalendarOAuthAuthorizeUrl,
GOOGLE_CALENDAR_OAUTH_CALLBACK_PATH,
GOOGLE_CALENDAR_OAUTH_SCOPES,
} from '@/lib/googleCalendarOAuth'
import {
exchangeGoogleCalendarOAuthCode,
GOOGLE_CALENDAR_OAUTH_CLIENT_ID_ENV,
GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET_ENV,
GoogleCalendarOAuthError,
readGoogleCalendarOAuthCredentials,
} from '@/utilities/googleCalendarOAuth'
const CREDENTIALS = {
clientId: 'client-id.apps.googleusercontent.com',
clientSecret: 'client-secret',
}
const REDIRECT_URI = `https://jorgesolla1313.com.br${GOOGLE_CALENDAR_OAUTH_CALLBACK_PATH}`
describe('buildGoogleCalendarOAuthAuthorizeUrl', () => {
it('pins the two literal minimum scopes (C149)', () => {
expect([...GOOGLE_CALENDAR_OAUTH_SCOPES]).toEqual([
'https://www.googleapis.com/auth/calendar.events',
'https://www.googleapis.com/auth/calendar.calendarlist.readonly',
])
})
it('builds the consent URL with offline access, forced consent and the state', () => {
const url = new URL(
buildGoogleCalendarOAuthAuthorizeUrl({
clientId: CREDENTIALS.clientId,
redirectUri: REDIRECT_URI,
state: 'state-123',
}),
)
expect(`${url.origin}${url.pathname}`).toBe('https://accounts.google.com/o/oauth2/v2/auth')
expect(url.searchParams.get('client_id')).toBe(CREDENTIALS.clientId)
expect(url.searchParams.get('redirect_uri')).toBe(REDIRECT_URI)
expect(url.searchParams.get('response_type')).toBe('code')
expect(url.searchParams.get('scope')).toBe(GOOGLE_CALENDAR_OAUTH_SCOPES.join(' '))
expect(url.searchParams.get('access_type')).toBe('offline')
expect(url.searchParams.get('prompt')).toBe('consent')
expect(url.searchParams.get('state')).toBe('state-123')
expect(url.search).not.toContain('client_secret')
})
})
describe('readGoogleCalendarOAuthCredentials', () => {
const original = {
id: process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_ID_ENV],
secret: process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET_ENV],
}
afterEach(() => {
if (original.id === undefined) delete process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_ID_ENV]
else process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_ID_ENV] = original.id
if (original.secret === undefined) delete process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET_ENV]
else process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET_ENV] = original.secret
})
it('fails closed (null) when either side is missing', () => {
delete process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_ID_ENV]
delete process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET_ENV]
expect(readGoogleCalendarOAuthCredentials()).toBeNull()
process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_ID_ENV] = 'client-id'
expect(readGoogleCalendarOAuthCredentials()).toBeNull()
delete process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_ID_ENV]
process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET_ENV] = 'client-secret'
expect(readGoogleCalendarOAuthCredentials()).toBeNull()
})
it('returns the pair when both sides are set', () => {
process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_ID_ENV] = 'client-id'
process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET_ENV] = 'client-secret'
expect(readGoogleCalendarOAuthCredentials()).toEqual({
clientId: 'client-id',
clientSecret: 'client-secret',
})
})
})
describe('exchangeGoogleCalendarOAuthCode', () => {
it('posts the authorization code and returns the refresh token + scope', async () => {
const calls: Array<{ url: string; body?: string }> = []
const fetchImpl = (async (input: RequestInfo | URL, init?: RequestInit) => {
calls.push({ url: String(input), body: typeof init?.body === 'string' ? init.body : '' })
return new Response(
JSON.stringify({
access_token: 'access-token',
refresh_token: 'refresh-token',
scope: GOOGLE_CALENDAR_OAUTH_SCOPES.join(' '),
}),
{ status: 200, headers: { 'Content-Type': 'application/json' } },
)
}) as typeof fetch
const tokens = await exchangeGoogleCalendarOAuthCode({
code: 'code-123',
redirectUri: REDIRECT_URI,
credentials: CREDENTIALS,
fetchImpl,
})
expect(tokens).toEqual({
refreshToken: 'refresh-token',
scope: GOOGLE_CALENDAR_OAUTH_SCOPES.join(' '),
})
const params = new URLSearchParams(calls[0]?.body)
expect(calls[0]?.url).toBe('https://oauth2.googleapis.com/token')
expect(params.get('grant_type')).toBe('authorization_code')
expect(params.get('code')).toBe('code-123')
expect(params.get('redirect_uri')).toBe(REDIRECT_URI)
expect(params.get('client_id')).toBe(CREDENTIALS.clientId)
expect(params.get('client_secret')).toBe(CREDENTIALS.clientSecret)
})
it('maps a non-OK response to a safe error without echoing the body', async () => {
const fetchImpl = (async () =>
new Response(JSON.stringify({ error: 'invalid_grant', secret: 'leak-me' }), {
status: 400,
headers: { 'Content-Type': 'application/json' },
})) as typeof fetch
const error = await exchangeGoogleCalendarOAuthCode({
code: 'code-123',
redirectUri: REDIRECT_URI,
credentials: CREDENTIALS,
fetchImpl,
}).catch((caught: unknown) => caught)
expect(error).toBeInstanceOf(GoogleCalendarOAuthError)
expect((error as Error).message).not.toContain('leak-me')
expect((error as Error).message).not.toContain('invalid_grant')
})
it('rejects a partial grant that misses a required scope', async () => {
const fetchImpl = (async () =>
new Response(
JSON.stringify({
access_token: 'access-token',
refresh_token: 'refresh-token',
scope: 'https://www.googleapis.com/auth/calendar.events',
}),
{ status: 200, headers: { 'Content-Type': 'application/json' } },
)) as typeof fetch
await expect(
exchangeGoogleCalendarOAuthCode({
code: 'code-123',
redirectUri: REDIRECT_URI,
credentials: CREDENTIALS,
fetchImpl,
}),
).rejects.toBeInstanceOf(GoogleCalendarOAuthError)
})
it('fails safely when Google does not return a refresh token', async () => {
const fetchImpl = (async () =>
new Response(JSON.stringify({ access_token: 'access-token' }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})) as typeof fetch
await expect(
exchangeGoogleCalendarOAuthCode({
code: 'code-123',
redirectUri: REDIRECT_URI,
credentials: CREDENTIALS,
fetchImpl,
}),
).rejects.toBeInstanceOf(GoogleCalendarOAuthError)
})
it('maps a network failure to a safe error', async () => {
const fetchImpl = (async () => {
throw new Error('socket hang up')
}) as typeof fetch
await expect(
exchangeGoogleCalendarOAuthCode({
code: 'code-123',
redirectUri: REDIRECT_URI,
credentials: CREDENTIALS,
fetchImpl,
}),
).rejects.toBeInstanceOf(GoogleCalendarOAuthError)
})
})

View file

@ -0,0 +1,218 @@
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import type {
GoogleCalendarListActionResult,
GoogleCalendarSyncActionResult,
} from '@/app/(campaign)/campanha/actions/googleCalendarSync'
import { GoogleCalendarPickerDialog } from '@/components/campaign/activity/GoogleCalendarPickerDialog'
/**
* C150 — the primary-calendar picker: live list states (loading/error/empty),
* the "em uso" mark, the confirm gating and the choose callback. Desktop
* layout (matchMedia false); the mobile drawer shares the same content.
*/
const CALENDAR_A = 'c_campanha@group.calendar.google.com'
const CALENDAR_B = 'c_pessoal@group.calendar.google.com'
const listResult: GoogleCalendarListActionResult = {
ok: true,
calendars: [
{ id: CALENDAR_A, summary: 'Agenda da Campanha', primary: false },
{ id: CALENDAR_B, summary: 'Meu calendário', primary: true },
],
}
const syncResult = (
overrides: Partial<GoogleCalendarSyncActionResult> = {},
): GoogleCalendarSyncActionResult => ({
ok: true,
canManageConnection: true,
connection: 'connected',
oauthAvailable: true,
oauthConnectedAt: '2026-08-01T12:00:00.000Z',
oauthError: null,
status: 'synced',
calendarId: CALENDAR_B,
lastSyncedAt: null,
lastSuccessAt: null,
lastErrorAt: null,
lastError: null,
pushChannelExpiresAt: null,
pushChannelError: null,
addLink: null,
...overrides,
})
const renderPicker = (
overrides: {
currentCalendarId?: string | null
onOpenChange?: (open: boolean) => void
onListCalendars?: () => Promise<GoogleCalendarListActionResult>
onChooseCalendar?: (calendarId: string) => Promise<GoogleCalendarSyncActionResult>
} = {},
) =>
render(
<GoogleCalendarPickerDialog
open
onOpenChange={overrides.onOpenChange ?? vi.fn()}
currentCalendarId={overrides.currentCalendarId ?? CALENDAR_A}
onListCalendars={overrides.onListCalendars ?? vi.fn(async () => listResult)}
onChooseCalendar={overrides.onChooseCalendar ?? vi.fn(async () => syncResult())}
/>,
)
const matchMediaMock = vi.fn()
beforeAll(() => {
vi.stubGlobal(
'ResizeObserver',
class {
observe() {}
unobserve() {}
disconnect() {}
},
)
Element.prototype.scrollIntoView = () => {}
})
beforeEach(() => {
matchMediaMock.mockImplementation((query: string) => ({
matches: false,
media: query,
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
addListener: vi.fn(),
removeListener: vi.fn(),
dispatchEvent: vi.fn(),
}))
vi.stubGlobal('matchMedia', matchMediaMock)
})
afterEach(() => {
cleanup()
vi.clearAllMocks()
})
afterAll(() => {
vi.unstubAllGlobals()
})
describe('GoogleCalendarPickerDialog (C150)', () => {
it('shows the loading state while the live list is fetched', () => {
renderPicker({
onListCalendars: vi.fn((): Promise<GoogleCalendarListActionResult> => new Promise(() => {})),
})
expect(screen.getByText('Carregando calendários...')).toBeTruthy()
})
it('lists the calendars, marks the current one and disables the no-op confirm', async () => {
renderPicker()
const picker = await screen.findByRole('dialog', {
name: /Calendário principal da campanha/,
})
const current = within(picker).getByRole('button', {
name: /Agenda da Campanha/,
pressed: true,
})
expect(current.getAttribute('aria-pressed')).toBe('true')
expect(within(picker).getByText('em uso')).toBeTruthy()
expect(within(picker).getByText('Calendário principal da conta')).toBeTruthy()
const confirm = within(picker).getByRole('button', { name: 'Escolher calendário' })
expect(confirm.hasAttribute('disabled')).toBe(true)
})
it('chooses another calendar and closes on success', async () => {
const onOpenChange = vi.fn()
const onChooseCalendar = vi.fn(async () => syncResult())
renderPicker({ onOpenChange, onChooseCalendar })
const picker = await screen.findByRole('dialog', {
name: /Calendário principal da campanha/,
})
fireEvent.click(within(picker).getByRole('button', { name: /Meu calendário/ }))
fireEvent.click(within(picker).getByRole('button', { name: 'Escolher calendário' }))
await waitFor(() => expect(onChooseCalendar).toHaveBeenCalledWith(CALENDAR_B))
await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false))
})
it('keeps the picker open and shows the failure message', async () => {
const onOpenChange = vi.fn()
const onChooseCalendar = vi.fn(async () =>
syncResult({ ok: false, message: 'O calendário escolhido não está mais disponível.' }),
)
renderPicker({ onOpenChange, onChooseCalendar })
const picker = await screen.findByRole('dialog', {
name: /Calendário principal da campanha/,
})
fireEvent.click(within(picker).getByRole('button', { name: /Meu calendário/ }))
fireEvent.click(within(picker).getByRole('button', { name: 'Escolher calendário' }))
expect(await within(picker).findByText(/não está mais disponível/)).toBeTruthy()
expect(onOpenChange).not.toHaveBeenCalled()
})
it('offers a retry when the list fails', async () => {
const onListCalendars = vi
.fn<() => Promise<GoogleCalendarListActionResult>>()
.mockResolvedValueOnce({ ok: false, message: 'Não foi possível listar os calendários.' })
.mockResolvedValueOnce(listResult)
renderPicker({ onListCalendars })
expect(await screen.findByText('Não foi possível listar os calendários.')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: 'Tentar de novo' }))
expect(await screen.findByText('Agenda da Campanha')).toBeTruthy()
expect(onListCalendars).toHaveBeenCalledTimes(2)
})
it('shows the empty state when the account has no writable calendar', async () => {
renderPicker({
onListCalendars: vi.fn(
async (): Promise<GoogleCalendarListActionResult> => ({ ok: true, calendars: [] }),
),
})
expect(
await screen.findByText('Nenhum calendário com permissão de edição nesta conta Google.'),
).toBeTruthy()
expect(screen.queryByRole('button', { name: 'Escolher calendário' })).toBeNull()
})
it('maps a rejected list action to the error state with retry', async () => {
const onListCalendars = vi
.fn<() => Promise<GoogleCalendarListActionResult>>()
.mockRejectedValueOnce(new Error('transport down'))
.mockResolvedValueOnce(listResult)
renderPicker({ onListCalendars })
expect(await screen.findByText('Não foi possível listar os calendários agora.')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: 'Tentar de novo' }))
expect(await screen.findByText('Agenda da Campanha')).toBeTruthy()
})
it('maps a rejected choose action to an inline error without closing', async () => {
const onOpenChange = vi.fn()
const onChooseCalendar = vi
.fn<() => Promise<GoogleCalendarSyncActionResult>>()
.mockRejectedValueOnce(new Error('transport down'))
renderPicker({ onOpenChange, onChooseCalendar })
const picker = await screen.findByRole('dialog', {
name: /Calendário principal da campanha/,
})
fireEvent.click(within(picker).getByRole('button', { name: /Meu calendário/ }))
fireEvent.click(within(picker).getByRole('button', { name: 'Escolher calendário' }))
expect(
await within(picker).findByText(/Não foi possível escolher o calendário agora/),
).toBeTruthy()
expect(onOpenChange).not.toHaveBeenCalled()
})
})

View file

@ -2,11 +2,22 @@ import { afterEach, describe, expect, it } from 'vitest'
import type { Activity, GoogleCalendarSync as GoogleCalendarSyncDoc } from '@/payload-types'
import { REQUEST_TIMEOUT_MS } from '@/utilities/googleCalendarClient'
import {
GoogleCalendarApiError,
GoogleCalendarAuthError,
REQUEST_TIMEOUT_MS,
} from '@/utilities/googleCalendarClient'
import {
GOOGLE_CALENDAR_OAUTH_CLIENT_ID_ENV,
GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET_ENV,
} from '@/utilities/googleCalendarOAuth'
import {
deriveGoogleCalendarConnectionStatus,
deriveGoogleCalendarSyncStatus,
GOOGLE_CALENDAR_SERVICE_ACCOUNT_KEY_ENV,
GOOGLE_CALENDAR_SYNC_HOOK_TIMEOUT_MS,
oauthErrorPatchFor,
readGoogleCalendarAuth,
readGoogleServiceAccountCredentials,
shouldSyncActivityOperation,
shouldSyncConfigChange,
@ -61,6 +72,71 @@ describe('deriveGoogleCalendarSyncStatus', () => {
})
})
describe('deriveGoogleCalendarConnectionStatus (C149)', () => {
it('is not-configured without a refresh token and without an error', () => {
expect(deriveGoogleCalendarConnectionStatus({ hasRefreshToken: false })).toBe('not-configured')
})
it('is connected with a refresh token and no newer error', () => {
expect(
deriveGoogleCalendarConnectionStatus({
hasRefreshToken: true,
oauthConnectedAt: '2026-08-11T10:00:00.000Z',
}),
).toBe('connected')
// An error recorded BEFORE the last connection is stale — connected wins.
expect(
deriveGoogleCalendarConnectionStatus({
hasRefreshToken: true,
oauthConnectedAt: '2026-08-11T12:00:00.000Z',
oauthErrorAt: '2026-08-11T10:00:00.000Z',
}),
).toBe('connected')
})
it('is error when the auth error is newer than the connection (or there is none)', () => {
expect(
deriveGoogleCalendarConnectionStatus({
hasRefreshToken: true,
oauthConnectedAt: '2026-08-11T10:00:00.000Z',
oauthErrorAt: '2026-08-11T12:00:00.000Z',
}),
).toBe('error')
// A failed handshake before the first connection has no connectedAt.
expect(
deriveGoogleCalendarConnectionStatus({
hasRefreshToken: false,
oauthErrorAt: '2026-08-11T12:00:00.000Z',
}),
).toBe('error')
})
})
describe('oauthErrorPatchFor (C149)', () => {
it('maps a dead OAuth connection to the connection error fields', () => {
expect(
oauthErrorPatchFor(
new GoogleCalendarAuthError('A conexão com o Google expirou. Reconecte a conta.'),
'2026-09-12T10:00:00.000Z',
),
).toEqual({
oauthErrorAt: '2026-09-12T10:00:00.000Z',
oauthError: 'A conexão com o Google expirou. Reconecte a conta.',
})
})
it('leaves every other failure out of the connection state', () => {
expect(oauthErrorPatchFor(new Error('HTTP 500'), 'at')).toBeNull()
expect(oauthErrorPatchFor(new GoogleCalendarApiError('HTTP 403', 403), 'at')).toBeNull()
expect(oauthErrorPatchFor('not-an-error', 'at')).toBeNull()
})
it('truncates the message to the stored 500-char limit', () => {
const patch = oauthErrorPatchFor(new GoogleCalendarAuthError('x'.repeat(900)), 'at')
expect(patch?.oauthError).toHaveLength(500)
})
})
describe('readGoogleServiceAccountCredentials', () => {
const originalKey = process.env[GOOGLE_CALENDAR_SERVICE_ACCOUNT_KEY_ENV]
@ -103,6 +179,86 @@ describe('readGoogleServiceAccountCredentials', () => {
})
})
describe('readGoogleCalendarAuth (C149)', () => {
const original = {
sa: process.env[GOOGLE_CALENDAR_SERVICE_ACCOUNT_KEY_ENV],
id: process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_ID_ENV],
secret: process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET_ENV],
}
afterEach(() => {
const restore = (key: string, value: string | undefined) => {
if (value === undefined) delete process.env[key]
else process.env[key] = value
}
restore(GOOGLE_CALENDAR_SERVICE_ACCOUNT_KEY_ENV, original.sa)
restore(GOOGLE_CALENDAR_OAUTH_CLIENT_ID_ENV, original.id)
restore(GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET_ENV, original.secret)
})
const setServiceAccountEnv = () => {
process.env[GOOGLE_CALENDAR_SERVICE_ACCOUNT_KEY_ENV] = Buffer.from(
JSON.stringify({
client_email: 'teqo-sa@projeto.iam.gserviceaccount.com',
private_key: '-----BEGIN PRIVATE KEY-----\nMOCK\n-----END PRIVATE KEY-----\n',
}),
'utf8',
).toString('base64')
}
const setOAuthClientEnv = () => {
process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_ID_ENV] = 'client-id'
process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET_ENV] = 'client-secret'
}
const doc = (overrides: Record<string, unknown> = {}) =>
({ id: 1, ...overrides }) as unknown as GoogleCalendarSyncDoc
it('prefers the OAuth connection over the service account', () => {
setServiceAccountEnv()
setOAuthClientEnv()
const auth = readGoogleCalendarAuth(doc({ oauthRefreshToken: 'refresh-token' }))
expect(auth).toEqual({
kind: 'oauth',
credentials: {
clientId: 'client-id',
clientSecret: 'client-secret',
refreshToken: 'refresh-token',
},
})
})
it('falls back to the service account without a refresh token', () => {
setServiceAccountEnv()
setOAuthClientEnv()
const auth = readGoogleCalendarAuth(doc())
expect(auth?.kind).toBe('service-account')
})
it('falls back to the service account when the OAuth client env is missing', () => {
setServiceAccountEnv()
delete process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_ID_ENV]
delete process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET_ENV]
expect(readGoogleCalendarAuth(doc({ oauthRefreshToken: 'refresh-token' }))?.kind).toBe(
'service-account',
)
})
it('is null (fail-closed) without any credential', () => {
delete process.env[GOOGLE_CALENDAR_SERVICE_ACCOUNT_KEY_ENV]
delete process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_ID_ENV]
delete process.env[GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET_ENV]
expect(readGoogleCalendarAuth(doc({ oauthRefreshToken: 'refresh-token' }))).toBeNull()
expect(readGoogleCalendarAuth(null)).toBeNull()
})
})
describe('shouldSyncActivityOperation', () => {
const activity = (overrides: Record<string, unknown> = {}) =>
({ id: 1, title: 'Caminhada', status: 'confirmado', ...overrides }) as unknown as Activity
@ -239,6 +395,20 @@ describe('shouldSyncConfigChange', () => {
}),
).toBe(true)
})
it('skips OAuth-connection writes — the callback runs its own pass (C149)', () => {
expect(
shouldSyncConfigChange({
operation: 'update',
doc: config({
oauthRefreshToken: 'refresh-token',
oauthConnectedAt: 'x',
oauthError: null,
}),
previousDoc: config({ oauthRefreshToken: null }),
}),
).toBe(false)
})
})
describe('sync deadlines (C114-LOCK)', () => {

View file

@ -1,4 +1,4 @@
import { cleanup, render, screen, within } from '@testing-library/react'
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import type { GoogleCalendarSyncActionResult } from '@/app/(campaign)/campanha/actions/googleCalendarSync'
@ -9,6 +9,11 @@ const syncedState = (
overrides: Partial<GoogleCalendarSyncActionResult> = {},
): GoogleCalendarSyncActionResult => ({
ok: true,
canManageConnection: true,
connection: 'connected',
oauthAvailable: true,
oauthConnectedAt: '2026-08-01T12:00:00.000Z',
oauthError: null,
status: 'synced',
calendarId: 'c_campanha@group.calendar.google.com',
lastSyncedAt: '2026-08-11T12:00:00.000Z',
@ -17,12 +22,19 @@ const syncedState = (
lastError: null,
pushChannelExpiresAt: null,
pushChannelError: null,
addLink: 'https://calendar.google.com/calendar/r?cid=webcal%3A%2F%2F…',
addLink: 'https://calendar.google.com/calendar/r?cid=c_campanha%40group.calendar.google.com',
...overrides,
})
const notConfiguredState = (): GoogleCalendarSyncActionResult => ({
const notConfiguredState = (
overrides: Partial<GoogleCalendarSyncActionResult> = {},
): GoogleCalendarSyncActionResult => ({
ok: true,
canManageConnection: true,
connection: 'not-configured',
oauthAvailable: true,
oauthConnectedAt: null,
oauthError: null,
status: 'not-configured',
calendarId: null,
lastSyncedAt: null,
@ -32,9 +44,19 @@ const notConfiguredState = (): GoogleCalendarSyncActionResult => ({
pushChannelExpiresAt: null,
pushChannelError: null,
addLink: null,
...overrides,
})
const renderDialog = (state: GoogleCalendarSyncActionResult) =>
const renderDialog = (
state: GoogleCalendarSyncActionResult,
overrides: {
onStartOAuth?: () => Promise<
{ ok: true; authorizeUrl: string } | { ok: false; message: string }
>
onDisconnect?: () => Promise<GoogleCalendarSyncActionResult>
onOpenPicker?: () => void
} = {},
) =>
render(
<GoogleCalendarSyncDialog
open
@ -42,6 +64,9 @@ const renderDialog = (state: GoogleCalendarSyncActionResult) =>
state={state}
onSyncNow={vi.fn()}
onSetDisabled={vi.fn()}
onStartOAuth={overrides.onStartOAuth ?? vi.fn()}
onDisconnect={overrides.onDisconnect ?? vi.fn()}
onOpenPicker={overrides.onOpenPicker ?? vi.fn()}
/>,
)
@ -129,6 +154,103 @@ describe('GoogleCalendarSyncDialog — encaixe desktop (C148)', () => {
})
})
describe('GoogleCalendarSyncDialog — card de conexão OAuth (C149)', () => {
it('offers the connect button when the OAuth client is configured', () => {
renderDialog(notConfiguredState())
const dialog = screen.getByRole('dialog', { name: /Agenda da Campanha no Google/ })
expect(within(dialog).getByText('Não configurado')).toBeTruthy()
expect(within(dialog).getByRole('button', { name: /Conectar com o Google/ })).toBeTruthy()
// The service account remains documented as the technical fallback.
expect(within(dialog).getByText(/service account continua disponível/)).toBeTruthy()
})
it('shows the handshake error with the one-click reconnect path', () => {
renderDialog(
syncedState({
connection: 'error',
oauthError: 'A conexão com o Google expirou ou foi revogada.',
}),
)
const dialog = screen.getByRole('dialog', { name: /Agenda da Campanha no Google/ })
expect(within(dialog).getByText('Erro')).toBeTruthy()
expect(within(dialog).getByText(/expirou ou foi revogada/)).toBeTruthy()
expect(within(dialog).getByRole('button', { name: /Reconectar com o Google/ })).toBeTruthy()
})
it('disconnects from the card when connected', async () => {
const onDisconnect = vi.fn(async () => notConfiguredState())
renderDialog(syncedState(), { onDisconnect })
fireEvent.click(screen.getByRole('button', { name: 'Desconectar' }))
await waitFor(() => expect(onDisconnect).toHaveBeenCalledTimes(1))
})
it('hides the connect/disconnect actions from non-managers (advisor)', () => {
renderDialog(notConfiguredState({ canManageConnection: false }))
expect(screen.queryByRole('button', { name: /Conectar com o Google/ })).toBeNull()
expect(screen.getByText(/Somente candidato ou coordenação/)).toBeTruthy()
})
it('falls back to the admin runbook when the server has no OAuth client', () => {
renderDialog(notConfiguredState({ oauthAvailable: false }))
expect(screen.getByText(/service account do Teqo/)).toBeTruthy()
expect(screen.queryByRole('button', { name: /Conectar com o Google/ })).toBeNull()
})
})
describe('GoogleCalendarSyncDialog — calendário principal e one-click (C150)', () => {
it('shows the current calendar and the picker trigger to managers', () => {
renderDialog(syncedState())
const dialog = screen.getByRole('dialog', { name: /Agenda da Campanha no Google/ })
expect(within(dialog).getByText('Calendário principal da campanha')).toBeTruthy()
expect(within(dialog).getByText('c_campanha@group.calendar.google.com')).toBeTruthy()
expect(within(dialog).getByRole('button', { name: 'Trocar calendário principal' })).toBeTruthy()
})
it('opens the picker from the connection card', () => {
const onOpenPicker = vi.fn()
renderDialog(syncedState(), { onOpenPicker })
fireEvent.click(screen.getByRole('button', { name: 'Trocar calendário principal' }))
expect(onOpenPicker).toHaveBeenCalledTimes(1)
})
it('offers to choose when the connection is active but no calendar is set', () => {
renderDialog(syncedState({ status: 'not-configured', calendarId: null, addLink: null }))
const dialog = screen.getByRole('dialog', { name: /Agenda da Campanha no Google/ })
expect(
within(dialog).getByRole('button', { name: 'Escolher calendário principal' }),
).toBeTruthy()
expect(within(dialog).getByText(/Escolha o calendário principal/)).toBeTruthy()
})
it('hides the picker trigger from non-managers and names the nucleus', () => {
renderDialog(syncedState({ canManageConnection: false }))
const dialog = screen.getByRole('dialog', { name: /Agenda da Campanha no Google/ })
expect(within(dialog).queryByRole('button', { name: /calendário principal/ })).toBeNull()
expect(within(dialog).getByText(/escolhido por candidato ou coordenação/)).toBeTruthy()
})
it('renders the one-click add link and the public iCal URL for the manual path', () => {
renderDialog(syncedState())
const dialog = screen.getByRole('dialog', { name: /Agenda da Campanha no Google/ })
const addLink = within(dialog).getByRole('link', {
name: /Adicionar ao meu Google Calendar/,
})
expect(addLink.getAttribute('href')).toBe(
'https://calendar.google.com/calendar/r?cid=c_campanha%40group.calendar.google.com',
)
const icalInput = within(dialog).getByLabelText(
'URL pública do calendário (Por URL, Apple Calendar e Outlook)',
) as HTMLInputElement
expect(icalInput.value).toBe(
'https://calendar.google.com/calendar/ical/c_campanha%40group.calendar.google.com/public/basic.ics',
)
})
})
describe('ActivityUpdateFeed — atribuição do registro reverso (C115)', () => {
const renderFeed = (updates: Parameters<typeof ActivityUpdateFeed>[0]['updates']) =>
render(<ActivityUpdateFeed updates={updates} />)

View file

@ -0,0 +1,72 @@
// @vitest-environment node
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { afterEach, describe, expect, it, vi } from 'vitest'
import robots from '@/app/robots'
import { isStagingSite, isStagingSiteUrl } from '@/lib/siteEnvironment'
const repoRoot = join(fileURLToPath(new URL('.', import.meta.url)), '../..')
describe('isStagingSiteUrl (OPS103)', () => {
it('detects staging hostnames', () => {
expect(isStagingSiteUrl('https://staging.jorgesolla1313.com.br')).toBe(true)
expect(isStagingSiteUrl('http://staging.example.com:3000')).toBe(true)
expect(isStagingSiteUrl('https://staging.jorgesolla1313.com.br/caminho?q=1')).toBe(true)
})
it('leaves production, staging-lookalikes and invalid origins indexable', () => {
expect(isStagingSiteUrl('https://jorgesolla1313.com.br')).toBe(false)
expect(isStagingSiteUrl('https://example.com/staging')).toBe(false)
expect(isStagingSiteUrl('https://xstaging.example.com')).toBe(false)
expect(isStagingSiteUrl(undefined)).toBe(false)
expect(isStagingSiteUrl(null)).toBe(false)
expect(isStagingSiteUrl('')).toBe(false)
expect(isStagingSiteUrl('not-a-url')).toBe(false)
})
})
describe('isStagingSite (OPS103)', () => {
afterEach(() => vi.unstubAllEnvs())
it('reads NEXT_PUBLIC_SITE_URL at call time (the identity each build carries)', () => {
vi.stubEnv('NEXT_PUBLIC_SITE_URL', 'https://staging.jorgesolla1313.com.br')
expect(isStagingSite()).toBe(true)
vi.stubEnv('NEXT_PUBLIC_SITE_URL', 'https://jorgesolla1313.com.br')
expect(isStagingSite()).toBe(false)
})
})
describe('staging noindex wiring (OPS103)', () => {
afterEach(() => vi.unstubAllEnvs())
it('robots() disallows every path on staging and allows production', () => {
vi.stubEnv('NEXT_PUBLIC_SITE_URL', 'https://staging.jorgesolla1313.com.br')
expect(robots().rules).toEqual({ userAgent: '*', disallow: '/' })
vi.stubEnv('NEXT_PUBLIC_SITE_URL', 'https://jorgesolla1313.com.br')
expect(robots().rules).toEqual({ userAgent: '*', allow: '/' })
})
it('robots.ts lives at the app-dir root and consumes the helper', () => {
// Next 15 only recognizes metadata route files at the app-dir root (route
// groups are not part of the match), so this path is load-bearing.
const robotsSource = readFileSync(join(repoRoot, 'src/app/robots.ts'), 'utf8')
expect(robotsSource).toContain("from '@/lib/siteEnvironment'")
expect(robotsSource).toContain('isStagingSite')
})
it('the frontend layout flips robots.index off only for staging', () => {
const layout = readFileSync(join(repoRoot, 'src/app/(frontend)/layout.tsx'), 'utf8')
expect(layout).toContain("from '@/lib/siteEnvironment'")
// Pin the exact ternary: presence of `index: false` and `index: true`
// somewhere would survive an inverted condition.
expect(layout).toContain(
'robots: isStagingSite() ? { index: false, follow: false } : { index: true, follow: true },',
)
})
})