- ~70 strings visiveis + labels de admin (headers de coluna, APIErrors, empty states, dashboard, mapa, formularios, filtros) com concordancia de genero corrigida
- apoiadores desambiguado: cidade do contato vira 'Cidade'; a unidade operacional assume 'Municipio' (filtro, coluna, ficha)
- comentarios de codigo atualizados; payload-types regenerado
- fora por decisao D6: textos provisorios de consent do Onda 0 (lote juridico) e migrations congeladas
- e2e do plano de acao acompanha o label ('Municipio *')
- triplo de cenarios: municipalityMapData usa VoteEstimateScenarioFields (2 grafias inline eliminadas)
- MAX_LEADERSHIP_MUNICIPALITIES: Leadership.ts importa de lib/schemas/leadership (const local removida)
- campaignUserInitials: copia divergente do AvatarStack removida; fonte unica em campaignUserProfile (com fallback defensivo)
- tendencia politica: options do select da collection derivam de politicalTrendStatuses + politicalTrendLabels; ProjectionTrendStatus vira alias de PoliticalTrendStatusValue
- MunicipalityStrategyViewModel nomeado e exportado (consumidores param de indexar NonNullable<...['strategy']>); nota de por que NAO deriva do zod
- DynamicFind documentado como a unica grafia aprovada do cast
- stub<T> nos doubles de teste onde a checagem por propriedade e real (campaignUserPhone, campaignAuth, campaignConsent); deep fakes mantem o cast localizado
- formatElectionNumber -> src/lib/electionFormat.ts (13 importers); computeVoteTrend + tipos -> src/lib/voteTrend.ts
- ~52 exports sem consumidor deletados (limiares 35/20/10 da era nucleos, gap vs 2022, conversao, mobilizacao, ticket flip/leverage) - decisao D2; formulas no git history; E10 nasce em modulo novo (nota no plano classificacao-territorial-relativa.md)
- specs: voteTrend.unit.spec.ts (pins vivos + pin do defeito E18 de fracao), electionPartySpectrum.unit.spec.ts sem os blocos de ticket; electionInsights.unit.spec.ts deletado
- fix de regressao W2 pega pelo knip: scripts/import-projecao.mjs importava voteEstimate/slug nos paths antigos (knip agora roda sem pipe mascarando exit code)
- knip unused exports: 157 -> 140
106 arquivos flat -> 15 dominios (actionPlan, advisor, auth, dashboard, demand, invite, leadership, map, municipality, organization, stateDeputy, supporter, votePledge, shared, shell) via git mv; imports absolutos reescritos em 98 arquivos; excecao de lint do campaign-logo e paths dos specs de contrato (campaignInviteUi, campaignComponents) atualizados. Sem mudanca de conteudo nos componentes.
- CampaignTable/CampaignTableHead: colunas como dado (id, head island, cell, seams B17 mandatory/defaultVisible); colSpan derivado
- CampaignListFooter: contagem + paginacao compartilhadas
- MunicipalityList reescrita sobre column defs; cards mobile inalterados
- municipalityUi.ts (765/59 exports) dividido: municipalityListUrl / municipalityListFilters / municipalityLabels / municipalitySignal; contrato de URL byte-identico (pins verdes)
- B16+ absorvido: useOptimistic no HeaderFilter (onNavigate dentro da transition), hrefs de opcao via serializador canonico confiavel (1 serializacao por opcao, pin de byte-igualdade), facet de municipio como slugs rotulados no cliente (-20KB), facets no mesmo Promise.all (seed por promise), catalogo DRY, clearMunicipalityListFilters
- timeout explicito no int test de facets (2 bundles full-scope sob suite 47-way)
A revisão paralela do /simplify achou três defeitos funcionais na entrega
dos filtros no header, todos corrigidos aqui:
- as facetas omitiam só o param multi, então "Prioritária" escondia os
municípios não-prioritários do popover onde o próprio check mora e
"Sem assessor" esvaziava o popover de Assessores; cada faceta passa a
omitir o grupo de params do seu popover (int test cobre os dois casos);
- "todas as tendências" tinha duas codificações — as três marcadas
deixavam trend= inútil na URL com o funil se declarando inativo; o
parse agora canonicaliza o conjunto completo para ausente;
- o filtro de Território havia sumido do mobile ao virar multi.
Também devolve o "Limpar" aos popovers curtos (estava preso ao limiar da
busca) e registra o que sobrou como B16+ (escala/DRY), com o
CampaignListEmptyState compartilhado e o firstValue duplicado absorvidos
no C8, e a fragilidade do build sem o global metadata no site público.
Popover de filtro por coluna no desktop (multi-seleção OR em município,
território, assessores e tendência; busca acento-insensível e "Limpar"),
mantendo os selects empilhados no mobile. Header sticky com a página como
scroller e empty state que substitui só as linhas de conteúdo, preservando
overview e filtros. Remove a coluna "Assessoria": a ordenação foi para
"Assessores" e o com/sem assessor virou opção do mesmo popover.
Lista+detalhe única de edição para coordinator/candidate: nome, e-mail e
celular com auto-save debounced (edit-where-you-see-it); carteira de
municípios por chips com agregação de território de identidade,
adição/remoção com UI otimista; criação inline no topo da tabela; ação de
WhatsApp por assessor; reset de senha via e-mail (bloqueado para
placeholders @planilha.invalid). Alinha access de update/phone/atribuição
de município a isCampaignUnrestricted (coordinator + candidate).
Sem migration. Testes int (campaignAdvisorManagement) + unit (schema e
portfólio de municípios) cobrindo access, conflito de e-mail único, cap de
assessores por município e agregação por território/ZE.
Cross-checked by parallel code-quality/performance/reuse reviewers against
the E9 commit. Behavior-preserving:
- laterTimestamp/resolveMunicipalityLastSignalAt were the same "latest of
two ISO timestamps" written twice; both now delegate to a new
latestIsoTimestamp in campaignTime.ts, which documents the fixed-width
UTC invariant that makes the string compare sound.
- Hoisted the frescor comparator's Date.now() out of the per-comparison
accessor so the sort key stops drifting mid-sort.
- Deleted the unread baseTotal/growthFactor/belowBase passthrough from the
statewide goal entry point and fixed a comment citing a symbol
(goalDecompositionBelowBase) that never existed; renamed
computeStatewideGoalDecomposition -> computeStatewideSuggestedGoals now
that nothing is proportionally decomposed.
- Collapsed the advisor badge's two copies (desktop table vs mobile card)
into one AdvisorStatusBadge; they had quietly diverged on which icon
renders for the "no advisor" state.
- Renamed the sort-menu's stale "Cobertura" label for advisor coverage to
"Assessoria" (E8 already renamed the list column for the same reason);
derived the sort-key set from the label record instead of a third
parallel list.
- Consolidated three zeroed-scenario-record literals into one
zeroByVoteEstimateScenario() factory in voteEstimate.ts.
- Routed three separate votesByYear[2022] reads through one votesInYear
helper in municipalityPotential.ts.
- Gated the goal card's empty-state copy on !usesMesaEstimate so it stops
telling a município with an existing mesa estimate to enter one.
- Swapped a test assertion pinned to a raw Tailwind token for a stable
data-signal="cold" hook, and tightened the "desert" test's bound to
check against the actual growth factor (the old bound was true for
every slug regardless of the formula).
Left alone (roadmap decision, not cleanup): sanityCheckSuggestedGoalsByTerritory
has no production caller yet (deferred to E11/E12); comment shortened
instead of deleting the dead-but-documented code.
Verified: tsc --noEmit, pnpm lint (0 warnings), 337 unit + 366 integration
tests, pnpm build all green.
A lista de municípios vira a fila de decisão, sem rota nova, sem coluna nova
e sem migration.
Fase 0 corrige a meta sintética do E8, que repartia a meta estadual
proporcionalmente só ao teto do campo e ignorava a votação própria (meta 2.911
para Vitória da Conquista, de 5.005 votos em 2022; 813 para Campo Formoso, de
47). `deriveSuggestedGoalsByScenario` substitui `decomposeStateGoal` e ancora a
meta na votação de 2022 por cenário — pessimista = base × (1 − margin), central
= base, otimista = base × (stateGoal ÷ Σ base), com clamp. `goalCoverage` passa
a receber `SuggestedGoalByScenario`, deixando `expectedVotes[S] ??
suggestedGoal[S]` simétrico. Só descrições do global mudaram.
Fase 1 adiciona frescor e ordenações: `declaredAt`/`estimatedAt` no select do
agregado de pledges (`lastPledgeAt`), `lastSignalAt` no view model via
`resolveMunicipalityLastSignalAt` (mesmo helper para o comparador do servidor e
a célula), e as sort keys `deficit` (novo default do staff) e `frescor`,
derivadas em memória no cenário central.
Fase 2 dobra os sinais nas células existentes: "há N dias" na coluna de última
atualização (frio ≥ 21 dias, em âmbar — vermelho já é da prioridade), badge
"sem responsável" em prioridade alta sem assessor, coluna da vergonha no
detalhe da métrica de assessoria, tooltip de cobertura nomeando o cenário e
copy Praças→Municípios.
Cortes: votos em jogo → B13, LQ/captura → E10, coluna dedicada de déficit
desnecessária.
Nova rota staff-only /campanha/conceitos (glossário curado em
src/lib/campaignIntelligenceConcepts.ts, revisado junto das fórmulas
que descreve em municipalityPotential.ts/goalCoverage.ts) com
descoberta por "Saiba mais" nos tooltips do card "Conta da cadeira" e
entrada fixa no rodapé da sidebar (staffSecondaryNav). Corrige defeito
E8 de formatElectionNumber (meta fracionária lida como cem mil em
pt-BR). Ajustes pós-/simplify: MetricExplanation.conceptID obrigatório,
href da sidebar desacoplado do módulo de conteúdo (client bundle).
- MunicipalityHoverTooltip/MunicipalityGoalAccountCard: hover/focus tooltips on
the 4 "Conta da cadeira" diagnostic numbers, hardened per /impeccable
critique (touch dead-end fix via controlled open + pointerup toggle +
outside-tap dismiss, tooltip no longer covers "Cobertura da meta", clearer
two-tier copy, distinguishable button trigger, thicker 0% progress bar).
- seed-tse-results.mjs/electionResultsBuild/electionResultsParse: seed also
imports presidente/governador for 2014/2018 (previously deputado federal
only), with vote-em-transito duplicate merging so the unique constraints
hold; artifact/formulas stay 2022-only by design.
- Registered E18 (documentacao-conceitos-campanha) roadmap item/plan for a
future /campanha/conceitos glossary page.
First regional surface in /campanha: a sortable 27-TI overview table on the
Início staff dashboard, next to the municipal map. Per-TI aggregates only
(sums and ratios of aggregates — MAUP safeguard); Metropolitano decomposed
into Salvador (19 zones) vs. demais RMS. Loader is server-only with
overrideAccess:true (regional context, not management; TI-level exposure
only); pure rollup stays client-safe for the sortable table. First slice of
E12, which extends with capture/LQ/meta coverage.
Meta Bom/Regular/Mínimo duplicated the estimate scenarios — keep a single municipality series (pessimista/média/otimista), backfill then drop the old columns, and map the spreadsheet onto expectedVotes.
E2E-driven fixes (the suite now passes 9/9; two journeys remain
latency-flaky on cold dev compiles and pass on retry):
- leader home crashed with Forbidden since the remodel:
loadLeaderContactsPageData loaded municipality options through the
staff-scoped loader (leaders are denied municipality reads); their scope
now derives from the engaged leadership's linked municipalities
- leaders saw 'Contato — —' instead of their supporters' names:
getAccessibleContactIds now mirrors canReadSupporter for leaders
(contacts of supporters they created)
- leader nav had two items with the same /campanha href (duplicate React
keys); the leader home IS the contact tool — one entry
- RSC serialization contracts: CampaignListPagination is a server component
again (hrefForPage stays server-side; CampaignTransitionAnchor client leaf
intercepts clicks with serializable props); CampaignSearchForm takes
basePath instead of a function prop
- hasAnyEstimate moved from the 'use client' PledgeEstimateForm to
voteEstimate.ts — server components may not call client-module exports
- playwright.config honors TEQO_TEST_DATABASE_URL (parity with
vitest.setup.ts) and uses a fixed .next/e2e dist dir so Next stops
appending per-PID entries to tsconfig include; report artifacts
eslint-ignored
- MunicipalityMapSelection leaf owns hover/selection: a mouseover re-renders
only the map + readout, not the whole panel (controls, legend, zone list);
Leaflet paint stays ref-based (B6)
- municípios list: MunicipalityEstimateScenarioProvider now wraps only the
results — scenario switches no longer re-render the filter controls
(dashboard already scoped it to the map)
- LeaderContactsPanel is a server component again: header + contacts table
render on the server; only LeaderContactForm (new client file) hydrates
- ledgered with rationale: map-bundle slimming deferred (gzip crushes the
repeating keys; instant year/scenario switching is a core analysis flow);
props-to-state effect mirrors reviewed and accepted as the correct
server-echo reconciliation pattern
Closes the 'Feel the action' gaps (.cursor/rules/campanha-action-feedback.mdc):
- BUG: action-plan task checkbox was optimistic but never revalidated — a
successful toggle visually reverted when the transition ended. The action
now revalidates the plan page; checkbox disables while pending
- map compare + candidate compare picker: optimistic select value +
useTransition; the map region dims with aria-busy and a live region
instead of flashing the full-page skeleton
- CampaignListPendingBoundary/CampaignListResults: one shared transition so
filters (municípios/apoiadores/planos), pagination, demandas status chips
(new CampaignFilterChips), and the name-search pages (new
CampaignSearchForm on lideranças/organizações/dobradinhas) dim the RESULTS
region, not only the control — children stay server-rendered (composition)
- streaming: dashboard map section behind Suspense (KPI shell paints first;
React cache() keeps the municipality scope shared, not reloaded);
municipality detail tabs (elections/leaderships/updates) stream below the
header; list-shaped loading.tsx for /municipios and /apoiadores
- logout button gets a pending state; BahiaMap init shows a visible spinner
(was sr-only)
- committed artifact src/lib/electionAggregates/bahia-federal-baseline.json
(Solla nominal + federal T1 valid votes per catalog municipality × TSE year,
Salvador split by zone) generated by pnpm build:election-aggregates from the
locally seeded TSE data; typed loader src/lib/bahiaElectionAggregates.ts;
snapshot spec pins artifact ↔ catalog ↔ baseline ticket
- map bundle: historical years now read the artifact (was 6 statewide
city×zone scans per dashboard visit); compare mode keeps only the OTHER
candidate on the DB path (Solla side from the artifact)
- loadMunicipalityScope (React cache()): one municipality find + pledge
aggregate per request shared by dashboard KPIs, map bundle, and the
municípios list overview (was 2-3 duplicate loads)
- unstable_cache + election-tse tag on the immutable elections-tab loaders
(baseline, candidate comparison, candidate options); tag added to the
/api/revalidate allowlist — runbook: re-seed then bust the tag
- municipalityMapContract.ts: client-safe map vocabulary/bundle types so the
client panel no longer imports the server data module (build had pulled
@payload-config into the client graph); municipalityMapData is server-only
and re-exports the contract; PLAZA_MAP_* renamed to MUNICIPALITY_MAP_*
- petition generateStaticParams enumerates bare ids (getPetitionIds)
- knip (files/deps at error level; unused exports ledgered as warn) with
config for Payload/Next entries; deleted the dead modules it confirmed:
RecentlyVisited + UpcomingActionPlansCard + actionPlanUpcomingPreview,
lazy-dialog helpers, tseZone, federalCandidateTotalsAggregate (test-only),
unused ui kit files, one-shot rename script; pruned unused radix deps and
typescript-eslint; added pg/@types/pg (pinned to drizzle's 8.10.2)
- GitHub Actions CI on the mirror: lint, typecheck, knip, unit, migrate, int
against a Postgres 17 service
- eslint: unused-vars with ^_ ignore patterns (migrations args exempt),
repo-wide ban on `as never` (no-restricted-syntax), lint gate at
--max-warnings=0; fixed all 54 pre-existing warnings (dead imports,
hooks deps, tracking-pixel img disable with impeccable config exception)
- tsconfig: include consolidated from 219 lines to 5 (wildcard covers all
.next dist variants), noUnusedLocals on
- typed replacements for every as-never: hookFilledCreateData (actions
create data completed by collection hooks), drizzle scopeColumn narrowing,
tests' stub<T> helper (property-level checking kept, completeness waived)
- test infra: leased-consent generalization used by onda0 spec (shared
leases over the stable consent keys; window race ledgered), purge fix
- docs: IMPROVE-CODE-QUALITY-PLAN.md tracker, TECH-DEBT.md ledger,
TESTING.md safety-net map (package.json also gains the Phase 2
build:election-aggregates script entry; the script lands next commit)
Rename the operational unit "Praça"/"Núcleo" to "Município" (code identifier
`municipality`) and land the 2026-07-23 course changes:
- New `candidate` role with unrestricted visibility (`isCampaignStaff` now
includes it) alongside coordinator/advisor; leader is locked down to the
supporter contact tool only.
- Demandas become staff-only; dobradinhas modeled via a `stateDeputy` entity.
- Camaçari consolidated to a single município (ZE 170/171 aggregated);
Salvador keeps its 19 zone municípios.
- Map moves to the staff dashboard; `/campanha/municipios` is list/overview.
- Vote pledges keep the declared vs estimated (scenario) asymmetry; leaders
never see estimates.
Destructive migration for the campaign vertical (drops nucleus/plaza-era
tables, wipes campaign rows, seeds 435 municípios). Public-site data untouched.
Includes the post-delivery /simplify cleanups: shared reloadStaffActor /
reloadCoordinatorActor helpers, req.context cache for getFreshCampaignUser,
parallelized dashboard loads, candidate dashboard-copy fix, and dead
leader-dashboard / roleKind code removal.
Unify list and /editar server actions in plazaStaffFormActions.ts so B9 inline edits and the edit page share one implementation without behavior changes.
Ship static zone-to-neighborhood mapping for Salvador/Camaçari Praças-zona, overview UI card, tests/fixture, and roadmap/plan updates including F2 prep follow-ups from capture-review-debts.
Keep GeoJSON stable across metric/scale/hover changes via pathByKeyRef and O(2) restyle; extract bahiaMapStyle helpers with unit tests and close B10/B11 perf debt refs in plans.
Deduplicate pledge aggregation via loadPlazaListPageBundle, add plazaRevalidation with slug-scoped detail paths after inline saves, and document the fill-in as shipped.
Adds valid-votes denominators to the map bundle, a Total vs % dos válidos selector with fixed 0–100% coloring, and readout/legend alignment via scaleMax; updates roadmap and post-simplify debt docs.
Adds polygon highlight, vote readout, and navigation (desktop click / mobile 2nd tap) on the filtered Praças choropleth, with simplify cleanup and B6 plan updates for incremental setStyle.
Add staff-only expectedVotes with migration, edit flow, and expectedVotes ?? pledge fallback across map, overview, and dashboard; document delivery and the A9+ loader dedup fill-in on the roadmap.
Let marketing configure a numeric facebookPixelId per petition in Payload, fire PageView on load and Lead after a successful signature, and mark the roadmap item delivered with deferred follow-ups documented.
436 seeded Praças (municipality-based; per-TSE-zone in Salvador/Camaçari) become
the operational unit; roles renamed to coordinator/advisor/leader with advisors
scoped to administered Praças. Leadership is one record per person across many
Praças/organizations; vote pledges split leader-declared vs staff-estimated
(estimates never serialized to leaders). Adds organizations, demand workflow
with staff-only cost/receipts, action-plan results with deputy presence, manual
political trend, multi-candidate comparison and the diverging red/white/blue
map mode. Migration 20260721_020109_remodel_plazas deliberately resets the
campaign vertical in production (public site untouched); test suite ported to
the new model (unit 187 / int 306 / e2e 9 green).
Surface brancos/nulos/abstenções as mobilization opportunity on nucleus detail and list overview, with loader aggregate and unit tests; register pending int coverage in escala-dry-pos-e2.
Extract dashboard cards into focused components (queues, upcoming plans, leadership status, recently visited, choropleth legend), compile the roadmap for outcome-oriented tracking, document the customer job and improve-app journey, and tighten roadmap skills with decision-quality gates.
Fix header alignment and rhythm, swap Megaphone for CampaignLogo, add progressive disclosure for first access, and extract shared auth shells with corrected individual-account copy; record closed critique items in RS+.