Pass 2: formatacao da revisao (prettier em tabelas md + ordenacao de imports; SQL da migration inalterado) e remocao de duplicata stray do CampaignListEmptyState no path antigo

This commit is contained in:
Francisco Ignácio Fontoura Solla 2026-07-25 16:53:51 -03:00
parent e8a440b837
commit 51dd779ddd
18 changed files with 101 additions and 129 deletions

View file

@ -73,7 +73,6 @@ Backlog consolidado (bloqueadores, site, campanha, white-label): [`docs/roadmap.
**Recently resolved (2026-07-24):** **E9** Fila de alocação — the municipality list became the allocation queue, with **no new route, no new column and no migration** (the column picker is B17 and is not shipped, so every new signal folds into an existing cell). Ordering: two new sort keys in `municipalityUi.ts` — `deficit` (**the new staff default**, descending) and `frescor` — both derived in memory in `applyDerivedMunicipalitySort` over the already-loaded bundle, fixed to the `central` scenario server-side (moving the scenario into the URL is the "Cenário junto aos filtros" fill-in). Freshness: `aggregatePledgesByMunicipality` now selects `declaredAt`/`estimatedAt` and exposes `lastPledgeAt`; `resolveMunicipalityLastSignalAt` (max of `municipality.lastUpdateAt` and `lastPledgeAt`) feeds both the comparator and the view model's `lastSignalAt`, so server ordering and rendered copy cannot drift; cold threshold `MUNICIPALITY_COLD_SIGNAL_DAYS` = 21. UI: "há N dias" in the existing "Última atualização" column (amber `text-estimate-pending-foreground`, deliberately not `destructive` — the priority and "sem responsável" badges already compete for red on the same row), a "sem responsável" badge when `priority === 'alta'` with zero advisors, the "coluna da vergonha" as the advisor-coverage metric's detail linking `?priority=alta&coverage=sem_assessor`, a scenario-named coverage tooltip, and the leftover "Praças" copy fixed to "Municípios". Cut and re-homed: votes at stake → **B13**, LQ/capture → **E10**, a dedicated deficit column → unnecessary (the E8 cell already shows % and signed deficit). Plano: [`docs/plans/fila-de-alocacao.md`](docs/plans/fila-de-alocacao.md). **Recently resolved (2026-07-24):** **E9** Fila de alocação — the municipality list became the allocation queue, with **no new route, no new column and no migration** (the column picker is B17 and is not shipped, so every new signal folds into an existing cell). Ordering: two new sort keys in `municipalityUi.ts` — `deficit` (**the new staff default**, descending) and `frescor` — both derived in memory in `applyDerivedMunicipalitySort` over the already-loaded bundle, fixed to the `central` scenario server-side (moving the scenario into the URL is the "Cenário junto aos filtros" fill-in). Freshness: `aggregatePledgesByMunicipality` now selects `declaredAt`/`estimatedAt` and exposes `lastPledgeAt`; `resolveMunicipalityLastSignalAt` (max of `municipality.lastUpdateAt` and `lastPledgeAt`) feeds both the comparator and the view model's `lastSignalAt`, so server ordering and rendered copy cannot drift; cold threshold `MUNICIPALITY_COLD_SIGNAL_DAYS` = 21. UI: "há N dias" in the existing "Última atualização" column (amber `text-estimate-pending-foreground`, deliberately not `destructive` — the priority and "sem responsável" badges already compete for red on the same row), a "sem responsável" badge when `priority === 'alta'` with zero advisors, the "coluna da vergonha" as the advisor-coverage metric's detail linking `?priority=alta&coverage=sem_assessor`, a scenario-named coverage tooltip, and the leftover "Praças" copy fixed to "Municípios". Cut and re-homed: votes at stake → **B13**, LQ/capture → **E10**, a dedicated deficit column → unnecessary (the E8 cell already shows % and signed deficit). Plano: [`docs/plans/fila-de-alocacao.md`](docs/plans/fila-de-alocacao.md).
**Recently resolved (2026-07-24):** **E18** Documentação dos conceitos de inteligência — staff-only route `/campanha/conceitos` (`isCampaignStaff`; `leader` redirected to `/campanha`) rendering `src/lib/campaignIntelligenceConcepts.ts`. The glossary is **curated content in code, not a Payload collection**: each entry (what it measures, the formula in plain text, a hand-written example, why it matters, where it appears) sits next to the formulas it documents (`municipalityPotential.ts` / `goalCoverage.ts`) and is reviewed in the same PR that changes them; a unit test guards anchor-safe unique IDs and content completeness. Seven E8 concepts in three groups — base do cálculo (válidos projetados, teto do campo), diagnóstico (captura, share intracampo, roll-off), meta e cobertura (meta/meta sugerida, cobertura da meta). Reading surface, not cards: one `article` per concept with hairline dividers, `max-w-prose` column, sticky index at `lg` only, `article:target` tint so anchor arrivals land oriented. Two discovery paths from `MunicipalityGoalAccountCard`: per-metric "Saiba mais" links inside the hover tooltips (`MetricExplanation` takes a `conceptID`) and a whole-page link in the title `CampaignInfoHint` **Popover** — the Popover is the keyboard path because Radix Tooltip content is not tabbable; for touch, `MunicipalityHoverTooltip` now treats its own content as "inside" in the `pointerdown` dismiss handler (the link used to unmount before the tap landed). Sidebar entry lives in `staffSecondaryNav` (`nav.ts`) rendered in its own `SidebarGroup` with `mt-auto` at the foot of the navigation — deliberately outside `staffNav` (the seven work destinations) and outside the mobile bottom bar, since it is reference material; `getCampaignSecondaryNav` returns nothing for `leader`. Fixed an E8 defect found while writing the docs: `formatElectionNumber` rendered a fractional suggested goal as "100,968" (read as a hundred thousand in pt-BR) — now `maximumFractionDigits: 0`. No migration, no collection, no server action; later slices of the intelligence program (E9/E10/B13/E11/E12/E13/E14) each append their section to the array. Plano: [`docs/plans/documentacao-conceitos-campanha.md`](docs/plans/documentacao-conceitos-campanha.md). **Recently resolved (2026-07-24):** **E18** Documentação dos conceitos de inteligência — staff-only route `/campanha/conceitos` (`isCampaignStaff`; `leader` redirected to `/campanha`) rendering `src/lib/campaignIntelligenceConcepts.ts`. The glossary is **curated content in code, not a Payload collection**: each entry (what it measures, the formula in plain text, a hand-written example, why it matters, where it appears) sits next to the formulas it documents (`municipalityPotential.ts` / `goalCoverage.ts`) and is reviewed in the same PR that changes them; a unit test guards anchor-safe unique IDs and content completeness. Seven E8 concepts in three groups — base do cálculo (válidos projetados, teto do campo), diagnóstico (captura, share intracampo, roll-off), meta e cobertura (meta/meta sugerida, cobertura da meta). Reading surface, not cards: one `article` per concept with hairline dividers, `max-w-prose` column, sticky index at `lg` only, `article:target` tint so anchor arrivals land oriented. Two discovery paths from `MunicipalityGoalAccountCard`: per-metric "Saiba mais" links inside the hover tooltips (`MetricExplanation` takes a `conceptID`) and a whole-page link in the title `CampaignInfoHint` **Popover** — the Popover is the keyboard path because Radix Tooltip content is not tabbable; for touch, `MunicipalityHoverTooltip` now treats its own content as "inside" in the `pointerdown` dismiss handler (the link used to unmount before the tap landed). Sidebar entry lives in `staffSecondaryNav` (`nav.ts`) rendered in its own `SidebarGroup` with `mt-auto` at the foot of the navigation — deliberately outside `staffNav` (the seven work destinations) and outside the mobile bottom bar, since it is reference material; `getCampaignSecondaryNav` returns nothing for `leader`. Fixed an E8 defect found while writing the docs: `formatElectionNumber` rendered a fractional suggested goal as "100,968" (read as a hundred thousand in pt-BR) — now `maximumFractionDigits: 0`. No migration, no collection, no server action; later slices of the intelligence program (E9/E10/B13/E11/E12/E13/E14) each append their section to the array. Plano: [`docs/plans/documentacao-conceitos-campanha.md`](docs/plans/documentacao-conceitos-campanha.md).
**Recently resolved (2026-07-24):** **B19** Gerenciar assessores — `/campanha/assessores` (lista + novo + detalhe) for coordinator/candidate only (`isCampaignUnrestricted`); create/edit `advisor` accounts, municipality portfolio (per-municipality auto-save + advisory lock), password-reset email (blocks `@planilha.invalid`); aligned `canUpdateCampaignUser` / phone field access / `canAssignMunicipalityAdvisors` / `assignMunicipalityAdvisorsRecord` to unrestricted; privileged email read in `advisorData` loaders after the route gate; `reloadUnrestrictedActor`. No migration. Plano: [`docs/plans/gerenciar-assessores.md`](docs/plans/gerenciar-assessores.md). **Recently resolved (2026-07-24):** **B19** Gerenciar assessores — `/campanha/assessores` (lista + novo + detalhe) for coordinator/candidate only (`isCampaignUnrestricted`); create/edit `advisor` accounts, municipality portfolio (per-municipality auto-save + advisory lock), password-reset email (blocks `@planilha.invalid`); aligned `canUpdateCampaignUser` / phone field access / `canAssignMunicipalityAdvisors` / `assignMunicipalityAdvisorsRecord` to unrestricted; privileged email read in `advisorData` loaders after the route gate; `reloadUnrestrictedActor`. No migration. Plano: [`docs/plans/gerenciar-assessores.md`](docs/plans/gerenciar-assessores.md).

View file

@ -7,7 +7,7 @@ O mapa conceitual do repositório: como o sistema se divide, em que direção o
Um único app Next.js (App Router) + Payload CMS sobre um Postgres (Neon em produção, Docker local), hospedado na Vercel. Três produtos em três route groups, com **duas barreiras de autenticação independentes** que podem coexistir no mesmo navegador: Um único app Next.js (App Router) + Payload CMS sobre um Postgres (Neon em produção, Docker local), hospedado na Vercel. Três produtos em três route groups, com **duas barreiras de autenticação independentes** que podem coexistir no mesmo navegador:
| Route group | Produto | Auth | | Route group | Produto | Auth |
| -------------- | ---------------------------------------------- | ------------------------------------------------------------------------------------------ | | ------------ | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| `(frontend)` | Site público (notícias, petições, WhatsApp) | anônimo; ISR + tag caching | | `(frontend)` | Site público (notícias, petições, WhatsApp) | anônimo; ISR + tag caching |
| `(payload)` | Admin editorial `/admin` | collection `users`, cookie `payload-token` | | `(payload)` | Admin editorial `/admin` | collection `users`, cookie `payload-token` |
| `(campaign)` | Ferramenta interna `/campanha` | collection `campaignUser`, cookie próprio `campaign-token` (path `/campanha`); barreira no layout de `(app)` | | `(campaign)` | Ferramenta interna `/campanha` | collection `campaignUser`, cookie próprio `campaign-token` (path `/campanha`); barreira no layout de `(app)` |
@ -62,7 +62,7 @@ flowchart LR
Papéis em `campaignUser.role` — predicados client-safe em `lib/campaignRoles.ts`, checks de ator em `utilities/access/shared.ts`, regras por domínio em `utilities/access/*` (re-exportadas por `campaignAccess.ts`): Papéis em `campaignUser.role` — predicados client-safe em `lib/campaignRoles.ts`, checks de ator em `utilities/access/shared.ts`, regras por domínio em `utilities/access/*` (re-exportadas por `campaignAccess.ts`):
| Papel | Escopo | | Papel | Escopo |
| ------------- | ---------------------------------------------------------------------------------------------------------- | | ------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `coordinator` | tudo (staff irrestrito); único que importa CSV de apoiadores e gerencia assessores (com `candidate`) | | `coordinator` | tudo (staff irrestrito); único que importa CSV de apoiadores e gerencia assessores (com `candidate`) |
| `candidate` | visibilidade irrestrita (staff); elegível como assessor responsável | | `candidate` | visibilidade irrestrita (staff); elegível como assessor responsável |
| `advisor` | staff restrito aos municípios em `municipality.advisors` | | `advisor` | staff restrito aos municípios em `municipality.advisors` |
@ -79,7 +79,7 @@ Dois contexts principais + um de suporte, espelhados nos prefixos de módulo e n
- **Município** — a unidade operacional PREDEFINIDA (435 no catálogo: 416 municípios; Salvador em 19 zonas; Camaçari inteiro). ≠ município IBGE genérico; geografia é read-only, estratégia é editável. Sinônimos históricos mortos: Núcleo, Praça (copy varrida no Pass 2 W4f; só migrations congeladas e textos provisórios de consent do Onda 0 ainda dizem "Praça"). - **Município** — a unidade operacional PREDEFINIDA (435 no catálogo: 416 municípios; Salvador em 19 zonas; Camaçari inteiro). ≠ município IBGE genérico; geografia é read-only, estratégia é editável. Sinônimos históricos mortos: Núcleo, Praça (copy varrida no Pass 2 W4f; só migrations congeladas e textos provisórios de consent do Onda 0 ainda dizem "Praça").
- **Liderança** — ficha única por pessoa (`contact` UNIQUE), atua em N municípios/organizações; pode ter conta `leader`. - **Liderança** — ficha única por pessoa (`contact` UNIQUE), atua em N municípios/organizações; pode ter conta `leader`.
- **Pledge (compromisso de votos)** — por liderança×município; `declaredVotes` (staff-entered, visível à liderança) vs `estimatedVotes` (staff-only, 3 cenários: `pessimistic|central|optimistic`). - **Pledge (compromisso de votos)** — por liderança×município; `declaredVotes` (staff-entered, visível à liderança) vs `estimatedVotes` (staff-only, 3 cenários: `pessimistic|central|optimistic`).
- **Conta da cadeira (E8)** — vocabulário staff-only: *válidos projetados*, *teto do campo*, *captura*, *share intracampo*, *roll-off*, *meta* (`expectedVotes[cenário] ?? meta sugerida`), *cobertura da meta* (`comprometido ÷ meta`, comprometido = SÓ pledges). Glossário do usuário em `/campanha/conceitos` (`lib/campaignIntelligenceConcepts.ts`). - **Conta da cadeira (E8)** — vocabulário staff-only: _válidos projetados_, _teto do campo_, _captura_, _share intracampo_, _roll-off_, _meta_ (`expectedVotes[cenário] ?? meta sugerida`), _cobertura da meta_ (`comprometido ÷ meta`, comprometido = SÓ pledges). Glossário do usuário em `/campanha/conceitos` (`lib/campaignIntelligenceConcepts.ts`).
- **Demanda** — pedido de material/serviço, staff-only, escalada decidida por coordinator/candidate. **Plano de Ação** — evento/agenda ancorado em UM município. **Apoiador** — join `Contact`↔campanha (consent LGPD fail-closed por chave estável). **Dobradinha** — deputado estadual parceiro (`stateDeputy`). **Assessor responsável** — carteira em `municipality.advisors`. - **Demanda** — pedido de material/serviço, staff-only, escalada decidida por coordinator/candidate. **Plano de Ação** — evento/agenda ancorado em UM município. **Apoiador** — join `Contact`↔campanha (consent LGPD fail-closed por chave estável). **Dobradinha** — deputado estadual parceiro (`stateDeputy`). **Assessor responsável** — carteira em `municipality.advisors`.
- **Contact** é o registro normalizado de PESSOA compartilhado com o site público — features novas criam JOINS para `contact`, nunca uma segunda tabela de pessoa. - **Contact** é o registro normalizado de PESSOA compartilhado com o site público — features novas criam JOINS para `contact`, nunca uma segunda tabela de pessoa.
@ -90,7 +90,7 @@ Dois contexts principais + um de suporte, espelhados nos prefixos de módulo e n
## Log de decisões estruturais ## Log de decisões estruturais
| Data | Decisão | | Data | Decisão |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 2026-07-16 | Auth da campanha isolada do admin: collection `campaignUser` + cookie `campaign-token` com path próprio | | 2026-07-16 | Auth da campanha isolada do admin: collection `campaignUser` + cookie `campaign-token` com path próprio |
| 2026-07-23 | Toda collection declara `access` explícito; default do Payload tratado como bug (JWT de campanha alcança `/api/*`) | | 2026-07-23 | Toda collection declara `access` explícito; default do Payload tratado como bug (JWT de campanha alcança `/api/*`) |
| 2026-07-23 | Município como unidade operacional predefinida (remodel destrutivo aplicado em produção) | | 2026-07-23 | Município como unidade operacional predefinida (remodel destrutivo aplicado em produção) |

View file

@ -67,7 +67,7 @@ Statuses: pending · in-progress · awaiting-evidence · done · deferred: \<rea
## Workstream Status ## Workstream Status
| WS | Content | Plan file | Status | Date | | WS | Content | Plan file | Status | Date |
| --- | --------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- | ------- | ---- | | --- | --------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | ------ | ---------- |
| W0 | Safety net: pin list URL parsers + list loaders (unit + int smokes); TESTING/TECH-DEBT truth-up | [pinagem-superficies-lista.md](plans/pinagem-superficies-lista.md) | done | 2026-07-25 | | W0 | Safety net: pin list URL parsers + list loaders (unit + int smokes); TESTING/TECH-DEBT truth-up | [pinagem-superficies-lista.md](plans/pinagem-superficies-lista.md) | done | 2026-07-25 |
| W1 | Generalized campaign list system (D1 core + municipality; D2 migrate entity triplet/demandas/apoiadores/assessores + delete superseded) | [sistema-listas-campanha.md](plans/sistema-listas-campanha.md) | done | 2026-07-25 | | W1 | Generalized campaign list system (D1 core + municipality; D2 migrate entity triplet/demandas/apoiadores/assessores + delete superseded) | [sistema-listas-campanha.md](plans/sistema-listas-campanha.md) | done | 2026-07-25 |
| W2 | Architecture decision (DDD/clean-arch/SDP evaluation → conventions + boundary fixes) + staged `components/campaign` subfolders | [decisao-arquitetura-dominios.md](plans/decisao-arquitetura-dominios.md) | done | 2026-07-25 | | W2 | Architecture decision (DDD/clean-arch/SDP evaluation → conventions + boundary fixes) + staged `components/campaign` subfolders | [decisao-arquitetura-dominios.md](plans/decisao-arquitetura-dominios.md) | done | 2026-07-25 |
@ -86,7 +86,7 @@ Statuses: pending · in-progress · awaiting-evidence · done · deferred: \<rea
## Pass 2 Decisions (signed off 2026-07-25) ## Pass 2 Decisions (signed off 2026-07-25)
| ID | Decision | Rationale | | ID | Decision | Rationale |
| --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| D1 | **No `src/domains/` reorg, no ports-and-adapters.** Conventions + mechanical boundary fixes + staged within-layer subfolders for `components/campaign/`; `utilities/` subfoldering deferred with trigger | Payload collections ARE the data model; a big-bang move freezes the repo mid-window and risks the importmap. Full evaluation in [decisao-arquitetura-dominios.md](plans/decisao-arquitetura-dominios.md) | | D1 | **No `src/domains/` reorg, no ports-and-adapters.** Conventions + mechanical boundary fixes + staged within-layer subfolders for `components/campaign/`; `utilities/` subfoldering deferred with trigger | Payload collections ARE the data model; a big-bang move freezes the repo mid-window and risks the importmap. Full evaluation in [decisao-arquitetura-dominios.md](plans/decisao-arquitetura-dominios.md) |
| D2 | **Delete** the ~52 consumer-less `electionInsights` exports (+ their tests) rather than quarantining them | git history + plans carry the formulas; E10 replaces the 35/20/10 threshold approach with relative classification — keeping dead math invites accidental reuse | | D2 | **Delete** the ~52 consumer-less `electionInsights` exports (+ their tests) rather than quarantining them | git history + plans carry the formulas; E10 replaces the 35/20/10 threshold approach with relative classification — keeping dead math invites accidental reuse |
| D3 | `consent: 2` hardcode folded into the Onda 0 provisional-key pattern in-pass, as an isolated delivery with the migration SQL explicitly reviewed by the user before landing | Same fail-closed pattern as `lideranca-autopreenchimento`; leaving the hardcode makes the legal batch harder to verify | | D3 | `consent: 2` hardcode folded into the Onda 0 provisional-key pattern in-pass, as an isolated delivery with the migration SQL explicitly reviewed by the user before landing | Same fail-closed pattern as `lideranca-autopreenchimento`; leaving the hardcode makes the legal batch harder to verify |

View file

@ -5,7 +5,7 @@ Ledger of known engineering debt. Items large enough to be scheduled work become
## Debt Ledger ## Debt Ledger
| Item | Location | Type | Risk | Effort | Priority | Status | Ref | | Item | Location | Type | Risk | Effort | Priority | Status | Ref |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | -------------------- | --------------------------- | ----------------------------------------------------------------------------------------- | -------------------- | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | -------------------- | --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------- |
| 164 unused exports + 60 unused types reported by knip (warn-level; 158 at Pass 1) | god modules, ui kit families | dead code | low | M | P2 | closed 2026-07-25 (Pass 2 W4b): 0 findings; `exports`/`types`/`enumMembers` at **error** in CI; tests entered the knip graph; `duplicates` off (only hits were the 6 deliberate access aliases `canUpdateX = canReadX`) | Pass 2 W4b | | 164 unused exports + 60 unused types reported by knip (warn-level; 158 at Pass 1) | god modules, ui kit families | dead code | low | M | P2 | closed 2026-07-25 (Pass 2 W4b): 0 findings; `exports`/`types`/`enumMembers` at **error** in CI; tests entered the knip graph; `duplicates` off (only hits were the 6 deliberate access aliases `canUpdateX = canReadX`) | Pass 2 W4b |
| knip loader noise: `Error loading src/payload.config.ts` (server-only guard) | knip run output | tooling noise | none (exit 0, static graph resolves) | S | P3 | open | | | knip loader noise: `Error loading src/payload.config.ts` (server-only guard) | knip run output | tooling noise | none (exit 0, static graph resolves) | S | P3 | open | |
| Missing-consent window fixture releases its exclusive lease during the observation window — readers can interleave (rare flake). Full fix: session-level advisory lock spanning delete→op→restore + updated fault-path pins | `tests/helpers/testDatabaseLease.ts` (`withMissingInviteConsentFixture`) | test-infra race | low (ms-wide window; shared leases added 2026-07-23 narrow it) | M | P2 | open | | | Missing-consent window fixture releases its exclusive lease during the observation window — readers can interleave (rare flake). Full fix: session-level advisory lock spanning delete→op→restore + updated fault-path pins | `tests/helpers/testDatabaseLease.ts` (`withMissingInviteConsentFixture`) | test-infra race | low (ms-wide window; shared leases added 2026-07-23 narrow it) | M | P2 | open | |
@ -26,7 +26,7 @@ Ledger of known engineering debt. Items large enough to be scheduled work become
## Smell Inventory ## Smell Inventory
| Smell | Location | Refactoring | Status | | Smell | Location | Refactoring | Status |
| ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------ | ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------ | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| God module: RBAC for every collection in one file (964 lines, ~80 exports) | `src/utilities/campaignAccess.ts` | split per domain under `src/utilities/access/` | done 2026-07-23 (14 domain modules; `campaignAccess.ts` kept as re-export surface) | | God module: RBAC for every collection in one file (964 lines, ~80 exports) | `src/utilities/campaignAccess.ts` | split per domain under `src/utilities/access/` | done 2026-07-23 (14 domain modules; `campaignAccess.ts` kept as re-export surface) |
| God module: ~71 exports of electoral math | `src/lib/electionInsights.ts` | split by concern when next touched | done 2026-07-25 (Pass 2 W4a): module DELETED; survivors in `electionFormat.ts` + `voteTrend.ts` | | God module: ~71 exports of electoral math | `src/lib/electionInsights.ts` | split by concern when next touched | done 2026-07-25 (Pass 2 W4a): module DELETED; survivors in `electionFormat.ts` + `voteTrend.ts` |
| Multi-feature action bag: CRUD + CSV import pipeline + LGPD in one file (722 lines) | `src/app/(campaign)/campanha/actions/supporter.ts` | split CRUD vs import | done 2026-07-23 (`supporterImport.ts`) | | Multi-feature action bag: CRUD + CSV import pipeline + LGPD in one file (722 lines) | `src/app/(campaign)/campanha/actions/supporter.ts` | split CRUD vs import | done 2026-07-23 (`supporterImport.ts`) |

View file

@ -9,16 +9,10 @@
"tests/**/*.spec.ts", "tests/**/*.spec.ts",
"tests/helpers/serverOnly.ts" "tests/helpers/serverOnly.ts"
], ],
"project": [ "project": ["src/**/*.{ts,tsx,js}", "scripts/**/*.mjs", "tests/**/*.ts"],
"src/**/*.{ts,tsx,js}",
"scripts/**/*.mjs",
"tests/**/*.ts"
],
"ignore": [], "ignore": [],
"paths": { "paths": {
"server-only": [ "server-only": ["tests/helpers/serverOnly.ts"]
"tests/helpers/serverOnly.ts"
]
}, },
"ignoreBinaries": [], "ignoreBinaries": [],
"ignoreDependencies": [ "ignoreDependencies": [

View file

@ -11,12 +11,9 @@ import {
removeSupporterData, removeSupporterData,
setSupporterVoteIntention, setSupporterVoteIntention,
} from '@/app/(campaign)/campanha/actions/supporter' } from '@/app/(campaign)/campanha/actions/supporter'
import { import { checkboxFormValue, requiredRelationshipFormValue } from '@/lib/formData'
checkboxFormValue,
requiredRelationshipFormValue,
} from '@/lib/formData'
import { supporterRemoveSchema, supporterVoteIntentionSchema } from '@/lib/schemas/supporter'
import type { SupporterVoteIntention } from '@/lib/schemas/supporter' import type { SupporterVoteIntention } from '@/lib/schemas/supporter'
import { supporterRemoveSchema, supporterVoteIntentionSchema } from '@/lib/schemas/supporter'
import { import {
mapCampaignFormActionError, mapCampaignFormActionError,
type CampaignFormErrorState, type CampaignFormErrorState,
@ -38,9 +35,7 @@ const safeVoteIntentionMessages = [
'Somente a coordenação e a assessoria podem gerenciar apoiadores.', 'Somente a coordenação e a assessoria podem gerenciar apoiadores.',
] as const ] as const
const toMessageOnlyState = ( const toMessageOnlyState = (mapped: CampaignFormErrorState<unknown>): { message?: string } => {
mapped: CampaignFormErrorState<unknown>,
): { message?: string } => {
if (mapped.message) return { message: mapped.message } if (mapped.message) return { message: mapped.message }
if (!mapped.fieldErrors) return {} if (!mapped.fieldErrors) return {}

View file

@ -3,14 +3,10 @@
import { revalidatePath } from 'next/cache' import { revalidatePath } from 'next/cache'
import { createSupporter } from '@/app/(campaign)/campanha/actions/supporter' import { createSupporter } from '@/app/(campaign)/campanha/actions/supporter'
import { import { checkboxFormValue, nullableRelationshipFormValue, optionalFormText } from '@/lib/formData'
checkboxFormValue, import { sanitizeBrazilianPhoneInput } from '@/lib/phone'
nullableRelationshipFormValue,
optionalFormText,
} from '@/lib/formData'
import { supporterCreateSchema } from '@/lib/schemas/supporter' import { supporterCreateSchema } from '@/lib/schemas/supporter'
import { runCampaignFormAction } from '@/utilities/campaignFormActionError' import { runCampaignFormAction } from '@/utilities/campaignFormActionError'
import { sanitizeBrazilianPhoneInput } from '@/lib/phone'
export type SupporterFormState = { export type SupporterFormState = {
status?: 'success' status?: 'success'

View file

@ -10,8 +10,8 @@ import { getPayload } from 'payload'
import { CampaignListEmptyState } from '@/components/campaign/shared/CampaignListEmptyState' import { CampaignListEmptyState } from '@/components/campaign/shared/CampaignListEmptyState'
import { CampaignListFooter } from '@/components/campaign/shared/CampaignListFooter' import { CampaignListFooter } from '@/components/campaign/shared/CampaignListFooter'
import { CampaignPageShell } from '@/components/campaign/shell/CampaignPageShell'
import { CampaignScopeBadge } from '@/components/campaign/shared/CampaignScopeBadge' import { CampaignScopeBadge } from '@/components/campaign/shared/CampaignScopeBadge'
import { CampaignPageShell } from '@/components/campaign/shell/CampaignPageShell'
import { SupporterFilters } from '@/components/campaign/supporter/SupporterFilters' import { SupporterFilters } from '@/components/campaign/supporter/SupporterFilters'
import { SupporterList } from '@/components/campaign/supporter/SupporterList' import { SupporterList } from '@/components/campaign/supporter/SupporterList'
import { SupporterListOverview } from '@/components/campaign/supporter/SupporterListOverview' import { SupporterListOverview } from '@/components/campaign/supporter/SupporterListOverview'

View file

@ -7,11 +7,7 @@ import {
setAdvisorMunicipalityMembership, setAdvisorMunicipalityMembership,
updateAdvisorProfile, updateAdvisorProfile,
} from '@/app/(campaign)/campanha/actions/advisor' } from '@/app/(campaign)/campanha/actions/advisor'
import { import { nullableFormText, requiredFormText, requiredRelationshipFormValue } from '@/lib/formData'
nullableFormText,
requiredFormText,
requiredRelationshipFormValue,
} from '@/lib/formData'
import { ADVISOR_ACTION_SAFE_MESSAGES } from '@/lib/schemas/advisor' import { ADVISOR_ACTION_SAFE_MESSAGES } from '@/lib/schemas/advisor'
import { import {
runCampaignFormAction, runCampaignFormAction,

View file

@ -11,12 +11,12 @@ import {
CampaignListPendingBoundary, CampaignListPendingBoundary,
CampaignListResults, CampaignListResults,
} from '@/components/campaign/shared/CampaignListPending' } from '@/components/campaign/shared/CampaignListPending'
import { CampaignPageShell } from '@/components/campaign/shell/CampaignPageShell'
import { import {
CampaignTable, CampaignTable,
CampaignTableHead, CampaignTableHead,
type CampaignTableColumn, type CampaignTableColumn,
} from '@/components/campaign/shared/CampaignTable' } from '@/components/campaign/shared/CampaignTable'
import { CampaignPageShell } from '@/components/campaign/shell/CampaignPageShell'
import { Badge } from '@/components/ui/Badge' import { Badge } from '@/components/ui/Badge'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { import {

View file

@ -24,6 +24,5 @@ export const updateStateDeputyFormAction = async (
return { message: 'Dobradinha atualizada.' } return { message: 'Dobradinha atualizada.' }
}, },
safeMessages: ['Somente a coordenação e a assessoria gerenciam dobradinhas.'], safeMessages: ['Somente a coordenação e a assessoria gerenciam dobradinhas.'],
genericMessage: genericMessage: 'Não foi possível salvar a dobradinha. Verifique seu acesso e tente novamente.',
'Não foi possível salvar a dobradinha. Verifique seu acesso e tente novamente.',
}) })

View file

@ -39,6 +39,5 @@ export const updateMunicipalityStrategyFormAction = async (
return { message: 'Estratégia atualizada.' } return { message: 'Estratégia atualizada.' }
}, },
safeMessages: municipalityStaffEditSafeMessages, safeMessages: municipalityStaffEditSafeMessages,
genericMessage: genericMessage: 'Não foi possível salvar a estratégia. Verifique seu acesso e tente novamente.',
'Não foi possível salvar a estratégia. Verifique seu acesso e tente novamente.',
}) })

