mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-27 06:13: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
|
# OH10 — Writes municipality staff CAS: update, declareVotes, tendência, engagement, advisors
|
||||||
|
|
||||||
Status: em implementação
|
Status: pronto para PR
|
||||||
Atualizado em: 2026-08-02
|
Atualizado em: 2026-08-02
|
||||||
Issue: #171
|
Issue: #171
|
||||||
Priority: P1
|
Priority: P1
|
||||||
|
|
@ -10,6 +10,11 @@ Appetite: ~2–3 dias eng
|
||||||
Depends: OH7, OH9
|
Depends: OH7, OH9
|
||||||
Responsável: —
|
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)
|
## 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`.
|
- 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)
|
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 (
|
export const setMunicipalityAdvisorMembershipCasRecord = async (
|
||||||
payload: Payload,
|
payload: Payload,
|
||||||
actor: CampaignUser,
|
actor: CampaignUser,
|
||||||
|
|
|
||||||
|
|
@ -81,6 +81,7 @@ export const MunicipalityLeadershipsPanel = ({
|
||||||
<DeclareVotesForm
|
<DeclareVotesForm
|
||||||
municipalityID={municipalityID}
|
municipalityID={municipalityID}
|
||||||
leadershipID={leadership.id}
|
leadershipID={leadership.id}
|
||||||
|
pledgeId={pledge?.id}
|
||||||
currentDeclaredVotes={pledge?.declaredVotes ?? null}
|
currentDeclaredVotes={pledge?.declaredVotes ?? null}
|
||||||
currentUpdatedAt={pledge?.updatedAt ?? null}
|
currentUpdatedAt={pledge?.updatedAt ?? null}
|
||||||
formAction={declareFormAction}
|
formAction={declareFormAction}
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,9 @@
|
||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { XIcon } from 'lucide-react'
|
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 type { MunicipalityListAdvisorsResponse } from '@/app/(campaign)/campanha/(app)/municipios/advisors/types'
|
||||||
import {
|
import {
|
||||||
|
|
@ -14,13 +16,21 @@ import {
|
||||||
type CampaignCellEditOverlayVariant,
|
type CampaignCellEditOverlayVariant,
|
||||||
} from '@/components/campaign/shared/CampaignCellEditOverlay'
|
} from '@/components/campaign/shared/CampaignCellEditOverlay'
|
||||||
import { useCampaignCellFailureChannel } from '@/components/campaign/shared/useCampaignCellFailureChannel'
|
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 { Alert, AlertDescription } from '@/components/ui/Alert'
|
||||||
import { Badge } from '@/components/ui/Badge'
|
import { Badge } from '@/components/ui/Badge'
|
||||||
import { Command, CommandInput, CommandItem, CommandList } from '@/components/ui/Command'
|
import { Command, CommandInput, CommandItem, CommandList } from '@/components/ui/Command'
|
||||||
import { Spinner } from '@/components/ui/Spinner'
|
import { Spinner } from '@/components/ui/Spinner'
|
||||||
import { postCampaignJson } from '@/lib/campaignJsonRequest'
|
import { postCampaignJson } from '@/lib/campaignJsonRequest'
|
||||||
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
|
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
|
||||||
|
import { OPS_UPDATED_AT_CONFLICT_MESSAGE } from '@/lib/schemas/opsCas'
|
||||||
import { sameIdSet } from '@/lib/sameIdSet'
|
import { sameIdSet } from '@/lib/sameIdSet'
|
||||||
import { cn } from '@/lib/utils'
|
import { cn } from '@/lib/utils'
|
||||||
import { matchesAtWordStart } from '@/lib/wordStartFilter'
|
import { matchesAtWordStart } from '@/lib/wordStartFilter'
|
||||||
|
|
@ -31,6 +41,7 @@ import type {
|
||||||
|
|
||||||
const ADVISORS_ENDPOINT = '/campanha/municipios/advisors'
|
const ADVISORS_ENDPOINT = '/campanha/municipios/advisors'
|
||||||
const SAVE_ERROR_MESSAGE = 'Não foi possível atualizar os assessores. Tente novamente.'
|
const SAVE_ERROR_MESSAGE = 'Não foi possível atualizar os assessores. Tente novamente.'
|
||||||
|
const CONFLICT_TOAST_ID_PREFIX = 'ops-advisors-conflict:'
|
||||||
|
|
||||||
type MunicipalityListAdvisorsControlProps = {
|
type MunicipalityListAdvisorsControlProps = {
|
||||||
municipalityID: number
|
municipalityID: number
|
||||||
|
|
@ -55,6 +66,8 @@ export const MunicipalityListAdvisorsControl = ({
|
||||||
updatedAt,
|
updatedAt,
|
||||||
variant,
|
variant,
|
||||||
}: MunicipalityListAdvisorsControlProps) => {
|
}: MunicipalityListAdvisorsControlProps) => {
|
||||||
|
const router = useRouter()
|
||||||
|
const opsHybrid = resolveOpsHybridEnabled()
|
||||||
const [open, setOpen] = useState(false)
|
const [open, setOpen] = useState(false)
|
||||||
const [selectedIDs, setSelectedIDs] = useState<number[]>(currentAdvisorIDs)
|
const [selectedIDs, setSelectedIDs] = useState<number[]>(currentAdvisorIDs)
|
||||||
const [query, setQuery] = useState('')
|
const [query, setQuery] = useState('')
|
||||||
|
|
@ -74,6 +87,14 @@ export const MunicipalityListAdvisorsControl = ({
|
||||||
// clobber the optimistic state back to it.
|
// clobber the optimistic state back to it.
|
||||||
const requestSeqRef = useRef(0)
|
const requestSeqRef = useRef(0)
|
||||||
const latestConfirmedRef = useRef<{ seq: number; advisors: number[] } | null>(null)
|
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) => {
|
const handleOpenChange = (nextOpen: boolean) => {
|
||||||
noteOpenChange(nextOpen)
|
noteOpenChange(nextOpen)
|
||||||
|
|
@ -89,6 +110,51 @@ export const MunicipalityListAdvisorsControl = ({
|
||||||
setSelectedIDs(currentAdvisorIDs)
|
setSelectedIDs(currentAdvisorIDs)
|
||||||
}, [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
|
// Every eligible account (coordinator/advisor/candidate) is listed here
|
||||||
// regardless of current assignment, so it doubles as the name lookup for an
|
// 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
|
// id the popover just optimistically added — no round trip needed to label
|
||||||
|
|
@ -164,11 +230,12 @@ export const MunicipalityListAdvisorsControl = ({
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (resolveOpsHybridEnabled()) {
|
if (opsHybrid) {
|
||||||
|
const mirrorUpdatedAt = municipalitiesCollection.get(municipalityID)?.updatedAt
|
||||||
await enqueueAdvisorsAssignment({
|
await enqueueAdvisorsAssignment({
|
||||||
municipalityId: municipalityID,
|
municipalityId: municipalityID,
|
||||||
advisors: nextIds,
|
advisors: nextIds,
|
||||||
baseUpdatedAt: updatedAt,
|
baseUpdatedAt: mirrorUpdatedAt ?? updatedAt,
|
||||||
})
|
})
|
||||||
if (requestSeq > (latestConfirmedRef.current?.seq ?? 0)) {
|
if (requestSeq > (latestConfirmedRef.current?.seq ?? 0)) {
|
||||||
latestConfirmedRef.current = { seq: requestSeq, advisors: nextIds }
|
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 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
|
// the `Command` can stay full-bleed in both containers — hence `px-0` on the
|
||||||
// sheet body and `p-0` on the popover content.
|
// 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
|
// 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.
|
// even those — so who is assigned goes in the label, by extenso.
|
||||||
triggerLabel={`Editar assessores em ${municipalityName} — ${assignedLabel}`}
|
triggerLabel={`Editar assessores em ${municipalityName} — ${assignedLabel}`}
|
||||||
triggerBusy={isPending}
|
triggerBusy={isPending || outboxPending}
|
||||||
statusMessage={statusMessage}
|
statusMessage={statusMessage}
|
||||||
tooltipContent={tooltipContent}
|
tooltipContent={tooltipContent}
|
||||||
contentClassName="w-80 p-0"
|
contentClassName="w-80 p-0"
|
||||||
|
|
@ -232,7 +304,7 @@ export const MunicipalityListAdvisorsControl = ({
|
||||||
<p className={cn('text-xs text-muted-foreground', isSheet && 'pr-6')}>
|
<p className={cn('text-xs text-muted-foreground', isSheet && 'pr-6')}>
|
||||||
O assessor vê e gerencia somente os municípios que administra.
|
O assessor vê e gerencia somente os municípios que administra.
|
||||||
</p>
|
</p>
|
||||||
{isPending ? (
|
{isPending || outboxPending ? (
|
||||||
<Spinner
|
<Spinner
|
||||||
className={cn(
|
className={cn(
|
||||||
'absolute size-3.5 text-muted-foreground',
|
'absolute size-3.5 text-muted-foreground',
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,7 @@ import {
|
||||||
type CampaignCellEditOverlayVariant,
|
type CampaignCellEditOverlayVariant,
|
||||||
} from '@/components/campaign/shared/CampaignCellEditOverlay'
|
} from '@/components/campaign/shared/CampaignCellEditOverlay'
|
||||||
import { useCampaignCellFailureChannel } from '@/components/campaign/shared/useCampaignCellFailureChannel'
|
import { useCampaignCellFailureChannel } from '@/components/campaign/shared/useCampaignCellFailureChannel'
|
||||||
|
import { municipalitiesCollection } from '@/components/campaign/opsSync/opsMirrorClient'
|
||||||
import { enqueueEngagementLevel } from '@/components/campaign/opsSync/opsMunicipalityOutbox'
|
import { enqueueEngagementLevel } from '@/components/campaign/opsSync/opsMunicipalityOutbox'
|
||||||
import { Alert, AlertDescription } from '@/components/ui/Alert'
|
import { Alert, AlertDescription } from '@/components/ui/Alert'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
|
|
@ -170,6 +171,7 @@ export const MunicipalityListLevelControl = ({
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (resolveOpsHybridEnabled()) {
|
if (resolveOpsHybridEnabled()) {
|
||||||
|
const mirrorUpdatedAt = municipalitiesCollection.get(municipalityID)?.updatedAt
|
||||||
await enqueueEngagementLevel({
|
await enqueueEngagementLevel({
|
||||||
municipalityId: municipalityID,
|
municipalityId: municipalityID,
|
||||||
level: draftLevel,
|
level: draftLevel,
|
||||||
|
|
@ -177,7 +179,7 @@ export const MunicipalityListLevelControl = ({
|
||||||
reversalSignals,
|
reversalSignals,
|
||||||
triangulatedShock,
|
triangulatedShock,
|
||||||
override,
|
override,
|
||||||
baseUpdatedAt: updatedAt,
|
baseUpdatedAt: mirrorUpdatedAt ?? updatedAt,
|
||||||
})
|
})
|
||||||
setSaved({
|
setSaved({
|
||||||
level: draftLevel,
|
level: draftLevel,
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,7 @@ import {
|
||||||
type CampaignCellEditOverlayVariant,
|
type CampaignCellEditOverlayVariant,
|
||||||
} from '@/components/campaign/shared/CampaignCellEditOverlay'
|
} from '@/components/campaign/shared/CampaignCellEditOverlay'
|
||||||
import { useCampaignCellAutosave } from '@/components/campaign/shared/useCampaignCellAutosave'
|
import { useCampaignCellAutosave } from '@/components/campaign/shared/useCampaignCellAutosave'
|
||||||
|
import { municipalitiesCollection } from '@/components/campaign/opsSync/opsMirrorClient'
|
||||||
import { enqueuePoliticalTrend } from '@/components/campaign/opsSync/opsMunicipalityOutbox'
|
import { enqueuePoliticalTrend } from '@/components/campaign/opsSync/opsMunicipalityOutbox'
|
||||||
import { Alert, AlertDescription } from '@/components/ui/Alert'
|
import { Alert, AlertDescription } from '@/components/ui/Alert'
|
||||||
import { Badge } from '@/components/ui/Badge'
|
import { Badge } from '@/components/ui/Badge'
|
||||||
|
|
@ -81,11 +82,12 @@ export const MunicipalityListTrendControl = ({
|
||||||
pendingMessage: 'Salvando tendência.',
|
pendingMessage: 'Salvando tendência.',
|
||||||
persist: opsHybrid
|
persist: opsHybrid
|
||||||
? async (trend) => {
|
? async (trend) => {
|
||||||
|
const mirrorUpdatedAt = municipalitiesCollection.get(municipalityID)?.updatedAt
|
||||||
await enqueuePoliticalTrend({
|
await enqueuePoliticalTrend({
|
||||||
municipalityId: municipalityID,
|
municipalityId: municipalityID,
|
||||||
status: trend.status,
|
status: trend.status,
|
||||||
note: trend.note,
|
note: trend.note,
|
||||||
baseUpdatedAt: updatedAt,
|
baseUpdatedAt: mirrorUpdatedAt ?? updatedAt,
|
||||||
})
|
})
|
||||||
return {
|
return {
|
||||||
ok: true,
|
ok: true,
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@
|
||||||
|
|
||||||
import { useActionState, useState, type FormEvent } from 'react'
|
import { useActionState, useState, type FormEvent } from 'react'
|
||||||
|
|
||||||
|
import { municipalitiesCollection } from '@/components/campaign/opsSync/opsMirrorClient'
|
||||||
import { enqueueMunicipalityUpdate } from '@/components/campaign/opsSync/opsMunicipalityOutbox'
|
import { enqueueMunicipalityUpdate } from '@/components/campaign/opsSync/opsMunicipalityOutbox'
|
||||||
import { CampaignFormActionMessage } from '@/components/campaign/shared/CampaignFormActionMessage'
|
import { CampaignFormActionMessage } from '@/components/campaign/shared/CampaignFormActionMessage'
|
||||||
import { Badge } from '@/components/ui/Badge'
|
import { Badge } from '@/components/ui/Badge'
|
||||||
|
|
@ -69,6 +70,7 @@ export const MunicipalityUpdateForm = ({
|
||||||
|
|
||||||
setHybridPending(true)
|
setHybridPending(true)
|
||||||
setHybridMessage(null)
|
setHybridMessage(null)
|
||||||
|
const mirrorUpdatedAt = municipalitiesCollection.get(municipalityID)?.updatedAt
|
||||||
void enqueueMunicipalityUpdate({
|
void enqueueMunicipalityUpdate({
|
||||||
clientId: crypto.randomUUID(),
|
clientId: crypto.randomUUID(),
|
||||||
municipalityId: municipalityID,
|
municipalityId: municipalityID,
|
||||||
|
|
@ -80,7 +82,7 @@ export const MunicipalityUpdateForm = ({
|
||||||
activeVolunteers: readCount('activeVolunteers'),
|
activeVolunteers: readCount('activeVolunteers'),
|
||||||
newSupports: readCount('newSupports'),
|
newSupports: readCount('newSupports'),
|
||||||
signalType: parseMunicipalitySignalType(readText('signalType')),
|
signalType: parseMunicipalitySignalType(readText('signalType')),
|
||||||
baseUpdatedAt: municipalityUpdatedAt,
|
baseUpdatedAt: mirrorUpdatedAt ?? municipalityUpdatedAt,
|
||||||
}).then(
|
}).then(
|
||||||
() => {
|
() => {
|
||||||
setHybridPending(false)
|
setHybridPending(false)
|
||||||
|
|
|
||||||
|
|
@ -369,13 +369,18 @@ export const enqueueDeclareVotes = async (input: {
|
||||||
municipalityId: number
|
municipalityId: number
|
||||||
leadershipId: number
|
leadershipId: number
|
||||||
declaredVotes: number
|
declaredVotes: number
|
||||||
|
pledgeId?: number
|
||||||
baseUpdatedAt?: string | null
|
baseUpdatedAt?: string | null
|
||||||
}): Promise<void> => {
|
}): Promise<void> => {
|
||||||
const executor = await getOpsMunicipalityOfflineExecutor()
|
const executor = await getOpsMunicipalityOfflineExecutor()
|
||||||
const id = declareVotesOutboxKey(input.leadershipId, input.municipalityId)
|
const id = declareVotesOutboxKey(input.leadershipId, input.municipalityId)
|
||||||
const mirrorPledge = votePledgesCollection.toArray.find(
|
const mirrorPledge =
|
||||||
(row) => row.leadership === input.leadershipId && row.municipality === input.municipalityId,
|
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 =
|
const baseUpdatedAt =
|
||||||
input.baseUpdatedAt !== undefined ? input.baseUpdatedAt : (mirrorPledge?.updatedAt ?? null)
|
input.baseUpdatedAt !== undefined ? input.baseUpdatedAt : (mirrorPledge?.updatedAt ?? null)
|
||||||
|
|
||||||
|
|
@ -386,18 +391,20 @@ export const enqueueDeclareVotes = async (input: {
|
||||||
id,
|
id,
|
||||||
municipalityId: variables.municipalityId,
|
municipalityId: variables.municipalityId,
|
||||||
leadershipId: variables.leadershipId,
|
leadershipId: variables.leadershipId,
|
||||||
|
pledgeId,
|
||||||
declaredVotes: variables.declaredVotes,
|
declaredVotes: variables.declaredVotes,
|
||||||
baseUpdatedAt: variables.baseUpdatedAt ?? baseUpdatedAt,
|
baseUpdatedAt: variables.baseUpdatedAt ?? baseUpdatedAt,
|
||||||
status: 'pending',
|
status: 'pending',
|
||||||
}
|
}
|
||||||
if (mirrorPledge && votePledgesCollection.has(mirrorPledge.id)) {
|
if (pledgeId !== undefined && votePledgesCollection.has(pledgeId)) {
|
||||||
votePledgesCollection.update(mirrorPledge.id, (draft) => {
|
votePledgesCollection.update(pledgeId, (draft) => {
|
||||||
draft.declaredVotes = variables.declaredVotes
|
draft.declaredVotes = variables.declaredVotes
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
if (declareVotesOutboxCollection.has(id)) {
|
if (declareVotesOutboxCollection.has(id)) {
|
||||||
declareVotesOutboxCollection.update(id, (draft) => {
|
declareVotesOutboxCollection.update(id, (draft) => {
|
||||||
draft.declaredVotes = next.declaredVotes
|
draft.declaredVotes = next.declaredVotes
|
||||||
|
draft.pledgeId = next.pledgeId
|
||||||
draft.baseUpdatedAt = next.baseUpdatedAt
|
draft.baseUpdatedAt = next.baseUpdatedAt
|
||||||
draft.status = 'pending'
|
draft.status = 'pending'
|
||||||
draft.serverUpdatedAt = undefined
|
draft.serverUpdatedAt = undefined
|
||||||
|
|
@ -408,7 +415,7 @@ export const enqueueDeclareVotes = async (input: {
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
run({ ...input, baseUpdatedAt })
|
run({ ...input, baseUpdatedAt, pledgeId })
|
||||||
}
|
}
|
||||||
|
|
||||||
export const enqueueMunicipalityUpdate = async (input: {
|
export const enqueueMunicipalityUpdate = async (input: {
|
||||||
|
|
@ -560,10 +567,14 @@ export const collectOpsMunicipalityOutboxKeys = (): Set<OpsOutboxKey> => {
|
||||||
const keys = new Set<OpsOutboxKey>()
|
const keys = new Set<OpsOutboxKey>()
|
||||||
for (const row of declareVotesOutboxCollection.toArray) {
|
for (const row of declareVotesOutboxCollection.toArray) {
|
||||||
if (row.status === 'pending' || row.status === 'conflict') {
|
if (row.status === 'pending' || row.status === 'conflict') {
|
||||||
const pledge = votePledgesCollection.toArray.find(
|
if (row.pledgeId !== undefined) {
|
||||||
(p) => p.leadership === row.leadershipId && p.municipality === row.municipalityId,
|
keys.add(opsOutboxKey('votePledges', row.pledgeId))
|
||||||
)
|
} else {
|
||||||
if (pledge) keys.add(opsOutboxKey('votePledges', pledge.id))
|
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) {
|
for (const row of municipalityUpdateOutboxCollection.toArray) {
|
||||||
|
|
@ -619,17 +630,17 @@ export const discardOpsDeclareVotesOutboxRow = (
|
||||||
if (declareVotesOutboxCollection.has(id)) declareVotesOutboxCollection.delete(id)
|
if (declareVotesOutboxCollection.has(id)) declareVotesOutboxCollection.delete(id)
|
||||||
}
|
}
|
||||||
|
|
||||||
export const readOpsPoliticalTrendOutboxRow = (
|
export const readOpsAdvisorsOutboxRow = (
|
||||||
municipalityId: number,
|
municipalityId: number,
|
||||||
): OpsPoliticalTrendOutboxRow | undefined => politicalTrendOutboxCollection.get(municipalityId)
|
): OpsAdvisorsOutboxRow | undefined => advisorsOutboxCollection.get(municipalityId)
|
||||||
|
|
||||||
export const subscribeOpsPoliticalTrendOutboxRow = (
|
export const subscribeOpsAdvisorsOutboxRow = (
|
||||||
municipalityId: number,
|
municipalityId: number,
|
||||||
onStoreChange: () => void,
|
onStoreChange: () => void,
|
||||||
): (() => void) => {
|
): (() => void) => {
|
||||||
let previous = politicalTrendOutboxCollection.get(municipalityId)
|
let previous = advisorsOutboxCollection.get(municipalityId)
|
||||||
const subscription = politicalTrendOutboxCollection.subscribeChanges(() => {
|
const subscription = advisorsOutboxCollection.subscribeChanges(() => {
|
||||||
const next = politicalTrendOutboxCollection.get(municipalityId)
|
const next = advisorsOutboxCollection.get(municipalityId)
|
||||||
if (next === previous) return
|
if (next === previous) return
|
||||||
previous = next
|
previous = next
|
||||||
onStoreChange()
|
onStoreChange()
|
||||||
|
|
@ -637,26 +648,6 @@ export const subscribeOpsPoliticalTrendOutboxRow = (
|
||||||
return () => subscription.unsubscribe()
|
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 => {
|
export const discardOpsAdvisorsOutboxRow = (municipalityId: number): void => {
|
||||||
if (advisorsOutboxCollection.has(municipalityId)) {
|
if (advisorsOutboxCollection.has(municipalityId)) {
|
||||||
advisorsOutboxCollection.delete(municipalityId)
|
advisorsOutboxCollection.delete(municipalityId)
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,8 @@ export type OpsDeclareVotesOutboxRow = {
|
||||||
id: string
|
id: string
|
||||||
municipalityId: number
|
municipalityId: number
|
||||||
leadershipId: number
|
leadershipId: number
|
||||||
|
/** Mirror pledge id when known — avoids O(n) lookup in collectOutboxKeys. */
|
||||||
|
pledgeId?: number
|
||||||
declaredVotes: number
|
declaredVotes: number
|
||||||
baseUpdatedAt?: string | null
|
baseUpdatedAt?: string | null
|
||||||
status: OpsMunicipalityWriteSyncStatus
|
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 => {
|
export const applyOpsVotePledgeEstimateWrite = (doc: VotePledgeEstimateWriteResult): void => {
|
||||||
const mapped = mapVotePledgeWriteToOps(doc)
|
const mapped = mapVotePledgeWriteToOps(doc)
|
||||||
if (votePledgesCollection.has(mapped.id)) {
|
if (votePledgesCollection.has(mapped.id)) {
|
||||||
votePledgesCollection.update(mapped.id, (draft) => {
|
votePledgesCollection.update(mapped.id, (draft) => {
|
||||||
|
draft.declaredVotes = mapped.declaredVotes
|
||||||
|
draft.declaredAt = mapped.declaredAt
|
||||||
|
draft.declaredBy = mapped.declaredBy
|
||||||
draft.estimatedVotes = mapped.estimatedVotes
|
draft.estimatedVotes = mapped.estimatedVotes
|
||||||
draft.estimateNote = mapped.estimateNote
|
draft.estimateNote = mapped.estimateNote
|
||||||
draft.estimatedAt = mapped.estimatedAt
|
draft.estimatedAt = mapped.estimatedAt
|
||||||
|
|
|
||||||
|
|
@ -39,6 +39,8 @@ type DeclareVotesFormProps = {
|
||||||
municipalityID: number
|
municipalityID: number
|
||||||
/** Present when staff declare on behalf of a leadership. */
|
/** Present when staff declare on behalf of a leadership. */
|
||||||
leadershipID?: number
|
leadershipID?: number
|
||||||
|
/** Mirror / outbox key when a pledge row already exists (OH10). */
|
||||||
|
pledgeId?: number
|
||||||
currentDeclaredVotes: number | null
|
currentDeclaredVotes: number | null
|
||||||
/** Pledge row `updatedAt` for CAS when a pledge already exists. */
|
/** Pledge row `updatedAt` for CAS when a pledge already exists. */
|
||||||
currentUpdatedAt?: string | null
|
currentUpdatedAt?: string | null
|
||||||
|
|
@ -61,6 +63,7 @@ const CONFLICT_TOAST_ID_PREFIX = 'ops-declare-conflict:'
|
||||||
export const DeclareVotesForm = ({
|
export const DeclareVotesForm = ({
|
||||||
municipalityID,
|
municipalityID,
|
||||||
leadershipID,
|
leadershipID,
|
||||||
|
pledgeId,
|
||||||
currentDeclaredVotes,
|
currentDeclaredVotes,
|
||||||
currentUpdatedAt = null,
|
currentUpdatedAt = null,
|
||||||
opsHybridEnabled = resolveOpsHybridEnabled(),
|
opsHybridEnabled = resolveOpsHybridEnabled(),
|
||||||
|
|
@ -81,6 +84,7 @@ export const DeclareVotesForm = ({
|
||||||
<HybridDeclareVotesForm
|
<HybridDeclareVotesForm
|
||||||
municipalityID={municipalityID}
|
municipalityID={municipalityID}
|
||||||
leadershipID={leadershipID}
|
leadershipID={leadershipID}
|
||||||
|
pledgeId={pledgeId}
|
||||||
currentDeclaredVotes={currentDeclaredVotes}
|
currentDeclaredVotes={currentDeclaredVotes}
|
||||||
currentUpdatedAt={currentUpdatedAt}
|
currentUpdatedAt={currentUpdatedAt}
|
||||||
/>
|
/>
|
||||||
|
|
@ -136,11 +140,13 @@ const LegacyDeclareVotesForm = ({
|
||||||
const HybridDeclareVotesForm = ({
|
const HybridDeclareVotesForm = ({
|
||||||
municipalityID,
|
municipalityID,
|
||||||
leadershipID,
|
leadershipID,
|
||||||
|
pledgeId: initialPledgeId,
|
||||||
currentDeclaredVotes,
|
currentDeclaredVotes,
|
||||||
currentUpdatedAt,
|
currentUpdatedAt,
|
||||||
}: {
|
}: {
|
||||||
municipalityID: number
|
municipalityID: number
|
||||||
leadershipID: number
|
leadershipID: number
|
||||||
|
pledgeId?: number
|
||||||
currentDeclaredVotes: number | null
|
currentDeclaredVotes: number | null
|
||||||
currentUpdatedAt: string | null
|
currentUpdatedAt: string | null
|
||||||
}) => {
|
}) => {
|
||||||
|
|
@ -152,21 +158,27 @@ const HybridDeclareVotesForm = ({
|
||||||
const [formError, setFormError] = useState<string | null>(null)
|
const [formError, setFormError] = useState<string | null>(null)
|
||||||
const [baseOverride, setBaseOverride] = useState<string | null | undefined>(undefined)
|
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(
|
const mirrorPledge = useSyncExternalStore(
|
||||||
(onStoreChange) => {
|
(onStoreChange) => {
|
||||||
const pledge = votePledgesCollection.toArray.find(
|
if (resolvedPledgeId === undefined) return () => undefined
|
||||||
(row) => row.leadership === leadershipID && row.municipality === municipalityID,
|
return subscribeOpsVotePledge(resolvedPledgeId, onStoreChange)
|
||||||
)
|
|
||||||
if (!pledge) return () => undefined
|
|
||||||
return subscribeOpsVotePledge(pledge.id, onStoreChange)
|
|
||||||
},
|
},
|
||||||
() =>
|
() =>
|
||||||
votePledgesCollection.toArray.find(
|
resolvedPledgeId !== undefined
|
||||||
(row) => row.leadership === leadershipID && row.municipality === municipalityID,
|
? votePledgesCollection.get(resolvedPledgeId)
|
||||||
),
|
: votePledgesCollection.toArray.find(
|
||||||
|
(row) => row.leadership === leadershipID && row.municipality === municipalityID,
|
||||||
|
),
|
||||||
() => undefined,
|
() => undefined,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const pledgeId = initialPledgeId ?? mirrorPledge?.id
|
||||||
const displayVotes = mirrorPledge?.declaredVotes ?? currentDeclaredVotes
|
const displayVotes = mirrorPledge?.declaredVotes ?? currentDeclaredVotes
|
||||||
const mirrorUpdatedAt = mirrorPledge?.updatedAt ?? currentUpdatedAt
|
const mirrorUpdatedAt = mirrorPledge?.updatedAt ?? currentUpdatedAt
|
||||||
const baseUpdatedAt = baseOverride !== undefined ? baseOverride : mirrorUpdatedAt
|
const baseUpdatedAt = baseOverride !== undefined ? baseOverride : mirrorUpdatedAt
|
||||||
|
|
@ -211,6 +223,7 @@ const HybridDeclareVotesForm = ({
|
||||||
void enqueueDeclareVotes({
|
void enqueueDeclareVotes({
|
||||||
municipalityId: municipalityID,
|
municipalityId: municipalityID,
|
||||||
leadershipId: leadershipID,
|
leadershipId: leadershipID,
|
||||||
|
pledgeId,
|
||||||
declaredVotes: Math.trunc(declaredVotes),
|
declaredVotes: Math.trunc(declaredVotes),
|
||||||
baseUpdatedAt: outboxRow.serverUpdatedAt ?? null,
|
baseUpdatedAt: outboxRow.serverUpdatedAt ?? null,
|
||||||
}).then(
|
}).then(
|
||||||
|
|
@ -238,7 +251,7 @@ const HybridDeclareVotesForm = ({
|
||||||
return () => {
|
return () => {
|
||||||
toast.dismiss(toastId)
|
toast.dismiss(toastId)
|
||||||
}
|
}
|
||||||
}, [outboxRow, leadershipID, municipalityID, router])
|
}, [outboxRow, leadershipID, municipalityID, pledgeId, router])
|
||||||
|
|
||||||
const onSubmit = (event: FormEvent<HTMLFormElement>) => {
|
const onSubmit = (event: FormEvent<HTMLFormElement>) => {
|
||||||
event.preventDefault()
|
event.preventDefault()
|
||||||
|
|
@ -254,6 +267,7 @@ const HybridDeclareVotesForm = ({
|
||||||
void enqueueDeclareVotes({
|
void enqueueDeclareVotes({
|
||||||
municipalityId: municipalityID,
|
municipalityId: municipalityID,
|
||||||
leadershipId: leadershipID,
|
leadershipId: leadershipID,
|
||||||
|
pledgeId,
|
||||||
declaredVotes: Math.trunc(declaredVotes),
|
declaredVotes: Math.trunc(declaredVotes),
|
||||||
baseUpdatedAt,
|
baseUpdatedAt,
|
||||||
}).then(
|
}).then(
|
||||||
|
|
|
||||||
|
|
@ -101,10 +101,6 @@ export const MUNICIPALITY_ENGAGEMENT_LEVEL_SAFE_MESSAGES = [
|
||||||
OPS_UPDATED_AT_CONFLICT_MESSAGE,
|
OPS_UPDATED_AT_CONFLICT_MESSAGE,
|
||||||
] as const
|
] 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
|
* 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
|
* 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({
|
export const municipalityExpectedVotesSchema = z.object({
|
||||||
municipality: positiveRelationshipId,
|
municipality: positiveRelationshipId,
|
||||||
expectedVotes: voteEstimateScenarioFieldsSchema,
|
expectedVotes: voteEstimateScenarioFieldsSchema,
|
||||||
/** OH10 CAS opt-in on municipality `updatedAt`. Absent → last-write-wins. */
|
|
||||||
baseUpdatedAt: optionalBaseUpdatedAtSchema,
|
|
||||||
})
|
})
|
||||||
|
|
||||||
export type MunicipalityStrategyUpdateInput = z.input<typeof municipalityStrategyUpdateSchema>
|
export type MunicipalityStrategyUpdateInput = z.input<typeof municipalityStrategyUpdateSchema>
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue