mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-26 21:53:06 +00:00
feat(OH6): estimateVotesCas with optional baseEstimatedAt
Add CAS opt-in on vote pledge estimates: without baseEstimatedAt keep last-write-wins; with a stale base refuse the write and stamp the server estimatedAt for the outbox conflict toast. Co-authored-by: Francisco Solla <fsolla@users.noreply.github.com>
This commit is contained in:
parent
79f62d62b6
commit
df4ee3fb76
6 changed files with 273 additions and 5 deletions
|
|
@ -1,6 +1,6 @@
|
|||
# OH6 — `estimateVotesCas` + outbox mínimo + toasts (tracer bullet)
|
||||
|
||||
Status: rascunho
|
||||
Status: em implementação
|
||||
Atualizado em: 2026-08-01
|
||||
Issue: #167
|
||||
Priority: P1
|
||||
|
|
@ -10,13 +10,19 @@ Appetite: ~2–3 dias eng
|
|||
Depends: OH1
|
||||
Responsável: —
|
||||
|
||||
## Freshness audit (2026-08-01)
|
||||
|
||||
- OH1 (#164) `done`/`in-prod`. Paths e assinaturas (`estimateVotesRecord`, `PledgeEstimateForm`, `estimateVotesSchema`, `estimatedAt` no hook) batem.
|
||||
- `OPS_HYBRID` / `lib/campaignOps` ainda não existem (OH2 #163 in-progress em paralelo) — OH6 lê `OPS_HYBRID` via `next.config` `env` + helper local em `opsSync/` (sem abrir o pacote OH2).
|
||||
- `@tanstack/offline-transactions@1.0.42` exige collection TanStack DB — tracer usa `localOnlyCollectionOptions` (OH7 troca pelo mirror).
|
||||
|
||||
## Premissas
|
||||
|
||||
1. Tracer prova a dor do carro **antes** do mirror completo: outbox auto-contido (storage simples), sem depender de OH5.
|
||||
2. Semântica actual preservada quando `baseEstimatedAt` **não** é enviado (último write ganha).
|
||||
3. `PledgeEstimateForm` usa `useActionState` + `formAction` por rota — o outbox chama a action de domínio directamente, não o wrapper de form.
|
||||
|
||||
→ Corrija agora ou sigo com estas.
|
||||
→ Confirmadas; a implementar.
|
||||
|
||||
## Objetivos
|
||||
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ import {
|
|||
} from '@/lib/formData'
|
||||
import {
|
||||
VOTE_PLEDGE_DECLARE_SAFE_MESSAGES,
|
||||
VOTE_PLEDGE_ESTIMATE_STAFF_MESSAGE,
|
||||
VOTE_PLEDGE_ESTIMATE_SAFE_MESSAGES,
|
||||
} from '@/lib/schemas/votePledge'
|
||||
import {
|
||||
runCampaignFormAction,
|
||||
|
|
@ -62,7 +62,7 @@ export const estimateVotesFormAction = async (
|
|||
revalidatePath('/campanha/municipios/[slug]', 'page')
|
||||
return { message: 'Estimativa registrada.' }
|
||||
},
|
||||
safeMessages: [VOTE_PLEDGE_ESTIMATE_STAFF_MESSAGE],
|
||||
safeMessages: VOTE_PLEDGE_ESTIMATE_SAFE_MESSAGES,
|
||||
genericMessage:
|
||||
'Não foi possível registrar a estimativa. Verifique seu acesso e tente novamente.',
|
||||
})
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import { relationshipId, requireRelationshipId } from '@/lib/relationship'
|
|||
import {
|
||||
declareVotesSchema,
|
||||
estimateVotesSchema,
|
||||
opsEstimateConflictError,
|
||||
VOTE_PLEDGE_DECLARE_STAFF_MESSAGE,
|
||||
VOTE_PLEDGE_ESTIMATE_STAFF_MESSAGE,
|
||||
VOTE_PLEDGE_LEADERSHIP_REQUIRED_MESSAGE,
|
||||
|
|
@ -127,6 +128,7 @@ export const estimateVotesRecord = async (
|
|||
payload: Payload,
|
||||
actor: CampaignUser,
|
||||
input: EstimateVotesInput,
|
||||
options?: { cas?: boolean },
|
||||
) => {
|
||||
const data = estimateVotesSchema.parse({
|
||||
...input,
|
||||
|
|
@ -134,6 +136,7 @@ export const estimateVotesRecord = async (
|
|||
toVoteEstimateScenarioViewModel(input.estimatedVotes),
|
||||
),
|
||||
})
|
||||
const enforceCas = options?.cas === true
|
||||
|
||||
return withPayloadTransaction(
|
||||
payload,
|
||||
|
|
@ -157,9 +160,27 @@ export const estimateVotesRecord = async (
|
|||
`vote-pledge:${requireRelationshipId(pledge.leadership)}:${requireRelationshipId(pledge.municipality)}`,
|
||||
])
|
||||
|
||||
return payload.update({
|
||||
// Re-read under the lock so CAS sees the committed `estimatedAt`, not a
|
||||
// pre-lock snapshot that another writer may have already bumped.
|
||||
const lockedPledge = await payload.findByID({
|
||||
collection: 'votePledge',
|
||||
id: pledge.id,
|
||||
depth: 0,
|
||||
user: currentActor,
|
||||
overrideAccess: false,
|
||||
req,
|
||||
})
|
||||
|
||||
if (enforceCas && data.baseEstimatedAt !== undefined) {
|
||||
const currentEstimatedAt = lockedPledge.estimatedAt ?? null
|
||||
if (currentEstimatedAt !== data.baseEstimatedAt) {
|
||||
throw opsEstimateConflictError(currentEstimatedAt)
|
||||
}
|
||||
}
|
||||
|
||||
return payload.update({
|
||||
collection: 'votePledge',
|
||||
id: lockedPledge.id,
|
||||
data: {
|
||||
estimatedVotes: data.estimatedVotes,
|
||||
estimateNote: data.estimateNote,
|
||||
|
|
@ -178,3 +199,20 @@ export const estimateVotes = async (input: EstimateVotesInput) => {
|
|||
const { payload, actor } = await getCampaignActionContext()
|
||||
return estimateVotesRecord(payload, actor, input)
|
||||
}
|
||||
|
||||
/**
|
||||
* OH6 — estimate with optional CAS on `estimatedAt`. Without `baseEstimatedAt`
|
||||
* this matches `estimateVotes` (last-write-wins). With a base, a stale token
|
||||
* refuses the write so the outbox can surface a conflict toast.
|
||||
*/
|
||||
export const estimateVotesCas = async (input: EstimateVotesInput) => {
|
||||
const { payload, actor } = await getCampaignActionContext()
|
||||
return estimateVotesRecord(payload, actor, input, { cas: true })
|
||||
}
|
||||
|
||||
/** Test/helpers entry that enforces CAS without minting a campaign session. */
|
||||
export const estimateVotesCasRecord = async (
|
||||
payload: Payload,
|
||||
actor: CampaignUser,
|
||||
input: EstimateVotesInput,
|
||||
) => estimateVotesRecord(payload, actor, input, { cas: true })
|
||||
|
|
|
|||
|
|
@ -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<typeof declareVotesSchema>
|
||||
export type EstimateVotesInput = z.input<typeof estimateVotesSchema>
|
||||
|
|
|
|||
160
tests/int/votePledgeCas.int.spec.ts
Normal file
160
tests/int/votePledgeCas.int.spec.ts
Normal file
|
|
@ -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
|
||||
})
|
||||
})
|
||||
})
|
||||
29
tests/unit/opsEstimateConflict.unit.spec.ts
Normal file
29
tests/unit/opsEstimateConflict.unit.spec.ts
Normal file
|
|
@ -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()
|
||||
})
|
||||
})
|
||||
Loading…
Reference in a new issue