mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-26 21:53:06 +00:00
OH9: dual-path municipality detail (HeaderView + Local + OfflineBoundary)
Extract presentational header shared by RSC and offline Local; OfflineBoundary swaps to mirror-backed Local only when OPS_HYBRID is on and the browser is offline (sync failure stays on RSC + chrome). Closes #172. Co-authored-by: Francisco Solla <fsolla@users.noreply.github.com>
This commit is contained in:
parent
49d12b875f
commit
4e65559fdd
11 changed files with 546 additions and 101 deletions
|
|
@ -4,7 +4,11 @@ Conteúdo movido do `AGENTS.md` em 2026-07-30 (fatiamento do paradigma de agente
|
|||
|
||||
---
|
||||
|
||||
<<<<<<< HEAD
|
||||
**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-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).
|
||||
>>>>>>> 719e35ce (OH9: dual-path municipality detail (HeaderView + Local + OfflineBoundary))
|
||||
|
||||
**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)
|
||||
|
||||
Status: rascunho
|
||||
Atualizado em: 2026-08-01
|
||||
Status: entregue (PR)
|
||||
Atualizado em: 2026-08-02
|
||||
Issue: #172
|
||||
Priority: P1
|
||||
Model: cursor-grok-4.5-medium
|
||||
|
|
@ -10,13 +10,22 @@ Appetite: ~2–3 dias eng
|
|||
Depends: OH8, OH5
|
||||
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
|
||||
|
||||
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.
|
||||
3. Sem mini-router: `OfflineBoundary` declarado só nesta rota no v1.
|
||||
|
||||
→ Corrija agora ou sigo com estas.
|
||||
→ Confirmadas; sigo.
|
||||
|
||||
## Objetivos
|
||||
|
||||
|
|
@ -43,11 +52,11 @@ flowchart LR
|
|||
|
||||
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/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”.
|
||||
- **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.”
|
||||
- **Page** (alterado): envolve o conteúdo actual com `OfflineBoundary` passando `fallback={<MunicipalityDetailLocal slug={slug} />}`.
|
||||
|
||||
|
|
@ -58,8 +67,8 @@ Componentes:
|
|||
- **Quota:** ~0,4
|
||||
- **Entrega:** header extraído; RSC renderiza pela view nova; pins OH8 verdes.
|
||||
- **Aceite:**
|
||||
- [ ] `pnpm gate:fast` + pins caracterização verdes
|
||||
- [ ] diff visual zero (check manual)
|
||||
- [x] `pnpm gate:fast` + pins caracterização verdes
|
||||
- [x] diff visual zero (check manual)
|
||||
- **Verify:** gate + specs OH8
|
||||
- **Files:** `MunicipalityDetailHeaderView.tsx`, page
|
||||
- **Tamanho:** M
|
||||
|
|
@ -69,11 +78,11 @@ Componentes:
|
|||
- **Quota:** ~0,6
|
||||
- **Entrega:** `MunicipalityDetailLocal` + `OfflineBoundary` ligados; e2e airplane.
|
||||
- **Aceite:**
|
||||
- [ ] online: Network mostra Flight; UI igual
|
||||
- [ ] offline (flag ON): header + pledges do mirror; empty state fora do mirror
|
||||
- [ ] tabs/regiões online-only com mensagem honesta (não crash)
|
||||
- [ ] leader nunca vê `estimatedVotes` (view model por papel mantido no Local)
|
||||
- **Verify:** `pnpm gate:fast` + `tests/e2e/campaign-ops-offline.e2e.spec.ts`
|
||||
- [x] online: Network mostra Flight; UI igual
|
||||
- [x] offline (flag ON): header + pledges do mirror; empty state fora do mirror
|
||||
- [x] tabs/regiões online-only com mensagem honesta (não crash)
|
||||
- [x] leader nunca vê `estimatedVotes` (view model por papel mantido no Local)
|
||||
- **Verify:** `pnpm gate:fast` + `tests/e2e/campaignOpsOffline.e2e.spec.ts`
|
||||
- **Files:** Local, boundary, page, spec e2e
|
||||
- **Tamanho:** M
|
||||
|
||||
|
|
|
|||
|
|
@ -5,18 +5,17 @@ import { getPayload } from 'payload'
|
|||
import { Suspense } from 'react'
|
||||
|
||||
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 { OfflineBoundary } from '@/components/campaign/opsSync/OfflineBoundary'
|
||||
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 {
|
||||
resolveMunicipalityDetailTab,
|
||||
type MunicipalityDetailSearchParams,
|
||||
} from '@/utilities/municipality/municipalityDetailTabUi'
|
||||
import {
|
||||
formatMunicipalityGeographyLabel,
|
||||
municipalityKindLabels,
|
||||
} from '@/utilities/municipality/municipalityLabels'
|
||||
import {
|
||||
getMunicipalityDetailViewModel,
|
||||
MunicipalityNotFoundError,
|
||||
|
|
@ -38,8 +37,6 @@ type MunicipalityDetailPageProps = {
|
|||
searchParams: Promise<MunicipalityDetailSearchParams>
|
||||
}
|
||||
|
||||
const dateFormatter = new Intl.DateTimeFormat('pt-BR')
|
||||
|
||||
export default async function MunicipalityDetailPage({
|
||||
params,
|
||||
searchParams,
|
||||
|
|
@ -62,99 +59,94 @@ export default async function MunicipalityDetailPage({
|
|||
const view = await getMunicipalityDetailViewModel(payload, context, user)
|
||||
|
||||
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 (
|
||||
<CampaignPageShell>
|
||||
{/* print: the dossier tab carries its own capa; page chrome stays out. */}
|
||||
<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">
|
||||
{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>
|
||||
<OfflineBoundary fallback={<MunicipalityDetailLocal slug={slug} />}>
|
||||
{/* print: the dossier tab carries its own capa; page chrome stays out. */}
|
||||
<MunicipalityDetailHeaderView view={headerView} advisorSummaries={advisorSummaries} />
|
||||
|
||||
<MunicipalityTabNav
|
||||
activeTab={activeTab}
|
||||
municipalitySlug={view.slug}
|
||||
searchParams={rawSearchParams}
|
||||
/>
|
||||
<MunicipalityTabNav
|
||||
activeTab={activeTab}
|
||||
municipalitySlug={view.slug}
|
||||
searchParams={rawSearchParams}
|
||||
/>
|
||||
|
||||
{activeTab === 'overview' ? (
|
||||
<OverviewTab view={view} payloadUser={{ payload, user }} />
|
||||
) : null}
|
||||
{activeTab === 'overview' ? (
|
||||
<OverviewTab view={view} payloadUser={{ payload, user }} />
|
||||
) : null}
|
||||
|
||||
{activeTab === 'dossie' ? (
|
||||
// Composes every vertical of the município in one read — streams like
|
||||
// the elections tab since it includes the same TSE baseline read.
|
||||
<Suspense fallback={<MunicipalityTabFallback />}>
|
||||
<DossierTab
|
||||
view={view}
|
||||
advisorSummaries={advisorSummaries}
|
||||
payloadUser={{ payload, user }}
|
||||
/>
|
||||
</Suspense>
|
||||
) : null}
|
||||
{activeTab === 'dossie' ? (
|
||||
// Composes every vertical of the município in one read — streams like
|
||||
// the elections tab since it includes the same TSE baseline read.
|
||||
<Suspense fallback={<MunicipalityTabFallback />}>
|
||||
<DossierTab
|
||||
view={view}
|
||||
advisorSummaries={advisorSummaries}
|
||||
payloadUser={{ payload, user }}
|
||||
/>
|
||||
</Suspense>
|
||||
) : null}
|
||||
|
||||
{activeTab === 'elections' ? (
|
||||
// Streams below the header/tab chrome — the TSE baselines and the
|
||||
// comparison table are the slowest reads on this page.
|
||||
<Suspense fallback={<MunicipalityTabFallback />}>
|
||||
<ElectionsTab
|
||||
slug={view.slug}
|
||||
rawSearchParams={rawSearchParams}
|
||||
payloadUser={{ payload, user }}
|
||||
/>
|
||||
</Suspense>
|
||||
) : null}
|
||||
{activeTab === 'elections' ? (
|
||||
// Streams below the header/tab chrome — the TSE baselines and the
|
||||
// comparison table are the slowest reads on this page.
|
||||
<Suspense fallback={<MunicipalityTabFallback />}>
|
||||
<ElectionsTab
|
||||
slug={view.slug}
|
||||
rawSearchParams={rawSearchParams}
|
||||
payloadUser={{ payload, user }}
|
||||
/>
|
||||
</Suspense>
|
||||
) : null}
|
||||
|
||||
{activeTab === 'leaderships' ? (
|
||||
<Suspense fallback={<MunicipalityTabFallback />}>
|
||||
<LeadershipsTab municipalityID={view.id} payloadUser={{ payload, user }} />
|
||||
</Suspense>
|
||||
) : null}
|
||||
{activeTab === 'leaderships' ? (
|
||||
<Suspense fallback={<MunicipalityTabFallback />}>
|
||||
<LeadershipsTab municipalityID={view.id} payloadUser={{ payload, user }} />
|
||||
</Suspense>
|
||||
) : null}
|
||||
|
||||
{activeTab === 'updates' ? (
|
||||
<Suspense fallback={<MunicipalityTabFallback />}>
|
||||
<UpdatesTab
|
||||
municipalityID={view.id}
|
||||
municipalitySlug={view.slug}
|
||||
rawSearchParams={rawSearchParams}
|
||||
payloadUser={{ payload, user }}
|
||||
/>
|
||||
</Suspense>
|
||||
) : null}
|
||||
{activeTab === 'updates' ? (
|
||||
<Suspense fallback={<MunicipalityTabFallback />}>
|
||||
<UpdatesTab
|
||||
municipalityID={view.id}
|
||||
municipalitySlug={view.slug}
|
||||
rawSearchParams={rawSearchParams}
|
||||
payloadUser={{ payload, user }}
|
||||
/>
|
||||
</Suspense>
|
||||
) : null}
|
||||
|
||||
{activeTab === 'demands' ? (
|
||||
<section className="rounded-xl border px-4 py-6">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
As demandas deste município aparecem em{' '}
|
||||
<Link
|
||||
href="/campanha/demandas"
|
||||
className="text-primary underline-offset-4 hover:underline"
|
||||
>
|
||||
Demandas
|
||||
</Link>
|
||||
.
|
||||
</p>
|
||||
</section>
|
||||
) : null}
|
||||
{activeTab === 'demands' ? (
|
||||
<section className="rounded-xl border px-4 py-6">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
As demandas deste município aparecem em{' '}
|
||||
<Link
|
||||
href="/campanha/demandas"
|
||||
className="text-primary underline-offset-4 hover:underline"
|
||||
>
|
||||
Demandas
|
||||
</Link>
|
||||
.
|
||||
</p>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
<RecentVisitTracker
|
||||
entry={{
|
||||
href: `/campanha/municipios/${view.slug}`,
|
||||
label: view.name,
|
||||
kind: 'municipality',
|
||||
}}
|
||||
/>
|
||||
<RecentVisitTracker
|
||||
entry={{
|
||||
href: `/campanha/municipios/${view.slug}`,
|
||||
label: view.name,
|
||||
kind: 'municipality',
|
||||
}}
|
||||
/>
|
||||
</OfflineBoundary>
|
||||
</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')
|
||||
|
||||
export 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,13 @@ const createRowCollection = <T extends { id: number }>(id: string) =>
|
|||
)
|
||||
|
||||
export const municipalitiesCollection = createRowCollection<OpsMunicipality>('ops-municipalities')
|
||||
<<<<<<< HEAD
|
||||
const leadershipsCollection = createRowCollection<OpsLeadership>('ops-leaderships')
|
||||
export { votePledgesCollection } from '@/components/campaign/opsSync/opsVotePledgeMirror'
|
||||
=======
|
||||
export const leadershipsCollection = createRowCollection<OpsLeadership>('ops-leaderships')
|
||||
export const votePledgesCollection = createRowCollection<OpsVotePledge>('ops-vote-pledges')
|
||||
>>>>>>> 719e35ce (OH9: dual-path municipality detail (HeaderView + Local + OfflineBoundary))
|
||||
const activitiesCollection = createRowCollection<OpsActivity>('ops-activities')
|
||||
const stateDeputiesCollection = createRowCollection<OpsStateDeputy>('ops-state-deputies')
|
||||
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