mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-26 21:53:06 +00:00
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:
parent
eb4ed64377
commit
59907172f7
8 changed files with 201 additions and 220 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: 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)
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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<Response> {
|
||||
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 })
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<string, unknown>): 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<string, unknown>): 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<string, unknown>
|
||||
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<string, unknown>): 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<string, unknown>): OpsLeadership => ({
|
|||
updatedAt: requireIso(doc.updatedAt),
|
||||
})
|
||||
|
||||
const mapVotePledge = (
|
||||
doc: Record<string, unknown>,
|
||||
includeEstimates: boolean,
|
||||
): OpsVotePledge => {
|
||||
const mapVotePledge = (doc: Record<string, unknown>, 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<string, unknown>): 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<string, unknown>): 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<string, unknown>): OpsActivity => ({
|
|||
})
|
||||
|
||||
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 ?? ''),
|
||||
slug: String(doc.slug ?? ''),
|
||||
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 => ({
|
||||
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<string, unknown>): OpsOrganization => ({
|
|||
})
|
||||
|
||||
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 ?? ''),
|
||||
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<string, unknown>): OpsDemand => ({
|
|||
})
|
||||
|
||||
const mapMunicipalityUpdate = (doc: Record<string, unknown>): 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<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 (
|
||||
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<OpsSnapshot> => {
|
||||
const includeEstimates = isCampaignStaff(actor)
|
||||
const updateLimit =
|
||||
options.municipalityUpdateLimit ?? OPS_MUNICIPALITY_UPDATE_LIMIT_PER_MUNICIPALITY
|
||||
|
||||
const municipalities = (
|
||||
await findAllDocs(payload, actor, '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,
|
||||
|
|
@ -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<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', {
|
||||
}),
|
||||
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<string, unknown>)
|
||||
}),
|
||||
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<string, unknown>),
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 })
|
||||
|
|
|
|||
|
|
@ -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