mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-26 21:53:06 +00:00
Merge pull request #190 from fsolla/cursor/pool-i160-be5d66d3-a0aa
CL5 — Assessores: CampaignTable + URL canónico + factory
This commit is contained in:
commit
d5ab7d0b51
14 changed files with 617 additions and 422 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):** **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).
|
**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):** **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).
|
**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
|
# CL5 — Assessores: pré-work `CampaignTable` + URL canónico, depois factory
|
||||||
|
|
||||||
Status: rascunho
|
Status: em execução
|
||||||
Atualizado em: 2026-08-01
|
Atualizado em: 2026-08-01
|
||||||
Issue: #160
|
Issue: #160
|
||||||
Priority: P1
|
Priority: P1
|
||||||
Model: cursor-grok-4.5-medium
|
Model: cursor-grok-4.5-medium
|
||||||
Impeccable: B — mesma superfície `/campanha/assessores`, tabela reescrita no sistema da casa
|
Impeccable: B — mesma superfície `/campanha/assessores`, tabela reescrita no sistema da casa
|
||||||
Appetite: ~2–3 dias eng
|
Appetite: ~2–3 dias eng
|
||||||
Depends: CL3
|
Depends: CL3 (done / in-prod — #157)
|
||||||
Responsável: —
|
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
|
## Premissas
|
||||||
|
|
||||||
1. Hoje `AdvisorsTable` usa `ui/Table` cru (fora de `CampaignTable`) e o parse de URL não tem canonical redirect.
|
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).
|
2. O toggle “Editar nome e contato” permanece (produto não pediu mudança).
|
||||||
3. Gate `unrestricted` (coordinator/candidate) mantido.
|
3. Gate `unrestricted` (coordinator/candidate) mantido.
|
||||||
|
|
||||||
→ Corrija agora ou sigo com estas.
|
→ Premissas confirmadas; sigo.
|
||||||
|
|
||||||
## Objetivos
|
## 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) |
|
| 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 |
|
| `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).
|
- **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
|
## Fases verificáveis
|
||||||
|
|
@ -61,8 +69,8 @@ Componentes:
|
||||||
- **Quota:** ~0,5
|
- **Quota:** ~0,5
|
||||||
- **Entrega:** reescrita da tabela sem mexer em URL; paridade visual desktop/mobile.
|
- **Entrega:** reescrita da tabela sem mexer em URL; paridade visual desktop/mobile.
|
||||||
- **Aceite:**
|
- **Aceite:**
|
||||||
- [ ] mesmas linhas/colunas/ações visíveis
|
- [x] mesmas linhas/colunas/ações visíveis
|
||||||
- [ ] seletor de colunas funciona com cookie próprio
|
- [x] seletor de colunas funciona com cookie próprio
|
||||||
- **Verify:** `pnpm gate:fast` + e2e assessores
|
- **Verify:** `pnpm gate:fast` + e2e assessores
|
||||||
- **Files:** `AdvisorsTable.tsx`, `src/lib/campaignColumnVisibility.ts`, page assessores
|
- **Files:** `AdvisorsTable.tsx`, `src/lib/campaignColumnVisibility.ts`, page assessores
|
||||||
- **Tamanho:** M
|
- **Tamanho:** M
|
||||||
|
|
@ -72,8 +80,8 @@ Componentes:
|
||||||
- **Quota:** ~0,3
|
- **Quota:** ~0,3
|
||||||
- **Entrega:** `resolveAdvisorListUrl` + redirect na page; pins unit do parser.
|
- **Entrega:** `resolveAdvisorListUrl` + redirect na page; pins unit do parser.
|
||||||
- **Aceite:**
|
- **Aceite:**
|
||||||
- [ ] params lixo redirecionam para a forma canónica
|
- [x] params lixo redirecionam para a forma canónica
|
||||||
- [ ] sort/filtros sobrevivem ao redirect
|
- [x] sort/filtros sobrevivem ao redirect
|
||||||
- **Verify:** `pnpm gate:fast` + pin unit `advisorListUrl`
|
- **Verify:** `pnpm gate:fast` + pin unit `advisorListUrl`
|
||||||
- **Files:** `advisorListUrl.ts`, `tests/unit/advisorListUrl.unit.spec.ts`, page
|
- **Files:** `advisorListUrl.ts`, `tests/unit/advisorListUrl.unit.spec.ts`, page
|
||||||
- **Tamanho:** M
|
- **Tamanho:** M
|
||||||
|
|
@ -81,10 +89,10 @@ Componentes:
|
||||||
### Fase 3 — Factory (CL5b)
|
### Fase 3 — Factory (CL5b)
|
||||||
|
|
||||||
- **Quota:** ~0,2
|
- **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
|
- **Aceite:** paridade com flag ON/OFF
|
||||||
- **Verify:** `pnpm gate:fast` + e2e assessores com env
|
- **Verify:** `pnpm gate:fast` + pin unit `opsListPage`
|
||||||
- **Files:** registry, page
|
- **Files:** registry (`columnListId`/`canonicalRedirect`), page
|
||||||
- **Tamanho:** S
|
- **Tamanho:** S
|
||||||
|
|
||||||
### Checkpoint
|
### Checkpoint
|
||||||
|
|
|
||||||
|
|
@ -40,22 +40,22 @@ Predecessor entregue: Pass 2 W1 ([`sistema-listas-campanha.md`](sistema-listas-c
|
||||||
|
|
||||||
Tabela canónica dos metadados v1. Planos filhos (**CL2+**) citam esta secção — **não** reescrevem as células. Ordem estável = **por `routePath`** (não alfabética). `gate` = valor as-built de `requireCampaignPageActor` (ou alvo documentado).
|
Tabela canónica dos metadados v1. Planos filhos (**CL2+**) citam esta secção — **não** reescrevem as células. Ordem estável = **por `routePath`** (não alfabética). `gate` = valor as-built de `requireCampaignPageActor` (ou alvo documentado).
|
||||||
|
|
||||||
| slug | routePath | gate | columnListId | savedFilters | sortModel | canonicalRedirect |
|
| slug | routePath | gate | columnListId | savedFilters | sortModel | canonicalRedirect |
|
||||||
| -------------- | ------------------------ | -------------- | ------------------------------- | ------------ | ------------------------ | ---------------------------------------- |
|
| -------------- | ------------------------ | -------------- | -------------------- | ------------ | ------------------------ | ---------------------------------------- |
|
||||||
| `municipios` | `/campanha/municipios` | `noLeader` | `municipios` | `true` | `url` | `true` |
|
| `municipios` | `/campanha/municipios` | `noLeader` | `municipios` | `true` | `url` | `true` |
|
||||||
| `liderancas` | `/campanha/liderancas` | `staff` | `liderancas` | `false` | `url` | `true` |
|
| `liderancas` | `/campanha/liderancas` | `staff` | `liderancas` | `false` | `url` | `true` |
|
||||||
| `dobradinhas` | `/campanha/dobradinhas` | `staff` | `dobradinhas` | `false` | `url` | `true` |
|
| `dobradinhas` | `/campanha/dobradinhas` | `staff` | `dobradinhas` | `false` | `url` | `true` |
|
||||||
| `demandas` | `/campanha/demandas` | `staff` | `demandas` | `false` | `fixed` (`-createdAt`) | `false` |
|
| `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) |
|
| `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` |
|
| `apoiadores` | `/campanha/apoiadores` | `staff` † | `apoiadores` | `false` | `url` | `true` |
|
||||||
| `organizacoes` | `/campanha/organizacoes` | `staff` | `organizacoes` | `false` | `fixed` (`name`) | `false` |
|
| `organizacoes` | `/campanha/organizacoes` | `staff` | `organizacoes` | `false` | `fixed` (`name`) | `false` |
|
||||||
|
|
||||||
† `apoiadores` hoje: `requireCampaignPageActor()` sem gate + `canAccessSupporterArea` (= staff). Registry pina `staff` como alvo da factory.
|
† `apoiadores` hoje: `requireCampaignPageActor()` sem gate + `canAccessSupporterArea` (= staff). Registry pina `staff` como alvo da factory.
|
||||||
|
|
||||||
`atividades` **não** entra em `opsListDomains` — cards + tabs (`ActivityList` / `ActivityCard`); rota intocada. Documentar a razão no comentário do registry (Pass 2 D5).
|
`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'`.
|
Campos de implementação (CL2), fora desta tabela: `layout: 'table'`, tipagem `OpsListDomainMeta` — sem `status: 'excluded'`.
|
||||||
|
|
||||||
|
|
@ -78,17 +78,17 @@ Campos de implementação (CL2), fora desta tabela: `layout: 'table'`, tipagem `
|
||||||
|
|
||||||
Estado **hoje** (não o contrato-alvo). Para sortModel / canonicalRedirect / columnListId alvo, ver § Escopo.
|
Estado **hoje** (não o contrato-alvo). Para sortModel / canonicalRedirect / columnListId alvo, ver § Escopo.
|
||||||
|
|
||||||
| Rota | Layout | URL hoje | Paginação hoje | Tabela hoje |
|
| Rota | Layout | URL hoje | Paginação hoje | Tabela hoje |
|
||||||
| ------------------------ | -------------- | ------------------------------------------------------------- | ----------------------------------------- | ------------------------------------------- |
|
| ------------------------ | --------- | ------------------------------------------------------------- | ----------------------------------------- | --------------------------------------- |
|
||||||
| `/campanha/municipios` | table | `resolveMunicipalityListUrl` (canonical) | server | `CampaignTable` + picker |
|
| `/campanha/municipios` | table | `resolveMunicipalityListUrl` (canonical) | server | `CampaignTable` + picker |
|
||||||
| `/campanha/liderancas` | table | `resolveLeadershipListUrl` | server | `CampaignTable` |
|
| `/campanha/liderancas` | table | `resolveLeadershipListUrl` | server | `CampaignTable` |
|
||||||
| `/campanha/dobradinhas` | table | `resolveStateDeputyListUrl` | server | `CampaignTable` |
|
| `/campanha/dobradinhas` | table | `resolveStateDeputyListUrl` | server | `CampaignTable` |
|
||||||
| `/campanha/demandas` | table | `parseDemandListParams` (sem resolve canónico) | 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/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/apoiadores` | table | resolve via `supporterUi` | server | `CampaignTable` |
|
||||||
| `/campanha/organizacoes` | table | `parseOrganizationListParams` (sem resolve canónico) | server | `CampaignTable` |
|
| `/campanha/organizacoes` | table | `parseOrganizationListParams` (sem resolve canónico) | server | `CampaignTable` |
|
||||||
| `/campanha/atividades` | **cards** | `resolveActivityListUrl` | server | `ActivityList` — **excluída** |
|
| `/campanha/atividades` | **cards** | `resolveActivityListUrl` | server | `ActivityList` — **excluída** |
|
||||||
|
|
||||||
## Boundaries Teqo
|
## Boundaries Teqo
|
||||||
|
|
||||||
|
|
@ -134,19 +134,19 @@ Números GitHub (#156–#162) **não** seguem a ordem de execução (CL5=#160, C
|
||||||
|
|
||||||
## Mapa de ficheiros (as-built → alvo)
|
## Mapa de ficheiros (as-built → alvo)
|
||||||
|
|
||||||
| Domínio | Parser / URL hoje | Loader / page data | UI |
|
| Domínio | Parser / URL hoje | Loader / page data | UI |
|
||||||
| ---------------------- | ------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------- |
|
| ---------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------- |
|
||||||
| municípios | `utilities/municipality/municipalityListUrl.ts` | `municipality*Data` | `components/campaign/municipality/` |
|
| municípios | `utilities/municipality/municipalityListUrl.ts` | `municipality*Data` | `components/campaign/municipality/` |
|
||||||
| lideranças | `utilities/leadership/leadershipListUrl.ts` | `leadership*Data` | `components/campaign/leadership/` |
|
| lideranças | `utilities/leadership/leadershipListUrl.ts` | `leadership*Data` | `components/campaign/leadership/` |
|
||||||
| dobradinhas | `utilities/stateDeputyListUrl.ts` | state-deputy loaders | `components/campaign/stateDeputy/` |
|
| dobradinhas | `utilities/stateDeputyListUrl.ts` | state-deputy loaders | `components/campaign/stateDeputy/` |
|
||||||
| demandas | `utilities/campaignDemandData.ts` (`parseDemandListParams`) | idem | `components/campaign/demand/` |
|
| 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/` |
|
| 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/` |
|
| apoiadores | `utilities/supporter/supporterUi.ts` | `supporter/*Data` | `components/campaign/supporter/` |
|
||||||
| organizações | `utilities/organizationData.ts` (`parseOrganizationListParams`) | idem | `components/campaign/organization/` |
|
| organizações | `utilities/organizationData.ts` (`parseOrganizationListParams`) | idem | `components/campaign/organization/` |
|
||||||
| atividades | `utilities/activityUi.ts` | `activityPageData` | `ActivityList` (excluída) |
|
| atividades | `utilities/activityUi.ts` | `activityPageData` | `ActivityList` (excluída) |
|
||||||
| comum | `utilities/campaignListUrl.ts`, `lib/campaignColumnVisibility.ts` | — | `shared/CampaignTable.tsx` + shells |
|
| comum | `utilities/campaignListUrl.ts`, `lib/campaignColumnVisibility.ts` | — | `shared/CampaignTable.tsx` + shells |
|
||||||
| registry (novo em CL2) | — | — | `src/lib/opsListRegistry/` |
|
| registry (novo em CL2) | — | — | `src/lib/opsListRegistry/` |
|
||||||
|
|
||||||
## Referências
|
## Referências
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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 config from '@payload-config'
|
||||||
|
import { redirect } from 'next/navigation'
|
||||||
import { getPayload } from 'payload'
|
import { getPayload } from 'payload'
|
||||||
|
import type { ReactNode } from 'react'
|
||||||
|
|
||||||
import { AdvisorsTable } from '@/components/campaign/advisor/AdvisorsTable'
|
import { AdvisorsTable } from '@/components/campaign/advisor/AdvisorsTable'
|
||||||
import { CampaignListFooter } from '@/components/campaign/shared/CampaignListFooter'
|
import { CampaignListFooter } from '@/components/campaign/shared/CampaignListFooter'
|
||||||
|
|
@ -10,13 +10,13 @@ import {
|
||||||
CampaignListResults,
|
CampaignListResults,
|
||||||
} 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 { CampaignPageShell } from '@/components/campaign/shell/CampaignPageShell'
|
import { CampaignPageShell } from '@/components/campaign/shell/CampaignPageShell'
|
||||||
import {
|
import { CAMPAIGN_ADVISORS_HOME } from '@/lib/campaignPaths'
|
||||||
advisorListHrefForPage,
|
import { resolveListUnifiedEnabled } from '@/lib/opsListRegistry/opsListFlag'
|
||||||
loadAdvisorListPageData,
|
import { advisorListHrefForPage, resolveAdvisorListUrl } from '@/utilities/advisor/advisorListUrl'
|
||||||
parseAdvisorListParams,
|
import { loadAdvisorListPageData } from '@/utilities/advisorData'
|
||||||
} from '@/utilities/advisorData'
|
import { readCampaignColumnVisibility } from '@/utilities/campaignColumnVisibilityCookie'
|
||||||
import { firstValue } from '@/utilities/campaignListUrl'
|
|
||||||
import { requireCampaignPageActor } from '@/utilities/campaignPageActor'
|
import { requireCampaignPageActor } from '@/utilities/campaignPageActor'
|
||||||
import { loadMunicipalityPortfolioIndex } from '@/utilities/municipality/municipalityPortfolioIndex'
|
import { loadMunicipalityPortfolioIndex } from '@/utilities/municipality/municipalityPortfolioIndex'
|
||||||
import {
|
import {
|
||||||
|
|
@ -32,18 +32,77 @@ type AdvisorsPageProps = {
|
||||||
|
|
||||||
export default async function AdvisorsPage({ searchParams }: AdvisorsPageProps) {
|
export default async function AdvisorsPage({ searchParams }: AdvisorsPageProps) {
|
||||||
const rawSearchParams = await searchParams
|
const rawSearchParams = await searchParams
|
||||||
|
const canonicalUrl = resolveAdvisorListUrl(rawSearchParams)
|
||||||
|
if (canonicalUrl.redirectHref) redirect(canonicalUrl.redirectHref)
|
||||||
|
|
||||||
const [, payload] = await Promise.all([
|
const [, payload] = await Promise.all([
|
||||||
requireCampaignPageActor({ gate: 'unrestricted' }),
|
requireCampaignPageActor({ gate: 'unrestricted' }),
|
||||||
getPayload({ config }),
|
getPayload({ config }),
|
||||||
])
|
])
|
||||||
|
|
||||||
const state = parseAdvisorListParams(rawSearchParams)
|
const [{ rows, totalDocs, totalPages }, municipalityIndex, columnVisibility] = await Promise.all([
|
||||||
const autoCreateDraft = firstValue(rawSearchParams[ADVISOR_QUICK_CREATE_PARAM]) === '1'
|
loadAdvisorListPageData(payload, canonicalUrl.state),
|
||||||
const [{ rows, totalDocs, totalPages }, municipalityIndex] = await Promise.all([
|
|
||||||
loadAdvisorListPageData(payload, state),
|
|
||||||
loadMunicipalityPortfolioIndex(),
|
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 (
|
return (
|
||||||
<CampaignPageShell>
|
<CampaignPageShell>
|
||||||
<header className="flex flex-col gap-2">
|
<header className="flex flex-col gap-2">
|
||||||
|
|
@ -54,38 +113,7 @@ export default async function AdvisorsPage({ searchParams }: AdvisorsPageProps)
|
||||||
</p>
|
</p>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<CampaignListPendingBoundary>
|
{main}
|
||||||
<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>
|
|
||||||
</CampaignPageShell>
|
</CampaignPageShell>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@ import {
|
||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
import Link from 'next/link'
|
import Link from 'next/link'
|
||||||
import { useRouter } from 'next/navigation'
|
import { useRouter } from 'next/navigation'
|
||||||
import { useEffect, useMemo, useState, useTransition } from 'react'
|
import { useEffect, useState, useTransition } from 'react'
|
||||||
import { toast } from 'sonner'
|
import { toast } from 'sonner'
|
||||||
|
|
||||||
import { AdvisorDebouncedTextCell } from '@/components/campaign/advisor/AdvisorDebouncedTextCell'
|
import { AdvisorDebouncedTextCell } from '@/components/campaign/advisor/AdvisorDebouncedTextCell'
|
||||||
|
|
@ -22,18 +22,16 @@ import {
|
||||||
} from '@/components/campaign/shared/CampaignCopyableCell'
|
} from '@/components/campaign/shared/CampaignCopyableCell'
|
||||||
import { CampaignListEmptyState } from '@/components/campaign/shared/CampaignListEmptyState'
|
import { CampaignListEmptyState } from '@/components/campaign/shared/CampaignListEmptyState'
|
||||||
import { CampaignListSheetProvider } from '@/components/campaign/shared/CampaignListSheetHost'
|
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 { MunicipalityPortfolioCell } from '@/components/campaign/shared/MunicipalityPortfolioCell'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Input } from '@/components/ui/input'
|
import { Input } from '@/components/ui/input'
|
||||||
import { Spinner } from '@/components/ui/Spinner'
|
import { Spinner } from '@/components/ui/Spinner'
|
||||||
import {
|
import type { CampaignColumnVisibility } from '@/lib/campaignColumnVisibility'
|
||||||
Table,
|
|
||||||
TableBody,
|
|
||||||
TableCell,
|
|
||||||
TableHead,
|
|
||||||
TableHeader,
|
|
||||||
TableRow,
|
|
||||||
} from '@/components/ui/Table'
|
|
||||||
import { campaignInlineInputClassName } from '@/lib/campaignInlineInput'
|
import { campaignInlineInputClassName } from '@/lib/campaignInlineInput'
|
||||||
import type { MunicipalityPortfolioIndexEntry } from '@/lib/municipalityPortfolio'
|
import type { MunicipalityPortfolioIndexEntry } from '@/lib/municipalityPortfolio'
|
||||||
import {
|
import {
|
||||||
|
|
@ -53,10 +51,15 @@ type DraftAdvisor = {
|
||||||
municipalityIds: number[]
|
municipalityIds: number[]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type AdvisorTableRow =
|
||||||
|
| { kind: 'draft'; draft: DraftAdvisor }
|
||||||
|
| { kind: 'advisor'; advisor: AdvisorRowViewModel }
|
||||||
|
|
||||||
type AdvisorsTableProps = {
|
type AdvisorsTableProps = {
|
||||||
rows: AdvisorRowViewModel[]
|
rows: AdvisorRowViewModel[]
|
||||||
municipalityIndex: MunicipalityPortfolioIndexEntry[]
|
municipalityIndex: MunicipalityPortfolioIndexEntry[]
|
||||||
hasQuery: boolean
|
hasQuery: boolean
|
||||||
|
columnVisibility: CampaignColumnVisibility
|
||||||
updateProfileAction: (
|
updateProfileAction: (
|
||||||
state: CampaignFormActionState,
|
state: CampaignFormActionState,
|
||||||
formData: FormData,
|
formData: FormData,
|
||||||
|
|
@ -92,6 +95,7 @@ export const AdvisorsTable = ({
|
||||||
rows,
|
rows,
|
||||||
municipalityIndex,
|
municipalityIndex,
|
||||||
hasQuery,
|
hasQuery,
|
||||||
|
columnVisibility,
|
||||||
updateProfileAction,
|
updateProfileAction,
|
||||||
municipalitiesAction,
|
municipalitiesAction,
|
||||||
createAction,
|
createAction,
|
||||||
|
|
@ -105,13 +109,6 @@ export const AdvisorsTable = ({
|
||||||
|
|
||||||
const refresh = () => router.refresh()
|
const refresh = () => router.refresh()
|
||||||
|
|
||||||
// One array per row per render of `rows`, not per render of this table: the
|
|
||||||
// cell reconciles its optimistic state against this prop by identity.
|
|
||||||
const municipalityIdsByAdvisor = useMemo(
|
|
||||||
() => new Map(rows.map((row) => [row.id, row.municipalityIDs])),
|
|
||||||
[rows],
|
|
||||||
)
|
|
||||||
|
|
||||||
const startDraft = () => {
|
const startDraft = () => {
|
||||||
setEditing(true)
|
setEditing(true)
|
||||||
setDraft(emptyDraft())
|
setDraft(emptyDraft())
|
||||||
|
|
@ -159,7 +156,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={advisor.municipalityIDs}
|
||||||
|
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 (
|
return (
|
||||||
// One shared Drawer for the portfolio chip cells on coarse pointers
|
// One shared Drawer for the portfolio chip cells on coarse pointers
|
||||||
|
|
@ -188,248 +434,31 @@ export const AdvisorsTable = ({
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{showEmpty ? (
|
<CampaignTable
|
||||||
<CampaignListEmptyState
|
columns={columns}
|
||||||
icon={hasQuery ? SearchXIcon : UserCogIcon}
|
columnVisibility={columnVisibility}
|
||||||
title={hasQuery ? 'Nenhum assessor encontrado' : 'Nenhum assessor cadastrado'}
|
rows={tableRows}
|
||||||
description={
|
rowKey={(row) => (row.kind === 'draft' ? 'draft' : row.advisor.id)}
|
||||||
hasQuery
|
rowClassName={(row) => (row.kind === 'draft' ? 'bg-muted/20' : undefined)}
|
||||||
? 'Ajuste a busca ou limpe o filtro para ver todos.'
|
empty={
|
||||||
: 'Ative a edição e crie a conta na tabela.'
|
<CampaignListEmptyState
|
||||||
}
|
icon={hasQuery ? SearchXIcon : UserCogIcon}
|
||||||
>
|
title={hasQuery ? 'Nenhum assessor encontrado' : 'Nenhum assessor cadastrado'}
|
||||||
{!hasQuery ? (
|
description={
|
||||||
<Button type="button" className="min-h-11" onClick={startDraft}>
|
hasQuery
|
||||||
<PlusIcon data-icon="inline-start" aria-hidden="true" />
|
? 'Ajuste a busca ou limpe o filtro para ver todos.'
|
||||||
Novo assessor
|
: 'Ative a edição e crie a conta na tabela.'
|
||||||
</Button>
|
}
|
||||||
) : null}
|
>
|
||||||
</CampaignListEmptyState>
|
{!hasQuery ? (
|
||||||
) : (
|
<Button type="button" className="min-h-11" onClick={startDraft}>
|
||||||
<div className="overflow-x-auto rounded-xl border">
|
<PlusIcon data-icon="inline-start" aria-hidden="true" />
|
||||||
<Table className="min-w-[56rem] table-fixed">
|
Novo assessor
|
||||||
<TableHeader>
|
</Button>
|
||||||
<TableRow>
|
) : null}
|
||||||
<TableHead className="w-[20%]">Nome</TableHead>
|
</CampaignListEmptyState>
|
||||||
<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>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</CampaignListSheetProvider>
|
</CampaignListSheetProvider>
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -25,6 +25,7 @@ const CAMPAIGN_LIST_IDS = [
|
||||||
'demandas',
|
'demandas',
|
||||||
'apoiadores',
|
'apoiadores',
|
||||||
'territorios',
|
'territorios',
|
||||||
|
'assessores',
|
||||||
] as const
|
] as const
|
||||||
|
|
||||||
export type CampaignListId = (typeof CAMPAIGN_LIST_IDS)[number]
|
export type CampaignListId = (typeof CAMPAIGN_LIST_IDS)[number]
|
||||||
|
|
|
||||||
|
|
@ -80,10 +80,10 @@ export const opsListRegistry: Record<OpsListDomainId, OpsListDomainMeta> = {
|
||||||
id: 'assessores',
|
id: 'assessores',
|
||||||
routePath: '/campanha/assessores',
|
routePath: '/campanha/assessores',
|
||||||
gate: 'unrestricted',
|
gate: 'unrestricted',
|
||||||
columnListId: null,
|
columnListId: 'assessores',
|
||||||
savedFilters: false,
|
savedFilters: false,
|
||||||
sortModel: 'fixed',
|
sortModel: 'fixed',
|
||||||
canonicalRedirect: false,
|
canonicalRedirect: true,
|
||||||
layout: 'table',
|
layout: 'table',
|
||||||
},
|
},
|
||||||
territorios: {
|
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 } : {}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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,9 @@ import 'server-only'
|
||||||
import type { Payload } from 'payload'
|
import type { Payload } from 'payload'
|
||||||
|
|
||||||
import { relationshipId } from '@/lib/relationship'
|
import { relationshipId } from '@/lib/relationship'
|
||||||
import {
|
import type { AdvisorListState } from '@/utilities/advisor/advisorListUrl'
|
||||||
buildListHref,
|
|
||||||
firstValue,
|
|
||||||
normalizedText,
|
|
||||||
strictDecimalInteger,
|
|
||||||
type RawSearchParams,
|
|
||||||
} from '@/utilities/campaignListUrl'
|
|
||||||
|
|
||||||
const advisorPageSize = 25
|
const advisorPageSize = 25
|
||||||
const advisorListBasePath = '/campanha/assessores'
|
|
||||||
|
|
||||||
export type AdvisorListState = {
|
|
||||||
page: number
|
|
||||||
q?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
type AdvisorMunicipalityViewModel = {
|
type AdvisorMunicipalityViewModel = {
|
||||||
id: number
|
id: number
|
||||||
|
|
@ -45,26 +33,6 @@ export type AdvisorDetailViewModel = AdvisorAccountViewModel & {
|
||||||
municipalities: AdvisorMunicipalityViewModel[]
|
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. */
|
/** Fan a município out to each of the advisors the caller asked about. */
|
||||||
const collectByAdvisor = <T>(
|
const collectByAdvisor = <T>(
|
||||||
advisors: readonly unknown[] | null | undefined,
|
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', () => {
|
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'],
|
municipios: ['kind'],
|
||||||
})
|
})
|
||||||
expect(parseCampaignHiddenColumns('municipios:kind~<script>~trend')).toEqual({
|
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', () => {
|
it('dedupes and refuses an oversized cookie instead of trusting it', () => {
|
||||||
expect(parseCampaignHiddenColumns('municipios:kind~kind')).toEqual({ municipios: ['kind'] })
|
expect(parseCampaignHiddenColumns('municipios:kind~kind')).toEqual({ municipios: ['kind'] })
|
||||||
expect(parseCampaignHiddenColumns(`municipios:${'a'.repeat(4000)}`)).toEqual({})
|
expect(parseCampaignHiddenColumns(`municipios:${'a'.repeat(4000)}`)).toEqual({})
|
||||||
|
|
|
||||||
|
|
@ -1,38 +1,13 @@
|
||||||
/**
|
/**
|
||||||
* Pins the "simple" entity list parsers ahead of the Pass 2 list-system
|
* Pins the "simple" entity list parsers ahead of the Pass 2 list-system
|
||||||
* consolidation (W1): organizações, demandas and assessores. Lideranças left
|
* consolidation (W1): organizações and demandas. Assessores moved to
|
||||||
* this group in B29 — its parser grew a full sort/filter contract of its own
|
* `advisorListUrl.ts` (CL5); lideranças left earlier in B29.
|
||||||
* and moved to `leadershipListUrl.ts`, pinned in
|
|
||||||
* `leadershipListUrl.unit.spec.ts`. Dobradinhas left earlier in B33.
|
|
||||||
*/
|
*/
|
||||||
import { describe, expect, it } from 'vitest'
|
import { describe, expect, it } from 'vitest'
|
||||||
|
|
||||||
import { advisorListHrefForPage, parseAdvisorListParams } from '@/utilities/advisorData'
|
|
||||||
import { parseDemandListParams } from '@/utilities/campaignDemandData'
|
import { parseDemandListParams } from '@/utilities/campaignDemandData'
|
||||||
import { parseOrganizationListParams } from '@/utilities/organizationData'
|
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', () => {
|
describe('parseOrganizationListParams', () => {
|
||||||
it('keeps only known organization kinds', () => {
|
it('keeps only known organization kinds', () => {
|
||||||
expect(parseOrganizationListParams({ kind: 'sindicato' }).kind).toBe('sindicato')
|
expect(parseOrganizationListParams({ kind: 'sindicato' }).kind).toBe('sindicato')
|
||||||
|
|
@ -60,12 +35,3 @@ describe('parseDemandListParams', () => {
|
||||||
expect(parseDemandListParams({})).toEqual({ page: 1 })
|
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',
|
|
||||||
)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,7 @@ const ROUTE_PAGES = {
|
||||||
liderancas: join(process.cwd(), 'src/app/(campaign)/campanha/(app)/liderancas/page.tsx'),
|
liderancas: join(process.cwd(), 'src/app/(campaign)/campanha/(app)/liderancas/page.tsx'),
|
||||||
dobradinhas: join(process.cwd(), 'src/app/(campaign)/campanha/(app)/dobradinhas/page.tsx'),
|
dobradinhas: join(process.cwd(), 'src/app/(campaign)/campanha/(app)/dobradinhas/page.tsx'),
|
||||||
demandas: join(process.cwd(), 'src/app/(campaign)/campanha/(app)/demandas/page.tsx'),
|
demandas: join(process.cwd(), 'src/app/(campaign)/campanha/(app)/demandas/page.tsx'),
|
||||||
|
assessores: join(process.cwd(), 'src/app/(campaign)/campanha/(app)/assessores/page.tsx'),
|
||||||
} as const
|
} as const
|
||||||
|
|
||||||
const expectOpsListPageWiring = (source: string) => {
|
const expectOpsListPageWiring = (source: string) => {
|
||||||
|
|
@ -31,3 +32,11 @@ describe('OpsListPage CL4 routes', () => {
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('OpsListPage assessores (CL5)', () => {
|
||||||
|
it('wires LIST_UNIFIED behind OpsListPage on the assessores route', () => {
|
||||||
|
const source = readFileSync(ROUTE_PAGES.assessores, 'utf8')
|
||||||
|
expectOpsListPageWiring(source)
|
||||||
|
expect(source).toContain('resolveAdvisorListUrl')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
|
||||||
|
|
@ -17,6 +17,7 @@ const CAMPAIGN_LIST_IDS: readonly CampaignListId[] = [
|
||||||
'demandas',
|
'demandas',
|
||||||
'apoiadores',
|
'apoiadores',
|
||||||
'territorios',
|
'territorios',
|
||||||
|
'assessores',
|
||||||
]
|
]
|
||||||
|
|
||||||
const isCampaignListId = (value: string): value is CampaignListId =>
|
const isCampaignListId = (value: string): value is CampaignListId =>
|
||||||
|
|
@ -73,7 +74,8 @@ describe('opsListRegistry v1', () => {
|
||||||
if (columnListId === null) continue
|
if (columnListId === null) continue
|
||||||
expect(isCampaignListId(columnListId)).toBe(true)
|
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)', () => {
|
it('requires every meta field (no partial entries)', () => {
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue