mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-16 20:13:04 +00:00
Pass 2 W4a: electionInsights.ts deletado (941 linhas, 71 exports, 2 vivos)
- 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
This commit is contained in:
parent
c706c62098
commit
0c1127b35a
21 changed files with 149 additions and 1455 deletions
|
|
@ -1,6 +1,7 @@
|
|||
# E10 — Classificação territorial relativa (defesa/ataque para DF)
|
||||
|
||||
Status: rascunho
|
||||
Atualizado em: 2026-07-25 (Pass 2 W4a) — **`src/lib/electionInsights.ts` foi deletado**: os ~52 exports sem consumidor (limiares 35/20/10 da era núcleos, gap vs 2022, conversão, mobilização, ticket flip/leverage e os helpers de badge/label citados abaixo) saíram do repo com decisão D2 assinada; as fórmulas ficam no git history (commit "Pass 2 W4a"). Sobreviventes: `formatElectionNumber` → `src/lib/electionFormat.ts`; `computeVoteTrend` → `src/lib/voteTrend.ts`. **E10 nasce em módulo novo** (ex.: `dfTerritorialClass.ts`) em terreno limpo — a premissa "editar electionInsights in place" abaixo está superada.
|
||||
Atualizado em: 2026-07-24 (refs sincronizadas pós-remodelagem Municípios + hardening)
|
||||
Item do roadmap: [docs/roadmap.md](../roadmap.md) (seção "Inteligência de campanha", E10; plano-mestre [inteligencia-campanha.md](inteligencia-campanha.md))
|
||||
Impeccable: B — muda o conteúdo de cards/badges existentes (insights do município, overview da lista); sem rota nova
|
||||
|
|
|
|||
|
|
@ -282,11 +282,11 @@ const {
|
|||
voteEstimatesEqual,
|
||||
voteEstimateScenarioLabels,
|
||||
hasAnyVoteEstimate,
|
||||
} = await import('../src/utilities/voteEstimate.ts')
|
||||
} = await import('../src/lib/voteEstimate.ts')
|
||||
const { withPayloadTransaction } = await import('../src/utilities/payloadTransaction.ts')
|
||||
const { slugify } = await import('../src/utilities/slug.ts')
|
||||
const { slugify } = await import('../src/lib/slug.ts')
|
||||
|
||||
/** @param {import('../src/utilities/voteEstimate.ts').VoteEstimateScenarioViewModel} estimates */
|
||||
/** @param {import('../src/lib/voteEstimate.ts').VoteEstimateScenarioViewModel} estimates */
|
||||
const formatEstimates = (estimates) => {
|
||||
if (!hasAnyVoteEstimate(estimates)) return '(vazio)'
|
||||
return `${voteEstimateScenarioLabels.optimistic}:${estimates.optimistic ?? '—'} | ${voteEstimateScenarioLabels.central}:${estimates.central ?? '—'} | ${voteEstimateScenarioLabels.pessimistic}:${estimates.pessimistic ?? '—'}`
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ import {
|
|||
import { RecentlyVisitedCard } from '@/components/campaign/dashboard/RecentlyVisitedCard'
|
||||
import { Badge } from '@/components/ui/Badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { formatElectionNumber } from '@/lib/electionInsights'
|
||||
import { formatElectionNumber } from '@/lib/electionFormat'
|
||||
import type { StaffDashboardView } from '@/utilities/campaignDashboardData'
|
||||
import {
|
||||
formatGoalCoverageDeficitLabel,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { choroplethGradientCss } from '@/lib/choroplethColorScale'
|
||||
import { formatElectionNumber } from '@/lib/electionInsights'
|
||||
import { formatElectionNumber } from '@/lib/electionFormat'
|
||||
|
||||
type ChoroplethLegendProps = {
|
||||
max: number
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import Link from 'next/link'
|
|||
|
||||
import type { BahiaMapFeatureInfo } from '@/components/campaign/map/BahiaMap'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { formatElectionNumber } from '@/lib/electionInsights'
|
||||
import { formatElectionNumber } from '@/lib/electionFormat'
|
||||
import type { MunicipalityMapNavigation } from '@/utilities/municipalityMapNavigation'
|
||||
import type { MunicipalityMapScaleMode } from '@/utilities/municipalityMapContract'
|
||||
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ import { Field, FieldLabel } from '@/components/ui/field'
|
|||
import { NativeSelect, NativeSelectOption } from '@/components/ui/native-select'
|
||||
import { computeChoroplethMax } from '@/lib/bahiaMapStyle'
|
||||
import { computeValidVoteShares, divergingGradientCss } from '@/lib/choroplethColorScale'
|
||||
import { formatElectionNumber } from '@/lib/electionInsights'
|
||||
import { formatElectionNumber } from '@/lib/electionFormat'
|
||||
import type { FederalCandidateOption } from '@/utilities/electionCandidateOptions'
|
||||
import {
|
||||
MUNICIPALITY_MAP_SCALE_MODES,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { MunicipalityHoverTooltip } from '@/components/campaign/municipality/MunicipalityHoverTooltip'
|
||||
import { computeVoteTrend, formatElectionNumber } from '@/lib/electionInsights'
|
||||
import { formatElectionNumber } from '@/lib/electionFormat'
|
||||
import { computeVoteTrend } from '@/lib/voteTrend'
|
||||
import {
|
||||
DEFAULT_VOTE_RANK_YEAR,
|
||||
formatMunicipalityVoteRank,
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import { MunicipalityUpdateFeed } from '@/components/campaign/municipality/Munic
|
|||
import { SupportStatusBadge } from '@/components/campaign/leadership/SupportStatusBadge'
|
||||
import { Badge } from '@/components/ui/Badge'
|
||||
import type { MunicipalityAgeBandKey } from '@/lib/bahiaMunicipalityDemographics'
|
||||
import { formatElectionNumber } from '@/lib/electionInsights'
|
||||
import { formatElectionNumber } from '@/lib/electionFormat'
|
||||
import { actionPlanKindLabels } from '@/lib/schemas/actionPlan'
|
||||
import type { ActionPlanListViewModel } from '@/utilities/actionPlanViewModels'
|
||||
import { formatBahiaDateTimeLabel } from '@/utilities/campaignTime'
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ import {
|
|||
campaignConceptHref,
|
||||
type CampaignConceptId,
|
||||
} from '@/lib/campaignIntelligenceConcepts'
|
||||
import { formatElectionNumber } from '@/lib/electionInsights'
|
||||
import { formatElectionNumber } from '@/lib/electionFormat'
|
||||
import {
|
||||
formatGoalCoverageDeficitLabel,
|
||||
formatGoalCoverageRatioLabel,
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ import {
|
|||
EmptyMedia,
|
||||
EmptyTitle,
|
||||
} from '@/components/ui/Empty'
|
||||
import { formatElectionNumber } from '@/lib/electionInsights'
|
||||
import { formatElectionNumber } from '@/lib/electionFormat'
|
||||
import { formatMunicipalityVoteRank, formatMunicipalityVoteShare } from '@/lib/municipalityVoteRank'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { CampaignFormActionState } from '@/utilities/campaignFormActionError'
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ import {
|
|||
VoteEstimateScenarioField,
|
||||
} from '@/components/campaign/votePledge/VoteEstimateScenarioField'
|
||||
import { VoteEstimateScenarioStrip } from '@/components/campaign/votePledge/VoteEstimateScenarioStrip'
|
||||
import { formatElectionNumber } from '@/lib/electionInsights'
|
||||
import { formatElectionNumber } from '@/lib/electionFormat'
|
||||
import { cn } from '@/lib/utils'
|
||||
import {
|
||||
formatGoalCoverageDeficitLabel,
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ import {
|
|||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/Table'
|
||||
import { formatElectionNumber } from '@/lib/electionInsights'
|
||||
import { formatElectionNumber } from '@/lib/electionFormat'
|
||||
import {
|
||||
sortTerritoryRows,
|
||||
type TerritoryOverviewRow,
|
||||
|
|
|
|||
9
src/lib/electionFormat.ts
Normal file
9
src/lib/electionFormat.ts
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
/**
|
||||
* Vote counts are whole votes, including the derived ones (E8's decomposed
|
||||
* suggested goal and its deficit are fractional). Without pinning the fraction
|
||||
* digits, pt-BR renders a goal of 100.968 votes as "100,968" — read as a
|
||||
* hundred thousand by every human in the room.
|
||||
*/
|
||||
const numberFormatter = new Intl.NumberFormat('pt-BR', { maximumFractionDigits: 0 })
|
||||
|
||||
export const formatElectionNumber = (value: number): string => numberFormatter.format(value)
|
||||
|
|
@ -1,941 +0,0 @@
|
|||
import { BASELINE_TICKET_2022 } from '@/lib/electionResults'
|
||||
import { partySpectrum } from '@/lib/electionPartySpectrum'
|
||||
|
||||
export const NO_ELECTION_BASELINE_MESSAGE =
|
||||
'Sem baseline TSE (informe território/município)' as const
|
||||
|
||||
/** ±10% band between consecutive elections → stable (product default, E2). */
|
||||
export const VOTE_TREND_STABLE_BAND = 0.1
|
||||
|
||||
/** Below this share of aptos → growth opportunity (literature reference, A5). */
|
||||
export const CONVERSION_OPPORTUNITY_MAX = 0.15
|
||||
|
||||
/** At or above this share of aptos → stronghold (literature reference, A5). */
|
||||
export const CONVERSION_REDUTO_MIN = 0.4
|
||||
|
||||
/** Share of federal nominal votes outside the chapa field → flip opportunity (A5 Fase 2). */
|
||||
export const RIGHT_SHARE_THRESHOLD = 0.25
|
||||
|
||||
/** At or above this share of valid federal votes → defesa (literature reference, A5-2). */
|
||||
export const TERRITORIAL_DEFESA_MIN = 0.35
|
||||
|
||||
/** At or above this share → indecisa (between defesa and ataque). */
|
||||
export const TERRITORIAL_INDECISA_MIN = 0.2
|
||||
|
||||
/** At or above this share → ataque; below → perdida. */
|
||||
export const TERRITORIAL_ATAQUE_MIN = 0.1
|
||||
|
||||
export type VoteTrendStatus = 'decline' | 'stable' | 'increase' | 'noBaseline'
|
||||
|
||||
export type VoteTrendSeries = {
|
||||
y2014: number
|
||||
y2018: number
|
||||
y2022: number
|
||||
}
|
||||
|
||||
export type VoteTrendResult = {
|
||||
status: VoteTrendStatus
|
||||
message: string
|
||||
ratio: number | null
|
||||
}
|
||||
|
||||
export type GapVs2022Status =
|
||||
| 'above'
|
||||
| 'below'
|
||||
| 'noBaseline'
|
||||
| 'noEstimate'
|
||||
| 'noCandidateVotes'
|
||||
|
||||
export type GapVs2022Result = {
|
||||
gap: number | null
|
||||
ratio: number | null
|
||||
status: GapVs2022Status
|
||||
message: string
|
||||
}
|
||||
|
||||
export type ConversionRateBand =
|
||||
| 'reduto'
|
||||
| 'consolidado'
|
||||
| 'oportunidade'
|
||||
| 'semEstimativa'
|
||||
| 'semBaseline'
|
||||
| 'semAptos'
|
||||
|
||||
export type ConversionRateInput = {
|
||||
aptos: number | null
|
||||
abstencoes: number | null
|
||||
confirmedVoteEstimate: number | null
|
||||
}
|
||||
|
||||
export type ConversionRateResult = {
|
||||
rate: number | null
|
||||
rateTurnout: number | null
|
||||
band: ConversionRateBand
|
||||
message: string
|
||||
supportLine: string | null
|
||||
}
|
||||
|
||||
export type ConversionBandDistribution = {
|
||||
reduto: number
|
||||
consolidado: number
|
||||
oportunidade: number
|
||||
}
|
||||
|
||||
export type MobilizationOpportunityStatus =
|
||||
| 'opportunity'
|
||||
| 'zero'
|
||||
| 'semBaseline'
|
||||
| 'semAptos'
|
||||
|
||||
export type MobilizationOpportunityInput = {
|
||||
abstencoes: number | null
|
||||
brancos: number | null
|
||||
nulos: number | null
|
||||
aptos: number | null
|
||||
}
|
||||
|
||||
export type MobilizationOpportunityResult = {
|
||||
absolute: number
|
||||
relative: number | null
|
||||
abstencoes: number
|
||||
brancosNulos: number
|
||||
status: MobilizationOpportunityStatus
|
||||
message: string
|
||||
supportLine: string | null
|
||||
}
|
||||
|
||||
export type TerritorialClassificationBand =
|
||||
| 'defesa'
|
||||
| 'ataque'
|
||||
| 'indecisa'
|
||||
| 'perdida'
|
||||
| 'semBaseline'
|
||||
|
||||
export type ComparableTerritorialClass = Exclude<TerritorialClassificationBand, 'semBaseline'>
|
||||
|
||||
export type TerritorialClassificationInput = {
|
||||
sollaVotes: number
|
||||
federalValidVotes: number | null
|
||||
}
|
||||
|
||||
export type TerritorialClassificationResult = {
|
||||
percentValid: number | null
|
||||
band: TerritorialClassificationBand
|
||||
title: string
|
||||
priorityLine: string
|
||||
supportLine: string | null
|
||||
}
|
||||
|
||||
export type TerritorialClassificationDistribution = {
|
||||
defesa: number
|
||||
ataque: number
|
||||
indecisa: number
|
||||
perdida: number
|
||||
}
|
||||
|
||||
/** Minimal baseline shape for Gap vs 2022 (full detail VM is assignable). */
|
||||
export type GapVs2022Baseline = {
|
||||
candidate: { votes: number }
|
||||
} | null
|
||||
|
||||
/**
|
||||
* Vote counts are whole votes, including the derived ones (E8's decomposed
|
||||
* suggested goal and its deficit are fractional). Without pinning the fraction
|
||||
* digits, pt-BR renders a goal of 100.968 votes as "100,968" — read as a
|
||||
* hundred thousand by every human in the room.
|
||||
*/
|
||||
const numberFormatter = new Intl.NumberFormat('pt-BR', { maximumFractionDigits: 0 })
|
||||
|
||||
export const formatElectionNumber = (value: number): string => numberFormatter.format(value)
|
||||
|
||||
const formatPercent = (ratio: number): number => Math.round(ratio * 100)
|
||||
|
||||
export const formatVoteTrendSeries = (series: VoteTrendSeries): string =>
|
||||
`${formatElectionNumber(series.y2014)} (2014) → ${formatElectionNumber(series.y2018)} (2018) → ${formatElectionNumber(series.y2022)} (2022)`
|
||||
|
||||
export const formatVoteTrendSeriesCompact = (series: VoteTrendSeries): string =>
|
||||
`2014: ${formatElectionNumber(series.y2014)} → 2018: ${formatElectionNumber(series.y2018)} → 2022: ${formatElectionNumber(series.y2022)}`
|
||||
|
||||
export type VoteTrendDistribution = Record<VoteTrendStatus, number>
|
||||
|
||||
export const emptyVoteTrendDistribution = (): VoteTrendDistribution => ({
|
||||
decline: 0,
|
||||
stable: 0,
|
||||
increase: 0,
|
||||
noBaseline: 0,
|
||||
})
|
||||
|
||||
export const comparableTrendCount = (trend: VoteTrendDistribution): number =>
|
||||
trend.increase + trend.stable + trend.decline
|
||||
|
||||
export const emptyConversionBandDistribution = (): ConversionBandDistribution => ({
|
||||
reduto: 0,
|
||||
consolidado: 0,
|
||||
oportunidade: 0,
|
||||
})
|
||||
|
||||
export const aggregateConversionBand = (
|
||||
bands: readonly ConversionRateBand[],
|
||||
): ConversionBandDistribution => {
|
||||
const distribution = emptyConversionBandDistribution()
|
||||
for (const band of bands) {
|
||||
if (isComparableConversionBand(band)) {
|
||||
distribution[band] += 1
|
||||
}
|
||||
}
|
||||
return distribution
|
||||
}
|
||||
|
||||
export const isComparableConversionBand = (
|
||||
band: ConversionRateBand,
|
||||
): band is 'reduto' | 'consolidado' | 'oportunidade' =>
|
||||
band === 'reduto' || band === 'consolidado' || band === 'oportunidade'
|
||||
|
||||
const emptyTerritorialClassificationDistribution =
|
||||
(): TerritorialClassificationDistribution => ({
|
||||
defesa: 0,
|
||||
ataque: 0,
|
||||
indecisa: 0,
|
||||
perdida: 0,
|
||||
})
|
||||
|
||||
export const aggregateTerritorialClass = (
|
||||
bands: readonly TerritorialClassificationBand[],
|
||||
): TerritorialClassificationDistribution => {
|
||||
const distribution = emptyTerritorialClassificationDistribution()
|
||||
for (const band of bands) {
|
||||
if (isComparableTerritorialClass(band)) {
|
||||
distribution[band] += 1
|
||||
}
|
||||
}
|
||||
return distribution
|
||||
}
|
||||
|
||||
export const isComparableTerritorialClass = (
|
||||
band: TerritorialClassificationBand,
|
||||
): band is ComparableTerritorialClass =>
|
||||
band === 'defesa' || band === 'ataque' || band === 'indecisa' || band === 'perdida'
|
||||
|
||||
const TERRITORIAL_CLASS_UI = {
|
||||
defesa: {
|
||||
label: 'Defesa',
|
||||
badgeVariant: 'estimate-confirmed',
|
||||
alertVariant: 'default',
|
||||
title: 'Território de defesa',
|
||||
priorityLine: 'Base sólida — prioridade: manter engajamento',
|
||||
},
|
||||
indecisa: {
|
||||
label: 'Indecisa',
|
||||
badgeVariant: 'estimate-pending',
|
||||
alertVariant: 'pending',
|
||||
title: 'Território indeciso',
|
||||
priorityLine: 'Pulverizado — prioridade: consolidar',
|
||||
},
|
||||
ataque: {
|
||||
label: 'Ataque',
|
||||
badgeVariant: 'destructive',
|
||||
alertVariant: 'destructive',
|
||||
title: 'Território de ataque',
|
||||
priorityLine: 'Desfavorável relevante — prioridade: virar/reduzir margem',
|
||||
},
|
||||
perdida: {
|
||||
label: 'Perdida',
|
||||
badgeVariant: 'secondary',
|
||||
alertVariant: 'default',
|
||||
title: 'Território perdido',
|
||||
priorityLine: 'Baixa base histórica — prioridade: minimizar perda',
|
||||
},
|
||||
} as const satisfies Record<
|
||||
ComparableTerritorialClass,
|
||||
{
|
||||
label: string
|
||||
badgeVariant: 'estimate-confirmed' | 'estimate-pending' | 'destructive' | 'secondary'
|
||||
alertVariant: 'default' | 'pending' | 'destructive'
|
||||
title: string
|
||||
priorityLine: string
|
||||
}
|
||||
>
|
||||
|
||||
export const territorialClassLabel = (band: TerritorialClassificationBand): string =>
|
||||
isComparableTerritorialClass(band) ? TERRITORIAL_CLASS_UI[band].label : 'Sem baseline'
|
||||
|
||||
export const territorialClassBadgeVariant = (
|
||||
band: TerritorialClassificationBand,
|
||||
): (typeof TERRITORIAL_CLASS_UI)[ComparableTerritorialClass]['badgeVariant'] =>
|
||||
isComparableTerritorialClass(band) ? TERRITORIAL_CLASS_UI[band].badgeVariant : 'secondary'
|
||||
|
||||
export const territorialClassAlertVariant = (
|
||||
band: TerritorialClassificationBand,
|
||||
): (typeof TERRITORIAL_CLASS_UI)[ComparableTerritorialClass]['alertVariant'] =>
|
||||
isComparableTerritorialClass(band) ? TERRITORIAL_CLASS_UI[band].alertVariant : 'default'
|
||||
|
||||
export const conversionRateAlertVariant = (band: ConversionRateBand): 'default' | 'pending' =>
|
||||
band === 'oportunidade' ? 'pending' : 'default'
|
||||
|
||||
export const isComparableMobilization = (
|
||||
status: MobilizationOpportunityStatus,
|
||||
): status is 'opportunity' => status === 'opportunity'
|
||||
|
||||
type TrendPair = { fromVotes: number; toVotes: number; fromYear: number; toYear: number }
|
||||
|
||||
const trendPairsByPriority = (series: VoteTrendSeries): TrendPair[] => [
|
||||
{ fromVotes: series.y2018, toVotes: series.y2022, fromYear: 2018, toYear: 2022 },
|
||||
{ fromVotes: series.y2014, toVotes: series.y2018, fromYear: 2014, toYear: 2018 },
|
||||
{ fromVotes: series.y2014, toVotes: series.y2022, fromYear: 2014, toYear: 2022 },
|
||||
]
|
||||
|
||||
/**
|
||||
* Classify vote trend from the federal candidate series (2014/2018/2022).
|
||||
* Uses the most recent consecutive pair with votes in both years; ±10% → stable.
|
||||
*/
|
||||
export const computeVoteTrend = (series: VoteTrendSeries): VoteTrendResult => {
|
||||
for (const pair of trendPairsByPriority(series)) {
|
||||
if (pair.fromVotes <= 0 || pair.toVotes <= 0) continue
|
||||
|
||||
const ratio = pair.toVotes / pair.fromVotes
|
||||
const change = ratio - 1
|
||||
const percent = Math.round(Math.abs(change) * 100)
|
||||
|
||||
if (Math.abs(change) <= VOTE_TREND_STABLE_BAND) {
|
||||
return {
|
||||
status: 'stable',
|
||||
ratio,
|
||||
message: `Mantém (${pair.fromYear}→${pair.toYear}, variação de ${percent}%)`,
|
||||
}
|
||||
}
|
||||
|
||||
if (change > VOTE_TREND_STABLE_BAND) {
|
||||
return {
|
||||
status: 'increase',
|
||||
ratio,
|
||||
message: `Aumento (${pair.fromYear}→${pair.toYear}, +${percent}%)`,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
status: 'decline',
|
||||
ratio,
|
||||
message: `Queda (${pair.fromYear}→${pair.toYear}, −${percent}%)`,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
status: 'noBaseline',
|
||||
ratio: null,
|
||||
message: 'Sem série histórica suficiente para tendência',
|
||||
}
|
||||
}
|
||||
|
||||
export const aggregateVoteTrend = (seriesList: readonly VoteTrendSeries[]): VoteTrendDistribution => {
|
||||
const distribution = emptyVoteTrendDistribution()
|
||||
for (const series of seriesList) {
|
||||
distribution[computeVoteTrend(series).status] += 1
|
||||
}
|
||||
return distribution
|
||||
}
|
||||
|
||||
export const voteTrendStatusLabel = (status: VoteTrendStatus): string => {
|
||||
switch (status) {
|
||||
case 'decline':
|
||||
return 'Queda'
|
||||
case 'stable':
|
||||
return 'Mantém'
|
||||
case 'increase':
|
||||
return 'Aumento'
|
||||
case 'noBaseline':
|
||||
return 'Sem baseline'
|
||||
}
|
||||
}
|
||||
|
||||
export const voteTrendAlertVariant = (
|
||||
status: Exclude<VoteTrendStatus, 'noBaseline'>,
|
||||
): 'default' | 'pending' => (status === 'decline' ? 'pending' : 'default')
|
||||
|
||||
export const voteTrendBadgeVariant = (
|
||||
status: VoteTrendStatus,
|
||||
): 'estimate-confirmed' | 'estimate-pending' | 'secondary' => {
|
||||
switch (status) {
|
||||
case 'increase':
|
||||
return 'estimate-confirmed'
|
||||
case 'decline':
|
||||
return 'estimate-pending'
|
||||
case 'stable':
|
||||
case 'noBaseline':
|
||||
return 'secondary'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare a confirmed vote estimate against the campaign candidate's 2022
|
||||
* votes in the same geography.
|
||||
*/
|
||||
export const computeGapVs2022 = (
|
||||
baseline: GapVs2022Baseline,
|
||||
confirmedVoteEstimate: number | null,
|
||||
): GapVs2022Result => {
|
||||
if (!baseline) {
|
||||
return {
|
||||
gap: null,
|
||||
ratio: null,
|
||||
status: 'noBaseline',
|
||||
message: NO_ELECTION_BASELINE_MESSAGE,
|
||||
}
|
||||
}
|
||||
|
||||
if (confirmedVoteEstimate === null) {
|
||||
return {
|
||||
gap: null,
|
||||
ratio: null,
|
||||
status: 'noEstimate',
|
||||
message: 'Sem estimativa confirmada para comparar',
|
||||
}
|
||||
}
|
||||
|
||||
const candidateVotes2022 = baseline.candidate.votes
|
||||
if (candidateVotes2022 <= 0) {
|
||||
return {
|
||||
gap: null,
|
||||
ratio: null,
|
||||
status: 'noCandidateVotes',
|
||||
message: `${BASELINE_TICKET_2022.candidate.name} não recebeu votos aqui em 2022 — território novo a abrir`,
|
||||
}
|
||||
}
|
||||
|
||||
const gap = confirmedVoteEstimate - candidateVotes2022
|
||||
const ratio = confirmedVoteEstimate / candidateVotes2022
|
||||
|
||||
if (gap < 0) {
|
||||
return {
|
||||
gap,
|
||||
ratio,
|
||||
status: 'below',
|
||||
message: `Faltam ${formatElectionNumber(Math.abs(gap))} votos para o patamar de 2022`,
|
||||
}
|
||||
}
|
||||
|
||||
const percentAbove = Math.round((ratio - 1) * 100)
|
||||
return {
|
||||
gap,
|
||||
ratio,
|
||||
status: 'above',
|
||||
message: `Já superamos 2022 em ${percentAbove}%`,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare a confirmed vote estimate against the electorate size (aptos) in the
|
||||
* same geography. Optional turnout line uses aptos − abstencoes.
|
||||
*/
|
||||
export const computeConversionRate = ({
|
||||
aptos,
|
||||
abstencoes,
|
||||
confirmedVoteEstimate,
|
||||
}: ConversionRateInput): ConversionRateResult => {
|
||||
if (aptos === null) {
|
||||
return {
|
||||
rate: null,
|
||||
rateTurnout: null,
|
||||
band: 'semBaseline',
|
||||
message: NO_ELECTION_BASELINE_MESSAGE,
|
||||
supportLine: null,
|
||||
}
|
||||
}
|
||||
|
||||
if (confirmedVoteEstimate === null) {
|
||||
return {
|
||||
rate: null,
|
||||
rateTurnout: null,
|
||||
band: 'semEstimativa',
|
||||
message: 'Sem estimativa confirmada para calcular a conversão',
|
||||
supportLine: null,
|
||||
}
|
||||
}
|
||||
|
||||
if (aptos <= 0) {
|
||||
return {
|
||||
rate: null,
|
||||
rateTurnout: null,
|
||||
band: 'semAptos',
|
||||
message: 'Sem eleitores aptos no baseline para esta geografia',
|
||||
supportLine: null,
|
||||
}
|
||||
}
|
||||
|
||||
const rate = confirmedVoteEstimate / aptos
|
||||
const percent = Math.round(rate * 100)
|
||||
|
||||
let band: ConversionRateBand
|
||||
if (rate < CONVERSION_OPPORTUNITY_MAX) {
|
||||
band = 'oportunidade'
|
||||
} else if (rate >= CONVERSION_REDUTO_MIN) {
|
||||
band = 'reduto'
|
||||
} else {
|
||||
band = 'consolidado'
|
||||
}
|
||||
|
||||
const abst = abstencoes ?? 0
|
||||
const comparecimento = aptos - abst
|
||||
const rateTurnout = comparecimento > 0 ? confirmedVoteEstimate / comparecimento : null
|
||||
|
||||
let supportLine = `${formatElectionNumber(confirmedVoteEstimate)} votos / ${formatElectionNumber(aptos)} eleitores aptos`
|
||||
if (rateTurnout !== null) {
|
||||
supportLine += ` · ${Math.round(rateTurnout * 100)}% do comparecimento`
|
||||
}
|
||||
|
||||
return {
|
||||
rate,
|
||||
rateTurnout,
|
||||
band,
|
||||
message: `Taxa de conversão: ${percent}% do eleitorado apto`,
|
||||
supportLine,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sum abstentions + blank + null votes as mobilization potential (excludes anulados).
|
||||
*/
|
||||
export const computeMobilizationOpportunity = ({
|
||||
abstencoes,
|
||||
brancos,
|
||||
nulos,
|
||||
aptos,
|
||||
}: MobilizationOpportunityInput): MobilizationOpportunityResult => {
|
||||
if (aptos === null) {
|
||||
return {
|
||||
absolute: 0,
|
||||
relative: null,
|
||||
abstencoes: 0,
|
||||
brancosNulos: 0,
|
||||
status: 'semBaseline',
|
||||
message: NO_ELECTION_BASELINE_MESSAGE,
|
||||
supportLine: null,
|
||||
}
|
||||
}
|
||||
|
||||
if (aptos <= 0) {
|
||||
return {
|
||||
absolute: 0,
|
||||
relative: null,
|
||||
abstencoes: 0,
|
||||
brancosNulos: 0,
|
||||
status: 'semAptos',
|
||||
message: 'Sem eleitores aptos no baseline para esta geografia',
|
||||
supportLine: null,
|
||||
}
|
||||
}
|
||||
|
||||
const abstencoesTotal = abstencoes ?? 0
|
||||
const brancosNulos = (brancos ?? 0) + (nulos ?? 0)
|
||||
const absolute = abstencoesTotal + brancosNulos
|
||||
const relative = absolute / aptos
|
||||
|
||||
if (absolute <= 0) {
|
||||
return {
|
||||
absolute: 0,
|
||||
relative: 0,
|
||||
abstencoes: abstencoesTotal,
|
||||
brancosNulos,
|
||||
status: 'zero',
|
||||
message: 'Sem potencial de mobilização no baseline 2022',
|
||||
supportLine: 'Sem brancos, nulos ou abstenções no baseline 2022',
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
absolute,
|
||||
relative,
|
||||
abstencoes: abstencoesTotal,
|
||||
brancosNulos,
|
||||
status: 'opportunity',
|
||||
message: 'Oportunidade de mobilização',
|
||||
supportLine: `${formatElectionNumber(brancosNulos)} brancos/nulos + ${formatElectionNumber(abstencoesTotal)} abstenções = ${formatElectionNumber(absolute)} votos possíveis · ${formatPercent(relative)}% do eleitorado apto`,
|
||||
}
|
||||
}
|
||||
|
||||
export type TicketLeverageStatus =
|
||||
| 'comparable'
|
||||
| 'noEstimate'
|
||||
| 'noBaseline'
|
||||
| 'noTicketVotes'
|
||||
|
||||
export type TicketLeverageInput = {
|
||||
confirmedVoteEstimate: number | null
|
||||
presidentVotes: number | null
|
||||
governorVotes: number | null
|
||||
}
|
||||
|
||||
export type TicketLeverageResult = {
|
||||
headlinePercent: number | null
|
||||
/** Stronger majoritarian base used for the headline ratio (comparable only). */
|
||||
ticketVotes: number | null
|
||||
status: TicketLeverageStatus
|
||||
message: string
|
||||
supportLine: string | null
|
||||
}
|
||||
|
||||
export type MajoritarianWinner = {
|
||||
name: string
|
||||
party: string
|
||||
votes: number
|
||||
} | null
|
||||
|
||||
export type TicketFlipTrigger = 'winner' | 'share' | 'both'
|
||||
|
||||
export type MajoritarianAlignment = 'president' | 'governor' | 'both'
|
||||
|
||||
export type TicketFlipStatus =
|
||||
| 'opportunity'
|
||||
| 'noOpportunity'
|
||||
| 'ambiguous'
|
||||
| 'unknownSpectrum'
|
||||
| 'incomplete'
|
||||
|
||||
export type TicketFlipOpportunityInput = {
|
||||
winnerPresident: MajoritarianWinner
|
||||
winnerGovernor: MajoritarianWinner
|
||||
winnerFederal: MajoritarianWinner
|
||||
federalVotesByParty: Readonly<Record<string, number>>
|
||||
}
|
||||
|
||||
export type TicketFlipOpportunityResult = {
|
||||
status: TicketFlipStatus
|
||||
trigger: TicketFlipTrigger | null
|
||||
majoritarianAlignment: MajoritarianAlignment | null
|
||||
rightShare: number | null
|
||||
rightVotes: number
|
||||
totalFederalVotes: number
|
||||
message: string
|
||||
supportLine: string | null
|
||||
}
|
||||
|
||||
export type TicketLeverageOverviewAggregate = {
|
||||
weightedPercent: number
|
||||
unconvertedCount: number
|
||||
}
|
||||
|
||||
export type TicketFlipOverviewAggregate = {
|
||||
count: number
|
||||
bothAlignedCount: number
|
||||
}
|
||||
|
||||
export type MobilizationOverviewAggregate = {
|
||||
absoluteTotal: number
|
||||
relativePercent: number
|
||||
brancosNulosTotal: number
|
||||
abstencoesTotal: number
|
||||
}
|
||||
|
||||
/** User-facing label for the configured majoritarian ticket base (cycle-specific names). */
|
||||
export const formatMajoritarianTicketBaseLabel = (): string =>
|
||||
`${BASELINE_TICKET_2022.president.name}/${BASELINE_TICKET_2022.governor.name.split(' ')[0]}`
|
||||
|
||||
const MAJORITARIAN_ALIGNMENT_MESSAGE_PREFIX: Record<MajoritarianAlignment, string> = {
|
||||
both: 'Majoritários alinhados. ',
|
||||
president: 'Presidente alinhado. ',
|
||||
governor: 'Governador alinhado. ',
|
||||
}
|
||||
|
||||
const ticketLeverageUnavailable = (
|
||||
status: Exclude<TicketLeverageStatus, 'comparable'>,
|
||||
message: string,
|
||||
): TicketLeverageResult => ({
|
||||
headlinePercent: null,
|
||||
ticketVotes: null,
|
||||
status,
|
||||
message,
|
||||
supportLine: null,
|
||||
})
|
||||
|
||||
/**
|
||||
* Fase 1 — how much of the president/governor majoritarian base the confirmed estimate captures.
|
||||
*/
|
||||
export const computeTicketLeverage = ({
|
||||
confirmedVoteEstimate,
|
||||
presidentVotes,
|
||||
governorVotes,
|
||||
}: TicketLeverageInput): TicketLeverageResult => {
|
||||
if (presidentVotes === null && governorVotes === null) {
|
||||
return ticketLeverageUnavailable('noBaseline', NO_ELECTION_BASELINE_MESSAGE)
|
||||
}
|
||||
|
||||
if (confirmedVoteEstimate === null) {
|
||||
return ticketLeverageUnavailable(
|
||||
'noEstimate',
|
||||
'Sem estimativa confirmada para calcular a alavancagem',
|
||||
)
|
||||
}
|
||||
|
||||
const presidentVoteTotal = presidentVotes ?? 0
|
||||
const governorVoteTotal = governorVotes ?? 0
|
||||
const ticketVotes = Math.max(presidentVoteTotal, governorVoteTotal)
|
||||
|
||||
if (ticketVotes <= 0) {
|
||||
return ticketLeverageUnavailable(
|
||||
'noTicketVotes',
|
||||
'Sem votos da chapa majoritária nesta geografia em 2022',
|
||||
)
|
||||
}
|
||||
|
||||
const headlineRatio = confirmedVoteEstimate / ticketVotes
|
||||
const headlinePercent = formatPercent(headlineRatio)
|
||||
|
||||
const unconverted = headlineRatio < 1
|
||||
const supportParts: string[] = []
|
||||
if (presidentVoteTotal > 0) {
|
||||
supportParts.push(
|
||||
`${BASELINE_TICKET_2022.president.name}: ${formatPercent(confirmedVoteEstimate / presidentVoteTotal)}% (${formatElectionNumber(confirmedVoteEstimate)} / ${formatElectionNumber(presidentVoteTotal)})`,
|
||||
)
|
||||
}
|
||||
if (governorVoteTotal > 0) {
|
||||
supportParts.push(
|
||||
`${BASELINE_TICKET_2022.governor.name}: ${formatPercent(confirmedVoteEstimate / governorVoteTotal)}% (${formatElectionNumber(confirmedVoteEstimate)} / ${formatElectionNumber(governorVoteTotal)})`,
|
||||
)
|
||||
}
|
||||
|
||||
const ticketBaseLabel = formatMajoritarianTicketBaseLabel()
|
||||
|
||||
return {
|
||||
headlinePercent,
|
||||
ticketVotes,
|
||||
status: 'comparable',
|
||||
message: `Alavancagem da chapa: ${headlinePercent}%`,
|
||||
supportLine: unconverted
|
||||
? `Da base ${ticketBaseLabel} ainda não convertida${supportParts.length ? ` · ${supportParts.join(' · ')}` : ''}`
|
||||
: supportParts.join(' · ') || null,
|
||||
}
|
||||
}
|
||||
|
||||
export const isComparableTicketLeverage = (status: TicketLeverageStatus): status is 'comparable' =>
|
||||
status === 'comparable'
|
||||
|
||||
const sumRightFederalVotes = (
|
||||
federalVotesByParty: Readonly<Record<string, number>>,
|
||||
): { rightVotes: number; totalVotes: number; hasUnknownParty: boolean } => {
|
||||
let rightVotes = 0
|
||||
let totalVotes = 0
|
||||
let hasUnknownParty = false
|
||||
|
||||
for (const [party, votes] of Object.entries(federalVotesByParty)) {
|
||||
if (votes <= 0) continue
|
||||
totalVotes += votes
|
||||
const spectrum = partySpectrum(party)
|
||||
if (spectrum === null) {
|
||||
hasUnknownParty = true
|
||||
continue
|
||||
}
|
||||
if (spectrum === 'direita') rightVotes += votes
|
||||
}
|
||||
|
||||
return { rightVotes, totalVotes, hasUnknownParty }
|
||||
}
|
||||
|
||||
const resolveMajoritarianAlignment = (
|
||||
winnerPresident: MajoritarianWinner,
|
||||
winnerGovernor: MajoritarianWinner,
|
||||
): MajoritarianAlignment | null => {
|
||||
const presidentLeft = winnerPresident ? partySpectrum(winnerPresident.party) === 'esquerda' : false
|
||||
const governorLeft = winnerGovernor ? partySpectrum(winnerGovernor.party) === 'esquerda' : false
|
||||
|
||||
if (presidentLeft && governorLeft) return 'both'
|
||||
if (presidentLeft) return 'president'
|
||||
if (governorLeft) return 'governor'
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Fase 2 — majoritarian left alignment + federal proportional still outside the chapa field.
|
||||
*/
|
||||
export const computeTicketFlipOpportunity = ({
|
||||
winnerPresident,
|
||||
winnerGovernor,
|
||||
winnerFederal,
|
||||
federalVotesByParty,
|
||||
}: TicketFlipOpportunityInput): TicketFlipOpportunityResult => {
|
||||
const majoritarianAlignment = resolveMajoritarianAlignment(winnerPresident, winnerGovernor)
|
||||
|
||||
if (!majoritarianAlignment) {
|
||||
return {
|
||||
status: 'incomplete',
|
||||
trigger: null,
|
||||
majoritarianAlignment: null,
|
||||
rightShare: null,
|
||||
rightVotes: 0,
|
||||
totalFederalVotes: 0,
|
||||
message: 'Sem alinhamento majoritário de esquerda nesta geografia',
|
||||
supportLine: null,
|
||||
}
|
||||
}
|
||||
|
||||
const { rightVotes, totalVotes, hasUnknownParty } = sumRightFederalVotes(federalVotesByParty)
|
||||
|
||||
if (totalVotes <= 0) {
|
||||
return {
|
||||
status: 'incomplete',
|
||||
trigger: null,
|
||||
majoritarianAlignment,
|
||||
rightShare: null,
|
||||
rightVotes: 0,
|
||||
totalFederalVotes: 0,
|
||||
message: 'Sem votos nominais federais nesta geografia',
|
||||
supportLine: null,
|
||||
}
|
||||
}
|
||||
|
||||
if (hasUnknownParty) {
|
||||
return {
|
||||
status: 'unknownSpectrum',
|
||||
trigger: null,
|
||||
majoritarianAlignment,
|
||||
rightShare: rightVotes / totalVotes,
|
||||
rightVotes,
|
||||
totalFederalVotes: totalVotes,
|
||||
message: 'Espectro partidário incompleto para avaliar oportunidade',
|
||||
supportLine: null,
|
||||
}
|
||||
}
|
||||
|
||||
const rightShare = rightVotes / totalVotes
|
||||
const triggerWinner =
|
||||
winnerFederal !== null && partySpectrum(winnerFederal.party) === 'direita'
|
||||
const triggerShare = rightShare >= RIGHT_SHARE_THRESHOLD
|
||||
|
||||
if (!triggerWinner && !triggerShare) {
|
||||
return {
|
||||
status: 'noOpportunity',
|
||||
trigger: null,
|
||||
majoritarianAlignment,
|
||||
rightShare,
|
||||
rightVotes,
|
||||
totalFederalVotes: totalVotes,
|
||||
message: 'Sem oportunidade de completar a chapa neste território',
|
||||
supportLine: null,
|
||||
}
|
||||
}
|
||||
|
||||
const trigger: TicketFlipTrigger =
|
||||
triggerWinner && triggerShare ? 'both' : triggerWinner ? 'winner' : 'share'
|
||||
|
||||
const prefix = MAJORITARIAN_ALIGNMENT_MESSAGE_PREFIX[majoritarianAlignment]
|
||||
const opportunityLead = 'Oportunidade de completar a chapa'
|
||||
const shareLine = `${formatPercent(rightShare)}% do proporcional federal ficou fora do campo da chapa.`
|
||||
let message: string
|
||||
let supportLine: string | null = null
|
||||
|
||||
if ((trigger === 'winner' || trigger === 'both') && winnerFederal) {
|
||||
message = `${prefix}${opportunityLead} — o mais votado a dep. federal ficou fora do campo (${winnerFederal.name}, ${winnerFederal.party}).`
|
||||
if (trigger === 'both') supportLine = shareLine
|
||||
} else {
|
||||
message = `${prefix}${opportunityLead} — ${shareLine}`
|
||||
}
|
||||
|
||||
return {
|
||||
status: 'opportunity',
|
||||
trigger,
|
||||
majoritarianAlignment,
|
||||
rightShare,
|
||||
rightVotes,
|
||||
totalFederalVotes: totalVotes,
|
||||
message,
|
||||
supportLine,
|
||||
}
|
||||
}
|
||||
|
||||
export const aggregateTicketLeverageOverview = (
|
||||
rows: readonly { estimate: number; ticketVotes: number }[],
|
||||
): TicketLeverageOverviewAggregate | null => {
|
||||
let estimateSum = 0
|
||||
let ticketVotesSum = 0
|
||||
let unconvertedCount = 0
|
||||
|
||||
for (const { estimate, ticketVotes } of rows) {
|
||||
if (ticketVotes <= 0) continue
|
||||
estimateSum += estimate
|
||||
ticketVotesSum += ticketVotes
|
||||
if (estimate < ticketVotes) unconvertedCount += 1
|
||||
}
|
||||
|
||||
if (ticketVotesSum <= 0) return null
|
||||
|
||||
return {
|
||||
weightedPercent: Math.round((estimateSum / ticketVotesSum) * 100),
|
||||
unconvertedCount,
|
||||
}
|
||||
}
|
||||
|
||||
export const aggregateTicketFlipOverview = (
|
||||
results: readonly TicketFlipOpportunityResult[],
|
||||
): TicketFlipOverviewAggregate => {
|
||||
let count = 0
|
||||
let bothAlignedCount = 0
|
||||
|
||||
for (const result of results) {
|
||||
if (result.status !== 'opportunity') continue
|
||||
count += 1
|
||||
if (result.majoritarianAlignment === 'both') bothAlignedCount += 1
|
||||
}
|
||||
|
||||
return { count, bothAlignedCount }
|
||||
}
|
||||
|
||||
export const aggregateMobilizationOverview = (
|
||||
input: MobilizationOpportunityInput,
|
||||
): MobilizationOverviewAggregate | null => {
|
||||
const result = computeMobilizationOpportunity(input)
|
||||
if (!isComparableMobilization(result.status)) return null
|
||||
|
||||
return {
|
||||
absoluteTotal: result.absolute,
|
||||
relativePercent: formatPercent(result.relative ?? 0),
|
||||
brancosNulosTotal: result.brancosNulos,
|
||||
abstencoesTotal: result.abstencoes,
|
||||
}
|
||||
}
|
||||
|
||||
export const ticketLeverageAlertVariant = (
|
||||
leverage: TicketLeverageResult,
|
||||
): 'default' | 'pending' =>
|
||||
isComparableTicketLeverage(leverage.status) && (leverage.headlinePercent ?? 0) < 100
|
||||
? 'pending'
|
||||
: 'default'
|
||||
|
||||
export const computeTerritorialClass = ({
|
||||
sollaVotes,
|
||||
federalValidVotes,
|
||||
}: TerritorialClassificationInput): TerritorialClassificationResult => {
|
||||
if (federalValidVotes === null || federalValidVotes <= 0) {
|
||||
return {
|
||||
percentValid: null,
|
||||
band: 'semBaseline',
|
||||
title: 'Classificação territorial',
|
||||
priorityLine:
|
||||
federalValidVotes === null
|
||||
? NO_ELECTION_BASELINE_MESSAGE
|
||||
: 'Sem votos válidos no baseline para esta geografia',
|
||||
supportLine: null,
|
||||
}
|
||||
}
|
||||
|
||||
const percentValid = sollaVotes / federalValidVotes
|
||||
const percent = Math.round(percentValid * 100)
|
||||
|
||||
let band: ComparableTerritorialClass
|
||||
if (percentValid >= TERRITORIAL_DEFESA_MIN) {
|
||||
band = 'defesa'
|
||||
} else if (percentValid >= TERRITORIAL_INDECISA_MIN) {
|
||||
band = 'indecisa'
|
||||
} else if (percentValid >= TERRITORIAL_ATAQUE_MIN) {
|
||||
band = 'ataque'
|
||||
} else {
|
||||
band = 'perdida'
|
||||
}
|
||||
|
||||
const { title, priorityLine } = TERRITORIAL_CLASS_UI[band]
|
||||
|
||||
return {
|
||||
percentValid,
|
||||
band,
|
||||
title,
|
||||
priorityLine,
|
||||
supportLine: `${percent}% dos votos válidos federais em 2022 (${formatElectionNumber(sollaVotes)} / ${formatElectionNumber(federalValidVotes)})`,
|
||||
}
|
||||
}
|
||||
|
|
@ -2,7 +2,7 @@ import {
|
|||
federalBaselineMunicipalitySlugs,
|
||||
getMunicipalityFederalBaseline,
|
||||
} from '@/lib/bahiaElectionAggregates'
|
||||
import { formatElectionNumber } from '@/lib/electionInsights'
|
||||
import { formatElectionNumber } from '@/lib/electionFormat'
|
||||
|
||||
/** Year the mesa uses as the current priority lens (A11 list sort + default readout). */
|
||||
export const DEFAULT_VOTE_RANK_YEAR = 2022
|
||||
|
|
|
|||
73
src/lib/voteTrend.ts
Normal file
73
src/lib/voteTrend.ts
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
/**
|
||||
* "Evolução de votos" — numeric trend derived from the candidate's federal
|
||||
* series (2014/2018/2022). Distinct concept from the manually recorded
|
||||
* "Tendência política" (`municipality.politicalTrend`). Survivor of the
|
||||
* nucleus-era `electionInsights.ts`, gutted in Pass 2 W4a — the deleted
|
||||
* absolute-threshold insight clusters are superseded by E10's relative
|
||||
* territorial classification (see `docs/plans/classificacao-territorial-relativa.md`).
|
||||
*/
|
||||
export const VOTE_TREND_STABLE_BAND = 0.1
|
||||
|
||||
export type VoteTrendStatus = 'decline' | 'stable' | 'increase' | 'noBaseline'
|
||||
|
||||
export type VoteTrendSeries = {
|
||||
y2014: number
|
||||
y2018: number
|
||||
y2022: number
|
||||
}
|
||||
|
||||
export type VoteTrendResult = {
|
||||
status: VoteTrendStatus
|
||||
message: string
|
||||
ratio: number | null
|
||||
}
|
||||
|
||||
type TrendPair = { fromVotes: number; toVotes: number; fromYear: number; toYear: number }
|
||||
|
||||
const trendPairsByPriority = (series: VoteTrendSeries): TrendPair[] => [
|
||||
{ fromVotes: series.y2018, toVotes: series.y2022, fromYear: 2018, toYear: 2022 },
|
||||
{ fromVotes: series.y2014, toVotes: series.y2018, fromYear: 2014, toYear: 2018 },
|
||||
{ fromVotes: series.y2014, toVotes: series.y2022, fromYear: 2014, toYear: 2022 },
|
||||
]
|
||||
|
||||
/**
|
||||
* Classify vote trend from the federal candidate series (2014/2018/2022).
|
||||
* Uses the most recent consecutive pair with votes in both years; ±10% → stable.
|
||||
*/
|
||||
export const computeVoteTrend = (series: VoteTrendSeries): VoteTrendResult => {
|
||||
for (const pair of trendPairsByPriority(series)) {
|
||||
if (pair.fromVotes <= 0 || pair.toVotes <= 0) continue
|
||||
|
||||
const ratio = pair.toVotes / pair.fromVotes
|
||||
const change = ratio - 1
|
||||
const percent = Math.round(Math.abs(change) * 100)
|
||||
|
||||
if (Math.abs(change) <= VOTE_TREND_STABLE_BAND) {
|
||||
return {
|
||||
status: 'stable',
|
||||
ratio,
|
||||
message: `Mantém (${pair.fromYear}→${pair.toYear}, variação de ${percent}%)`,
|
||||
}
|
||||
}
|
||||
|
||||
if (change > VOTE_TREND_STABLE_BAND) {
|
||||
return {
|
||||
status: 'increase',
|
||||
ratio,
|
||||
message: `Aumento (${pair.fromYear}→${pair.toYear}, +${percent}%)`,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
status: 'decline',
|
||||
ratio,
|
||||
message: `Queda (${pair.fromYear}→${pair.toYear}, −${percent}%)`,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
status: 'noBaseline',
|
||||
ratio: null,
|
||||
message: 'Sem série histórica suficiente para tendência',
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { formatElectionNumber } from '@/lib/electionInsights'
|
||||
import { formatElectionNumber } from '@/lib/electionFormat'
|
||||
import type { SuggestedGoalByScenario } from '@/utilities/municipalityPotential'
|
||||
import type { MunicipalityPledgeAggregate } from '@/utilities/votePledgeViews'
|
||||
import {
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
* surfaces. Client-safe: types + string tables only (split out of the former
|
||||
* `municipalityUi.ts` in Pass 2 W1).
|
||||
*/
|
||||
import { formatElectionNumber } from '@/lib/electionInsights'
|
||||
import { formatElectionNumber } from '@/lib/electionFormat'
|
||||
import { municipalityCatalog } from '@/lib/municipalityCatalog'
|
||||
import type { CampaignUser, Municipality } from '@/payload-types'
|
||||
|
||||
|
|
|
|||
|
|
@ -1,366 +0,0 @@
|
|||
// @vitest-environment node
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
aggregateConversionBand,
|
||||
aggregateMobilizationOverview,
|
||||
aggregateTerritorialClass,
|
||||
aggregateVoteTrend,
|
||||
comparableTrendCount,
|
||||
computeConversionRate,
|
||||
computeGapVs2022,
|
||||
computeMobilizationOpportunity,
|
||||
computeTerritorialClass,
|
||||
computeVoteTrend,
|
||||
CONVERSION_OPPORTUNITY_MAX,
|
||||
CONVERSION_REDUTO_MIN,
|
||||
isComparableConversionBand,
|
||||
isComparableMobilization,
|
||||
type GapVs2022Baseline,
|
||||
TERRITORIAL_ATAQUE_MIN,
|
||||
TERRITORIAL_DEFESA_MIN,
|
||||
TERRITORIAL_INDECISA_MIN,
|
||||
} from '@/lib/electionInsights'
|
||||
|
||||
const baseline = (candidateVotes: number): GapVs2022Baseline => ({
|
||||
candidate: { votes: candidateVotes },
|
||||
})
|
||||
|
||||
describe('computeGapVs2022', () => {
|
||||
it('reports below when the estimate is under the 2022 patamar', () => {
|
||||
expect(computeGapVs2022(baseline(850), 500)).toEqual({
|
||||
gap: -350,
|
||||
ratio: 500 / 850,
|
||||
status: 'below',
|
||||
message: 'Faltam 350 votos para o patamar de 2022',
|
||||
})
|
||||
})
|
||||
|
||||
it('reports above with the percent over 2022', () => {
|
||||
expect(computeGapVs2022(baseline(850), 952)).toMatchObject({
|
||||
gap: 102,
|
||||
status: 'above',
|
||||
message: 'Já superamos 2022 em 12%',
|
||||
})
|
||||
})
|
||||
|
||||
it('reports noCandidateVotes when the geography had zero candidate votes in 2022', () => {
|
||||
expect(computeGapVs2022(baseline(0), 100)).toEqual({
|
||||
gap: null,
|
||||
ratio: null,
|
||||
status: 'noCandidateVotes',
|
||||
message: 'Jorge Solla não recebeu votos aqui em 2022 — território novo a abrir',
|
||||
})
|
||||
})
|
||||
|
||||
it('reports noEstimate when confirmedVoteEstimate is null', () => {
|
||||
expect(computeGapVs2022(baseline(850), null)).toEqual({
|
||||
gap: null,
|
||||
ratio: null,
|
||||
status: 'noEstimate',
|
||||
message: 'Sem estimativa confirmada para comparar',
|
||||
})
|
||||
})
|
||||
|
||||
it('reports noBaseline when geography is missing', () => {
|
||||
expect(computeGapVs2022(null, 100)).toEqual({
|
||||
gap: null,
|
||||
ratio: null,
|
||||
status: 'noBaseline',
|
||||
message: 'Sem baseline TSE (informe território/município)',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('computeVoteTrend', () => {
|
||||
it('classifies increase when the latest step exceeds 10%', () => {
|
||||
expect(computeVoteTrend({ y2014: 1000, y2018: 1200, y2022: 1400 })).toMatchObject({
|
||||
status: 'increase',
|
||||
ratio: 1400 / 1200,
|
||||
})
|
||||
})
|
||||
|
||||
it('classifies decline when the latest step drops more than 10%', () => {
|
||||
expect(computeVoteTrend({ y2014: 1000, y2018: 1200, y2022: 1000 })).toMatchObject({
|
||||
status: 'decline',
|
||||
ratio: 1000 / 1200,
|
||||
})
|
||||
})
|
||||
|
||||
it('classifies stable within the ±10% band on the preferred 2018→2022 pair', () => {
|
||||
expect(computeVoteTrend({ y2014: 500, y2018: 1000, y2022: 1050 })).toMatchObject({
|
||||
status: 'stable',
|
||||
ratio: 1.05,
|
||||
})
|
||||
})
|
||||
|
||||
it('falls back to 2014→2018 when 2022 is missing', () => {
|
||||
expect(computeVoteTrend({ y2014: 1000, y2018: 1500, y2022: 0 })).toMatchObject({
|
||||
status: 'increase',
|
||||
})
|
||||
})
|
||||
|
||||
it('reports noBaseline with fewer than two non-zero years', () => {
|
||||
expect(computeVoteTrend({ y2014: 0, y2018: 0, y2022: 500 }).status).toBe('noBaseline')
|
||||
})
|
||||
})
|
||||
|
||||
describe('aggregateVoteTrend', () => {
|
||||
it('counts trend statuses across nucleus series', () => {
|
||||
expect(
|
||||
aggregateVoteTrend([
|
||||
{ y2014: 1000, y2018: 1200, y2022: 1400 },
|
||||
{ y2014: 1000, y2018: 1200, y2022: 1000 },
|
||||
{ y2014: 0, y2018: 0, y2022: 500 },
|
||||
]),
|
||||
).toEqual({
|
||||
increase: 1,
|
||||
decline: 1,
|
||||
stable: 0,
|
||||
noBaseline: 1,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('comparableTrendCount', () => {
|
||||
it('sums increase, stable, and decline only', () => {
|
||||
expect(
|
||||
comparableTrendCount({ increase: 2, stable: 1, decline: 3, noBaseline: 4 }),
|
||||
).toBe(6)
|
||||
})
|
||||
})
|
||||
|
||||
describe('computeConversionRate', () => {
|
||||
it('classifies oportunidade below 15%', () => {
|
||||
const aptos = 10_000
|
||||
const estimate = Math.floor(aptos * (CONVERSION_OPPORTUNITY_MAX - 0.001))
|
||||
expect(computeConversionRate({ aptos, abstencoes: 0, confirmedVoteEstimate: estimate })).toMatchObject({
|
||||
band: 'oportunidade',
|
||||
message: `Taxa de conversão: ${Math.round((estimate / aptos) * 100)}% do eleitorado apto`,
|
||||
})
|
||||
})
|
||||
|
||||
it('classifies consolidado at 15%', () => {
|
||||
const aptos = 10_000
|
||||
const estimate = aptos * CONVERSION_OPPORTUNITY_MAX
|
||||
expect(computeConversionRate({ aptos, abstencoes: 0, confirmedVoteEstimate: estimate }).band).toBe(
|
||||
'consolidado',
|
||||
)
|
||||
})
|
||||
|
||||
it('classifies reduto at 40%', () => {
|
||||
const aptos = 10_000
|
||||
const estimate = aptos * CONVERSION_REDUTO_MIN
|
||||
expect(computeConversionRate({ aptos, abstencoes: 0, confirmedVoteEstimate: estimate }).band).toBe(
|
||||
'reduto',
|
||||
)
|
||||
})
|
||||
|
||||
it('reports semAptos when aptos is zero', () => {
|
||||
expect(computeConversionRate({ aptos: 0, abstencoes: 0, confirmedVoteEstimate: 100 })).toMatchObject({
|
||||
band: 'semAptos',
|
||||
rate: null,
|
||||
})
|
||||
})
|
||||
|
||||
it('reports semEstimativa when estimate is null', () => {
|
||||
expect(computeConversionRate({ aptos: 4700, abstencoes: 680, confirmedVoteEstimate: null })).toMatchObject({
|
||||
band: 'semEstimativa',
|
||||
rate: null,
|
||||
})
|
||||
})
|
||||
|
||||
it('includes turnout percent in support line when comparecimento is positive', () => {
|
||||
expect(
|
||||
computeConversionRate({ aptos: 4700, abstencoes: 680, confirmedVoteEstimate: 850 }).supportLine,
|
||||
).toBe('850 votos / 4.700 eleitores aptos · 21% do comparecimento')
|
||||
})
|
||||
})
|
||||
|
||||
describe('aggregateConversionBand', () => {
|
||||
it('counts comparable bands only', () => {
|
||||
expect(
|
||||
aggregateConversionBand(['reduto', 'consolidado', 'oportunidade', 'semEstimativa', 'semAptos']),
|
||||
).toEqual({
|
||||
reduto: 1,
|
||||
consolidado: 1,
|
||||
oportunidade: 1,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('isComparableConversionBand', () => {
|
||||
it('accepts the three comparable bands', () => {
|
||||
expect(isComparableConversionBand('reduto')).toBe(true)
|
||||
expect(isComparableConversionBand('semEstimativa')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('computeMobilizationOpportunity', () => {
|
||||
it('matches the design-ref subtotals and total', () => {
|
||||
expect(
|
||||
computeMobilizationOpportunity({
|
||||
abstencoes: 680,
|
||||
brancos: 100,
|
||||
nulos: 42,
|
||||
aptos: 4700,
|
||||
}),
|
||||
).toMatchObject({
|
||||
absolute: 822,
|
||||
brancosNulos: 142,
|
||||
abstencoes: 680,
|
||||
status: 'opportunity',
|
||||
message: 'Oportunidade de mobilização',
|
||||
supportLine:
|
||||
'142 brancos/nulos + 680 abstenções = 822 votos possíveis · 17% do eleitorado apto',
|
||||
})
|
||||
})
|
||||
|
||||
it('reports semAptos when aptos is zero', () => {
|
||||
expect(
|
||||
computeMobilizationOpportunity({ abstencoes: 10, brancos: 5, nulos: 2, aptos: 0 }),
|
||||
).toMatchObject({
|
||||
status: 'semAptos',
|
||||
absolute: 0,
|
||||
})
|
||||
})
|
||||
|
||||
it('reports zero when all components are absent', () => {
|
||||
expect(
|
||||
computeMobilizationOpportunity({ abstencoes: 0, brancos: 0, nulos: 0, aptos: 1000 }),
|
||||
).toMatchObject({
|
||||
status: 'zero',
|
||||
absolute: 0,
|
||||
})
|
||||
})
|
||||
|
||||
it('reports semBaseline when aptos is null', () => {
|
||||
expect(
|
||||
computeMobilizationOpportunity({ abstencoes: 10, brancos: 5, nulos: 2, aptos: null }),
|
||||
).toMatchObject({
|
||||
status: 'semBaseline',
|
||||
absolute: 0,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('isComparableMobilization', () => {
|
||||
it('accepts only opportunity', () => {
|
||||
expect(isComparableMobilization('opportunity')).toBe(true)
|
||||
expect(isComparableMobilization('zero')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('aggregateMobilizationOverview', () => {
|
||||
it('maps comparable opportunity to overview fields', () => {
|
||||
expect(
|
||||
aggregateMobilizationOverview({
|
||||
abstencoes: 680,
|
||||
brancos: 100,
|
||||
nulos: 42,
|
||||
aptos: 4700,
|
||||
}),
|
||||
).toEqual({
|
||||
absoluteTotal: 822,
|
||||
relativePercent: 17,
|
||||
brancosNulosTotal: 142,
|
||||
abstencoesTotal: 680,
|
||||
})
|
||||
})
|
||||
|
||||
it('returns null when there is no mobilization potential', () => {
|
||||
expect(
|
||||
aggregateMobilizationOverview({ abstencoes: 0, brancos: 0, nulos: 0, aptos: 1000 }),
|
||||
).toBeNull()
|
||||
expect(
|
||||
aggregateMobilizationOverview({ abstencoes: 10, brancos: 5, nulos: 2, aptos: null }),
|
||||
).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('computeTerritorialClass', () => {
|
||||
it('classifies defesa at 35% of valid votes', () => {
|
||||
const validos = 2490
|
||||
expect(
|
||||
computeTerritorialClass({
|
||||
sollaVotes: Math.ceil(validos * TERRITORIAL_DEFESA_MIN),
|
||||
federalValidVotes: validos,
|
||||
}),
|
||||
).toMatchObject({
|
||||
band: 'defesa',
|
||||
title: 'Território de defesa',
|
||||
})
|
||||
})
|
||||
|
||||
it('classifies indecisa at 20% of valid votes', () => {
|
||||
expect(
|
||||
computeTerritorialClass({
|
||||
sollaVotes: Math.floor(2490 * TERRITORIAL_INDECISA_MIN),
|
||||
federalValidVotes: 2490,
|
||||
}),
|
||||
).toMatchObject({
|
||||
band: 'indecisa',
|
||||
title: 'Território indeciso',
|
||||
})
|
||||
})
|
||||
|
||||
it('classifies ataque at 10% of valid votes', () => {
|
||||
expect(
|
||||
computeTerritorialClass({
|
||||
sollaVotes: Math.floor(2490 * TERRITORIAL_ATAQUE_MIN),
|
||||
federalValidVotes: 2490,
|
||||
}),
|
||||
).toMatchObject({
|
||||
band: 'ataque',
|
||||
title: 'Território de ataque',
|
||||
})
|
||||
})
|
||||
|
||||
it('classifies perdida below 10%', () => {
|
||||
expect(
|
||||
computeTerritorialClass({
|
||||
sollaVotes: Math.floor(2490 * (TERRITORIAL_ATAQUE_MIN - 0.001)),
|
||||
federalValidVotes: 2490,
|
||||
}),
|
||||
).toMatchObject({
|
||||
band: 'perdida',
|
||||
title: 'Território perdido',
|
||||
})
|
||||
})
|
||||
|
||||
it('reports semBaseline when validos is zero', () => {
|
||||
expect(computeTerritorialClass({ sollaVotes: 100, federalValidVotes: 0 })).toMatchObject({
|
||||
band: 'semBaseline',
|
||||
percentValid: null,
|
||||
})
|
||||
})
|
||||
|
||||
it('reports semBaseline when validos is null', () => {
|
||||
expect(computeTerritorialClass({ sollaVotes: 100, federalValidVotes: null })).toMatchObject({
|
||||
band: 'semBaseline',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('aggregateTerritorialClass', () => {
|
||||
it('counts comparable territorial bands only', () => {
|
||||
expect(
|
||||
aggregateTerritorialClass(['defesa', 'ataque', 'indecisa', 'perdida', 'semBaseline']),
|
||||
).toEqual({
|
||||
defesa: 1,
|
||||
ataque: 1,
|
||||
indecisa: 1,
|
||||
perdida: 1,
|
||||
})
|
||||
})
|
||||
|
||||
it('returns all zeros when every band is semBaseline', () => {
|
||||
expect(aggregateTerritorialClass(['semBaseline', 'semBaseline'])).toEqual({
|
||||
defesa: 0,
|
||||
ataque: 0,
|
||||
indecisa: 0,
|
||||
perdida: 0,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
|
@ -7,13 +7,6 @@ import {
|
|||
normalizePartySigla,
|
||||
partySpectrum,
|
||||
} from '@/lib/electionPartySpectrum'
|
||||
import {
|
||||
aggregateTicketFlipOverview,
|
||||
aggregateTicketLeverageOverview,
|
||||
computeTicketFlipOpportunity,
|
||||
computeTicketLeverage,
|
||||
RIGHT_SHARE_THRESHOLD,
|
||||
} from '@/lib/electionInsights'
|
||||
|
||||
describe('partySpectrum', () => {
|
||||
it('classifies left-wing parties from the 2022 survey', () => {
|
||||
|
|
@ -44,128 +37,3 @@ describe('partySpectrum', () => {
|
|||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('computeTicketLeverage', () => {
|
||||
it('reports headline percent against the stronger majoritarian base', () => {
|
||||
const result = computeTicketLeverage({
|
||||
confirmedVoteEstimate: 500,
|
||||
presidentVotes: 1480,
|
||||
governorVotes: 1310,
|
||||
})
|
||||
expect(result.status).toBe('comparable')
|
||||
expect(result.headlinePercent).toBe(34)
|
||||
expect(result.message).toBe('Alavancagem da chapa: 34%')
|
||||
expect(result.supportLine).toContain('Da base Lula/Jerônimo ainda não convertida')
|
||||
})
|
||||
|
||||
it('reports noEstimate without a confirmed estimate', () => {
|
||||
expect(
|
||||
computeTicketLeverage({
|
||||
confirmedVoteEstimate: null,
|
||||
presidentVotes: 1000,
|
||||
governorVotes: 900,
|
||||
}).status,
|
||||
).toBe('noEstimate')
|
||||
})
|
||||
})
|
||||
|
||||
describe('computeTicketFlipOpportunity', () => {
|
||||
const presidentLeft = { name: 'LULA', party: 'PT', votes: 8000 }
|
||||
const governorLeft = { name: 'JERÔNIMO', party: 'PT', votes: 6000 }
|
||||
|
||||
it('fires on a right-wing federal winner when majoritarians align left', () => {
|
||||
const result = computeTicketFlipOpportunity({
|
||||
winnerPresident: presidentLeft,
|
||||
winnerGovernor: governorLeft,
|
||||
winnerFederal: { name: 'RIVAL', party: 'PL', votes: 2500 },
|
||||
federalVotesByParty: { PT: 2100, PL: 2500 },
|
||||
})
|
||||
expect(result.status).toBe('opportunity')
|
||||
expect(result.trigger).toBe('both')
|
||||
expect(result.majoritarianAlignment).toBe('both')
|
||||
expect(result.message).toContain('fora do campo')
|
||||
expect(result.message).not.toMatch(/direita/i)
|
||||
})
|
||||
|
||||
it('fires on high right share even when the federal winner is left', () => {
|
||||
const result = computeTicketFlipOpportunity({
|
||||
winnerPresident: presidentLeft,
|
||||
winnerGovernor: null,
|
||||
winnerFederal: { name: 'SOLLA', party: 'PT', votes: 2100 },
|
||||
federalVotesByParty: { PT: 2100, PL: 900, PSDB: 500 },
|
||||
})
|
||||
expect(result.status).toBe('opportunity')
|
||||
expect(result.trigger).toBe('share')
|
||||
expect(result.majoritarianAlignment).toBe('president')
|
||||
expect(result.rightShare).toBeGreaterThanOrEqual(RIGHT_SHARE_THRESHOLD)
|
||||
})
|
||||
|
||||
it('does not fire when right share is below the threshold and winner is left', () => {
|
||||
const result = computeTicketFlipOpportunity({
|
||||
winnerPresident: presidentLeft,
|
||||
winnerGovernor: governorLeft,
|
||||
winnerFederal: { name: 'SOLLA', party: 'PT', votes: 2100 },
|
||||
federalVotesByParty: { PT: 2100, PL: 100 },
|
||||
})
|
||||
expect(result.status).toBe('noOpportunity')
|
||||
})
|
||||
|
||||
it('does not fire without left majoritarian alignment', () => {
|
||||
const result = computeTicketFlipOpportunity({
|
||||
winnerPresident: { name: 'BOLSONARO', party: 'PL', votes: 5000 },
|
||||
winnerGovernor: { name: 'RIVAL', party: 'PSDB', votes: 4500 },
|
||||
winnerFederal: { name: 'RIVAL', party: 'PL', votes: 1900 },
|
||||
federalVotesByParty: { PL: 1900, PT: 500 },
|
||||
})
|
||||
expect(result.status).toBe('incomplete')
|
||||
})
|
||||
|
||||
it('fails closed on unknown party spectrum', () => {
|
||||
const result = computeTicketFlipOpportunity({
|
||||
winnerPresident: presidentLeft,
|
||||
winnerGovernor: governorLeft,
|
||||
winnerFederal: { name: 'SOLLA', party: 'PT', votes: 2100 },
|
||||
federalVotesByParty: { PT: 2100, 'SIGLA NOVA': 900 },
|
||||
})
|
||||
expect(result.status).toBe('unknownSpectrum')
|
||||
})
|
||||
})
|
||||
|
||||
describe('overview aggregates', () => {
|
||||
it('computes weighted leverage and unconverted nuclei', () => {
|
||||
expect(
|
||||
aggregateTicketLeverageOverview([
|
||||
{ estimate: 500, ticketVotes: 1000 },
|
||||
{ estimate: 800, ticketVotes: 1000 },
|
||||
]),
|
||||
).toEqual({ weightedPercent: 65, unconvertedCount: 2 })
|
||||
})
|
||||
|
||||
it('counts flip opportunities and both-aligned subset', () => {
|
||||
expect(
|
||||
aggregateTicketFlipOverview([
|
||||
{
|
||||
status: 'opportunity',
|
||||
trigger: 'winner',
|
||||
majoritarianAlignment: 'both',
|
||||
rightShare: 0.3,
|
||||
rightVotes: 300,
|
||||
totalFederalVotes: 1000,
|
||||
message: 'x',
|
||||
supportLine: null,
|
||||
},
|
||||
{
|
||||
status: 'opportunity',
|
||||
trigger: 'share',
|
||||
majoritarianAlignment: 'president',
|
||||
rightShare: 0.3,
|
||||
rightVotes: 300,
|
||||
totalFederalVotes: 1000,
|
||||
message: 'y',
|
||||
supportLine: null,
|
||||
},
|
||||
{ status: 'noOpportunity', trigger: null, majoritarianAlignment: null, rightShare: null, rightVotes: 0, totalFederalVotes: 0, message: 'z', supportLine: null },
|
||||
]),
|
||||
).toEqual({ count: 2, bothAlignedCount: 1 })
|
||||
})
|
||||
})
|
||||
|
|
|
|||
49
tests/unit/voteTrend.unit.spec.ts
Normal file
49
tests/unit/voteTrend.unit.spec.ts
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
// @vitest-environment node
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { formatElectionNumber } from '@/lib/electionFormat'
|
||||
import { computeVoteTrend } from '@/lib/voteTrend'
|
||||
|
||||
describe('formatElectionNumber', () => {
|
||||
it('formats whole votes with pt-BR thousands separators', () => {
|
||||
expect(formatElectionNumber(150_000)).toBe('150.000')
|
||||
})
|
||||
|
||||
it('never renders decimals — a fractional goal must not read as thousands (E18 defect)', () => {
|
||||
expect(formatElectionNumber(100.968)).toBe('101')
|
||||
})
|
||||
})
|
||||
|
||||
describe('computeVoteTrend', () => {
|
||||
it('classifies increase when the latest step exceeds 10%', () => {
|
||||
expect(computeVoteTrend({ y2014: 1000, y2018: 1200, y2022: 1400 })).toMatchObject({
|
||||
status: 'increase',
|
||||
ratio: 1400 / 1200,
|
||||
})
|
||||
})
|
||||
|
||||
it('classifies decline when the latest step drops more than 10%', () => {
|
||||
expect(computeVoteTrend({ y2014: 1000, y2018: 1200, y2022: 1000 })).toMatchObject({
|
||||
status: 'decline',
|
||||
ratio: 1000 / 1200,
|
||||
})
|
||||
})
|
||||
|
||||
it('classifies stable within the ±10% band on the preferred 2018→2022 pair', () => {
|
||||
expect(computeVoteTrend({ y2014: 500, y2018: 1000, y2022: 1050 })).toMatchObject({
|
||||
status: 'stable',
|
||||
ratio: 1.05,
|
||||
})
|
||||
})
|
||||
|
||||
it('falls back to 2014→2018 when 2022 is missing', () => {
|
||||
expect(computeVoteTrend({ y2014: 1000, y2018: 1500, y2022: 0 })).toMatchObject({
|
||||
status: 'increase',
|
||||
})
|
||||
})
|
||||
|
||||
it('reports noBaseline with fewer than two non-zero years', () => {
|
||||
expect(computeVoteTrend({ y2014: 0, y2018: 0, y2022: 500 }).status).toBe('noBaseline')
|
||||
})
|
||||
})
|
||||
Loading…
Reference in a new issue