mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-26 21:53:06 +00:00
Merge pull request #230 from fsolla/cursor/pool-i175-29b01649-361e
OH14 — Limpeza da flag OPS_HYBRID + documentação final
This commit is contained in:
commit
4942e3d149
54 changed files with 375 additions and 808 deletions
|
|
@ -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=
|
||||
|
|
|
|||
|
|
@ -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).
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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`)
|
||||
|
|
|
|||
|
|
@ -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: {
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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 ?? '',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
|
|
|||
|
|
@ -5,21 +5,11 @@ import { revalidatePath } from 'next/cache'
|
|||
import {
|
||||
attachCampaignDemandReceiptRecord,
|
||||
setCampaignDemandCost,
|
||||
transitionCampaignDemand,
|
||||
} from '@/app/(campaign)/campanha/actions/demand'
|
||||
import {
|
||||
FormDataBoundaryError,
|
||||
nullableFormText,
|
||||
requiredFormText,
|
||||
requiredRelationshipFormValue,
|
||||
} from '@/lib/formData'
|
||||
import { FormDataBoundaryError, requiredRelationshipFormValue } from '@/lib/formData'
|
||||
import {
|
||||
CAMPAIGN_DEMAND_COST_STAFF_MESSAGE,
|
||||
CAMPAIGN_DEMAND_INVALID_STATUS_MESSAGE,
|
||||
CAMPAIGN_DEMAND_RECEIPT_SAFE_MESSAGES,
|
||||
CAMPAIGN_DEMAND_TRANSITION_SAFE_MESSAGES,
|
||||
campaignDemandStatuses,
|
||||
type CampaignDemandStatus,
|
||||
} from '@/lib/schemas/campaignDemand'
|
||||
import { getCampaignActionContext } from '@/utilities/campaignActionContext'
|
||||
import {
|
||||
|
|
@ -27,33 +17,6 @@ import {
|
|||
type CampaignFormActionState,
|
||||
} from '@/utilities/campaignFormActionError'
|
||||
|
||||
const INVALID_STATUS_MESSAGE = CAMPAIGN_DEMAND_INVALID_STATUS_MESSAGE
|
||||
|
||||
const transitionSafeMessages = CAMPAIGN_DEMAND_TRANSITION_SAFE_MESSAGES
|
||||
|
||||
export const transitionDemandFormAction = async (
|
||||
_state: CampaignFormActionState,
|
||||
formData: FormData,
|
||||
): Promise<CampaignFormActionState> =>
|
||||
runCampaignFormAction({
|
||||
execute: async () => {
|
||||
const rawStatus = requiredFormText(formData, 'status')
|
||||
if (!campaignDemandStatuses.includes(rawStatus as CampaignDemandStatus)) {
|
||||
throw new Error(INVALID_STATUS_MESSAGE)
|
||||
}
|
||||
|
||||
await transitionCampaignDemand({
|
||||
id: requiredRelationshipFormValue(formData, 'demandId'),
|
||||
status: rawStatus as CampaignDemandStatus,
|
||||
decisionNote: nullableFormText(formData, 'decisionNote'),
|
||||
})
|
||||
revalidatePath('/campanha/demandas/[slug]', 'page')
|
||||
return { message: 'Demanda atualizada.' }
|
||||
},
|
||||
safeMessages: transitionSafeMessages,
|
||||
genericMessage: 'Não foi possível mover a demanda. Verifique seu acesso e tente novamente.',
|
||||
})
|
||||
|
||||
export const setDemandCostFormAction = async (
|
||||
_state: CampaignFormActionState,
|
||||
formData: FormData,
|
||||
|
|
|
|||
|
|
@ -17,11 +17,7 @@ import {
|
|||
import { isCampaignUnrestricted } from '@/utilities/campaignAccess'
|
||||
import { loadDemandDetail } from '@/utilities/campaignDemandData'
|
||||
import { requireCampaignPageActor } from '@/utilities/campaignPageActor'
|
||||
import {
|
||||
attachDemandReceiptFormAction,
|
||||
setDemandCostFormAction,
|
||||
transitionDemandFormAction,
|
||||
} from './formActions'
|
||||
import { attachDemandReceiptFormAction, setDemandCostFormAction } from './formActions'
|
||||
|
||||
type DemandDetailPageProps = {
|
||||
params: Promise<{ slug: string }>
|
||||
|
|
@ -129,7 +125,6 @@ export default async function DemandDetailPage({ params }: DemandDetailPageProps
|
|||
canDecideEscalated={isCampaignUnrestricted(user)}
|
||||
currentCost={demand.cost}
|
||||
updatedAt={demand.updatedAt}
|
||||
transitionFormAction={transitionDemandFormAction}
|
||||
costFormAction={setDemandCostFormAction}
|
||||
receiptFormAction={attachDemandReceiptFormAction}
|
||||
/>
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -4,17 +4,9 @@ import { revalidatePath } from 'next/cache'
|
|||
|
||||
import { MAX_VOTE_COUNT } from '@/lib/schemas/primitives'
|
||||
|
||||
import { declareVotes, estimateVotes } from '@/app/(campaign)/campanha/actions/votePledge'
|
||||
import {
|
||||
nullableFormText,
|
||||
requiredIntegerFormValue,
|
||||
requiredRelationshipFormValue,
|
||||
voteEstimateScenarioFromForm,
|
||||
} from '@/lib/formData'
|
||||
import {
|
||||
VOTE_PLEDGE_DECLARE_SAFE_MESSAGES,
|
||||
VOTE_PLEDGE_ESTIMATE_SAFE_MESSAGES,
|
||||
} from '@/lib/schemas/votePledge'
|
||||
import { declareVotes } from '@/app/(campaign)/campanha/actions/votePledge'
|
||||
import { requiredIntegerFormValue, requiredRelationshipFormValue } from '@/lib/formData'
|
||||
import { VOTE_PLEDGE_DECLARE_SAFE_MESSAGES } from '@/lib/schemas/votePledge'
|
||||
import {
|
||||
runCampaignFormAction,
|
||||
type CampaignFormActionState,
|
||||
|
|
@ -43,26 +35,3 @@ export const declareVotesFormAction = async (
|
|||
genericMessage:
|
||||
'Não foi possível registrar a declaração. Verifique seu acesso e tente novamente.',
|
||||
})
|
||||
|
||||
export const estimateVotesFormAction = async (
|
||||
_state: CampaignFormActionState,
|
||||
formData: FormData,
|
||||
): Promise<CampaignFormActionState> =>
|
||||
runCampaignFormAction({
|
||||
execute: async () => {
|
||||
const pledge = requiredRelationshipFormValue(formData, 'pledgeId')
|
||||
const estimatedVotes = voteEstimateScenarioFromForm(formData, 'estimatedVotes')
|
||||
const estimateNote = nullableFormText(formData, 'estimateNote')
|
||||
|
||||
await estimateVotes({
|
||||
pledge,
|
||||
estimatedVotes,
|
||||
estimateNote,
|
||||
})
|
||||
revalidatePath('/campanha/municipios/[slug]', 'page')
|
||||
return { message: 'Estimativa registrada.' }
|
||||
},
|
||||
safeMessages: VOTE_PLEDGE_ESTIMATE_SAFE_MESSAGES,
|
||||
genericMessage:
|
||||
'Não foi possível registrar a estimativa. Verifique seu acesso e tente novamente.',
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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.',
|
||||
})
|
||||
|
|
@ -206,11 +206,6 @@ export const createCampaignDemand = async (input: CampaignDemandCreateInput) =>
|
|||
return createCampaignDemandRecord(payload, actor, input)
|
||||
}
|
||||
|
||||
export const transitionCampaignDemand = async (input: CampaignDemandTransitionInput) => {
|
||||
const { payload, actor } = await getCampaignActionContext()
|
||||
return transitionCampaignDemandRecord(payload, actor, input)
|
||||
}
|
||||
|
||||
export const transitionCampaignDemandCas = async (input: CampaignDemandTransitionInput) => {
|
||||
const { payload, actor } = await getCampaignActionContext()
|
||||
return transitionCampaignDemandRecord(payload, actor, input, { cas: true })
|
||||
|
|
|
|||
|
|
@ -222,11 +222,6 @@ export const estimateVotesRecord = async (
|
|||
)
|
||||
}
|
||||
|
||||
export const estimateVotes = async (input: EstimateVotesInput) => {
|
||||
const { payload, actor } = await getCampaignActionContext()
|
||||
return estimateVotesRecord(payload, actor, input)
|
||||
}
|
||||
|
||||
/**
|
||||
* OH6 — estimate with optional CAS on `estimatedAt`. Without `baseEstimatedAt`
|
||||
* this matches `estimateVotes` (last-write-wins). With a base, a stale token
|
||||
|
|
|
|||
|
|
@ -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) =>
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
|
|
|||
|
|
@ -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) => {
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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,8 +27,6 @@ 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'
|
||||
|
|
@ -39,7 +36,6 @@ import type {
|
|||
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 {
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
'use client'
|
||||
|
||||
import { createCollection, localOnlyCollectionOptions } from '@tanstack/db'
|
||||
import { createCollection, localOnlyCollectionOptions, type Transaction } from '@tanstack/db'
|
||||
import {
|
||||
IndexedDBAdapter,
|
||||
NonRetriableError,
|
||||
|
|
@ -43,6 +43,14 @@ const LEADERSHIP_CREATE_FN = 'createLeadership'
|
|||
const DEMAND_TRANSITION_FN = 'transitionCampaignDemand'
|
||||
const ACTIVITY_UPDATE_FN = 'updateActivity'
|
||||
|
||||
const outboxMutationRow = <TRow>(transaction: Transaction, collectionId: string): TRow => {
|
||||
const mutation = transaction.mutations.find((entry) => entry.collection?.id === collectionId)
|
||||
if (!mutation) {
|
||||
throw new NonRetriableError(`Mutação de outbox ausente (${collectionId}).`)
|
||||
}
|
||||
return mutation.modified as TRow
|
||||
}
|
||||
|
||||
const leadershipUpdateOutboxCollection = createCollection(
|
||||
localOnlyCollectionOptions<OpsLeadershipUpdateOutboxRow, number>({
|
||||
id: 'ops-leadership-update-outbox',
|
||||
|
|
@ -129,14 +137,19 @@ const createDomainOfflineExecutor = (): OfflineExecutor =>
|
|||
leadershipCreateOutbox: leadershipCreateOutboxCollection,
|
||||
demandTransitionOutbox: demandTransitionOutboxCollection,
|
||||
activityUpdateOutbox: activityUpdateOutboxCollection,
|
||||
// Mirror rows touched in onMutate must be registered for persistence.
|
||||
leaderships: leadershipsCollection,
|
||||
demands: demandsCollection,
|
||||
activities: activitiesCollection,
|
||||
},
|
||||
storage: new IndexedDBAdapter('teqo-ops-domain', 'outbox'),
|
||||
beforeRetry: collapseAllDomainOutbox,
|
||||
mutationFns: {
|
||||
[LEADERSHIP_UPDATE_FN]: async ({ transaction }) => {
|
||||
const mutation = transaction.mutations[0]
|
||||
if (!mutation) throw new NonRetriableError('Mutação de liderança vazia.')
|
||||
const row = mutation.modified as OpsLeadershipUpdateOutboxRow
|
||||
const row = outboxMutationRow<OpsLeadershipUpdateOutboxRow>(
|
||||
transaction,
|
||||
'ops-leadership-update-outbox',
|
||||
)
|
||||
try {
|
||||
const updated = await updateLeadershipInternalCas({
|
||||
id: row.leadershipId,
|
||||
|
|
@ -193,9 +206,10 @@ const createDomainOfflineExecutor = (): OfflineExecutor =>
|
|||
}
|
||||
},
|
||||
[LEADERSHIP_CREATE_FN]: async ({ transaction }) => {
|
||||
const mutation = transaction.mutations[0]
|
||||
if (!mutation) throw new NonRetriableError('Mutação de cadastro vazia.')
|
||||
const row = mutation.modified as OpsLeadershipCreateOutboxRow
|
||||
const row = outboxMutationRow<OpsLeadershipCreateOutboxRow>(
|
||||
transaction,
|
||||
'ops-leadership-create-outbox',
|
||||
)
|
||||
try {
|
||||
await createLeadershipCas({
|
||||
name: row.name,
|
||||
|
|
@ -224,9 +238,10 @@ const createDomainOfflineExecutor = (): OfflineExecutor =>
|
|||
}
|
||||
},
|
||||
[DEMAND_TRANSITION_FN]: async ({ transaction }) => {
|
||||
const mutation = transaction.mutations[0]
|
||||
if (!mutation) throw new NonRetriableError('Mutação de demanda vazia.')
|
||||
const row = mutation.modified as OpsDemandTransitionOutboxRow
|
||||
const row = outboxMutationRow<OpsDemandTransitionOutboxRow>(
|
||||
transaction,
|
||||
'ops-demand-transition-outbox',
|
||||
)
|
||||
try {
|
||||
const updated = await transitionCampaignDemandCas({
|
||||
id: row.demandId,
|
||||
|
|
@ -267,9 +282,10 @@ const createDomainOfflineExecutor = (): OfflineExecutor =>
|
|||
}
|
||||
},
|
||||
[ACTIVITY_UPDATE_FN]: async ({ transaction }) => {
|
||||
const mutation = transaction.mutations[0]
|
||||
if (!mutation) throw new NonRetriableError('Mutação de atividade vazia.')
|
||||
const row = mutation.modified as OpsActivityUpdateOutboxRow
|
||||
const row = outboxMutationRow<OpsActivityUpdateOutboxRow>(
|
||||
transaction,
|
||||
'ops-activity-update-outbox',
|
||||
)
|
||||
try {
|
||||
const updated = await updateActivityCas({
|
||||
id: row.activityId,
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
'use client'
|
||||
|
||||
import { createCollection, localOnlyCollectionOptions } from '@tanstack/db'
|
||||
import { createCollection, localOnlyCollectionOptions, type Transaction } from '@tanstack/db'
|
||||
import {
|
||||
IndexedDBAdapter,
|
||||
NonRetriableError,
|
||||
|
|
@ -19,6 +19,7 @@ import {
|
|||
applyOpsVotePledgeEstimateWrite,
|
||||
patchOpsVotePledgeEstimateOptimistic,
|
||||
readOpsVotePledge,
|
||||
votePledgesCollection,
|
||||
} from '@/components/campaign/opsSync/opsVotePledgeMirror'
|
||||
import { opsOutboxKey, type OpsOutboxKey } from '@/lib/campaignOps/opsContract'
|
||||
import {
|
||||
|
|
@ -28,6 +29,14 @@ import {
|
|||
|
||||
const ESTIMATE_MUTATION_FN = 'estimateVotes'
|
||||
|
||||
const outboxMutationRow = <TRow>(transaction: Transaction, collectionId: string): TRow => {
|
||||
const mutation = transaction.mutations.find((entry) => entry.collection?.id === collectionId)
|
||||
if (!mutation) {
|
||||
throw new NonRetriableError(`Mutação de outbox ausente (${collectionId}).`)
|
||||
}
|
||||
return mutation.modified as TRow
|
||||
}
|
||||
|
||||
const opsEstimateOutboxCollection = createCollection(
|
||||
localOnlyCollectionOptions<OpsEstimateOutboxRow, number>({
|
||||
id: 'ops-estimate-outbox',
|
||||
|
|
@ -40,17 +49,16 @@ let initPromise: Promise<OfflineExecutor> | null = null
|
|||
|
||||
const createEstimateOfflineExecutor = (): OfflineExecutor =>
|
||||
startOfflineExecutor({
|
||||
collections: { estimateOutbox: opsEstimateOutboxCollection },
|
||||
collections: {
|
||||
estimateOutbox: opsEstimateOutboxCollection,
|
||||
// Mirror rows touched in onMutate must be registered for persistence.
|
||||
votePledges: votePledgesCollection,
|
||||
},
|
||||
storage: new IndexedDBAdapter('teqo-ops-estimate', 'outbox'),
|
||||
beforeRetry: collapseEstimateOutboxByPledge,
|
||||
mutationFns: {
|
||||
[ESTIMATE_MUTATION_FN]: async ({ transaction }) => {
|
||||
const mutation = transaction.mutations[0]
|
||||
if (!mutation) {
|
||||
throw new NonRetriableError('Mutação de estimativa vazia.')
|
||||
}
|
||||
|
||||
const row = mutation.modified as OpsEstimateOutboxRow
|
||||
const row = outboxMutationRow<OpsEstimateOutboxRow>(transaction, 'ops-estimate-outbox')
|
||||
|
||||
try {
|
||||
const updated = await estimateVotesCas({
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
'use client'
|
||||
|
||||
import { createCollection, localOnlyCollectionOptions } from '@tanstack/db'
|
||||
import { createCollection, localOnlyCollectionOptions, type Transaction } from '@tanstack/db'
|
||||
import {
|
||||
IndexedDBAdapter,
|
||||
NonRetriableError,
|
||||
|
|
@ -50,6 +50,14 @@ const TREND_MUTATION_FN = 'setPoliticalTrend'
|
|||
const ENGAGEMENT_MUTATION_FN = 'setEngagementLevel'
|
||||
const ADVISORS_MUTATION_FN = 'assignAdvisors'
|
||||
|
||||
const outboxMutationRow = <TRow>(transaction: Transaction, collectionId: string): TRow => {
|
||||
const mutation = transaction.mutations.find((entry) => entry.collection?.id === collectionId)
|
||||
if (!mutation) {
|
||||
throw new NonRetriableError(`Mutação de outbox ausente (${collectionId}).`)
|
||||
}
|
||||
return mutation.modified as TRow
|
||||
}
|
||||
|
||||
const declareVotesOutboxCollection = createCollection(
|
||||
localOnlyCollectionOptions<OpsDeclareVotesOutboxRow, string>({
|
||||
id: 'ops-declare-votes-outbox',
|
||||
|
|
@ -148,14 +156,17 @@ const createMunicipalityOfflineExecutor = (): OfflineExecutor =>
|
|||
politicalTrendOutbox: politicalTrendOutboxCollection,
|
||||
engagementLevelOutbox: engagementLevelOutboxCollection,
|
||||
advisorsOutbox: advisorsOutboxCollection,
|
||||
// Mirror rows touched in onMutate must be registered for persistence.
|
||||
votePledges: votePledgesCollection,
|
||||
},
|
||||
storage: new IndexedDBAdapter('teqo-ops-municipality', 'outbox'),
|
||||
beforeRetry: collapseAllMunicipalityOutbox,
|
||||
mutationFns: {
|
||||
[DECLARE_MUTATION_FN]: async ({ transaction }) => {
|
||||
const mutation = transaction.mutations[0]
|
||||
if (!mutation) throw new NonRetriableError('Mutação de declaração vazia.')
|
||||
const row = mutation.modified as OpsDeclareVotesOutboxRow
|
||||
const row = outboxMutationRow<OpsDeclareVotesOutboxRow>(
|
||||
transaction,
|
||||
'ops-declare-votes-outbox',
|
||||
)
|
||||
try {
|
||||
const updated = await declareVotesCas({
|
||||
municipality: row.municipalityId,
|
||||
|
|
@ -191,9 +202,10 @@ const createMunicipalityOfflineExecutor = (): OfflineExecutor =>
|
|||
}
|
||||
},
|
||||
[MUNICIPALITY_UPDATE_MUTATION_FN]: async ({ transaction }) => {
|
||||
const mutation = transaction.mutations[0]
|
||||
if (!mutation) throw new NonRetriableError('Mutação de atualização vazia.')
|
||||
const row = mutation.modified as OpsMunicipalityUpdateOutboxRow
|
||||
const row = outboxMutationRow<OpsMunicipalityUpdateOutboxRow>(
|
||||
transaction,
|
||||
'ops-municipality-update-outbox',
|
||||
)
|
||||
try {
|
||||
await createMunicipalityUpdateCas({
|
||||
municipality: row.municipalityId,
|
||||
|
|
@ -234,9 +246,10 @@ const createMunicipalityOfflineExecutor = (): OfflineExecutor =>
|
|||
}
|
||||
},
|
||||
[TREND_MUTATION_FN]: async ({ transaction }) => {
|
||||
const mutation = transaction.mutations[0]
|
||||
if (!mutation) throw new NonRetriableError('Mutação de tendência vazia.')
|
||||
const row = mutation.modified as OpsPoliticalTrendOutboxRow
|
||||
const row = outboxMutationRow<OpsPoliticalTrendOutboxRow>(
|
||||
transaction,
|
||||
'ops-political-trend-outbox',
|
||||
)
|
||||
try {
|
||||
await setMunicipalityPoliticalTrendCas({
|
||||
municipality: row.municipalityId,
|
||||
|
|
@ -271,9 +284,10 @@ const createMunicipalityOfflineExecutor = (): OfflineExecutor =>
|
|||
}
|
||||
},
|
||||
[ENGAGEMENT_MUTATION_FN]: async ({ transaction }) => {
|
||||
const mutation = transaction.mutations[0]
|
||||
if (!mutation) throw new NonRetriableError('Mutação de nível vazia.')
|
||||
const row = mutation.modified as OpsEngagementLevelOutboxRow
|
||||
const row = outboxMutationRow<OpsEngagementLevelOutboxRow>(
|
||||
transaction,
|
||||
'ops-engagement-level-outbox',
|
||||
)
|
||||
try {
|
||||
await setMunicipalityEngagementLevelCas({
|
||||
municipality: row.municipalityId,
|
||||
|
|
@ -311,9 +325,7 @@ const createMunicipalityOfflineExecutor = (): OfflineExecutor =>
|
|||
}
|
||||
},
|
||||
[ADVISORS_MUTATION_FN]: async ({ transaction }) => {
|
||||
const mutation = transaction.mutations[0]
|
||||
if (!mutation) throw new NonRetriableError('Mutação de assessores vazia.')
|
||||
const row = mutation.modified as OpsAdvisorsOutboxRow
|
||||
const row = outboxMutationRow<OpsAdvisorsOutboxRow>(transaction, 'ops-advisors-outbox')
|
||||
try {
|
||||
await assignMunicipalityAdvisorsCas({
|
||||
municipality: row.municipalityId,
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
|
|
@ -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 (
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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'
|
||||
}
|
||||
|
|
@ -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[] = []
|
||||
|
|
|
|||
|
|
@ -93,16 +93,6 @@ export const requiredIntegerFormValue = (
|
|||
return parsed
|
||||
}
|
||||
|
||||
export const optionalIntegerFormValue = (
|
||||
formData: FormData,
|
||||
field: string,
|
||||
options?: { minimum?: number; maximum?: number },
|
||||
): number | undefined => {
|
||||
const entry = formEntry(formData, field)
|
||||
if (!entry.present || !entry.value.trim()) return undefined
|
||||
return requiredIntegerFormValue(formData, field, options)
|
||||
}
|
||||
|
||||
const optionalNullableIntegerFormValue = (
|
||||
formData: FormData,
|
||||
field: string,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,3 @@
|
|||
import { OPS_UPDATED_AT_CONFLICT_MESSAGE } from '@/lib/schemas/opsCas'
|
||||
|
||||
export const campaignDemandKinds = [
|
||||
'material',
|
||||
'servico',
|
||||
|
|
@ -80,13 +78,6 @@ export const CAMPAIGN_DEMAND_RECEIPT_TYPE_MESSAGE = 'Envie uma imagem (JPEG, PNG
|
|||
export const CAMPAIGN_DEMAND_RECEIPT_EMPTY_MESSAGE = 'O arquivo enviado está vazio.'
|
||||
export const CAMPAIGN_DEMAND_RECEIPT_SIZE_MESSAGE = 'O comprovante deve ter no máximo 10 MB.'
|
||||
|
||||
export const CAMPAIGN_DEMAND_TRANSITION_SAFE_MESSAGES = [
|
||||
CAMPAIGN_DEMAND_TRANSITION_STAFF_MESSAGE,
|
||||
CAMPAIGN_DEMAND_ESCALATED_DECISION_MESSAGE,
|
||||
CAMPAIGN_DEMAND_INVALID_STATUS_MESSAGE,
|
||||
OPS_UPDATED_AT_CONFLICT_MESSAGE,
|
||||
] as const
|
||||
|
||||
export const CAMPAIGN_DEMAND_RECEIPT_SAFE_MESSAGES = [
|
||||
CAMPAIGN_DEMAND_RECEIPT_TYPE_MESSAGE,
|
||||
CAMPAIGN_DEMAND_RECEIPT_EMPTY_MESSAGE,
|
||||
|
|
|
|||
|
|
@ -100,10 +100,5 @@ export const VOTE_PLEDGE_DECLARE_SAFE_MESSAGES = [
|
|||
OPS_UPDATED_AT_CONFLICT_MESSAGE,
|
||||
] as const
|
||||
|
||||
export const VOTE_PLEDGE_ESTIMATE_SAFE_MESSAGES = [
|
||||
VOTE_PLEDGE_ESTIMATE_STAFF_MESSAGE,
|
||||
OPS_ESTIMATE_CONFLICT_MESSAGE,
|
||||
] as const
|
||||
|
||||
export type DeclareVotesInput = z.input<typeof declareVotesSchema>
|
||||
export type EstimateVotesInput = z.input<typeof estimateVotesSchema>
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ test.describe('Lideranças — shell (OH8)', () => {
|
|||
await page.goto(`${campaign.baseURL}/campanha/liderancas`)
|
||||
await expect(page.getByRole('heading', { name: 'Lideranças', exact: true })).toBeVisible()
|
||||
await expect(page.getByLabel('Buscar liderança por nome')).toBeVisible()
|
||||
await expect(page.getByText(/\d+ lideranças/)).toBeVisible()
|
||||
await expect(page.getByText(/\d+ lideranças/).first()).toBeVisible()
|
||||
})
|
||||
})
|
||||
|
||||
|
|
@ -50,12 +50,12 @@ test.describe('campaign leaderships list', () => {
|
|||
await expect(statusPopover).toBeVisible()
|
||||
await expect(statusPopover.getByRole('button', { name: 'Salvar' })).toHaveCount(0)
|
||||
|
||||
// Auto-save (150 ms debounce): wait for the actual POST response — the
|
||||
// Auto-save (150 ms debounce): wait for the CAS server action POST — the
|
||||
// badge text updates optimistically before the request even lands, so a
|
||||
// text-only assertion here would race the reload below against a save
|
||||
// that hasn't reached the database yet.
|
||||
await Promise.all([
|
||||
expectPostResponse(page, '/campanha/liderancas/support-status'),
|
||||
expectPostResponse(page, '/campanha/liderancas'),
|
||||
statusPopover.getByLabel('Status de apoio', { exact: true }).selectOption('engajado'),
|
||||
])
|
||||
await expect(page.getByRole('button', { name: 'Editar status de apoio' })).toContainText(
|
||||
|
|
|
|||
|
|
@ -89,7 +89,7 @@ test.describe('Municípios — jornadas por papel', () => {
|
|||
// the freshness column the ordering is paired with. `exact` keeps this off
|
||||
// the table caption, which embeds the same summary plus column glossary.
|
||||
await expect(
|
||||
page.getByText('Ordenado por Cobertura (maior déficit primeiro)', { exact: true }),
|
||||
page.getByText('Ordenado por Cobertura (maior déficit primeiro)', { exact: true }).first(),
|
||||
).toBeVisible()
|
||||
await expect(
|
||||
page.getByRole('columnheader', { name: /Ordenar por Frescor do sinal/ }),
|
||||
|
|
@ -118,7 +118,7 @@ test.describe('Municípios — jornadas por papel', () => {
|
|||
// (visually a hover-only preview otherwise), so assert against that
|
||||
// unique, unambiguous string rather than a bare "5.000" substring —
|
||||
// that also matches the (opacity-0 but DOM-visible) hover-preview span.
|
||||
await expect(page.getByText('Otimista: 5.000')).toBeVisible()
|
||||
await expect(page.getByText('Otimista: 5.000').first()).toBeVisible()
|
||||
await expect(page.getByText(`Assessoria: ${advisor.name}`)).toBeVisible()
|
||||
})
|
||||
|
||||
|
|
@ -163,7 +163,10 @@ test.describe('Municípios — jornadas por papel', () => {
|
|||
// no-op, so the probe retries until the chip sticks.
|
||||
await expect(async () => {
|
||||
await search.fill(searchNamePart)
|
||||
await option.click({ timeout: 1_000 })
|
||||
await Promise.all([
|
||||
expectPostResponse(page, '/campanha/municipios'),
|
||||
option.click({ timeout: 1_000 }),
|
||||
])
|
||||
await expect(chip).toBeVisible({ timeout: 4_000 })
|
||||
}).toPass({ timeout: 20_000 })
|
||||
|
||||
|
|
@ -212,7 +215,7 @@ test.describe('Municípios — jornadas por papel', () => {
|
|||
await trendPopover.getByLabel('Justificativa').fill(note)
|
||||
await trendPopover.getByLabel('Tendência', { exact: true }).selectOption('favoravel')
|
||||
await Promise.all([
|
||||
expectPostResponse(page, '/campanha/municipios/political-trend'),
|
||||
expectPostResponse(page, '/campanha/municipios'),
|
||||
trendPopover.getByLabel('Justificativa').blur(),
|
||||
])
|
||||
|
||||
|
|
@ -334,8 +337,11 @@ test.describe('Municípios — jornadas por papel', () => {
|
|||
await page.goto(`${campaign.baseURL}/campanha/municipios/${administered.slug}?tab=leaderships`)
|
||||
await expect(page.getByRole('link', { name: contact.name })).toBeVisible()
|
||||
await page.getByLabel('Quantos votos a liderança traz neste município?').fill('250')
|
||||
await page.getByRole('button', { name: 'Declarar' }).click()
|
||||
await expect(page.getByText('Declaração de votos registrada.')).toBeVisible()
|
||||
await Promise.all([
|
||||
expectPostResponse(page, `/campanha/municipios/${administered.slug}`),
|
||||
page.getByRole('button', { name: 'Declarar' }).click(),
|
||||
])
|
||||
await expect(page.getByRole('button', { name: 'Atualizar' })).toBeVisible()
|
||||
|
||||
// Advisor records an internal estimate on the overview pledges panel.
|
||||
await page.goto(`${campaign.baseURL}/campanha/municipios/${administered.slug}`)
|
||||
|
|
|
|||
|
|
@ -1,16 +1,19 @@
|
|||
import { expect, test } from './fixtures/campaignE2EFixtures.js'
|
||||
import {
|
||||
expect,
|
||||
reloadWhileOffline,
|
||||
test,
|
||||
waitForCampaignServiceWorker,
|
||||
} 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.')
|
||||
/** Offline specs intentionally hit blocked network resources — allowlist for the guard. */
|
||||
test.use({
|
||||
expectedRequestFailurePaths: ['/campanha/api/ops-sync', '/favicon.ico'],
|
||||
expectedRequestFailurePathPrefixes: ['/campanha'],
|
||||
allowOfflineRscPrefetchErrors: true,
|
||||
})
|
||||
|
||||
/** 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,
|
||||
|
|
@ -46,13 +49,20 @@ test.describe('OH6 estimate outbox (OPS_HYBRID)', () => {
|
|||
await campaign.login(page, advisor.email!, advisor.password)
|
||||
await page.goto(`${campaign.baseURL}/campanha/municipios/${municipality.slug}`)
|
||||
|
||||
await page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/campanha/api/ops-sync') && response.request().method() === 'GET',
|
||||
{ timeout: 30_000 },
|
||||
)
|
||||
await waitForCampaignServiceWorker(page)
|
||||
|
||||
await page.context().setOffline(true)
|
||||
await page.getByLabel('Média', { exact: true }).fill('55')
|
||||
await page.getByLabel('Justificativa').fill('Editado na estrada.')
|
||||
await page.getByRole('button', { name: 'Salvar estimativa' }).click()
|
||||
await expect(page.getByText('Pendente', { exact: true })).toBeVisible()
|
||||
|
||||
await page.reload()
|
||||
await reloadWhileOffline(page)
|
||||
await expect(page.getByText('Pendente', { exact: true })).toBeVisible()
|
||||
|
||||
await page.context().setOffline(false)
|
||||
|
|
|
|||
|
|
@ -1,17 +1,19 @@
|
|||
import { expect, test } from './fixtures/campaignE2EFixtures.js'
|
||||
import {
|
||||
expect,
|
||||
reloadWhileOffline,
|
||||
test,
|
||||
waitForCampaignServiceWorker,
|
||||
} 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.')
|
||||
/** Offline specs intentionally hit blocked network resources — allowlist for the guard. */
|
||||
test.use({
|
||||
expectedRequestFailurePaths: ['/campanha/api/ops-sync', '/favicon.ico'],
|
||||
expectedRequestFailurePathPrefixes: ['/campanha'],
|
||||
allowOfflineRscPrefetchErrors: true,
|
||||
})
|
||||
|
||||
/** 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,
|
||||
|
|
@ -54,6 +56,7 @@ test.describe('OH9/OH11 campaign ops offline (OPS_HYBRID)', () => {
|
|||
response.url().includes('/campanha/api/ops-sync') && response.request().method() === 'GET',
|
||||
{ timeout: 30_000 },
|
||||
)
|
||||
await waitForCampaignServiceWorker(page)
|
||||
|
||||
await page.context().setOffline(true)
|
||||
|
||||
|
|
@ -108,6 +111,7 @@ test.describe('OH9/OH11 campaign ops offline (OPS_HYBRID)', () => {
|
|||
response.url().includes('/campanha/api/ops-sync') && response.request().method() === 'GET',
|
||||
{ timeout: 30_000 },
|
||||
)
|
||||
await waitForCampaignServiceWorker(page)
|
||||
|
||||
await page.context().setOffline(true)
|
||||
|
||||
|
|
@ -117,7 +121,7 @@ test.describe('OH9/OH11 campaign ops offline (OPS_HYBRID)', () => {
|
|||
await page.getByRole('button', { name: 'Salvar estimativa' }).click()
|
||||
await expect(page.getByText('Pendente', { exact: true })).toBeVisible()
|
||||
|
||||
await page.reload()
|
||||
await reloadWhileOffline(page)
|
||||
await expect(page.getByText('Pendente', { exact: true })).toBeVisible()
|
||||
|
||||
await page.context().setOffline(false)
|
||||
|
|
@ -125,9 +129,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()
|
||||
|
|
@ -151,13 +153,22 @@ test.describe('OH12 municipality list Local (OPS_HYBRID)', () => {
|
|||
response.url().includes('/campanha/api/ops-sync') && response.request().method() === 'GET',
|
||||
{ timeout: 30_000 },
|
||||
)
|
||||
await waitForCampaignServiceWorker(page)
|
||||
|
||||
await page.context().setOffline(true)
|
||||
await page.goto(
|
||||
`${campaign.baseURL}/campanha/municipios?q=${encodeURIComponent(municipality.name)}`,
|
||||
)
|
||||
await expect(
|
||||
page.getByText('Edição na lista disponível quando estiveres online.'),
|
||||
).toBeVisible()
|
||||
|
||||
await expect(page.getByRole('heading', { name: 'Municípios' })).toBeVisible()
|
||||
const search = page.getByLabel('Buscar município')
|
||||
await search.fill(municipality.name)
|
||||
await expect(page.getByRole('link', { name: municipality.name })).toBeVisible({
|
||||
timeout: 15_000,
|
||||
})
|
||||
|
||||
await expect(
|
||||
page.getByRole('heading', { name: 'Municípios', exact: true }).first(),
|
||||
).toBeVisible()
|
||||
await expect(
|
||||
page.getByText('Edição na lista disponível quando estiveres online.'),
|
||||
).toBeVisible()
|
||||
|
|
|
|||
|
|
@ -40,11 +40,11 @@ test.describe('Territórios de Identidade', () => {
|
|||
|
||||
await campaign.login(page, coordinator.email!, coordinator.password)
|
||||
await page.goto('/campanha/territorios')
|
||||
await expect(page.getByText(/27 territórios encontrados/)).toBeVisible()
|
||||
await expect(page.getByText(/27 territórios encontrados/).first()).toBeVisible()
|
||||
|
||||
await page.getByRole('link', { name: 'Ir para a página 2' }).click()
|
||||
await expect(page).toHaveURL(/\/campanha\/territorios\?page=2/)
|
||||
await expect(page.getByText(/27 territórios encontrados/)).toBeVisible()
|
||||
await expect(page.getByText(/27 territórios encontrados/).first()).toBeVisible()
|
||||
})
|
||||
|
||||
test('parent territory rows expose hash anchor ids for deep links', async ({
|
||||
|
|
@ -61,8 +61,8 @@ test.describe('Territórios de Identidade', () => {
|
|||
await campaign.login(page, email, password)
|
||||
await page.goto('/campanha/territorios')
|
||||
|
||||
await expect(page.locator('#ti-irece')).toBeVisible()
|
||||
await expect(page.locator('#ti-velho-chico')).toBeVisible()
|
||||
await expect(page.locator('#ti-irece').first()).toBeVisible()
|
||||
await expect(page.locator('#ti-velho-chico').first()).toBeVisible()
|
||||
})
|
||||
|
||||
test('leader cannot open the territories page', async ({ campaign, page }) => {
|
||||
|
|
|
|||
|
|
@ -74,7 +74,7 @@ test('enrolls a passkey, signs in with it, then revokes it', async ({
|
|||
await expectCampaignBiometricsReady(page)
|
||||
await page.goto('/campanha/perfil')
|
||||
|
||||
await expect(page.getByText('Nenhum aparelho cadastrado ainda.')).toBeVisible()
|
||||
await expect(page.getByRole('main').getByText('Nenhum aparelho cadastrado ainda.')).toBeVisible()
|
||||
|
||||
const deviceLabel = page.getByLabel('Nome deste aparelho')
|
||||
await expect(deviceLabel).toBeVisible()
|
||||
|
|
@ -82,7 +82,7 @@ test('enrolls a passkey, signs in with it, then revokes it', async ({
|
|||
await page.getByRole('button', { name: 'Ativar neste aparelho' }).click()
|
||||
|
||||
await expect(page.getByText('Celular da assessora')).toBeVisible({ timeout: CEREMONY_TIMEOUT })
|
||||
await expect(page.getByText('Nenhum aparelho cadastrado ainda.')).toBeHidden()
|
||||
await expect(page.getByRole('main').getByText('Nenhum aparelho cadastrado ainda.')).toBeHidden()
|
||||
|
||||
// 2. Password-less sign-in issues the 14-day cookie — enrolling the device IS
|
||||
// the "remember me" opt-in, so there is no checkbox in this path.
|
||||
|
|
@ -103,7 +103,7 @@ test('enrolls a passkey, signs in with it, then revokes it', async ({
|
|||
// the profile and it has to actually stop the credential.
|
||||
await page.goto('/campanha/perfil')
|
||||
await page.getByRole('button', { name: 'Remover Celular da assessora' }).click()
|
||||
await expect(page.getByText('Nenhum aparelho cadastrado ainda.')).toBeVisible()
|
||||
await expect(page.getByRole('main').getByText('Nenhum aparelho cadastrado ainda.')).toBeVisible()
|
||||
|
||||
await context.clearCookies()
|
||||
await page.goto('/campanha/login')
|
||||
|
|
|
|||
|
|
@ -455,6 +455,27 @@ export const expectPostResponse = (page: Page, urlFragment: string) =>
|
|||
response.ok(),
|
||||
)
|
||||
|
||||
/**
|
||||
* Production e2e (`pnpm start`) registers the campaign SW; offline reload
|
||||
* specs need a controlling worker so navigation is served from Cache Storage.
|
||||
*/
|
||||
export const waitForCampaignServiceWorker = async (page: Page): Promise<void> => {
|
||||
await expect(async () => {
|
||||
const ready = await page.evaluate(async () => {
|
||||
if (!('serviceWorker' in navigator)) return false
|
||||
await navigator.serviceWorker.ready
|
||||
return navigator.serviceWorker.controller !== null
|
||||
})
|
||||
expect(ready).toBe(true)
|
||||
}).toPass({ timeout: 30_000 })
|
||||
}
|
||||
|
||||
/** Reload while the browser context is offline — requires SW (production e2e). */
|
||||
export const reloadWhileOffline = async (page: Page): Promise<void> => {
|
||||
await waitForCampaignServiceWorker(page)
|
||||
await page.reload({ waitUntil: 'domcontentloaded' })
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks a Radix Checkbox only once the page has hydrated. A Radix checkbox is
|
||||
* a button whose hidden input is synced by React, so a click that lands BEFORE
|
||||
|
|
|
|||
|
|
@ -27,6 +27,10 @@ type E2EFailureGuardFixtures = {
|
|||
* mid-test.
|
||||
*/
|
||||
expectedRequestFailurePaths: string[]
|
||||
/** Pathname prefix allowlist for intentional offline prefetch failures. */
|
||||
expectedRequestFailurePathPrefixes: string[]
|
||||
/** Next.js RSC prefetch console noise while the browser context is offline. */
|
||||
allowOfflineRscPrefetchErrors: boolean
|
||||
}
|
||||
|
||||
const loadFailurePrefix = 'Failed to load resource'
|
||||
|
|
@ -49,6 +53,8 @@ const isAllowedConsoleError = (
|
|||
message: ConsoleMessage,
|
||||
origin: string | null,
|
||||
expectedRequestFailurePaths: string[],
|
||||
expectedRequestFailurePathPrefixes: string[],
|
||||
allowOfflineRscPrefetchErrors: boolean,
|
||||
): boolean => {
|
||||
const { url } = message.location()
|
||||
if (!url || origin === null) return false
|
||||
|
|
@ -59,23 +65,50 @@ const isAllowedConsoleError = (
|
|||
// The app intentionally has no /favicon.ico asset yet.
|
||||
if (message.text() === missingFaviconConsoleError) return location.pathname === '/favicon.ico'
|
||||
|
||||
return (
|
||||
message.text().startsWith(loadFailurePrefix) &&
|
||||
expectedRequestFailurePaths.includes(location.pathname)
|
||||
)
|
||||
if (
|
||||
allowOfflineRscPrefetchErrors &&
|
||||
message.text().includes('Failed to fetch RSC payload') &&
|
||||
message.text().includes('/campanha')
|
||||
) {
|
||||
return true
|
||||
}
|
||||
|
||||
const pathAllowed =
|
||||
expectedRequestFailurePaths.includes(location.pathname) ||
|
||||
expectedRequestFailurePathPrefixes.some((prefix) => location.pathname.startsWith(prefix))
|
||||
|
||||
return message.text().startsWith(loadFailurePrefix) && pathAllowed
|
||||
}
|
||||
|
||||
export const test = base.extend<E2EFailureGuardFixtures>({
|
||||
expectedRequestFailurePaths: [[], { option: true }],
|
||||
expectedRequestFailurePathPrefixes: [[], { option: true }],
|
||||
allowOfflineRscPrefetchErrors: [false, { option: true }],
|
||||
e2eFailureGuard: [
|
||||
async ({ baseURL, context, expectedRequestFailurePaths, page }, use) => {
|
||||
async (
|
||||
{
|
||||
baseURL,
|
||||
context,
|
||||
expectedRequestFailurePaths,
|
||||
expectedRequestFailurePathPrefixes,
|
||||
allowOfflineRscPrefetchErrors,
|
||||
page,
|
||||
},
|
||||
use,
|
||||
) => {
|
||||
const failures: BrowserFailure[] = []
|
||||
const origin = baseURL ? new URL(baseURL).origin : null
|
||||
|
||||
const onConsole = (message: ConsoleMessage) => {
|
||||
if (
|
||||
message.type() !== 'error' ||
|
||||
isAllowedConsoleError(message, origin, expectedRequestFailurePaths)
|
||||
isAllowedConsoleError(
|
||||
message,
|
||||
origin,
|
||||
expectedRequestFailurePaths,
|
||||
expectedRequestFailurePathPrefixes,
|
||||
allowOfflineRscPrefetchErrors,
|
||||
)
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 = {
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
Loading…
Reference in a new issue