) => {
+ event.preventDefault()
+ const form = event.currentTarget
+ const estimatedVotes = readScenarioFromForm(form)
+ const estimateNoteRaw = new FormData(form).get('estimateNote')
+ const estimateNote =
+ typeof estimateNoteRaw === 'string' && estimateNoteRaw.trim() !== ''
+ ? estimateNoteRaw.trim()
+ : null
+
+ setIsSubmitting(true)
+ setFormError(null)
+
+ void enqueueEstimateVotes({
+ pledge: pledgeID,
+ estimatedVotes,
+ estimateNote,
+ baseEstimatedAt,
+ }).then(
+ () => {
+ setIsSubmitting(false)
+ setFormError(null)
+ },
+ (error: unknown) => {
+ setIsSubmitting(false)
+ setFormError(
+ error instanceof Error ? error.message : 'Não foi possível enfileirar a estimativa.',
+ )
+ },
+ )
+ }
+
+ return (
+
+ )
+}
diff --git a/src/lib/schemas/votePledge.ts b/src/lib/schemas/votePledge.ts
index 00b1d276..aff5488f 100644
--- a/src/lib/schemas/votePledge.ts
+++ b/src/lib/schemas/votePledge.ts
@@ -41,6 +41,11 @@ export const estimateVotesSchema = z.object({
pledge: positiveRelationshipId,
estimatedVotes: voteEstimateScenarioFieldsSchema,
estimateNote: trimmedNullableText(1000),
+ /**
+ * OH6 CAS opt-in. Absent → last-write-wins (legacy). Present (including
+ * `null`) → refuse when the row's `estimatedAt` differs.
+ */
+ baseEstimatedAt: z.string().datetime().nullable().optional(),
})
/**
@@ -57,11 +62,41 @@ export const VOTE_PLEDGE_MUNICIPALITY_NOT_LINKED_MESSAGE =
export const VOTE_PLEDGE_ESTIMATE_STAFF_MESSAGE =
'Somente a coordenação, a assessoria e o candidato registram estimativas.'
+/**
+ * OH6 — CAS conflict. Exact match for `safeMessages`; outbox may append a
+ * second line with the server's `estimatedAt` (see `opsEstimateConflictError`).
+ */
+export const OPS_ESTIMATE_CONFLICT_MESSAGE =
+ 'Esta estimativa foi alterada por outra pessoa. Escolha manter a sua ou usar a nova.'
+
+export const opsEstimateConflictError = (serverEstimatedAt: string | null): Error =>
+ new Error(
+ serverEstimatedAt == null
+ ? OPS_ESTIMATE_CONFLICT_MESSAGE
+ : `${OPS_ESTIMATE_CONFLICT_MESSAGE}\n${serverEstimatedAt}`,
+ )
+
+export const isOpsEstimateConflictMessage = (message: string): boolean =>
+ message === OPS_ESTIMATE_CONFLICT_MESSAGE ||
+ message.startsWith(`${OPS_ESTIMATE_CONFLICT_MESSAGE}\n`)
+
+export const parseOpsEstimateConflictServerEstimatedAt = (message: string): string | null => {
+ if (!isOpsEstimateConflictMessage(message)) return null
+ if (message === OPS_ESTIMATE_CONFLICT_MESSAGE) return null
+ const stamped = message.slice(OPS_ESTIMATE_CONFLICT_MESSAGE.length + 1)
+ return stamped === '' ? null : stamped
+}
+
export const VOTE_PLEDGE_DECLARE_SAFE_MESSAGES = [
VOTE_PLEDGE_DECLARE_STAFF_MESSAGE,
VOTE_PLEDGE_MUNICIPALITY_NOT_LINKED_MESSAGE,
VOTE_PLEDGE_LEADERSHIP_REQUIRED_MESSAGE,
] as const
+export const VOTE_PLEDGE_ESTIMATE_SAFE_MESSAGES = [
+ VOTE_PLEDGE_ESTIMATE_STAFF_MESSAGE,
+ OPS_ESTIMATE_CONFLICT_MESSAGE,
+] as const
+
export type DeclareVotesInput = z.input
export type EstimateVotesInput = z.input
diff --git a/tests/e2e/campaignOpsEstimateOutbox.e2e.spec.ts b/tests/e2e/campaignOpsEstimateOutbox.e2e.spec.ts
new file mode 100644
index 00000000..ecaa8ae3
--- /dev/null
+++ b/tests/e2e/campaignOpsEstimateOutbox.e2e.spec.ts
@@ -0,0 +1,61 @@
+import { expect, test } from './fixtures/campaignE2EFixtures.js'
+
+/**
+ * OH6 — flaky-network outbox for estimateVotes. Requires `OPS_HYBRID=1` on the
+ * Playwright webServer (compile-time). Default CI keeps the flag off so
+ * `campaignMunicipalities` continues to pin the legacy formAction path.
+ */
+const opsHybridEnabled =
+ process.env.OPS_HYBRID === '1' || process.env.OPS_HYBRID?.toLowerCase() === 'true'
+
+test.describe('OH6 estimate outbox (OPS_HYBRID)', () => {
+ test.skip(!opsHybridEnabled, 'Set OPS_HYBRID=1 on the e2e webServer to run this tracer.')
+
+ test('offline edit stays queued across reload and flushes when online', async ({
+ campaign,
+ page,
+ }) => {
+ const { fixtures } = campaign
+ const municipality = await fixtures.claimMunicipality()
+ const advisor = await fixtures.createCampaignUser('advisor', {
+ name: fixtures.value('Assessor Outbox'),
+ })
+ await campaign.payload.update({
+ collection: 'municipality',
+ id: municipality.id,
+ data: { advisors: [advisor.id] },
+ depth: 0,
+ })
+ fixtures.touchMunicipality(municipality.id)
+
+ const { leadershipId } = await fixtures.createStaffLeadership({
+ namePrefix: 'Liderança Outbox',
+ municipalities: [municipality],
+ supportStatus: 'engajado',
+ })
+ await campaign.payload.create({
+ collection: 'votePledge',
+ data: {
+ leadership: leadershipId,
+ municipality: municipality.id,
+ declaredVotes: 120,
+ },
+ depth: 0,
+ })
+
+ await campaign.login(page, advisor.email!, advisor.password)
+ await page.goto(`${campaign.baseURL}/campanha/municipios/${municipality.slug}`)
+
+ await page.context().setOffline(true)
+ await page.getByLabel('Média', { exact: true }).fill('55')
+ await page.getByLabel('Justificativa').fill('Editado na estrada.')
+ await page.getByRole('button', { name: 'Salvar estimativa' }).click()
+ await expect(page.getByText('Pendente', { exact: true })).toBeVisible()
+
+ await page.reload()
+ await expect(page.getByText('Pendente', { exact: true })).toBeVisible()
+
+ await page.context().setOffline(false)
+ await expect(page.getByText('Média: 55')).toBeVisible({ timeout: 30_000 })
+ })
+})
diff --git a/tests/int/campaignMigrationReconciliation.int.spec.ts b/tests/int/campaignMigrationReconciliation.int.spec.ts
index 64fecedf..c0be188d 100644
--- a/tests/int/campaignMigrationReconciliation.int.spec.ts
+++ b/tests/int/campaignMigrationReconciliation.int.spec.ts
@@ -88,9 +88,23 @@ afterEach(async () => {
database = undefined
databasePool = undefined
- if (databaseName) {
- const adminPool = new Pool({ connectionString: adminUrl })
- await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdentifier(databaseName)} WITH (FORCE)`)
+ if (!databaseName) return
+
+ const adminPool = new Pool({ connectionString: adminUrl })
+ try {
+ // WITH (FORCE) needs rights some Cloud Postgres roles lack when another
+ // backend still holds the DB; fall back to a plain DROP, then warn.
+ try {
+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdentifier(databaseName)} WITH (FORCE)`)
+ } catch {
+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdentifier(databaseName)}`)
+ }
+ } catch (error) {
+ console.warn(
+ `[campaignMigrationReconciliation] could not drop disposable DB ${databaseName}:`,
+ error,
+ )
+ } finally {
await adminPool.end()
}
})
diff --git a/tests/int/votePledgeCas.int.spec.ts b/tests/int/votePledgeCas.int.spec.ts
new file mode 100644
index 00000000..4640bf67
--- /dev/null
+++ b/tests/int/votePledgeCas.int.spec.ts
@@ -0,0 +1,160 @@
+// @vitest-environment node
+
+import type { Payload } from 'payload'
+import { getPayload } from 'payload'
+import { beforeAll, describe, expect, it } from 'vitest'
+
+import {
+ declareVotesRecord,
+ estimateVotesCasRecord,
+ estimateVotesRecord,
+} from '@/app/(campaign)/campanha/actions/votePledge'
+import {
+ isOpsEstimateConflictMessage,
+ OPS_ESTIMATE_CONFLICT_MESSAGE,
+ parseOpsEstimateConflictServerEstimatedAt,
+} from '@/lib/schemas/votePledge'
+import config from '@/payload.config'
+
+import { installCampaignFixtures } from '../helpers/campaignFixtures'
+
+let payload: Payload
+const campaignFixtures = installCampaignFixtures({
+ getPayload: () => payload,
+ setPayload: (nextPayload) => {
+ payload = nextPayload
+ },
+})
+
+describe('estimateVotesCas (OH6)', () => {
+ beforeAll(async () => {
+ payload = await getPayload({ config: await config })
+ })
+
+ const createPledgeForAdvisor = async () => {
+ const fixtures = campaignFixtures()
+ const municipality = await fixtures.getMunicipality()
+ const advisor = await fixtures.createCampaignUser('advisor')
+ await fixtures.assignMunicipalityAdvisors(municipality.id, [advisor.id])
+ const contact = await fixtures.createContact()
+ const leadership = await fixtures.createLeadership({
+ contact: contact.id,
+ municipalities: [municipality.id],
+ supportStatus: 'engajado',
+ })
+ const pledge = await declareVotesRecord(payload, advisor, {
+ municipality: municipality.id,
+ leadership: leadership.id,
+ declaredVotes: 100,
+ })
+ fixtures.own('votePledge', pledge.id)
+ return { fixtures, advisor, pledge }
+ }
+
+ it('writes like estimateVotes when baseEstimatedAt is omitted', async () => {
+ const { advisor, pledge } = await createPledgeForAdvisor()
+
+ const updated = await estimateVotesCasRecord(payload, advisor, {
+ pledge: pledge.id,
+ estimatedVotes: { pessimistic: null, central: 40, optimistic: null },
+ estimateNote: null,
+ })
+
+ expect(updated.estimatedVotes?.central).toBe(40)
+ expect(updated.estimatedAt).toBeTruthy()
+ expect(updated.estimatedBy).toBe(advisor.id)
+ })
+
+ it('refuses a stale baseEstimatedAt without writing', async () => {
+ const { advisor, pledge } = await createPledgeForAdvisor()
+
+ const first = await estimateVotesRecord(payload, advisor, {
+ pledge: pledge.id,
+ estimatedVotes: { pessimistic: null, central: 50, optimistic: null },
+ estimateNote: 'primeira',
+ })
+ expect(first.estimatedAt).toBeTruthy()
+
+ await estimateVotesRecord(payload, advisor, {
+ pledge: pledge.id,
+ estimatedVotes: { pessimistic: null, central: 75, optimistic: null },
+ estimateNote: 'segunda',
+ })
+
+ await expect(
+ estimateVotesCasRecord(payload, advisor, {
+ pledge: pledge.id,
+ estimatedVotes: { pessimistic: null, central: 99, optimistic: null },
+ estimateNote: 'stale',
+ baseEstimatedAt: first.estimatedAt ?? null,
+ }),
+ ).rejects.toSatisfy((error: unknown) => {
+ expect(error).toBeInstanceOf(Error)
+ const message = (error as Error).message
+ expect(isOpsEstimateConflictMessage(message)).toBe(true)
+ expect(message.startsWith(OPS_ESTIMATE_CONFLICT_MESSAGE)).toBe(true)
+ return true
+ })
+
+ const current = await payload.findByID({
+ collection: 'votePledge',
+ id: pledge.id,
+ depth: 0,
+ overrideAccess: true,
+ })
+ expect(current.estimatedVotes?.central).toBe(75)
+ expect(current.estimateNote).toBe('segunda')
+ })
+
+ it('writes when baseEstimatedAt matches and refreshes estimatedAt/estimatedBy', async () => {
+ const { advisor, pledge } = await createPledgeForAdvisor()
+
+ const first = await estimateVotesRecord(payload, advisor, {
+ pledge: pledge.id,
+ estimatedVotes: { pessimistic: 10, central: 20, optimistic: 30 },
+ estimateNote: null,
+ })
+ const baseEstimatedAt = first.estimatedAt ?? null
+ expect(baseEstimatedAt).toBeTruthy()
+
+ const updated = await estimateVotesCasRecord(payload, advisor, {
+ pledge: pledge.id,
+ estimatedVotes: { pessimistic: 11, central: 22, optimistic: 33 },
+ estimateNote: 'cas ok',
+ baseEstimatedAt,
+ })
+
+ expect(updated.estimatedVotes?.central).toBe(22)
+ expect(updated.estimateNote).toBe('cas ok')
+ expect(updated.estimatedBy).toBe(advisor.id)
+ expect(updated.estimatedAt).toBeTruthy()
+ expect(updated.estimatedAt).not.toBe(baseEstimatedAt)
+ })
+
+ it('accepts null baseEstimatedAt only while the row has never been estimated', async () => {
+ const { advisor, pledge } = await createPledgeForAdvisor()
+ expect(pledge.estimatedAt ?? null).toBeNull()
+
+ const created = await estimateVotesCasRecord(payload, advisor, {
+ pledge: pledge.id,
+ estimatedVotes: { pessimistic: null, central: 15, optimistic: null },
+ estimateNote: null,
+ baseEstimatedAt: null,
+ })
+ expect(created.estimatedVotes?.central).toBe(15)
+
+ await expect(
+ estimateVotesCasRecord(payload, advisor, {
+ pledge: pledge.id,
+ estimatedVotes: { pessimistic: null, central: 16, optimistic: null },
+ estimateNote: null,
+ baseEstimatedAt: null,
+ }),
+ ).rejects.toSatisfy((error: unknown) => {
+ const message = (error as Error).message
+ expect(isOpsEstimateConflictMessage(message)).toBe(true)
+ expect(parseOpsEstimateConflictServerEstimatedAt(message)).toBe(created.estimatedAt)
+ return true
+ })
+ })
+})
diff --git a/tests/unit/opsEstimateConflict.unit.spec.ts b/tests/unit/opsEstimateConflict.unit.spec.ts
new file mode 100644
index 00000000..5db68b82
--- /dev/null
+++ b/tests/unit/opsEstimateConflict.unit.spec.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from 'vitest'
+
+import {
+ isOpsEstimateConflictMessage,
+ OPS_ESTIMATE_CONFLICT_MESSAGE,
+ opsEstimateConflictError,
+ parseOpsEstimateConflictServerEstimatedAt,
+} from '@/lib/schemas/votePledge'
+
+describe('opsEstimateConflict helpers (OH6)', () => {
+ it('round-trips a stamped server estimatedAt through the error message', () => {
+ const stamped = opsEstimateConflictError('2026-08-01T12:00:00.000Z')
+ expect(isOpsEstimateConflictMessage(stamped.message)).toBe(true)
+ expect(parseOpsEstimateConflictServerEstimatedAt(stamped.message)).toBe(
+ '2026-08-01T12:00:00.000Z',
+ )
+ })
+
+ it('keeps the bare conflict message exact for safeMessages matching', () => {
+ const bare = opsEstimateConflictError(null)
+ expect(bare.message).toBe(OPS_ESTIMATE_CONFLICT_MESSAGE)
+ expect(parseOpsEstimateConflictServerEstimatedAt(bare.message)).toBeNull()
+ })
+
+ it('rejects unrelated messages', () => {
+ expect(isOpsEstimateConflictMessage('outro erro')).toBe(false)
+ expect(parseOpsEstimateConflictServerEstimatedAt('outro erro')).toBeNull()
+ })
+})
diff --git a/tests/unit/opsEstimateOutbox.unit.spec.ts b/tests/unit/opsEstimateOutbox.unit.spec.ts
new file mode 100644
index 00000000..f8253096
--- /dev/null
+++ b/tests/unit/opsEstimateOutbox.unit.spec.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from 'vitest'
+
+import {
+ collapseEstimateOutboxByPledge,
+ resolveEstimateTransactionPledgeKey,
+ toOpsEstimateOutboxRow,
+} from '@/components/campaign/opsSync/opsEstimateOutboxModel'
+import type { OfflineTransaction } from '@tanstack/offline-transactions'
+
+const tx = (id: string, pledgeId: number, createdAtMs: number): OfflineTransaction =>
+ ({
+ id,
+ mutationFnName: 'estimateVotes',
+ mutations: [{ key: pledgeId } as OfflineTransaction['mutations'][number]],
+ keys: [String(pledgeId)],
+ idempotencyKey: id,
+ createdAt: new Date(createdAtMs),
+ retryCount: 0,
+ nextAttemptAt: createdAtMs,
+ metadata: { pledgeId },
+ version: 1,
+ }) as OfflineTransaction
+
+describe('opsEstimateOutboxModel (OH6)', () => {
+ it('collapses superseded transactions for the same pledge', () => {
+ const collapsed = collapseEstimateOutboxByPledge([
+ tx('a', 1, 1000),
+ tx('b', 1, 3000),
+ tx('c', 2, 2000),
+ tx('d', 1, 2500),
+ ])
+
+ expect(collapsed.map((entry) => entry.id)).toEqual(['c', 'b'])
+ expect(resolveEstimateTransactionPledgeKey(collapsed[1]!)).toBe('1')
+ })
+
+ it('builds a pending outbox row from an enqueue payload', () => {
+ expect(
+ toOpsEstimateOutboxRow({
+ pledge: 9,
+ estimatedVotes: { pessimistic: 1, central: 2, optimistic: 3 },
+ estimateNote: 'nota',
+ baseEstimatedAt: '2026-08-01T00:00:00.000Z',
+ }),
+ ).toEqual({
+ pledgeId: 9,
+ estimatedVotes: { pessimistic: 1, central: 2, optimistic: 3 },
+ estimateNote: 'nota',
+ baseEstimatedAt: '2026-08-01T00:00:00.000Z',
+ status: 'pending',
+ })
+ })
+})