View file

@ -17,17 +17,17 @@ import { Badge } from '@/components/ui/Badge'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { actionPlanKindLabels } from '@/lib/schemas/actionPlan' import { actionPlanKindLabels } from '@/lib/schemas/actionPlan'
import { isCampaignStaff } from '@/utilities/campaignAccess'
import { getCampaignUser } from '@/utilities/campaignAuth'
import {
ActionPlanNotFoundError,
resolveAccessibleActionPlanContext,
} from '@/utilities/actionPlanPageData'
import { getActionPlanDetailPageData } from '@/utilities/actionPlanDetailPageData' import { getActionPlanDetailPageData } from '@/utilities/actionPlanDetailPageData'
import { import {
getActionPlanDetailTabRedirect, getActionPlanDetailTabRedirect,
resolveActionPlanDetailTab, resolveActionPlanDetailTab,
} from '@/utilities/actionPlanDetailTabUi' } from '@/utilities/actionPlanDetailTabUi'
import {
ActionPlanNotFoundError,
resolveAccessibleActionPlanContext,
} from '@/utilities/actionPlanPageData'
import { isCampaignStaff } from '@/utilities/campaignAccess'
import { getCampaignUser } from '@/utilities/campaignAuth'
import { formatBahiaDateTimeLabel } from '@/utilities/campaignTime' import { formatBahiaDateTimeLabel } from '@/utilities/campaignTime'
import { ActionPlanOverviewTab } from './ActionPlanOverviewTab' import { ActionPlanOverviewTab } from './ActionPlanOverviewTab'

