Files
agenciapsilmno/database-novo/schema/04_tables/documentos.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

118 lines
5.2 KiB
SQL

-- Tables: Documentos
-- Gerado automaticamente em 2026-04-17T12:23:05.229Z
-- Total: 6
CREATE TABLE public.document_access_logs (
id uuid DEFAULT gen_random_uuid() NOT NULL,
documento_id uuid NOT NULL,
tenant_id uuid NOT NULL,
acao text NOT NULL,
user_id uuid,
ip inet,
user_agent text,
acessado_em timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT dal_acao_check CHECK ((acao = ANY (ARRAY['visualizou'::text, 'baixou'::text, 'imprimiu'::text, 'compartilhou'::text, 'assinou'::text])))
);
CREATE TABLE public.document_generated (
id uuid DEFAULT gen_random_uuid() NOT NULL,
template_id uuid NOT NULL,
patient_id uuid NOT NULL,
tenant_id uuid NOT NULL,
dados_preenchidos jsonb DEFAULT '{}'::jsonb NOT NULL,
pdf_path text NOT NULL,
storage_bucket text DEFAULT 'generated-docs'::text NOT NULL,
documento_id uuid,
gerado_por uuid NOT NULL,
gerado_em timestamp with time zone DEFAULT now() NOT NULL
);
CREATE TABLE public.document_share_links (
id uuid DEFAULT gen_random_uuid() NOT NULL,
documento_id uuid NOT NULL,
tenant_id uuid NOT NULL,
token text DEFAULT encode(extensions.gen_random_bytes(32), 'hex'::text) NOT NULL,
expira_em timestamp with time zone NOT NULL,
usos_max smallint DEFAULT 5 NOT NULL,
usos smallint DEFAULT 0 NOT NULL,
criado_por uuid NOT NULL,
criado_em timestamp with time zone DEFAULT now(),
ativo boolean DEFAULT true NOT NULL
);
CREATE TABLE public.document_signatures (
id uuid DEFAULT gen_random_uuid() NOT NULL,
documento_id uuid NOT NULL,
tenant_id uuid NOT NULL,
signatario_tipo text NOT NULL,
signatario_id uuid,
signatario_nome text,
signatario_email text,
ordem smallint DEFAULT 1 NOT NULL,
status text DEFAULT 'pendente'::text NOT NULL,
ip inet,
user_agent text,
assinado_em timestamp with time zone,
hash_documento text,
criado_em timestamp with time zone DEFAULT now(),
atualizado_em timestamp with time zone DEFAULT now(),
CONSTRAINT ds_signatario_tipo_check CHECK ((signatario_tipo = ANY (ARRAY['paciente'::text, 'responsavel_legal'::text, 'terapeuta'::text]))),
CONSTRAINT ds_status_check CHECK ((status = ANY (ARRAY['pendente'::text, 'enviado'::text, 'assinado'::text, 'recusado'::text, 'expirado'::text])))
);
CREATE TABLE public.document_templates (
id uuid DEFAULT gen_random_uuid() NOT NULL,
tenant_id uuid,
owner_id uuid,
nome_template text NOT NULL,
tipo text DEFAULT 'outro'::text NOT NULL,
descricao text,
corpo_html text DEFAULT ''::text NOT NULL,
cabecalho_html text,
rodape_html text,
variaveis text[] DEFAULT '{}'::text[],
logo_url text,
is_global boolean DEFAULT false NOT NULL,
ativo boolean DEFAULT true NOT NULL,
created_at timestamp with time zone DEFAULT now(),
updated_at timestamp with time zone DEFAULT now(),
CONSTRAINT dt_tipo_check CHECK ((tipo = ANY (ARRAY['declaracao_comparecimento'::text, 'atestado_psicologico'::text, 'relatorio_acompanhamento'::text, 'recibo_pagamento'::text, 'termo_consentimento'::text, 'encaminhamento'::text, 'contrato_servicos'::text, 'tcle'::text, 'autorizacao_menor'::text, 'laudo_psicologico'::text, 'parecer_psicologico'::text, 'termo_sigilo'::text, 'declaracao_inicio_tratamento'::text, 'termo_alta'::text, 'tcle_online'::text, 'outro'::text])))
);
CREATE TABLE public.documents (
id uuid DEFAULT gen_random_uuid() NOT NULL,
owner_id uuid NOT NULL,
tenant_id uuid NOT NULL,
patient_id uuid NOT NULL,
bucket_path text NOT NULL,
storage_bucket text DEFAULT 'documents'::text NOT NULL,
nome_original text NOT NULL,
mime_type text,
tamanho_bytes bigint,
tipo_documento text DEFAULT 'outro'::text NOT NULL,
categoria text,
descricao text,
tags text[] DEFAULT '{}'::text[],
agenda_evento_id uuid,
session_note_id uuid,
visibilidade text DEFAULT 'privado'::text NOT NULL,
compartilhado_portal boolean DEFAULT false NOT NULL,
compartilhado_supervisor boolean DEFAULT false NOT NULL,
compartilhado_em timestamp with time zone,
expira_compartilhamento timestamp with time zone,
enviado_pelo_paciente boolean DEFAULT false NOT NULL,
status_revisao text DEFAULT 'aprovado'::text,
revisado_por uuid,
revisado_em timestamp with time zone,
uploaded_by uuid NOT NULL,
uploaded_at timestamp with time zone DEFAULT now() NOT NULL,
deleted_at timestamp with time zone,
deleted_by uuid,
retencao_ate timestamp with time zone,
created_at timestamp with time zone DEFAULT now(),
updated_at timestamp with time zone DEFAULT now(),
CONSTRAINT documents_status_revisao_check CHECK ((status_revisao = ANY (ARRAY['pendente'::text, 'aprovado'::text, 'rejeitado'::text]))),
CONSTRAINT documents_tipo_check CHECK ((tipo_documento = ANY (ARRAY['laudo'::text, 'receita'::text, 'exame'::text, 'termo_assinado'::text, 'relatorio_externo'::text, 'identidade'::text, 'convenio'::text, 'declaracao'::text, 'atestado'::text, 'recibo'::text, 'outro'::text]))),
CONSTRAINT documents_visibilidade_check CHECK ((visibilidade = ANY (ARRAY['privado'::text, 'compartilhado_supervisor'::text, 'compartilhado_portal'::text])))
);