diff --git a/docs/plans/oh10-municipality-writes-cas.md b/docs/plans/oh10-municipality-writes-cas.md index 5316a859..ca07958b 100644 --- a/docs/plans/oh10-municipality-writes-cas.md +++ b/docs/plans/oh10-municipality-writes-cas.md @@ -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`. diff --git a/src/app/(campaign)/campanha/actions/municipality.ts b/src/app/(campaign)/campanha/actions/municipality.ts index b27c255a..86d5e1fe 100644 --- a/src/app/(campaign)/campanha/actions/municipality.ts +++ b/src/app/(campaign)/campanha/actions/municipality.ts @@ -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, diff --git a/src/components/campaign/municipality/MunicipalityLeadershipsPanel.tsx b/src/components/campaign/municipality/MunicipalityLeadershipsPanel.tsx index 7534d596..bb8eb851 100644 --- a/src/components/campaign/municipality/MunicipalityLeadershipsPanel.tsx +++ b/src/components/campaign/municipality/MunicipalityLeadershipsPanel.tsx @@ -81,6 +81,7 @@ export const MunicipalityLeadershipsPanel = ({ { + const router = useRouter() + const opsHybrid = resolveOpsHybridEnabled() const [open, setOpen] = useState(false) const [selectedIDs, setSelectedIDs] = useState(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(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 = ({

O assessor vê e gerencia somente os municípios que administra.

- {isPending ? ( + {isPending || outboxPending ? ( { + const mirrorUpdatedAt = municipalitiesCollection.get(municipalityID)?.updatedAt await enqueuePoliticalTrend({ municipalityId: municipalityID, status: trend.status, note: trend.note, - baseUpdatedAt: updatedAt, + baseUpdatedAt: mirrorUpdatedAt ?? updatedAt, }) return { ok: true, diff --git a/src/components/campaign/municipality/MunicipalityUpdateForm.tsx b/src/components/campaign/municipality/MunicipalityUpdateForm.tsx index ab385a36..51757532 100644 --- a/src/components/campaign/municipality/MunicipalityUpdateForm.tsx +++ b/src/components/campaign/municipality/MunicipalityUpdateForm.tsx @@ -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) diff --git a/src/components/campaign/opsSync/opsMunicipalityOutbox.ts b/src/components/campaign/opsSync/opsMunicipalityOutbox.ts index 7f3103f4..de167a6e 100644 --- a/src/components/campaign/opsSync/opsMunicipalityOutbox.ts +++ b/src/components/campaign/opsSync/opsMunicipalityOutbox.ts @@ -369,13 +369,18 @@ export const enqueueDeclareVotes = async (input: { municipalityId: number leadershipId: number declaredVotes: number + pledgeId?: number baseUpdatedAt?: string | null }): Promise => { 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 => { const keys = new Set() 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) diff --git a/src/components/campaign/opsSync/opsMunicipalityOutboxModel.ts b/src/components/campaign/opsSync/opsMunicipalityOutboxModel.ts index ffbfa017..416ea677 100644 --- a/src/components/campaign/opsSync/opsMunicipalityOutboxModel.ts +++ b/src/components/campaign/opsSync/opsMunicipalityOutboxModel.ts @@ -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 diff --git a/src/components/campaign/opsSync/opsVotePledgeMirror.ts b/src/components/campaign/opsSync/opsVotePledgeMirror.ts index 51e29937..d5ecfbf3 100644 --- a/src/components/campaign/opsSync/opsVotePledgeMirror.ts +++ b/src/components/campaign/opsSync/opsVotePledgeMirror.ts @@ -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 diff --git a/src/components/campaign/votePledge/DeclareVotesForm.tsx b/src/components/campaign/votePledge/DeclareVotesForm.tsx index a7dc5e94..c845d025 100644 --- a/src/components/campaign/votePledge/DeclareVotesForm.tsx +++ b/src/components/campaign/votePledge/DeclareVotesForm.tsx @@ -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 = ({ @@ -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(null) const [baseOverride, setBaseOverride] = useState(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) => { event.preventDefault() @@ -254,6 +267,7 @@ const HybridDeclareVotesForm = ({ void enqueueDeclareVotes({ municipalityId: municipalityID, leadershipId: leadershipID, + pledgeId, declaredVotes: Math.trunc(declaredVotes), baseUpdatedAt, }).then( diff --git a/src/lib/schemas/municipality.ts b/src/lib/schemas/municipality.ts index 4bdf51a0..12b0d4a8 100644 --- a/src/lib/schemas/municipality.ts +++ b/src/lib/schemas/municipality.ts @@ -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