mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-25 20:33:11 +00:00
Cross-checked by parallel code-quality/performance/reuse reviewers against the E9 commit. Behavior-preserving: - laterTimestamp/resolveMunicipalityLastSignalAt were the same "latest of two ISO timestamps" written twice; both now delegate to a new latestIsoTimestamp in campaignTime.ts, which documents the fixed-width UTC invariant that makes the string compare sound. - Hoisted the frescor comparator's Date.now() out of the per-comparison accessor so the sort key stops drifting mid-sort. - Deleted the unread baseTotal/growthFactor/belowBase passthrough from the statewide goal entry point and fixed a comment citing a symbol (goalDecompositionBelowBase) that never existed; renamed computeStatewideGoalDecomposition -> computeStatewideSuggestedGoals now that nothing is proportionally decomposed. - Collapsed the advisor badge's two copies (desktop table vs mobile card) into one AdvisorStatusBadge; they had quietly diverged on which icon renders for the "no advisor" state. - Renamed the sort-menu's stale "Cobertura" label for advisor coverage to "Assessoria" (E8 already renamed the list column for the same reason); derived the sort-key set from the label record instead of a third parallel list. - Consolidated three zeroed-scenario-record literals into one zeroByVoteEstimateScenario() factory in voteEstimate.ts. - Routed three separate votesByYear[2022] reads through one votesInYear helper in municipalityPotential.ts. - Gated the goal card's empty-state copy on !usesMesaEstimate so it stops telling a município with an existing mesa estimate to enter one. - Swapped a test assertion pinned to a raw Tailwind token for a stable data-signal="cold" hook, and tightened the "desert" test's bound to check against the actual growth factor (the old bound was true for every slug regardless of the formula). Left alone (roadmap decision, not cleanup): sanityCheckSuggestedGoalsByTerritory has no production caller yet (deferred to E11/E12); comment shortened instead of deleting the dead-but-documented code. Verified: tsc --noEmit, pnpm lint (0 warnings), 337 unit + 366 integration tests, pnpm build all green.
360 lines
12 KiB
TypeScript
360 lines
12 KiB
TypeScript
import type { Payload } from 'payload'
|
||
|
||
import { getMunicipalityCatalogEntry } from '@/lib/municipalityCatalog'
|
||
import {
|
||
compareMunicipalityVotesForSort,
|
||
computeVoteRankByYear,
|
||
DEFAULT_VOTE_RANK_YEAR,
|
||
type MunicipalityVoteRankEntry,
|
||
} from '@/lib/municipalityVoteRank'
|
||
import type { CampaignUser, Municipality } from '@/payload-types'
|
||
import { isCampaignLeader, isCampaignStaff } from '@/utilities/campaignAccess'
|
||
import { loadMunicipalityScope } from '@/utilities/campaignMunicipalityScope'
|
||
import type { MunicipalityGoalCoverage } from '@/utilities/goalCoverage'
|
||
import { loadMunicipalityGoalCoverageBundle } from '@/utilities/municipalityGoalAccount'
|
||
import {
|
||
buildMunicipalityListWhere,
|
||
municipalityPageSize,
|
||
parseMunicipalityListParams,
|
||
resolveMunicipalityLastSignalAt,
|
||
resolveMunicipalityListSort,
|
||
type MunicipalityListSearchParams,
|
||
type MunicipalityListSortDirection,
|
||
type MunicipalityListSortKey,
|
||
} from '@/utilities/municipalityUi'
|
||
import {
|
||
municipalityListSelect,
|
||
toMunicipalityDetailViewModel,
|
||
toMunicipalityListViewModel,
|
||
type MunicipalityDetailViewModel,
|
||
type MunicipalityListViewModel,
|
||
} from '@/utilities/municipalityViewModels'
|
||
import { relationshipId } from '@/utilities/relationship'
|
||
import { loadStateDeputySummaries } from '@/utilities/stateDeputyData'
|
||
import { type VoteEstimateScenario } from '@/utilities/voteEstimate'
|
||
import {
|
||
rollupMunicipalityStaffVotes,
|
||
type MunicipalityPledgeAggregate,
|
||
} from '@/utilities/votePledgeData'
|
||
|
||
export class MunicipalityNotFoundError extends Error {
|
||
override name = 'MunicipalityNotFoundError'
|
||
|
||
constructor() {
|
||
super('Município não encontrado.')
|
||
}
|
||
}
|
||
|
||
export type MunicipalityListOverviewData = {
|
||
municipalityCount: number
|
||
staffVoteTotalByScenario: Record<VoteEstimateScenario, number>
|
||
pledgeCount: number
|
||
missingEstimateCount: number
|
||
withAdvisorCount: number
|
||
/**
|
||
* E9 "coluna da vergonha": priority municipalities in scope with nobody
|
||
* answering for them — the one gap the coordination can close today, so it
|
||
* gets named as a number and a filtered link instead of hiding inside the
|
||
* assessoria ratio.
|
||
*/
|
||
priorityWithoutAdvisorCount: number
|
||
/** E8 "conta da cadeira" — meta × comprometido do escopo filtrado, por cenário. */
|
||
goalCoverageByScenario: Record<VoteEstimateScenario, MunicipalityGoalCoverage>
|
||
}
|
||
|
||
export type MunicipalityListPageBundle = {
|
||
municipalities: MunicipalityListViewModel[]
|
||
totalDocs: number
|
||
totalPages: number
|
||
scopeTotal: number
|
||
overview: MunicipalityListOverviewData | null
|
||
}
|
||
|
||
const payloadSortFieldByKey: Partial<Record<MunicipalityListSortKey, string>> = {
|
||
name: 'name',
|
||
region: 'region',
|
||
kind: 'kind',
|
||
lastUpdateAt: 'lastUpdateAt',
|
||
trend: 'politicalTrend.status',
|
||
}
|
||
|
||
const municipalityNameCompare = (left: Municipality, right: Municipality): number =>
|
||
left.name.localeCompare(right.name, 'pt-BR')
|
||
|
||
type MunicipalityValueAccessor = (municipality: Municipality) => number | null | undefined
|
||
|
||
const sortByNullableValue = (
|
||
docs: Municipality[],
|
||
dir: MunicipalityListSortDirection,
|
||
getValue: MunicipalityValueAccessor,
|
||
): Municipality[] => {
|
||
const direction = dir === 'asc' ? 1 : -1
|
||
return [...docs].sort((left, right) => {
|
||
const leftValue = getValue(left) ?? null
|
||
const rightValue = getValue(right) ?? null
|
||
if (leftValue === null && rightValue === null) return municipalityNameCompare(left, right)
|
||
if (leftValue === null) return 1
|
||
if (rightValue === null) return -1
|
||
if (leftValue === rightValue) return municipalityNameCompare(left, right)
|
||
return (leftValue - rightValue) * direction
|
||
})
|
||
}
|
||
|
||
type DerivedSortContext = {
|
||
ranks: ReadonlyMap<string, MunicipalityVoteRankEntry>
|
||
goalCoverageByMunicipalityID: ReadonlyMap<
|
||
number,
|
||
Record<VoteEstimateScenario, MunicipalityGoalCoverage>
|
||
>
|
||
pledgeAggregates: ReadonlyMap<number, MunicipalityPledgeAggregate>
|
||
}
|
||
|
||
const applyDerivedMunicipalitySort = (
|
||
docs: Municipality[],
|
||
sortKey: MunicipalityListSortKey,
|
||
dir: MunicipalityListSortDirection,
|
||
{ ranks, goalCoverageByMunicipalityID, pledgeAggregates }: DerivedSortContext,
|
||
): Municipality[] => {
|
||
switch (sortKey) {
|
||
case 'expectedVotes':
|
||
return sortByNullableValue(docs, dir, (municipality) => municipality.expectedVotes?.central)
|
||
case 'coverage':
|
||
return sortByNullableValue(docs, dir, (municipality) => municipality.advisors?.length)
|
||
case 'votos':
|
||
return [...docs].sort((left, right) => {
|
||
const byVotes = compareMunicipalityVotesForSort(
|
||
ranks.get(left.slug)?.votes ?? 0,
|
||
ranks.get(right.slug)?.votes ?? 0,
|
||
dir,
|
||
)
|
||
if (byVotes !== 0) return byVotes
|
||
return municipalityNameCompare(left, right)
|
||
})
|
||
case 'deficit':
|
||
// Fixed to `central`: the scenario picker is client-side state, so the
|
||
// server has no scenario to sort by (moving it to the URL is the
|
||
// "Cenário junto aos filtros" fill-in). A município with no goal at all
|
||
// has no deficit to rank — `null` sends it to the end either way.
|
||
return sortByNullableValue(docs, dir, (municipality) => {
|
||
const coverage = goalCoverageByMunicipalityID.get(municipality.id)?.central
|
||
return coverage && coverage.goal > 0 ? coverage.deficit : null
|
||
})
|
||
case 'frescor': {
|
||
// One clock read for the whole sort: the accessor runs per comparison,
|
||
// and a "now" that drifts mid-sort is not a consistent ordering key.
|
||
const now = Date.now()
|
||
// Descending = coldest first, so "never had a signal" must outrank the
|
||
// oldest date instead of sinking as a null: age is +Infinity there.
|
||
return sortByNullableValue(docs, dir, (municipality) => {
|
||
const lastSignalAt = resolveMunicipalityLastSignalAt(
|
||
municipality.lastUpdateAt ?? null,
|
||
pledgeAggregates.get(municipality.id)?.lastPledgeAt ?? null,
|
||
)
|
||
if (!lastSignalAt) return Number.POSITIVE_INFINITY
|
||
return now - new Date(lastSignalAt).getTime()
|
||
})
|
||
}
|
||
default:
|
||
return docs
|
||
}
|
||
}
|
||
|
||
export const loadMunicipalityListPageBundle = async (
|
||
payload: Payload,
|
||
user: CampaignUser,
|
||
searchParams: MunicipalityListSearchParams,
|
||
): Promise<MunicipalityListPageBundle> => {
|
||
const state = parseMunicipalityListParams(searchParams)
|
||
const where = buildMunicipalityListWhere(state)
|
||
const isStaff = isCampaignStaff(user)
|
||
const { sort: sortKey, dir: sortDir } = resolveMunicipalityListSort(state)
|
||
|
||
if (isCampaignLeader(user)) {
|
||
return {
|
||
municipalities: [],
|
||
totalDocs: 0,
|
||
totalPages: 0,
|
||
scopeTotal: 0,
|
||
overview: null,
|
||
}
|
||
}
|
||
|
||
const ranks = computeVoteRankByYear(DEFAULT_VOTE_RANK_YEAR)
|
||
const nativeSortField = payloadSortFieldByKey[sortKey]
|
||
const isNative = nativeSortField !== undefined
|
||
|
||
const listQuery = payload.find({
|
||
collection: 'municipality',
|
||
depth: 0,
|
||
where,
|
||
select: municipalityListSelect,
|
||
user,
|
||
overrideAccess: false,
|
||
...(isNative
|
||
? {
|
||
limit: municipalityPageSize,
|
||
page: state.page,
|
||
sort: `${sortDir === 'desc' ? '-' : ''}${nativeSortField}`,
|
||
}
|
||
: {
|
||
limit: 0,
|
||
pagination: false,
|
||
}),
|
||
})
|
||
|
||
const [listResult, scopeCount, staffScope] = await Promise.all([
|
||
listQuery,
|
||
payload.count({
|
||
collection: 'municipality',
|
||
where: {},
|
||
user,
|
||
overrideAccess: false,
|
||
}),
|
||
// Request-scoped shared load (docs + pledge aggregates in one place).
|
||
isStaff ? loadMunicipalityScope(payload, user, where) : Promise.resolve(null),
|
||
])
|
||
|
||
let overview: MunicipalityListOverviewData | null = null
|
||
let pledgeAggregates = new Map<number, MunicipalityPledgeAggregate>()
|
||
let goalCoverageByMunicipalityID = new Map<
|
||
number,
|
||
Record<VoteEstimateScenario, MunicipalityGoalCoverage>
|
||
>()
|
||
|
||
if (staffScope && staffScope.municipalities.length > 0) {
|
||
pledgeAggregates = staffScope.pledgeAggregates
|
||
const rollup = rollupMunicipalityStaffVotes(staffScope.municipalities, pledgeAggregates)
|
||
const goalCoverageBundle = await loadMunicipalityGoalCoverageBundle(
|
||
payload,
|
||
user,
|
||
staffScope.municipalities,
|
||
pledgeAggregates,
|
||
)
|
||
goalCoverageByMunicipalityID = goalCoverageBundle.coverageByMunicipalityID
|
||
overview = {
|
||
municipalityCount: staffScope.municipalities.length,
|
||
staffVoteTotalByScenario: { ...rollup.staffVoteTotalByScenario },
|
||
pledgeCount: rollup.pledgeCount,
|
||
missingEstimateCount: rollup.missingEstimateCount,
|
||
withAdvisorCount: staffScope.municipalities.filter(
|
||
(municipality) => (municipality.advisors ?? []).length > 0,
|
||
).length,
|
||
priorityWithoutAdvisorCount: staffScope.municipalities.filter(
|
||
(municipality) =>
|
||
municipality.priority === 'alta' && (municipality.advisors ?? []).length === 0,
|
||
).length,
|
||
goalCoverageByScenario: goalCoverageBundle.aggregateByScenario,
|
||
}
|
||
}
|
||
|
||
let pageDocs: Municipality[]
|
||
let totalDocs: number
|
||
let totalPages: number
|
||
|
||
if (isNative) {
|
||
// Payload select narrows the inferred type; the selected fields cover the view model.
|
||
pageDocs = listResult.docs as Municipality[]
|
||
totalDocs = listResult.totalDocs
|
||
totalPages = listResult.totalPages
|
||
} else {
|
||
const allDocs = applyDerivedMunicipalitySort(
|
||
listResult.docs as Municipality[],
|
||
sortKey,
|
||
sortDir,
|
||
{
|
||
ranks,
|
||
goalCoverageByMunicipalityID,
|
||
pledgeAggregates,
|
||
},
|
||
)
|
||
totalDocs = allDocs.length
|
||
totalPages = Math.max(1, Math.ceil(totalDocs / municipalityPageSize))
|
||
const start = (state.page - 1) * municipalityPageSize
|
||
pageDocs = allDocs.slice(start, start + municipalityPageSize)
|
||
}
|
||
|
||
return {
|
||
municipalities: pageDocs.map((municipality) =>
|
||
toMunicipalityListViewModel(
|
||
municipality,
|
||
isStaff ? pledgeAggregates.get(municipality.id) : undefined,
|
||
ranks.get(municipality.slug) ?? null,
|
||
isStaff ? goalCoverageByMunicipalityID.get(municipality.id) : undefined,
|
||
),
|
||
),
|
||
totalDocs,
|
||
totalPages,
|
||
scopeTotal: scopeCount.totalDocs,
|
||
overview,
|
||
}
|
||
}
|
||
|
||
export type AccessibleMunicipalityContext = {
|
||
id: number
|
||
slug: string
|
||
document: Municipality
|
||
}
|
||
|
||
export const resolveAccessibleMunicipalityContext = async (
|
||
payload: Pick<Payload, 'find'>,
|
||
user: CampaignUser,
|
||
municipalitySlug: string,
|
||
): Promise<AccessibleMunicipalityContext> => {
|
||
const result = await payload.find({
|
||
collection: 'municipality',
|
||
where: { slug: { equals: municipalitySlug } },
|
||
depth: 0,
|
||
limit: 1,
|
||
pagination: false,
|
||
user,
|
||
overrideAccess: false,
|
||
})
|
||
const municipality = result.docs[0]
|
||
if (!municipality) throw new MunicipalityNotFoundError()
|
||
|
||
return {
|
||
id: municipality.id,
|
||
slug: municipality.slug,
|
||
document: municipality as Municipality,
|
||
}
|
||
}
|
||
|
||
export const getMunicipalityDetailViewModel = async (
|
||
payload: Payload,
|
||
context: AccessibleMunicipalityContext,
|
||
user: CampaignUser,
|
||
): Promise<MunicipalityDetailViewModel> => {
|
||
const catalogEntry = getMunicipalityCatalogEntry(context.slug)
|
||
const tseZones = catalogEntry ? [...catalogEntry.tseZones] : []
|
||
|
||
let trendRecordedByName: string | null = null
|
||
const recordedByID = relationshipId(context.document.politicalTrend?.recordedBy)
|
||
if (user.role !== 'leader' && recordedByID) {
|
||
try {
|
||
const recorder = await payload.findByID({
|
||
collection: 'campaignUser',
|
||
id: recordedByID,
|
||
depth: 0,
|
||
select: { name: true },
|
||
overrideAccess: true,
|
||
})
|
||
trendRecordedByName = recorder.name
|
||
} catch {
|
||
trendRecordedByName = null
|
||
}
|
||
}
|
||
|
||
const stateDeputyIDs = (context.document.stateDeputies ?? [])
|
||
.map(relationshipId)
|
||
.filter((id): id is number => id !== null)
|
||
const stateDeputies =
|
||
user.role === 'leader' ? [] : await loadStateDeputySummaries(payload, stateDeputyIDs)
|
||
|
||
return toMunicipalityDetailViewModel(
|
||
context.document,
|
||
user.role,
|
||
tseZones,
|
||
trendRecordedByName,
|
||
stateDeputies,
|
||
)
|
||
}
|