teqo-backup/src/utilities/contacts/contactNameInvariant.ts
Francisco Solla e71b062650 feat(C139): schemas e actions de contato — criação staff e edição por célula
Fase 3 (server) do plano aprovado:
- schemas/contact.ts: contactCreateSchema (nome único via invariante, state
  obrigatório, phones opcionais C112); contactFieldUpdateSchema ganha variantes
  city e postalCode ('' → clear); mensagens das actions client-safe aqui.
- schemas/personGenders.ts: enum de gênero em módulo folha (ciclo de imports
  contact ↔ leadership detectado e quebrado).
- actions/contact.ts: createContact (gate staff + bypass justificado, lock
  contact-name:{normalized}) e updateContactField (escopo 'edita o que vê'
  via re-check user-threaded para advisor; reorder de telefone primário).
  Apagar reusa as actions C100 existentes.
- collections Contact e Supporter: label de gênero 'Outro' → 'Não binário'
  (sem migration; nenhum teste pina a label).
- 11 testes unit novos; lint, tsc e prettier limpos.
2026-08-13 14:12:53 -03:00

55 lines
1.9 KiB
TypeScript

import 'server-only'
import type { Payload, PayloadRequest } from 'payload'
import { CONTACT_NAME_CONFLICT_MESSAGE } from '@/lib/schemas/contact'
import { acquireTextAdvisoryLocks } from '@/utilities/postgresTransactionLocks'
type ContactNameRequest = Pick<PayloadRequest, 'transactionID'>
/**
* C139 — the Contact ficha is the "person" record and the contacts page lets
* staff edit names in place, so the name becomes a first-class lookup key:
* normalize (trim + collapse whitespace + lowercase), compare exactly on the
* normalized form. The DB query is only a case-insensitive substring
* prefilter (the Postgres adapter has no normalized-equality operator); the
* verdict is the in-memory exact check.
*/
export const normalizeContactName = (name: string): string =>
name.trim().replace(/\s+/g, ' ').toLowerCase()
export const assertContactNameAvailable = async (
payload: Pick<Payload, 'db' | 'find'>,
req: ContactNameRequest,
name: string,
contactID?: number,
): Promise<void> => {
const normalized = normalizeContactName(name)
if (req.transactionID !== undefined && req.transactionID !== null) {
await acquireTextAdvisoryLocks(payload, req, [`contact-name:${normalized}`])
}
const candidates = await payload.find({
collection: 'contact',
where: {
and: [
{ name: { like: normalized } },
...(contactID === undefined ? [] : [{ id: { not_equals: contactID } }]),
],
},
depth: 0,
limit: 0,
pagination: false,
select: { name: true },
// Intentional bypass: the invariant must see rows outside the current
// actor scope (same rationale as the stateDeputy name invariant).
overrideAccess: true,
req,
})
const conflict = (candidates.docs as { name: string }[]).some(
(doc) => normalizeContactName(doc.name) === normalized,
)
if (conflict) throw new Error(CONTACT_NAME_CONFLICT_MESSAGE)
}