B134 — motivo opcional (tendência wizard + nível); remove reversalSignals

Co-authored-by: Francisco Solla <fsolla@users.noreply.github.com>
This commit is contained in:
Cursor Agent 2026-08-02 21:36:41 +00:00
parent 345db9474f
commit 28ff9615ce
No known key found for this signature in database
7 changed files with 107 additions and 49 deletions

View file

@ -0,0 +1,61 @@
# Impl: B134 — Motivo opcional — tendência (wizard) + nível; remover voltar atrás do DB
Status: aprovado
Atualizado em: 2026-08-02
Issue: #288
Intenção: docs/plans/motivo-opcional-tendencia-e-nivel.md (ausente no repo — aceite inferido do título da Issue e do código E14/B64)
Appetite restante: ~meio dia eng
## Leitura da intenção
- **Outcome:** coordenação pode registrar mudança de tendência (wizard) e de nível de envolvimento sem obrigar texto de justificativa; o campo "O que faria voltar atrás" deixa de existir (UI + payload + snapshot de `allocationDecision`).
- **O que NÃO negociar:** movimento de nível continua submit explícito com regras de histerese/override; tendência no wizard mantém Salvar explícito; `leader` lockdown; gravação transacional em `allocationDecision` para movimentos de nível.
- **O que reavaliar:** a hipótese E14 de motivo + sinais de reversão obrigatórios no schema — produto pede relaxar motivo e eliminar reversão por completo.
## Abordagem recomendada
```mermaid
flowchart LR
Wizard["WizardTrendNoteStep"] --> Schema["municipalityPoliticalTrendSchema (já nullable)"]
LevelUI["MunicipalityListLevelControl"] --> LevelSchema["municipalityEngagementLevelSchema"]
LevelSchema --> Action["setMunicipalityEngagementLevelRecord"]
Action --> Mun["municipality.levelNote"]
Action --> Dec["allocationDecision sem reversalSignals"]
```
**Opções consideradas:** A) tornar motivo opcional só na UI mantendo schema | B) relaxar schema + remover reversalSignals do snapshot | C) migration para apagar coluna reversalSignals
**Recomendação:** B — `reversalSignals` nunca foi coluna de banco, só JSON no snapshot e campo do body Zod; remover do schema, action e UI. Motivo vira `trimmedNullableText` no Zod de nível; wizard remove `required` HTML.
**Rejeitadas:** C (não há coluna); A (schema e UI divergiriam).
### Componentes / mudanças
- **`src/lib/schemas/municipality.ts`**: `note` opcional em `municipalityEngagementLevelSchema`; remover `reversalSignals`.
- **`src/app/(campaign)/campanha/actions/municipality.ts`**: snapshot sem `reversalSignals`; `rationale` aceita string vazia quando nota omitida.
- **`src/components/campaign/municipality/MunicipalityListLevelControl.tsx`**: remover campo "O que faria voltar atrás"; `canSubmit` só exige movimento (+ override se violações).
- **`src/components/campaign/municipality/WizardTrendNoteStep.tsx`**: remover `required` do textarea; label indica opcional.
- **`src/lib/campaignIntelligenceConcepts.ts`**: copy do verbete E14 sem exigir sinais de reversão.
- **Migration:** sem migration (snapshot JSON é schema-less; dados históricos com `reversalSignals` permanecem legíveis).
- **Testes:** int `campaignMunicipalityEngagementLevel` atualizado + caso movimento sem nota.
## Fases verificáveis
1. **Schema/server** — Zod + action + int tests
2. **UI** — level control + wizard note step
3. **Gates** — `pnpm gate:fast`; push via `pnpm push`
## Rabbit holes / Não escopo
- Tornar motivo opcional no popover de tendência da lista (B24 já aceita nota vazia via autosave)
- Backfill ou limpeza de `reversalSignals` em snapshots antigos
- Alterar `allocationDecision.rationale` para `required: false` no Payload
## Riscos e mitigação
- `rationale` required no Payload com nota vazia → enviar `''` (válido para textarea required)
- Testes int que passam `reversalSignals` → remover do fixture
## Aceite de engenharia
- [x] Aceite de produto da intenção ainda coberto
- [x] Invariantes AGENTS/engineering-standards
- [x] Testes de domínio previstos (int engagement level)

View file