View file

@ -7,19 +7,19 @@
// don't grow parameters for. // don't grow parameters for.
import config from '@payload-config' import config from '@payload-config'
import { getPayload } from 'payload'
import { redirect } from 'next/navigation' import { redirect } from 'next/navigation'
import { getPayload } from 'payload'
import { createActionPlan, updateActionPlan } from '@/app/(campaign)/campanha/actions/actionPlan' import { createActionPlan, updateActionPlan } from '@/app/(campaign)/campanha/actions/actionPlan'
import type { ActionPlanFormState } from '@/components/campaign/actionPlan/ActionPlanForm' import type { ActionPlanFormState } from '@/components/campaign/actionPlan/ActionPlanForm'
import { optionalFormText } from '@/lib/formData' import { optionalFormText } from '@/lib/formData'
import { getCampaignUser } from '@/utilities/campaignAuth' import { slugify } from '@/lib/slug'
import { mapCampaignFormActionError } from '@/utilities/campaignFormActionError'
import { import {
parseActionPlanCreateFormData, parseActionPlanCreateFormData,
parseActionPlanUpdateFormData, parseActionPlanUpdateFormData,
} from '@/utilities/actionPlanFormData' } from '@/utilities/actionPlanFormData'
import { slugify } from '@/lib/slug' import { getCampaignUser } from '@/utilities/campaignAuth'
import { mapCampaignFormActionError } from '@/utilities/campaignFormActionError'
const getActionError = (error: unknown): ActionPlanFormState => { const getActionError = (error: unknown): ActionPlanFormState => {
if ( if (

View file

@ -17,9 +17,9 @@ import {
reloadCampaignActor, reloadCampaignActor,
reloadStaffActor, reloadStaffActor,
} from '@/utilities/campaignActionContext' } from '@/utilities/campaignActionContext'
import { hookFilledCreateData } from '@/utilities/hookFilledData'
import { withPayloadTransaction } from '@/utilities/payloadTransaction' import { withPayloadTransaction } from '@/utilities/payloadTransaction'
import { acquireTextAdvisoryLocks } from '@/utilities/postgresTransactionLocks' import { acquireTextAdvisoryLocks } from '@/utilities/postgresTransactionLocks'
import { hookFilledCreateData } from '@/utilities/hookFilledData'
export const createCampaignDemandRecord = async ( export const createCampaignDemandRecord = async (
payload: Payload, payload: Payload,

View file

@ -6,13 +6,13 @@ import {
redeemCampaignInviteAutofill, redeemCampaignInviteAutofill,
redeemCampaignInviteLogin, redeemCampaignInviteLogin,
} from '@/app/(campaign)/campanha/actions/invite' } from '@/app/(campaign)/campanha/actions/invite'
import { campaignInviteAutofillSchema, campaignInviteLoginSchema } from '@/lib/schemas/invite'
import { import {
checkboxFormValue, checkboxFormValue,
nullableFormText, nullableFormText,
requiredFormSecret, requiredFormSecret,
requiredFormText, requiredFormText,
} from '@/lib/formData' } from '@/lib/formData'
import { campaignInviteAutofillSchema, campaignInviteLoginSchema } from '@/lib/schemas/invite'
import { import {
mapCampaignFormActionError, mapCampaignFormActionError,
runCampaignFormAction, runCampaignFormAction,

View file

@ -1,4 +1,4 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres' import { MigrateDownArgs, MigrateUpArgs, sql } from '@payloadcms/db-postgres'
/** /**
* Pass 2 D3 — retire the last hardcoded consent document id. * Pass 2 D3 — retire the last hardcoded consent document id.

View file

@ -1,11 +1,11 @@
import type { Where } from 'payload' import type { Where } from 'payload'
import { isStaffCampaignRole } from '@/lib/campaignRoles'
import { import {
isSupporterVoteIntention, isSupporterVoteIntention,
resolveBahiaMunicipality, resolveBahiaMunicipality,
type SupporterVoteIntention, type SupporterVoteIntention,
} from '@/lib/schemas/supporter' } from '@/lib/schemas/supporter'
import { isStaffCampaignRole } from '@/lib/campaignRoles'
import type { CampaignUser, Supporter } from '@/payload-types' import type { CampaignUser, Supporter } from '@/payload-types'
import { import {
buildListHref, buildListHref,
@ -44,13 +44,7 @@ export type SupporterListState = {
type RawSearchParams = CampaignListRawSearchParams type RawSearchParams = CampaignListRawSearchParams
const supporterListParamNames = [ const supporterListParamNames = ['q', 'voteIntention', 'city', 'municipality', 'page'] as const
'q',
'voteIntention',
'city',
'municipality',
'page',
] as const
const supporterListParamNameSet = new Set<string>(supporterListParamNames) const supporterListParamNameSet = new Set<string>(supporterListParamNames)