teqo-backup/src/utilities/supporter/supporterViewModels.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

105 lines
3.6 KiB
TypeScript

import { territoryForCity } from '@/lib/bahiaTerritories'
import { formatBrazilianPhoneInput, phoneValuesOf, primaryPhoneOf } from '@/lib/phone'
import { isPopulatedRelationship } from '@/lib/relationship'
import type { SupporterVoteIntention } from '@/lib/schemas/supporter'
import type { CampaignUser, Contact, Municipality, Supporter } from '@/payload-types'
import { supporterSourceLabels } from '@/utilities/supporter/supporterUi'
export type SupporterListItemViewModel = {
id: number
name: string
phone: string
email: string | null
city: string | null
municipalityName: string | null
municipalitySlug: string | null
voteIntention: SupporterVoteIntention | null
}
export type SupporterListOverviewViewModel = {
total: number
certoAndTende: number
indeciso: number
}
export type SupporterDetailViewModel = {
id: number
name: string
phone: string
phoneDisplay: string
/** Every number of the person, order = priority (primary first). */
phones: string[]
email: string | null
city: string | null
territory: string | null
municipalityName: string | null
municipalitySlug: string | null
voteIntention: SupporterVoteIntention | null
sourceLabel: string
consentedAt: string | null
createdByName: string | null
hasVoteIntentionConsent: boolean
createdAt: string
}
const contactFromSupporter = (supporter: { contact: Supporter['contact'] }): Contact | null =>
isPopulatedRelationship<Contact>(supporter.contact) ? supporter.contact : null
const municipalityFromSupporter = (supporter: {
municipality?: Supporter['municipality']
}): Municipality | null =>
isPopulatedRelationship<Municipality>(supporter.municipality) ? supporter.municipality : null
export const toSupporterListItemViewModel = (
supporter: Pick<Supporter, 'id' | 'voteIntention' | 'contact' | 'municipality'>,
): SupporterListItemViewModel => {
const contact = contactFromSupporter(supporter)
const municipality = municipalityFromSupporter(supporter)
return {
id: supporter.id,
name: contact?.name ?? 'Contato sem nome',
phone: primaryPhoneOf(contact?.phones) ?? '',
email: contact?.email ?? null,
city: contact?.city ?? null,
municipalityName: municipality?.name ?? null,
municipalitySlug: municipality?.slug ?? null,
voteIntention: supporter.voteIntention ?? null,
}
}
export const toSupporterDetailViewModel = (supporter: Supporter): SupporterDetailViewModel => {
const contact = contactFromSupporter(supporter)
const municipality = municipalityFromSupporter(supporter)
const creator = isPopulatedRelationship<CampaignUser>(supporter.createdBy)
? supporter.createdBy
: null
const city = contact?.city ?? null
const phones = phoneValuesOf(contact?.phones)
const phone = phones[0] ?? ''
return {
id: supporter.id,
name: contact?.name ?? 'Contato sem nome',
phone,
phoneDisplay: phone ? formatBrazilianPhoneInput(phone) : '',
phones,
email: contact?.email ?? null,
city,
territory: city ? (territoryForCity(city) ?? null) : null,
municipalityName: municipality?.name ?? null,
municipalitySlug: municipality?.slug ?? null,
voteIntention: supporter.voteIntention ?? null,
sourceLabel: supporterSourceLabels[supporter.source],
consentedAt: supporter.consentedAt ?? null,
createdByName: creator?.name ?? null,
hasVoteIntentionConsent: Boolean(supporter.voteIntentionConsentedAt),
createdAt: supporter.createdAt,
}
}
export const parseSupporterId = (value: string): number | null => {
if (!/^[1-9]\d*$/.test(value)) return null
const id = Number(value)
return Number.isSafeInteger(id) ? id : null
}