Merge pull request #212 from fsolla/cursor/pool-i169-4a2cf9cf-a1b4

OH7 — Estimativas ligadas ao mirror completo
This commit is contained in:
Francisco Solla 2026-08-01 22:02:58 -03:00 committed by GitHub
commit b5a5bb3cc5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 214 additions and 32 deletions

View file

@ -15,6 +15,11 @@ import {
type EnqueueEstimateVotesInput, type EnqueueEstimateVotesInput,
type OpsEstimateOutboxRow, type OpsEstimateOutboxRow,
} from '@/components/campaign/opsSync/opsEstimateOutboxModel' } from '@/components/campaign/opsSync/opsEstimateOutboxModel'
import {
applyOpsVotePledgeEstimateWrite,
patchOpsVotePledgeEstimateOptimistic,
readOpsVotePledge,
} from '@/components/campaign/opsSync/opsVotePledgeMirror'
import { opsOutboxKey, type OpsOutboxKey } from '@/lib/campaignOps/opsContract' import { opsOutboxKey, type OpsOutboxKey } from '@/lib/campaignOps/opsContract'
import { import {
isOpsEstimateConflictMessage, isOpsEstimateConflictMessage,
@ -48,16 +53,18 @@ const createEstimateOfflineExecutor = (): OfflineExecutor =>
const row = mutation.modified as OpsEstimateOutboxRow const row = mutation.modified as OpsEstimateOutboxRow
try { try {
await estimateVotesCas({ const updated = await estimateVotesCas({
pledge: row.pledgeId, pledge: row.pledgeId,
estimatedVotes: row.estimatedVotes, estimatedVotes: row.estimatedVotes,
estimateNote: row.estimateNote, estimateNote: row.estimateNote,
baseEstimatedAt: row.baseEstimatedAt, baseEstimatedAt: row.baseEstimatedAt,
}) })
applyOpsVotePledgeEstimateWrite(updated)
opsEstimateOutboxCollection.utils.acceptMutations(transaction) opsEstimateOutboxCollection.utils.acceptMutations(transaction)
if (opsEstimateOutboxCollection.has(row.pledgeId)) { if (opsEstimateOutboxCollection.has(row.pledgeId)) {
// Drop the local row so RSC props win after refresh (OH7 will opsEstimateOutboxCollection.update(row.pledgeId, (draft) => {
// patch the mirror instead of keeping a synced stub). draft.status = 'synced'
})
opsEstimateOutboxCollection.delete(row.pledgeId) opsEstimateOutboxCollection.delete(row.pledgeId)
} }
} catch (error) { } catch (error) {
@ -110,7 +117,13 @@ export const enqueueEstimateVotes = async (input: EnqueueEstimateVotesInput): Pr
const run = executor.createOfflineAction<EnqueueEstimateVotesInput>({ const run = executor.createOfflineAction<EnqueueEstimateVotesInput>({
mutationFnName: ESTIMATE_MUTATION_FN, mutationFnName: ESTIMATE_MUTATION_FN,
onMutate: (variables) => { 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)) { if (opsEstimateOutboxCollection.has(next.pledgeId)) {
opsEstimateOutboxCollection.update(next.pledgeId, (draft) => { opsEstimateOutboxCollection.update(next.pledgeId, (draft) => {
draft.estimatedVotes = next.estimatedVotes draft.estimatedVotes = next.estimatedVotes

View file

@ -8,6 +8,7 @@ import {
type OpsMirrorPersistenceMode, type OpsMirrorPersistenceMode,
type OpsMirrorStore, type OpsMirrorStore,
} from '@/components/campaign/opsSync/opsMirrorPersistence' } from '@/components/campaign/opsSync/opsMirrorPersistence'
import { votePledgesCollection } from '@/components/campaign/opsSync/opsVotePledgeMirror'
import { import {
createEmptyOpsSnapshot, createEmptyOpsSnapshot,
type OpsActivity, type OpsActivity,
@ -20,7 +21,6 @@ import {
type OpsOutboxKey, type OpsOutboxKey,
type OpsSnapshot, type OpsSnapshot,
type OpsStateDeputy, type OpsStateDeputy,
type OpsVotePledge,
} from '@/lib/campaignOps/opsContract' } from '@/lib/campaignOps/opsContract'
import { mergeOpsSnapshot } from '@/lib/campaignOps/opsMerge' import { mergeOpsSnapshot } from '@/lib/campaignOps/opsMerge'
import { OPS_MIRROR_SCHEMA_VERSION } from '@/lib/campaignOps/opsMirrorVersion' import { OPS_MIRROR_SCHEMA_VERSION } from '@/lib/campaignOps/opsMirrorVersion'
@ -38,7 +38,7 @@ const createRowCollection = <T extends { id: number }>(id: string) =>
export const municipalitiesCollection = createRowCollection<OpsMunicipality>('ops-municipalities') export const municipalitiesCollection = createRowCollection<OpsMunicipality>('ops-municipalities')
const leadershipsCollection = createRowCollection<OpsLeadership>('ops-leaderships') const leadershipsCollection = createRowCollection<OpsLeadership>('ops-leaderships')
export const votePledgesCollection = createRowCollection<OpsVotePledge>('ops-vote-pledges') export { votePledgesCollection } from '@/components/campaign/opsSync/opsVotePledgeMirror'
const activitiesCollection = createRowCollection<OpsActivity>('ops-activities') const activitiesCollection = createRowCollection<OpsActivity>('ops-activities')
const stateDeputiesCollection = createRowCollection<OpsStateDeputy>('ops-state-deputies') const stateDeputiesCollection = createRowCollection<OpsStateDeputy>('ops-state-deputies')
const organizationsCollection = createRowCollection<OpsOrganization>('ops-organizations') const organizationsCollection = createRowCollection<OpsOrganization>('ops-organizations')

View file

@ -0,0 +1,65 @@
'use client'
import { createCollection, localOnlyCollectionOptions } from '@tanstack/db'
import {
mapVotePledgeWriteToOps,
type VotePledgeEstimateWriteResult,
} from '@/lib/campaignOps/mapVotePledgeWriteToOps'
import type { OpsVotePledge } from '@/lib/campaignOps/opsContract'
import type { VoteEstimateScenarioViewModel } from '@/lib/voteEstimate'
export const votePledgesCollection = createCollection(
localOnlyCollectionOptions<OpsVotePledge, number>({
id: 'ops-vote-pledges',
getKey: (row) => row.id,
}),
)
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, subscribeOpsEstimateOutboxRow,
} from '@/components/campaign/opsSync/opsEstimateOutbox' } from '@/components/campaign/opsSync/opsEstimateOutbox'
import type { OpsEstimateSyncStatus } from '@/components/campaign/opsSync/opsEstimateOutboxModel' import type { OpsEstimateSyncStatus } from '@/components/campaign/opsSync/opsEstimateOutboxModel'
import {
readOpsVotePledge,
subscribeOpsVotePledge,
} from '@/components/campaign/opsSync/opsVotePledgeMirror'
import { CampaignFormActionMessage } from '@/components/campaign/shared/CampaignFormActionMessage' import { CampaignFormActionMessage } from '@/components/campaign/shared/CampaignFormActionMessage'
import { VoteEstimateScenarioInputs } from '@/components/campaign/votePledge/VoteEstimateScenarioInputs' import { VoteEstimateScenarioInputs } from '@/components/campaign/votePledge/VoteEstimateScenarioInputs'
import { Badge } from '@/components/ui/Badge' import { Badge } from '@/components/ui/Badge'
@ -87,7 +91,7 @@ export const PledgeEstimateForm = ({
pledgeID, pledgeID,
currentEstimatedVotes, currentEstimatedVotes,
currentEstimateNote, currentEstimateNote,
currentEstimatedAt, currentEstimatedAt: _currentEstimatedAt,
opsHybridEnabled, opsHybridEnabled,
formAction, formAction,
}: PledgeEstimateFormProps) => { }: PledgeEstimateFormProps) => {
@ -102,14 +106,7 @@ export const PledgeEstimateForm = ({
) )
} }
return ( return <HybridPledgeEstimateForm pledgeID={pledgeID} />
<HybridPledgeEstimateForm
pledgeID={pledgeID}
currentEstimatedVotes={currentEstimatedVotes}
currentEstimateNote={currentEstimateNote}
currentEstimatedAt={currentEstimatedAt}
/>
)
} }
const LegacyPledgeEstimateForm = ({ const LegacyPledgeEstimateForm = ({
@ -165,26 +162,26 @@ const LegacyPledgeEstimateForm = ({
) )
} }
const HybridPledgeEstimateForm = ({ const HybridPledgeEstimateForm = ({ pledgeID }: { pledgeID: number }) => {
pledgeID,
currentEstimatedVotes,
currentEstimateNote,
currentEstimatedAt,
}: {
pledgeID: number
currentEstimatedVotes: VoteEstimateScenarioViewModel
currentEstimateNote: string | null
currentEstimatedAt: string | null
}) => {
const router = useRouter() const router = useRouter()
const liveRegionId = useId() const liveRegionId = useId()
const formRef = useRef<HTMLFormElement>(null) const formRef = useRef<HTMLFormElement>(null)
const previousStatusRef = useRef<OpsEstimateSyncStatus | undefined>(undefined) const previousStatusRef = useRef<OpsEstimateSyncStatus | undefined>(undefined)
const [isSubmitting, setIsSubmitting] = useState(false) const [isSubmitting, setIsSubmitting] = useState(false)
const [formError, setFormError] = useState<string | null>(null) 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 [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( const outboxRow = useSyncExternalStore(
(onStoreChange) => subscribeOpsEstimateOutboxRow(pledgeID, onStoreChange), (onStoreChange) => subscribeOpsEstimateOutboxRow(pledgeID, onStoreChange),
@ -199,7 +196,7 @@ const HybridPledgeEstimateForm = ({
useEffect(() => { useEffect(() => {
setBaseOverride(undefined) setBaseOverride(undefined)
}, [currentEstimatedAt]) }, [mirrorEstimatedAt])
useEffect(() => { useEffect(() => {
const previous = previousStatusRef.current const previous = previousStatusRef.current
@ -262,7 +259,7 @@ const HybridPledgeEstimateForm = ({
const status = outboxRow?.status const status = outboxRow?.status
const pending = isSubmitting || status === 'pending' 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>) => { const onSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault() event.preventDefault()
@ -310,7 +307,7 @@ const HybridPledgeEstimateForm = ({
<div key={fieldsKey} className="flex flex-col gap-3"> <div key={fieldsKey} className="flex flex-col gap-3">
<VoteEstimateScenarioInputs <VoteEstimateScenarioInputs
fieldPrefix="estimatedVotes" fieldPrefix="estimatedVotes"
values={outboxRow?.estimatedVotes ?? currentEstimatedVotes} values={outboxRow?.estimatedVotes ?? mirrorEstimatedVotes}
idPrefix={`pledge-estimate-${pledgeID}`} idPrefix={`pledge-estimate-${pledgeID}`}
/> />
<Field> <Field>
@ -321,7 +318,7 @@ const HybridPledgeEstimateForm = ({
id={`pledge-note-${pledgeID}`} id={`pledge-note-${pledgeID}`}
name="estimateNote" name="estimateNote"
maxLength={1000} maxLength={1000}
defaultValue={outboxRow?.estimateNote ?? currentEstimateNote ?? undefined} defaultValue={outboxRow?.estimateNote ?? mirrorEstimateNote ?? undefined}
className="min-h-11" className="min-h-11"
/> />
</Field> </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

@ -18,6 +18,10 @@ import {
formatOpsSyncRelative, formatOpsSyncRelative,
resolveOpsSyncChromeLabel, resolveOpsSyncChromeLabel,
} from '@/components/campaign/opsSync/opsSyncChromeCopy' } from '@/components/campaign/opsSync/opsSyncChromeCopy'
import {
applyOpsVotePledgeEstimateWrite,
patchOpsVotePledgeEstimateOptimistic,
} from '@/components/campaign/opsSync/opsVotePledgeMirror'
import { import {
createEmptyOpsSnapshot, createEmptyOpsSnapshot,
opsOutboxKey, opsOutboxKey,
@ -157,6 +161,37 @@ describe('opsMirrorClient', () => {
expect(stored?.lastSyncedAt).toBe(sync.lastSyncedAt) 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 () => { it('does not smash outbox-marked pledge rows on merge', async () => {
applyOpsMirrorSnapshot( applyOpsMirrorSnapshot(
baseSnapshot({ baseSnapshot({