mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-26 21:53:06 +00:00
feat(OH6): estimate outbox + hybrid PledgeEstimateForm toasts
Wire @tanstack/offline-transactions for estimateVotesCas when OPS_HYBRID is on: IndexedDB outbox, pending/conflict badges, Sonner keep/discard resolution; legacy formAction path unchanged when the flag is off. Co-authored-by: Francisco Solla <fsolla@users.noreply.github.com>
This commit is contained in:
parent
df4ee3fb76
commit
f7e3591ea9
15 changed files with 712 additions and 11 deletions
|
|
@ -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=
|
||||
|
|
|
|||
|
|
@ -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).
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# OH6 — `estimateVotesCas` + outbox mínimo + toasts (tracer bullet)
|
||||
|
||||
Status: em implementação
|
||||
Status: implementado
|
||||
Atualizado em: 2026-08-01
|
||||
Issue: #167
|
||||
Priority: P1
|
||||
|
|
@ -66,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
|
||||
|
|
@ -78,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
|
||||
|
|
|
|||
|
|
@ -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}/**`)],
|
||||
},
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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:
|
||||
|
|
|
|||
|
|
@ -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'],
|
||||
},
|
||||
]
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import { MunicipalityGoalAccountCard } from '@/components/campaign/municipality/
|
|||
import { MunicipalityLeadershipsPanel } from '@/components/campaign/municipality/MunicipalityLeadershipsPanel'
|
||||
import { MunicipalityPledgesPanel } from '@/components/campaign/municipality/MunicipalityPledgesPanel'
|
||||
import { MunicipalityStrategyCard } from '@/components/campaign/municipality/MunicipalityStrategyCard'
|
||||
import { resolveOpsHybridEnabled } from '@/components/campaign/opsSync/opsHybridEnabled'
|
||||
import { MunicipalityTicketPartnersCard } from '@/components/campaign/municipality/MunicipalityTicketPartnersCard'
|
||||
import { MunicipalityUpdateFeed } from '@/components/campaign/municipality/MunicipalityUpdateFeed'
|
||||
import { MunicipalityUpdateForm } from '@/components/campaign/municipality/MunicipalityUpdateForm'
|
||||
|
|
@ -122,7 +123,11 @@ export const OverviewTab = async ({
|
|||
</Suspense>
|
||||
</>
|
||||
) : null}
|
||||
<MunicipalityPledgesPanel pledges={pledges} estimateFormAction={estimateVotesFormAction} />
|
||||
<MunicipalityPledgesPanel
|
||||
pledges={pledges}
|
||||
opsHybridEnabled={resolveOpsHybridEnabled()}
|
||||
estimateFormAction={estimateVotesFormAction}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
/>
|
||||
</li>
|
||||
|
|
|
|||
156
src/components/campaign/opsSync/opsEstimateOutbox.ts
Normal file
156
src/components/campaign/opsSync/opsEstimateOutbox.ts
Normal 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'
|
||||
|
||||
export 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)) {
|
||||
opsEstimateOutboxCollection.update(row.pledgeId, (draft) => {
|
||||
draft.status = 'synced'
|
||||
draft.serverEstimatedAt = undefined
|
||||
draft.errorMessage = undefined
|
||||
})
|
||||
}
|
||||
} 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) => {
|
||||
const subscription = opsEstimateOutboxCollection.subscribeChanges(() => {
|
||||
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)
|
||||
}
|
||||
}
|
||||
68
src/components/campaign/opsSync/opsEstimateOutboxModel.ts
Normal file
68
src/components/campaign/opsSync/opsEstimateOutboxModel.ts
Normal 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,
|
||||
})
|
||||
11
src/components/campaign/opsSync/opsHybridEnabled.ts
Normal file
11
src/components/campaign/opsSync/opsHybridEnabled.ts
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
/**
|
||||
* OH6 tracer — compile-time `OPS_HYBRID` reader for the estimate outbox island.
|
||||
* OH2 owns the canonical `src/lib/campaignOps/opsHybridFlag.ts`; this local
|
||||
* helper avoids opening that package while OH2 lands in parallel.
|
||||
*/
|
||||
export const resolveOpsHybridEnabled = (
|
||||
env: NodeJS.ProcessEnv | Record<string, string | undefined> = process.env,
|
||||
): boolean => {
|
||||
const raw = env.OPS_HYBRID?.trim().toLowerCase()
|
||||
return raw === '1' || raw === 'true'
|
||||
}
|
||||
|
|
@ -1,14 +1,38 @@
|
|||
'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,
|
||||
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 +40,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<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. */
|
||||
export const PledgeEstimateForm = ({
|
||||
pledgeID,
|
||||
currentEstimatedVotes,
|
||||
currentEstimateNote,
|
||||
currentEstimatedAt,
|
||||
opsHybridEnabled,
|
||||
formAction,
|
||||
}: 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, {})
|
||||
|
||||
return (
|
||||
|
|
@ -75,3 +165,163 @@ export const PledgeEstimateForm = ({
|
|||
</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 [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [formError, setFormError] = useState<string | null>(null)
|
||||
const [baseEstimatedAt, setBaseEstimatedAt] = useState<string | null>(currentEstimatedAt)
|
||||
|
||||
const outboxRow = useSyncExternalStore(
|
||||
(onStoreChange) => subscribeOpsEstimateOutboxRow(pledgeID, onStoreChange),
|
||||
() => readOpsEstimateOutboxRow(pledgeID),
|
||||
() => undefined,
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
setBaseEstimatedAt(currentEstimatedAt)
|
||||
}, [currentEstimatedAt])
|
||||
|
||||
useEffect(() => {
|
||||
if (outboxRow?.status !== 'synced') return
|
||||
router.refresh()
|
||||
}, [outboxRow?.status, 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(
|
||||
() => {
|
||||
setBaseEstimatedAt(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 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>
|
||||
<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>
|
||||
<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>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
61
tests/e2e/campaignOpsEstimateOutbox.e2e.spec.ts
Normal file
61
tests/e2e/campaignOpsEstimateOutbox.e2e.spec.ts
Normal 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 })
|
||||
})
|
||||
})
|
||||
69
tests/unit/opsEstimateOutbox.unit.spec.ts
Normal file
69
tests/unit/opsEstimateOutbox.unit.spec.ts
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
collapseEstimateOutboxByPledge,
|
||||
resolveEstimateTransactionPledgeKey,
|
||||
toOpsEstimateOutboxRow,
|
||||
} from '@/components/campaign/opsSync/opsEstimateOutboxModel'
|
||||
import { resolveOpsHybridEnabled } from '@/components/campaign/opsSync/opsHybridEnabled'
|
||||
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',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveOpsHybridEnabled (OH6)', () => {
|
||||
it('accepts 1/true and rejects absent/other values', () => {
|
||||
expect(resolveOpsHybridEnabled({ OPS_HYBRID: '1' })).toBe(true)
|
||||
expect(resolveOpsHybridEnabled({ OPS_HYBRID: 'true' })).toBe(true)
|
||||
expect(resolveOpsHybridEnabled({ OPS_HYBRID: 'TRUE' })).toBe(true)
|
||||
expect(resolveOpsHybridEnabled({ OPS_HYBRID: '0' })).toBe(false)
|
||||
expect(resolveOpsHybridEnabled({ OPS_HYBRID: '' })).toBe(false)
|
||||
expect(resolveOpsHybridEnabled({})).toBe(false)
|
||||
})
|
||||
})
|
||||
Loading…
Reference in a new issue