diff --git a/.env.example b/.env.example index b14eadb6..c49f9669 100644 --- a/.env.example +++ b/.env.example @@ -35,3 +35,7 @@ CAMPAIGN_EMAIL_FROM_NAME=Campanha Jorge Solla # 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". + +# 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= diff --git a/docs/CHANGELOG-AGENTS.md b/docs/CHANGELOG-AGENTS.md index 450ea8c3..4e7b3c16 100644 --- a/docs/CHANGELOG-AGENTS.md +++ b/docs/CHANGELOG-AGENTS.md @@ -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):** **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). diff --git a/docs/plans/oh6-estimatevotes-cas-outbox.md b/docs/plans/oh6-estimatevotes-cas-outbox.md index 54e88cc5..b1a422a5 100644 --- a/docs/plans/oh6-estimatevotes-cas-outbox.md +++ b/docs/plans/oh6-estimatevotes-cas-outbox.md @@ -1,6 +1,6 @@ # OH6 — `estimateVotesCas` + outbox mínimo + toasts (tracer bullet) -Status: rascunho +Status: implementado 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. +- 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 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 @@ -60,9 +66,9 @@ Componentes: - **Quota:** ~0,4 - **Entrega:** schema + action + pins int. - **Aceite:** - - [ ] sem `baseEstimatedAt`: escreve como hoje - - [ ] com base stale: lança conflito, **não** escreve - - [ ] com base igual: escreve e hook actualiza `estimatedAt/estimatedBy` + - [x] sem `baseEstimatedAt`: escreve como hoje + - [x] com base stale: lança conflito, **não** escreve + - [x] com base igual: escreve e hook actualiza `estimatedAt/estimatedBy` - **Verify:** `pnpm gate:fast` + `tests/int/votePledgeCas.int.spec.ts` - **Files:** schema, action, spec int - **Tamanho:** M @@ -72,9 +78,9 @@ Componentes: - **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”). - **Aceite:** - - [ ] 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 - - [ ] flag OFF: form comporta-se exactamente como hoje (pin e2e existente) + - [x] editar com rede cortada → badge pending; reload da página → mutação ainda na fila; online → aplica + - [x] conflito → toast com escolha; “Manter o meu” re-envia com `baseEstimatedAt` do server mais recente + - [x] flag OFF: form comporta-se exactamente como hoje (pin e2e existente) - **Verify:** `pnpm gate:fast` + teste e2e flaky-network (Playwright route abort) - **Files:** `opsEstimateOutbox.ts`, form, spec e2e - **Tamanho:** M diff --git a/next.config.mjs b/next.config.mjs index 9b677705..6039efb4 100644 --- a/next.config.mjs +++ b/next.config.mjs @@ -5,6 +5,11 @@ const allowedImageHost = process.env.NEXT_PUBLIC_SITE_URL || 'https://jorgesolla const nextConfig = { 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: { remotePatterns: [new URL(`${allowedImageHost}/**`)], }, diff --git a/package.json b/package.json index 2bb4789f..19ee5fa7 100644 --- a/package.json +++ b/package.json @@ -87,6 +87,8 @@ "@payloadcms/ui": "3.82.0", "@simplewebauthn/browser": "^13.3.0", "@simplewebauthn/server": "^13.3.2", + "@tanstack/db": "0.6.17", + "@tanstack/offline-transactions": "^1.0.42", "@vercel/analytics": "^1.6.1", "@vercel/speed-insights": "^1.3.1", "class-variance-authority": "^0.7.1", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 1e79ae8e..71d41bd4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -44,6 +44,12 @@ importers: '@simplewebauthn/server': specifier: ^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': 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) @@ -3033,6 +3039,31 @@ packages: '@tailwindcss/postcss@4.1.18': 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': resolution: {integrity: sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==} engines: {node: '>=18'} @@ -4838,6 +4869,10 @@ packages: resolution: {integrity: sha512-w/XBfkibaTl3YDqASwfDUqkna4Z2p9cFSr1aHDt0WoMTECnRfBOv2WArlZILlqgWlmdIlALXGpM2AOhEk5W3IA==} 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: resolution: {integrity: sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==} engines: {node: '>= 0.8'} @@ -6736,6 +6771,9 @@ packages: react: ^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: resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} engines: {node: '>=0.10.0'} @@ -10312,6 +10350,27 @@ snapshots: postcss: 8.5.6 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': dependencies: '@babel/code-frame': 7.29.0 @@ -12272,6 +12331,8 @@ snapshots: frac@1.1.2: {} + fractional-indexing@3.4.0: {} + fresh@2.0.0: {} fs-extra@11.3.4: @@ -14546,6 +14607,8 @@ snapshots: 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-support@0.5.21: diff --git a/scripts/lib/e2e-affected-manifest.mjs b/scripts/lib/e2e-affected-manifest.mjs index f27a72f8..ef7f9dac 100644 --- a/scripts/lib/e2e-affected-manifest.mjs +++ b/scripts/lib/e2e-affected-manifest.mjs @@ -104,6 +104,7 @@ export const E2E_AFFECTED_MANIFEST = [ 'src/components/campaign/suggestion', 'src/components/campaign/supporter', 'src/components/campaign/votePledge', + 'src/components/campaign/opsSync', 'src/components/campaign/auth', `${CAMPAIGN_APP}/acoes`, 'src/components/campaign/shared/WizardMunicipality', @@ -118,6 +119,6 @@ export const E2E_AFFECTED_MANIFEST = [ `${CAMPAIGN_APP}/perfil`, `${CAMPAIGN_APP}/quadro`, ], - specs: ['campaignHomeActions'], + specs: ['campaignHomeActions', 'campaignMunicipalities', 'campaignOpsEstimateOutbox'], }, ] diff --git a/src/app/(campaign)/campanha/(app)/municipios/[slug]/MunicipalityDetailTabs.tsx b/src/app/(campaign)/campanha/(app)/municipios/[slug]/MunicipalityDetailTabs.tsx index b9bd1690..bf3d7be7 100644 --- a/src/app/(campaign)/campanha/(app)/municipios/[slug]/MunicipalityDetailTabs.tsx +++ b/src/app/(campaign)/campanha/(app)/municipios/[slug]/MunicipalityDetailTabs.tsx @@ -13,6 +13,7 @@ import { MunicipalityVisitEligibilityCard } from '@/components/campaign/municipa import { MunicipalityZoneNeighborhoodsCard } from '@/components/campaign/municipality/MunicipalityZoneNeighborhoodsCard' import { CampaignListPagination } from '@/components/campaign/shared/CampaignListPagination' import { SuggestionsPanel } from '@/components/campaign/suggestion/SuggestionsPanel' +import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag' import type { VoteEstimateScenarioViewModel } from '@/lib/voteEstimate' import type { getCampaignUser } from '@/utilities/campaignAuth' import { loadFederalCandidateOptions } from '@/utilities/electionCandidateOptions' @@ -122,7 +123,11 @@ export const OverviewTab = async ({ ) : null} - + ) } diff --git a/src/app/(campaign)/campanha/(app)/municipios/[slug]/pledgeFormActions.ts b/src/app/(campaign)/campanha/(app)/municipios/[slug]/pledgeFormActions.ts index db24118f..9b522f3a 100644 --- a/src/app/(campaign)/campanha/(app)/municipios/[slug]/pledgeFormActions.ts +++ b/src/app/(campaign)/campanha/(app)/municipios/[slug]/pledgeFormActions.ts @@ -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.', }) diff --git a/src/app/(campaign)/campanha/actions/votePledge.ts b/src/app/(campaign)/campanha/actions/votePledge.ts index bbaae497..58650714 100644 --- a/src/app/(campaign)/campanha/actions/votePledge.ts +++ b/src/app/(campaign)/campanha/actions/votePledge.ts @@ -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,30 @@ export const estimateVotesRecord = async ( `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({ collection: 'votePledge', - id: pledge.id, + id: lockedPledge.id, data: { estimatedVotes: data.estimatedVotes, estimateNote: data.estimateNote, @@ -178,3 +202,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 }) diff --git a/src/components/campaign/municipality/MunicipalityPledgesPanel.tsx b/src/components/campaign/municipality/MunicipalityPledgesPanel.tsx index cf52037b..f9523e29 100644 --- a/src/components/campaign/municipality/MunicipalityPledgesPanel.tsx +++ b/src/components/campaign/municipality/MunicipalityPledgesPanel.tsx @@ -14,6 +14,7 @@ const dateFormatter = new Intl.DateTimeFormat('pt-BR') type MunicipalityPledgesPanelProps = { pledges: StaffPledgeRow[] + opsHybridEnabled: boolean estimateFormAction: ( state: CampaignFormActionState, formData: FormData, @@ -23,6 +24,7 @@ type MunicipalityPledgesPanelProps = { /** Staff-only: declared vs estimated votes per leadership in this municipality. */ export const MunicipalityPledgesPanel = ({ pledges, + opsHybridEnabled, estimateFormAction, }: MunicipalityPledgesPanelProps) => { const declaredTotal = pledges.reduce((total, pledge) => total + pledge.declaredVotes, 0) @@ -95,6 +97,8 @@ export const MunicipalityPledgesPanel = ({ pledgeID={pledge.id} currentEstimatedVotes={pledge.estimatedVotes} currentEstimateNote={pledge.estimateNote} + currentEstimatedAt={pledge.estimatedAt} + opsHybridEnabled={opsHybridEnabled} formAction={estimateFormAction} /> diff --git a/src/components/campaign/opsSync/opsEstimateOutbox.ts b/src/components/campaign/opsSync/opsEstimateOutbox.ts new file mode 100644 index 00000000..2775f75d --- /dev/null +++ b/src/components/campaign/opsSync/opsEstimateOutbox.ts @@ -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({ + id: 'ops-estimate-outbox', + getKey: (row) => row.pledgeId, + }), +) + +let executorSingleton: OfflineExecutor | null = null +let initPromise: Promise | 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 => { + 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 => { + const executor = await getOpsEstimateOfflineExecutor() + + const run = executor.createOfflineAction({ + 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) + } +} diff --git a/src/components/campaign/opsSync/opsEstimateOutboxModel.ts b/src/components/campaign/opsSync/opsEstimateOutboxModel.ts new file mode 100644 index 00000000..de112eee --- /dev/null +++ b/src/components/campaign/opsSync/opsEstimateOutboxModel.ts @@ -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() + + 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, +}) diff --git a/src/components/campaign/votePledge/PledgeEstimateForm.tsx b/src/components/campaign/votePledge/PledgeEstimateForm.tsx index 4b2fa846..613aac88 100644 --- a/src/components/campaign/votePledge/PledgeEstimateForm.tsx +++ b/src/components/campaign/votePledge/PledgeEstimateForm.tsx @@ -1,14 +1,37 @@ '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 { VoteEstimateScenarioInputs } from '@/components/campaign/votePledge/VoteEstimateScenarioInputs' +import { Badge } from '@/components/ui/Badge' import { Button } from '@/components/ui/button' import { Field, FieldError, FieldLabel } from '@/components/ui/field' import { Input } from '@/components/ui/input' 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 { fieldError } from '@/utilities/campaignFormFields' @@ -16,19 +39,85 @@ type PledgeEstimateFormProps = { pledgeID: number currentEstimatedVotes: VoteEstimateScenarioViewModel currentEstimateNote: string | null + /** RSC `estimatedAt` used as CAS base when the hybrid outbox path is on. */ + currentEstimatedAt: string | null + opsHybridEnabled: boolean formAction: ( state: CampaignFormActionState, formData: FormData, ) => Promise } +const syncStatusLabel: Record = { + pending: 'Pendente', + synced: 'Sincronizado', + conflict: 'Conflito', + error: 'Erro', +} + +const syncStatusBadgeVariant: Record< + Exclude, + '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. */ export const PledgeEstimateForm = ({ pledgeID, currentEstimatedVotes, currentEstimateNote, + currentEstimatedAt, + opsHybridEnabled, formAction, }: PledgeEstimateFormProps) => { + if (!opsHybridEnabled) { + return ( + + ) + } + + return ( + + ) +} + +const LegacyPledgeEstimateForm = ({ + pledgeID, + currentEstimatedVotes, + currentEstimateNote, + formAction, +}: Omit) => { const [state, submitAction, isPending] = useActionState(formAction, {}) return ( @@ -75,3 +164,173 @@ export const PledgeEstimateForm = ({ ) } + +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(null) + const previousStatusRef = useRef(undefined) + const [isSubmitting, setIsSubmitting] = useState(false) + const [formError, setFormError] = useState(null) + // Override only until RSC props catch up after "Manter o meu". + const [baseOverride, setBaseOverride] = useState(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) => { + 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 ( +
+ +
+ {status && status !== 'synced' ? ( + {syncStatusLabel[status]} + ) : null} + + {pending ? 'Salvando estimativa…' : null} + +
+
+ + + + Justificativa + + + +
+ + {formError ? {formError} : null} +
+ ) +} 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', + }) + }) +})