mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-29 17:43:05 +00:00
feat(OH4): GET /campanha/api/ops-sync full snapshot + scoped access
Add buildOpsSnapshot (server-only) with overrideAccess:false queries, municipality_update truncation (OH3 N=50), and int pins for 401/403/200 + advisor portfolio + truncation. Co-authored-by: Francisco Solla <fsolla@users.noreply.github.com>
This commit is contained in:
parent
f9128f92b8
commit
eb4ed64377
4 changed files with 722 additions and 3 deletions
|
|
@ -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: rascunho
|
Status: em execução
|
||||||
Atualizado em: 2026-08-01
|
Atualizado em: 2026-08-01
|
||||||
Issue: #166
|
Issue: #166
|
||||||
Priority: P1
|
Priority: P1
|
||||||
|
|
@ -10,13 +10,21 @@ Appetite: ~1,5–2 dias eng
|
||||||
Depends: OH3
|
Depends: OH3
|
||||||
Responsável: —
|
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
|
## Premissas
|
||||||
|
|
||||||
1. Full-only: sem `?since=`, sem delta, sem gzip obrigatório (decisão de compressão fica para OH11 se o benchmark mandar).
|
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).
|
3. Leader recebe 403 (sem mirror de ops).
|
||||||
|
|
||||||
→ Corrija agora ou sigo com estas.
|
→ Confirmadas.
|
||||||
|
|
||||||
## Objetivos
|
## Objetivos
|
||||||
|
|
||||||
|
|
|
||||||
30
src/app/(campaign)/campanha/api/ops-sync/route.ts
Normal file
30
src/app/(campaign)/campanha/api/ops-sync/route.ts
Normal file
|
|
@ -0,0 +1,30 @@
|
||||||
|
import config from '@payload-config'
|
||||||
|
import { getPayload } from 'payload'
|
||||||
|
|
||||||
|
import { isCampaignLeader, isCampaignStaff } from '@/utilities/access/shared'
|
||||||
|
import { getCampaignUser } from '@/utilities/campaignAuth'
|
||||||
|
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: 'Não autenticado.' }, { status: 401 })
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isCampaignLeader(user) || !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' },
|
||||||
|
})
|
||||||
|
}
|
||||||
458
src/utilities/campaignOps/buildOpsSnapshot.ts
Normal file
458
src/utilities/campaignOps/buildOpsSnapshot.ts
Normal file
|
|
@ -0,0 +1,458 @@
|
||||||
|
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 } from '@/lib/campaignOps/opsSnapshotPolicy'
|
||||||
|
import { relationshipId, uniqueRelationshipIds } from '@/lib/relationship'
|
||||||
|
import type { CampaignUser } from '@/payload-types'
|
||||||
|
import { isCampaignStaff } from '@/utilities/access/shared'
|
||||||
|
|
||||||
|
type OpsActor = CampaignUser
|
||||||
|
|
||||||
|
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 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'),
|
||||||
|
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: 'Contato' }
|
||||||
|
}
|
||||||
|
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',
|
||||||
|
phone: typeof doc.phone === 'string' ? doc.phone : null,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const mapLeadership = (doc: Record<string, unknown>): OpsLeadership => ({
|
||||||
|
id: requireId(doc.id, '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: requireId(doc.id, 'votePledge.id'),
|
||||||
|
leadership: requireId(doc.leadership, 'votePledge.leadership'),
|
||||||
|
municipality: requireId(doc.municipality, '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: requireId(doc.id, '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: requireId(doc.municipality, '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: requireId(doc.id, '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: requireId(doc.id, '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: requireId(doc.id, 'campaignDemand.id'),
|
||||||
|
title: String(doc.title ?? ''),
|
||||||
|
slug: String(doc.slug ?? ''),
|
||||||
|
kind: doc.kind as OpsDemand['kind'],
|
||||||
|
municipality: requireId(doc.municipality, '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: requireId(doc.id, 'municipalityUpdate.id'),
|
||||||
|
municipality: requireId(doc.municipality, 'municipalityUpdate.municipality'),
|
||||||
|
author: requireId(doc.author, '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),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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,
|
||||||
|
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: OpsActor,
|
||||||
|
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', {
|
||||||
|
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,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
).map(mapMunicipality)
|
||||||
|
|
||||||
|
const leaderships = (
|
||||||
|
await 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,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
).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', {
|
||||||
|
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,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
).map(mapActivity)
|
||||||
|
|
||||||
|
const stateDeputies = (
|
||||||
|
await findAllDocs(payload, actor, 'stateDeputy', {
|
||||||
|
select: {
|
||||||
|
name: true,
|
||||||
|
slug: true,
|
||||||
|
party: true,
|
||||||
|
notes: true,
|
||||||
|
updatedAt: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
).map(mapStateDeputy)
|
||||||
|
|
||||||
|
const organizations = (
|
||||||
|
await findAllDocs(payload, actor, 'organization', {
|
||||||
|
select: {
|
||||||
|
name: true,
|
||||||
|
slug: true,
|
||||||
|
kind: true,
|
||||||
|
municipalities: true,
|
||||||
|
notes: true,
|
||||||
|
updatedAt: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
).map(mapOrganization)
|
||||||
|
|
||||||
|
const demands = (
|
||||||
|
await findAllDocs(payload, actor, 'campaignDemand', {
|
||||||
|
select: {
|
||||||
|
title: true,
|
||||||
|
slug: true,
|
||||||
|
kind: true,
|
||||||
|
municipality: true,
|
||||||
|
activity: true,
|
||||||
|
leadership: true,
|
||||||
|
status: true,
|
||||||
|
updatedAt: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
).map(mapDemand)
|
||||||
|
|
||||||
|
const allUpdates = (
|
||||||
|
await findAllDocs(payload, actor, 'municipalityUpdate', {
|
||||||
|
select: {
|
||||||
|
municipality: true,
|
||||||
|
author: true,
|
||||||
|
kind: true,
|
||||||
|
body: true,
|
||||||
|
signalType: true,
|
||||||
|
updatedAt: true,
|
||||||
|
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>)
|
||||||
|
|
||||||
|
const snapshot = createEmptyOpsSnapshot(new Date().toISOString())
|
||||||
|
return {
|
||||||
|
...snapshot,
|
||||||
|
municipalities,
|
||||||
|
leaderships,
|
||||||
|
votePledges,
|
||||||
|
activities,
|
||||||
|
stateDeputies,
|
||||||
|
organizations,
|
||||||
|
demands,
|
||||||
|
municipalityUpdates,
|
||||||
|
goals,
|
||||||
|
}
|
||||||
|
}
|
||||||
223
tests/int/campaignOpsSync.int.spec.ts
Normal file
223
tests/int/campaignOpsSync.int.spec.ts
Normal file
|
|
@ -0,0 +1,223 @@
|
||||||
|
// @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 { 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 { 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('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 })
|
||||||
|
})
|
||||||
|
|
||||||
|
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)
|
||||||
|
})
|
||||||
|
})
|
||||||
Loading…
Reference in a new issue