From 4e65559fdd20e64d647f4f9b2b3817fc291cf91c Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 2 Aug 2026 01:01:04 +0000 Subject: [PATCH 1/3] 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 --- docs/CHANGELOG-AGENTS.md | 4 + docs/plans/oh9-municipio-detalhe-dualpath.md | 33 ++-- .../campanha/(app)/municipios/[slug]/page.tsx | 170 +++++++++--------- .../MunicipalityDetailHeaderView.tsx | 50 ++++++ .../municipality/MunicipalityDetailLocal.tsx | 112 ++++++++++++ .../campaign/opsSync/OfflineBoundary.tsx | 44 +++++ .../campaign/opsSync/opsMirrorClient.ts | 5 + .../municipalityDetailHeaderView.ts | 20 +++ .../municipalityDetailLocalViews.ts | 47 +++++ tests/e2e/campaignOpsOffline.e2e.spec.ts | 68 +++++++ .../municipalityDetailLocalViews.unit.spec.ts | 94 ++++++++++ 11 files changed, 546 insertions(+), 101 deletions(-) create mode 100644 src/components/campaign/municipality/MunicipalityDetailHeaderView.tsx create mode 100644 src/components/campaign/municipality/MunicipalityDetailLocal.tsx create mode 100644 src/components/campaign/opsSync/OfflineBoundary.tsx create mode 100644 src/lib/campaignOps/municipalityDetailHeaderView.ts create mode 100644 src/lib/campaignOps/municipalityDetailLocalViews.ts create mode 100644 tests/e2e/campaignOpsOffline.e2e.spec.ts create mode 100644 tests/unit/municipalityDetailLocalViews.unit.spec.ts diff --git a/docs/CHANGELOG-AGENTS.md b/docs/CHANGELOG-AGENTS.md index b6baebe3..6633590c 100644 --- a/docs/CHANGELOG-AGENTS.md +++ b/docs/CHANGELOG-AGENTS.md @@ -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). diff --git a/docs/plans/oh9-municipio-detalhe-dualpath.md b/docs/plans/oh9-municipio-detalhe-dualpath.md index 00c96fac..a622b582 100644 --- a/docs/plans/oh9-municipio-detalhe-dualpath.md +++ b/docs/plans/oh9-municipio-detalhe-dualpath.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={}`. @@ -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 diff --git a/src/app/(campaign)/campanha/(app)/municipios/[slug]/page.tsx b/src/app/(campaign)/campanha/(app)/municipios/[slug]/page.tsx index 6112a912..91d1e2fb 100644 --- a/src/app/(campaign)/campanha/(app)/municipios/[slug]/page.tsx +++ b/src/app/(campaign)/campanha/(app)/municipios/[slug]/page.tsx @@ -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 } -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 ( - {/* print: the dossier tab carries its own capa; page chrome stays out. */} -
-
-

{view.name}

- {municipalityKindLabels[view.kind]} -
-

{formatMunicipalityGeographyLabel(view)}

-

- {advisorSummaries.length - ? `Assessoria: ${advisorSummaries.map((advisor) => advisor.name).join(', ')}` - : 'Sem assessor designado.'} - {view.lastUpdateAt - ? ` · Última atualização em ${dateFormatter.format(new Date(view.lastUpdateAt))}` - : ''} -

-
+ }> + {/* print: the dossier tab carries its own capa; page chrome stays out. */} + - + - {activeTab === 'overview' ? ( - - ) : null} + {activeTab === 'overview' ? ( + + ) : 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. - }> - - - ) : 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. + }> + + + ) : null} - {activeTab === 'elections' ? ( - // Streams below the header/tab chrome — the TSE baselines and the - // comparison table are the slowest reads on this page. - }> - - - ) : null} + {activeTab === 'elections' ? ( + // Streams below the header/tab chrome — the TSE baselines and the + // comparison table are the slowest reads on this page. + }> + + + ) : null} - {activeTab === 'leaderships' ? ( - }> - - - ) : null} + {activeTab === 'leaderships' ? ( + }> + + + ) : null} - {activeTab === 'updates' ? ( - }> - - - ) : null} + {activeTab === 'updates' ? ( + }> + + + ) : null} - {activeTab === 'demands' ? ( -
-

- As demandas deste município aparecem em{' '} - - Demandas - - . -

-
- ) : null} + {activeTab === 'demands' ? ( +
+

+ As demandas deste município aparecem em{' '} + + Demandas + + . +

+
+ ) : null} - + +
) } diff --git a/src/components/campaign/municipality/MunicipalityDetailHeaderView.tsx b/src/components/campaign/municipality/MunicipalityDetailHeaderView.tsx new file mode 100644 index 00000000..ff100ced --- /dev/null +++ b/src/components/campaign/municipality/MunicipalityDetailHeaderView.tsx @@ -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 + /** + * 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 ( +
+
+

{view.name}

+ {municipalityKindLabels[view.kind]} +
+

{formatMunicipalityGeographyLabel(view)}

+

+ {advisorLine} + {view.lastUpdateAt + ? ` · Última atualização em ${dateFormatter.format(new Date(view.lastUpdateAt))}` + : ''} +

+
+ ) +} diff --git a/src/components/campaign/municipality/MunicipalityDetailLocal.tsx b/src/components/campaign/municipality/MunicipalityDetailLocal.tsx new file mode 100644 index 00000000..57f9e633 --- /dev/null +++ b/src/components/campaign/municipality/MunicipalityDetailLocal.tsx @@ -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(() => 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 ( +
+

+ Este município não está no espelho offline. {ONLINE_ONLY_MESSAGE} +

+
+ ) + } + + const headerView = toDetailHeaderView(municipality) + const advisorsUnavailable = (municipality.advisors?.length ?? 0) > 0 + + return ( +
+ + + + +
+

{ONLINE_ONLY_MESSAGE}

+
+
+ ) +} diff --git a/src/components/campaign/opsSync/OfflineBoundary.tsx b/src/components/campaign/opsSync/OfflineBoundary.tsx new file mode 100644 index 00000000..23b33f7f --- /dev/null +++ b/src/components/campaign/opsSync/OfflineBoundary.tsx @@ -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
{mounted && hybrid && browserOffline ? fallback : children}
+} diff --git a/src/components/campaign/opsSync/opsMirrorClient.ts b/src/components/campaign/opsSync/opsMirrorClient.ts index 8a6fe238..ed178bc4 100644 --- a/src/components/campaign/opsSync/opsMirrorClient.ts +++ b/src/components/campaign/opsSync/opsMirrorClient.ts @@ -37,8 +37,13 @@ const createRowCollection = (id: string) => ) export const municipalitiesCollection = createRowCollection('ops-municipalities') +<<<<<<< HEAD const leadershipsCollection = createRowCollection('ops-leaderships') export { votePledgesCollection } from '@/components/campaign/opsSync/opsVotePledgeMirror' +======= +export const leadershipsCollection = createRowCollection('ops-leaderships') +export const votePledgesCollection = createRowCollection('ops-vote-pledges') +>>>>>>> 719e35ce (OH9: dual-path municipality detail (HeaderView + Local + OfflineBoundary)) const activitiesCollection = createRowCollection('ops-activities') const stateDeputiesCollection = createRowCollection('ops-state-deputies') const organizationsCollection = createRowCollection('ops-organizations') diff --git a/src/lib/campaignOps/municipalityDetailHeaderView.ts b/src/lib/campaignOps/municipalityDetailHeaderView.ts new file mode 100644 index 00000000..e4a89f81 --- /dev/null +++ b/src/lib/campaignOps/municipalityDetailHeaderView.ts @@ -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, +): MunicipalityDetailHeaderViewModel => ({ + name: municipality.name, + kind: municipality.kind, + region: municipality.region, + zoneNumber: municipality.zoneNumber ?? null, + lastUpdateAt: municipality.lastUpdateAt ?? null, +}) diff --git a/src/lib/campaignOps/municipalityDetailLocalViews.ts b/src/lib/campaignOps/municipalityDetailLocalViews.ts new file mode 100644 index 00000000..4a19c342 --- /dev/null +++ b/src/lib/campaignOps/municipalityDetailLocalViews.ts @@ -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, + slug: string, +): OpsMunicipality | null => municipalities.find((row) => row.slug === slug) ?? null + +export const toLocalStaffPledgeRows = ( + municipalityId: number, + pledges: ReadonlyArray, + leaderships: ReadonlyArray, +): 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')) +} diff --git a/tests/e2e/campaignOpsOffline.e2e.spec.ts b/tests/e2e/campaignOpsOffline.e2e.spec.ts new file mode 100644 index 00000000..27e7bfbb --- /dev/null +++ b/tests/e2e/campaignOpsOffline.e2e.spec.ts @@ -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) + }) +}) diff --git a/tests/unit/municipalityDetailLocalViews.unit.spec.ts b/tests/unit/municipalityDetailLocalViews.unit.spec.ts new file mode 100644 index 00000000..248f8be5 --- /dev/null +++ b/tests/unit/municipalityDetailLocalViews.unit.spec.ts @@ -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 & Pick, +): 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', + }) + }) +}) From 625907088ade4694cbc5e24523a684e13d6e671c Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 2 Aug 2026 01:02:06 +0000 Subject: [PATCH 2/3] OH9: unexport unused HeaderView advisor summary type (knip) --- .../campaign/municipality/MunicipalityDetailHeaderView.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/components/campaign/municipality/MunicipalityDetailHeaderView.tsx b/src/components/campaign/municipality/MunicipalityDetailHeaderView.tsx index ff100ced..a4023afb 100644 --- a/src/components/campaign/municipality/MunicipalityDetailHeaderView.tsx +++ b/src/components/campaign/municipality/MunicipalityDetailHeaderView.tsx @@ -7,7 +7,7 @@ import { const dateFormatter = new Intl.DateTimeFormat('pt-BR') -export type MunicipalityDetailHeaderAdvisorSummary = { +type MunicipalityDetailHeaderAdvisorSummary = { name: string } From fb63c7636396e2b5c38857b582bbc95a8962449e Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 2 Aug 2026 01:10:15 +0000 Subject: [PATCH 3/3] OH9: resolve rebase conflicts with main (opsVotePledgeMirror + changelog) Keep leadershipsCollection export; re-export votePledgesCollection from the OH7 mirror module; preserve both OH9 and B114 changelog entries. --- docs/CHANGELOG-AGENTS.md | 6 ++---- src/components/campaign/opsSync/opsMirrorClient.ts | 7 +------ 2 files changed, 3 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG-AGENTS.md b/docs/CHANGELOG-AGENTS.md index 6633590c..0c150d48 100644 --- a/docs/CHANGELOG-AGENTS.md +++ b/docs/CHANGELOG-AGENTS.md @@ -4,11 +4,9 @@ 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):** **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). diff --git a/src/components/campaign/opsSync/opsMirrorClient.ts b/src/components/campaign/opsSync/opsMirrorClient.ts index ed178bc4..75f7b102 100644 --- a/src/components/campaign/opsSync/opsMirrorClient.ts +++ b/src/components/campaign/opsSync/opsMirrorClient.ts @@ -37,13 +37,8 @@ const createRowCollection = (id: string) => ) export const municipalitiesCollection = createRowCollection('ops-municipalities') -<<<<<<< HEAD -const leadershipsCollection = createRowCollection('ops-leaderships') -export { votePledgesCollection } from '@/components/campaign/opsSync/opsVotePledgeMirror' -======= export const leadershipsCollection = createRowCollection('ops-leaderships') -export const votePledgesCollection = createRowCollection('ops-vote-pledges') ->>>>>>> 719e35ce (OH9: dual-path municipality detail (HeaderView + Local + OfflineBoundary)) +export { votePledgesCollection } const activitiesCollection = createRowCollection('ops-activities') const stateDeputiesCollection = createRowCollection('ops-state-deputies') const organizationsCollection = createRowCollection('ops-organizations')