teqo-backup/src/components/campaign/CampaignDashboard.tsx
Francisco Ignácio Fontoura Solla a32ba3b4f0 Cache the campaign hot path: committed TSE artifact + request-scoped dedup
- 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)
2026-07-23 23:06:28 -03:00

177 lines
6.7 KiB
TypeScript

import { ArrowRightIcon } from 'lucide-react'
import Link from 'next/link'
import { CampaignMetricStrip } from '@/components/campaign/CampaignMetricStrip'
import {
CampaignPageShell,
campaignPrioritySurfaceClassName,
} from '@/components/campaign/CampaignPageShell'
import { MunicipalityEstimateScenarioProvider } from '@/components/campaign/MunicipalityEstimateScenarioContext'
import { MunicipalityMapPanelDynamic } from '@/components/campaign/MunicipalityMapPanelDynamic'
import { RecentlyVisitedCard } from '@/components/campaign/RecentlyVisitedCard'
import { Badge } from '@/components/ui/Badge'
import { Button } from '@/components/ui/button'
import { formatElectionNumber } from '@/lib/electionInsights'
import type { StaffDashboardView } from '@/utilities/campaignDashboardData'
import type { FederalCandidateOption } from '@/utilities/electionCandidateOptions'
import type { MunicipalityMapBundle } from '@/utilities/municipalityMapContract'
import {
formatVoteEstimateEndpointsLabel,
voteEstimateScenarioLabels,
} from '@/utilities/voteEstimate'
const dateTimeFormatter = new Intl.DateTimeFormat('pt-BR', {
dateStyle: 'short',
timeStyle: 'short',
})
export const CampaignDashboard = ({
view,
userName,
mapBundle = null,
candidateOptions = [],
}: {
view: StaffDashboardView
userName: string
mapBundle?: MunicipalityMapBundle | null
candidateOptions?: FederalCandidateOption[]
}) => (
<CampaignPageShell>
<header className="flex flex-col gap-1">
<h1 className="text-2xl font-semibold tracking-tight">Olá, {userName}</h1>
<p className="text-muted-foreground">
{view.role === 'advisor'
? 'Quadro das Praças sob sua assessoria.'
: 'Quadro geral da campanha por Praça.'}
</p>
</header>
{mapBundle ? (
<MunicipalityEstimateScenarioProvider>
<MunicipalityMapPanelDynamic bundle={mapBundle} candidateOptions={candidateOptions} />
</MunicipalityEstimateScenarioProvider>
) : null}
<section
aria-label="Indicadores das Praças"
className={`rounded-xl ${campaignPrioritySurfaceClassName}`}
>
<CampaignMetricStrip
metrics={[
{
label: `${voteEstimateScenarioLabels.central} nas Praças`,
value: formatElectionNumber(view.staffVoteTotalByScenario.central),
detail: formatVoteEstimateEndpointsLabel(view.staffVoteTotalByScenario) ?? undefined,
emphasize: true,
},
{
label: 'Cobertura de assessoria',
value: `${view.withAdvisorCount} de ${view.municipalityCount} Praças`,
progress:
view.municipalityCount > 0
? Math.round((view.withAdvisorCount / view.municipalityCount) * 100)
: undefined,
},
{
label: 'Declarações sem estimativa',
value: formatElectionNumber(view.missingEstimateCount),
},
]}
/>
</section>
<div className="grid gap-6 lg:grid-cols-2">
<section
aria-labelledby="dashboard-missing-title"
className="flex flex-col gap-3 rounded-xl border p-4"
>
<div className="flex items-center justify-between gap-2">
<h2 id="dashboard-missing-title" className="text-base font-medium">
Declarações aguardando estimativa
</h2>
<Badge variant="estimate-pending">{view.missingEstimateCount}</Badge>
</div>
{view.missingEstimates.length ? (
<ul className="flex flex-col gap-2">
{view.missingEstimates.map((item) => (
<li key={item.pledgeID} className="flex items-center justify-between gap-2">
<div className="flex min-w-0 flex-col">
<span className="truncate font-medium">{item.contactName}</span>
<span className="truncate text-sm text-muted-foreground">
{item.municipalityName} · declarou {formatElectionNumber(item.declaredVotes)}{' '}
votos
</span>
</div>
<Button asChild variant="ghost" className="min-h-11 shrink-0">
<Link href={`/campanha/municipios/${item.municipalitySlug}`}>Revisar</Link>
</Button>
</li>
))}
</ul>
) : (
<p className="text-sm text-muted-foreground">
Todas as declarações do seu escopo têm estimativa registrada.
</p>
)}
</section>
<section
aria-labelledby="dashboard-updates-title"
className="flex flex-col gap-3 rounded-xl border p-4"
>
<h2 id="dashboard-updates-title" className="text-base font-medium">
Últimas atualizações de campo
</h2>
{view.recentUpdates.length ? (
<ul className="flex flex-col gap-2">
{view.recentUpdates.map((update) => (
<li key={update.id} className="flex items-center justify-between gap-2">
<div className="flex min-w-0 flex-col">
<span className="truncate font-medium">{update.municipalityName}</span>
<span className="truncate text-sm text-muted-foreground">
{update.authorName} · {dateTimeFormatter.format(new Date(update.createdAt))}
</span>
</div>
<Button asChild variant="ghost" className="min-h-11 shrink-0">
<Link href={`/campanha/municipios/${update.municipalitySlug}?tab=updates`}>
Abrir
</Link>
</Button>
</li>
))}
</ul>
) : (
<p className="text-sm text-muted-foreground">Nenhuma atualização registrada ainda.</p>
)}
</section>
</div>
{view.priorityMunicipalities.length ? (
<section aria-labelledby="dashboard-priority-title" className="flex flex-col gap-3">
<h2 id="dashboard-priority-title" className="text-base font-medium">
Praças prioritárias
</h2>
<ul className="flex flex-wrap gap-2">
{view.priorityMunicipalities.map((municipality) => (
<li key={municipality.slug}>
<Button asChild variant="outline" className="min-h-11">
<Link href={`/campanha/municipios/${municipality.slug}`}>{municipality.name}</Link>
</Button>
</li>
))}
</ul>
</section>
) : null}
<RecentlyVisitedCard now={new Date()} />
<div>
<Button asChild className="min-h-11">
<Link href="/campanha/municipios">
Ver todas as Praças
<ArrowRightIcon data-icon="inline-end" aria-hidden="true" />
</Link>
</Button>
</div>
</CampaignPageShell>
)