From 59907172f714a2a1a8d5fd84b48abe210bcf3399 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 1 Aug 2026 22:52:14 +0000 Subject: [PATCH] refactor(OH4): parallel snapshot queries + simplify reuse MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- docs/CHANGELOG-AGENTS.md | 1 + docs/plans/oh4-ops-sync-route.md | 26 +- scripts/benchmark-ops-snapshot.mjs | 26 +- .../(campaign)/campanha/api/ops-sync/route.ts | 7 +- src/lib/campaignOps/opsSnapshotPolicy.ts | 29 +++ src/utilities/campaignOps/buildOpsSnapshot.ts | 237 ++++++++---------- tests/int/campaignOpsSync.int.spec.ts | 52 +--- tests/unit/campaignOps.unit.spec.ts | 43 ++++ 8 files changed, 201 insertions(+), 220 deletions(-) diff --git a/docs/CHANGELOG-AGENTS.md b/docs/CHANGELOG-AGENTS.md index a66008fc..1f257274 100644 --- a/docs/CHANGELOG-AGENTS.md +++ b/docs/CHANGELOG-AGENTS.md @@ -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). diff --git a/docs/plans/oh4-ops-sync-route.md b/docs/plans/oh4-ops-sync-route.md index 9f23cf1e..759e442e 100644 --- a/docs/plans/oh4-ops-sync-route.md +++ b/docs/plans/oh4-ops-sync-route.md @@ -1,6 +1,6 @@ # OH4 — Route `GET /campanha/api/ops-sync` FULL + scoped + int access -Status: em execução +Status: done Atualizado em: 2026-08-01 Issue: #166 Priority: P1 @@ -50,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 @@ -61,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 @@ -72,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 @@ -89,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) diff --git a/scripts/benchmark-ops-snapshot.mjs b/scripts/benchmark-ops-snapshot.mjs index ea1a664d..342650bd 100644 --- a/scripts/benchmark-ops-snapshot.mjs +++ b/scripts/benchmark-ops-snapshot.mjs @@ -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} */ - 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) diff --git a/src/app/(campaign)/campanha/api/ops-sync/route.ts b/src/app/(campaign)/campanha/api/ops-sync/route.ts index ef6d87b5..c5bb58b4 100644 --- a/src/app/(campaign)/campanha/api/ops-sync/route.ts +++ b/src/app/(campaign)/campanha/api/ops-sync/route.ts @@ -1,8 +1,9 @@ import config from '@payload-config' import { getPayload } from 'payload' -import { isCampaignLeader, isCampaignStaff } from '@/utilities/access/shared' +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' @@ -14,10 +15,10 @@ export const dynamic = 'force-dynamic' export async function GET(): Promise { const user = await getCampaignUser() 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 }) } diff --git a/src/lib/campaignOps/opsSnapshotPolicy.ts b/src/lib/campaignOps/opsSnapshotPolicy.ts index ff34914d..ada065bd 100644 --- a/src/lib/campaignOps/opsSnapshotPolicy.ts +++ b/src/lib/campaignOps/opsSnapshotPolicy.ts @@ -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 = ( + updates: TUpdate[], + limitPerMunicipality: number = OPS_MUNICIPALITY_UPDATE_LIMIT_PER_MUNICIPALITY, +): TUpdate[] => { + if (limitPerMunicipality <= 0) return [] + + 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: TUpdate[] = [] + for (const bucket of byMunicipality.values()) { + bucket.sort((left, right) => right.updatedAt.localeCompare(left.updatedAt)) + kept.push(...bucket.slice(0, limitPerMunicipality)) + } + + return kept +} diff --git a/src/utilities/campaignOps/buildOpsSnapshot.ts b/src/utilities/campaignOps/buildOpsSnapshot.ts index eb0335fe..5f93348e 100644 --- a/src/utilities/campaignOps/buildOpsSnapshot.ts +++ b/src/utilities/campaignOps/buildOpsSnapshot.ts @@ -17,12 +17,18 @@ import { type OpsVoteEstimateScenarioFields, type OpsVotePledge, } from '@/lib/campaignOps/opsContract' -import { OPS_MUNICIPALITY_UPDATE_LIMIT_PER_MUNICIPALITY } from '@/lib/campaignOps/opsSnapshotPolicy' -import { relationshipId, uniqueRelationshipIds } from '@/lib/relationship' +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/access/shared' - -type OpsActor = CampaignUser +import { isCampaignStaff } from '@/utilities/campaignAccess' const toIso = (value: unknown): string | 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 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 => { if (typeof value !== 'object' || value === null) return null return value as OpsVoteEstimateScenarioFields } const mapMunicipality = (doc: Record): OpsMunicipality => ({ - id: requireId(doc.id, 'municipality.id'), + id: requireRelationshipId(doc.id, 'Ops snapshot: missing municipality.id'), name: String(doc.name ?? ''), slug: String(doc.slug ?? ''), kind: doc.kind === 'zona' ? 'zona' : 'municipio', @@ -90,18 +90,18 @@ const mapMunicipality = (doc: Record): OpsMunicipality => ({ const mapLeadershipContact = (contact: unknown): OpsLeadershipContact => { 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 return { - id: requireId(doc.id, 'leadership.contact.id'), - name: typeof doc.name === 'string' && doc.name.length > 0 ? doc.name : 'Contato', + 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): OpsLeadership => ({ - id: requireId(doc.id, 'leadership.id'), + id: requireRelationshipId(doc.id, 'Ops snapshot: missing leadership.id'), contact: mapLeadershipContact(doc.contact), municipalities: uniqueRelationshipIds( doc.municipalities as readonly unknown[] | null | undefined, @@ -120,14 +120,17 @@ const mapLeadership = (doc: Record): OpsLeadership => ({ updatedAt: requireIso(doc.updatedAt), }) -const mapVotePledge = ( - doc: Record, - includeEstimates: boolean, -): OpsVotePledge => { +const mapVotePledge = (doc: Record, includeEstimates: boolean): OpsVotePledge => { const base = { - id: requireId(doc.id, 'votePledge.id'), - leadership: requireId(doc.leadership, 'votePledge.leadership'), - municipality: requireId(doc.municipality, 'votePledge.municipality'), + 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), @@ -146,7 +149,7 @@ const mapVotePledge = ( } const mapActivity = (doc: Record): OpsActivity => ({ - id: requireId(doc.id, 'activity.id'), + id: requireRelationshipId(doc.id, 'Ops snapshot: missing activity.id'), title: String(doc.title ?? ''), slug: String(doc.slug ?? ''), kind: doc.kind as OpsActivity['kind'], @@ -154,7 +157,10 @@ const mapActivity = (doc: Record): OpsActivity => ({ deputyPresent: typeof doc.deputyPresent === 'boolean' ? doc.deputyPresent : null, startAt: toIso(doc.startAt), 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, organizations: uniqueRelationshipIds(doc.organizations as readonly unknown[] | null | undefined), advisors: uniqueRelationshipIds(doc.advisors as readonly unknown[] | null | undefined), @@ -165,7 +171,7 @@ const mapActivity = (doc: Record): OpsActivity => ({ }) const mapStateDeputy = (doc: Record): OpsStateDeputy => ({ - id: requireId(doc.id, 'stateDeputy.id'), + 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, @@ -174,7 +180,7 @@ const mapStateDeputy = (doc: Record): OpsStateDeputy => ({ }) const mapOrganization = (doc: Record): OpsOrganization => ({ - id: requireId(doc.id, 'organization.id'), + id: requireRelationshipId(doc.id, 'Ops snapshot: missing organization.id'), name: String(doc.name ?? ''), slug: String(doc.slug ?? ''), kind: doc.kind as OpsOrganization['kind'], @@ -186,11 +192,14 @@ const mapOrganization = (doc: Record): OpsOrganization => ({ }) const mapDemand = (doc: Record): OpsDemand => ({ - id: requireId(doc.id, 'campaignDemand.id'), + id: requireRelationshipId(doc.id, 'Ops snapshot: missing campaignDemand.id'), title: String(doc.title ?? ''), slug: String(doc.slug ?? ''), 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), leadership: relationshipId(doc.leadership), status: doc.status as OpsDemand['status'], @@ -198,9 +207,12 @@ const mapDemand = (doc: Record): OpsDemand => ({ }) const mapMunicipalityUpdate = (doc: Record): OpsMunicipalityUpdate => ({ - id: requireId(doc.id, 'municipalityUpdate.id'), - municipality: requireId(doc.municipality, 'municipalityUpdate.municipality'), - author: requireId(doc.author, 'municipalityUpdate.author'), + 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: @@ -226,33 +238,9 @@ const mapGoals = (doc: Record | 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() - - 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 ( payload: Payload, - actor: OpsActor, + actor: CampaignUser, collection: | 'municipality' | 'leadership' @@ -288,15 +276,41 @@ const findAllDocs = async ( */ export const buildOpsSnapshot = async ( payload: Payload, - actor: OpsActor, + actor: CampaignUser, options: { municipalityUpdateLimit?: number } = {}, ): Promise => { const includeEstimates = isCampaignStaff(actor) const updateLimit = options.municipalityUpdateLimit ?? OPS_MUNICIPALITY_UPDATE_LIMIT_PER_MUNICIPALITY - const municipalities = ( - await findAllDocs(payload, actor, 'municipality', { + const votePledgeSelect: Record = { + 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, @@ -316,11 +330,8 @@ export const buildOpsSnapshot = async ( lastUpdateAt: true, updatedAt: true, }, - }) - ).map(mapMunicipality) - - const leaderships = ( - await findAllDocs(payload, actor, 'leadership', { + }), + findAllDocs(payload, actor, 'leadership', { // Contact name/phone are part of OpsLeadership — single depth:1 exception. depth: 1, select: { @@ -333,31 +344,9 @@ export const buildOpsSnapshot = async ( notes: true, updatedAt: true, }, - }) - ).map(mapLeadership) - - const votePledgeSelect: Record = { - 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', { + }), + findAllDocs(payload, actor, 'votePledge', { select: votePledgeSelect }), + findAllDocs(payload, actor, 'activity', { select: { title: true, slug: true, @@ -375,11 +364,8 @@ export const buildOpsSnapshot = async ( taskDoneCount: true, updatedAt: true, }, - }) - ).map(mapActivity) - - const stateDeputies = ( - await findAllDocs(payload, actor, 'stateDeputy', { + }), + findAllDocs(payload, actor, 'stateDeputy', { select: { name: true, slug: true, @@ -387,11 +373,8 @@ export const buildOpsSnapshot = async ( notes: true, updatedAt: true, }, - }) - ).map(mapStateDeputy) - - const organizations = ( - await findAllDocs(payload, actor, 'organization', { + }), + findAllDocs(payload, actor, 'organization', { select: { name: true, slug: true, @@ -400,11 +383,8 @@ export const buildOpsSnapshot = async ( notes: true, updatedAt: true, }, - }) - ).map(mapOrganization) - - const demands = ( - await findAllDocs(payload, actor, 'campaignDemand', { + }), + findAllDocs(payload, actor, 'campaignDemand', { select: { title: true, slug: true, @@ -415,11 +395,8 @@ export const buildOpsSnapshot = async ( status: true, updatedAt: true, }, - }) - ).map(mapDemand) - - const allUpdates = ( - await findAllDocs(payload, actor, 'municipalityUpdate', { + }), + findAllDocs(payload, actor, 'municipalityUpdate', { select: { municipality: true, author: true, @@ -430,29 +407,29 @@ export const buildOpsSnapshot = async ( createdAt: true, }, sort: '-updatedAt', - }) - ).map(mapMunicipalityUpdate) - const municipalityUpdates = truncateMunicipalityUpdates(allUpdates, updateLimit) - - const goalsDoc = await payload.findGlobal({ - slug: 'campaignGoals', - depth: 0, - user: actor, - overrideAccess: false, - }) - const goals = mapGoals(goalsDoc as unknown as Record) + }), + payload.findGlobal({ + slug: 'campaignGoals', + depth: 0, + user: actor, + overrideAccess: false, + }), + ]) const snapshot = createEmptyOpsSnapshot(new Date().toISOString()) return { ...snapshot, - municipalities, - leaderships, - votePledges, - activities, - stateDeputies, - organizations, - demands, - municipalityUpdates, - goals, + 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), } } diff --git a/tests/int/campaignOpsSync.int.spec.ts b/tests/int/campaignOpsSync.int.spec.ts index a52397b4..b7042258 100644 --- a/tests/int/campaignOpsSync.int.spec.ts +++ b/tests/int/campaignOpsSync.int.spec.ts @@ -4,13 +4,9 @@ import { getPayload, type Payload } from 'payload' import { beforeAll, describe, expect, it, vi } from 'vitest' 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 config from '@/payload.config' -import { - buildOpsSnapshot, - truncateMunicipalityUpdates, -} from '@/utilities/campaignOps/buildOpsSnapshot' +import { buildOpsSnapshot } from '@/utilities/campaignOps/buildOpsSnapshot' 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', () => { beforeAll(async () => { payload = await getPayload({ config: await config }) diff --git a/tests/unit/campaignOps.unit.spec.ts b/tests/unit/campaignOps.unit.spec.ts index 066157d0..5b639223 100644 --- a/tests/unit/campaignOps.unit.spec.ts +++ b/tests/unit/campaignOps.unit.spec.ts @@ -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)