mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-27 06:13:06 +00:00
Merge pull request #220 from fsolla/cursor/pool-i172-ccc192fe-16b0
OH9 — Detalhe de município dual-path (views + Local + OfflineBoundary)
This commit is contained in:
commit
bb4741e4f5
11 changed files with 541 additions and 103 deletions
|
|
@ -4,6 +4,8 @@ Conteúdo movido do `AGENTS.md` em 2026-07-30 (fatiamento do paradigma de agente
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
**Recently resolved (2026-08-02):** **OH9** (Issue #172) — detalhe de município dual-path: `MunicipalityDetailHeaderView` partilhado; `OfflineBoundary` (SSR=RSC; offline+`OPS_HYBRID`→Local); `MunicipalityDetailLocal` lê mirror (município + pledges×leaderships); regiões online-only com “Disponível quando estiveres online.”; e2e `campaignOpsOffline` (skip sem flag). Plano: [`oh9-municipio-detalhe-dualpath.md`](docs/plans/oh9-municipio-detalhe-dualpath.md).
|
||||||
|
|
||||||
**Recently resolved (2026-08-01):** **B114** (Issue #195) — wizard Voltar header = Android back: contrato `wizardBack` + `useWizardBackHistory` (pushState/popstate), previousHrefs canônicos, layer form liderança. Plano: [`wizard-back-navigation-system.md`](docs/plans/wizard-back-navigation-system.md).
|
**Recently resolved (2026-08-01):** **B114** (Issue #195) — wizard Voltar header = Android back: contrato `wizardBack` + `useWizardBackHistory` (pushState/popstate), previousHrefs canônicos, layer form liderança. Plano: [`wizard-back-navigation-system.md`](docs/plans/wizard-back-navigation-system.md).
|
||||||
|
|
||||||
**Recently resolved (2026-08-01):** **OH5** (Issue #168) — `CampaignOpsSyncProvider` no layout `(app)`: bootstrap mirror (OPFS file → IDB dump/hydrate + TanStack `localOnly` collections), poll 3 min foreground + `visibilitychange`/`online`, chrome “Actualizado…” / “A sincronizar…” / “Dados podem estar desatualizados”; leader no-op. Plano: [`oh5-sync-provider-mirror.md`](docs/plans/oh5-sync-provider-mirror.md).
|
**Recently resolved (2026-08-01):** **OH5** (Issue #168) — `CampaignOpsSyncProvider` no layout `(app)`: bootstrap mirror (OPFS file → IDB dump/hydrate + TanStack `localOnly` collections), poll 3 min foreground + `visibilitychange`/`online`, chrome “Actualizado…” / “A sincronizar…” / “Dados podem estar desatualizados”; leader no-op. Plano: [`oh5-sync-provider-mirror.md`](docs/plans/oh5-sync-provider-mirror.md).
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
# OH9 — Detalhe de município dual-path (views + Local + OfflineBoundary)
|
# OH9 — Detalhe de município dual-path (views + Local + OfflineBoundary)
|
||||||
|
|
||||||
Status: rascunho
|
Status: entregue (PR)
|
||||||
Atualizado em: 2026-08-01
|
Atualizado em: 2026-08-02
|
||||||
Issue: #172
|
Issue: #172
|
||||||
Priority: P1
|
Priority: P1
|
||||||
Model: cursor-grok-4.5-medium
|
Model: cursor-grok-4.5-medium
|
||||||
|
|
@ -10,13 +10,22 @@ Appetite: ~2–3 dias eng
|
||||||
Depends: OH8, OH5
|
Depends: OH8, OH5
|
||||||
Responsável: —
|
Responsável: —
|
||||||
|
|
||||||
|
## Freshness audit (2026-08-02)
|
||||||
|
|
||||||
|
- OH5 (#168) e OH8 (#170) `done`+`in-prod`. Provider expõe `useOpsOffline()`; collections mirror em `opsMirrorClient` (`municipalitiesCollection`, `votePledgesCollection`; `leadershipsCollection` exportada neste lote).
|
||||||
|
- Página detalhe intacta em `[slug]/page.tsx` (header inline); pins OH8 em `municipalityDetailCharacterization.int.spec.ts` + e2e characterization.
|
||||||
|
- **Sem `@tanstack/react-db`:** só `@tanstack/db@0.6.17`. Local usa `subscribeChanges` nas 3 collections (sem dep nova — Ask first do OH1).
|
||||||
|
- Snapshot **não** inclui `campaignUser` — Local usa “Assessoria: indisponível offline” quando há advisor IDs.
|
||||||
|
- Rota já tem `gate: 'noLeader'`; Local é staff-only na prática; pledges Local reusam `MunicipalityPledgesPanel` + outbox OH6.
|
||||||
|
- E2e airplane: ficheiro novo `campaignOpsOffline.e2e.spec.ts` (OH11 alarga depois); skip sem `OPS_HYBRID` como OH6.
|
||||||
|
|
||||||
## Premissas
|
## Premissas
|
||||||
|
|
||||||
1. Pins de caracterização (OH8) verdes antes de extrair views.
|
1. Pins de caracterização (OH8) verdes antes de extrair views.
|
||||||
2. SSR/primeiro paint **sempre** RSC; Local só renderiza com `OPS_HYBRID` ON + offline.
|
2. SSR/primeiro paint **sempre** RSC; Local só renderiza com `OPS_HYBRID` ON + offline.
|
||||||
3. Sem mini-router: `OfflineBoundary` declarado só nesta rota no v1.
|
3. Sem mini-router: `OfflineBoundary` declarado só nesta rota no v1.
|
||||||
|
|
||||||
→ Corrija agora ou sigo com estas.
|
→ Confirmadas; sigo.
|
||||||
|
|
||||||
## Objetivos
|
## Objetivos
|
||||||
|
|
||||||
|
|
@ -43,11 +52,11 @@ flowchart LR
|
||||||
|
|
||||||
Componentes:
|
Componentes:
|
||||||
|
|
||||||
- **`src/components/campaign/opsSync/OfflineBoundary.tsx`** (novo): spec OH1 — SSR sempre children; `useOpsHybridEnabled() && useOpsOffline()` → fallback.
|
- **`src/components/campaign/opsSync/OfflineBoundary.tsx`** (novo): SSR sempre children; após mount, `OPS_HYBRID` + `navigator.onLine === false` → fallback. Falha de sync **não** troca para Local (chrome cobre).
|
||||||
- **`src/components/campaign/municipality/MunicipalityDetailHeaderView.tsx`** (extração): recebe `view` + `advisorSummaries` por props — o JSX actual do header (h1, `Badge` de kind, `formatMunicipalityGeographyLabel`, linha “Assessoria/Última atualização”).
|
- **`src/components/campaign/municipality/MunicipalityDetailHeaderView.tsx`** (extração): recebe `view` + `advisorSummaries` por props — o JSX actual do header (h1, `Badge` de kind, `formatMunicipalityGeographyLabel`, linha “Assessoria/Última atualização”).
|
||||||
- **`src/components/campaign/municipality/MunicipalityDetailLocal.tsx`** (novo). Mapeamento mirror → view (travado):
|
- **`src/components/campaign/municipality/MunicipalityDetailLocal.tsx`** (novo). Mapeamento mirror → view (travado):
|
||||||
- **Header:** alimentado pelo DTO `OpsMunicipality` (nome, `kind`, geography, advisors ids, `lastUpdateAt`) — `toDetailHeaderView(municipalityDto)` (helper puro novo em `src/lib/campaignOps/`); `advisorSummaries` vêm da collection `campaignUsers`/advisors do mirror quando presente; se ausente → linha “Assessoria: indisponível offline”.
|
- **Header:** alimentado pelo DTO `OpsMunicipality` (nome, `kind`, geography, advisors ids, `lastUpdateAt`) — `toDetailHeaderView(municipalityDto)` (helper puro novo em `src/lib/campaignOps/`); `advisorSummaries` vêm da collection `campaignUsers`/advisors do mirror quando presente; se ausente → linha “Assessoria: indisponível offline”.
|
||||||
- **Pledges:** `useLiveQuery` join `votePledges` × `leaderships` do mirror → mesmo shape de props do painel (`declaredVotes`, faixa de estimativa para staff). Liderança nunca vê `estimatedVotes` — o Local **não monta** o painel de estimativa para role leader (view model por papel, igual ao RSC).
|
- **Pledges:** join `votePledges` × `leaderships` do mirror via `subscribeChanges` (sem `@tanstack/react-db`) → mesmo shape de props do painel (`declaredVotes`, faixa de estimativa para staff). Liderança nunca vê `estimatedVotes` — o Local **não monta** o painel de estimativa para role leader (view model por papel, igual ao RSC).
|
||||||
- **Online-only (mensagem honesta, não crash):** tabs (Visão geral/Tarefas/Atualizações), updates feed, dossiê eleitoral/TSE, mapa. Renderiza placeholder pt-BR: “Disponível quando estiveres online.”
|
- **Online-only (mensagem honesta, não crash):** tabs (Visão geral/Tarefas/Atualizações), updates feed, dossiê eleitoral/TSE, mapa. Renderiza placeholder pt-BR: “Disponível quando estiveres online.”
|
||||||
- **Page** (alterado): envolve o conteúdo actual com `OfflineBoundary` passando `fallback={<MunicipalityDetailLocal slug={slug} />}`.
|
- **Page** (alterado): envolve o conteúdo actual com `OfflineBoundary` passando `fallback={<MunicipalityDetailLocal slug={slug} />}`.
|
||||||
|
|
||||||
|
|
@ -58,8 +67,8 @@ Componentes:
|
||||||
- **Quota:** ~0,4
|
- **Quota:** ~0,4
|
||||||
- **Entrega:** header extraído; RSC renderiza pela view nova; pins OH8 verdes.
|
- **Entrega:** header extraído; RSC renderiza pela view nova; pins OH8 verdes.
|
||||||
- **Aceite:**
|
- **Aceite:**
|
||||||
- [ ] `pnpm gate:fast` + pins caracterização verdes
|
- [x] `pnpm gate:fast` + pins caracterização verdes
|
||||||
- [ ] diff visual zero (check manual)
|
- [x] diff visual zero (check manual)
|
||||||
- **Verify:** gate + specs OH8
|
- **Verify:** gate + specs OH8
|
||||||
- **Files:** `MunicipalityDetailHeaderView.tsx`, page
|
- **Files:** `MunicipalityDetailHeaderView.tsx`, page
|
||||||
- **Tamanho:** M
|
- **Tamanho:** M
|
||||||
|
|
@ -69,11 +78,11 @@ Componentes:
|
||||||
- **Quota:** ~0,6
|
- **Quota:** ~0,6
|
||||||
- **Entrega:** `MunicipalityDetailLocal` + `OfflineBoundary` ligados; e2e airplane.
|
- **Entrega:** `MunicipalityDetailLocal` + `OfflineBoundary` ligados; e2e airplane.
|
||||||
- **Aceite:**
|
- **Aceite:**
|
||||||
- [ ] online: Network mostra Flight; UI igual
|
- [x] online: Network mostra Flight; UI igual
|
||||||
- [ ] offline (flag ON): header + pledges do mirror; empty state fora do mirror
|
- [x] offline (flag ON): header + pledges do mirror; empty state fora do mirror
|
||||||
- [ ] tabs/regiões online-only com mensagem honesta (não crash)
|
- [x] tabs/regiões online-only com mensagem honesta (não crash)
|
||||||
- [ ] leader nunca vê `estimatedVotes` (view model por papel mantido no Local)
|
- [x] leader nunca vê `estimatedVotes` (view model por papel mantido no Local)
|
||||||
- **Verify:** `pnpm gate:fast` + `tests/e2e/campaign-ops-offline.e2e.spec.ts`
|
- **Verify:** `pnpm gate:fast` + `tests/e2e/campaignOpsOffline.e2e.spec.ts`
|
||||||
- **Files:** Local, boundary, page, spec e2e
|
- **Files:** Local, boundary, page, spec e2e
|
||||||
- **Tamanho:** M
|
- **Tamanho:** M
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -5,18 +5,17 @@ import { getPayload } from 'payload'
|
||||||
import { Suspense } from 'react'
|
import { Suspense } from 'react'
|
||||||
|
|
||||||
import { RecentVisitTracker } from '@/components/campaign/dashboard/RecentVisitTracker'
|
import { RecentVisitTracker } from '@/components/campaign/dashboard/RecentVisitTracker'
|
||||||
|
import { MunicipalityDetailHeaderView } from '@/components/campaign/municipality/MunicipalityDetailHeaderView'
|
||||||
|
import { MunicipalityDetailLocal } from '@/components/campaign/municipality/MunicipalityDetailLocal'
|
||||||
import { MunicipalityTabNav } from '@/components/campaign/municipality/MunicipalityTabNav'
|
import { MunicipalityTabNav } from '@/components/campaign/municipality/MunicipalityTabNav'
|
||||||
|
import { OfflineBoundary } from '@/components/campaign/opsSync/OfflineBoundary'
|
||||||
import { CampaignPageShell } from '@/components/campaign/shell/CampaignPageShell'
|
import { CampaignPageShell } from '@/components/campaign/shell/CampaignPageShell'
|
||||||
import { Badge } from '@/components/ui/Badge'
|
import { toDetailHeaderView } from '@/lib/campaignOps/municipalityDetailHeaderView'
|
||||||
import { requireCampaignPageActor } from '@/utilities/campaignPageActor'
|
import { requireCampaignPageActor } from '@/utilities/campaignPageActor'
|
||||||
import {
|
import {
|
||||||
resolveMunicipalityDetailTab,
|
resolveMunicipalityDetailTab,
|
||||||
type MunicipalityDetailSearchParams,
|
type MunicipalityDetailSearchParams,
|
||||||
} from '@/utilities/municipality/municipalityDetailTabUi'
|
} from '@/utilities/municipality/municipalityDetailTabUi'
|
||||||
import {
|
|
||||||
formatMunicipalityGeographyLabel,
|
|
||||||
municipalityKindLabels,
|
|
||||||
} from '@/utilities/municipality/municipalityLabels'
|
|
||||||
import {
|
import {
|
||||||
getMunicipalityDetailViewModel,
|
getMunicipalityDetailViewModel,
|
||||||
MunicipalityNotFoundError,
|
MunicipalityNotFoundError,
|
||||||
|
|
@ -38,8 +37,6 @@ type MunicipalityDetailPageProps = {
|
||||||
searchParams: Promise<MunicipalityDetailSearchParams>
|
searchParams: Promise<MunicipalityDetailSearchParams>
|
||||||
}
|
}
|
||||||
|
|
||||||
const dateFormatter = new Intl.DateTimeFormat('pt-BR')
|
|
||||||
|
|
||||||
export default async function MunicipalityDetailPage({
|
export default async function MunicipalityDetailPage({
|
||||||
params,
|
params,
|
||||||
searchParams,
|
searchParams,
|
||||||
|
|
@ -62,99 +59,94 @@ export default async function MunicipalityDetailPage({
|
||||||
const view = await getMunicipalityDetailViewModel(payload, context, user)
|
const view = await getMunicipalityDetailViewModel(payload, context, user)
|
||||||
|
|
||||||
const advisorSummaries = await loadAdvisorSummaries(payload, user, view.advisorIDs)
|
const advisorSummaries = await loadAdvisorSummaries(payload, user, view.advisorIDs)
|
||||||
|
const headerView = toDetailHeaderView({
|
||||||
|
name: view.name,
|
||||||
|
kind: view.kind,
|
||||||
|
region: view.region,
|
||||||
|
zoneNumber: view.zoneNumber,
|
||||||
|
lastUpdateAt: view.lastUpdateAt,
|
||||||
|
})
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<CampaignPageShell>
|
<CampaignPageShell>
|
||||||
{/* print: the dossier tab carries its own capa; page chrome stays out. */}
|
<OfflineBoundary fallback={<MunicipalityDetailLocal slug={slug} />}>
|
||||||
<header className="flex flex-col gap-2 print:hidden">
|
{/* print: the dossier tab carries its own capa; page chrome stays out. */}
|
||||||
<div className="flex flex-wrap items-center gap-2">
|
<MunicipalityDetailHeaderView view={headerView} advisorSummaries={advisorSummaries} />
|
||||||
<h1 className="text-2xl font-semibold tracking-tight">{view.name}</h1>
|
|
||||||
<Badge variant="scope">{municipalityKindLabels[view.kind]}</Badge>
|
|
||||||
</div>
|
|
||||||
<p className="text-muted-foreground">{formatMunicipalityGeographyLabel(view)}</p>
|
|
||||||
<p className="text-sm text-muted-foreground">
|
|
||||||
{advisorSummaries.length
|
|
||||||
? `Assessoria: ${advisorSummaries.map((advisor) => advisor.name).join(', ')}`
|
|
||||||
: 'Sem assessor designado.'}
|
|
||||||
{view.lastUpdateAt
|
|
||||||
? ` · Última atualização em ${dateFormatter.format(new Date(view.lastUpdateAt))}`
|
|
||||||
: ''}
|
|
||||||
</p>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
<MunicipalityTabNav
|
<MunicipalityTabNav
|
||||||
activeTab={activeTab}
|
activeTab={activeTab}
|
||||||
municipalitySlug={view.slug}
|
municipalitySlug={view.slug}
|
||||||
searchParams={rawSearchParams}
|
searchParams={rawSearchParams}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{activeTab === 'overview' ? (
|
{activeTab === 'overview' ? (
|
||||||
<OverviewTab view={view} payloadUser={{ payload, user }} />
|
<OverviewTab view={view} payloadUser={{ payload, user }} />
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{activeTab === 'dossie' ? (
|
{activeTab === 'dossie' ? (
|
||||||
// Composes every vertical of the município in one read — streams like
|
// Composes every vertical of the município in one read — streams like
|
||||||
// the elections tab since it includes the same TSE baseline read.
|
// the elections tab since it includes the same TSE baseline read.
|
||||||
<Suspense fallback={<MunicipalityTabFallback />}>
|
<Suspense fallback={<MunicipalityTabFallback />}>
|
||||||
<DossierTab
|
<DossierTab
|
||||||
view={view}
|
view={view}
|
||||||
advisorSummaries={advisorSummaries}
|
advisorSummaries={advisorSummaries}
|
||||||
payloadUser={{ payload, user }}
|
payloadUser={{ payload, user }}
|
||||||
/>
|
/>
|
||||||
</Suspense>
|
</Suspense>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{activeTab === 'elections' ? (
|
{activeTab === 'elections' ? (
|
||||||
// Streams below the header/tab chrome — the TSE baselines and the
|
// Streams below the header/tab chrome — the TSE baselines and the
|
||||||
// comparison table are the slowest reads on this page.
|
// comparison table are the slowest reads on this page.
|
||||||
<Suspense fallback={<MunicipalityTabFallback />}>
|
<Suspense fallback={<MunicipalityTabFallback />}>
|
||||||
<ElectionsTab
|
<ElectionsTab
|
||||||
slug={view.slug}
|
slug={view.slug}
|
||||||
rawSearchParams={rawSearchParams}
|
rawSearchParams={rawSearchParams}
|
||||||
payloadUser={{ payload, user }}
|
payloadUser={{ payload, user }}
|
||||||
/>
|
/>
|
||||||
</Suspense>
|
</Suspense>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{activeTab === 'leaderships' ? (
|
{activeTab === 'leaderships' ? (
|
||||||
<Suspense fallback={<MunicipalityTabFallback />}>
|
<Suspense fallback={<MunicipalityTabFallback />}>
|
||||||
<LeadershipsTab municipalityID={view.id} payloadUser={{ payload, user }} />
|
<LeadershipsTab municipalityID={view.id} payloadUser={{ payload, user }} />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{activeTab === 'updates' ? (
|
{activeTab === 'updates' ? (
|
||||||
<Suspense fallback={<MunicipalityTabFallback />}>
|
<Suspense fallback={<MunicipalityTabFallback />}>
|
||||||
<UpdatesTab
|
<UpdatesTab
|
||||||
municipalityID={view.id}
|
municipalityID={view.id}
|
||||||
municipalitySlug={view.slug}
|
municipalitySlug={view.slug}
|
||||||
rawSearchParams={rawSearchParams}
|
rawSearchParams={rawSearchParams}
|
||||||
payloadUser={{ payload, user }}
|
payloadUser={{ payload, user }}
|
||||||
/>
|
/>
|
||||||
</Suspense>
|
</Suspense>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{activeTab === 'demands' ? (
|
{activeTab === 'demands' ? (
|
||||||
<section className="rounded-xl border px-4 py-6">
|
<section className="rounded-xl border px-4 py-6">
|
||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-sm text-muted-foreground">
|
||||||
As demandas deste município aparecem em{' '}
|
As demandas deste município aparecem em{' '}
|
||||||
<Link
|
<Link
|
||||||
href="/campanha/demandas"
|
href="/campanha/demandas"
|
||||||
className="text-primary underline-offset-4 hover:underline"
|
className="text-primary underline-offset-4 hover:underline"
|
||||||
>
|
>
|
||||||
Demandas
|
Demandas
|
||||||
</Link>
|
</Link>
|
||||||
.
|
.
|
||||||
</p>
|
</p>
|
||||||
</section>
|
</section>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
<RecentVisitTracker
|
<RecentVisitTracker
|
||||||
entry={{
|
entry={{
|
||||||
href: `/campanha/municipios/${view.slug}`,
|
href: `/campanha/municipios/${view.slug}`,
|
||||||
label: view.name,
|
label: view.name,
|
||||||
kind: 'municipality',
|
kind: 'municipality',
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
</OfflineBoundary>
|
||||||
</CampaignPageShell>
|
</CampaignPageShell>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,50 @@
|
||||||
|
import { Badge } from '@/components/ui/Badge'
|
||||||
|
import type { MunicipalityDetailHeaderViewModel } from '@/lib/campaignOps/municipalityDetailHeaderView'
|
||||||
|
import {
|
||||||
|
formatMunicipalityGeographyLabel,
|
||||||
|
municipalityKindLabels,
|
||||||
|
} from '@/utilities/municipality/municipalityLabels'
|
||||||
|
|
||||||
|
const dateFormatter = new Intl.DateTimeFormat('pt-BR')
|
||||||
|
|
||||||
|
type MunicipalityDetailHeaderAdvisorSummary = {
|
||||||
|
name: string
|
||||||
|
}
|
||||||
|
|
||||||
|
type MunicipalityDetailHeaderViewProps = {
|
||||||
|
view: MunicipalityDetailHeaderViewModel
|
||||||
|
advisorSummaries: ReadonlyArray<MunicipalityDetailHeaderAdvisorSummary>
|
||||||
|
/**
|
||||||
|
* Mirror has advisor IDs but no campaignUser rows — cannot resolve names offline.
|
||||||
|
* When true, the assessoria line is the honest offline copy regardless of summaries.
|
||||||
|
*/
|
||||||
|
advisorsUnavailable?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export const MunicipalityDetailHeaderView = ({
|
||||||
|
view,
|
||||||
|
advisorSummaries,
|
||||||
|
advisorsUnavailable = false,
|
||||||
|
}: MunicipalityDetailHeaderViewProps) => {
|
||||||
|
const advisorLine = advisorsUnavailable
|
||||||
|
? 'Assessoria: indisponível offline'
|
||||||
|
: advisorSummaries.length
|
||||||
|
? `Assessoria: ${advisorSummaries.map((advisor) => advisor.name).join(', ')}`
|
||||||
|
: 'Sem assessor designado.'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<header className="flex flex-col gap-2 print:hidden">
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<h1 className="text-2xl font-semibold tracking-tight">{view.name}</h1>
|
||||||
|
<Badge variant="scope">{municipalityKindLabels[view.kind]}</Badge>
|
||||||
|
</div>
|
||||||
|
<p className="text-muted-foreground">{formatMunicipalityGeographyLabel(view)}</p>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
{advisorLine}
|
||||||
|
{view.lastUpdateAt
|
||||||
|
? ` · Última atualização em ${dateFormatter.format(new Date(view.lastUpdateAt))}`
|
||||||
|
: ''}
|
||||||
|
</p>
|
||||||
|
</header>
|
||||||
|
)
|
||||||
|
}
|
||||||
112
src/components/campaign/municipality/MunicipalityDetailLocal.tsx
Normal file
112
src/components/campaign/municipality/MunicipalityDetailLocal.tsx
Normal file
|
|
@ -0,0 +1,112 @@
|
||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useEffect, useRef, useState } from 'react'
|
||||||
|
|
||||||
|
import { estimateVotesFormAction } from '@/app/(campaign)/campanha/(app)/municipios/[slug]/pledgeFormActions'
|
||||||
|
import { MunicipalityDetailHeaderView } from '@/components/campaign/municipality/MunicipalityDetailHeaderView'
|
||||||
|
import { MunicipalityPledgesPanel } from '@/components/campaign/municipality/MunicipalityPledgesPanel'
|
||||||
|
import {
|
||||||
|
leadershipsCollection,
|
||||||
|
municipalitiesCollection,
|
||||||
|
votePledgesCollection,
|
||||||
|
} from '@/components/campaign/opsSync/opsMirrorClient'
|
||||||
|
import { toDetailHeaderView } from '@/lib/campaignOps/municipalityDetailHeaderView'
|
||||||
|
import {
|
||||||
|
findOpsMunicipalityBySlug,
|
||||||
|
toLocalStaffPledgeRows,
|
||||||
|
type OpsLocalStaffPledgeRow,
|
||||||
|
} from '@/lib/campaignOps/municipalityDetailLocalViews'
|
||||||
|
import type { OpsMunicipality } from '@/lib/campaignOps/opsContract'
|
||||||
|
|
||||||
|
const ONLINE_ONLY_MESSAGE = 'Disponível quando estiveres online.'
|
||||||
|
|
||||||
|
type MunicipalityDetailLocalProps = {
|
||||||
|
slug: string
|
||||||
|
}
|
||||||
|
|
||||||
|
type LocalDetailSnapshot = {
|
||||||
|
municipality: OpsMunicipality | null
|
||||||
|
pledges: OpsLocalStaffPledgeRow[]
|
||||||
|
}
|
||||||
|
|
||||||
|
const readLocalDetailSnapshot = (slug: string): LocalDetailSnapshot => {
|
||||||
|
const municipality = findOpsMunicipalityBySlug(municipalitiesCollection.toArray, slug)
|
||||||
|
return {
|
||||||
|
municipality,
|
||||||
|
pledges: municipality
|
||||||
|
? toLocalStaffPledgeRows(
|
||||||
|
municipality.id,
|
||||||
|
votePledgesCollection.toArray,
|
||||||
|
leadershipsCollection.toArray,
|
||||||
|
)
|
||||||
|
: [],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Offline Local path for municipality detail (OH9). Reads municipality +
|
||||||
|
* pledges × leaderships from the ops mirror. Online-only regions (tabs TSE,
|
||||||
|
* dossier, updates feed, map) render an honest placeholder — no crash.
|
||||||
|
*/
|
||||||
|
export const MunicipalityDetailLocal = ({ slug }: MunicipalityDetailLocalProps) => {
|
||||||
|
const [snapshot, setSnapshot] = useState<LocalDetailSnapshot>(() => readLocalDetailSnapshot(slug))
|
||||||
|
const coalesceRef = useRef<(() => void) | null>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const refresh = () => {
|
||||||
|
// replaceCollectionRows emits per-row changes — coalesce to one snapshot
|
||||||
|
// rebuild per microtask while Local is mounted.
|
||||||
|
if (coalesceRef.current) return
|
||||||
|
coalesceRef.current = () => {
|
||||||
|
coalesceRef.current = null
|
||||||
|
setSnapshot(readLocalDetailSnapshot(slug))
|
||||||
|
}
|
||||||
|
queueMicrotask(coalesceRef.current)
|
||||||
|
}
|
||||||
|
refresh()
|
||||||
|
const subscriptions = [
|
||||||
|
municipalitiesCollection.subscribeChanges(refresh),
|
||||||
|
votePledgesCollection.subscribeChanges(refresh),
|
||||||
|
leadershipsCollection.subscribeChanges(refresh),
|
||||||
|
]
|
||||||
|
return () => {
|
||||||
|
for (const subscription of subscriptions) subscription.unsubscribe()
|
||||||
|
coalesceRef.current = null
|
||||||
|
}
|
||||||
|
}, [slug])
|
||||||
|
|
||||||
|
const { municipality, pledges } = snapshot
|
||||||
|
|
||||||
|
if (!municipality) {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col gap-4">
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Este município não está no espelho offline. {ONLINE_ONLY_MESSAGE}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const headerView = toDetailHeaderView(municipality)
|
||||||
|
const advisorsUnavailable = (municipality.advisors?.length ?? 0) > 0
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col gap-6">
|
||||||
|
<MunicipalityDetailHeaderView
|
||||||
|
view={headerView}
|
||||||
|
advisorSummaries={[]}
|
||||||
|
advisorsUnavailable={advisorsUnavailable}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<MunicipalityPledgesPanel
|
||||||
|
pledges={pledges}
|
||||||
|
opsHybridEnabled
|
||||||
|
estimateFormAction={estimateVotesFormAction}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<section aria-label="Conteúdo disponível só online" className="rounded-xl border px-4 py-6">
|
||||||
|
<p className="text-sm text-muted-foreground">{ONLINE_ONLY_MESSAGE}</p>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
44
src/components/campaign/opsSync/OfflineBoundary.tsx
Normal file
44
src/components/campaign/opsSync/OfflineBoundary.tsx
Normal file
|
|
@ -0,0 +1,44 @@
|
||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useEffect, useState, type ReactNode } from 'react'
|
||||||
|
|
||||||
|
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Dual-path shell (OH9): SSR and first client paint always render `children`
|
||||||
|
* (RSC). After mount, when OPS_HYBRID is on and the *browser* is offline,
|
||||||
|
* swap to `fallback` (Local mirror view).
|
||||||
|
*
|
||||||
|
* Sync-failure is intentionally NOT a Local trigger — RSC still works online;
|
||||||
|
* chrome owns “Dados podem estar desatualizados” via `useOpsOffline()`.
|
||||||
|
*
|
||||||
|
* `display: contents` keeps page shell flex/gap intact — this wrapper must not
|
||||||
|
* become the sole flex child of `CampaignPageShell`.
|
||||||
|
*/
|
||||||
|
export const OfflineBoundary = ({
|
||||||
|
children,
|
||||||
|
fallback,
|
||||||
|
}: {
|
||||||
|
children: ReactNode
|
||||||
|
fallback: ReactNode
|
||||||
|
}) => {
|
||||||
|
const hybrid = resolveOpsHybridEnabled()
|
||||||
|
const [mounted, setMounted] = useState(false)
|
||||||
|
const [browserOffline, setBrowserOffline] = useState(false)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setMounted(true)
|
||||||
|
setBrowserOffline(typeof navigator !== 'undefined' ? !navigator.onLine : false)
|
||||||
|
|
||||||
|
const onOnline = () => setBrowserOffline(false)
|
||||||
|
const onOffline = () => setBrowserOffline(true)
|
||||||
|
window.addEventListener('online', onOnline)
|
||||||
|
window.addEventListener('offline', onOffline)
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('online', onOnline)
|
||||||
|
window.removeEventListener('offline', onOffline)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
return <div className="contents">{mounted && hybrid && browserOffline ? fallback : children}</div>
|
||||||
|
}
|
||||||
|
|
@ -37,8 +37,8 @@ const createRowCollection = <T extends { id: number }>(id: string) =>
|
||||||
)
|
)
|
||||||
|
|
||||||
export const municipalitiesCollection = createRowCollection<OpsMunicipality>('ops-municipalities')
|
export const municipalitiesCollection = createRowCollection<OpsMunicipality>('ops-municipalities')
|
||||||
const leadershipsCollection = createRowCollection<OpsLeadership>('ops-leaderships')
|
export const leadershipsCollection = createRowCollection<OpsLeadership>('ops-leaderships')
|
||||||
export { votePledgesCollection } from '@/components/campaign/opsSync/opsVotePledgeMirror'
|
export { votePledgesCollection }
|
||||||
const activitiesCollection = createRowCollection<OpsActivity>('ops-activities')
|
const activitiesCollection = createRowCollection<OpsActivity>('ops-activities')
|
||||||
const stateDeputiesCollection = createRowCollection<OpsStateDeputy>('ops-state-deputies')
|
const stateDeputiesCollection = createRowCollection<OpsStateDeputy>('ops-state-deputies')
|
||||||
const organizationsCollection = createRowCollection<OpsOrganization>('ops-organizations')
|
const organizationsCollection = createRowCollection<OpsOrganization>('ops-organizations')
|
||||||
|
|
|
||||||
20
src/lib/campaignOps/municipalityDetailHeaderView.ts
Normal file
20
src/lib/campaignOps/municipalityDetailHeaderView.ts
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
import type { OpsMunicipality } from '@/lib/campaignOps/opsContract'
|
||||||
|
|
||||||
|
/** Presentational header slice shared by RSC detail and Local offline (OH9). */
|
||||||
|
export type MunicipalityDetailHeaderViewModel = {
|
||||||
|
name: string
|
||||||
|
kind: OpsMunicipality['kind']
|
||||||
|
region: string
|
||||||
|
zoneNumber: number | null
|
||||||
|
lastUpdateAt: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export const toDetailHeaderView = (
|
||||||
|
municipality: Pick<OpsMunicipality, 'name' | 'kind' | 'region' | 'zoneNumber' | 'lastUpdateAt'>,
|
||||||
|
): MunicipalityDetailHeaderViewModel => ({
|
||||||
|
name: municipality.name,
|
||||||
|
kind: municipality.kind,
|
||||||
|
region: municipality.region,
|
||||||
|
zoneNumber: municipality.zoneNumber ?? null,
|
||||||
|
lastUpdateAt: municipality.lastUpdateAt ?? null,
|
||||||
|
})
|
||||||
47
src/lib/campaignOps/municipalityDetailLocalViews.ts
Normal file
47
src/lib/campaignOps/municipalityDetailLocalViews.ts
Normal file
|
|
@ -0,0 +1,47 @@
|
||||||
|
import type { OpsLeadership, OpsMunicipality, OpsVotePledge } from '@/lib/campaignOps/opsContract'
|
||||||
|
import {
|
||||||
|
toVoteEstimateScenarioViewModel,
|
||||||
|
type VoteEstimateScenarioViewModel,
|
||||||
|
} from '@/lib/voteEstimate'
|
||||||
|
|
||||||
|
/** Mirror→panel row — structural match for `StaffPledgeRow` without importing utilities. */
|
||||||
|
export type OpsLocalStaffPledgeRow = {
|
||||||
|
id: number
|
||||||
|
leadershipID: number
|
||||||
|
contactName: string
|
||||||
|
declaredVotes: number
|
||||||
|
declaredAt: string | null
|
||||||
|
estimatedVotes: VoteEstimateScenarioViewModel
|
||||||
|
estimateNote: string | null
|
||||||
|
estimatedAt: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export const findOpsMunicipalityBySlug = (
|
||||||
|
municipalities: ReadonlyArray<OpsMunicipality>,
|
||||||
|
slug: string,
|
||||||
|
): OpsMunicipality | null => municipalities.find((row) => row.slug === slug) ?? null
|
||||||
|
|
||||||
|
export const toLocalStaffPledgeRows = (
|
||||||
|
municipalityId: number,
|
||||||
|
pledges: ReadonlyArray<OpsVotePledge>,
|
||||||
|
leaderships: ReadonlyArray<OpsLeadership>,
|
||||||
|
): OpsLocalStaffPledgeRow[] => {
|
||||||
|
const leadershipById = new Map(leaderships.map((row) => [row.id, row]))
|
||||||
|
|
||||||
|
return pledges
|
||||||
|
.filter((pledge) => pledge.municipality === municipalityId)
|
||||||
|
.map((pledge) => {
|
||||||
|
const leadership = leadershipById.get(pledge.leadership)
|
||||||
|
return {
|
||||||
|
id: pledge.id,
|
||||||
|
leadershipID: pledge.leadership,
|
||||||
|
contactName: leadership?.contact.name ?? 'Liderança',
|
||||||
|
declaredVotes: pledge.declaredVotes,
|
||||||
|
declaredAt: pledge.declaredAt ?? null,
|
||||||
|
estimatedVotes: toVoteEstimateScenarioViewModel(pledge.estimatedVotes),
|
||||||
|
estimateNote: pledge.estimateNote ?? null,
|
||||||
|
estimatedAt: pledge.estimatedAt ?? null,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.sort((left, right) => left.contactName.localeCompare(right.contactName, 'pt-BR'))
|
||||||
|
}
|
||||||
68
tests/e2e/campaignOpsOffline.e2e.spec.ts
Normal file
68
tests/e2e/campaignOpsOffline.e2e.spec.ts
Normal file
|
|
@ -0,0 +1,68 @@
|
||||||
|
import { expect, test } from './fixtures/campaignE2EFixtures.js'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* OH9 — dual-path municipality detail. Requires `OPS_HYBRID=1` on the
|
||||||
|
* Playwright webServer (compile-time). Default CI keeps the flag off so
|
||||||
|
* characterization / municipalities specs continue to pin the RSC path.
|
||||||
|
*/
|
||||||
|
const opsHybridEnabled =
|
||||||
|
process.env.OPS_HYBRID === '1' || process.env.OPS_HYBRID?.toLowerCase() === 'true'
|
||||||
|
|
||||||
|
test.describe('OH9 municipality detail dual-path (OPS_HYBRID)', () => {
|
||||||
|
test.skip(!opsHybridEnabled, 'Set OPS_HYBRID=1 on the e2e webServer to run this dual-path.')
|
||||||
|
|
||||||
|
test('offline swaps to Local header + pledges with honest online-only placeholder', async ({
|
||||||
|
campaign,
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
const { fixtures } = campaign
|
||||||
|
const municipality = await fixtures.claimMunicipality()
|
||||||
|
const advisor = await fixtures.createCampaignUser('advisor', {
|
||||||
|
name: fixtures.value('Assessor OH9'),
|
||||||
|
})
|
||||||
|
await campaign.payload.update({
|
||||||
|
collection: 'municipality',
|
||||||
|
id: municipality.id,
|
||||||
|
data: { advisors: [advisor.id] },
|
||||||
|
depth: 0,
|
||||||
|
})
|
||||||
|
fixtures.touchMunicipality(municipality.id)
|
||||||
|
|
||||||
|
const { leadershipId } = await fixtures.createStaffLeadership({
|
||||||
|
namePrefix: 'Liderança OH9',
|
||||||
|
municipalities: [municipality],
|
||||||
|
supportStatus: 'engajado',
|
||||||
|
})
|
||||||
|
await campaign.payload.create({
|
||||||
|
collection: 'votePledge',
|
||||||
|
data: {
|
||||||
|
leadership: leadershipId,
|
||||||
|
municipality: municipality.id,
|
||||||
|
declaredVotes: 90,
|
||||||
|
},
|
||||||
|
depth: 0,
|
||||||
|
})
|
||||||
|
|
||||||
|
await campaign.login(page, advisor.email!, advisor.password)
|
||||||
|
await page.goto(`${campaign.baseURL}/campanha/municipios/${municipality.slug}`)
|
||||||
|
await expect(page.getByRole('heading', { name: municipality.name })).toBeVisible()
|
||||||
|
|
||||||
|
// Wait for ops-sync so the mirror has this município before airplane mode.
|
||||||
|
await page.waitForResponse(
|
||||||
|
(response) =>
|
||||||
|
response.url().includes('/campanha/api/ops-sync') && response.request().method() === 'GET',
|
||||||
|
{ timeout: 30_000 },
|
||||||
|
)
|
||||||
|
|
||||||
|
await page.context().setOffline(true)
|
||||||
|
|
||||||
|
await expect(page.getByRole('heading', { name: municipality.name })).toBeVisible()
|
||||||
|
await expect(page.getByText('Assessoria: indisponível offline')).toBeVisible()
|
||||||
|
await expect(
|
||||||
|
page.getByRole('region', { name: 'Votos declarados pelas lideranças' }),
|
||||||
|
).toBeVisible()
|
||||||
|
await expect(page.getByText('Disponível quando estiveres online.')).toBeVisible()
|
||||||
|
// Tab nav is RSC-only — Local path must not crash by remounting it.
|
||||||
|
await expect(page.getByRole('link', { name: 'Visão geral' })).toHaveCount(0)
|
||||||
|
})
|
||||||
|
})
|
||||||
94
tests/unit/municipalityDetailLocalViews.unit.spec.ts
Normal file
94
tests/unit/municipalityDetailLocalViews.unit.spec.ts
Normal file
|
|
@ -0,0 +1,94 @@
|
||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
|
||||||
|
import { toDetailHeaderView } from '@/lib/campaignOps/municipalityDetailHeaderView'
|
||||||
|
import {
|
||||||
|
findOpsMunicipalityBySlug,
|
||||||
|
toLocalStaffPledgeRows,
|
||||||
|
} from '@/lib/campaignOps/municipalityDetailLocalViews'
|
||||||
|
import type { OpsLeadership, OpsMunicipality, OpsVotePledge } from '@/lib/campaignOps/opsContract'
|
||||||
|
|
||||||
|
const municipality = (
|
||||||
|
partial: Partial<OpsMunicipality> & Pick<OpsMunicipality, 'id' | 'slug'>,
|
||||||
|
): OpsMunicipality => ({
|
||||||
|
name: 'Feira de Santana',
|
||||||
|
kind: 'municipio',
|
||||||
|
city: 'Feira de Santana',
|
||||||
|
region: 'Portal do Sertão',
|
||||||
|
ibgeCode: '2910800',
|
||||||
|
updatedAt: '2026-08-01T00:00:00.000Z',
|
||||||
|
...partial,
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('municipalityDetailHeaderView (OH9)', () => {
|
||||||
|
it('maps OpsMunicipality fields into the presentational header slice', () => {
|
||||||
|
const view = toDetailHeaderView(
|
||||||
|
municipality({
|
||||||
|
id: 1,
|
||||||
|
slug: 'feira-de-santana',
|
||||||
|
zoneNumber: null,
|
||||||
|
lastUpdateAt: '2026-07-15T12:00:00.000Z',
|
||||||
|
advisors: [10, 11],
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(view).toEqual({
|
||||||
|
name: 'Feira de Santana',
|
||||||
|
kind: 'municipio',
|
||||||
|
region: 'Portal do Sertão',
|
||||||
|
zoneNumber: null,
|
||||||
|
lastUpdateAt: '2026-07-15T12:00:00.000Z',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('municipalityDetailLocalViews (OH9)', () => {
|
||||||
|
it('finds a municipality by slug and joins pledges to leadership contact names', () => {
|
||||||
|
const rows = [
|
||||||
|
municipality({ id: 1, slug: 'feira-de-santana' }),
|
||||||
|
municipality({ id: 2, slug: 'salvador-ze-1', name: 'Salvador — ZE 1', kind: 'zona' }),
|
||||||
|
]
|
||||||
|
expect(findOpsMunicipalityBySlug(rows, 'salvador-ze-1')?.id).toBe(2)
|
||||||
|
expect(findOpsMunicipalityBySlug(rows, 'missing')).toBeNull()
|
||||||
|
|
||||||
|
const leaderships: OpsLeadership[] = [
|
||||||
|
{
|
||||||
|
id: 5,
|
||||||
|
contact: { id: 50, name: 'Ana Líder' },
|
||||||
|
municipalities: [1],
|
||||||
|
supportStatus: 'engajado',
|
||||||
|
updatedAt: '2026-08-01T00:00:00.000Z',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
const pledges: OpsVotePledge[] = [
|
||||||
|
{
|
||||||
|
id: 9,
|
||||||
|
leadership: 5,
|
||||||
|
municipality: 1,
|
||||||
|
declaredVotes: 120,
|
||||||
|
declaredAt: '2026-07-20T00:00:00.000Z',
|
||||||
|
estimatedVotes: { pessimistic: 80, central: 100, optimistic: 130 },
|
||||||
|
estimateNote: 'Campo',
|
||||||
|
estimatedAt: '2026-07-21T00:00:00.000Z',
|
||||||
|
updatedAt: '2026-07-21T00:00:00.000Z',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 10,
|
||||||
|
leadership: 5,
|
||||||
|
municipality: 2,
|
||||||
|
declaredVotes: 10,
|
||||||
|
updatedAt: '2026-07-21T00:00:00.000Z',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
const localRows = toLocalStaffPledgeRows(1, pledges, leaderships)
|
||||||
|
expect(localRows).toHaveLength(1)
|
||||||
|
expect(localRows[0]).toMatchObject({
|
||||||
|
id: 9,
|
||||||
|
leadershipID: 5,
|
||||||
|
contactName: 'Ana Líder',
|
||||||
|
declaredVotes: 120,
|
||||||
|
estimatedVotes: { pessimistic: 80, central: 100, optimistic: 130 },
|
||||||
|
estimateNote: 'Campo',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
Loading…
Reference in a new issue