fix(OH6): bootstrap outbox on mount and tighten CAS/subscribe

Restore IndexedDB pending rows on hybrid form mount, drop synced stubs
so RSC props win, gate the post-lock re-read to CAS only, and notify
per-pledge subscribers instead of every estimate island.

Co-authored-by: Francisco Solla <fsolla@users.noreply.github.com>
This commit is contained in:
Cursor Agent 2026-08-01 22:15:19 +00:00
parent f7e3591ea9
commit 9a402d2ac1
No known key found for this signature in database
3 changed files with 58 additions and 38 deletions

View file

@ -160,16 +160,19 @@ export const estimateVotesRecord = async (
`vote-pledge:${requireRelationshipId(pledge.leadership)}:${requireRelationshipId(pledge.municipality)}`, `vote-pledge:${requireRelationshipId(pledge.leadership)}:${requireRelationshipId(pledge.municipality)}`,
]) ])
// Re-read under the lock so CAS sees the committed `estimatedAt`, not a // Re-read under the lock only when CAS is armed — LWW callers keep the
// pre-lock snapshot that another writer may have already bumped. // pre-lock row (same access check + advisory lock as before OH6).
const lockedPledge = await payload.findByID({ const lockedPledge =
collection: 'votePledge', enforceCas && data.baseEstimatedAt !== undefined
id: pledge.id, ? await payload.findByID({
depth: 0, collection: 'votePledge',
user: currentActor, id: pledge.id,
overrideAccess: false, depth: 0,
req, user: currentActor,
}) overrideAccess: false,
req,
})
: pledge
if (enforceCas && data.baseEstimatedAt !== undefined) { if (enforceCas && data.baseEstimatedAt !== undefined) {
const currentEstimatedAt = lockedPledge.estimatedAt ?? null const currentEstimatedAt = lockedPledge.estimatedAt ?? null

View file

@ -55,11 +55,9 @@ const createEstimateOfflineExecutor = (): OfflineExecutor =>
}) })
opsEstimateOutboxCollection.utils.acceptMutations(transaction) opsEstimateOutboxCollection.utils.acceptMutations(transaction)
if (opsEstimateOutboxCollection.has(row.pledgeId)) { if (opsEstimateOutboxCollection.has(row.pledgeId)) {
opsEstimateOutboxCollection.update(row.pledgeId, (draft) => { // Drop the local row so RSC props win after refresh (OH7 will
draft.status = 'synced' // patch the mirror instead of keeping a synced stub).
draft.serverEstimatedAt = undefined opsEstimateOutboxCollection.delete(row.pledgeId)
draft.errorMessage = undefined
})
} }
} catch (error) { } catch (error) {
const message = error instanceof Error ? error.message : String(error) const message = error instanceof Error ? error.message : String(error)
@ -135,10 +133,14 @@ export const enqueueEstimateVotes = async (
} }
export const subscribeOpsEstimateOutboxRow = ( export const subscribeOpsEstimateOutboxRow = (
_pledgeId: number, pledgeId: number,
onStoreChange: () => void, onStoreChange: () => void,
): (() => void) => { ): (() => void) => {
let previous = opsEstimateOutboxCollection.get(pledgeId)
const subscription = opsEstimateOutboxCollection.subscribeChanges(() => { const subscription = opsEstimateOutboxCollection.subscribeChanges(() => {
const next = opsEstimateOutboxCollection.get(pledgeId)
if (next === previous) return
previous = next
onStoreChange() onStoreChange()
}) })
return () => { return () => {

View file

@ -15,6 +15,7 @@ import { toast } from 'sonner'
import { import {
discardOpsEstimateOutboxRow, discardOpsEstimateOutboxRow,
enqueueEstimateVotes, enqueueEstimateVotes,
getOpsEstimateOfflineExecutor,
readOpsEstimateOutboxRow, readOpsEstimateOutboxRow,
subscribeOpsEstimateOutboxRow, subscribeOpsEstimateOutboxRow,
} from '@/components/campaign/opsSync/opsEstimateOutbox' } from '@/components/campaign/opsSync/opsEstimateOutbox'
@ -180,9 +181,12 @@ const HybridPledgeEstimateForm = ({
const router = useRouter() const router = useRouter()
const liveRegionId = useId() const liveRegionId = useId()
const formRef = useRef<HTMLFormElement>(null) const formRef = useRef<HTMLFormElement>(null)
const previousStatusRef = useRef<OpsEstimateSyncStatus | undefined>(undefined)
const [isSubmitting, setIsSubmitting] = useState(false) const [isSubmitting, setIsSubmitting] = useState(false)
const [formError, setFormError] = useState<string | null>(null) const [formError, setFormError] = useState<string | null>(null)
const [baseEstimatedAt, setBaseEstimatedAt] = useState<string | null>(currentEstimatedAt) // Override only until RSC props catch up after "Manter o meu".
const [baseOverride, setBaseOverride] = useState<string | null | undefined>(undefined)
const baseEstimatedAt = baseOverride !== undefined ? baseOverride : currentEstimatedAt
const outboxRow = useSyncExternalStore( const outboxRow = useSyncExternalStore(
(onStoreChange) => subscribeOpsEstimateOutboxRow(pledgeID, onStoreChange), (onStoreChange) => subscribeOpsEstimateOutboxRow(pledgeID, onStoreChange),
@ -191,13 +195,21 @@ const HybridPledgeEstimateForm = ({
) )
useEffect(() => { useEffect(() => {
setBaseEstimatedAt(currentEstimatedAt) // Restore IndexedDB outbox + optimistic rows across reload.
void getOpsEstimateOfflineExecutor()
}, [])
useEffect(() => {
setBaseOverride(undefined)
}, [currentEstimatedAt]) }, [currentEstimatedAt])
useEffect(() => { useEffect(() => {
if (outboxRow?.status !== 'synced') return const previous = previousStatusRef.current
router.refresh() previousStatusRef.current = outboxRow?.status
}, [outboxRow?.status, router]) if (previous === 'pending' && outboxRow === undefined) {
router.refresh()
}
}, [outboxRow, router])
useEffect(() => { useEffect(() => {
if (outboxRow?.status !== 'conflict') return if (outboxRow?.status !== 'conflict') return
@ -224,7 +236,7 @@ const HybridPledgeEstimateForm = ({
baseEstimatedAt: outboxRow.serverEstimatedAt ?? null, baseEstimatedAt: outboxRow.serverEstimatedAt ?? null,
}).then( }).then(
() => { () => {
setBaseEstimatedAt(outboxRow.serverEstimatedAt ?? null) setBaseOverride(outboxRow.serverEstimatedAt ?? null)
setFormError(null) setFormError(null)
}, },
(error: unknown) => { (error: unknown) => {
@ -254,6 +266,7 @@ const HybridPledgeEstimateForm = ({
const status = outboxRow?.status const status = outboxRow?.status
const pending = isSubmitting || status === 'pending' const pending = isSubmitting || status === 'pending'
const fieldsKey = `pledge-estimate-fields-${pledgeID}-${outboxRow?.status ?? 'rsc'}-${currentEstimatedAt ?? 'none'}`
const onSubmit = (event: FormEvent<HTMLFormElement>) => { const onSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault() event.preventDefault()
@ -300,23 +313,25 @@ const HybridPledgeEstimateForm = ({
{pending ? 'Salvando estimativa…' : null} {pending ? 'Salvando estimativa…' : null}
</span> </span>
</div> </div>
<VoteEstimateScenarioInputs <div key={fieldsKey} className="flex flex-col gap-3">
fieldPrefix="estimatedVotes" <VoteEstimateScenarioInputs
values={outboxRow?.estimatedVotes ?? currentEstimatedVotes} fieldPrefix="estimatedVotes"
idPrefix={`pledge-estimate-${pledgeID}`} values={outboxRow?.estimatedVotes ?? currentEstimatedVotes}
/> idPrefix={`pledge-estimate-${pledgeID}`}
<Field>
<FieldLabel htmlFor={`pledge-note-${pledgeID}`} className="text-xs">
Justificativa
</FieldLabel>
<Input
id={`pledge-note-${pledgeID}`}
name="estimateNote"
maxLength={1000}
defaultValue={outboxRow?.estimateNote ?? currentEstimateNote ?? undefined}
className="min-h-11"
/> />
</Field> <Field>
<FieldLabel htmlFor={`pledge-note-${pledgeID}`} className="text-xs">
Justificativa
</FieldLabel>
<Input
id={`pledge-note-${pledgeID}`}
name="estimateNote"
maxLength={1000}
defaultValue={outboxRow?.estimateNote ?? currentEstimateNote ?? undefined}
className="min-h-11"
/>
</Field>
</div>
<Button type="submit" variant="secondary" disabled={pending} className="min-h-11 self-start"> <Button type="submit" variant="secondary" disabled={pending} className="min-h-11 self-start">
{pending ? <Spinner data-icon="inline-start" aria-hidden="true" /> : null} {pending ? <Spinner data-icon="inline-start" aria-hidden="true" /> : null}
Salvar estimativa Salvar estimativa