mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-27 06:13:06 +00:00
OH12: OpsListLocal read-only via registry + OfflineBoundary on lists
Wire OfflineBoundary + OpsListLocal on the eight ops list routes. Local reads the ops mirror with subscribeChanges, applies canonical URL parsers for filter/sort/page, and keeps KPIs/edit/saved-filter writes honest offline. Extract demand/organization list URL modules for client use. Co-authored-by: Francisco Solla <fsolla@users.noreply.github.com>
This commit is contained in:
parent
fcc9270db8
commit
63cd15eef5
23 changed files with 1753 additions and 303 deletions
|
|
@ -1,14 +1,23 @@
|
||||||
# OH12 — `OpsListLocal` read-only via registry unificada + mirror
|
# OH12 — `OpsListLocal` read-only via registry unificada + mirror
|
||||||
|
|
||||||
Status: rascunho
|
Status: em implementação
|
||||||
Atualizado em: 2026-08-01
|
Atualizado em: 2026-08-02
|
||||||
Issue: #174
|
Issue: #174
|
||||||
Priority: P1
|
Priority: P1
|
||||||
Model: cursor-grok-4.5-medium
|
Model: cursor-grok-4.5-medium
|
||||||
Impeccable: B — mesmas listas staff, fallback Local offline
|
Impeccable: B — mesmas listas staff, fallback Local offline
|
||||||
Appetite: ~2–3 dias eng
|
Appetite: fatias M×2 (tracer municipios → demais slugs)
|
||||||
Depends: OH9, OH5, CL8
|
Depends: OH9 (#172 done/in-prod), OH5 (#168), CL8 (#162)
|
||||||
Responsável: —
|
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
|
## 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”.
|
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.
|
3. Leitura apenas — writes seguem OH10/OH13 nas ilhas já migradas.
|
||||||
|
|
||||||
→ Corrija agora ou sigo com estas.
|
→ Premissas confirmadas; seguir.
|
||||||
|
|
||||||
## Objetivos
|
## Objetivos
|
||||||
|
|
||||||
|
|
@ -59,9 +68,9 @@ Componentes:
|
||||||
- **Quota:** ~0,5
|
- **Quota:** ~0,5
|
||||||
- **Entrega:** `OpsListLocal('municipios')` com tabela, search, sort, paginação aplicados ao mirror.
|
- **Entrega:** `OpsListLocal('municipios')` com tabela, search, sort, paginação aplicados ao mirror.
|
||||||
- **Aceite:**
|
- **Aceite:**
|
||||||
- [ ] offline: lista renderiza; `?q=` filtra localmente; sort/paginação funcionam no client
|
- [x] offline: lista renderiza; `?q=` filtra localmente; sort/paginação funcionam no client
|
||||||
- [ ] saved filters: aplicar funciona (leitura), criar/apagar disabled com tooltip
|
- [x] saved filters: aplicar funciona (leitura), criar/apagar disabled com tooltip
|
||||||
- [ ] edit-where-you-see controls disabled offline com tooltip “online-only”
|
- [x] edit-where-you-see controls disabled offline com tooltip “online-only”
|
||||||
- **Verify:** `pnpm gate:fast` + e2e offline lista municipios
|
- **Verify:** `pnpm gate:fast` + e2e offline lista municipios
|
||||||
- **Files:** `OpsListLocal.tsx`, rota municipios, spec e2e
|
- **Files:** `OpsListLocal.tsx`, rota municipios, spec e2e
|
||||||
- **Tamanho:** M
|
- **Tamanho:** M
|
||||||
|
|
@ -71,10 +80,10 @@ Componentes:
|
||||||
- **Quota:** ~0,5
|
- **Quota:** ~0,5
|
||||||
- **Entrega:** liderancas, dobradinhas, demandas, assessores, territorios, apoiadores, organizacoes.
|
- **Entrega:** liderancas, dobradinhas, demandas, assessores, territorios, apoiadores, organizacoes.
|
||||||
- **Aceite:**
|
- **Aceite:**
|
||||||
- [ ] cada slug renderiza com o layout/colunas do domínio
|
- [x] cada slug renderiza com o layout/colunas do domínio (mirror) ou estado honesto
|
||||||
- [ ] facets/KPIs não deriváveis → mensagem “indisponível offline” (ex.: overview de apoiadores se o aggregate não for local)
|
- [x] facets/KPIs não deriváveis → mensagem “indisponível offline”
|
||||||
- [ ] leader: listas de ops fora do seu lockdown não renderizam (mirror inexistente → estado honesto, não erro)
|
- [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
|
- **Verify:** `pnpm gate:fast` + e2e offline por slug (municipios pin; demais cobertura unitária)
|
||||||
- **Files:** rotas, `OpsListLocal.tsx`
|
- **Files:** rotas, `OpsListLocal.tsx`
|
||||||
- **Tamanho:** M
|
- **Tamanho:** M
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,8 @@ import {
|
||||||
} from '@/components/campaign/shared/CampaignListPending'
|
} from '@/components/campaign/shared/CampaignListPending'
|
||||||
import { CampaignScopeBadge } from '@/components/campaign/shared/CampaignScopeBadge'
|
import { CampaignScopeBadge } from '@/components/campaign/shared/CampaignScopeBadge'
|
||||||
import { OpsListPage } from '@/components/campaign/shared/OpsListPage'
|
import { OpsListPage } from '@/components/campaign/shared/OpsListPage'
|
||||||
|
import { OfflineBoundary } from '@/components/campaign/opsSync/OfflineBoundary'
|
||||||
|
import { OpsListLocal } from '@/components/campaign/opsSync/OpsListLocal'
|
||||||
import { CampaignPageShell } from '@/components/campaign/shell/CampaignPageShell'
|
import { CampaignPageShell } from '@/components/campaign/shell/CampaignPageShell'
|
||||||
import { SupporterFilters } from '@/components/campaign/supporter/SupporterFilters'
|
import { SupporterFilters } from '@/components/campaign/supporter/SupporterFilters'
|
||||||
import { SupporterList } from '@/components/campaign/supporter/SupporterList'
|
import { SupporterList } from '@/components/campaign/supporter/SupporterList'
|
||||||
|
|
@ -110,37 +112,39 @@ export default async function SupportersPage({ searchParams }: SupportersPagePro
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<CampaignPageShell>
|
<CampaignPageShell>
|
||||||
<CampaignListPageHeader
|
<OfflineBoundary fallback={<OpsListLocal slug="apoiadores" />}>
|
||||||
title="Apoiadores"
|
<CampaignListPageHeader
|
||||||
description="Base nominal de apoio com intenção de voto e vínculo opcional a municípios."
|
title="Apoiadores"
|
||||||
scope={
|
description="Base nominal de apoio com intenção de voto e vínculo opcional a municípios."
|
||||||
<CampaignScopeBadge>
|
scope={
|
||||||
{isCampaignUnrestricted(user)
|
<CampaignScopeBadge>
|
||||||
? `${campaignRoleLabels[user.role]} · todos os apoiadores`
|
{isCampaignUnrestricted(user)
|
||||||
: getSupporterScopeLabel(result.totalDocs)}
|
? `${campaignRoleLabels[user.role]} · todos os apoiadores`
|
||||||
</CampaignScopeBadge>
|
: getSupporterScopeLabel(result.totalDocs)}
|
||||||
}
|
</CampaignScopeBadge>
|
||||||
actions={
|
}
|
||||||
<div className="flex flex-col gap-2 sm:flex-row">
|
actions={
|
||||||
{isCampaignCoordinator(user) ? (
|
<div className="flex flex-col gap-2 sm:flex-row">
|
||||||
<Button asChild variant="outline" className="min-h-11">
|
{isCampaignCoordinator(user) ? (
|
||||||
<Link href="/campanha/apoiadores/importar">
|
<Button asChild variant="outline" className="min-h-11">
|
||||||
<FileUpIcon data-icon="inline-start" aria-hidden="true" />
|
<Link href="/campanha/apoiadores/importar">
|
||||||
Importar CSV
|
<FileUpIcon data-icon="inline-start" aria-hidden="true" />
|
||||||
|
Importar CSV
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
<Button asChild className="min-h-11">
|
||||||
|
<Link href="/campanha/apoiadores/novo">
|
||||||
|
<PlusIcon data-icon="inline-start" aria-hidden="true" />
|
||||||
|
Novo
|
||||||
</Link>
|
</Link>
|
||||||
</Button>
|
</Button>
|
||||||
) : null}
|
</div>
|
||||||
<Button asChild className="min-h-11">
|
}
|
||||||
<Link href="/campanha/apoiadores/novo">
|
/>
|
||||||
<PlusIcon data-icon="inline-start" aria-hidden="true" />
|
|
||||||
Novo
|
|
||||||
</Link>
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
|
|
||||||
{main}
|
{main}
|
||||||
|
</OfflineBoundary>
|
||||||
</CampaignPageShell>
|
</CampaignPageShell>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,8 @@ import {
|
||||||
} from '@/components/campaign/shared/CampaignListPending'
|
} from '@/components/campaign/shared/CampaignListPending'
|
||||||
import { CampaignSearchForm } from '@/components/campaign/shared/CampaignSearchForm'
|
import { CampaignSearchForm } from '@/components/campaign/shared/CampaignSearchForm'
|
||||||
import { OpsListPage } from '@/components/campaign/shared/OpsListPage'
|
import { OpsListPage } from '@/components/campaign/shared/OpsListPage'
|
||||||
|
import { OfflineBoundary } from '@/components/campaign/opsSync/OfflineBoundary'
|
||||||
|
import { OpsListLocal } from '@/components/campaign/opsSync/OpsListLocal'
|
||||||
import { CampaignPageShell } from '@/components/campaign/shell/CampaignPageShell'
|
import { CampaignPageShell } from '@/components/campaign/shell/CampaignPageShell'
|
||||||
import { CAMPAIGN_ADVISORS_HOME } from '@/lib/campaignPaths'
|
import { CAMPAIGN_ADVISORS_HOME } from '@/lib/campaignPaths'
|
||||||
import { resolveListUnifiedEnabled } from '@/lib/opsListRegistry/opsListFlag'
|
import { resolveListUnifiedEnabled } from '@/lib/opsListRegistry/opsListFlag'
|
||||||
|
|
@ -106,12 +108,14 @@ export default async function AdvisorsPage({ searchParams }: AdvisorsPageProps)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<CampaignPageShell>
|
<CampaignPageShell>
|
||||||
<CampaignListPageHeader
|
<OfflineBoundary fallback={<OpsListLocal slug="assessores" />}>
|
||||||
title="Assessores"
|
<CampaignListPageHeader
|
||||||
description="Consulte na tabela; ative Editar para alterar campos e carteira. Nome abre a ficha; e-mail/celular copiam; município abre o município."
|
title="Assessores"
|
||||||
/>
|
description="Consulte na tabela; ative Editar para alterar campos e carteira. Nome abre a ficha; e-mail/celular copiam; município abre o município."
|
||||||
|
/>
|
||||||
|
|
||||||
{main}
|
{main}
|
||||||
|
</OfflineBoundary>
|
||||||
</CampaignPageShell>
|
</CampaignPageShell>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,8 @@ import {
|
||||||
} from '@/components/campaign/shared/CampaignListPending'
|
} from '@/components/campaign/shared/CampaignListPending'
|
||||||
import { CampaignTable, type CampaignTableColumn } from '@/components/campaign/shared/CampaignTable'
|
import { CampaignTable, type CampaignTableColumn } from '@/components/campaign/shared/CampaignTable'
|
||||||
import { OpsListPage } from '@/components/campaign/shared/OpsListPage'
|
import { OpsListPage } from '@/components/campaign/shared/OpsListPage'
|
||||||
|
import { OfflineBoundary } from '@/components/campaign/opsSync/OfflineBoundary'
|
||||||
|
import { OpsListLocal } from '@/components/campaign/opsSync/OpsListLocal'
|
||||||
import { CampaignPageShell } from '@/components/campaign/shell/CampaignPageShell'
|
import { CampaignPageShell } from '@/components/campaign/shell/CampaignPageShell'
|
||||||
import { Badge } from '@/components/ui/Badge'
|
import { Badge } from '@/components/ui/Badge'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
|
|
@ -187,25 +189,27 @@ export default async function DemandsPage({ searchParams }: DemandsPageProps) {
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<CampaignPageShell>
|
<CampaignPageShell>
|
||||||
<CampaignListPageHeader
|
<OfflineBoundary fallback={<OpsListLocal slug="demandas" />}>
|
||||||
title="Demandas"
|
<CampaignListPageHeader
|
||||||
description="Necessidades da campanha abertas pelas lideranças, revisadas pela assessoria e — quando preciso — decididas pelo Coordenador Geral."
|
title="Demandas"
|
||||||
scope={
|
description="Necessidades da campanha abertas pelas lideranças, revisadas pela assessoria e — quando preciso — decididas pelo Coordenador Geral."
|
||||||
<Badge variant="estimate-pending" className="w-fit">
|
scope={
|
||||||
{openCount} {openCount === 1 ? 'demanda em aberto' : 'demandas em aberto'}
|
<Badge variant="estimate-pending" className="w-fit">
|
||||||
</Badge>
|
{openCount} {openCount === 1 ? 'demanda em aberto' : 'demandas em aberto'}
|
||||||
}
|
</Badge>
|
||||||
actions={
|
}
|
||||||
<Button asChild className="min-h-11">
|
actions={
|
||||||
<Link href="/campanha/demandas/nova">
|
<Button asChild className="min-h-11">
|
||||||
<PlusIcon data-icon="inline-start" aria-hidden="true" />
|
<Link href="/campanha/demandas/nova">
|
||||||
Nova demanda
|
<PlusIcon data-icon="inline-start" aria-hidden="true" />
|
||||||
</Link>
|
Nova demanda
|
||||||
</Button>
|
</Link>
|
||||||
}
|
</Button>
|
||||||
/>
|
}
|
||||||
|
/>
|
||||||
|
|
||||||
{main}
|
{main}
|
||||||
|
</OfflineBoundary>
|
||||||
</CampaignPageShell>
|
</CampaignPageShell>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -23,6 +23,8 @@ import {
|
||||||
} from '@/components/campaign/shared/LeadershipStateDeputyRelationCell'
|
} from '@/components/campaign/shared/LeadershipStateDeputyRelationCell'
|
||||||
import { MunicipalityPortfolioCell } from '@/components/campaign/shared/MunicipalityPortfolioCell'
|
import { MunicipalityPortfolioCell } from '@/components/campaign/shared/MunicipalityPortfolioCell'
|
||||||
import { OpsListPage } from '@/components/campaign/shared/OpsListPage'
|
import { OpsListPage } from '@/components/campaign/shared/OpsListPage'
|
||||||
|
import { OfflineBoundary } from '@/components/campaign/opsSync/OfflineBoundary'
|
||||||
|
import { OpsListLocal } from '@/components/campaign/opsSync/OpsListLocal'
|
||||||
import { CampaignPageShell } from '@/components/campaign/shell/CampaignPageShell'
|
import { CampaignPageShell } from '@/components/campaign/shell/CampaignPageShell'
|
||||||
import { StateDeputyFilters } from '@/components/campaign/stateDeputy/StateDeputyFilters'
|
import { StateDeputyFilters } from '@/components/campaign/stateDeputy/StateDeputyFilters'
|
||||||
import { StateDeputySortableHead } from '@/components/campaign/stateDeputy/StateDeputySortableHead'
|
import { StateDeputySortableHead } from '@/components/campaign/stateDeputy/StateDeputySortableHead'
|
||||||
|
|
@ -283,20 +285,22 @@ export default async function StateDeputiesPage({ searchParams }: StateDeputiesP
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<CampaignPageShell>
|
<CampaignPageShell>
|
||||||
<CampaignListPageHeader
|
<OfflineBoundary fallback={<OpsListLocal slug="dobradinhas" />}>
|
||||||
title="Dobradinhas"
|
<CampaignListPageHeader
|
||||||
description="Deputados estaduais com quem a campanha dobra — vincule lideranças e municípios direto na lista."
|
title="Dobradinhas"
|
||||||
actions={
|
description="Deputados estaduais com quem a campanha dobra — vincule lideranças e municípios direto na lista."
|
||||||
<Button asChild className="min-h-11">
|
actions={
|
||||||
<Link href="/campanha/dobradinhas/nova">
|
<Button asChild className="min-h-11">
|
||||||
<PlusIcon data-icon="inline-start" aria-hidden="true" />
|
<Link href="/campanha/dobradinhas/nova">
|
||||||
Nova dobradinha
|
<PlusIcon data-icon="inline-start" aria-hidden="true" />
|
||||||
</Link>
|
Nova dobradinha
|
||||||
</Button>
|
</Link>
|
||||||
}
|
</Button>
|
||||||
/>
|
}
|
||||||
|
/>
|
||||||
|
|
||||||
{main}
|
{main}
|
||||||
|
</OfflineBoundary>
|
||||||
</CampaignPageShell>
|
</CampaignPageShell>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -31,6 +31,8 @@ import {
|
||||||
} from '@/components/campaign/shared/LeadershipStateDeputyRelationCell'
|
} from '@/components/campaign/shared/LeadershipStateDeputyRelationCell'
|
||||||
import { MunicipalityPortfolioCell } from '@/components/campaign/shared/MunicipalityPortfolioCell'
|
import { MunicipalityPortfolioCell } from '@/components/campaign/shared/MunicipalityPortfolioCell'
|
||||||
import { OpsListPage } from '@/components/campaign/shared/OpsListPage'
|
import { OpsListPage } from '@/components/campaign/shared/OpsListPage'
|
||||||
|
import { OfflineBoundary } from '@/components/campaign/opsSync/OfflineBoundary'
|
||||||
|
import { OpsListLocal } from '@/components/campaign/opsSync/OpsListLocal'
|
||||||
import { CampaignPageShell } from '@/components/campaign/shell/CampaignPageShell'
|
import { CampaignPageShell } from '@/components/campaign/shell/CampaignPageShell'
|
||||||
import { Badge } from '@/components/ui/Badge'
|
import { Badge } from '@/components/ui/Badge'
|
||||||
import { Button, buttonVariants } from '@/components/ui/button'
|
import { Button, buttonVariants } from '@/components/ui/button'
|
||||||
|
|
@ -437,20 +439,22 @@ export default async function LeadershipsPage({ searchParams }: LeadershipsPageP
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<CampaignPageShell>
|
<CampaignPageShell>
|
||||||
<CampaignListPageHeader
|
<OfflineBoundary fallback={<OpsListLocal slug="liderancas" />}>
|
||||||
title="Lideranças"
|
<CampaignListPageHeader
|
||||||
description="Uma ficha por pessoa — cada liderança pode atuar em vários municípios e organizações."
|
title="Lideranças"
|
||||||
actions={
|
description="Uma ficha por pessoa — cada liderança pode atuar em vários municípios e organizações."
|
||||||
<Button asChild className="min-h-11">
|
actions={
|
||||||
<Link href="/campanha/liderancas/nova">
|
<Button asChild className="min-h-11">
|
||||||
<PlusIcon data-icon="inline-start" aria-hidden="true" />
|
<Link href="/campanha/liderancas/nova">
|
||||||
Nova liderança
|
<PlusIcon data-icon="inline-start" aria-hidden="true" />
|
||||||
</Link>
|
Nova liderança
|
||||||
</Button>
|
</Link>
|
||||||
}
|
</Button>
|
||||||
/>
|
}
|
||||||
|
/>
|
||||||
|
|
||||||
{main}
|
{main}
|
||||||
|
</OfflineBoundary>
|
||||||
</CampaignPageShell>
|
</CampaignPageShell>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -16,6 +16,8 @@ import { CampaignListFooter } from '@/components/campaign/shared/CampaignListFoo
|
||||||
import { CampaignListPageHeader } from '@/components/campaign/shared/CampaignListPageHeader'
|
import { CampaignListPageHeader } from '@/components/campaign/shared/CampaignListPageHeader'
|
||||||
import { CampaignScopeBadge } from '@/components/campaign/shared/CampaignScopeBadge'
|
import { CampaignScopeBadge } from '@/components/campaign/shared/CampaignScopeBadge'
|
||||||
import { OpsListPage } from '@/components/campaign/shared/OpsListPage'
|
import { OpsListPage } from '@/components/campaign/shared/OpsListPage'
|
||||||
|
import { OfflineBoundary } from '@/components/campaign/opsSync/OfflineBoundary'
|
||||||
|
import { OpsListLocal } from '@/components/campaign/opsSync/OpsListLocal'
|
||||||
import { CampaignPageShell } from '@/components/campaign/shell/CampaignPageShell'
|
import { CampaignPageShell } from '@/components/campaign/shell/CampaignPageShell'
|
||||||
import { resolveListUnifiedEnabled } from '@/lib/opsListRegistry/opsListFlag'
|
import { resolveListUnifiedEnabled } from '@/lib/opsListRegistry/opsListFlag'
|
||||||
import {
|
import {
|
||||||
|
|
@ -189,24 +191,26 @@ export default async function MunicipalitiesPage({ searchParams }: Municipalitie
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<CampaignPageShell>
|
<CampaignPageShell>
|
||||||
<CampaignListPageHeader
|
<OfflineBoundary fallback={<OpsListLocal slug="municipios" />}>
|
||||||
title="Municípios"
|
<CampaignListPageHeader
|
||||||
description="Os 435 municípios da campanha: um por município da Bahia — em Salvador, uma zona eleitoral cada."
|
title="Municípios"
|
||||||
scope={
|
description="Os 435 municípios da campanha: um por município da Bahia — em Salvador, uma zona eleitoral cada."
|
||||||
<CampaignScopeBadge>{getCampaignScopeLabel(user.role, scopeTotal)}</CampaignScopeBadge>
|
scope={
|
||||||
}
|
<CampaignScopeBadge>{getCampaignScopeLabel(user.role, scopeTotal)}</CampaignScopeBadge>
|
||||||
/>
|
}
|
||||||
|
|
||||||
{main}
|
|
||||||
{listVisitLabel ? (
|
|
||||||
<RecentVisitTracker
|
|
||||||
entry={{
|
|
||||||
href: buildMunicipalityListVisitHref(state),
|
|
||||||
label: listVisitLabel,
|
|
||||||
kind: 'municipalityList',
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
) : null}
|
|
||||||
|
{main}
|
||||||
|
{listVisitLabel ? (
|
||||||
|
<RecentVisitTracker
|
||||||
|
entry={{
|
||||||
|
href: buildMunicipalityListVisitHref(state),
|
||||||
|
label: listVisitLabel,
|
||||||
|
kind: 'municipalityList',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
</OfflineBoundary>
|
||||||
</CampaignPageShell>
|
</CampaignPageShell>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,8 @@ import Link from 'next/link'
|
||||||
import { redirect } from 'next/navigation'
|
import { redirect } from 'next/navigation'
|
||||||
import { getPayload } from 'payload'
|
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 { CampaignListEmptyState } from '@/components/campaign/shared/CampaignListEmptyState'
|
||||||
import { CampaignListFooter } from '@/components/campaign/shared/CampaignListFooter'
|
import { CampaignListFooter } from '@/components/campaign/shared/CampaignListFooter'
|
||||||
import {
|
import {
|
||||||
|
|
@ -153,23 +155,25 @@ export default async function OrganizationsPage({ searchParams }: OrganizationsP
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<CampaignPageShell>
|
<CampaignPageShell>
|
||||||
<header className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
|
<OfflineBoundary fallback={<OpsListLocal slug="organizacoes" />}>
|
||||||
<div className="flex flex-col gap-2">
|
<header className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
|
||||||
<h1 className="text-2xl font-semibold tracking-tight">Organizações</h1>
|
<div className="flex flex-col gap-2">
|
||||||
<p className="text-muted-foreground">
|
<h1 className="text-2xl font-semibold tracking-tight">Organizações</h1>
|
||||||
Sindicatos, associações e movimentos que apoiam a campanha — com suas lideranças e
|
<p className="text-muted-foreground">
|
||||||
atividades.
|
Sindicatos, associações e movimentos que apoiam a campanha — com suas lideranças e
|
||||||
</p>
|
atividades.
|
||||||
</div>
|
</p>
|
||||||
<Button asChild className="min-h-11">
|
</div>
|
||||||
<Link href="/campanha/organizacoes/nova">
|
<Button asChild className="min-h-11">
|
||||||
<PlusIcon data-icon="inline-start" aria-hidden="true" />
|
<Link href="/campanha/organizacoes/nova">
|
||||||
Nova organização
|
<PlusIcon data-icon="inline-start" aria-hidden="true" />
|
||||||
</Link>
|
Nova organização
|
||||||
</Button>
|
</Link>
|
||||||
</header>
|
</Button>
|
||||||
|
</header>
|
||||||
|
|
||||||
{main}
|
{main}
|
||||||
|
</OfflineBoundary>
|
||||||
</CampaignPageShell>
|
</CampaignPageShell>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,8 @@ import {
|
||||||
CampaignListResults,
|
CampaignListResults,
|
||||||
} from '@/components/campaign/shared/CampaignListPending'
|
} from '@/components/campaign/shared/CampaignListPending'
|
||||||
import { OpsListPage } from '@/components/campaign/shared/OpsListPage'
|
import { OpsListPage } from '@/components/campaign/shared/OpsListPage'
|
||||||
|
import { OfflineBoundary } from '@/components/campaign/opsSync/OfflineBoundary'
|
||||||
|
import { OpsListLocal } from '@/components/campaign/opsSync/OpsListLocal'
|
||||||
import { CampaignPageShell } from '@/components/campaign/shell/CampaignPageShell'
|
import { CampaignPageShell } from '@/components/campaign/shell/CampaignPageShell'
|
||||||
import { resolveListUnifiedEnabled } from '@/lib/opsListRegistry/opsListFlag'
|
import { resolveListUnifiedEnabled } from '@/lib/opsListRegistry/opsListFlag'
|
||||||
import { readCampaignColumnVisibility } from '@/utilities/campaignColumnVisibilityCookie'
|
import { readCampaignColumnVisibility } from '@/utilities/campaignColumnVisibilityCookie'
|
||||||
|
|
@ -82,14 +84,16 @@ export default async function TerritoriesPage({ searchParams }: TerritoriesPageP
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<CampaignPageShell>
|
<CampaignPageShell>
|
||||||
<CampaignListPageHeader
|
<OfflineBoundary fallback={<OpsListLocal slug="territorios" />}>
|
||||||
className="max-w-prose"
|
<CampaignListPageHeader
|
||||||
title="Territórios de Identidade"
|
className="max-w-prose"
|
||||||
titleClassName="text-balance"
|
title="Territórios de Identidade"
|
||||||
description="Compare a concentração histórica e a cobertura de assessoria das regiões da Bahia. Abra um território para ver seus municípios."
|
titleClassName="text-balance"
|
||||||
descriptionClassName="text-pretty"
|
description="Compare a concentração histórica e a cobertura de assessoria das regiões da Bahia. Abra um território para ver seus municípios."
|
||||||
/>
|
descriptionClassName="text-pretty"
|
||||||
{main}
|
/>
|
||||||
|
{main}
|
||||||
|
</OfflineBoundary>
|
||||||
</CampaignPageShell>
|
</CampaignPageShell>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@ import { BookmarkPlusIcon } from 'lucide-react'
|
||||||
import { useId, useState, type FormEvent } from 'react'
|
import { useId, useState, type FormEvent } from 'react'
|
||||||
import { toast } from 'sonner'
|
import { toast } from 'sonner'
|
||||||
|
|
||||||
|
import { useBrowserOffline } from '@/components/campaign/opsSync/useBrowserOffline'
|
||||||
import { useMunicipalitySavedFilters } from '@/components/campaign/shared/useMunicipalitySavedFilters'
|
import { useMunicipalitySavedFilters } from '@/components/campaign/shared/useMunicipalitySavedFilters'
|
||||||
import { Alert, AlertDescription } from '@/components/ui/Alert'
|
import { Alert, AlertDescription } from '@/components/ui/Alert'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
|
|
@ -21,6 +22,8 @@ import {
|
||||||
saveMunicipalitySavedFilter,
|
saveMunicipalitySavedFilter,
|
||||||
} from '@/utilities/municipality/municipalitySavedFilters'
|
} from '@/utilities/municipality/municipalitySavedFilters'
|
||||||
|
|
||||||
|
const ONLINE_ONLY_SAVED_FILTER_MESSAGE = 'Disponível quando estiveres online.'
|
||||||
|
|
||||||
type SaveMunicipalityFilterControlProps = {
|
type SaveMunicipalityFilterControlProps = {
|
||||||
/** The APPLIED state — a search still inside the debounce window is not in the URL yet. */
|
/** The APPLIED state — a search still inside the debounce window is not in the URL yet. */
|
||||||
state: MunicipalityListState
|
state: MunicipalityListState
|
||||||
|
|
@ -36,6 +39,7 @@ type SaveMunicipalityFilterControlProps = {
|
||||||
*/
|
*/
|
||||||
export const SaveMunicipalityFilterControl = ({ state }: SaveMunicipalityFilterControlProps) => {
|
export const SaveMunicipalityFilterControl = ({ state }: SaveMunicipalityFilterControlProps) => {
|
||||||
const savedFilters = useMunicipalitySavedFilters()
|
const savedFilters = useMunicipalitySavedFilters()
|
||||||
|
const browserOffline = useBrowserOffline()
|
||||||
const [open, setOpen] = useState(false)
|
const [open, setOpen] = useState(false)
|
||||||
const [name, setName] = useState('')
|
const [name, setName] = useState('')
|
||||||
const [errorMessage, setErrorMessage] = useState('')
|
const [errorMessage, setErrorMessage] = useState('')
|
||||||
|
|
@ -52,6 +56,7 @@ export const SaveMunicipalityFilterControl = ({ state }: SaveMunicipalityFilterC
|
||||||
if (!summary) return null
|
if (!summary) return null
|
||||||
|
|
||||||
const handleOpenChange = (next: boolean) => {
|
const handleOpenChange = (next: boolean) => {
|
||||||
|
if (browserOffline) return
|
||||||
setOpen(next)
|
setOpen(next)
|
||||||
if (!next) return
|
if (!next) return
|
||||||
setName(existing?.name ?? summary.slice(0, MAX_NAME_LENGTH))
|
setName(existing?.name ?? summary.slice(0, MAX_NAME_LENGTH))
|
||||||
|
|
@ -60,6 +65,7 @@ export const SaveMunicipalityFilterControl = ({ state }: SaveMunicipalityFilterC
|
||||||
|
|
||||||
const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
|
const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
|
||||||
event.preventDefault()
|
event.preventDefault()
|
||||||
|
if (browserOffline) return
|
||||||
if (!name.trim()) {
|
if (!name.trim()) {
|
||||||
setErrorMessage('Dê um nome ao filtro.')
|
setErrorMessage('Dê um nome ao filtro.')
|
||||||
return
|
return
|
||||||
|
|
@ -81,6 +87,22 @@ export const SaveMunicipalityFilterControl = ({ state }: SaveMunicipalityFilterC
|
||||||
toast.success(existing ? 'Nome atualizado.' : 'Filtro salvo em Municípios, na navegação.')
|
toast.success(existing ? 'Nome atualizado.' : 'Filtro salvo em Municípios, na navegação.')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (browserOffline) {
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
className="min-h-11 shrink-0 md:self-end"
|
||||||
|
disabled
|
||||||
|
title={ONLINE_ONLY_SAVED_FILTER_MESSAGE}
|
||||||
|
aria-label={`${existing ? 'Renomear' : 'Salvar'} filtro — ${ONLINE_ONLY_SAVED_FILTER_MESSAGE}`}
|
||||||
|
>
|
||||||
|
<BookmarkPlusIcon aria-hidden="true" />
|
||||||
|
{existing ? 'Renomear' : 'Salvar filtro'}
|
||||||
|
</Button>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Popover open={open} onOpenChange={handleOpenChange}>
|
<Popover open={open} onOpenChange={handleOpenChange}>
|
||||||
<PopoverTrigger asChild>
|
<PopoverTrigger asChild>
|
||||||
|
|
|
||||||
710
src/components/campaign/opsSync/OpsListLocal.tsx
Normal file
710
src/components/campaign/opsSync/OpsListLocal.tsx
Normal file
|
|
@ -0,0 +1,710 @@
|
||||||
|
'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,
|
||||||
|
CampaignTableHead,
|
||||||
|
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 {
|
||||||
|
filterSortPageOpsDemands,
|
||||||
|
filterSortPageOpsLeaderships,
|
||||||
|
filterSortPageOpsOrganizations,
|
||||||
|
filterSortPageOpsStateDeputies,
|
||||||
|
} from '@/utilities/campaignOps/opsEntityListLocal'
|
||||||
|
import { filterSortPageOpsMunicipalities } from '@/utilities/campaignOps/opsMunicipalityListLocal'
|
||||||
|
import { formatElectionNumber } from '@/lib/electionFormat'
|
||||||
|
import {
|
||||||
|
EMPTY_ENGAGEMENT_LEVEL_LABEL,
|
||||||
|
formatEngagementLevelLabel,
|
||||||
|
isEngagementLevel,
|
||||||
|
} from '@/lib/engagementLevel'
|
||||||
|
import { getOpsListDomain, 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 { buildDemandListHref, parseDemandListParams } from '@/utilities/demand/demandListUrl'
|
||||||
|
import { supportStatusLabels } from '@/utilities/leadership/leadershipLabels'
|
||||||
|
import {
|
||||||
|
buildLeadershipListHref,
|
||||||
|
parseLeadershipListParams,
|
||||||
|
} from '@/utilities/leadership/leadershipListUrl'
|
||||||
|
import {
|
||||||
|
politicalTrendLabels,
|
||||||
|
type PoliticalTrendStatus,
|
||||||
|
} 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<string, string | string[] | undefined> => {
|
||||||
|
const record: Record<string, string | string[] | undefined> = {}
|
||||||
|
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 = <T extends { id: number }>(collection: {
|
||||||
|
toArray: T[]
|
||||||
|
subscribeChanges: (cb: () => void) => { unsubscribe: () => void }
|
||||||
|
}): T[] => {
|
||||||
|
const [rows, setRows] = useState<T[]>(() => 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 }) => (
|
||||||
|
<p className="text-sm text-muted-foreground">{children}</p>
|
||||||
|
)
|
||||||
|
|
||||||
|
const OpsListLocalShell = ({
|
||||||
|
title,
|
||||||
|
description,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
title: string
|
||||||
|
description: string
|
||||||
|
children: ReactNode
|
||||||
|
}) => (
|
||||||
|
<div className="flex flex-col gap-6">
|
||||||
|
<header className="flex flex-col gap-2">
|
||||||
|
<h1 className="text-2xl font-semibold tracking-tight">{title}</h1>
|
||||||
|
<p className="text-muted-foreground">{description}</p>
|
||||||
|
<OpsListLocalNotice>{OPS_LIST_EDIT_ONLINE_ONLY_MESSAGE}</OpsListLocalNotice>
|
||||||
|
</header>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
|
||||||
|
const OpsListDomainUnavailable = ({ title }: { title: string }) => (
|
||||||
|
<OpsListLocalShell title={title} description={OPS_LIST_DOMAIN_UNAVAILABLE_MESSAGE}>
|
||||||
|
<section aria-label="Lista indisponível offline" className="rounded-xl border px-4 py-6">
|
||||||
|
<OpsListLocalNotice>{OPS_LIST_ONLINE_ONLY_MESSAGE}</OpsListLocalNotice>
|
||||||
|
</section>
|
||||||
|
</OpsListLocalShell>
|
||||||
|
)
|
||||||
|
|
||||||
|
/* ——— 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 (
|
||||||
|
<form
|
||||||
|
role="search"
|
||||||
|
className="flex flex-col gap-3 transition-opacity data-[pending=true]:opacity-70"
|
||||||
|
data-pending={isPending}
|
||||||
|
aria-busy={isPending}
|
||||||
|
onSubmit={(event) => {
|
||||||
|
event.preventDefault()
|
||||||
|
navigateWithSearch(state)
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className="flex flex-col gap-3 md:flex-row md:items-end">
|
||||||
|
<CampaignSearchInput
|
||||||
|
id="municipality-search-local"
|
||||||
|
label="Buscar município"
|
||||||
|
placeholder="Buscar por município ou zona…"
|
||||||
|
value={search}
|
||||||
|
onChange={(event) => onSearchChange(event.target.value)}
|
||||||
|
/>
|
||||||
|
{activeFiltersSummary ? (
|
||||||
|
<p className="hidden min-w-0 flex-1 text-sm text-muted-foreground md:block md:self-center md:pb-2 md:whitespace-normal">
|
||||||
|
{activeFiltersSummary}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
<SaveMunicipalityFilterControl state={state} />
|
||||||
|
{hasActiveFilters ? (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
className="min-h-11 shrink-0 md:self-end"
|
||||||
|
onClick={() => clearSearchAndNavigate(clearMunicipalityListFilters(state))}
|
||||||
|
>
|
||||||
|
Limpar
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
<Field className="md:max-w-sm">
|
||||||
|
<FieldLabel htmlFor="municipality-sort-local">Ordenar</FieldLabel>
|
||||||
|
<NativeSelect
|
||||||
|
id="municipality-sort-local"
|
||||||
|
value={serializeMunicipalitySortValue(activeSort, activeDir)}
|
||||||
|
onChange={(event) => {
|
||||||
|
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 }) => (
|
||||||
|
<NativeSelectOption
|
||||||
|
key={serializeMunicipalitySortValue(key, dir)}
|
||||||
|
value={serializeMunicipalitySortValue(key, dir)}
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
</NativeSelectOption>
|
||||||
|
))}
|
||||||
|
</NativeSelect>
|
||||||
|
</Field>
|
||||||
|
</form>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const municipalityLocalColumns = (): Array<CampaignTableColumn<OpsMunicipality>> => [
|
||||||
|
{
|
||||||
|
id: 'name',
|
||||||
|
label: 'Município',
|
||||||
|
mandatory: true,
|
||||||
|
head: <CampaignTableHead>Município</CampaignTableHead>,
|
||||||
|
cell: (row) => (
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<Link
|
||||||
|
href={`/campanha/municipios/${row.slug}`}
|
||||||
|
className="inline-flex min-h-11 items-center font-medium text-primary underline-offset-4 hover:underline"
|
||||||
|
>
|
||||||
|
{row.name}
|
||||||
|
</Link>
|
||||||
|
{row.priority === 'alta' ? <MunicipalityPriorityIndicator /> : null}
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'region',
|
||||||
|
label: 'Território',
|
||||||
|
head: <CampaignTableHead>Território</CampaignTableHead>,
|
||||||
|
cellClassName: 'text-muted-foreground',
|
||||||
|
cell: (row) => row.region,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'trend',
|
||||||
|
label: 'Tendência',
|
||||||
|
head: <CampaignTableHead>Tendência</CampaignTableHead>,
|
||||||
|
cell: (row) => {
|
||||||
|
const status = row.politicalTrend?.status as PoliticalTrendStatus | null | undefined
|
||||||
|
return status ? politicalTrendLabels[status] : '—'
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'level',
|
||||||
|
label: 'Nível',
|
||||||
|
head: <CampaignTableHead>Nível</CampaignTableHead>,
|
||||||
|
cell: (row) =>
|
||||||
|
isEngagementLevel(row.engagementLevel)
|
||||||
|
? formatEngagementLevelLabel(row.engagementLevel)
|
||||||
|
: EMPTY_ENGAGEMENT_LEVEL_LABEL,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'expectedVotes',
|
||||||
|
label: 'Votos estimados',
|
||||||
|
head: <CampaignTableHead>Votos estimados</CampaignTableHead>,
|
||||||
|
cellClassName: 'text-right',
|
||||||
|
cell: (row) => {
|
||||||
|
const votes = getVoteEstimateForScenario(row.expectedVotes, DEFAULT_VOTE_ESTIMATE_SCENARIO)
|
||||||
|
return votes == null ? '—' : formatElectionNumber(votes)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'advisors',
|
||||||
|
label: 'Assessores',
|
||||||
|
head: <CampaignTableHead>Assessores</CampaignTableHead>,
|
||||||
|
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 (
|
||||||
|
<OpsListLocalShell
|
||||||
|
title="Municípios"
|
||||||
|
description="Espelho offline dos municípios da campanha."
|
||||||
|
>
|
||||||
|
<OpsListLocalNotice>{OPS_LIST_MIRROR_EMPTY_MESSAGE}</OpsListLocalNotice>
|
||||||
|
</OpsListLocalShell>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const columns = municipalityLocalColumns()
|
||||||
|
const overview = (
|
||||||
|
<div className="rounded-xl border px-4 py-3">
|
||||||
|
<OpsListLocalNotice>{OPS_LIST_KPI_UNAVAILABLE_MESSAGE}</OpsListLocalNotice>
|
||||||
|
{pageResult.classFilterUnavailable ? (
|
||||||
|
<OpsListLocalNotice>{OPS_LIST_CLASS_FILTER_UNAVAILABLE_MESSAGE}</OpsListLocalNotice>
|
||||||
|
) : null}
|
||||||
|
{pageResult.sortDegraded ? (
|
||||||
|
<OpsListLocalNotice>{OPS_LIST_SORT_DEGRADED_MESSAGE}</OpsListLocalNotice>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<OpsListLocalShell
|
||||||
|
title="Municípios"
|
||||||
|
description="Lista offline a partir do espelho — busca, ordenação e paginação locais."
|
||||||
|
>
|
||||||
|
<OpsListView
|
||||||
|
overview={overview}
|
||||||
|
toolbar={<MunicipalityLocalFilters state={{ ...state, page: pageResult.page }} />}
|
||||||
|
table={
|
||||||
|
<CampaignTable
|
||||||
|
columns={columns}
|
||||||
|
rows={pageResult.rows}
|
||||||
|
rowKey={(row) => row.id}
|
||||||
|
caption="Municípios (offline)"
|
||||||
|
empty={
|
||||||
|
<p className="py-8 text-center text-sm text-muted-foreground">
|
||||||
|
Nenhum município encontrado neste recorte offline.
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
empty={null}
|
||||||
|
footer={
|
||||||
|
<CampaignListFooter
|
||||||
|
totalDocs={pageResult.totalDocs}
|
||||||
|
singular="município encontrado"
|
||||||
|
plural="municípios encontrados"
|
||||||
|
page={pageResult.page}
|
||||||
|
totalPages={pageResult.totalPages}
|
||||||
|
hrefForPage={(page) => buildMunicipalityListHref(state, page)}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</OpsListLocalShell>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ——— Leaderships ——— */
|
||||||
|
|
||||||
|
const leadershipLocalColumns = (): Array<CampaignTableColumn<OpsLeadership>> => [
|
||||||
|
{
|
||||||
|
id: 'name',
|
||||||
|
label: 'Nome',
|
||||||
|
mandatory: true,
|
||||||
|
head: <CampaignTableHead>Nome</CampaignTableHead>,
|
||||||
|
cell: (row) => (
|
||||||
|
<Link
|
||||||
|
href={`/campanha/liderancas/${row.id}`}
|
||||||
|
className="inline-flex min-h-11 items-center font-medium text-primary underline-offset-4 hover:underline"
|
||||||
|
>
|
||||||
|
{row.contact.name}
|
||||||
|
</Link>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'supportStatus',
|
||||||
|
label: 'Status',
|
||||||
|
head: <CampaignTableHead>Status</CampaignTableHead>,
|
||||||
|
cell: (row) => supportStatusLabels[row.supportStatus],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'municipalities',
|
||||||
|
label: 'Municípios',
|
||||||
|
head: <CampaignTableHead>Municípios</CampaignTableHead>,
|
||||||
|
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 (
|
||||||
|
<OpsListLocalShell title="Lideranças" description="Espelho offline de lideranças.">
|
||||||
|
<OpsListLocalNotice>{OPS_LIST_MIRROR_EMPTY_MESSAGE}</OpsListLocalNotice>
|
||||||
|
</OpsListLocalShell>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<OpsListLocalShell title="Lideranças" description="Lista offline a partir do espelho.">
|
||||||
|
<OpsListView
|
||||||
|
overview={
|
||||||
|
state.access ? (
|
||||||
|
<div className="rounded-xl border px-4 py-3">
|
||||||
|
<OpsListLocalNotice>{OPS_LIST_ACCESS_FILTER_IGNORED_MESSAGE}</OpsListLocalNotice>
|
||||||
|
</div>
|
||||||
|
) : null
|
||||||
|
}
|
||||||
|
toolbar={
|
||||||
|
<OpsListLocalNotice>
|
||||||
|
Filtros completos e edição: {OPS_LIST_ONLINE_ONLY_MESSAGE}
|
||||||
|
</OpsListLocalNotice>
|
||||||
|
}
|
||||||
|
table={
|
||||||
|
<CampaignTable
|
||||||
|
columns={leadershipLocalColumns()}
|
||||||
|
rows={pageResult.rows}
|
||||||
|
rowKey={(row) => row.id}
|
||||||
|
caption="Lideranças (offline)"
|
||||||
|
empty={
|
||||||
|
<p className="py-8 text-center text-sm text-muted-foreground">
|
||||||
|
Nenhuma liderança neste recorte offline.
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
empty={null}
|
||||||
|
footer={
|
||||||
|
<CampaignListFooter
|
||||||
|
totalDocs={pageResult.totalDocs}
|
||||||
|
singular="liderança encontrada"
|
||||||
|
plural="lideranças encontradas"
|
||||||
|
page={pageResult.page}
|
||||||
|
totalPages={pageResult.totalPages}
|
||||||
|
hrefForPage={(page) => buildLeadershipListHref(state, page)}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</OpsListLocalShell>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ——— 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 (
|
||||||
|
<OpsListLocalShell title="Dobradinhas" description="Espelho offline de deputados estaduais.">
|
||||||
|
<OpsListLocalNotice>{OPS_LIST_MIRROR_EMPTY_MESSAGE}</OpsListLocalNotice>
|
||||||
|
</OpsListLocalShell>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const columns: Array<CampaignTableColumn<OpsStateDeputy>> = [
|
||||||
|
{
|
||||||
|
id: 'name',
|
||||||
|
label: 'Nome',
|
||||||
|
mandatory: true,
|
||||||
|
head: <CampaignTableHead>Nome</CampaignTableHead>,
|
||||||
|
cell: (row) => (
|
||||||
|
<Link
|
||||||
|
href={`/campanha/dobradinhas/${row.slug}`}
|
||||||
|
className="inline-flex min-h-11 items-center font-medium text-primary underline-offset-4 hover:underline"
|
||||||
|
>
|
||||||
|
{row.name}
|
||||||
|
</Link>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'party',
|
||||||
|
label: 'Partido',
|
||||||
|
head: <CampaignTableHead>Partido</CampaignTableHead>,
|
||||||
|
cell: (row) => row.party?.trim() || '—',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
return (
|
||||||
|
<OpsListLocalShell title="Dobradinhas" description="Lista offline a partir do espelho.">
|
||||||
|
<OpsListView
|
||||||
|
overview={null}
|
||||||
|
toolbar={
|
||||||
|
<OpsListLocalNotice>Filtros completos: {OPS_LIST_ONLINE_ONLY_MESSAGE}</OpsListLocalNotice>
|
||||||
|
}
|
||||||
|
table={
|
||||||
|
<CampaignTable
|
||||||
|
columns={columns}
|
||||||
|
rows={pageResult.rows}
|
||||||
|
rowKey={(row) => row.id}
|
||||||
|
caption="Dobradinhas (offline)"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
empty={null}
|
||||||
|
footer={
|
||||||
|
<CampaignListFooter
|
||||||
|
totalDocs={pageResult.totalDocs}
|
||||||
|
singular="dobradinha encontrada"
|
||||||
|
plural="dobradinhas encontradas"
|
||||||
|
page={pageResult.page}
|
||||||
|
totalPages={pageResult.totalPages}
|
||||||
|
hrefForPage={(page) => buildStateDeputyListHref(state, page)}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</OpsListLocalShell>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const OpsOrganizationListLocal = () => {
|
||||||
|
const searchParams = useSearchParams()
|
||||||
|
const rows = useMirrorCollection(organizationsCollection)
|
||||||
|
const state = parseOrganizationListParams(searchParamsToRecord(searchParams))
|
||||||
|
const pageResult = filterSortPageOpsOrganizations(rows, state)
|
||||||
|
|
||||||
|
if (rows.length === 0) {
|
||||||
|
return (
|
||||||
|
<OpsListLocalShell title="Organizações" description="Espelho offline de organizações.">
|
||||||
|
<OpsListLocalNotice>{OPS_LIST_MIRROR_EMPTY_MESSAGE}</OpsListLocalNotice>
|
||||||
|
</OpsListLocalShell>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const columns: Array<CampaignTableColumn<OpsOrganization>> = [
|
||||||
|
{
|
||||||
|
id: 'name',
|
||||||
|
label: 'Nome',
|
||||||
|
mandatory: true,
|
||||||
|
head: <CampaignTableHead>Nome</CampaignTableHead>,
|
||||||
|
cell: (row) => (
|
||||||
|
<Link
|
||||||
|
href={`/campanha/organizacoes/${row.slug}`}
|
||||||
|
className="inline-flex min-h-11 items-center font-medium text-primary underline-offset-4 hover:underline"
|
||||||
|
>
|
||||||
|
{row.name}
|
||||||
|
</Link>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'kind',
|
||||||
|
label: 'Tipo',
|
||||||
|
head: <CampaignTableHead>Tipo</CampaignTableHead>,
|
||||||
|
cell: (row) => organizationKindLabels[row.kind],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
return (
|
||||||
|
<OpsListLocalShell title="Organizações" description="Lista offline a partir do espelho.">
|
||||||
|
<OpsListView
|
||||||
|
overview={null}
|
||||||
|
toolbar={
|
||||||
|
<OpsListLocalNotice>Filtros completos: {OPS_LIST_ONLINE_ONLY_MESSAGE}</OpsListLocalNotice>
|
||||||
|
}
|
||||||
|
table={
|
||||||
|
<CampaignTable
|
||||||
|
columns={columns}
|
||||||
|
rows={pageResult.rows}
|
||||||
|
rowKey={(row) => row.id}
|
||||||
|
caption="Organizações (offline)"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
empty={null}
|
||||||
|
footer={
|
||||||
|
<CampaignListFooter
|
||||||
|
totalDocs={pageResult.totalDocs}
|
||||||
|
singular="organização encontrada"
|
||||||
|
plural="organizações encontradas"
|
||||||
|
page={pageResult.page}
|
||||||
|
totalPages={pageResult.totalPages}
|
||||||
|
hrefForPage={(page) => buildOrganizationListHref(state, page)}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</OpsListLocalShell>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const OpsDemandListLocal = () => {
|
||||||
|
const searchParams = useSearchParams()
|
||||||
|
const rows = useMirrorCollection(demandsCollection)
|
||||||
|
const state = parseDemandListParams(searchParamsToRecord(searchParams))
|
||||||
|
const pageResult = filterSortPageOpsDemands(rows, state)
|
||||||
|
|
||||||
|
if (rows.length === 0) {
|
||||||
|
return (
|
||||||
|
<OpsListLocalShell title="Demandas" description="Espelho offline de demandas.">
|
||||||
|
<OpsListLocalNotice>{OPS_LIST_MIRROR_EMPTY_MESSAGE}</OpsListLocalNotice>
|
||||||
|
</OpsListLocalShell>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const columns: Array<CampaignTableColumn<OpsDemand>> = [
|
||||||
|
{
|
||||||
|
id: 'title',
|
||||||
|
label: 'Título',
|
||||||
|
mandatory: true,
|
||||||
|
head: <CampaignTableHead>Título</CampaignTableHead>,
|
||||||
|
cell: (row) => (
|
||||||
|
<Link
|
||||||
|
href={`/campanha/demandas/${row.slug}`}
|
||||||
|
className="inline-flex min-h-11 items-center font-medium text-primary underline-offset-4 hover:underline"
|
||||||
|
>
|
||||||
|
{row.title}
|
||||||
|
</Link>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'kind',
|
||||||
|
label: 'Tipo',
|
||||||
|
head: <CampaignTableHead>Tipo</CampaignTableHead>,
|
||||||
|
cell: (row) => campaignDemandKindLabels[row.kind],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'status',
|
||||||
|
label: 'Status',
|
||||||
|
head: <CampaignTableHead>Status</CampaignTableHead>,
|
||||||
|
cell: (row) => campaignDemandStatusLabels[row.status],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
return (
|
||||||
|
<OpsListLocalShell title="Demandas" description="Lista offline a partir do espelho.">
|
||||||
|
<OpsListView
|
||||||
|
overview={
|
||||||
|
<div className="rounded-xl border px-4 py-3">
|
||||||
|
<OpsListLocalNotice>{OPS_LIST_KPI_UNAVAILABLE_MESSAGE}</OpsListLocalNotice>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
toolbar={
|
||||||
|
<OpsListLocalNotice>Filtros completos: {OPS_LIST_ONLINE_ONLY_MESSAGE}</OpsListLocalNotice>
|
||||||
|
}
|
||||||
|
table={
|
||||||
|
<CampaignTable
|
||||||
|
columns={columns}
|
||||||
|
rows={pageResult.rows}
|
||||||
|
rowKey={(row) => row.id}
|
||||||
|
caption="Demandas (offline)"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
empty={null}
|
||||||
|
footer={
|
||||||
|
<CampaignListFooter
|
||||||
|
totalDocs={pageResult.totalDocs}
|
||||||
|
singular="demanda encontrada"
|
||||||
|
plural="demandas encontradas"
|
||||||
|
page={pageResult.page}
|
||||||
|
totalPages={pageResult.totalPages}
|
||||||
|
hrefForPage={(page) => buildDemandListHref(state, page)}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</OpsListLocalShell>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const DOMAIN_TITLES: Record<OpsListDomainId, string> = {
|
||||||
|
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 }) => {
|
||||||
|
const meta = getOpsListDomain(slug)
|
||||||
|
if (!meta) {
|
||||||
|
return <OpsListDomainUnavailable title={slug} />
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (slug) {
|
||||||
|
case 'municipios':
|
||||||
|
return <OpsMunicipalityListLocal />
|
||||||
|
case 'liderancas':
|
||||||
|
return <OpsLeadershipListLocal />
|
||||||
|
case 'dobradinhas':
|
||||||
|
return <OpsStateDeputyListLocal />
|
||||||
|
case 'organizacoes':
|
||||||
|
return <OpsOrganizationListLocal />
|
||||||
|
case 'demandas':
|
||||||
|
return <OpsDemandListLocal />
|
||||||
|
case 'assessores':
|
||||||
|
case 'territorios':
|
||||||
|
case 'apoiadores':
|
||||||
|
return <OpsListDomainUnavailable title={DOMAIN_TITLES[slug]} />
|
||||||
|
default: {
|
||||||
|
const _exhaustive: never = slug
|
||||||
|
return _exhaustive
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
21
src/components/campaign/opsSync/opsListLocalCopy.ts
Normal file
21
src/components/campaign/opsSync/opsListLocalCopy.ts
Normal file
|
|
@ -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.'
|
||||||
|
|
@ -41,9 +41,9 @@ export const municipalitiesCollection = createRowCollection<OpsMunicipality>('op
|
||||||
export const leadershipsCollection = createRowCollection<OpsLeadership>('ops-leaderships')
|
export const leadershipsCollection = createRowCollection<OpsLeadership>('ops-leaderships')
|
||||||
export { votePledgesCollection }
|
export { votePledgesCollection }
|
||||||
const activitiesCollection = createRowCollection<OpsActivity>('ops-activities')
|
const activitiesCollection = createRowCollection<OpsActivity>('ops-activities')
|
||||||
const stateDeputiesCollection = createRowCollection<OpsStateDeputy>('ops-state-deputies')
|
export const stateDeputiesCollection = createRowCollection<OpsStateDeputy>('ops-state-deputies')
|
||||||
const organizationsCollection = createRowCollection<OpsOrganization>('ops-organizations')
|
export const organizationsCollection = createRowCollection<OpsOrganization>('ops-organizations')
|
||||||
const demandsCollection = createRowCollection<OpsDemand>('ops-demands')
|
export const demandsCollection = createRowCollection<OpsDemand>('ops-demands')
|
||||||
const municipalityUpdatesCollection = createRowCollection<OpsMunicipalityUpdate>(
|
const municipalityUpdatesCollection = createRowCollection<OpsMunicipalityUpdate>(
|
||||||
'ops-municipality-updates',
|
'ops-municipality-updates',
|
||||||
)
|
)
|
||||||
|
|
|
||||||
24
src/components/campaign/opsSync/useBrowserOffline.ts
Normal file
24
src/components/campaign/opsSync/useBrowserOffline.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
|
||||||
|
/** Browser online/offline only — matches OfflineBoundary Local trigger. */
|
||||||
|
export const useBrowserOffline = (): boolean => {
|
||||||
|
const [offline, setOffline] = useState(() =>
|
||||||
|
typeof navigator !== 'undefined' ? !navigator.onLine : false,
|
||||||
|
)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const onOnline = () => setOffline(false)
|
||||||
|
const onOffline = () => setOffline(true)
|
||||||
|
setOffline(!navigator.onLine)
|
||||||
|
window.addEventListener('online', onOnline)
|
||||||
|
window.addEventListener('offline', onOffline)
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('online', onOnline)
|
||||||
|
window.removeEventListener('offline', onOffline)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
return offline
|
||||||
|
}
|
||||||
|
|
@ -6,6 +6,7 @@ import { usePathname, useSearchParams } from 'next/navigation'
|
||||||
import { useEffect, useId, useRef, useState } from 'react'
|
import { useEffect, useId, useRef, useState } from 'react'
|
||||||
import { toast } from 'sonner'
|
import { toast } from 'sonner'
|
||||||
|
|
||||||
|
import { useBrowserOffline } from '@/components/campaign/opsSync/useBrowserOffline'
|
||||||
import { useMunicipalitySavedFilters } from '@/components/campaign/shared/useMunicipalitySavedFilters'
|
import { useMunicipalitySavedFilters } from '@/components/campaign/shared/useMunicipalitySavedFilters'
|
||||||
import {
|
import {
|
||||||
SidebarMenuAction,
|
SidebarMenuAction,
|
||||||
|
|
@ -33,6 +34,7 @@ const IGNORED_PARAMS = ['page']
|
||||||
*/
|
*/
|
||||||
export const MunicipalityNavSavedFilters = ({ onNavigate }: { onNavigate: () => void }) => {
|
export const MunicipalityNavSavedFilters = ({ onNavigate }: { onNavigate: () => void }) => {
|
||||||
const savedFilters = useMunicipalitySavedFilters()
|
const savedFilters = useMunicipalitySavedFilters()
|
||||||
|
const browserOffline = useBrowserOffline()
|
||||||
const pathname = usePathname()
|
const pathname = usePathname()
|
||||||
const searchParams = useSearchParams()
|
const searchParams = useSearchParams()
|
||||||
// Read once, not tracked: the store owns the list, this is only the
|
// Read once, not tracked: the store owns the list, this is only the
|
||||||
|
|
@ -136,8 +138,19 @@ export const MunicipalityNavSavedFilters = ({ onNavigate }: { onNavigate: () =>
|
||||||
</SidebarMenuSubButton>
|
</SidebarMenuSubButton>
|
||||||
<SidebarMenuAction
|
<SidebarMenuAction
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => handleRemove(entry)}
|
onClick={() => {
|
||||||
aria-label={`Apagar o filtro salvo ${entry.name}`}
|
if (browserOffline) return
|
||||||
|
handleRemove(entry)
|
||||||
|
}}
|
||||||
|
disabled={browserOffline}
|
||||||
|
title={
|
||||||
|
browserOffline ? 'Apagar filtro disponível quando estiveres online.' : undefined
|
||||||
|
}
|
||||||
|
aria-label={
|
||||||
|
browserOffline
|
||||||
|
? `Apagar o filtro salvo ${entry.name} — disponível quando estiveres online.`
|
||||||
|
: `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"
|
className="top-1 group-focus-within/menu-sub-item:opacity-100 group-hover/menu-sub-item:opacity-100 md:opacity-0"
|
||||||
>
|
>
|
||||||
<Trash2Icon aria-hidden="true" />
|
<Trash2Icon aria-hidden="true" />
|
||||||
|
|
|
||||||
|
|
@ -4,23 +4,21 @@ import type { Payload } from 'payload'
|
||||||
|
|
||||||
import { isPopulatedRelationship, relationshipId } from '@/lib/relationship'
|
import { isPopulatedRelationship, relationshipId } from '@/lib/relationship'
|
||||||
import type { CampaignDemandKind, CampaignDemandStatus } from '@/lib/schemas/campaignDemand'
|
import type { CampaignDemandKind, CampaignDemandStatus } from '@/lib/schemas/campaignDemand'
|
||||||
import { campaignDemandKinds, campaignDemandStatuses } from '@/lib/schemas/campaignDemand'
|
|
||||||
import type { Activity, CampaignDemand, CampaignUser } from '@/payload-types'
|
import type { Activity, CampaignDemand, CampaignUser } from '@/payload-types'
|
||||||
import { isCampaignStaff } from '@/utilities/campaignAccess'
|
import { isCampaignStaff } from '@/utilities/campaignAccess'
|
||||||
import {
|
import { demandPageSize, type DemandListState } from '@/utilities/demand/demandListUrl'
|
||||||
buildListHref,
|
|
||||||
firstValue,
|
|
||||||
resolveListUrl,
|
|
||||||
strictDecimalInteger,
|
|
||||||
type RawSearchParams,
|
|
||||||
} from '@/utilities/campaignListUrl'
|
|
||||||
import {
|
import {
|
||||||
loadCampaignUserNamesByIds,
|
loadCampaignUserNamesByIds,
|
||||||
loadLeadershipContactNamesByIds,
|
loadLeadershipContactNamesByIds,
|
||||||
loadMunicipalityLabelsByIds,
|
loadMunicipalityLabelsByIds,
|
||||||
} from '@/utilities/loadNamesByIds'
|
} from '@/utilities/loadNamesByIds'
|
||||||
|
|
||||||
const demandPageSize = 25
|
export {
|
||||||
|
buildDemandListHref,
|
||||||
|
parseDemandListParams,
|
||||||
|
resolveDemandListUrl,
|
||||||
|
} from '@/utilities/demand/demandListUrl'
|
||||||
|
export type { DemandListSearchParams, DemandListState } from '@/utilities/demand/demandListUrl'
|
||||||
|
|
||||||
export type DemandRowViewModel = {
|
export type DemandRowViewModel = {
|
||||||
id: number
|
id: number
|
||||||
|
|
@ -35,81 +33,6 @@ export type DemandRowViewModel = {
|
||||||
createdAt: string
|
createdAt: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export type DemandListState = {
|
|
||||||
page: number
|
|
||||||
status?: CampaignDemandStatus
|
|
||||||
kind?: CampaignDemandKind
|
|
||||||
activityId?: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export type DemandListSearchParams = RawSearchParams
|
|
||||||
|
|
||||||
const demandListParamNames = ['status', 'kind', 'activity', 'page'] as const
|
|
||||||
const demandListParamNameSet = new Set<string>(demandListParamNames)
|
|
||||||
|
|
||||||
export const parseDemandListParams = (searchParams: RawSearchParams): DemandListState => {
|
|
||||||
const rawStatus = firstValue(searchParams.status)
|
|
||||||
const rawKind = firstValue(searchParams.kind)
|
|
||||||
const activityId = strictDecimalInteger(firstValue(searchParams.activity))
|
|
||||||
|
|
||||||
return {
|
|
||||||
page: strictDecimalInteger(firstValue(searchParams.page)) ?? 1,
|
|
||||||
...(campaignDemandStatuses.includes(rawStatus as CampaignDemandStatus)
|
|
||||||
? { status: rawStatus as CampaignDemandStatus }
|
|
||||||
: {}),
|
|
||||||
...(campaignDemandKinds.includes(rawKind as CampaignDemandKind)
|
|
||||||
? { kind: rawKind as CampaignDemandKind }
|
|
||||||
: {}),
|
|
||||||
...(activityId ? { activityId } : {}),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const demandListStateToRawParams = (
|
|
||||||
state: DemandListState,
|
|
||||||
page = state.page,
|
|
||||||
): DemandListSearchParams => ({
|
|
||||||
page: String(page),
|
|
||||||
status: state.status,
|
|
||||||
kind: state.kind,
|
|
||||||
activity: state.activityId ? String(state.activityId) : undefined,
|
|
||||||
})
|
|
||||||
|
|
||||||
const serializeCanonicalDemandListSearchParams = (
|
|
||||||
canonicalState: DemandListState,
|
|
||||||
): URLSearchParams => {
|
|
||||||
const params = new URLSearchParams()
|
|
||||||
if (canonicalState.status) params.set('status', canonicalState.status)
|
|
||||||
if (canonicalState.kind) params.set('kind', canonicalState.kind)
|
|
||||||
if (canonicalState.activityId) params.set('activity', String(canonicalState.activityId))
|
|
||||||
if (canonicalState.page > 1) params.set('page', String(canonicalState.page))
|
|
||||||
return params
|
|
||||||
}
|
|
||||||
|
|
||||||
const buildDemandListSearchParams = (state: DemandListState, page = state.page): URLSearchParams =>
|
|
||||||
serializeCanonicalDemandListSearchParams(
|
|
||||||
parseDemandListParams(demandListStateToRawParams(state, page)),
|
|
||||||
)
|
|
||||||
|
|
||||||
export const buildDemandListHref = (state: DemandListState, page: number): string =>
|
|
||||||
buildListHref(state, buildDemandListSearchParams, '/campanha/demandas', page)
|
|
||||||
|
|
||||||
export const resolveDemandListUrl = (
|
|
||||||
params: DemandListSearchParams,
|
|
||||||
totalPages?: number,
|
|
||||||
): {
|
|
||||||
state: DemandListState
|
|
||||||
href: string
|
|
||||||
redirectHref?: string
|
|
||||||
} =>
|
|
||||||
resolveListUrl({
|
|
||||||
params,
|
|
||||||
paramNameSet: demandListParamNameSet,
|
|
||||||
parse: parseDemandListParams,
|
|
||||||
buildSearchParams: buildDemandListSearchParams,
|
|
||||||
basePath: '/campanha/demandas',
|
|
||||||
totalPages,
|
|
||||||
})
|
|
||||||
|
|
||||||
const resolveMunicipalityAndRequesterNames = async (
|
const resolveMunicipalityAndRequesterNames = async (
|
||||||
payload: Payload,
|
payload: Payload,
|
||||||
demands: CampaignDemand[],
|
demands: CampaignDemand[],
|
||||||
|
|
|
||||||
153
src/utilities/campaignOps/opsEntityListLocal.ts
Normal file
153
src/utilities/campaignOps/opsEntityListLocal.ts
Normal file
|
|
@ -0,0 +1,153 @@
|
||||||
|
/**
|
||||||
|
* OH12 — pure filter / sort / page helpers for mirror-backed ops lists
|
||||||
|
* (leadership, state deputy, organization, demand).
|
||||||
|
*/
|
||||||
|
import type {
|
||||||
|
OpsDemand,
|
||||||
|
OpsLeadership,
|
||||||
|
OpsOrganization,
|
||||||
|
OpsStateDeputy,
|
||||||
|
} from '@/lib/campaignOps/opsContract'
|
||||||
|
import { demandPageSize, type DemandListState } from '@/utilities/demand/demandListUrl'
|
||||||
|
import {
|
||||||
|
leadershipPageSize,
|
||||||
|
resolveLeadershipListSort,
|
||||||
|
type LeadershipListState,
|
||||||
|
} from '@/utilities/leadership/leadershipListUrl'
|
||||||
|
import {
|
||||||
|
organizationPageSize,
|
||||||
|
type OrganizationListState,
|
||||||
|
} from '@/utilities/organization/organizationListUrl'
|
||||||
|
import {
|
||||||
|
NO_PARTY_FILTER_VALUE,
|
||||||
|
resolveStateDeputyListSort,
|
||||||
|
stateDeputyPageSize,
|
||||||
|
type StateDeputyListState,
|
||||||
|
} from '@/utilities/stateDeputyListUrl'
|
||||||
|
|
||||||
|
export type OpsPagedResult<T> = {
|
||||||
|
rows: T[]
|
||||||
|
totalDocs: number
|
||||||
|
totalPages: number
|
||||||
|
page: number
|
||||||
|
}
|
||||||
|
|
||||||
|
const paginate = <T>(rows: T[], page: number, pageSize: number): OpsPagedResult<T> => {
|
||||||
|
const totalDocs = rows.length
|
||||||
|
const totalPages = Math.max(1, Math.ceil(totalDocs / pageSize))
|
||||||
|
const safePage = Math.min(Math.max(1, page), totalPages)
|
||||||
|
const start = (safePage - 1) * pageSize
|
||||||
|
return {
|
||||||
|
rows: rows.slice(start, start + pageSize),
|
||||||
|
totalDocs,
|
||||||
|
totalPages,
|
||||||
|
page: safePage,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const filterSortPageOpsLeaderships = (
|
||||||
|
rows: ReadonlyArray<OpsLeadership>,
|
||||||
|
state: LeadershipListState,
|
||||||
|
): OpsPagedResult<OpsLeadership> => {
|
||||||
|
let filtered = [...rows]
|
||||||
|
if (state.q) {
|
||||||
|
const needle = state.q.toLocaleLowerCase('pt-BR')
|
||||||
|
filtered = filtered.filter((row) =>
|
||||||
|
row.contact.name.toLocaleLowerCase('pt-BR').includes(needle),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (state.statuses?.length) {
|
||||||
|
filtered = filtered.filter((row) => state.statuses!.includes(row.supportStatus))
|
||||||
|
}
|
||||||
|
if (state.municipalities?.length) {
|
||||||
|
filtered = filtered.filter((row) =>
|
||||||
|
state.municipalities!.some((id) => row.municipalities.includes(id)),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
// `access` (com/sem app) needs campaignUser join — not in mirror; ignore offline.
|
||||||
|
|
||||||
|
const { sort, dir } = resolveLeadershipListSort(state)
|
||||||
|
const factor = dir === 'asc' ? 1 : -1
|
||||||
|
filtered.sort((left, right) => {
|
||||||
|
let cmp = 0
|
||||||
|
if (sort === 'name') {
|
||||||
|
cmp = left.contact.name.localeCompare(right.contact.name, 'pt-BR')
|
||||||
|
} else if (sort === 'supportStatus') {
|
||||||
|
cmp = left.supportStatus.localeCompare(right.supportStatus, 'pt-BR')
|
||||||
|
} else {
|
||||||
|
cmp = left.updatedAt.localeCompare(right.updatedAt)
|
||||||
|
}
|
||||||
|
if (cmp !== 0) return cmp * factor
|
||||||
|
return left.contact.name.localeCompare(right.contact.name, 'pt-BR')
|
||||||
|
})
|
||||||
|
|
||||||
|
return paginate(filtered, state.page, leadershipPageSize)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const filterSortPageOpsStateDeputies = (
|
||||||
|
rows: ReadonlyArray<OpsStateDeputy>,
|
||||||
|
state: StateDeputyListState,
|
||||||
|
): OpsPagedResult<OpsStateDeputy> => {
|
||||||
|
let filtered = [...rows]
|
||||||
|
if (state.q) {
|
||||||
|
const needle = state.q.toLocaleLowerCase('pt-BR')
|
||||||
|
filtered = filtered.filter((row) => row.name.toLocaleLowerCase('pt-BR').includes(needle))
|
||||||
|
}
|
||||||
|
if (state.parties?.length) {
|
||||||
|
filtered = filtered.filter((row) => {
|
||||||
|
const party = row.party?.trim() ? row.party : null
|
||||||
|
return state.parties!.some((value) =>
|
||||||
|
value === NO_PARTY_FILTER_VALUE ? party === null : party === value,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const { sort, dir } = resolveStateDeputyListSort(state)
|
||||||
|
const factor = dir === 'asc' ? 1 : -1
|
||||||
|
filtered.sort((left, right) => {
|
||||||
|
let cmp = 0
|
||||||
|
if (sort === 'party') {
|
||||||
|
cmp = (left.party ?? '').localeCompare(right.party ?? '', 'pt-BR')
|
||||||
|
} else {
|
||||||
|
cmp = left.name.localeCompare(right.name, 'pt-BR')
|
||||||
|
}
|
||||||
|
if (cmp !== 0) return cmp * factor
|
||||||
|
return left.name.localeCompare(right.name, 'pt-BR')
|
||||||
|
})
|
||||||
|
|
||||||
|
return paginate(filtered, state.page, stateDeputyPageSize)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const filterSortPageOpsOrganizations = (
|
||||||
|
rows: ReadonlyArray<OpsOrganization>,
|
||||||
|
state: OrganizationListState,
|
||||||
|
): OpsPagedResult<OpsOrganization> => {
|
||||||
|
let filtered = [...rows]
|
||||||
|
if (state.q) {
|
||||||
|
const needle = state.q.toLocaleLowerCase('pt-BR')
|
||||||
|
filtered = filtered.filter((row) => row.name.toLocaleLowerCase('pt-BR').includes(needle))
|
||||||
|
}
|
||||||
|
if (state.kind) {
|
||||||
|
filtered = filtered.filter((row) => row.kind === state.kind)
|
||||||
|
}
|
||||||
|
filtered.sort((left, right) => left.name.localeCompare(right.name, 'pt-BR'))
|
||||||
|
return paginate(filtered, state.page, organizationPageSize)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const filterSortPageOpsDemands = (
|
||||||
|
rows: ReadonlyArray<OpsDemand>,
|
||||||
|
state: DemandListState,
|
||||||
|
): OpsPagedResult<OpsDemand> => {
|
||||||
|
let filtered = [...rows]
|
||||||
|
if (state.status) {
|
||||||
|
filtered = filtered.filter((row) => row.status === state.status)
|
||||||
|
}
|
||||||
|
if (state.kind) {
|
||||||
|
filtered = filtered.filter((row) => row.kind === state.kind)
|
||||||
|
}
|
||||||
|
if (state.activityId) {
|
||||||
|
filtered = filtered.filter((row) => row.activity === state.activityId)
|
||||||
|
}
|
||||||
|
filtered.sort((left, right) => right.updatedAt.localeCompare(left.updatedAt))
|
||||||
|
return paginate(filtered, state.page, demandPageSize)
|
||||||
|
}
|
||||||
187
src/utilities/campaignOps/opsMunicipalityListLocal.ts
Normal file
187
src/utilities/campaignOps/opsMunicipalityListLocal.ts
Normal file
|
|
@ -0,0 +1,187 @@
|
||||||
|
/**
|
||||||
|
* OH12 — pure filter / sort / page over OpsMunicipality rows for the offline
|
||||||
|
* municipios list. Uses the same MunicipalityListState parsers produce; does
|
||||||
|
* not invent server-only aggregates (classe / déficit / votos 2022).
|
||||||
|
*/
|
||||||
|
import type { OpsMunicipality } from '@/lib/campaignOps/opsContract'
|
||||||
|
import { engagementLevelRank, type EngagementLevel } from '@/lib/engagementLevel'
|
||||||
|
import {
|
||||||
|
DEFAULT_VOTE_ESTIMATE_SCENARIO,
|
||||||
|
getVoteEstimateForScenario,
|
||||||
|
type VoteEstimateScenario,
|
||||||
|
} from '@/lib/voteEstimate'
|
||||||
|
import { strictDecimalInteger } from '@/utilities/campaignListUrl'
|
||||||
|
import {
|
||||||
|
municipalityPageSize,
|
||||||
|
NO_LEVEL_FILTER_VALUE,
|
||||||
|
resolveMunicipalityListSort,
|
||||||
|
type MunicipalityListSortKey,
|
||||||
|
type MunicipalityListState,
|
||||||
|
} from '@/utilities/municipality/municipalityListUrl'
|
||||||
|
|
||||||
|
const TREND_SORT_RANK: Record<string, number> = {
|
||||||
|
favoravel: 2,
|
||||||
|
neutra: 1,
|
||||||
|
desfavoravel: 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Sort keys that need TSE / goal-coverage data absent from the mirror. */
|
||||||
|
export const OPS_MUNICIPALITY_OFFLINE_UNAVAILABLE_SORTS = new Set<MunicipalityListSortKey>([
|
||||||
|
'votos',
|
||||||
|
'deficit',
|
||||||
|
'frescor',
|
||||||
|
'classe',
|
||||||
|
])
|
||||||
|
|
||||||
|
export type OpsMunicipalityListLocalResult = {
|
||||||
|
rows: OpsMunicipality[]
|
||||||
|
totalDocs: number
|
||||||
|
totalPages: number
|
||||||
|
page: number
|
||||||
|
/** True when URL asks for classe filter — not applied offline. */
|
||||||
|
classFilterUnavailable: boolean
|
||||||
|
/** True when active sort falls back to name because it needs server data. */
|
||||||
|
sortDegraded: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
const matchesQuery = (row: OpsMunicipality, q: string): boolean => {
|
||||||
|
const needle = q.toLocaleLowerCase('pt-BR')
|
||||||
|
if (row.name.toLocaleLowerCase('pt-BR').includes(needle)) return true
|
||||||
|
if (row.city.toLocaleLowerCase('pt-BR').includes(needle)) return true
|
||||||
|
const zone = strictDecimalInteger(q)
|
||||||
|
if (zone !== undefined && zone <= 999 && row.zoneNumber === zone) return true
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
const matchesMunicipalityFilters = (
|
||||||
|
row: OpsMunicipality,
|
||||||
|
state: MunicipalityListState,
|
||||||
|
): boolean => {
|
||||||
|
if (state.q && !matchesQuery(row, state.q)) return false
|
||||||
|
if (
|
||||||
|
state.regions?.length &&
|
||||||
|
!state.regions.includes(row.region as (typeof state.regions)[number])
|
||||||
|
) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if (state.slugs?.length && !state.slugs.includes(row.slug)) return false
|
||||||
|
if (state.advisors?.length) {
|
||||||
|
const advisors = row.advisors ?? []
|
||||||
|
if (!state.advisors.some((id) => advisors.includes(id))) return false
|
||||||
|
}
|
||||||
|
if (state.coverage === 'com_assessor' && !(row.advisors && row.advisors.length > 0)) return false
|
||||||
|
if (state.coverage === 'sem_assessor' && row.advisors && row.advisors.length > 0) return false
|
||||||
|
if (state.priority === 'alta' && row.priority !== 'alta') return false
|
||||||
|
if (state.trends?.length) {
|
||||||
|
const trend = row.politicalTrend?.status ?? null
|
||||||
|
if (!trend || !state.trends.includes(trend)) return false
|
||||||
|
}
|
||||||
|
if (state.levels?.length) {
|
||||||
|
const level = row.engagementLevel ?? null
|
||||||
|
const hit = state.levels.some((value) =>
|
||||||
|
value === NO_LEVEL_FILTER_VALUE ? level === null : level === value,
|
||||||
|
)
|
||||||
|
if (!hit) return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
const compareNullableString = (left: string | null | undefined, right: string | null | undefined) =>
|
||||||
|
(left ?? '').localeCompare(right ?? '', 'pt-BR')
|
||||||
|
|
||||||
|
const sortMunicipalityRows = (
|
||||||
|
rows: OpsMunicipality[],
|
||||||
|
sort: MunicipalityListSortKey,
|
||||||
|
dir: 'asc' | 'desc',
|
||||||
|
scenario: VoteEstimateScenario,
|
||||||
|
): OpsMunicipality[] => {
|
||||||
|
const factor = dir === 'asc' ? 1 : -1
|
||||||
|
return [...rows].sort((left, right) => {
|
||||||
|
let cmp = 0
|
||||||
|
switch (sort) {
|
||||||
|
case 'name':
|
||||||
|
cmp = left.name.localeCompare(right.name, 'pt-BR')
|
||||||
|
break
|
||||||
|
case 'region':
|
||||||
|
cmp =
|
||||||
|
left.region.localeCompare(right.region, 'pt-BR') ||
|
||||||
|
left.name.localeCompare(right.name, 'pt-BR')
|
||||||
|
break
|
||||||
|
case 'trend': {
|
||||||
|
const leftRank = left.politicalTrend?.status
|
||||||
|
? (TREND_SORT_RANK[left.politicalTrend.status] ?? -1)
|
||||||
|
: -1
|
||||||
|
const rightRank = right.politicalTrend?.status
|
||||||
|
? (TREND_SORT_RANK[right.politicalTrend.status] ?? -1)
|
||||||
|
: -1
|
||||||
|
cmp = leftRank - rightRank
|
||||||
|
break
|
||||||
|
}
|
||||||
|
case 'expectedVotes': {
|
||||||
|
const leftVotes = getVoteEstimateForScenario(left.expectedVotes, scenario) ?? -1
|
||||||
|
const rightVotes = getVoteEstimateForScenario(right.expectedVotes, scenario) ?? -1
|
||||||
|
cmp = leftVotes - rightVotes
|
||||||
|
break
|
||||||
|
}
|
||||||
|
case 'lastUpdateAt':
|
||||||
|
cmp = compareNullableString(left.lastUpdateAt, right.lastUpdateAt)
|
||||||
|
break
|
||||||
|
case 'coverage':
|
||||||
|
cmp = (left.advisors?.length ?? 0) - (right.advisors?.length ?? 0)
|
||||||
|
break
|
||||||
|
case 'nivel': {
|
||||||
|
const leftLevel = left.engagementLevel as EngagementLevel | null | undefined
|
||||||
|
const rightLevel = right.engagementLevel as EngagementLevel | null | undefined
|
||||||
|
const leftRank = leftLevel ? engagementLevelRank[leftLevel] : -1
|
||||||
|
const rightRank = rightLevel ? engagementLevelRank[rightLevel] : -1
|
||||||
|
cmp = leftRank - rightRank
|
||||||
|
break
|
||||||
|
}
|
||||||
|
case 'votos':
|
||||||
|
case 'deficit':
|
||||||
|
case 'frescor':
|
||||||
|
case 'classe':
|
||||||
|
cmp = left.name.localeCompare(right.name, 'pt-BR')
|
||||||
|
break
|
||||||
|
default: {
|
||||||
|
const _exhaustive: never = sort
|
||||||
|
void _exhaustive
|
||||||
|
cmp = left.name.localeCompare(right.name, 'pt-BR')
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (cmp !== 0) return cmp * factor
|
||||||
|
return left.name.localeCompare(right.name, 'pt-BR')
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export const filterSortPageOpsMunicipalities = (
|
||||||
|
rows: ReadonlyArray<OpsMunicipality>,
|
||||||
|
state: MunicipalityListState,
|
||||||
|
options: { scenario?: VoteEstimateScenario } = {},
|
||||||
|
): OpsMunicipalityListLocalResult => {
|
||||||
|
const classFilterUnavailable = Boolean(state.classes?.length)
|
||||||
|
const filtered = rows.filter((row) => matchesMunicipalityFilters(row, state))
|
||||||
|
const resolved = resolveMunicipalityListSort(state)
|
||||||
|
const sortDegraded = OPS_MUNICIPALITY_OFFLINE_UNAVAILABLE_SORTS.has(resolved.sort)
|
||||||
|
const effectiveSort: MunicipalityListSortKey = sortDegraded ? 'name' : resolved.sort
|
||||||
|
const effectiveDir = sortDegraded ? 'asc' : resolved.dir
|
||||||
|
const sorted = sortMunicipalityRows(
|
||||||
|
filtered,
|
||||||
|
effectiveSort,
|
||||||
|
effectiveDir,
|
||||||
|
options.scenario ?? DEFAULT_VOTE_ESTIMATE_SCENARIO,
|
||||||
|
)
|
||||||
|
const totalDocs = sorted.length
|
||||||
|
const totalPages = Math.max(1, Math.ceil(totalDocs / municipalityPageSize))
|
||||||
|
const page = Math.min(Math.max(1, state.page), totalPages)
|
||||||
|
const start = (page - 1) * municipalityPageSize
|
||||||
|
return {
|
||||||
|
rows: sorted.slice(start, start + municipalityPageSize),
|
||||||
|
totalDocs,
|
||||||
|
totalPages,
|
||||||
|
page,
|
||||||
|
classFilterUnavailable,
|
||||||
|
sortDegraded,
|
||||||
|
}
|
||||||
|
}
|
||||||
90
src/utilities/demand/demandListUrl.ts
Normal file
90
src/utilities/demand/demandListUrl.ts
Normal file
|
|
@ -0,0 +1,90 @@
|
||||||
|
/**
|
||||||
|
* Campaign demand list URL contract — client-safe (OH12). Loaders stay in
|
||||||
|
* `campaignDemandData.ts` (`server-only`).
|
||||||
|
*/
|
||||||
|
import type { CampaignDemandKind, CampaignDemandStatus } from '@/lib/schemas/campaignDemand'
|
||||||
|
import { campaignDemandKinds, campaignDemandStatuses } from '@/lib/schemas/campaignDemand'
|
||||||
|
import {
|
||||||
|
buildListHref,
|
||||||
|
firstValue,
|
||||||
|
resolveListUrl,
|
||||||
|
strictDecimalInteger,
|
||||||
|
type RawSearchParams,
|
||||||
|
} from '@/utilities/campaignListUrl'
|
||||||
|
|
||||||
|
export const demandPageSize = 25
|
||||||
|
|
||||||
|
export type DemandListState = {
|
||||||
|
page: number
|
||||||
|
status?: CampaignDemandStatus
|
||||||
|
kind?: CampaignDemandKind
|
||||||
|
activityId?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export type DemandListSearchParams = RawSearchParams
|
||||||
|
|
||||||
|
const demandListParamNames = ['status', 'kind', 'activity', 'page'] as const
|
||||||
|
const demandListParamNameSet = new Set<string>(demandListParamNames)
|
||||||
|
|
||||||
|
export const parseDemandListParams = (searchParams: RawSearchParams): DemandListState => {
|
||||||
|
const rawStatus = firstValue(searchParams.status)
|
||||||
|
const rawKind = firstValue(searchParams.kind)
|
||||||
|
const activityId = strictDecimalInteger(firstValue(searchParams.activity))
|
||||||
|
|
||||||
|
return {
|
||||||
|
page: strictDecimalInteger(firstValue(searchParams.page)) ?? 1,
|
||||||
|
...(campaignDemandStatuses.includes(rawStatus as CampaignDemandStatus)
|
||||||
|
? { status: rawStatus as CampaignDemandStatus }
|
||||||
|
: {}),
|
||||||
|
...(campaignDemandKinds.includes(rawKind as CampaignDemandKind)
|
||||||
|
? { kind: rawKind as CampaignDemandKind }
|
||||||
|
: {}),
|
||||||
|
...(activityId ? { activityId } : {}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const demandListStateToRawParams = (
|
||||||
|
state: DemandListState,
|
||||||
|
page = state.page,
|
||||||
|
): DemandListSearchParams => ({
|
||||||
|
page: String(page),
|
||||||
|
status: state.status,
|
||||||
|
kind: state.kind,
|
||||||
|
activity: state.activityId ? String(state.activityId) : undefined,
|
||||||
|
})
|
||||||
|
|
||||||
|
const serializeCanonicalDemandListSearchParams = (
|
||||||
|
canonicalState: DemandListState,
|
||||||
|
): URLSearchParams => {
|
||||||
|
const params = new URLSearchParams()
|
||||||
|
if (canonicalState.status) params.set('status', canonicalState.status)
|
||||||
|
if (canonicalState.kind) params.set('kind', canonicalState.kind)
|
||||||
|
if (canonicalState.activityId) params.set('activity', String(canonicalState.activityId))
|
||||||
|
if (canonicalState.page > 1) params.set('page', String(canonicalState.page))
|
||||||
|
return params
|
||||||
|
}
|
||||||
|
|
||||||
|
const buildDemandListSearchParams = (state: DemandListState, page = state.page): URLSearchParams =>
|
||||||
|
serializeCanonicalDemandListSearchParams(
|
||||||
|
parseDemandListParams(demandListStateToRawParams(state, page)),
|
||||||
|
)
|
||||||
|
|
||||||
|
export const buildDemandListHref = (state: DemandListState, page: number): string =>
|
||||||
|
buildListHref(state, buildDemandListSearchParams, '/campanha/demandas', page)
|
||||||
|
|
||||||
|
export const resolveDemandListUrl = (
|
||||||
|
params: DemandListSearchParams,
|
||||||
|
totalPages?: number,
|
||||||
|
): {
|
||||||
|
state: DemandListState
|
||||||
|
href: string
|
||||||
|
redirectHref?: string
|
||||||
|
} =>
|
||||||
|
resolveListUrl({
|
||||||
|
params,
|
||||||
|
paramNameSet: demandListParamNameSet,
|
||||||
|
parse: parseDemandListParams,
|
||||||
|
buildSearchParams: buildDemandListSearchParams,
|
||||||
|
basePath: '/campanha/demandas',
|
||||||
|
totalPages,
|
||||||
|
})
|
||||||
89
src/utilities/organization/organizationListUrl.ts
Normal file
89
src/utilities/organization/organizationListUrl.ts
Normal file
|
|
@ -0,0 +1,89 @@
|
||||||
|
/**
|
||||||
|
* Organization list URL contract — client-safe (OH12). Loaders stay in
|
||||||
|
* `organizationData.ts` (`server-only`).
|
||||||
|
*/
|
||||||
|
import type { OrganizationKind } from '@/lib/schemas/organization'
|
||||||
|
import { organizationKinds } from '@/lib/schemas/organization'
|
||||||
|
import {
|
||||||
|
buildListHref,
|
||||||
|
firstValue,
|
||||||
|
normalizedText,
|
||||||
|
resolveListUrl,
|
||||||
|
strictDecimalInteger,
|
||||||
|
type RawSearchParams,
|
||||||
|
} from '@/utilities/campaignListUrl'
|
||||||
|
|
||||||
|
export const organizationPageSize = 25
|
||||||
|
|
||||||
|
export type OrganizationListState = {
|
||||||
|
page: number
|
||||||
|
q?: string
|
||||||
|
kind?: OrganizationKind
|
||||||
|
}
|
||||||
|
|
||||||
|
export type OrganizationListSearchParams = RawSearchParams
|
||||||
|
|
||||||
|
const organizationListParamNames = ['q', 'kind', 'page'] as const
|
||||||
|
const organizationListParamNameSet = new Set<string>(organizationListParamNames)
|
||||||
|
|
||||||
|
export const parseOrganizationListParams = (
|
||||||
|
searchParams: RawSearchParams,
|
||||||
|
): OrganizationListState => {
|
||||||
|
const q = normalizedText(firstValue(searchParams.q))
|
||||||
|
const rawKind = firstValue(searchParams.kind)
|
||||||
|
|
||||||
|
return {
|
||||||
|
page: strictDecimalInteger(firstValue(searchParams.page)) ?? 1,
|
||||||
|
...(q ? { q } : {}),
|
||||||
|
...(organizationKinds.includes(rawKind as OrganizationKind)
|
||||||
|
? { kind: rawKind as OrganizationKind }
|
||||||
|
: {}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const organizationListStateToRawParams = (
|
||||||
|
state: OrganizationListState,
|
||||||
|
page = state.page,
|
||||||
|
): OrganizationListSearchParams => ({
|
||||||
|
page: String(page),
|
||||||
|
q: state.q,
|
||||||
|
kind: state.kind,
|
||||||
|
})
|
||||||
|
|
||||||
|
const serializeCanonicalOrganizationListSearchParams = (
|
||||||
|
canonicalState: OrganizationListState,
|
||||||
|
): URLSearchParams => {
|
||||||
|
const params = new URLSearchParams()
|
||||||
|
if (canonicalState.q) params.set('q', canonicalState.q)
|
||||||
|
if (canonicalState.kind) params.set('kind', canonicalState.kind)
|
||||||
|
if (canonicalState.page > 1) params.set('page', String(canonicalState.page))
|
||||||
|
return params
|
||||||
|
}
|
||||||
|
|
||||||
|
const buildOrganizationListSearchParams = (
|
||||||
|
state: OrganizationListState,
|
||||||
|
page = state.page,
|
||||||
|
): URLSearchParams =>
|
||||||
|
serializeCanonicalOrganizationListSearchParams(
|
||||||
|
parseOrganizationListParams(organizationListStateToRawParams(state, page)),
|
||||||
|
)
|
||||||
|
|
||||||
|
export const buildOrganizationListHref = (state: OrganizationListState, page: number): string =>
|
||||||
|
buildListHref(state, buildOrganizationListSearchParams, '/campanha/organizacoes', page)
|
||||||
|
|
||||||
|
export const resolveOrganizationListUrl = (
|
||||||
|
params: OrganizationListSearchParams,
|
||||||
|
totalPages?: number,
|
||||||
|
): {
|
||||||
|
state: OrganizationListState
|
||||||
|
href: string
|
||||||
|
redirectHref?: string
|
||||||
|
} =>
|
||||||
|
resolveListUrl({
|
||||||
|
params,
|
||||||
|
paramNameSet: organizationListParamNameSet,
|
||||||
|
parse: parseOrganizationListParams,
|
||||||
|
buildSearchParams: buildOrganizationListSearchParams,
|
||||||
|
basePath: '/campanha/organizacoes',
|
||||||
|
totalPages,
|
||||||
|
})
|
||||||
|
|
@ -4,20 +4,23 @@ import type { Payload } from 'payload'
|
||||||
|
|
||||||
import { relationshipId } from '@/lib/relationship'
|
import { relationshipId } from '@/lib/relationship'
|
||||||
import type { OrganizationKind } from '@/lib/schemas/organization'
|
import type { OrganizationKind } from '@/lib/schemas/organization'
|
||||||
import { organizationKinds } from '@/lib/schemas/organization'
|
|
||||||
import type { CampaignUser, Organization } from '@/payload-types'
|
import type { CampaignUser, Organization } from '@/payload-types'
|
||||||
import type { ActivityStatus } from '@/utilities/activityUi'
|
import type { ActivityStatus } from '@/utilities/activityUi'
|
||||||
import {
|
|
||||||
buildListHref,
|
|
||||||
firstValue,
|
|
||||||
normalizedText,
|
|
||||||
resolveListUrl,
|
|
||||||
strictDecimalInteger,
|
|
||||||
type RawSearchParams,
|
|
||||||
} from '@/utilities/campaignListUrl'
|
|
||||||
import { loadMunicipalityLabelsByIds } from '@/utilities/loadNamesByIds'
|
import { loadMunicipalityLabelsByIds } from '@/utilities/loadNamesByIds'
|
||||||
|
import {
|
||||||
|
organizationPageSize,
|
||||||
|
type OrganizationListState,
|
||||||
|
} from '@/utilities/organization/organizationListUrl'
|
||||||
|
|
||||||
const organizationPageSize = 25
|
export {
|
||||||
|
buildOrganizationListHref,
|
||||||
|
parseOrganizationListParams,
|
||||||
|
resolveOrganizationListUrl,
|
||||||
|
} from '@/utilities/organization/organizationListUrl'
|
||||||
|
export type {
|
||||||
|
OrganizationListSearchParams,
|
||||||
|
OrganizationListState,
|
||||||
|
} from '@/utilities/organization/organizationListUrl'
|
||||||
|
|
||||||
export type OrganizationRowViewModel = {
|
export type OrganizationRowViewModel = {
|
||||||
id: number
|
id: number
|
||||||
|
|
@ -28,79 +31,6 @@ export type OrganizationRowViewModel = {
|
||||||
leadershipCount: number
|
leadershipCount: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export type OrganizationListState = {
|
|
||||||
page: number
|
|
||||||
q?: string
|
|
||||||
kind?: OrganizationKind
|
|
||||||
}
|
|
||||||
|
|
||||||
export type OrganizationListSearchParams = RawSearchParams
|
|
||||||
|
|
||||||
const organizationListParamNames = ['q', 'kind', 'page'] as const
|
|
||||||
const organizationListParamNameSet = new Set<string>(organizationListParamNames)
|
|
||||||
|
|
||||||
export const parseOrganizationListParams = (
|
|
||||||
searchParams: RawSearchParams,
|
|
||||||
): OrganizationListState => {
|
|
||||||
const q = normalizedText(firstValue(searchParams.q))
|
|
||||||
const rawKind = firstValue(searchParams.kind)
|
|
||||||
|
|
||||||
return {
|
|
||||||
page: strictDecimalInteger(firstValue(searchParams.page)) ?? 1,
|
|
||||||
...(q ? { q } : {}),
|
|
||||||
...(organizationKinds.includes(rawKind as OrganizationKind)
|
|
||||||
? { kind: rawKind as OrganizationKind }
|
|
||||||
: {}),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const organizationListStateToRawParams = (
|
|
||||||
state: OrganizationListState,
|
|
||||||
page = state.page,
|
|
||||||
): OrganizationListSearchParams => ({
|
|
||||||
page: String(page),
|
|
||||||
q: state.q,
|
|
||||||
kind: state.kind,
|
|
||||||
})
|
|
||||||
|
|
||||||
const serializeCanonicalOrganizationListSearchParams = (
|
|
||||||
canonicalState: OrganizationListState,
|
|
||||||
): URLSearchParams => {
|
|
||||||
const params = new URLSearchParams()
|
|
||||||
if (canonicalState.q) params.set('q', canonicalState.q)
|
|
||||||
if (canonicalState.kind) params.set('kind', canonicalState.kind)
|
|
||||||
if (canonicalState.page > 1) params.set('page', String(canonicalState.page))
|
|
||||||
return params
|
|
||||||
}
|
|
||||||
|
|
||||||
const buildOrganizationListSearchParams = (
|
|
||||||
state: OrganizationListState,
|
|
||||||
page = state.page,
|
|
||||||
): URLSearchParams =>
|
|
||||||
serializeCanonicalOrganizationListSearchParams(
|
|
||||||
parseOrganizationListParams(organizationListStateToRawParams(state, page)),
|
|
||||||
)
|
|
||||||
|
|
||||||
export const buildOrganizationListHref = (state: OrganizationListState, page: number): string =>
|
|
||||||
buildListHref(state, buildOrganizationListSearchParams, '/campanha/organizacoes', page)
|
|
||||||
|
|
||||||
export const resolveOrganizationListUrl = (
|
|
||||||
params: OrganizationListSearchParams,
|
|
||||||
totalPages?: number,
|
|
||||||
): {
|
|
||||||
state: OrganizationListState
|
|
||||||
href: string
|
|
||||||
redirectHref?: string
|
|
||||||
} =>
|
|
||||||
resolveListUrl({
|
|
||||||
params,
|
|
||||||
paramNameSet: organizationListParamNameSet,
|
|
||||||
parse: parseOrganizationListParams,
|
|
||||||
buildSearchParams: buildOrganizationListSearchParams,
|
|
||||||
basePath: '/campanha/organizacoes',
|
|
||||||
totalPages,
|
|
||||||
})
|
|
||||||
|
|
||||||
const municipalityNamesByIds = async (
|
const municipalityNamesByIds = async (
|
||||||
payload: Payload,
|
payload: Payload,
|
||||||
ids: number[],
|
ids: number[],
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,16 @@
|
||||||
import { expect, test } from './fixtures/campaignE2EFixtures.js'
|
import { expect, test } from './fixtures/campaignE2EFixtures.js'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
<<<<<<< HEAD
|
||||||
* OH9/OH11 — dual-path municipality detail + full offline journey. Requires
|
* OH9/OH11 — dual-path municipality detail + full offline journey. Requires
|
||||||
* `OPS_HYBRID=1` on the Playwright webServer (compile-time). Default CI keeps
|
* `OPS_HYBRID=1` on the Playwright webServer (compile-time). Default CI keeps
|
||||||
* the flag off so characterization / municipalities specs continue to pin the
|
* the flag off so characterization / municipalities specs continue to pin the
|
||||||
* RSC path.
|
* RSC path.
|
||||||
|
=======
|
||||||
|
* OH9 / OH12 — dual-path municipality detail + list. 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.
|
||||||
|
>>>>>>> c9e3e84f (OH12: OpsListLocal read-only via registry + OfflineBoundary on lists)
|
||||||
*/
|
*/
|
||||||
const opsHybridEnabled =
|
const opsHybridEnabled =
|
||||||
process.env.OPS_HYBRID === '1' || process.env.OPS_HYBRID?.toLowerCase() === 'true'
|
process.env.OPS_HYBRID === '1' || process.env.OPS_HYBRID?.toLowerCase() === 'true'
|
||||||
|
|
@ -124,3 +130,44 @@ test.describe('OH9/OH11 campaign ops offline (OPS_HYBRID)', () => {
|
||||||
await expect(page.getByText('Média: 42')).toBeVisible({ timeout: 30_000 })
|
await expect(page.getByText('Média: 42')).toBeVisible({ timeout: 30_000 })
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test.describe('OH12 municipality list Local (OPS_HYBRID)', () => {
|
||||||
|
test.skip(!opsHybridEnabled, 'Set OPS_HYBRID=1 on the e2e webServer to run this dual-path.')
|
||||||
|
|
||||||
|
test('offline list renders mirror rows and filters by ?q=', async ({ campaign, page }) => {
|
||||||
|
const { fixtures } = campaign
|
||||||
|
const municipality = await fixtures.claimMunicipality()
|
||||||
|
const advisor = await fixtures.createCampaignUser('advisor', {
|
||||||
|
name: fixtures.value('Assessor OH12'),
|
||||||
|
})
|
||||||
|
await campaign.payload.update({
|
||||||
|
collection: 'municipality',
|
||||||
|
id: municipality.id,
|
||||||
|
data: { advisors: [advisor.id] },
|
||||||
|
depth: 0,
|
||||||
|
})
|
||||||
|
fixtures.touchMunicipality(municipality.id)
|
||||||
|
|
||||||
|
await campaign.login(page, advisor.email!, advisor.password)
|
||||||
|
await page.goto(`${campaign.baseURL}/campanha/municipios`)
|
||||||
|
await expect(page.getByRole('heading', { name: 'Municípios' })).toBeVisible()
|
||||||
|
|
||||||
|
await page.waitForResponse(
|
||||||
|
(response) =>
|
||||||
|
response.url().includes('/campanha/api/ops-sync') && response.request().method() === 'GET',
|
||||||
|
{ timeout: 30_000 },
|
||||||
|
)
|
||||||
|
|
||||||
|
await page.context().setOffline(true)
|
||||||
|
await page.goto(
|
||||||
|
`${campaign.baseURL}/campanha/municipios?q=${encodeURIComponent(municipality.name)}`,
|
||||||
|
)
|
||||||
|
|
||||||
|
await expect(page.getByRole('heading', { name: 'Municípios' })).toBeVisible()
|
||||||
|
await expect(
|
||||||
|
page.getByText('Edição na lista disponível quando estiveres online.'),
|
||||||
|
).toBeVisible()
|
||||||
|
await expect(page.getByRole('link', { name: municipality.name })).toBeVisible()
|
||||||
|
await expect(page.getByText('Indicadores indisponíveis offline.')).toBeVisible()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
|
||||||
200
tests/unit/opsListLocal.unit.spec.ts
Normal file
200
tests/unit/opsListLocal.unit.spec.ts
Normal file
|
|
@ -0,0 +1,200 @@
|
||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
|
||||||
|
import type {
|
||||||
|
OpsDemand,
|
||||||
|
OpsLeadership,
|
||||||
|
OpsMunicipality,
|
||||||
|
OpsOrganization,
|
||||||
|
OpsStateDeputy,
|
||||||
|
} from '@/lib/campaignOps/opsContract'
|
||||||
|
import {
|
||||||
|
filterSortPageOpsDemands,
|
||||||
|
filterSortPageOpsLeaderships,
|
||||||
|
filterSortPageOpsOrganizations,
|
||||||
|
filterSortPageOpsStateDeputies,
|
||||||
|
} from '@/utilities/campaignOps/opsEntityListLocal'
|
||||||
|
import { filterSortPageOpsMunicipalities } from '@/utilities/campaignOps/opsMunicipalityListLocal'
|
||||||
|
|
||||||
|
const municipality = (
|
||||||
|
partial: Partial<OpsMunicipality> & Pick<OpsMunicipality, 'id' | 'slug' | 'name'>,
|
||||||
|
): OpsMunicipality => ({
|
||||||
|
kind: 'municipio',
|
||||||
|
city: partial.name,
|
||||||
|
region: 'Portal do Sertão',
|
||||||
|
ibgeCode: '2910800',
|
||||||
|
updatedAt: '2026-08-01T00:00:00.000Z',
|
||||||
|
...partial,
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('filterSortPageOpsMunicipalities (OH12)', () => {
|
||||||
|
const rows = [
|
||||||
|
municipality({
|
||||||
|
id: 1,
|
||||||
|
slug: 'feira-de-santana',
|
||||||
|
name: 'Feira de Santana',
|
||||||
|
advisors: [10],
|
||||||
|
priority: 'alta',
|
||||||
|
politicalTrend: { status: 'favoravel' },
|
||||||
|
engagementLevel: 'n3',
|
||||||
|
expectedVotes: { central: 200 },
|
||||||
|
}),
|
||||||
|
municipality({
|
||||||
|
id: 2,
|
||||||
|
slug: 'alagoinhas',
|
||||||
|
name: 'Alagoinhas',
|
||||||
|
region: 'Litoral Norte e Agreste Baiano',
|
||||||
|
advisors: [],
|
||||||
|
politicalTrend: { status: 'neutra' },
|
||||||
|
engagementLevel: 'n1',
|
||||||
|
expectedVotes: { central: 50 },
|
||||||
|
}),
|
||||||
|
municipality({
|
||||||
|
id: 3,
|
||||||
|
slug: 'salvador-ze-1',
|
||||||
|
name: 'Salvador — ZE 1',
|
||||||
|
kind: 'zona',
|
||||||
|
city: 'Salvador',
|
||||||
|
region: 'Metropolitana de Salvador',
|
||||||
|
zoneNumber: 1,
|
||||||
|
advisors: [10, 11],
|
||||||
|
}),
|
||||||
|
]
|
||||||
|
|
||||||
|
it('filters by q on name and paginates', () => {
|
||||||
|
const result = filterSortPageOpsMunicipalities(rows, {
|
||||||
|
page: 1,
|
||||||
|
q: 'feira',
|
||||||
|
sort: 'name',
|
||||||
|
dir: 'asc',
|
||||||
|
})
|
||||||
|
expect(result.rows.map((row) => row.slug)).toEqual(['feira-de-santana'])
|
||||||
|
expect(result.totalDocs).toBe(1)
|
||||||
|
expect(result.classFilterUnavailable).toBe(false)
|
||||||
|
expect(result.sortDegraded).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('filters coverage / priority / trend / level from mirror fields', () => {
|
||||||
|
const result = filterSortPageOpsMunicipalities(rows, {
|
||||||
|
page: 1,
|
||||||
|
coverage: 'sem_assessor',
|
||||||
|
sort: 'name',
|
||||||
|
dir: 'asc',
|
||||||
|
})
|
||||||
|
expect(result.rows.map((row) => row.slug)).toEqual(['alagoinhas'])
|
||||||
|
|
||||||
|
const priority = filterSortPageOpsMunicipalities(rows, {
|
||||||
|
page: 1,
|
||||||
|
priority: 'alta',
|
||||||
|
sort: 'name',
|
||||||
|
dir: 'asc',
|
||||||
|
})
|
||||||
|
expect(priority.rows.map((row) => row.slug)).toEqual(['feira-de-santana'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('marks classe filter and server-only sorts as unavailable / degraded', () => {
|
||||||
|
const withClass = filterSortPageOpsMunicipalities(rows, {
|
||||||
|
page: 1,
|
||||||
|
classes: ['reduto'],
|
||||||
|
sort: 'deficit',
|
||||||
|
dir: 'desc',
|
||||||
|
})
|
||||||
|
expect(withClass.classFilterUnavailable).toBe(true)
|
||||||
|
expect(withClass.sortDegraded).toBe(true)
|
||||||
|
// Degraded sort falls back to name asc
|
||||||
|
expect(withClass.rows.map((row) => row.slug)).toEqual([
|
||||||
|
'alagoinhas',
|
||||||
|
'feira-de-santana',
|
||||||
|
'salvador-ze-1',
|
||||||
|
])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('ops entity list local helpers (OH12)', () => {
|
||||||
|
it('filters leaderships by q and status', () => {
|
||||||
|
const rows: OpsLeadership[] = [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
contact: { id: 1, name: 'Ana' },
|
||||||
|
municipalities: [10],
|
||||||
|
supportStatus: 'engajado',
|
||||||
|
updatedAt: '2026-08-01T00:00:00.000Z',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 2,
|
||||||
|
contact: { id: 2, name: 'Bruno' },
|
||||||
|
municipalities: [11],
|
||||||
|
supportStatus: 'a_abordar',
|
||||||
|
updatedAt: '2026-07-01T00:00:00.000Z',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
const result = filterSortPageOpsLeaderships(rows, {
|
||||||
|
page: 1,
|
||||||
|
q: 'ana',
|
||||||
|
statuses: ['engajado'],
|
||||||
|
sort: 'name',
|
||||||
|
dir: 'asc',
|
||||||
|
})
|
||||||
|
expect(result.rows.map((row) => row.id)).toEqual([1])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('filters state deputies, organizations and demands', () => {
|
||||||
|
const deputies: OpsStateDeputy[] = [
|
||||||
|
{ id: 1, name: 'João', slug: 'joao', party: 'PT', updatedAt: '2026-08-01T00:00:00.000Z' },
|
||||||
|
{ id: 2, name: 'Maria', slug: 'maria', party: null, updatedAt: '2026-08-01T00:00:00.000Z' },
|
||||||
|
]
|
||||||
|
expect(
|
||||||
|
filterSortPageOpsStateDeputies(deputies, {
|
||||||
|
page: 1,
|
||||||
|
q: 'mar',
|
||||||
|
sort: 'name',
|
||||||
|
dir: 'asc',
|
||||||
|
}).rows.map((row) => row.slug),
|
||||||
|
).toEqual(['maria'])
|
||||||
|
|
||||||
|
const orgs: OpsOrganization[] = [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
name: 'Sindicato A',
|
||||||
|
slug: 'sindicato-a',
|
||||||
|
kind: 'sindicato',
|
||||||
|
updatedAt: '2026-08-01T00:00:00.000Z',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 2,
|
||||||
|
name: 'Associação B',
|
||||||
|
slug: 'associacao-b',
|
||||||
|
kind: 'associacao',
|
||||||
|
updatedAt: '2026-08-01T00:00:00.000Z',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
expect(
|
||||||
|
filterSortPageOpsOrganizations(orgs, { page: 1, kind: 'sindicato' }).rows.map(
|
||||||
|
(row) => row.slug,
|
||||||
|
),
|
||||||
|
).toEqual(['sindicato-a'])
|
||||||
|
|
||||||
|
const demands: OpsDemand[] = [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
title: 'Material',
|
||||||
|
slug: 'material',
|
||||||
|
kind: 'material',
|
||||||
|
municipality: 1,
|
||||||
|
status: 'aberta',
|
||||||
|
updatedAt: '2026-08-02T00:00:00.000Z',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 2,
|
||||||
|
title: 'Transporte',
|
||||||
|
slug: 'transporte',
|
||||||
|
kind: 'transporte',
|
||||||
|
municipality: 1,
|
||||||
|
status: 'aprovada',
|
||||||
|
updatedAt: '2026-08-01T00:00:00.000Z',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
expect(
|
||||||
|
filterSortPageOpsDemands(demands, { page: 1, status: 'aberta' }).rows.map((row) => row.slug),
|
||||||
|
).toEqual(['material'])
|
||||||
|
})
|
||||||
|
})
|
||||||
Loading…
Reference in a new issue