teqo/src/utilities/municipalityGoalAccount.ts
Francisco Ignácio Fontoura Solla 31fcc20ffd E9 /simplify: consolidate duplicated helpers, dead passthrough, comment drift
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.
2026-07-25 02:24:18 -03:00

146 lines
5.3 KiB
TypeScript

import 'server-only'
import { cache } from 'react'
import type { Payload } from 'payload'
import type { CampaignUser, User } from '@/payload-types'
import { loadCampaignGoals } from '@/utilities/campaignGoals'
import {
aggregateGoalCoverage,
computeGoalCoverage,
computeGoalCoverageByScenario,
type MunicipalityGoalCoverage,
} from '@/utilities/goalCoverage'
import {
computeMunicipalityPotential,
computeStatewideSuggestedGoals,
type MunicipalityPotential,
type SuggestedGoalByScenario,
} from '@/utilities/municipalityPotential'
import {
DEFAULT_VOTE_ESTIMATE_SCENARIO,
VOTE_ESTIMATE_SCENARIOS,
zeroByVoteEstimateScenario,
type VoteEstimateScenarioFields,
type VoteEstimateScenario,
} from '@/utilities/voteEstimate'
import {
emptyMunicipalityPledgeAggregate,
type MunicipalityPledgeAggregate,
} from '@/utilities/votePledgeData'
type GoalAccountReader = CampaignUser | User
/**
* E8 "conta da cadeira" — request-scoped statewide suggested-goal ladder
* (`campaignGoals` global + `computeStatewideSuggestedGoals`), degrau 1 da
* caching ladder. Every surface (dashboard, list overview, list rows, detail
* card) needs the SAME goals — the optimistic scenario's growth factor is
* `stateGoal / Σ base` over the full 435-slug catalog, so this always runs
* over the whole catalog, never a filtered scope, and is
* `cache()`-deduplicated so dashboard + list + detail don't each recompute it
* on requests that touch more than one.
*/
const loadSuggestedGoalsCached = cache(
async (payload: Payload, user: GoalAccountReader) => {
const goals = await loadCampaignGoals(payload, user)
return computeStatewideSuggestedGoals(goals)
},
)
export type MunicipalityGoalCoverageBundle = {
coverageByMunicipalityID: Map<number, Record<VoteEstimateScenario, MunicipalityGoalCoverage>>
/** Sum of every municipality's coverage in `municipalities`, per scenario (dashboard/overview metric). */
aggregateByScenario: Record<VoteEstimateScenario, MunicipalityGoalCoverage>
}
/**
* Per-scenario goal coverage for a scope of municipalities (dashboard total,
* or the list's filtered overview) plus the per-municipality breakdown the
* list rows pick a scenario from client-side — mirrors
* `rollupMunicipalityStaffVotes`'s "compute all 3 scenarios server-side, pick
* client-side" shape.
*/
export const loadMunicipalityGoalCoverageBundle = async (
payload: Payload,
user: GoalAccountReader,
municipalities: ReadonlyArray<{
id: number
slug: string
expectedVotes?: VoteEstimateScenarioFields | null
}>,
pledgeAggregates: Map<number, MunicipalityPledgeAggregate>,
): Promise<MunicipalityGoalCoverageBundle> => {
const { suggestedGoalBySlug } = await loadSuggestedGoalsCached(payload, user)
const coverageByMunicipalityID = new Map<
number,
Record<VoteEstimateScenario, MunicipalityGoalCoverage>
>()
for (const municipality of municipalities) {
const pledgeAggregate =
pledgeAggregates.get(municipality.id) ?? emptyMunicipalityPledgeAggregate
const suggestedGoalByScenario =
suggestedGoalBySlug.get(municipality.slug) ?? emptySuggestedGoalByScenario
coverageByMunicipalityID.set(
municipality.id,
computeGoalCoverageByScenario(
municipality.expectedVotes,
suggestedGoalByScenario,
pledgeAggregate,
),
)
}
const coverages = [...coverageByMunicipalityID.values()]
const aggregateByScenario = {} as Record<VoteEstimateScenario, MunicipalityGoalCoverage>
for (const scenario of VOTE_ESTIMATE_SCENARIOS) {
aggregateByScenario[scenario] = aggregateGoalCoverage(
coverages.map((coverageByScenario) => coverageByScenario[scenario]),
)
}
return { coverageByMunicipalityID, aggregateByScenario }
}
/** Unknown slug (never in the catalog): zero goal in every scenario, never mutated. */
const emptySuggestedGoalByScenario: Readonly<SuggestedGoalByScenario> = zeroByVoteEstimateScenario()
export type MunicipalityGoalAccount = {
/** Fixed to the `central` scenario, like `goalCoverage` below. */
suggestedGoal: number
/** Fixed to the `central` scenario — the detail page has no scenario selector. */
goalCoverage: MunicipalityGoalCoverage
potential: MunicipalityPotential
}
/**
* One município's full "conta da cadeira": suggested goal, coverage (central
* scenario), and the diagnostic potential block (teto do campo, captura,
* share intracampo, roll-off) — the detail page's "Conta da cadeira" card.
*/
export const loadMunicipalityGoalAccount = async (
payload: Payload,
user: GoalAccountReader,
municipality: { slug: string; expectedVotes?: VoteEstimateScenarioFields | null },
pledgeAggregate: MunicipalityPledgeAggregate,
): Promise<MunicipalityGoalAccount> => {
const { suggestedGoalBySlug, potentialBySlug } = await loadSuggestedGoalsCached(payload, user)
const suggestedGoalByScenario =
suggestedGoalBySlug.get(municipality.slug) ?? emptySuggestedGoalByScenario
const goalCoverage = computeGoalCoverage(
municipality.expectedVotes,
suggestedGoalByScenario,
pledgeAggregate,
DEFAULT_VOTE_ESTIMATE_SCENARIO,
)
const potential =
potentialBySlug.get(municipality.slug) ?? computeMunicipalityPotential(municipality.slug)
return {
suggestedGoal: suggestedGoalByScenario[DEFAULT_VOTE_ESTIMATE_SCENARIO],
goalCoverage,
potential,
}
}