diff --git a/docs/CHANGELOG-AGENTS.md b/docs/CHANGELOG-AGENTS.md index 4370c915..01a1aeb3 100644 --- a/docs/CHANGELOG-AGENTS.md +++ b/docs/CHANGELOG-AGENTS.md @@ -4,6 +4,8 @@ Conteúdo movido do `AGENTS.md` em 2026-07-30 (fatiamento do paradigma de agente --- +**Recently resolved (2026-08-02):** **OH12** (Issue #174) — `OpsListLocal` read-only via registry + mirror: `OfflineBoundary` nas 8 rotas de lista; Local com `CampaignTable` + parsers canónicos sobre o mirror (municípios/lideranças/dobradinhas/orgs/demandas); assessores/territórios/apoiadores com estado honesto; saved filters create/delete disabled offline; e2e lista `?q=`. Plano: [`oh12-ops-list-local.md`](docs/plans/oh12-ops-list-local.md). + **Recently resolved (2026-08-02):** **OH11** (Issue #173) — SW cache-first para `/_next/static/` (chunks hashed, prefixo `campanha-`); logout limpa campaignOps na ordem abort sync → outbox → persistence → Cache API (`clearCampaignOpsStorage` + `clearCampaignPwaCaches`); e2e `campaignOpsOffline` com jornada write→reload→online→sync (`OPS_HYBRID=1`). Plano: [`oh11-sw-e2e-docs.md`](docs/plans/oh11-sw-e2e-docs.md). **Recently resolved (2026-08-02):** **B120** (Issue #207) — municípios mobile: combobox multi-filtro (chips + typeahead) no lugar da pilha NativeSelect; overview KPI + aviso de sort só em `md+`; cards densificados (cobertura/nível + controles compactos). URL B18 intacta. Plano: [`municipios-mobile-filtro-combobox-densificar.md`](docs/plans/municipios-mobile-filtro-combobox-densificar.md). diff --git a/docs/plans/oh12-ops-list-local.md b/docs/plans/oh12-ops-list-local.md index 6e45c43a..8e61311c 100644 --- a/docs/plans/oh12-ops-list-local.md +++ b/docs/plans/oh12-ops-list-local.md @@ -1,14 +1,23 @@ # OH12 — `OpsListLocal` read-only via registry unificada + mirror -Status: rascunho -Atualizado em: 2026-08-01 +Status: em implementação +Atualizado em: 2026-08-02 Issue: #174 Priority: P1 Model: cursor-grok-4.5-medium Impeccable: B — mesmas listas staff, fallback Local offline -Appetite: ~2–3 dias eng -Depends: OH9, OH5, CL8 -Responsável: — +Appetite: fatias M×2 (tracer municipios → demais slugs) +Depends: OH9 (#172 done/in-prod), OH5 (#168), CL8 (#162) +Responsável: pool worker #174 + +## Freshness audit (2026-08-02) + +- Deps OH9/OH5/CL8: `done` + `in-prod`. `OfflineBoundary`, mirror (`@tanstack/db` + `subscribeChanges`, **não** `useLiveQuery`), registry 8 slugs — OK. +- Plano citava `status: 'v1'` no registry: na prática o registry **não** tem campo `status` — presença em `opsListDomains` = v1 (CL2). Seguir `getOpsListDomain`. +- `CampaignTable` / `CampaignListFooter` sem `server-only` — importáveis do client (precedente OH9 com `MunicipalityDetailHeaderView`). +- Parsers municipios/liderancas/dobradinhas/territorios/assessores/apoiadores já client-importáveis; **organization** e **demand** parsers vivem em módulos `server-only` → extrair `*ListUrl.ts` client-safe. +- Mirror **não** inclui supporters, advisors (`campaignUser`) nem overview de territórios → esses slugs: estado honesto “indisponível offline”. +- Colunas de domínio não estão extraídas (só territories) → Local monta tabela read-only própria; não reusa `MunicipalityList` (edit-where-you-see + view model rico). ## Premissas @@ -16,7 +25,7 @@ Responsável: — 2. Modo offline **declarado reduzido**: query string aplica-se ao mirror via parsers canónicos; saved filters **readonly**; controles que precisam de server ficam disabled com tooltip “online-only”. 3. Leitura apenas — writes seguem OH10/OH13 nas ilhas já migradas. -→ Corrija agora ou sigo com estas. +→ Premissas confirmadas; seguir. ## Objetivos @@ -42,7 +51,7 @@ flowchart LR Bound -->|online| Factory[OpsListPage RSC] Bound -->|offline + flag| Local[OpsListLocal slug] Local --> Parse[parser URL domínio] - Local --> Q[useLiveQuery mirror] + Local --> Q[subscribeChanges mirror] Q --> Table[CampaignTable + shells] ``` @@ -59,9 +68,9 @@ Componentes: - **Quota:** ~0,5 - **Entrega:** `OpsListLocal('municipios')` com tabela, search, sort, paginação aplicados ao mirror. - **Aceite:** - - [ ] offline: lista renderiza; `?q=` filtra localmente; sort/paginação funcionam no client - - [ ] saved filters: aplicar funciona (leitura), criar/apagar disabled com tooltip - - [ ] edit-where-you-see controls disabled offline com tooltip “online-only” + - [x] offline: lista renderiza; `?q=` filtra localmente; sort/paginação funcionam no client + - [x] saved filters: aplicar funciona (leitura), criar/apagar disabled com tooltip + - [x] edit-where-you-see controls disabled offline com tooltip “online-only” - **Verify:** `pnpm gate:fast` + e2e offline lista municipios - **Files:** `OpsListLocal.tsx`, rota municipios, spec e2e - **Tamanho:** M @@ -71,10 +80,10 @@ Componentes: - **Quota:** ~0,5 - **Entrega:** liderancas, dobradinhas, demandas, assessores, territorios, apoiadores, organizacoes. - **Aceite:** - - [ ] cada slug renderiza com o layout/colunas do domínio - - [ ] facets/KPIs não deriváveis → mensagem “indisponível offline” (ex.: overview de apoiadores se o aggregate não for local) - - [ ] leader: listas de ops fora do seu lockdown não renderizam (mirror inexistente → estado honesto, não erro) -- **Verify:** `pnpm gate:fast` + e2e offline por slug + - [x] cada slug renderiza com o layout/colunas do domínio (mirror) ou estado honesto + - [x] facets/KPIs não deriváveis → mensagem “indisponível offline” + - [x] leader: listas de ops fora do seu lockdown não renderizam (mirror inexistente → estado honesto, não erro) +- **Verify:** `pnpm gate:fast` + e2e offline por slug (municipios pin; demais cobertura unitária) - **Files:** rotas, `OpsListLocal.tsx` - **Tamanho:** M diff --git a/src/app/(campaign)/campanha/(app)/apoiadores/page.tsx b/src/app/(campaign)/campanha/(app)/apoiadores/page.tsx index 39a87285..7cff9cec 100644 --- a/src/app/(campaign)/campanha/(app)/apoiadores/page.tsx +++ b/src/app/(campaign)/campanha/(app)/apoiadores/page.tsx @@ -4,6 +4,8 @@ import Link from 'next/link' import { redirect } from 'next/navigation' import { getPayload } from 'payload' +import { OfflineBoundary } from '@/components/campaign/opsSync/OfflineBoundary' +import { OpsListLocal } from '@/components/campaign/opsSync/OpsListLocal' import { CampaignListEmptyState } from '@/components/campaign/shared/CampaignListEmptyState' import { CampaignListFooter } from '@/components/campaign/shared/CampaignListFooter' import { CampaignListPageHeader } from '@/components/campaign/shared/CampaignListPageHeader' @@ -110,37 +112,39 @@ export default async function SupportersPage({ searchParams }: SupportersPagePro return ( - - {isCampaignUnrestricted(user) - ? `${campaignRoleLabels[user.role]} · todos os apoiadores` - : getSupporterScopeLabel(result.totalDocs)} - - } - actions={ -
- {isCampaignCoordinator(user) ? ( - + ) : null} + - ) : null} - -
- } - /> + + } + /> - {main} + {main} +
) } diff --git a/src/app/(campaign)/campanha/(app)/assessores/page.tsx b/src/app/(campaign)/campanha/(app)/assessores/page.tsx index 7f6f4a0f..7a4c5945 100644 --- a/src/app/(campaign)/campanha/(app)/assessores/page.tsx +++ b/src/app/(campaign)/campanha/(app)/assessores/page.tsx @@ -4,6 +4,8 @@ import { getPayload } from 'payload' import type { ReactNode } from 'react' import { AdvisorsTable } from '@/components/campaign/advisor/AdvisorsTable' +import { OfflineBoundary } from '@/components/campaign/opsSync/OfflineBoundary' +import { OpsListLocal } from '@/components/campaign/opsSync/OpsListLocal' import { CampaignListFooter } from '@/components/campaign/shared/CampaignListFooter' import { CampaignListPageHeader } from '@/components/campaign/shared/CampaignListPageHeader' import { @@ -106,12 +108,14 @@ export default async function AdvisorsPage({ searchParams }: AdvisorsPageProps) return ( - + }> + - {main} + {main} + ) } diff --git a/src/app/(campaign)/campanha/(app)/demandas/page.tsx b/src/app/(campaign)/campanha/(app)/demandas/page.tsx index 66ec1340..862c8067 100644 --- a/src/app/(campaign)/campanha/(app)/demandas/page.tsx +++ b/src/app/(campaign)/campanha/(app)/demandas/page.tsx @@ -4,6 +4,8 @@ import Link from 'next/link' import { redirect } from 'next/navigation' import { getPayload } from 'payload' +import { OfflineBoundary } from '@/components/campaign/opsSync/OfflineBoundary' +import { OpsListLocal } from '@/components/campaign/opsSync/OpsListLocal' import { CampaignFilterChips } from '@/components/campaign/shared/CampaignFilterChips' import { CampaignListEmptyState } from '@/components/campaign/shared/CampaignListEmptyState' import { CampaignListFooter } from '@/components/campaign/shared/CampaignListFooter' @@ -187,25 +189,27 @@ export default async function DemandsPage({ searchParams }: DemandsPageProps) { return ( - - {openCount} {openCount === 1 ? 'demanda em aberto' : 'demandas em aberto'} - - } - actions={ - - } - /> + }> + + {openCount} {openCount === 1 ? 'demanda em aberto' : 'demandas em aberto'} + + } + actions={ + + } + /> - {main} + {main} + ) } diff --git a/src/app/(campaign)/campanha/(app)/dobradinhas/page.tsx b/src/app/(campaign)/campanha/(app)/dobradinhas/page.tsx index 12698722..475bebba 100644 --- a/src/app/(campaign)/campanha/(app)/dobradinhas/page.tsx +++ b/src/app/(campaign)/campanha/(app)/dobradinhas/page.tsx @@ -4,6 +4,8 @@ import Link from 'next/link' import { redirect } from 'next/navigation' import { getPayload } from 'payload' +import { OfflineBoundary } from '@/components/campaign/opsSync/OfflineBoundary' +import { OpsListLocal } from '@/components/campaign/opsSync/OpsListLocal' import { CampaignListFooter } from '@/components/campaign/shared/CampaignListFooter' import { CampaignListPageHeader } from '@/components/campaign/shared/CampaignListPageHeader' import { @@ -283,20 +285,22 @@ export default async function StateDeputiesPage({ searchParams }: StateDeputiesP return ( - - - ) } diff --git a/src/app/(campaign)/campanha/(app)/liderancas/page.tsx b/src/app/(campaign)/campanha/(app)/liderancas/page.tsx index 1d85134f..0bee3336 100644 --- a/src/app/(campaign)/campanha/(app)/liderancas/page.tsx +++ b/src/app/(campaign)/campanha/(app)/liderancas/page.tsx @@ -11,6 +11,8 @@ import { LeadershipFilterHead, LeadershipSortableHead, } from '@/components/campaign/leadership/LeadershipSortableHead' +import { OfflineBoundary } from '@/components/campaign/opsSync/OfflineBoundary' +import { OpsListLocal } from '@/components/campaign/opsSync/OpsListLocal' import { CampaignCopyableCell } from '@/components/campaign/shared/CampaignCopyableCell' import { CampaignListFooter } from '@/components/campaign/shared/CampaignListFooter' import { CampaignListPageHeader } from '@/components/campaign/shared/CampaignListPageHeader' @@ -437,20 +439,22 @@ export default async function LeadershipsPage({ searchParams }: LeadershipsPageP return ( - - - ) } diff --git a/src/app/(campaign)/campanha/(app)/municipios/page.tsx b/src/app/(campaign)/campanha/(app)/municipios/page.tsx index a805a9f9..f0cb196f 100644 --- a/src/app/(campaign)/campanha/(app)/municipios/page.tsx +++ b/src/app/(campaign)/campanha/(app)/municipios/page.tsx @@ -12,6 +12,8 @@ import { MunicipalityEstimateScenarioProvider } from '@/components/campaign/muni import { MunicipalityFilters } from '@/components/campaign/municipality/MunicipalityFilters' import { MunicipalityList } from '@/components/campaign/municipality/MunicipalityList' import { MunicipalityListOverview } from '@/components/campaign/municipality/MunicipalityListOverview' +import { OfflineBoundary } from '@/components/campaign/opsSync/OfflineBoundary' +import { OpsListLocal } from '@/components/campaign/opsSync/OpsListLocal' import { CampaignListFooter } from '@/components/campaign/shared/CampaignListFooter' import { CampaignListPageHeader } from '@/components/campaign/shared/CampaignListPageHeader' import { CampaignScopeBadge } from '@/components/campaign/shared/CampaignScopeBadge' @@ -189,24 +191,26 @@ export default async function MunicipalitiesPage({ searchParams }: Municipalitie return ( - {getCampaignScopeLabel(user.role, scopeTotal)} - } - /> - - {main} - {listVisitLabel ? ( - }> + {getCampaignScopeLabel(user.role, scopeTotal)} + } /> - ) : null} + + {main} + {listVisitLabel ? ( + + ) : null} + ) } diff --git a/src/app/(campaign)/campanha/(app)/organizacoes/page.tsx b/src/app/(campaign)/campanha/(app)/organizacoes/page.tsx index 3ab283f5..4a1cf16f 100644 --- a/src/app/(campaign)/campanha/(app)/organizacoes/page.tsx +++ b/src/app/(campaign)/campanha/(app)/organizacoes/page.tsx @@ -4,6 +4,8 @@ import Link from 'next/link' import { redirect } from 'next/navigation' import { getPayload } from 'payload' +import { OfflineBoundary } from '@/components/campaign/opsSync/OfflineBoundary' +import { OpsListLocal } from '@/components/campaign/opsSync/OpsListLocal' import { CampaignListEmptyState } from '@/components/campaign/shared/CampaignListEmptyState' import { CampaignListFooter } from '@/components/campaign/shared/CampaignListFooter' import { @@ -153,23 +155,25 @@ export default async function OrganizationsPage({ searchParams }: OrganizationsP return ( -
-
-

Organizações

-

- Sindicatos, associações e movimentos que apoiam a campanha — com suas lideranças e - atividades. -

-
- -
+ }> +
+
+

