import 'server-only' import type { Payload } from 'payload' import type { SupportStatus } from '@/lib/schemas/leadership' import { isSupportStatus } from '@/lib/schemas/leadership' import type { CampaignUser, Leadership } from '@/payload-types' import { isCampaignStaff } from '@/utilities/campaignAccess' import { buildLeadershipListWhere, leadershipPageSize, resolveLeadershipListPayloadSort, resolveLeadershipListSort, type LeadershipListState, } from '@/utilities/leadershipListUrl' import { relationshipId } from '@/utilities/relationship' import { loadStateDeputySummaries, type StateDeputySummary } from '@/utilities/stateDeputyData' export type LeadershipRowViewModel = { id: number contactID: number name: string phone: string | null email: string | null supportStatus: SupportStatus | null sector: string | null /** * Ids only: the "Municípios" cell renders chips through * `buildMunicipalityPortfolioChips` over the shared portfolio index, which * already carries every name/slug and is what collapses a whole território * into one chip. Resolving names here too would be a second source of truth. */ municipalityIDs: number[] organizationNames: string[] stateDeputies: StateDeputySummary[] hasAppAccess: boolean /** Last write to the leadership row — the dossier's freshness readout. */ updatedAt: string } const contactSummary = ( contact: Leadership['contact'], ): { id: number; name: string; phone: string | null; email: string | null } => { if (typeof contact === 'object' && contact !== null) { return { id: contact.id, name: contact.name ?? 'Contato', phone: contact.phone ?? null, email: contact.email ?? null, } } return { id: Number(contact), name: 'Contato', phone: null, email: null } } const organizationNamesForIds = async ( payload: Payload, ids: number[], ): Promise> => { if (ids.length === 0) return new Map() // Intentional admin bypass: display-name resolution for rows the actor // already passed row-level access on. const result = await payload.find({ collection: 'organization', where: { id: { in: ids } }, depth: 0, limit: 0, pagination: false, select: { name: true }, overrideAccess: true, }) return new Map(result.docs.map((doc) => [doc.id, doc.name])) } const toLeadershipRows = async ( payload: Payload, docs: Leadership[], ): Promise => { const organizationIDs = new Set() const stateDeputyIDs = new Set() for (const doc of docs) { for (const organization of doc.organizations ?? []) { const id = relationshipId(organization) if (id !== null) organizationIDs.add(id) } for (const stateDeputy of doc.stateDeputies ?? []) { const id = relationshipId(stateDeputy) if (id !== null) stateDeputyIDs.add(id) } } const [organizationNames, stateDeputySummaries] = await Promise.all([ organizationNamesForIds(payload, [...organizationIDs]), loadStateDeputySummaries(payload, [...stateDeputyIDs]), ]) const stateDeputyById = new Map(stateDeputySummaries.map((summary) => [summary.id, summary])) return docs.map((doc) => { const contact = contactSummary(doc.contact) return { id: doc.id, contactID: contact.id, name: contact.name, phone: contact.phone, email: contact.email, supportStatus: isSupportStatus(doc.supportStatus) ? doc.supportStatus : null, sector: doc.sector ?? null, municipalityIDs: (doc.municipalities ?? []) .map(relationshipId) .filter((id): id is number => id !== null), organizationNames: (doc.organizations ?? []) .map(relationshipId) .filter((id): id is number => id !== null) .map((id) => organizationNames.get(id) ?? 'Organização'), stateDeputies: (doc.stateDeputies ?? []) .map(relationshipId) .filter((id): id is number => id !== null) .map((id) => stateDeputyById.get(id)) .filter((summary): summary is StateDeputySummary => summary !== undefined), hasAppAccess: relationshipId(doc.user) !== null, updatedAt: doc.updatedAt, } }) } export const loadMunicipalityLeaderships = async ( payload: Payload, user: CampaignUser, municipalityID: number, ): Promise => { const result = await payload.find({ collection: 'leadership', where: { municipalities: { in: [municipalityID] } }, depth: 1, limit: 0, pagination: false, sort: 'createdAt', user, overrideAccess: false, }) return toLeadershipRows(payload, result.docs as Leadership[]) } /** * Dossier variant: only the `limit` most recently updated rows (sorted in * Postgres), plus the full count — avoids fetching every leadership of a * heavy município just to slice a handful. */ export const loadFreshestMunicipalityLeaderships = async ( payload: Payload, user: CampaignUser, municipalityID: number, limit: number, ): Promise<{ rows: LeadershipRowViewModel[]; totalCount: number }> => { const result = await payload.find({ collection: 'leadership', where: { municipalities: { in: [municipalityID] } }, depth: 1, limit, sort: '-updatedAt', user, overrideAccess: false, }) return { rows: await toLeadershipRows(payload, result.docs as Leadership[]), totalCount: result.totalDocs, } } export type LeadershipListFilterFacets = { /** Municipality ids present under the other active filters (cross-filtered). */ municipalityIDs: number[] } /** * Respects every OTHER filter (search, status, sector, access) but drops the * municipality filter itself — same contract as `loadStateDeputyPartyFacet`: * a selected id is unioned in so it stays visible to undo. */ const loadLeadershipMunicipalityFacet = async ( payload: Payload, user: CampaignUser, state: LeadershipListState, ): Promise => { const result = await payload.find({ collection: 'leadership', where: buildLeadershipListWhere({ ...state, municipalities: undefined }), depth: 0, limit: 0, pagination: false, select: { municipalities: true }, user, overrideAccess: false, }) const available = new Set(state.municipalities ?? []) for (const doc of result.docs) { for (const municipality of doc.municipalities ?? []) { const id = relationshipId(municipality) if (id !== null) available.add(id) } } return { municipalityIDs: [...available].sort((left, right) => left - right), } } export const loadLeadershipListPageData = async ( payload: Payload, user: CampaignUser, state: LeadershipListState, ): Promise<{ rows: LeadershipRowViewModel[] totalDocs: number totalPages: number filterFacets: LeadershipListFilterFacets }> => { if (!isCampaignStaff(user)) { return { rows: [], totalDocs: 0, totalPages: 0, filterFacets: { municipalityIDs: [] } } } const { sort, dir } = resolveLeadershipListSort(state) const [result, filterFacets] = await Promise.all([ payload.find({ collection: 'leadership', where: buildLeadershipListWhere(state), depth: 1, limit: leadershipPageSize, page: state.page, sort: resolveLeadershipListPayloadSort(sort, dir), user, overrideAccess: false, }), loadLeadershipMunicipalityFacet(payload, user, state), ]) return { rows: await toLeadershipRows(payload, result.docs as Leadership[]), totalDocs: result.totalDocs, totalPages: result.totalPages, filterFacets, } } export type LeadershipDetailViewModel = LeadershipRowViewModel & { municipalityIDs: number[] organizationIDs: number[] stateDeputyIDs: number[] sectorNotes: string | null notes: string | null consentNote: string | null } export const loadLeadershipDetail = async ( payload: Payload, user: CampaignUser, leadershipID: number, ): Promise => { const result = await payload.find({ collection: 'leadership', where: { id: { equals: leadershipID } }, depth: 1, limit: 1, pagination: false, user, overrideAccess: false, }) const doc = result.docs[0] as Leadership | undefined if (!doc) return null const [row] = await toLeadershipRows(payload, [doc]) if (!row) return null return { ...row, municipalityIDs: (doc.municipalities ?? []) .map(relationshipId) .filter((id): id is number => id !== null), organizationIDs: (doc.organizations ?? []) .map(relationshipId) .filter((id): id is number => id !== null), stateDeputyIDs: row.stateDeputies.map((summary) => summary.id), sectorNotes: doc.sectorNotes ?? null, notes: doc.notes ?? null, consentNote: doc.consentNote ?? null, } }