@ -149,7 +149,7 @@ export const setMunicipalityEngagementLevelRecord = async (
actor: CampaignUser,
input: MunicipalityEngagementLevelInput,
) => {
const { municipality, level, note, reversalSignals, triangulatedShock, override } =
const { municipality, level, note, triangulatedShock, override } =
municipalityEngagementLevelSchema.parse(input)
return withPayloadTransaction(
@ -187,10 +187,12 @@ export const setMunicipalityEngagementLevelRecord = async (
if (violations.length > 0 && !override) throw new EngagementLevelBlockedError(violations)
const levelNote = note ?? null
const updated = await payload.update({
collection: 'municipality',
id: municipality,
data: { engagementLevel: level, levelNote: note },
data: { engagementLevel: level, levelNote },
depth: 0,
user: currentActor,
overrideAccess: false,
@ -203,13 +205,12 @@ export const setMunicipalityEngagementLevelRecord = async (
municipality,
patternId: ENGAGEMENT_LEVEL_PATTERN_ID,
outcome: 'movimento',
rationale: note,
rationale: levelNote ?? '',
// Only the values the decision was taken on — no document dumps
// (the collection caps the serialized snapshot at 16 KB).
snapshot: {
from,
to: level,
reversalSignals,
triangulatedShock,
violations: violations.map((violation) => violation.id),
overridden: violations.length > 0,

View file

@ -45,9 +45,8 @@ type MunicipalityListLevelControlProps = {
/**
* E14 — unlike the trend and estimate cells next to it, this one submits
* explicitly: a movement carries a motivo AND the signals that would reverse
* it, and it may need an override. Auto-saving half of that would file an
* incomplete decision under the coordinator's name.
* explicitly: a movement may need an override. Auto-saving half of that would
* file an incomplete decision under the coordinator's name.
*/
export const MunicipalityListLevelControl = ({
municipalityID,
@ -73,7 +72,6 @@ export const MunicipalityListLevelControl = ({
// with it the select — is not mounted.
const [draftLevel, setDraftLevel] = useState<EngagementLevel | ''>('')
const [note, setNote] = useState('')
const [reversalSignals, setReversalSignals] = useState('')
const [triangulatedShock, setTriangulatedShock] = useState(false)
const [override, setOverride] = useState(false)
const [isPending, setIsPending] = useState(false)
@ -142,7 +140,6 @@ export const MunicipalityListLevelControl = ({
const resetDraft = () => {
setDraftLevel(currentLevel ?? '')
setNote('')
setReversalSignals('')
setTriangulatedShock(false)
setOverride(false)
setErrorMessage(null)
@ -174,7 +171,6 @@ export const MunicipalityListLevelControl = ({
municipalityId: municipalityID,
level: draftLevel,
note,
reversalSignals,
triangulatedShock,
override,
},
@ -205,11 +201,7 @@ export const MunicipalityListLevelControl = ({
}
}
const canSubmit =
isMovement &&
note.trim().length > 0 &&
reversalSignals.trim().length > 0 &&
(violations.length === 0 || override)
const canSubmit = isMovement && (violations.length === 0 || override)
const fieldId = (suffix: string) => `municipality-list-level-${suffix}-${municipalityID}`
const isSheet = variant === 'sheet'
const submitButton = (
@ -283,7 +275,7 @@ export const MunicipalityListLevelControl = ({
</NativeSelect>
</Field>
<Field>
<FieldLabel htmlFor={fieldId('note')}>Motivo</FieldLabel>
<FieldLabel htmlFor={fieldId('note')}>Motivo (opcional)</FieldLabel>
<Textarea
id={fieldId('note')}
value={note}
@ -294,18 +286,6 @@ export const MunicipalityListLevelControl = ({
placeholder="O que mudou para justificar este nível?"
/>
</Field>
<Field>
<FieldLabel htmlFor={fieldId('reversal')}>O que faria voltar atrás</FieldLabel>
<Textarea
id={fieldId('reversal')}
value={reversalSignals}
onChange={(event) => setReversalSignals(event.target.value)}
maxLength={ENGAGEMENT_LEVEL_TEXT_MAX_LENGTH}
rows={2}
className="min-h-16 resize-y"
placeholder="Sinais que fariam rever esta decisão."
/>
</Field>
{isJump ? (
<Field orientation="horizontal" className={isSheet ? 'min-h-11' : undefined}>
<Checkbox

View file

@ -97,7 +97,7 @@ export const WizardTrendNoteStep = ({
<div className="flex flex-col gap-2">
<label htmlFor="wizard-trend-note" className="text-sm font-medium">
Por que mudar a tendência?
Por que mudar a tendência? (opcional)
</label>
<Textarea
id="wizard-trend-note"
@ -106,7 +106,6 @@ export const WizardTrendNoteStep = ({
onChange={(event) => setNote(event.target.value)}
rows={5}
maxLength={2000}
required
disabled={isPending}
autoFocus
className="min-h-28"

View file

@ -194,11 +194,11 @@ export const campaignIntelligenceConcepts: ReadonlyArray<CampaignIntelligenceCon
oneLiner:
'Quanto a campanha decidiu investir neste município: N0 monitorar, N1 presença de mandato, N2 rede sem agenda, N3 rede com agenda, N4 investimento pleno.',
formula:
'Não é calculado: é declarado pela coordenação geral. Todo movimento exige motivo e os sinais que o fariam ser revertido, e fica registrado em Decisões de alocação com o nível anterior, o novo e a data. Três regras seguram a oscilação: pular dois níveis de uma vez só com choque triangulado, não rebaixar um nível decidido há menos de três semanas, e um movimento por mês. A coordenação pode passar por cima delas — o override é gravado com as regras que contrariou.',
'Não é calculado: é declarado pela coordenação geral. Todo movimento fica registrado em Decisões de alocação com o nível anterior, o novo, a data e um motivo opcional. Três regras seguram a oscilação: pular dois níveis de uma vez só com choque triangulado, não rebaixar um nível decidido há menos de três semanas, e um movimento por mês. A coordenação pode passar por cima delas — o override é gravado com as regras que contrariou.',
example:
'Um município em N1 que recebeu rede e entrou na agenda de giro sobe para N3; nas três semanas seguintes um pedido de rebaixamento fica bloqueado até a janela de proteção fechar, salvo override justificado.',
whyItMatters:
'Separa o que a campanha SABE sobre o município (classe, captura, cobertura da meta) do que a campanha DECIDIU fazer nele. Sem esse registro, a alocação de presença vira memória de reunião: ninguém sabe quem prometeu o quê, nem por quê, nem o que faria voltar atrás. Os cortes das regras de estabilidade são ilustrativos até o backtest calibrá-los.',
'Separa o que a campanha SABE sobre o município (classe, captura, cobertura da meta) do que a campanha DECIDIU fazer nele. Sem esse registro, a alocação de presença vira memória de reunião: ninguém sabe quem prometeu o quê nem por quê. Os cortes das regras de estabilidade são ilustrativos até o backtest calibrá-los.',
whereItAppears:
'Coluna "Nível" da lista de municípios (com filtro, ordenação e edição pela coordenação) e bloco de estratégia no detalhe do município.',
},

View file

@ -1,7 +1,11 @@
import { z } from 'zod'
import { ENGAGEMENT_LEVEL_TEXT_MAX_LENGTH, engagementLevels } from '@/lib/engagementLevel'
import { positiveRelationshipId, trimmedNullableText } from '@/lib/schemas/primitives'
import {
positiveRelationshipId,
trimmedNullableText,
trimmedOptionalText,
} from '@/lib/schemas/primitives'
import { voteEstimateScenarioFieldsSchema } from '@/lib/schemas/votePledge'
export const politicalTrendStatuses = ['favoravel', 'neutra', 'desfavoravel'] as const
@ -88,16 +92,11 @@ export const MUNICIPALITY_ADVISOR_MEMBERSHIP_SAFE_MESSAGES = [
export const MUNICIPALITY_ENGAGEMENT_LEVEL_UNRESTRICTED_MESSAGE =
'Somente a coordenação geral ou o candidato move o nível de envolvimento.'
/**
* E14 — a movement is never just the new level: the motivo and the signals
* that would reverse it are what make the decision auditable later, so both
* are required by the schema rather than by the form alone.
*/
/** E14 — movement of the N0–N4 ladder; motivo is optional (B134). */
export const municipalityEngagementLevelSchema = z.object({
municipality: positiveRelationshipId,
level: z.enum(engagementLevels),
note: z.string().trim().min(1).max(ENGAGEMENT_LEVEL_TEXT_MAX_LENGTH),
reversalSignals: z.string().trim().min(1).max(ENGAGEMENT_LEVEL_TEXT_MAX_LENGTH),
note: trimmedOptionalText(ENGAGEMENT_LEVEL_TEXT_MAX_LENGTH),
/** Licenses a two-level jump (research §6.8). */
triangulatedShock: z.boolean().default(false),
/** Accepts the listed violations knowingly; recorded in the decision snapshot. */

View file

@ -41,7 +41,6 @@ describe('municipality engagement level (E14)', () => {
municipality: municipality.id,
level: 'n3',
note: 'Prefeitura aliada e duas lideranças novas.',
reversalSignals: 'Rompimento do prefeito ou pledges abaixo de 40% da meta.',
})
fixtures.touchMunicipality(municipality.id)
@ -61,12 +60,38 @@ describe('municipality engagement level (E14)', () => {
expect(decision.snapshot).toMatchObject({
from: null,
to: 'n3',
reversalSignals: 'Rompimento do prefeito ou pledges abaixo de 40% da meta.',
violations: [],
overridden: false,
})
})
it('accepts a movement without a motivo (B134)', async () => {
const fixtures = campaignFixtures()
const coordinator = await fixtures.createCampaignUser('coordinator')
const municipality = await fixtures.getMunicipality()
const updated = await setMunicipalityEngagementLevelRecord(payload, coordinator, {
municipality: municipality.id,
level: 'n1',
})
fixtures.touchMunicipality(municipality.id)
expect(updated.engagementLevel).toBe('n1')
expect(updated.levelNote).toBeNull()
const decisions = await findDecisions(municipality.id)
expect(decisions.docs).toHaveLength(1)
const decision = decisions.docs[0]!
fixtures.own('allocationDecision', decision.id)
expect(decision.rationale).toBe('')
expect(decision.snapshot).toMatchObject({
from: null,
to: 'n1',
})
expect(decision.snapshot).not.toHaveProperty('reversalSignals')
})
it('holds a movement that breaks the rules and writes nothing', async () => {
const fixtures = campaignFixtures()
const coordinator = await fixtures.createCampaignUser('coordinator')
@ -76,7 +101,6 @@ describe('municipality engagement level (E14)', () => {
municipality: municipality.id,
level: 'n1',
note: 'Entrada no mapa como presença de mandato.',
reversalSignals: 'Nenhuma agenda executada no trimestre.',
})
fixtures.touchMunicipality(municipality.id)
@ -86,7 +110,6 @@ describe('municipality engagement level (E14)', () => {
municipality: municipality.id,
level: 'n3',
note: 'Achismo da semana.',
reversalSignals: 'Nada.',
}).catch((error: unknown) => error)
expect(blocked).toBeInstanceOf(EngagementLevelBlockedError)
@ -115,7 +138,6 @@ describe('municipality engagement level (E14)', () => {
municipality: municipality.id,
level: 'n1',
note: 'Entrada no mapa.',
reversalSignals: 'Agenda vazia por um trimestre.',
})
fixtures.touchMunicipality(municipality.id)
@ -123,7 +145,6 @@ describe('municipality engagement level (E14)', () => {
municipality: municipality.id,
level: 'n2',
note: 'Adversário abriu comitê e o prefeito pediu presença.',
reversalSignals: 'Comitê adversário fechar.',
override: true,
})
expect(moved.engagementLevel).toBe('n2')
@ -164,7 +185,6 @@ describe('municipality engagement level (E14)', () => {
municipality: municipality.id,
level: 'n3',
note: 'Três sinais independentes de invasão na mesma semana.',
reversalSignals: 'Adversário recuar do território.',
triangulatedShock: true,
})
expect(moved.engagementLevel).toBe('n3')
@ -191,7 +211,6 @@ describe('municipality engagement level (E14)', () => {
municipality: municipality.id,
level: 'n2',
note: 'Quero subir o meu município.',
reversalSignals: 'Nada.',
}),
).rejects.toThrow('coordenação geral ou o candidato')
@ -218,7 +237,6 @@ describe('municipality engagement level (E14)', () => {
municipality: municipality.id,
level: 'n4',
note: 'Prioridade máxima do ciclo.',
reversalSignals: 'Queda de captura por dois meses.',
})
fixtures.touchMunicipality(municipality.id)
const decisions = await findDecisions(municipality.id)