teqo-backup/tests/unit/federalCandidateTotalsAggregate.unit.spec.ts
Francisco Ignácio Fontoura Solla c2381cecde Deliver A7 Fase 2 cityCode TSE geography filters and absorb simplify debts.
Switch election geography queries from cityName to TSE cityCode via a static Bahia map and nucleusElectionGeography module, with simplify cleanup and plan updates for F3–F5 follow-ups.
2026-07-19 22:48:08 -03:00

87 lines
2.5 KiB
TypeScript

// @vitest-environment node
import { describe, expect, it, vi } from 'vitest'
import type { Payload } from 'payload'
import type { CampaignUser, User } from '@/payload-types'
import { assertCanReadElectionData } from '@/utilities/campaignAccess'
import { loadFederalCandidateTotalsAggregated } from '@/utilities/federalCandidateTotalsAggregate'
import * as drizzleBulk from '@/utilities/drizzleBulk'
import { resolveNucleusElectionGeography } from '@/utilities/nucleusElectionGeography'
describe('assertCanReadElectionData', () => {
it('allows payload admins and campaign users to read election data', () => {
expect(() =>
assertCanReadElectionData({
collection: 'users',
id: 1,
} as User),
).not.toThrow()
expect(() =>
assertCanReadElectionData({
collection: 'campaignUser',
id: 1,
role: 'lideranca',
} as CampaignUser),
).not.toThrow()
})
it('denies readers outside campaign/admin collections', () => {
expect(() =>
assertCanReadElectionData({
collection: 'contact',
id: 1,
} as never),
).toThrow('Leitura de dados eleitorais negada.')
})
})
describe('loadFederalCandidateTotalsAggregated', () => {
it('maps drizzle aggregate rows and scopes geography in SQL', async () => {
const geography = resolveNucleusElectionGeography({
cities: ['Salvador'],
regions: [],
tseZones: [1, 2],
})!
const execute = vi.fn().mockResolvedValue({
rows: [
{
candidate_number: 1313,
candidate_name: 'JORGE SOLLA',
party: 'PT',
votes: 2100,
},
{
candidate_number: 1234,
candidate_name: 'OUTRO',
party: 'PL',
votes: 900,
},
],
})
vi.spyOn(drizzleBulk, 'requirePostgresDrizzle').mockReturnValue({ execute })
const payload = { db: { name: 'postgres' } } as Pick<Payload, 'db'>
const totals = await loadFederalCandidateTotalsAggregated(
payload,
{
collection: 'campaignUser',
id: 1,
role: 'geral',
} as CampaignUser,
geography,
)
expect(totals).toEqual([
{ candidateNumber: 1313, name: 'JORGE SOLLA', party: 'PT', votes: 2100 },
{ candidateNumber: 1234, name: 'OUTRO', party: 'PL', votes: 900 },
])
expect(execute).toHaveBeenCalledOnce()
const sqlPayload = JSON.stringify(execute.mock.calls[0]?.[0])
expect(sqlPayload).toContain('city_code')
expect(sqlPayload).not.toContain('city_name')
vi.restoreAllMocks()
})
})