mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-26 21:53:06 +00:00
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>
This commit is contained in:
parent
26bda9e430
commit
daeff53bf4
12 changed files with 151 additions and 70 deletions
|
|
@ -1,6 +1,6 @@
|
|||
# OH10 — Writes municipality staff CAS: update, declareVotes, tendência, engagement, advisors
|
||||
|
||||
Status: em implementação
|
||||
Status: pronto para PR
|
||||
Atualizado em: 2026-08-02
|
||||
Issue: #171
|
||||
Priority: P1
|
||||
|
|
@ -10,6 +10,11 @@ Appetite: ~2–3 dias eng
|
|||
Depends: OH7, OH9
|
||||
Responsável: —
|
||||
|
||||
## Débitos pós-/simplify (não bloqueiam OH10)
|
||||
|
||||
- Toast de conflito CAS em tendência/nível da lista (só advisors + declareVotes têm escolha Manter/Usar).
|
||||
- Unificar executores OH6+OH10 (já previsto em OH13).
|
||||
|
||||
## Freshness audit (2026-08-02)
|
||||
|
||||
- OH7 (#169) e OH9 (#172) `done`+`in-prod`. OH6 CAS em `estimateVotesCas` + `opsEstimateOutbox` intactos; mirror tem `updatedAt` em `OpsMunicipality` / `OpsVotePledge`.
|
||||
|
|
|
|||
|
|
@ -412,13 +412,6 @@ export const setMunicipalityAdvisorMembership = async (
|
|||
return setMunicipalityAdvisorMembershipRecord(payload, actor, input)
|
||||
}
|
||||
|
||||
export const setMunicipalityAdvisorMembershipCas = async (
|
||||
input: MunicipalityAdvisorMembershipInput,
|
||||
) => {
|
||||
const { payload, actor } = await getCampaignActionContext()
|
||||
return setMunicipalityAdvisorMembershipRecord(payload, actor, input, { cas: true })
|
||||
}
|
||||
|
||||
export const setMunicipalityAdvisorMembershipCasRecord = async (
|
||||
payload: Payload,
|
||||
actor: CampaignUser,
|
||||
|
|
|
|||
|
|
@ -81,6 +81,7 @@ export const MunicipalityLeadershipsPanel = ({
|
|||
<DeclareVotesForm
|
||||
municipalityID={municipalityID}
|
||||
leadershipID={leadership.id}
|
||||
pledgeId={pledge?.id}
|
||||
currentDeclaredVotes={pledge?.declaredVotes ?? null}
|
||||
currentUpdatedAt={pledge?.updatedAt ?? null}
|
||||
formAction={declareFormAction}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
'use client'
|
||||
|
||||
import { XIcon } from 'lucide-react'
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
import type { MunicipalityListAdvisorsResponse } from '@/app/(campaign)/campanha/(app)/municipios/advisors/types'
|
||||
import {
|
||||
|
|
@ -14,13 +16,21 @@ import {
|
|||
type CampaignCellEditOverlayVariant,
|
||||
} from '@/components/campaign/shared/CampaignCellEditOverlay'
|
||||
import { useCampaignCellFailureChannel } from '@/components/campaign/shared/useCampaignCellFailureChannel'
|
||||
import { enqueueAdvisorsAssignment } from '@/components/campaign/opsSync/opsMunicipalityOutbox'
|
||||
import { municipalitiesCollection } from '@/components/campaign/opsSync/opsMirrorClient'
|
||||
import {
|
||||
discardOpsAdvisorsOutboxRow,
|
||||
enqueueAdvisorsAssignment,
|
||||
readOpsAdvisorsOutboxRow,
|
||||
subscribeOpsAdvisorsOutboxRow,
|
||||
} from '@/components/campaign/opsSync/opsMunicipalityOutbox'
|
||||
import type { OpsMunicipalityWriteSyncStatus } from '@/components/campaign/opsSync/opsMunicipalityOutboxModel'
|
||||
import { Alert, AlertDescription } from '@/components/ui/Alert'
|
||||
import { Badge } from '@/components/ui/Badge'
|
||||
import { Command, CommandInput, CommandItem, CommandList } from '@/components/ui/Command'
|
||||
import { Spinner } from '@/components/ui/Spinner'
|
||||
import { postCampaignJson } from '@/lib/campaignJsonRequest'
|
||||
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
|
||||
import { OPS_UPDATED_AT_CONFLICT_MESSAGE } from '@/lib/schemas/opsCas'
|
||||
import { sameIdSet } from '@/lib/sameIdSet'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { matchesAtWordStart } from '@/lib/wordStartFilter'
|
||||
|
|
@ -31,6 +41,7 @@ import type {
|
|||
|
||||
const ADVISORS_ENDPOINT = '/campanha/municipios/advisors'
|
||||
const SAVE_ERROR_MESSAGE = 'Não foi possível atualizar os assessores. Tente novamente.'
|
||||
const CONFLICT_TOAST_ID_PREFIX = 'ops-advisors-conflict:'
|
||||
|
||||
type MunicipalityListAdvisorsControlProps = {
|
||||
municipalityID: number
|
||||
|
|
@ -55,6 +66,8 @@ export const MunicipalityListAdvisorsControl = ({
|
|||
updatedAt,
|
||||
variant,
|
||||
}: MunicipalityListAdvisorsControlProps) => {
|
||||
const router = useRouter()
|
||||
const opsHybrid = resolveOpsHybridEnabled()
|
||||
const [open, setOpen] = useState(false)
|
||||
const [selectedIDs, setSelectedIDs] = useState<number[]>(currentAdvisorIDs)
|
||||
const [query, setQuery] = useState('')
|
||||
|
|
@ -74,6 +87,14 @@ export const MunicipalityListAdvisorsControl = ({
|
|||
// clobber the optimistic state back to it.
|
||||
const requestSeqRef = useRef(0)
|
||||
const latestConfirmedRef = useRef<{ seq: number; advisors: number[] } | null>(null)
|
||||
const previousOutboxStatusRef = useRef<OpsMunicipalityWriteSyncStatus | undefined>(undefined)
|
||||
|
||||
const outboxRow = useSyncExternalStore(
|
||||
(onStoreChange) =>
|
||||
opsHybrid ? subscribeOpsAdvisorsOutboxRow(municipalityID, onStoreChange) : () => undefined,
|
||||
() => (opsHybrid ? readOpsAdvisorsOutboxRow(municipalityID) : undefined),
|
||||
() => undefined,
|
||||
)
|
||||
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
noteOpenChange(nextOpen)
|
||||
|
|
@ -89,6 +110,51 @@ export const MunicipalityListAdvisorsControl = ({
|
|||
setSelectedIDs(currentAdvisorIDs)
|
||||
}, [currentAdvisorIDs])
|
||||
|
||||
useEffect(() => {
|
||||
const previous = previousOutboxStatusRef.current
|
||||
previousOutboxStatusRef.current = outboxRow?.status
|
||||
if (previous === 'pending' && outboxRow === undefined) {
|
||||
router.refresh()
|
||||
}
|
||||
}, [outboxRow, router])
|
||||
|
||||
useEffect(() => {
|
||||
if (!opsHybrid || outboxRow?.status !== 'conflict') return
|
||||
const toastId = `${CONFLICT_TOAST_ID_PREFIX}${municipalityID}`
|
||||
toast.message(OPS_UPDATED_AT_CONFLICT_MESSAGE, {
|
||||
id: toastId,
|
||||
duration: Infinity,
|
||||
action: {
|
||||
label: 'Manter o meu',
|
||||
onClick: () => {
|
||||
void enqueueAdvisorsAssignment({
|
||||
municipalityId: municipalityID,
|
||||
advisors: outboxRow.advisors,
|
||||
baseUpdatedAt: outboxRow.serverUpdatedAt ?? null,
|
||||
}).then(
|
||||
() => setErrorMessage(null),
|
||||
(error: unknown) => {
|
||||
reportFailure(
|
||||
error instanceof Error ? error.message : 'Não foi possível reenviar os assessores.',
|
||||
)
|
||||
},
|
||||
)
|
||||
},
|
||||
},
|
||||
cancel: {
|
||||
label: 'Usar o novo',
|
||||
onClick: () => {
|
||||
discardOpsAdvisorsOutboxRow(municipalityID)
|
||||
setErrorMessage(null)
|
||||
router.refresh()
|
||||
},
|
||||
},
|
||||
})
|
||||
return () => {
|
||||
toast.dismiss(toastId)
|
||||
}
|
||||
}, [opsHybrid, outboxRow, municipalityID, router, reportFailure, setErrorMessage])
|
||||
|
||||
// Every eligible account (coordinator/advisor/candidate) is listed here
|
||||
// regardless of current assignment, so it doubles as the name lookup for an
|
||||
// id the popover just optimistically added — no round trip needed to label
|
||||
|
|
@ -164,11 +230,12 @@ export const MunicipalityListAdvisorsControl = ({
|
|||
}
|
||||
|
||||
try {
|
||||
if (resolveOpsHybridEnabled()) {
|
||||
if (opsHybrid) {
|
||||
const mirrorUpdatedAt = municipalitiesCollection.get(municipalityID)?.updatedAt
|
||||
await enqueueAdvisorsAssignment({
|
||||
municipalityId: municipalityID,
|
||||
advisors: nextIds,
|
||||
baseUpdatedAt: updatedAt,
|
||||
baseUpdatedAt: mirrorUpdatedAt ?? updatedAt,
|
||||
})
|
||||
if (requestSeq > (latestConfirmedRef.current?.seq ?? 0)) {
|
||||
latestConfirmedRef.current = { seq: requestSeq, advisors: nextIds }
|
||||
|
|
@ -201,7 +268,12 @@ export const MunicipalityListAdvisorsControl = ({
|
|||
})()
|
||||
}
|
||||
|
||||
const statusMessage = errorMessage ? errorMessage : isPending ? 'Salvando assessores.' : ''
|
||||
const outboxPending = outboxRow?.status === 'pending' || outboxRow?.status === 'conflict'
|
||||
const statusMessage = errorMessage
|
||||
? errorMessage
|
||||
: isPending || outboxPending
|
||||
? 'Salvando assessores.'
|
||||
: ''
|
||||
// The body pads its own sections (`px-4`, aligned with the Drawer header) so
|
||||
// the `Command` can stay full-bleed in both containers — hence `px-0` on the
|
||||
// sheet body and `p-0` on the popover content.
|
||||
|
|
@ -217,7 +289,7 @@ export const MunicipalityListAdvisorsControl = ({
|
|||
// The avatar stack reads as initials at best, and an `aria-label` replaces
|
||||
// even those — so who is assigned goes in the label, by extenso.
|
||||
triggerLabel={`Editar assessores em ${municipalityName} — ${assignedLabel}`}
|
||||
triggerBusy={isPending}
|
||||
triggerBusy={isPending || outboxPending}
|
||||
statusMessage={statusMessage}
|
||||
tooltipContent={tooltipContent}
|
||||
contentClassName="w-80 p-0"
|
||||
|
|
@ -232,7 +304,7 @@ export const MunicipalityListAdvisorsControl = ({
|
|||
<p className={cn('text-xs text-muted-foreground', isSheet && 'pr-6')}>
|
||||
O assessor vê e gerencia somente os municípios que administra.
|
||||
</p>
|
||||
{isPending ? (
|
||||
{isPending || outboxPending ? (
|
||||
<Spinner
|
||||
className={cn(
|
||||
'absolute size-3.5 text-muted-foreground',
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import {
|
|||
type CampaignCellEditOverlayVariant,
|
||||
} from '@/components/campaign/shared/CampaignCellEditOverlay'
|
||||
import { useCampaignCellFailureChannel } from '@/components/campaign/shared/useCampaignCellFailureChannel'
|
||||
import { municipalitiesCollection } from '@/components/campaign/opsSync/opsMirrorClient'
|
||||
import { enqueueEngagementLevel } from '@/components/campaign/opsSync/opsMunicipalityOutbox'
|
||||
import { Alert, AlertDescription } from '@/components/ui/Alert'
|
||||
import { Button } from '@/components/ui/button'
|
||||
|
|
@ -170,6 +171,7 @@ export const MunicipalityListLevelControl = ({
|
|||
|
||||
try {
|
||||
if (resolveOpsHybridEnabled()) {
|
||||
const mirrorUpdatedAt = municipalitiesCollection.get(municipalityID)?.updatedAt
|
||||
await enqueueEngagementLevel({
|
||||
municipalityId: municipalityID,
|
||||
level: draftLevel,
|
||||
|
|
@ -177,7 +179,7 @@ export const MunicipalityListLevelControl = ({
|
|||
reversalSignals,
|
||||
triangulatedShock,
|
||||
override,
|
||||
baseUpdatedAt: updatedAt,
|
||||
baseUpdatedAt: mirrorUpdatedAt ?? updatedAt,
|
||||
})
|
||||
setSaved({
|
||||
level: draftLevel,
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import {
|
|||
type CampaignCellEditOverlayVariant,
|
||||
} from '@/components/campaign/shared/CampaignCellEditOverlay'
|
||||
import { useCampaignCellAutosave } from '@/components/campaign/shared/useCampaignCellAutosave'
|
||||
import { municipalitiesCollection } from '@/components/campaign/opsSync/opsMirrorClient'
|
||||
import { enqueuePoliticalTrend } from '@/components/campaign/opsSync/opsMunicipalityOutbox'
|
||||
import { Alert, AlertDescription } from '@/components/ui/Alert'
|
||||
import { Badge } from '@/components/ui/Badge'
|
||||
|
|
@ -81,11 +82,12 @@ export const MunicipalityListTrendControl = ({
|
|||
pendingMessage: 'Salvando tendência.',
|
||||
persist: opsHybrid
|
||||
? async (trend) => {
|
||||
const mirrorUpdatedAt = municipalitiesCollection.get(municipalityID)?.updatedAt
|
||||
await enqueuePoliticalTrend({
|
||||
municipalityId: municipalityID,
|
||||
status: trend.status,
|
||||
note: trend.note,
|
||||
baseUpdatedAt: updatedAt,
|
||||
baseUpdatedAt: mirrorUpdatedAt ?? updatedAt,
|
||||
})
|
||||
return {
|
||||
ok: true,
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@
|
|||
|
||||
import { useActionState, useState, type FormEvent } from 'react'
|
||||
|
||||
import { municipalitiesCollection } from '@/components/campaign/opsSync/opsMirrorClient'
|
||||
import { enqueueMunicipalityUpdate } from '@/components/campaign/opsSync/opsMunicipalityOutbox'
|
||||
import { CampaignFormActionMessage } from '@/components/campaign/shared/CampaignFormActionMessage'
|
||||
import { Badge } from '@/components/ui/Badge'
|
||||
|
|
@ -69,6 +70,7 @@ export const MunicipalityUpdateForm = ({
|
|||
|
||||
setHybridPending(true)
|
||||
setHybridMessage(null)
|
||||
const mirrorUpdatedAt = municipalitiesCollection.get(municipalityID)?.updatedAt
|
||||
void enqueueMunicipalityUpdate({
|
||||
clientId: crypto.randomUUID(),
|
||||
municipalityId: municipalityID,
|
||||
|
|
@ -80,7 +82,7 @@ export const MunicipalityUpdateForm = ({
|
|||
activeVolunteers: readCount('activeVolunteers'),
|
||||
newSupports: readCount('newSupports'),
|
||||
signalType: parseMunicipalitySignalType(readText('signalType')),
|
||||
baseUpdatedAt: municipalityUpdatedAt,
|
||||
baseUpdatedAt: mirrorUpdatedAt ?? municipalityUpdatedAt,
|
||||
}).then(
|
||||
() => {
|
||||
setHybridPending(false)
|
||||
|
|
|
|||
|
|
@ -369,13 +369,18 @@ export const enqueueDeclareVotes = async (input: {
|
|||
municipalityId: number
|
||||
leadershipId: number
|
||||
declaredVotes: number
|
||||
pledgeId?: number
|
||||
baseUpdatedAt?: string | null
|
||||
}): Promise<void> => {
|
||||
const executor = await getOpsMunicipalityOfflineExecutor()
|
||||
const id = declareVotesOutboxKey(input.leadershipId, input.municipalityId)
|
||||
const mirrorPledge = votePledgesCollection.toArray.find(
|
||||
(row) => row.leadership === input.leadershipId && row.municipality === input.municipalityId,
|
||||
)
|
||||
const mirrorPledge =
|
||||
input.pledgeId !== undefined
|
||||
? votePledgesCollection.get(input.pledgeId)
|
||||
: votePledgesCollection.toArray.find(
|
||||
(row) => row.leadership === input.leadershipId && row.municipality === input.municipalityId,
|
||||
)
|
||||
const pledgeId = input.pledgeId ?? mirrorPledge?.id
|
||||
const baseUpdatedAt =
|
||||
input.baseUpdatedAt !== undefined ? input.baseUpdatedAt : (mirrorPledge?.updatedAt ?? null)
|
||||
|
||||
|
|
@ -386,18 +391,20 @@ export const enqueueDeclareVotes = async (input: {
|
|||
id,
|
||||
municipalityId: variables.municipalityId,
|
||||
leadershipId: variables.leadershipId,
|
||||
pledgeId,
|
||||
declaredVotes: variables.declaredVotes,
|
||||
baseUpdatedAt: variables.baseUpdatedAt ?? baseUpdatedAt,
|
||||
status: 'pending',
|
||||
}
|
||||
if (mirrorPledge && votePledgesCollection.has(mirrorPledge.id)) {
|
||||
votePledgesCollection.update(mirrorPledge.id, (draft) => {
|
||||
if (pledgeId !== undefined && votePledgesCollection.has(pledgeId)) {
|
||||
votePledgesCollection.update(pledgeId, (draft) => {
|
||||
draft.declaredVotes = variables.declaredVotes
|
||||
})
|
||||
}
|
||||
if (declareVotesOutboxCollection.has(id)) {
|
||||
declareVotesOutboxCollection.update(id, (draft) => {
|
||||
draft.declaredVotes = next.declaredVotes
|
||||
draft.pledgeId = next.pledgeId
|
||||
draft.baseUpdatedAt = next.baseUpdatedAt
|
||||
draft.status = 'pending'
|
||||
draft.serverUpdatedAt = undefined
|
||||
|
|
@ -408,7 +415,7 @@ export const enqueueDeclareVotes = async (input: {
|
|||
}
|
||||
},
|
||||
})
|
||||
run({ ...input, baseUpdatedAt })
|
||||
run({ ...input, baseUpdatedAt, pledgeId })
|
||||
}
|
||||
|
||||
export const enqueueMunicipalityUpdate = async (input: {
|
||||
|
|
@ -560,10 +567,14 @@ export const collectOpsMunicipalityOutboxKeys = (): Set<OpsOutboxKey> => {
|
|||
const keys = new Set<OpsOutboxKey>()
|
||||
for (const row of declareVotesOutboxCollection.toArray) {
|
||||
if (row.status === 'pending' || row.status === 'conflict') {
|
||||
const pledge = votePledgesCollection.toArray.find(
|
||||
(p) => p.leadership === row.leadershipId && p.municipality === row.municipalityId,
|
||||
)
|
||||
if (pledge) keys.add(opsOutboxKey('votePledges', pledge.id))
|
||||
if (row.pledgeId !== undefined) {
|
||||
keys.add(opsOutboxKey('votePledges', row.pledgeId))
|
||||
} else {
|
||||
const pledge = votePledgesCollection.toArray.find(
|
||||
(p) => p.leadership === row.leadershipId && p.municipality === row.municipalityId,
|
||||
)
|
||||
if (pledge) keys.add(opsOutboxKey('votePledges', pledge.id))
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const row of municipalityUpdateOutboxCollection.toArray) {
|
||||
|
|
@ -619,17 +630,17 @@ export const discardOpsDeclareVotesOutboxRow = (
|
|||
if (declareVotesOutboxCollection.has(id)) declareVotesOutboxCollection.delete(id)
|
||||
}
|
||||
|
||||
export const readOpsPoliticalTrendOutboxRow = (
|
||||
export const readOpsAdvisorsOutboxRow = (
|
||||
municipalityId: number,
|
||||
): OpsPoliticalTrendOutboxRow | undefined => politicalTrendOutboxCollection.get(municipalityId)
|
||||
): OpsAdvisorsOutboxRow | undefined => advisorsOutboxCollection.get(municipalityId)
|
||||
|
||||
export const subscribeOpsPoliticalTrendOutboxRow = (
|
||||
export const subscribeOpsAdvisorsOutboxRow = (
|
||||
municipalityId: number,
|
||||
onStoreChange: () => void,
|
||||
): (() => void) => {
|
||||
let previous = politicalTrendOutboxCollection.get(municipalityId)
|
||||
const subscription = politicalTrendOutboxCollection.subscribeChanges(() => {
|
||||
const next = politicalTrendOutboxCollection.get(municipalityId)
|
||||
let previous = advisorsOutboxCollection.get(municipalityId)
|
||||
const subscription = advisorsOutboxCollection.subscribeChanges(() => {
|
||||
const next = advisorsOutboxCollection.get(municipalityId)
|
||||
if (next === previous) return
|
||||
previous = next
|
||||
onStoreChange()
|
||||
|
|
@ -637,26 +648,6 @@ export const subscribeOpsPoliticalTrendOutboxRow = (
|
|||
return () => subscription.unsubscribe()
|
||||
}
|
||||
|
||||
export const discardOpsPoliticalTrendOutboxRow = (municipalityId: number): void => {
|
||||
if (politicalTrendOutboxCollection.has(municipalityId)) {
|
||||
politicalTrendOutboxCollection.delete(municipalityId)
|
||||
}
|
||||
}
|
||||
|
||||
export const readOpsEngagementLevelOutboxRow = (
|
||||
municipalityId: number,
|
||||
): OpsEngagementLevelOutboxRow | undefined => engagementLevelOutboxCollection.get(municipalityId)
|
||||
|
||||
export const discardOpsEngagementLevelOutboxRow = (municipalityId: number): void => {
|
||||
if (engagementLevelOutboxCollection.has(municipalityId)) {
|
||||
engagementLevelOutboxCollection.delete(municipalityId)
|
||||
}
|
||||
}
|
||||
|
||||
export const readOpsAdvisorsOutboxRow = (
|
||||
municipalityId: number,
|
||||
): OpsAdvisorsOutboxRow | undefined => advisorsOutboxCollection.get(municipalityId)
|
||||
|
||||
export const discardOpsAdvisorsOutboxRow = (municipalityId: number): void => {
|
||||
if (advisorsOutboxCollection.has(municipalityId)) {
|
||||
advisorsOutboxCollection.delete(municipalityId)
|
||||
|
|
|
|||
|
|
@ -13,6 +13,8 @@ export type OpsDeclareVotesOutboxRow = {
|
|||
id: string
|
||||
municipalityId: number
|
||||
leadershipId: number
|
||||
/** Mirror pledge id when known — avoids O(n) lookup in collectOutboxKeys. */
|
||||
pledgeId?: number
|
||||
declaredVotes: number
|
||||
baseUpdatedAt?: string | null
|
||||
status: OpsMunicipalityWriteSyncStatus
|
||||
|
|
|
|||
|
|
@ -48,11 +48,14 @@ export const patchOpsVotePledgeEstimateOptimistic = (
|
|||
})
|
||||
}
|
||||
|
||||
/** Authoritative patch after a successful server write (OH7). */
|
||||
/** 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
|
||||
|
|
|
|||
|
|
@ -39,6 +39,8 @@ type DeclareVotesFormProps = {
|
|||
municipalityID: number
|
||||
/** Present when staff declare on behalf of a leadership. */
|
||||
leadershipID?: number
|
||||
/** Mirror / outbox key when a pledge row already exists (OH10). */
|
||||
pledgeId?: number
|
||||
currentDeclaredVotes: number | null
|
||||
/** Pledge row `updatedAt` for CAS when a pledge already exists. */
|
||||
currentUpdatedAt?: string | null
|
||||
|
|
@ -61,6 +63,7 @@ const CONFLICT_TOAST_ID_PREFIX = 'ops-declare-conflict:'
|
|||
export const DeclareVotesForm = ({
|
||||
municipalityID,
|
||||
leadershipID,
|
||||
pledgeId,
|
||||
currentDeclaredVotes,
|
||||
currentUpdatedAt = null,
|
||||
opsHybridEnabled = resolveOpsHybridEnabled(),
|
||||
|
|
@ -81,6 +84,7 @@ export const DeclareVotesForm = ({
|
|||
<HybridDeclareVotesForm
|
||||
municipalityID={municipalityID}
|
||||
leadershipID={leadershipID}
|
||||
pledgeId={pledgeId}
|
||||
currentDeclaredVotes={currentDeclaredVotes}
|
||||
currentUpdatedAt={currentUpdatedAt}
|
||||
/>
|
||||
|
|
@ -136,11 +140,13 @@ const LegacyDeclareVotesForm = ({
|
|||
const HybridDeclareVotesForm = ({
|
||||
municipalityID,
|
||||
leadershipID,
|
||||
pledgeId: initialPledgeId,
|
||||
currentDeclaredVotes,
|
||||
currentUpdatedAt,
|
||||
}: {
|
||||
municipalityID: number
|
||||
leadershipID: number
|
||||
pledgeId?: number
|
||||
currentDeclaredVotes: number | null
|
||||
currentUpdatedAt: string | null
|
||||
}) => {
|
||||
|
|
@ -152,21 +158,27 @@ const HybridDeclareVotesForm = ({
|
|||
const [formError, setFormError] = useState<string | null>(null)
|
||||
const [baseOverride, setBaseOverride] = useState<string | null | undefined>(undefined)
|
||||
|
||||
const resolvedPledgeId =
|
||||
initialPledgeId ??
|
||||
votePledgesCollection.toArray.find(
|
||||
(row) => row.leadership === leadershipID && row.municipality === municipalityID,
|
||||
)?.id
|
||||
|
||||
const mirrorPledge = useSyncExternalStore(
|
||||
(onStoreChange) => {
|
||||
const pledge = votePledgesCollection.toArray.find(
|
||||
(row) => row.leadership === leadershipID && row.municipality === municipalityID,
|
||||
)
|
||||
if (!pledge) return () => undefined
|
||||
return subscribeOpsVotePledge(pledge.id, onStoreChange)
|
||||
if (resolvedPledgeId === undefined) return () => undefined
|
||||
return subscribeOpsVotePledge(resolvedPledgeId, onStoreChange)
|
||||
},
|
||||
() =>
|
||||
votePledgesCollection.toArray.find(
|
||||
(row) => row.leadership === leadershipID && row.municipality === municipalityID,
|
||||
),
|
||||
resolvedPledgeId !== undefined
|
||||
? votePledgesCollection.get(resolvedPledgeId)
|
||||
: votePledgesCollection.toArray.find(
|
||||
(row) => row.leadership === leadershipID && row.municipality === municipalityID,
|
||||
),
|
||||
() => undefined,
|
||||
)
|
||||
|
||||
const pledgeId = initialPledgeId ?? mirrorPledge?.id
|
||||
const displayVotes = mirrorPledge?.declaredVotes ?? currentDeclaredVotes
|
||||
const mirrorUpdatedAt = mirrorPledge?.updatedAt ?? currentUpdatedAt
|
||||
const baseUpdatedAt = baseOverride !== undefined ? baseOverride : mirrorUpdatedAt
|
||||
|
|
@ -211,6 +223,7 @@ const HybridDeclareVotesForm = ({
|
|||
void enqueueDeclareVotes({
|
||||
municipalityId: municipalityID,
|
||||
leadershipId: leadershipID,
|
||||
pledgeId,
|
||||
declaredVotes: Math.trunc(declaredVotes),
|
||||
baseUpdatedAt: outboxRow.serverUpdatedAt ?? null,
|
||||
}).then(
|
||||
|
|
@ -238,7 +251,7 @@ const HybridDeclareVotesForm = ({
|
|||
return () => {
|
||||
toast.dismiss(toastId)
|
||||
}
|
||||
}, [outboxRow, leadershipID, municipalityID, router])
|
||||
}, [outboxRow, leadershipID, municipalityID, pledgeId, router])
|
||||
|
||||
const onSubmit = (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault()
|
||||
|
|
@ -254,6 +267,7 @@ const HybridDeclareVotesForm = ({
|
|||
void enqueueDeclareVotes({
|
||||
municipalityId: municipalityID,
|
||||
leadershipId: leadershipID,
|
||||
pledgeId,
|
||||
declaredVotes: Math.trunc(declaredVotes),
|
||||
baseUpdatedAt,
|
||||
}).then(
|
||||
|
|
|
|||
|
|
@ -101,10 +101,6 @@ export const MUNICIPALITY_ENGAGEMENT_LEVEL_SAFE_MESSAGES = [
|
|||
OPS_UPDATED_AT_CONFLICT_MESSAGE,
|
||||
] as const
|
||||
|
||||
export const MUNICIPALITY_POLITICAL_TREND_SAFE_MESSAGES = [
|
||||
OPS_UPDATED_AT_CONFLICT_MESSAGE,
|
||||
] as const
|
||||
|
||||
/**
|
||||
* E14 — a movement is never just the new level: the motivo and the signals
|
||||
* that would reverse it are what make the decision auditable later, so both
|
||||
|
|
@ -126,8 +122,6 @@ export const municipalityEngagementLevelSchema = z.object({
|
|||
export const municipalityExpectedVotesSchema = z.object({
|
||||
municipality: positiveRelationshipId,
|
||||
expectedVotes: voteEstimateScenarioFieldsSchema,
|
||||
/** OH10 CAS opt-in on municipality `updatedAt`. Absent → last-write-wins. */
|
||||
baseUpdatedAt: optionalBaseUpdatedAtSchema,
|
||||
})
|
||||
|
||||
export type MunicipalityStrategyUpdateInput = z.input<typeof municipalityStrategyUpdateSchema>
|
||||
|
|
|
|||
Loading…
Reference in a new issue