teqo-backup/src/utilities/homeSearch/searchHomeLeaderships.ts
Francisco Solla 6de8fad8f6 feat(C112): múltiplos telefones por pessoa — Contact.phones array (ordem = prioridade)
- Contact.phone (text único) → phones (array field Payload, subcampo value):
  fonte única; principal = phones[0]; beforeValidate normaliza, filtra vazios,
  rejeita inválido e duplicado DENTRO da ficha (C111 entre fichas preservado)
- migration add_contact_phones_array: backfill phone → phones[0] (gen_random_uuid)
  antes do drop da coluna + índice em value (hand-edit documentado; snapshot .json
  gerado mantém as colunas C99/C100 já existentes)
- primaryPhoneOf / phoneValuesOf / reorderWithPrimaryPhone em src/lib/phone.ts
  (ordem = prioridade; inline edit = seta o principal preservando o resto)
- findOrCreateContactByPhone aceita phones[] (dedupe pelo primário; reuse faz
  append dos faltantes; locks em todos os números digitados)
- sync conta→ficha (CampaignUser): phone da conta faz APPEND quando a ficha não
  tem (nunca reordena nem remove); tombstone LGPD substitui TODOS os telefones
- convite redemption: telefone digitado vira principal, demais preservados
- import CSV: preview sinaliza compartilhado também por número secundário;
  bulk insere contact_phones (JOIN nas leituras, uuid no insert)
- busca por telefone (apoiadores, pickers, combobox) casa qualquer número
- UI: PhonesFieldEditor compartilhado (repetível mascarado, remover, ↑/↓,
  modo inline com Salvar) nas 5 superfícies — liderança (form/ficha/lista),
  apoiador (form/ficha), dobradinha (ficha), assessor (ficha), wizard
- UI pública (petição/WhatsApp) intocada: zod e forms ficam com phone;
  as ações mapeiam phone → phones[0]
- testes: spec novo campaignMultiPhones (aceite completo), specs C111/C99
  atualizados, e2e wizard/apoiador ajustados
2026-08-11 10:47:02 -03:00

112 lines
3.6 KiB
TypeScript

import 'server-only'
import type { Payload } from 'payload'
import {
HOME_SEARCH_RESULT_HIT_CAP,
homeSearchQueryIsActive,
normalizeHomeSearchRaw,
} from '@/lib/campaignHomeSearchContract'
import type { HomeSearchLeadershipHit } from '@/lib/campaignHomeSearchHits'
import { HOME_SEARCH_STAFF_ONLY_MESSAGE } from '@/lib/campaignHomeSearchMessages'
import { isStaffCampaignRole } from '@/lib/campaignRoles'
import {
compareHomeSearchNameRelevance,
normalizeHomeSearchName,
} from '@/lib/homeSearchMunicipalityMatch'
import { primaryPhoneOf } from '@/lib/phone'
import { populatedContactName } from '@/lib/relationship'
import { matchesNormalizedAtWordStart } from '@/lib/wordStartFilter'
import type { CampaignUser, Leadership } from '@/payload-types'
import { truncatedNamesLabel } from '@/utilities/campaignListUrl'
import { buildLeadershipListWhere } from '@/utilities/leadership/leadershipListUrl'
const populatedContactPhone = (contact: unknown): string | null => {
if (typeof contact !== 'object' || contact === null || !('phones' in contact)) return null
const phones = (contact as { phones?: unknown }).phones
return Array.isArray(phones) ? primaryPhoneOf(phones as { value?: string | null }[]) : null
}
const municipalityNamesFromLeadership = (doc: Leadership): string[] => {
const names = new Set<string>()
for (const municipality of doc.municipalities ?? []) {
if (typeof municipality === 'object' && municipality !== null && 'name' in municipality) {
const name = municipality.name
if (typeof name === 'string' && name.length > 0) names.add(name)
}
}
return [...names].sort((left, right) => left.localeCompare(right, 'pt-BR'))
}
export const searchHomeLeaderships = async (
payload: Payload,
user: CampaignUser,
rawQuery: string,
): Promise<HomeSearchLeadershipHit[]> => {
if (!isStaffCampaignRole(user.role)) {
throw new Error(HOME_SEARCH_STAFF_ONLY_MESSAGE)
}
const query = normalizeHomeSearchRaw(rawQuery)
if (!homeSearchQueryIsActive(query)) {
return []
}
const normalizedQuery = normalizeHomeSearchName(query)
// List search uses `contains`; home search refines to word-start in memory (B49).
const result = await payload.find({
collection: 'leadership',
where: buildLeadershipListWhere({ page: 1, q: query }),
depth: 1,
limit: 0,
pagination: false,
select: {
id: true,
updatedAt: true,
contact: true,
municipalities: true,
},
user,
overrideAccess: false,
})
const candidates: Array<{
normalizedName: string
tieBreakDesc: number
id: number
name: string
phone: string | null
municipalityNames: string[]
}> = []
for (const doc of result.docs as Leadership[]) {
const name = populatedContactName(doc.contact)
const normalizedName = normalizeHomeSearchName(name)
if (!matchesNormalizedAtWordStart(normalizedName, normalizedQuery)) {
continue
}
const tieBreakDesc = Date.parse(doc.updatedAt)
candidates.push({
normalizedName,
tieBreakDesc: Number.isFinite(tieBreakDesc) ? tieBreakDesc : 0,
id: doc.id,
name,
phone: populatedContactPhone(doc.contact),
municipalityNames: municipalityNamesFromLeadership(doc),
})
}
return candidates
.sort((left, right) => compareHomeSearchNameRelevance(left, right, normalizedQuery))
.slice(0, HOME_SEARCH_RESULT_HIT_CAP)
.map(
(row): HomeSearchLeadershipHit => ({
kind: 'leadership',
id: row.id,
name: row.name,
phone: row.phone,
municipalitiesSummary: truncatedNamesLabel(row.municipalityNames),
}),
)
}