teqo-backup/src/components/campaign/opsSync/opsVotePledgeMirror.ts
Cursor Agent daeff53bf4
OH10: mirror CAS base, advisors conflict toast, pledgeId path
Prefer municipalitiesCollection updatedAt for list/update outbox CAS,
restore advisors conflict Manter/Usar toast, and pass pledgeId for O(1)
declareVotes mirror/outbox keys. Drop unused membership Cas export and
expectedVotes baseUpdatedAt.

Co-authored-by: Francisco Solla <fsolla@users.noreply.github.com>
2026-08-02 01:42:23 +00:00

68 lines
2.2 KiB
TypeScript

'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/OH10). */
export const applyOpsVotePledgeEstimateWrite = (doc: VotePledgeEstimateWriteResult): void => {
const mapped = mapVotePledgeWriteToOps(doc)
if (votePledgesCollection.has(mapped.id)) {
votePledgesCollection.update(mapped.id, (draft) => {
draft.declaredVotes = mapped.declaredVotes
draft.declaredAt = mapped.declaredAt
draft.declaredBy = mapped.declaredBy
draft.estimatedVotes = mapped.estimatedVotes
draft.estimateNote = mapped.estimateNote
draft.estimatedAt = mapped.estimatedAt
draft.estimatedBy = mapped.estimatedBy
draft.updatedAt = mapped.updatedAt
})
return
}
votePledgesCollection.insert(mapped)
}