mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-26 21:53:06 +00:00
Merge pull request #212 from fsolla/cursor/pool-i169-4a2cf9cf-a1b4
OH7 — Estimativas ligadas ao mirror completo
This commit is contained in:
commit
b5a5bb3cc5
7 changed files with 214 additions and 32 deletions
|
|
@ -15,6 +15,11 @@ import {
|
|||
type EnqueueEstimateVotesInput,
|
||||
type OpsEstimateOutboxRow,
|
||||
} from '@/components/campaign/opsSync/opsEstimateOutboxModel'
|
||||
import {
|
||||
applyOpsVotePledgeEstimateWrite,
|
||||
patchOpsVotePledgeEstimateOptimistic,
|
||||
readOpsVotePledge,
|
||||
} from '@/components/campaign/opsSync/opsVotePledgeMirror'
|
||||
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) {
|
||||
|
|
@ -110,7 +117,13 @@ 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
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import {
|
|||
type OpsMirrorPersistenceMode,
|
||||
type OpsMirrorStore,
|
||||
} from '@/components/campaign/opsSync/opsMirrorPersistence'
|
||||
import { votePledgesCollection } from '@/components/campaign/opsSync/opsVotePledgeMirror'
|
||||
import {
|
||||
createEmptyOpsSnapshot,
|
||||
type OpsActivity,
|
||||
|
|
@ -20,7 +21,6 @@ import {
|
|||
type OpsOutboxKey,
|
||||
type OpsSnapshot,
|
||||
type OpsStateDeputy,
|
||||
type OpsVotePledge,
|
||||
} from '@/lib/campaignOps/opsContract'
|
||||
import { mergeOpsSnapshot } from '@/lib/campaignOps/opsMerge'
|
||||
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')
|
||||
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 stateDeputiesCollection = createRowCollection<OpsStateDeputy>('ops-state-deputies')
|
||||
const organizationsCollection = createRowCollection<OpsOrganization>('ops-organizations')
|
||||
|
|
|
|||
65
src/components/campaign/opsSync/opsVotePledgeMirror.ts
Normal file
65
src/components/campaign/opsSync/opsVotePledgeMirror.ts
Normal 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)
|
||||
}
|
||||
|
|
@ -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/opsVotePledgeMirror'
|
||||
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) => {
|
||||
|
|
@ -102,14 +106,7 @@ export const PledgeEstimateForm = ({
|
|||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<HybridPledgeEstimateForm
|
||||
pledgeID={pledgeID}
|
||||
currentEstimatedVotes={currentEstimatedVotes}
|
||||
currentEstimateNote={currentEstimateNote}
|
||||
currentEstimatedAt={currentEstimatedAt}
|
||||
/>
|
||||
)
|
||||
return <HybridPledgeEstimateForm pledgeID={pledgeID} />
|
||||
}
|
||||
|
||||
const LegacyPledgeEstimateForm = ({
|
||||
|
|
@ -165,26 +162,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 +196,7 @@ const HybridPledgeEstimateForm = ({
|
|||
|
||||
useEffect(() => {
|
||||
setBaseOverride(undefined)
|
||||
}, [currentEstimatedAt])
|
||||
}, [mirrorEstimatedAt])
|
||||
|
||||
useEffect(() => {
|
||||
const previous = previousStatusRef.current
|
||||
|
|
@ -262,7 +259,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 +307,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 +318,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>
|
||||
|
|
|
|||
37
src/lib/campaignOps/mapVotePledgeWriteToOps.ts
Normal file
37
src/lib/campaignOps/mapVotePledgeWriteToOps.ts
Normal 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,
|
||||
})
|
||||
35
tests/unit/mapVotePledgeWriteToOps.unit.spec.ts
Normal file
35
tests/unit/mapVotePledgeWriteToOps.unit.spec.ts
Normal 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',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
|
@ -18,6 +18,10 @@ import {
|
|||
formatOpsSyncRelative,
|
||||
resolveOpsSyncChromeLabel,
|
||||
} from '@/components/campaign/opsSync/opsSyncChromeCopy'
|
||||
import {
|
||||
applyOpsVotePledgeEstimateWrite,
|
||||
patchOpsVotePledgeEstimateOptimistic,
|
||||
} from '@/components/campaign/opsSync/opsVotePledgeMirror'
|
||||
import {
|
||||
createEmptyOpsSnapshot,
|
||||
opsOutboxKey,
|
||||
|
|
@ -157,6 +161,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({
|
||||
|
|
|
|||
Loading…
Reference in a new issue