mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-27 06:13:06 +00:00
feat(campanha): B155+ — migrar quick-edits de célula para padrão rota
F1: POST /campanha/municipios/signal substitui createMunicipalityListSignalFormAction; MunicipalityListSignalControl troca useActionState por postCampaignJson + useCampaignCellFailureChannel. F2+F3: POST /campanha/liderancas/state-deputies e /municipalities substituem setLeadershipStateDeputyMembershipFormAction e setLeadershipMunicipalitiesFormAction; wrappers 'use client' LeadershipMunicipalitiesColumnCell / LeadershipStateDeputiesColumnCell criam shims route-backed com mesma assinatura das shared cells. Closes #368
This commit is contained in:
parent
781360bcf9
commit
e494fdcaa0
23 changed files with 508 additions and 137 deletions
139
docs/plans/escala-dry-pos-b155-padrao-rota-impl.md
Normal file
139
docs/plans/escala-dry-pos-b155-padrao-rota-impl.md
Normal file
|
|
@ -0,0 +1,139 @@
|
||||||
|
# Impl: Padrão de escrita de célula — migrar quick-edits via form action para rota (célula → rota)
|
||||||
|
|
||||||
|
Status: aprovado
|
||||||
|
Atualizado em: 2026-08-04
|
||||||
|
Issue: #368
|
||||||
|
Intenção: docs/plans/escala-dry-pos-b155-padrao-rota.md
|
||||||
|
Appetite restante: ~0,5–1 dia eng; sem migration
|
||||||
|
|
||||||
|
## Leitura da intenção
|
||||||
|
|
||||||
|
- **Outcome:** As 3 anomalias de quick-edit (1 sinal em municípios, 2 colunas em lideranças) que ainda passam por form action são migradas para o padrão `campaignJsonMutationRoute` + `postCampaignJson` — mesmo transporte das 8+ rotas irmãs que já usam. Sem mudança de comportamento, sem migration.
|
||||||
|
- **O que NÃO negociar:** `campaignJsonMutationRoute` é obrigatório (codebaseConventions recusa POST nu); as actions record existentes são reusadas sem mudança de domínio; `useCampaignCellAutosave` nos controles de lista mantém debounce/abort.
|
||||||
|
- **O que reavaliar:** A hipótese da intenção é que cada controle troca `useActionState`/form action por `postCampaignJson` diretamente. Para F2 e F3 isso é mais sutil — o `MunicipalityPortfolioCell` e o `LeadershipStateDeputyRelationCell` são células compartilhadas que aceitam `commitAction`/`membershipAction` com assinatura `(state, formData) => Promise<{status, message}>`. A abordagem recomendada é manter as shared cells inalteradas e trocar **o que a página passa** de server action para um shim cliente que chama `postCampaignJson` → essa é a mudança de transporte preservando o contrato de chamada.
|
||||||
|
|
||||||
|
## Abordagem recomendada
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
subgraph "F1 — Sinal (MunicipalityListSignalControl)"
|
||||||
|
S1C[SignalControl] -->|postCampaignJson| S1R[POST /municipios/signal]
|
||||||
|
S1R --> S1A[createMunicipalityUpdate]
|
||||||
|
end
|
||||||
|
subgraph "F2 — Dobradinhas (LeadershipStateDeputyRelationCell)"
|
||||||
|
S2C[RelationOptionCell] -->|shim cliente→postCampaignJson| S2R[POST /liderancas/state-deputies]
|
||||||
|
S2R --> S2A[setLeadershipStateDeputyMembership]
|
||||||
|
end
|
||||||
|
subgraph "F3 — Municípios (MunicipalityPortfolioCell)"
|
||||||
|
S3C[RelationChipCell] -->|shim cliente→postCampaignJson| S3R[POST /liderancas/municipalities]
|
||||||
|
S3R --> S3A[setLeadershipMunicipalitiesMembership]
|
||||||
|
end
|
||||||
|
```
|
||||||
|
|
||||||
|
**Opções consideradas:** A (controles trocam internamente) | B (shim cliente com mesma assinatura) | C (refatorar shared cells para aceitar ambos os transportes)
|
||||||
|
|
||||||
|
**Recomendação:** **B para F2+F3, A para F1** — porque:
|
||||||
|
|
||||||
|
- **F1 — A:** O `MunicipalityListSignalControl` é específico da lista de municípios e só tem 1 consumidor. Trocar `useActionState` → `postCampaignJson` direto é simples e elimina a dependência de form action no componente. O `useCampaignFormSuccessToast` é substituído por feedback inline (padrão dos outros controles da mesma lista que já são rota: advisors, leaderships, level, trend — todos usam `useCampaignCellFailureChannel` + mensagem inline).
|
||||||
|
- **F2+F3 — B:** `MunicipalityPortfolioCell` e `LeadershipStateDeputyRelationCell` são shared cells com múltiplos consumidores (lideranças + assessores + dobradinhas). Mudar seu transporte interno quebraria os outros consumidores ou exigiria refatoração dupla. Um shim cliente que aceita `(state, formData)` e chama `postCampaignJson` preserva o contrato e isola a mudança ao call site da página `/campanha/liderancas`.
|
||||||
|
|
||||||
|
**Rejeitadas:**
|
||||||
|
|
||||||
|
- **A para F2+F3:** refatorar shared cells para `postCampaignJson` interno → afeta assessores (outro PR, outro domínio) e quebra o princípio de "transporte apenas".
|
||||||
|
- **C:** adicionar um terceiro modo de transporte às shared cells (prop `transport: 'form' | 'route'`) → complexidade desnecessária para 2 call sites, e o plano é que toda escrita de célula migre para rota — não faz sentido manter os dois modos.
|
||||||
|
|
||||||
|
### Componentes / mudanças
|
||||||
|
|
||||||
|
- **`POST /campanha/municipios/signal/route.ts`** (nova rota): `campaignJsonMutationRoute` com body `{ municipalityId, body?, signalType? }`. Reusa `createMunicipalityUpdate({ kind: 'sinal', … })` + `revalidateMunicipalityListPaths`. Response: `{ status: 'success', message, savedSignal: { kind, body, signalType, createdAt } }`.
|
||||||
|
- **`MunicipalityListSignalControl`** (editado): remove `useActionState`/`formAction` prop; troca por `postCampaignJson(SIGNAL_ENDPOINT, …)` com feedback via `useCampaignCellFailureChannel` (padrão dos controles irmãos). Remove `useCampaignFormSuccessToast`.
|
||||||
|
- **`MunicipalityList` + `municipios/page.tsx`** (editado): remove `signalFormAction` prop; `MunicipalityListSignalControl` já não a recebe.
|
||||||
|
- **`POST /campanha/liderancas/state-deputies/route.ts`** (nova rota): `campaignJsonMutationRoute` com body `{ leadershipId, stateDeputyId, assigned }`. Reusa `setLeadershipStateDeputyMembership`. Response: `{ status: 'success', message }`.
|
||||||
|
- **`POST /campanha/liderancas/municipalities/route.ts`** (nova rota): `campaignJsonMutationRoute` com body `{ leadershipId, municipalityIds[], assigned }`. Reusa `setLeadershipMunicipalitiesMembership`. Response: `{ status: 'success', message }`.
|
||||||
|
- **`liderancas/page.tsx`** (editado): troca `setLeadershipMunicipalitiesFormAction` e `setLeadershipStateDeputyMembershipFormAction` por shims cliente que chamam `postCampaignJson` nas novas rotas e retornam `{ status, message }`.
|
||||||
|
- **`liderancas/formActions.ts`** (editado): remove `setLeadershipStateDeputyMembershipFormAction` e `setLeadershipMunicipalitiesFormAction` (ficam sem consumidores).
|
||||||
|
- **`municipalityStaffFormActions.ts`** (editado): remove `createMunicipalityListSignalFormAction`.
|
||||||
|
- **`municipio/[slug]/v2/formActions.ts`** (editado): `createMunicipalityV2SignalFormAction` deixa de importar de `municipalityStaffFormActions` e passa a chamar a rota (ou vira um shim rota também).
|
||||||
|
- **Migration:** nenhuma.
|
||||||
|
- **Access / Consent:** sem mudança — as actions record reusadas já têm access control (`overrideAccess: false`). A rota herda a verificação de sessão do `campaignJsonMutationRoute` (que chama `getCampaignUser` implicitamente via as actions — na verdade, o `campaignJsonMutationRoute` NÃO autentica; quem autentica são as actions chamadas dentro do handler. As actions existentes já fazem `requireCampaignPageActor` → OK).
|
||||||
|
- **UI:** Impeccable A — refactor de transporte; sem mudança de comportamento nem de UI. Nenhuma shape/craft/critique.
|
||||||
|
|
||||||
|
### Dados → forma
|
||||||
|
|
||||||
|
Não se aplica (transporte apenas, sem mudança de apresentação).
|
||||||
|
|
||||||
|
## Decisões de engenharia
|
||||||
|
|
||||||
|
### Shim cliente vs refatoração interna da shared cell
|
||||||
|
|
||||||
|
**Opções:** A (shim: função cliente com assinatura de form action que chama `postCampaignJson`) | B (refatorar `RelationChipCell`/`RelationOptionCell` para `postCampaignJson` interno)
|
||||||
|
|
||||||
|
**Recomendação:** A — porque as shared cells têm múltiplos consumidores e a mudança de transporte é específica de `/campanha/liderancas`. Um shim é ~15 linhas, auto-contido no call site, e a assinatura `(state, formData) => Promise<{status, message}>` já é exatamente o que `postCampaignJson` resolve. As shared cells chamam `commitAction({}, formData)` como async function regular (não é `useActionState`), então qualquer função com a assinatura certa funciona.
|
||||||
|
|
||||||
|
**Rejeitadas:** B porque exigiria refatorar também os consumidores de assessores/dobradinhas, que não estão no escopo deste lote.
|
||||||
|
|
||||||
|
### F1: remover `formAction` prop vs wrapper interno
|
||||||
|
|
||||||
|
**Opções:** A (remover a prop, controle chama `postCampaignJson` direto) | B (manter a prop, passar um shim)
|
||||||
|
|
||||||
|
**Recomendação:** A — o `MunicipalityListSignalControl` tem 1 consumidor e é específico da lista de municípios. Remover a prop `formAction` simplifica o componente e o torna consistente com os controles irmãos (AdvisorsControl, LeadershipsControl, LevelControl, TrendControl — nenhum recebe form action, todos chamam `postCampaignJson` internamente).
|
||||||
|
|
||||||
|
**Rejeitadas:** B porque manteria uma prop desnecessária e um nível de indireção que os controles irmãos já não têm.
|
||||||
|
|
||||||
|
### Revalidação após mutation
|
||||||
|
|
||||||
|
**Situação:** As actions record (`setLeadershipStateDeputyMembership`, `setLeadershipMunicipalitiesMembership`, `createMunicipalityUpdate`) já fazem `revalidatePath` internamente. As form actions wrappers NÃO adicionavam revalidação extra para a lista de `/campanha/liderancas`. A intenção confirma: "as actions record reusadas já revalidam paths de detalhe; a lista onde o chip está NÃO é revalidada — contrato B34/B31."
|
||||||
|
|
||||||
|
**Decisão:** As novas rotas mantêm esse contrato — sem `revalidatePath` adicional. Se a lista precisar de refresh, o RSC re-fetch natural (navegação ou recarga) cobre. Alterar o contrato de revalidação agora seria mudança de comportamento, não de transporte.
|
||||||
|
|
||||||
|
## Fases verificáveis
|
||||||
|
|
||||||
|
### Fase 1 — F1: sinal de municípios (ROI mais alto — mesma superfície já no padrão)
|
||||||
|
|
||||||
|
1. Criar `src/app/(campaign)/campanha/(app)/municipios/signal/route.ts` + `types.ts`
|
||||||
|
2. Editar `MunicipalityListSignalControl`: remover `useActionState`/`formAction` prop, trocar por `postCampaignJson` + `useCampaignCellFailureChannel`
|
||||||
|
3. Remover `signalFormAction` prop de `MunicipalityList` e `municipios/page.tsx`
|
||||||
|
4. Remover `createMunicipalityListSignalFormAction` de `municipalityStaffFormActions.ts`
|
||||||
|
5. Atualizar `municipio/[slug]/v2/formActions.ts` (shim para a rota)
|
||||||
|
6. Atualizar `WizardSignalBodyStep` (usa `createMunicipalityListSignalFormAction` como `useActionState`)
|
||||||
|
7. Adicionar rota ao prewarm do e2e setup
|
||||||
|
8. Rodar gates: `pnpm gate:fast`, testes afetados
|
||||||
|
|
||||||
|
### Fase 2 — F2 + F3: colunas de `/campanha/liderancas`
|
||||||
|
|
||||||
|
1. Criar `src/app/(campaign)/campanha/(app)/liderancas/state-deputies/route.ts` + `types.ts`
|
||||||
|
2. Criar `src/app/(campaign)/campanha/(app)/liderancas/municipalities/route.ts` + `types.ts`
|
||||||
|
3. Criar shims cliente em `liderancas/page.tsx` (ou módulo auxiliar) que chamam `postCampaignJson`
|
||||||
|
4. Trocar `commitAction`/`membershipAction` em `liderancas/page.tsx` para os shims
|
||||||
|
5. Remover `setLeadershipStateDeputyMembershipFormAction` e `setLeadershipMunicipalitiesFormAction` de `liderancas/formActions.ts`
|
||||||
|
6. Adicionar rotas ao prewarm do e2e setup
|
||||||
|
7. Rodar gates: `pnpm gate:fast`, testes afetados (campaignLeaderships e2e)
|
||||||
|
|
||||||
|
### Fase 3 — Gates finais
|
||||||
|
|
||||||
|
1. `pnpm gate:fast` (todas as fases)
|
||||||
|
2. `pnpm exec knip` — remover exports órfãos
|
||||||
|
3. `pnpm check:cycles`
|
||||||
|
4. `pnpm test:e2e` — campaignMunicipalities, campaignLeaderships
|
||||||
|
5. `pnpm push` + PR + auto-merge
|
||||||
|
|
||||||
|
## Rabbit holes / Não escopo (engenharia)
|
||||||
|
|
||||||
|
- **Generalizar controles de chip** durante a migração — refactor de transporte apenas; os 2+2 controles seguem espelhos.
|
||||||
|
- **Mudar o contrato do sinal** (hoje sem debounce automático — `useCampaignCellAutosave` era mencionado na intenção mas o código atual não o usa; o controle faz submit explícito com botão "Registrar sinal").
|
||||||
|
- **Fundir com UX** — nenhum achado de critique nesta superfície; manter o lote só-engenharia.
|
||||||
|
- **Adicionar `revalidatePath` na lista de `/campanha/liderancas`** — seria mudança de comportamento, não de transporte.
|
||||||
|
|
||||||
|
## Riscos e mitigação
|
||||||
|
|
||||||
|
- **`WizardSignalBodyStep`:** Este componente usa `createMunicipalityListSignalFormAction` com `useActionState`. Migrar para rota exigiria mudar o fluxo do wizard (que hoje usa form POST). **Mitigação:** O `WizardSignalBodyStep` pode continuar usando uma server action — o que muda é que essa server action deixa de ser `createMunicipalityListSignalFormAction` (que era uma casca sobre `runCampaignFormAction`) e vira uma ação própria que chama `createMunicipalityUpdate` diretamente (ou via `postCampaignJson` — mas no wizard faz mais sentido manter server action, já que é um form multi-campo, não um quick-edit de célula). A intenção diz que "forms multi-campo usam server action" — e o wizard é exatamente isso. Então `createMunicipalityListSignalFormAction` é substituída por uma action local ao wizard.
|
||||||
|
- **`codebaseConventions`:** O teste varre `src/app` por `POST` handlers sem `campaignJsonMutationRoute`. As 3 novas rotas entram automaticamente no enforcement. **Mitigação:** As rotas são criadas com `campaignJsonMutationRoute` desde o início.
|
||||||
|
- **`knip`:** Remover as 3 form actions vai orfanar exports. **Mitigação:** Rodar `pnpm exec knip` e verificar cada remoção com `git grep`.
|
||||||
|
|
||||||
|
## Aceite de engenharia
|
||||||
|
|
||||||
|
- [ ] Aceite de produto da intenção ainda coberto
|
||||||
|
- [ ] Invariantes AGENTS/engineering-standards
|
||||||
|
- [ ] Testes de domínio previstos (unit/int) onde access/write paths mudam
|
||||||
|
- [ ] `codebaseConventions` — novas rotas passam no sweep
|
||||||
|
- [ ] `knip` — zero novos exports órfãos
|
||||||
|
- [ ] `pnpm check:cycles` — zero ciclos
|
||||||
|
|
@ -1,18 +1,8 @@
|
||||||
'use server'
|
'use server'
|
||||||
|
|
||||||
import { leadershipStaffEditSafeMessages } from '@/app/(campaign)/campanha/(app)/liderancas/leadershipStaffEditMessages'
|
import { leadershipStaffEditSafeMessages } from '@/app/(campaign)/campanha/(app)/liderancas/leadershipStaffEditMessages'
|
||||||
import {
|
import { updateLeadershipContact } from '@/app/(campaign)/campanha/actions/leadership'
|
||||||
setLeadershipMunicipalitiesMembership,
|
import { nullableFormText, requiredFormText, requiredRelationshipFormValue } from '@/lib/formData'
|
||||||
setLeadershipStateDeputyMembership,
|
|
||||||
updateLeadershipContact,
|
|
||||||
} from '@/app/(campaign)/campanha/actions/leadership'
|
|
||||||
import {
|
|
||||||
nullableFormText,
|
|
||||||
repeatedRelationshipFormValues,
|
|
||||||
requiredFormBoolean,
|
|
||||||
requiredFormText,
|
|
||||||
requiredRelationshipFormValue,
|
|
||||||
} from '@/lib/formData'
|
|
||||||
import {
|
import {
|
||||||
LEADERSHIP_INVALID_CONTACT_MESSAGE,
|
LEADERSHIP_INVALID_CONTACT_MESSAGE,
|
||||||
LEADERSHIP_MUNICIPALITY_CAP_MESSAGE,
|
LEADERSHIP_MUNICIPALITY_CAP_MESSAGE,
|
||||||
|
|
@ -80,44 +70,3 @@ export const updateLeadershipContactFormAction = async (
|
||||||
safeMessages,
|
safeMessages,
|
||||||
genericMessage: 'Não foi possível salvar. Verifique os dados e tente novamente.',
|
genericMessage: 'Não foi possível salvar. Verifique os dados e tente novamente.',
|
||||||
})
|
})
|
||||||
|
|
||||||
/** One chip toggle in the "Dobradinhas" column of `/campanha/liderancas` (B31). */
|
|
||||||
export const setLeadershipStateDeputyMembershipFormAction = async (
|
|
||||||
_state: CampaignFormActionState,
|
|
||||||
formData: FormData,
|
|
||||||
): Promise<CampaignFormActionState> =>
|
|
||||||
runCampaignFormAction({
|
|
||||||
execute: async () => {
|
|
||||||
await setLeadershipStateDeputyMembership({
|
|
||||||
leadershipId: requiredRelationshipFormValue(formData, 'leadershipId'),
|
|
||||||
stateDeputyId: requiredRelationshipFormValue(formData, 'stateDeputyId'),
|
|
||||||
assigned: requiredFormBoolean(formData, 'assigned'),
|
|
||||||
})
|
|
||||||
return { message: 'Dobradinhas atualizadas.' }
|
|
||||||
},
|
|
||||||
safeMessages,
|
|
||||||
genericMessage: 'Não foi possível atualizar as dobradinhas. Tente novamente.',
|
|
||||||
})
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Add or remove municipalities in the "Municípios" column of
|
|
||||||
* `/campanha/liderancas` (B34) — one chip or a whole território/ZE. `ownerId` is
|
|
||||||
* the field name `MunicipalityPortfolioCell` sends, so the same cell serves
|
|
||||||
* lideranças and assessores.
|
|
||||||
*/
|
|
||||||
export const setLeadershipMunicipalitiesFormAction = async (
|
|
||||||
_state: CampaignFormActionState,
|
|
||||||
formData: FormData,
|
|
||||||
): Promise<CampaignFormActionState> =>
|
|
||||||
runCampaignFormAction({
|
|
||||||
execute: async () => {
|
|
||||||
await setLeadershipMunicipalitiesMembership({
|
|
||||||
leadershipId: requiredRelationshipFormValue(formData, 'ownerId'),
|
|
||||||
municipalityIds: repeatedRelationshipFormValues(formData, 'municipalityIds'),
|
|
||||||
assigned: requiredFormBoolean(formData, 'assigned'),
|
|
||||||
})
|
|
||||||
return { message: 'Municípios atualizados.' }
|
|
||||||
},
|
|
||||||
safeMessages,
|
|
||||||
genericMessage: 'Não foi possível atualizar os municípios. Tente novamente.',
|
|
||||||
})
|
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,45 @@
|
||||||
|
import { NextResponse } from 'next/server'
|
||||||
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
import { leadershipStaffEditSafeMessages } from '@/app/(campaign)/campanha/(app)/liderancas/leadershipStaffEditMessages'
|
||||||
|
import { setLeadershipMunicipalitiesMembership } from '@/app/(campaign)/campanha/actions/leadership'
|
||||||
|
import { MAX_LEADERSHIP_MUNICIPALITIES } from '@/lib/schemas/leadership'
|
||||||
|
import { positiveRelationshipId } from '@/lib/schemas/primitives'
|
||||||
|
import { campaignJsonMutationRoute } from '@/utilities/campaignJsonMutationRoute'
|
||||||
|
|
||||||
|
import type { LeadershipListMunicipalitiesResponse } from './types'
|
||||||
|
|
||||||
|
export type { LeadershipListMunicipalitiesResponse } from './types'
|
||||||
|
|
||||||
|
export const dynamic = 'force-dynamic'
|
||||||
|
|
||||||
|
/** Matches `leadershipMunicipalitiesMembershipSchema` exactly. */
|
||||||
|
const bodySchema = z.object({
|
||||||
|
leadershipId: positiveRelationshipId,
|
||||||
|
municipalityIds: z
|
||||||
|
.array(positiveRelationshipId)
|
||||||
|
.min(1)
|
||||||
|
.max(MAX_LEADERSHIP_MUNICIPALITIES)
|
||||||
|
.transform((ids) => [...new Set(ids)]),
|
||||||
|
assigned: z.boolean(),
|
||||||
|
})
|
||||||
|
|
||||||
|
export const POST = campaignJsonMutationRoute(
|
||||||
|
{
|
||||||
|
bodySchema,
|
||||||
|
safeMessages: leadershipStaffEditSafeMessages,
|
||||||
|
genericMessage: 'Não foi possível atualizar os municípios. Tente novamente.',
|
||||||
|
},
|
||||||
|
async ({ leadershipId, municipalityIds, assigned }) => {
|
||||||
|
await setLeadershipMunicipalitiesMembership({
|
||||||
|
leadershipId,
|
||||||
|
municipalityIds,
|
||||||
|
assigned,
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.json<LeadershipListMunicipalitiesResponse>({
|
||||||
|
status: 'success',
|
||||||
|
message: 'Municípios atualizados.',
|
||||||
|
})
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
@ -0,0 +1,9 @@
|
||||||
|
export type LeadershipListMunicipalitiesResponse =
|
||||||
|
| {
|
||||||
|
status: 'success'
|
||||||
|
message: string
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
status: 'error'
|
||||||
|
message: string
|
||||||
|
}
|
||||||
|
|
@ -8,10 +8,12 @@ import { LeadershipInviteRowAction } from '@/components/campaign/invite/Leadersh
|
||||||
import { LeadershipContactFieldControl } from '@/components/campaign/leadership/LeadershipContactFieldControl'
|
import { LeadershipContactFieldControl } from '@/components/campaign/leadership/LeadershipContactFieldControl'
|
||||||
import { LeadershipFilters } from '@/components/campaign/leadership/LeadershipFilters'
|
import { LeadershipFilters } from '@/components/campaign/leadership/LeadershipFilters'
|
||||||
import { LeadershipListSupportStatusControl } from '@/components/campaign/leadership/LeadershipListSupportStatusControl'
|
import { LeadershipListSupportStatusControl } from '@/components/campaign/leadership/LeadershipListSupportStatusControl'
|
||||||
|
import { LeadershipMunicipalitiesColumnCell } from '@/components/campaign/leadership/LeadershipMunicipalitiesColumnCell'
|
||||||
import {
|
import {
|
||||||
LeadershipFilterHead,
|
LeadershipFilterHead,
|
||||||
LeadershipSortableHead,
|
LeadershipSortableHead,
|
||||||
} from '@/components/campaign/leadership/LeadershipSortableHead'
|
} from '@/components/campaign/leadership/LeadershipSortableHead'
|
||||||
|
import { LeadershipStateDeputiesColumnCell } from '@/components/campaign/leadership/LeadershipStateDeputiesColumnCell'
|
||||||
import { CampaignColumnPickerTrailing } from '@/components/campaign/shared/CampaignColumnPickerTrailing'
|
import { CampaignColumnPickerTrailing } from '@/components/campaign/shared/CampaignColumnPickerTrailing'
|
||||||
import { CampaignListFooter } from '@/components/campaign/shared/CampaignListFooter'
|
import { CampaignListFooter } from '@/components/campaign/shared/CampaignListFooter'
|
||||||
import {
|
import {
|
||||||
|
|
@ -25,11 +27,7 @@ import {
|
||||||
CampaignTableHead,
|
CampaignTableHead,
|
||||||
type CampaignTableColumn,
|
type CampaignTableColumn,
|
||||||
} from '@/components/campaign/shared/CampaignTable'
|
} from '@/components/campaign/shared/CampaignTable'
|
||||||
import {
|
import { type RelationCellOption } from '@/components/campaign/shared/LeadershipStateDeputyRelationCell'
|
||||||
LeadershipStateDeputyRelationCell,
|
|
||||||
type RelationCellOption,
|
|
||||||
} from '@/components/campaign/shared/LeadershipStateDeputyRelationCell'
|
|
||||||
import { MunicipalityPortfolioCell } from '@/components/campaign/shared/MunicipalityPortfolioCell'
|
|
||||||
import { CampaignPageShell } from '@/components/campaign/shell/CampaignPageShell'
|
import { CampaignPageShell } from '@/components/campaign/shell/CampaignPageShell'
|
||||||
import { Badge } from '@/components/ui/Badge'
|
import { Badge } from '@/components/ui/Badge'
|
||||||
import { Button, buttonVariants } from '@/components/ui/button'
|
import { Button, buttonVariants } from '@/components/ui/button'
|
||||||
|
|
@ -78,11 +76,6 @@ import { loadOrganizationNamesByIds } from '@/utilities/loadNamesByIds'
|
||||||
import { loadMunicipalityPortfolioIndex } from '@/utilities/municipality/municipalityPortfolioIndex'
|
import { loadMunicipalityPortfolioIndex } from '@/utilities/municipality/municipalityPortfolioIndex'
|
||||||
import { loadStateDeputySummaries } from '@/utilities/stateDeputyData'
|
import { loadStateDeputySummaries } from '@/utilities/stateDeputyData'
|
||||||
|
|
||||||
import {
|
|
||||||
setLeadershipMunicipalitiesFormAction,
|
|
||||||
setLeadershipStateDeputyMembershipFormAction,
|
|
||||||
} from './formActions'
|
|
||||||
|
|
||||||
export const metadata = campaignPageMetadataFromCatalog('liderancas')
|
export const metadata = campaignPageMetadataFromCatalog('liderancas')
|
||||||
|
|
||||||
type LeadershipsPageProps = {
|
type LeadershipsPageProps = {
|
||||||
|
|
@ -192,7 +185,7 @@ const leadershipColumns = ({
|
||||||
),
|
),
|
||||||
cellClassName: 'max-w-64 whitespace-normal',
|
cellClassName: 'max-w-64 whitespace-normal',
|
||||||
cell: (row) => (
|
cell: (row) => (
|
||||||
<MunicipalityPortfolioCell
|
<LeadershipMunicipalitiesColumnCell
|
||||||
ownerId={row.id}
|
ownerId={row.id}
|
||||||
ownerName={row.name}
|
ownerName={row.name}
|
||||||
municipalityIds={row.municipalityIDs}
|
municipalityIds={row.municipalityIDs}
|
||||||
|
|
@ -200,7 +193,6 @@ const leadershipColumns = ({
|
||||||
{...(addableMunicipalityIds ? { addableIds: addableMunicipalityIds } : {})}
|
{...(addableMunicipalityIds ? { addableIds: addableMunicipalityIds } : {})}
|
||||||
minItems={1}
|
minItems={1}
|
||||||
maxItems={MAX_LEADERSHIP_MUNICIPALITIES}
|
maxItems={MAX_LEADERSHIP_MUNICIPALITIES}
|
||||||
commitAction={setLeadershipMunicipalitiesFormAction}
|
|
||||||
drawerTitle="Municípios da liderança"
|
drawerTitle="Municípios da liderança"
|
||||||
updateErrorMessage="Não foi possível atualizar os municípios."
|
updateErrorMessage="Não foi possível atualizar os municípios."
|
||||||
/>
|
/>
|
||||||
|
|
@ -217,7 +209,7 @@ const leadershipColumns = ({
|
||||||
label: 'Dobradinhas',
|
label: 'Dobradinhas',
|
||||||
cellClassName: 'max-w-56 whitespace-normal',
|
cellClassName: 'max-w-56 whitespace-normal',
|
||||||
cell: (row) => (
|
cell: (row) => (
|
||||||
<LeadershipStateDeputyRelationCell
|
<LeadershipStateDeputiesColumnCell
|
||||||
direction="fromLeadership"
|
direction="fromLeadership"
|
||||||
fixedId={row.id}
|
fixedId={row.id}
|
||||||
ownerName={row.name}
|
ownerName={row.name}
|
||||||
|
|
@ -228,7 +220,6 @@ const leadershipColumns = ({
|
||||||
...(deputy.party ? { party: deputy.party } : {}),
|
...(deputy.party ? { party: deputy.party } : {}),
|
||||||
}))}
|
}))}
|
||||||
options={stateDeputyOptions}
|
options={stateDeputyOptions}
|
||||||
membershipAction={setLeadershipStateDeputyMembershipFormAction}
|
|
||||||
measureOverflow={false}
|
measureOverflow={false}
|
||||||
/>
|
/>
|
||||||
),
|
),
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,35 @@
|
||||||
|
import { NextResponse } from 'next/server'
|
||||||
|
|
||||||
|
import { leadershipStaffEditSafeMessages } from '@/app/(campaign)/campanha/(app)/liderancas/leadershipStaffEditMessages'
|
||||||
|
import { setLeadershipStateDeputyMembership } from '@/app/(campaign)/campanha/actions/leadership'
|
||||||
|
import { leadershipStateDeputyMembershipSchema } from '@/lib/schemas/leadership'
|
||||||
|
import { campaignJsonMutationRoute } from '@/utilities/campaignJsonMutationRoute'
|
||||||
|
|
||||||
|
import type { LeadershipListStateDeputiesResponse } from './types'
|
||||||
|
|
||||||
|
export type { LeadershipListStateDeputiesResponse } from './types'
|
||||||
|
|
||||||
|
export const dynamic = 'force-dynamic'
|
||||||
|
|
||||||
|
/** Matches `leadershipStateDeputyMembershipSchema` exactly. */
|
||||||
|
const bodySchema = leadershipStateDeputyMembershipSchema
|
||||||
|
|
||||||
|
export const POST = campaignJsonMutationRoute(
|
||||||
|
{
|
||||||
|
bodySchema,
|
||||||
|
safeMessages: leadershipStaffEditSafeMessages,
|
||||||
|
genericMessage: 'Não foi possível atualizar as dobradinhas. Tente novamente.',
|
||||||
|
},
|
||||||
|
async ({ leadershipId, stateDeputyId, assigned }) => {
|
||||||
|
await setLeadershipStateDeputyMembership({
|
||||||
|
leadershipId,
|
||||||
|
stateDeputyId,
|
||||||
|
assigned,
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.json<LeadershipListStateDeputiesResponse>({
|
||||||
|
status: 'success',
|
||||||
|
message: assigned ? 'Dobradinha vinculada.' : 'Dobradinha removida.',
|
||||||
|
})
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
@ -0,0 +1,9 @@
|
||||||
|
export type LeadershipListStateDeputiesResponse =
|
||||||
|
| {
|
||||||
|
status: 'success'
|
||||||
|
message: string
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
status: 'error'
|
||||||
|
message: string
|
||||||
|
}
|
||||||
|
|
@ -1,9 +1,36 @@
|
||||||
'use server'
|
'use server'
|
||||||
|
|
||||||
import { createMunicipalityListSignalFormAction } from '@/app/(campaign)/campanha/(app)/municipios/municipalityStaffFormActions'
|
import { createMunicipalityUpdate } from '@/app/(campaign)/campanha/actions/municipalityUpdate'
|
||||||
import type { CampaignFormActionState } from '@/utilities/campaignFormActionError'
|
import {
|
||||||
|
optionalFormText,
|
||||||
|
optionalMunicipalitySlugFromForm,
|
||||||
|
requiredRelationshipFormValue,
|
||||||
|
} from '@/lib/formData'
|
||||||
|
import { parseMunicipalitySignalType } from '@/lib/schemas/municipalityUpdate'
|
||||||
|
import { WIZARD_SIGNAL_SAVED_MESSAGE } from '@/lib/wizardSignalUi'
|
||||||
|
import {
|
||||||
|
runCampaignFormAction,
|
||||||
|
type CampaignFormActionState,
|
||||||
|
} from '@/utilities/campaignFormActionError'
|
||||||
|
import { revalidateMunicipalityListPaths } from '@/utilities/municipality/municipalityRevalidation'
|
||||||
|
|
||||||
/** Thin alias — same write path as the list signal control (B147). */
|
/** Thin alias — same write path as the list signal control (B147). */
|
||||||
export const createMunicipalityV2SignalFormAction = async (
|
export const createMunicipalityV2SignalFormAction = async (
|
||||||
|
_state: CampaignFormActionState,
|
||||||
formData: FormData,
|
formData: FormData,
|
||||||
): Promise<CampaignFormActionState> => createMunicipalityListSignalFormAction({}, formData)
|
): Promise<CampaignFormActionState> =>
|
||||||
|
runCampaignFormAction({
|
||||||
|
execute: async () => {
|
||||||
|
const municipality = requiredRelationshipFormValue(formData, 'municipalityId')
|
||||||
|
|
||||||
|
await createMunicipalityUpdate({
|
||||||
|
municipality,
|
||||||
|
kind: 'sinal',
|
||||||
|
body: optionalFormText(formData, 'body'),
|
||||||
|
signalType: parseMunicipalitySignalType(optionalFormText(formData, 'signalType')),
|
||||||
|
})
|
||||||
|
revalidateMunicipalityListPaths({ slug: optionalMunicipalitySlugFromForm(formData) })
|
||||||
|
return { message: WIZARD_SIGNAL_SAVED_MESSAGE }
|
||||||
|
},
|
||||||
|
genericMessage: 'Não foi possível registrar o sinal. Verifique seu acesso e tente novamente.',
|
||||||
|
})
|
||||||
|
|
|
||||||
|
|
@ -61,7 +61,7 @@ export default async function MunicipalityV2Page({ params }: MunicipalityV2PageP
|
||||||
<div className="flex flex-col gap-8">
|
<div className="flex flex-col gap-8">
|
||||||
<MunicipalityV2StatusStrip
|
<MunicipalityV2StatusStrip
|
||||||
status={status}
|
status={status}
|
||||||
signalFormAction={createMunicipalityV2SignalFormAction}
|
signalFormAction={(formData) => createMunicipalityV2SignalFormAction({}, formData)}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<MunicipalityV2LocalAccountSection
|
<MunicipalityV2LocalAccountSection
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,6 @@ import {
|
||||||
setMunicipalityExpectedVotes,
|
setMunicipalityExpectedVotes,
|
||||||
setMunicipalityPoliticalTrend,
|
setMunicipalityPoliticalTrend,
|
||||||
} from '@/app/(campaign)/campanha/actions/municipality'
|
} from '@/app/(campaign)/campanha/actions/municipality'
|
||||||
import { createMunicipalityUpdate } from '@/app/(campaign)/campanha/actions/municipalityUpdate'
|
|
||||||
import {
|
import {
|
||||||
createMunicipalityStateDeputy,
|
createMunicipalityStateDeputy,
|
||||||
setStateDeputyMunicipalitiesBatch,
|
setStateDeputyMunicipalitiesBatch,
|
||||||
|
|
@ -27,14 +26,12 @@ import {
|
||||||
MUNICIPALITY_STATE_DEPUTIES_CAP_MESSAGE,
|
MUNICIPALITY_STATE_DEPUTIES_CAP_MESSAGE,
|
||||||
parsePoliticalTrendStatusFormValue,
|
parsePoliticalTrendStatusFormValue,
|
||||||
} from '@/lib/schemas/municipality'
|
} from '@/lib/schemas/municipality'
|
||||||
import { parseMunicipalitySignalType } from '@/lib/schemas/municipalityUpdate'
|
|
||||||
import {
|
import {
|
||||||
STATE_DEPUTY_CONFLICT_MESSAGE,
|
STATE_DEPUTY_CONFLICT_MESSAGE,
|
||||||
STATE_DEPUTY_MUNICIPALITIES_SAFE_MESSAGES,
|
STATE_DEPUTY_MUNICIPALITIES_SAFE_MESSAGES,
|
||||||
STATE_DEPUTY_NAME_REQUIRED_MESSAGE,
|
STATE_DEPUTY_NAME_REQUIRED_MESSAGE,
|
||||||
STATE_DEPUTY_STAFF_MESSAGE,
|
STATE_DEPUTY_STAFF_MESSAGE,
|
||||||
} from '@/lib/schemas/stateDeputy'
|
} from '@/lib/schemas/stateDeputy'
|
||||||
import { WIZARD_SIGNAL_SAVED_MESSAGE } from '@/lib/wizardSignalUi'
|
|
||||||
import {
|
import {
|
||||||
runCampaignFormAction,
|
runCampaignFormAction,
|
||||||
type CampaignFormActionState,
|
type CampaignFormActionState,
|
||||||
|
|
@ -101,26 +98,6 @@ export const assignMunicipalityAdvisorsFormAction = async (
|
||||||
'Não foi possível atualizar os assessores. Verifique seu acesso e tente novamente.',
|
'Não foi possível atualizar os assessores. Verifique seu acesso e tente novamente.',
|
||||||
})
|
})
|
||||||
|
|
||||||
export const createMunicipalityListSignalFormAction = async (
|
|
||||||
_state: CampaignFormActionState,
|
|
||||||
formData: FormData,
|
|
||||||
): Promise<CampaignFormActionState> =>
|
|
||||||
runCampaignFormAction({
|
|
||||||
execute: async () => {
|
|
||||||
const municipality = requiredRelationshipFormValue(formData, 'municipalityId')
|
|
||||||
|
|
||||||
await createMunicipalityUpdate({
|
|
||||||
municipality,
|
|
||||||
kind: 'sinal',
|
|
||||||
body: optionalFormText(formData, 'body'),
|
|
||||||
signalType: parseMunicipalitySignalType(optionalFormText(formData, 'signalType')),
|
|
||||||
})
|
|
||||||
revalidateMunicipalityListPaths({ slug: optionalMunicipalitySlugFromForm(formData) })
|
|
||||||
return { message: WIZARD_SIGNAL_SAVED_MESSAGE }
|
|
||||||
},
|
|
||||||
genericMessage: 'Não foi possível registrar o sinal. Verifique seu acesso e tente novamente.',
|
|
||||||
})
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* B157 — one chip toggle in the "Dobradinhas" column of `/campanha/municipios`.
|
* B157 — one chip toggle in the "Dobradinhas" column of `/campanha/municipios`.
|
||||||
* Deliberately NOT a new record: the B37 batch already owns the inverted write
|
* Deliberately NOT a new record: the B37 batch already owns the inverted write
|
||||||
|
|
|
||||||
|
|
@ -41,7 +41,6 @@ import {
|
||||||
loadAdvisorSummaries,
|
loadAdvisorSummaries,
|
||||||
} from '@/utilities/municipality/municipalityViewModels'
|
} from '@/utilities/municipality/municipalityViewModels'
|
||||||
import {
|
import {
|
||||||
createMunicipalityListSignalFormAction,
|
|
||||||
createMunicipalityStateDeputyFormAction,
|
createMunicipalityStateDeputyFormAction,
|
||||||
setMunicipalityStateDeputiesFormAction,
|
setMunicipalityStateDeputiesFormAction,
|
||||||
} from './municipalityStaffFormActions'
|
} from './municipalityStaffFormActions'
|
||||||
|
|
@ -154,7 +153,6 @@ export default async function MunicipalitiesPage({ searchParams }: Municipalitie
|
||||||
stateDeputyCommitAction={setMunicipalityStateDeputiesFormAction}
|
stateDeputyCommitAction={setMunicipalityStateDeputiesFormAction}
|
||||||
stateDeputyCreateAction={createMunicipalityStateDeputyFormAction}
|
stateDeputyCreateAction={createMunicipalityStateDeputyFormAction}
|
||||||
columnFilterOptions={columnFilterOptions}
|
columnFilterOptions={columnFilterOptions}
|
||||||
signalFormAction={createMunicipalityListSignalFormAction}
|
|
||||||
state={state}
|
state={state}
|
||||||
columnVisibility={columnVisibility}
|
columnVisibility={columnVisibility}
|
||||||
/>
|
/>
|
||||||
|
|
|
||||||
44
src/app/(campaign)/campanha/(app)/municipios/signal/route.ts
Normal file
44
src/app/(campaign)/campanha/(app)/municipios/signal/route.ts
Normal file
|
|
@ -0,0 +1,44 @@
|
||||||
|
import { NextResponse } from 'next/server'
|
||||||
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
import { municipalityStaffEditSafeMessages } from '@/app/(campaign)/campanha/(app)/municipios/municipalityStaffEditMessages'
|
||||||
|
import { createMunicipalityUpdate } from '@/app/(campaign)/campanha/actions/municipalityUpdate'
|
||||||
|
import { municipalitySignalTypes } from '@/lib/schemas/municipalityUpdate'
|
||||||
|
import { positiveRelationshipId, trimmedOptionalText } from '@/lib/schemas/primitives'
|
||||||
|
import { campaignJsonMutationRoute } from '@/utilities/campaignJsonMutationRoute'
|
||||||
|
import { revalidateMunicipalityListPaths } from '@/utilities/municipality/municipalityRevalidation'
|
||||||
|
|
||||||
|
import type { MunicipalityListSignalResponse } from './types'
|
||||||
|
|
||||||
|
export type { MunicipalityListSignalResponse } from './types'
|
||||||
|
|
||||||
|
export const dynamic = 'force-dynamic'
|
||||||
|
|
||||||
|
const bodySchema = z.object({
|
||||||
|
municipalityId: positiveRelationshipId,
|
||||||
|
body: trimmedOptionalText(5000).optional(),
|
||||||
|
signalType: z.enum(municipalitySignalTypes).optional(),
|
||||||
|
})
|
||||||
|
|
||||||
|
export const POST = campaignJsonMutationRoute(
|
||||||
|
{
|
||||||
|
bodySchema,
|
||||||
|
safeMessages: municipalityStaffEditSafeMessages,
|
||||||
|
genericMessage: 'Não foi possível registrar o sinal. Verifique seu acesso e tente novamente.',
|
||||||
|
},
|
||||||
|
async ({ municipalityId, body, signalType }) => {
|
||||||
|
await createMunicipalityUpdate({
|
||||||
|
municipality: municipalityId,
|
||||||
|
kind: 'sinal',
|
||||||
|
body: body ?? undefined,
|
||||||
|
signalType,
|
||||||
|
})
|
||||||
|
|
||||||
|
revalidateMunicipalityListPaths({})
|
||||||
|
|
||||||
|
return NextResponse.json<MunicipalityListSignalResponse>({
|
||||||
|
status: 'success',
|
||||||
|
message: 'Sinal registrado.',
|
||||||
|
})
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
@ -0,0 +1,9 @@
|
||||||
|
export type MunicipalityListSignalResponse =
|
||||||
|
| {
|
||||||
|
status: 'success'
|
||||||
|
message: string
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
status: 'error'
|
||||||
|
message: string
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,58 @@
|
||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useMemo } from 'react'
|
||||||
|
|
||||||
|
import type { LeadershipListMunicipalitiesResponse } from '@/app/(campaign)/campanha/(app)/liderancas/municipalities/types'
|
||||||
|
import { CampaignListSheetProvider } from '@/components/campaign/shared/CampaignListSheetHost'
|
||||||
|
import {
|
||||||
|
MunicipalityPortfolioCell,
|
||||||
|
type MunicipalityPortfolioCellProps,
|
||||||
|
} from '@/components/campaign/shared/MunicipalityPortfolioCell'
|
||||||
|
import { postCampaignJson } from '@/lib/campaignJsonRequest'
|
||||||
|
import type { CampaignFormActionState } from '@/utilities/campaignFormActionError'
|
||||||
|
|
||||||
|
const ENDPOINT = '/campanha/liderancas/municipalities'
|
||||||
|
const GENERIC_ERROR = 'Não foi possível atualizar os municípios. Tente novamente.'
|
||||||
|
|
||||||
|
type Props = Omit<MunicipalityPortfolioCellProps, 'commitAction'>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Thin adapter: wraps `MunicipalityPortfolioCell` with a route-based
|
||||||
|
* `commitAction` that posts JSON to `POST /campanha/liderancas/municipalities`.
|
||||||
|
*/
|
||||||
|
export const LeadershipMunicipalitiesColumnCell = (props: Props) => {
|
||||||
|
const commitAction = useMemo(
|
||||||
|
() =>
|
||||||
|
async (
|
||||||
|
_state: CampaignFormActionState,
|
||||||
|
formData: FormData,
|
||||||
|
): Promise<CampaignFormActionState> => {
|
||||||
|
const leadershipId = Number(formData.get('ownerId'))
|
||||||
|
const assigned = formData.get('assigned') === 'true'
|
||||||
|
const municipalityIds = formData.getAll('municipalityIds').map(Number)
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { ok, payload } = await postCampaignJson<LeadershipListMunicipalitiesResponse>(
|
||||||
|
ENDPOINT,
|
||||||
|
{ leadershipId, municipalityIds, assigned },
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!ok || payload.status !== 'success') {
|
||||||
|
return {
|
||||||
|
message: payload.status === 'error' ? payload.message : GENERIC_ERROR,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { status: 'success' as const, message: payload.message }
|
||||||
|
} catch {
|
||||||
|
return { message: GENERIC_ERROR }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<CampaignListSheetProvider>
|
||||||
|
<MunicipalityPortfolioCell {...props} commitAction={commitAction} />
|
||||||
|
</CampaignListSheetProvider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,58 @@
|
||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useMemo } from 'react'
|
||||||
|
|
||||||
|
import type { LeadershipListStateDeputiesResponse } from '@/app/(campaign)/campanha/(app)/liderancas/state-deputies/types'
|
||||||
|
import { CampaignListSheetProvider } from '@/components/campaign/shared/CampaignListSheetHost'
|
||||||
|
import {
|
||||||
|
LeadershipStateDeputyRelationCell,
|
||||||
|
type LeadershipStateDeputyRelationCellProps,
|
||||||
|
} from '@/components/campaign/shared/LeadershipStateDeputyRelationCell'
|
||||||
|
import { postCampaignJson } from '@/lib/campaignJsonRequest'
|
||||||
|
import type { CampaignFormActionState } from '@/utilities/campaignFormActionError'
|
||||||
|
|
||||||
|
const ENDPOINT = '/campanha/liderancas/state-deputies'
|
||||||
|
const GENERIC_ERROR = 'Não foi possível atualizar as dobradinhas. Tente novamente.'
|
||||||
|
|
||||||
|
type Props = Omit<LeadershipStateDeputyRelationCellProps, 'membershipAction'>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Thin adapter: wraps `LeadershipStateDeputyRelationCell` with a route-based
|
||||||
|
* `membershipAction` that posts JSON to `POST /campanha/liderancas/state-deputies`.
|
||||||
|
*/
|
||||||
|
export const LeadershipStateDeputiesColumnCell = (props: Props) => {
|
||||||
|
const membershipAction = useMemo(
|
||||||
|
() =>
|
||||||
|
async (
|
||||||
|
_state: CampaignFormActionState,
|
||||||
|
formData: FormData,
|
||||||
|
): Promise<CampaignFormActionState> => {
|
||||||
|
const leadershipId = Number(formData.get('leadershipId'))
|
||||||
|
const stateDeputyId = Number(formData.get('stateDeputyId'))
|
||||||
|
const assigned = formData.get('assigned') === 'true'
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { ok, payload } = await postCampaignJson<LeadershipListStateDeputiesResponse>(
|
||||||
|
ENDPOINT,
|
||||||
|
{ leadershipId, stateDeputyId, assigned },
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!ok || payload.status !== 'success') {
|
||||||
|
return {
|
||||||
|
message: payload.status === 'error' ? payload.message : GENERIC_ERROR,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { status: 'success' as const, message: payload.message }
|
||||||
|
} catch {
|
||||||
|
return { message: GENERIC_ERROR }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<CampaignListSheetProvider>
|
||||||
|
<LeadershipStateDeputyRelationCell {...props} membershipAction={membershipAction} />
|
||||||
|
</CampaignListSheetProvider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -115,7 +115,6 @@ export type MunicipalityListProps = {
|
||||||
stateDeputyCommitAction: MunicipalityStaffFormAction
|
stateDeputyCommitAction: MunicipalityStaffFormAction
|
||||||
stateDeputyCreateAction: MunicipalityStateDeputyCreateAction
|
stateDeputyCreateAction: MunicipalityStateDeputyCreateAction
|
||||||
columnFilterOptions: MunicipalityColumnFilterOptions
|
columnFilterOptions: MunicipalityColumnFilterOptions
|
||||||
signalFormAction: MunicipalityStaffFormAction
|
|
||||||
state: MunicipalityListState
|
state: MunicipalityListState
|
||||||
columnVisibility: CampaignColumnVisibility
|
columnVisibility: CampaignColumnVisibility
|
||||||
}
|
}
|
||||||
|
|
@ -173,7 +172,6 @@ const municipalityListColumns = ({
|
||||||
stateDeputyOptions,
|
stateDeputyOptions,
|
||||||
stateDeputyCommitAction,
|
stateDeputyCommitAction,
|
||||||
stateDeputyCreateAction,
|
stateDeputyCreateAction,
|
||||||
signalFormAction,
|
|
||||||
}: MunicipalityListProps): Array<MunicipalityColumn> => [
|
}: MunicipalityListProps): Array<MunicipalityColumn> => [
|
||||||
{
|
{
|
||||||
id: 'name',
|
id: 'name',
|
||||||
|
|
@ -453,7 +451,6 @@ const municipalityListColumns = ({
|
||||||
municipalityName={municipality.name}
|
municipalityName={municipality.name}
|
||||||
lastSignalAt={municipality.lastSignalAt}
|
lastSignalAt={municipality.lastSignalAt}
|
||||||
variant="popover"
|
variant="popover"
|
||||||
formAction={signalFormAction}
|
|
||||||
>
|
>
|
||||||
<SignalAgeReadout lastSignalAt={municipality.lastSignalAt} layout="table" />
|
<SignalAgeReadout lastSignalAt={municipality.lastSignalAt} layout="table" />
|
||||||
</MunicipalityListSignalControl>
|
</MunicipalityListSignalControl>
|
||||||
|
|
@ -567,7 +564,6 @@ export const MunicipalityList = (props: MunicipalityListProps) => {
|
||||||
stateDeputyOptions={stateDeputyOptions}
|
stateDeputyOptions={stateDeputyOptions}
|
||||||
stateDeputyCommitAction={stateDeputyCommitAction}
|
stateDeputyCommitAction={stateDeputyCommitAction}
|
||||||
stateDeputyCreateAction={stateDeputyCreateAction}
|
stateDeputyCreateAction={stateDeputyCreateAction}
|
||||||
signalFormAction={props.signalFormAction}
|
|
||||||
emptySlot={<MunicipalityListEmptyState state={state} />}
|
emptySlot={<MunicipalityListEmptyState state={state} />}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -59,7 +59,6 @@ export type MunicipalityListMobileCardsProps = {
|
||||||
stateDeputyOptions: StateDeputyRelationOption[]
|
stateDeputyOptions: StateDeputyRelationOption[]
|
||||||
stateDeputyCommitAction: MunicipalityStaffFormAction
|
stateDeputyCommitAction: MunicipalityStaffFormAction
|
||||||
stateDeputyCreateAction: MunicipalityStateDeputyCreateAction
|
stateDeputyCreateAction: MunicipalityStateDeputyCreateAction
|
||||||
signalFormAction: MunicipalityStaffFormAction
|
|
||||||
emptySlot: ReactNode
|
emptySlot: ReactNode
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -80,7 +79,6 @@ export const MunicipalityListMobileCards = ({
|
||||||
stateDeputyOptions,
|
stateDeputyOptions,
|
||||||
stateDeputyCommitAction,
|
stateDeputyCommitAction,
|
||||||
stateDeputyCreateAction,
|
stateDeputyCreateAction,
|
||||||
signalFormAction,
|
|
||||||
emptySlot,
|
emptySlot,
|
||||||
}: MunicipalityListMobileCardsProps) => (
|
}: MunicipalityListMobileCardsProps) => (
|
||||||
<div data-view="mobile-cards" className="flex flex-col gap-4 md:hidden">
|
<div data-view="mobile-cards" className="flex flex-col gap-4 md:hidden">
|
||||||
|
|
@ -191,7 +189,6 @@ export const MunicipalityListMobileCards = ({
|
||||||
municipalityName={municipality.name}
|
municipalityName={municipality.name}
|
||||||
lastSignalAt={municipality.lastSignalAt}
|
lastSignalAt={municipality.lastSignalAt}
|
||||||
variant="sheet"
|
variant="sheet"
|
||||||
formAction={signalFormAction}
|
|
||||||
>
|
>
|
||||||
<SignalAgeReadout lastSignalAt={municipality.lastSignalAt} layout="card" />
|
<SignalAgeReadout lastSignalAt={municipality.lastSignalAt} layout="card" />
|
||||||
</MunicipalityListSignalControl>
|
</MunicipalityListSignalControl>
|
||||||
|
|
|
||||||
|
|
@ -1,27 +1,26 @@
|
||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { useActionState, useId, useState, type ReactNode } from 'react'
|
import { useId, useState, type FormEvent, type ReactNode } from 'react'
|
||||||
|
|
||||||
|
import type { MunicipalityListSignalResponse } from '@/app/(campaign)/campanha/(app)/municipios/signal/types'
|
||||||
import { MunicipalitySignalFields } from '@/components/campaign/municipality/MunicipalitySignalFields'
|
import { MunicipalitySignalFields } from '@/components/campaign/municipality/MunicipalitySignalFields'
|
||||||
import {
|
import {
|
||||||
CampaignCellEditOverlay,
|
CampaignCellEditOverlay,
|
||||||
type CampaignCellEditOverlayVariant,
|
type CampaignCellEditOverlayVariant,
|
||||||
} from '@/components/campaign/shared/CampaignCellEditOverlay'
|
} from '@/components/campaign/shared/CampaignCellEditOverlay'
|
||||||
import { CampaignFormActionMessage } from '@/components/campaign/shared/CampaignFormActionMessage'
|
import { useCampaignCellFailureChannel } from '@/components/campaign/shared/useCampaignCellFailureChannel'
|
||||||
import { useCampaignFormSuccessToast } from '@/components/campaign/shared/useCampaignFormSuccessToast'
|
import { Alert, AlertDescription } from '@/components/ui/Alert'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { DrawerCloseButton } from '@/components/ui/Drawer'
|
import { DrawerCloseButton } from '@/components/ui/Drawer'
|
||||||
import { Spinner } from '@/components/ui/Spinner'
|
import { Spinner } from '@/components/ui/Spinner'
|
||||||
import type { CampaignFormActionState } from '@/utilities/campaignFormActionError'
|
import { postCampaignJson } from '@/lib/campaignJsonRequest'
|
||||||
import {
|
import {
|
||||||
formatMunicipalitySignalAgeLabel,
|
formatMunicipalitySignalAgeLabel,
|
||||||
municipalitySignalAgeInDays,
|
municipalitySignalAgeInDays,
|
||||||
} from '@/utilities/municipality/municipalitySignal'
|
} from '@/utilities/municipality/municipalitySignal'
|
||||||
|
|
||||||
type MunicipalityStaffFormAction = (
|
const SIGNAL_ENDPOINT = '/campanha/municipios/signal'
|
||||||
state: CampaignFormActionState,
|
const SAVE_ERROR_MESSAGE = 'Não foi possível registrar o sinal. Tente novamente.'
|
||||||
formData: FormData,
|
|
||||||
) => Promise<CampaignFormActionState>
|
|
||||||
|
|
||||||
type MunicipalityListSignalControlProps = {
|
type MunicipalityListSignalControlProps = {
|
||||||
municipalityID: number
|
municipalityID: number
|
||||||
|
|
@ -29,39 +28,64 @@ type MunicipalityListSignalControlProps = {
|
||||||
municipalityName: string
|
municipalityName: string
|
||||||
lastSignalAt: string | null
|
lastSignalAt: string | null
|
||||||
variant: CampaignCellEditOverlayVariant
|
variant: CampaignCellEditOverlayVariant
|
||||||
formAction: MunicipalityStaffFormAction
|
|
||||||
children: ReactNode
|
children: ReactNode
|
||||||
}
|
}
|
||||||
|
|
||||||
export const MunicipalityListSignalControl = ({
|
export const MunicipalityListSignalControl = ({
|
||||||
municipalityID,
|
municipalityID,
|
||||||
municipalitySlug,
|
municipalitySlug: _municipalitySlug,
|
||||||
municipalityName,
|
municipalityName,
|
||||||
lastSignalAt,
|
lastSignalAt,
|
||||||
variant,
|
variant,
|
||||||
formAction,
|
|
||||||
children,
|
children,
|
||||||
}: MunicipalityListSignalControlProps) => {
|
}: MunicipalityListSignalControlProps) => {
|
||||||
const [open, setOpen] = useState(false)
|
const [open, setOpen] = useState(false)
|
||||||
const [formKey, setFormKey] = useState(0)
|
const [formKey, setFormKey] = useState(0)
|
||||||
const [state, submitAction, isPending] = useActionState(formAction, {})
|
const [isPending, setIsPending] = useState(false)
|
||||||
|
const { errorMessage, setErrorMessage, reportFailure, noteOpenChange } =
|
||||||
|
useCampaignCellFailureChannel()
|
||||||
const reactId = useId()
|
const reactId = useId()
|
||||||
const idPrefix = `municipality-list-signal-${variant}-${municipalityID}-${reactId}`
|
const idPrefix = `municipality-list-signal-${variant}-${municipalityID}-${reactId}`
|
||||||
const formId = `${idPrefix}-form`
|
const formId = `${idPrefix}-form`
|
||||||
const isSheet = variant === 'sheet'
|
const isSheet = variant === 'sheet'
|
||||||
const frescorLabel = formatMunicipalitySignalAgeLabel(municipalitySignalAgeInDays(lastSignalAt))
|
const frescorLabel = formatMunicipalitySignalAgeLabel(municipalitySignalAgeInDays(lastSignalAt))
|
||||||
|
|
||||||
useCampaignFormSuccessToast(state, () => {
|
const handleOpenChange = (nextOpen: boolean) => {
|
||||||
setOpen(false)
|
setOpen(nextOpen)
|
||||||
setFormKey((key) => key + 1)
|
noteOpenChange(nextOpen)
|
||||||
})
|
}
|
||||||
|
|
||||||
|
const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
|
||||||
|
event.preventDefault()
|
||||||
|
setErrorMessage(null)
|
||||||
|
setIsPending(true)
|
||||||
|
|
||||||
|
const formData = new FormData(event.currentTarget)
|
||||||
|
const body = (formData.get('body') as string) || undefined
|
||||||
|
const signalType = (formData.get('signalType') as string) || undefined
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { ok, payload } = await postCampaignJson<MunicipalityListSignalResponse>(
|
||||||
|
SIGNAL_ENDPOINT,
|
||||||
|
{ municipalityId: municipalityID, body, signalType },
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!ok || payload.status !== 'success') {
|
||||||
|
reportFailure(payload.status === 'error' ? payload.message : SAVE_ERROR_MESSAGE)
|
||||||
|
setIsPending(false)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setOpen(false)
|
||||||
|
setFormKey((key) => key + 1)
|
||||||
|
} catch {
|
||||||
|
reportFailure(SAVE_ERROR_MESSAGE)
|
||||||
|
} finally {
|
||||||
|
setIsPending(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const submitButton = (
|
const submitButton = (
|
||||||
// On the sheet this button lives in the footer, outside the `<form>` it
|
|
||||||
// submits: `form={formId}` is the standard association, and React's action
|
|
||||||
// still runs because the submit event fires on the form either way. That is
|
|
||||||
// what let this control drop the Drawer/Popover it used to hand-roll only
|
|
||||||
// because its `<form>` had to wrap the footer (B32+ F5).
|
|
||||||
<Button type="submit" form={formId} disabled={isPending} className="min-h-11 w-full">
|
<Button type="submit" form={formId} disabled={isPending} className="min-h-11 w-full">
|
||||||
{isPending ? <Spinner data-icon="inline-start" aria-hidden="true" /> : null}
|
{isPending ? <Spinner data-icon="inline-start" aria-hidden="true" /> : null}
|
||||||
Registrar sinal
|
Registrar sinal
|
||||||
|
|
@ -72,7 +96,7 @@ export const MunicipalityListSignalControl = ({
|
||||||
<CampaignCellEditOverlay
|
<CampaignCellEditOverlay
|
||||||
variant={variant}
|
variant={variant}
|
||||||
open={open}
|
open={open}
|
||||||
onOpenChange={setOpen}
|
onOpenChange={handleOpenChange}
|
||||||
title="Registrar sinal"
|
title="Registrar sinal"
|
||||||
description={municipalityName}
|
description={municipalityName}
|
||||||
triggerLabel={`Registrar sinal em ${municipalityName} — ${frescorLabel}`}
|
triggerLabel={`Registrar sinal em ${municipalityName} — ${frescorLabel}`}
|
||||||
|
|
@ -93,14 +117,16 @@ export const MunicipalityListSignalControl = ({
|
||||||
<form
|
<form
|
||||||
key={formKey}
|
key={formKey}
|
||||||
id={formId}
|
id={formId}
|
||||||
action={submitAction}
|
onSubmit={handleSubmit}
|
||||||
className="flex flex-col gap-3"
|
className="flex flex-col gap-3"
|
||||||
aria-busy={isPending || undefined}
|
aria-busy={isPending || undefined}
|
||||||
>
|
>
|
||||||
<input type="hidden" name="municipalityId" value={municipalityID} />
|
<MunicipalitySignalFields idPrefix={idPrefix} />
|
||||||
<input type="hidden" name="municipalitySlug" value={municipalitySlug} />
|
{errorMessage ? (
|
||||||
<MunicipalitySignalFields idPrefix={idPrefix} fieldErrors={state.fieldErrors} />
|
<Alert variant="destructive">
|
||||||
{state.status !== 'success' ? <CampaignFormActionMessage state={state} /> : null}
|
<AlertDescription>{errorMessage}</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
) : null}
|
||||||
{isSheet ? null : submitButton}
|
{isSheet ? null : submitButton}
|
||||||
</form>
|
</form>
|
||||||
</CampaignCellEditOverlay>
|
</CampaignCellEditOverlay>
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@
|
||||||
import { useRouter } from 'next/navigation'
|
import { useRouter } from 'next/navigation'
|
||||||
import { useActionState } from 'react'
|
import { useActionState } from 'react'
|
||||||
|
|
||||||
import { createMunicipalityListSignalFormAction } from '@/app/(campaign)/campanha/(app)/municipios/municipalityStaffFormActions'
|
import { createMunicipalityV2SignalFormAction as createMunicipalityListSignalFormAction } from '@/app/(campaign)/campanha/(app)/municipio/[slug]/v2/formActions'
|
||||||
import { WizardSignalSkipTrailing } from '@/components/campaign/municipality/WizardSignalSkipTrailing'
|
import { WizardSignalSkipTrailing } from '@/components/campaign/municipality/WizardSignalSkipTrailing'
|
||||||
import { CampaignFormActionMessage } from '@/components/campaign/shared/CampaignFormActionMessage'
|
import { CampaignFormActionMessage } from '@/components/campaign/shared/CampaignFormActionMessage'
|
||||||
import { CampaignWizardShell } from '@/components/campaign/shared/CampaignWizardShell'
|
import { CampaignWizardShell } from '@/components/campaign/shared/CampaignWizardShell'
|
||||||
|
|
|
||||||
|
|
@ -17,7 +17,7 @@ export type {
|
||||||
|
|
||||||
type LeadershipStateDeputyRelationDirection = 'fromLeadership' | 'fromStateDeputy'
|
type LeadershipStateDeputyRelationDirection = 'fromLeadership' | 'fromStateDeputy'
|
||||||
|
|
||||||
type LeadershipStateDeputyRelationCellProps = {
|
export type LeadershipStateDeputyRelationCellProps = {
|
||||||
direction: LeadershipStateDeputyRelationDirection
|
direction: LeadershipStateDeputyRelationDirection
|
||||||
fixedId: number
|
fixedId: number
|
||||||
/** Whose relation this is — spoken in the aria-labels and the Drawer. */
|
/** Whose relation this is — spoken in the aria-labels and the Drawer. */
|
||||||
|
|
|
||||||
|
|
@ -49,7 +49,7 @@ const toRelationHit = (hit: MunicipalityPortfolioSearchHit): RelationSearchHit =
|
||||||
ids: hit.kind === 'municipality' ? [hit.municipalityId] : hit.municipalityIds,
|
ids: hit.kind === 'municipality' ? [hit.municipalityId] : hit.municipalityIds,
|
||||||
})
|
})
|
||||||
|
|
||||||
type MunicipalityPortfolioCellProps = {
|
export type MunicipalityPortfolioCellProps = {
|
||||||
/** `null` in draft mode (a row that does not exist yet). */
|
/** `null` in draft mode (a row that does not exist yet). */
|
||||||
ownerId: number | null
|
ownerId: number | null
|
||||||
/** Whose portfolio this is — spoken in the aria-labels and the Drawer. */
|
/** Whose portfolio this is — spoken in the aria-labels and the Drawer. */
|
||||||
|
|
|
||||||
|
|
@ -36,6 +36,9 @@ test('prewarms shared Next route bundles sequentially', async ({ request }) => {
|
||||||
'/campanha/municipios/pledge-declared-votes',
|
'/campanha/municipios/pledge-declared-votes',
|
||||||
'/campanha/municipios/pledge-estimated-votes',
|
'/campanha/municipios/pledge-estimated-votes',
|
||||||
'/campanha/municipios/political-trend',
|
'/campanha/municipios/political-trend',
|
||||||
|
'/campanha/municipios/signal',
|
||||||
|
'/campanha/liderancas/state-deputies',
|
||||||
|
'/campanha/liderancas/municipalities',
|
||||||
'/campanha/liderancas/support-status',
|
'/campanha/liderancas/support-status',
|
||||||
'/campanha/webauthn/login-options',
|
'/campanha/webauthn/login-options',
|
||||||
'/campanha/webauthn/login',
|
'/campanha/webauthn/login',
|
||||||
|
|
|
||||||
|
|
@ -129,7 +129,6 @@ const overlayCases: OverlayCase[] = [
|
||||||
municipalityName: MUNICIPALITY_NAME,
|
municipalityName: MUNICIPALITY_NAME,
|
||||||
lastSignalAt: null,
|
lastSignalAt: null,
|
||||||
variant,
|
variant,
|
||||||
formAction: async () => ({}),
|
|
||||||
children: createElement('span', null, 'Sem sinal'),
|
children: createElement('span', null, 'Sem sinal'),
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
|
|
@ -292,7 +291,10 @@ describe('campaign cell edit overlay', () => {
|
||||||
* would look right and do nothing.
|
* would look right and do nothing.
|
||||||
*/
|
*/
|
||||||
it('submits the signal form from a button rendered in the sheet footer', async () => {
|
it('submits the signal form from a button rendered in the sheet footer', async () => {
|
||||||
const formAction = vi.fn(async () => ({}))
|
vi.stubGlobal(
|
||||||
|
'fetch',
|
||||||
|
vi.fn(async () => Response.json({ status: 'success', message: 'Sinal registrado.' })),
|
||||||
|
)
|
||||||
|
|
||||||
renderWithTooltip(
|
renderWithTooltip(
|
||||||
// `createElement`'s typing puts a required `children` in props, so the
|
// `createElement`'s typing puts a required `children` in props, so the
|
||||||
|
|
@ -304,7 +306,6 @@ describe('campaign cell edit overlay', () => {
|
||||||
municipalityName: MUNICIPALITY_NAME,
|
municipalityName: MUNICIPALITY_NAME,
|
||||||
lastSignalAt: null,
|
lastSignalAt: null,
|
||||||
variant: 'sheet',
|
variant: 'sheet',
|
||||||
formAction,
|
|
||||||
children: createElement('span', null, 'Sem sinal'),
|
children: createElement('span', null, 'Sem sinal'),
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
@ -326,7 +327,7 @@ describe('campaign cell edit overlay', () => {
|
||||||
|
|
||||||
fireEvent.click(submit as HTMLButtonElement)
|
fireEvent.click(submit as HTMLButtonElement)
|
||||||
|
|
||||||
await waitFor(() => expect(formAction).toHaveBeenCalledTimes(1))
|
await waitFor(() => expect(fetch).toHaveBeenCalledTimes(1))
|
||||||
})
|
})
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue