Merge pull request #183 from fsolla/cursor/pool-i167-a82e10a2-9a34

OH6 — estimateVotesCas + outbox mínimo + toasts (tracer bullet)
This commit is contained in:
Francisco Solla 2026-08-01 20:06:15 -03:00 committed by GitHub
commit d909e3d28d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
20 changed files with 986 additions and 18 deletions

View file

@ -35,3 +35,7 @@ CAMPAIGN_EMAIL_FROM_NAME=Campanha Jorge Solla
# Note: the automated test suite ignores this file and reads .env.test instead, # Note: the automated test suite ignores this file and reads .env.test instead,
# and only ever runs against a database whose name ends with "_test". # and only ever runs against a database whose name ends with "_test".
# Ops hybrid RSC/local (OH*). Compile-time; set to 1/true to enable estimate outbox + CAS.
# Absent or 0 keeps /campanha identical to main. See docs/plans/ops-hibrido-rsc-local-spec.md
OPS_HYBRID=

View file

@ -4,6 +4,8 @@ Conteúdo movido do `AGENTS.md` em 2026-07-30 (fatiamento do paradigma de agente
--- ---
**Recently resolved (2026-08-01):** **OH6** (Issue #167) — tracer `estimateVotesCas` (CAS opt-in via `baseEstimatedAt`) + outbox mínimo (`@tanstack/offline-transactions`) + toasts Sonner de conflito na ilha `PledgeEstimateForm` quando `OPS_HYBRID=1`; flag OFF mantém `formAction`. Plano: [`oh6-estimatevotes-cas-outbox.md`](docs/plans/oh6-estimatevotes-cas-outbox.md).
**Recently resolved (2026-08-01):** **CL3** (Issue #157) — tracer da factory de listas unificadas: `OpsListView` (slots) + `OpsListPage` (casca server); `/campanha/municipios` atrás de `LIST_UNIFIED` com paridade OFF. Plano: [`cl3-ops-list-page-municipios.md`](docs/plans/cl3-ops-list-page-municipios.md). **Recently resolved (2026-08-01):** **CL3** (Issue #157) — tracer da factory de listas unificadas: `OpsListView` (slots) + `OpsListPage` (casca server); `/campanha/municipios` atrás de `LIST_UNIFIED` com paridade OFF. Plano: [`cl3-ops-list-page-municipios.md`](docs/plans/cl3-ops-list-page-municipios.md).
**Recently resolved (2026-08-01):** **CL1** (Issue #155) — spec-mãe da Lista Unificada Campanha: decisões travadas (factory = prólogo+slots, não data path; registry em `lib/opsListRegistry`; 8 slugs v1 + atividades excluída; conflitos por domínio; CL5a/CL6a obrigatórios). Inventário as-built + index CL2–CL8 + acoplamento OH. Plano: [`lista-unificada-campanha-spec.md`](docs/plans/lista-unificada-campanha-spec.md). **Recently resolved (2026-08-01):** **CL1** (Issue #155) — spec-mãe da Lista Unificada Campanha: decisões travadas (factory = prólogo+slots, não data path; registry em `lib/opsListRegistry`; 8 slugs v1 + atividades excluída; conflitos por domínio; CL5a/CL6a obrigatórios). Inventário as-built + index CL2–CL8 + acoplamento OH. Plano: [`lista-unificada-campanha-spec.md`](docs/plans/lista-unificada-campanha-spec.md).

View file

@ -1,6 +1,6 @@
# OH6 — `estimateVotesCas` + outbox mínimo + toasts (tracer bullet) # OH6 — `estimateVotesCas` + outbox mínimo + toasts (tracer bullet)
Status: rascunho Status: implementado
Atualizado em: 2026-08-01 Atualizado em: 2026-08-01
Issue: #167 Issue: #167
Priority: P1 Priority: P1
@ -10,13 +10,19 @@ Appetite: ~2–3 dias eng
Depends: OH1 Depends: OH1
Responsável: — Responsável: —
## Freshness audit (2026-08-01)
- OH1 (#164) `done`/`in-prod`. Paths e assinaturas (`estimateVotesRecord`, `PledgeEstimateForm`, `estimateVotesSchema`, `estimatedAt` no hook) batem.
- OH2 (#163) mergeou durante a entrega — OH6 reusa `resolveOpsHybridEnabled` de `lib/campaignOps/opsHybridFlag.ts` + `OPS_HYBRID` via `next.config` `env`.
- `@tanstack/offline-transactions@1.0.42` exige collection TanStack DB — tracer usa `localOnlyCollectionOptions` (OH7 troca pelo mirror).
## Premissas ## Premissas
1. Tracer prova a dor do carro **antes** do mirror completo: outbox auto-contido (storage simples), sem depender de OH5. 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). 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. 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 ## Objetivos
@ -60,9 +66,9 @@ Componentes:
- **Quota:** ~0,4 - **Quota:** ~0,4
- **Entrega:** schema + action + pins int. - **Entrega:** schema + action + pins int.
- **Aceite:** - **Aceite:**
- [ ] sem `baseEstimatedAt`: escreve como hoje - [x] sem `baseEstimatedAt`: escreve como hoje
- [ ] com base stale: lança conflito, **não** escreve - [x] com base stale: lança conflito, **não** escreve
- [ ] com base igual: escreve e hook actualiza `estimatedAt/estimatedBy` - [x] com base igual: escreve e hook actualiza `estimatedAt/estimatedBy`
- **Verify:** `pnpm gate:fast` + `tests/int/votePledgeCas.int.spec.ts` - **Verify:** `pnpm gate:fast` + `tests/int/votePledgeCas.int.spec.ts`
- **Files:** schema, action, spec int - **Files:** schema, action, spec int
- **Tamanho:** M - **Tamanho:** M
@ -72,9 +78,9 @@ Componentes:
- **Quota:** ~0,6 - **Quota:** ~0,6
- **Entrega:** outbox ligado à ilha; estados; toasts; resolução de conflito (re-enviar com base nova = “Manter o meu”; descartar = “Usar o novo”). - **Entrega:** outbox ligado à ilha; estados; toasts; resolução de conflito (re-enviar com base nova = “Manter o meu”; descartar = “Usar o novo”).
- **Aceite:** - **Aceite:**
- [ ] editar com rede cortada → badge pending; reload da página → mutação ainda na fila; online → aplica - [x] editar com rede cortada → badge pending; reload da página → mutação ainda na fila; online → aplica
- [ ] conflito → toast com escolha; “Manter o meu” re-envia com `baseEstimatedAt` do server mais recente - [x] conflito → toast com escolha; “Manter o meu” re-envia com `baseEstimatedAt` do server mais recente
- [ ] flag OFF: form comporta-se exactamente como hoje (pin e2e existente) - [x] flag OFF: form comporta-se exactamente como hoje (pin e2e existente)
- **Verify:** `pnpm gate:fast` + teste e2e flaky-network (Playwright route abort) - **Verify:** `pnpm gate:fast` + teste e2e flaky-network (Playwright route abort)
- **Files:** `opsEstimateOutbox.ts`, form, spec e2e - **Files:** `opsEstimateOutbox.ts`, form, spec e2e
- **Tamanho:** M - **Tamanho:** M

View file

@ -5,6 +5,11 @@ const allowedImageHost = process.env.NEXT_PUBLIC_SITE_URL || 'https://jorgesolla
const nextConfig = { const nextConfig = {
distDir: process.env.NEXT_DIST_DIR || '.next', distDir: process.env.NEXT_DIST_DIR || '.next',
// OH6/OH*: compile-time ops hybrid flag (mother spec). Inlined for client
// islands; absent/`0` keeps CI identical to main.
env: {
OPS_HYBRID: process.env.OPS_HYBRID ?? '',
},
images: { images: {
remotePatterns: [new URL(`${allowedImageHost}/**`)], remotePatterns: [new URL(`${allowedImageHost}/**`)],
}, },

View file

@ -87,6 +87,8 @@
"@payloadcms/ui": "3.82.0", "@payloadcms/ui": "3.82.0",
"@simplewebauthn/browser": "^13.3.0", "@simplewebauthn/browser": "^13.3.0",
"@simplewebauthn/server": "^13.3.2", "@simplewebauthn/server": "^13.3.2",
"@tanstack/db": "0.6.17",
"@tanstack/offline-transactions": "^1.0.42",
"@vercel/analytics": "^1.6.1", "@vercel/analytics": "^1.6.1",
"@vercel/speed-insights": "^1.3.1", "@vercel/speed-insights": "^1.3.1",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",

View file

@ -44,6 +44,12 @@ importers:
'@simplewebauthn/server': '@simplewebauthn/server':
specifier: ^13.3.2 specifier: ^13.3.2
version: 13.3.2 version: 13.3.2
'@tanstack/db':
specifier: 0.6.17
version: 0.6.17(@typescript/typescript6@6.0.2)
'@tanstack/offline-transactions':
specifier: ^1.0.42
version: 1.0.42(@typescript/typescript6@6.0.2)
'@vercel/analytics': '@vercel/analytics':
specifier: ^1.6.1 specifier: ^1.6.1
version: 1.6.1(next@15.4.11(@babel/core@7.29.0)(@playwright/test@1.58.2)(babel-plugin-macros@3.1.0)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(sass@1.77.4))(react@19.2.4) version: 1.6.1(next@15.4.11(@babel/core@7.29.0)(@playwright/test@1.58.2)(babel-plugin-macros@3.1.0)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(sass@1.77.4))(react@19.2.4)
@ -3033,6 +3039,31 @@ packages:
'@tailwindcss/postcss@4.1.18': '@tailwindcss/postcss@4.1.18':
resolution: {integrity: sha512-Ce0GFnzAOuPyfV5SxjXGn0CubwGcuDB0zcdaPuCSzAa/2vII24JTkH+I6jcbXLb1ctjZMZZI6OjDaLPJQL1S0g==} resolution: {integrity: sha512-Ce0GFnzAOuPyfV5SxjXGn0CubwGcuDB0zcdaPuCSzAa/2vII24JTkH+I6jcbXLb1ctjZMZZI6OjDaLPJQL1S0g==}
'@tanstack/db-ivm@0.1.18':
resolution: {integrity: sha512-+pZJiRKdoKRM5Epq9T7otD9ZJl82pRFauo7LKuJGrarjVKQ7r+QQlPe3kGdN9LEKSnuNGIWjX9OOY4M8kH4eLw==}
peerDependencies:
typescript: '>=4.7'
'@tanstack/db@0.6.17':
resolution: {integrity: sha512-/i6+dedEkOCVQbTQtCjQHx3Nqlkqe6zvi+9/JPnSgm47o+akoaPqcSwxTmesDZxc/efHokUtzeD2ocow257RdQ==}
peerDependencies:
typescript: '>=4.7'
'@tanstack/offline-transactions@1.0.42':
resolution: {integrity: sha512-wn9/hhBRf1iK7DDx6njwIBv/eFyi9CzmMyM8AHvQs+f9G/xaBmIa1VvlJ7n5YokBASlxffaTnA2CS0+/v0uL5Q==}
peerDependencies:
'@react-native-community/netinfo': '>=11.0.0'
react-native: '>=0.70.0'
peerDependenciesMeta:
'@react-native-community/netinfo':
optional: true
react-native:
optional: true
'@tanstack/pacer-lite@0.2.2':
resolution: {integrity: sha512-eQ1MyLKCHyXiH7NbdmB80W77OhiMgGBUb+qDx/8WMGbwg5Lf/NlfD0TfNYAqY77i8V3AxoDoYdICrQE5ADw4Yw==}
engines: {node: '>=18'}
'@testing-library/dom@10.4.1': '@testing-library/dom@10.4.1':
resolution: {integrity: sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==} resolution: {integrity: sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==}
engines: {node: '>=18'} engines: {node: '>=18'}
@ -4838,6 +4869,10 @@ packages:
resolution: {integrity: sha512-w/XBfkibaTl3YDqASwfDUqkna4Z2p9cFSr1aHDt0WoMTECnRfBOv2WArlZILlqgWlmdIlALXGpM2AOhEk5W3IA==} resolution: {integrity: sha512-w/XBfkibaTl3YDqASwfDUqkna4Z2p9cFSr1aHDt0WoMTECnRfBOv2WArlZILlqgWlmdIlALXGpM2AOhEk5W3IA==}
engines: {node: '>=0.8'} engines: {node: '>=0.8'}
fractional-indexing@3.4.0:
resolution: {integrity: sha512-8J3glhz2rrpKG6KmI7wmJo3zH1VjeOpN+vTJSw1fOyO+Viqq3zX6/5NGh6oaZB2qIAYdOYuu5Dz9xp4faOO0Pg==}
engines: {node: ^14.13.1 || >=16.0.0}
fresh@2.0.0: fresh@2.0.0:
resolution: {integrity: sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==} resolution: {integrity: sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==}
engines: {node: '>= 0.8'} engines: {node: '>= 0.8'}
@ -6736,6 +6771,9 @@ packages:
react: ^18.0.0 || ^19.0.0 || ^19.0.0-rc react: ^18.0.0 || ^19.0.0 || ^19.0.0-rc
react-dom: ^18.0.0 || ^19.0.0 || ^19.0.0-rc react-dom: ^18.0.0 || ^19.0.0 || ^19.0.0-rc
sorted-btree@1.8.1:
resolution: {integrity: sha512-395+XIP+wqNn3USkFSrNz7G3Ss/MXlZEqesxvzCRFwL14h6e8LukDHdLBePn5pwbm5OQ9vGu8mDyz2lLDIqamQ==}
source-map-js@1.2.1: source-map-js@1.2.1:
resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
engines: {node: '>=0.10.0'} engines: {node: '>=0.10.0'}
@ -10312,6 +10350,27 @@ snapshots:
postcss: 8.5.6 postcss: 8.5.6
tailwindcss: 4.1.18 tailwindcss: 4.1.18
'@tanstack/db-ivm@0.1.18(@typescript/typescript6@6.0.2)':
dependencies:
fractional-indexing: 3.4.0
sorted-btree: 1.8.1
typescript: '@typescript/typescript6@6.0.2'
'@tanstack/db@0.6.17(@typescript/typescript6@6.0.2)':
dependencies:
'@standard-schema/spec': 1.1.0
'@tanstack/db-ivm': 0.1.18(@typescript/typescript6@6.0.2)
'@tanstack/pacer-lite': 0.2.2
typescript: '@typescript/typescript6@6.0.2'
'@tanstack/offline-transactions@1.0.42(@typescript/typescript6@6.0.2)':
dependencies:
'@tanstack/db': 0.6.17(@typescript/typescript6@6.0.2)
transitivePeerDependencies:
- typescript
'@tanstack/pacer-lite@0.2.2': {}
'@testing-library/dom@10.4.1': '@testing-library/dom@10.4.1':
dependencies: dependencies:
'@babel/code-frame': 7.29.0 '@babel/code-frame': 7.29.0
@ -12272,6 +12331,8 @@ snapshots:
frac@1.1.2: {} frac@1.1.2: {}
fractional-indexing@3.4.0: {}
fresh@2.0.0: {} fresh@2.0.0: {}
fs-extra@11.3.4: fs-extra@11.3.4:
@ -14546,6 +14607,8 @@ snapshots:
react: 19.2.4 react: 19.2.4
react-dom: 19.2.4(react@19.2.4) react-dom: 19.2.4(react@19.2.4)
sorted-btree@1.8.1: {}
source-map-js@1.2.1: {} source-map-js@1.2.1: {}
source-map-support@0.5.21: source-map-support@0.5.21:

View file

@ -104,6 +104,7 @@ export const E2E_AFFECTED_MANIFEST = [
'src/components/campaign/suggestion', 'src/components/campaign/suggestion',
'src/components/campaign/supporter', 'src/components/campaign/supporter',
'src/components/campaign/votePledge', 'src/components/campaign/votePledge',
'src/components/campaign/opsSync',
'src/components/campaign/auth', 'src/components/campaign/auth',
`${CAMPAIGN_APP}/acoes`, `${CAMPAIGN_APP}/acoes`,
'src/components/campaign/shared/WizardMunicipality', 'src/components/campaign/shared/WizardMunicipality',
@ -118,6 +119,6 @@ export const E2E_AFFECTED_MANIFEST = [
`${CAMPAIGN_APP}/perfil`, `${CAMPAIGN_APP}/perfil`,
`${CAMPAIGN_APP}/quadro`, `${CAMPAIGN_APP}/quadro`,
], ],
specs: ['campaignHomeActions'], specs: ['campaignHomeActions', 'campaignMunicipalities', 'campaignOpsEstimateOutbox'],
}, },
] ]

View file

@ -13,6 +13,7 @@ import { MunicipalityVisitEligibilityCard } from '@/components/campaign/municipa
import { MunicipalityZoneNeighborhoodsCard } from '@/components/campaign/municipality/MunicipalityZoneNeighborhoodsCard' import { MunicipalityZoneNeighborhoodsCard } from '@/components/campaign/municipality/MunicipalityZoneNeighborhoodsCard'
import { CampaignListPagination } from '@/components/campaign/shared/CampaignListPagination' import { CampaignListPagination } from '@/components/campaign/shared/CampaignListPagination'
import { SuggestionsPanel } from '@/components/campaign/suggestion/SuggestionsPanel' import { SuggestionsPanel } from '@/components/campaign/suggestion/SuggestionsPanel'
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
import type { VoteEstimateScenarioViewModel } from '@/lib/voteEstimate' import type { VoteEstimateScenarioViewModel } from '@/lib/voteEstimate'
import type { getCampaignUser } from '@/utilities/campaignAuth' import type { getCampaignUser } from '@/utilities/campaignAuth'
import { loadFederalCandidateOptions } from '@/utilities/electionCandidateOptions' import { loadFederalCandidateOptions } from '@/utilities/electionCandidateOptions'
@ -122,7 +123,11 @@ export const OverviewTab = async ({
</Suspense> </Suspense>
</> </>
) : null} ) : null}
<MunicipalityPledgesPanel pledges={pledges} estimateFormAction={estimateVotesFormAction} /> <MunicipalityPledgesPanel
pledges={pledges}
opsHybridEnabled={resolveOpsHybridEnabled()}
estimateFormAction={estimateVotesFormAction}
/>
</div> </div>
) )
} }

View file

@ -13,7 +13,7 @@ import {
} from '@/lib/formData' } from '@/lib/formData'
import { import {
VOTE_PLEDGE_DECLARE_SAFE_MESSAGES, VOTE_PLEDGE_DECLARE_SAFE_MESSAGES,
VOTE_PLEDGE_ESTIMATE_STAFF_MESSAGE, VOTE_PLEDGE_ESTIMATE_SAFE_MESSAGES,
} from '@/lib/schemas/votePledge' } from '@/lib/schemas/votePledge'
import { import {
runCampaignFormAction, runCampaignFormAction,
@ -62,7 +62,7 @@ export const estimateVotesFormAction = async (
revalidatePath('/campanha/municipios/[slug]', 'page') revalidatePath('/campanha/municipios/[slug]', 'page')
return { message: 'Estimativa registrada.' } return { message: 'Estimativa registrada.' }
}, },
safeMessages: [VOTE_PLEDGE_ESTIMATE_STAFF_MESSAGE], safeMessages: VOTE_PLEDGE_ESTIMATE_SAFE_MESSAGES,
genericMessage: genericMessage:
'Não foi possível registrar a estimativa. Verifique seu acesso e tente novamente.', 'Não foi possível registrar a estimativa. Verifique seu acesso e tente novamente.',
}) })

