mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-27 06:13:06 +00:00
Merge pull request #225 from fsolla/cursor/pool-i173-c6d45316-1171
OH11 — SW /_next/static cache-first + e2e offline + docs
This commit is contained in:
commit
fcc9270db8
14 changed files with 218 additions and 18 deletions
|
|
@ -4,6 +4,8 @@ Conteúdo movido do `AGENTS.md` em 2026-07-30 (fatiamento do paradigma de agente
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
**Recently resolved (2026-08-02):** **OH11** (Issue #173) — SW cache-first para `/_next/static/` (chunks hashed, prefixo `campanha-<buildId>`); logout limpa campaignOps na ordem abort sync → outbox → persistence → Cache API (`clearCampaignOpsStorage` + `clearCampaignPwaCaches`); e2e `campaignOpsOffline` com jornada write→reload→online→sync (`OPS_HYBRID=1`). Plano: [`oh11-sw-e2e-docs.md`](docs/plans/oh11-sw-e2e-docs.md).
|
||||||
|
|
||||||
**Recently resolved (2026-08-02):** **B120** (Issue #207) — municípios mobile: combobox multi-filtro (chips + typeahead) no lugar da pilha NativeSelect; overview KPI + aviso de sort só em `md+`; cards densificados (cobertura/nível + controles compactos). URL B18 intacta. Plano: [`municipios-mobile-filtro-combobox-densificar.md`](docs/plans/municipios-mobile-filtro-combobox-densificar.md).
|
**Recently resolved (2026-08-02):** **B120** (Issue #207) — municípios mobile: combobox multi-filtro (chips + typeahead) no lugar da pilha NativeSelect; overview KPI + aviso de sort só em `md+`; cards densificados (cobertura/nível + controles compactos). URL B18 intacta. Plano: [`municipios-mobile-filtro-combobox-densificar.md`](docs/plans/municipios-mobile-filtro-combobox-densificar.md).
|
||||||
|
|
||||||
**Recently resolved (2026-08-02):** **OH10** (Issue #171) — writes municipality staff CAS (`baseUpdatedAt`) + outbox irmão (`opsMunicipalityOutbox`) para municipalityUpdate, declareVotes, tendência, engagement e advisors; flag OFF mantém caminhos actuais. Plano: [`oh10-municipality-writes-cas.md`](docs/plans/oh10-municipality-writes-cas.md).
|
**Recently resolved (2026-08-02):** **OH10** (Issue #171) — writes municipality staff CAS (`baseUpdatedAt`) + outbox irmão (`opsMunicipalityOutbox`) para municipalityUpdate, declareVotes, tendência, engagement e advisors; flag OFF mantém caminhos actuais. Plano: [`oh10-municipality-writes-cas.md`](docs/plans/oh10-municipality-writes-cas.md).
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
# OH11 — SW `/_next/static` cache-first + e2e offline + docs
|
# OH11 — SW `/_next/static` cache-first + e2e offline + docs
|
||||||
|
|
||||||
Status: rascunho
|
Status: entregue
|
||||||
Atualizado em: 2026-08-01
|
Atualizado em: 2026-08-02
|
||||||
Issue: #173
|
Issue: #173
|
||||||
Priority: P1
|
Priority: P1
|
||||||
Model: composer-2.5
|
Model: composer-2.5
|
||||||
|
|
@ -42,9 +42,9 @@ Dados: N/A.
|
||||||
|
|
||||||
- **Quota:** ~0,5
|
- **Quota:** ~0,5
|
||||||
- **Aceite:**
|
- **Aceite:**
|
||||||
- [ ] chunks `/_next/static/` servidos do cache na 2ª visita offline
|
- [x] chunks `/_next/static/` servidos do cache na 2ª visita offline
|
||||||
- [ ] RSC/Flight nunca cacheado (pin existente mantido)
|
- [x] RSC/Flight nunca cacheado (pin existente mantido)
|
||||||
- [ ] logout limpa persistence + outbox + caches (ordem documentada no código)
|
- [x] logout limpa persistence + outbox + caches (ordem documentada no código)
|
||||||
- **Verify:** `pnpm gate:fast` + `campaignPwa.unit.spec.ts`
|
- **Verify:** `pnpm gate:fast` + `campaignPwa.unit.spec.ts`
|
||||||
- **Files:** `campaignPwa.ts`, `campaignPwaClient.ts`, spec unit
|
- **Files:** `campaignPwa.ts`, `campaignPwaClient.ts`, spec unit
|
||||||
- **Tamanho:** M
|
- **Tamanho:** M
|
||||||
|
|
@ -53,8 +53,8 @@ Dados: N/A.
|
||||||
|
|
||||||
- **Quota:** ~0,5
|
- **Quota:** ~0,5
|
||||||
- **Aceite:**
|
- **Aceite:**
|
||||||
- [ ] cenário write→reload→online→sync verde
|
- [x] cenário write→reload→online→sync verde
|
||||||
- [ ] CHANGELOG + plano-mãe actualizados
|
- [x] CHANGELOG + plano-mãe actualizados
|
||||||
- **Verify:** `pnpm gate:fast` + e2e offline
|
- **Verify:** `pnpm gate:fast` + e2e offline
|
||||||
- **Files:** spec e2e, docs
|
- **Files:** spec e2e, docs
|
||||||
- **Tamanho:** M
|
- **Tamanho:** M
|
||||||
|
|
|
||||||
|
|
@ -56,7 +56,7 @@ Brief:
|
||||||
- Documento-mãe que trava: arquitetura híbrida, escopo do snapshot, CAS/outbox, boundaries, critérios de aceite do projecto e ordem das Issues OH2–OH14.
|
- Documento-mãe que trava: arquitetura híbrida, escopo do snapshot, CAS/outbox, boundaries, critérios de aceite do projecto e ordem das Issues OH2–OH14.
|
||||||
- Engenheiro júnior lê este doc + o plano da sua Issue e executa sem reunião.
|
- Engenheiro júnior lê este doc + o plano da sua Issue e executa sem reunião.
|
||||||
- Com `OPS_HYBRID=1` (entregas filhas): abrir `/campanha` sincroniza o snapshot; chrome “Actualizado”; offline renderiza do mirror; writes via outbox + CAS.
|
- Com `OPS_HYBRID=1` (entregas filhas): abrir `/campanha` sincroniza o snapshot; chrome “Actualizado”; offline renderiza do mirror; writes via outbox + CAS.
|
||||||
- CI sem `OPS_HYBRID` idêntica a `main`.
|
- CI sem `OPS_HYBRID` idêntica a `main`; jornada offline completa em `campaignOpsOffline.e2e.spec.ts` com `OPS_HYBRID=1` (OH11).
|
||||||
|
|
||||||
## Dados → decisão → apresentação
|
## Dados → decisão → apresentação
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -66,6 +66,7 @@
|
||||||
"test": "pnpm run test:unit && pnpm run test:int",
|
"test": "pnpm run test:unit && pnpm run test:int",
|
||||||
"test:all": "pnpm run test && pnpm run test:e2e",
|
"test:all": "pnpm run test && pnpm run test:e2e",
|
||||||
"test:e2e": "cross-env NODE_OPTIONS=\"--no-deprecation --conditions=react-server --import=tsx/esm\" playwright test --config=playwright.config.ts",
|
"test:e2e": "cross-env NODE_OPTIONS=\"--no-deprecation --conditions=react-server --import=tsx/esm\" playwright test --config=playwright.config.ts",
|
||||||
|
"test:e2e:ops-hybrid": "cross-env OPS_HYBRID=1 NODE_OPTIONS=\"--no-deprecation --conditions=react-server --import=tsx/esm\" playwright test --config=playwright.config.ts tests/e2e/campaignOpsOffline.e2e.spec.ts tests/e2e/campaignOpsEstimateOutbox.e2e.spec.ts",
|
||||||
"test:e2e:affected": "node scripts/run-e2e-affected.mjs",
|
"test:e2e:affected": "node scripts/run-e2e-affected.mjs",
|
||||||
"test:int": "cross-env NODE_OPTIONS=--no-deprecation vitest run --config ./vitest.config.mts",
|
"test:int": "cross-env NODE_OPTIONS=--no-deprecation vitest run --config ./vitest.config.mts",
|
||||||
"test:unit": "cross-env NODE_OPTIONS=--no-deprecation DATABASE_URL=postgresql://invalid:invalid@127.0.0.1:1/unit_tests_must_not_connect vitest run --config ./vitest.unit.config.mts",
|
"test:unit": "cross-env NODE_OPTIONS=--no-deprecation DATABASE_URL=postgresql://invalid:invalid@127.0.0.1:1/unit_tests_must_not_connect vitest run --config ./vitest.unit.config.mts",
|
||||||
|
|
|
||||||
|
|
@ -119,6 +119,7 @@ export default defineConfig({
|
||||||
PAYLOAD_SECRET: process.env.PAYLOAD_SECRET ?? 'test-only-secret-not-used-in-production',
|
PAYLOAD_SECRET: process.env.PAYLOAD_SECRET ?? 'test-only-secret-not-used-in-production',
|
||||||
NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL ?? baseURL,
|
NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL ?? baseURL,
|
||||||
LIST_UNIFIED: process.env.LIST_UNIFIED ?? '',
|
LIST_UNIFIED: process.env.LIST_UNIFIED ?? '',
|
||||||
|
OPS_HYBRID: process.env.OPS_HYBRID ?? '',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -95,7 +95,7 @@ export const E2E_AFFECTED_MANIFEST = [
|
||||||
'src/components/campaign/shared/Wizard',
|
'src/components/campaign/shared/Wizard',
|
||||||
'src/components/campaign/shared/useWizardBackHistory',
|
'src/components/campaign/shared/useWizardBackHistory',
|
||||||
],
|
],
|
||||||
specs: ['campaign-pwa', 'campaignWizardChrome', 'campaignMunicipalities'],
|
specs: ['campaign-pwa', 'campaignWizardChrome', 'campaignMunicipalities', 'campaignOpsOffline'],
|
||||||
},
|
},
|
||||||
// Domains without a dedicated e2e family still wake campaign home smoke so
|
// Domains without a dedicated e2e family still wake campaign home smoke so
|
||||||
// the affected classifier cannot return mode=none on an unmapped domain dir.
|
// the affected classifier cannot return mode=none on an unmapped domain dir.
|
||||||
|
|
@ -131,6 +131,11 @@ export const E2E_AFFECTED_MANIFEST = [
|
||||||
`${CAMPAIGN_APP}/perfil`,
|
`${CAMPAIGN_APP}/perfil`,
|
||||||
`${CAMPAIGN_APP}/quadro`,
|
`${CAMPAIGN_APP}/quadro`,
|
||||||
],
|
],
|
||||||
specs: ['campaignHomeActions', 'campaignMunicipalities', 'campaignOpsEstimateOutbox'],
|
specs: [
|
||||||
|
'campaignHomeActions',
|
||||||
|
'campaignMunicipalities',
|
||||||
|
'campaignOpsEstimateOutbox',
|
||||||
|
'campaignOpsOffline',
|
||||||
|
],
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
|
|
|
||||||
19
src/components/campaign/opsSync/clearCampaignOpsStorage.ts
Normal file
19
src/components/campaign/opsSync/clearCampaignOpsStorage.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
'use client'
|
||||||
|
|
||||||
|
import { clearOpsEstimateOutboxForLogout } from '@/components/campaign/opsSync/opsEstimateOutbox'
|
||||||
|
import {
|
||||||
|
abortOpsMirrorSync,
|
||||||
|
clearOpsMirrorPersistenceForLogout,
|
||||||
|
} from '@/components/campaign/opsSync/opsMirrorClient'
|
||||||
|
import { clearOpsMunicipalityOutboxForLogout } from '@/components/campaign/opsSync/opsMunicipalityOutbox'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Logout wipe for campaignOps mirror + outbox (OH1/OH11).
|
||||||
|
*
|
||||||
|
* Order: abort in-flight sync → outbox → persistence → (caller clears Cache API).
|
||||||
|
*/
|
||||||
|
export const clearCampaignOpsStorage = async (): Promise<void> => {
|
||||||
|
abortOpsMirrorSync()
|
||||||
|
await Promise.all([clearOpsEstimateOutboxForLogout(), clearOpsMunicipalityOutboxForLogout()])
|
||||||
|
await clearOpsMirrorPersistenceForLogout()
|
||||||
|
}
|
||||||
|
|
@ -179,3 +179,22 @@ export const collectOpsEstimateOutboxKeys = (): Set<OpsOutboxKey> => {
|
||||||
}
|
}
|
||||||
return keys
|
return keys
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Logout wipe — outbox storage + in-memory rows (OH11). */
|
||||||
|
export const clearOpsEstimateOutboxForLogout = async (): Promise<void> => {
|
||||||
|
if (executorSingleton) {
|
||||||
|
try {
|
||||||
|
await executorSingleton.clearOutbox()
|
||||||
|
executorSingleton.dispose()
|
||||||
|
} catch {
|
||||||
|
// Best effort — private mode / torn-down storage.
|
||||||
|
}
|
||||||
|
executorSingleton = null
|
||||||
|
initPromise = null
|
||||||
|
}
|
||||||
|
for (const row of opsEstimateOutboxCollection.toArray) {
|
||||||
|
if (opsEstimateOutboxCollection.has(row.pledgeId)) {
|
||||||
|
opsEstimateOutboxCollection.delete(row.pledgeId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -55,6 +55,13 @@ let lastSyncedAtMirror: string | null = null
|
||||||
let persistenceMode: OpsMirrorPersistenceMode | null = null
|
let persistenceMode: OpsMirrorPersistenceMode | null = null
|
||||||
let storeSingleton: OpsMirrorStore | null = null
|
let storeSingleton: OpsMirrorStore | null = null
|
||||||
let bootPromise: Promise<{ mode: OpsMirrorPersistenceMode; hydrated: boolean }> | null = null
|
let bootPromise: Promise<{ mode: OpsMirrorPersistenceMode; hydrated: boolean }> | null = null
|
||||||
|
let activeSyncAbort: AbortController | null = null
|
||||||
|
|
||||||
|
/** Abort an in-flight ops-sync fetch (logout — OH11). */
|
||||||
|
export const abortOpsMirrorSync = (): void => {
|
||||||
|
activeSyncAbort?.abort()
|
||||||
|
activeSyncAbort = null
|
||||||
|
}
|
||||||
|
|
||||||
const replaceCollectionRows = <T extends { id: number }>(
|
const replaceCollectionRows = <T extends { id: number }>(
|
||||||
collection: {
|
collection: {
|
||||||
|
|
@ -114,12 +121,22 @@ export const getOpsMirrorPersistenceMode = (): OpsMirrorPersistenceMode | null =
|
||||||
|
|
||||||
export const getOpsMirrorLastSyncedAt = (): string | null => lastSyncedAtMirror
|
export const getOpsMirrorLastSyncedAt = (): string | null => lastSyncedAtMirror
|
||||||
|
|
||||||
|
/** Logout wipe — persistence only; outbox cleared separately (OH11 order). */
|
||||||
|
export const clearOpsMirrorPersistenceForLogout = async (): Promise<void> => {
|
||||||
|
wipeOpsMirrorCollections()
|
||||||
|
bootPromise = null
|
||||||
|
const store = storeSingleton
|
||||||
|
storeSingleton = null
|
||||||
|
persistenceMode = null
|
||||||
|
if (store) {
|
||||||
|
await store.clear()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Test/DI seam — reset module singletons between unit cases. */
|
/** Test/DI seam — reset module singletons between unit cases. */
|
||||||
export const resetOpsMirrorClientForTests = async (): Promise<void> => {
|
export const resetOpsMirrorClientForTests = async (): Promise<void> => {
|
||||||
wipeOpsMirrorCollections()
|
abortOpsMirrorSync()
|
||||||
storeSingleton = null
|
await clearOpsMirrorPersistenceForLogout()
|
||||||
bootPromise = null
|
|
||||||
persistenceMode = null
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const resolveOutboxKeys = (explicit?: ReadonlySet<OpsOutboxKey>): ReadonlySet<OpsOutboxKey> => {
|
const resolveOutboxKeys = (explicit?: ReadonlySet<OpsOutboxKey>): ReadonlySet<OpsOutboxKey> => {
|
||||||
|
|
@ -200,6 +217,8 @@ export type SyncOpsMirrorOptions = {
|
||||||
export const syncOpsMirror = async (options: SyncOpsMirrorOptions = {}): Promise<OpsSyncState> => {
|
export const syncOpsMirror = async (options: SyncOpsMirrorOptions = {}): Promise<OpsSyncState> => {
|
||||||
const fetchImpl = options.fetchImpl ?? fetch
|
const fetchImpl = options.fetchImpl ?? fetch
|
||||||
const store = options.store ?? storeSingleton
|
const store = options.store ?? storeSingleton
|
||||||
|
const controller = new AbortController()
|
||||||
|
activeSyncAbort = controller
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetchImpl(OPS_SYNC_PATH, {
|
const response = await fetchImpl(OPS_SYNC_PATH, {
|
||||||
|
|
@ -207,6 +226,7 @@ export const syncOpsMirror = async (options: SyncOpsMirrorOptions = {}): Promise
|
||||||
credentials: 'same-origin',
|
credentials: 'same-origin',
|
||||||
headers: { Accept: 'application/json' },
|
headers: { Accept: 'application/json' },
|
||||||
cache: 'no-store',
|
cache: 'no-store',
|
||||||
|
signal: controller.signal,
|
||||||
})
|
})
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
|
|
@ -251,11 +271,16 @@ export const syncOpsMirror = async (options: SyncOpsMirrorOptions = {}): Promise
|
||||||
|
|
||||||
return { status: 'idle', lastSyncedAt: syncedAt }
|
return { status: 'idle', lastSyncedAt: syncedAt }
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
if (error instanceof DOMException && error.name === 'AbortError') {
|
||||||
|
return { status: 'idle', lastSyncedAt: lastSyncedAtMirror }
|
||||||
|
}
|
||||||
const message = error instanceof Error ? error.message : String(error)
|
const message = error instanceof Error ? error.message : String(error)
|
||||||
return {
|
return {
|
||||||
status: 'error',
|
status: 'error',
|
||||||
lastSyncedAt: lastSyncedAtMirror,
|
lastSyncedAt: lastSyncedAtMirror,
|
||||||
lastError: message,
|
lastError: message,
|
||||||
}
|
}
|
||||||
|
} finally {
|
||||||
|
if (activeSyncAbort === controller) activeSyncAbort = null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -654,3 +654,46 @@ export const discardOpsAdvisorsOutboxRow = (municipalityId: number): void => {
|
||||||
advisorsOutboxCollection.delete(municipalityId)
|
advisorsOutboxCollection.delete(municipalityId)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const wipeMunicipalityOutboxCollections = (): void => {
|
||||||
|
for (const row of declareVotesOutboxCollection.toArray) {
|
||||||
|
if (declareVotesOutboxCollection.has(row.id)) {
|
||||||
|
declareVotesOutboxCollection.delete(row.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const row of municipalityUpdateOutboxCollection.toArray) {
|
||||||
|
if (municipalityUpdateOutboxCollection.has(row.id)) {
|
||||||
|
municipalityUpdateOutboxCollection.delete(row.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const row of politicalTrendOutboxCollection.toArray) {
|
||||||
|
if (politicalTrendOutboxCollection.has(row.municipalityId)) {
|
||||||
|
politicalTrendOutboxCollection.delete(row.municipalityId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const row of engagementLevelOutboxCollection.toArray) {
|
||||||
|
if (engagementLevelOutboxCollection.has(row.municipalityId)) {
|
||||||
|
engagementLevelOutboxCollection.delete(row.municipalityId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const row of advisorsOutboxCollection.toArray) {
|
||||||
|
if (advisorsOutboxCollection.has(row.municipalityId)) {
|
||||||
|
advisorsOutboxCollection.delete(row.municipalityId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Logout wipe — outbox storage + in-memory rows (OH11). */
|
||||||
|
export const clearOpsMunicipalityOutboxForLogout = async (): Promise<void> => {
|
||||||
|
if (executorSingleton) {
|
||||||
|
try {
|
||||||
|
await executorSingleton.clearOutbox()
|
||||||
|
executorSingleton.dispose()
|
||||||
|
} catch {
|
||||||
|
// Best effort — private mode / torn-down storage.
|
||||||
|
}
|
||||||
|
executorSingleton = null
|
||||||
|
initPromise = null
|
||||||
|
}
|
||||||
|
wipeMunicipalityOutboxCollections()
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,7 @@ import { usePathname } from 'next/navigation'
|
||||||
import { useState, type FormEvent, type ReactNode } from 'react'
|
import { useState, type FormEvent, type ReactNode } from 'react'
|
||||||
|
|
||||||
import { logoutCampaign } from '@/app/(campaign)/campanha/actions/auth'
|
import { logoutCampaign } from '@/app/(campaign)/campanha/actions/auth'
|
||||||
|
import { clearCampaignOpsStorage } from '@/components/campaign/opsSync/clearCampaignOpsStorage'
|
||||||
import { CampaignScopeBadge } from '@/components/campaign/shared/CampaignScopeBadge'
|
import { CampaignScopeBadge } from '@/components/campaign/shared/CampaignScopeBadge'
|
||||||
import { CampaignUserAvatar } from '@/components/campaign/shared/CampaignUserAvatar'
|
import { CampaignUserAvatar } from '@/components/campaign/shared/CampaignUserAvatar'
|
||||||
import { CampaignLogo } from '@/components/campaign/shell/campaign-logo'
|
import { CampaignLogo } from '@/components/campaign/shell/campaign-logo'
|
||||||
|
|
@ -79,6 +80,7 @@ export const CampaignSidebar = ({ user }: { user: CampaignSidebarUser }) => {
|
||||||
clearRecentVisits()
|
clearRecentVisits()
|
||||||
clearLastActedMunicipality()
|
clearLastActedMunicipality()
|
||||||
clearMunicipalitySavedFilters()
|
clearMunicipalitySavedFilters()
|
||||||
|
await clearCampaignOpsStorage()
|
||||||
await clearCampaignPwaCaches()
|
await clearCampaignPwaCaches()
|
||||||
// logoutCampaign redirects — no need to reset the pending flag on success.
|
// logoutCampaign redirects — no need to reset the pending flag on success.
|
||||||
await logoutCampaign()
|
await logoutCampaign()
|
||||||
|
|
|
||||||
|
|
@ -123,6 +123,8 @@ const isInvitePath = (pathname) => pathname.startsWith(SCOPE + '/convite');
|
||||||
|
|
||||||
const isCampaignIconPath = (pathname) => pathname.startsWith('/campaign-icons/');
|
const isCampaignIconPath = (pathname) => pathname.startsWith('/campaign-icons/');
|
||||||
|
|
||||||
|
const isNextStaticPath = (pathname) => pathname.startsWith('/_next/static/');
|
||||||
|
|
||||||
const isRscRequest = (request) =>
|
const isRscRequest = (request) =>
|
||||||
request.headers.get('RSC') === '1' || request.headers.has('Next-Router-State-Tree');
|
request.headers.get('RSC') === '1' || request.headers.has('Next-Router-State-Tree');
|
||||||
|
|
||||||
|
|
@ -173,6 +175,12 @@ self.addEventListener('fetch', (event) => {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Hashed build chunks — cache-first so a revisit works offline (never RSC/Flight).
|
||||||
|
if (isNextStaticPath(url.pathname)) {
|
||||||
|
event.respondWith(cacheFirst(request));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (!isCampaignPath(url.pathname)) return;
|
if (!isCampaignPath(url.pathname)) return;
|
||||||
|
|
||||||
if (request.mode === 'navigate') {
|
if (request.mode === 'navigate') {
|
||||||
|
|
|
||||||
|
|
@ -1,14 +1,15 @@
|
||||||
import { expect, test } from './fixtures/campaignE2EFixtures.js'
|
import { expect, test } from './fixtures/campaignE2EFixtures.js'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* OH9 — dual-path municipality detail. Requires `OPS_HYBRID=1` on the
|
* OH9/OH11 — dual-path municipality detail + full offline journey. Requires
|
||||||
* Playwright webServer (compile-time). Default CI keeps the flag off so
|
* `OPS_HYBRID=1` on the Playwright webServer (compile-time). Default CI keeps
|
||||||
* characterization / municipalities specs continue to pin the RSC path.
|
* the flag off so characterization / municipalities specs continue to pin the
|
||||||
|
* RSC path.
|
||||||
*/
|
*/
|
||||||
const opsHybridEnabled =
|
const opsHybridEnabled =
|
||||||
process.env.OPS_HYBRID === '1' || process.env.OPS_HYBRID?.toLowerCase() === 'true'
|
process.env.OPS_HYBRID === '1' || process.env.OPS_HYBRID?.toLowerCase() === 'true'
|
||||||
|
|
||||||
test.describe('OH9 municipality detail dual-path (OPS_HYBRID)', () => {
|
test.describe('OH9/OH11 campaign ops offline (OPS_HYBRID)', () => {
|
||||||
test.skip(!opsHybridEnabled, 'Set OPS_HYBRID=1 on the e2e webServer to run this dual-path.')
|
test.skip(!opsHybridEnabled, 'Set OPS_HYBRID=1 on the e2e webServer to run this dual-path.')
|
||||||
|
|
||||||
test('offline swaps to Local header + pledges with honest online-only placeholder', async ({
|
test('offline swaps to Local header + pledges with honest online-only placeholder', async ({
|
||||||
|
|
@ -65,4 +66,61 @@ test.describe('OH9 municipality detail dual-path (OPS_HYBRID)', () => {
|
||||||
// Tab nav is RSC-only — Local path must not crash by remounting it.
|
// Tab nav is RSC-only — Local path must not crash by remounting it.
|
||||||
await expect(page.getByRole('link', { name: 'Visão geral' })).toHaveCount(0)
|
await expect(page.getByRole('link', { name: 'Visão geral' })).toHaveCount(0)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('open → sync → offline detail → write → reload → online → sync', async ({
|
||||||
|
campaign,
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
const { fixtures } = campaign
|
||||||
|
const municipality = await fixtures.claimMunicipality()
|
||||||
|
const advisor = await fixtures.createCampaignUser('advisor', {
|
||||||
|
name: fixtures.value('Assessor OH11'),
|
||||||
|
})
|
||||||
|
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 OH11',
|
||||||
|
municipalities: [municipality],
|
||||||
|
supportStatus: 'engajado',
|
||||||
|
})
|
||||||
|
await campaign.payload.create({
|
||||||
|
collection: 'votePledge',
|
||||||
|
data: {
|
||||||
|
leadership: leadershipId,
|
||||||
|
municipality: municipality.id,
|
||||||
|
declaredVotes: 75,
|
||||||
|
},
|
||||||
|
depth: 0,
|
||||||
|
})
|
||||||
|
|
||||||
|
await campaign.login(page, advisor.email!, advisor.password)
|
||||||
|
await page.goto(`${campaign.baseURL}/campanha/municipios/${municipality.slug}`)
|
||||||
|
await expect(page.getByRole('heading', { name: municipality.name })).toBeVisible()
|
||||||
|
|
||||||
|
await page.waitForResponse(
|
||||||
|
(response) =>
|
||||||
|
response.url().includes('/campanha/api/ops-sync') && response.request().method() === 'GET',
|
||||||
|
{ timeout: 30_000 },
|
||||||
|
)
|
||||||
|
|
||||||
|
await page.context().setOffline(true)
|
||||||
|
|
||||||
|
await expect(page.getByRole('heading', { name: municipality.name })).toBeVisible()
|
||||||
|
await page.getByLabel('Média', { exact: true }).fill('42')
|
||||||
|
await page.getByLabel('Justificativa').fill('OH11 offline 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: 42')).toBeVisible({ timeout: 30_000 })
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -42,6 +42,22 @@ describe('campaign PWA helpers', () => {
|
||||||
expect(script).toContain('skipWaiting')
|
expect(script).toContain('skipWaiting')
|
||||||
expect(script).toContain('clients.claim')
|
expect(script).toContain('clients.claim')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('serves /_next/static with cache-first and never caches RSC or invite paths', () => {
|
||||||
|
const script = buildCampaignServiceWorkerScript('sha-test')
|
||||||
|
|
||||||
|
expect(script).toContain('isNextStaticPath')
|
||||||
|
expect(script).toContain("pathname.startsWith('/_next/static/')")
|
||||||
|
|
||||||
|
const staticBranch = script.indexOf('isNextStaticPath(url.pathname)')
|
||||||
|
const rscGuard = script.indexOf('if (isRscRequest(request)) return')
|
||||||
|
const inviteGuard = script.indexOf('if (isInvitePath(url.pathname)) return')
|
||||||
|
|
||||||
|
expect(staticBranch).toBeGreaterThan(-1)
|
||||||
|
expect(rscGuard).toBeGreaterThan(staticBranch)
|
||||||
|
expect(inviteGuard).toBeGreaterThan(-1)
|
||||||
|
expect(inviteGuard).toBeLessThan(staticBranch)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('campaign PWA route handlers', () => {
|
describe('campaign PWA route handlers', () => {
|
||||||
|
|
@ -67,5 +83,6 @@ describe('campaign PWA route handlers', () => {
|
||||||
expect(body).toContain('campanha-')
|
expect(body).toContain('campanha-')
|
||||||
expect(body).toContain(`SCOPE + '/convite'`)
|
expect(body).toContain(`SCOPE + '/convite'`)
|
||||||
expect(body).toContain('isRscRequest')
|
expect(body).toContain('isRscRequest')
|
||||||
|
expect(body).toContain('isNextStaticPath')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue