Files
agenciapsilmno/database-novo/schema/04_tables/pacientes.sql
T
Leonardo 7c20b518d4 Sessoes 1-6 acumuladas: hardening B2, defesa em camadas, +192 testes
Repositorio estava ha ~5 sessoes sem commit. Consolida tudo desde d088a89.

Ver commit.md na raiz para descricao completa por sessao.

# Numeros
- A# auditoria abertos: 0/30
- V# verificacoes abertos: 5/52 (todos adiados com plano)
- T# testes escritos: 10/10
- Vitest: 192/192
- SQL integration: 33/33
- E2E (Playwright, novo): 5/5
- Migrations: 17 (10 novas Sessao 6)
- Areas auditadas: 7 (+documentos com 10 V#)

# Highlights Sessao 6 (hoje)
- V#34/V#41 Opcao B2: tenant_features com plano + override (RPC SECURITY DEFINER, tela /saas/tenant-features)
- A#20 rev2 self-hosted: defesa em 5 camadas (honeypot + rate limit + math captcha condicional + paranoid mode + dashboard /saas/security)
- Documentos hardening (V#43-V#49): tenant scoping em storage policies (vazamento entre clinicas eliminado), RPC validate_share_token, signatures policy granular
- SaaS Twilio Config (/saas/twilio-config): UI editavel para SID/webhook/cotacao; AUTH_TOKEN permanece em env var
- T#9 + T#10: useAgendaEvents.spec.js + Playwright E2E (descobriu bug no front que foi corrigido)

# Sessoes anteriores (1-5) consolidadas
- Sessao 1: auth/router/session, normalizeRole extraido
- Sessao 2: agenda - composables/services consolidados
- Sessao 3: pacientes - tenant_id em todas queries
- Sessao 4: security review pagina publica - 14/15 vulnerabilidades corrigidas
- Sessao 5: SaaS - P0 (A#30: 7 tabelas com RLS off corrigidas)

# .gitignore ajustado
- supabase/* + !supabase/functions/ (mantem 10 edge functions, ignora .temp/migrations gerados pelo CLI)
- database-novo/backups/ (regeneravel via db.cjs backup)
- test-results/ + playwright-report/
- .claude/settings.local.json (config local com senha de dev removida do tracking)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 15:42:46 -03:00

252 lines
8.9 KiB
SQL

-- Tables: Pacientes
-- Gerado automaticamente em 2026-04-17T12:23:05.230Z
-- Total: 12
CREATE TABLE public.patient_contacts (
id uuid DEFAULT gen_random_uuid() NOT NULL,
patient_id uuid NOT NULL,
tenant_id uuid NOT NULL,
nome text NOT NULL,
tipo text NOT NULL,
relacao text,
telefone text,
email text,
cpf text,
especialidade text,
registro_profissional text,
is_primario boolean DEFAULT false NOT NULL,
ativo boolean DEFAULT true NOT NULL,
created_at timestamp with time zone DEFAULT now() NOT NULL,
updated_at timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT patient_contacts_tipo_check CHECK ((tipo = ANY (ARRAY['emergencia'::text, 'responsavel_legal'::text, 'profissional_saude'::text, 'outro'::text])))
);
CREATE TABLE public.patient_discounts (
id uuid DEFAULT gen_random_uuid() NOT NULL,
owner_id uuid NOT NULL,
tenant_id uuid NOT NULL,
patient_id uuid NOT NULL,
discount_pct numeric(5,2) DEFAULT 0,
discount_flat numeric(10,2) DEFAULT 0,
reason text,
active boolean DEFAULT true NOT NULL,
active_from timestamp with time zone DEFAULT now(),
active_to timestamp with time zone,
created_at timestamp with time zone DEFAULT now()
);
CREATE TABLE public.patient_group_patient (
patient_group_id uuid NOT NULL,
patient_id uuid NOT NULL,
created_at timestamp with time zone DEFAULT now(),
tenant_id uuid NOT NULL
);
CREATE TABLE public.patient_groups (
id uuid DEFAULT gen_random_uuid() NOT NULL,
nome text NOT NULL,
descricao text,
cor text,
is_active boolean DEFAULT true NOT NULL,
is_system boolean DEFAULT false NOT NULL,
owner_id uuid DEFAULT auth.uid() NOT NULL,
created_at timestamp with time zone DEFAULT now() NOT NULL,
updated_at timestamp with time zone DEFAULT now() NOT NULL,
therapist_id uuid,
tenant_id uuid NOT NULL
);
CREATE TABLE public.patient_intake_requests (
id uuid DEFAULT gen_random_uuid() NOT NULL,
owner_id uuid NOT NULL,
token text NOT NULL,
consent boolean DEFAULT false NOT NULL,
status text DEFAULT 'new'::text NOT NULL,
created_at timestamp with time zone DEFAULT now() NOT NULL,
converted_patient_id uuid,
rejected_reason text,
updated_at timestamp with time zone DEFAULT now() NOT NULL,
cpf text,
rg text,
cep text,
nome_completo text,
email_principal text,
telefone text,
pais text,
cidade text,
estado text,
endereco text,
numero text,
bairro text,
complemento text,
data_nascimento date,
naturalidade text,
genero text,
estado_civil text,
onde_nos_conheceu text,
encaminhado_por text,
observacoes text,
notas_internas text,
email_alternativo text,
telefone_alternativo text,
profissao text,
escolaridade text,
nacionalidade text,
avatar_url text,
tenant_id uuid,
CONSTRAINT chk_intakes_status CHECK ((status = ANY (ARRAY['new'::text, 'converted'::text, 'rejected'::text])))
);
CREATE TABLE public.patient_invites (
id uuid DEFAULT gen_random_uuid() NOT NULL,
owner_id uuid NOT NULL,
token text NOT NULL,
active boolean DEFAULT true NOT NULL,
expires_at timestamp with time zone,
max_uses integer,
uses integer DEFAULT 0 NOT NULL,
created_at timestamp with time zone DEFAULT now() NOT NULL,
tenant_id uuid
);
CREATE TABLE public.patient_patient_tag (
owner_id uuid NOT NULL,
patient_id uuid NOT NULL,
tag_id uuid NOT NULL,
created_at timestamp with time zone DEFAULT now() NOT NULL,
tenant_id uuid NOT NULL
);
CREATE TABLE public.patient_status_history (
id uuid DEFAULT gen_random_uuid() NOT NULL,
patient_id uuid NOT NULL,
tenant_id uuid NOT NULL,
status_anterior text,
status_novo text NOT NULL,
motivo text,
encaminhado_para text,
data_saida date,
alterado_por uuid,
alterado_em timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT psh_status_novo_check CHECK ((status_novo = ANY (ARRAY['Ativo'::text, 'Inativo'::text, 'Alta'::text, 'Encaminhado'::text, 'Arquivado'::text])))
);
CREATE TABLE public.patient_support_contacts (
id uuid DEFAULT gen_random_uuid() NOT NULL,
patient_id uuid NOT NULL,
owner_id uuid NOT NULL,
tenant_id uuid NOT NULL,
nome text,
relacao text,
tipo text,
telefone text,
email text,
is_primario boolean DEFAULT false NOT NULL,
created_at timestamp with time zone DEFAULT now(),
updated_at timestamp with time zone DEFAULT now()
);
CREATE TABLE public.patient_tags (
id uuid DEFAULT gen_random_uuid() NOT NULL,
owner_id uuid NOT NULL,
nome text NOT NULL,
cor text,
is_padrao boolean DEFAULT false NOT NULL,
created_at timestamp with time zone DEFAULT now() NOT NULL,
updated_at timestamp with time zone,
tenant_id uuid NOT NULL
);
CREATE TABLE public.patient_timeline (
id uuid DEFAULT gen_random_uuid() NOT NULL,
patient_id uuid NOT NULL,
tenant_id uuid NOT NULL,
evento_tipo text NOT NULL,
titulo text NOT NULL,
descricao text,
icone_cor text DEFAULT 'gray'::text,
link_ref_tipo text,
link_ref_id uuid,
gerado_por uuid,
ocorrido_em timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT pt_evento_tipo_check CHECK ((evento_tipo = ANY (ARRAY['primeira_sessao'::text, 'sessao_realizada'::text, 'sessao_cancelada'::text, 'falta'::text, 'status_alterado'::text, 'risco_sinalizado'::text, 'risco_removido'::text, 'documento_assinado'::text, 'documento_adicionado'::text, 'escala_respondida'::text, 'escala_enviada'::text, 'pagamento_vencido'::text, 'pagamento_recebido'::text, 'tarefa_combinada'::text, 'contato_adicionado'::text, 'prontuario_editado'::text, 'nota_adicionada'::text, 'manual'::text]))),
CONSTRAINT pt_icone_cor_check CHECK ((icone_cor = ANY (ARRAY['green'::text, 'blue'::text, 'amber'::text, 'red'::text, 'gray'::text, 'purple'::text])))
);
CREATE TABLE public.patients (
id uuid DEFAULT gen_random_uuid() NOT NULL,
nome_completo text NOT NULL,
email_principal text,
telefone text,
created_at timestamp with time zone DEFAULT now(),
owner_id uuid,
avatar_url text,
status text DEFAULT 'Ativo'::text,
last_attended_at timestamp with time zone,
is_native boolean DEFAULT false,
naturalidade text,
data_nascimento date,
rg text,
cpf text,
identification_color text,
genero text,
estado_civil text,
email_alternativo text,
pais text DEFAULT 'Brasil'::text,
cep text,
cidade text,
estado text,
endereco text,
numero text,
bairro text,
complemento text,
escolaridade text,
profissao text,
nome_parente text,
grau_parentesco text,
telefone_alternativo text,
onde_nos_conheceu text,
encaminhado_por text,
nome_responsavel text,
telefone_responsavel text,
cpf_responsavel text,
observacao_responsavel text,
cobranca_no_responsavel boolean DEFAULT false,
observacoes text,
notas_internas text,
updated_at timestamp with time zone DEFAULT now(),
telefone_parente text,
tenant_id uuid NOT NULL,
responsible_member_id uuid NOT NULL,
user_id uuid,
patient_scope text DEFAULT 'clinic'::text NOT NULL,
therapist_member_id uuid,
nome_social text,
pronomes text,
etnia text,
religiao text,
faixa_renda text,
canal_preferido text DEFAULT 'whatsapp'::text,
horario_contato_inicio time without time zone DEFAULT '08:00:00'::time without time zone,
horario_contato_fim time without time zone DEFAULT '20:00:00'::time without time zone,
idioma text DEFAULT 'pt-BR'::text,
origem text,
metodo_pagamento_preferido text,
motivo_saida text,
data_saida date,
encaminhado_para text,
risco_elevado boolean DEFAULT false NOT NULL,
risco_nota text,
risco_sinalizado_em timestamp with time zone,
risco_sinalizado_por uuid,
horario_contato text,
convenio text,
convenio_id uuid,
CONSTRAINT cpf_responsavel_format_check CHECK (((cpf_responsavel IS NULL) OR (cpf_responsavel ~ '^\d{11}$'::text))),
CONSTRAINT patients_cpf_format_check CHECK (((cpf IS NULL) OR (cpf ~ '^\d{11}$'::text))),
CONSTRAINT patients_faixa_renda_check CHECK (((faixa_renda IS NULL) OR (faixa_renda = ANY (ARRAY['ate_1sm'::text, '1_3sm'::text, '3_6sm'::text, '6_10sm'::text, 'acima_10sm'::text, 'nao_informado'::text])))),
CONSTRAINT patients_metodo_pagamento_check CHECK (((metodo_pagamento_preferido IS NULL) OR (metodo_pagamento_preferido = ANY (ARRAY['pix'::text, 'cartao'::text, 'dinheiro'::text, 'deposito'::text, 'convenio'::text])))),
CONSTRAINT patients_risco_consistency_check CHECK (((risco_elevado = false) OR ((risco_elevado = true) AND (risco_nota IS NOT NULL) AND (risco_sinalizado_por IS NOT NULL)))),
CONSTRAINT patients_status_check CHECK ((status = ANY (ARRAY['Ativo'::text, 'Em espera'::text, 'Inativo'::text, 'Alta'::text, 'Encaminhado'::text, 'Arquivado'::text])))
);