View file

@ -6,6 +6,7 @@ import { relationshipId, requireRelationshipId } from '@/lib/relationship'
import { import {
declareVotesSchema, declareVotesSchema,
estimateVotesSchema, estimateVotesSchema,
opsEstimateConflictError,
VOTE_PLEDGE_DECLARE_STAFF_MESSAGE, VOTE_PLEDGE_DECLARE_STAFF_MESSAGE,
VOTE_PLEDGE_ESTIMATE_STAFF_MESSAGE, VOTE_PLEDGE_ESTIMATE_STAFF_MESSAGE,
VOTE_PLEDGE_LEADERSHIP_REQUIRED_MESSAGE, VOTE_PLEDGE_LEADERSHIP_REQUIRED_MESSAGE,
@ -127,6 +128,7 @@ export const estimateVotesRecord = async (
payload: Payload, payload: Payload,
actor: CampaignUser, actor: CampaignUser,
input: EstimateVotesInput, input: EstimateVotesInput,
options?: { cas?: boolean },
) => { ) => {
const data = estimateVotesSchema.parse({ const data = estimateVotesSchema.parse({
...input, ...input,
@ -134,6 +136,7 @@ export const estimateVotesRecord = async (
toVoteEstimateScenarioViewModel(input.estimatedVotes), toVoteEstimateScenarioViewModel(input.estimatedVotes),
), ),
}) })
const enforceCas = options?.cas === true
return withPayloadTransaction( return withPayloadTransaction(
payload, payload,
@ -157,9 +160,30 @@ 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 only when CAS is armed — LWW callers keep the
// pre-lock row (same access check + advisory lock as before OH6).
const lockedPledge =
enforceCas && data.baseEstimatedAt !== undefined
? await payload.findByID({
collection: 'votePledge',
id: pledge.id,
depth: 0,
user: currentActor,
overrideAccess: false,
req,
})
: pledge
if (enforceCas && data.baseEstimatedAt !== undefined) {
const currentEstimatedAt = lockedPledge.estimatedAt ?? null
if (currentEstimatedAt !== data.baseEstimatedAt) {
throw opsEstimateConflictError(currentEstimatedAt)
}
}
return payload.update({ return payload.update({
collection: 'votePledge', collection: 'votePledge',
id: pledge.id, id: lockedPledge.id,
data: { data: {
estimatedVotes: data.estimatedVotes, estimatedVotes: data.estimatedVotes,
estimateNote: data.estimateNote, estimateNote: data.estimateNote,
@ -178,3 +202,20 @@ export const estimateVotes = async (input: EstimateVotesInput) => {
const { payload, actor } = await getCampaignActionContext() const { payload, actor } = await getCampaignActionContext()
return estimateVotesRecord(payload, actor, input) 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 })

View file

@ -14,6 +14,7 @@ const dateFormatter = new Intl.DateTimeFormat('pt-BR')
type MunicipalityPledgesPanelProps = { type MunicipalityPledgesPanelProps = {
pledges: StaffPledgeRow[] pledges: StaffPledgeRow[]
opsHybridEnabled: boolean
estimateFormAction: ( estimateFormAction: (
state: CampaignFormActionState, state: CampaignFormActionState,
formData: FormData, formData: FormData,
@ -23,6 +24,7 @@ type MunicipalityPledgesPanelProps = {
/** Staff-only: declared vs estimated votes per leadership in this municipality. */ /** Staff-only: declared vs estimated votes per leadership in this municipality. */
export const MunicipalityPledgesPanel = ({ export const MunicipalityPledgesPanel = ({
pledges, pledges,
opsHybridEnabled,
estimateFormAction, estimateFormAction,
}: MunicipalityPledgesPanelProps) => { }: MunicipalityPledgesPanelProps) => {
const declaredTotal = pledges.reduce((total, pledge) => total + pledge.declaredVotes, 0) const declaredTotal = pledges.reduce((total, pledge) => total + pledge.declaredVotes, 0)
@ -95,6 +97,8 @@ export const MunicipalityPledgesPanel = ({
pledgeID={pledge.id} pledgeID={pledge.id}
currentEstimatedVotes={pledge.estimatedVotes} currentEstimatedVotes={pledge.estimatedVotes}
currentEstimateNote={pledge.estimateNote} currentEstimateNote={pledge.estimateNote}
currentEstimatedAt={pledge.estimatedAt}
opsHybridEnabled={opsHybridEnabled}
formAction={estimateFormAction} formAction={estimateFormAction}
/> />
</li> </li>

View file

@ -0,0 +1,156 @@
'use client'
import { createCollection, localOnlyCollectionOptions } from '@tanstack/db'
import {
IndexedDBAdapter,
NonRetriableError,
startOfflineExecutor,
type OfflineExecutor,
} from '@tanstack/offline-transactions'
import { estimateVotesCas } from '@/app/(campaign)/campanha/actions/votePledge'
import {
collapseEstimateOutboxByPledge,
toOpsEstimateOutboxRow,
type EnqueueEstimateVotesInput,
type OpsEstimateOutboxRow,
} from '@/components/campaign/opsSync/opsEstimateOutboxModel'
import {
isOpsEstimateConflictMessage,
parseOpsEstimateConflictServerEstimatedAt,
} from '@/lib/schemas/votePledge'
const ESTIMATE_MUTATION_FN = 'estimateVotes'
const opsEstimateOutboxCollection = createCollection(
localOnlyCollectionOptions<OpsEstimateOutboxRow, number>({
id: 'ops-estimate-outbox',
getKey: (row) => row.pledgeId,
}),
)
let executorSingleton: OfflineExecutor | null = null
let initPromise: Promise<OfflineExecutor> | null = null
const createEstimateOfflineExecutor = (): OfflineExecutor =>
startOfflineExecutor({
collections: { estimateOutbox: opsEstimateOutboxCollection },
storage: new IndexedDBAdapter('teqo-ops-estimate', 'outbox'),
beforeRetry: collapseEstimateOutboxByPledge,
mutationFns: {
[ESTIMATE_MUTATION_FN]: async ({ transaction }) => {
const mutation = transaction.mutations[0]
if (!mutation) {
throw new NonRetriableError('Mutação de estimativa vazia.')
}
const row = mutation.modified as OpsEstimateOutboxRow
try {
await estimateVotesCas({
pledge: row.pledgeId,
estimatedVotes: row.estimatedVotes,
estimateNote: row.estimateNote,
baseEstimatedAt: row.baseEstimatedAt,
})
opsEstimateOutboxCollection.utils.acceptMutations(transaction)
if (opsEstimateOutboxCollection.has(row.pledgeId)) {
// Drop the local row so RSC props win after refresh (OH7 will
// patch the mirror instead of keeping a synced stub).
opsEstimateOutboxCollection.delete(row.pledgeId)
}
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
if (isOpsEstimateConflictMessage(message)) {
const serverEstimatedAt = parseOpsEstimateConflictServerEstimatedAt(message)
if (opsEstimateOutboxCollection.has(row.pledgeId)) {
opsEstimateOutboxCollection.update(row.pledgeId, (draft) => {
draft.status = 'conflict'
draft.serverEstimatedAt = serverEstimatedAt
draft.errorMessage = message
})
}
throw new NonRetriableError(message)
}
if (opsEstimateOutboxCollection.has(row.pledgeId)) {
opsEstimateOutboxCollection.update(row.pledgeId, (draft) => {
draft.status = 'error'
draft.errorMessage = message
})
}
throw error instanceof Error ? error : new Error(message)
}
},
},
})
export const getOpsEstimateOfflineExecutor = async (): Promise<OfflineExecutor> => {
if (executorSingleton) {
await executorSingleton.waitForInit()
return executorSingleton
}
if (!initPromise) {
initPromise = (async () => {
const executor = createEstimateOfflineExecutor()
await executor.waitForInit()
executorSingleton = executor
return executor
})()
}
return initPromise
}
export const enqueueEstimateVotes = async (input: EnqueueEstimateVotesInput): Promise<void> => {
const executor = await getOpsEstimateOfflineExecutor()
const run = executor.createOfflineAction<EnqueueEstimateVotesInput>({
mutationFnName: ESTIMATE_MUTATION_FN,
onMutate: (variables) => {
const next = toOpsEstimateOutboxRow(variables, 'pending')
if (opsEstimateOutboxCollection.has(next.pledgeId)) {
opsEstimateOutboxCollection.update(next.pledgeId, (draft) => {
draft.estimatedVotes = next.estimatedVotes
draft.estimateNote = next.estimateNote
draft.baseEstimatedAt = next.baseEstimatedAt
draft.status = 'pending'
draft.serverEstimatedAt = undefined
draft.errorMessage = undefined
})
} else {
opsEstimateOutboxCollection.insert(next)
}
},
})
// Fire-and-forget: awaiting isPersisted would hang while offline (retriable
// failures stay queued). UI follows collection status via subscribeChanges.
run(input)
}
export const subscribeOpsEstimateOutboxRow = (
pledgeId: number,
onStoreChange: () => void,
): (() => void) => {
let previous = opsEstimateOutboxCollection.get(pledgeId)
const subscription = opsEstimateOutboxCollection.subscribeChanges(() => {
const next = opsEstimateOutboxCollection.get(pledgeId)
if (next === previous) return
previous = next
onStoreChange()
})
return () => {
subscription.unsubscribe()
}
}
export const readOpsEstimateOutboxRow = (pledgeId: number): OpsEstimateOutboxRow | undefined =>
opsEstimateOutboxCollection.get(pledgeId)
export const discardOpsEstimateOutboxRow = (pledgeId: number): void => {
if (opsEstimateOutboxCollection.has(pledgeId)) {
opsEstimateOutboxCollection.delete(pledgeId)
}
}

View file

@ -0,0 +1,68 @@
import type { OfflineTransaction } from '@tanstack/offline-transactions'
import type { VoteEstimateScenarioViewModel } from '@/lib/voteEstimate'
export type OpsEstimateSyncStatus = 'pending' | 'synced' | 'conflict' | 'error'
export type OpsEstimateOutboxRow = {
pledgeId: number
estimatedVotes: VoteEstimateScenarioViewModel
estimateNote: string | null
/** CAS token; `undefined` means last-write-wins for this enqueue. */
baseEstimatedAt?: string | null
status: OpsEstimateSyncStatus
serverEstimatedAt?: string | null
errorMessage?: string
}
export type EnqueueEstimateVotesInput = {
pledge: number
estimatedVotes: VoteEstimateScenarioViewModel
estimateNote: string | null
baseEstimatedAt?: string | null
}
/**
* Keep only the newest transaction per pledge key so retries don't replay
* superseded edits after a flaky reconnect.
*/
export const collapseEstimateOutboxByPledge = (
transactions: OfflineTransaction[],
): OfflineTransaction[] => {
const latestByPledge = new Map<string, OfflineTransaction>()
for (const transaction of transactions) {
const pledgeKey = resolveEstimateTransactionPledgeKey(transaction)
const current = latestByPledge.get(pledgeKey)
if (!current || transaction.createdAt.getTime() >= current.createdAt.getTime()) {
latestByPledge.set(pledgeKey, transaction)
}
}
return [...latestByPledge.values()].sort(
(left, right) => left.createdAt.getTime() - right.createdAt.getTime(),
)
}
export const resolveEstimateTransactionPledgeKey = (transaction: OfflineTransaction): string => {
const fromMetadata = transaction.metadata?.pledgeId
if (typeof fromMetadata === 'number' || typeof fromMetadata === 'string') {
return String(fromMetadata)
}
const mutationKey = transaction.mutations[0]?.key
if (mutationKey != null) return String(mutationKey)
return transaction.id
}
export const toOpsEstimateOutboxRow = (
input: EnqueueEstimateVotesInput,
status: OpsEstimateSyncStatus = 'pending',
): OpsEstimateOutboxRow => ({
pledgeId: input.pledge,
estimatedVotes: input.estimatedVotes,
estimateNote: input.estimateNote,
baseEstimatedAt: input.baseEstimatedAt,
status,
})

View file

@ -1,14 +1,37 @@
'use client' 'use client'
import { useActionState } from 'react' import { useRouter } from 'next/navigation'
import {
useActionState,
useEffect,
useId,
useRef,
useState,
useSyncExternalStore,
type FormEvent,
} from 'react'
import { toast } from 'sonner'
import {
discardOpsEstimateOutboxRow,
enqueueEstimateVotes,
getOpsEstimateOfflineExecutor,
readOpsEstimateOutboxRow,
subscribeOpsEstimateOutboxRow,
} from '@/components/campaign/opsSync/opsEstimateOutbox'
import type { OpsEstimateSyncStatus } from '@/components/campaign/opsSync/opsEstimateOutboxModel'
import { CampaignFormActionMessage } from '@/components/campaign/shared/CampaignFormActionMessage' import { CampaignFormActionMessage } from '@/components/campaign/shared/CampaignFormActionMessage'
import { VoteEstimateScenarioInputs } from '@/components/campaign/votePledge/VoteEstimateScenarioInputs' import { VoteEstimateScenarioInputs } from '@/components/campaign/votePledge/VoteEstimateScenarioInputs'
import { Badge } from '@/components/ui/Badge'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { Field, FieldError, FieldLabel } from '@/components/ui/field' import { Field, FieldError, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input' import { Input } from '@/components/ui/input'
import { Spinner } from '@/components/ui/Spinner' import { Spinner } from '@/components/ui/Spinner'
import type { VoteEstimateScenarioViewModel } from '@/lib/voteEstimate' import { OPS_ESTIMATE_CONFLICT_MESSAGE } from '@/lib/schemas/votePledge'
import {
toVoteEstimateScenarioViewModel,
type VoteEstimateScenarioViewModel,
} from '@/lib/voteEstimate'
import type { CampaignFormActionState } from '@/utilities/campaignFormActionError' import type { CampaignFormActionState } from '@/utilities/campaignFormActionError'
import { fieldError } from '@/utilities/campaignFormFields' import { fieldError } from '@/utilities/campaignFormFields'
@ -16,19 +39,85 @@ type PledgeEstimateFormProps = {
pledgeID: number pledgeID: number
currentEstimatedVotes: VoteEstimateScenarioViewModel currentEstimatedVotes: VoteEstimateScenarioViewModel
currentEstimateNote: string | null currentEstimateNote: string | null
/** RSC `estimatedAt` used as CAS base when the hybrid outbox path is on. */
currentEstimatedAt: string | null
opsHybridEnabled: boolean
formAction: ( formAction: (
state: CampaignFormActionState, state: CampaignFormActionState,
formData: FormData, formData: FormData,
) => Promise<CampaignFormActionState> ) => Promise<CampaignFormActionState>
} }
const syncStatusLabel: Record<OpsEstimateSyncStatus, string> = {
pending: 'Pendente',
synced: 'Sincronizado',
conflict: 'Conflito',
error: 'Erro',
}
const syncStatusBadgeVariant: Record<
Exclude<OpsEstimateSyncStatus, 'synced'>,
'estimate-pending' | 'destructive'
> = {
pending: 'estimate-pending',
conflict: 'destructive',
error: 'destructive',
}
/** Mirrors `voteEstimateScenarioFromForm` field names without importing server-only formData. */
const readScenarioFromForm = (form: HTMLFormElement): VoteEstimateScenarioViewModel => {
const data = new FormData(form)
const read = (name: string): number | null => {
const raw = data.get(name)
if (typeof raw !== 'string' || raw.trim() === '') return null
const value = Number(raw)
return Number.isFinite(value) ? Math.trunc(value) : null
}
return toVoteEstimateScenarioViewModel({
pessimistic: read('estimatedVotesPessimistic'),
central: read('estimatedVotesCentral'),
optimistic: read('estimatedVotesOptimistic'),
})
}
const CONFLICT_TOAST_ID_PREFIX = 'ops-estimate-conflict:'
/** Staff-only inline estimate. The leader never sees these fields. */ /** Staff-only inline estimate. The leader never sees these fields. */
export const PledgeEstimateForm = ({ export const PledgeEstimateForm = ({
pledgeID, pledgeID,
currentEstimatedVotes, currentEstimatedVotes,
currentEstimateNote, currentEstimateNote,
currentEstimatedAt,
opsHybridEnabled,
formAction, formAction,
}: PledgeEstimateFormProps) => { }: PledgeEstimateFormProps) => {
if (!opsHybridEnabled) {
return (
<LegacyPledgeEstimateForm
pledgeID={pledgeID}
currentEstimatedVotes={currentEstimatedVotes}
currentEstimateNote={currentEstimateNote}
formAction={formAction}
/>
)
}
return (
<HybridPledgeEstimateForm
pledgeID={pledgeID}
currentEstimatedVotes={currentEstimatedVotes}
currentEstimateNote={currentEstimateNote}
currentEstimatedAt={currentEstimatedAt}
/>
)
}
const LegacyPledgeEstimateForm = ({
pledgeID,
currentEstimatedVotes,
currentEstimateNote,
formAction,
}: Omit<PledgeEstimateFormProps, 'opsHybridEnabled' | 'currentEstimatedAt'>) => {
const [state, submitAction, isPending] = useActionState(formAction, {}) const [state, submitAction, isPending] = useActionState(formAction, {})
return ( return (
@ -75,3 +164,173 @@ export const PledgeEstimateForm = ({
</form> </form>
) )
} }
const HybridPledgeEstimateForm = ({
pledgeID,
currentEstimatedVotes,
currentEstimateNote,
currentEstimatedAt,
}: {
pledgeID: number
currentEstimatedVotes: VoteEstimateScenarioViewModel
currentEstimateNote: string | null
currentEstimatedAt: string | null
}) => {
const router = useRouter()
const liveRegionId = useId()
const formRef = useRef<HTMLFormElement>(null)
const previousStatusRef = useRef<OpsEstimateSyncStatus | undefined>(undefined)
const [isSubmitting, setIsSubmitting] = useState(false)
const [formError, setFormError] = useState<string | null>(null)
// 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(
(onStoreChange) => subscribeOpsEstimateOutboxRow(pledgeID, onStoreChange),
() => readOpsEstimateOutboxRow(pledgeID),
() => undefined,
)
useEffect(() => {
// Restore IndexedDB outbox + optimistic rows across reload.
void getOpsEstimateOfflineExecutor()
}, [])
useEffect(() => {
setBaseOverride(undefined)
}, [currentEstimatedAt])
useEffect(() => {
const previous = previousStatusRef.current
previousStatusRef.current = outboxRow?.status
if (previous === 'pending' && outboxRow === undefined) {
router.refresh()
}
}, [outboxRow, router])
useEffect(() => {
if (outboxRow?.status !== 'conflict') return
const toastId = `${CONFLICT_TOAST_ID_PREFIX}${pledgeID}`
toast.message(OPS_ESTIMATE_CONFLICT_MESSAGE, {
id: toastId,
duration: Infinity,
action: {
label: 'Manter o meu',
onClick: () => {
const form = formRef.current
if (!form) return
const estimatedVotes = readScenarioFromForm(form)
const estimateNoteRaw = new FormData(form).get('estimateNote')
const estimateNote =
typeof estimateNoteRaw === 'string' && estimateNoteRaw.trim() !== ''
? estimateNoteRaw.trim()
: null
void enqueueEstimateVotes({
pledge: pledgeID,
estimatedVotes,
estimateNote,
baseEstimatedAt: outboxRow.serverEstimatedAt ?? null,
}).then(
() => {
setBaseOverride(outboxRow.serverEstimatedAt ?? null)
setFormError(null)
},
(error: unknown) => {
setFormError(
error instanceof Error ? error.message : 'Não foi possível reenviar a estimativa.',
)
},
)
},
},
cancel: {
label: 'Usar o novo',
onClick: () => {
discardOpsEstimateOutboxRow(pledgeID)
setFormError(null)
router.refresh()
},
},
})
return () => {
toast.dismiss(toastId)
}
}, [outboxRow?.status, outboxRow?.serverEstimatedAt, pledgeID, router])
const status = outboxRow?.status
const pending = isSubmitting || status === 'pending'
const fieldsKey = `pledge-estimate-fields-${pledgeID}-${outboxRow?.status ?? 'rsc'}-${currentEstimatedAt ?? 'none'}`
const onSubmit = (event: FormEvent<HTMLFormElement>) => {
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 (
<form ref={formRef} onSubmit={onSubmit} className="flex flex-col gap-3" aria-busy={pending}>
<input type="hidden" name="pledgeId" value={pledgeID} />
<div className="flex flex-wrap items-center gap-2">
{status && status !== 'synced' ? (
<Badge variant={syncStatusBadgeVariant[status]}>{syncStatusLabel[status]}</Badge>
) : null}
<span id={liveRegionId} className="sr-only" aria-live="polite">
{pending ? 'Salvando estimativa…' : null}
</span>
</div>
<div key={fieldsKey} className="flex flex-col gap-3">
<VoteEstimateScenarioInputs
fieldPrefix="estimatedVotes"
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>
</div>
<Button type="submit" variant="secondary" disabled={pending} className="min-h-11 self-start">
{pending ? <Spinner data-icon="inline-start" aria-hidden="true" /> : null}
Salvar estimativa
</Button>
{formError ? <FieldError>{formError}</FieldError> : null}
</form>
)
}

View file

@ -41,6 +41,11 @@ export const estimateVotesSchema = z.object({
pledge: positiveRelationshipId, pledge: positiveRelationshipId,
estimatedVotes: voteEstimateScenarioFieldsSchema, estimatedVotes: voteEstimateScenarioFieldsSchema,
estimateNote: trimmedNullableText(1000), 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 = export const VOTE_PLEDGE_ESTIMATE_STAFF_MESSAGE =
'Somente a coordenação, a assessoria e o candidato registram estimativas.' '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 = [ export const VOTE_PLEDGE_DECLARE_SAFE_MESSAGES = [
VOTE_PLEDGE_DECLARE_STAFF_MESSAGE, VOTE_PLEDGE_DECLARE_STAFF_MESSAGE,
VOTE_PLEDGE_MUNICIPALITY_NOT_LINKED_MESSAGE, VOTE_PLEDGE_MUNICIPALITY_NOT_LINKED_MESSAGE,
VOTE_PLEDGE_LEADERSHIP_REQUIRED_MESSAGE, VOTE_PLEDGE_LEADERSHIP_REQUIRED_MESSAGE,
] as const ] 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 DeclareVotesInput = z.input<typeof declareVotesSchema>
export type EstimateVotesInput = z.input<typeof estimateVotesSchema> export type EstimateVotesInput = z.input<typeof estimateVotesSchema>

View file

@ -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 })
})
})

View file

@ -88,9 +88,23 @@ afterEach(async () => {
database = undefined database = undefined
databasePool = undefined databasePool = undefined
if (databaseName) { if (!databaseName) return
const adminPool = new Pool({ connectionString: adminUrl })
await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdentifier(databaseName)} WITH (FORCE)`) 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() await adminPool.end()
} }
}) })

View 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
})
})
})

View 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()
})
})

View file

@ -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',
})
})
})