OH14 — remove OPS_HYBRID flag; sync always on for staff

Decision: remove compile-time OPS_HYBRID after OH11/OH13 green in CI/staging.
Staff hybrid sync is gated only by isStaffCampaignRole in the app layout;
OfflineBoundary swaps to Local when the browser is offline.

- Delete opsHybridFlag.ts and legacy formAction branches in staff controls
- E2e offline specs run in CI without OPS_HYBRID env
- Update ops-hibrido spec to implementado + offline write recipe

Closes #175

Co-authored-by: Francisco Solla <fsolla@users.noreply.github.com>
This commit is contained in:
Cursor Agent 2026-08-02 03:47:04 +00:00
parent 15949be761
commit 9b56b641a6
No known key found for this signature in database
38 changed files with 169 additions and 635 deletions

View file

@ -36,10 +36,6 @@ CAMPAIGN_EMAIL_FROM_NAME=Campanha Jorge Solla
# Note: the automated test suite ignores this file and reads .env.test instead,
# and only ever runs against a database whose name ends with "_test".
# Ops hybrid RSC/local (OH*). Compile-time; set to 1/true to enable estimate outbox + CAS.
# Absent or 0 keeps /campanha identical to main. See docs/plans/ops-hibrido-rsc-local-spec.md
OPS_HYBRID=
# Unified list factory (CL*). Compile-time; set to 1/true to render lists via OpsListPage.
# Absent or 0 keeps the legacy list shells. See docs/plans/lista-unificada-campanha-spec.md
LIST_UNIFIED=

View file

