mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-26 21:53:06 +00:00
CL5: Assessores CampaignTable + URL canónico + OpsListPage
Rewrite AdvisorsTable on CampaignTable with column picker, add resolveAdvisorListUrl (preserves criar=1), register assessores in CAMPAIGN_LIST_IDS/opsListRegistry, and wire LIST_UNIFIED factory shell. Closes #160 Co-authored-by: Francisco Solla <fsolla@users.noreply.github.com>
This commit is contained in:
parent
d909e3d28d
commit
76d6129e1e
14 changed files with 596 additions and 383 deletions
|
|
@ -4,7 +4,11 @@ Conteúdo movido do `AGENTS.md` em 2026-07-30 (fatiamento do paradigma de agente
|
|||
|
||||
---
|
||||
|
||||
<<<<<<< HEAD
|
||||
**Recently resolved (2026-08-01):** **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).
|
||||
=======
|
||||
**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).
|
||||
>>>>>>> 7ebf891 (CL5: Assessores CampaignTable + URL canónico + OpsListPage)
|
||||
|
||||
**Recently resolved (2026-08-01):** **CL3** (Issue #157) — tracer da factory de listas unificadas: `OpsListView` (slots) + `OpsListPage` (casca server); `/campanha/municipios` atrás de `LIST_UNIFIED` com paridade OFF. Plano: [`cl3-ops-list-page-municipios.md`](docs/plans/cl3-ops-list-page-municipios.md).
|
||||
|
||||
|
|
|
|||
|
|
@ -1,22 +1,30 @@
|
|||
# CL5 — Assessores: pré-work `CampaignTable` + URL canónico, depois factory
|
||||
|
||||
Status: rascunho
|
||||
Status: em execução
|
||||
Atualizado em: 2026-08-01
|
||||
Issue: #160
|
||||
Priority: P1
|
||||
Model: cursor-grok-4.5-medium
|
||||
Impeccable: B — mesma superfície `/campanha/assessores`, tabela reescrita no sistema da casa
|
||||
Appetite: ~2–3 dias eng
|
||||
Depends: CL3
|
||||
Depends: CL3 (done / in-prod — #157)
|
||||
Responsável: —
|
||||
|
||||
## Freshness audit (2026-08-01)
|
||||
|
||||
- CL3 (#157) `done`/`in-prod`; `OpsListPage`/`OpsListView` + flag `LIST_UNIFIED` existem; registry já tem slug `assessores` com `columnListId: null`, `sortModel: 'fixed'`, `canonicalRedirect: false`.
|
||||
- Paths citados existem (`AdvisorsTable`, `advisorData.ts`, `leadershipListUrl.ts` como padrão). Pasta `utilities/advisor/` ainda não existe — criar `advisorListUrl.ts` lá.
|
||||
- **Correção:** registry alvo `sortModel` permanece `'fixed'` (sort server sempre `name`; fases não adicionam sort por URL). Só `columnListId: 'assessores'` + `canonicalRedirect: true`. O SSOT `lista-unificada` que dizia `fixed → url` estava à frente do appetite.
|
||||
- **Param `criar=1`:** quick-create (B87) — `resolveAdvisorListUrl` deve preservá-lo no canónico (senão o redirect mata o draft).
|
||||
- Fase 3 “`status: 'v1'`”: registry actual não tem campo `status` — paridade = page delega a `OpsListPage` com `resolveListUnifiedEnabled()` (padrão CL3/municípios).
|
||||
|
||||
## Premissas
|
||||
|
||||
1. Hoje `AdvisorsTable` usa `ui/Table` cru (fora de `CampaignTable`) e o parse de URL não tem canonical redirect.
|
||||
2. O toggle “Editar nome e contato” permanece (produto não pediu mudança).
|
||||
3. Gate `unrestricted` (coordinator/candidate) mantido.
|
||||
|
||||
→ Corrija agora ou sigo com estas.
|
||||
→ Premissas confirmadas; sigo.
|
||||
|
||||
## Objetivos
|
||||
|
||||
|
|
@ -51,7 +59,7 @@ Componentes:
|
|||
| Toggle “Editar nome e contato” (`editing` state) | permanece no topo da tabela (fora das colunas — controla read vs edit das células de texto) |
|
||||
| `CampaignListEmptyState` / `CampaignListSheetProvider` | empty slot + provider envolvendo a tabela |
|
||||
|
||||
- **Registry:** adicionar `assessores` (`sortModel: 'url'`, `canonicalRedirect: true`, `columnListId: 'assessores'`).
|
||||
- **Registry:** actualizar `assessores` (`sortModel: 'fixed'`, `canonicalRedirect: true`, `columnListId: 'assessores'`).
|
||||
- **Column visibility:** registar `'assessores'` em `CAMPAIGN_LIST_IDS` ([`src/lib/campaignColumnVisibility.ts`](src/lib/campaignColumnVisibility.ts)); colunas novas nascem visíveis (regra: só ocultas persistidas).
|
||||
|
||||
## Fases verificáveis
|
||||
|
|
@ -61,8 +69,8 @@ Componentes:
|
|||
- **Quota:** ~0,5
|
||||
- **Entrega:** reescrita da tabela sem mexer em URL; paridade visual desktop/mobile.
|
||||
- **Aceite:**
|
||||
- [ ] mesmas linhas/colunas/ações visíveis
|
||||
- [ ] seletor de colunas funciona com cookie próprio
|
||||
- [x] mesmas linhas/colunas/ações visíveis
|
||||
- [x] seletor de colunas funciona com cookie próprio
|
||||
- **Verify:** `pnpm gate:fast` + e2e assessores
|
||||
- **Files:** `AdvisorsTable.tsx`, `src/lib/campaignColumnVisibility.ts`, page assessores
|
||||
- **Tamanho:** M
|
||||
|
|
@ -72,8 +80,8 @@ Componentes:
|
|||
- **Quota:** ~0,3
|
||||
- **Entrega:** `resolveAdvisorListUrl` + redirect na page; pins unit do parser.
|
||||
- **Aceite:**
|
||||
- [ ] params lixo redirecionam para a forma canónica
|
||||
- [ ] sort/filtros sobrevivem ao redirect
|
||||
- [x] params lixo redirecionam para a forma canónica
|
||||
- [x] sort/filtros sobrevivem ao redirect
|
||||
- **Verify:** `pnpm gate:fast` + pin unit `advisorListUrl`
|
||||
- **Files:** `advisorListUrl.ts`, `tests/unit/advisorListUrl.unit.spec.ts`, page
|
||||
- **Tamanho:** M
|
||||
|
|
@ -81,10 +89,10 @@ Componentes:
|
|||
### Fase 3 — Factory (CL5b)
|
||||
|
||||
- **Quota:** ~0,2
|
||||
- **Entrega:** registry `status: 'v1'`; page delega com flag ON.
|
||||
- **Entrega:** page delega a `OpsListPage` com `LIST_UNIFIED` (registry sem campo `status`).
|
||||
- **Aceite:** paridade com flag ON/OFF
|
||||
- **Verify:** `pnpm gate:fast` + e2e assessores com env
|
||||
- **Files:** registry, page
|
||||
- **Verify:** `pnpm gate:fast` + pin unit `opsListPage`
|
||||
- **Files:** registry (`columnListId`/`canonicalRedirect`), page
|
||||
- **Tamanho:** S
|
||||
|
||||
### Checkpoint
|
||||
|
|
|
|||
|
|
@ -46,7 +46,7 @@ Tabela canónica dos metadados v1. Planos filhos (**CL2+**) citam esta secção
|
|||
| `liderancas` | `/campanha/liderancas` | `staff` | `liderancas` | `false` | `url` | `true` |
|
||||
| `dobradinhas` | `/campanha/dobradinhas` | `staff` | `dobradinhas` | `false` | `url` | `true` |
|
||||
| `demandas` | `/campanha/demandas` | `staff` | `demandas` | `false` | `fixed` (`-createdAt`) | `false` |
|
||||
| `assessores` | `/campanha/assessores` | `unrestricted` | `null` → `'assessores'` em CL5a | `false` | `fixed` → `url` em CL5a | `false` → `true` em CL5a |
|
||||
| `assessores` | `/campanha/assessores` | `unrestricted` | `'assessores'` (CL5) | `false` | `fixed` (sort `name`) | `true` (CL5) |
|
||||
| `territorios` | `/campanha/territorios` | `noLeader` | `territorios` | `false` | `memory` → `url` em CL6a | `true` (sem `page` → com `page` em CL6a) |
|
||||
| `apoiadores` | `/campanha/apoiadores` | `staff` † | `apoiadores` | `false` | `url` | `true` |
|
||||
| `organizacoes` | `/campanha/organizacoes` | `staff` | `organizacoes` | `false` | `fixed` (`name`) | `false` |
|
||||
|
|
@ -55,7 +55,7 @@ Tabela canónica dos metadados v1. Planos filhos (**CL2+**) citam esta secção
|
|||
|
||||
`atividades` **não** entra em `opsListDomains` — cards + tabs (`ActivityList` / `ActivityCard`); rota intocada. Documentar a razão no comentário do registry (Pass 2 D5).
|
||||
|
||||
`CampaignListId` hoje (`CAMPAIGN_LIST_IDS`): `municipios`, `liderancas`, `dobradinhas`, `organizacoes`, `demandas`, `apoiadores`, `territorios`. **Falta `'assessores'`** — entra em CL5a; até lá `columnListId: null`.
|
||||
`CampaignListId` (`CAMPAIGN_LIST_IDS`): `municipios`, `liderancas`, `dobradinhas`, `organizacoes`, `demandas`, `apoiadores`, `territorios`, `assessores` (CL5).
|
||||
|
||||
Campos de implementação (CL2), fora desta tabela: `layout: 'table'`, tipagem `OpsListDomainMeta` — sem `status: 'excluded'`.
|
||||
|
||||
|
|
@ -84,7 +84,7 @@ Estado **hoje** (não o contrato-alvo). Para sortModel / canonicalRedirect / col
|
|||
| `/campanha/liderancas` | table | `resolveLeadershipListUrl` | server | `CampaignTable` |
|
||||
| `/campanha/dobradinhas` | table | `resolveStateDeputyListUrl` | server | `CampaignTable` |
|
||||
| `/campanha/demandas` | table | `parseDemandListParams` (sem resolve canónico) | server | `CampaignTable` |
|
||||
| `/campanha/assessores` | table (custom) | `parseAdvisorListParams` (sem redirect) | server | **`AdvisorsTable`** (`ui/Table` cru) — CL5a |
|
||||
| `/campanha/assessores` | table | `resolveAdvisorListUrl` (CL5) | server | `AdvisorsTable` → `CampaignTable` (CL5) |
|
||||
| `/campanha/territorios` | table | `resolveTerritoryListUrl` (sem `page`); sort/filter in-memory | **fake** (`page=1`/`totalPages=1`) — CL6a | `CampaignTable` |
|
||||
| `/campanha/apoiadores` | table | resolve via `supporterUi` | server | `CampaignTable` |
|
||||
| `/campanha/organizacoes` | table | `parseOrganizationListParams` (sem resolve canónico) | server | `CampaignTable` |
|
||||
|
|
@ -140,7 +140,7 @@ Números GitHub (#156–#162) **não** seguem a ordem de execução (CL5=#160, C
|
|||
| lideranças | `utilities/leadership/leadershipListUrl.ts` | `leadership*Data` | `components/campaign/leadership/` |
|
||||
| dobradinhas | `utilities/stateDeputyListUrl.ts` | state-deputy loaders | `components/campaign/stateDeputy/` |
|
||||
| demandas | `utilities/campaignDemandData.ts` (`parseDemandListParams`) | idem | `components/campaign/demand/` |
|
||||
| assessores | `utilities/advisorData.ts` (`parseAdvisorListParams`) → **CL5a:** `utilities/advisor/advisorListUrl.ts` | `loadAdvisorListPageData` | `components/campaign/advisor/AdvisorsTable.tsx` → `CampaignTable` |
|
||||
| assessores | `utilities/advisor/advisorListUrl.ts` | `loadAdvisorListPageData` | `components/campaign/advisor/AdvisorsTable.tsx` (`CampaignTable`) |
|
||||
| territórios | `utilities/territory/territoryListUrl.ts` | `loadTerritoryOverview.ts` + `territoryOverview.ts` (filter/sort) | `components/campaign/territory/` |
|
||||
| apoiadores | `utilities/supporter/supporterUi.ts` | `supporter/*Data` | `components/campaign/supporter/` |
|
||||
| organizações | `utilities/organizationData.ts` (`parseOrganizationListParams`) | idem | `components/campaign/organization/` |
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { ADVISOR_QUICK_CREATE_PARAM } from '@/lib/campaignAdvisorQuickActions'
|
||||
import { CAMPAIGN_ADVISORS_HOME } from '@/lib/campaignPaths'
|
||||
import config from '@payload-config'
|
||||
import { redirect } from 'next/navigation'
|
||||
import { getPayload } from 'payload'
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
import { AdvisorsTable } from '@/components/campaign/advisor/AdvisorsTable'
|
||||
import { CampaignListFooter } from '@/components/campaign/shared/CampaignListFooter'
|
||||
|
|
@ -10,13 +10,13 @@ import {
|
|||
CampaignListResults,
|
||||
} from '@/components/campaign/shared/CampaignListPending'
|
||||
import { CampaignSearchForm } from '@/components/campaign/shared/CampaignSearchForm'
|
||||
import { OpsListPage } from '@/components/campaign/shared/OpsListPage'
|
||||
import { CampaignPageShell } from '@/components/campaign/shell/CampaignPageShell'
|
||||
import {
|
||||
advisorListHrefForPage,
|
||||
loadAdvisorListPageData,
|
||||
parseAdvisorListParams,
|
||||
} from '@/utilities/advisorData'
|
||||
import { firstValue } from '@/utilities/campaignListUrl'
|
||||
import { CAMPAIGN_ADVISORS_HOME } from '@/lib/campaignPaths'
|
||||
import { resolveListUnifiedEnabled } from '@/lib/opsListRegistry/opsListFlag'
|
||||
import { advisorListHrefForPage, resolveAdvisorListUrl } from '@/utilities/advisor/advisorListUrl'
|
||||
import { loadAdvisorListPageData } from '@/utilities/advisorData'
|
||||
import { readCampaignColumnVisibility } from '@/utilities/campaignColumnVisibilityCookie'
|
||||
import { requireCampaignPageActor } from '@/utilities/campaignPageActor'
|
||||
import { loadMunicipalityPortfolioIndex } from '@/utilities/municipality/municipalityPortfolioIndex'
|
||||
import {
|
||||
|
|
@ -32,18 +32,77 @@ type AdvisorsPageProps = {
|
|||
|
||||
export default async function AdvisorsPage({ searchParams }: AdvisorsPageProps) {
|
||||
const rawSearchParams = await searchParams
|
||||
const canonicalUrl = resolveAdvisorListUrl(rawSearchParams)
|
||||
if (canonicalUrl.redirectHref) redirect(canonicalUrl.redirectHref)
|
||||
|
||||
const [, payload] = await Promise.all([
|
||||
requireCampaignPageActor({ gate: 'unrestricted' }),
|
||||
getPayload({ config }),
|
||||
])
|
||||
|
||||
const state = parseAdvisorListParams(rawSearchParams)
|
||||
const autoCreateDraft = firstValue(rawSearchParams[ADVISOR_QUICK_CREATE_PARAM]) === '1'
|
||||
const [{ rows, totalDocs, totalPages }, municipalityIndex] = await Promise.all([
|
||||
loadAdvisorListPageData(payload, state),
|
||||
const [{ rows, totalDocs, totalPages }, municipalityIndex, columnVisibility] = await Promise.all([
|
||||
loadAdvisorListPageData(payload, canonicalUrl.state),
|
||||
loadMunicipalityPortfolioIndex(),
|
||||
readCampaignColumnVisibility('assessores'),
|
||||
])
|
||||
|
||||
const resolvedUrl = resolveAdvisorListUrl(rawSearchParams, totalPages)
|
||||
if (resolvedUrl.redirectHref) redirect(resolvedUrl.redirectHref)
|
||||
const { state } = resolvedUrl
|
||||
|
||||
const tableNode = (
|
||||
<AdvisorsTable
|
||||
rows={rows}
|
||||
municipalityIndex={municipalityIndex}
|
||||
hasQuery={Boolean(state.q)}
|
||||
columnVisibility={columnVisibility}
|
||||
updateProfileAction={updateAdvisorProfileFormAction}
|
||||
municipalitiesAction={setAdvisorMunicipalitiesFormAction}
|
||||
createAction={createAdvisorFormAction}
|
||||
passwordResetAction={sendAdvisorPasswordResetFormAction}
|
||||
autoCreateDraft={Boolean(state.autoCreateDraft)}
|
||||
/>
|
||||
)
|
||||
|
||||
const footerNode =
|
||||
totalDocs > 0 ? (
|
||||
<CampaignListFooter
|
||||
totalDocs={totalDocs}
|
||||
singular="assessor"
|
||||
plural="assessores"
|
||||
page={state.page}
|
||||
totalPages={totalPages}
|
||||
hrefForPage={(page) => advisorListHrefForPage(state, page)}
|
||||
/>
|
||||
) : null
|
||||
|
||||
const toolbar = (
|
||||
<CampaignSearchForm
|
||||
ariaLabel="Buscar assessor por nome ou e-mail"
|
||||
placeholder="Buscar por nome ou e-mail…"
|
||||
initialQuery={state.q ?? ''}
|
||||
basePath={CAMPAIGN_ADVISORS_HOME}
|
||||
/>
|
||||
)
|
||||
|
||||
const main: ReactNode = resolveListUnifiedEnabled() ? (
|
||||
<OpsListPage
|
||||
overview={null}
|
||||
toolbar={toolbar}
|
||||
table={tableNode}
|
||||
empty={null}
|
||||
footer={footerNode}
|
||||
/>
|
||||
) : (
|
||||
<CampaignListPendingBoundary>
|
||||
{toolbar}
|
||||
<CampaignListResults>
|
||||
{tableNode}
|
||||
{footerNode}
|
||||
</CampaignListResults>
|
||||
</CampaignListPendingBoundary>
|
||||
)
|
||||
|
||||
return (
|
||||
<CampaignPageShell>
|
||||
<header className="flex flex-col gap-2">
|
||||
|
|
@ -54,38 +113,7 @@ export default async function AdvisorsPage({ searchParams }: AdvisorsPageProps)
|
|||
</p>
|
||||
</header>
|
||||
|
||||
<CampaignListPendingBoundary>
|
||||
<CampaignSearchForm
|
||||
ariaLabel="Buscar assessor por nome ou e-mail"
|
||||
placeholder="Buscar por nome ou e-mail…"
|
||||
initialQuery={state.q ?? ''}
|
||||
basePath={CAMPAIGN_ADVISORS_HOME}
|
||||
/>
|
||||
|
||||
<CampaignListResults>
|
||||
<AdvisorsTable
|
||||
rows={rows}
|
||||
municipalityIndex={municipalityIndex}
|
||||
hasQuery={Boolean(state.q)}
|
||||
updateProfileAction={updateAdvisorProfileFormAction}
|
||||
municipalitiesAction={setAdvisorMunicipalitiesFormAction}
|
||||
createAction={createAdvisorFormAction}
|
||||
passwordResetAction={sendAdvisorPasswordResetFormAction}
|
||||
autoCreateDraft={autoCreateDraft}
|
||||
/>
|
||||
|
||||
{totalDocs > 0 ? (
|
||||
<CampaignListFooter
|
||||
totalDocs={totalDocs}
|
||||
singular="assessor"
|
||||
plural="assessores"
|
||||
page={state.page}
|
||||
totalPages={totalPages}
|
||||
hrefForPage={(page) => advisorListHrefForPage(state, page)}
|
||||
/>
|
||||
) : null}
|
||||
</CampaignListResults>
|
||||
</CampaignListPendingBoundary>
|
||||
{main}
|
||||
</CampaignPageShell>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,18 +22,16 @@ import {
|
|||
} from '@/components/campaign/shared/CampaignCopyableCell'
|
||||
import { CampaignListEmptyState } from '@/components/campaign/shared/CampaignListEmptyState'
|
||||
import { CampaignListSheetProvider } from '@/components/campaign/shared/CampaignListSheetHost'
|
||||
import {
|
||||
CampaignTable,
|
||||
CampaignTableHead,
|
||||
type CampaignTableColumn,
|
||||
} from '@/components/campaign/shared/CampaignTable'
|
||||
import { MunicipalityPortfolioCell } from '@/components/campaign/shared/MunicipalityPortfolioCell'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Spinner } from '@/components/ui/Spinner'
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/Table'
|
||||
import type { CampaignColumnVisibility } from '@/lib/campaignColumnVisibility'
|
||||
import { campaignInlineInputClassName } from '@/lib/campaignInlineInput'
|
||||
import type { MunicipalityPortfolioIndexEntry } from '@/lib/municipalityPortfolio'
|
||||
import {
|
||||
|
|
@ -53,10 +51,15 @@ type DraftAdvisor = {
|
|||
municipalityIds: number[]
|
||||
}
|
||||
|
||||
type AdvisorTableRow =
|
||||
| { kind: 'draft'; draft: DraftAdvisor }
|
||||
| { kind: 'advisor'; advisor: AdvisorRowViewModel }
|
||||
|
||||
type AdvisorsTableProps = {
|
||||
rows: AdvisorRowViewModel[]
|
||||
municipalityIndex: MunicipalityPortfolioIndexEntry[]
|
||||
hasQuery: boolean
|
||||
columnVisibility: CampaignColumnVisibility
|
||||
updateProfileAction: (
|
||||
state: CampaignFormActionState,
|
||||
formData: FormData,
|
||||
|
|
@ -92,6 +95,7 @@ export const AdvisorsTable = ({
|
|||
rows,
|
||||
municipalityIndex,
|
||||
hasQuery,
|
||||
columnVisibility,
|
||||
updateProfileAction,
|
||||
municipalitiesAction,
|
||||
createAction,
|
||||
|
|
@ -159,7 +163,256 @@ export const AdvisorsTable = ({
|
|||
})
|
||||
}
|
||||
|
||||
const showEmpty = rows.length === 0 && !draft
|
||||
const tableRows: AdvisorTableRow[] = [
|
||||
...(draft ? [{ kind: 'draft' as const, draft }] : []),
|
||||
...rows.map((advisor) => ({ kind: 'advisor' as const, advisor })),
|
||||
]
|
||||
|
||||
const columns: Array<CampaignTableColumn<AdvisorTableRow>> = [
|
||||
{
|
||||
id: 'name',
|
||||
label: 'Nome',
|
||||
mandatory: true,
|
||||
cell: (row) => {
|
||||
if (row.kind === 'draft') {
|
||||
return (
|
||||
<Input
|
||||
value={row.draft.name}
|
||||
onChange={(event) => {
|
||||
const name = event.currentTarget.value
|
||||
setDraft((current) => (current ? { ...current, name } : current))
|
||||
}}
|
||||
placeholder="Nome"
|
||||
aria-label="Nome do novo assessor"
|
||||
className={campaignInlineInputClassName}
|
||||
autoFocus
|
||||
/>
|
||||
)
|
||||
}
|
||||
const { advisor } = row
|
||||
if (editing) {
|
||||
return (
|
||||
<AdvisorDebouncedTextCell
|
||||
advisorId={advisor.id}
|
||||
field="name"
|
||||
defaultValue={advisor.name}
|
||||
ariaLabel={`Nome de ${advisor.name}`}
|
||||
formAction={updateProfileAction}
|
||||
/>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<Link
|
||||
href={`/campanha/assessores/${advisor.id}`}
|
||||
className={cn(
|
||||
campaignReadCellClassName,
|
||||
'font-medium text-primary underline-offset-4 hover:underline',
|
||||
)}
|
||||
>
|
||||
<span className="truncate">{advisor.name}</span>
|
||||
</Link>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'email',
|
||||
label: 'E-mail',
|
||||
cell: (row) => {
|
||||
if (row.kind === 'draft') {
|
||||
return (
|
||||
<Input
|
||||
type="email"
|
||||
value={row.draft.email}
|
||||
onChange={(event) => {
|
||||
const email = event.currentTarget.value
|
||||
setDraft((current) => (current ? { ...current, email } : current))
|
||||
}}
|
||||
placeholder="E-mail"
|
||||
aria-label="E-mail do novo assessor"
|
||||
className={campaignInlineInputClassName}
|
||||
/>
|
||||
)
|
||||
}
|
||||
const { advisor } = row
|
||||
if (editing) {
|
||||
return (
|
||||
<AdvisorDebouncedTextCell
|
||||
advisorId={advisor.id}
|
||||
field="email"
|
||||
type="email"
|
||||
defaultValue={advisor.email ?? ''}
|
||||
placeholder="E-mail"
|
||||
ariaLabel={`E-mail de ${advisor.name}`}
|
||||
placeholderEmailFallback={advisor.email}
|
||||
formAction={updateProfileAction}
|
||||
/>
|
||||
)
|
||||
}
|
||||
return <CampaignCopyableCell value={displayEmail(advisor.email)} label="E-mail" />
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'phone',
|
||||
label: 'Celular',
|
||||
cell: (row) => {
|
||||
if (row.kind === 'draft') {
|
||||
return (
|
||||
<Input
|
||||
type="tel"
|
||||
inputMode="numeric"
|
||||
value={row.draft.phone}
|
||||
onChange={(event) => {
|
||||
const phone = formatBrazilianPhoneInput(
|
||||
sanitizeBrazilianPhoneInput(event.currentTarget.value),
|
||||
)
|
||||
setDraft((current) => (current ? { ...current, phone } : current))
|
||||
}}
|
||||
placeholder="Celular"
|
||||
aria-label="Celular do novo assessor"
|
||||
className={campaignInlineInputClassName}
|
||||
/>
|
||||
)
|
||||
}
|
||||
const { advisor } = row
|
||||
if (editing) {
|
||||
return (
|
||||
<AdvisorDebouncedTextCell
|
||||
advisorId={advisor.id}
|
||||
field="phone"
|
||||
type="tel"
|
||||
defaultValue={advisor.phone ? formatBrazilianPhoneInput(advisor.phone) : ''}
|
||||
placeholder="Celular"
|
||||
ariaLabel={`Celular de ${advisor.name}`}
|
||||
formAction={updateProfileAction}
|
||||
/>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<CampaignCopyableCell
|
||||
value={advisor.phone}
|
||||
label="Celular"
|
||||
displayValue={advisor.phone ? formatBrazilianPhoneInput(advisor.phone) : undefined}
|
||||
className="tabular-nums"
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'municipalities',
|
||||
label: 'Municípios',
|
||||
cell: (row) => {
|
||||
if (row.kind === 'draft') {
|
||||
return (
|
||||
<MunicipalityPortfolioCell
|
||||
ownerId={null}
|
||||
ownerName={row.draft.name.trim() || 'um novo assessor'}
|
||||
municipalityIds={row.draft.municipalityIds}
|
||||
municipalityIndex={municipalityIndex}
|
||||
draft
|
||||
onDraftChange={(municipalityIds) =>
|
||||
setDraft((current) => (current ? { ...current, municipalityIds } : current))
|
||||
}
|
||||
commitAction={municipalitiesAction}
|
||||
drawerTitle="Carteira do assessor"
|
||||
updateErrorMessage="Não foi possível atualizar a carteira."
|
||||
/>
|
||||
)
|
||||
}
|
||||
const { advisor } = row
|
||||
return (
|
||||
<MunicipalityPortfolioCell
|
||||
ownerId={advisor.id}
|
||||
ownerName={advisor.name}
|
||||
municipalityIds={municipalityIdsByAdvisor.get(advisor.id) ?? []}
|
||||
municipalityIndex={municipalityIndex}
|
||||
commitAction={municipalitiesAction}
|
||||
drawerTitle="Carteira do assessor"
|
||||
updateErrorMessage="Não foi possível atualizar a carteira."
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'actions',
|
||||
label: 'Ações',
|
||||
head: (
|
||||
<CampaignTableHead align="right">
|
||||
<span className="sr-only">Ações</span>
|
||||
</CampaignTableHead>
|
||||
),
|
||||
cellClassName: 'text-right',
|
||||
cell: (row) => {
|
||||
if (row.kind === 'draft') {
|
||||
return (
|
||||
<div className="flex justify-end gap-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-10"
|
||||
aria-label="Cancelar novo assessor"
|
||||
disabled={isCreating}
|
||||
onClick={cancelDraft}
|
||||
>
|
||||
<XIcon className="size-4" aria-hidden="true" />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="icon"
|
||||
className="size-10"
|
||||
aria-label="Salvar novo assessor"
|
||||
disabled={isCreating}
|
||||
onClick={saveDraft}
|
||||
>
|
||||
{isCreating ? (
|
||||
<Spinner className="size-4" aria-hidden="true" />
|
||||
) : (
|
||||
<SaveIcon className="size-4" aria-hidden="true" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
const { advisor } = row
|
||||
const whatsAppHref = whatsAppHrefForPhone(advisor.phone)
|
||||
const emailShown = displayEmail(advisor.email)
|
||||
return (
|
||||
<div className="flex justify-end gap-1">
|
||||
{whatsAppHref ? (
|
||||
<Button asChild variant="ghost" size="icon" className="size-10">
|
||||
<a
|
||||
href={whatsAppHref}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
aria-label={`Enviar WhatsApp para ${advisor.name}`}
|
||||
>
|
||||
<MessageCircleIcon className="size-4" aria-hidden="true" />
|
||||
</a>
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-10"
|
||||
disabled
|
||||
aria-label={`WhatsApp indisponível — ${advisor.name} sem celular`}
|
||||
>
|
||||
<MessageCircleIcon className="size-4" aria-hidden="true" />
|
||||
</Button>
|
||||
)}
|
||||
<AdvisorPasswordResetButton
|
||||
advisorId={advisor.id}
|
||||
disabled={!emailShown}
|
||||
layout="icon"
|
||||
accessibleName={`Enviar link de senha para ${advisor.name}`}
|
||||
formAction={passwordResetAction}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
// One shared Drawer for the portfolio chip cells on coarse pointers
|
||||
|
|
@ -188,248 +441,31 @@ export const AdvisorsTable = ({
|
|||
</Button>
|
||||
</div>
|
||||
|
||||
{showEmpty ? (
|
||||
<CampaignListEmptyState
|
||||
icon={hasQuery ? SearchXIcon : UserCogIcon}
|
||||
title={hasQuery ? 'Nenhum assessor encontrado' : 'Nenhum assessor cadastrado'}
|
||||
description={
|
||||
hasQuery
|
||||
? 'Ajuste a busca ou limpe o filtro para ver todos.'
|
||||
: 'Ative a edição e crie a conta na tabela.'
|
||||
}
|
||||
>
|
||||
{!hasQuery ? (
|
||||
<Button type="button" className="min-h-11" onClick={startDraft}>
|
||||
<PlusIcon data-icon="inline-start" aria-hidden="true" />
|
||||
Novo assessor
|
||||
</Button>
|
||||
) : null}
|
||||
</CampaignListEmptyState>
|
||||
) : (
|
||||
<div className="overflow-x-auto rounded-xl border">
|
||||
<Table className="min-w-[56rem] table-fixed">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-[20%]">Nome</TableHead>
|
||||
<TableHead className="w-[24%]">E-mail</TableHead>
|
||||
<TableHead className="w-[14%]">Celular</TableHead>
|
||||
<TableHead>Municípios</TableHead>
|
||||
<TableHead className="w-28 text-right">
|
||||
<span className="sr-only">Ações</span>
|
||||
</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{draft ? (
|
||||
<TableRow className="bg-muted/20">
|
||||
<TableCell>
|
||||
<Input
|
||||
value={draft.name}
|
||||
onChange={(event) => {
|
||||
const name = event.currentTarget.value
|
||||
setDraft((current) => (current ? { ...current, name } : current))
|
||||
}}
|
||||
placeholder="Nome"
|
||||
aria-label="Nome do novo assessor"
|
||||
className={campaignInlineInputClassName}
|
||||
autoFocus
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Input
|
||||
type="email"
|
||||
value={draft.email}
|
||||
onChange={(event) => {
|
||||
const email = event.currentTarget.value
|
||||
setDraft((current) => (current ? { ...current, email } : current))
|
||||
}}
|
||||
placeholder="E-mail"
|
||||
aria-label="E-mail do novo assessor"
|
||||
className={campaignInlineInputClassName}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Input
|
||||
type="tel"
|
||||
inputMode="numeric"
|
||||
value={draft.phone}
|
||||
onChange={(event) => {
|
||||
const phone = formatBrazilianPhoneInput(
|
||||
sanitizeBrazilianPhoneInput(event.currentTarget.value),
|
||||
)
|
||||
setDraft((current) => (current ? { ...current, phone } : current))
|
||||
}}
|
||||
placeholder="Celular"
|
||||
aria-label="Celular do novo assessor"
|
||||
className={campaignInlineInputClassName}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<MunicipalityPortfolioCell
|
||||
ownerId={null}
|
||||
ownerName={draft.name.trim() || 'um novo assessor'}
|
||||
municipalityIds={draft.municipalityIds}
|
||||
municipalityIndex={municipalityIndex}
|
||||
draft
|
||||
onDraftChange={(municipalityIds) =>
|
||||
setDraft((current) =>
|
||||
current ? { ...current, municipalityIds } : current,
|
||||
)
|
||||
}
|
||||
commitAction={municipalitiesAction}
|
||||
drawerTitle="Carteira do assessor"
|
||||
updateErrorMessage="Não foi possível atualizar a carteira."
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<div className="flex justify-end gap-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-10"
|
||||
aria-label="Cancelar novo assessor"
|
||||
disabled={isCreating}
|
||||
onClick={cancelDraft}
|
||||
>
|
||||
<XIcon className="size-4" aria-hidden="true" />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="icon"
|
||||
className="size-10"
|
||||
aria-label="Salvar novo assessor"
|
||||
disabled={isCreating}
|
||||
onClick={saveDraft}
|
||||
>
|
||||
{isCreating ? (
|
||||
<Spinner className="size-4" aria-hidden="true" />
|
||||
) : (
|
||||
<SaveIcon className="size-4" aria-hidden="true" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : null}
|
||||
|
||||
{rows.map((row) => {
|
||||
const whatsAppHref = whatsAppHrefForPhone(row.phone)
|
||||
const emailShown = displayEmail(row.email)
|
||||
|
||||
return (
|
||||
<TableRow key={row.id}>
|
||||
<TableCell>
|
||||
{editing ? (
|
||||
<AdvisorDebouncedTextCell
|
||||
advisorId={row.id}
|
||||
field="name"
|
||||
defaultValue={row.name}
|
||||
ariaLabel={`Nome de ${row.name}`}
|
||||
formAction={updateProfileAction}
|
||||
/>
|
||||
) : (
|
||||
<Link
|
||||
href={`/campanha/assessores/${row.id}`}
|
||||
className={cn(
|
||||
campaignReadCellClassName,
|
||||
'font-medium text-primary underline-offset-4 hover:underline',
|
||||
)}
|
||||
>
|
||||
<span className="truncate">{row.name}</span>
|
||||
</Link>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{editing ? (
|
||||
<AdvisorDebouncedTextCell
|
||||
advisorId={row.id}
|
||||
field="email"
|
||||
type="email"
|
||||
defaultValue={row.email ?? ''}
|
||||
placeholder="E-mail"
|
||||
ariaLabel={`E-mail de ${row.name}`}
|
||||
placeholderEmailFallback={row.email}
|
||||
formAction={updateProfileAction}
|
||||
/>
|
||||
) : (
|
||||
<CampaignCopyableCell value={emailShown} label="E-mail" />
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{editing ? (
|
||||
<AdvisorDebouncedTextCell
|
||||
advisorId={row.id}
|
||||
field="phone"
|
||||
type="tel"
|
||||
defaultValue={row.phone ? formatBrazilianPhoneInput(row.phone) : ''}
|
||||
placeholder="Celular"
|
||||
ariaLabel={`Celular de ${row.name}`}
|
||||
formAction={updateProfileAction}
|
||||
/>
|
||||
) : (
|
||||
<CampaignCopyableCell
|
||||
value={row.phone}
|
||||
label="Celular"
|
||||
displayValue={
|
||||
row.phone ? formatBrazilianPhoneInput(row.phone) : undefined
|
||||
}
|
||||
className="tabular-nums"
|
||||
/>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<MunicipalityPortfolioCell
|
||||
ownerId={row.id}
|
||||
ownerName={row.name}
|
||||
municipalityIds={municipalityIdsByAdvisor.get(row.id) ?? []}
|
||||
municipalityIndex={municipalityIndex}
|
||||
commitAction={municipalitiesAction}
|
||||
drawerTitle="Carteira do assessor"
|
||||
updateErrorMessage="Não foi possível atualizar a carteira."
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<div className="flex justify-end gap-1">
|
||||
{whatsAppHref ? (
|
||||
<Button asChild variant="ghost" size="icon" className="size-10">
|
||||
<a
|
||||
href={whatsAppHref}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
aria-label={`Enviar WhatsApp para ${row.name}`}
|
||||
>
|
||||
<MessageCircleIcon className="size-4" aria-hidden="true" />
|
||||
</a>
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-10"
|
||||
disabled
|
||||
aria-label={`WhatsApp indisponível — ${row.name} sem celular`}
|
||||
>
|
||||
<MessageCircleIcon className="size-4" aria-hidden="true" />
|
||||
</Button>
|
||||
)}
|
||||
<AdvisorPasswordResetButton
|
||||
advisorId={row.id}
|
||||
disabled={!emailShown}
|
||||
layout="icon"
|
||||
accessibleName={`Enviar link de senha para ${row.name}`}
|
||||
formAction={passwordResetAction}
|
||||
/>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)}
|
||||
<CampaignTable
|
||||
columns={columns}
|
||||
columnVisibility={columnVisibility}
|
||||
rows={tableRows}
|
||||
rowKey={(row) => (row.kind === 'draft' ? 'draft' : row.advisor.id)}
|
||||
rowClassName={(row) => (row.kind === 'draft' ? 'bg-muted/20' : undefined)}
|
||||
empty={
|
||||
<CampaignListEmptyState
|
||||
icon={hasQuery ? SearchXIcon : UserCogIcon}
|
||||
title={hasQuery ? 'Nenhum assessor encontrado' : 'Nenhum assessor cadastrado'}
|
||||
description={
|
||||
hasQuery
|
||||
? 'Ajuste a busca ou limpe o filtro para ver todos.'
|
||||
: 'Ative a edição e crie a conta na tabela.'
|
||||
}
|
||||
>
|
||||
{!hasQuery ? (
|
||||
<Button type="button" className="min-h-11" onClick={startDraft}>
|
||||
<PlusIcon data-icon="inline-start" aria-hidden="true" />
|
||||
Novo assessor
|
||||
</Button>
|
||||
) : null}
|
||||
</CampaignListEmptyState>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</CampaignListSheetProvider>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ const CAMPAIGN_LIST_IDS = [
|
|||
'demandas',
|
||||
'apoiadores',
|
||||
'territorios',
|
||||
'assessores',
|
||||
] as const
|
||||
|
||||
export type CampaignListId = (typeof CAMPAIGN_LIST_IDS)[number]
|
||||
|
|
|
|||
|
|
@ -80,10 +80,10 @@ export const opsListRegistry: Record<OpsListDomainId, OpsListDomainMeta> = {
|
|||
id: 'assessores',
|
||||
routePath: '/campanha/assessores',
|
||||
gate: 'unrestricted',
|
||||
columnListId: null,
|
||||
columnListId: 'assessores',
|
||||
savedFilters: false,
|
||||
sortModel: 'fixed',
|
||||
canonicalRedirect: false,
|
||||
canonicalRedirect: true,
|
||||
layout: 'table',
|
||||
},
|
||||
territorios: {
|
||||
|
|
|
|||
92
src/utilities/advisor/advisorListUrl.ts
Normal file
92
src/utilities/advisor/advisorListUrl.ts
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
/**
|
||||
* Advisor list URL contract: state, param parse/canonicalize and hrefs.
|
||||
* Own module (same shape as `leadershipListUrl`) — list params only; loaders
|
||||
* stay in `advisorData.ts`.
|
||||
*/
|
||||
import { ADVISOR_QUICK_CREATE_PARAM } from '@/lib/campaignAdvisorQuickActions'
|
||||
import { CAMPAIGN_ADVISORS_HOME } from '@/lib/campaignPaths'
|
||||
import {
|
||||
buildListHref,
|
||||
firstValue,
|
||||
normalizedText,
|
||||
resolveListUrl,
|
||||
strictDecimalInteger,
|
||||
type RawSearchParams,
|
||||
} from '@/utilities/campaignListUrl'
|
||||
|
||||
export type AdvisorListState = {
|
||||
page: number
|
||||
q?: string
|
||||
/** B87 quick-create — preserved through canonical redirect when `criar=1`. */
|
||||
autoCreateDraft?: boolean
|
||||
}
|
||||
|
||||
export type AdvisorListSearchParams = RawSearchParams
|
||||
|
||||
const advisorListParamNames = ['q', 'page', ADVISOR_QUICK_CREATE_PARAM] as const
|
||||
const advisorListParamNameSet = new Set<string>(advisorListParamNames)
|
||||
|
||||
export const parseAdvisorListParams = (params: AdvisorListSearchParams): AdvisorListState => {
|
||||
const q = normalizedText(firstValue(params.q))
|
||||
const page = strictDecimalInteger(firstValue(params.page)) ?? 1
|
||||
const autoCreateDraft = firstValue(params[ADVISOR_QUICK_CREATE_PARAM]) === '1'
|
||||
|
||||
return {
|
||||
page,
|
||||
...(q ? { q } : {}),
|
||||
...(autoCreateDraft ? { autoCreateDraft: true } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export const advisorListStateToRawParams = (
|
||||
state: AdvisorListState,
|
||||
page = state.page,
|
||||
): AdvisorListSearchParams => ({
|
||||
page: String(page),
|
||||
q: state.q,
|
||||
...(state.autoCreateDraft ? { [ADVISOR_QUICK_CREATE_PARAM]: '1' } : {}),
|
||||
})
|
||||
|
||||
export const serializeCanonicalAdvisorListSearchParams = (
|
||||
canonicalState: AdvisorListState,
|
||||
): URLSearchParams => {
|
||||
const params = new URLSearchParams()
|
||||
if (canonicalState.q) params.set('q', canonicalState.q)
|
||||
if (canonicalState.autoCreateDraft) params.set(ADVISOR_QUICK_CREATE_PARAM, '1')
|
||||
if (canonicalState.page > 1) params.set('page', String(canonicalState.page))
|
||||
return params
|
||||
}
|
||||
|
||||
const buildAdvisorListSearchParams = (
|
||||
state: AdvisorListState,
|
||||
page = state.page,
|
||||
): URLSearchParams =>
|
||||
serializeCanonicalAdvisorListSearchParams(
|
||||
parseAdvisorListParams(advisorListStateToRawParams(state, page)),
|
||||
)
|
||||
|
||||
/** Pagination / filter hrefs drop the one-shot quick-create flag. */
|
||||
export const advisorListHrefForPage = (state: AdvisorListState, page: number): string =>
|
||||
buildListHref(
|
||||
{ page: state.page, ...(state.q ? { q: state.q } : {}) },
|
||||
buildAdvisorListSearchParams,
|
||||
CAMPAIGN_ADVISORS_HOME,
|
||||
page,
|
||||
)
|
||||
|
||||
export const resolveAdvisorListUrl = (
|
||||
params: AdvisorListSearchParams,
|
||||
totalPages?: number,
|
||||
): {
|
||||
state: AdvisorListState
|
||||
href: string
|
||||
redirectHref?: string
|
||||
} =>
|
||||
resolveListUrl({
|
||||
params,
|
||||
paramNameSet: advisorListParamNameSet,
|
||||
parse: parseAdvisorListParams,
|
||||
buildSearchParams: (state) => buildAdvisorListSearchParams(state),
|
||||
basePath: CAMPAIGN_ADVISORS_HOME,
|
||||
totalPages,
|
||||
})
|
||||
|
|
@ -3,21 +3,11 @@ import 'server-only'
|
|||
import type { Payload } from 'payload'
|
||||
|
||||
import { relationshipId } from '@/lib/relationship'
|
||||
import {
|
||||
buildListHref,
|
||||
firstValue,
|
||||
normalizedText,
|
||||
strictDecimalInteger,
|
||||
type RawSearchParams,
|
||||
} from '@/utilities/campaignListUrl'
|
||||
import type { AdvisorListState } from '@/utilities/advisor/advisorListUrl'
|
||||
|
||||
export type { AdvisorListState } from '@/utilities/advisor/advisorListUrl'
|
||||
|
||||
const advisorPageSize = 25
|
||||
const advisorListBasePath = '/campanha/assessores'
|
||||
|
||||
export type AdvisorListState = {
|
||||
page: number
|
||||
q?: string
|
||||
}
|
||||
|
||||
type AdvisorMunicipalityViewModel = {
|
||||
id: number
|
||||
|
|
@ -45,26 +35,6 @@ export type AdvisorDetailViewModel = AdvisorAccountViewModel & {
|
|||
municipalities: AdvisorMunicipalityViewModel[]
|
||||
}
|
||||
|
||||
export const parseAdvisorListParams = (searchParams: RawSearchParams): AdvisorListState => {
|
||||
const q = normalizedText(firstValue(searchParams.q))
|
||||
const page = strictDecimalInteger(firstValue(searchParams.page)) ?? 1
|
||||
|
||||
return {
|
||||
page,
|
||||
...(q ? { q } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
const buildAdvisorListSearchParams = (state: AdvisorListState, page = state.page) => {
|
||||
const params = new URLSearchParams()
|
||||
if (state.q) params.set('q', state.q)
|
||||
if (page > 1) params.set('page', String(page))
|
||||
return params
|
||||
}
|
||||
|
||||
export const advisorListHrefForPage = (state: AdvisorListState, page: number): string =>
|
||||
buildListHref(state, buildAdvisorListSearchParams, advisorListBasePath, page)
|
||||
|
||||
/** Fan a município out to each of the advisors the caller asked about. */
|
||||
const collectByAdvisor = <T>(
|
||||
advisors: readonly unknown[] | null | undefined,
|
||||
|
|
|
|||
83
tests/unit/advisorListUrl.unit.spec.ts
Normal file
83
tests/unit/advisorListUrl.unit.spec.ts
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
advisorListHrefForPage,
|
||||
parseAdvisorListParams,
|
||||
resolveAdvisorListUrl,
|
||||
serializeCanonicalAdvisorListSearchParams,
|
||||
} from '@/utilities/advisor/advisorListUrl'
|
||||
|
||||
describe('advisor list URL contract', () => {
|
||||
it('defaults to page 1 without q', () => {
|
||||
expect(parseAdvisorListParams({})).toEqual({ page: 1 })
|
||||
})
|
||||
|
||||
it('validates page as a positive decimal integer', () => {
|
||||
expect(parseAdvisorListParams({ page: '4' }).page).toBe(4)
|
||||
expect(parseAdvisorListParams({ page: '0' }).page).toBe(1)
|
||||
expect(parseAdvisorListParams({ page: '-2' }).page).toBe(1)
|
||||
expect(parseAdvisorListParams({ page: '01' }).page).toBe(1)
|
||||
expect(parseAdvisorListParams({ page: 'abc' }).page).toBe(1)
|
||||
})
|
||||
|
||||
it('trims q, omits it when empty and takes the first repeated cell', () => {
|
||||
expect(parseAdvisorListParams({ q: ' ana ' }).q).toBe('ana')
|
||||
expect(parseAdvisorListParams({ q: ' ' }).q).toBeUndefined()
|
||||
expect(parseAdvisorListParams({ q: ['primeiro', 'segundo'] }).q).toBe('primeiro')
|
||||
})
|
||||
|
||||
it('preserves criar=1 as autoCreateDraft through parse and serialize', () => {
|
||||
const state = parseAdvisorListParams({ criar: '1', q: 'edi' })
|
||||
expect(state).toEqual({ page: 1, q: 'edi', autoCreateDraft: true })
|
||||
expect(serializeCanonicalAdvisorListSearchParams(state).toString()).toBe('q=edi&criar=1')
|
||||
})
|
||||
|
||||
it('drops criar when it is not the quick-create sentinel', () => {
|
||||
expect(parseAdvisorListParams({ criar: '0' })).toEqual({ page: 1 })
|
||||
expect(parseAdvisorListParams({ criar: 'yes' })).toEqual({ page: 1 })
|
||||
})
|
||||
|
||||
it('serializes q then page against the assessores base path', () => {
|
||||
expect(advisorListHrefForPage({ page: 1 }, 1)).toBe('/campanha/assessores')
|
||||
expect(advisorListHrefForPage({ page: 1, q: 'edi' }, 3)).toBe(
|
||||
'/campanha/assessores?q=edi&page=3',
|
||||
)
|
||||
})
|
||||
|
||||
it('pagination hrefs drop the one-shot criar flag', () => {
|
||||
expect(advisorListHrefForPage({ page: 1, q: 'edi', autoCreateDraft: true }, 2)).toBe(
|
||||
'/campanha/assessores?q=edi&page=2',
|
||||
)
|
||||
})
|
||||
|
||||
it('redirects junk params to the canonical form', () => {
|
||||
expect(resolveAdvisorListUrl({ foo: 'bar', q: ' ana ', page: '01' })).toEqual({
|
||||
state: { page: 1, q: 'ana' },
|
||||
href: '/campanha/assessores?q=ana',
|
||||
redirectHref: '/campanha/assessores?q=ana',
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves criar=1 across canonical redirect of junk params', () => {
|
||||
expect(resolveAdvisorListUrl({ criar: '1', junk: 'x' })).toEqual({
|
||||
state: { page: 1, autoCreateDraft: true },
|
||||
href: '/campanha/assessores?criar=1',
|
||||
redirectHref: '/campanha/assessores?criar=1',
|
||||
})
|
||||
})
|
||||
|
||||
it('clamps page above totalPages', () => {
|
||||
expect(resolveAdvisorListUrl({ page: '9' }, 2)).toEqual({
|
||||
state: { page: 2 },
|
||||
href: '/campanha/assessores?page=2',
|
||||
redirectHref: '/campanha/assessores?page=2',
|
||||
})
|
||||
})
|
||||
|
||||
it('is a no-op redirect when already canonical', () => {
|
||||
expect(resolveAdvisorListUrl({ q: 'ana', page: '2' })).toEqual({
|
||||
state: { page: 2, q: 'ana' },
|
||||
href: '/campanha/assessores?q=ana&page=2',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
|
@ -27,7 +27,7 @@ describe('parseCampaignHiddenColumns', () => {
|
|||
})
|
||||
|
||||
it('drops unknown lists and column ids that are not identifiers', () => {
|
||||
expect(parseCampaignHiddenColumns('assessores:email|municipios:kind')).toEqual({
|
||||
expect(parseCampaignHiddenColumns('desconhecidos:email|municipios:kind')).toEqual({
|
||||
municipios: ['kind'],
|
||||
})
|
||||
expect(parseCampaignHiddenColumns('municipios:kind~<script>~trend')).toEqual({
|
||||
|
|
@ -35,6 +35,13 @@ describe('parseCampaignHiddenColumns', () => {
|
|||
})
|
||||
})
|
||||
|
||||
it('accepts assessores as a column-picker list id (CL5)', () => {
|
||||
expect(parseCampaignHiddenColumns('assessores:email|municipios:kind')).toEqual({
|
||||
assessores: ['email'],
|
||||
municipios: ['kind'],
|
||||
})
|
||||
})
|
||||
|
||||
it('dedupes and refuses an oversized cookie instead of trusting it', () => {
|
||||
expect(parseCampaignHiddenColumns('municipios:kind~kind')).toEqual({ municipios: ['kind'] })
|
||||
expect(parseCampaignHiddenColumns(`municipios:${'a'.repeat(4000)}`)).toEqual({})
|
||||
|
|
|
|||
|
|
@ -1,38 +1,13 @@
|
|||
/**
|
||||
* Pins the "simple" entity list parsers ahead of the Pass 2 list-system
|
||||
* consolidation (W1): organizações, demandas and assessores. Lideranças left
|
||||
* this group in B29 — its parser grew a full sort/filter contract of its own
|
||||
* and moved to `leadershipListUrl.ts`, pinned in
|
||||
* `leadershipListUrl.unit.spec.ts`. Dobradinhas left earlier in B33.
|
||||
* consolidation (W1): organizações and demandas. Assessores moved to
|
||||
* `advisorListUrl.ts` (CL5); lideranças left earlier in B29.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { advisorListHrefForPage, parseAdvisorListParams } from '@/utilities/advisorData'
|
||||
import { parseDemandListParams } from '@/utilities/campaignDemandData'
|
||||
import { parseOrganizationListParams } from '@/utilities/organizationData'
|
||||
|
||||
const qAndPageParsers = [['advisor', parseAdvisorListParams]] as const
|
||||
|
||||
describe.each(qAndPageParsers)('%s list parser (q + page)', (_name, parse) => {
|
||||
it('defaults to page 1 without q', () => {
|
||||
expect(parse({})).toEqual({ page: 1 })
|
||||
})
|
||||
|
||||
it('validates page as a positive decimal integer', () => {
|
||||
expect(parse({ page: '4' }).page).toBe(4)
|
||||
expect(parse({ page: '0' }).page).toBe(1)
|
||||
expect(parse({ page: '-2' }).page).toBe(1)
|
||||
expect(parse({ page: '01' }).page).toBe(1)
|
||||
expect(parse({ page: 'abc' }).page).toBe(1)
|
||||
})
|
||||
|
||||
it('trims q, omits it when empty and takes the first repeated cell', () => {
|
||||
expect(parse({ q: ' ana ' }).q).toBe('ana')
|
||||
expect(parse({ q: ' ' }).q).toBeUndefined()
|
||||
expect(parse({ q: ['primeiro', 'segundo'] }).q).toBe('primeiro')
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseOrganizationListParams', () => {
|
||||
it('keeps only known organization kinds', () => {
|
||||
expect(parseOrganizationListParams({ kind: 'sindicato' }).kind).toBe('sindicato')
|
||||
|
|
@ -60,12 +35,3 @@ describe('parseDemandListParams', () => {
|
|||
expect(parseDemandListParams({})).toEqual({ page: 1 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('advisorListHrefForPage', () => {
|
||||
it('serializes q then page against the assessores base path', () => {
|
||||
expect(advisorListHrefForPage({ page: 1 }, 1)).toBe('/campanha/assessores')
|
||||
expect(advisorListHrefForPage({ page: 1, q: 'edi' }, 3)).toBe(
|
||||
'/campanha/assessores?q=edi&page=3',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { join } from 'node:path'
|
|||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
<<<<<<< HEAD
|
||||
const ROUTE_PAGES = {
|
||||
municipios: join(process.cwd(), 'src/app/(campaign)/campanha/(app)/municipios/page.tsx'),
|
||||
liderancas: join(process.cwd(), 'src/app/(campaign)/campanha/(app)/liderancas/page.tsx'),
|
||||
|
|
@ -16,6 +17,10 @@ const expectOpsListPageWiring = (source: string) => {
|
|||
expect(source).toContain("from '@/components/campaign/shared/OpsListPage'")
|
||||
expect(source).toContain("from '@/lib/opsListRegistry/opsListFlag'")
|
||||
}
|
||||
=======
|
||||
const MUNICIPIOS_PAGE = join(process.cwd(), 'src/app/(campaign)/campanha/(app)/municipios/page.tsx')
|
||||
const ASSESSORES_PAGE = join(process.cwd(), 'src/app/(campaign)/campanha/(app)/assessores/page.tsx')
|
||||
>>>>>>> 7ebf891 (CL5: Assessores CampaignTable + URL canónico + OpsListPage)
|
||||
|
||||
describe('OpsListPage municipios tracer (CL3)', () => {
|
||||
it('wires LIST_UNIFIED behind OpsListPage on the municipios route', () => {
|
||||
|
|
@ -23,6 +28,7 @@ describe('OpsListPage municipios tracer (CL3)', () => {
|
|||
})
|
||||
})
|
||||
|
||||
<<<<<<< HEAD
|
||||
describe('OpsListPage CL4 routes', () => {
|
||||
it.each(['liderancas', 'dobradinhas', 'demandas'] as const)(
|
||||
'wires LIST_UNIFIED behind OpsListPage on the %s route',
|
||||
|
|
@ -30,4 +36,14 @@ describe('OpsListPage CL4 routes', () => {
|
|||
expectOpsListPageWiring(readFileSync(ROUTE_PAGES[route], 'utf8'))
|
||||
},
|
||||
)
|
||||
=======
|
||||
describe('OpsListPage assessores (CL5)', () => {
|
||||
it('wires LIST_UNIFIED behind OpsListPage on the assessores route', () => {
|
||||
const source = readFileSync(ASSESSORES_PAGE, 'utf8')
|
||||
expect(source).toContain('resolveListUnifiedEnabled')
|
||||
expect(source).toContain('OpsListPage')
|
||||
expect(source).toContain('resolveAdvisorListUrl')
|
||||
expect(source).toContain("from '@/components/campaign/shared/OpsListPage'")
|
||||
})
|
||||
>>>>>>> 7ebf891 (CL5: Assessores CampaignTable + URL canónico + OpsListPage)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ const CAMPAIGN_LIST_IDS: readonly CampaignListId[] = [
|
|||
'demandas',
|
||||
'apoiadores',
|
||||
'territorios',
|
||||
'assessores',
|
||||
]
|
||||
|
||||
const isCampaignListId = (value: string): value is CampaignListId =>
|
||||
|
|
@ -73,7 +74,8 @@ describe('opsListRegistry v1', () => {
|
|||
if (columnListId === null) continue
|
||||
expect(isCampaignListId(columnListId)).toBe(true)
|
||||
}
|
||||
expect(opsListRegistry.assessores.columnListId).toBeNull()
|
||||
expect(opsListRegistry.assessores.columnListId).toBe('assessores')
|
||||
expect(opsListRegistry.assessores.canonicalRedirect).toBe(true)
|
||||
})
|
||||
|
||||
it('requires every meta field (no partial entries)', () => {
|
||||
|
|
|
|||
Loading…
Reference in a new issue