From 8fd5838914edf350d6fb26e2050b129264ff0460 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 2 Aug 2026 00:45:32 +0000 Subject: [PATCH] =?UTF-8?q?OH7=20=E2=80=94=20estimativas=20ligadas=20ao=20?= =?UTF-8?q?mirror=20completo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- .../campaign/opsSync/opsEstimateOutbox.ts | 37 +++++++++++-- .../campaign/opsSync/opsMirrorClient.ts | 53 +++++++++++++++++++ .../votePledge/PledgeEstimateForm.tsx | 43 +++++++-------- .../campaignOps/mapVotePledgeWriteToOps.ts | 37 +++++++++++++ .../unit/mapVotePledgeWriteToOps.unit.spec.ts | 35 ++++++++++++ tests/unit/opsMirrorClient.unit.spec.ts | 33 ++++++++++++ 6 files changed, 213 insertions(+), 25 deletions(-) create mode 100644 src/lib/campaignOps/mapVotePledgeWriteToOps.ts create mode 100644 tests/unit/mapVotePledgeWriteToOps.unit.spec.ts diff --git a/src/components/campaign/opsSync/opsEstimateOutbox.ts b/src/components/campaign/opsSync/opsEstimateOutbox.ts index 87b745a4..1d193772 100644 --- a/src/components/campaign/opsSync/opsEstimateOutbox.ts +++ b/src/components/campaign/opsSync/opsEstimateOutbox.ts @@ -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 => { if (executorSingleton) { await executorSingleton.waitForInit() @@ -110,7 +126,20 @@ export const enqueueEstimateVotes = async (input: EnqueueEstimateVotesInput): Pr const run = executor.createOfflineAction({ 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 diff --git a/src/components/campaign/opsSync/opsMirrorClient.ts b/src/components/campaign/opsSync/opsMirrorClient.ts index d94ed92a..1fbf99f8 100644 --- a/src/components/campaign/opsSync/opsMirrorClient.ts +++ b/src/components/campaign/opsSync/opsMirrorClient.ts @@ -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) +} diff --git a/src/components/campaign/votePledge/PledgeEstimateForm.tsx b/src/components/campaign/votePledge/PledgeEstimateForm.tsx index 613aac88..ecee325a 100644 --- a/src/components/campaign/votePledge/PledgeEstimateForm.tsx +++ b/src/components/campaign/votePledge/PledgeEstimateForm.tsx @@ -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 ( ) } @@ -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(null) const previousStatusRef = useRef(undefined) const [isSubmitting, setIsSubmitting] = useState(false) const [formError, setFormError] = useState(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(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) => { event.preventDefault() @@ -310,7 +311,7 @@ const HybridPledgeEstimateForm = ({
@@ -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" /> diff --git a/src/lib/campaignOps/mapVotePledgeWriteToOps.ts b/src/lib/campaignOps/mapVotePledgeWriteToOps.ts new file mode 100644 index 00000000..80be64f3 --- /dev/null +++ b/src/lib/campaignOps/mapVotePledgeWriteToOps.ts @@ -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, +}) diff --git a/tests/unit/mapVotePledgeWriteToOps.unit.spec.ts b/tests/unit/mapVotePledgeWriteToOps.unit.spec.ts new file mode 100644 index 00000000..acbafa80 --- /dev/null +++ b/tests/unit/mapVotePledgeWriteToOps.unit.spec.ts @@ -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', + }) + }) +}) diff --git a/tests/unit/opsMirrorClient.unit.spec.ts b/tests/unit/opsMirrorClient.unit.spec.ts index 4ee49851..0f8cd29c 100644 --- a/tests/unit/opsMirrorClient.unit.spec.ts +++ b/tests/unit/opsMirrorClient.unit.spec.ts @@ -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({