@ -4,6 +4,8 @@ Conteúdo movido do `AGENTS.md` em 2026-07-30 (fatiamento do paradigma de agente
---
**Recently resolved (2026-08-02):** **OH14** (Issue #175) — removida flag compile-time `OPS_HYBRID`: sync híbrido sempre ON para staff (`isStaffCampaignRole` no layout); ramificações legacy OFF apagadas nos forms/controles; e2e offline em CI sem env; spec-mãe `ops-hibrido-rsc-local-spec.md` em **implementado** com receita de nova write offline. Plano: [`oh14-flag-cleanup.md`](docs/plans/oh14-flag-cleanup.md).
**Recently resolved (2026-08-02):** **OH13** (Issue #176) — writes CAS por domínio: `baseUpdatedAt` + `*Cas` em leadership / demand transition / activity update / stateDeputy vínculos; helper `assertCampaignDocCas`; outbox `opsDomainOutbox` com Manter/Usar nos forms; flag OFF intacto. Plano: [`oh13-domain-writes-cas.md`](docs/plans/oh13-domain-writes-cas.md).
**Recently resolved (2026-08-02):** **OH12** (Issue #174) — `OpsListLocal` read-only via registry + mirror: `OfflineBoundary` nas 8 rotas de lista; Local com `CampaignTable` + parsers canónicos sobre o mirror (municípios/lideranças/dobradinhas/orgs/demandas); assessores/territórios/apoiadores com estado honesto; saved filters create/delete disabled offline; e2e lista `?q=`. Plano: [`oh12-ops-list-local.md`](docs/plans/oh12-ops-list-local.md).

View file

@ -1,7 +1,7 @@
# OH14 — Limpeza da flag `OPS_HYBRID` + documentação final
Status: rascunho
Atualizado em: 2026-08-01
Status: implementado
Atualizado em: 2026-08-02
Issue: #175
Priority: P1
Model: composer-2.5
@ -10,65 +10,25 @@ Appetite: ~0,5–1 dia eng
Depends: OH13, OH11
Responsável: —
## Premissas
## Decisão (OH14)
1. Feature verde em staging (e2e offline + CI) — é hora de ligar por omissão ou decidir manter flag.
2. Prod ainda está em desenvolvimento: a decisão é “remover a flag e ligar sempre” **ou** “manter flag até data X” — registrar explicitamente.
**Opção A — remover a flag e ligar sempre para staff.** Justificativa: OH11 (e2e offline + SW) e OH13 (writes CAS por domínio) verdes em staging/CI; prod ainda em desenvolvimento; a flag compile-time só servia rollout seguro durante OH2–OH13.
## Objetivos
## Entrega
- Decisão registada e aplicada: remover `OPS_HYBRID` (sync sempre ON para staff) **ou** manter com default documentado.
- Se removida: `resolveOpsHybridEnabled` apagado, código desligado morto removido, knip/cycles limpos.
- Doc final: como o híbrido funciona (sync, mirror, outbox, CAS, OfflineBoundary) numa página de referência para futuras features.
## Dados → decisão → apresentação
Dados: N/A.
## Abordagem proposta
- **Se remover:** deletar `opsHybridFlag.ts`, props `enabled` do provider/boundary, branches OFF mortos; e2e deixa de precisar da env.
- **Se manter:** documentar default e o caminho de remoção futura; NADA muda em código.
- **Doc de referência:** `docs/plans/ops-hibrido-rsc-local-spec.md` actualizada para “Status: implementado” + secção “Como adicionar uma nova write offline” (receita: schema base → action Cas → mutationFn → controle).
- Apagado `resolveOpsHybridEnabled` / `OPS_HYBRID` (`next.config`, `.env.example`, Playwright).
- `CampaignOpsSyncProvider` liga por `isStaffCampaignRole` no layout; `OfflineBoundary` só verifica offline do browser.
- Ramificações legacy OFF removidas dos forms/controles staff; e2e offline corre em CI sem env.
- Spec-mãe `ops-hibrido-rsc-local-spec.md` → `Status: implementado` + receita “nova write offline”.
## Fases verificáveis
### Fase 1 — Decisão + aplicação
- **Quota:** ~0,6
- **Aceite:**
- [ ] decisão no corpo do PR com justificativa (staging verde citado)
- [ ] se removida: `pnpm exec knip` sem novos erros; 0 ciclos; e2e sem env verde
- [ ] se mantida: doc de default + remoção futura; código intacto
- **Verify:** `pnpm gate:fast` + knip + cycles
- **Files:** flag/provider/boundary (se remoção), docs
- **Tamanho:** M
- [x] decisão no PR (staging verde OH11/OH13)
- [x] `knip` / cycles limpos; e2e sem `OPS_HYBRID`
### Fase 2 — Doc de referência
- **Quota:** ~0,4
- **Aceite:**
- [ ] plano-mãe em “implementado” + receita de nova write offline
- [ ] CHANGELOG-AGENTS entrada final
- **Verify:** `pnpm gate:fast`
- **Files:** docs
- **Tamanho:** S
## Dependências
- OH13, OH11 (feature completa e medida em staging).
## Não escopo
- Novas writes (OH13 fechou o lote); delta sync/tombstones; WebSocket.
## Rabbit holes
- **Remover a flag sem staging medido.** Rollback caro. **Mitigação:** dependência dura OH11 + verde em staging citado.
- **Manter flag “para sempre” sem doc.** Dívida silenciosa. **Mitigação:** doc obrigatória em qualquer dos desfechos.
## Referências
- [`src/lib/campaignOps/opsHybridFlag.ts`](src/lib/campaignOps/opsHybridFlag.ts) (se existir na altura)
- [`docs/CHANGELOG-AGENTS.md`](docs/CHANGELOG-AGENTS.md)
- OH1 (spec-mãe)
- [x] plano-mãe em “implementado” + receita de nova write offline
- [x] CHANGELOG-AGENTS entrada final

View file

@ -1,7 +1,7 @@
# Ops híbrido RSC/local — spec-mãe e critérios
Status: aprovado
Atualizado em: 2026-08-01
Status: implementado
Atualizado em: 2026-08-02
Issue: #164
Priority: P1
Model: cursor-grok-4.5-high
@ -16,7 +16,7 @@ Responsável: —
3. Persistence OPFS/WA-SQLite pode falhar em iOS antigo — fallback IndexedDB obrigatório.
4. Sync full-only v1; deletes podem ficar no mirror até ao próximo full sync.
5. Leader sem mirror de ops (lockdown actual).
6. `OPS_HYBRID` compile-time env; sem rollout/cohort/kill switch.
6. **OH14 (#175):** sync híbrido **sempre ligado para staff** — a flag compile-time `OPS_HYBRID` foi removida após e2e offline verde (OH11) e writes CAS completos (OH13).
Premissas confirmadas no gate de registo das Issues OH2–OH14 (2026-08-01).
@ -44,7 +44,7 @@ Brief:
│ └──────────────────────────────────────────┘ │
│ ┌─ detalhe município / lista ──────────────┐ │
│ │ online → RSC children │ │
│ │ offline + OPS_HYBRID → Local + OfflineBoundary │
│ │ offline → Local + OfflineBoundary │
│ │ região online-only → “Indisponível offline” │
│ └──────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────┘
@ -55,8 +55,8 @@ Brief:
- Documento-mãe que trava: arquitetura híbrida, escopo do snapshot, CAS/outbox, boundaries, critérios de aceite do projecto e ordem das Issues OH2–OH14.
- Engenheiro júnior lê este doc + o plano da sua Issue e executa sem reunião.
- Com `OPS_HYBRID=1` (entregas filhas): abrir `/campanha` sincroniza o snapshot; chrome “Actualizado”; offline renderiza do mirror; writes via outbox + CAS.
- CI sem `OPS_HYBRID` idêntica a `main`; jornada offline completa em `campaignOpsOffline.e2e.spec.ts` com `OPS_HYBRID=1` (OH11).
- Abrir `/campanha` (staff): sincroniza o snapshot; chrome “Actualizado”; offline renderiza do mirror; writes via outbox + CAS.
- CI inclui `campaignOpsOffline.e2e.spec.ts` e `campaignOpsEstimateOutbox.e2e.spec.ts` sem env extra (OH14).
## Dados → decisão → apresentação
@ -76,10 +76,10 @@ Ops em prod medidas em 2026-08-01: campanha ~4 MB vs TSE ~128 MB (não sincroniz
- **Tracer = estimativas antes do mirror completo (OH6 paralelo a OH2–OH5).** **Rejeitado:** mirror primeiro (atraso no feedback da dor real).
- **Persistência OPFS primeiro, fallback IDB.** **Rejeitado:** só OPFS (iOS antigo falha); só localStorage (limite/estrutura).
- **Leader sem mirror.** **Rejeitado:** mirror parcial para `leader` (ex. só supporters `createdBy`) — abre lockdown e fatia LGPD.
- **`OPS_HYBRID` compile-time env.** Sem cohort/rollout/kill switch runtime. **Rejeitado:** feature flag remote / percentage rollout.
- **OH14 — flag removida; staff sempre ON.** Durante OH2–OH13 usámos `OPS_HYBRID` compile-time para rollout seguro. Com OH11/OH13 verdes, removemos a flag: `CampaignOpsSyncProvider` liga por `isStaffCampaignRole` no layout; `OfflineBoundary` troca só com `navigator.onLine === false`. **Rejeitado:** manter flag “para sempre” sem doc; kill switch runtime.
- **Poll 3 min só em foreground** (`visibilityState === 'visible'`); re-sync em `visibilitychange`/`online`; sync in-flight coalescido (timer + focus + online). **Rejeitado:** poll em background; busy-wait / `setTimeout(0)`.
- **Orçamento do snapshot:** alvo ≤ ~2 MB gzip (número final medido/justificado em OH3); construção do snapshot = **uma (ou poucas) query(s) por collection**, nunca I/O por município no hot path. **Rejeitado:** N+1 por município; sync que bloqueia o paint RSC (fire-and-forget + chrome “A sincronizar…”).
- **i18n:** identificadores em inglês (`OPS_HYBRID`, `ops-sync`, `campaignOps`, `OfflineBoundary`); strings de chrome/toast em pt-BR. **Rejeitado:** identificadores em pt-BR / mistos.
- **i18n:** identificadores em inglês (`ops-sync`, `campaignOps`, `OfflineBoundary`); strings de chrome/toast em pt-BR. **Rejeitado:** identificadores em pt-BR / mistos.
## Escopo do snapshot (travado)
@ -94,19 +94,17 @@ Fora: TSE/`election_*`, geometries, media blobs, `supporter`, site público, `/a
## Questões em aberto
- **Remover `OPS_HYBRID` após verde em staging?** **Opções:** A) remover e ligar sempre para staff; B) manter flag com default documentado até data X. **Recomendação:** decidir em OH14 com evidência e2e offline + staging — não nesta Issue.
_(Nenhuma — OH14 fechou a remoção da flag.)_
## Abordagem proposta
```mermaid
flowchart TB
Open["/campanha open"] --> Flag{OPS_HYBRID?}
Flag -->|off| RSC[RSC actual — CI = main]
Flag -->|on| Prov[CampaignOpsSyncProvider]
Open["/campanha open (staff)"] --> Prov[CampaignOpsSyncProvider]
Prov --> GET["GET /campanha/api/ops-sync"]
GET --> Merge[mergeOpsSnapshot]
Merge --> Mirror[(OPFS / IDB mirror)]
Online[Online] --> RSC
Online[Online] --> RSC[RSC children]
Offline[Offline] --> Local[Local views + OfflineBoundary]
Mirror --> Local
Write[Staff write] --> Outbox[outbox + CAS]
@ -116,7 +114,7 @@ flowchart TB
Componentes (entregues pelas Issues filhas — não nesta Issue):
- **`src/lib/campaignOps/*`** (OH2): DTOs, merge, flag, schema version.
- **`src/lib/campaignOps/*`** (OH2): DTOs, merge, schema version.
- **`scripts/benchmark-ops-snapshot.mjs`** (OH3): bytes/tempo → trunca `municipality_update`.
- **`GET …/api/ops-sync`** (OH4): snapshot scoped, 403 leader, `no-store`.
- **`CampaignOpsSyncProvider` + persistence + chrome** (OH5).
@ -130,7 +128,7 @@ Sem migration, sem collection, sem server action **nesta** Issue (só spec).
| ID | Issue | Depende de | Entrega curta |
| ---- | ----- | ------------- | ------------------------------------------------- |
| OH2 | #163 | OH1 | `lib/campaignOps` contrato + merge + flag |
| OH2 | #163 | OH1 | `lib/campaignOps` contrato + merge |
| OH3 | #165 | OH2 | Benchmark snapshot + truncamento |
| OH4 | #166 | OH3 | `GET /campanha/api/ops-sync` FULL + access |
| OH5 | #168 | OH4 | SyncProvider + OPFS→IDB + poll + chrome |
@ -164,12 +162,12 @@ Paralelas OK após OH1: OH2→OH5 em série; OH6 em paralelo a OH2–OH5; OH1–
## Critérios de aceite do projecto
1. Sem `OPS_HYBRID`: CI idêntica a `main` (e2e existentes).
2. Com env, online: GET `ops-sync` 200 com snapshot (alvo ≤ ~2 MB gzip ou justificativa OH3); chrome “Actualizado”; sync não bloqueia paint RSC.
1. Staff: `CampaignOpsSyncProvider` activo no layout; leader no-op.
2. Online: GET `ops-sync` 200 com snapshot (alvo ≤ ~2 MB gzip ou justificativa OH3); chrome “Actualizado”; sync não bloqueia paint RSC.
3. Airplane: detalhe no mirror renderiza via Local; regiões online-only com estado honesto.
4. Write offline → pending → online → aplica ou conflict UI; outbox sobrevive reload.
5. Advisor nunca recebe municípios fora da carteira; leader sem mirror.
6. `pnpm gate:fast` + specs novos verdes.
6. `pnpm gate:fast` + e2e offline (`campaignOpsOffline`, `campaignOpsEstimateOutbox`) verdes em CI.
## Dependências
@ -194,9 +192,20 @@ Paralelas OK após OH1: OH2→OH5 em série; OH6 em paralelo a OH2–OH5; OH1–
## Adiado com gatilho
- **Delta sync + tombstones.** Revisitar quando: OH3 reportar gzip ≫ ~2 MB **ou** poll full for inviável em campo.
- **Remoção da flag `OPS_HYBRID`.** Revisitar em OH14 com e2e offline verde em staging.
- **Compressão no wire.** Revisitar se OH3/OH11 medirem necessidade após full sync.
## Como adicionar uma nova write offline
Receita mínima para staff (após OH13 — copiar um vizinho do mesmo domínio):
1. **Schema / action server** — adicionar `baseUpdatedAt` (ou `baseEstimatedAt`) opcional na zod da action existente; implementar `*Cas` com `assertCampaignDocCas` quando `base*` presente; manter caminho sem `base*` para call sites legados fora do outbox.
2. **`mutationFn` no outbox** — em `opsMunicipalityOutbox`, `opsDomainOutbox` ou `opsEstimateOutbox`: chamar a action Cas com o token; em conflito, guardar `serverUpdatedAt` na row para o toast.
3. **Controle UI** — ilha client: `enqueue*` no submit; `useSyncExternalStore` na row do outbox; toast Sonner “Manter o meu / Usar o novo” no `status === 'conflict'`; badge Pendente/Conflito; **não** levantar estado para spreadsheet mode.
4. **Mirror** — se a write altera dados já no snapshot, garantir que o merge/outbox actualiza a collection TanStack (`opsMirrorClient`) ou que o próximo full sync reflecte (full-only v1).
5. **Testes** — unit no parser/enqueue; int na action Cas; e2e só se a jornada offline for user-visible (padrão OH6/OH11).
Vizinhos por domínio: município (`MunicipalityListTrendControl`, `MunicipalityUpdateForm`), estimativa (`PledgeEstimateForm`), liderança (`LeadershipInternalForm`, `LeadershipListSupportStatusControl`), demanda (`DemandWorkflowCard`), atividade (`ActivityForm` update).
## Referências
- GitHub Issue #164 (`id: OH1`)

View file

@ -5,10 +5,8 @@ const allowedImageHost = process.env.NEXT_PUBLIC_SITE_URL || 'https://jorgesolla
const nextConfig = {
distDir: process.env.NEXT_DIST_DIR || '.next',
// OH6/OH* + CL*: compile-time flags inlined for client islands; absent/`0`
// keeps CI identical to main.
// CL*: compile-time flag inlined for client islands; absent/`0` keeps legacy list shells.
env: {
OPS_HYBRID: process.env.OPS_HYBRID ?? '',
LIST_UNIFIED: process.env.LIST_UNIFIED ?? '',
},
images: {

View file

@ -66,7 +66,7 @@
"test": "pnpm run test:unit && pnpm run test:int",
"test:all": "pnpm run test && pnpm run test:e2e",
"test:e2e": "cross-env NODE_OPTIONS=\"--no-deprecation --conditions=react-server --import=tsx/esm\" playwright test --config=playwright.config.ts",
"test:e2e:ops-hybrid": "cross-env OPS_HYBRID=1 NODE_OPTIONS=\"--no-deprecation --conditions=react-server --import=tsx/esm\" playwright test --config=playwright.config.ts tests/e2e/campaignOpsOffline.e2e.spec.ts tests/e2e/campaignOpsEstimateOutbox.e2e.spec.ts",
"test:e2e:ops-hybrid": "cross-env NODE_OPTIONS=\"--no-deprecation --conditions=react-server --import=tsx/esm\" playwright test --config=playwright.config.ts tests/e2e/campaignOpsOffline.e2e.spec.ts tests/e2e/campaignOpsEstimateOutbox.e2e.spec.ts",
"test:e2e:affected": "node scripts/run-e2e-affected.mjs",
"test:int": "cross-env NODE_OPTIONS=--no-deprecation vitest run --config ./vitest.config.mts",
"test:unit": "cross-env NODE_OPTIONS=--no-deprecation DATABASE_URL=postgresql://invalid:invalid@127.0.0.1:1/unit_tests_must_not_connect vitest run --config ./vitest.unit.config.mts",

View file

@ -119,7 +119,6 @@ export default defineConfig({
PAYLOAD_SECRET: process.env.PAYLOAD_SECRET ?? 'test-only-secret-not-used-in-production',
NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL ?? baseURL,
LIST_UNIFIED: process.env.LIST_UNIFIED ?? '',
OPS_HYBRID: process.env.OPS_HYBRID ?? '',
},
},
})

View file

@ -20,7 +20,6 @@ import { requireCampaignPageActor } from '@/utilities/campaignPageActor'
import {
attachDemandReceiptFormAction,
setDemandCostFormAction,
transitionDemandFormAction,
} from './formActions'
type DemandDetailPageProps = {
@ -129,7 +128,6 @@ export default async function DemandDetailPage({ params }: DemandDetailPageProps
canDecideEscalated={isCampaignUnrestricted(user)}
currentCost={demand.cost}
updatedAt={demand.updatedAt}
transitionFormAction={transitionDemandFormAction}
costFormAction={setDemandCostFormAction}
receiptFormAction={attachDemandReceiptFormAction}
/>

View file

@ -28,7 +28,6 @@ import {
} from '@/components/ui/Sidebar'
import { Toaster } from '@/components/ui/Toaster'
import { TooltipProvider } from '@/components/ui/tooltip'
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
import { isStaffCampaignRole } from '@/lib/campaignRoles'
import { deviceLabelFromUserAgent } from '@/lib/deviceLabel'
import { getCampaignUserWithAvatar } from '@/utilities/campaignAuth'
@ -47,7 +46,7 @@ export default async function CampaignAppLayout({ children }: { children: React.
const sidebarStateCookie = cookieStore.get(SIDEBAR_COOKIE_NAME)
const hasSidebarCookie = sidebarStateCookie !== undefined
const defaultOpen = sidebarStateCookie ? sidebarStateCookie.value === 'true' : true
const opsSyncEnabled = resolveOpsHybridEnabled() && isStaffCampaignRole(user.role)
const opsSyncEnabled = isStaffCampaignRole(user.role)
// B40 discovery. The relying party is decided from headers alone, so it is
// resolved first and this layout — which runs on every authenticated

View file

@ -21,7 +21,6 @@ import {
} from '@/utilities/campaignRelationOptions'
import { loadLeadershipDetail } from '@/utilities/leadership/leadershipData'
import { loadMunicipalityPortfolioIndex } from '@/utilities/municipality/municipalityPortfolioIndex'
import { updateLeadershipInternalFormAction } from './formActions'
type LeadershipDetailPageProps = {
params: Promise<{ id: string }>
@ -111,7 +110,6 @@ export default async function LeadershipDetailPage({ params }: LeadershipDetailP
municipalityOptions={municipalityOptions}
organizationOptions={organizationOptions}
stateDeputyOptions={stateDeputyOptions}
formAction={updateLeadershipInternalFormAction}
/>
</section>
</CampaignPageShell>

View file

@ -12,7 +12,6 @@ import {
loadOrganizationOptions,
loadStateDeputyOptions,
} from '@/utilities/campaignRelationOptions'
import { createLeadershipFormAction } from './formActions'
type NewLeadershipPageProps = {
searchParams: Promise<Record<string, string | string[] | undefined>>
@ -65,7 +64,6 @@ export default async function NewLeadershipPage({ searchParams }: NewLeadershipP
organizationOptions={organizationOptions}
stateDeputyOptions={stateDeputyOptions}
initialMunicipalityIDs={initialMunicipalityIDs}
formAction={createLeadershipFormAction}
/>
</CampaignPageShell>
)

View file

@ -13,7 +13,6 @@ import { MunicipalityVisitEligibilityCard } from '@/components/campaign/municipa
import { MunicipalityZoneNeighborhoodsCard } from '@/components/campaign/municipality/MunicipalityZoneNeighborhoodsCard'
import { CampaignListPagination } from '@/components/campaign/shared/CampaignListPagination'
import { SuggestionsPanel } from '@/components/campaign/suggestion/SuggestionsPanel'
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
import type { VoteEstimateScenarioViewModel } from '@/lib/voteEstimate'
import type { getCampaignUser } from '@/utilities/campaignAuth'
import { loadFederalCandidateOptions } from '@/utilities/electionCandidateOptions'
@ -52,8 +51,7 @@ import type { getPayload } from 'payload'
import { Suspense } from 'react'
import { resolveSuggestionFormAction } from '../../suggestionFormActions'
import { declareVotesFormAction, estimateVotesFormAction } from './pledgeFormActions'
import { createMunicipalityUpdateFormAction } from './updateFormActions'
import { declareVotesFormAction } from './pledgeFormActions'
type PayloadUser = {
payload: Awaited<ReturnType<typeof getPayload>>
@ -123,11 +121,7 @@ export const OverviewTab = async ({
</Suspense>
</>
) : null}
<MunicipalityPledgesPanel
pledges={pledges}
opsHybridEnabled={resolveOpsHybridEnabled()}
estimateFormAction={estimateVotesFormAction}
/>
<MunicipalityPledgesPanel pledges={pledges} />
</div>
)
}
@ -359,7 +353,6 @@ export const UpdatesTab = async ({
<MunicipalityUpdateForm
municipalityID={municipalityID}
municipalityUpdatedAt={municipalityUpdatedAt}
formAction={createMunicipalityUpdateFormAction}
/>
<MunicipalityUpdateFeed updates={feed.updates} />
<CampaignListPagination

View file

@ -1,50 +0,0 @@
'use server'
import { revalidatePath } from 'next/cache'
import { createMunicipalityUpdate } from '@/app/(campaign)/campanha/actions/municipalityUpdate'
import {
optionalFormText,
optionalIntegerFormValue,
requiredFormText,
requiredRelationshipFormValue,
} from '@/lib/formData'
import {
municipalityUpdateKinds,
parseMunicipalitySignalType,
type MunicipalityUpdateKind,
} from '@/lib/schemas/municipalityUpdate'
import {
runCampaignFormAction,
type CampaignFormActionState,
} from '@/utilities/campaignFormActionError'
export const createMunicipalityUpdateFormAction = async (
_state: CampaignFormActionState,
formData: FormData,
): Promise<CampaignFormActionState> =>
runCampaignFormAction({
execute: async () => {
const municipality = requiredRelationshipFormValue(formData, 'municipalityId')
const rawKind = requiredFormText(formData, 'kind')
const kind = municipalityUpdateKinds.includes(rawKind as MunicipalityUpdateKind)
? (rawKind as MunicipalityUpdateKind)
: 'semanal'
await createMunicipalityUpdate({
municipality,
kind,
worked: optionalFormText(formData, 'worked'),
failed: optionalFormText(formData, 'failed'),
needs: optionalFormText(formData, 'needs'),
body: optionalFormText(formData, 'body'),
activeVolunteers: optionalIntegerFormValue(formData, 'activeVolunteers'),
newSupports: optionalIntegerFormValue(formData, 'newSupports'),
signalType: parseMunicipalitySignalType(optionalFormText(formData, 'signalType')),
})
revalidatePath('/campanha/municipios/[slug]', 'page')
return { message: 'Atualização registrada com sucesso.' }
},
genericMessage:
'Não foi possível registrar a atualização. Verifique seu acesso e tente novamente.',
})

View file

@ -49,7 +49,6 @@ import { NativeSelect, NativeSelectOption } from '@/components/ui/native-select'
import { Spinner } from '@/components/ui/Spinner'
import { Textarea } from '@/components/ui/textarea'
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/ToggleGroup'
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
import { readFormRelationshipIds, readOptionalFormText } from '@/lib/campaignOps/opsHybridFormData'
import { formatIsoAsBahiaDateTimeInput, parseBahiaDateTimeInput } from '@/lib/campaignTime'
import { isContactSearchQueryReady } from '@/lib/contactSearchQuery'
@ -495,18 +494,16 @@ export const ActivityForm = ({
submitLabel,
searchContacts,
searchLeaderships,
opsHybridEnabled = resolveOpsHybridEnabled(),
}: ActivityFormFieldsProps & {
action: ActivityFormAction
submitLabel: string
opsHybridEnabled?: boolean
}) => {
const router = useRouter()
const [state, formAction, pending] = useActionState(action, {})
const [hybridPending, setHybridPending] = useState(false)
const [hybridMessage, setHybridMessage] = useState<string | null>(null)
const previousOutboxStatusRef = useRef<string | undefined>(undefined)
const hybridUpdate = Boolean(opsHybridEnabled && activity)
const hybridUpdate = Boolean(activity)
const outboxRow = useSyncExternalStore(
(onStoreChange) =>

View file

@ -25,7 +25,6 @@ import { Field, FieldError, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import { Spinner } from '@/components/ui/Spinner'
import { Textarea } from '@/components/ui/textarea'
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
import {
campaignDemandStatuses,
campaignDemandTransitionLabels,
@ -47,10 +46,8 @@ type DemandWorkflowCardProps = {
/** Coordinator or candidate — the roles allowed to decide escalated demands. */
canDecideEscalated: boolean
currentCost: number | null
/** OH13 — CAS base when OPS_HYBRID outbox path is on. */
/** CAS base for transition outbox writes. */
updatedAt?: string
opsHybridEnabled?: boolean
transitionFormAction: FormAction
costFormAction: FormAction
receiptFormAction: FormAction
}
@ -67,16 +64,10 @@ export const DemandWorkflowCard = ({
canDecideEscalated,
currentCost,
updatedAt,
opsHybridEnabled = resolveOpsHybridEnabled(),
transitionFormAction,
costFormAction,
receiptFormAction,
}: DemandWorkflowCardProps) => {
const router = useRouter()
const [transitionState, submitTransition, transitionPending] = useActionState(
transitionFormAction,
{},
)
const [costState, submitCost, costPending] = useActionState(costFormAction, {})
const [receiptState, submitReceipt, receiptPending] = useActionState(receiptFormAction, {})
const [hybridPending, setHybridPending] = useState(false)
@ -84,11 +75,8 @@ export const DemandWorkflowCard = ({
const previousOutboxStatusRef = useRef<string | undefined>(undefined)
const outboxRow = useSyncExternalStore(
(onStoreChange) =>
opsHybridEnabled
? subscribeOpsDemandTransitionOutboxRow(demandID, onStoreChange)
: () => undefined,
() => (opsHybridEnabled ? readOpsDemandTransitionOutboxRow(demandID) : undefined),
(onStoreChange) => subscribeOpsDemandTransitionOutboxRow(demandID, onStoreChange),
() => readOpsDemandTransitionOutboxRow(demandID),
() => undefined,
)
@ -101,7 +89,7 @@ export const DemandWorkflowCard = ({
}, [outboxRow, router])
useEffect(() => {
if (!opsHybridEnabled || outboxRow?.statusSync !== 'conflict') return
if (outboxRow?.statusSync !== 'conflict') return
const toastId = `${CONFLICT_TOAST_ID_PREFIX}${demandID}`
toast.message(OPS_UPDATED_AT_CONFLICT_MESSAGE, {
id: toastId,
@ -128,7 +116,7 @@ export const DemandWorkflowCard = ({
return () => {
toast.dismiss(toastId)
}
}, [opsHybridEnabled, outboxRow, demandID, router])
}, [outboxRow, demandID, router])
const availableTransitions = campaignDemandTransitions[status].filter(
(target) =>
@ -181,9 +169,7 @@ export const DemandWorkflowCard = ({
)
}
const transitionBusy = opsHybridEnabled
? hybridPending || outboxRow?.statusSync === 'pending'
: transitionPending
const transitionBusy = hybridPending || outboxRow?.statusSync === 'pending'
return (
<section
@ -209,11 +195,7 @@ export const DemandWorkflowCard = ({
</div>
{availableTransitions.length ? (
<form
action={opsHybridEnabled ? undefined : submitTransition}
onSubmit={opsHybridEnabled ? onHybridTransition : undefined}
className="flex flex-col gap-3"
>
<form onSubmit={onHybridTransition} className="flex flex-col gap-3">
<input type="hidden" name="demandId" value={demandID} />
<Field>
<FieldLabel htmlFor={`demand-note-${demandID}`}>Nota da decisão</FieldLabel>
@ -241,16 +223,6 @@ export const DemandWorkflowCard = ({
</Button>
))}
</div>
{!opsHybridEnabled && transitionState.message && transitionState.status !== 'success' ? (
<Alert variant="destructive">
<AlertDescription>{transitionState.message}</AlertDescription>
</Alert>
) : null}
{!opsHybridEnabled && transitionState.status === 'success' ? (
<Alert>
<AlertDescription>{transitionState.message}</AlertDescription>
</Alert>
) : null}
{hybridMessage ? (
<p className="text-sm text-muted-foreground" role="status">
{hybridMessage}

View file

@ -1,9 +1,8 @@
'use client'
import { useActionState, useState, type FormEvent } from 'react'
import { useState, type FormEvent } from 'react'
import { enqueueLeadershipCreate } from '@/components/campaign/opsSync/opsDomainOutbox'
import { CampaignFormActionMessage } from '@/components/campaign/shared/CampaignFormActionMessage'
import {
RelationMultiSelect,
type RelationOption,
@ -11,20 +10,17 @@ import {
import { Badge } from '@/components/ui/Badge'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/Checkbox'
import { Field, FieldError, FieldLabel } from '@/components/ui/field'
import { Field, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import { NativeSelect, NativeSelectOption } from '@/components/ui/native-select'
import { Spinner } from '@/components/ui/Spinner'
import { Textarea } from '@/components/ui/textarea'
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
import { readFormRelationshipIds, readOptionalFormText } from '@/lib/campaignOps/opsHybridFormData'
import {
isSupportStatus,
leadershipSupportStatuses,
type SupportStatus,
} from '@/lib/schemas/leadership'
import type { CampaignFormActionState } from '@/utilities/campaignFormActionError'
import { fieldError } from '@/utilities/campaignFormFields'
import { supportStatusLabels } from '@/utilities/leadership/leadershipLabels'
type LeadershipFormProps = {
@ -32,11 +28,6 @@ type LeadershipFormProps = {
organizationOptions: RelationOption[]
stateDeputyOptions: RelationOption[]
initialMunicipalityIDs: number[]
formAction: (
state: CampaignFormActionState,
formData: FormData,
) => Promise<CampaignFormActionState>
opsHybridEnabled?: boolean
}
export const LeadershipForm = ({
@ -44,10 +35,7 @@ export const LeadershipForm = ({
organizationOptions,
stateDeputyOptions,
initialMunicipalityIDs,
formAction,
opsHybridEnabled = resolveOpsHybridEnabled(),
}: LeadershipFormProps) => {
const [state, submitAction, isPending] = useActionState(formAction, {})
const [hybridPending, setHybridPending] = useState(false)
const [hybridMessage, setHybridMessage] = useState<string | null>(null)
@ -102,14 +90,8 @@ export const LeadershipForm = ({
)
}
const pending = opsHybridEnabled ? hybridPending : isPending
return (
<form
action={opsHybridEnabled ? undefined : submitAction}
onSubmit={opsHybridEnabled ? onHybridSubmit : undefined}
className="flex max-w-2xl flex-col gap-4"
>
<form onSubmit={onHybridSubmit} className="flex max-w-2xl flex-col gap-4">
<div className="flex flex-wrap items-center gap-2">
{hybridPending ? <Badge variant="estimate-pending">Pendente</Badge> : null}
</div>
@ -123,9 +105,6 @@ export const LeadershipForm = ({
maxLength={120}
className="min-h-11"
/>
{fieldError(state.fieldErrors, 'name') ? (
<FieldError>{fieldError(state.fieldErrors, 'name')}</FieldError>
) : null}
</Field>
<div className="grid gap-4 sm:grid-cols-2">
<Field>
@ -138,16 +117,10 @@ export const LeadershipForm = ({
autoComplete="tel-national"
className="min-h-11"
/>
{fieldError(state.fieldErrors, 'phone') ? (
<FieldError>{fieldError(state.fieldErrors, 'phone')}</FieldError>
) : null}
</Field>
<Field>
<FieldLabel htmlFor="leadership-email">E-mail (opcional)</FieldLabel>
<Input id="leadership-email" name="email" type="email" className="min-h-11" />
{fieldError(state.fieldErrors, 'email') ? (
<FieldError>{fieldError(state.fieldErrors, 'email')}</FieldError>
) : null}
</Field>
</div>
@ -156,7 +129,6 @@ export const LeadershipForm = ({
label="Municípios em que atua"
options={municipalityOptions}
initialSelectedIDs={initialMunicipalityIDs}
error={fieldError(state.fieldErrors, 'municipalities')}
placeholder="Adicionar município…"
/>
@ -164,7 +136,6 @@ export const LeadershipForm = ({
name="organizations"
label="Organizações (sindicatos, associações…)"
options={organizationOptions}
error={fieldError(state.fieldErrors, 'organizations')}
placeholder="Adicionar organização…"
/>
@ -172,7 +143,6 @@ export const LeadershipForm = ({
name="stateDeputies"
label="Dobradinhas"
options={stateDeputyOptions}
error={fieldError(state.fieldErrors, 'stateDeputies')}
placeholder="Adicionar dobradinha…"
/>
@ -206,16 +176,13 @@ export const LeadershipForm = ({
<Textarea id="leadership-notes" name="notes" rows={3} maxLength={3000} />
</Field>
{!opsHybridEnabled && state.status !== 'success' ? (
<CampaignFormActionMessage state={state} />
) : null}
{hybridMessage ? (
<p className="text-sm text-muted-foreground" role="status">
{hybridMessage}
</p>
) : null}
<Button type="submit" disabled={pending} className="min-h-11 self-start">
{pending ? <Spinner data-icon="inline-start" aria-hidden="true" /> : null}
<Button type="submit" disabled={hybridPending} className="min-h-11 self-start">
{hybridPending ? <Spinner data-icon="inline-start" aria-hidden="true" /> : null}
Cadastrar liderança
</Button>
</form>

View file

@ -1,14 +1,7 @@
'use client'
import { useRouter } from 'next/navigation'
import {
useActionState,
useEffect,
useRef,
useState,
useSyncExternalStore,
type FormEvent,
} from 'react'
import { useEffect, useRef, useState, useSyncExternalStore, type FormEvent } from 'react'
import { toast } from 'sonner'
import {
@ -18,7 +11,6 @@ import {
subscribeOpsLeadershipUpdateOutboxRow,
} from '@/components/campaign/opsSync/opsDomainOutbox'
import { leadershipsCollection } from '@/components/campaign/opsSync/opsMirrorClient'
import { CampaignFormActionMessage } from '@/components/campaign/shared/CampaignFormActionMessage'
import {
RelationMultiSelect,
type RelationOption,
@ -30,7 +22,6 @@ import { Field, FieldLabel } from '@/components/ui/field'
import { NativeSelect, NativeSelectOption } from '@/components/ui/native-select'
import { Spinner } from '@/components/ui/Spinner'
import { Textarea } from '@/components/ui/textarea'
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
import { readFormRelationshipIds, readOptionalFormText } from '@/lib/campaignOps/opsHybridFormData'
import {
isSupportStatus,
@ -38,8 +29,6 @@ import {
type SupportStatus,
} from '@/lib/schemas/leadership'
import { OPS_UPDATED_AT_CONFLICT_MESSAGE } from '@/lib/schemas/opsCas'
import type { CampaignFormActionState } from '@/utilities/campaignFormActionError'
import { fieldError } from '@/utilities/campaignFormFields'
import type { LeadershipDetailViewModel } from '@/utilities/leadership/leadershipData'
import { supportStatusLabels } from '@/utilities/leadership/leadershipLabels'
@ -50,11 +39,6 @@ type LeadershipInternalFormProps = {
municipalityOptions: RelationOption[]
organizationOptions: RelationOption[]
stateDeputyOptions: RelationOption[]
formAction: (
state: CampaignFormActionState,
formData: FormData,
) => Promise<CampaignFormActionState>
opsHybridEnabled?: boolean
}
/** Staff-only internal evaluation + links (municipalities, organizations). */
@ -63,21 +47,15 @@ export const LeadershipInternalForm = ({
municipalityOptions,
organizationOptions,
stateDeputyOptions,
formAction,
opsHybridEnabled = resolveOpsHybridEnabled(),
}: LeadershipInternalFormProps) => {
const router = useRouter()
const [state, submitAction, isPending] = useActionState(formAction, {})
const [hybridPending, setHybridPending] = useState(false)
const [hybridMessage, setHybridMessage] = useState<string | null>(null)
const previousOutboxStatusRef = useRef<string | undefined>(undefined)
const outboxRow = useSyncExternalStore(
(onStoreChange) =>
opsHybridEnabled
? subscribeOpsLeadershipUpdateOutboxRow(leadership.id, onStoreChange)
: () => undefined,
() => (opsHybridEnabled ? readOpsLeadershipUpdateOutboxRow(leadership.id) : undefined),
(onStoreChange) => subscribeOpsLeadershipUpdateOutboxRow(leadership.id, onStoreChange),
() => readOpsLeadershipUpdateOutboxRow(leadership.id),
() => undefined,
)
@ -90,7 +68,7 @@ export const LeadershipInternalForm = ({
}, [outboxRow, router])
useEffect(() => {
if (!opsHybridEnabled || outboxRow?.status !== 'conflict') return
if (outboxRow?.status !== 'conflict') return
const toastId = `${CONFLICT_TOAST_ID_PREFIX}${leadership.id}`
toast.message(OPS_UPDATED_AT_CONFLICT_MESSAGE, {
id: toastId,
@ -121,7 +99,7 @@ export const LeadershipInternalForm = ({
return () => {
toast.dismiss(toastId)
}
}, [opsHybridEnabled, outboxRow, leadership.id, router])
}, [outboxRow, leadership.id, router])
const onHybridSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault()
@ -159,14 +137,10 @@ export const LeadershipInternalForm = ({
)
}
const pending = opsHybridEnabled ? hybridPending || outboxRow?.status === 'pending' : isPending
const pending = hybridPending || outboxRow?.status === 'pending'
return (
<form
action={opsHybridEnabled ? undefined : submitAction}
onSubmit={opsHybridEnabled ? onHybridSubmit : undefined}
className="flex max-w-2xl flex-col gap-4"
>
<form onSubmit={onHybridSubmit} className="flex max-w-2xl flex-col gap-4">
<div className="flex flex-wrap items-center gap-2">
<input type="hidden" name="leadershipId" value={leadership.id} />
{outboxRow?.status === 'pending' ? (
@ -180,7 +154,6 @@ export const LeadershipInternalForm = ({
label="Municípios em que atua"
options={municipalityOptions}
initialSelectedIDs={leadership.municipalityIDs}
error={fieldError(state.fieldErrors, 'municipalities')}
placeholder="Adicionar município…"
/>
@ -189,7 +162,6 @@ export const LeadershipInternalForm = ({
label="Organizações"
options={organizationOptions}
initialSelectedIDs={leadership.organizationIDs}
error={fieldError(state.fieldErrors, 'organizations')}
placeholder="Adicionar organização…"
/>
@ -198,7 +170,6 @@ export const LeadershipInternalForm = ({
label="Dobradinhas"
options={stateDeputyOptions}
initialSelectedIDs={leadership.stateDeputyIDs}
error={fieldError(state.fieldErrors, 'stateDeputies')}
placeholder="Adicionar dobradinha…"
/>
@ -242,7 +213,6 @@ export const LeadershipInternalForm = ({
/>
</Field>
{!opsHybridEnabled ? <CampaignFormActionMessage state={state} /> : null}
{hybridMessage ? (
<p className="text-sm text-muted-foreground" role="status">
{hybridMessage}

View file

@ -19,7 +19,6 @@ import { Alert, AlertDescription } from '@/components/ui/Alert'
import { Field, FieldLabel } from '@/components/ui/field'
import { NativeSelect, NativeSelectOption } from '@/components/ui/native-select'
import { Spinner } from '@/components/ui/Spinner'
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
import {
isSupportStatus,
leadershipSupportStatuses,
@ -37,7 +36,7 @@ const CONFLICT_TOAST_ID_PREFIX = 'ops-leadership-status-conflict:'
type LeadershipListSupportStatusControlProps = {
leadershipID: number
status: SupportStatus | null
/** OH13 — CAS base when OPS_HYBRID outbox path is on. */
/** CAS base for outbox writes. */
updatedAt?: string
}
@ -47,15 +46,11 @@ export const LeadershipListSupportStatusControl = ({
updatedAt,
}: LeadershipListSupportStatusControlProps) => {
const router = useRouter()
const opsHybrid = resolveOpsHybridEnabled()
const previousOutboxStatusRef = useRef<string | undefined>(undefined)
const outboxRow = useSyncExternalStore(
(onStoreChange) =>
opsHybrid
? subscribeOpsLeadershipUpdateOutboxRow(leadershipID, onStoreChange)
: () => undefined,
() => (opsHybrid ? readOpsLeadershipUpdateOutboxRow(leadershipID) : undefined),
(onStoreChange) => subscribeOpsLeadershipUpdateOutboxRow(leadershipID, onStoreChange),
() => readOpsLeadershipUpdateOutboxRow(leadershipID),
() => undefined,
)
@ -68,7 +63,7 @@ export const LeadershipListSupportStatusControl = ({
}, [outboxRow, router])
useEffect(() => {
if (!opsHybrid || outboxRow?.status !== 'conflict') return
if (outboxRow?.status !== 'conflict') return
const toastId = `${CONFLICT_TOAST_ID_PREFIX}${leadershipID}`
toast.message(OPS_UPDATED_AT_CONFLICT_MESSAGE, {
id: toastId,
@ -99,7 +94,7 @@ export const LeadershipListSupportStatusControl = ({
return () => {
toast.dismiss(toastId)
}
}, [opsHybrid, outboxRow, leadershipID, router])
}, [outboxRow, leadershipID, router])
const { open, onOpenChange, value, change, isPending, errorMessage, statusMessage } =
useCampaignCellAutosave<SupportStatus, LeadershipListSupportStatusResponse>({
@ -110,24 +105,22 @@ export const LeadershipListSupportStatusControl = ({
readSaved: (payload) => payload.savedSupportStatus,
errorMessage: SAVE_ERROR_MESSAGE,
pendingMessage: 'Salvando status de apoio.',
persist: opsHybrid
? async (supportStatus) => {
const mirrorUpdatedAt = leadershipsCollection.get(leadershipID)?.updatedAt
await enqueueLeadershipUpdate({
leadershipId: leadershipID,
supportStatus,
baseUpdatedAt: mirrorUpdatedAt ?? updatedAt,
})
return {
ok: true,
payload: {
status: 'success',
message: 'Status de apoio atualizado.',
savedSupportStatus: supportStatus,
},
}
}
: undefined,
persist: async (supportStatus) => {
const mirrorUpdatedAt = leadershipsCollection.get(leadershipID)?.updatedAt
await enqueueLeadershipUpdate({
leadershipId: leadershipID,
supportStatus,
baseUpdatedAt: mirrorUpdatedAt ?? updatedAt,
})
return {
ok: true,
payload: {
status: 'success',
message: 'Status de apoio atualizado.',
savedSupportStatus: supportStatus,
},
}
},
})
const handleStatusChange = (raw: string) => {

View file

@ -2,7 +2,6 @@
import { useEffect, useRef, useState } from 'react'
import { estimateVotesFormAction } from '@/app/(campaign)/campanha/(app)/municipios/[slug]/pledgeFormActions'
import { MunicipalityDetailHeaderView } from '@/components/campaign/municipality/MunicipalityDetailHeaderView'
import { MunicipalityPledgesPanel } from '@/components/campaign/municipality/MunicipalityPledgesPanel'
import {
@ -98,11 +97,7 @@ export const MunicipalityDetailLocal = ({ slug }: MunicipalityDetailLocalProps)
advisorsUnavailable={advisorsUnavailable}
/>
<MunicipalityPledgesPanel
pledges={pledges}
opsHybridEnabled
estimateFormAction={estimateVotesFormAction}
/>
<MunicipalityPledgesPanel pledges={pledges} />
<section aria-label="Conteúdo disponível só online" className="rounded-xl border px-4 py-6">
<p className="text-sm text-muted-foreground">{ONLINE_ONLY_MESSAGE}</p>

View file

@ -5,7 +5,6 @@ import { useRouter } from 'next/navigation'
import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
import { toast } from 'sonner'
import type { MunicipalityListAdvisorsResponse } from '@/app/(campaign)/campanha/(app)/municipios/advisors/types'
import {
advisorEntriesFromIds,
formatAdvisorNamesTooltip,
@ -28,18 +27,15 @@ import { Alert, AlertDescription } from '@/components/ui/Alert'
import { Badge } from '@/components/ui/Badge'
import { Command, CommandInput, CommandItem, CommandList } from '@/components/ui/Command'
import { Spinner } from '@/components/ui/Spinner'
import { postCampaignJson } from '@/lib/campaignJsonRequest'
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
import { sameIdSet } from '@/lib/sameIdSet'
import { OPS_UPDATED_AT_CONFLICT_MESSAGE } from '@/lib/schemas/opsCas'
import { cn } from '@/lib/utils'
import { OPS_UPDATED_AT_CONFLICT_MESSAGE } from '@/lib/schemas/opsCas'
import { sameIdSet } from '@/lib/sameIdSet'
import { matchesAtWordStart } from '@/lib/wordStartFilter'
import type {
EligibleAdvisorOption,
MunicipalityAdvisorSummary,
} from '@/utilities/municipality/municipalityViewModels'
const ADVISORS_ENDPOINT = '/campanha/municipios/advisors'
const SAVE_ERROR_MESSAGE = 'Não foi possível atualizar os assessores. Tente novamente.'
const CONFLICT_TOAST_ID_PREFIX = 'ops-advisors-conflict:'
@ -51,7 +47,7 @@ type MunicipalityListAdvisorsControlProps = {
isPriority: boolean
advisorNamesById: ReadonlyMap<number, MunicipalityAdvisorSummary>
options: EligibleAdvisorOption[]
/** OH10 — CAS base when OPS_HYBRID outbox path is on. */
/** CAS base for outbox writes. */
updatedAt?: string
variant: CampaignCellEditOverlayVariant
}
@ -67,7 +63,6 @@ export const MunicipalityListAdvisorsControl = ({
variant,
}: MunicipalityListAdvisorsControlProps) => {
const router = useRouter()
const opsHybrid = resolveOpsHybridEnabled()
const [open, setOpen] = useState(false)
const [selectedIDs, setSelectedIDs] = useState<number[]>(currentAdvisorIDs)
const [query, setQuery] = useState('')
@ -90,9 +85,8 @@ export const MunicipalityListAdvisorsControl = ({
const previousOutboxStatusRef = useRef<OpsMunicipalityWriteSyncStatus | undefined>(undefined)
const outboxRow = useSyncExternalStore(
(onStoreChange) =>
opsHybrid ? subscribeOpsAdvisorsOutboxRow(municipalityID, onStoreChange) : () => undefined,
() => (opsHybrid ? readOpsAdvisorsOutboxRow(municipalityID) : undefined),
(onStoreChange) => subscribeOpsAdvisorsOutboxRow(municipalityID, onStoreChange),
() => readOpsAdvisorsOutboxRow(municipalityID),
() => undefined,
)
@ -119,7 +113,7 @@ export const MunicipalityListAdvisorsControl = ({
}, [outboxRow, router])
useEffect(() => {
if (!opsHybrid || outboxRow?.status !== 'conflict') return
if (outboxRow?.status !== 'conflict') return
const toastId = `${CONFLICT_TOAST_ID_PREFIX}${municipalityID}`
toast.message(OPS_UPDATED_AT_CONFLICT_MESSAGE, {
id: toastId,
@ -153,7 +147,7 @@ export const MunicipalityListAdvisorsControl = ({
return () => {
toast.dismiss(toastId)
}
}, [opsHybrid, outboxRow, municipalityID, router, reportFailure, setErrorMessage])
}, [outboxRow, municipalityID, router, reportFailure, setErrorMessage])
// Every eligible account (coordinator/advisor/candidate) is listed here
// regardless of current assignment, so it doubles as the name lookup for an
@ -230,34 +224,14 @@ export const MunicipalityListAdvisorsControl = ({
}
try {
if (opsHybrid) {
const mirrorUpdatedAt = municipalitiesCollection.get(municipalityID)?.updatedAt
await enqueueAdvisorsAssignment({
municipalityId: municipalityID,
advisors: nextIds,
baseUpdatedAt: mirrorUpdatedAt ?? updatedAt,
})
if (requestSeq > (latestConfirmedRef.current?.seq ?? 0)) {
latestConfirmedRef.current = { seq: requestSeq, advisors: nextIds }
}
finishRequest()
return
}
const { ok, payload } = await postCampaignJson<MunicipalityListAdvisorsResponse>(
ADVISORS_ENDPOINT,
{ municipalityId: municipalityID, advisorId, assigned },
)
if (!ok || payload.status !== 'success') {
revertDelta()
reportFailure(payload.status === 'error' ? payload.message : SAVE_ERROR_MESSAGE)
finishRequest()
return
}
const mirrorUpdatedAt = municipalitiesCollection.get(municipalityID)?.updatedAt
await enqueueAdvisorsAssignment({
municipalityId: municipalityID,
advisors: nextIds,
baseUpdatedAt: mirrorUpdatedAt ?? updatedAt,
})
if (requestSeq > (latestConfirmedRef.current?.seq ?? 0)) {
latestConfirmedRef.current = { seq: requestSeq, advisors: payload.advisors }
latestConfirmedRef.current = { seq: requestSeq, advisors: nextIds }
}
finishRequest()
} catch {

View file

@ -2,7 +2,6 @@
import { useEffect, useRef, useState } from 'react'
import type { MunicipalityListEngagementLevelResponse } from '@/app/(campaign)/campanha/(app)/municipios/engagement-level/types'
import { MunicipalityLevelBadge } from '@/components/campaign/municipality/MunicipalityLevelBadge'
import { municipalitiesCollection } from '@/components/campaign/opsSync/opsMirrorClient'
import { enqueueEngagementLevel } from '@/components/campaign/opsSync/opsMunicipalityOutbox'
@ -18,8 +17,6 @@ import { Field, FieldContent, FieldLabel } from '@/components/ui/field'
import { NativeSelect, NativeSelectOption } from '@/components/ui/native-select'
import { Spinner } from '@/components/ui/Spinner'
import { Textarea } from '@/components/ui/textarea'
import { postCampaignJson } from '@/lib/campaignJsonRequest'
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
import {
EMPTY_ENGAGEMENT_LEVEL_LABEL,
ENGAGEMENT_LEVEL_RULES,
@ -33,7 +30,6 @@ import {
type EngagementLevelViolation,
} from '@/lib/engagementLevel'
const ENGAGEMENT_LEVEL_ENDPOINT = '/campanha/municipios/engagement-level'
const SAVE_ERROR_MESSAGE = 'Não foi possível registrar o nível. Tente novamente.'
type MunicipalityListLevelControlProps = {
@ -42,7 +38,7 @@ type MunicipalityListLevelControlProps = {
level: EngagementLevel | null
levelNote: string | null
levelChangedAt: string | null
/** OH10 — CAS base when OPS_HYBRID outbox path is on. */
/** CAS base for outbox writes. */
updatedAt?: string
variant: CampaignCellEditOverlayVariant
}
@ -170,56 +166,22 @@ export const MunicipalityListLevelControl = ({
setServerBlock(null)
try {
if (resolveOpsHybridEnabled()) {
const mirrorUpdatedAt = municipalitiesCollection.get(municipalityID)?.updatedAt
await enqueueEngagementLevel({
municipalityId: municipalityID,
level: draftLevel,
note,
reversalSignals,
triangulatedShock,
override,
baseUpdatedAt: mirrorUpdatedAt ?? updatedAt,
})
setSaved({
level: draftLevel,
note,
changedAt: new Date().toISOString(),
})
handleOpenChange(false)
return
}
// Deliberately ignores the transport's `ok` the way the siblings do not:
// `blocked` arrives as a 409 carrying the violations the coordinator may
// override, so the status line is not the signal here — the discriminant is.
const { payload } = await postCampaignJson<MunicipalityListEngagementLevelResponse>(
ENGAGEMENT_LEVEL_ENDPOINT,
{
municipalityId: municipalityID,
level: draftLevel,
note,
reversalSignals,
triangulatedShock,
override,
},
controller.signal,
)
if (payload.status === 'success') {
setSaved(payload.savedLevel)
handleOpenChange(false)
return
}
// A blocked movement keeps the overlay open with the draft intact: the
// next click is "override", not "type it all again".
if (payload.status === 'blocked') {
setServerBlock({ level: draftLevel, violations: payload.violations })
return
}
reportFailure(payload.message)
const mirrorUpdatedAt = municipalitiesCollection.get(municipalityID)?.updatedAt
await enqueueEngagementLevel({
municipalityId: municipalityID,
level: draftLevel,
note,
reversalSignals,
triangulatedShock,
override,
baseUpdatedAt: mirrorUpdatedAt ?? updatedAt,
})
setSaved({
level: draftLevel,
note,
changedAt: new Date().toISOString(),
})
handleOpenChange(false)
} catch {
// Network failure, a non-JSON error page, or the unmount abort below —
// only the first two have anyone left to tell.

View file

@ -19,7 +19,6 @@ import { Field, FieldLabel } from '@/components/ui/field'
import { NativeSelect, NativeSelectOption } from '@/components/ui/native-select'
import { Spinner } from '@/components/ui/Spinner'
import { Textarea } from '@/components/ui/textarea'
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
import { parsePoliticalTrendStatusFormValue } from '@/lib/schemas/municipality'
import {
politicalTrendBadgeVariant,
@ -47,7 +46,7 @@ type MunicipalityListTrendControlProps = {
municipalityName: string
status: MunicipalityListSavedPoliticalTrend['status']
trendNote: string | null
/** OH10 — CAS base when OPS_HYBRID outbox path is on. */
/** CAS base for outbox writes. */
updatedAt?: string
variant: CampaignCellEditOverlayVariant
}
@ -60,7 +59,6 @@ export const MunicipalityListTrendControl = ({
updatedAt,
variant,
}: MunicipalityListTrendControlProps) => {
const opsHybrid = resolveOpsHybridEnabled()
const { open, onOpenChange, value, change, flush, isPending, errorMessage, statusMessage } =
useCampaignCellAutosave<
MunicipalityListSavedPoliticalTrend,
@ -80,25 +78,23 @@ export const MunicipalityListTrendControl = ({
readSaved: (payload) => payload.savedTrend,
errorMessage: SAVE_ERROR_MESSAGE,
pendingMessage: 'Salvando tendência.',
persist: opsHybrid
? async (trend) => {
const mirrorUpdatedAt = municipalitiesCollection.get(municipalityID)?.updatedAt
await enqueuePoliticalTrend({
municipalityId: municipalityID,
status: trend.status,
note: trend.note,
baseUpdatedAt: mirrorUpdatedAt ?? updatedAt,
})
return {
ok: true,
payload: {
status: 'success',
message: 'Tendência política registrada.',
savedTrend: trend,
},
}
}
: undefined,
persist: async (trend) => {
const mirrorUpdatedAt = municipalitiesCollection.get(municipalityID)?.updatedAt
await enqueuePoliticalTrend({
municipalityId: municipalityID,
status: trend.status,
note: trend.note,
baseUpdatedAt: mirrorUpdatedAt ?? updatedAt,
})
return {
ok: true,
payload: {
status: 'success',
message: 'Tendência política registrada.',
savedTrend: trend,
},
}
},
})
// The only state the hook cannot hold: the textarea's raw text, which the

View file

@ -6,7 +6,6 @@ import {
getVoteEstimateForScenario,
hasAnyVoteEstimate,
} from '@/lib/voteEstimate'
import type { CampaignFormActionState } from '@/utilities/campaignFormActionError'
import { type StaffPledgeRow } from '@/utilities/votePledgeViews'
const voteFormatter = new Intl.NumberFormat('pt-BR')
@ -14,19 +13,10 @@ const dateFormatter = new Intl.DateTimeFormat('pt-BR')
type MunicipalityPledgesPanelProps = {
pledges: StaffPledgeRow[]
opsHybridEnabled: boolean
estimateFormAction: (
state: CampaignFormActionState,
formData: FormData,
) => Promise<CampaignFormActionState>
}
/** Staff-only: declared vs estimated votes per leadership in this municipality. */
export const MunicipalityPledgesPanel = ({
pledges,
opsHybridEnabled,
estimateFormAction,
}: MunicipalityPledgesPanelProps) => {
export const MunicipalityPledgesPanel = ({ pledges }: MunicipalityPledgesPanelProps) => {
const declaredTotal = pledges.reduce((total, pledge) => total + pledge.declaredVotes, 0)
const effectiveTotal = pledges.reduce(
(total, pledge) =>
@ -93,14 +83,7 @@ export const MunicipalityPledgesPanel = ({
</Badge>
)}
</div>
<PledgeEstimateForm
pledgeID={pledge.id}
currentEstimatedVotes={pledge.estimatedVotes}
currentEstimateNote={pledge.estimateNote}
currentEstimatedAt={pledge.estimatedAt}
opsHybridEnabled={opsHybridEnabled}
formAction={estimateFormAction}
/>
<PledgeEstimateForm pledgeID={pledge.id} />
</li>
)
})}
@ -108,7 +91,7 @@ export const MunicipalityPledgesPanel = ({
</>
) : (
<p className="text-sm text-muted-foreground">
Nenhuma liderança declarou votos neste município ainda.
Nenhuma liderança vinculada a este município declarou votos ainda.
</p>
)}
</section>

View file

@ -1,18 +1,16 @@
'use client'
import { useActionState, useState, type FormEvent } from 'react'
import { useState, type FormEvent } from 'react'
import { municipalitiesCollection } from '@/components/campaign/opsSync/opsMirrorClient'
import { enqueueMunicipalityUpdate } from '@/components/campaign/opsSync/opsMunicipalityOutbox'
import { CampaignFormActionMessage } from '@/components/campaign/shared/CampaignFormActionMessage'
import { Badge } from '@/components/ui/Badge'
import { Button } from '@/components/ui/button'
import { Field, FieldDescription, FieldError, FieldLabel } from '@/components/ui/field'
import { Field, FieldDescription, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import { NativeSelect, NativeSelectOption } from '@/components/ui/native-select'
import { Spinner } from '@/components/ui/Spinner'
import { Textarea } from '@/components/ui/textarea'
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
import {
municipalitySignalTypeDescriptions,
municipalitySignalTypeLabels,
@ -22,27 +20,17 @@ import {
parseMunicipalitySignalType,
type MunicipalityUpdateKind,
} from '@/lib/schemas/municipalityUpdate'
import type { CampaignFormActionState } from '@/utilities/campaignFormActionError'
import { fieldError } from '@/utilities/campaignFormFields'
type MunicipalityUpdateFormProps = {
municipalityID: number
/** OH10 — parent municipality `updatedAt` for CAS when OPS_HYBRID is on. */
/** Parent municipality `updatedAt` for CAS. */
municipalityUpdatedAt?: string
opsHybridEnabled?: boolean
formAction: (
state: CampaignFormActionState,
formData: FormData,
) => Promise<CampaignFormActionState>
}
export const MunicipalityUpdateForm = ({
municipalityID,
municipalityUpdatedAt,
opsHybridEnabled = resolveOpsHybridEnabled(),
formAction,
}: MunicipalityUpdateFormProps) => {
const [state, submitAction, isPending] = useActionState(formAction, {})
const [kind, setKind] = useState<MunicipalityUpdateKind>('semanal')
const [hybridPending, setHybridPending] = useState(false)
const [hybridMessage, setHybridMessage] = useState<string | null>(null)
@ -99,14 +87,8 @@ export const MunicipalityUpdateForm = ({
)
}
const pending = opsHybridEnabled ? hybridPending : isPending
return (
<form
action={opsHybridEnabled ? undefined : submitAction}
onSubmit={opsHybridEnabled ? onHybridSubmit : undefined}
className="flex flex-col gap-4 rounded-xl border p-4"
>
<form onSubmit={onHybridSubmit} className="flex flex-col gap-4 rounded-xl border p-4">
<div className="flex flex-wrap items-center gap-2">
<h3 className="text-base font-medium">Registrar atualização</h3>
{hybridPending ? <Badge variant="estimate-pending">Pendente</Badge> : null}
@ -133,23 +115,14 @@ export const MunicipalityUpdateForm = ({
<Field>
<FieldLabel htmlFor="municipality-update-worked">O que funcionou</FieldLabel>
<Textarea id="municipality-update-worked" name="worked" rows={3} maxLength={3000} />
{fieldError(state.fieldErrors, 'worked') ? (
<FieldError>{fieldError(state.fieldErrors, 'worked')}</FieldError>
) : null}
</Field>
<Field>
<FieldLabel htmlFor="municipality-update-failed">O que não funcionou</FieldLabel>
<Textarea id="municipality-update-failed" name="failed" rows={3} maxLength={3000} />
{fieldError(state.fieldErrors, 'failed') ? (
<FieldError>{fieldError(state.fieldErrors, 'failed')}</FieldError>
) : null}
</Field>
<Field>
<FieldLabel htmlFor="municipality-update-needs">O que preciso</FieldLabel>
<Textarea id="municipality-update-needs" name="needs" rows={3} maxLength={3000} />
{fieldError(state.fieldErrors, 'needs') ? (
<FieldError>{fieldError(state.fieldErrors, 'needs')}</FieldError>
) : null}
</Field>
<div className="grid gap-4 sm:grid-cols-2">
<Field>
@ -186,9 +159,6 @@ export const MunicipalityUpdateForm = ({
rows={kind === 'sinal' ? 2 : 4}
maxLength={5000}
/>
{fieldError(state.fieldErrors, 'body') ? (
<FieldError>{fieldError(state.fieldErrors, 'body')}</FieldError>
) : null}
</Field>
{kind === 'sinal' ? (
<Field>
@ -222,15 +192,13 @@ export const MunicipalityUpdateForm = ({
) : null}
</>
)}
{!opsHybridEnabled ? (
<CampaignFormActionMessage state={state} successFallbackMessage="Atualização registrada." />
) : hybridMessage ? (
{hybridMessage ? (
<p className="text-sm text-muted-foreground" aria-live="polite">
{hybridMessage}
</p>
) : null}
<Button type="submit" disabled={pending} className="min-h-11 self-start">
{pending ? <Spinner data-icon="inline-start" aria-hidden="true" /> : null}
<Button type="submit" disabled={hybridPending} className="min-h-11 self-start">
{hybridPending ? <Spinner data-icon="inline-start" aria-hidden="true" /> : null}
Registrar atualização
</Button>
</form>

View file

@ -3,12 +3,11 @@
import { useEffect, useState, type ReactNode } from 'react'
import { useBrowserOffline } from '@/components/campaign/opsSync/useBrowserOffline'
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
/**
* Dual-path shell (OH9): SSR and first client paint always render `children`
* (RSC). After mount, when OPS_HYBRID is on and the *browser* is offline,
* swap to `fallback` (Local mirror view).
* (RSC). After mount, when the *browser* is offline, swap to `fallback` (Local
* mirror view).
*
* Sync-failure is intentionally NOT a Local trigger — RSC still works online;
* chrome owns “Dados podem estar desatualizados” via `useOpsOffline()`.
@ -23,7 +22,6 @@ export const OfflineBoundary = ({
children: ReactNode
fallback: ReactNode
}) => {
const hybrid = resolveOpsHybridEnabled()
const [mounted, setMounted] = useState(false)
const browserOffline = useBrowserOffline()
@ -31,5 +29,5 @@ export const OfflineBoundary = ({
setMounted(true)
}, [])
return <div className="contents">{mounted && hybrid && browserOffline ? fallback : children}</div>
return <div className="contents">{mounted && browserOffline ? fallback : children}</div>
}

View file

@ -41,7 +41,7 @@ export const CampaignMobileTopBar = ({
opsSyncStatus,
}: {
notificationBell?: ReactNode
/** OH5 — discreet sync chrome; only passed when OPS_HYBRID + staff. */
/** OH5 — discreet sync chrome; staff layout only. */
opsSyncStatus?: ReactNode
}) => {
const chrome = useCampaignWizardChrome()

View file

@ -30,7 +30,6 @@ import { Button } from '@/components/ui/button'
import { Field, FieldError, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import { Spinner } from '@/components/ui/Spinner'
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
import { OPS_UPDATED_AT_CONFLICT_MESSAGE } from '@/lib/schemas/opsCas'
import type { CampaignFormActionState } from '@/utilities/campaignFormActionError'
import { fieldError } from '@/utilities/campaignFormFields'
@ -44,7 +43,6 @@ type DeclareVotesFormProps = {
currentDeclaredVotes: number | null
/** Pledge row `updatedAt` for CAS when a pledge already exists. */
currentUpdatedAt?: string | null
opsHybridEnabled?: boolean
formAction: (
state: CampaignFormActionState,
formData: FormData,
@ -66,10 +64,9 @@ export const DeclareVotesForm = ({
pledgeId,
currentDeclaredVotes,
currentUpdatedAt = null,
opsHybridEnabled = resolveOpsHybridEnabled(),
formAction,
}: DeclareVotesFormProps) => {
if (!opsHybridEnabled || leadershipID === undefined) {
if (leadershipID === undefined) {
return (
<LegacyDeclareVotesForm
municipalityID={municipalityID}
@ -96,7 +93,7 @@ const LegacyDeclareVotesForm = ({
leadershipID,
currentDeclaredVotes,
formAction,
}: Omit<DeclareVotesFormProps, 'opsHybridEnabled' | 'currentUpdatedAt'>) => {
}: Omit<DeclareVotesFormProps, 'currentUpdatedAt'>) => {
const [state, submitAction, isPending] = useActionState(formAction, {})
return (

View file

@ -1,15 +1,7 @@
'use client'
import { useRouter } from 'next/navigation'
import {
useActionState,
useEffect,
useId,
useRef,
useState,
useSyncExternalStore,
type FormEvent,
} from 'react'
import { useEffect, useId, useRef, useState, useSyncExternalStore, type FormEvent } from 'react'
import { toast } from 'sonner'
import {
@ -24,7 +16,6 @@ import {
readOpsVotePledge,
subscribeOpsVotePledge,
} from '@/components/campaign/opsSync/opsVotePledgeMirror'
import { CampaignFormActionMessage } from '@/components/campaign/shared/CampaignFormActionMessage'
import { VoteEstimateScenarioInputs } from '@/components/campaign/votePledge/VoteEstimateScenarioInputs'
import { Badge } from '@/components/ui/Badge'
import { Button } from '@/components/ui/button'
@ -36,20 +27,9 @@ import {
toVoteEstimateScenarioViewModel,
type VoteEstimateScenarioViewModel,
} from '@/lib/voteEstimate'
import type { CampaignFormActionState } from '@/utilities/campaignFormActionError'
import { fieldError } from '@/utilities/campaignFormFields'
type PledgeEstimateFormProps = {
pledgeID: number
currentEstimatedVotes: VoteEstimateScenarioViewModel
currentEstimateNote: string | null
/** RSC `estimatedAt` used as CAS base when the hybrid outbox path is on. */
currentEstimatedAt: string | null
opsHybridEnabled: boolean
formAction: (
state: CampaignFormActionState,
formData: FormData,
) => Promise<CampaignFormActionState>
}
const syncStatusLabel: Record<OpsEstimateSyncStatus, string> = {
@ -87,82 +67,7 @@ const readScenarioFromForm = (form: HTMLFormElement): VoteEstimateScenarioViewMo
const CONFLICT_TOAST_ID_PREFIX = 'ops-estimate-conflict:'
/** Staff-only inline estimate. The leader never sees these fields. */
export const PledgeEstimateForm = ({
pledgeID,
currentEstimatedVotes,
currentEstimateNote,
currentEstimatedAt: _currentEstimatedAt,
opsHybridEnabled,
formAction,
}: PledgeEstimateFormProps) => {
if (!opsHybridEnabled) {
return (
<LegacyPledgeEstimateForm
pledgeID={pledgeID}
currentEstimatedVotes={currentEstimatedVotes}
currentEstimateNote={currentEstimateNote}
formAction={formAction}
/>
)
}
return <HybridPledgeEstimateForm pledgeID={pledgeID} />
}
const LegacyPledgeEstimateForm = ({
pledgeID,
currentEstimatedVotes,
currentEstimateNote,
formAction,
}: Omit<PledgeEstimateFormProps, 'opsHybridEnabled' | 'currentEstimatedAt'>) => {
const [state, submitAction, isPending] = useActionState(formAction, {})
return (
<form action={submitAction} className="flex flex-col gap-3">
<input type="hidden" name="pledgeId" value={pledgeID} />
<VoteEstimateScenarioInputs
fieldPrefix="estimatedVotes"
values={currentEstimatedVotes}
idPrefix={`pledge-estimate-${pledgeID}`}
/>
<Field>
<FieldLabel htmlFor={`pledge-note-${pledgeID}`} className="text-xs">
Justificativa
</FieldLabel>
<Input
id={`pledge-note-${pledgeID}`}
name="estimateNote"
maxLength={1000}
defaultValue={currentEstimateNote ?? undefined}
className="min-h-11"
/>
</Field>
<Button
type="submit"
variant="secondary"
disabled={isPending}
className="min-h-11 self-start"
>
{isPending ? <Spinner data-icon="inline-start" aria-hidden="true" /> : null}
Salvar estimativa
</Button>
{fieldError(state.fieldErrors, 'estimatedVotes') ||
fieldError(state.fieldErrors, 'pessimistic') ||
fieldError(state.fieldErrors, 'central') ||
fieldError(state.fieldErrors, 'optimistic') ? (
<FieldError>
{fieldError(state.fieldErrors, 'estimatedVotes') ||
fieldError(state.fieldErrors, 'pessimistic') ||
fieldError(state.fieldErrors, 'central') ||
fieldError(state.fieldErrors, 'optimistic')}
</FieldError>
) : null}
{state.status !== 'success' ? <CampaignFormActionMessage state={state} /> : null}
</form>
)
}
const HybridPledgeEstimateForm = ({ pledgeID }: { pledgeID: number }) => {
export const PledgeEstimateForm = ({ pledgeID }: PledgeEstimateFormProps) => {
const router = useRouter()
const liveRegionId = useId()
const formRef = useRef<HTMLFormElement>(null)

View file

@ -1,7 +0,0 @@
type OpsHybridEnv = Record<string, string | undefined>
/** Compile-time env gate for the ops hybrid mirror (OH1). Truthy only for `'1'` or `'true'`. */
export const resolveOpsHybridEnabled = (env: OpsHybridEnv = process.env): boolean => {
const value = env.OPS_HYBRID
return value === '1' || value === 'true'
}

View file

@ -1,4 +1,4 @@
/** Client-safe FormData helpers for OPS_HYBRID enqueue paths (OH13). */
/** Client-safe FormData helpers for ops hybrid enqueue paths (OH13). */
export const readFormRelationshipIds = (data: FormData, name: string): number[] => {
const ids: number[] = []

View file

@ -143,7 +143,7 @@ export type ActivityFormViewModel = {
responsible: { id: number; name: string; phone: string | null } | null
leadership: { id: number; label: string } | null
tasks: ActivityFormTaskViewModel[]
/** OH13 — CAS token for staff updates when OPS_HYBRID is on. */
/** OH13 — CAS token for staff update outbox writes. */
updatedAt: string
}

View file

@ -153,7 +153,7 @@ export type DemandDetailViewModel = DemandRowViewModel & {
}>
canLeaderEdit: boolean
activity: { title: string; slug: string } | null
/** OH13 — CAS token for staff transitions when OPS_HYBRID is on. */
/** OH13 — CAS token for staff transition outbox writes. */
updatedAt: string
}

View file

@ -74,7 +74,7 @@ export type MunicipalityListViewModel = {
* ordering.
*/
lastSignalAt: string | null
/** OH10 — CAS token for staff writes when OPS_HYBRID is on. */
/** OH10 — CAS token for staff outbox writes. */
updatedAt: string
expectedVotes: VoteEstimateScenarioViewModel
politicalTrendStatus: PoliticalTrendStatus | null
@ -153,7 +153,7 @@ export type MunicipalityDetailViewModel = {
tseZones: number[]
advisorIDs: number[]
lastUpdateAt: string | null
/** OH10 — CAS token for staff writes when OPS_HYBRID is on. */
/** OH10 — CAS token for staff outbox writes. */
updatedAt: string
/** Staff-only block — null for the leader view model. */
strategy: MunicipalityStrategyViewModel | null

View file

@ -162,6 +162,6 @@ export type StaffPledgeRow = {
estimatedVotes: VoteEstimateScenarioViewModel
estimateNote: string | null
estimatedAt: string | null
/** OH10 — CAS token for declareVotes when OPS_HYBRID is on. */
/** OH10 — CAS token for declareVotes outbox writes. */
updatedAt: string
}

View file

@ -1,16 +1,7 @@
import { expect, test } from './fixtures/campaignE2EFixtures.js'
/**
* OH6 — flaky-network outbox for estimateVotes. Requires `OPS_HYBRID=1` on the
* Playwright webServer (compile-time). Default CI keeps the flag off so
* `campaignMunicipalities` continues to pin the legacy formAction path.
*/
const opsHybridEnabled =
process.env.OPS_HYBRID === '1' || process.env.OPS_HYBRID?.toLowerCase() === 'true'
test.describe('OH6 estimate outbox (OPS_HYBRID)', () => {
test.skip(!opsHybridEnabled, 'Set OPS_HYBRID=1 on the e2e webServer to run this tracer.')
/** OH6 — flaky-network outbox for estimateVotes. */
test.describe('OH6 estimate outbox', () => {
test('offline edit stays queued across reload and flushes when online', async ({
campaign,
page,

View file

@ -1,17 +1,7 @@
import { expect, test } from './fixtures/campaignE2EFixtures.js'
/**
* OH9/OH11/OH12 — dual-path municipality detail + offline journey + list Local.
* Requires `OPS_HYBRID=1` on the Playwright webServer (compile-time). Default CI
* keeps the flag off so characterization / municipalities specs continue to pin
* the RSC path.
*/
const opsHybridEnabled =
process.env.OPS_HYBRID === '1' || process.env.OPS_HYBRID?.toLowerCase() === 'true'
test.describe('OH9/OH11 campaign ops offline (OPS_HYBRID)', () => {
test.skip(!opsHybridEnabled, 'Set OPS_HYBRID=1 on the e2e webServer to run this dual-path.')
/** OH9/OH11/OH12 — dual-path municipality detail + offline journey + list Local. */
test.describe('OH9/OH11 campaign ops offline', () => {
test('offline swaps to Local header + pledges with honest online-only placeholder', async ({
campaign,
page,
@ -125,9 +115,7 @@ test.describe('OH9/OH11 campaign ops offline (OPS_HYBRID)', () => {
})
})
test.describe('OH12 municipality list Local (OPS_HYBRID)', () => {
test.skip(!opsHybridEnabled, 'Set OPS_HYBRID=1 on the e2e webServer to run this dual-path.')
test.describe('OH12 municipality list Local', () => {
test('offline list renders mirror rows and filters by ?q=', async ({ campaign, page }) => {
const { fixtures } = campaign
const municipality = await fixtures.claimMunicipality()

View file

@ -20,7 +20,6 @@ import {
type OpsVotePledge,
type OpsVotePledgeLeaderView,
} from '@/lib/campaignOps/opsContract'
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
import { diffOpsIds, mergeOpsSnapshot, type OpsCollectionIdDiff } from '@/lib/campaignOps/opsMerge'
import { OPS_MIRROR_SCHEMA_VERSION } from '@/lib/campaignOps/opsMirrorVersion'
import type { OpsSyncState, OpsSyncStatus } from '@/lib/campaignOps/opsSyncMeta'
@ -178,20 +177,6 @@ describe('contract surface (knip + OH4 consumers)', () => {
})
})
describe('resolveOpsHybridEnabled', () => {
it.each([
['1', true],
['true', true],
['0', false],
['false', false],
['', false],
[undefined, false],
['yes', false],
] as const)('parses OPS_HYBRID=%j as %s', (value, expected) => {
expect(resolveOpsHybridEnabled({ OPS_HYBRID: value })).toBe(expected)
})
})
describe('OpsVotePledgeLeaderView', () => {
it('excludes staff-only estimate fields at the type level', () => {
const leaderView: OpsVotePledgeLeaderView = {

View file

@ -276,7 +276,7 @@ describe('opsMirrorClient', () => {
})
describe('leader defense in depth (layout gate)', () => {
it('treats leader as non-staff so provider stays no-op even with OPS_HYBRID', () => {
it('treats leader as non-staff so provider stays no-op', () => {
expect(isStaffCampaignRole('leader')).toBe(false)
expect(isStaffCampaignRole('advisor')).toBe(true)
expect(isStaffCampaignRole('coordinator')).toBe(true)