OH10: municipality staff writes CAS + offline outbox

Add baseUpdatedAt CAS for declareVotes, municipalityUpdate, political
trend, engagement level, and advisors. Sibling outbox executor wires
hybrid controls when OPS_HYBRID is on; flag OFF keeps legacy paths.

Co-authored-by: Francisco Solla <fsolla@users.noreply.github.com>
This commit is contained in:
Cursor Agent 2026-08-02 01:33:58 +00:00
parent bb4741e4f5
commit a517638e3c
No known key found for this signature in database
33 changed files with 1974 additions and 26 deletions

View file

@ -4,6 +4,8 @@ Conteúdo movido do `AGENTS.md` em 2026-07-30 (fatiamento do paradigma de agente
---
**Recently resolved (2026-08-02):** **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).

View file

@ -1,7 +1,7 @@
# OH10 — Writes municipality staff CAS: update, declareVotes, tendência, engagement, advisors
Status: rascunho
Atualizado em: 2026-08-01
Status: em implementação
Atualizado em: 2026-08-02
Issue: #171
Priority: P1
Model: cursor-grok-4.5-medium
@ -10,13 +10,20 @@ Appetite: ~2–3 dias eng
Depends: OH7, OH9
Responsável: —
## 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

View file

@ -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 ({
<div className="flex flex-col gap-6">
<MunicipalityUpdateForm
municipalityID={municipalityID}
municipalityUpdatedAt={municipalityUpdatedAt}
formAction={createMunicipalityUpdateFormAction}
/>
<MunicipalityUpdateFeed updates={feed.updates} />

View file

@ -118,6 +118,7 @@ export default async function MunicipalityDetailPage({
<UpdatesTab
municipalityID={view.id}
municipalitySlug={view.slug}
municipalityUpdatedAt={view.updatedAt}
rawSearchParams={rawSearchParams}
payloadUser={{ payload, user }}
/>

View file

@ -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 }) => {

View file

@ -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

View file

@ -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,24 @@ 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 +119,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 +174,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 +198,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 +263,26 @@ 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 +296,18 @@ export const assignMunicipalityAdvisorsRecord = async (
await acquireTextAdvisoryLocks(payload, req, [`municipality-advisors:${municipality}`])
if (enforceCas && baseUpdatedAt !== undefined) {
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 +328,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 +354,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 +376,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 +409,16 @@ export const setMunicipalityAdvisorMembership = async (
const { payload, actor } = await getCampaignActionContext()
return setMunicipalityAdvisorMembershipRecord(payload, actor, input)
}
export const setMunicipalityAdvisorMembershipCas = async (
input: MunicipalityAdvisorMembershipInput,
) => {
const { payload, actor } = await getCampaignActionContext()
return setMunicipalityAdvisorMembershipRecord(payload, actor, input, { cas: true })
}
export const setMunicipalityAdvisorMembershipCasRecord = async (
payload: Payload,
actor: CampaignUser,
input: MunicipalityAdvisorMembershipInput,
) => setMunicipalityAdvisorMembershipRecord(payload, actor, input, { cas: true })

View file

@ -2,6 +2,7 @@
import type { Payload } from 'payload'
import { assertOpsUpdatedAtCas } from '@/lib/schemas/opsCas'
import {
municipalityUpdateCreateSchema,
type MunicipalityUpdateCreateInput,
@ -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 })

View file

@ -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,

View file

@ -82,6 +82,7 @@ export const MunicipalityLeadershipsPanel = ({
municipalityID={municipalityID}
leadershipID={leadership.id}
currentDeclaredVotes={pledge?.declaredVotes ?? null}
currentUpdatedAt={pledge?.updatedAt ?? null}
formAction={declareFormAction}
/>
</li>

View file

@ -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"
/>
),

View file

@ -14,11 +14,13 @@ import {
type CampaignCellEditOverlayVariant,
} from '@/components/campaign/shared/CampaignCellEditOverlay'
import { useCampaignCellFailureChannel } from '@/components/campaign/shared/useCampaignCellFailureChannel'
import { enqueueAdvisorsAssignment } from '@/components/campaign/opsSync/opsMunicipalityOutbox'
import { Alert, AlertDescription } from '@/components/ui/Alert'
import { Badge } from '@/components/ui/Badge'
import { Command, CommandInput, CommandItem, CommandList } from '@/components/ui/Command'
import { Spinner } from '@/components/ui/Spinner'
import { postCampaignJson } from '@/lib/campaignJsonRequest'
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
import { sameIdSet } from '@/lib/sameIdSet'
import { cn } from '@/lib/utils'
import { matchesAtWordStart } from '@/lib/wordStartFilter'
@ -38,6 +40,8 @@ type MunicipalityListAdvisorsControlProps = {
isPriority: boolean
advisorNamesById: ReadonlyMap<number, MunicipalityAdvisorSummary>
options: EligibleAdvisorOption[]
/** OH10 — CAS base when OPS_HYBRID outbox path is on. */
updatedAt?: string
variant: CampaignCellEditOverlayVariant
}
@ -48,6 +52,7 @@ export const MunicipalityListAdvisorsControl = ({
isPriority,
advisorNamesById,
options,
updatedAt,
variant,
}: MunicipalityListAdvisorsControlProps) => {
const [open, setOpen] = useState(false)
@ -122,11 +127,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 +164,19 @@ export const MunicipalityListAdvisorsControl = ({
}
try {
if (resolveOpsHybridEnabled()) {
await enqueueAdvisorsAssignment({
municipalityId: municipalityID,
advisors: nextIds,
baseUpdatedAt: updatedAt,
})
if (requestSeq > (latestConfirmedRef.current?.seq ?? 0)) {
latestConfirmedRef.current = { seq: requestSeq, advisors: nextIds }
}
finishRequest()
return
}
const { ok, payload } = await postCampaignJson<MunicipalityListAdvisorsResponse>(
ADVISORS_ENDPOINT,
{ municipalityId: municipalityID, advisorId, assigned },

View file

@ -9,6 +9,7 @@ import {
type CampaignCellEditOverlayVariant,
} from '@/components/campaign/shared/CampaignCellEditOverlay'
import { useCampaignCellFailureChannel } from '@/components/campaign/shared/useCampaignCellFailureChannel'
import { enqueueEngagementLevel } from '@/components/campaign/opsSync/opsMunicipalityOutbox'
import { Alert, AlertDescription } from '@/components/ui/Alert'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/Checkbox'
@ -17,6 +18,7 @@ import { NativeSelect, NativeSelectOption } from '@/components/ui/native-select'
import { Spinner } from '@/components/ui/Spinner'
import { Textarea } from '@/components/ui/textarea'
import { postCampaignJson } from '@/lib/campaignJsonRequest'
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
import {
EMPTY_ENGAGEMENT_LEVEL_LABEL,
ENGAGEMENT_LEVEL_RULES,
@ -39,6 +41,8 @@ type MunicipalityListLevelControlProps = {
level: EngagementLevel | null
levelNote: string | null
levelChangedAt: string | null
/** OH10 — CAS base when OPS_HYBRID outbox path is on. */
updatedAt?: string
variant: CampaignCellEditOverlayVariant
}
@ -54,6 +58,7 @@ export const MunicipalityListLevelControl = ({
level,
levelNote,
levelChangedAt,
updatedAt,
variant,
}: MunicipalityListLevelControlProps) => {
const [open, setOpen] = useState(false)
@ -164,6 +169,25 @@ export const MunicipalityListLevelControl = ({
setServerBlock(null)
try {
if (resolveOpsHybridEnabled()) {
await enqueueEngagementLevel({
municipalityId: municipalityID,
level: draftLevel,
note,
reversalSignals,
triangulatedShock,
override,
baseUpdatedAt: 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.

View file

@ -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"
/>
</dd>
@ -186,6 +188,7 @@ export const MunicipalityListMobileCards = ({
isPriority={isPriority}
advisorNamesById={advisorNamesById}
options={advisorOptions}
updatedAt={municipality.updatedAt}
variant="sheet"
/>
) : names.length ? (

View file

@ -11,12 +11,14 @@ import {
type CampaignCellEditOverlayVariant,
} from '@/components/campaign/shared/CampaignCellEditOverlay'
import { useCampaignCellAutosave } from '@/components/campaign/shared/useCampaignCellAutosave'
import { enqueuePoliticalTrend } from '@/components/campaign/opsSync/opsMunicipalityOutbox'
import { Alert, AlertDescription } from '@/components/ui/Alert'
import { Badge } from '@/components/ui/Badge'
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 +46,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 +56,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 +79,24 @@ export const MunicipalityListTrendControl = ({
readSaved: (payload) => payload.savedTrend,
errorMessage: SAVE_ERROR_MESSAGE,
pendingMessage: 'Salvando tendência.',
persist: opsHybrid
? async (trend) => {
await enqueuePoliticalTrend({
municipalityId: municipalityID,
status: trend.status,
note: trend.note,
baseUpdatedAt: 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

View file

@ -1,20 +1,24 @@
'use client'
import { useActionState, useState } from 'react'
import { useActionState, useState, type FormEvent } from 'react'
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 +26,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 +37,78 @@ type MunicipalityUpdateFormProps = {
export const MunicipalityUpdateForm = ({
municipalityID,
municipalityUpdatedAt,
opsHybridEnabled = resolveOpsHybridEnabled(),
formAction,
}: MunicipalityUpdateFormProps) => {
const [state, submitAction, isPending] = useActionState(formAction, {})
const [kind, setKind] = useState<MunicipalityUpdateKind>('semanal')
const [hybridPending, setHybridPending] = useState(false)
const [hybridMessage, setHybridMessage] = useState<string | null>(null)
const onHybridSubmit = (event: FormEvent<HTMLFormElement>) => {
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)
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: 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 (
<form action={submitAction} className="flex flex-col gap-4 rounded-xl border p-4">
<h3 className="text-base font-medium">Registrar atualização</h3>
<form
action={opsHybridEnabled ? undefined : submitAction}
onSubmit={opsHybridEnabled ? onHybridSubmit : undefined}
className="flex flex-col gap-4 rounded-xl border p-4"
>
<div className="flex flex-wrap items-center gap-2">
<h3 className="text-base font-medium">Registrar atualização</h3>
{hybridPending ? <Badge variant="estimate-pending">Pendente</Badge> : null}
</div>
<input type="hidden" name="municipalityId" value={municipalityID} />
<Field>
<FieldLabel htmlFor="municipality-update-kind">Tipo</FieldLabel>
@ -149,9 +220,15 @@ export const MunicipalityUpdateForm = ({
) : null}
</>
)}
<CampaignFormActionMessage state={state} successFallbackMessage="Atualização registrada." />
<Button type="submit" disabled={isPending} className="min-h-11 self-start">
{isPending ? <Spinner data-icon="inline-start" aria-hidden="true" /> : null}
{!opsHybridEnabled ? (
<CampaignFormActionMessage state={state} successFallbackMessage="Atualização registrada." />
) : hybridMessage ? (
<p className="text-sm text-muted-foreground" aria-live="polite">
{hybridMessage}
</p>
) : null}
<Button type="submit" disabled={pending} className="min-h-11 self-start">
{pending ? <Spinner data-icon="inline-start" aria-hidden="true" /> : null}
Registrar atualização
</Button>
</form>

View file

@ -3,6 +3,7 @@
import { createCollection, localOnlyCollectionOptions } from '@tanstack/db'
import { collectOpsEstimateOutboxKeys } from '@/components/campaign/opsSync/opsEstimateOutbox'
import { collectOpsMunicipalityOutboxKeys } from '@/components/campaign/opsSync/opsMunicipalityOutbox'
import {
openOpsMirrorStore,
type OpsMirrorPersistenceMode,
@ -47,6 +48,8 @@ const municipalityUpdatesCollection = createRowCollection<OpsMunicipalityUpdate>
'ops-municipality-updates',
)
export { municipalityUpdatesCollection }
let goalsMirror: OpsGoals | null = null
let revisedAtMirror: string = new Date(0).toISOString()
let schemaVersionMirror: number = OPS_MIRROR_SCHEMA_VERSION
@ -123,7 +126,9 @@ export const resetOpsMirrorClientForTests = async (): Promise<void> => {
const resolveOutboxKeys = (explicit?: ReadonlySet<OpsOutboxKey>): ReadonlySet<OpsOutboxKey> => {
if (explicit) return explicit
return collectOpsEstimateOutboxKeys()
const keys = collectOpsEstimateOutboxKeys()
for (const key of collectOpsMunicipalityOutboxKeys()) keys.add(key)
return keys
}
const persistMirrorSnapshot = async (

View file

@ -0,0 +1,669 @@
'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 type { EngagementLevel } from '@/lib/engagementLevel'
import { opsOutboxKey, type OpsOutboxKey } from '@/lib/campaignOps/opsContract'
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<OpsDeclareVotesOutboxRow, string>({
id: 'ops-declare-votes-outbox',
getKey: (row) => row.id,
}),
)
const municipalityUpdateOutboxCollection = createCollection(
localOnlyCollectionOptions<OpsMunicipalityUpdateOutboxRow, string>({
id: 'ops-municipality-update-outbox',
getKey: (row) => row.id,
}),
)
const politicalTrendOutboxCollection = createCollection(
localOnlyCollectionOptions<OpsPoliticalTrendOutboxRow, number>({
id: 'ops-political-trend-outbox',
getKey: (row) => row.municipalityId,
}),
)
const engagementLevelOutboxCollection = createCollection(
localOnlyCollectionOptions<OpsEngagementLevelOutboxRow, number>({
id: 'ops-engagement-level-outbox',
getKey: (row) => row.municipalityId,
}),
)
const advisorsOutboxCollection = createCollection(
localOnlyCollectionOptions<OpsAdvisorsOutboxRow, number>({
id: 'ops-advisors-outbox',
getKey: (row) => row.municipalityId,
}),
)
let executorSingleton: OfflineExecutor | null = null
let initPromise: Promise<OfflineExecutor> | null = null
const collapseAllMunicipalityOutbox = (
transactions: Parameters<typeof collapseDeclareVotesOutbox>[0],
) => {
const byFn = new Map<string, typeof transactions>()
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<OfflineExecutor> => {
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
baseUpdatedAt?: string | null
}): Promise<void> => {
const executor = await getOpsMunicipalityOfflineExecutor()
const id = declareVotesOutboxKey(input.leadershipId, input.municipalityId)
const mirrorPledge = votePledgesCollection.toArray.find(
(row) => row.leadership === input.leadershipId && row.municipality === input.municipalityId,
)
const baseUpdatedAt =
input.baseUpdatedAt !== undefined ? input.baseUpdatedAt : (mirrorPledge?.updatedAt ?? null)
const run = executor.createOfflineAction<typeof input>({
mutationFnName: DECLARE_MUTATION_FN,
metadata: { declareKey: id },
onMutate: (variables) => {
const next: OpsDeclareVotesOutboxRow = {
id,
municipalityId: variables.municipalityId,
leadershipId: variables.leadershipId,
declaredVotes: variables.declaredVotes,
baseUpdatedAt: variables.baseUpdatedAt ?? baseUpdatedAt,
status: 'pending',
}
if (mirrorPledge && votePledgesCollection.has(mirrorPledge.id)) {
votePledgesCollection.update(mirrorPledge.id, (draft) => {
draft.declaredVotes = variables.declaredVotes
})
}
if (declareVotesOutboxCollection.has(id)) {
declareVotesOutboxCollection.update(id, (draft) => {
draft.declaredVotes = next.declaredVotes
draft.baseUpdatedAt = next.baseUpdatedAt
draft.status = 'pending'
draft.serverUpdatedAt = undefined
draft.errorMessage = undefined
})
} else {
declareVotesOutboxCollection.insert(next)
}
},
})
run({ ...input, baseUpdatedAt })
}
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<void> => {
const executor = await getOpsMunicipalityOfflineExecutor()
const run = executor.createOfflineAction<typeof input>({
mutationFnName: MUNICIPALITY_UPDATE_MUTATION_FN,
metadata: { clientId: input.clientId },
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<void> => {
const executor = await getOpsMunicipalityOfflineExecutor()
const run = executor.createOfflineAction<typeof input>({
mutationFnName: TREND_MUTATION_FN,
metadata: { municipalityId: input.municipalityId },
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<void> => {
const executor = await getOpsMunicipalityOfflineExecutor()
const run = executor.createOfflineAction<typeof input>({
mutationFnName: ENGAGEMENT_MUTATION_FN,
metadata: { municipalityId: input.municipalityId },
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<void> => {
const executor = await getOpsMunicipalityOfflineExecutor()
const run = executor.createOfflineAction<typeof input>({
mutationFnName: ADVISORS_MUTATION_FN,
metadata: { municipalityId: input.municipalityId },
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<OpsOutboxKey> => {
const keys = new Set<OpsOutboxKey>()
for (const row of declareVotesOutboxCollection.toArray) {
if (row.status === 'pending' || row.status === 'conflict') {
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 readOpsPoliticalTrendOutboxRow = (
municipalityId: number,
): OpsPoliticalTrendOutboxRow | undefined => politicalTrendOutboxCollection.get(municipalityId)
export const subscribeOpsPoliticalTrendOutboxRow = (
municipalityId: number,
onStoreChange: () => void,
): (() => void) => {
let previous = politicalTrendOutboxCollection.get(municipalityId)
const subscription = politicalTrendOutboxCollection.subscribeChanges(() => {
const next = politicalTrendOutboxCollection.get(municipalityId)
if (next === previous) return
previous = next
onStoreChange()
})
return () => subscription.unsubscribe()
}
export const discardOpsPoliticalTrendOutboxRow = (municipalityId: number): void => {
if (politicalTrendOutboxCollection.has(municipalityId)) {
politicalTrendOutboxCollection.delete(municipalityId)
}
}
export const readOpsEngagementLevelOutboxRow = (
municipalityId: number,
): OpsEngagementLevelOutboxRow | undefined => engagementLevelOutboxCollection.get(municipalityId)
export const discardOpsEngagementLevelOutboxRow = (municipalityId: number): void => {
if (engagementLevelOutboxCollection.has(municipalityId)) {
engagementLevelOutboxCollection.delete(municipalityId)
}
}
export const readOpsAdvisorsOutboxRow = (
municipalityId: number,
): OpsAdvisorsOutboxRow | undefined => advisorsOutboxCollection.get(municipalityId)
export const discardOpsAdvisorsOutboxRow = (municipalityId: number): void => {
if (advisorsOutboxCollection.has(municipalityId)) {
advisorsOutboxCollection.delete(municipalityId)
}
}

View file

@ -0,0 +1,118 @@
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
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<string, OfflineTransaction>()
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}`

View file

@ -23,6 +23,14 @@ type UseCampaignCellAutosaveOptions<TValue, TResponse extends CampaignCellAutosa
errorMessage: string
/** Announced while a save is in flight, e.g. "Salvando tendência." */
pendingMessage: string
/**
* OH10 — optional persist path (outbox). When set, replaces the JSON POST.
* Must resolve a success-shaped payload so `readSaved` can adopt the value.
*/
persist?: (
value: TValue,
signal: AbortSignal,
) => Promise<{ ok: boolean; payload: TResponse }>
}
/**
@ -140,11 +148,13 @@ export const useCampaignCellAutosave = <TValue, TResponse extends CampaignCellAu
}
try {
const { ok, payload } = await postCampaignJson<TResponse>(
current.endpoint,
current.buildBody(next),
controller.signal,
)
const { ok, payload } = current.persist
? await current.persist(next, controller.signal)
: await postCampaignJson<TResponse>(
current.endpoint,
current.buildBody(next),
controller.signal,
)
if (generation !== saveGenerationRef.current) return

View file

@ -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'
@ -15,18 +40,59 @@ type DeclareVotesFormProps = {
/** Present when staff declare on behalf of a leadership. */
leadershipID?: 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<CampaignFormActionState>
}
const syncStatusLabel: Record<OpsMunicipalityWriteSyncStatus, string> = {
pending: 'Pendente',
synced: 'Sincronizado',
conflict: 'Conflito',
error: 'Erro',
}
const CONFLICT_TOAST_ID_PREFIX = 'ops-declare-conflict:'
export const DeclareVotesForm = ({
municipalityID,
leadershipID,
currentDeclaredVotes,
currentUpdatedAt = null,
opsHybridEnabled = resolveOpsHybridEnabled(),
formAction,
}: DeclareVotesFormProps) => {
if (!opsHybridEnabled || leadershipID === undefined) {
return (
<LegacyDeclareVotesForm
municipalityID={municipalityID}
leadershipID={leadershipID}
currentDeclaredVotes={currentDeclaredVotes}
formAction={formAction}
/>
)
}
return (
<HybridDeclareVotesForm
municipalityID={municipalityID}
leadershipID={leadershipID}
currentDeclaredVotes={currentDeclaredVotes}
currentUpdatedAt={currentUpdatedAt}
/>
)
}
const LegacyDeclareVotesForm = ({
municipalityID,
leadershipID,
currentDeclaredVotes,
formAction,
}: Omit<DeclareVotesFormProps, 'opsHybridEnabled' | 'currentUpdatedAt'>) => {
const [state, submitAction, isPending] = useActionState(formAction, {})
return (
@ -66,3 +132,179 @@ export const DeclareVotesForm = ({
</form>
)
}
const HybridDeclareVotesForm = ({
municipalityID,
leadershipID,
currentDeclaredVotes,
currentUpdatedAt,
}: {
municipalityID: number
leadershipID: number
currentDeclaredVotes: number | null
currentUpdatedAt: string | null
}) => {
const router = useRouter()
const liveRegionId = useId()
const formRef = useRef<HTMLFormElement>(null)
const previousStatusRef = useRef<OpsMunicipalityWriteSyncStatus | undefined>(undefined)
const [isSubmitting, setIsSubmitting] = useState(false)
const [formError, setFormError] = useState<string | null>(null)
const [baseOverride, setBaseOverride] = useState<string | null | undefined>(undefined)
const mirrorPledge = useSyncExternalStore(
(onStoreChange) => {
const pledge = votePledgesCollection.toArray.find(
(row) => row.leadership === leadershipID && row.municipality === municipalityID,
)
if (!pledge) return () => undefined
return subscribeOpsVotePledge(pledge.id, onStoreChange)
},
() =>
votePledgesCollection.toArray.find(
(row) => row.leadership === leadershipID && row.municipality === municipalityID,
),
() => undefined,
)
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,
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, router])
const onSubmit = (event: FormEvent<HTMLFormElement>) => {
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,
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 (
<form ref={formRef} onSubmit={onSubmit} className="flex flex-col gap-3">
<Field>
<FieldLabel htmlFor={`declare-votes-${municipalityID}-${leadershipID}`}>
Quantos votos a liderança traz neste município?
</FieldLabel>
<div className="flex flex-wrap items-center gap-2">
<Input
id={`declare-votes-${municipalityID}-${leadershipID}`}
name="declaredVotes"
type="number"
min={0}
max={1000000}
required
inputMode="numeric"
defaultValue={displayVotes ?? undefined}
className="min-h-11 w-36"
/>
<Button type="submit" disabled={pending} className="min-h-11">
{pending ? <Spinner data-icon="inline-start" aria-hidden="true" /> : null}
{displayVotes == null ? 'Declarar' : 'Atualizar'}
</Button>
{status && status !== 'synced' ? (
<Badge variant={status === 'pending' ? 'estimate-pending' : 'destructive'}>
{syncStatusLabel[status]}
</Badge>
) : null}
</div>
{formError || outboxRow?.errorMessage ? (
<FieldError>{formError ?? outboxRow?.errorMessage}</FieldError>
) : null}
</Field>
<p id={liveRegionId} className="sr-only" aria-live="polite">
{pending ? 'Salvando declaração…' : null}
</p>
</form>
)
}

View file

@ -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'))

View file

@ -1,6 +1,7 @@
import { z } from 'zod'
import { ENGAGEMENT_LEVEL_TEXT_MAX_LENGTH, engagementLevels } from '@/lib/engagementLevel'
import { optionalBaseUpdatedAtSchema, OPS_UPDATED_AT_CONFLICT_MESSAGE } 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,21 @@ 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
export const MUNICIPALITY_POLITICAL_TREND_SAFE_MESSAGES = [
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,11 +119,15 @@ 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({
municipality: positiveRelationshipId,
expectedVotes: voteEstimateScenarioFieldsSchema,
/** OH10 CAS opt-in on municipality `updatedAt`. Absent → last-write-wins. */
baseUpdatedAt: optionalBaseUpdatedAtSchema,
})
export type MunicipalityStrategyUpdateInput = z.input<typeof municipalityStrategyUpdateSchema>

View file

@ -1,5 +1,6 @@
import { z } from 'zod'
import { optionalBaseUpdatedAtSchema, OPS_UPDATED_AT_CONFLICT_MESSAGE } 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') {
@ -101,4 +107,8 @@ export const municipalityUpdateCreateSchema = z
}
})
export const MUNICIPALITY_UPDATE_CREATE_SAFE_MESSAGES = [
OPS_UPDATED_AT_CONFLICT_MESSAGE,
] as const
export type MunicipalityUpdateCreateInput = z.input<typeof municipalityUpdateCreateSchema>

38
src/lib/schemas/opsCas.ts Normal file
View file

@ -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)
}
}

View file

@ -1,5 +1,6 @@
import { z } from 'zod'
import { optionalBaseUpdatedAtSchema, OPS_UPDATED_AT_CONFLICT_MESSAGE } 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 = [

View file

@ -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

View file

@ -139,5 +139,6 @@ export const loadMunicipalityPledges = async (
estimatedVotes: toVoteEstimateScenarioViewModel(pledge.estimatedVotes),
estimateNote: pledge.estimateNote ?? null,
estimatedAt: pledge.estimatedAt ?? null,
updatedAt: pledge.updatedAt,
}))
}

View file

@ -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
}

View file

@ -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]))
})
})

View file

@ -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')
})
})

View file

@ -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',
})
})
})

View file

@ -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()
})
})