diff --git a/docs/CHANGELOG-AGENTS.md b/docs/CHANGELOG-AGENTS.md
index 0c150d48..f2a157ba 100644
--- a/docs/CHANGELOG-AGENTS.md
+++ b/docs/CHANGELOG-AGENTS.md
@@ -4,6 +4,8 @@ Conteúdo movido do `AGENTS.md` em 2026-07-30 (fatiamento do paradigma de agente
---
+**Recently resolved (2026-08-02):** **OH10** (Issue #171) — writes municipality staff CAS (`baseUpdatedAt`) + outbox irmão (`opsMunicipalityOutbox`) para municipalityUpdate, declareVotes, tendência, engagement e advisors; flag OFF mantém caminhos actuais. Plano: [`oh10-municipality-writes-cas.md`](docs/plans/oh10-municipality-writes-cas.md).
+
**Recently resolved (2026-08-02):** **OH9** (Issue #172) — detalhe de município dual-path: `MunicipalityDetailHeaderView` partilhado; `OfflineBoundary` (SSR=RSC; offline+`OPS_HYBRID`→Local); `MunicipalityDetailLocal` lê mirror (município + pledges×leaderships); regiões online-only com “Disponível quando estiveres online.”; e2e `campaignOpsOffline` (skip sem flag). Plano: [`oh9-municipio-detalhe-dualpath.md`](docs/plans/oh9-municipio-detalhe-dualpath.md).
**Recently resolved (2026-08-01):** **B114** (Issue #195) — wizard Voltar header = Android back: contrato `wizardBack` + `useWizardBackHistory` (pushState/popstate), previousHrefs canônicos, layer form liderança. Plano: [`wizard-back-navigation-system.md`](docs/plans/wizard-back-navigation-system.md).
diff --git a/docs/plans/oh10-municipality-writes-cas.md b/docs/plans/oh10-municipality-writes-cas.md
index 402dc545..ca07958b 100644
--- a/docs/plans/oh10-municipality-writes-cas.md
+++ b/docs/plans/oh10-municipality-writes-cas.md
@@ -1,7 +1,7 @@
# OH10 — Writes municipality staff CAS: update, declareVotes, tendência, engagement, advisors
-Status: rascunho
-Atualizado em: 2026-08-01
+Status: pronto para PR
+Atualizado em: 2026-08-02
Issue: #171
Priority: P1
Model: cursor-grok-4.5-medium
@@ -10,13 +10,25 @@ Appetite: ~2–3 dias eng
Depends: OH7, OH9
Responsável: —
+## Débitos pós-/simplify (não bloqueiam OH10)
+
+- Toast de conflito CAS em tendência/nível da lista (só advisors + declareVotes têm escolha Manter/Usar).
+- Unificar executores OH6+OH10 (já previsto em OH13).
+
+## Freshness audit (2026-08-02)
+
+- OH7 (#169) e OH9 (#172) `done`+`in-prod`. OH6 CAS em `estimateVotesCas` + `opsEstimateOutbox` intactos; mirror tem `updatedAt` em `OpsMunicipality` / `OpsVotePledge`.
+- Actions citadas batem: `declareVotesRecord`, `createMunicipalityUpdateRecord`, `setMunicipalityPoliticalTrendRecord`, `setMunicipalityEngagementLevelRecord`, `setMunicipalityAdvisorMembershipRecord` / `assignMunicipalityAdvisorsRecord`.
+- Controles B9 intactos (JSON routes + forms). Sem `baseUpdatedAt` ainda — a implementar.
+- Outbox: executor OH6 fica; OH10 adiciona executor irmão (`opsMunicipalityOutbox`) com as mesmas chaves de merge — evita refactor arriscado do singleton de estimativas; OH13 pode unificar.
+
## Premissas
1. Padrão provado: OH6/OH7 (CAS + outbox + mirror keys).
2. Cada write ganha CAS por `baseUpdatedAt` do doc alvo; sem base → comportamento actual.
3. Engagement level continua a escrever `allocationDecision` na mesma transação (invariante E14) — o outbox só re-executa a action inteira, nunca a parte.
-→ Corrija agora ou sigo com estas.
+→ Confirmadas; a implementar.
## Objetivos
diff --git a/src/app/(campaign)/campanha/(app)/municipios/[slug]/MunicipalityDetailTabs.tsx b/src/app/(campaign)/campanha/(app)/municipios/[slug]/MunicipalityDetailTabs.tsx
index bf3d7be7..e39cbf30 100644
--- a/src/app/(campaign)/campanha/(app)/municipios/[slug]/MunicipalityDetailTabs.tsx
+++ b/src/app/(campaign)/campanha/(app)/municipios/[slug]/MunicipalityDetailTabs.tsx
@@ -341,11 +341,13 @@ export const LeadershipsTab = async ({
export const UpdatesTab = async ({
municipalityID,
municipalitySlug,
+ municipalityUpdatedAt,
rawSearchParams,
payloadUser: { payload, user },
}: {
municipalityID: number
municipalitySlug: string
+ municipalityUpdatedAt?: string
rawSearchParams: MunicipalityDetailSearchParams
payloadUser: PayloadUser
}) => {
@@ -356,6 +358,7 @@ export const UpdatesTab = async ({
diff --git a/src/app/(campaign)/campanha/(app)/municipios/[slug]/page.tsx b/src/app/(campaign)/campanha/(app)/municipios/[slug]/page.tsx
index 91d1e2fb..dc633f65 100644
--- a/src/app/(campaign)/campanha/(app)/municipios/[slug]/page.tsx
+++ b/src/app/(campaign)/campanha/(app)/municipios/[slug]/page.tsx
@@ -118,6 +118,7 @@ export default async function MunicipalityDetailPage({
diff --git a/src/app/(campaign)/campanha/(app)/municipios/engagement-level/route.ts b/src/app/(campaign)/campanha/(app)/municipios/engagement-level/route.ts
index e8224a0d..584e06ce 100644
--- a/src/app/(campaign)/campanha/(app)/municipios/engagement-level/route.ts
+++ b/src/app/(campaign)/campanha/(app)/municipios/engagement-level/route.ts
@@ -3,7 +3,7 @@ import { NextResponse } from 'next/server'
import { setMunicipalityEngagementLevel } from '@/app/(campaign)/campanha/actions/municipality'
import { EngagementLevelBlockedError } from '@/lib/engagementLevel'
import {
- MUNICIPALITY_ENGAGEMENT_LEVEL_UNRESTRICTED_MESSAGE,
+ MUNICIPALITY_ENGAGEMENT_LEVEL_SAFE_MESSAGES,
municipalityEngagementLevelSchema,
} from '@/lib/schemas/municipality'
import { positiveRelationshipId } from '@/lib/schemas/primitives'
@@ -25,7 +25,7 @@ export const POST = campaignJsonMutationRoute(
bodySchema,
// Only the unrestricted-actor message: this action reloads the actor with
// its own guard, never through `getFreshStaffActor` (same as `advisors/`).
- safeMessages: [MUNICIPALITY_ENGAGEMENT_LEVEL_UNRESTRICTED_MESSAGE],
+ safeMessages: MUNICIPALITY_ENGAGEMENT_LEVEL_SAFE_MESSAGES,
genericMessage: 'Não foi possível registrar o nível. Verifique seu acesso e tente novamente.',
},
async ({ municipalityId, ...movement }) => {
diff --git a/src/app/(campaign)/campanha/(app)/municipios/municipalityStaffEditMessages.ts b/src/app/(campaign)/campanha/(app)/municipios/municipalityStaffEditMessages.ts
index 4ceb65c1..22eb4b28 100644
--- a/src/app/(campaign)/campanha/(app)/municipios/municipalityStaffEditMessages.ts
+++ b/src/app/(campaign)/campanha/(app)/municipios/municipalityStaffEditMessages.ts
@@ -1,4 +1,7 @@
+import { OPS_UPDATED_AT_CONFLICT_MESSAGE } from '@/lib/schemas/opsCas'
+
/** Shared form-error copy for municipality staff edits — kept out of `'use server'` files. */
export const municipalityStaffEditSafeMessages = [
'Somente a coordenação e a assessoria podem editar o município.',
+ OPS_UPDATED_AT_CONFLICT_MESSAGE,
] as const
diff --git a/src/app/(campaign)/campanha/actions/municipality.ts b/src/app/(campaign)/campanha/actions/municipality.ts
index 229d1ef8..9d420914 100644
--- a/src/app/(campaign)/campanha/actions/municipality.ts
+++ b/src/app/(campaign)/campanha/actions/municipality.ts
@@ -25,6 +25,7 @@ import {
type MunicipalityPoliticalTrendInput,
type MunicipalityStrategyUpdateInput,
} from '@/lib/schemas/municipality'
+import { assertOpsUpdatedAtCas } from '@/lib/schemas/opsCas'
import { normalizeVoteEstimateOnSave, toVoteEstimateScenarioViewModel } from '@/lib/voteEstimate'
import type { CampaignUser } from '@/payload-types'
import {
@@ -83,10 +84,25 @@ export const setMunicipalityPoliticalTrendRecord = async (
payload: Payload,
actor: CampaignUser,
input: MunicipalityPoliticalTrendInput,
+ options?: { cas?: boolean },
) => {
- const { municipality, status, note } = municipalityPoliticalTrendSchema.parse(input)
+ const { municipality, status, note, baseUpdatedAt } =
+ municipalityPoliticalTrendSchema.parse(input)
+ const enforceCas = options?.cas === true
const currentActor = await getFreshStaffActor(payload, actor)
+ if (enforceCas && baseUpdatedAt !== undefined) {
+ const current = await payload.findByID({
+ collection: 'municipality',
+ id: municipality,
+ depth: 0,
+ select: { updatedAt: true },
+ user: currentActor,
+ overrideAccess: false,
+ })
+ assertOpsUpdatedAtCas(true, baseUpdatedAt, current.updatedAt)
+ }
+
return payload.update({
collection: 'municipality',
id: municipality,
@@ -104,6 +120,17 @@ export const setMunicipalityPoliticalTrend = async (input: MunicipalityPolitical
return setMunicipalityPoliticalTrendRecord(payload, actor, input)
}
+export const setMunicipalityPoliticalTrendCas = async (input: MunicipalityPoliticalTrendInput) => {
+ const { payload, actor } = await getCampaignActionContext()
+ return setMunicipalityPoliticalTrendRecord(payload, actor, input, { cas: true })
+}
+
+export const setMunicipalityPoliticalTrendCasRecord = async (
+ payload: Payload,
+ actor: CampaignUser,
+ input: MunicipalityPoliticalTrendInput,
+) => setMunicipalityPoliticalTrendRecord(payload, actor, input, { cas: true })
+
/** Staff-only total expected votes for the municipality (distinct from pledge aggregates). */
export const setMunicipalityExpectedVotesRecord = async (
payload: Payload,
@@ -148,9 +175,11 @@ export const setMunicipalityEngagementLevelRecord = async (
payload: Payload,
actor: CampaignUser,
input: MunicipalityEngagementLevelInput,
+ options?: { cas?: boolean },
) => {
- const { municipality, level, note, reversalSignals, triangulatedShock, override } =
+ const { municipality, level, note, reversalSignals, triangulatedShock, override, baseUpdatedAt } =
municipalityEngagementLevelSchema.parse(input)
+ const enforceCas = options?.cas === true
return withPayloadTransaction(
payload,
@@ -170,12 +199,14 @@ export const setMunicipalityEngagementLevelRecord = async (
collection: 'municipality',
id: municipality,
depth: 0,
- select: { engagementLevel: true, levelChangedAt: true },
+ select: { engagementLevel: true, levelChangedAt: true, updatedAt: true },
user: currentActor,
overrideAccess: false,
req,
})
+ assertOpsUpdatedAtCas(enforceCas, baseUpdatedAt, current.updatedAt)
+
const from = current.engagementLevel ?? null
const violations = getEngagementLevelViolations({
from,
@@ -233,13 +264,29 @@ export const setMunicipalityEngagementLevel = async (input: MunicipalityEngageme
return setMunicipalityEngagementLevelRecord(payload, actor, input)
}
+export const setMunicipalityEngagementLevelCas = async (
+ input: MunicipalityEngagementLevelInput,
+) => {
+ const { payload, actor } = await getCampaignActionContext()
+ return setMunicipalityEngagementLevelRecord(payload, actor, input, { cas: true })
+}
+
+export const setMunicipalityEngagementLevelCasRecord = async (
+ payload: Payload,
+ actor: CampaignUser,
+ input: MunicipalityEngagementLevelInput,
+) => setMunicipalityEngagementLevelRecord(payload, actor, input, { cas: true })
+
/** Advisor assignment is unrestricted staff (coordinator + candidate); the hook validates eligibility. */
export const assignMunicipalityAdvisorsRecord = async (
payload: Payload,
actor: CampaignUser,
input: MunicipalityAdvisorsAssignmentInput,
+ options?: { cas?: boolean },
) => {
- const { municipality, advisors } = municipalityAdvisorsAssignmentSchema.parse(input)
+ const { municipality, advisors, baseUpdatedAt } =
+ municipalityAdvisorsAssignmentSchema.parse(input)
+ const enforceCas = options?.cas === true
return withPayloadTransaction(
payload,
@@ -253,6 +300,20 @@ export const assignMunicipalityAdvisorsRecord = async (
await acquireTextAdvisoryLocks(payload, req, [`municipality-advisors:${municipality}`])
+ if (enforceCas && baseUpdatedAt !== undefined) {
+ // Intentional admin bypass: unrestricted role verified above; advisors
+ // field access would otherwise hide `updatedAt` from some actors.
+ const current = await payload.findByID({
+ collection: 'municipality',
+ id: municipality,
+ depth: 0,
+ select: { updatedAt: true },
+ overrideAccess: true,
+ req,
+ })
+ assertOpsUpdatedAtCas(true, baseUpdatedAt, current.updatedAt)
+ }
+
// Intentional admin bypass: unrestricted role was freshly verified above;
// the advisors field is admin-only by field access.
return payload.update({
@@ -273,6 +334,17 @@ export const assignMunicipalityAdvisors = async (input: MunicipalityAdvisorsAssi
return assignMunicipalityAdvisorsRecord(payload, actor, input)
}
+export const assignMunicipalityAdvisorsCas = async (input: MunicipalityAdvisorsAssignmentInput) => {
+ const { payload, actor } = await getCampaignActionContext()
+ return assignMunicipalityAdvisorsRecord(payload, actor, input, { cas: true })
+}
+
+export const assignMunicipalityAdvisorsCasRecord = async (
+ payload: Payload,
+ actor: CampaignUser,
+ input: MunicipalityAdvisorsAssignmentInput,
+) => assignMunicipalityAdvisorsRecord(payload, actor, input, { cas: true })
+
/**
* Single-advisor delta from the list popover — writes one toggle instead of
* replacing the whole `advisors` array, so a concurrent edit from another
@@ -288,8 +360,11 @@ export const setMunicipalityAdvisorMembershipRecord = async (
payload: Payload,
actor: CampaignUser,
input: MunicipalityAdvisorMembershipInput,
+ options?: { cas?: boolean },
) => {
- const { municipality, advisor, assigned } = municipalityAdvisorMembershipSchema.parse(input)
+ const { municipality, advisor, assigned, baseUpdatedAt } =
+ municipalityAdvisorMembershipSchema.parse(input)
+ const enforceCas = options?.cas === true
return withPayloadTransaction(
payload,
@@ -307,11 +382,13 @@ export const setMunicipalityAdvisorMembershipRecord = async (
collection: 'municipality',
id: municipality,
depth: 0,
- select: { advisors: true },
+ select: { advisors: true, updatedAt: true },
overrideAccess: true,
req,
})
+ assertOpsUpdatedAtCas(enforceCas, baseUpdatedAt, current.updatedAt)
+
const currentAdvisorIDs = uniqueRelationshipIds(current.advisors)
const nextAdvisorIDs = nextAdvisorIdsAfterMembership(currentAdvisorIDs, advisor, assigned)
if (nextAdvisorIDs === null) return current
@@ -338,3 +415,9 @@ export const setMunicipalityAdvisorMembership = async (
const { payload, actor } = await getCampaignActionContext()
return setMunicipalityAdvisorMembershipRecord(payload, actor, input)
}
+
+export const setMunicipalityAdvisorMembershipCasRecord = async (
+ payload: Payload,
+ actor: CampaignUser,
+ input: MunicipalityAdvisorMembershipInput,
+) => setMunicipalityAdvisorMembershipRecord(payload, actor, input, { cas: true })
diff --git a/src/app/(campaign)/campanha/actions/municipalityUpdate.ts b/src/app/(campaign)/campanha/actions/municipalityUpdate.ts
index 190252e3..3d339e46 100644
--- a/src/app/(campaign)/campanha/actions/municipalityUpdate.ts
+++ b/src/app/(campaign)/campanha/actions/municipalityUpdate.ts
@@ -6,6 +6,7 @@ import {
municipalityUpdateCreateSchema,
type MunicipalityUpdateCreateInput,
} from '@/lib/schemas/municipalityUpdate'
+import { assertOpsUpdatedAtCas } from '@/lib/schemas/opsCas'
import type { CampaignUser } from '@/payload-types'
import { getCampaignActionContext, reloadCampaignActor } from '@/utilities/campaignActionContext'
import { hookFilledCreateData } from '@/utilities/hookFilledData'
@@ -15,17 +16,35 @@ export const createMunicipalityUpdateRecord = async (
payload: Payload,
actor: CampaignUser,
input: MunicipalityUpdateCreateInput,
+ options?: { cas?: boolean },
) => {
const data = municipalityUpdateCreateSchema.parse(input)
+ const enforceCas = options?.cas === true
return withPayloadTransaction(
payload,
async ({ req }) => {
const currentActor = await reloadCampaignActor(payload, actor, req)
+ // CAS on parent municipality `updatedAt` (feed order / consistency).
+ if (enforceCas && data.baseUpdatedAt !== undefined) {
+ const parent = await payload.findByID({
+ collection: 'municipality',
+ id: data.municipality,
+ depth: 0,
+ select: { updatedAt: true },
+ user: currentActor,
+ overrideAccess: false,
+ req,
+ })
+ assertOpsUpdatedAtCas(true, data.baseUpdatedAt, parent.updatedAt)
+ }
+
+ const { baseUpdatedAt: _baseUpdatedAt, ...createData } = data
+
return payload.create({
collection: 'municipalityUpdate',
- data: hookFilledCreateData<'municipalityUpdate'>(data),
+ data: hookFilledCreateData<'municipalityUpdate'>(createData),
depth: 0,
user: currentActor,
overrideAccess: false,
@@ -40,3 +59,15 @@ export const createMunicipalityUpdate = async (input: MunicipalityUpdateCreateIn
const { payload, actor } = await getCampaignActionContext()
return createMunicipalityUpdateRecord(payload, actor, input)
}
+
+/** OH10 — create feed update with optional CAS on parent municipality `updatedAt`. */
+export const createMunicipalityUpdateCas = async (input: MunicipalityUpdateCreateInput) => {
+ const { payload, actor } = await getCampaignActionContext()
+ return createMunicipalityUpdateRecord(payload, actor, input, { cas: true })
+}
+
+export const createMunicipalityUpdateCasRecord = async (
+ payload: Payload,
+ actor: CampaignUser,
+ input: MunicipalityUpdateCreateInput,
+) => createMunicipalityUpdateRecord(payload, actor, input, { cas: true })
diff --git a/src/app/(campaign)/campanha/actions/votePledge.ts b/src/app/(campaign)/campanha/actions/votePledge.ts
index 58650714..8d012c57 100644
--- a/src/app/(campaign)/campanha/actions/votePledge.ts
+++ b/src/app/(campaign)/campanha/actions/votePledge.ts
@@ -3,6 +3,7 @@
import type { Payload } from 'payload'
import { relationshipId, requireRelationshipId } from '@/lib/relationship'
+import { assertOpsUpdatedAtCas } from '@/lib/schemas/opsCas'
import {
declareVotesSchema,
estimateVotesSchema,
@@ -29,8 +30,10 @@ export const declareVotesRecord = async (
payload: Payload,
actor: CampaignUser,
input: DeclareVotesInput,
+ options?: { cas?: boolean },
) => {
const data = declareVotesSchema.parse(input)
+ const enforceCas = options?.cas === true
return withPayloadTransaction(
payload,
@@ -89,6 +92,15 @@ export const declareVotesRecord = async (
})
const current = existing.docs[0]
+ if (enforceCas && data.baseUpdatedAt !== undefined) {
+ if (current) {
+ assertOpsUpdatedAtCas(true, data.baseUpdatedAt, current.updatedAt)
+ } else if (data.baseUpdatedAt !== null) {
+ // Client expected an existing pledge; it is gone — refuse.
+ assertOpsUpdatedAtCas(true, data.baseUpdatedAt, '')
+ }
+ }
+
if (current) {
return payload.update({
collection: 'votePledge',
@@ -123,6 +135,18 @@ export const declareVotes = async (input: DeclareVotesInput) => {
return declareVotesRecord(payload, actor, input)
}
+/** OH10 — declare with optional CAS on pledge `updatedAt`. */
+export const declareVotesCas = async (input: DeclareVotesInput) => {
+ const { payload, actor } = await getCampaignActionContext()
+ return declareVotesRecord(payload, actor, input, { cas: true })
+}
+
+export const declareVotesCasRecord = async (
+ payload: Payload,
+ actor: CampaignUser,
+ input: DeclareVotesInput,
+) => declareVotesRecord(payload, actor, input, { cas: true })
+
/** Staff estimate of the real value — never visible to the leadership. */
export const estimateVotesRecord = async (
payload: Payload,
diff --git a/src/components/campaign/municipality/MunicipalityLeadershipsPanel.tsx b/src/components/campaign/municipality/MunicipalityLeadershipsPanel.tsx
index 1868eaa5..bb8eb851 100644
--- a/src/components/campaign/municipality/MunicipalityLeadershipsPanel.tsx
+++ b/src/components/campaign/municipality/MunicipalityLeadershipsPanel.tsx
@@ -81,7 +81,9 @@ export const MunicipalityLeadershipsPanel = ({
diff --git a/src/components/campaign/municipality/MunicipalityList.tsx b/src/components/campaign/municipality/MunicipalityList.tsx
index e53f2bc5..0266e9f9 100644
--- a/src/components/campaign/municipality/MunicipalityList.tsx
+++ b/src/components/campaign/municipality/MunicipalityList.tsx
@@ -249,6 +249,7 @@ const municipalityListColumns = ({
level={municipality.engagementLevel}
levelNote={municipality.levelNote}
levelChangedAt={municipality.levelChangedAt}
+ updatedAt={municipality.updatedAt}
variant="popover"
/>
) : (
@@ -288,6 +289,7 @@ const municipalityListColumns = ({
isPriority={municipality.priority === 'alta'}
advisorNamesById={advisorNamesById}
options={advisorOptions}
+ updatedAt={municipality.updatedAt}
variant="popover"
/>
) : (
@@ -321,6 +323,7 @@ const municipalityListColumns = ({
municipalityName={municipality.name}
status={municipality.politicalTrendStatus}
trendNote={municipality.politicalTrendNote}
+ updatedAt={municipality.updatedAt}
variant="popover"
/>
),
diff --git a/src/components/campaign/municipality/MunicipalityListAdvisorsControl.tsx b/src/components/campaign/municipality/MunicipalityListAdvisorsControl.tsx
index b6c254d7..e516540b 100644
--- a/src/components/campaign/municipality/MunicipalityListAdvisorsControl.tsx
+++ b/src/components/campaign/municipality/MunicipalityListAdvisorsControl.tsx
@@ -1,7 +1,9 @@
'use client'
import { XIcon } from 'lucide-react'
-import { useEffect, useMemo, useRef, useState } from 'react'
+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 {
@@ -9,6 +11,14 @@ import {
formatAdvisorNamesTooltip,
MunicipalityAdvisorAvatarStack,
} from '@/components/campaign/municipality/MunicipalityAdvisorAvatarStack'
+import { municipalitiesCollection } from '@/components/campaign/opsSync/opsMirrorClient'
+import {
+ discardOpsAdvisorsOutboxRow,
+ enqueueAdvisorsAssignment,
+ readOpsAdvisorsOutboxRow,
+ subscribeOpsAdvisorsOutboxRow,
+} from '@/components/campaign/opsSync/opsMunicipalityOutbox'
+import type { OpsMunicipalityWriteSyncStatus } from '@/components/campaign/opsSync/opsMunicipalityOutboxModel'
import {
CampaignCellEditOverlay,
type CampaignCellEditOverlayVariant,
@@ -19,7 +29,9 @@ import { Badge } from '@/components/ui/Badge'
import { Command, CommandInput, CommandItem, CommandList } from '@/components/ui/Command'
import { Spinner } from '@/components/ui/Spinner'
import { postCampaignJson } from '@/lib/campaignJsonRequest'
+import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
import { sameIdSet } from '@/lib/sameIdSet'
+import { OPS_UPDATED_AT_CONFLICT_MESSAGE } from '@/lib/schemas/opsCas'
import { cn } from '@/lib/utils'
import { matchesAtWordStart } from '@/lib/wordStartFilter'
import type {
@@ -29,6 +41,7 @@ import type {
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:'
type MunicipalityListAdvisorsControlProps = {
municipalityID: number
@@ -38,6 +51,8 @@ type MunicipalityListAdvisorsControlProps = {
isPriority: boolean
advisorNamesById: ReadonlyMap
options: EligibleAdvisorOption[]
+ /** OH10 — CAS base when OPS_HYBRID outbox path is on. */
+ updatedAt?: string
variant: CampaignCellEditOverlayVariant
}
@@ -48,8 +63,11 @@ export const MunicipalityListAdvisorsControl = ({
isPriority,
advisorNamesById,
options,
+ updatedAt,
variant,
}: MunicipalityListAdvisorsControlProps) => {
+ const router = useRouter()
+ const opsHybrid = resolveOpsHybridEnabled()
const [open, setOpen] = useState(false)
const [selectedIDs, setSelectedIDs] = useState(currentAdvisorIDs)
const [query, setQuery] = useState('')
@@ -69,6 +87,14 @@ export const MunicipalityListAdvisorsControl = ({
// clobber the optimistic state back to it.
const requestSeqRef = useRef(0)
const latestConfirmedRef = useRef<{ seq: number; advisors: number[] } | null>(null)
+ const previousOutboxStatusRef = useRef(undefined)
+
+ const outboxRow = useSyncExternalStore(
+ (onStoreChange) =>
+ opsHybrid ? subscribeOpsAdvisorsOutboxRow(municipalityID, onStoreChange) : () => undefined,
+ () => (opsHybrid ? readOpsAdvisorsOutboxRow(municipalityID) : undefined),
+ () => undefined,
+ )
const handleOpenChange = (nextOpen: boolean) => {
noteOpenChange(nextOpen)
@@ -84,6 +110,51 @@ export const MunicipalityListAdvisorsControl = ({
setSelectedIDs(currentAdvisorIDs)
}, [currentAdvisorIDs])
+ useEffect(() => {
+ const previous = previousOutboxStatusRef.current
+ previousOutboxStatusRef.current = outboxRow?.status
+ if (previous === 'pending' && outboxRow === undefined) {
+ router.refresh()
+ }
+ }, [outboxRow, router])
+
+ useEffect(() => {
+ if (!opsHybrid || outboxRow?.status !== 'conflict') return
+ const toastId = `${CONFLICT_TOAST_ID_PREFIX}${municipalityID}`
+ toast.message(OPS_UPDATED_AT_CONFLICT_MESSAGE, {
+ id: toastId,
+ duration: Infinity,
+ action: {
+ label: 'Manter o meu',
+ onClick: () => {
+ void enqueueAdvisorsAssignment({
+ municipalityId: municipalityID,
+ advisors: outboxRow.advisors,
+ baseUpdatedAt: outboxRow.serverUpdatedAt ?? null,
+ }).then(
+ () => setErrorMessage(null),
+ (error: unknown) => {
+ reportFailure(
+ error instanceof Error ? error.message : 'Não foi possível reenviar os assessores.',
+ )
+ },
+ )
+ },
+ },
+ cancel: {
+ label: 'Usar o novo',
+ onClick: () => {
+ discardOpsAdvisorsOutboxRow(municipalityID)
+ setErrorMessage(null)
+ router.refresh()
+ },
+ },
+ })
+ return () => {
+ toast.dismiss(toastId)
+ }
+ }, [opsHybrid, 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
// id the popover just optimistically added — no round trip needed to label
@@ -122,11 +193,13 @@ export const MunicipalityListAdvisorsControl = ({
const toggle = (advisorId: number, assigned: boolean) => {
setErrorMessage(null)
+ let nextIds: number[] = []
setSelectedIDs((current) => {
const next = new Set(current)
if (assigned) next.add(advisorId)
else next.delete(advisorId)
- return [...next]
+ nextIds = [...next]
+ return nextIds
})
setQuery('')
@@ -157,6 +230,20 @@ 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(
ADVISORS_ENDPOINT,
{ municipalityId: municipalityID, advisorId, assigned },
@@ -181,7 +268,12 @@ export const MunicipalityListAdvisorsControl = ({
})()
}
- const statusMessage = errorMessage ? errorMessage : isPending ? 'Salvando assessores.' : ''
+ const outboxPending = outboxRow?.status === 'pending' || outboxRow?.status === 'conflict'
+ const statusMessage = errorMessage
+ ? errorMessage
+ : isPending || outboxPending
+ ? 'Salvando assessores.'
+ : ''
// The body pads its own sections (`px-4`, aligned with the Drawer header) so
// the `Command` can stay full-bleed in both containers — hence `px-0` on the
// sheet body and `p-0` on the popover content.
@@ -197,7 +289,7 @@ export const MunicipalityListAdvisorsControl = ({
// The avatar stack reads as initials at best, and an `aria-label` replaces
// even those — so who is assigned goes in the label, by extenso.
triggerLabel={`Editar assessores em ${municipalityName} — ${assignedLabel}`}
- triggerBusy={isPending}
+ triggerBusy={isPending || outboxPending}
statusMessage={statusMessage}
tooltipContent={tooltipContent}
contentClassName="w-80 p-0"
@@ -212,7 +304,7 @@ export const MunicipalityListAdvisorsControl = ({
O assessor vê e gerencia somente os municípios que administra.
- {isPending ? (
+ {isPending || outboxPending ? (
{
const [open, setOpen] = useState(false)
@@ -164,6 +170,26 @@ 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.
diff --git a/src/components/campaign/municipality/MunicipalityListMobileCards.tsx b/src/components/campaign/municipality/MunicipalityListMobileCards.tsx
index 36206150..46815b71 100644
--- a/src/components/campaign/municipality/MunicipalityListMobileCards.tsx
+++ b/src/components/campaign/municipality/MunicipalityListMobileCards.tsx
@@ -137,6 +137,7 @@ export const MunicipalityListMobileCards = ({
level={municipality.engagementLevel}
levelNote={municipality.levelNote}
levelChangedAt={municipality.levelChangedAt}
+ updatedAt={municipality.updatedAt}
variant="sheet"
/>
) : (
@@ -156,6 +157,7 @@ export const MunicipalityListMobileCards = ({
municipalityName={municipality.name}
status={municipality.politicalTrendStatus}
trendNote={municipality.politicalTrendNote}
+ updatedAt={municipality.updatedAt}
variant="sheet"
/>
@@ -186,6 +188,7 @@ export const MunicipalityListMobileCards = ({
isPriority={isPriority}
advisorNamesById={advisorNamesById}
options={advisorOptions}
+ updatedAt={municipality.updatedAt}
variant="sheet"
/>
) : names.length ? (
diff --git a/src/components/campaign/municipality/MunicipalityListTrendControl.tsx b/src/components/campaign/municipality/MunicipalityListTrendControl.tsx
index 667eea68..1a58c9fd 100644
--- a/src/components/campaign/municipality/MunicipalityListTrendControl.tsx
+++ b/src/components/campaign/municipality/MunicipalityListTrendControl.tsx
@@ -6,6 +6,8 @@ import type {
MunicipalityListPoliticalTrendResponse,
MunicipalityListSavedPoliticalTrend,
} from '@/app/(campaign)/campanha/(app)/municipios/political-trend/types'
+import { municipalitiesCollection } from '@/components/campaign/opsSync/opsMirrorClient'
+import { enqueuePoliticalTrend } from '@/components/campaign/opsSync/opsMunicipalityOutbox'
import {
CampaignCellEditOverlay,
type CampaignCellEditOverlayVariant,
@@ -17,6 +19,7 @@ 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,
@@ -44,6 +47,8 @@ type MunicipalityListTrendControlProps = {
municipalityName: string
status: MunicipalityListSavedPoliticalTrend['status']
trendNote: string | null
+ /** OH10 — CAS base when OPS_HYBRID outbox path is on. */
+ updatedAt?: string
variant: CampaignCellEditOverlayVariant
}
@@ -52,8 +57,10 @@ export const MunicipalityListTrendControl = ({
municipalityName,
status,
trendNote,
+ updatedAt,
variant,
}: MunicipalityListTrendControlProps) => {
+ const opsHybrid = resolveOpsHybridEnabled()
const { open, onOpenChange, value, change, flush, isPending, errorMessage, statusMessage } =
useCampaignCellAutosave<
MunicipalityListSavedPoliticalTrend,
@@ -73,6 +80,25 @@ 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,
})
// The only state the hook cannot hold: the textarea's raw text, which the
diff --git a/src/components/campaign/municipality/MunicipalityUpdateForm.tsx b/src/components/campaign/municipality/MunicipalityUpdateForm.tsx
index 19f0639f..51757532 100644
--- a/src/components/campaign/municipality/MunicipalityUpdateForm.tsx
+++ b/src/components/campaign/municipality/MunicipalityUpdateForm.tsx
@@ -1,20 +1,25 @@
'use client'
-import { useActionState, useState } from 'react'
+import { useActionState, 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 { 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,
municipalitySignalTypes,
municipalityUpdateKindLabels,
municipalityUpdateKinds,
+ parseMunicipalitySignalType,
type MunicipalityUpdateKind,
} from '@/lib/schemas/municipalityUpdate'
import type { CampaignFormActionState } from '@/utilities/campaignFormActionError'
@@ -22,6 +27,9 @@ import { fieldError } from '@/utilities/campaignFormFields'
type MunicipalityUpdateFormProps = {
municipalityID: number
+ /** OH10 — parent municipality `updatedAt` for CAS when OPS_HYBRID is on. */
+ municipalityUpdatedAt?: string
+ opsHybridEnabled?: boolean
formAction: (
state: CampaignFormActionState,
formData: FormData,
@@ -30,14 +38,79 @@ type MunicipalityUpdateFormProps = {
export const MunicipalityUpdateForm = ({
municipalityID,
+ municipalityUpdatedAt,
+ opsHybridEnabled = resolveOpsHybridEnabled(),
formAction,
}: MunicipalityUpdateFormProps) => {
const [state, submitAction, isPending] = useActionState(formAction, {})
const [kind, setKind] = useState('semanal')
+ const [hybridPending, setHybridPending] = useState(false)
+ const [hybridMessage, setHybridMessage] = useState(null)
+
+ const onHybridSubmit = (event: FormEvent) => {
+ event.preventDefault()
+ const form = event.currentTarget
+ const data = new FormData(form)
+ const rawKind = data.get('kind')
+ const nextKind =
+ typeof rawKind === 'string' &&
+ municipalityUpdateKinds.includes(rawKind as MunicipalityUpdateKind)
+ ? (rawKind as MunicipalityUpdateKind)
+ : 'semanal'
+ const readText = (name: string) => {
+ const raw = data.get(name)
+ return typeof raw === 'string' && raw.trim() !== '' ? raw.trim() : undefined
+ }
+ const readCount = (name: string) => {
+ const raw = data.get(name)
+ if (typeof raw !== 'string' || raw.trim() === '') return undefined
+ const value = Number(raw)
+ return Number.isFinite(value) ? Math.trunc(value) : undefined
+ }
+
+ setHybridPending(true)
+ setHybridMessage(null)
+ const mirrorUpdatedAt = municipalitiesCollection.get(municipalityID)?.updatedAt
+ void enqueueMunicipalityUpdate({
+ clientId: crypto.randomUUID(),
+ municipalityId: municipalityID,
+ kind: nextKind,
+ worked: readText('worked'),
+ failed: readText('failed'),
+ needs: readText('needs'),
+ body: readText('body'),
+ activeVolunteers: readCount('activeVolunteers'),
+ newSupports: readCount('newSupports'),
+ signalType: parseMunicipalitySignalType(readText('signalType')),
+ baseUpdatedAt: mirrorUpdatedAt ?? municipalityUpdatedAt,
+ }).then(
+ () => {
+ setHybridPending(false)
+ setHybridMessage('Atualização enfileirada. Será enviada ao reconectar.')
+ form.reset()
+ setKind('semanal')
+ },
+ (error: unknown) => {
+ setHybridPending(false)
+ setHybridMessage(
+ error instanceof Error ? error.message : 'Não foi possível enfileirar a atualização.',
+ )
+ },
+ )
+ }
+
+ const pending = opsHybridEnabled ? hybridPending : isPending
return (
-
diff --git a/src/components/campaign/opsSync/opsMirrorClient.ts b/src/components/campaign/opsSync/opsMirrorClient.ts
index 75f7b102..a80fa51d 100644
--- a/src/components/campaign/opsSync/opsMirrorClient.ts
+++ b/src/components/campaign/opsSync/opsMirrorClient.ts
@@ -8,6 +8,7 @@ import {
type OpsMirrorPersistenceMode,
type OpsMirrorStore,
} from '@/components/campaign/opsSync/opsMirrorPersistence'
+import { collectOpsMunicipalityOutboxKeys } from '@/components/campaign/opsSync/opsMunicipalityOutbox'
import { votePledgesCollection } from '@/components/campaign/opsSync/opsVotePledgeMirror'
import {
createEmptyOpsSnapshot,
@@ -123,7 +124,9 @@ export const resetOpsMirrorClientForTests = async (): Promise => {
const resolveOutboxKeys = (explicit?: ReadonlySet): ReadonlySet => {
if (explicit) return explicit
- return collectOpsEstimateOutboxKeys()
+ const keys = collectOpsEstimateOutboxKeys()
+ for (const key of collectOpsMunicipalityOutboxKeys()) keys.add(key)
+ return keys
}
const persistMirrorSnapshot = async (
diff --git a/src/components/campaign/opsSync/opsMunicipalityOutbox.ts b/src/components/campaign/opsSync/opsMunicipalityOutbox.ts
new file mode 100644
index 00000000..f66280a0
--- /dev/null
+++ b/src/components/campaign/opsSync/opsMunicipalityOutbox.ts
@@ -0,0 +1,656 @@
+'use client'
+
+import { createCollection, localOnlyCollectionOptions } from '@tanstack/db'
+import {
+ IndexedDBAdapter,
+ NonRetriableError,
+ startOfflineExecutor,
+ type OfflineExecutor,
+} from '@tanstack/offline-transactions'
+
+import {
+ assignMunicipalityAdvisorsCas,
+ setMunicipalityEngagementLevelCas,
+ setMunicipalityPoliticalTrendCas,
+} from '@/app/(campaign)/campanha/actions/municipality'
+import { createMunicipalityUpdateCas } from '@/app/(campaign)/campanha/actions/municipalityUpdate'
+import { declareVotesCas } from '@/app/(campaign)/campanha/actions/votePledge'
+import {
+ collapseAdvisorsOutbox,
+ collapseDeclareVotesOutbox,
+ collapseEngagementLevelOutbox,
+ collapseMunicipalityUpdateOutbox,
+ collapsePoliticalTrendOutbox,
+ declareVotesOutboxKey,
+ type OpsAdvisorsOutboxRow,
+ type OpsDeclareVotesOutboxRow,
+ type OpsEngagementLevelOutboxRow,
+ type OpsMunicipalityUpdateOutboxRow,
+ type OpsPoliticalTrendOutboxRow,
+} from '@/components/campaign/opsSync/opsMunicipalityOutboxModel'
+import {
+ applyOpsVotePledgeEstimateWrite,
+ votePledgesCollection,
+} from '@/components/campaign/opsSync/opsVotePledgeMirror'
+import { opsOutboxKey, type OpsOutboxKey } from '@/lib/campaignOps/opsContract'
+import type { EngagementLevel } from '@/lib/engagementLevel'
+import type { PoliticalTrendStatusValue } from '@/lib/schemas/municipality'
+import type {
+ MunicipalitySignalType,
+ MunicipalityUpdateKind,
+} from '@/lib/schemas/municipalityUpdate'
+import {
+ isOpsUpdatedAtConflictMessage,
+ parseOpsUpdatedAtConflictServerUpdatedAt,
+} from '@/lib/schemas/opsCas'
+
+const DECLARE_MUTATION_FN = 'declareVotes'
+const MUNICIPALITY_UPDATE_MUTATION_FN = 'createMunicipalityUpdate'
+const TREND_MUTATION_FN = 'setPoliticalTrend'
+const ENGAGEMENT_MUTATION_FN = 'setEngagementLevel'
+const ADVISORS_MUTATION_FN = 'assignAdvisors'
+
+const declareVotesOutboxCollection = createCollection(
+ localOnlyCollectionOptions({
+ id: 'ops-declare-votes-outbox',
+ getKey: (row) => row.id,
+ }),
+)
+
+const municipalityUpdateOutboxCollection = createCollection(
+ localOnlyCollectionOptions({
+ id: 'ops-municipality-update-outbox',
+ getKey: (row) => row.id,
+ }),
+)
+
+const politicalTrendOutboxCollection = createCollection(
+ localOnlyCollectionOptions({
+ id: 'ops-political-trend-outbox',
+ getKey: (row) => row.municipalityId,
+ }),
+)
+
+const engagementLevelOutboxCollection = createCollection(
+ localOnlyCollectionOptions({
+ id: 'ops-engagement-level-outbox',
+ getKey: (row) => row.municipalityId,
+ }),
+)
+
+const advisorsOutboxCollection = createCollection(
+ localOnlyCollectionOptions({
+ id: 'ops-advisors-outbox',
+ getKey: (row) => row.municipalityId,
+ }),
+)
+
+let executorSingleton: OfflineExecutor | null = null
+let initPromise: Promise | null = null
+
+const collapseAllMunicipalityOutbox = (
+ transactions: Parameters[0],
+) => {
+ const byFn = new Map()
+ for (const transaction of transactions) {
+ const fn = transaction.mutationFnName ?? ''
+ const list = byFn.get(fn) ?? []
+ list.push(transaction)
+ byFn.set(fn, list)
+ }
+
+ const collapsed = [
+ ...(byFn.get(DECLARE_MUTATION_FN)
+ ? collapseDeclareVotesOutbox(byFn.get(DECLARE_MUTATION_FN)!)
+ : []),
+ ...(byFn.get(MUNICIPALITY_UPDATE_MUTATION_FN)
+ ? collapseMunicipalityUpdateOutbox(byFn.get(MUNICIPALITY_UPDATE_MUTATION_FN)!)
+ : []),
+ ...(byFn.get(TREND_MUTATION_FN)
+ ? collapsePoliticalTrendOutbox(byFn.get(TREND_MUTATION_FN)!)
+ : []),
+ ...(byFn.get(ENGAGEMENT_MUTATION_FN)
+ ? collapseEngagementLevelOutbox(byFn.get(ENGAGEMENT_MUTATION_FN)!)
+ : []),
+ ...(byFn.get(ADVISORS_MUTATION_FN)
+ ? collapseAdvisorsOutbox(byFn.get(ADVISORS_MUTATION_FN)!)
+ : []),
+ ]
+
+ for (const [fn, list] of byFn) {
+ if (
+ fn !== DECLARE_MUTATION_FN &&
+ fn !== MUNICIPALITY_UPDATE_MUTATION_FN &&
+ fn !== TREND_MUTATION_FN &&
+ fn !== ENGAGEMENT_MUTATION_FN &&
+ fn !== ADVISORS_MUTATION_FN
+ ) {
+ collapsed.push(...list)
+ }
+ }
+
+ return collapsed.sort((left, right) => left.createdAt.getTime() - right.createdAt.getTime())
+}
+
+const handleUpdatedAtConflict = (
+ message: string,
+ onConflict: (serverUpdatedAt: string | null) => void,
+): never => {
+ onConflict(parseOpsUpdatedAtConflictServerUpdatedAt(message))
+ throw new NonRetriableError(message)
+}
+
+const createMunicipalityOfflineExecutor = (): OfflineExecutor =>
+ startOfflineExecutor({
+ collections: {
+ declareVotesOutbox: declareVotesOutboxCollection,
+ municipalityUpdateOutbox: municipalityUpdateOutboxCollection,
+ politicalTrendOutbox: politicalTrendOutboxCollection,
+ engagementLevelOutbox: engagementLevelOutboxCollection,
+ advisorsOutbox: advisorsOutboxCollection,
+ },
+ 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
+ try {
+ const updated = await declareVotesCas({
+ municipality: row.municipalityId,
+ leadership: row.leadershipId,
+ declaredVotes: row.declaredVotes,
+ baseUpdatedAt: row.baseUpdatedAt,
+ })
+ applyOpsVotePledgeEstimateWrite(updated)
+ declareVotesOutboxCollection.utils.acceptMutations(transaction)
+ if (declareVotesOutboxCollection.has(row.id)) {
+ declareVotesOutboxCollection.delete(row.id)
+ }
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error)
+ if (isOpsUpdatedAtConflictMessage(message)) {
+ handleUpdatedAtConflict(message, (serverUpdatedAt) => {
+ if (declareVotesOutboxCollection.has(row.id)) {
+ declareVotesOutboxCollection.update(row.id, (draft) => {
+ draft.status = 'conflict'
+ draft.serverUpdatedAt = serverUpdatedAt
+ draft.errorMessage = message
+ })
+ }
+ })
+ }
+ if (declareVotesOutboxCollection.has(row.id)) {
+ declareVotesOutboxCollection.update(row.id, (draft) => {
+ draft.status = 'error'
+ draft.errorMessage = message
+ })
+ }
+ throw error instanceof Error ? error : new Error(message)
+ }
+ },
+ [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
+ try {
+ await createMunicipalityUpdateCas({
+ municipality: row.municipalityId,
+ kind: row.kind,
+ worked: row.worked,
+ failed: row.failed,
+ needs: row.needs,
+ body: row.body,
+ activeVolunteers: row.activeVolunteers,
+ newSupports: row.newSupports,
+ signalType: row.signalType,
+ baseUpdatedAt: row.baseUpdatedAt,
+ })
+ municipalityUpdateOutboxCollection.utils.acceptMutations(transaction)
+ if (municipalityUpdateOutboxCollection.has(row.id)) {
+ municipalityUpdateOutboxCollection.delete(row.id)
+ }
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error)
+ if (isOpsUpdatedAtConflictMessage(message)) {
+ handleUpdatedAtConflict(message, (serverUpdatedAt) => {
+ if (municipalityUpdateOutboxCollection.has(row.id)) {
+ municipalityUpdateOutboxCollection.update(row.id, (draft) => {
+ draft.status = 'conflict'
+ draft.serverUpdatedAt = serverUpdatedAt
+ draft.errorMessage = message
+ })
+ }
+ })
+ }
+ if (municipalityUpdateOutboxCollection.has(row.id)) {
+ municipalityUpdateOutboxCollection.update(row.id, (draft) => {
+ draft.status = 'error'
+ draft.errorMessage = message
+ })
+ }
+ throw error instanceof Error ? error : new Error(message)
+ }
+ },
+ [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
+ try {
+ await setMunicipalityPoliticalTrendCas({
+ municipality: row.municipalityId,
+ status: row.status,
+ note: row.note,
+ baseUpdatedAt: row.baseUpdatedAt,
+ })
+ politicalTrendOutboxCollection.utils.acceptMutations(transaction)
+ if (politicalTrendOutboxCollection.has(row.municipalityId)) {
+ politicalTrendOutboxCollection.delete(row.municipalityId)
+ }
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error)
+ if (isOpsUpdatedAtConflictMessage(message)) {
+ handleUpdatedAtConflict(message, (serverUpdatedAt) => {
+ if (politicalTrendOutboxCollection.has(row.municipalityId)) {
+ politicalTrendOutboxCollection.update(row.municipalityId, (draft) => {
+ draft.statusSync = 'conflict'
+ draft.serverUpdatedAt = serverUpdatedAt
+ draft.errorMessage = message
+ })
+ }
+ })
+ }
+ if (politicalTrendOutboxCollection.has(row.municipalityId)) {
+ politicalTrendOutboxCollection.update(row.municipalityId, (draft) => {
+ draft.statusSync = 'error'
+ draft.errorMessage = message
+ })
+ }
+ throw error instanceof Error ? error : new Error(message)
+ }
+ },
+ [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
+ try {
+ await setMunicipalityEngagementLevelCas({
+ municipality: row.municipalityId,
+ level: row.level,
+ note: row.note,
+ reversalSignals: row.reversalSignals,
+ triangulatedShock: row.triangulatedShock,
+ override: row.override,
+ baseUpdatedAt: row.baseUpdatedAt,
+ })
+ engagementLevelOutboxCollection.utils.acceptMutations(transaction)
+ if (engagementLevelOutboxCollection.has(row.municipalityId)) {
+ engagementLevelOutboxCollection.delete(row.municipalityId)
+ }
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error)
+ if (isOpsUpdatedAtConflictMessage(message)) {
+ handleUpdatedAtConflict(message, (serverUpdatedAt) => {
+ if (engagementLevelOutboxCollection.has(row.municipalityId)) {
+ engagementLevelOutboxCollection.update(row.municipalityId, (draft) => {
+ draft.status = 'conflict'
+ draft.serverUpdatedAt = serverUpdatedAt
+ draft.errorMessage = message
+ })
+ }
+ })
+ }
+ if (engagementLevelOutboxCollection.has(row.municipalityId)) {
+ engagementLevelOutboxCollection.update(row.municipalityId, (draft) => {
+ draft.status = 'error'
+ draft.errorMessage = message
+ })
+ }
+ throw error instanceof Error ? error : new Error(message)
+ }
+ },
+ [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
+ try {
+ await assignMunicipalityAdvisorsCas({
+ municipality: row.municipalityId,
+ advisors: row.advisors,
+ baseUpdatedAt: row.baseUpdatedAt,
+ })
+ advisorsOutboxCollection.utils.acceptMutations(transaction)
+ if (advisorsOutboxCollection.has(row.municipalityId)) {
+ advisorsOutboxCollection.delete(row.municipalityId)
+ }
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error)
+ if (isOpsUpdatedAtConflictMessage(message)) {
+ handleUpdatedAtConflict(message, (serverUpdatedAt) => {
+ if (advisorsOutboxCollection.has(row.municipalityId)) {
+ advisorsOutboxCollection.update(row.municipalityId, (draft) => {
+ draft.status = 'conflict'
+ draft.serverUpdatedAt = serverUpdatedAt
+ draft.errorMessage = message
+ })
+ }
+ })
+ }
+ if (advisorsOutboxCollection.has(row.municipalityId)) {
+ advisorsOutboxCollection.update(row.municipalityId, (draft) => {
+ draft.status = 'error'
+ draft.errorMessage = message
+ })
+ }
+ throw error instanceof Error ? error : new Error(message)
+ }
+ },
+ },
+ })
+
+export const getOpsMunicipalityOfflineExecutor = async (): Promise => {
+ if (executorSingleton) {
+ await executorSingleton.waitForInit()
+ return executorSingleton
+ }
+ if (!initPromise) {
+ initPromise = (async () => {
+ const executor = createMunicipalityOfflineExecutor()
+ await executor.waitForInit()
+ executorSingleton = executor
+ return executor
+ })()
+ }
+ return initPromise
+}
+
+export const enqueueDeclareVotes = async (input: {
+ municipalityId: number
+ leadershipId: number
+ declaredVotes: number
+ pledgeId?: number
+ baseUpdatedAt?: string | null
+}): Promise => {
+ const executor = await getOpsMunicipalityOfflineExecutor()
+ const id = declareVotesOutboxKey(input.leadershipId, input.municipalityId)
+ const mirrorPledge =
+ input.pledgeId !== undefined
+ ? votePledgesCollection.get(input.pledgeId)
+ : votePledgesCollection.toArray.find(
+ (row) =>
+ row.leadership === input.leadershipId && row.municipality === input.municipalityId,
+ )
+ const pledgeId = input.pledgeId ?? mirrorPledge?.id
+ const baseUpdatedAt =
+ input.baseUpdatedAt !== undefined ? input.baseUpdatedAt : (mirrorPledge?.updatedAt ?? null)
+
+ const run = executor.createOfflineAction({
+ mutationFnName: DECLARE_MUTATION_FN,
+ onMutate: (variables) => {
+ const next: OpsDeclareVotesOutboxRow = {
+ id,
+ municipalityId: variables.municipalityId,
+ leadershipId: variables.leadershipId,
+ pledgeId,
+ declaredVotes: variables.declaredVotes,
+ baseUpdatedAt: variables.baseUpdatedAt ?? baseUpdatedAt,
+ status: 'pending',
+ }
+ if (pledgeId !== undefined && votePledgesCollection.has(pledgeId)) {
+ votePledgesCollection.update(pledgeId, (draft) => {
+ draft.declaredVotes = variables.declaredVotes
+ })
+ }
+ if (declareVotesOutboxCollection.has(id)) {
+ declareVotesOutboxCollection.update(id, (draft) => {
+ draft.declaredVotes = next.declaredVotes
+ draft.pledgeId = next.pledgeId
+ draft.baseUpdatedAt = next.baseUpdatedAt
+ draft.status = 'pending'
+ draft.serverUpdatedAt = undefined
+ draft.errorMessage = undefined
+ })
+ } else {
+ declareVotesOutboxCollection.insert(next)
+ }
+ },
+ })
+ run({ ...input, baseUpdatedAt, pledgeId })
+}
+
+export const enqueueMunicipalityUpdate = async (input: {
+ clientId: string
+ municipalityId: number
+ kind: MunicipalityUpdateKind
+ worked?: string
+ failed?: string
+ needs?: string
+ body?: string
+ activeVolunteers?: number
+ newSupports?: number
+ signalType?: MunicipalitySignalType
+ baseUpdatedAt?: string | null
+}): Promise => {
+ const executor = await getOpsMunicipalityOfflineExecutor()
+ const run = executor.createOfflineAction({
+ mutationFnName: MUNICIPALITY_UPDATE_MUTATION_FN,
+ onMutate: (variables) => {
+ const next: OpsMunicipalityUpdateOutboxRow = {
+ id: variables.clientId,
+ municipalityId: variables.municipalityId,
+ kind: variables.kind,
+ worked: variables.worked,
+ failed: variables.failed,
+ needs: variables.needs,
+ body: variables.body,
+ activeVolunteers: variables.activeVolunteers,
+ newSupports: variables.newSupports,
+ signalType: variables.signalType,
+ baseUpdatedAt: variables.baseUpdatedAt,
+ status: 'pending',
+ }
+ if (municipalityUpdateOutboxCollection.has(next.id)) {
+ municipalityUpdateOutboxCollection.update(next.id, (draft) => {
+ Object.assign(draft, next)
+ })
+ } else {
+ municipalityUpdateOutboxCollection.insert(next)
+ }
+ },
+ })
+ run(input)
+}
+
+export const enqueuePoliticalTrend = async (input: {
+ municipalityId: number
+ status: PoliticalTrendStatusValue | null
+ note: string | null
+ baseUpdatedAt?: string | null
+}): Promise => {
+ const executor = await getOpsMunicipalityOfflineExecutor()
+ const run = executor.createOfflineAction({
+ mutationFnName: TREND_MUTATION_FN,
+ onMutate: (variables) => {
+ const next: OpsPoliticalTrendOutboxRow = {
+ municipalityId: variables.municipalityId,
+ status: variables.status,
+ note: variables.note,
+ baseUpdatedAt: variables.baseUpdatedAt,
+ statusSync: 'pending',
+ }
+ if (politicalTrendOutboxCollection.has(variables.municipalityId)) {
+ politicalTrendOutboxCollection.update(variables.municipalityId, (draft) => {
+ draft.status = next.status
+ draft.note = next.note
+ draft.baseUpdatedAt = next.baseUpdatedAt
+ draft.statusSync = 'pending'
+ draft.serverUpdatedAt = undefined
+ draft.errorMessage = undefined
+ })
+ } else {
+ politicalTrendOutboxCollection.insert(next)
+ }
+ },
+ })
+ run(input)
+}
+
+export const enqueueEngagementLevel = async (input: {
+ municipalityId: number
+ level: EngagementLevel
+ note: string
+ reversalSignals: string
+ triangulatedShock: boolean
+ override: boolean
+ baseUpdatedAt?: string | null
+}): Promise => {
+ const executor = await getOpsMunicipalityOfflineExecutor()
+ const run = executor.createOfflineAction({
+ mutationFnName: ENGAGEMENT_MUTATION_FN,
+ onMutate: (variables) => {
+ const next: OpsEngagementLevelOutboxRow = {
+ municipalityId: variables.municipalityId,
+ level: variables.level,
+ note: variables.note,
+ reversalSignals: variables.reversalSignals,
+ triangulatedShock: variables.triangulatedShock,
+ override: variables.override,
+ baseUpdatedAt: variables.baseUpdatedAt,
+ status: 'pending',
+ }
+ if (engagementLevelOutboxCollection.has(variables.municipalityId)) {
+ engagementLevelOutboxCollection.update(variables.municipalityId, (draft) => {
+ Object.assign(draft, next)
+ draft.serverUpdatedAt = undefined
+ draft.errorMessage = undefined
+ })
+ } else {
+ engagementLevelOutboxCollection.insert(next)
+ }
+ },
+ })
+ run(input)
+}
+
+export const enqueueAdvisorsAssignment = async (input: {
+ municipalityId: number
+ advisors: number[]
+ baseUpdatedAt?: string | null
+}): Promise => {
+ const executor = await getOpsMunicipalityOfflineExecutor()
+ const run = executor.createOfflineAction({
+ mutationFnName: ADVISORS_MUTATION_FN,
+ onMutate: (variables) => {
+ const next: OpsAdvisorsOutboxRow = {
+ municipalityId: variables.municipalityId,
+ advisors: variables.advisors,
+ baseUpdatedAt: variables.baseUpdatedAt,
+ status: 'pending',
+ }
+ if (advisorsOutboxCollection.has(variables.municipalityId)) {
+ advisorsOutboxCollection.update(variables.municipalityId, (draft) => {
+ draft.advisors = next.advisors
+ draft.baseUpdatedAt = next.baseUpdatedAt
+ draft.status = 'pending'
+ draft.serverUpdatedAt = undefined
+ draft.errorMessage = undefined
+ })
+ } else {
+ advisorsOutboxCollection.insert(next)
+ }
+ },
+ })
+ run(input)
+}
+
+export const collectOpsMunicipalityOutboxKeys = (): Set => {
+ const keys = new Set()
+ for (const row of declareVotesOutboxCollection.toArray) {
+ if (row.status === 'pending' || row.status === 'conflict') {
+ if (row.pledgeId !== undefined) {
+ keys.add(opsOutboxKey('votePledges', row.pledgeId))
+ } else {
+ const pledge = votePledgesCollection.toArray.find(
+ (p) => p.leadership === row.leadershipId && p.municipality === row.municipalityId,
+ )
+ if (pledge) keys.add(opsOutboxKey('votePledges', pledge.id))
+ }
+ }
+ }
+ for (const row of municipalityUpdateOutboxCollection.toArray) {
+ if (row.status === 'pending' || row.status === 'conflict') {
+ keys.add(opsOutboxKey('municipalities', row.municipalityId))
+ }
+ }
+ for (const row of politicalTrendOutboxCollection.toArray) {
+ if (row.statusSync === 'pending' || row.statusSync === 'conflict') {
+ keys.add(opsOutboxKey('municipalities', row.municipalityId))
+ }
+ }
+ for (const row of engagementLevelOutboxCollection.toArray) {
+ if (row.status === 'pending' || row.status === 'conflict') {
+ keys.add(opsOutboxKey('municipalities', row.municipalityId))
+ }
+ }
+ for (const row of advisorsOutboxCollection.toArray) {
+ if (row.status === 'pending' || row.status === 'conflict') {
+ keys.add(opsOutboxKey('municipalities', row.municipalityId))
+ }
+ }
+ return keys
+}
+
+export const readOpsDeclareVotesOutboxRow = (
+ leadershipId: number,
+ municipalityId: number,
+): OpsDeclareVotesOutboxRow | undefined =>
+ declareVotesOutboxCollection.get(declareVotesOutboxKey(leadershipId, municipalityId))
+
+export const subscribeOpsDeclareVotesOutboxRow = (
+ leadershipId: number,
+ municipalityId: number,
+ onStoreChange: () => void,
+): (() => void) => {
+ const id = declareVotesOutboxKey(leadershipId, municipalityId)
+ let previous = declareVotesOutboxCollection.get(id)
+ const subscription = declareVotesOutboxCollection.subscribeChanges(() => {
+ const next = declareVotesOutboxCollection.get(id)
+ if (next === previous) return
+ previous = next
+ onStoreChange()
+ })
+ return () => subscription.unsubscribe()
+}
+
+export const discardOpsDeclareVotesOutboxRow = (
+ leadershipId: number,
+ municipalityId: number,
+): void => {
+ const id = declareVotesOutboxKey(leadershipId, municipalityId)
+ if (declareVotesOutboxCollection.has(id)) declareVotesOutboxCollection.delete(id)
+}
+
+export const readOpsAdvisorsOutboxRow = (
+ municipalityId: number,
+): OpsAdvisorsOutboxRow | undefined => advisorsOutboxCollection.get(municipalityId)
+
+export const subscribeOpsAdvisorsOutboxRow = (
+ municipalityId: number,
+ onStoreChange: () => void,
+): (() => void) => {
+ let previous = advisorsOutboxCollection.get(municipalityId)
+ const subscription = advisorsOutboxCollection.subscribeChanges(() => {
+ const next = advisorsOutboxCollection.get(municipalityId)
+ if (next === previous) return
+ previous = next
+ onStoreChange()
+ })
+ return () => subscription.unsubscribe()
+}
+
+export const discardOpsAdvisorsOutboxRow = (municipalityId: number): void => {
+ if (advisorsOutboxCollection.has(municipalityId)) {
+ advisorsOutboxCollection.delete(municipalityId)
+ }
+}
diff --git a/src/components/campaign/opsSync/opsMunicipalityOutboxModel.ts b/src/components/campaign/opsSync/opsMunicipalityOutboxModel.ts
new file mode 100644
index 00000000..b4a7aa20
--- /dev/null
+++ b/src/components/campaign/opsSync/opsMunicipalityOutboxModel.ts
@@ -0,0 +1,119 @@
+import type { OfflineTransaction } from '@tanstack/offline-transactions'
+
+import type { EngagementLevel } from '@/lib/engagementLevel'
+import type { PoliticalTrendStatusValue } from '@/lib/schemas/municipality'
+import type {
+ MunicipalitySignalType,
+ MunicipalityUpdateKind,
+} from '@/lib/schemas/municipalityUpdate'
+
+export type OpsMunicipalityWriteSyncStatus = 'pending' | 'synced' | 'conflict' | 'error'
+
+export type OpsDeclareVotesOutboxRow = {
+ id: string
+ municipalityId: number
+ leadershipId: number
+ /** Mirror pledge id when known — avoids O(n) lookup in collectOutboxKeys. */
+ pledgeId?: number
+ declaredVotes: number
+ baseUpdatedAt?: string | null
+ status: OpsMunicipalityWriteSyncStatus
+ serverUpdatedAt?: string | null
+ errorMessage?: string
+}
+
+export type OpsMunicipalityUpdateOutboxRow = {
+ id: string
+ municipalityId: number
+ kind: MunicipalityUpdateKind
+ worked?: string
+ failed?: string
+ needs?: string
+ body?: string
+ activeVolunteers?: number
+ newSupports?: number
+ signalType?: MunicipalitySignalType
+ baseUpdatedAt?: string | null
+ status: OpsMunicipalityWriteSyncStatus
+ serverUpdatedAt?: string | null
+ errorMessage?: string
+}
+
+export type OpsPoliticalTrendOutboxRow = {
+ municipalityId: number
+ status: PoliticalTrendStatusValue | null
+ note: string | null
+ baseUpdatedAt?: string | null
+ statusSync: OpsMunicipalityWriteSyncStatus
+ serverUpdatedAt?: string | null
+ errorMessage?: string
+}
+
+export type OpsEngagementLevelOutboxRow = {
+ municipalityId: number
+ level: EngagementLevel
+ note: string
+ reversalSignals: string
+ triangulatedShock: boolean
+ override: boolean
+ baseUpdatedAt?: string | null
+ status: OpsMunicipalityWriteSyncStatus
+ serverUpdatedAt?: string | null
+ errorMessage?: string
+}
+
+export type OpsAdvisorsOutboxRow = {
+ municipalityId: number
+ advisors: number[]
+ baseUpdatedAt?: string | null
+ status: OpsMunicipalityWriteSyncStatus
+ serverUpdatedAt?: string | null
+ errorMessage?: string
+}
+
+/** Collapse declare-votes retries to the newest per leadership×municipality. */
+export const collapseDeclareVotesOutbox = (
+ transactions: OfflineTransaction[],
+): OfflineTransaction[] => collapseByMetadataKey(transactions, 'declareKey')
+
+/** Feed creates are append-only — keep every distinct client id. */
+export const collapseMunicipalityUpdateOutbox = (
+ transactions: OfflineTransaction[],
+): OfflineTransaction[] => collapseByMetadataKey(transactions, 'clientId')
+
+export const collapsePoliticalTrendOutbox = (
+ transactions: OfflineTransaction[],
+): OfflineTransaction[] => collapseByMetadataKey(transactions, 'municipalityId')
+
+export const collapseEngagementLevelOutbox = (
+ transactions: OfflineTransaction[],
+): OfflineTransaction[] => collapseByMetadataKey(transactions, 'municipalityId')
+
+export const collapseAdvisorsOutbox = (transactions: OfflineTransaction[]): OfflineTransaction[] =>
+ collapseByMetadataKey(transactions, 'municipalityId')
+
+const collapseByMetadataKey = (
+ transactions: OfflineTransaction[],
+ metadataKey: string,
+): OfflineTransaction[] => {
+ const latestByKey = new Map()
+
+ for (const transaction of transactions) {
+ const raw = transaction.metadata?.[metadataKey]
+ const key =
+ typeof raw === 'number' || typeof raw === 'string'
+ ? String(raw)
+ : String(transaction.mutations[0]?.key ?? transaction.id)
+ const current = latestByKey.get(key)
+ if (!current || transaction.createdAt.getTime() >= current.createdAt.getTime()) {
+ latestByKey.set(key, transaction)
+ }
+ }
+
+ return [...latestByKey.values()].sort(
+ (left, right) => left.createdAt.getTime() - right.createdAt.getTime(),
+ )
+}
+
+export const declareVotesOutboxKey = (leadershipId: number, municipalityId: number): string =>
+ `${leadershipId}:${municipalityId}`
diff --git a/src/components/campaign/opsSync/opsVotePledgeMirror.ts b/src/components/campaign/opsSync/opsVotePledgeMirror.ts
index 51e29937..d5ecfbf3 100644
--- a/src/components/campaign/opsSync/opsVotePledgeMirror.ts
+++ b/src/components/campaign/opsSync/opsVotePledgeMirror.ts
@@ -48,11 +48,14 @@ export const patchOpsVotePledgeEstimateOptimistic = (
})
}
-/** Authoritative patch after a successful server write (OH7). */
+/** Authoritative patch after a successful server write (OH7/OH10). */
export const applyOpsVotePledgeEstimateWrite = (doc: VotePledgeEstimateWriteResult): void => {
const mapped = mapVotePledgeWriteToOps(doc)
if (votePledgesCollection.has(mapped.id)) {
votePledgesCollection.update(mapped.id, (draft) => {
+ draft.declaredVotes = mapped.declaredVotes
+ draft.declaredAt = mapped.declaredAt
+ draft.declaredBy = mapped.declaredBy
draft.estimatedVotes = mapped.estimatedVotes
draft.estimateNote = mapped.estimateNote
draft.estimatedAt = mapped.estimatedAt
diff --git a/src/components/campaign/shared/useCampaignCellAutosave.ts b/src/components/campaign/shared/useCampaignCellAutosave.ts
index f9105bc7..18c7b557 100644
--- a/src/components/campaign/shared/useCampaignCellAutosave.ts
+++ b/src/components/campaign/shared/useCampaignCellAutosave.ts
@@ -23,6 +23,11 @@ type UseCampaignCellAutosaveOptions Promise<{ ok: boolean; payload: TResponse }>
}
/**
@@ -140,11 +145,13 @@ export const useCampaignCellAutosave = (
- current.endpoint,
- current.buildBody(next),
- controller.signal,
- )
+ const { ok, payload } = current.persist
+ ? await current.persist(next, controller.signal)
+ : await postCampaignJson(
+ current.endpoint,
+ current.buildBody(next),
+ controller.signal,
+ )
if (generation !== saveGenerationRef.current) return
diff --git a/src/components/campaign/votePledge/DeclareVotesForm.tsx b/src/components/campaign/votePledge/DeclareVotesForm.tsx
index 773a60e5..f1d0a668 100644
--- a/src/components/campaign/votePledge/DeclareVotesForm.tsx
+++ b/src/components/campaign/votePledge/DeclareVotesForm.tsx
@@ -1,12 +1,37 @@
'use client'
-import { useActionState } from 'react'
+import { useRouter } from 'next/navigation'
+import {
+ useActionState,
+ useEffect,
+ useId,
+ useRef,
+ useState,
+ useSyncExternalStore,
+ type FormEvent,
+} from 'react'
+import { toast } from 'sonner'
+import {
+ discardOpsDeclareVotesOutboxRow,
+ enqueueDeclareVotes,
+ getOpsMunicipalityOfflineExecutor,
+ readOpsDeclareVotesOutboxRow,
+ subscribeOpsDeclareVotesOutboxRow,
+} from '@/components/campaign/opsSync/opsMunicipalityOutbox'
+import type { OpsMunicipalityWriteSyncStatus } from '@/components/campaign/opsSync/opsMunicipalityOutboxModel'
+import {
+ subscribeOpsVotePledge,
+ votePledgesCollection,
+} from '@/components/campaign/opsSync/opsVotePledgeMirror'
import { CampaignFormActionMessage } from '@/components/campaign/shared/CampaignFormActionMessage'
+import { Badge } from '@/components/ui/Badge'
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'
@@ -14,19 +39,64 @@ type DeclareVotesFormProps = {
municipalityID: number
/** Present when staff declare on behalf of a leadership. */
leadershipID?: number
+ /** Mirror / outbox key when a pledge row already exists (OH10). */
+ pledgeId?: number
currentDeclaredVotes: number | null
+ /** Pledge row `updatedAt` for CAS when a pledge already exists. */
+ currentUpdatedAt?: string | null
+ opsHybridEnabled?: boolean
formAction: (
state: CampaignFormActionState,
formData: FormData,
) => Promise
}
+const syncStatusLabel: Record = {
+ pending: 'Pendente',
+ synced: 'Sincronizado',
+ conflict: 'Conflito',
+ error: 'Erro',
+}
+
+const CONFLICT_TOAST_ID_PREFIX = 'ops-declare-conflict:'
+
export const DeclareVotesForm = ({
+ municipalityID,
+ leadershipID,
+ pledgeId,
+ currentDeclaredVotes,
+ currentUpdatedAt = null,
+ opsHybridEnabled = resolveOpsHybridEnabled(),
+ formAction,
+}: DeclareVotesFormProps) => {
+ if (!opsHybridEnabled || leadershipID === undefined) {
+ return (
+
+ )
+ }
+
+ return (
+
+ )
+}
+
+const LegacyDeclareVotesForm = ({
municipalityID,
leadershipID,
currentDeclaredVotes,
formAction,
-}: DeclareVotesFormProps) => {
+}: Omit) => {
const [state, submitAction, isPending] = useActionState(formAction, {})
return (
@@ -66,3 +136,189 @@ export const DeclareVotesForm = ({
)
}
+
+const HybridDeclareVotesForm = ({
+ municipalityID,
+ leadershipID,
+ pledgeId: initialPledgeId,
+ currentDeclaredVotes,
+ currentUpdatedAt,
+}: {
+ municipalityID: number
+ leadershipID: number
+ pledgeId?: number
+ currentDeclaredVotes: number | null
+ currentUpdatedAt: string | null
+}) => {
+ const router = useRouter()
+ const liveRegionId = useId()
+ const formRef = useRef(null)
+ const previousStatusRef = useRef(undefined)
+ const [isSubmitting, setIsSubmitting] = useState(false)
+ const [formError, setFormError] = useState(null)
+ const [baseOverride, setBaseOverride] = useState(undefined)
+
+ const resolvedPledgeId =
+ initialPledgeId ??
+ votePledgesCollection.toArray.find(
+ (row) => row.leadership === leadershipID && row.municipality === municipalityID,
+ )?.id
+
+ const mirrorPledge = useSyncExternalStore(
+ (onStoreChange) => {
+ if (resolvedPledgeId === undefined) return () => undefined
+ return subscribeOpsVotePledge(resolvedPledgeId, onStoreChange)
+ },
+ () =>
+ resolvedPledgeId !== undefined
+ ? votePledgesCollection.get(resolvedPledgeId)
+ : votePledgesCollection.toArray.find(
+ (row) => row.leadership === leadershipID && row.municipality === municipalityID,
+ ),
+ () => undefined,
+ )
+
+ const pledgeId = initialPledgeId ?? mirrorPledge?.id
+ const displayVotes = mirrorPledge?.declaredVotes ?? currentDeclaredVotes
+ const mirrorUpdatedAt = mirrorPledge?.updatedAt ?? currentUpdatedAt
+ const baseUpdatedAt = baseOverride !== undefined ? baseOverride : mirrorUpdatedAt
+
+ const outboxRow = useSyncExternalStore(
+ (onStoreChange) =>
+ subscribeOpsDeclareVotesOutboxRow(leadershipID, municipalityID, onStoreChange),
+ () => readOpsDeclareVotesOutboxRow(leadershipID, municipalityID),
+ () => undefined,
+ )
+
+ useEffect(() => {
+ void getOpsMunicipalityOfflineExecutor()
+ }, [])
+
+ useEffect(() => {
+ setBaseOverride(undefined)
+ }, [mirrorUpdatedAt])
+
+ useEffect(() => {
+ const previous = previousStatusRef.current
+ previousStatusRef.current = outboxRow?.status
+ if (previous === 'pending' && outboxRow === undefined) {
+ router.refresh()
+ }
+ }, [outboxRow, router])
+
+ useEffect(() => {
+ if (outboxRow?.status !== 'conflict') return
+ const toastId = `${CONFLICT_TOAST_ID_PREFIX}${leadershipID}:${municipalityID}`
+ toast.message(OPS_UPDATED_AT_CONFLICT_MESSAGE, {
+ id: toastId,
+ duration: Infinity,
+ action: {
+ label: 'Manter o meu',
+ onClick: () => {
+ const form = formRef.current
+ if (!form) return
+ const raw = new FormData(form).get('declaredVotes')
+ const declaredVotes = typeof raw === 'string' ? Number(raw) : NaN
+ if (!Number.isFinite(declaredVotes)) return
+ void enqueueDeclareVotes({
+ municipalityId: municipalityID,
+ leadershipId: leadershipID,
+ pledgeId,
+ declaredVotes: Math.trunc(declaredVotes),
+ baseUpdatedAt: outboxRow.serverUpdatedAt ?? null,
+ }).then(
+ () => {
+ setBaseOverride(outboxRow.serverUpdatedAt ?? null)
+ setFormError(null)
+ },
+ (error: unknown) => {
+ setFormError(
+ error instanceof Error ? error.message : 'Não foi possível reenviar a declaração.',
+ )
+ },
+ )
+ },
+ },
+ cancel: {
+ label: 'Usar o novo',
+ onClick: () => {
+ discardOpsDeclareVotesOutboxRow(leadershipID, municipalityID)
+ setFormError(null)
+ router.refresh()
+ },
+ },
+ })
+ return () => {
+ toast.dismiss(toastId)
+ }
+ }, [outboxRow, leadershipID, municipalityID, pledgeId, router])
+
+ const onSubmit = (event: FormEvent) => {
+ event.preventDefault()
+ const form = event.currentTarget
+ const raw = new FormData(form).get('declaredVotes')
+ const declaredVotes = typeof raw === 'string' ? Number(raw) : NaN
+ if (!Number.isFinite(declaredVotes) || declaredVotes < 0) {
+ setFormError('Informe um número válido de votos.')
+ return
+ }
+ setIsSubmitting(true)
+ setFormError(null)
+ void enqueueDeclareVotes({
+ municipalityId: municipalityID,
+ leadershipId: leadershipID,
+ pledgeId,
+ declaredVotes: Math.trunc(declaredVotes),
+ baseUpdatedAt,
+ }).then(
+ () => setIsSubmitting(false),
+ (error: unknown) => {
+ setIsSubmitting(false)
+ setFormError(
+ error instanceof Error ? error.message : 'Não foi possível enfileirar a declaração.',
+ )
+ },
+ )
+ }
+
+ const status = outboxRow?.status
+ const pending = isSubmitting || status === 'pending'
+
+ return (
+
+ )
+}
diff --git a/src/lib/campaignOps/municipalityDetailLocalViews.ts b/src/lib/campaignOps/municipalityDetailLocalViews.ts
index 4a19c342..b37ff9be 100644
--- a/src/lib/campaignOps/municipalityDetailLocalViews.ts
+++ b/src/lib/campaignOps/municipalityDetailLocalViews.ts
@@ -14,6 +14,7 @@ export type OpsLocalStaffPledgeRow = {
estimatedVotes: VoteEstimateScenarioViewModel
estimateNote: string | null
estimatedAt: string | null
+ updatedAt: string
}
export const findOpsMunicipalityBySlug = (
@@ -41,6 +42,7 @@ export const toLocalStaffPledgeRows = (
estimatedVotes: toVoteEstimateScenarioViewModel(pledge.estimatedVotes),
estimateNote: pledge.estimateNote ?? null,
estimatedAt: pledge.estimatedAt ?? null,
+ updatedAt: pledge.updatedAt,
}
})
.sort((left, right) => left.contactName.localeCompare(right.contactName, 'pt-BR'))
diff --git a/src/lib/schemas/municipality.ts b/src/lib/schemas/municipality.ts
index dcd68a2b..57c58906 100644
--- a/src/lib/schemas/municipality.ts
+++ b/src/lib/schemas/municipality.ts
@@ -1,6 +1,7 @@
import { z } from 'zod'
import { ENGAGEMENT_LEVEL_TEXT_MAX_LENGTH, engagementLevels } from '@/lib/engagementLevel'
+import { OPS_UPDATED_AT_CONFLICT_MESSAGE, optionalBaseUpdatedAtSchema } from '@/lib/schemas/opsCas'
import { positiveRelationshipId, trimmedNullableText } from '@/lib/schemas/primitives'
import { voteEstimateScenarioFieldsSchema } from '@/lib/schemas/votePledge'
@@ -47,6 +48,8 @@ export const municipalityPoliticalTrendSchema = z.object({
municipality: positiveRelationshipId,
status: z.enum(politicalTrendStatuses).nullable(),
note: trimmedNullableText(2000),
+ /** OH10 CAS opt-in on municipality `updatedAt`. Absent → last-write-wins. */
+ baseUpdatedAt: optionalBaseUpdatedAtSchema,
})
export const parsePoliticalTrendStatusFormValue = (
@@ -68,6 +71,8 @@ export const municipalityAdvisorsAssignmentSchema = z.object({
.array(positiveRelationshipId)
.max(MAX_ADVISORS_PER_MUNICIPALITY)
.transform((ids) => [...new Set(ids)]),
+ /** OH10 CAS opt-in on municipality `updatedAt`. Absent → last-write-wins. */
+ baseUpdatedAt: optionalBaseUpdatedAtSchema,
})
/** Single-toggle delta from the list popover — one advisor at a time, never the whole array. */
@@ -75,6 +80,8 @@ export const municipalityAdvisorMembershipSchema = z.object({
municipality: positiveRelationshipId,
advisor: positiveRelationshipId,
assigned: z.boolean(),
+ /** OH10 CAS opt-in on municipality `updatedAt`. Absent → last-write-wins. */
+ baseUpdatedAt: optionalBaseUpdatedAtSchema,
})
export const MUNICIPALITY_ADVISOR_MEMBERSHIP_UNRESTRICTED_MESSAGE =
@@ -83,11 +90,17 @@ export const MUNICIPALITY_ADVISOR_MEMBERSHIP_UNRESTRICTED_MESSAGE =
export const MUNICIPALITY_ADVISOR_MEMBERSHIP_SAFE_MESSAGES = [
MUNICIPALITY_ADVISOR_MEMBERSHIP_UNRESTRICTED_MESSAGE,
MUNICIPALITY_ADVISORS_CAP_MESSAGE,
+ OPS_UPDATED_AT_CONFLICT_MESSAGE,
] as const
export const MUNICIPALITY_ENGAGEMENT_LEVEL_UNRESTRICTED_MESSAGE =
'Somente a coordenação geral ou o candidato move o nível de envolvimento.'
+export const MUNICIPALITY_ENGAGEMENT_LEVEL_SAFE_MESSAGES = [
+ MUNICIPALITY_ENGAGEMENT_LEVEL_UNRESTRICTED_MESSAGE,
+ OPS_UPDATED_AT_CONFLICT_MESSAGE,
+] as const
+
/**
* E14 — a movement is never just the new level: the motivo and the signals
* that would reverse it are what make the decision auditable later, so both
@@ -102,6 +115,8 @@ export const municipalityEngagementLevelSchema = z.object({
triangulatedShock: z.boolean().default(false),
/** Accepts the listed violations knowingly; recorded in the decision snapshot. */
override: z.boolean().default(false),
+ /** OH10 CAS opt-in on municipality `updatedAt`. Absent → last-write-wins. */
+ baseUpdatedAt: optionalBaseUpdatedAtSchema,
})
export const municipalityExpectedVotesSchema = z.object({
diff --git a/src/lib/schemas/municipalityUpdate.ts b/src/lib/schemas/municipalityUpdate.ts
index 0c075b22..81fec122 100644
--- a/src/lib/schemas/municipalityUpdate.ts
+++ b/src/lib/schemas/municipalityUpdate.ts
@@ -1,5 +1,6 @@
import { z } from 'zod'
+import { optionalBaseUpdatedAtSchema } from '@/lib/schemas/opsCas'
import {
MAX_VOTE_COUNT,
positiveRelationshipId,
@@ -63,6 +64,11 @@ export const municipalityUpdateCreateSchema = z
activeVolunteers: optionalCount,
newSupports: optionalCount,
signalType: z.enum(municipalitySignalTypes).optional(),
+ /**
+ * OH10 CAS opt-in on the parent municipality's `updatedAt` (feed order).
+ * Absent → last-write-wins create.
+ */
+ baseUpdatedAt: optionalBaseUpdatedAtSchema,
})
.superRefine((data, context) => {
if (data.kind === 'semanal') {
diff --git a/src/lib/schemas/opsCas.ts b/src/lib/schemas/opsCas.ts
new file mode 100644
index 00000000..4ed8e172
--- /dev/null
+++ b/src/lib/schemas/opsCas.ts
@@ -0,0 +1,38 @@
+import { z } from 'zod'
+
+/**
+ * OH10 — shared CAS token for doc `updatedAt`. Opt-in: absent → last-write-wins
+ * (legacy). Present (including matching the current stamp) → refuse when the
+ * row's `updatedAt` differs. Same exact-string + optional stamp contract as
+ * OH6's `OPS_ESTIMATE_CONFLICT_MESSAGE` (safeMessages + outbox parse).
+ */
+export const optionalBaseUpdatedAtSchema = z.string().datetime().nullable().optional()
+
+export const OPS_UPDATED_AT_CONFLICT_MESSAGE =
+ 'Este registro foi alterado por outra pessoa. Escolha manter a sua ou usar a nova.'
+
+export const opsUpdatedAtConflictError = (serverUpdatedAt: string): Error =>
+ new Error(`${OPS_UPDATED_AT_CONFLICT_MESSAGE}\n${serverUpdatedAt}`)
+
+export const isOpsUpdatedAtConflictMessage = (message: string): boolean =>
+ message === OPS_UPDATED_AT_CONFLICT_MESSAGE ||
+ message.startsWith(`${OPS_UPDATED_AT_CONFLICT_MESSAGE}\n`)
+
+export const parseOpsUpdatedAtConflictServerUpdatedAt = (message: string): string | null => {
+ if (!isOpsUpdatedAtConflictMessage(message)) return null
+ if (message === OPS_UPDATED_AT_CONFLICT_MESSAGE) return null
+ const stamped = message.slice(OPS_UPDATED_AT_CONFLICT_MESSAGE.length + 1)
+ return stamped === '' ? null : stamped
+}
+
+/** Refuse when CAS is armed and the live stamp differs from the client's base. */
+export const assertOpsUpdatedAtCas = (
+ enforceCas: boolean,
+ baseUpdatedAt: string | null | undefined,
+ currentUpdatedAt: string,
+): void => {
+ if (!enforceCas || baseUpdatedAt === undefined) return
+ if (currentUpdatedAt !== baseUpdatedAt) {
+ throw opsUpdatedAtConflictError(currentUpdatedAt)
+ }
+}
diff --git a/src/lib/schemas/votePledge.ts b/src/lib/schemas/votePledge.ts
index aff5488f..4379ce2f 100644
--- a/src/lib/schemas/votePledge.ts
+++ b/src/lib/schemas/votePledge.ts
@@ -1,5 +1,6 @@
import { z } from 'zod'
+import { OPS_UPDATED_AT_CONFLICT_MESSAGE, optionalBaseUpdatedAtSchema } from '@/lib/schemas/opsCas'
import {
MAX_VOTE_COUNT,
positiveRelationshipId,
@@ -34,6 +35,11 @@ export const declareVotesSchema = z.object({
municipality: positiveRelationshipId,
leadership: positiveRelationshipId,
declaredVotes: z.number().int().min(0).max(MAX_VOTE_COUNT),
+ /**
+ * OH10 CAS opt-in on the pledge row's `updatedAt`. Absent → last-write-wins.
+ * When no pledge exists yet, pass `null` to assert a create.
+ */
+ baseUpdatedAt: optionalBaseUpdatedAtSchema,
})
/** Staff record their internal estimate for one pledge. */
@@ -91,6 +97,7 @@ export const VOTE_PLEDGE_DECLARE_SAFE_MESSAGES = [
VOTE_PLEDGE_DECLARE_STAFF_MESSAGE,
VOTE_PLEDGE_MUNICIPALITY_NOT_LINKED_MESSAGE,
VOTE_PLEDGE_LEADERSHIP_REQUIRED_MESSAGE,
+ OPS_UPDATED_AT_CONFLICT_MESSAGE,
] as const
export const VOTE_PLEDGE_ESTIMATE_SAFE_MESSAGES = [
diff --git a/src/utilities/municipality/municipalityViewModels.ts b/src/utilities/municipality/municipalityViewModels.ts
index 65a8b661..4d8ef2d8 100644
--- a/src/utilities/municipality/municipalityViewModels.ts
+++ b/src/utilities/municipality/municipalityViewModels.ts
@@ -38,6 +38,7 @@ export const municipalityListSelect = {
advisors: true,
priority: true,
lastUpdateAt: true,
+ updatedAt: true,
expectedVotes: true,
politicalTrend: {
status: true,
@@ -73,6 +74,8 @@ export type MunicipalityListViewModel = {
* ordering.
*/
lastSignalAt: string | null
+ /** OH10 — CAS token for staff writes when OPS_HYBRID is on. */
+ updatedAt: string
expectedVotes: VoteEstimateScenarioViewModel
politicalTrendStatus: PoliticalTrendStatus | null
politicalTrendNote: string | null
@@ -116,6 +119,7 @@ export const toMunicipalityListViewModel = (
municipality.lastUpdateAt ?? null,
pledges?.lastPledgeAt ?? null,
),
+ updatedAt: municipality.updatedAt,
expectedVotes: toVoteEstimateScenarioViewModel(municipality.expectedVotes),
politicalTrendStatus: municipality.politicalTrend?.status ?? null,
politicalTrendNote: municipality.politicalTrend?.note ?? null,
@@ -149,6 +153,8 @@ export type MunicipalityDetailViewModel = {
tseZones: number[]
advisorIDs: number[]
lastUpdateAt: string | null
+ /** OH10 — CAS token for staff writes when OPS_HYBRID is on. */
+ updatedAt: string
/** Staff-only block — null for the leader view model. */
strategy: MunicipalityStrategyViewModel | null
}
@@ -196,6 +202,7 @@ export const toMunicipalityDetailViewModel = (
.map(relationshipId)
.filter((id): id is number => id !== null),
lastUpdateAt: municipality.lastUpdateAt ?? null,
+ updatedAt: municipality.updatedAt,
strategy:
role === 'leader'
? null
diff --git a/src/utilities/votePledgeData.ts b/src/utilities/votePledgeData.ts
index f93a39c1..8fdb5279 100644
--- a/src/utilities/votePledgeData.ts
+++ b/src/utilities/votePledgeData.ts
@@ -139,5 +139,6 @@ export const loadMunicipalityPledges = async (
estimatedVotes: toVoteEstimateScenarioViewModel(pledge.estimatedVotes),
estimateNote: pledge.estimateNote ?? null,
estimatedAt: pledge.estimatedAt ?? null,
+ updatedAt: pledge.updatedAt,
}))
}
diff --git a/src/utilities/votePledgeViews.ts b/src/utilities/votePledgeViews.ts
index 9dd90375..7261d350 100644
--- a/src/utilities/votePledgeViews.ts
+++ b/src/utilities/votePledgeViews.ts
@@ -162,4 +162,6 @@ export type StaffPledgeRow = {
estimatedVotes: VoteEstimateScenarioViewModel
estimateNote: string | null
estimatedAt: string | null
+ /** OH10 — CAS token for declareVotes when OPS_HYBRID is on. */
+ updatedAt: string
}
diff --git a/tests/int/municipalityStaffCas.int.spec.ts b/tests/int/municipalityStaffCas.int.spec.ts
new file mode 100644
index 00000000..a916b881
--- /dev/null
+++ b/tests/int/municipalityStaffCas.int.spec.ts
@@ -0,0 +1,243 @@
+// @vitest-environment node
+
+import type { Payload } from 'payload'
+import { getPayload } from 'payload'
+import { beforeAll, describe, expect, it } from 'vitest'
+
+import {
+ assignMunicipalityAdvisorsCasRecord,
+ setMunicipalityAdvisorMembershipCasRecord,
+ setMunicipalityEngagementLevelCasRecord,
+ setMunicipalityEngagementLevelRecord,
+ setMunicipalityPoliticalTrendCasRecord,
+ setMunicipalityPoliticalTrendRecord,
+} from '@/app/(campaign)/campanha/actions/municipality'
+import { ENGAGEMENT_LEVEL_PATTERN_ID } from '@/lib/engagementLevel'
+import { isOpsUpdatedAtConflictMessage } from '@/lib/schemas/opsCas'
+import config from '@/payload.config'
+
+import { installCampaignFixtures } from '../helpers/campaignFixtures'
+
+let payload: Payload
+const campaignFixtures = installCampaignFixtures({
+ getPayload: () => payload,
+ setPayload: (nextPayload) => {
+ payload = nextPayload
+ },
+})
+
+describe('municipality staff CAS writes (OH10 fase 2)', () => {
+ beforeAll(async () => {
+ payload = await getPayload({ config: await config })
+ })
+
+ it('politicalTrend: refuses stale baseUpdatedAt', async () => {
+ const fixtures = campaignFixtures()
+ const municipality = await fixtures.getMunicipality()
+ const advisor = await fixtures.createCampaignUser('advisor')
+ await fixtures.assignMunicipalityAdvisors(municipality.id, [advisor.id])
+
+ const first = await setMunicipalityPoliticalTrendRecord(payload, advisor, {
+ municipality: municipality.id,
+ status: 'favoravel',
+ note: 'primeira',
+ })
+ const baseUpdatedAt = first.updatedAt
+
+ await setMunicipalityPoliticalTrendRecord(payload, advisor, {
+ municipality: municipality.id,
+ status: 'neutra',
+ note: 'segunda',
+ })
+
+ await expect(
+ setMunicipalityPoliticalTrendCasRecord(payload, advisor, {
+ municipality: municipality.id,
+ status: 'desfavoravel',
+ note: 'stale',
+ baseUpdatedAt,
+ }),
+ ).rejects.toSatisfy((error: unknown) => {
+ expect(isOpsUpdatedAtConflictMessage((error as Error).message)).toBe(true)
+ return true
+ })
+
+ const current = await payload.findByID({
+ collection: 'municipality',
+ id: municipality.id,
+ depth: 0,
+ overrideAccess: true,
+ })
+ expect(current.politicalTrend?.status).toBe('neutra')
+ expect(current.politicalTrend?.note).toBe('segunda')
+ })
+
+ it('engagement: matching CAS writes level + allocationDecision in one transaction', async () => {
+ const fixtures = campaignFixtures()
+ const municipality = await fixtures.getMunicipality()
+ const coordinator = await fixtures.createCampaignUser('coordinator')
+
+ const parent = await payload.findByID({
+ collection: 'municipality',
+ id: municipality.id,
+ depth: 0,
+ overrideAccess: true,
+ })
+
+ const updated = await setMunicipalityEngagementLevelCasRecord(payload, coordinator, {
+ municipality: municipality.id,
+ level: 'n1',
+ note: 'Motivo CAS',
+ reversalSignals: 'Sinais de reversão',
+ triangulatedShock: false,
+ override: false,
+ baseUpdatedAt: parent.updatedAt,
+ })
+ fixtures.touchMunicipality(municipality.id)
+
+ expect(updated.engagementLevel).toBe('n1')
+
+ const decisions = await payload.find({
+ collection: 'allocationDecision',
+ where: {
+ and: [
+ { municipality: { equals: municipality.id } },
+ { patternId: { equals: ENGAGEMENT_LEVEL_PATTERN_ID } },
+ ],
+ },
+ depth: 0,
+ limit: 5,
+ sort: '-createdAt',
+ overrideAccess: true,
+ })
+ fixtures.own('allocationDecision', decisions.docs[0]!.id)
+ expect(decisions.docs[0]?.rationale).toBe('Motivo CAS')
+ expect(decisions.docs[0]?.outcome).toBe('movimento')
+ })
+
+ it('engagement: stale CAS refuses without writing a decision', async () => {
+ const fixtures = campaignFixtures()
+ const municipality = await fixtures.getMunicipality()
+ const coordinator = await fixtures.createCampaignUser('coordinator')
+
+ const first = await setMunicipalityEngagementLevelRecord(payload, coordinator, {
+ municipality: municipality.id,
+ level: 'n0',
+ note: 'Primeiro movimento',
+ reversalSignals: 'Sinais',
+ triangulatedShock: false,
+ override: false,
+ })
+ const staleBase = first.updatedAt
+
+ await setMunicipalityEngagementLevelRecord(payload, coordinator, {
+ municipality: municipality.id,
+ level: 'n1',
+ note: 'Segundo movimento',
+ reversalSignals: 'Sinais 2',
+ triangulatedShock: false,
+ override: true,
+ })
+ fixtures.touchMunicipality(municipality.id)
+
+ const beforeCount = await payload.count({
+ collection: 'allocationDecision',
+ where: {
+ and: [
+ { municipality: { equals: municipality.id } },
+ { patternId: { equals: ENGAGEMENT_LEVEL_PATTERN_ID } },
+ ],
+ },
+ overrideAccess: true,
+ })
+
+ await expect(
+ setMunicipalityEngagementLevelCasRecord(payload, coordinator, {
+ municipality: municipality.id,
+ level: 'n2',
+ note: 'Stale',
+ reversalSignals: 'x',
+ triangulatedShock: false,
+ override: true,
+ baseUpdatedAt: staleBase,
+ }),
+ ).rejects.toSatisfy((error: unknown) => {
+ expect(isOpsUpdatedAtConflictMessage((error as Error).message)).toBe(true)
+ return true
+ })
+
+ const afterCount = await payload.count({
+ collection: 'allocationDecision',
+ where: {
+ and: [
+ { municipality: { equals: municipality.id } },
+ { patternId: { equals: ENGAGEMENT_LEVEL_PATTERN_ID } },
+ ],
+ },
+ overrideAccess: true,
+ })
+ expect(afterCount.totalDocs).toBe(beforeCount.totalDocs)
+
+ const current = await payload.findByID({
+ collection: 'municipality',
+ id: municipality.id,
+ depth: 0,
+ overrideAccess: true,
+ })
+ expect(current.engagementLevel).toBe('n1')
+ })
+
+ it('advisors assignment: refuses stale baseUpdatedAt', async () => {
+ const fixtures = campaignFixtures()
+ const municipality = await fixtures.getMunicipality()
+ const coordinator = await fixtures.createCampaignUser('coordinator')
+ const advisorA = await fixtures.createCampaignUser('advisor')
+ const advisorB = await fixtures.createCampaignUser('advisor')
+
+ const first = await assignMunicipalityAdvisorsCasRecord(payload, coordinator, {
+ municipality: municipality.id,
+ advisors: [advisorA.id],
+ })
+ const staleBase = first.updatedAt
+
+ await assignMunicipalityAdvisorsCasRecord(payload, coordinator, {
+ municipality: municipality.id,
+ advisors: [advisorB.id],
+ baseUpdatedAt: first.updatedAt,
+ })
+
+ await expect(
+ assignMunicipalityAdvisorsCasRecord(payload, coordinator, {
+ municipality: municipality.id,
+ advisors: [advisorA.id, advisorB.id],
+ baseUpdatedAt: staleBase,
+ }),
+ ).rejects.toSatisfy((error: unknown) => {
+ expect(isOpsUpdatedAtConflictMessage((error as Error).message)).toBe(true)
+ return true
+ })
+ })
+
+ it('advisor membership: matching CAS toggles one advisor', async () => {
+ const fixtures = campaignFixtures()
+ const municipality = await fixtures.getMunicipality()
+ const coordinator = await fixtures.createCampaignUser('coordinator')
+ const advisor = await fixtures.createCampaignUser('advisor')
+
+ const parent = await payload.findByID({
+ collection: 'municipality',
+ id: municipality.id,
+ depth: 0,
+ overrideAccess: true,
+ })
+
+ const updated = await setMunicipalityAdvisorMembershipCasRecord(payload, coordinator, {
+ municipality: municipality.id,
+ advisor: advisor.id,
+ assigned: true,
+ baseUpdatedAt: parent.updatedAt,
+ })
+
+ expect(updated.advisors).toEqual(expect.arrayContaining([advisor.id]))
+ })
+})
diff --git a/tests/int/municipalityWritesCas.int.spec.ts b/tests/int/municipalityWritesCas.int.spec.ts
new file mode 100644
index 00000000..c7975e4d
--- /dev/null
+++ b/tests/int/municipalityWritesCas.int.spec.ts
@@ -0,0 +1,218 @@
+// @vitest-environment node
+
+import type { Payload } from 'payload'
+import { getPayload } from 'payload'
+import { beforeAll, describe, expect, it } from 'vitest'
+
+import {
+ createMunicipalityUpdateCasRecord,
+ createMunicipalityUpdateRecord,
+} from '@/app/(campaign)/campanha/actions/municipalityUpdate'
+import {
+ declareVotesCasRecord,
+ declareVotesRecord,
+} from '@/app/(campaign)/campanha/actions/votePledge'
+import {
+ isOpsUpdatedAtConflictMessage,
+ OPS_UPDATED_AT_CONFLICT_MESSAGE,
+} from '@/lib/schemas/opsCas'
+import config from '@/payload.config'
+
+import { installCampaignFixtures } from '../helpers/campaignFixtures'
+
+let payload: Payload
+const campaignFixtures = installCampaignFixtures({
+ getPayload: () => payload,
+ setPayload: (nextPayload) => {
+ payload = nextPayload
+ },
+})
+
+describe('declareVotesCas (OH10)', () => {
+ beforeAll(async () => {
+ payload = await getPayload({ config: await config })
+ })
+
+ const createLinkedLeadership = async () => {
+ const fixtures = campaignFixtures()
+ const municipality = await fixtures.getMunicipality()
+ const advisor = await fixtures.createCampaignUser('advisor')
+ await fixtures.assignMunicipalityAdvisors(municipality.id, [advisor.id])
+ const contact = await fixtures.createContact()
+ const leadership = await fixtures.createLeadership({
+ contact: contact.id,
+ municipalities: [municipality.id],
+ supportStatus: 'engajado',
+ })
+ return { fixtures, advisor, municipality, leadership }
+ }
+
+ it('writes like declareVotes when baseUpdatedAt is omitted', async () => {
+ const { advisor, municipality, leadership, fixtures } = await createLinkedLeadership()
+
+ const pledge = await declareVotesCasRecord(payload, advisor, {
+ municipality: municipality.id,
+ leadership: leadership.id,
+ declaredVotes: 40,
+ })
+ fixtures.own('votePledge', pledge.id)
+
+ expect(pledge.declaredVotes).toBe(40)
+ })
+
+ it('refuses a stale baseUpdatedAt without writing', async () => {
+ const { advisor, municipality, leadership, fixtures } = await createLinkedLeadership()
+
+ const first = await declareVotesRecord(payload, advisor, {
+ municipality: municipality.id,
+ leadership: leadership.id,
+ declaredVotes: 50,
+ })
+ fixtures.own('votePledge', first.id)
+ const baseUpdatedAt = first.updatedAt
+
+ await declareVotesRecord(payload, advisor, {
+ municipality: municipality.id,
+ leadership: leadership.id,
+ declaredVotes: 75,
+ })
+
+ await expect(
+ declareVotesCasRecord(payload, advisor, {
+ municipality: municipality.id,
+ leadership: leadership.id,
+ declaredVotes: 99,
+ baseUpdatedAt,
+ }),
+ ).rejects.toSatisfy((error: unknown) => {
+ expect(error).toBeInstanceOf(Error)
+ const message = (error as Error).message
+ expect(isOpsUpdatedAtConflictMessage(message)).toBe(true)
+ expect(message.startsWith(OPS_UPDATED_AT_CONFLICT_MESSAGE)).toBe(true)
+ return true
+ })
+
+ const current = await payload.findByID({
+ collection: 'votePledge',
+ id: first.id,
+ depth: 0,
+ overrideAccess: true,
+ })
+ expect(current.declaredVotes).toBe(75)
+ })
+
+ it('writes when baseUpdatedAt matches', async () => {
+ const { advisor, municipality, leadership, fixtures } = await createLinkedLeadership()
+
+ const first = await declareVotesRecord(payload, advisor, {
+ municipality: municipality.id,
+ leadership: leadership.id,
+ declaredVotes: 10,
+ })
+ fixtures.own('votePledge', first.id)
+
+ const updated = await declareVotesCasRecord(payload, advisor, {
+ municipality: municipality.id,
+ leadership: leadership.id,
+ declaredVotes: 22,
+ baseUpdatedAt: first.updatedAt,
+ })
+
+ expect(updated.declaredVotes).toBe(22)
+ expect(updated.updatedAt).not.toBe(first.updatedAt)
+ })
+})
+
+describe('createMunicipalityUpdateCas (OH10)', () => {
+ beforeAll(async () => {
+ payload = await getPayload({ config: await config })
+ })
+
+ it('creates when baseUpdatedAt matches the parent municipality', async () => {
+ const fixtures = campaignFixtures()
+ const municipality = await fixtures.getMunicipality()
+ const advisor = await fixtures.createCampaignUser('advisor')
+ await fixtures.assignMunicipalityAdvisors(municipality.id, [advisor.id])
+
+ const parent = await payload.findByID({
+ collection: 'municipality',
+ id: municipality.id,
+ depth: 0,
+ overrideAccess: true,
+ })
+
+ const created = await createMunicipalityUpdateCasRecord(payload, advisor, {
+ municipality: municipality.id,
+ kind: 'nota',
+ body: 'Nota CAS ok',
+ baseUpdatedAt: parent.updatedAt,
+ })
+ fixtures.own('municipalityUpdate', created.id)
+
+ expect(created.body).toBe('Nota CAS ok')
+ })
+
+ it('refuses a stale parent baseUpdatedAt without creating', async () => {
+ const fixtures = campaignFixtures()
+ const municipality = await fixtures.getMunicipality()
+ const advisor = await fixtures.createCampaignUser('advisor')
+ await fixtures.assignMunicipalityAdvisors(municipality.id, [advisor.id])
+
+ const parent = await payload.findByID({
+ collection: 'municipality',
+ id: municipality.id,
+ depth: 0,
+ overrideAccess: true,
+ })
+ const staleBase = parent.updatedAt
+
+ // Bump parent updatedAt via a strategy-adjacent field write.
+ await payload.update({
+ collection: 'municipality',
+ id: municipality.id,
+ data: { nextSteps: 'bump' },
+ depth: 0,
+ overrideAccess: true,
+ })
+
+ const beforeCount = await payload.count({
+ collection: 'municipalityUpdate',
+ where: { municipality: { equals: municipality.id } },
+ overrideAccess: true,
+ })
+
+ await expect(
+ createMunicipalityUpdateCasRecord(payload, advisor, {
+ municipality: municipality.id,
+ kind: 'nota',
+ body: 'stale',
+ baseUpdatedAt: staleBase,
+ }),
+ ).rejects.toSatisfy((error: unknown) => {
+ expect(isOpsUpdatedAtConflictMessage((error as Error).message)).toBe(true)
+ return true
+ })
+
+ const afterCount = await payload.count({
+ collection: 'municipalityUpdate',
+ where: { municipality: { equals: municipality.id } },
+ overrideAccess: true,
+ })
+ expect(afterCount.totalDocs).toBe(beforeCount.totalDocs)
+ })
+
+ it('creates like today when baseUpdatedAt is omitted', async () => {
+ const fixtures = campaignFixtures()
+ const municipality = await fixtures.getMunicipality()
+ const advisor = await fixtures.createCampaignUser('advisor')
+ await fixtures.assignMunicipalityAdvisors(municipality.id, [advisor.id])
+
+ const created = await createMunicipalityUpdateRecord(payload, advisor, {
+ municipality: municipality.id,
+ kind: 'nota',
+ body: 'LWW create',
+ })
+ fixtures.own('municipalityUpdate', created.id)
+ expect(created.body).toBe('LWW create')
+ })
+})
diff --git a/tests/unit/campaignCellEditOverlay.unit.spec.ts b/tests/unit/campaignCellEditOverlay.unit.spec.ts
index 4b2fdc50..bb106479 100644
--- a/tests/unit/campaignCellEditOverlay.unit.spec.ts
+++ b/tests/unit/campaignCellEditOverlay.unit.spec.ts
@@ -13,6 +13,14 @@ import { MunicipalityPortfolioCell } from '@/components/campaign/shared/Municipa
import { TooltipProvider } from '@/components/ui/tooltip'
import { toVoteEstimateScenarioViewModel } from '@/lib/voteEstimate'
+vi.mock('next/navigation', () => ({
+ useRouter: () => ({
+ refresh: vi.fn(),
+ push: vi.fn(),
+ replace: vi.fn(),
+ }),
+}))
+
/**
* B42: the quick-edit cells of `/campanha/municipios` share one container
* (`CampaignCellEditOverlay`) that is a Popover in the desktop table and a
diff --git a/tests/unit/campaignComponents.unit.spec.ts b/tests/unit/campaignComponents.unit.spec.ts
index 1f761b7f..3588b6ba 100644
--- a/tests/unit/campaignComponents.unit.spec.ts
+++ b/tests/unit/campaignComponents.unit.spec.ts
@@ -194,6 +194,7 @@ describe('campaign visual foundation', () => {
priority: 'alta',
lastUpdateAt: null,
lastSignalAt: null,
+ updatedAt: '2026-08-01T00:00:00.000Z',
expectedVotes: { pessimistic: null, central: 1500, optimistic: null },
politicalTrendStatus: 'favoravel',
politicalTrendNote: null,
@@ -237,6 +238,7 @@ describe('campaign visual foundation', () => {
priority: 'normal',
lastUpdateAt: null,
lastSignalAt: null,
+ updatedAt: '2026-08-01T00:00:00.000Z',
expectedVotes: toVoteEstimateScenarioViewModel(null),
politicalTrendStatus: null,
politicalTrendNote: null,
@@ -377,6 +379,7 @@ describe('campaign visual foundation', () => {
priority: 'alta',
lastUpdateAt: staleSignal,
lastSignalAt: staleSignal,
+ updatedAt: '2026-08-01T00:00:00.000Z',
expectedVotes: toVoteEstimateScenarioViewModel(null),
politicalTrendStatus: null,
politicalTrendNote: null,
@@ -421,6 +424,7 @@ describe('campaign visual foundation', () => {
priority: 'normal',
lastUpdateAt: null,
lastSignalAt: null,
+ updatedAt: '2026-08-01T00:00:00.000Z',
expectedVotes: toVoteEstimateScenarioViewModel(null),
politicalTrendStatus: null,
politicalTrendNote: null,
@@ -462,6 +466,7 @@ describe('campaign visual foundation', () => {
priority: 'normal',
lastUpdateAt: null,
lastSignalAt: null,
+ updatedAt: '2026-08-01T00:00:00.000Z',
expectedVotes: toVoteEstimateScenarioViewModel(null),
politicalTrendStatus: null,
politicalTrendNote: null,
@@ -509,6 +514,7 @@ describe('campaign visual foundation', () => {
priority: 'alta',
lastUpdateAt: null,
lastSignalAt: null,
+ updatedAt: '2026-08-01T00:00:00.000Z',
expectedVotes: toVoteEstimateScenarioViewModel(null),
politicalTrendStatus: null,
politicalTrendNote: null,
@@ -582,6 +588,7 @@ describe('campaign visual foundation', () => {
priority: 'normal' as const,
lastUpdateAt: null,
lastSignalAt: null,
+ updatedAt: '2026-08-01T00:00:00.000Z',
expectedVotes: toVoteEstimateScenarioViewModel(null),
politicalTrendStatus: null,
politicalTrendNote: null,
diff --git a/tests/unit/municipalityDetailLocalViews.unit.spec.ts b/tests/unit/municipalityDetailLocalViews.unit.spec.ts
index 248f8be5..6f3ab998 100644
--- a/tests/unit/municipalityDetailLocalViews.unit.spec.ts
+++ b/tests/unit/municipalityDetailLocalViews.unit.spec.ts
@@ -89,6 +89,7 @@ describe('municipalityDetailLocalViews (OH9)', () => {
declaredVotes: 120,
estimatedVotes: { pessimistic: 80, central: 100, optimistic: 130 },
estimateNote: 'Campo',
+ updatedAt: '2026-07-21T00:00:00.000Z',
})
})
})
diff --git a/tests/unit/opsUpdatedAtCas.unit.spec.ts b/tests/unit/opsUpdatedAtCas.unit.spec.ts
new file mode 100644
index 00000000..08c9c24e
--- /dev/null
+++ b/tests/unit/opsUpdatedAtCas.unit.spec.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from 'vitest'
+
+import {
+ assertOpsUpdatedAtCas,
+ isOpsUpdatedAtConflictMessage,
+ OPS_UPDATED_AT_CONFLICT_MESSAGE,
+ opsUpdatedAtConflictError,
+ parseOpsUpdatedAtConflictServerUpdatedAt,
+} from '@/lib/schemas/opsCas'
+
+describe('opsUpdatedAtCas helpers (OH10)', () => {
+ it('round-trips a stamped server updatedAt through the error message', () => {
+ const stamped = opsUpdatedAtConflictError('2026-08-01T12:00:00.000Z')
+ expect(isOpsUpdatedAtConflictMessage(stamped.message)).toBe(true)
+ expect(parseOpsUpdatedAtConflictServerUpdatedAt(stamped.message)).toBe(
+ '2026-08-01T12:00:00.000Z',
+ )
+ })
+
+ it('keeps the bare conflict message exact for safeMessages matching', () => {
+ expect(OPS_UPDATED_AT_CONFLICT_MESSAGE.length).toBeGreaterThan(10)
+ expect(isOpsUpdatedAtConflictMessage(OPS_UPDATED_AT_CONFLICT_MESSAGE)).toBe(true)
+ expect(parseOpsUpdatedAtConflictServerUpdatedAt(OPS_UPDATED_AT_CONFLICT_MESSAGE)).toBeNull()
+ })
+
+ it('rejects unrelated messages', () => {
+ expect(isOpsUpdatedAtConflictMessage('outro erro')).toBe(false)
+ expect(parseOpsUpdatedAtConflictServerUpdatedAt('outro erro')).toBeNull()
+ })
+
+ it('assertOpsUpdatedAtCas is a no-op without enforce or base', () => {
+ expect(() => assertOpsUpdatedAtCas(false, '2026-08-01T12:00:00.000Z', 'other')).not.toThrow()
+ expect(() => assertOpsUpdatedAtCas(true, undefined, 'other')).not.toThrow()
+ })
+
+ it('assertOpsUpdatedAtCas refuses a stale base', () => {
+ expect(() =>
+ assertOpsUpdatedAtCas(true, '2026-08-01T12:00:00.000Z', '2026-08-01T13:00:00.000Z'),
+ ).toThrow(Error)
+ })
+
+ it('assertOpsUpdatedAtCas allows a matching base', () => {
+ expect(() =>
+ assertOpsUpdatedAtCas(true, '2026-08-01T12:00:00.000Z', '2026-08-01T12:00:00.000Z'),
+ ).not.toThrow()
+ })
+})