mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-26 21:53:06 +00:00
Merge pull request #188 from fsolla/cursor/pool-i166-e6739edf-00ad
OH4 — Route GET /campanha/api/ops-sync FULL + scoped + int access
This commit is contained in:
commit
56d2469fc3
8 changed files with 738 additions and 38 deletions
|
|
@ -5,6 +5,7 @@ Conteúdo movido do `AGENTS.md` em 2026-07-30 (fatiamento do paradigma de agente
|
|||
---
|
||||
|
||||
**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):** **OH4** (Issue #166) — `GET /campanha/api/ops-sync` full snapshot: `buildOpsSnapshot` (`overrideAccess: false`, queries em paralelo, truncamento 50 updates/município), 401/403 staff gate, pins int advisor/leader. Plano: [`oh4-ops-sync-route.md`](docs/plans/oh4-ops-sync-route.md).
|
||||
|
||||
**Recently resolved (2026-08-01):** **CL5** (Issue #160) — assessores no sistema de listas: `AdvisorsTable` → `CampaignTable` + picker (`assessores` em `CAMPAIGN_LIST_IDS`); `resolveAdvisorListUrl` (canonical + preserva `criar=1`); registry `columnListId`/`canonicalRedirect`; page atrás de `LIST_UNIFIED`/`OpsListPage`. Plano: [`cl5-assessores-factory.md`](docs/plans/cl5-assessores-factory.md).
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# OH4 — Route `GET /campanha/api/ops-sync` FULL + scoped + int access
|
||||
|
||||
Status: rascunho
|
||||
Status: done
|
||||
Atualizado em: 2026-08-01
|
||||
Issue: #166
|
||||
Priority: P1
|
||||
|
|
@ -10,13 +10,21 @@ Appetite: ~1,5–2 dias eng
|
|||
Depends: OH3
|
||||
Responsável: —
|
||||
|
||||
## Freshness audit (2026-08-01)
|
||||
|
||||
- OH3 `#165` `done`/`in-prod`; truncamento = `OPS_MUNICIPALITY_UPDATE_LIMIT_PER_MUNICIPALITY` (**50**) em [`src/lib/campaignOps/opsSnapshotPolicy.ts`](../../src/lib/campaignOps/opsSnapshotPolicy.ts).
|
||||
- DTOs OH2 vivem em [`src/lib/campaignOps/`](../../src/lib/campaignOps/) (client-safe) — o builder é `server-only` em `src/utilities/campaignOps/` (não misturar).
|
||||
- Escopo advisor: `overrideAccess: false` + access modules (já usam `resolveActorScopedRead`); não re-spellar where no builder.
|
||||
- Exceção `depth: 1` só em `leadership` (DTO embute `OpsLeadershipContact`); demais collections `depth: 0`.
|
||||
- Benchmark OH3 ([`scripts/benchmark-ops-snapshot.mjs`](../../scripts/benchmark-ops-snapshot.mjs)) é a referência de selects/mappers — extrair a lógica canônica para o builder.
|
||||
|
||||
## Premissas
|
||||
|
||||
1. Full-only: sem `?since=`, sem delta, sem gzip obrigatório (decisão de compressão fica para OH11 se o benchmark mandar).
|
||||
2. Truncamento de `municipality_update` usa o número travado em OH3.
|
||||
2. Truncamento de `municipality_update` usa o número travado em OH3 (`50`/município).
|
||||
3. Leader recebe 403 (sem mirror de ops).
|
||||
|
||||
→ Corrija agora ou sigo com estas.
|
||||
→ Confirmadas.
|
||||
|
||||
## Objetivos
|
||||
|
||||
|
|
@ -42,9 +50,9 @@ flowchart LR
|
|||
|
||||
Componentes:
|
||||
|
||||
- **`src/utilities/campaignOps/buildOpsSnapshot.ts`** (novo, `import 'server-only'`): uma função por collection. Todas `payload.find` com `user: actor`, `overrideAccess: false`, `depth: 0`, `select` mínimo dos DTOs de OH2 (`opsContract.ts` — campos exactos definidos lá; esta issue importa os tipos, não redefine). Escopo advisor: reusar `resolveActorScopedRead` / `advisorMunicipalityScopeWhere` ([`src/utilities/access/shared.ts`](src/utilities/access/shared.ts)) para o where de municípios e derivados — **não** reimplementar RBAC. Devolve `OpsSnapshot` com `revisedAt` e `schemaVersion`.
|
||||
- **`src/app/(campaign)/campanha/api/ops-sync/route.ts`** (novo): `export async function GET()` — auth, role check, `Response.json(snapshot, { headers: { 'Cache-Control': 'no-store' } })`.
|
||||
- **Defense in depth:** o `select` de `vote_pledge` **nunca** inclui `estimatedVotes` quando o actor não for staff (hoje só staff consome o endpoint; o pin int cobre leader 403 antes disto importar).
|
||||
- **`src/utilities/campaignOps/buildOpsSnapshot.ts`** (novo, `import 'server-only'`): queries em paralelo (`Promise.all`) com `user: actor`, `overrideAccess: false`, `select` mínimo dos DTOs OH2. Escopo via access modules — **não** re-spellar RBAC. Truncamento via `truncateMunicipalityUpdates` (lib). Devolve `OpsSnapshot` com `revisedAt` e `schemaVersion`.
|
||||
- **`src/app/(campaign)/campanha/api/ops-sync/route.ts`** (novo): `GET()` — auth, staff check, `Response.json(snapshot, { headers: { 'Cache-Control': 'no-store' } })`.
|
||||
- **Defense in depth:** o `select` de `vote_pledge` **nunca** inclui `estimatedVotes` quando o actor não for staff.
|
||||
|
||||
## Fases verificáveis
|
||||
|
||||
|
|
@ -53,9 +61,9 @@ Componentes:
|
|||
- **Quota:** ~0,4
|
||||
- **Entrega:** route devolve `{ revisedAt, schemaVersion, municipalities }` scoped.
|
||||
- **Aceite:**
|
||||
- [ ] 401 sem sessão; 403 leader; 200 coordinator/advisor/candidate
|
||||
- [ ] advisor recebe só municípios da carteira (pin int com fixtures)
|
||||
- **Verify:** `pnpm gate:fast` + `tests/int/campaignOpsSync.int.spec.ts` (municipalities)
|
||||
- [x] 401 sem sessão; 403 leader; 200 coordinator/advisor/candidate
|
||||
- [x] advisor recebe só municípios da carteira (pin int com fixtures)
|
||||
- **Verify:** `pnpm gate:fast` + `tests/int/campaignOpsSync.int.spec.ts`
|
||||
- **Files:** builder, route, spec int
|
||||
- **Tamanho:** M
|
||||
|
||||
|
|
@ -64,9 +72,9 @@ Componentes:
|
|||
- **Quota:** ~0,6
|
||||
- **Entrega:** snapshot completo conforme OH2 + updates truncadas (N de OH3).
|
||||
- **Aceite:**
|
||||
- [ ] todas as collections presentes com select mínimo (sem `estimatedVotes` em payload destinado a roles que não devem ver — defense in depth além do client)
|
||||
- [ ] `municipality_update` limitado a N/município (pin int)
|
||||
- [ ] shape bate com `OpsSnapshot` (validação zod ou type-level no teste)
|
||||
- [x] todas as collections presentes com select mínimo (sem `estimatedVotes` para non-staff — defense in depth)
|
||||
- [x] `municipality_update` limitado a N/município (pin int)
|
||||
- [x] shape bate com `OpsSnapshot` (type-level no teste)
|
||||
- **Verify:** `pnpm gate:fast` + spec int completa
|
||||
- **Files:** builder, spec int
|
||||
- **Tamanho:** M
|
||||
|
|
@ -81,9 +89,13 @@ Componentes:
|
|||
|
||||
## Rabbit holes
|
||||
|
||||
- **`depth: 1` “para facilitar joins”.** Explode tamanho e vaza shape para o client. **Mitigação:** IDs + `depth: 0`; joins no client (OH5/OH12).
|
||||
- **`depth: 1` “para facilitar joins”.** Explode tamanho e vaza shape para o client. **Mitigação:** IDs + `depth: 0`; joins no client (OH5/OH12). Exceção documentada: `leadership` depth:1 só para `OpsLeadershipContact`.
|
||||
- **Bypass de access “porque é endpoint interno”.** Invariante do repo. **Mitigação:** pin int de advisor/leader.
|
||||
|
||||
## Débitos pós-simplify (defer)
|
||||
|
||||
- Benchmark OH3 ainda duplica mappers/`toIso` — apontar `scripts/benchmark-ops-snapshot.mjs` a `buildOpsSnapshot` quando o timing por-collection deixar de precisar do pipeline paralelo (gatilho: OH11 sizing / drift). Issue de follow-up com `depends: [OH4]`.
|
||||
|
||||
## Referências
|
||||
|
||||
- [`src/utilities/campaignAuth.ts`](src/utilities/campaignAuth.ts)
|
||||
|
|
|
|||
|
|
@ -38,6 +38,7 @@ const {
|
|||
OPS_SNAPSHOT_GZIP_TARGET_BYTES,
|
||||
OPS_SNAPSHOT_PROD_GZIP_RATIO_ESTIMATE,
|
||||
OPS_SNAPSHOT_PROD_MEASURED_JSON_BYTES,
|
||||
truncateMunicipalityUpdates,
|
||||
} = await import('../src/lib/campaignOps/opsSnapshotPolicy.ts')
|
||||
const { relationshipId, uniqueRelationshipIds } = await import('../src/lib/relationship.ts')
|
||||
const { MINIMAL_CAMPAIGN_USERS } = await import('./lib/seed-minimal-manifest.mjs')
|
||||
|
|
@ -284,31 +285,6 @@ const mapGoals = (doc) =>
|
|||
}
|
||||
: null
|
||||
|
||||
/**
|
||||
* @param {Array<{ municipality: number; updatedAt: string }>} updates
|
||||
* @param {number} limitPerMunicipality
|
||||
*/
|
||||
const truncateMunicipalityUpdates = (updates, limitPerMunicipality) => {
|
||||
if (limitPerMunicipality <= 0) return []
|
||||
|
||||
/** @type {Map<number, typeof updates>} */
|
||||
const byMunicipality = new Map()
|
||||
|
||||
for (const update of updates) {
|
||||
const bucket = byMunicipality.get(update.municipality) ?? []
|
||||
bucket.push(update)
|
||||
byMunicipality.set(update.municipality, bucket)
|
||||
}
|
||||
|
||||
const kept = []
|
||||
for (const bucket of byMunicipality.values()) {
|
||||
bucket.sort((left, right) => right.updatedAt.localeCompare(left.updatedAt))
|
||||
kept.push(...bucket.slice(0, limitPerMunicipality))
|
||||
}
|
||||
|
||||
return kept
|
||||
}
|
||||
|
||||
const measureJson = (value) => {
|
||||
const json = typeof value === 'string' ? value : JSON.stringify(value)
|
||||
const gzip = gzipSync(json)
|
||||
|
|
|
|||
31
src/app/(campaign)/campanha/api/ops-sync/route.ts
Normal file
31
src/app/(campaign)/campanha/api/ops-sync/route.ts
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
import config from '@payload-config'
|
||||
import { getPayload } from 'payload'
|
||||
|
||||
import { isCampaignStaff } from '@/utilities/campaignAccess'
|
||||
import { getCampaignUser } from '@/utilities/campaignAuth'
|
||||
import { CAMPAIGN_AUTH_REQUIRED_MESSAGE } from '@/utilities/campaignFormActionError'
|
||||
import { buildOpsSnapshot } from '@/utilities/campaignOps/buildOpsSnapshot'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
/**
|
||||
* Full staff ops snapshot for the hybrid mirror (OH4). Full-only — no `?since=`.
|
||||
* Outside `(app)` so unauthenticated callers get JSON 401 instead of a login redirect.
|
||||
*/
|
||||
export async function GET(): Promise<Response> {
|
||||
const user = await getCampaignUser()
|
||||
if (!user) {
|
||||
return Response.json({ error: CAMPAIGN_AUTH_REQUIRED_MESSAGE }, { status: 401 })
|
||||
}
|
||||
|
||||
if (!isCampaignStaff(user)) {
|
||||
return Response.json({ error: 'Sem permissão.' }, { status: 403 })
|
||||
}
|
||||
|
||||
const payload = await getPayload({ config })
|
||||
const snapshot = await buildOpsSnapshot(payload, user)
|
||||
|
||||
return Response.json(snapshot, {
|
||||
headers: { 'Cache-Control': 'no-store' },
|
||||
})
|
||||
}
|
||||
|
|
@ -12,3 +12,32 @@ export const OPS_SNAPSHOT_PROD_MEASURED_JSON_BYTES = 4 * 1024 * 1024
|
|||
|
||||
/** Conservative gzip ratio for prod ops JSON (text-heavy updates). */
|
||||
export const OPS_SNAPSHOT_PROD_GZIP_RATIO_ESTIMATE = 0.5
|
||||
|
||||
type TruncatableMunicipalityUpdate = {
|
||||
municipality: number
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
/** Keep the latest N municipality_update rows per municipality (updatedAt desc). */
|
||||
export const truncateMunicipalityUpdates = <TUpdate extends TruncatableMunicipalityUpdate>(
|
||||
updates: TUpdate[],
|
||||
limitPerMunicipality: number = OPS_MUNICIPALITY_UPDATE_LIMIT_PER_MUNICIPALITY,
|
||||
): TUpdate[] => {
|
||||
if (limitPerMunicipality <= 0) return []
|
||||
|
||||
const byMunicipality = new Map<number, TUpdate[]>()
|
||||
|
||||
for (const update of updates) {
|
||||
const bucket = byMunicipality.get(update.municipality) ?? []
|
||||
bucket.push(update)
|
||||
byMunicipality.set(update.municipality, bucket)
|
||||
}
|
||||
|
||||
const kept: TUpdate[] = []
|
||||
for (const bucket of byMunicipality.values()) {
|
||||
bucket.sort((left, right) => right.updatedAt.localeCompare(left.updatedAt))
|
||||
kept.push(...bucket.slice(0, limitPerMunicipality))
|
||||
}
|
||||
|
||||
return kept
|
||||
}
|
||||
|
|
|
|||
435
src/utilities/campaignOps/buildOpsSnapshot.ts
Normal file
435
src/utilities/campaignOps/buildOpsSnapshot.ts
Normal file
|
|
@ -0,0 +1,435 @@
|
|||
import 'server-only'
|
||||
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import {
|
||||
createEmptyOpsSnapshot,
|
||||
type OpsActivity,
|
||||
type OpsDemand,
|
||||
type OpsGoals,
|
||||
type OpsLeadership,
|
||||
type OpsLeadershipContact,
|
||||
type OpsMunicipality,
|
||||
type OpsMunicipalityUpdate,
|
||||
type OpsOrganization,
|
||||
type OpsSnapshot,
|
||||
type OpsStateDeputy,
|
||||
type OpsVoteEstimateScenarioFields,
|
||||
type OpsVotePledge,
|
||||
} from '@/lib/campaignOps/opsContract'
|
||||
import {
|
||||
OPS_MUNICIPALITY_UPDATE_LIMIT_PER_MUNICIPALITY,
|
||||
truncateMunicipalityUpdates,
|
||||
} from '@/lib/campaignOps/opsSnapshotPolicy'
|
||||
import {
|
||||
populatedContactName,
|
||||
relationshipId,
|
||||
requireRelationshipId,
|
||||
uniqueRelationshipIds,
|
||||
} from '@/lib/relationship'
|
||||
import type { CampaignUser } from '@/payload-types'
|
||||
import { isCampaignStaff } from '@/utilities/campaignAccess'
|
||||
|
||||
const toIso = (value: unknown): string | null => {
|
||||
if (value === null || value === undefined || value === '') return null
|
||||
if (typeof value === 'string') return value
|
||||
if (value instanceof Date) return value.toISOString()
|
||||
return String(value)
|
||||
}
|
||||
|
||||
const requireIso = (value: unknown): string => toIso(value) ?? new Date(0).toISOString()
|
||||
|
||||
const asEstimateFields = (value: unknown): OpsVoteEstimateScenarioFields | null => {
|
||||
if (typeof value !== 'object' || value === null) return null
|
||||
return value as OpsVoteEstimateScenarioFields
|
||||
}
|
||||
|
||||
const mapMunicipality = (doc: Record<string, unknown>): OpsMunicipality => ({
|
||||
id: requireRelationshipId(doc.id, 'Ops snapshot: missing municipality.id'),
|
||||
name: String(doc.name ?? ''),
|
||||
slug: String(doc.slug ?? ''),
|
||||
kind: doc.kind === 'zona' ? 'zona' : 'municipio',
|
||||
city: String(doc.city ?? ''),
|
||||
region: String(doc.region ?? ''),
|
||||
ibgeCode: String(doc.ibgeCode ?? ''),
|
||||
zoneNumber: typeof doc.zoneNumber === 'number' ? doc.zoneNumber : null,
|
||||
advisors: uniqueRelationshipIds(doc.advisors as readonly unknown[] | null | undefined),
|
||||
priority: doc.priority === 'alta' || doc.priority === 'normal' ? doc.priority : null,
|
||||
engagementLevel:
|
||||
doc.engagementLevel === 'n0' ||
|
||||
doc.engagementLevel === 'n1' ||
|
||||
doc.engagementLevel === 'n2' ||
|
||||
doc.engagementLevel === 'n3' ||
|
||||
doc.engagementLevel === 'n4'
|
||||
? doc.engagementLevel
|
||||
: null,
|
||||
levelNote: typeof doc.levelNote === 'string' ? doc.levelNote : null,
|
||||
levelChangedAt: toIso(doc.levelChangedAt),
|
||||
expectedVotes: asEstimateFields(doc.expectedVotes),
|
||||
politicalTrend:
|
||||
typeof doc.politicalTrend === 'object' && doc.politicalTrend !== null
|
||||
? (() => {
|
||||
const trend = doc.politicalTrend as Record<string, unknown>
|
||||
return {
|
||||
status:
|
||||
trend.status === 'favoravel' ||
|
||||
trend.status === 'neutra' ||
|
||||
trend.status === 'desfavoravel'
|
||||
? trend.status
|
||||
: null,
|
||||
note: typeof trend.note === 'string' ? trend.note : null,
|
||||
recordedBy: relationshipId(trend.recordedBy),
|
||||
recordedAt: toIso(trend.recordedAt),
|
||||
}
|
||||
})()
|
||||
: null,
|
||||
stateDeputies: uniqueRelationshipIds(doc.stateDeputies as readonly unknown[] | null | undefined),
|
||||
lastUpdateAt: toIso(doc.lastUpdateAt),
|
||||
updatedAt: requireIso(doc.updatedAt),
|
||||
})
|
||||
|
||||
const mapLeadershipContact = (contact: unknown): OpsLeadershipContact => {
|
||||
if (typeof contact !== 'object' || contact === null) {
|
||||
return { id: relationshipId(contact) ?? 0, name: populatedContactName(contact) }
|
||||
}
|
||||
const doc = contact as Record<string, unknown>
|
||||
return {
|
||||
id: requireRelationshipId(doc.id, 'Ops snapshot: missing leadership.contact.id'),
|
||||
name: populatedContactName(contact),
|
||||
phone: typeof doc.phone === 'string' ? doc.phone : null,
|
||||
}
|
||||
}
|
||||
|
||||
const mapLeadership = (doc: Record<string, unknown>): OpsLeadership => ({
|
||||
id: requireRelationshipId(doc.id, 'Ops snapshot: missing leadership.id'),
|
||||
contact: mapLeadershipContact(doc.contact),
|
||||
municipalities: uniqueRelationshipIds(
|
||||
doc.municipalities as readonly unknown[] | null | undefined,
|
||||
),
|
||||
organizations: uniqueRelationshipIds(doc.organizations as readonly unknown[] | null | undefined),
|
||||
stateDeputies: uniqueRelationshipIds(doc.stateDeputies as readonly unknown[] | null | undefined),
|
||||
exclusive: typeof doc.exclusive === 'boolean' ? doc.exclusive : null,
|
||||
supportStatus:
|
||||
doc.supportStatus === 'engajado' ||
|
||||
doc.supportStatus === 'a_abordar' ||
|
||||
doc.supportStatus === 'em_disputa' ||
|
||||
doc.supportStatus === 'negativo'
|
||||
? doc.supportStatus
|
||||
: 'a_abordar',
|
||||
notes: typeof doc.notes === 'string' ? doc.notes : null,
|
||||
updatedAt: requireIso(doc.updatedAt),
|
||||
})
|
||||
|
||||
const mapVotePledge = (doc: Record<string, unknown>, includeEstimates: boolean): OpsVotePledge => {
|
||||
const base = {
|
||||
id: requireRelationshipId(doc.id, 'Ops snapshot: missing votePledge.id'),
|
||||
leadership: requireRelationshipId(
|
||||
doc.leadership,
|
||||
'Ops snapshot: missing votePledge.leadership',
|
||||
),
|
||||
municipality: requireRelationshipId(
|
||||
doc.municipality,
|
||||
'Ops snapshot: missing votePledge.municipality',
|
||||
),
|
||||
declaredVotes: typeof doc.declaredVotes === 'number' ? doc.declaredVotes : 0,
|
||||
declaredAt: toIso(doc.declaredAt),
|
||||
declaredBy: relationshipId(doc.declaredBy),
|
||||
updatedAt: requireIso(doc.updatedAt),
|
||||
}
|
||||
|
||||
if (!includeEstimates) return base
|
||||
|
||||
return {
|
||||
...base,
|
||||
estimatedVotes: asEstimateFields(doc.estimatedVotes),
|
||||
estimateNote: typeof doc.estimateNote === 'string' ? doc.estimateNote : null,
|
||||
estimatedBy: relationshipId(doc.estimatedBy),
|
||||
estimatedAt: toIso(doc.estimatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
const mapActivity = (doc: Record<string, unknown>): OpsActivity => ({
|
||||
id: requireRelationshipId(doc.id, 'Ops snapshot: missing activity.id'),
|
||||
title: String(doc.title ?? ''),
|
||||
slug: String(doc.slug ?? ''),
|
||||
kind: doc.kind as OpsActivity['kind'],
|
||||
status: doc.status as OpsActivity['status'],
|
||||
deputyPresent: typeof doc.deputyPresent === 'boolean' ? doc.deputyPresent : null,
|
||||
startAt: toIso(doc.startAt),
|
||||
endAt: toIso(doc.endAt),
|
||||
municipality: requireRelationshipId(
|
||||
doc.municipality,
|
||||
'Ops snapshot: missing activity.municipality',
|
||||
),
|
||||
locality: typeof doc.locality === 'string' ? doc.locality : null,
|
||||
organizations: uniqueRelationshipIds(doc.organizations as readonly unknown[] | null | undefined),
|
||||
advisors: uniqueRelationshipIds(doc.advisors as readonly unknown[] | null | undefined),
|
||||
leadership: relationshipId(doc.leadership),
|
||||
taskTotal: typeof doc.taskTotal === 'number' ? doc.taskTotal : null,
|
||||
taskDoneCount: typeof doc.taskDoneCount === 'number' ? doc.taskDoneCount : null,
|
||||
updatedAt: requireIso(doc.updatedAt),
|
||||
})
|
||||
|
||||
const mapStateDeputy = (doc: Record<string, unknown>): OpsStateDeputy => ({
|
||||
id: requireRelationshipId(doc.id, 'Ops snapshot: missing stateDeputy.id'),
|
||||
name: String(doc.name ?? ''),
|
||||
slug: String(doc.slug ?? ''),
|
||||
party: typeof doc.party === 'string' ? doc.party : null,
|
||||
notes: typeof doc.notes === 'string' ? doc.notes : null,
|
||||
updatedAt: requireIso(doc.updatedAt),
|
||||
})
|
||||
|
||||
const mapOrganization = (doc: Record<string, unknown>): OpsOrganization => ({
|
||||
id: requireRelationshipId(doc.id, 'Ops snapshot: missing organization.id'),
|
||||
name: String(doc.name ?? ''),
|
||||
slug: String(doc.slug ?? ''),
|
||||
kind: doc.kind as OpsOrganization['kind'],
|
||||
municipalities: uniqueRelationshipIds(
|
||||
doc.municipalities as readonly unknown[] | null | undefined,
|
||||
),
|
||||
notes: typeof doc.notes === 'string' ? doc.notes : null,
|
||||
updatedAt: requireIso(doc.updatedAt),
|
||||
})
|
||||
|
||||
const mapDemand = (doc: Record<string, unknown>): OpsDemand => ({
|
||||
id: requireRelationshipId(doc.id, 'Ops snapshot: missing campaignDemand.id'),
|
||||
title: String(doc.title ?? ''),
|
||||
slug: String(doc.slug ?? ''),
|
||||
kind: doc.kind as OpsDemand['kind'],
|
||||
municipality: requireRelationshipId(
|
||||
doc.municipality,
|
||||
'Ops snapshot: missing campaignDemand.municipality',
|
||||
),
|
||||
activity: relationshipId(doc.activity),
|
||||
leadership: relationshipId(doc.leadership),
|
||||
status: doc.status as OpsDemand['status'],
|
||||
updatedAt: requireIso(doc.updatedAt),
|
||||
})
|
||||
|
||||
const mapMunicipalityUpdate = (doc: Record<string, unknown>): OpsMunicipalityUpdate => ({
|
||||
id: requireRelationshipId(doc.id, 'Ops snapshot: missing municipalityUpdate.id'),
|
||||
municipality: requireRelationshipId(
|
||||
doc.municipality,
|
||||
'Ops snapshot: missing municipalityUpdate.municipality',
|
||||
),
|
||||
author: requireRelationshipId(doc.author, 'Ops snapshot: missing municipalityUpdate.author'),
|
||||
kind: doc.kind as OpsMunicipalityUpdate['kind'],
|
||||
body: typeof doc.body === 'string' ? doc.body : null,
|
||||
signalType:
|
||||
doc.signalType === 'invasao' ||
|
||||
doc.signalType === 'esfriamento' ||
|
||||
doc.signalType === 'visita_adversario' ||
|
||||
doc.signalType === 'proposta_broker' ||
|
||||
doc.signalType === 'outro'
|
||||
? doc.signalType
|
||||
: null,
|
||||
updatedAt: requireIso(doc.updatedAt),
|
||||
createdAt: requireIso(doc.createdAt),
|
||||
})
|
||||
|
||||
const mapGoals = (doc: Record<string, unknown> | null | undefined): OpsGoals | null => {
|
||||
if (!doc) return null
|
||||
return {
|
||||
stateGoal: typeof doc.stateGoal === 'number' ? doc.stateGoal : 0,
|
||||
margin: typeof doc.margin === 'number' ? doc.margin : null,
|
||||
baseYear: typeof doc.baseYear === 'number' ? doc.baseYear : null,
|
||||
note: typeof doc.note === 'string' ? doc.note : null,
|
||||
updatedAt: toIso(doc.updatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
const findAllDocs = async (
|
||||
payload: Payload,
|
||||
actor: CampaignUser,
|
||||
collection:
|
||||
| 'municipality'
|
||||
| 'leadership'
|
||||
| 'votePledge'
|
||||
| 'activity'
|
||||
| 'stateDeputy'
|
||||
| 'organization'
|
||||
| 'campaignDemand'
|
||||
| 'municipalityUpdate',
|
||||
options: {
|
||||
depth?: 0 | 1
|
||||
select: Record<string, true>
|
||||
sort?: string
|
||||
},
|
||||
): Promise<Array<Record<string, unknown>>> => {
|
||||
const result = await payload.find({
|
||||
collection,
|
||||
depth: options.depth ?? 0,
|
||||
pagination: false,
|
||||
user: actor,
|
||||
overrideAccess: false,
|
||||
select: options.select,
|
||||
...(options.sort ? { sort: options.sort } : {}),
|
||||
})
|
||||
|
||||
return result.docs as unknown as Array<Record<string, unknown>>
|
||||
}
|
||||
|
||||
/**
|
||||
* Staff ops snapshot for the hybrid mirror (OH4). Every query runs with
|
||||
* `user: actor` + `overrideAccess: false` so collection access (advisor
|
||||
* portfolio, leader deny) is the scoping authority — never bypassed.
|
||||
*/
|
||||
export const buildOpsSnapshot = async (
|
||||
payload: Payload,
|
||||
actor: CampaignUser,
|
||||
options: { municipalityUpdateLimit?: number } = {},
|
||||
): Promise<OpsSnapshot> => {
|
||||
const includeEstimates = isCampaignStaff(actor)
|
||||
const updateLimit =
|
||||
options.municipalityUpdateLimit ?? OPS_MUNICIPALITY_UPDATE_LIMIT_PER_MUNICIPALITY
|
||||
|
||||
const votePledgeSelect: Record<string, true> = {
|
||||
leadership: true,
|
||||
municipality: true,
|
||||
declaredVotes: true,
|
||||
declaredAt: true,
|
||||
declaredBy: true,
|
||||
updatedAt: true,
|
||||
}
|
||||
// Defense in depth: never select staff-only estimate fields for non-staff.
|
||||
if (includeEstimates) {
|
||||
votePledgeSelect.estimatedVotes = true
|
||||
votePledgeSelect.estimateNote = true
|
||||
votePledgeSelect.estimatedBy = true
|
||||
votePledgeSelect.estimatedAt = true
|
||||
}
|
||||
|
||||
const [
|
||||
municipalityDocs,
|
||||
leadershipDocs,
|
||||
votePledgeDocs,
|
||||
activityDocs,
|
||||
stateDeputyDocs,
|
||||
organizationDocs,
|
||||
demandDocs,
|
||||
updateDocs,
|
||||
goalsDoc,
|
||||
] = await Promise.all([
|
||||
findAllDocs(payload, actor, 'municipality', {
|
||||
select: {
|
||||
name: true,
|
||||
slug: true,
|
||||
kind: true,
|
||||
city: true,
|
||||
region: true,
|
||||
ibgeCode: true,
|
||||
zoneNumber: true,
|
||||
advisors: true,
|
||||
priority: true,
|
||||
engagementLevel: true,
|
||||
levelNote: true,
|
||||
levelChangedAt: true,
|
||||
expectedVotes: true,
|
||||
politicalTrend: true,
|
||||
stateDeputies: true,
|
||||
lastUpdateAt: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
}),
|
||||
findAllDocs(payload, actor, 'leadership', {
|
||||
// Contact name/phone are part of OpsLeadership — single depth:1 exception.
|
||||
depth: 1,
|
||||
select: {
|
||||
contact: true,
|
||||
municipalities: true,
|
||||
organizations: true,
|
||||
stateDeputies: true,
|
||||
exclusive: true,
|
||||
supportStatus: true,
|
||||
notes: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
}),
|
||||
findAllDocs(payload, actor, 'votePledge', { select: votePledgeSelect }),
|
||||
findAllDocs(payload, actor, 'activity', {
|
||||
select: {
|
||||
title: true,
|
||||
slug: true,
|
||||
kind: true,
|
||||
status: true,
|
||||
deputyPresent: true,
|
||||
startAt: true,
|
||||
endAt: true,
|
||||
municipality: true,
|
||||
locality: true,
|
||||
organizations: true,
|
||||
advisors: true,
|
||||
leadership: true,
|
||||
taskTotal: true,
|
||||
taskDoneCount: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
}),
|
||||
findAllDocs(payload, actor, 'stateDeputy', {
|
||||
select: {
|
||||
name: true,
|
||||
slug: true,
|
||||
party: true,
|
||||
notes: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
}),
|
||||
findAllDocs(payload, actor, 'organization', {
|
||||
select: {
|
||||
name: true,
|
||||
slug: true,
|
||||
kind: true,
|
||||
municipalities: true,
|
||||
notes: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
}),
|
||||
findAllDocs(payload, actor, 'campaignDemand', {
|
||||
select: {
|
||||
title: true,
|
||||
slug: true,
|
||||
kind: true,
|
||||
municipality: true,
|
||||
activity: true,
|
||||
leadership: true,
|
||||
status: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
}),
|
||||
findAllDocs(payload, actor, 'municipalityUpdate', {
|
||||
select: {
|
||||
municipality: true,
|
||||
author: true,
|
||||
kind: true,
|
||||
body: true,
|
||||
signalType: true,
|
||||
updatedAt: true,
|
||||
createdAt: true,
|
||||
},
|
||||
sort: '-updatedAt',
|
||||
}),
|
||||
payload.findGlobal({
|
||||
slug: 'campaignGoals',
|
||||
depth: 0,
|
||||
user: actor,
|
||||
overrideAccess: false,
|
||||
}),
|
||||
])
|
||||
|
||||
const snapshot = createEmptyOpsSnapshot(new Date().toISOString())
|
||||
return {
|
||||
...snapshot,
|
||||
municipalities: municipalityDocs.map(mapMunicipality),
|
||||
leaderships: leadershipDocs.map(mapLeadership),
|
||||
votePledges: votePledgeDocs.map((doc) => mapVotePledge(doc, includeEstimates)),
|
||||
activities: activityDocs.map(mapActivity),
|
||||
stateDeputies: stateDeputyDocs.map(mapStateDeputy),
|
||||
organizations: organizationDocs.map(mapOrganization),
|
||||
demands: demandDocs.map(mapDemand),
|
||||
municipalityUpdates: truncateMunicipalityUpdates(
|
||||
updateDocs.map(mapMunicipalityUpdate),
|
||||
updateLimit,
|
||||
),
|
||||
goals: mapGoals(goalsDoc as unknown as Record<string, unknown>),
|
||||
}
|
||||
}
|
||||
173
tests/int/campaignOpsSync.int.spec.ts
Normal file
173
tests/int/campaignOpsSync.int.spec.ts
Normal file
|
|
@ -0,0 +1,173 @@
|
|||
// @vitest-environment node
|
||||
|
||||
import { getPayload, type Payload } from 'payload'
|
||||
import { beforeAll, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { OPS_MIRROR_SCHEMA_VERSION } from '@/lib/campaignOps/opsMirrorVersion'
|
||||
import type { CampaignUser } from '@/payload-types'
|
||||
import config from '@/payload.config'
|
||||
import { buildOpsSnapshot } from '@/utilities/campaignOps/buildOpsSnapshot'
|
||||
|
||||
import { installCampaignFixtures } from '../helpers/campaignFixtures'
|
||||
|
||||
const authState = vi.hoisted(() => ({
|
||||
user: null as CampaignUser | null,
|
||||
}))
|
||||
|
||||
vi.mock('@/utilities/campaignAuth', () => ({
|
||||
getCampaignUser: async () => authState.user,
|
||||
}))
|
||||
|
||||
import { GET as getOpsSync } from '@/app/(campaign)/campanha/api/ops-sync/route'
|
||||
|
||||
let payload: Payload
|
||||
const campaignFixtures = installCampaignFixtures({
|
||||
getPayload: () => payload,
|
||||
setPayload: (nextPayload) => {
|
||||
payload = nextPayload
|
||||
},
|
||||
})
|
||||
|
||||
describe('GET /campanha/api/ops-sync', () => {
|
||||
beforeAll(async () => {
|
||||
payload = await getPayload({ config: await config })
|
||||
})
|
||||
|
||||
it('returns 401 without a session', async () => {
|
||||
authState.user = null
|
||||
const response = await getOpsSync()
|
||||
expect(response.status).toBe(401)
|
||||
expect(response.headers.get('Cache-Control')).toBeNull()
|
||||
})
|
||||
|
||||
it('returns 403 for a leader', async () => {
|
||||
const fixtures = campaignFixtures()
|
||||
const leader = await fixtures.createCampaignUser('leader')
|
||||
authState.user = leader
|
||||
|
||||
const response = await getOpsSync()
|
||||
expect(response.status).toBe(403)
|
||||
})
|
||||
|
||||
it.each(['coordinator', 'candidate', 'advisor'] as const)(
|
||||
'returns 200 with no-store for a %s',
|
||||
async (role) => {
|
||||
const fixtures = campaignFixtures()
|
||||
const actor = await fixtures.createCampaignUser(role)
|
||||
if (role === 'advisor') {
|
||||
const municipality = await fixtures.getMunicipality()
|
||||
await fixtures.assignMunicipalityAdvisors(municipality, [actor])
|
||||
}
|
||||
authState.user = actor
|
||||
|
||||
const response = await getOpsSync()
|
||||
expect(response.status).toBe(200)
|
||||
expect(response.headers.get('Cache-Control')).toBe('no-store')
|
||||
|
||||
const body = (await response.json()) as Awaited<ReturnType<typeof buildOpsSnapshot>>
|
||||
expect(body.schemaVersion).toBe(OPS_MIRROR_SCHEMA_VERSION)
|
||||
expect(typeof body.revisedAt).toBe('string')
|
||||
expect(Array.isArray(body.municipalities)).toBe(true)
|
||||
expect(Array.isArray(body.leaderships)).toBe(true)
|
||||
expect(Array.isArray(body.votePledges)).toBe(true)
|
||||
expect(Array.isArray(body.activities)).toBe(true)
|
||||
expect(Array.isArray(body.stateDeputies)).toBe(true)
|
||||
expect(Array.isArray(body.organizations)).toBe(true)
|
||||
expect(Array.isArray(body.demands)).toBe(true)
|
||||
expect(Array.isArray(body.municipalityUpdates)).toBe(true)
|
||||
expect(body.goals === null || typeof body.goals.stateGoal === 'number').toBe(true)
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
describe('buildOpsSnapshot access scope', () => {
|
||||
beforeAll(async () => {
|
||||
payload = await getPayload({ config: await config })
|
||||
})
|
||||
|
||||
it('scopes an advisor to the municipality portfolio', async () => {
|
||||
const fixtures = campaignFixtures()
|
||||
const advisor = await fixtures.createCampaignUser('advisor')
|
||||
const inPortfolio = await fixtures.getMunicipality()
|
||||
const outOfPortfolio = await fixtures.getMunicipality()
|
||||
await fixtures.assignMunicipalityAdvisors(inPortfolio, [advisor])
|
||||
|
||||
const contact = await fixtures.createContact()
|
||||
const leadership = await fixtures.createLeadership({
|
||||
contact,
|
||||
municipalities: [inPortfolio, outOfPortfolio],
|
||||
})
|
||||
await fixtures.createVotePledge({
|
||||
leadership,
|
||||
municipality: inPortfolio,
|
||||
declaredVotes: 40,
|
||||
estimatedVotes: { pessimistic: 30, central: 40, optimistic: 50 },
|
||||
})
|
||||
await fixtures.createVotePledge({
|
||||
leadership,
|
||||
municipality: outOfPortfolio,
|
||||
declaredVotes: 90,
|
||||
estimatedVotes: { pessimistic: 80, central: 90, optimistic: 100 },
|
||||
})
|
||||
await fixtures.createMunicipalityUpdate({
|
||||
municipality: inPortfolio,
|
||||
author: advisor,
|
||||
body: fixtures.value('update-in'),
|
||||
})
|
||||
await fixtures.createMunicipalityUpdate({
|
||||
municipality: outOfPortfolio,
|
||||
author: advisor,
|
||||
body: fixtures.value('update-out'),
|
||||
})
|
||||
|
||||
const snapshot = await buildOpsSnapshot(payload, advisor)
|
||||
|
||||
expect(snapshot.municipalities.map((row) => row.id)).toEqual([inPortfolio.id])
|
||||
expect(snapshot.votePledges.map((row) => row.municipality)).toEqual([inPortfolio.id])
|
||||
expect(snapshot.municipalityUpdates.map((row) => row.municipality)).toEqual([inPortfolio.id])
|
||||
expect(snapshot.votePledges[0]?.estimatedVotes?.central).toBe(40)
|
||||
})
|
||||
|
||||
it('lets a coordinator see municipalities beyond a single advisor portfolio', async () => {
|
||||
const fixtures = campaignFixtures()
|
||||
const coordinator = await fixtures.createCampaignUser('coordinator')
|
||||
const advisor = await fixtures.createCampaignUser('advisor')
|
||||
const inPortfolio = await fixtures.getMunicipality()
|
||||
const outOfPortfolio = await fixtures.getMunicipality()
|
||||
await fixtures.assignMunicipalityAdvisors(inPortfolio, [advisor])
|
||||
|
||||
const advisorSnapshot = await buildOpsSnapshot(payload, advisor)
|
||||
const coordinatorSnapshot = await buildOpsSnapshot(payload, coordinator)
|
||||
|
||||
expect(advisorSnapshot.municipalities.map((row) => row.id)).toEqual([inPortfolio.id])
|
||||
expect(coordinatorSnapshot.municipalities.some((row) => row.id === inPortfolio.id)).toBe(true)
|
||||
expect(coordinatorSnapshot.municipalities.some((row) => row.id === outOfPortfolio.id)).toBe(
|
||||
true,
|
||||
)
|
||||
expect(coordinatorSnapshot.municipalities.length).toBeGreaterThan(
|
||||
advisorSnapshot.municipalities.length,
|
||||
)
|
||||
})
|
||||
|
||||
it('truncates municipality_update to the OH3 per-municipality limit', async () => {
|
||||
const fixtures = campaignFixtures()
|
||||
const coordinator = await fixtures.createCampaignUser('coordinator')
|
||||
const municipality = await fixtures.getMunicipality()
|
||||
|
||||
for (let index = 0; index < 5; index += 1) {
|
||||
await fixtures.createMunicipalityUpdate({
|
||||
municipality,
|
||||
author: coordinator,
|
||||
body: fixtures.value(`upd-${index}`),
|
||||
})
|
||||
}
|
||||
|
||||
const snapshot = await buildOpsSnapshot(payload, coordinator, {
|
||||
municipalityUpdateLimit: 2,
|
||||
})
|
||||
const forMunicipality = snapshot.municipalityUpdates.filter(
|
||||
(row) => row.municipality === municipality.id,
|
||||
)
|
||||
expect(forMunicipality).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
|
|
@ -59,6 +59,49 @@ describe('opsSnapshotPolicy', () => {
|
|||
})
|
||||
})
|
||||
|
||||
describe('truncateMunicipalityUpdates', () => {
|
||||
it('keeps the newest N updates per municipality (updatedAt desc)', async () => {
|
||||
const { truncateMunicipalityUpdates } = await import('@/lib/campaignOps/opsSnapshotPolicy')
|
||||
const updates = [
|
||||
{
|
||||
id: 1,
|
||||
municipality: 10,
|
||||
author: 1,
|
||||
kind: 'nota' as const,
|
||||
updatedAt: '2026-08-01T10:00:00.000Z',
|
||||
createdAt: '2026-08-01T10:00:00.000Z',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
municipality: 10,
|
||||
author: 1,
|
||||
kind: 'nota' as const,
|
||||
updatedAt: '2026-08-01T12:00:00.000Z',
|
||||
createdAt: '2026-08-01T12:00:00.000Z',
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
municipality: 10,
|
||||
author: 1,
|
||||
kind: 'nota' as const,
|
||||
updatedAt: '2026-08-01T11:00:00.000Z',
|
||||
createdAt: '2026-08-01T11:00:00.000Z',
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
municipality: 20,
|
||||
author: 1,
|
||||
kind: 'nota' as const,
|
||||
updatedAt: '2026-08-01T09:00:00.000Z',
|
||||
createdAt: '2026-08-01T09:00:00.000Z',
|
||||
},
|
||||
]
|
||||
|
||||
const truncated = truncateMunicipalityUpdates(updates, 2)
|
||||
expect(truncated.map((row) => row.id).sort()).toEqual([2, 3, 4])
|
||||
})
|
||||
})
|
||||
|
||||
describe('OPS_MIRROR_SCHEMA_VERSION', () => {
|
||||
it('is pinned at 1', () => {
|
||||
expect(OPS_MIRROR_SCHEMA_VERSION).toBe(1)
|
||||
|
|
|
|||
Loading…
Reference in a new issue