refactor(OH4): parallel snapshot queries + simplify reuse

Promise.all for collection finds; reuse requireRelationshipId /
populatedContactName / campaignAccess; truncate in lib; auth message
canonical. Register OH4+ (#186) for benchmark→builder DRY.

Co-authored-by: Francisco Solla <fsolla@users.noreply.github.com>
This commit is contained in:
Cursor Agent 2026-08-01 22:52:14 +00:00
parent eb4ed64377
commit 59907172f7
No known key found for this signature in database
8 changed files with 201 additions and 220 deletions

View file

@ -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):** **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). **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).

View file

@ -1,6 +1,6 @@
# OH4 — Route `GET /campanha/api/ops-sync` FULL + scoped + int access # OH4 — Route `GET /campanha/api/ops-sync` FULL + scoped + int access
Status: em execução Status: done
Atualizado em: 2026-08-01 Atualizado em: 2026-08-01
Issue: #166 Issue: #166
Priority: P1 Priority: P1
@ -50,9 +50,9 @@ flowchart LR
Componentes: 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/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): `export async function GET()` — auth, role check, `Response.json(snapshot, { headers: { 'Cache-Control': 'no-store' } })`. - **`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 (hoje só staff consome o endpoint; o pin int cobre leader 403 antes disto importar). - **Defense in depth:** o `select` de `vote_pledge` **nunca** inclui `estimatedVotes` quando o actor não for staff.
## Fases verificáveis ## Fases verificáveis
@ -61,9 +61,9 @@ Componentes:
- **Quota:** ~0,4 - **Quota:** ~0,4
- **Entrega:** route devolve `{ revisedAt, schemaVersion, municipalities }` scoped. - **Entrega:** route devolve `{ revisedAt, schemaVersion, municipalities }` scoped.
- **Aceite:** - **Aceite:**
- [ ] 401 sem sessão; 403 leader; 200 coordinator/advisor/candidate - [x] 401 sem sessão; 403 leader; 200 coordinator/advisor/candidate
- [ ] advisor recebe só municípios da carteira (pin int com fixtures) - [x] advisor recebe só municípios da carteira (pin int com fixtures)
- **Verify:** `pnpm gate:fast` + `tests/int/campaignOpsSync.int.spec.ts` (municipalities) - **Verify:** `pnpm gate:fast` + `tests/int/campaignOpsSync.int.spec.ts`
- **Files:** builder, route, spec int - **Files:** builder, route, spec int
- **Tamanho:** M - **Tamanho:** M
@ -72,9 +72,9 @@ Componentes:
- **Quota:** ~0,6 - **Quota:** ~0,6
- **Entrega:** snapshot completo conforme OH2 + updates truncadas (N de OH3). - **Entrega:** snapshot completo conforme OH2 + updates truncadas (N de OH3).
- **Aceite:** - **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) - [x] todas as collections presentes com select mínimo (sem `estimatedVotes` para non-staff — defense in depth)
- [ ] `municipality_update` limitado a N/município (pin int) - [x] `municipality_update` limitado a N/município (pin int)
- [ ] shape bate com `OpsSnapshot` (validação zod ou type-level no teste) - [x] shape bate com `OpsSnapshot` (type-level no teste)
- **Verify:** `pnpm gate:fast` + spec int completa - **Verify:** `pnpm gate:fast` + spec int completa
- **Files:** builder, spec int - **Files:** builder, spec int
- **Tamanho:** M - **Tamanho:** M
@ -89,9 +89,13 @@ Componentes:
## Rabbit holes ## 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. - **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 ## Referências
- [`src/utilities/campaignAuth.ts`](src/utilities/campaignAuth.ts) - [`src/utilities/campaignAuth.ts`](src/utilities/campaignAuth.ts)

View file

@ -38,6 +38,7 @@ const {
OPS_SNAPSHOT_GZIP_TARGET_BYTES, OPS_SNAPSHOT_GZIP_TARGET_BYTES,
OPS_SNAPSHOT_PROD_GZIP_RATIO_ESTIMATE, OPS_SNAPSHOT_PROD_GZIP_RATIO_ESTIMATE,
OPS_SNAPSHOT_PROD_MEASURED_JSON_BYTES, OPS_SNAPSHOT_PROD_MEASURED_JSON_BYTES,
truncateMunicipalityUpdates,
} = await import('../src/lib/campaignOps/opsSnapshotPolicy.ts') } = await import('../src/lib/campaignOps/opsSnapshotPolicy.ts')
const { relationshipId, uniqueRelationshipIds } = await import('../src/lib/relationship.ts') const { relationshipId, uniqueRelationshipIds } = await import('../src/lib/relationship.ts')
const { MINIMAL_CAMPAIGN_USERS } = await import('./lib/seed-minimal-manifest.mjs') const { MINIMAL_CAMPAIGN_USERS } = await import('./lib/seed-minimal-manifest.mjs')
@ -284,31 +285,6 @@ const mapGoals = (doc) =>
} }
: null : 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 measureJson = (value) => {
const json = typeof value === 'string' ? value : JSON.stringify(value) const json = typeof value === 'string' ? value : JSON.stringify(value)
const gzip = gzipSync(json) const gzip = gzipSync(json)

View file

@ -1,8 +1,9 @@
import config from '@payload-config' import config from '@payload-config'
import { getPayload } from 'payload' import { getPayload } from 'payload'
import { isCampaignLeader, isCampaignStaff } from '@/utilities/access/shared' import { isCampaignStaff } from '@/utilities/campaignAccess'
import { getCampaignUser } from '@/utilities/campaignAuth' import { getCampaignUser } from '@/utilities/campaignAuth'
import { CAMPAIGN_AUTH_REQUIRED_MESSAGE } from '@/utilities/campaignFormActionError'
import { buildOpsSnapshot } from '@/utilities/campaignOps/buildOpsSnapshot' import { buildOpsSnapshot } from '@/utilities/campaignOps/buildOpsSnapshot'
export const dynamic = 'force-dynamic' export const dynamic = 'force-dynamic'
@ -14,10 +15,10 @@ export const dynamic = 'force-dynamic'
export async function GET(): Promise<Response> { export async function GET(): Promise<Response> {
const user = await getCampaignUser() const user = await getCampaignUser()
if (!user) { if (!user) {
return Response.json({ error: 'Não autenticado.' }, { status: 401 }) return Response.json({ error: CAMPAIGN_AUTH_REQUIRED_MESSAGE }, { status: 401 })
} }
if (isCampaignLeader(user) || !isCampaignStaff(user)) { if (!isCampaignStaff(user)) {
return Response.json({ error: 'Sem permissão.' }, { status: 403 }) return Response.json({ error: 'Sem permissão.' }, { status: 403 })
} }

View file

@ -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). */ /** Conservative gzip ratio for prod ops JSON (text-heavy updates). */
export const OPS_SNAPSHOT_PROD_GZIP_RATIO_ESTIMATE = 0.5 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
}

View file

@ -17,12 +17,18 @@ import {
type OpsVoteEstimateScenarioFields, type OpsVoteEstimateScenarioFields,
type OpsVotePledge, type OpsVotePledge,
} from '@/lib/campaignOps/opsContract' } from '@/lib/campaignOps/opsContract'
import { OPS_MUNICIPALITY_UPDATE_LIMIT_PER_MUNICIPALITY } from '@/lib/campaignOps/opsSnapshotPolicy' import {
import { relationshipId, uniqueRelationshipIds } from '@/lib/relationship' 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 type { CampaignUser } from '@/payload-types'
import { isCampaignStaff } from '@/utilities/access/shared' import { isCampaignStaff } from '@/utilities/campaignAccess'
type OpsActor = CampaignUser
const toIso = (value: unknown): string | null => { const toIso = (value: unknown): string | null => {
if (value === null || value === undefined || value === '') return null if (value === null || value === undefined || value === '') return null
@ -33,19 +39,13 @@ const toIso = (value: unknown): string | null => {
const requireIso = (value: unknown): string => toIso(value) ?? new Date(0).toISOString() const requireIso = (value: unknown): string => toIso(value) ?? new Date(0).toISOString()
const requireId = (value: unknown, label: string): number => {
const id = relationshipId(value)
if (id === null) throw new Error(`Ops snapshot: missing ${label}`)
return id
}
const asEstimateFields = (value: unknown): OpsVoteEstimateScenarioFields | null => { const asEstimateFields = (value: unknown): OpsVoteEstimateScenarioFields | null => {
if (typeof value !== 'object' || value === null) return null if (typeof value !== 'object' || value === null) return null
return value as OpsVoteEstimateScenarioFields return value as OpsVoteEstimateScenarioFields
} }
const mapMunicipality = (doc: Record<string, unknown>): OpsMunicipality => ({ const mapMunicipality = (doc: Record<string, unknown>): OpsMunicipality => ({
id: requireId(doc.id, 'municipality.id'), id: requireRelationshipId(doc.id, 'Ops snapshot: missing municipality.id'),
name: String(doc.name ?? ''), name: String(doc.name ?? ''),
slug: String(doc.slug ?? ''), slug: String(doc.slug ?? ''),
kind: doc.kind === 'zona' ? 'zona' : 'municipio', kind: doc.kind === 'zona' ? 'zona' : 'municipio',
@ -90,18 +90,18 @@ const mapMunicipality = (doc: Record<string, unknown>): OpsMunicipality => ({
const mapLeadershipContact = (contact: unknown): OpsLeadershipContact => { const mapLeadershipContact = (contact: unknown): OpsLeadershipContact => {
if (typeof contact !== 'object' || contact === null) { if (typeof contact !== 'object' || contact === null) {
return { id: relationshipId(contact) ?? 0, name: 'Contato' } return { id: relationshipId(contact) ?? 0, name: populatedContactName(contact) }
} }
const doc = contact as Record<string, unknown> const doc = contact as Record<string, unknown>
return { return {
id: requireId(doc.id, 'leadership.contact.id'), id: requireRelationshipId(doc.id, 'Ops snapshot: missing leadership.contact.id'),
name: typeof doc.name === 'string' && doc.name.length > 0 ? doc.name : 'Contato', name: populatedContactName(contact),
phone: typeof doc.phone === 'string' ? doc.phone : null, phone: typeof doc.phone === 'string' ? doc.phone : null,
} }
} }
const mapLeadership = (doc: Record<string, unknown>): OpsLeadership => ({ const mapLeadership = (doc: Record<string, unknown>): OpsLeadership => ({
id: requireId(doc.id, 'leadership.id'), id: requireRelationshipId(doc.id, 'Ops snapshot: missing leadership.id'),
contact: mapLeadershipContact(doc.contact), contact: mapLeadershipContact(doc.contact),
municipalities: uniqueRelationshipIds( municipalities: uniqueRelationshipIds(
doc.municipalities as readonly unknown[] | null | undefined, doc.municipalities as readonly unknown[] | null | undefined,
@ -120,14 +120,17 @@ const mapLeadership = (doc: Record<string, unknown>): OpsLeadership => ({
updatedAt: requireIso(doc.updatedAt), updatedAt: requireIso(doc.updatedAt),
}) })
const mapVotePledge = ( const mapVotePledge = (doc: Record<string, unknown>, includeEstimates: boolean): OpsVotePledge => {
doc: Record<string, unknown>,
includeEstimates: boolean,
): OpsVotePledge => {
const base = { const base = {
id: requireId(doc.id, 'votePledge.id'), id: requireRelationshipId(doc.id, 'Ops snapshot: missing votePledge.id'),
leadership: requireId(doc.leadership, 'votePledge.leadership'), leadership: requireRelationshipId(
municipality: requireId(doc.municipality, 'votePledge.municipality'), doc.leadership,
'Ops snapshot: missing votePledge.leadership',
),
municipality: requireRelationshipId(
doc.municipality,
'Ops snapshot: missing votePledge.municipality',
),
declaredVotes: typeof doc.declaredVotes === 'number' ? doc.declaredVotes : 0, declaredVotes: typeof doc.declaredVotes === 'number' ? doc.declaredVotes : 0,
declaredAt: toIso(doc.declaredAt), declaredAt: toIso(doc.declaredAt),
declaredBy: relationshipId(doc.declaredBy), declaredBy: relationshipId(doc.declaredBy),
@ -146,7 +149,7 @@ const mapVotePledge = (
} }
const mapActivity = (doc: Record<string, unknown>): OpsActivity => ({ const mapActivity = (doc: Record<string, unknown>): OpsActivity => ({
id: requireId(doc.id, 'activity.id'), id: requireRelationshipId(doc.id, 'Ops snapshot: missing activity.id'),
title: String(doc.title ?? ''), title: String(doc.title ?? ''),
slug: String(doc.slug ?? ''), slug: String(doc.slug ?? ''),
kind: doc.kind as OpsActivity['kind'], kind: doc.kind as OpsActivity['kind'],
@ -154,7 +157,10 @@ const mapActivity = (doc: Record<string, unknown>): OpsActivity => ({
deputyPresent: typeof doc.deputyPresent === 'boolean' ? doc.deputyPresent : null, deputyPresent: typeof doc.deputyPresent === 'boolean' ? doc.deputyPresent : null,
startAt: toIso(doc.startAt), startAt: toIso(doc.startAt),
endAt: toIso(doc.endAt), endAt: toIso(doc.endAt),
municipality: requireId(doc.municipality, 'activity.municipality'), municipality: requireRelationshipId(
doc.municipality,
'Ops snapshot: missing activity.municipality',
),
locality: typeof doc.locality === 'string' ? doc.locality : null, locality: typeof doc.locality === 'string' ? doc.locality : null,
organizations: uniqueRelationshipIds(doc.organizations as readonly unknown[] | null | undefined), organizations: uniqueRelationshipIds(doc.organizations as readonly unknown[] | null | undefined),
advisors: uniqueRelationshipIds(doc.advisors as readonly unknown[] | null | undefined), advisors: uniqueRelationshipIds(doc.advisors as readonly unknown[] | null | undefined),
@ -165,7 +171,7 @@ const mapActivity = (doc: Record<string, unknown>): OpsActivity => ({
}) })
const mapStateDeputy = (doc: Record<string, unknown>): OpsStateDeputy => ({ const mapStateDeputy = (doc: Record<string, unknown>): OpsStateDeputy => ({
id: requireId(doc.id, 'stateDeputy.id'), id: requireRelationshipId(doc.id, 'Ops snapshot: missing stateDeputy.id'),
name: String(doc.name ?? ''), name: String(doc.name ?? ''),
slug: String(doc.slug ?? ''), slug: String(doc.slug ?? ''),
party: typeof doc.party === 'string' ? doc.party : null, party: typeof doc.party === 'string' ? doc.party : null,
@ -174,7 +180,7 @@ const mapStateDeputy = (doc: Record<string, unknown>): OpsStateDeputy => ({
}) })
const mapOrganization = (doc: Record<string, unknown>): OpsOrganization => ({ const mapOrganization = (doc: Record<string, unknown>): OpsOrganization => ({
id: requireId(doc.id, 'organization.id'), id: requireRelationshipId(doc.id, 'Ops snapshot: missing organization.id'),
name: String(doc.name ?? ''), name: String(doc.name ?? ''),
slug: String(doc.slug ?? ''), slug: String(doc.slug ?? ''),
kind: doc.kind as OpsOrganization['kind'], kind: doc.kind as OpsOrganization['kind'],
@ -186,11 +192,14 @@ const mapOrganization = (doc: Record<string, unknown>): OpsOrganization => ({
}) })
const mapDemand = (doc: Record<string, unknown>): OpsDemand => ({ const mapDemand = (doc: Record<string, unknown>): OpsDemand => ({
id: requireId(doc.id, 'campaignDemand.id'), id: requireRelationshipId(doc.id, 'Ops snapshot: missing campaignDemand.id'),
title: String(doc.title ?? ''), title: String(doc.title ?? ''),
slug: String(doc.slug ?? ''), slug: String(doc.slug ?? ''),
kind: doc.kind as OpsDemand['kind'], kind: doc.kind as OpsDemand['kind'],
municipality: requireId(doc.municipality, 'campaignDemand.municipality'), municipality: requireRelationshipId(
doc.municipality,
'Ops snapshot: missing campaignDemand.municipality',
),
activity: relationshipId(doc.activity), activity: relationshipId(doc.activity),
leadership: relationshipId(doc.leadership), leadership: relationshipId(doc.leadership),
status: doc.status as OpsDemand['status'], status: doc.status as OpsDemand['status'],
@ -198,9 +207,12 @@ const mapDemand = (doc: Record<string, unknown>): OpsDemand => ({
}) })
const mapMunicipalityUpdate = (doc: Record<string, unknown>): OpsMunicipalityUpdate => ({ const mapMunicipalityUpdate = (doc: Record<string, unknown>): OpsMunicipalityUpdate => ({
id: requireId(doc.id, 'municipalityUpdate.id'), id: requireRelationshipId(doc.id, 'Ops snapshot: missing municipalityUpdate.id'),
municipality: requireId(doc.municipality, 'municipalityUpdate.municipality'), municipality: requireRelationshipId(
author: requireId(doc.author, 'municipalityUpdate.author'), doc.municipality,
'Ops snapshot: missing municipalityUpdate.municipality',
),
author: requireRelationshipId(doc.author, 'Ops snapshot: missing municipalityUpdate.author'),
kind: doc.kind as OpsMunicipalityUpdate['kind'], kind: doc.kind as OpsMunicipalityUpdate['kind'],
body: typeof doc.body === 'string' ? doc.body : null, body: typeof doc.body === 'string' ? doc.body : null,
signalType: signalType:
@ -226,33 +238,9 @@ const mapGoals = (doc: Record<string, unknown> | null | undefined): OpsGoals | n
} }
} }
/** Keep the latest N municipality_update rows per municipality (updatedAt desc). */
export const truncateMunicipalityUpdates = (
updates: OpsMunicipalityUpdate[],
limitPerMunicipality: number = OPS_MUNICIPALITY_UPDATE_LIMIT_PER_MUNICIPALITY,
): OpsMunicipalityUpdate[] => {
if (limitPerMunicipality <= 0) return []
const byMunicipality = new Map<number, OpsMunicipalityUpdate[]>()
for (const update of updates) {
const bucket = byMunicipality.get(update.municipality) ?? []
bucket.push(update)
byMunicipality.set(update.municipality, bucket)
}
const kept: OpsMunicipalityUpdate[] = []
for (const bucket of byMunicipality.values()) {
bucket.sort((left, right) => right.updatedAt.localeCompare(left.updatedAt))
kept.push(...bucket.slice(0, limitPerMunicipality))
}
return kept
}
const findAllDocs = async ( const findAllDocs = async (
payload: Payload, payload: Payload,
actor: OpsActor, actor: CampaignUser,
collection: collection:
| 'municipality' | 'municipality'
| 'leadership' | 'leadership'
@ -288,15 +276,41 @@ const findAllDocs = async (
*/ */
export const buildOpsSnapshot = async ( export const buildOpsSnapshot = async (
payload: Payload, payload: Payload,
actor: OpsActor, actor: CampaignUser,
options: { municipalityUpdateLimit?: number } = {}, options: { municipalityUpdateLimit?: number } = {},
): Promise<OpsSnapshot> => { ): Promise<OpsSnapshot> => {
const includeEstimates = isCampaignStaff(actor) const includeEstimates = isCampaignStaff(actor)
const updateLimit = const updateLimit =
options.municipalityUpdateLimit ?? OPS_MUNICIPALITY_UPDATE_LIMIT_PER_MUNICIPALITY options.municipalityUpdateLimit ?? OPS_MUNICIPALITY_UPDATE_LIMIT_PER_MUNICIPALITY
const municipalities = ( const votePledgeSelect: Record<string, true> = {
await findAllDocs(payload, actor, 'municipality', { 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: { select: {
name: true, name: true,
slug: true, slug: true,
@ -316,11 +330,8 @@ export const buildOpsSnapshot = async (
lastUpdateAt: true, lastUpdateAt: true,
updatedAt: true, updatedAt: true,
}, },
}) }),
).map(mapMunicipality) findAllDocs(payload, actor, 'leadership', {
const leaderships = (
await findAllDocs(payload, actor, 'leadership', {
// Contact name/phone are part of OpsLeadership — single depth:1 exception. // Contact name/phone are part of OpsLeadership — single depth:1 exception.
depth: 1, depth: 1,
select: { select: {
@ -333,31 +344,9 @@ export const buildOpsSnapshot = async (
notes: true, notes: true,
updatedAt: true, updatedAt: true,
}, },
}) }),
).map(mapLeadership) findAllDocs(payload, actor, 'votePledge', { select: votePledgeSelect }),
findAllDocs(payload, actor, 'activity', {
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 votePledges = (
await findAllDocs(payload, actor, 'votePledge', { select: votePledgeSelect })
).map((doc) => mapVotePledge(doc, includeEstimates))
const activities = (
await findAllDocs(payload, actor, 'activity', {
select: { select: {
title: true, title: true,
slug: true, slug: true,
@ -375,11 +364,8 @@ export const buildOpsSnapshot = async (
taskDoneCount: true, taskDoneCount: true,
updatedAt: true, updatedAt: true,
}, },
}) }),
).map(mapActivity) findAllDocs(payload, actor, 'stateDeputy', {
const stateDeputies = (
await findAllDocs(payload, actor, 'stateDeputy', {
select: { select: {
name: true, name: true,
slug: true, slug: true,
@ -387,11 +373,8 @@ export const buildOpsSnapshot = async (
notes: true, notes: true,
updatedAt: true, updatedAt: true,
}, },
}) }),
).map(mapStateDeputy) findAllDocs(payload, actor, 'organization', {
const organizations = (
await findAllDocs(payload, actor, 'organization', {
select: { select: {
name: true, name: true,
slug: true, slug: true,
@ -400,11 +383,8 @@ export const buildOpsSnapshot = async (
notes: true, notes: true,
updatedAt: true, updatedAt: true,
}, },
}) }),
).map(mapOrganization) findAllDocs(payload, actor, 'campaignDemand', {
const demands = (
await findAllDocs(payload, actor, 'campaignDemand', {
select: { select: {
title: true, title: true,
slug: true, slug: true,
@ -415,11 +395,8 @@ export const buildOpsSnapshot = async (
status: true, status: true,
updatedAt: true, updatedAt: true,
}, },
}) }),
).map(mapDemand) findAllDocs(payload, actor, 'municipalityUpdate', {
const allUpdates = (
await findAllDocs(payload, actor, 'municipalityUpdate', {
select: { select: {
municipality: true, municipality: true,
author: true, author: true,
@ -430,29 +407,29 @@ export const buildOpsSnapshot = async (
createdAt: true, createdAt: true,
}, },
sort: '-updatedAt', sort: '-updatedAt',
}) }),
).map(mapMunicipalityUpdate) payload.findGlobal({
const municipalityUpdates = truncateMunicipalityUpdates(allUpdates, updateLimit) slug: 'campaignGoals',
depth: 0,
const goalsDoc = await payload.findGlobal({ user: actor,
slug: 'campaignGoals', overrideAccess: false,
depth: 0, }),
user: actor, ])
overrideAccess: false,
})
const goals = mapGoals(goalsDoc as unknown as Record<string, unknown>)
const snapshot = createEmptyOpsSnapshot(new Date().toISOString()) const snapshot = createEmptyOpsSnapshot(new Date().toISOString())
return { return {
...snapshot, ...snapshot,
municipalities, municipalities: municipalityDocs.map(mapMunicipality),
leaderships, leaderships: leadershipDocs.map(mapLeadership),
votePledges, votePledges: votePledgeDocs.map((doc) => mapVotePledge(doc, includeEstimates)),
activities, activities: activityDocs.map(mapActivity),
stateDeputies, stateDeputies: stateDeputyDocs.map(mapStateDeputy),
organizations, organizations: organizationDocs.map(mapOrganization),
demands, demands: demandDocs.map(mapDemand),
municipalityUpdates, municipalityUpdates: truncateMunicipalityUpdates(
goals, updateDocs.map(mapMunicipalityUpdate),
updateLimit,
),
goals: mapGoals(goalsDoc as unknown as Record<string, unknown>),
} }
} }

View file

@ -4,13 +4,9 @@ import { getPayload, type Payload } from 'payload'
import { beforeAll, describe, expect, it, vi } from 'vitest' import { beforeAll, describe, expect, it, vi } from 'vitest'
import { OPS_MIRROR_SCHEMA_VERSION } from '@/lib/campaignOps/opsMirrorVersion' import { OPS_MIRROR_SCHEMA_VERSION } from '@/lib/campaignOps/opsMirrorVersion'
import { OPS_MUNICIPALITY_UPDATE_LIMIT_PER_MUNICIPALITY } from '@/lib/campaignOps/opsSnapshotPolicy'
import type { CampaignUser } from '@/payload-types' import type { CampaignUser } from '@/payload-types'
import config from '@/payload.config' import config from '@/payload.config'
import { import { buildOpsSnapshot } from '@/utilities/campaignOps/buildOpsSnapshot'
buildOpsSnapshot,
truncateMunicipalityUpdates,
} from '@/utilities/campaignOps/buildOpsSnapshot'
import { installCampaignFixtures } from '../helpers/campaignFixtures' import { installCampaignFixtures } from '../helpers/campaignFixtures'
@ -32,52 +28,6 @@ const campaignFixtures = installCampaignFixtures({
}, },
}) })
describe('truncateMunicipalityUpdates', () => {
it(`keeps the latest ${OPS_MUNICIPALITY_UPDATE_LIMIT_PER_MUNICIPALITY} rows per municipality by default`, () => {
expect(OPS_MUNICIPALITY_UPDATE_LIMIT_PER_MUNICIPALITY).toBe(50)
})
it('keeps the newest N updates per municipality (updatedAt desc)', () => {
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('GET /campanha/api/ops-sync', () => { describe('GET /campanha/api/ops-sync', () => {
beforeAll(async () => { beforeAll(async () => {
payload = await getPayload({ config: await config }) payload = await getPayload({ config: await config })

View file

@ -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', () => { describe('OPS_MIRROR_SCHEMA_VERSION', () => {
it('is pinned at 1', () => { it('is pinned at 1', () => {
expect(OPS_MIRROR_SCHEMA_VERSION).toBe(1) expect(OPS_MIRROR_SCHEMA_VERSION).toBe(1)