OH7 — estimativas ligadas ao mirror completo

- HybridPledgeEstimateForm lê valores de votePledgesCollection (não props RSC)
- Outbox faz patch optimista no mirror e aplica write do servidor com estimatedAt
- Helpers read/subscribe/patch no opsMirrorClient + mapper mapVotePledgeWriteToOps
- Testes unitários para merge protegido, patch optimista e mapper de write

Co-authored-by: Francisco Solla <fsolla@users.noreply.github.com>
This commit is contained in:
Cursor Agent 2026-08-02 00:45:32 +00:00
parent 891f654655
commit 8fd5838914
No known key found for this signature in database
6 changed files with 213 additions and 25 deletions

View file

@ -15,6 +15,11 @@ import {
type EnqueueEstimateVotesInput,
type OpsEstimateOutboxRow,
} from '@/components/campaign/opsSync/opsEstimateOutboxModel'
import {
applyOpsVotePledgeEstimateWrite,
patchOpsVotePledgeEstimateOptimistic,
readOpsVotePledge,
} from '@/components/campaign/opsSync/opsMirrorClient'
import { opsOutboxKey, type OpsOutboxKey } from '@/lib/campaignOps/opsContract'
import {
isOpsEstimateConflictMessage,
@ -48,16 +53,18 @@ const createEstimateOfflineExecutor = (): OfflineExecutor =>
const row = mutation.modified as OpsEstimateOutboxRow
try {
await estimateVotesCas({
const updated = await estimateVotesCas({
pledge: row.pledgeId,
estimatedVotes: row.estimatedVotes,
estimateNote: row.estimateNote,
baseEstimatedAt: row.baseEstimatedAt,
})
applyOpsVotePledgeEstimateWrite(updated)
opsEstimateOutboxCollection.utils.acceptMutations(transaction)
if (opsEstimateOutboxCollection.has(row.pledgeId)) {
// Drop the local row so RSC props win after refresh (OH7 will
// patch the mirror instead of keeping a synced stub).
opsEstimateOutboxCollection.update(row.pledgeId, (draft) => {
draft.status = 'synced'
})
opsEstimateOutboxCollection.delete(row.pledgeId)
}
} catch (error) {
@ -86,6 +93,15 @@ const createEstimateOfflineExecutor = (): OfflineExecutor =>
},
})
/** Test/DI seam — reset module singletons between unit cases. */
export const resetOpsEstimateOutboxForTests = (): void => {
for (const key of [...opsEstimateOutboxCollection.keys()]) {
opsEstimateOutboxCollection.delete(key)
}
executorSingleton = null
initPromise = null
}
export const getOpsEstimateOfflineExecutor = async (): Promise<OfflineExecutor> => {
if (executorSingleton) {
await executorSingleton.waitForInit()
@ -110,7 +126,20 @@ export const enqueueEstimateVotes = async (input: EnqueueEstimateVotesInput): Pr
const run = executor.createOfflineAction<EnqueueEstimateVotesInput>({
mutationFnName: ESTIMATE_MUTATION_FN,
onMutate: (variables) => {
const next = toOpsEstimateOutboxRow(variables, 'pending')
const mirrorRow = readOpsVotePledge(variables.pledge)
const baseEstimatedAt =
variables.baseEstimatedAt !== undefined
? variables.baseEstimatedAt
: (mirrorRow?.estimatedAt ?? null)
const next = toOpsEstimateOutboxRow(
{ ...variables, baseEstimatedAt },
'pending',
)
patchOpsVotePledgeEstimateOptimistic(
next.pledgeId,
next.estimatedVotes,
next.estimateNote,
)
if (opsEstimateOutboxCollection.has(next.pledgeId)) {
opsEstimateOutboxCollection.update(next.pledgeId, (draft) => {
draft.estimatedVotes = next.estimatedVotes

View file

@ -22,9 +22,14 @@ import {
type OpsStateDeputy,
type OpsVotePledge,
} from '@/lib/campaignOps/opsContract'
import {
mapVotePledgeWriteToOps,
type VotePledgeEstimateWriteResult,
} from '@/lib/campaignOps/mapVotePledgeWriteToOps'
import { mergeOpsSnapshot } from '@/lib/campaignOps/opsMerge'
import { OPS_MIRROR_SCHEMA_VERSION } from '@/lib/campaignOps/opsMirrorVersion'
import type { OpsSyncState } from '@/lib/campaignOps/opsSyncMeta'
import type { VoteEstimateScenarioViewModel } from '@/lib/voteEstimate'
export const OPS_SYNC_PATH = '/campanha/api/ops-sync'
@ -256,3 +261,51 @@ export const syncOpsMirror = async (options: SyncOpsMirrorOptions = {}): Promise
}
}
}
export const readOpsVotePledge = (pledgeId: number): OpsVotePledge | undefined =>
votePledgesCollection.get(pledgeId)
export const subscribeOpsVotePledge = (
pledgeId: number,
onStoreChange: () => void,
): (() => void) => {
let previous = votePledgesCollection.get(pledgeId)
const subscription = votePledgesCollection.subscribeChanges(() => {
const next = votePledgesCollection.get(pledgeId)
if (next === previous) return
previous = next
onStoreChange()
})
return () => {
subscription.unsubscribe()
}
}
/** Optimistic estimate patch while the outbox row is pending. */
export const patchOpsVotePledgeEstimateOptimistic = (
pledgeId: number,
estimatedVotes: VoteEstimateScenarioViewModel,
estimateNote: string | null,
): void => {
if (!votePledgesCollection.has(pledgeId)) return
votePledgesCollection.update(pledgeId, (draft) => {
draft.estimatedVotes = estimatedVotes
draft.estimateNote = estimateNote
})
}
/** Authoritative patch after a successful server write (OH7). */
export const applyOpsVotePledgeEstimateWrite = (doc: VotePledgeEstimateWriteResult): void => {
const mapped = mapVotePledgeWriteToOps(doc)
if (votePledgesCollection.has(mapped.id)) {
votePledgesCollection.update(mapped.id, (draft) => {
draft.estimatedVotes = mapped.estimatedVotes
draft.estimateNote = mapped.estimateNote
draft.estimatedAt = mapped.estimatedAt
draft.estimatedBy = mapped.estimatedBy
draft.updatedAt = mapped.updatedAt
})
return
}
votePledgesCollection.insert(mapped)
}

View file

@ -20,6 +20,10 @@ import {
subscribeOpsEstimateOutboxRow,
} from '@/components/campaign/opsSync/opsEstimateOutbox'
import type { OpsEstimateSyncStatus } from '@/components/campaign/opsSync/opsEstimateOutboxModel'
import {
readOpsVotePledge,
subscribeOpsVotePledge,
} from '@/components/campaign/opsSync/opsMirrorClient'
import { CampaignFormActionMessage } from '@/components/campaign/shared/CampaignFormActionMessage'
import { VoteEstimateScenarioInputs } from '@/components/campaign/votePledge/VoteEstimateScenarioInputs'
import { Badge } from '@/components/ui/Badge'
@ -87,7 +91,7 @@ export const PledgeEstimateForm = ({
pledgeID,
currentEstimatedVotes,
currentEstimateNote,
currentEstimatedAt,
currentEstimatedAt: _currentEstimatedAt,
opsHybridEnabled,
formAction,
}: PledgeEstimateFormProps) => {
@ -105,9 +109,6 @@ export const PledgeEstimateForm = ({
return (
<HybridPledgeEstimateForm
pledgeID={pledgeID}
currentEstimatedVotes={currentEstimatedVotes}
currentEstimateNote={currentEstimateNote}
currentEstimatedAt={currentEstimatedAt}
/>
)
}
@ -165,26 +166,26 @@ const LegacyPledgeEstimateForm = ({
)
}
const HybridPledgeEstimateForm = ({
pledgeID,
currentEstimatedVotes,
currentEstimateNote,
currentEstimatedAt,
}: {
pledgeID: number
currentEstimatedVotes: VoteEstimateScenarioViewModel
currentEstimateNote: string | null
currentEstimatedAt: string | null
}) => {
const HybridPledgeEstimateForm = ({ pledgeID }: { pledgeID: number }) => {
const router = useRouter()
const liveRegionId = useId()
const formRef = useRef<HTMLFormElement>(null)
const previousStatusRef = useRef<OpsEstimateSyncStatus | undefined>(undefined)
const [isSubmitting, setIsSubmitting] = useState(false)
const [formError, setFormError] = useState<string | null>(null)
// Override only until RSC props catch up after "Manter o meu".
// Override only until the mirror row catches up after "Manter o meu".
const [baseOverride, setBaseOverride] = useState<string | null | undefined>(undefined)
const baseEstimatedAt = baseOverride !== undefined ? baseOverride : currentEstimatedAt
const mirrorPledge = useSyncExternalStore(
(onStoreChange) => subscribeOpsVotePledge(pledgeID, onStoreChange),
() => readOpsVotePledge(pledgeID),
() => undefined,
)
const mirrorEstimatedVotes = toVoteEstimateScenarioViewModel(mirrorPledge?.estimatedVotes)
const mirrorEstimateNote = mirrorPledge?.estimateNote ?? null
const mirrorEstimatedAt = mirrorPledge?.estimatedAt ?? null
const baseEstimatedAt = baseOverride !== undefined ? baseOverride : mirrorEstimatedAt
const outboxRow = useSyncExternalStore(
(onStoreChange) => subscribeOpsEstimateOutboxRow(pledgeID, onStoreChange),
@ -199,7 +200,7 @@ const HybridPledgeEstimateForm = ({
useEffect(() => {
setBaseOverride(undefined)
}, [currentEstimatedAt])
}, [mirrorEstimatedAt])
useEffect(() => {
const previous = previousStatusRef.current
@ -262,7 +263,7 @@ const HybridPledgeEstimateForm = ({
const status = outboxRow?.status
const pending = isSubmitting || status === 'pending'
const fieldsKey = `pledge-estimate-fields-${pledgeID}-${outboxRow?.status ?? 'rsc'}-${currentEstimatedAt ?? 'none'}`
const fieldsKey = `pledge-estimate-fields-${pledgeID}-${outboxRow?.status ?? 'mirror'}-${mirrorEstimatedAt ?? 'none'}`
const onSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault()
@ -310,7 +311,7 @@ const HybridPledgeEstimateForm = ({
<div key={fieldsKey} className="flex flex-col gap-3">
<VoteEstimateScenarioInputs
fieldPrefix="estimatedVotes"
values={outboxRow?.estimatedVotes ?? currentEstimatedVotes}
values={outboxRow?.estimatedVotes ?? mirrorEstimatedVotes}
idPrefix={`pledge-estimate-${pledgeID}`}
/>
<Field>
@ -321,7 +322,7 @@ const HybridPledgeEstimateForm = ({
id={`pledge-note-${pledgeID}`}
name="estimateNote"
maxLength={1000}
defaultValue={outboxRow?.estimateNote ?? currentEstimateNote ?? undefined}
defaultValue={outboxRow?.estimateNote ?? mirrorEstimateNote ?? undefined}
className="min-h-11"
/>
</Field>

View file

@ -0,0 +1,37 @@
import { relationshipId, requireRelationshipId } from '@/lib/relationship'
import { toVoteEstimateScenarioViewModel } from '@/lib/voteEstimate'
import type { OpsVotePledge } from './opsContract'
/** Minimal write response shape from `estimateVotesCas` (depth 0). */
export type VotePledgeEstimateWriteResult = {
id: number
leadership: unknown
municipality: unknown
declaredVotes: number
declaredAt?: string | null
declaredBy?: unknown
updatedAt: string
estimatedVotes?: {
pessimistic?: number | null
central?: number | null
optimistic?: number | null
} | null
estimateNote?: string | null
estimatedBy?: unknown
estimatedAt?: string | null
}
export const mapVotePledgeWriteToOps = (doc: VotePledgeEstimateWriteResult): OpsVotePledge => ({
id: doc.id,
leadership: requireRelationshipId(doc.leadership, 'votePledge write: missing leadership'),
municipality: requireRelationshipId(doc.municipality, 'votePledge write: missing municipality'),
declaredVotes: doc.declaredVotes,
declaredAt: doc.declaredAt ?? null,
declaredBy: relationshipId(doc.declaredBy),
updatedAt: doc.updatedAt,
estimatedVotes: toVoteEstimateScenarioViewModel(doc.estimatedVotes),
estimateNote: doc.estimateNote ?? null,
estimatedBy: relationshipId(doc.estimatedBy),
estimatedAt: doc.estimatedAt ?? null,
})

View file

@ -0,0 +1,35 @@
import { describe, expect, it } from 'vitest'
import { mapVotePledgeWriteToOps } from '@/lib/campaignOps/mapVotePledgeWriteToOps'
describe('mapVotePledgeWriteToOps (OH7)', () => {
it('maps a depth-0 write response into an OpsVotePledge row', () => {
expect(
mapVotePledgeWriteToOps({
id: 10,
leadership: 2,
municipality: 1,
declaredVotes: 120,
declaredAt: '2026-08-01T10:00:00.000Z',
declaredBy: 5,
updatedAt: '2026-08-01T13:00:00.000Z',
estimatedVotes: { pessimistic: 80, central: 100, optimistic: 120 },
estimateNote: 'nota',
estimatedBy: 5,
estimatedAt: '2026-08-01T13:00:00.000Z',
}),
).toEqual({
id: 10,
leadership: 2,
municipality: 1,
declaredVotes: 120,
declaredAt: '2026-08-01T10:00:00.000Z',
declaredBy: 5,
updatedAt: '2026-08-01T13:00:00.000Z',
estimatedVotes: { pessimistic: 80, central: 100, optimistic: 120 },
estimateNote: 'nota',
estimatedBy: 5,
estimatedAt: '2026-08-01T13:00:00.000Z',
})
})
})

View file

@ -3,11 +3,13 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import {
applyOpsMirrorSnapshot,
applyOpsVotePledgeEstimateWrite,
bootstrapOpsMirror,
getOpsMirrorLastSyncedAt,
getOpsMirrorPersistenceMode,
municipalitiesCollection,
OPS_SYNC_PATH,
patchOpsVotePledgeEstimateOptimistic,
readOpsMirrorSnapshot,
resetOpsMirrorClientForTests,
syncOpsMirror,
@ -157,6 +159,37 @@ describe('opsMirrorClient', () => {
expect(stored?.lastSyncedAt).toBe(sync.lastSyncedAt)
})
it('patches estimate fields after a successful write', () => {
applyOpsMirrorSnapshot(baseSnapshot())
applyOpsVotePledgeEstimateWrite({
id: 10,
leadership: 2,
municipality: 1,
declaredVotes: 100,
updatedAt: '2026-08-01T14:00:00.000Z',
estimatedVotes: { pessimistic: 90, central: 110, optimistic: 130 },
estimateNote: 'patch',
estimatedBy: 3,
estimatedAt: '2026-08-01T14:00:00.000Z',
})
expect(votePledgesCollection.get(10)?.estimatedVotes?.central).toBe(110)
expect(votePledgesCollection.get(10)?.estimatedAt).toBe('2026-08-01T14:00:00.000Z')
expect(votePledgesCollection.get(10)?.estimateNote).toBe('patch')
})
it('applies optimistic estimate patches while pending', () => {
applyOpsMirrorSnapshot(baseSnapshot())
patchOpsVotePledgeEstimateOptimistic(
10,
{ pessimistic: 70, central: 80, optimistic: 90 },
'optimistic local',
)
expect(votePledgesCollection.get(10)?.estimatedVotes?.central).toBe(80)
expect(votePledgesCollection.get(10)?.estimateNote).toBe('optimistic local')
})
it('does not smash outbox-marked pledge rows on merge', async () => {
applyOpsMirrorSnapshot(
baseSnapshot({