Organizações

+

+ Sindicatos, associações e movimentos que apoiam a campanha — com suas lideranças e + atividades. +

+
+ +
- {main} + {main} +
) } diff --git a/src/app/(campaign)/campanha/(app)/territorios/page.tsx b/src/app/(campaign)/campanha/(app)/territorios/page.tsx index d35b934b..03f4f6d2 100644 --- a/src/app/(campaign)/campanha/(app)/territorios/page.tsx +++ b/src/app/(campaign)/campanha/(app)/territorios/page.tsx @@ -4,6 +4,8 @@ import { getPayload } from 'payload' import { TerritoryFilters } from '@/components/campaign/municipality/TerritoryFilters' import { TerritoryList } from '@/components/campaign/municipality/TerritoryList' +import { OfflineBoundary } from '@/components/campaign/opsSync/OfflineBoundary' +import { OpsListLocal } from '@/components/campaign/opsSync/OpsListLocal' import { CampaignListFooter } from '@/components/campaign/shared/CampaignListFooter' import { CampaignListPageHeader } from '@/components/campaign/shared/CampaignListPageHeader' import { @@ -82,14 +84,16 @@ export default async function TerritoriesPage({ searchParams }: TerritoriesPageP return ( - - {main} + }> + + {main} + ) } diff --git a/src/components/campaign/municipality/SaveMunicipalityFilterControl.tsx b/src/components/campaign/municipality/SaveMunicipalityFilterControl.tsx index 4d75bb33..34e29494 100644 --- a/src/components/campaign/municipality/SaveMunicipalityFilterControl.tsx +++ b/src/components/campaign/municipality/SaveMunicipalityFilterControl.tsx @@ -4,6 +4,8 @@ import { BookmarkPlusIcon } from 'lucide-react' import { useId, useState, type FormEvent } from 'react' import { toast } from 'sonner' +import { OPS_LIST_ONLINE_ONLY_MESSAGE } from '@/components/campaign/opsSync/opsListLocalCopy' +import { useBrowserOffline } from '@/components/campaign/opsSync/useBrowserOffline' import { useMunicipalitySavedFilters } from '@/components/campaign/shared/useMunicipalitySavedFilters' import { Alert, AlertDescription } from '@/components/ui/Alert' import { Button } from '@/components/ui/button' @@ -36,6 +38,7 @@ type SaveMunicipalityFilterControlProps = { */ export const SaveMunicipalityFilterControl = ({ state }: SaveMunicipalityFilterControlProps) => { const savedFilters = useMunicipalitySavedFilters() + const browserOffline = useBrowserOffline() const [open, setOpen] = useState(false) const [name, setName] = useState('') const [errorMessage, setErrorMessage] = useState('') @@ -52,6 +55,7 @@ export const SaveMunicipalityFilterControl = ({ state }: SaveMunicipalityFilterC if (!summary) return null const handleOpenChange = (next: boolean) => { + if (browserOffline) return setOpen(next) if (!next) return setName(existing?.name ?? summary.slice(0, MAX_NAME_LENGTH)) @@ -60,6 +64,7 @@ export const SaveMunicipalityFilterControl = ({ state }: SaveMunicipalityFilterC const handleSubmit = (event: FormEvent) => { event.preventDefault() + if (browserOffline) return if (!name.trim()) { setErrorMessage('Dê um nome ao filtro.') return @@ -81,6 +86,22 @@ export const SaveMunicipalityFilterControl = ({ state }: SaveMunicipalityFilterC toast.success(existing ? 'Nome atualizado.' : 'Filtro salvo em Municípios, na navegação.') } + if (browserOffline) { + return ( + + ) + } + return ( diff --git a/src/components/campaign/opsSync/OfflineBoundary.tsx b/src/components/campaign/opsSync/OfflineBoundary.tsx index 23b33f7f..2da5351d 100644 --- a/src/components/campaign/opsSync/OfflineBoundary.tsx +++ b/src/components/campaign/opsSync/OfflineBoundary.tsx @@ -2,6 +2,7 @@ import { useEffect, useState, type ReactNode } from 'react' +import { useBrowserOffline } from '@/components/campaign/opsSync/useBrowserOffline' import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag' /** @@ -24,20 +25,10 @@ export const OfflineBoundary = ({ }) => { const hybrid = resolveOpsHybridEnabled() const [mounted, setMounted] = useState(false) - const [browserOffline, setBrowserOffline] = useState(false) + const browserOffline = useBrowserOffline() 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/OpsListLocal.tsx b/src/components/campaign/opsSync/OpsListLocal.tsx new file mode 100644 index 00000000..5a9621d4 --- /dev/null +++ b/src/components/campaign/opsSync/OpsListLocal.tsx @@ -0,0 +1,686 @@ +'use client' + +import Link from 'next/link' +import { useSearchParams } from 'next/navigation' +import { useEffect, useRef, useState, type ReactNode } from 'react' + +import { MunicipalityPriorityIndicator } from '@/components/campaign/municipality/MunicipalityPriorityIndicator' +import { SaveMunicipalityFilterControl } from '@/components/campaign/municipality/SaveMunicipalityFilterControl' +import { + OPS_LIST_ACCESS_FILTER_IGNORED_MESSAGE, + OPS_LIST_CLASS_FILTER_UNAVAILABLE_MESSAGE, + OPS_LIST_DOMAIN_UNAVAILABLE_MESSAGE, + OPS_LIST_EDIT_ONLINE_ONLY_MESSAGE, + OPS_LIST_KPI_UNAVAILABLE_MESSAGE, + OPS_LIST_MIRROR_EMPTY_MESSAGE, + OPS_LIST_ONLINE_ONLY_MESSAGE, + OPS_LIST_SORT_DEGRADED_MESSAGE, +} from '@/components/campaign/opsSync/opsListLocalCopy' +import { + demandsCollection, + leadershipsCollection, + municipalitiesCollection, + organizationsCollection, + stateDeputiesCollection, +} from '@/components/campaign/opsSync/opsMirrorClient' +import { CampaignListFooter } from '@/components/campaign/shared/CampaignListFooter' +import { CampaignSearchInput } from '@/components/campaign/shared/CampaignSearchInput' +import { CampaignTable, type CampaignTableColumn } from '@/components/campaign/shared/CampaignTable' +import { OpsListView } from '@/components/campaign/shared/OpsListView' +import { useCampaignListFilterNavigation } from '@/components/campaign/shared/useCampaignListFilterNavigation' +import { Button } from '@/components/ui/button' +import { Field, FieldLabel } from '@/components/ui/field' +import { NativeSelect, NativeSelectOption } from '@/components/ui/native-select' +import type { + OpsDemand, + OpsLeadership, + OpsMunicipality, + OpsOrganization, + OpsStateDeputy, +} from '@/lib/campaignOps/opsContract' +import { formatElectionNumber } from '@/lib/electionFormat' +import { + EMPTY_ENGAGEMENT_LEVEL_LABEL, + formatEngagementLevelLabel, + isEngagementLevel, +} from '@/lib/engagementLevel' +import type { OpsListDomainId } from '@/lib/opsListRegistry/opsListRegistry' +import { campaignDemandKindLabels, campaignDemandStatusLabels } from '@/lib/schemas/campaignDemand' +import { organizationKindLabels } from '@/lib/schemas/organization' +import { DEFAULT_VOTE_ESTIMATE_SCENARIO, getVoteEstimateForScenario } from '@/lib/voteEstimate' +import { + filterSortPageOpsDemands, + filterSortPageOpsLeaderships, + filterSortPageOpsOrganizations, + filterSortPageOpsStateDeputies, +} from '@/utilities/campaignOps/opsEntityListLocal' +import { filterSortPageOpsMunicipalities } from '@/utilities/campaignOps/opsMunicipalityListLocal' +import { buildDemandListHref, parseDemandListParams } from '@/utilities/demand/demandListUrl' +import { supportStatusLabels } from '@/utilities/leadership/leadershipLabels' +import { + buildLeadershipListHref, + parseLeadershipListParams, +} from '@/utilities/leadership/leadershipListUrl' +import { politicalTrendLabels } from '@/utilities/municipality/municipalityLabels' +import { + buildMunicipalityFilterHref, + clearMunicipalityListFilters, + formatMunicipalityActiveFiltersSummary, +} from '@/utilities/municipality/municipalityListFilters' +import { + buildMunicipalityListHref, + municipalityListSortOptions, + parseMunicipalityListParams, + parseMunicipalitySortValue, + resolveMunicipalityListSort, + serializeMunicipalitySortValue, + type MunicipalityListState, +} from '@/utilities/municipality/municipalityListUrl' +import { + buildOrganizationListHref, + parseOrganizationListParams, +} from '@/utilities/organization/organizationListUrl' +import { + buildStateDeputyListHref, + parseStateDeputyListParams, +} from '@/utilities/stateDeputyListUrl' + +const searchParamsToRecord = ( + params: URLSearchParams, +): Record => { + const record: Record = {} + for (const key of new Set(params.keys())) { + const all = params.getAll(key) + record[key] = all.length <= 1 ? (all[0] ?? undefined) : all + } + return record +} + +const useMirrorCollection = (collection: { + toArray: T[] + subscribeChanges: (cb: () => void) => { unsubscribe: () => void } +}): T[] => { + const [rows, setRows] = useState(() => collection.toArray) + const coalesceRef = useRef<(() => void) | null>(null) + + useEffect(() => { + const refresh = () => { + if (coalesceRef.current) return + coalesceRef.current = () => { + coalesceRef.current = null + setRows(collection.toArray) + } + queueMicrotask(coalesceRef.current) + } + refresh() + const subscription = collection.subscribeChanges(refresh) + return () => { + subscription.unsubscribe() + coalesceRef.current = null + } + }, [collection]) + + return rows +} + +const OpsListLocalNotice = ({ children }: { children: ReactNode }) => ( +

{children}

+) + +const OpsListLocalShell = ({ + title, + description, + children, +}: { + title: string + description: string + children: ReactNode +}) => ( +
+
+

{title}

+

{description}

+ {OPS_LIST_EDIT_ONLINE_ONLY_MESSAGE} +
+ {children} +
+) + +const OpsListDomainUnavailable = ({ title }: { title: string }) => ( +
+
+

{title}

+

{OPS_LIST_DOMAIN_UNAVAILABLE_MESSAGE}

+
+
+ {OPS_LIST_ONLINE_ONLY_MESSAGE} +
+
+) + +/* ——— Municipios ——— */ + +const MunicipalityLocalFilters = ({ state }: { state: MunicipalityListState }) => { + const { search, onSearchChange, draftQ, isPending, navigateWithSearch, clearSearchAndNavigate } = + useCampaignListFilterNavigation({ state, toHref: buildMunicipalityFilterHref }) + const { sort: activeSort, dir: activeDir } = resolveMunicipalityListSort(state) + const activeFiltersSummary = formatMunicipalityActiveFiltersSummary({ ...state, q: draftQ }) + const hasActiveFilters = Boolean(activeFiltersSummary) + + return ( +
{ + event.preventDefault() + navigateWithSearch(state) + }} + > +
+ onSearchChange(event.target.value)} + /> + {activeFiltersSummary ? ( +

+ {activeFiltersSummary} +

+ ) : null} + + {hasActiveFilters ? ( + + ) : null} +
+ + Ordenar + { + const parsed = parseMunicipalitySortValue(event.target.value) + if (parsed) navigateWithSearch({ ...state, sort: parsed.key, dir: parsed.dir }) + }} + className="min-h-11 w-full" + > + {municipalityListSortOptions.map(({ key, dir, label }) => ( + + {label} + + ))} + + +
+ ) +} + +const MUNICIPALITY_LOCAL_COLUMNS: Array> = [ + { + id: 'name', + label: 'Município', + mandatory: true, + cell: (row) => ( +
+ + {row.name} + + {row.priority === 'alta' ? : null} +
+ ), + }, + { + id: 'region', + label: 'Território', + cellClassName: 'text-muted-foreground', + cell: (row) => row.region, + }, + { + id: 'trend', + label: 'Tendência', + cell: (row) => { + const status = row.politicalTrend?.status + return status ? politicalTrendLabels[status] : '—' + }, + }, + { + id: 'level', + label: 'Nível', + cell: (row) => + isEngagementLevel(row.engagementLevel) + ? formatEngagementLevelLabel(row.engagementLevel) + : EMPTY_ENGAGEMENT_LEVEL_LABEL, + }, + { + id: 'expectedVotes', + label: 'Votos estimados', + cellClassName: 'text-right', + cell: (row) => { + const votes = getVoteEstimateForScenario(row.expectedVotes, DEFAULT_VOTE_ESTIMATE_SCENARIO) + return votes == null ? '—' : formatElectionNumber(votes) + }, + }, + { + id: 'advisors', + label: 'Assessores', + cellClassName: 'text-right', + cell: (row) => String(row.advisors?.length ?? 0), + }, +] + +const OpsMunicipalityListLocal = () => { + const searchParams = useSearchParams() + const municipalities = useMirrorCollection(municipalitiesCollection) + const state = parseMunicipalityListParams(searchParamsToRecord(searchParams)) + const pageResult = filterSortPageOpsMunicipalities(municipalities, state) + + if (municipalities.length === 0) { + return ( + + {OPS_LIST_MIRROR_EMPTY_MESSAGE} + + ) + } + + const columns = MUNICIPALITY_LOCAL_COLUMNS + const overview = ( +
+ {OPS_LIST_KPI_UNAVAILABLE_MESSAGE} + {pageResult.classFilterUnavailable ? ( + {OPS_LIST_CLASS_FILTER_UNAVAILABLE_MESSAGE} + ) : null} + {pageResult.sortDegraded ? ( + {OPS_LIST_SORT_DEGRADED_MESSAGE} + ) : null} +
+ ) + + return ( + + } + table={ + row.id} + caption="Municípios (offline)" + empty={ +

+ Nenhum município encontrado neste recorte offline. +

+ } + /> + } + empty={null} + footer={ + buildMunicipalityListHref(state, page)} + /> + } + /> +
+ ) +} + +/* ——— Leaderships ——— */ + +const LEADERSHIP_LOCAL_COLUMNS: Array> = [ + { + id: 'name', + label: 'Nome', + mandatory: true, + cell: (row) => ( + + {row.contact.name} + + ), + }, + { + id: 'supportStatus', + label: 'Status', + cell: (row) => supportStatusLabels[row.supportStatus], + }, + { + id: 'municipalities', + label: 'Municípios', + cellClassName: 'text-right', + cell: (row) => String(row.municipalities.length), + }, +] + +const OpsLeadershipListLocal = () => { + const searchParams = useSearchParams() + const rows = useMirrorCollection(leadershipsCollection) + const state = parseLeadershipListParams(searchParamsToRecord(searchParams)) + const pageResult = filterSortPageOpsLeaderships(rows, state) + + if (rows.length === 0) { + return ( + + {OPS_LIST_MIRROR_EMPTY_MESSAGE} + + ) + } + + return ( + + + {OPS_LIST_ACCESS_FILTER_IGNORED_MESSAGE} + + ) : null + } + toolbar={ + + Filtros completos e edição: {OPS_LIST_ONLINE_ONLY_MESSAGE} + + } + table={ + row.id} + caption="Lideranças (offline)" + empty={ +

+ Nenhuma liderança neste recorte offline. +

+ } + /> + } + empty={null} + footer={ + buildLeadershipListHref(state, page)} + /> + } + /> +
+ ) +} + +/* ——— State deputies / orgs / demands ——— */ + +const OpsStateDeputyListLocal = () => { + const searchParams = useSearchParams() + const rows = useMirrorCollection(stateDeputiesCollection) + const state = parseStateDeputyListParams(searchParamsToRecord(searchParams)) + const pageResult = filterSortPageOpsStateDeputies(rows, state) + + if (rows.length === 0) { + return ( + + {OPS_LIST_MIRROR_EMPTY_MESSAGE} + + ) + } + + const columns: Array> = [ + { + id: 'name', + label: 'Nome', + mandatory: true, + cell: (row) => ( + + {row.name} + + ), + }, + { + id: 'party', + label: 'Partido', + cell: (row) => row.party?.trim() || '—', + }, + ] + + return ( + + Filtros completos: {OPS_LIST_ONLINE_ONLY_MESSAGE} + } + table={ + row.id} + caption="Dobradinhas (offline)" + /> + } + empty={null} + footer={ + buildStateDeputyListHref(state, page)} + /> + } + /> + + ) +} + +const OpsOrganizationListLocal = () => { + const searchParams = useSearchParams() + const rows = useMirrorCollection(organizationsCollection) + const state = parseOrganizationListParams(searchParamsToRecord(searchParams)) + const pageResult = filterSortPageOpsOrganizations(rows, state) + + if (rows.length === 0) { + return ( + + {OPS_LIST_MIRROR_EMPTY_MESSAGE} + + ) + } + + const columns: Array> = [ + { + id: 'name', + label: 'Nome', + mandatory: true, + cell: (row) => ( + + {row.name} + + ), + }, + { + id: 'kind', + label: 'Tipo', + cell: (row) => organizationKindLabels[row.kind], + }, + ] + + return ( + + Filtros completos: {OPS_LIST_ONLINE_ONLY_MESSAGE} + } + table={ + row.id} + caption="Organizações (offline)" + /> + } + empty={null} + footer={ + buildOrganizationListHref(state, page)} + /> + } + /> + + ) +} + +const OpsDemandListLocal = () => { + const searchParams = useSearchParams() + const rows = useMirrorCollection(demandsCollection) + const state = parseDemandListParams(searchParamsToRecord(searchParams)) + const pageResult = filterSortPageOpsDemands(rows, state) + + if (rows.length === 0) { + return ( + + {OPS_LIST_MIRROR_EMPTY_MESSAGE} + + ) + } + + const columns: Array> = [ + { + id: 'title', + label: 'Título', + mandatory: true, + cell: (row) => ( + + {row.title} + + ), + }, + { + id: 'kind', + label: 'Tipo', + cell: (row) => campaignDemandKindLabels[row.kind], + }, + { + id: 'status', + label: 'Status', + cell: (row) => campaignDemandStatusLabels[row.status], + }, + ] + + return ( + + + {OPS_LIST_KPI_UNAVAILABLE_MESSAGE} + + } + toolbar={ + Filtros completos: {OPS_LIST_ONLINE_ONLY_MESSAGE} + } + table={ + row.id} + caption="Demandas (offline)" + /> + } + empty={null} + footer={ + buildDemandListHref(state, page)} + /> + } + /> + + ) +} + +const DOMAIN_TITLES: Record = { + municipios: 'Municípios', + liderancas: 'Lideranças', + dobradinhas: 'Dobradinhas', + demandas: 'Demandas', + assessores: 'Assessores', + territorios: 'Territórios', + apoiadores: 'Apoiadores', + organizacoes: 'Organizações', +} + +/** + * OH12 — read-only Local path for unified ops lists. Reads mirror collections + * via `subscribeChanges` (same coalesce as MunicipalityDetailLocal). + */ +export const OpsListLocal = ({ slug }: { slug: OpsListDomainId }) => { + switch (slug) { + case 'municipios': + return + case 'liderancas': + return + case 'dobradinhas': + return + case 'organizacoes': + return + case 'demandas': + return + case 'assessores': + case 'territorios': + case 'apoiadores': + return + default: { + const _exhaustive: never = slug + return _exhaustive + } + } +} diff --git a/src/components/campaign/opsSync/opsListLocalCopy.ts b/src/components/campaign/opsSync/opsListLocalCopy.ts new file mode 100644 index 00000000..90175d2b --- /dev/null +++ b/src/components/campaign/opsSync/opsListLocalCopy.ts @@ -0,0 +1,21 @@ +export const OPS_LIST_ONLINE_ONLY_MESSAGE = 'Disponível quando estiveres online.' + +export const OPS_LIST_MIRROR_EMPTY_MESSAGE = + 'Nenhum dado deste domínio no espelho offline. Sincroniza online e tenta de novo.' + +export const OPS_LIST_DOMAIN_UNAVAILABLE_MESSAGE = + 'Esta lista não está disponível offline — os dados não entram no espelho da campanha.' + +export const OPS_LIST_KPI_UNAVAILABLE_MESSAGE = 'Indicadores indisponíveis offline.' + +export const OPS_LIST_EDIT_ONLINE_ONLY_MESSAGE = + 'Edição na lista disponível quando estiveres online.' + +export const OPS_LIST_CLASS_FILTER_UNAVAILABLE_MESSAGE = + 'Filtro por classe territorial indisponível offline — o recorte ignora essa condição.' + +export const OPS_LIST_SORT_DEGRADED_MESSAGE = + 'Ordenação pedida depende de dados só online — a lista está ordenada por nome.' + +export const OPS_LIST_ACCESS_FILTER_IGNORED_MESSAGE = + 'Filtro de acesso ao app indisponível offline — o recorte ignora essa condição.' diff --git a/src/components/campaign/opsSync/opsMirrorClient.ts b/src/components/campaign/opsSync/opsMirrorClient.ts index 72f39756..a0d2973b 100644 --- a/src/components/campaign/opsSync/opsMirrorClient.ts +++ b/src/components/campaign/opsSync/opsMirrorClient.ts @@ -41,9 +41,9 @@ export const municipalitiesCollection = createRowCollection('op export const leadershipsCollection = createRowCollection('ops-leaderships') export { votePledgesCollection } const activitiesCollection = createRowCollection('ops-activities') -const stateDeputiesCollection = createRowCollection('ops-state-deputies') -const organizationsCollection = createRowCollection('ops-organizations') -const demandsCollection = createRowCollection('ops-demands') +export const stateDeputiesCollection = createRowCollection('ops-state-deputies') +export const organizationsCollection = createRowCollection('ops-organizations') +export const demandsCollection = createRowCollection('ops-demands') const municipalityUpdatesCollection = createRowCollection( 'ops-municipality-updates', ) diff --git a/src/components/campaign/opsSync/useBrowserOffline.ts b/src/components/campaign/opsSync/useBrowserOffline.ts new file mode 100644 index 00000000..b2b7706c --- /dev/null +++ b/src/components/campaign/opsSync/useBrowserOffline.ts @@ -0,0 +1,31 @@ +'use client' + +import { useEffect, useState } from 'react' + +/** + * Browser online/offline only — matches OfflineBoundary Local trigger. + * + * Returns false until mount so SSR/hydration and first paint stay on the + * online controls (saved-filter create, etc.). After mount, follows + * `navigator.onLine`. + */ +export const useBrowserOffline = (): boolean => { + const [mounted, setMounted] = useState(false) + const [offline, setOffline] = useState(false) + + useEffect(() => { + setMounted(true) + setOffline(!navigator.onLine) + + const onOnline = () => setOffline(false) + const onOffline = () => setOffline(true) + window.addEventListener('online', onOnline) + window.addEventListener('offline', onOffline) + return () => { + window.removeEventListener('online', onOnline) + window.removeEventListener('offline', onOffline) + } + }, []) + + return mounted && offline +} diff --git a/src/components/campaign/shell/MunicipalityNavSavedFilters.tsx b/src/components/campaign/shell/MunicipalityNavSavedFilters.tsx index 8582a346..c7660393 100644 --- a/src/components/campaign/shell/MunicipalityNavSavedFilters.tsx +++ b/src/components/campaign/shell/MunicipalityNavSavedFilters.tsx @@ -6,6 +6,8 @@ import { usePathname, useSearchParams } from 'next/navigation' import { useEffect, useId, useRef, useState } from 'react' import { toast } from 'sonner' +import { OPS_LIST_ONLINE_ONLY_MESSAGE } from '@/components/campaign/opsSync/opsListLocalCopy' +import { useBrowserOffline } from '@/components/campaign/opsSync/useBrowserOffline' import { useMunicipalitySavedFilters } from '@/components/campaign/shared/useMunicipalitySavedFilters' import { SidebarMenuAction, @@ -33,6 +35,7 @@ const IGNORED_PARAMS = ['page'] */ export const MunicipalityNavSavedFilters = ({ onNavigate }: { onNavigate: () => void }) => { const savedFilters = useMunicipalitySavedFilters() + const browserOffline = useBrowserOffline() const pathname = usePathname() const searchParams = useSearchParams() // Read once, not tracked: the store owns the list, this is only the @@ -136,8 +139,17 @@ export const MunicipalityNavSavedFilters = ({ onNavigate }: { onNavigate: () => handleRemove(entry)} - aria-label={`Apagar o filtro salvo ${entry.name}`} + onClick={() => { + if (browserOffline) return + handleRemove(entry) + }} + disabled={browserOffline} + title={browserOffline ? OPS_LIST_ONLINE_ONLY_MESSAGE : undefined} + aria-label={ + browserOffline + ? `Apagar o filtro salvo ${entry.name} — ${OPS_LIST_ONLINE_ONLY_MESSAGE}` + : `Apagar o filtro salvo ${entry.name}` + } className="top-1 group-focus-within/menu-sub-item:opacity-100 group-hover/menu-sub-item:opacity-100 md:opacity-0" >