mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-26 21:53:06 +00:00
CL6: real territory list pagination + OpsListPage flag
Add page to the territories URL contract, apply filter/sort/slice in the loader (page size 25), flip registry sortModel to url, and render /campanha/territorios through OpsListPage when LIST_UNIFIED is on. Closes #159 Co-authored-by: Francisco Solla <fsolla@users.noreply.github.com>
This commit is contained in:
parent
d5ab7d0b51
commit
a91019f427
16 changed files with 307 additions and 100 deletions
|
|
@ -4,6 +4,8 @@ Conteúdo movido do `AGENTS.md` em 2026-07-30 (fatiamento do paradigma de agente
|
|||
|
||||
---
|
||||
|
||||
**Recently resolved (2026-08-01):** **CL6** (Issue #159) — territórios: paginação real + sort no loader (`selectTerritoryOverviewPage` / `loadTerritoryOverviewPage`), `page` no contrato URL, registry `sortModel: 'url'`, `/campanha/territorios` atrás de `LIST_UNIFIED` com paridade OFF. Plano: [`cl6-territorios-factory.md`](docs/plans/cl6-territorios-factory.md).
|
||||
|
||||
**Recently resolved (2026-08-01):** **CL5** (Issue #160) — assessores no sistema de listas: `AdvisorsTable` → `CampaignTable` + picker (`assessores` em `CAMPAIGN_LIST_IDS`); `resolveAdvisorListUrl` (canonical + preserva `criar=1`); registry `columnListId`/`canonicalRedirect`; page atrás de `LIST_UNIFIED`/`OpsListPage`. Plano: [`cl5-assessores-factory.md`](docs/plans/cl5-assessores-factory.md).
|
||||
|
||||
**Recently resolved (2026-08-01):** **OH6** (Issue #167) — tracer `estimateVotesCas` (CAS opt-in via `baseEstimatedAt`) + outbox mínimo (`@tanstack/offline-transactions`) + toasts Sonner de conflito na ilha `PledgeEstimateForm` quando `OPS_HYBRID=1`; flag OFF mantém `formAction`. Plano: [`oh6-estimatevotes-cas-outbox.md`](docs/plans/oh6-estimatevotes-cas-outbox.md).
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# CL6 — Territórios: paginação real + sort server, depois factory
|
||||
|
||||
Status: rascunho
|
||||
Status: ready-for-review
|
||||
Atualizado em: 2026-08-01
|
||||
Issue: #159
|
||||
Priority: P1
|
||||
|
|
@ -10,13 +10,20 @@ Appetite: ~2 dias eng
|
|||
Depends: CL3
|
||||
Responsável: —
|
||||
|
||||
## Freshness audit (2026-08-01)
|
||||
|
||||
- CL3 (#157) `done`/`in-prod`; `OpsListPage`/`OpsListView` + `resolveListUnifiedEnabled` existem; municípios já usam flag ON/OFF.
|
||||
- Paths citados existem; `territorios` no registry ainda tem `sortModel: 'memory'`; page footer ainda stub (`page=1`/`totalPages=1`).
|
||||
- Premissas 1–3 mantêm-se; `createSortToggleHref` já pinna `page: 1` — o state precisa ganhar `page`.
|
||||
- Sem divergência material; sigo.
|
||||
|
||||
## Premissas
|
||||
|
||||
1. Hoje `territorios` carrega tudo e filtra/ordena **em memória** na page; o footer de paginação é cosmético (`page=1`, `totalPages=1`).
|
||||
2. O parser `resolveTerritoryListUrl` não tem `page` — terá de ganhar (contrato interno da rota, não URL pública nova para utilizadores).
|
||||
3. São 27 territórios — paginação é arquitetura para o padrão da factory, não necessidade de escala.
|
||||
|
||||
→ Corrija agora ou sigo com estas.
|
||||
→ Corrigidas / confirmadas no freshness audit; sigo.
|
||||
|
||||
## Objetivos
|
||||
|
||||
|
|
@ -49,10 +56,10 @@ Componentes:
|
|||
- **Quota:** ~0,5
|
||||
- **Entrega:** loader pagina/ordena; page renderiza slice; footer real.
|
||||
- **Aceite:**
|
||||
- [ ] `?page=2` muda as linhas visíveis
|
||||
- [ ] sort por URL ordena no loader (não no client)
|
||||
- [ ] `totalPages` calculado do total real
|
||||
- **Verify:** `pnpm gate:fast` + pin int do loader + e2e territórios
|
||||
- [x] `?page=2` muda as linhas visíveis
|
||||
- [x] sort por URL ordena no loader (não no client)
|
||||
- [x] `totalPages` calculado do total real
|
||||
- **Verify:** `pnpm gate:fast` + pin unit do loader (`selectTerritoryOverviewPage`) + e2e territórios
|
||||
- **Files:** `territoryOverview.ts`, `territoryListUrl.ts`, page
|
||||
- **Tamanho:** M
|
||||
|
||||
|
|
|
|||
|
|
@ -9,15 +9,16 @@ import {
|
|||
CampaignListPendingBoundary,
|
||||
CampaignListResults,
|
||||
} from '@/components/campaign/shared/CampaignListPending'
|
||||
import { OpsListPage } from '@/components/campaign/shared/OpsListPage'
|
||||
import { CampaignPageShell } from '@/components/campaign/shell/CampaignPageShell'
|
||||
import { resolveListUnifiedEnabled } from '@/lib/opsListRegistry/opsListFlag'
|
||||
import { readCampaignColumnVisibility } from '@/utilities/campaignColumnVisibilityCookie'
|
||||
import { requireCampaignPageActor } from '@/utilities/campaignPageActor'
|
||||
import { loadTerritoryOverview } from '@/utilities/territory/loadTerritoryOverview'
|
||||
import { loadTerritoryOverviewPage } from '@/utilities/territory/loadTerritoryOverview'
|
||||
import {
|
||||
resolveTerritoryListSort,
|
||||
buildTerritoryListHref,
|
||||
resolveTerritoryListUrl,
|
||||
} from '@/utilities/territory/territoryListUrl'
|
||||
import { filterTerritoryRows, sortTerritoryRows } from '@/utilities/territory/territoryOverview'
|
||||
|
||||
type TerritoriesPageProps = {
|
||||
searchParams: Promise<Record<string, string | string[] | undefined>>
|
||||
|
|
@ -25,22 +26,52 @@ type TerritoriesPageProps = {
|
|||
|
||||
export default async function TerritoriesPage({ searchParams }: TerritoriesPageProps) {
|
||||
const rawSearchParams = await searchParams
|
||||
const resolvedUrl = resolveTerritoryListUrl(rawSearchParams)
|
||||
if (resolvedUrl.redirectHref) redirect(resolvedUrl.redirectHref)
|
||||
const canonicalUrl = resolveTerritoryListUrl(rawSearchParams)
|
||||
if (canonicalUrl.redirectHref) redirect(canonicalUrl.redirectHref)
|
||||
|
||||
const [user, payload] = await Promise.all([
|
||||
requireCampaignPageActor({ gate: 'noLeader' }),
|
||||
getPayload({ config }),
|
||||
])
|
||||
|
||||
const allRows = await loadTerritoryOverview(payload, user)
|
||||
const columnVisibility = await readCampaignColumnVisibility('territorios')
|
||||
const pageResult = await loadTerritoryOverviewPage(payload, user, canonicalUrl.state)
|
||||
const { rows, totalDocs, totalPages, regionOptions } = pageResult
|
||||
const resolvedUrl = resolveTerritoryListUrl(rawSearchParams, totalPages)
|
||||
if (resolvedUrl.redirectHref) redirect(resolvedUrl.redirectHref)
|
||||
const { state } = resolvedUrl
|
||||
const { sort, dir } = resolveTerritoryListSort(state)
|
||||
const rows = sortTerritoryRows(filterTerritoryRows(allRows, state), sort, dir)
|
||||
const regionOptions = allRows
|
||||
.map((row) => ({ value: row.region, label: row.region }))
|
||||
.sort((left, right) => left.label.localeCompare(right.label, 'pt-BR'))
|
||||
const columnVisibility = await readCampaignColumnVisibility('territorios')
|
||||
|
||||
const filters = <TerritoryFilters state={state} regionOptions={regionOptions} />
|
||||
const tableNode = (
|
||||
<TerritoryList
|
||||
rows={rows}
|
||||
state={state}
|
||||
regionOptions={regionOptions}
|
||||
columnVisibility={columnVisibility}
|
||||
/>
|
||||
)
|
||||
const footerNode = (
|
||||
<CampaignListFooter
|
||||
totalDocs={totalDocs}
|
||||
singular="território encontrado"
|
||||
plural="territórios encontrados"
|
||||
page={state.page}
|
||||
totalPages={totalPages}
|
||||
hrefForPage={(page) => buildTerritoryListHref(state, page)}
|
||||
/>
|
||||
)
|
||||
|
||||
const main = resolveListUnifiedEnabled() ? (
|
||||
<OpsListPage overview={null} toolbar={filters} table={tableNode} empty={null} footer={footerNode} />
|
||||
) : (
|
||||
<CampaignListPendingBoundary>
|
||||
{filters}
|
||||
<CampaignListResults>
|
||||
{tableNode}
|
||||
{footerNode}
|
||||
</CampaignListResults>
|
||||
</CampaignListPendingBoundary>
|
||||
)
|
||||
|
||||
return (
|
||||
<CampaignPageShell>
|
||||
|
|
@ -53,25 +84,7 @@ export default async function TerritoriesPage({ searchParams }: TerritoriesPageP
|
|||
território para ver seus municípios.
|
||||
</p>
|
||||
</header>
|
||||
<CampaignListPendingBoundary>
|
||||
<TerritoryFilters state={state} regionOptions={regionOptions} />
|
||||
<CampaignListResults>
|
||||
<TerritoryList
|
||||
rows={rows}
|
||||
state={state}
|
||||
regionOptions={regionOptions}
|
||||
columnVisibility={columnVisibility}
|
||||
/>
|
||||
<CampaignListFooter
|
||||
totalDocs={rows.length}
|
||||
singular="território encontrado"
|
||||
plural="territórios encontrados"
|
||||
page={1}
|
||||
totalPages={1}
|
||||
hrefForPage={() => resolvedUrl.href}
|
||||
/>
|
||||
</CampaignListResults>
|
||||
</CampaignListPendingBoundary>
|
||||
{main}
|
||||
</CampaignPageShell>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import { Button } from '@/components/ui/button'
|
|||
import { Field, FieldLabel } from '@/components/ui/field'
|
||||
import { NativeSelect, NativeSelectOption } from '@/components/ui/native-select'
|
||||
import {
|
||||
buildTerritoryFilterHref,
|
||||
clearTerritoryListFilters,
|
||||
formatTerritoryActiveFiltersSummary,
|
||||
territoryCoverageLabels,
|
||||
|
|
@ -14,7 +15,6 @@ import {
|
|||
type TerritoryFilterOption,
|
||||
} from '@/utilities/territory/territoryListFilters'
|
||||
import {
|
||||
buildTerritoryListHref,
|
||||
parseTerritorySortValue,
|
||||
resolveTerritoryListSort,
|
||||
serializeTerritorySortValue,
|
||||
|
|
@ -30,7 +30,7 @@ export const TerritoryFilters = ({
|
|||
regionOptions: TerritoryFilterOption[]
|
||||
}) => {
|
||||
const { search, onSearchChange, draftQ, isPending, navigateWithSearch, clearSearchAndNavigate } =
|
||||
useCampaignListFilterNavigation({ state, toHref: buildTerritoryListHref })
|
||||
useCampaignListFilterNavigation({ state, toHref: buildTerritoryFilterHref })
|
||||
const { sort, dir } = resolveTerritoryListSort(state)
|
||||
const activeSummary = formatTerritoryActiveFiltersSummary({ ...state, q: draftQ })
|
||||
|
||||
|
|
|
|||
|
|
@ -7,16 +7,14 @@ import {
|
|||
type CampaignHeaderFilterRow,
|
||||
} from '@/components/campaign/shared/CampaignHeaderFilterPopover'
|
||||
import {
|
||||
buildTerritoryFilterHref,
|
||||
isTerritoryFilterActive,
|
||||
territoryCoverageOptions,
|
||||
toggleTerritoryCoverageFilter,
|
||||
toggleTerritoryRegionFilter,
|
||||
type TerritoryFilterOption,
|
||||
} from '@/utilities/territory/territoryListFilters'
|
||||
import {
|
||||
buildTerritoryListHref,
|
||||
type TerritoryListState,
|
||||
} from '@/utilities/territory/territoryListUrl'
|
||||
import { type TerritoryListState } from '@/utilities/territory/territoryListUrl'
|
||||
|
||||
type TerritoryHeaderFilterProps =
|
||||
| {
|
||||
|
|
@ -45,7 +43,7 @@ export const TerritoryHeaderFilter = ({
|
|||
return {
|
||||
value: option.value,
|
||||
label: option.label,
|
||||
href: buildTerritoryListHref(next),
|
||||
href: buildTerritoryFilterHref(next),
|
||||
selected: Boolean(viewState.regions?.some((region) => region === option.value)),
|
||||
checkbox: true,
|
||||
onChoose: () => setOptimisticState(next),
|
||||
|
|
@ -56,7 +54,7 @@ export const TerritoryHeaderFilter = ({
|
|||
return {
|
||||
value: option.value,
|
||||
label: option.label,
|
||||
href: buildTerritoryListHref(next),
|
||||
href: buildTerritoryFilterHref(next),
|
||||
selected: viewState.coverage === option.value,
|
||||
checkbox: false,
|
||||
onChoose: () => setOptimisticState(next),
|
||||
|
|
@ -65,8 +63,8 @@ export const TerritoryHeaderFilter = ({
|
|||
|
||||
const clearedState: TerritoryListState =
|
||||
filterParam === 'region'
|
||||
? { ...viewState, regions: undefined }
|
||||
: { ...viewState, coverage: undefined }
|
||||
? { ...viewState, regions: undefined, page: 1 }
|
||||
: { ...viewState, coverage: undefined, page: 1 }
|
||||
|
||||
return (
|
||||
<CampaignHeaderFilterPopover
|
||||
|
|
@ -78,7 +76,7 @@ export const TerritoryHeaderFilter = ({
|
|||
clear={
|
||||
active
|
||||
? {
|
||||
href: buildTerritoryListHref(clearedState),
|
||||
href: buildTerritoryFilterHref(clearedState),
|
||||
onChoose: () => setOptimisticState(clearedState),
|
||||
}
|
||||
: undefined
|
||||
|
|
|
|||
|
|
@ -16,11 +16,11 @@ import type { CampaignColumnVisibility } from '@/lib/campaignColumnVisibility'
|
|||
import { territoryAnchorId } from '@/lib/territoryAnchor'
|
||||
import { cn } from '@/lib/utils'
|
||||
import {
|
||||
buildTerritoryFilterHref,
|
||||
clearTerritoryListFilters,
|
||||
type TerritoryFilterOption,
|
||||
} from '@/utilities/territory/territoryListFilters'
|
||||
import {
|
||||
buildTerritoryListHref,
|
||||
formatTerritoryListSortSummary,
|
||||
resolveTerritoryListSort,
|
||||
type TerritoryListState,
|
||||
|
|
@ -43,7 +43,7 @@ const TerritoryListEmptyState = ({ state }: { state: TerritoryListState }) => (
|
|||
</EmptyHeader>
|
||||
<EmptyContent>
|
||||
<CampaignTransitionAnchor
|
||||
href={buildTerritoryListHref(clearTerritoryListFilters(state))}
|
||||
href={buildTerritoryFilterHref(clearTerritoryListFilters(state))}
|
||||
replace
|
||||
scroll={false}
|
||||
className={cn(buttonVariants({ variant: 'outline' }), 'min-h-11')}
|
||||
|
|
|
|||
|
|
@ -92,7 +92,7 @@ export const opsListRegistry: Record<OpsListDomainId, OpsListDomainMeta> = {
|
|||
gate: 'noLeader',
|
||||
columnListId: 'territorios',
|
||||
savedFilters: false,
|
||||
sortModel: 'memory',
|
||||
sortModel: 'url',
|
||||
canonicalRedirect: true,
|
||||
layout: 'table',
|
||||
},
|
||||
|
|
|
|||
|
|
@ -11,8 +11,13 @@ import { loadMunicipalityScopeFromDocs } from '@/utilities/municipality/campaign
|
|||
import { loadMunicipalityGoalCoverageBundle } from '@/utilities/municipality/municipalityGoalAccount'
|
||||
import { fieldCeiling, ownVotes2022 } from '@/utilities/municipality/municipalityPotential'
|
||||
import { computeAggregateTerritorialClass } from '@/utilities/municipality/municipalityTerritorialClass'
|
||||
import {
|
||||
resolveTerritoryListSort,
|
||||
type TerritoryListState,
|
||||
} from '@/utilities/territory/territoryListUrl'
|
||||
import {
|
||||
computeTerritoryRollup,
|
||||
selectTerritoryOverviewPage,
|
||||
type TerritoryMunicipalityInput,
|
||||
type TerritoryOverviewRow,
|
||||
} from '@/utilities/territory/territoryOverview'
|
||||
|
|
@ -21,6 +26,14 @@ import {
|
|||
resolveMunicipalityStaffVoteTotal,
|
||||
} from '@/utilities/votePledgeViews'
|
||||
|
||||
export type TerritoryOverviewPageResult = {
|
||||
rows: TerritoryOverviewRow[]
|
||||
totalDocs: number
|
||||
totalPages: number
|
||||
/** Unfiltered TI labels for the region filter (full 27-row rollup). */
|
||||
regionOptions: Array<{ value: string; label: string }>
|
||||
}
|
||||
|
||||
type MunicipalityDoc = Pick<
|
||||
Municipality,
|
||||
'id' | 'slug' | 'name' | 'city' | 'region' | 'kind' | 'advisors' | 'expectedVotes'
|
||||
|
|
@ -127,3 +140,30 @@ export const loadTerritoryOverview = cache(
|
|||
return attachTerritorialClasses(inputs, rows)
|
||||
},
|
||||
)
|
||||
|
||||
/**
|
||||
* CL6a — filter/sort/page applied in the loader (not the page). Region options
|
||||
* stay unfiltered so the header popover still lists every TI.
|
||||
*/
|
||||
export const loadTerritoryOverviewPage = cache(
|
||||
async (
|
||||
payload: Payload,
|
||||
user: TerritoryReader,
|
||||
state: TerritoryListState,
|
||||
scenario: VoteEstimateScenario = DEFAULT_VOTE_ESTIMATE_SCENARIO,
|
||||
): Promise<TerritoryOverviewPageResult> => {
|
||||
const allRows = await loadTerritoryOverview(payload, user, scenario)
|
||||
const { sort, dir } = resolveTerritoryListSort(state)
|
||||
const { rows, totalDocs, totalPages } = selectTerritoryOverviewPage(allRows, {
|
||||
filters: state,
|
||||
sort,
|
||||
dir,
|
||||
page: state.page,
|
||||
})
|
||||
const regionOptions = allRows
|
||||
.map((row) => ({ value: row.region, label: row.region }))
|
||||
.sort((left, right) => left.label.localeCompare(right.label, 'pt-BR'))
|
||||
|
||||
return { rows, totalDocs, totalPages, regionOptions }
|
||||
},
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { truncatedNamesLabel } from '@/utilities/campaignListUrl'
|
||||
import {
|
||||
buildTerritoryListHref,
|
||||
parseTerritoryListParams,
|
||||
territoryListStateToRawParams,
|
||||
type TerritoryCoverage,
|
||||
|
|
@ -22,6 +23,9 @@ export const territoryCoverageOptions = (
|
|||
['com_assessor', 'sem_assessor'] as const satisfies readonly TerritoryCoverage[]
|
||||
).map((value) => ({ value, label: territoryCoverageLabels[value] }))
|
||||
|
||||
const withTerritoryListPageReset = (state: TerritoryListState): TerritoryListState =>
|
||||
parseTerritoryListParams(territoryListStateToRawParams({ ...state, page: 1 }, 1))
|
||||
|
||||
export const toggleTerritoryRegionFilter = (
|
||||
state: TerritoryListState,
|
||||
region: string,
|
||||
|
|
@ -31,7 +35,7 @@ export const toggleTerritoryRegionFilter = (
|
|||
? current.filter((entry) => entry !== region)
|
||||
: [...current, region]
|
||||
return parseTerritoryListParams({
|
||||
...territoryListStateToRawParams(state),
|
||||
...territoryListStateToRawParams({ ...state, page: 1 }, 1),
|
||||
region: regions,
|
||||
})
|
||||
}
|
||||
|
|
@ -40,16 +44,21 @@ export const toggleTerritoryCoverageFilter = (
|
|||
state: TerritoryListState,
|
||||
coverage: TerritoryCoverage,
|
||||
): TerritoryListState =>
|
||||
parseTerritoryListParams({
|
||||
...territoryListStateToRawParams(state),
|
||||
withTerritoryListPageReset({
|
||||
...state,
|
||||
coverage: state.coverage === coverage ? undefined : coverage,
|
||||
})
|
||||
|
||||
export const clearTerritoryListFilters = (state: TerritoryListState): TerritoryListState => ({
|
||||
page: 1,
|
||||
sort: state.sort,
|
||||
dir: state.dir,
|
||||
})
|
||||
|
||||
/** Every filter/search change resets pagination — sibling of `buildMunicipalityFilterHref`. */
|
||||
export const buildTerritoryFilterHref = (next: TerritoryListState): string =>
|
||||
buildTerritoryListHref(next, 1)
|
||||
|
||||
export const isTerritoryFilterActive = (
|
||||
state: TerritoryListState,
|
||||
param: TerritoryFilterParam,
|
||||
|
|
|
|||
|
|
@ -1,9 +1,11 @@
|
|||
import { type BahiaIdentityTerritory } from '@/lib/bahiaTerritories'
|
||||
import {
|
||||
buildListHref,
|
||||
createSortToggleHref,
|
||||
firstValue,
|
||||
inspectRawListParams,
|
||||
normalizedText,
|
||||
resolveListUrl,
|
||||
strictDecimalInteger,
|
||||
type RawSearchParams,
|
||||
} from '@/utilities/campaignListUrl'
|
||||
import type { TerritorySortDir, TerritorySortKey } from '@/utilities/territory/territoryOverview'
|
||||
|
|
@ -14,6 +16,7 @@ export type TerritoryListSortDirection = TerritorySortDir
|
|||
export type TerritoryCoverage = 'com_assessor' | 'sem_assessor'
|
||||
|
||||
export type TerritoryListState = {
|
||||
page: number
|
||||
q?: string
|
||||
regions?: BahiaIdentityTerritory[]
|
||||
coverage?: TerritoryCoverage
|
||||
|
|
@ -23,7 +26,7 @@ export type TerritoryListState = {
|
|||
|
||||
export type TerritoryListSearchParams = RawSearchParams
|
||||
|
||||
const territoryListParamNames = ['q', 'region', 'coverage', 'sort', 'dir'] as const
|
||||
const territoryListParamNames = ['q', 'region', 'coverage', 'sort', 'dir', 'page'] as const
|
||||
const territoryListParamNameSet = new Set<string>(territoryListParamNames)
|
||||
const territoryListSortKeys: TerritoryListSortKey[] = [
|
||||
'region',
|
||||
|
|
@ -81,7 +84,20 @@ export const formatTerritoryListSortSummary = (
|
|||
return `Ordenado por ${territoryListSortLabels[sort]} (${dir === 'asc' ? 'menor primeiro' : 'maior primeiro'})`
|
||||
}
|
||||
|
||||
export const territoryListStateToRawParams = (
|
||||
state: TerritoryListState,
|
||||
page = state.page,
|
||||
): TerritoryListSearchParams => ({
|
||||
page: String(page),
|
||||
q: state.q,
|
||||
region: state.regions,
|
||||
coverage: state.coverage,
|
||||
sort: state.sort,
|
||||
dir: state.dir,
|
||||
})
|
||||
|
||||
export const parseTerritoryListParams = (params: TerritoryListSearchParams): TerritoryListState => {
|
||||
const rawPage = strictDecimalInteger(firstValue(params.page))
|
||||
const q = normalizedText(firstValue(params.q))
|
||||
const regions = parseRegions(params.region)
|
||||
const rawCoverage = firstValue(params.coverage)
|
||||
|
|
@ -89,6 +105,7 @@ export const parseTerritoryListParams = (params: TerritoryListSearchParams): Ter
|
|||
const rawDir = firstValue(params.dir)
|
||||
|
||||
return {
|
||||
page: rawPage ?? 1,
|
||||
...(q ? { q } : {}),
|
||||
...(regions.length ? { regions } : {}),
|
||||
...(rawCoverage === 'com_assessor' || rawCoverage === 'sem_assessor'
|
||||
|
|
@ -103,16 +120,6 @@ export const parseTerritoryListParams = (params: TerritoryListSearchParams): Ter
|
|||
}
|
||||
}
|
||||
|
||||
export const territoryListStateToRawParams = (
|
||||
state: TerritoryListState,
|
||||
): TerritoryListSearchParams => ({
|
||||
q: state.q,
|
||||
region: state.regions,
|
||||
coverage: state.coverage,
|
||||
sort: state.sort,
|
||||
dir: state.dir,
|
||||
})
|
||||
|
||||
export const serializeTerritoryListSearchParams = (state: TerritoryListState): URLSearchParams => {
|
||||
const canonical = parseTerritoryListParams(territoryListStateToRawParams(state))
|
||||
const { sort, dir } = resolveTerritoryListSort(canonical)
|
||||
|
|
@ -125,13 +132,20 @@ export const serializeTerritoryListSearchParams = (state: TerritoryListState): U
|
|||
params.set('sort', sort)
|
||||
if (dir !== defaultTerritoryListSortDir(sort)) params.set('dir', dir)
|
||||
}
|
||||
if (canonical.page > 1) params.set('page', String(canonical.page))
|
||||
return params
|
||||
}
|
||||
|
||||
export const buildTerritoryListHref = (state: TerritoryListState): string => {
|
||||
const query = serializeTerritoryListSearchParams(state).toString()
|
||||
return query ? `/campanha/territorios?${query}` : '/campanha/territorios'
|
||||
}
|
||||
const buildTerritoryListSearchParams = (
|
||||
state: TerritoryListState,
|
||||
page = state.page,
|
||||
): URLSearchParams =>
|
||||
serializeTerritoryListSearchParams(
|
||||
parseTerritoryListParams(territoryListStateToRawParams(state, page)),
|
||||
)
|
||||
|
||||
export const buildTerritoryListHref = (state: TerritoryListState, page: number): string =>
|
||||
buildListHref(state, buildTerritoryListSearchParams, '/campanha/territorios', page)
|
||||
|
||||
export const buildTerritorySortHref = createSortToggleHref<
|
||||
TerritoryListState,
|
||||
|
|
@ -139,22 +153,21 @@ export const buildTerritorySortHref = createSortToggleHref<
|
|||
>({
|
||||
resolveCurrentSort: resolveTerritoryListSort,
|
||||
defaultDir: defaultTerritoryListSortDir,
|
||||
buildHref: buildTerritoryListHref,
|
||||
buildHref: (state) => buildTerritoryListHref(state, 1),
|
||||
})
|
||||
|
||||
export const resolveTerritoryListUrl = (
|
||||
params: TerritoryListSearchParams,
|
||||
): { state: TerritoryListState; href: string; redirectHref?: string } => {
|
||||
const state = parseTerritoryListParams(params)
|
||||
const href = buildTerritoryListHref(state)
|
||||
const canonicalQuery = serializeTerritoryListSearchParams(state).toString()
|
||||
const raw = inspectRawListParams(params, territoryListParamNameSet)
|
||||
return {
|
||||
state,
|
||||
href,
|
||||
...(raw.hasUnsupportedParams || raw.query !== canonicalQuery ? { redirectHref: href } : {}),
|
||||
}
|
||||
}
|
||||
totalPages?: number,
|
||||
): { state: TerritoryListState; href: string; redirectHref?: string } =>
|
||||
resolveListUrl({
|
||||
params,
|
||||
paramNameSet: territoryListParamNameSet,
|
||||
parse: parseTerritoryListParams,
|
||||
buildSearchParams: buildTerritoryListSearchParams,
|
||||
basePath: '/campanha/territorios',
|
||||
totalPages,
|
||||
})
|
||||
|
||||
const sortOptionLabel = (key: TerritoryListSortKey, dir: TerritoryListSortDirection): string => {
|
||||
const label = territoryListSortLabels[key]
|
||||
|
|
|
|||
|
|
@ -394,3 +394,37 @@ export const flattenTerritoryRows = (
|
|||
parentRegion: row.region,
|
||||
})),
|
||||
])
|
||||
|
||||
/** Page size for `/campanha/territorios` — same default as the other campaign lists. */
|
||||
export const TERRITORY_LIST_PAGE_SIZE = 25
|
||||
|
||||
/**
|
||||
* CL6a — filter → sort → page slice over the 27-TI rollup.
|
||||
* Out-of-range `page` yields an empty slice; the URL resolver clamps + redirects.
|
||||
*/
|
||||
export const selectTerritoryOverviewPage = (
|
||||
allRows: ReadonlyArray<TerritoryOverviewRow>,
|
||||
options: {
|
||||
filters: TerritoryRowFilters
|
||||
sort: TerritorySortKey
|
||||
dir: TerritorySortDir
|
||||
page: number
|
||||
pageSize?: number
|
||||
},
|
||||
): { rows: TerritoryOverviewRow[]; totalDocs: number; totalPages: number } => {
|
||||
const filtered = sortTerritoryRows(
|
||||
filterTerritoryRows(allRows, options.filters),
|
||||
options.sort,
|
||||
options.dir,
|
||||
)
|
||||
const pageSize = options.pageSize ?? TERRITORY_LIST_PAGE_SIZE
|
||||
const totalDocs = filtered.length
|
||||
const totalPages = totalDocs === 0 ? 0 : Math.ceil(totalDocs / pageSize)
|
||||
const page = Math.max(1, options.page)
|
||||
const start = (page - 1) * pageSize
|
||||
return {
|
||||
rows: filtered.slice(start, start + pageSize),
|
||||
totalDocs,
|
||||
totalPages,
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -32,6 +32,21 @@ test.describe('Territórios de Identidade', () => {
|
|||
await expect(page).toHaveURL(/\/campanha\/municipios\?region=Irec%C3%AA/)
|
||||
})
|
||||
|
||||
test('staff pagination reaches page 2 of the territory list', async ({ campaign, page }) => {
|
||||
const { fixtures } = campaign
|
||||
const coordinator = await fixtures.createCampaignUser('coordinator', {
|
||||
name: fixtures.value('Coordenadora Paginação TI'),
|
||||
})
|
||||
|
||||
await campaign.login(page, coordinator.email!, coordinator.password)
|
||||
await page.goto('/campanha/territorios')
|
||||
await expect(page.getByText(/27 territórios encontrados/)).toBeVisible()
|
||||
|
||||
await page.getByRole('link', { name: 'Ir para a página 2' }).click()
|
||||
await expect(page).toHaveURL(/\/campanha\/territorios\?page=2/)
|
||||
await expect(page.getByText(/27 territórios encontrados/)).toBeVisible()
|
||||
})
|
||||
|
||||
test('parent territory rows expose hash anchor ids for deep links', async ({
|
||||
campaign,
|
||||
page,
|
||||
|
|
|
|||
|
|
@ -70,12 +70,12 @@ const filterCases: FilterCase[] = [
|
|||
sortValue: 'region|asc',
|
||||
element: (currentQuery) =>
|
||||
createElement(TerritoryFilters, {
|
||||
state: { ...(currentQuery ? { q: currentQuery } : {}) },
|
||||
state: { page: 1, ...(currentQuery ? { q: currentQuery } : {}) },
|
||||
regionOptions: [],
|
||||
}),
|
||||
elementWithSort: () =>
|
||||
createElement(TerritoryFilters, {
|
||||
state: { sort: 'region', dir: 'asc' },
|
||||
state: { page: 1, sort: 'region', dir: 'asc' },
|
||||
regionOptions: [],
|
||||
}),
|
||||
},
|
||||
|
|
|
|||
|
|
@ -63,6 +63,14 @@ describe('opsListRegistry v1', () => {
|
|||
expect(meta?.canonicalRedirect).toBe(true)
|
||||
})
|
||||
|
||||
it('pins territorios to url sort after CL6a (no memory stub)', () => {
|
||||
const meta = getOpsListDomain('territorios')
|
||||
expect(meta).not.toBeNull()
|
||||
expect(meta?.sortModel).toBe('url')
|
||||
expect(meta?.canonicalRedirect).toBe(true)
|
||||
expect(meta?.columnListId).toBe('territorios')
|
||||
})
|
||||
|
||||
it('returns null for atividades (cards layout — excluded from factory)', () => {
|
||||
expect(getOpsListDomain('atividades')).toBeNull()
|
||||
expect(getOpsListDomain('unknown-slug')).toBeNull()
|
||||
|
|
|
|||
|
|
@ -24,8 +24,10 @@ describe('territory list URL contract', () => {
|
|||
coverage: 'sem_assessor',
|
||||
sort: 'votes2022',
|
||||
dir: 'asc',
|
||||
page: '2',
|
||||
}),
|
||||
).toEqual({
|
||||
page: 2,
|
||||
q: 'irecê',
|
||||
regions: ['Velho Chico', 'Irecê'],
|
||||
coverage: 'sem_assessor',
|
||||
|
|
@ -34,35 +36,56 @@ describe('territory list URL contract', () => {
|
|||
})
|
||||
})
|
||||
|
||||
it('omits the default sort pair from the canonical query', () => {
|
||||
const state = parseTerritoryListParams({ sort: 'pct', dir: 'desc' })
|
||||
it('omits the default sort pair and page 1 from the canonical query', () => {
|
||||
const state = parseTerritoryListParams({ sort: 'pct', dir: 'desc', page: '1' })
|
||||
|
||||
expect(serializeTerritoryListSearchParams(state).toString()).toBe('')
|
||||
expect(resolveTerritoryListSort(state)).toEqual({ sort: 'pct', dir: 'desc' })
|
||||
})
|
||||
|
||||
it('preserves filters while toggling sort direction', () => {
|
||||
const state = parseTerritoryListParams({ q: 'chico', region: 'Velho Chico' })
|
||||
it('serializes page > 1', () => {
|
||||
const state = parseTerritoryListParams({ page: '2' })
|
||||
expect(serializeTerritoryListSearchParams(state).toString()).toBe('page=2')
|
||||
expect(buildTerritoryListHref(state, 2)).toBe('/campanha/territorios?page=2')
|
||||
})
|
||||
|
||||
it('preserves filters while toggling sort direction and resets to page 1', () => {
|
||||
const state = parseTerritoryListParams({ q: 'chico', region: 'Velho Chico', page: '2' })
|
||||
|
||||
expect(buildTerritorySortHref(state, 'votes2022')).toBe(
|
||||
'/campanha/territorios?q=chico®ion=Velho+Chico&sort=votes2022',
|
||||
)
|
||||
expect(
|
||||
buildTerritorySortHref(
|
||||
parseTerritoryListParams({ ...state, sort: 'votes2022', dir: 'desc' }),
|
||||
parseTerritoryListParams({
|
||||
q: 'chico',
|
||||
region: 'Velho Chico',
|
||||
sort: 'votes2022',
|
||||
dir: 'desc',
|
||||
page: '2',
|
||||
}),
|
||||
'votes2022',
|
||||
),
|
||||
).toContain('dir=asc')
|
||||
expect(buildTerritorySortHref(state, 'votes2022')).not.toContain('page=')
|
||||
})
|
||||
|
||||
it('redirects unsupported and non-canonical query strings', () => {
|
||||
expect(resolveTerritoryListUrl({ q: ' Irecê ', unknown: 'x' })).toEqual({
|
||||
state: { q: 'Irecê' },
|
||||
state: { page: 1, q: 'Irecê' },
|
||||
href: '/campanha/territorios?q=Irec%C3%AA',
|
||||
redirectHref: '/campanha/territorios?q=Irec%C3%AA',
|
||||
})
|
||||
})
|
||||
|
||||
it('clamps page above totalPages via redirect', () => {
|
||||
expect(resolveTerritoryListUrl({ page: '9' }, 2)).toEqual({
|
||||
state: { page: 2 },
|
||||
href: '/campanha/territorios?page=2',
|
||||
redirectHref: '/campanha/territorios?page=2',
|
||||
})
|
||||
})
|
||||
|
||||
it('clears invalid values instead of serializing them', () => {
|
||||
const state = parseTerritoryListParams({
|
||||
coverage: 'talvez',
|
||||
|
|
@ -70,37 +93,39 @@ describe('territory list URL contract', () => {
|
|||
dir: 'sideways',
|
||||
})
|
||||
|
||||
expect(state).toEqual({})
|
||||
expect(buildTerritoryListHref(state)).toBe('/campanha/territorios')
|
||||
expect(state).toEqual({ page: 1 })
|
||||
expect(buildTerritoryListHref(state, 1)).toBe('/campanha/territorios')
|
||||
})
|
||||
})
|
||||
|
||||
describe('territory list filter state', () => {
|
||||
it('toggles region and coverage filters canonically', () => {
|
||||
const withRegion = toggleTerritoryRegionFilter({}, 'Irecê')
|
||||
expect(withRegion).toEqual({ regions: ['Irecê'] })
|
||||
expect(toggleTerritoryRegionFilter(withRegion, 'Irecê')).toEqual({})
|
||||
it('toggles region and coverage filters canonically and resets page', () => {
|
||||
const withRegion = toggleTerritoryRegionFilter({ page: 2 }, 'Irecê')
|
||||
expect(withRegion).toEqual({ page: 1, regions: ['Irecê'] })
|
||||
expect(toggleTerritoryRegionFilter(withRegion, 'Irecê')).toEqual({ page: 1 })
|
||||
|
||||
const withCoverage = toggleTerritoryCoverageFilter({}, 'sem_assessor')
|
||||
expect(withCoverage).toEqual({ coverage: 'sem_assessor' })
|
||||
expect(toggleTerritoryCoverageFilter(withCoverage, 'sem_assessor')).toEqual({})
|
||||
const withCoverage = toggleTerritoryCoverageFilter({ page: 2 }, 'sem_assessor')
|
||||
expect(withCoverage).toEqual({ page: 1, coverage: 'sem_assessor' })
|
||||
expect(toggleTerritoryCoverageFilter(withCoverage, 'sem_assessor')).toEqual({ page: 1 })
|
||||
})
|
||||
|
||||
it('clears filters while preserving the selected sort', () => {
|
||||
expect(
|
||||
clearTerritoryListFilters({
|
||||
page: 3,
|
||||
q: 'irecê',
|
||||
regions: ['Irecê'],
|
||||
coverage: 'sem_assessor',
|
||||
sort: 'votes2022',
|
||||
dir: 'asc',
|
||||
}),
|
||||
).toEqual({ sort: 'votes2022', dir: 'asc' })
|
||||
).toEqual({ page: 1, sort: 'votes2022', dir: 'asc' })
|
||||
})
|
||||
|
||||
it('formats a compact active-filter summary', () => {
|
||||
expect(
|
||||
formatTerritoryActiveFiltersSummary({
|
||||
page: 1,
|
||||
q: 'chico',
|
||||
regions: ['Irecê', 'Velho Chico'],
|
||||
coverage: 'sem_assessor',
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import {
|
|||
filterTerritoryRows,
|
||||
flattenTerritoryRows,
|
||||
meanCaptureRateOfMunicipalities,
|
||||
selectTerritoryOverviewPage,
|
||||
sortTerritoryRows,
|
||||
type TerritoryMunicipalityInput,
|
||||
} from '@/utilities/territory/territoryOverview'
|
||||
|
|
@ -223,6 +224,48 @@ describe('filterTerritoryRows', () => {
|
|||
})
|
||||
})
|
||||
|
||||
describe('selectTerritoryOverviewPage (CL6a)', () => {
|
||||
const rows = computeTerritoryRollup(fixture)
|
||||
|
||||
it('paginates after sort so page=2 shows a different slice', () => {
|
||||
const sorted = sortTerritoryRows(rows, 'region', 'asc')
|
||||
const page1 = selectTerritoryOverviewPage(rows, {
|
||||
filters: {},
|
||||
sort: 'region',
|
||||
dir: 'asc',
|
||||
page: 1,
|
||||
pageSize: 2,
|
||||
})
|
||||
const page2 = selectTerritoryOverviewPage(rows, {
|
||||
filters: {},
|
||||
sort: 'region',
|
||||
dir: 'asc',
|
||||
page: 2,
|
||||
pageSize: 2,
|
||||
})
|
||||
|
||||
expect(page1.totalDocs).toBe(sorted.length)
|
||||
expect(page1.totalPages).toBe(2)
|
||||
expect(page1.rows.map((row) => row.region)).toEqual(sorted.slice(0, 2).map((row) => row.region))
|
||||
expect(page2.rows.map((row) => row.region)).toEqual(sorted.slice(2, 4).map((row) => row.region))
|
||||
expect(page1.rows[0].region).not.toBe(page2.rows[0].region)
|
||||
})
|
||||
|
||||
it('filters before paging and reports real totalPages', () => {
|
||||
const result = selectTerritoryOverviewPage(rows, {
|
||||
filters: { regions: ['Irecê'] },
|
||||
sort: 'pct',
|
||||
dir: 'desc',
|
||||
page: 1,
|
||||
pageSize: 25,
|
||||
})
|
||||
expect(result.totalDocs).toBe(1)
|
||||
expect(result.totalPages).toBe(1)
|
||||
expect(result.rows).toHaveLength(1)
|
||||
expect(result.rows[0].region).toBe('Irecê')
|
||||
})
|
||||
})
|
||||
|
||||
describe('computeTerritoryE12Rollup (MAUP)', () => {
|
||||
const rows = computeTerritoryRollup(fixture)
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue