mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-26 21:53:06 +00:00
Merge pull request #201 from fsolla/cursor/pool-i168-cbb403da-9efe
OH5 — SyncProvider + persistence (OPFS→IDB) + poll + chrome
This commit is contained in:
commit
fcb5b1bfe5
13 changed files with 1070 additions and 48 deletions
|
|
@ -4,6 +4,8 @@ Conteúdo movido do `AGENTS.md` em 2026-07-30 (fatiamento do paradigma de agente
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
**Recently resolved (2026-08-01):** **OH5** (Issue #168) — `CampaignOpsSyncProvider` no layout `(app)`: bootstrap mirror (OPFS file → IDB dump/hydrate + TanStack `localOnly` collections), poll 3 min foreground + `visibilitychange`/`online`, chrome “Actualizado…” / “A sincronizar…” / “Dados podem estar desatualizados”; leader no-op. Plano: [`oh5-sync-provider-mirror.md`](docs/plans/oh5-sync-provider-mirror.md).
|
||||||
|
|
||||||
**Recently resolved (2026-08-01):** **CL8** (Issue #162) — contrato das 8 listas v1: pin slug↔rota (`opsListRegistryRoutes`), saved filters municípios intactos com `LIST_UNIFIED` (e2e tracer), `resolveDemandListUrl` + `resolveOrganizationListUrl` (redirect canónico; registry `canonicalRedirect: true`). Plano: [`cl8-contrato-cleanup.md`](docs/plans/cl8-contrato-cleanup.md).
|
**Recently resolved (2026-08-01):** **CL8** (Issue #162) — contrato das 8 listas v1: pin slug↔rota (`opsListRegistryRoutes`), saved filters municípios intactos com `LIST_UNIFIED` (e2e tracer), `resolveDemandListUrl` + `resolveOrganizationListUrl` (redirect canónico; registry `canonicalRedirect: true`). Plano: [`cl8-contrato-cleanup.md`](docs/plans/cl8-contrato-cleanup.md).
|
||||||
|
|
||||||
**Recently resolved (2026-08-01):** **CL6** (Issue #159) — territórios: paginação real + sort no loader (`selectTerritoryOverviewPage` / `loadTerritoryOverviewPage`), `page` no contrato URL, registry `sortModel: 'url'`, `/campanha/territorios` atrás de `LIST_UNIFIED` com paridade OFF. Plano: [`cl6-territorios-factory.md`](docs/plans/cl6-territorios-factory.md).
|
**Recently resolved (2026-08-01):** **CL6** (Issue #159) — territórios: paginação real + sort no loader (`selectTerritoryOverviewPage` / `loadTerritoryOverviewPage`), `page` no contrato URL, registry `sortModel: 'url'`, `/campanha/territorios` atrás de `LIST_UNIFIED` com paridade OFF. Plano: [`cl6-territorios-factory.md`](docs/plans/cl6-territorios-factory.md).
|
||||||
|
|
|
||||||
|
|
@ -1,22 +1,31 @@
|
||||||
# OH5 — SyncProvider + persistence (OPFS→IDB) + poll + chrome
|
# OH5 — SyncProvider + persistence (OPFS→IDB) + poll + chrome
|
||||||
|
|
||||||
Status: rascunho
|
Status: entregue (PR)
|
||||||
Atualizado em: 2026-08-01
|
Atualizado em: 2026-08-01
|
||||||
Issue: #168
|
Issue: #168
|
||||||
Priority: P1
|
Priority: P1
|
||||||
Model: cursor-grok-4.5-medium
|
Model: cursor-grok-4.5-medium
|
||||||
Impeccable: B — chrome de sync no shell `/campanha`
|
Impeccable: B — chrome de sync no shell `/campanha`
|
||||||
Appetite: ~2–3 dias eng
|
Appetite: ~2–3 dias eng
|
||||||
Depends: OH4
|
Depends: OH4 (done / in-prod — #166)
|
||||||
Responsável: —
|
Responsável: —
|
||||||
|
|
||||||
|
## Freshness audit (2026-08-01)
|
||||||
|
|
||||||
|
- OH4 (#166) `done`+`in-prod`; `GET /campanha/api/ops-sync` existe; layout `(app)` intacto.
|
||||||
|
- OH2 libs prontas: `mergeOpsSnapshot`, `OPS_MIRROR_SCHEMA_VERSION`, `resolveOpsHybridEnabled`, `OpsSyncState`.
|
||||||
|
- OH6 já pinou `@tanstack/db@0.6.17` + outbox em `opsSync/` (`localOnlyCollectionOptions`).
|
||||||
|
- **Persistence (decisão de implementação):** exports de `@tanstack/browser-db-sqlite-persistence@0.2.9` existem, mas o modelo OH4 é full-snapshot merge (não sync row-a-row). Fit: dump/hydrate do `OpsSnapshot` via **OPFS file** (`navigator.storage.getDirectory`) → **IndexedDB** fallback; collections TanStack ficam `localOnly` (mesmo padrão OH6). Pacote wa-sqlite **não** entra (build scripts ignorados pelo pnpm approve-builds; knip). Documentado no PR — é o fallback previsto no plano, não troca silenciosa de lib.
|
||||||
|
- Chrome: slot no header desktop + mobile top bar; strings pt-BR.
|
||||||
|
- Leader no-op: `enabled = OPS_HYBRID && isStaffCampaignRole(role)` no layout.
|
||||||
|
|
||||||
## Premissas
|
## Premissas
|
||||||
|
|
||||||
1. Com `OPS_HYBRID` ausente, o provider é no-op (zero efeito no layout).
|
1. Com `OPS_HYBRID` ausente, o provider é no-op (zero efeito no layout).
|
||||||
2. Persistence: OPFS/WA-SQLite primeiro; fallback IndexedDB com try/catch + feature-detect, decidido no boot e documentado em comentário.
|
2. Persistence: OPFS file primeiro; fallback IndexedDB com try/catch + feature-detect, decidido no boot e documentado em comentário.
|
||||||
3. Chrome discreto no shell: “Actualizado há Xm” / “A sincronizar…” / “Dados podem estar desatualizados”.
|
3. Chrome discreto no shell: “Actualizado há Xm” / “A sincronizar…” / “Dados podem estar desatualizados”.
|
||||||
|
|
||||||
→ Corrija agora ou sigo com estas.
|
→ Corrija agora ou siga com estas.
|
||||||
|
|
||||||
## Objetivos
|
## Objetivos
|
||||||
|
|
||||||
|
|
@ -45,12 +54,12 @@ flowchart TB
|
||||||
|
|
||||||
Componentes:
|
Componentes:
|
||||||
|
|
||||||
- **`src/components/campaign/opsSync/opsMirrorClient.ts`** (novo): boot/fallback da persistence, collections TanStack (`municipalitiesCollection`, `leadershipsCollection`, `votePledgesCollection`, …), `bootstrapOpsMirror()`, `syncOpsMirror()`, wipe por `OPS_MIRROR_SCHEMA_VERSION` mismatch.
|
- **`src/components/campaign/opsSync/opsMirrorPersistence.ts`** (novo): OPFS file → IDB store do snapshot + meta (`schemaVersion`, `lastSyncedAt`); `openOpsMirrorStore()`.
|
||||||
- **API TanStack (verificar antes de codar):** com `@tanstack/react-db@^0.1.95` + `@tanstack/browser-db-sqlite-persistence@^0.2.9`, confirmar no `node_modules`/docs da versão pinada os exports exactos (`createCollection`, `persistedCollectionOptions`, `createBrowserWASQLitePersistence`, coordinator). Se algum export não existir nesta versão, fallback documentado no PR: persistence manual em IndexedDB (hydrate/dump por collection) — **não** trocar de lib silenciosamente.
|
- **`src/components/campaign/opsSync/opsMirrorClient.ts`** (novo): collections TanStack `localOnly` (`municipalitiesCollection`, …), `bootstrapOpsMirror()`, `syncOpsMirror()`, wipe por `OPS_MIRROR_SCHEMA_VERSION` mismatch; outbox keys via estimate outbox pending/conflict.
|
||||||
- **`src/components/campaign/opsSync/CampaignOpsSyncProvider.tsx`** (novo): efeito de bootstrap + poll + listeners; expõe `useOpsSyncState()` (`{ status, lastSyncedAt }`) e **`useOpsOffline()`** — definido aqui: `true` quando `navigator.onLine === false` **ou** o último `syncOpsMirror()` falhou (mantido no estado do provider; volta a `false` no próximo sync OK ou evento `online`).
|
- **`src/components/campaign/opsSync/CampaignOpsSyncProvider.tsx`** (novo): efeito de bootstrap + poll + listeners; expõe `useOpsSyncState()` (`{ status, lastSyncedAt }`) e **`useOpsOffline()`** — `true` quando `navigator.onLine === false` **ou** o último `syncOpsMirror()` falhou (volta a `false` no próximo sync OK ou evento `online`).
|
||||||
- **`src/components/campaign/opsSync/OpsSyncStatusChrome.tsx`** (novo): texto de estado no shell (pt-BR), `role="status"`, sem banner intrusivo.
|
- **`src/components/campaign/opsSync/OpsSyncStatusChrome.tsx`** (novo): texto de estado no shell (pt-BR), `role="status"`, sem banner intrusivo.
|
||||||
- **Layout `(app)`** (alterado): envolve children com o provider passando `enabled` resolvido no server.
|
- **Layout `(app)`** (alterado): envolve children com o provider passando `enabled` resolvido no server.
|
||||||
- **Deps (setup):** `pnpm add @tanstack/react-db@^0.1.95 @tanstack/browser-db-sqlite-persistence@^0.2.9` (offline-transactions entra em OH6).
|
- **Deps:** reusa `@tanstack/db` já pinado por OH6 (sem novos pacotes de persistence).
|
||||||
|
|
||||||
## Fases verificáveis
|
## Fases verificáveis
|
||||||
|
|
||||||
|
|
@ -59,9 +68,9 @@ Componentes:
|
||||||
- **Quota:** ~0,5
|
- **Quota:** ~0,5
|
||||||
- **Entrega:** flag OFF = layout igual; ON = municipalities persistidas após GET.
|
- **Entrega:** flag OFF = layout igual; ON = municipalities persistidas após GET.
|
||||||
- **Aceite:**
|
- **Aceite:**
|
||||||
- [ ] sem env: zero requests novos, zero render diff
|
- [x] sem env: zero requests novos, zero render diff
|
||||||
- [ ] com env: GET corre, merge escreve na collection, reload reidrata sem GET (cache quente)
|
- [x] com env: GET corre, merge escreve na collection, reload reidrata sem GET (cache quente)
|
||||||
- [ ] leader com env: provider no-op (pin unit)
|
- [x] leader com env: provider no-op (pin unit)
|
||||||
- **Verify:** `pnpm gate:fast` + `tests/unit/opsMirrorClient.unit.spec.ts`
|
- **Verify:** `pnpm gate:fast` + `tests/unit/opsMirrorClient.unit.spec.ts`
|
||||||
- **Files:** `opsMirrorClient.ts`, provider, layout
|
- **Files:** `opsMirrorClient.ts`, provider, layout
|
||||||
- **Tamanho:** M
|
- **Tamanho:** M
|
||||||
|
|
@ -71,11 +80,11 @@ Componentes:
|
||||||
- **Quota:** ~0,5
|
- **Quota:** ~0,5
|
||||||
- **Entrega:** collections restantes; poll 3 min só foreground; re-sync focus/online; chrome; fallback IDB.
|
- **Entrega:** collections restantes; poll 3 min só foreground; re-sync focus/online; chrome; fallback IDB.
|
||||||
- **Aceite:**
|
- **Aceite:**
|
||||||
- [ ] poll dispara só com `visibilityState === 'visible'`
|
- [x] poll dispara só com `visibilityState === 'visible'`
|
||||||
- [ ] merge não esmaga keys marcadas (simulação de outbox keys)
|
- [x] merge não esmaga keys marcadas (simulação de outbox keys)
|
||||||
- [ ] falha de sync → chrome “Dados podem estar desatualizados”
|
- [x] falha de sync → chrome “Dados podem estar desatualizados”
|
||||||
- [ ] boot com OPFS indisponível cai para IDB sem crash (mock)
|
- [x] boot com OPFS indisponível cai para IDB sem crash (mock)
|
||||||
- [ ] `OPS_MIRROR_SCHEMA_VERSION` bumped → wipe + full re-sync
|
- [x] `OPS_MIRROR_SCHEMA_VERSION` bumped → wipe + full re-sync
|
||||||
- **Verify:** `pnpm gate:fast` + spec unit alargada
|
- **Verify:** `pnpm gate:fast` + spec unit alargada
|
||||||
- **Files:** provider, chrome, `opsMirrorClient.ts`
|
- **Files:** provider, chrome, `opsMirrorClient.ts`
|
||||||
- **Tamanho:** M
|
- **Tamanho:** M
|
||||||
|
|
@ -100,5 +109,4 @@ Boot testado manualmente em iPhone real (Safari) — checklist no PR.
|
||||||
## Referências
|
## Referências
|
||||||
|
|
||||||
- [`src/app/(campaign)/campanha/(app)/layout.tsx`](<src/app/(campaign)/campanha/(app)/layout.tsx>)
|
- [`src/app/(campaign)/campanha/(app)/layout.tsx`](<src/app/(campaign)/campanha/(app)/layout.tsx>)
|
||||||
- TanStack DB overview + persistence (docs oficiais da versão em package.json — verificar na implementação)
|
- OH2 — merge/flag/version; OH6 — `@tanstack/db` localOnly + outbox
|
||||||
- OH2 — merge/flag/version
|
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,8 @@ import { redirect } from 'next/navigation'
|
||||||
import { getPayload } from 'payload'
|
import { getPayload } from 'payload'
|
||||||
import React from 'react'
|
import React from 'react'
|
||||||
|
|
||||||
|
import { CampaignOpsSyncProvider } from '@/components/campaign/opsSync/CampaignOpsSyncProvider'
|
||||||
|
import { OpsSyncStatusChrome } from '@/components/campaign/opsSync/OpsSyncStatusChrome'
|
||||||
import { CampaignListPendingBoundary } from '@/components/campaign/shared/CampaignListPending'
|
import { CampaignListPendingBoundary } from '@/components/campaign/shared/CampaignListPending'
|
||||||
import {
|
import {
|
||||||
BiometricEnrollmentToast,
|
BiometricEnrollmentToast,
|
||||||
|
|
@ -26,6 +28,8 @@ import {
|
||||||
} from '@/components/ui/Sidebar'
|
} from '@/components/ui/Sidebar'
|
||||||
import { Toaster } from '@/components/ui/Toaster'
|
import { Toaster } from '@/components/ui/Toaster'
|
||||||
import { TooltipProvider } from '@/components/ui/tooltip'
|
import { TooltipProvider } from '@/components/ui/tooltip'
|
||||||
|
import { resolveOpsHybridEnabled } from '@/lib/campaignOps/opsHybridFlag'
|
||||||
|
import { isStaffCampaignRole } from '@/lib/campaignRoles'
|
||||||
import { deviceLabelFromUserAgent } from '@/lib/deviceLabel'
|
import { deviceLabelFromUserAgent } from '@/lib/deviceLabel'
|
||||||
import { getCampaignUserWithAvatar } from '@/utilities/campaignAuth'
|
import { getCampaignUserWithAvatar } from '@/utilities/campaignAuth'
|
||||||
import { campaignUserShellView } from '@/utilities/campaignUserProfile'
|
import { campaignUserShellView } from '@/utilities/campaignUserProfile'
|
||||||
|
|
@ -43,6 +47,7 @@ export default async function CampaignAppLayout({ children }: { children: React.
|
||||||
const sidebarStateCookie = cookieStore.get(SIDEBAR_COOKIE_NAME)
|
const sidebarStateCookie = cookieStore.get(SIDEBAR_COOKIE_NAME)
|
||||||
const hasSidebarCookie = sidebarStateCookie !== undefined
|
const hasSidebarCookie = sidebarStateCookie !== undefined
|
||||||
const defaultOpen = sidebarStateCookie ? sidebarStateCookie.value === 'true' : true
|
const defaultOpen = sidebarStateCookie ? sidebarStateCookie.value === 'true' : true
|
||||||
|
const opsSyncEnabled = resolveOpsHybridEnabled() && isStaffCampaignRole(user.role)
|
||||||
|
|
||||||
// B40 discovery. The relying party is decided from headers alone, so it is
|
// B40 discovery. The relying party is decided from headers alone, so it is
|
||||||
// resolved first and this layout — which runs on every authenticated
|
// resolved first and this layout — which runs on every authenticated
|
||||||
|
|
@ -72,40 +77,48 @@ export default async function CampaignAppLayout({ children }: { children: React.
|
||||||
defaultOpen={defaultOpen}
|
defaultOpen={defaultOpen}
|
||||||
className="h-svh min-h-0 overflow-hidden print:h-auto print:overflow-visible"
|
className="h-svh min-h-0 overflow-hidden print:h-auto print:overflow-visible"
|
||||||
>
|
>
|
||||||
<CampaignSidebarViewportDefault hasSidebarCookie={hasSidebarCookie} />
|
<CampaignOpsSyncProvider enabled={opsSyncEnabled}>
|
||||||
<CampaignSidebar user={campaignUserShellView(user)} />
|
<CampaignSidebarViewportDefault hasSidebarCookie={hasSidebarCookie} />
|
||||||
<SidebarInset className="h-svh min-h-0 overflow-hidden print:h-auto print:overflow-visible">
|
<CampaignSidebar user={campaignUserShellView(user)} />
|
||||||
<CampaignWizardChromeProvider>
|
<SidebarInset className="h-svh min-h-0 overflow-hidden print:h-auto print:overflow-visible">
|
||||||
<CampaignHomeSearchChromeProvider>
|
<CampaignWizardChromeProvider>
|
||||||
<CampaignQuickActionContextProvider>
|
<CampaignHomeSearchChromeProvider>
|
||||||
<CampaignListPendingBoundary>
|
<CampaignQuickActionContextProvider>
|
||||||
<CampaignMobileTopBar
|
<CampaignListPendingBoundary>
|
||||||
notificationBell={<CampaignNotificationBellSlot user={user} />}
|
<CampaignMobileTopBar
|
||||||
/>
|
notificationBell={<CampaignNotificationBellSlot user={user} />}
|
||||||
<header className="hidden min-h-11 shrink-0 items-center gap-2 border-b border-border px-4 md:flex print:hidden">
|
opsSyncStatus={
|
||||||
<SidebarTrigger />
|
opsSyncEnabled ? <OpsSyncStatusChrome className="max-w-[11rem]" /> : null
|
||||||
<div className="ml-auto">
|
}
|
||||||
<CampaignNotificationBellSlot user={user} />
|
/>
|
||||||
</div>
|
<header className="hidden min-h-11 shrink-0 items-center gap-2 border-b border-border px-4 md:flex print:hidden">
|
||||||
</header>
|
<SidebarTrigger />
|
||||||
{/*
|
<div className="ml-auto flex items-center gap-3">
|
||||||
|
{opsSyncEnabled ? <OpsSyncStatusChrome /> : null}
|
||||||
|
<CampaignNotificationBellSlot user={user} />
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
{/*
|
||||||
Provider must wrap CampaignAppScrollChrome, not only page children:
|
Provider must wrap CampaignAppScrollChrome, not only page children:
|
||||||
the mobile quick-actions drawer (B91/B100) mounts as a sibling of
|
the mobile quick-actions drawer (B91/B100) mounts as a sibling of
|
||||||
the scrollport and renders search hits with CampaignHoverTooltip
|
the scrollport and renders search hits with CampaignHoverTooltip
|
||||||
(priority flag). Nested only around {children} left focus→suggest
|
(priority flag). Nested only around {children} left focus→suggest
|
||||||
without a provider and crashed the page (B102).
|
without a provider and crashed the page (B102).
|
||||||
*/}
|
*/}
|
||||||
<TooltipProvider delayDuration={300}>
|
<TooltipProvider delayDuration={300}>
|
||||||
<CampaignAppScrollChrome role={user.role}>{children}</CampaignAppScrollChrome>
|
<CampaignAppScrollChrome role={user.role}>{children}</CampaignAppScrollChrome>
|
||||||
</TooltipProvider>
|
</TooltipProvider>
|
||||||
<Toaster position="top-center" />
|
<Toaster position="top-center" />
|
||||||
<InstallPwaToast />
|
<InstallPwaToast />
|
||||||
{biometricEnrollment ? <BiometricEnrollmentToast {...biometricEnrollment} /> : null}
|
{biometricEnrollment ? (
|
||||||
</CampaignListPendingBoundary>
|
<BiometricEnrollmentToast {...biometricEnrollment} />
|
||||||
</CampaignQuickActionContextProvider>
|
) : null}
|
||||||
</CampaignHomeSearchChromeProvider>
|
</CampaignListPendingBoundary>
|
||||||
</CampaignWizardChromeProvider>
|
</CampaignQuickActionContextProvider>
|
||||||
</SidebarInset>
|
</CampaignHomeSearchChromeProvider>
|
||||||
|
</CampaignWizardChromeProvider>
|
||||||
|
</SidebarInset>
|
||||||
|
</CampaignOpsSyncProvider>
|
||||||
</SidebarProvider>
|
</SidebarProvider>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
158
src/components/campaign/opsSync/CampaignOpsSyncProvider.tsx
Normal file
158
src/components/campaign/opsSync/CampaignOpsSyncProvider.tsx
Normal file
|
|
@ -0,0 +1,158 @@
|
||||||
|
'use client'
|
||||||
|
|
||||||
|
import {
|
||||||
|
createContext,
|
||||||
|
useCallback,
|
||||||
|
useContext,
|
||||||
|
useEffect,
|
||||||
|
useRef,
|
||||||
|
useState,
|
||||||
|
type ReactNode,
|
||||||
|
} from 'react'
|
||||||
|
|
||||||
|
import { bootstrapOpsMirror, syncOpsMirror } from '@/components/campaign/opsSync/opsMirrorClient'
|
||||||
|
import type { OpsSyncState, OpsSyncStatus } from '@/lib/campaignOps/opsSyncMeta'
|
||||||
|
|
||||||
|
const POLL_INTERVAL_MS = 3 * 60 * 1000
|
||||||
|
|
||||||
|
type OpsSyncContextValue = {
|
||||||
|
status: OpsSyncStatus
|
||||||
|
lastSyncedAt: string | null
|
||||||
|
lastError?: string
|
||||||
|
offline: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
const OpsSyncContext = createContext<OpsSyncContextValue | null>(null)
|
||||||
|
|
||||||
|
const initialState: OpsSyncContextValue = {
|
||||||
|
status: 'idle',
|
||||||
|
lastSyncedAt: null,
|
||||||
|
offline: false,
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useOpsSyncState = (): Pick<
|
||||||
|
OpsSyncContextValue,
|
||||||
|
'status' | 'lastSyncedAt' | 'lastError'
|
||||||
|
> => {
|
||||||
|
const value = useContext(OpsSyncContext)
|
||||||
|
if (!value) {
|
||||||
|
return { status: 'idle', lastSyncedAt: null }
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
status: value.status,
|
||||||
|
lastSyncedAt: value.lastSyncedAt,
|
||||||
|
lastError: value.lastError,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Offline when the browser reports offline OR the last sync failed.
|
||||||
|
* Clears on successful sync or the `online` event.
|
||||||
|
*/
|
||||||
|
export const useOpsOffline = (): boolean => {
|
||||||
|
const value = useContext(OpsSyncContext)
|
||||||
|
return value?.offline ?? false
|
||||||
|
}
|
||||||
|
|
||||||
|
export const CampaignOpsSyncProvider = ({
|
||||||
|
enabled,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
enabled: boolean
|
||||||
|
children: ReactNode
|
||||||
|
}) => {
|
||||||
|
const [state, setState] = useState<OpsSyncContextValue>(initialState)
|
||||||
|
const syncingRef = useRef(false)
|
||||||
|
const mountedRef = useRef(false)
|
||||||
|
|
||||||
|
const applySyncResult = useCallback((result: OpsSyncState, browserOnline: boolean) => {
|
||||||
|
if (!mountedRef.current) return
|
||||||
|
const syncFailed = result.status === 'error'
|
||||||
|
setState({
|
||||||
|
status: result.status,
|
||||||
|
lastSyncedAt: result.lastSyncedAt,
|
||||||
|
lastError: result.lastError,
|
||||||
|
offline: !browserOnline || syncFailed,
|
||||||
|
})
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const runSync = useCallback(async () => {
|
||||||
|
if (syncingRef.current) return
|
||||||
|
syncingRef.current = true
|
||||||
|
if (mountedRef.current) {
|
||||||
|
setState((prev) => ({ ...prev, status: 'syncing' }))
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const result = await syncOpsMirror()
|
||||||
|
applySyncResult(result, typeof navigator === 'undefined' ? true : navigator.onLine)
|
||||||
|
} finally {
|
||||||
|
syncingRef.current = false
|
||||||
|
}
|
||||||
|
}, [applySyncResult])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!enabled) return
|
||||||
|
|
||||||
|
mountedRef.current = true
|
||||||
|
let pollTimer: ReturnType<typeof setInterval> | null = null
|
||||||
|
|
||||||
|
const boot = async () => {
|
||||||
|
if (!mountedRef.current) return
|
||||||
|
setState((prev) => ({
|
||||||
|
...prev,
|
||||||
|
status: 'syncing',
|
||||||
|
offline: typeof navigator !== 'undefined' ? !navigator.onLine : false,
|
||||||
|
}))
|
||||||
|
try {
|
||||||
|
await bootstrapOpsMirror({ skipNetworkSync: true })
|
||||||
|
if (!mountedRef.current) return
|
||||||
|
await runSync()
|
||||||
|
} catch {
|
||||||
|
if (!mountedRef.current) return
|
||||||
|
setState((prev) => ({
|
||||||
|
...prev,
|
||||||
|
status: 'error',
|
||||||
|
offline: true,
|
||||||
|
lastError: 'bootstrap failed',
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void boot()
|
||||||
|
|
||||||
|
const onVisibility = () => {
|
||||||
|
if (document.visibilityState === 'visible') void runSync()
|
||||||
|
}
|
||||||
|
const onOnline = () => {
|
||||||
|
if (!mountedRef.current) return
|
||||||
|
setState((prev) => ({ ...prev, offline: false }))
|
||||||
|
void runSync()
|
||||||
|
}
|
||||||
|
const onOffline = () => {
|
||||||
|
if (!mountedRef.current) return
|
||||||
|
setState((prev) => ({ ...prev, offline: true }))
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('visibilitychange', onVisibility)
|
||||||
|
window.addEventListener('online', onOnline)
|
||||||
|
window.addEventListener('offline', onOffline)
|
||||||
|
|
||||||
|
pollTimer = setInterval(() => {
|
||||||
|
if (document.visibilityState === 'visible') void runSync()
|
||||||
|
}, POLL_INTERVAL_MS)
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
mountedRef.current = false
|
||||||
|
document.removeEventListener('visibilitychange', onVisibility)
|
||||||
|
window.removeEventListener('online', onOnline)
|
||||||
|
window.removeEventListener('offline', onOffline)
|
||||||
|
if (pollTimer) clearInterval(pollTimer)
|
||||||
|
}
|
||||||
|
}, [enabled, runSync])
|
||||||
|
|
||||||
|
if (!enabled) {
|
||||||
|
return children
|
||||||
|
}
|
||||||
|
|
||||||
|
return <OpsSyncContext.Provider value={state}>{children}</OpsSyncContext.Provider>
|
||||||
|
}
|
||||||
29
src/components/campaign/opsSync/OpsSyncStatusChrome.tsx
Normal file
29
src/components/campaign/opsSync/OpsSyncStatusChrome.tsx
Normal file
|
|
@ -0,0 +1,29 @@
|
||||||
|
'use client'
|
||||||
|
|
||||||
|
import {
|
||||||
|
useOpsOffline,
|
||||||
|
useOpsSyncState,
|
||||||
|
} from '@/components/campaign/opsSync/CampaignOpsSyncProvider'
|
||||||
|
import { resolveOpsSyncChromeLabel } from '@/components/campaign/opsSync/opsSyncChromeCopy'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
export const OpsSyncStatusChrome = ({ className }: { className?: string }) => {
|
||||||
|
const { status, lastSyncedAt } = useOpsSyncState()
|
||||||
|
const offline = useOpsOffline()
|
||||||
|
const label = resolveOpsSyncChromeLabel({ status, lastSyncedAt })
|
||||||
|
|
||||||
|
return (
|
||||||
|
<p
|
||||||
|
role="status"
|
||||||
|
aria-live="polite"
|
||||||
|
data-ops-offline={offline ? 'true' : undefined}
|
||||||
|
className={cn(
|
||||||
|
'truncate text-xs text-muted-foreground tabular-nums',
|
||||||
|
status === 'error' && 'text-destructive',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
</p>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -15,6 +15,7 @@ import {
|
||||||
type EnqueueEstimateVotesInput,
|
type EnqueueEstimateVotesInput,
|
||||||
type OpsEstimateOutboxRow,
|
type OpsEstimateOutboxRow,
|
||||||
} from '@/components/campaign/opsSync/opsEstimateOutboxModel'
|
} from '@/components/campaign/opsSync/opsEstimateOutboxModel'
|
||||||
|
import { opsOutboxKey, type OpsOutboxKey } from '@/lib/campaignOps/opsContract'
|
||||||
import {
|
import {
|
||||||
isOpsEstimateConflictMessage,
|
isOpsEstimateConflictMessage,
|
||||||
parseOpsEstimateConflictServerEstimatedAt,
|
parseOpsEstimateConflictServerEstimatedAt,
|
||||||
|
|
@ -154,3 +155,14 @@ export const discardOpsEstimateOutboxRow = (pledgeId: number): void => {
|
||||||
opsEstimateOutboxCollection.delete(pledgeId)
|
opsEstimateOutboxCollection.delete(pledgeId)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Pending/conflict pledge ids as merge outbox keys (OH5 — protect local rows). */
|
||||||
|
export const collectOpsEstimateOutboxKeys = (): Set<OpsOutboxKey> => {
|
||||||
|
const keys = new Set<OpsOutboxKey>()
|
||||||
|
for (const row of opsEstimateOutboxCollection.toArray) {
|
||||||
|
if (row.status === 'pending' || row.status === 'conflict') {
|
||||||
|
keys.add(opsOutboxKey('votePledges', row.pledgeId))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return keys
|
||||||
|
}
|
||||||
|
|
|
||||||
258
src/components/campaign/opsSync/opsMirrorClient.ts
Normal file
258
src/components/campaign/opsSync/opsMirrorClient.ts
Normal file
|
|
@ -0,0 +1,258 @@
|
||||||
|
'use client'
|
||||||
|
|
||||||
|
import { createCollection, localOnlyCollectionOptions } from '@tanstack/db'
|
||||||
|
|
||||||
|
import { collectOpsEstimateOutboxKeys } from '@/components/campaign/opsSync/opsEstimateOutbox'
|
||||||
|
import {
|
||||||
|
openOpsMirrorStore,
|
||||||
|
type OpsMirrorPersistenceMode,
|
||||||
|
type OpsMirrorStore,
|
||||||
|
} from '@/components/campaign/opsSync/opsMirrorPersistence'
|
||||||
|
import {
|
||||||
|
createEmptyOpsSnapshot,
|
||||||
|
type OpsActivity,
|
||||||
|
type OpsDemand,
|
||||||
|
type OpsGoals,
|
||||||
|
type OpsLeadership,
|
||||||
|
type OpsMunicipality,
|
||||||
|
type OpsMunicipalityUpdate,
|
||||||
|
type OpsOrganization,
|
||||||
|
type OpsOutboxKey,
|
||||||
|
type OpsSnapshot,
|
||||||
|
type OpsStateDeputy,
|
||||||
|
type OpsVotePledge,
|
||||||
|
} from '@/lib/campaignOps/opsContract'
|
||||||
|
import { mergeOpsSnapshot } from '@/lib/campaignOps/opsMerge'
|
||||||
|
import { OPS_MIRROR_SCHEMA_VERSION } from '@/lib/campaignOps/opsMirrorVersion'
|
||||||
|
import type { OpsSyncState } from '@/lib/campaignOps/opsSyncMeta'
|
||||||
|
|
||||||
|
export const OPS_SYNC_PATH = '/campanha/api/ops-sync'
|
||||||
|
|
||||||
|
const createRowCollection = <T extends { id: number }>(id: string) =>
|
||||||
|
createCollection(
|
||||||
|
localOnlyCollectionOptions<T, number>({
|
||||||
|
id,
|
||||||
|
getKey: (row) => row.id,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
export const municipalitiesCollection = createRowCollection<OpsMunicipality>('ops-municipalities')
|
||||||
|
const leadershipsCollection = createRowCollection<OpsLeadership>('ops-leaderships')
|
||||||
|
export const votePledgesCollection = createRowCollection<OpsVotePledge>('ops-vote-pledges')
|
||||||
|
const activitiesCollection = createRowCollection<OpsActivity>('ops-activities')
|
||||||
|
const stateDeputiesCollection = createRowCollection<OpsStateDeputy>('ops-state-deputies')
|
||||||
|
const organizationsCollection = createRowCollection<OpsOrganization>('ops-organizations')
|
||||||
|
const demandsCollection = createRowCollection<OpsDemand>('ops-demands')
|
||||||
|
const municipalityUpdatesCollection = createRowCollection<OpsMunicipalityUpdate>(
|
||||||
|
'ops-municipality-updates',
|
||||||
|
)
|
||||||
|
|
||||||
|
let goalsMirror: OpsGoals | null = null
|
||||||
|
let revisedAtMirror: string = new Date(0).toISOString()
|
||||||
|
let schemaVersionMirror: number = OPS_MIRROR_SCHEMA_VERSION
|
||||||
|
let lastSyncedAtMirror: string | null = null
|
||||||
|
let persistenceMode: OpsMirrorPersistenceMode | null = null
|
||||||
|
let storeSingleton: OpsMirrorStore | null = null
|
||||||
|
let bootPromise: Promise<{ mode: OpsMirrorPersistenceMode; hydrated: boolean }> | null = null
|
||||||
|
|
||||||
|
const replaceCollectionRows = <T extends { id: number }>(
|
||||||
|
collection: {
|
||||||
|
keys: () => IterableIterator<number>
|
||||||
|
has: (key: number) => boolean
|
||||||
|
delete: (key: number) => unknown
|
||||||
|
insert: (row: T) => unknown
|
||||||
|
},
|
||||||
|
rows: T[],
|
||||||
|
): void => {
|
||||||
|
const incomingIds = new Set(rows.map((row) => row.id))
|
||||||
|
for (const key of collection.keys()) {
|
||||||
|
if (!incomingIds.has(key)) collection.delete(key)
|
||||||
|
}
|
||||||
|
for (const row of rows) {
|
||||||
|
if (collection.has(row.id)) {
|
||||||
|
collection.delete(row.id)
|
||||||
|
}
|
||||||
|
collection.insert(row)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const readOpsMirrorSnapshot = (): OpsSnapshot => ({
|
||||||
|
revisedAt: revisedAtMirror,
|
||||||
|
schemaVersion: schemaVersionMirror,
|
||||||
|
municipalities: municipalitiesCollection.toArray,
|
||||||
|
leaderships: leadershipsCollection.toArray,
|
||||||
|
votePledges: votePledgesCollection.toArray,
|
||||||
|
activities: activitiesCollection.toArray,
|
||||||
|
stateDeputies: stateDeputiesCollection.toArray,
|
||||||
|
organizations: organizationsCollection.toArray,
|
||||||
|
demands: demandsCollection.toArray,
|
||||||
|
municipalityUpdates: municipalityUpdatesCollection.toArray,
|
||||||
|
goals: goalsMirror,
|
||||||
|
})
|
||||||
|
|
||||||
|
export const applyOpsMirrorSnapshot = (snapshot: OpsSnapshot): void => {
|
||||||
|
revisedAtMirror = snapshot.revisedAt
|
||||||
|
schemaVersionMirror = snapshot.schemaVersion
|
||||||
|
goalsMirror = snapshot.goals
|
||||||
|
replaceCollectionRows(municipalitiesCollection, snapshot.municipalities)
|
||||||
|
replaceCollectionRows(leadershipsCollection, snapshot.leaderships)
|
||||||
|
replaceCollectionRows(votePledgesCollection, snapshot.votePledges)
|
||||||
|
replaceCollectionRows(activitiesCollection, snapshot.activities)
|
||||||
|
replaceCollectionRows(stateDeputiesCollection, snapshot.stateDeputies)
|
||||||
|
replaceCollectionRows(organizationsCollection, snapshot.organizations)
|
||||||
|
replaceCollectionRows(demandsCollection, snapshot.demands)
|
||||||
|
replaceCollectionRows(municipalityUpdatesCollection, snapshot.municipalityUpdates)
|
||||||
|
}
|
||||||
|
|
||||||
|
const wipeOpsMirrorCollections = (): void => {
|
||||||
|
applyOpsMirrorSnapshot(createEmptyOpsSnapshot(new Date(0).toISOString()))
|
||||||
|
lastSyncedAtMirror = null
|
||||||
|
}
|
||||||
|
|
||||||
|
export const getOpsMirrorPersistenceMode = (): OpsMirrorPersistenceMode | null => persistenceMode
|
||||||
|
|
||||||
|
export const getOpsMirrorLastSyncedAt = (): string | null => lastSyncedAtMirror
|
||||||
|
|
||||||
|
/** Test/DI seam — reset module singletons between unit cases. */
|
||||||
|
export const resetOpsMirrorClientForTests = async (): Promise<void> => {
|
||||||
|
wipeOpsMirrorCollections()
|
||||||
|
storeSingleton = null
|
||||||
|
bootPromise = null
|
||||||
|
persistenceMode = null
|
||||||
|
}
|
||||||
|
|
||||||
|
const resolveOutboxKeys = (explicit?: ReadonlySet<OpsOutboxKey>): ReadonlySet<OpsOutboxKey> => {
|
||||||
|
if (explicit) return explicit
|
||||||
|
return collectOpsEstimateOutboxKeys()
|
||||||
|
}
|
||||||
|
|
||||||
|
const persistMirrorSnapshot = async (
|
||||||
|
store: OpsMirrorStore,
|
||||||
|
snapshot: OpsSnapshot,
|
||||||
|
lastSyncedAt: string | null,
|
||||||
|
) => {
|
||||||
|
await store.save({
|
||||||
|
schemaVersion: OPS_MIRROR_SCHEMA_VERSION,
|
||||||
|
lastSyncedAt,
|
||||||
|
snapshot,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export type BootstrapOpsMirrorOptions = {
|
||||||
|
store?: OpsMirrorStore
|
||||||
|
forceMode?: OpsMirrorPersistenceMode
|
||||||
|
skipNetworkSync?: boolean
|
||||||
|
fetchImpl?: typeof fetch
|
||||||
|
outboxKeys?: ReadonlySet<OpsOutboxKey>
|
||||||
|
}
|
||||||
|
|
||||||
|
export const bootstrapOpsMirror = async (
|
||||||
|
options: BootstrapOpsMirrorOptions = {},
|
||||||
|
): Promise<{ mode: OpsMirrorPersistenceMode; hydrated: boolean }> => {
|
||||||
|
if (bootPromise && !options.store && !options.forceMode) return bootPromise
|
||||||
|
|
||||||
|
const run = async () => {
|
||||||
|
const store = options.store ?? (await openOpsMirrorStore({ forceMode: options.forceMode }))
|
||||||
|
storeSingleton = store
|
||||||
|
persistenceMode = store.mode
|
||||||
|
|
||||||
|
const stored = await store.load()
|
||||||
|
let hydrated = false
|
||||||
|
|
||||||
|
if (stored) {
|
||||||
|
if (stored.schemaVersion !== OPS_MIRROR_SCHEMA_VERSION) {
|
||||||
|
await store.clear()
|
||||||
|
wipeOpsMirrorCollections()
|
||||||
|
} else {
|
||||||
|
applyOpsMirrorSnapshot(stored.snapshot)
|
||||||
|
lastSyncedAtMirror = stored.lastSyncedAt
|
||||||
|
hydrated = stored.snapshot.municipalities.length > 0 || stored.lastSyncedAt != null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!options.skipNetworkSync) {
|
||||||
|
await syncOpsMirror({
|
||||||
|
fetchImpl: options.fetchImpl,
|
||||||
|
outboxKeys: options.outboxKeys,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return { mode: store.mode, hydrated }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!options.store && !options.forceMode) {
|
||||||
|
bootPromise = run()
|
||||||
|
return bootPromise
|
||||||
|
}
|
||||||
|
|
||||||
|
return run()
|
||||||
|
}
|
||||||
|
|
||||||
|
export type SyncOpsMirrorOptions = {
|
||||||
|
fetchImpl?: typeof fetch
|
||||||
|
outboxKeys?: ReadonlySet<OpsOutboxKey>
|
||||||
|
store?: OpsMirrorStore
|
||||||
|
}
|
||||||
|
|
||||||
|
export const syncOpsMirror = async (options: SyncOpsMirrorOptions = {}): Promise<OpsSyncState> => {
|
||||||
|
const fetchImpl = options.fetchImpl ?? fetch
|
||||||
|
const store = options.store ?? storeSingleton
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetchImpl(OPS_SYNC_PATH, {
|
||||||
|
method: 'GET',
|
||||||
|
credentials: 'same-origin',
|
||||||
|
headers: { Accept: 'application/json' },
|
||||||
|
cache: 'no-store',
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const message = `ops-sync ${response.status}`
|
||||||
|
return {
|
||||||
|
status: 'error',
|
||||||
|
lastSyncedAt: lastSyncedAtMirror,
|
||||||
|
lastError: message,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const incoming = (await response.json()) as OpsSnapshot
|
||||||
|
if (
|
||||||
|
typeof incoming?.revisedAt !== 'string' ||
|
||||||
|
typeof incoming?.schemaVersion !== 'number' ||
|
||||||
|
!Array.isArray(incoming.municipalities)
|
||||||
|
) {
|
||||||
|
return {
|
||||||
|
status: 'error',
|
||||||
|
lastSyncedAt: lastSyncedAtMirror,
|
||||||
|
lastError: 'ops-sync payload inválido',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const outboxKeys = resolveOutboxKeys(options.outboxKeys)
|
||||||
|
const local = readOpsMirrorSnapshot()
|
||||||
|
|
||||||
|
// Skip apply+persist when the server mirror is unchanged and nothing is outboxed.
|
||||||
|
if (incoming.revisedAt === local.revisedAt && outboxKeys.size === 0 && lastSyncedAtMirror) {
|
||||||
|
return { status: 'idle', lastSyncedAt: lastSyncedAtMirror }
|
||||||
|
}
|
||||||
|
|
||||||
|
const merged = mergeOpsSnapshot(local, incoming, outboxKeys)
|
||||||
|
applyOpsMirrorSnapshot(merged)
|
||||||
|
|
||||||
|
const syncedAt = new Date().toISOString()
|
||||||
|
lastSyncedAtMirror = syncedAt
|
||||||
|
|
||||||
|
if (store) {
|
||||||
|
await persistMirrorSnapshot(store, merged, syncedAt)
|
||||||
|
}
|
||||||
|
|
||||||
|
return { status: 'idle', lastSyncedAt: syncedAt }
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : String(error)
|
||||||
|
return {
|
||||||
|
status: 'error',
|
||||||
|
lastSyncedAt: lastSyncedAtMirror,
|
||||||
|
lastError: message,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
197
src/components/campaign/opsSync/opsMirrorPersistence.ts
Normal file
197
src/components/campaign/opsSync/opsMirrorPersistence.ts
Normal file
|
|
@ -0,0 +1,197 @@
|
||||||
|
/**
|
||||||
|
* OH5 mirror persistence — OPFS file first, IndexedDB fallback.
|
||||||
|
*
|
||||||
|
* Decision (see docs/plans/oh5-sync-provider-mirror.md freshness audit):
|
||||||
|
* we dump/hydrate the full OpsSnapshot rather than wiring
|
||||||
|
* `@tanstack/browser-db-sqlite-persistence`. The GET `/ops-sync` contract is
|
||||||
|
* full-replace merge; TanStack collections stay `localOnly` (same pattern as
|
||||||
|
* OH6 outbox). OPFS is still preferred when `navigator.storage.getDirectory`
|
||||||
|
* works; otherwise IndexedDB.
|
||||||
|
*/
|
||||||
|
import { createEmptyOpsSnapshot, type OpsSnapshot } from '@/lib/campaignOps/opsContract'
|
||||||
|
import { OPS_MIRROR_SCHEMA_VERSION } from '@/lib/campaignOps/opsMirrorVersion'
|
||||||
|
|
||||||
|
export type OpsMirrorPersistenceMode = 'opfs' | 'idb' | 'memory'
|
||||||
|
|
||||||
|
export type OpsMirrorStoredPayload = {
|
||||||
|
schemaVersion: number
|
||||||
|
lastSyncedAt: string | null
|
||||||
|
snapshot: OpsSnapshot
|
||||||
|
}
|
||||||
|
|
||||||
|
export type OpsMirrorStore = {
|
||||||
|
readonly mode: OpsMirrorPersistenceMode
|
||||||
|
load: () => Promise<OpsMirrorStoredPayload | null>
|
||||||
|
save: (payload: OpsMirrorStoredPayload) => Promise<void>
|
||||||
|
clear: () => Promise<void>
|
||||||
|
}
|
||||||
|
|
||||||
|
const OPFS_DIR = 'teqo-ops-mirror'
|
||||||
|
const OPFS_FILE = 'snapshot.json'
|
||||||
|
const IDB_NAME = 'teqo-ops-mirror'
|
||||||
|
const IDB_STORE = 'mirror'
|
||||||
|
const IDB_KEY = 'payload'
|
||||||
|
|
||||||
|
export const createMemoryOpsMirrorStore = (
|
||||||
|
initial: OpsMirrorStoredPayload | null = null,
|
||||||
|
): OpsMirrorStore => {
|
||||||
|
let payload = initial
|
||||||
|
return {
|
||||||
|
mode: 'memory',
|
||||||
|
load: async () => payload,
|
||||||
|
save: async (next) => {
|
||||||
|
payload = next
|
||||||
|
},
|
||||||
|
clear: async () => {
|
||||||
|
payload = null
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const openIdb = (): Promise<IDBDatabase> =>
|
||||||
|
new Promise((resolve, reject) => {
|
||||||
|
const request = indexedDB.open(IDB_NAME, 1)
|
||||||
|
request.onerror = () => reject(request.error ?? new Error('IndexedDB open failed'))
|
||||||
|
request.onupgradeneeded = () => {
|
||||||
|
const db = request.result
|
||||||
|
if (!db.objectStoreNames.contains(IDB_STORE)) {
|
||||||
|
db.createObjectStore(IDB_STORE)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
request.onsuccess = () => resolve(request.result)
|
||||||
|
})
|
||||||
|
|
||||||
|
const idbRequest = <T>(request: IDBRequest<T>): Promise<T> =>
|
||||||
|
new Promise((resolve, reject) => {
|
||||||
|
request.onerror = () => reject(request.error ?? new Error('IndexedDB request failed'))
|
||||||
|
request.onsuccess = () => resolve(request.result)
|
||||||
|
})
|
||||||
|
|
||||||
|
export const createIdbOpsMirrorStore = (): OpsMirrorStore => ({
|
||||||
|
mode: 'idb',
|
||||||
|
load: async () => {
|
||||||
|
const db = await openIdb()
|
||||||
|
try {
|
||||||
|
const tx = db.transaction(IDB_STORE, 'readonly')
|
||||||
|
const raw = await idbRequest(tx.objectStore(IDB_STORE).get(IDB_KEY))
|
||||||
|
if (!raw || typeof raw !== 'object') return null
|
||||||
|
return raw as OpsMirrorStoredPayload
|
||||||
|
} finally {
|
||||||
|
db.close()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
save: async (payload) => {
|
||||||
|
const db = await openIdb()
|
||||||
|
try {
|
||||||
|
const tx = db.transaction(IDB_STORE, 'readwrite')
|
||||||
|
await idbRequest(tx.objectStore(IDB_STORE).put(payload, IDB_KEY))
|
||||||
|
await new Promise<void>((resolve, reject) => {
|
||||||
|
tx.oncomplete = () => resolve()
|
||||||
|
tx.onerror = () => reject(tx.error ?? new Error('IndexedDB write failed'))
|
||||||
|
})
|
||||||
|
} finally {
|
||||||
|
db.close()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
clear: async () => {
|
||||||
|
const db = await openIdb()
|
||||||
|
try {
|
||||||
|
const tx = db.transaction(IDB_STORE, 'readwrite')
|
||||||
|
await idbRequest(tx.objectStore(IDB_STORE).delete(IDB_KEY))
|
||||||
|
await new Promise<void>((resolve, reject) => {
|
||||||
|
tx.oncomplete = () => resolve()
|
||||||
|
tx.onerror = () => reject(tx.error ?? new Error('IndexedDB clear failed'))
|
||||||
|
})
|
||||||
|
} finally {
|
||||||
|
db.close()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const canUseOpfs = (): boolean =>
|
||||||
|
typeof navigator !== 'undefined' && typeof navigator.storage?.getDirectory === 'function'
|
||||||
|
|
||||||
|
const createOpfsOpsMirrorStore = (): OpsMirrorStore => {
|
||||||
|
const getFileHandle = async (create: boolean): Promise<FileSystemFileHandle> => {
|
||||||
|
const root = await navigator.storage.getDirectory()
|
||||||
|
const dir = await root.getDirectoryHandle(OPFS_DIR, { create })
|
||||||
|
return dir.getFileHandle(OPFS_FILE, { create })
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
mode: 'opfs',
|
||||||
|
load: async () => {
|
||||||
|
try {
|
||||||
|
const handle = await getFileHandle(false)
|
||||||
|
const file = await handle.getFile()
|
||||||
|
const text = await file.text()
|
||||||
|
if (!text) return null
|
||||||
|
return JSON.parse(text) as OpsMirrorStoredPayload
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
},
|
||||||
|
save: async (payload) => {
|
||||||
|
const handle = await getFileHandle(true)
|
||||||
|
const writable = await handle.createWritable()
|
||||||
|
try {
|
||||||
|
await writable.write(JSON.stringify(payload))
|
||||||
|
} finally {
|
||||||
|
await writable.close()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
clear: async () => {
|
||||||
|
try {
|
||||||
|
const root = await navigator.storage.getDirectory()
|
||||||
|
const dir = await root.getDirectoryHandle(OPFS_DIR, { create: false })
|
||||||
|
await dir.removeEntry(OPFS_FILE)
|
||||||
|
} catch {
|
||||||
|
// Missing dir/file is fine — already clear.
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Boot-time feature detect: try OPFS, fall back to IndexedDB on any failure
|
||||||
|
* (private mode, missing API, write probe fail). Never throws.
|
||||||
|
*/
|
||||||
|
export const openOpsMirrorStore = async (options?: {
|
||||||
|
forceMode?: OpsMirrorPersistenceMode
|
||||||
|
}): Promise<OpsMirrorStore> => {
|
||||||
|
if (options?.forceMode === 'memory') return createMemoryOpsMirrorStore()
|
||||||
|
if (options?.forceMode === 'idb') return createIdbOpsMirrorStore()
|
||||||
|
if (options?.forceMode === 'opfs') return createOpfsOpsMirrorStore()
|
||||||
|
|
||||||
|
if (canUseOpfs()) {
|
||||||
|
try {
|
||||||
|
const opfs = createOpfsOpsMirrorStore()
|
||||||
|
// Probe write so a later sync doesn't discover OPFS is read-only.
|
||||||
|
const existing = await opfs.load()
|
||||||
|
if (!existing) {
|
||||||
|
await opfs.save({
|
||||||
|
schemaVersion: OPS_MIRROR_SCHEMA_VERSION,
|
||||||
|
lastSyncedAt: null,
|
||||||
|
snapshot: createEmptyOpsSnapshot(new Date(0).toISOString()),
|
||||||
|
})
|
||||||
|
await opfs.clear()
|
||||||
|
}
|
||||||
|
return opfs
|
||||||
|
} catch {
|
||||||
|
// fall through to IDB
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof indexedDB === 'undefined') {
|
||||||
|
return createMemoryOpsMirrorStore()
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const idb = createIdbOpsMirrorStore()
|
||||||
|
// Probe open so a broken IDB surface falls to memory instead of crashing sync.
|
||||||
|
await idb.load()
|
||||||
|
return idb
|
||||||
|
} catch {
|
||||||
|
return createMemoryOpsMirrorStore()
|
||||||
|
}
|
||||||
|
}
|
||||||
33
src/components/campaign/opsSync/opsSyncChromeCopy.ts
Normal file
33
src/components/campaign/opsSync/opsSyncChromeCopy.ts
Normal file
|
|
@ -0,0 +1,33 @@
|
||||||
|
import type { OpsSyncStatus } from '@/lib/campaignOps/opsSyncMeta'
|
||||||
|
|
||||||
|
const MINUTE_MS = 60_000
|
||||||
|
const HOUR_MS = 60 * MINUTE_MS
|
||||||
|
|
||||||
|
/** Relative “Actualizado há …” for the shell chrome (pt-BR). */
|
||||||
|
export const formatOpsSyncRelative = (
|
||||||
|
lastSyncedAt: string | null,
|
||||||
|
nowMs: number = Date.now(),
|
||||||
|
): string => {
|
||||||
|
if (!lastSyncedAt) return 'A sincronizar…'
|
||||||
|
const syncedMs = Date.parse(lastSyncedAt)
|
||||||
|
if (Number.isNaN(syncedMs)) return 'A sincronizar…'
|
||||||
|
|
||||||
|
const elapsed = Math.max(0, nowMs - syncedMs)
|
||||||
|
if (elapsed < MINUTE_MS) return 'Actualizado agora'
|
||||||
|
const minutes = Math.floor(elapsed / MINUTE_MS)
|
||||||
|
if (minutes < 60) return `Actualizado há ${minutes}m`
|
||||||
|
const hours = Math.floor(elapsed / HOUR_MS)
|
||||||
|
if (hours < 24) return `Actualizado há ${hours}h`
|
||||||
|
const days = Math.floor(hours / 24)
|
||||||
|
return `Actualizado há ${days}d`
|
||||||
|
}
|
||||||
|
|
||||||
|
export const resolveOpsSyncChromeLabel = (input: {
|
||||||
|
status: OpsSyncStatus
|
||||||
|
lastSyncedAt: string | null
|
||||||
|
nowMs?: number
|
||||||
|
}): string => {
|
||||||
|
if (input.status === 'syncing') return 'A sincronizar…'
|
||||||
|
if (input.status === 'error') return 'Dados podem estar desatualizados'
|
||||||
|
return formatOpsSyncRelative(input.lastSyncedAt, input.nowMs)
|
||||||
|
}
|
||||||
|
|
@ -30,7 +30,14 @@ const wizardSkipButtonClass =
|
||||||
|
|
||||||
const wizardTitleSkeletonClass = 'mx-auto motion-reduce:animate-none bg-primary-foreground/20'
|
const wizardTitleSkeletonClass = 'mx-auto motion-reduce:animate-none bg-primary-foreground/20'
|
||||||
|
|
||||||
export const CampaignMobileTopBar = ({ notificationBell }: { notificationBell?: ReactNode }) => {
|
export const CampaignMobileTopBar = ({
|
||||||
|
notificationBell,
|
||||||
|
opsSyncStatus,
|
||||||
|
}: {
|
||||||
|
notificationBell?: ReactNode
|
||||||
|
/** OH5 — discreet sync chrome; only passed when OPS_HYBRID + staff. */
|
||||||
|
opsSyncStatus?: ReactNode
|
||||||
|
}) => {
|
||||||
const chrome = useCampaignWizardChrome()
|
const chrome = useCampaignWizardChrome()
|
||||||
const homeSearchChrome = useCampaignHomeSearchChrome()
|
const homeSearchChrome = useCampaignHomeSearchChrome()
|
||||||
const { isPending } = useCampaignListTransition()
|
const { isPending } = useCampaignListTransition()
|
||||||
|
|
@ -151,6 +158,11 @@ export const CampaignMobileTopBar = ({ notificationBell }: { notificationBell?:
|
||||||
<div className="min-w-0 flex-1 leading-tight">
|
<div className="min-w-0 flex-1 leading-tight">
|
||||||
<span className="block truncate text-sm font-semibold">Jorge Solla</span>
|
<span className="block truncate text-sm font-semibold">Jorge Solla</span>
|
||||||
<span className="block truncate text-xs text-primary-foreground/80">Campanha · Bahia</span>
|
<span className="block truncate text-xs text-primary-foreground/80">Campanha · Bahia</span>
|
||||||
|
{opsSyncStatus ? (
|
||||||
|
<div className="mt-0.5 text-primary-foreground/70 [&_[role=status]]:text-inherit">
|
||||||
|
{opsSyncStatus}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
{notificationBell ? <div className="shrink-0">{notificationBell}</div> : null}
|
{notificationBell ? <div className="shrink-0">{notificationBell}</div> : null}
|
||||||
</header>
|
</header>
|
||||||
|
|
|
||||||
|
|
@ -510,7 +510,10 @@ test.describe('Municípios — bottom drawer polish (B109)', () => {
|
||||||
const handle = page.getByRole('button', { name: 'Ocultar ações rápidas' })
|
const handle = page.getByRole('button', { name: 'Ocultar ações rápidas' })
|
||||||
const handleBox = await handle.boundingBox()
|
const handleBox = await handle.boundingBox()
|
||||||
expect(handleBox).toBeTruthy()
|
expect(handleBox).toBeTruthy()
|
||||||
expect(handleBox!.y).toBeLessThan(40)
|
// Fullscreen search docks the strip under the safe-area top bar; allow a
|
||||||
|
// few px of layout jitter (subpixel / font metrics) without losing the
|
||||||
|
// "near the top" assertion.
|
||||||
|
expect(handleBox!.y).toBeLessThan(48)
|
||||||
|
|
||||||
// Scope to the drawer: the município detail page also has a "Sugestões" region.
|
// Scope to the drawer: the município detail page also has a "Sugestões" region.
|
||||||
const drawer = page.getByRole('dialog', { name: 'Ações rápidas' })
|
const drawer = page.getByRole('dialog', { name: 'Ações rápidas' })
|
||||||
|
|
|
||||||
250
tests/unit/opsMirrorClient.unit.spec.ts
Normal file
250
tests/unit/opsMirrorClient.unit.spec.ts
Normal file
|
|
@ -0,0 +1,250 @@
|
||||||
|
// @vitest-environment jsdom
|
||||||
|
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
|
import {
|
||||||
|
applyOpsMirrorSnapshot,
|
||||||
|
bootstrapOpsMirror,
|
||||||
|
getOpsMirrorLastSyncedAt,
|
||||||
|
getOpsMirrorPersistenceMode,
|
||||||
|
municipalitiesCollection,
|
||||||
|
OPS_SYNC_PATH,
|
||||||
|
readOpsMirrorSnapshot,
|
||||||
|
resetOpsMirrorClientForTests,
|
||||||
|
syncOpsMirror,
|
||||||
|
votePledgesCollection,
|
||||||
|
} from '@/components/campaign/opsSync/opsMirrorClient'
|
||||||
|
import { createMemoryOpsMirrorStore } from '@/components/campaign/opsSync/opsMirrorPersistence'
|
||||||
|
import {
|
||||||
|
formatOpsSyncRelative,
|
||||||
|
resolveOpsSyncChromeLabel,
|
||||||
|
} from '@/components/campaign/opsSync/opsSyncChromeCopy'
|
||||||
|
import {
|
||||||
|
createEmptyOpsSnapshot,
|
||||||
|
opsOutboxKey,
|
||||||
|
type OpsSnapshot,
|
||||||
|
} from '@/lib/campaignOps/opsContract'
|
||||||
|
import { OPS_MIRROR_SCHEMA_VERSION } from '@/lib/campaignOps/opsMirrorVersion'
|
||||||
|
import { isStaffCampaignRole } from '@/lib/campaignRoles'
|
||||||
|
|
||||||
|
const baseSnapshot = (overrides: Partial<OpsSnapshot> = {}): OpsSnapshot => ({
|
||||||
|
...createEmptyOpsSnapshot('2026-08-01T12:00:00.000Z'),
|
||||||
|
municipalities: [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
name: 'Salvador',
|
||||||
|
slug: 'salvador',
|
||||||
|
kind: 'municipio',
|
||||||
|
city: 'Salvador',
|
||||||
|
region: 'RMS',
|
||||||
|
ibgeCode: '2927408',
|
||||||
|
updatedAt: '2026-08-01T12:00:00.000Z',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
votePledges: [
|
||||||
|
{
|
||||||
|
id: 10,
|
||||||
|
leadership: 2,
|
||||||
|
municipality: 1,
|
||||||
|
declaredVotes: 100,
|
||||||
|
estimatedVotes: { pessimistic: 80, central: 100, optimistic: 120 },
|
||||||
|
updatedAt: '2026-08-01T12:00:00.000Z',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
...overrides,
|
||||||
|
})
|
||||||
|
|
||||||
|
afterEach(async () => {
|
||||||
|
await resetOpsMirrorClientForTests()
|
||||||
|
vi.unstubAllGlobals()
|
||||||
|
vi.restoreAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('opsSync chrome copy', () => {
|
||||||
|
it('formats relative labels and error/syncing states', () => {
|
||||||
|
const now = Date.parse('2026-08-01T12:30:00.000Z')
|
||||||
|
expect(formatOpsSyncRelative('2026-08-01T12:29:30.000Z', now)).toBe('Actualizado agora')
|
||||||
|
expect(formatOpsSyncRelative('2026-08-01T12:25:00.000Z', now)).toBe('Actualizado há 5m')
|
||||||
|
expect(resolveOpsSyncChromeLabel({ status: 'syncing', lastSyncedAt: null })).toBe(
|
||||||
|
'A sincronizar…',
|
||||||
|
)
|
||||||
|
expect(
|
||||||
|
resolveOpsSyncChromeLabel({
|
||||||
|
status: 'error',
|
||||||
|
lastSyncedAt: '2026-08-01T12:00:00.000Z',
|
||||||
|
}),
|
||||||
|
).toBe('Dados podem estar desatualizados')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('opsMirrorClient', () => {
|
||||||
|
it('hydrates from store without network when skipNetworkSync', async () => {
|
||||||
|
const store = createMemoryOpsMirrorStore({
|
||||||
|
schemaVersion: OPS_MIRROR_SCHEMA_VERSION,
|
||||||
|
lastSyncedAt: '2026-08-01T11:00:00.000Z',
|
||||||
|
snapshot: baseSnapshot(),
|
||||||
|
})
|
||||||
|
|
||||||
|
const fetchImpl = vi.fn()
|
||||||
|
const result = await bootstrapOpsMirror({ store, skipNetworkSync: true, fetchImpl })
|
||||||
|
|
||||||
|
expect(result.hydrated).toBe(true)
|
||||||
|
expect(result.mode).toBe('memory')
|
||||||
|
expect(municipalitiesCollection.get(1)?.name).toBe('Salvador')
|
||||||
|
expect(getOpsMirrorLastSyncedAt()).toBe('2026-08-01T11:00:00.000Z')
|
||||||
|
expect(fetchImpl).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('wipes and rehydrates empty when stored schemaVersion mismatches', async () => {
|
||||||
|
const store = createMemoryOpsMirrorStore({
|
||||||
|
schemaVersion: OPS_MIRROR_SCHEMA_VERSION + 1,
|
||||||
|
lastSyncedAt: '2026-08-01T11:00:00.000Z',
|
||||||
|
snapshot: baseSnapshot(),
|
||||||
|
})
|
||||||
|
|
||||||
|
await bootstrapOpsMirror({ store, skipNetworkSync: true })
|
||||||
|
|
||||||
|
expect(municipalitiesCollection.size).toBe(0)
|
||||||
|
expect(await store.load()).toBeNull()
|
||||||
|
expect(getOpsMirrorLastSyncedAt()).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('syncs via GET, merges into collections, and persists', async () => {
|
||||||
|
const store = createMemoryOpsMirrorStore()
|
||||||
|
const incoming = baseSnapshot({
|
||||||
|
municipalities: [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
name: 'Salvador (sync)',
|
||||||
|
slug: 'salvador',
|
||||||
|
kind: 'municipio',
|
||||||
|
city: 'Salvador',
|
||||||
|
region: 'RMS',
|
||||||
|
ibgeCode: '2927408',
|
||||||
|
updatedAt: '2026-08-01T13:00:00.000Z',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 2,
|
||||||
|
name: 'Feira',
|
||||||
|
slug: 'feira-de-santana',
|
||||||
|
kind: 'municipio',
|
||||||
|
city: 'Feira de Santana',
|
||||||
|
region: 'Portal',
|
||||||
|
ibgeCode: '2910800',
|
||||||
|
updatedAt: '2026-08-01T13:00:00.000Z',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
|
||||||
|
const fetchImpl = vi.fn().mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
json: async () => incoming,
|
||||||
|
})
|
||||||
|
|
||||||
|
await bootstrapOpsMirror({ store, skipNetworkSync: true })
|
||||||
|
const sync = await syncOpsMirror({ store, fetchImpl })
|
||||||
|
|
||||||
|
expect(fetchImpl).toHaveBeenCalledWith(
|
||||||
|
OPS_SYNC_PATH,
|
||||||
|
expect.objectContaining({ method: 'GET', cache: 'no-store' }),
|
||||||
|
)
|
||||||
|
expect(sync.status).toBe('idle')
|
||||||
|
expect(municipalitiesCollection.get(1)?.name).toBe('Salvador (sync)')
|
||||||
|
expect(municipalitiesCollection.get(2)?.name).toBe('Feira')
|
||||||
|
expect(getOpsMirrorPersistenceMode()).toBe('memory')
|
||||||
|
|
||||||
|
const stored = await store.load()
|
||||||
|
expect(stored?.snapshot.municipalities).toHaveLength(2)
|
||||||
|
expect(stored?.lastSyncedAt).toBe(sync.lastSyncedAt)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not smash outbox-marked pledge rows on merge', async () => {
|
||||||
|
applyOpsMirrorSnapshot(
|
||||||
|
baseSnapshot({
|
||||||
|
votePledges: [
|
||||||
|
{
|
||||||
|
id: 10,
|
||||||
|
leadership: 2,
|
||||||
|
municipality: 1,
|
||||||
|
declaredVotes: 100,
|
||||||
|
estimatedVotes: { pessimistic: 50, central: 60, optimistic: 70 },
|
||||||
|
updatedAt: '2026-08-01T10:00:00.000Z',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
const store = createMemoryOpsMirrorStore()
|
||||||
|
const incoming = baseSnapshot({
|
||||||
|
votePledges: [
|
||||||
|
{
|
||||||
|
id: 10,
|
||||||
|
leadership: 2,
|
||||||
|
municipality: 1,
|
||||||
|
declaredVotes: 100,
|
||||||
|
estimatedVotes: { pessimistic: 200, central: 300, optimistic: 400 },
|
||||||
|
updatedAt: '2026-08-01T13:00:00.000Z',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
|
||||||
|
const fetchImpl = vi.fn().mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
json: async () => incoming,
|
||||||
|
})
|
||||||
|
|
||||||
|
const sync = await syncOpsMirror({
|
||||||
|
store,
|
||||||
|
fetchImpl,
|
||||||
|
outboxKeys: new Set([opsOutboxKey('votePledges', 10)]),
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(sync.status).toBe('idle')
|
||||||
|
expect(votePledgesCollection.get(10)?.estimatedVotes?.central).toBe(60)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns error state when fetch fails (chrome can show stale)', async () => {
|
||||||
|
const store = createMemoryOpsMirrorStore({
|
||||||
|
schemaVersion: OPS_MIRROR_SCHEMA_VERSION,
|
||||||
|
lastSyncedAt: '2026-08-01T11:00:00.000Z',
|
||||||
|
snapshot: baseSnapshot(),
|
||||||
|
})
|
||||||
|
await bootstrapOpsMirror({ store, skipNetworkSync: true })
|
||||||
|
|
||||||
|
const fetchImpl = vi.fn().mockRejectedValue(new Error('network down'))
|
||||||
|
const sync = await syncOpsMirror({ store, fetchImpl })
|
||||||
|
|
||||||
|
expect(sync.status).toBe('error')
|
||||||
|
expect(sync.lastError).toMatch(/network down/)
|
||||||
|
expect(sync.lastSyncedAt).toBe('2026-08-01T11:00:00.000Z')
|
||||||
|
expect(readOpsMirrorSnapshot().municipalities).toHaveLength(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('skips apply when revisedAt is unchanged and outbox is empty', async () => {
|
||||||
|
const snapshot = baseSnapshot()
|
||||||
|
const store = createMemoryOpsMirrorStore({
|
||||||
|
schemaVersion: OPS_MIRROR_SCHEMA_VERSION,
|
||||||
|
lastSyncedAt: '2026-08-01T11:00:00.000Z',
|
||||||
|
snapshot,
|
||||||
|
})
|
||||||
|
await bootstrapOpsMirror({ store, skipNetworkSync: true })
|
||||||
|
|
||||||
|
const fetchImpl = vi.fn().mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
json: async () => snapshot,
|
||||||
|
})
|
||||||
|
const sync = await syncOpsMirror({ store, fetchImpl, outboxKeys: new Set() })
|
||||||
|
|
||||||
|
expect(sync.status).toBe('idle')
|
||||||
|
expect(sync.lastSyncedAt).toBe('2026-08-01T11:00:00.000Z')
|
||||||
|
expect(municipalitiesCollection.get(1)?.name).toBe('Salvador')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('leader defense in depth (layout gate)', () => {
|
||||||
|
it('treats leader as non-staff so provider stays no-op even with OPS_HYBRID', () => {
|
||||||
|
expect(isStaffCampaignRole('leader')).toBe(false)
|
||||||
|
expect(isStaffCampaignRole('advisor')).toBe(true)
|
||||||
|
expect(isStaffCampaignRole('coordinator')).toBe(true)
|
||||||
|
expect(isStaffCampaignRole('candidate')).toBe(true)
|
||||||
|
})
|
||||||
|
})
|
||||||
47
tests/unit/opsMirrorPersistence.unit.spec.ts
Normal file
47
tests/unit/opsMirrorPersistence.unit.spec.ts
Normal file
|
|
@ -0,0 +1,47 @@
|
||||||
|
// @vitest-environment jsdom
|
||||||
|
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
|
import {
|
||||||
|
createIdbOpsMirrorStore,
|
||||||
|
createMemoryOpsMirrorStore,
|
||||||
|
openOpsMirrorStore,
|
||||||
|
} from '@/components/campaign/opsSync/opsMirrorPersistence'
|
||||||
|
import { createEmptyOpsSnapshot } from '@/lib/campaignOps/opsContract'
|
||||||
|
import { OPS_MIRROR_SCHEMA_VERSION } from '@/lib/campaignOps/opsMirrorVersion'
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.unstubAllGlobals()
|
||||||
|
vi.restoreAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('opsMirrorPersistence', () => {
|
||||||
|
it('round-trips through the memory store', async () => {
|
||||||
|
const store = createMemoryOpsMirrorStore()
|
||||||
|
const payload = {
|
||||||
|
schemaVersion: OPS_MIRROR_SCHEMA_VERSION,
|
||||||
|
lastSyncedAt: '2026-08-01T12:00:00.000Z',
|
||||||
|
snapshot: createEmptyOpsSnapshot('2026-08-01T12:00:00.000Z'),
|
||||||
|
}
|
||||||
|
await store.save(payload)
|
||||||
|
expect(await store.load()).toEqual(payload)
|
||||||
|
await store.clear()
|
||||||
|
expect(await store.load()).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('falls back when OPFS is unavailable (no navigator.storage.getDirectory)', async () => {
|
||||||
|
vi.stubGlobal('navigator', { storage: {} })
|
||||||
|
|
||||||
|
// Prefer an explicit idb force in environments without a working IDB;
|
||||||
|
// openOpsMirrorStore must not throw when OPFS is missing.
|
||||||
|
const store = await openOpsMirrorStore({ forceMode: 'idb' })
|
||||||
|
expect(store.mode).toBe('idb')
|
||||||
|
|
||||||
|
const auto = await openOpsMirrorStore()
|
||||||
|
// jsdom may or may not expose indexedDB — either idb or memory is fine.
|
||||||
|
expect(['idb', 'memory']).toContain(auto.mode)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('creates an idb store handle without crashing', () => {
|
||||||
|
expect(createIdbOpsMirrorStore().mode).toBe('idb')
|
||||||
|
})
|
||||||
|
})
|
||||||
Loading…
Reference in a new issue