Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 114d755f84 | |||
| 19caa42f3b | |||
| 4e42881d5e | |||
| 934c620295 | |||
| 8601ac0d70 |
@@ -1232,3 +1232,53 @@ DESIGN_ASAAS_GATEWAY.md completo. 7 arquivos novos: 2 migrations (tables+RLS) +
|
||||
## [2026-05-21 morning] session | Fase 3 — Compliance CFP #5/#8/#9
|
||||
Touched: none
|
||||
2 migrations (profiles registration + specialties+joinM:N+RLS) + 1 seed (33 specialties) + 1 service (specialtiesService.js). #8 nome social ja estava integrado. #6 consent forms e #7 assinatura adiados — schemas (document_templates+document_signatures) existem, falta UI workflow.
|
||||
|
||||
## [2026-05-21 afternoon] session | Compliance CFP #6 + #7 fechados
|
||||
Touched: none (durable em development/02-auditoria/PADRONIZACAO.md + memoria padronizacao_sweep)
|
||||
|
||||
Fechou Fase 1.2 Compliance basico BR do ROADMAP. 5 commits tematicos.
|
||||
|
||||
#6 (consent forms) — biblioteca de templates LGPD-compliant:
|
||||
- Migration 20260521000005 estende CHECK constraint de document_templates.tipo
|
||||
com 'termo_lgpd' + 'autorizacao_gravacao'
|
||||
- Seed seed_060 insere 2 templates globais novos (Consentimento LGPD com
|
||||
Art. 18 direitos do titular + Autorizacao para Gravacao de Sessao) +
|
||||
UPDATE no tcle_online amend cláusula LGPD explicita
|
||||
- Biblioteca completa pos-amend: TCLE, tcle_online (telehealth),
|
||||
autorizacao_menor (TCLE menores), termo_sigilo, termo_lgpd, autorizacao_
|
||||
gravacao + 9 outros tipos existentes
|
||||
|
||||
#7 (assinatura eletronica no portal) — fluxo end-to-end:
|
||||
- Migration 20260521000006: 3 RPCs (sign_document_by_signature_id +
|
||||
sign_document_by_token + get_signable_document_by_token). IP/UA
|
||||
capturados SERVER-SIDE via inet_client_addr() e current_setting
|
||||
('request.headers') — anti-spoof. Hash SHA-256 vem do cliente
|
||||
pra integridade
|
||||
- Migration 20260521000007: RPC list_my_signatures que cruza auth.uid()
|
||||
por 3 caminhos (signatario_id, signatario_email, patient.user_id)
|
||||
- DocumentSignatures.service ganha 4 wrappers: signByPortal,
|
||||
signByToken, getSignableDocumentByToken, listMySignatures
|
||||
- useDocumentSignatures composable novo (Tipo A blueprint)
|
||||
- PortalDocumentos.vue (nova) — lista pendencias do paciente logado
|
||||
com KPIs + filtro + botao "Assinar agora" que aponta pra share link
|
||||
- portal.menu.js ganha item "Documentos > Para assinar"
|
||||
- SharedDocumentPage.vue estendida: painel azul abaixo do preview
|
||||
com aviso LGPD/CFP + checkbox aceite + selecao multi-signatario
|
||||
+ botoes Assinar/Recusar com loading + computa SHA-256 do PDF
|
||||
baixado antes do sign
|
||||
- DocumentSignatureDialog (terapeuta-side, ja existia) ganha
|
||||
checkbox "Gerar link publico para assinatura" (default ON) +
|
||||
select validade (24h/3d/7d/30d) + bloco emerald com URL + copy
|
||||
|
||||
Fluxo end-to-end: terapeuta cria signature requests + share_link
|
||||
no dialog -> copia URL -> envia via WA/email -> paciente abre
|
||||
/shared/document/:token -> visualiza doc -> aceite -> assinatura
|
||||
registrada via RPC sign_document_by_token (IP/UA/timestamp/hash
|
||||
gravados server-side em document_signatures).
|
||||
|
||||
Pos-MVP nice-to-have: notificacao automatica do paciente quando
|
||||
signature criada (depende de Modulo 6 notifications WA/email
|
||||
channel factory). Por ora, terapeuta envia link manualmente.
|
||||
|
||||
PROXIMO: outras 5 secoes do ROADMAP Fase 1 (Asaas Fase B bloqueada,
|
||||
UX §1.3, Fiscal §1.4, Qualidade §1.5).
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
-- ============================================================================
|
||||
-- Compliance CFP #6 — Tipos de consent form (LGPD + Gravação)
|
||||
-- ----------------------------------------------------------------------------
|
||||
-- Estende o CHECK constraint de document_templates.tipo para acomodar dois
|
||||
-- novos tipos de consent form exigidos pela LGPD e pela prática clínica:
|
||||
-- • termo_lgpd — Consentimento de tratamento de dados pessoais
|
||||
-- • autorizacao_gravacao — Autorização de gravação de sessão (áudio/vídeo)
|
||||
--
|
||||
-- ROADMAP item #1.2 #6 (Biblioteca de consent forms editáveis).
|
||||
-- ============================================================================
|
||||
|
||||
BEGIN;
|
||||
|
||||
ALTER TABLE public.document_templates
|
||||
DROP CONSTRAINT IF EXISTS dt_tipo_check;
|
||||
|
||||
ALTER TABLE public.document_templates
|
||||
ADD CONSTRAINT dt_tipo_check CHECK (
|
||||
tipo = ANY (ARRAY[
|
||||
'declaracao_comparecimento',
|
||||
'atestado_psicologico',
|
||||
'relatorio_acompanhamento',
|
||||
'recibo_pagamento',
|
||||
'termo_consentimento',
|
||||
'encaminhamento',
|
||||
'contrato_servicos',
|
||||
'tcle',
|
||||
'autorizacao_menor',
|
||||
'laudo_psicologico',
|
||||
'parecer_psicologico',
|
||||
'termo_sigilo',
|
||||
'declaracao_inicio_tratamento',
|
||||
'termo_alta',
|
||||
'tcle_online',
|
||||
'termo_lgpd',
|
||||
'autorizacao_gravacao',
|
||||
'outro'
|
||||
])
|
||||
);
|
||||
|
||||
COMMENT ON COLUMN public.document_templates.tipo IS
|
||||
'Tipo do template. Inclui consent forms (tcle, tcle_online, autorizacao_menor, termo_sigilo, termo_lgpd, autorizacao_gravacao).';
|
||||
|
||||
COMMIT;
|
||||
@@ -0,0 +1,251 @@
|
||||
-- ============================================================================
|
||||
-- Compliance CFP #7 — RPCs de assinatura eletrônica
|
||||
-- ----------------------------------------------------------------------------
|
||||
-- Cria 2 RPCs que registram assinatura capturando IP server-side (anti-spoof)
|
||||
-- via inet_client_addr() e user-agent via request headers do Supabase.
|
||||
--
|
||||
-- • sign_document_by_signature_id — paciente logado assina via portal
|
||||
-- • sign_document_by_token — terceiro assina via share link público
|
||||
--
|
||||
-- ROADMAP item #1.2 #7 (Assinatura eletrônica pelo paciente no portal,
|
||||
-- simples, com IP+timestamp). Não usa ICP-Brasil — é assinatura simples
|
||||
-- com audit trail (IP, UA, timestamp, hash SHA-256 do documento).
|
||||
-- ============================================================================
|
||||
|
||||
BEGIN;
|
||||
|
||||
-- ──────────────────────────────────────────────────────────────────────────
|
||||
-- 1. sign_document_by_signature_id
|
||||
-- ----------------------------------------------------------------------------
|
||||
-- Para signatários LOGADOS no portal/sistema. SECURITY INVOKER — a RLS de
|
||||
-- document_signatures continua aplicando (signatario_id = auth.uid() ou
|
||||
-- tenant_members). RPC só serve pra centralizar captura de IP + UA + hash.
|
||||
-- ──────────────────────────────────────────────────────────────────────────
|
||||
CREATE OR REPLACE FUNCTION public.sign_document_by_signature_id(
|
||||
p_signature_id uuid,
|
||||
p_hash_documento text DEFAULT NULL
|
||||
) RETURNS public.document_signatures
|
||||
LANGUAGE plpgsql
|
||||
SECURITY INVOKER
|
||||
AS $$
|
||||
DECLARE
|
||||
v_row public.document_signatures;
|
||||
v_ip inet;
|
||||
v_ua text;
|
||||
BEGIN
|
||||
IF p_signature_id IS NULL THEN
|
||||
RAISE EXCEPTION 'p_signature_id obrigatório' USING ERRCODE = '22023';
|
||||
END IF;
|
||||
|
||||
-- Captura IP e UA do request (best-effort — pode vir NULL em alguns ambientes)
|
||||
v_ip := inet_client_addr();
|
||||
BEGIN
|
||||
v_ua := current_setting('request.headers', true)::json ->> 'user-agent';
|
||||
EXCEPTION WHEN OTHERS THEN
|
||||
v_ua := NULL;
|
||||
END;
|
||||
|
||||
UPDATE public.document_signatures
|
||||
SET status = 'assinado',
|
||||
ip = v_ip,
|
||||
user_agent = v_ua,
|
||||
assinado_em = now(),
|
||||
hash_documento = COALESCE(p_hash_documento, hash_documento),
|
||||
atualizado_em = now()
|
||||
WHERE id = p_signature_id
|
||||
AND status IN ('pendente', 'enviado')
|
||||
RETURNING * INTO v_row;
|
||||
|
||||
IF v_row.id IS NULL THEN
|
||||
RAISE EXCEPTION 'Assinatura não encontrada ou já processada' USING ERRCODE = 'P0002';
|
||||
END IF;
|
||||
|
||||
RETURN v_row;
|
||||
END;
|
||||
$$;
|
||||
|
||||
COMMENT ON FUNCTION public.sign_document_by_signature_id(uuid, text) IS
|
||||
'Assinatura via portal logado. Captura IP/UA server-side. RLS aplica (SECURITY INVOKER).';
|
||||
|
||||
GRANT EXECUTE ON FUNCTION public.sign_document_by_signature_id(uuid, text) TO authenticated;
|
||||
|
||||
-- ──────────────────────────────────────────────────────────────────────────
|
||||
-- 2. sign_document_by_token
|
||||
-- ----------------------------------------------------------------------------
|
||||
-- Para signatários NÃO LOGADOS via share link público. SECURITY DEFINER —
|
||||
-- bypassa RLS. Valida o share_link (token, ativo, expira_em, usos_max),
|
||||
-- localiza o signatário PENDENTE associado ao documento (signatario_email
|
||||
-- opcional p/ desambiguar quando há múltiplos), assina, incrementa usos.
|
||||
-- ──────────────────────────────────────────────────────────────────────────
|
||||
CREATE OR REPLACE FUNCTION public.sign_document_by_token(
|
||||
p_token text,
|
||||
p_signature_id uuid DEFAULT NULL,
|
||||
p_hash_documento text DEFAULT NULL
|
||||
) RETURNS public.document_signatures
|
||||
LANGUAGE plpgsql
|
||||
SECURITY DEFINER
|
||||
SET search_path = public
|
||||
AS $$
|
||||
DECLARE
|
||||
v_link public.document_share_links;
|
||||
v_sig public.document_signatures;
|
||||
v_ip inet;
|
||||
v_ua text;
|
||||
BEGIN
|
||||
IF p_token IS NULL OR length(p_token) < 32 THEN
|
||||
RAISE EXCEPTION 'Token inválido' USING ERRCODE = '22023';
|
||||
END IF;
|
||||
|
||||
-- Valida share_link
|
||||
SELECT * INTO v_link
|
||||
FROM public.document_share_links
|
||||
WHERE token = p_token
|
||||
AND ativo = true
|
||||
AND expira_em > now()
|
||||
AND usos < usos_max
|
||||
LIMIT 1;
|
||||
|
||||
IF v_link.id IS NULL THEN
|
||||
RAISE EXCEPTION 'Link expirado, inválido ou esgotado' USING ERRCODE = 'P0002';
|
||||
END IF;
|
||||
|
||||
-- Localiza a signature pendente do documento. Se p_signature_id veio,
|
||||
-- é desambiguação (multi-signatário); senão pega a primeira pendente
|
||||
-- por ordem.
|
||||
IF p_signature_id IS NOT NULL THEN
|
||||
SELECT * INTO v_sig
|
||||
FROM public.document_signatures
|
||||
WHERE id = p_signature_id
|
||||
AND documento_id = v_link.documento_id
|
||||
AND status IN ('pendente', 'enviado')
|
||||
LIMIT 1;
|
||||
ELSE
|
||||
SELECT * INTO v_sig
|
||||
FROM public.document_signatures
|
||||
WHERE documento_id = v_link.documento_id
|
||||
AND status IN ('pendente', 'enviado')
|
||||
ORDER BY ordem ASC, criado_em ASC
|
||||
LIMIT 1;
|
||||
END IF;
|
||||
|
||||
IF v_sig.id IS NULL THEN
|
||||
RAISE EXCEPTION 'Nenhuma assinatura pendente para este documento' USING ERRCODE = 'P0002';
|
||||
END IF;
|
||||
|
||||
-- Captura IP/UA
|
||||
v_ip := inet_client_addr();
|
||||
BEGIN
|
||||
v_ua := current_setting('request.headers', true)::json ->> 'user-agent';
|
||||
EXCEPTION WHEN OTHERS THEN
|
||||
v_ua := NULL;
|
||||
END;
|
||||
|
||||
-- Assina
|
||||
UPDATE public.document_signatures
|
||||
SET status = 'assinado',
|
||||
ip = v_ip,
|
||||
user_agent = v_ua,
|
||||
assinado_em = now(),
|
||||
hash_documento = COALESCE(p_hash_documento, hash_documento),
|
||||
atualizado_em = now()
|
||||
WHERE id = v_sig.id
|
||||
RETURNING * INTO v_sig;
|
||||
|
||||
-- Incrementa contador de usos do share_link
|
||||
UPDATE public.document_share_links
|
||||
SET usos = usos + 1
|
||||
WHERE id = v_link.id;
|
||||
|
||||
RETURN v_sig;
|
||||
END;
|
||||
$$;
|
||||
|
||||
COMMENT ON FUNCTION public.sign_document_by_token(text, uuid, text) IS
|
||||
'Assinatura via share link público. SECURITY DEFINER — valida token, captura IP/UA, incrementa usos. p_signature_id é opcional pra desambiguar multi-signatário.';
|
||||
|
||||
GRANT EXECUTE ON FUNCTION public.sign_document_by_token(text, uuid, text) TO anon, authenticated;
|
||||
|
||||
-- ──────────────────────────────────────────────────────────────────────────
|
||||
-- 3. get_signable_document_by_token
|
||||
-- ----------------------------------------------------------------------------
|
||||
-- View helper que retorna info do documento + signatários pendentes via token,
|
||||
-- sem assinar. Permite a página pública renderizar antes do click.
|
||||
-- SECURITY DEFINER porque share_link tem RLS pública mas documents+signatures
|
||||
-- têm RLS por owner/tenant.
|
||||
-- ──────────────────────────────────────────────────────────────────────────
|
||||
CREATE OR REPLACE FUNCTION public.get_signable_document_by_token(
|
||||
p_token text
|
||||
) RETURNS jsonb
|
||||
LANGUAGE plpgsql
|
||||
SECURITY DEFINER
|
||||
SET search_path = public
|
||||
AS $$
|
||||
DECLARE
|
||||
v_link public.document_share_links;
|
||||
v_doc public.documents;
|
||||
v_sigs jsonb;
|
||||
BEGIN
|
||||
IF p_token IS NULL OR length(p_token) < 32 THEN
|
||||
RAISE EXCEPTION 'Token inválido' USING ERRCODE = '22023';
|
||||
END IF;
|
||||
|
||||
SELECT * INTO v_link
|
||||
FROM public.document_share_links
|
||||
WHERE token = p_token
|
||||
AND ativo = true
|
||||
AND expira_em > now()
|
||||
AND usos < usos_max
|
||||
LIMIT 1;
|
||||
|
||||
IF v_link.id IS NULL THEN
|
||||
RETURN jsonb_build_object('valid', false, 'error', 'expired_or_invalid');
|
||||
END IF;
|
||||
|
||||
SELECT * INTO v_doc
|
||||
FROM public.documents
|
||||
WHERE id = v_link.documento_id
|
||||
AND deleted_at IS NULL
|
||||
LIMIT 1;
|
||||
|
||||
IF v_doc.id IS NULL THEN
|
||||
RETURN jsonb_build_object('valid', false, 'error', 'document_not_found');
|
||||
END IF;
|
||||
|
||||
SELECT jsonb_agg(
|
||||
jsonb_build_object(
|
||||
'id', s.id,
|
||||
'signatario_tipo', s.signatario_tipo,
|
||||
'signatario_nome', s.signatario_nome,
|
||||
'signatario_email', s.signatario_email,
|
||||
'ordem', s.ordem,
|
||||
'status', s.status,
|
||||
'assinado_em', s.assinado_em
|
||||
) ORDER BY s.ordem
|
||||
) INTO v_sigs
|
||||
FROM public.document_signatures s
|
||||
WHERE s.documento_id = v_doc.id;
|
||||
|
||||
RETURN jsonb_build_object(
|
||||
'valid', true,
|
||||
'document', jsonb_build_object(
|
||||
'id', v_doc.id,
|
||||
'nome_original', v_doc.nome_original,
|
||||
'mime_type', v_doc.mime_type,
|
||||
'tamanho_bytes', v_doc.tamanho_bytes,
|
||||
'bucket_path', v_doc.bucket_path,
|
||||
'storage_bucket', v_doc.storage_bucket,
|
||||
'tipo_documento', v_doc.tipo_documento
|
||||
),
|
||||
'signatures', COALESCE(v_sigs, '[]'::jsonb),
|
||||
'expira_em', v_link.expira_em,
|
||||
'usos_restantes', v_link.usos_max - v_link.usos
|
||||
);
|
||||
END;
|
||||
$$;
|
||||
|
||||
COMMENT ON FUNCTION public.get_signable_document_by_token(text) IS
|
||||
'Retorna documento + signatários pendentes via token. Usado pela página pública antes de assinar.';
|
||||
|
||||
GRANT EXECUTE ON FUNCTION public.get_signable_document_by_token(text) TO anon, authenticated;
|
||||
|
||||
COMMIT;
|
||||
@@ -0,0 +1,102 @@
|
||||
-- ============================================================================
|
||||
-- Compliance CFP #7 — RPC list_my_signatures (portal do paciente)
|
||||
-- ----------------------------------------------------------------------------
|
||||
-- Retorna as solicitações de assinatura do paciente logado (auth.uid()
|
||||
-- associado a patients.user_id). SECURITY DEFINER pra bypassar a RLS de
|
||||
-- document_signatures (que hoje só libera pra tenant_members).
|
||||
--
|
||||
-- Cada item já vem com o share_link.token associado, pra que o portal
|
||||
-- aponte direto pra /shared/document/:token onde o usuário vai assinar.
|
||||
-- O link público é gerado quando o terapeuta solicita a assinatura.
|
||||
-- ============================================================================
|
||||
|
||||
BEGIN;
|
||||
|
||||
CREATE OR REPLACE FUNCTION public.list_my_signatures(
|
||||
p_status text[] DEFAULT NULL
|
||||
) RETURNS TABLE (
|
||||
signature_id uuid,
|
||||
documento_id uuid,
|
||||
tenant_id uuid,
|
||||
signatario_tipo text,
|
||||
status text,
|
||||
ordem smallint,
|
||||
assinado_em timestamptz,
|
||||
criado_em timestamptz,
|
||||
-- Documento
|
||||
nome_original text,
|
||||
tipo_documento text,
|
||||
mime_type text,
|
||||
-- Share link (primeiro válido encontrado pro doc)
|
||||
share_token text,
|
||||
share_expira_em timestamptz
|
||||
)
|
||||
LANGUAGE plpgsql
|
||||
SECURITY DEFINER
|
||||
SET search_path = public
|
||||
AS $$
|
||||
DECLARE
|
||||
v_uid uuid;
|
||||
BEGIN
|
||||
v_uid := auth.uid();
|
||||
IF v_uid IS NULL THEN
|
||||
RAISE EXCEPTION 'Sessão inválida' USING ERRCODE = '28000';
|
||||
END IF;
|
||||
|
||||
RETURN QUERY
|
||||
SELECT
|
||||
s.id AS signature_id,
|
||||
s.documento_id AS documento_id,
|
||||
s.tenant_id AS tenant_id,
|
||||
s.signatario_tipo AS signatario_tipo,
|
||||
s.status AS status,
|
||||
s.ordem AS ordem,
|
||||
s.assinado_em AS assinado_em,
|
||||
s.criado_em AS criado_em,
|
||||
d.nome_original AS nome_original,
|
||||
d.tipo_documento AS tipo_documento,
|
||||
d.mime_type AS mime_type,
|
||||
sl.token AS share_token,
|
||||
sl.expira_em AS share_expira_em
|
||||
FROM public.document_signatures s
|
||||
JOIN public.documents d ON d.id = s.documento_id AND d.deleted_at IS NULL
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT token, expira_em
|
||||
FROM public.document_share_links
|
||||
WHERE documento_id = d.id
|
||||
AND ativo = true
|
||||
AND expira_em > now()
|
||||
AND usos < usos_max
|
||||
ORDER BY criado_em DESC
|
||||
LIMIT 1
|
||||
) sl ON true
|
||||
WHERE (
|
||||
-- signatario_id direto (quando registrado)
|
||||
s.signatario_id = v_uid
|
||||
OR
|
||||
-- Fallback: paciente pelo email (quando signatario_id veio NULL)
|
||||
s.signatario_email = (SELECT email FROM auth.users WHERE id = v_uid)
|
||||
OR
|
||||
-- Fallback: paciente pelo patient_id (documents.patient_id -> patients.user_id)
|
||||
d.patient_id IN (SELECT p.id FROM public.patients p WHERE p.user_id = v_uid)
|
||||
)
|
||||
AND (p_status IS NULL OR s.status = ANY (p_status))
|
||||
ORDER BY
|
||||
CASE s.status
|
||||
WHEN 'pendente' THEN 0
|
||||
WHEN 'enviado' THEN 1
|
||||
WHEN 'assinado' THEN 2
|
||||
WHEN 'recusado' THEN 3
|
||||
WHEN 'expirado' THEN 4
|
||||
ELSE 99
|
||||
END,
|
||||
s.criado_em DESC;
|
||||
END;
|
||||
$$;
|
||||
|
||||
COMMENT ON FUNCTION public.list_my_signatures(text[]) IS
|
||||
'Lista signatures do paciente logado (auth.uid()) cruzando por signatario_id, email ou patient.user_id. Inclui share_token pra link de assinatura.';
|
||||
|
||||
GRANT EXECUTE ON FUNCTION public.list_my_signatures(text[]) TO authenticated;
|
||||
|
||||
COMMIT;
|
||||
@@ -0,0 +1,74 @@
|
||||
-- ============================================================================
|
||||
-- Compliance CFP #6 — Consent forms extra (LGPD + Gravação) + LGPD amend
|
||||
-- ----------------------------------------------------------------------------
|
||||
-- Adiciona 2 templates globais novos exigidos pra completar a biblioteca de
|
||||
-- consent forms do ROADMAP item #1.2 #6:
|
||||
-- • termo_lgpd — Consentimento LGPD (tratamento de dados pessoais)
|
||||
-- • autorizacao_gravacao — Autorização de gravação de sessão
|
||||
--
|
||||
-- Também atualiza o template tcle_online existente pra incluir cláusula
|
||||
-- explícita de LGPD (estava mencionando criptografia mas não a Lei 13.709/2018
|
||||
-- nem direitos do titular).
|
||||
--
|
||||
-- Pré-requisito: migration 20260521000005_document_templates_consent_types.sql
|
||||
-- já aplicada (adiciona 'termo_lgpd' e 'autorizacao_gravacao' ao CHECK).
|
||||
-- ============================================================================
|
||||
|
||||
BEGIN;
|
||||
|
||||
-- ──────────────────────────────────────────────────────────────────────────
|
||||
-- 1. Termo de Consentimento LGPD (tratamento de dados pessoais)
|
||||
-- ──────────────────────────────────────────────────────────────────────────
|
||||
INSERT INTO public.document_templates (
|
||||
id, tenant_id, owner_id, nome_template, tipo, descricao,
|
||||
corpo_html, cabecalho_html, rodape_html,
|
||||
variaveis, is_global, ativo
|
||||
) VALUES (
|
||||
gen_random_uuid(), NULL, NULL,
|
||||
'Termo de Consentimento LGPD',
|
||||
'termo_lgpd',
|
||||
'Consentimento específico para tratamento de dados pessoais conforme Lei nº 13.709/2018 (LGPD).',
|
||||
E'<h2 style="text-align:center; margin-bottom:30px;">TERMO DE CONSENTIMENTO PARA TRATAMENTO DE DADOS PESSOAIS</h2>\n\n<p>Em conformidade com a <strong>Lei Geral de Proteção de Dados Pessoais — Lei nº 13.709/2018 (LGPD)</strong>, eu, <strong>{{paciente_nome}}</strong>, CPF nº <strong>{{paciente_cpf}}</strong>, declaro ter sido informado(a) e <strong>consinto livremente</strong> com o tratamento dos meus dados pessoais nos termos abaixo.</p>\n\n<h3>1. Controlador dos dados</h3>\n<p><strong>{{terapeuta_nome}}</strong>, Psicólogo(a) — CRP <strong>{{terapeuta_crp}}</strong>, atuando em <strong>{{clinica_nome}}</strong>, com endereço em <strong>{{clinica_endereco}}</strong>, atua como controlador dos dados pessoais coletados.</p>\n\n<h3>2. Dados tratados</h3>\n<p>Serão coletados e tratados os seguintes dados:</p>\n<ul>\n <li><strong>Identificação:</strong> nome, CPF, RG, data de nascimento, endereço, telefone, e-mail;</li>\n <li><strong>Dados sensíveis de saúde:</strong> histórico clínico, hipóteses diagnósticas, evolução terapêutica, prescrições, encaminhamentos (Art. 11 LGPD);</li>\n <li><strong>Dados de pagamento:</strong> valores, formas de pagamento, recibos emitidos;</li>\n <li><strong>Registros de atendimento:</strong> data, horário, modalidade e duração das sessões.</li>\n</ul>\n\n<h3>3. Finalidade e base legal</h3>\n<p>Os dados serão utilizados exclusivamente para:</p>\n<ul>\n <li><strong>Execução do contrato</strong> de prestação de serviços psicológicos (Art. 7º, V e Art. 11, II, "a" da LGPD);</li>\n <li>Cumprimento de <strong>obrigações legais e regulatórias</strong> (Resoluções CFP, retenção de prontuário por 5 anos — Art. 1º Res. CFP 001/2009);</li>\n <li>Proteção da <strong>vida e incolumidade física</strong> do titular ou de terceiros, quando necessário (Art. 11, II, "f" LGPD);</li>\n <li>Emissão de documentos solicitados (recibos, atestados, declarações).</li>\n</ul>\n\n<h3>4. Compartilhamento</h3>\n<p>Os dados <strong>não serão compartilhados</strong> com terceiros, exceto:</p>\n<ul>\n <li>Mediante <strong>autorização expressa</strong> do titular (ex: encaminhamentos);</li>\n <li>Por <strong>determinação judicial</strong> ou requisição legal de autoridade competente;</li>\n <li>Para <strong>processadores</strong> contratados (plataforma de prontuário eletrônico, serviços de armazenamento em nuvem), com cláusulas de confidencialidade e proteção equivalentes.</li>\n</ul>\n\n<h3>5. Armazenamento e retenção</h3>\n<p>Os dados serão mantidos pelo prazo mínimo de <strong>5 anos</strong> após o término do acompanhamento, conforme exigência do CFP (Resolução nº 001/2009), em ambiente eletrônico criptografado com controle de acesso restrito ao profissional responsável.</p>\n\n<h3>6. Direitos do titular (Art. 18 LGPD)</h3>\n<p>O(A) titular pode, a qualquer momento, solicitar ao controlador:</p>\n<ul>\n <li>Confirmação da existência de tratamento;</li>\n <li>Acesso aos seus dados;</li>\n <li>Correção de dados incompletos, inexatos ou desatualizados;</li>\n <li>Anonimização, bloqueio ou eliminação de dados desnecessários ou tratados em desconformidade;</li>\n <li>Portabilidade dos dados;</li>\n <li>Revogação deste consentimento, nos termos do §5º do Art. 8º (sem prejuízo do tratamento legalmente exigido).</li>\n</ul>\n\n<h3>7. Contato</h3>\n<p>Para exercer seus direitos ou esclarecer dúvidas: <strong>{{terapeuta_email}}</strong> · <strong>{{terapeuta_telefone}}</strong>.</p>\n\n<p style="margin-top:30px;">Declaro que <strong>li, compreendi e consinto</strong> livremente com o tratamento dos meus dados pessoais conforme descrito acima.</p>\n\n<p style="margin-top:20px;">{{cidade_estado}}, {{data_atual_extenso}}.</p>\n\n<div style="display:flex; justify-content:space-between; margin-top:80px;">\n <div style="text-align:center; width:45%;">\n <hr style="border:none; border-top:1px solid #333; margin-bottom:8px;" />\n <strong>{{paciente_nome}}</strong><br/>\n Titular dos dados — CPF: {{paciente_cpf}}\n </div>\n <div style="text-align:center; width:45%;">\n <hr style="border:none; border-top:1px solid #333; margin-bottom:8px;" />\n <strong>{{terapeuta_nome}}</strong><br/>\n Controlador — CRP {{terapeuta_crp}}\n </div>\n</div>',
|
||||
E'<div style="text-align:center;">\n <strong>{{clinica_nome}}</strong><br/>\n <span style="font-size:10pt; color:#666;">{{clinica_endereco}}</span>\n</div>',
|
||||
E'<div style="text-align:center; font-size:9pt; color:#999;">\n Documento regido pela Lei nº 13.709/2018 (LGPD) e pelo Código de Ética Profissional do Psicólogo.\n</div>',
|
||||
ARRAY['paciente_nome','paciente_cpf','terapeuta_nome','terapeuta_crp','terapeuta_email','terapeuta_telefone','cidade_estado','data_atual_extenso','clinica_nome','clinica_endereco'],
|
||||
true, true
|
||||
);
|
||||
|
||||
-- ──────────────────────────────────────────────────────────────────────────
|
||||
-- 2. Autorização para Gravação de Sessão
|
||||
-- ──────────────────────────────────────────────────────────────────────────
|
||||
INSERT INTO public.document_templates (
|
||||
id, tenant_id, owner_id, nome_template, tipo, descricao,
|
||||
corpo_html, cabecalho_html, rodape_html,
|
||||
variaveis, is_global, ativo
|
||||
) VALUES (
|
||||
gen_random_uuid(), NULL, NULL,
|
||||
'Autorização para Gravação de Sessão',
|
||||
'autorizacao_gravacao',
|
||||
'Autorização específica do paciente para gravação de áudio/vídeo das sessões (supervisão, ensino, registro clínico).',
|
||||
E'<h2 style="text-align:center; margin-bottom:30px;">AUTORIZAÇÃO PARA GRAVAÇÃO DE SESSÃO</h2>\n\n<p>Eu, <strong>{{paciente_nome}}</strong>, CPF nº <strong>{{paciente_cpf}}</strong>, declaro ter sido devidamente informado(a) pelo(a) psicólogo(a) <strong>{{terapeuta_nome}}</strong>, CRP <strong>{{terapeuta_crp}}</strong>, e <strong>AUTORIZO</strong> a gravação das sessões de atendimento psicológico nas condições abaixo.</p>\n\n<h3>1. Tipo de gravação</h3>\n<p>Modalidade autorizada: <strong>{{tipo_gravacao}}</strong> (áudio, vídeo ou ambos).</p>\n\n<h3>2. Finalidade</h3>\n<p>As gravações serão utilizadas exclusivamente para:</p>\n<ul>\n <li><strong>{{finalidade_gravacao}}</strong></li>\n</ul>\n<p>Finalidades comuns: registro clínico para análise posterior do profissional; supervisão técnica com supervisor identificado; uso didático em formação (com anonimização); pesquisa científica (mediante consentimento adicional específico).</p>\n\n<h3>3. Compartilhamento</h3>\n<p>As gravações são <strong>confidenciais</strong>. Não serão compartilhadas com terceiros, exceto quando:</p>\n<ul>\n <li>Houver autorização expressa e por escrito do(a) titular;</li>\n <li>Para fins de supervisão técnica, com o(a) supervisor(a) identificado(a) — <strong>{{supervisor_nome}}</strong> (quando aplicável);</li>\n <li>Anonimizadas, para fins didáticos ou de pesquisa (com novo consentimento específico).</li>\n</ul>\n\n<h3>4. Armazenamento e descarte</h3>\n<p>As gravações serão armazenadas em ambiente criptografado, com acesso restrito ao(à) profissional responsável, pelo prazo de <strong>{{prazo_retencao}}</strong>, após o qual serão definitivamente eliminadas, conforme a LGPD (Lei nº 13.709/2018).</p>\n\n<h3>5. Direitos do(a) paciente</h3>\n<ul>\n <li>Revogar esta autorização a qualquer tempo, com efeito sobre gravações futuras;</li>\n <li>Solicitar a eliminação imediata de gravações específicas;</li>\n <li>Solicitar cópia da gravação para fins próprios;</li>\n <li>Ser informado(a) sobre cada utilização (supervisão, pesquisa).</li>\n</ul>\n\n<h3>6. Considerações éticas</h3>\n<p>A presente autorização está em conformidade com o Código de Ética Profissional do Psicólogo, com a Resolução CFP nº 010/2005 (sigilo profissional) e com a Lei nº 13.709/2018 (LGPD). A negativa de gravação <strong>não prejudica</strong> o atendimento psicológico, que prosseguirá normalmente.</p>\n\n<p style="margin-top:30px;">Declaro que <strong>li, compreendi e autorizo</strong> a gravação das sessões nos termos acima.</p>\n\n<p style="margin-top:20px;">{{cidade_estado}}, {{data_atual_extenso}}.</p>\n\n<div style="display:flex; justify-content:space-between; margin-top:80px;">\n <div style="text-align:center; width:45%;">\n <hr style="border:none; border-top:1px solid #333; margin-bottom:8px;" />\n <strong>{{paciente_nome}}</strong><br/>\n CPF: {{paciente_cpf}}\n </div>\n <div style="text-align:center; width:45%;">\n <hr style="border:none; border-top:1px solid #333; margin-bottom:8px;" />\n <strong>{{terapeuta_nome}}</strong><br/>\n Psicólogo(a) — CRP {{terapeuta_crp}}\n </div>\n</div>',
|
||||
E'<div style="text-align:center;">\n <strong>{{clinica_nome}}</strong><br/>\n <span style="font-size:10pt; color:#666;">{{clinica_endereco}}</span>\n</div>',
|
||||
E'<div style="text-align:center; font-size:9pt; color:#999;">\n Autorização regida pelo Código de Ética do Psicólogo (CFP 010/2005) e pela Lei nº 13.709/2018 (LGPD).\n</div>',
|
||||
ARRAY['paciente_nome','paciente_cpf','terapeuta_nome','terapeuta_crp','tipo_gravacao','finalidade_gravacao','supervisor_nome','prazo_retencao','cidade_estado','data_atual_extenso','clinica_nome','clinica_endereco'],
|
||||
true, true
|
||||
);
|
||||
|
||||
-- ──────────────────────────────────────────────────────────────────────────
|
||||
-- 3. Amend tcle_online com cláusula LGPD explícita
|
||||
-- ----------------------------------------------------------------------------
|
||||
-- O template original (seed_015) menciona criptografia mas não cita a LGPD
|
||||
-- explicitamente nem os direitos do titular. Acrescenta uma seção 5.
|
||||
-- ──────────────────────────────────────────────────────────────────────────
|
||||
UPDATE public.document_templates
|
||||
SET corpo_html = REPLACE(
|
||||
corpo_html,
|
||||
'<h3>4. Limitações</h3>',
|
||||
E'<h3>5. Proteção de Dados (LGPD)</h3>\n<p>O atendimento online é regido pela <strong>Lei Geral de Proteção de Dados — Lei nº 13.709/2018 (LGPD)</strong>. Você tem direito a (Art. 18 LGPD): confirmar a existência de tratamento dos seus dados; acessar seus dados; corrigir dados incompletos ou inexatos; solicitar eliminação dos dados após o término do tratamento (resguardados os prazos legais de retenção do CFP); e revogar este consentimento a qualquer momento. Para exercê-los, contate <strong>{{terapeuta_email}}</strong>.</p>\n\n<h3>6. Limitações</h3>'
|
||||
),
|
||||
variaveis = ARRAY['paciente_nome','paciente_cpf','plataforma_online','terapeuta_nome','terapeuta_crp','terapeuta_email','cidade_estado','data_atual_extenso','clinica_nome','clinica_endereco'],
|
||||
descricao = 'Consentimento específico para atendimento psicológico por meios tecnológicos (Resolução CFP nº 11/2018) + cláusula LGPD.',
|
||||
updated_at = now()
|
||||
WHERE tipo = 'tcle_online' AND is_global = true;
|
||||
|
||||
COMMIT;
|
||||
@@ -107,12 +107,12 @@ Do `project_graphify_findings_20260504`:
|
||||
### Fase 3 — Gaps de MVP (Fase 1 do ROADMAP)
|
||||
|
||||
- [🟡] **Gateway Asaas (Fase A foundation 2026-05-21)** — Design doc + 2 migrations (tables + RLS) + client service + 3 Edge Function stubs (create-payment-record, cancel-payment, sync-payment). Schema: `asaas_customers`, `asaas_payments`, `asaas_webhook_events` + 5 colunas em `payment_settings`. Fase B (implementação real) depende de credenciais + decisão modelo negócio (A/B/C). Ver `development/02-auditoria/DESIGN_ASAAS_GATEWAY.md`.
|
||||
- [🟡] **Compliance CFP (#5/#8/#9 done · #6/#7 deferred · 2026-05-21)** —
|
||||
- [x] **Compliance CFP (#5/#6/#7/#8/#9 todos done · 2026-05-21)** —
|
||||
- #5 (registro profissional): migration `20260521000003_profiles_professional_registration.sql` — adiciona `professional_registration_type` (CHECK 8 conselhos) + `_number` + `_uf`.
|
||||
- #6 (consent forms editáveis): migration `20260521000005_document_templates_consent_types.sql` estende CHECK com `termo_lgpd` + `autorizacao_gravacao`. `seed_060_consent_forms_extra.sql` insere 2 templates novos (LGPD + Gravação) + UPDATE no `tcle_online` adicionando cláusula LGPD. Biblioteca completa: TCLE base, tcle_online (telehealth), autorizacao_menor, termo_sigilo, termo_lgpd, autorizacao_gravacao + UI já existente (`DocumentTemplatesPage` + `DocumentTemplateEditor`).
|
||||
- #7 (assinatura eletrônica no portal): 2 migrations RPC — `20260521000006` cria `sign_document_by_signature_id` + `sign_document_by_token` + `get_signable_document_by_token` (IP/UA capturados server-side via `inet_client_addr()` + `current_setting('request.headers')`); `20260521000007` cria `list_my_signatures` (cruzamento auth.uid() por 3 caminhos). `DocumentSignatures.service` estendido. `useDocumentSignatures` composable novo. `PortalDocumentos.vue` lista pendências do paciente logado. `SharedDocumentPage.vue` estendida com painel azul de assinatura (aviso LGPD + checkbox aceite + Assinar/Recusar). `DocumentSignatureDialog` (terapeuta-side, já existia) ganha checkbox "Gerar link público" + select de validade + bloco com URL gerado/copy.
|
||||
- #8 (nome social): JÁ INTEGRADO — `patients.nome_social` schema existia + UI em 7 arquivos.
|
||||
- #9 (especialidades): `20260521000004_specialties.sql` (tabela + profile_specialties M:N + RLS) + `seed_050_specialties.sql` (33 specialties) + `src/services/specialtiesService.js`.
|
||||
- **#6 consent forms DEFERRED**: schema `document_templates` existe; falta seed + UI editor + workflow.
|
||||
- **#7 assinatura DEFERRED**: schema `document_signatures` existe com status flow completo; falta portal UI pra paciente.
|
||||
- [ ] E2E Playwright crítico (#16)
|
||||
- [ ] Sentry (#18)
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
listSignatures,
|
||||
getSignatureStatus
|
||||
} from '@/services/DocumentSignatures.service'
|
||||
import { createShareLink, buildShareUrl } from '@/services/DocumentShareLinks.service'
|
||||
|
||||
const props = defineProps({
|
||||
visible: { type: Boolean, default: false },
|
||||
@@ -42,6 +43,11 @@ const TIPOS_SIGNATARIO = [
|
||||
const signatarios = ref([])
|
||||
const patientEmails = ref([])
|
||||
|
||||
// Geracao de share link p/ assinatura via portal/whatsapp
|
||||
const generateLink = ref(true)
|
||||
const linkExpiracaoHoras = ref(168) // 7 dias default
|
||||
const generatedShareUrl = ref('')
|
||||
|
||||
function addSignatario() {
|
||||
signatarios.value.push({ tipo: 'paciente', nome: '', email: '' })
|
||||
}
|
||||
@@ -81,6 +87,7 @@ function useEmail(email) {
|
||||
watch(() => props.visible, async (v) => {
|
||||
if (v && props.doc) {
|
||||
signatarios.value = []
|
||||
generatedShareUrl.value = ''
|
||||
loading.value = true
|
||||
try {
|
||||
const [sigs, status] = await Promise.all([
|
||||
@@ -99,6 +106,13 @@ watch(() => props.visible, async (v) => {
|
||||
}
|
||||
})
|
||||
|
||||
function copyShareUrl() {
|
||||
if (!generatedShareUrl.value) return
|
||||
navigator.clipboard.writeText(generatedShareUrl.value)
|
||||
.then(() => toast.add({ severity: 'success', summary: 'Link copiado', life: 1800 }))
|
||||
.catch(() => toast.add({ severity: 'warn', summary: 'Falha ao copiar', detail: 'Copie manualmente.', life: 2200 }))
|
||||
}
|
||||
|
||||
// ── Status badge ────────────────────────────────────────────
|
||||
|
||||
const statusColor = computed(() => {
|
||||
@@ -146,9 +160,39 @@ async function submit() {
|
||||
saving.value = true
|
||||
try {
|
||||
const result = await createSignatureRequests(props.doc.id, signatarios.value)
|
||||
|
||||
// Gera share link público quando habilitado — o paciente abre /shared/document/:token
|
||||
// e assina via fluxo público (RPC sign_document_by_token captura IP/UA server-side).
|
||||
if (generateLink.value) {
|
||||
try {
|
||||
const link = await createShareLink(props.doc.id, {
|
||||
expiracaoHoras: Number(linkExpiracaoHoras.value) || 168,
|
||||
usosMax: Math.max(signatarios.value.length * 3, 5)
|
||||
})
|
||||
generatedShareUrl.value = buildShareUrl(link.token)
|
||||
toast.add({
|
||||
severity: 'success',
|
||||
summary: 'Solicitação criada',
|
||||
detail: `${result.length} signatário(s). Link de assinatura gerado.`,
|
||||
life: 3500
|
||||
})
|
||||
} catch (linkErr) {
|
||||
toast.add({
|
||||
severity: 'warn',
|
||||
summary: 'Signatários criados, mas falhou o link',
|
||||
detail: linkErr?.message || 'Tente gerar o link na ação "Compartilhar".',
|
||||
life: 4500
|
||||
})
|
||||
}
|
||||
} else {
|
||||
toast.add({ severity: 'success', summary: 'Solicitação enviada', detail: `${result.length} signatário(s) adicionado(s).`, life: 3000 })
|
||||
emit('requested', result)
|
||||
emit('update:visible', false)
|
||||
}
|
||||
|
||||
emit('requested', { signatures: result, shareUrl: generatedShareUrl.value })
|
||||
|
||||
// Mantém dialog aberto se gerou link — pra terapeuta copiar.
|
||||
// Fecha automaticamente se não gerou link.
|
||||
if (!generatedShareUrl.value) emit('update:visible', false)
|
||||
} catch (e) {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || 'Falha ao solicitar assinatura.' })
|
||||
} finally {
|
||||
@@ -263,6 +307,49 @@ function close() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Toggle: gerar link público -->
|
||||
<div class="flex items-start gap-3 p-3 rounded-lg border border-blue-200 bg-blue-50/40">
|
||||
<Checkbox v-model="generateLink" :binary="true" inputId="cb-gen-link" class="mt-0.5" />
|
||||
<div class="flex-1">
|
||||
<label for="cb-gen-link" class="text-sm font-medium text-[var(--text-color)] cursor-pointer">
|
||||
Gerar link público para assinatura
|
||||
</label>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] mt-0.5">
|
||||
Cria um link em <code>/shared/document/<token></code> pra enviar via WhatsApp, e-mail ou copiar. O paciente assina sem precisar logar (IP, navegador e timestamp são registrados server-side).
|
||||
</div>
|
||||
<div v-if="generateLink" class="mt-2 flex items-center gap-2">
|
||||
<label class="text-xs text-[var(--text-color-secondary)]">Validade:</label>
|
||||
<Select
|
||||
v-model="linkExpiracaoHoras"
|
||||
:options="[
|
||||
{ value: 24, label: '24 horas' },
|
||||
{ value: 72, label: '3 dias' },
|
||||
{ value: 168, label: '7 dias' },
|
||||
{ value: 720, label: '30 dias' }
|
||||
]"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
class="!text-xs w-32"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Link gerado (após submit) -->
|
||||
<div v-if="generatedShareUrl" class="p-3 rounded-lg border border-emerald-200 bg-emerald-50/40">
|
||||
<div class="flex items-center gap-2 mb-2">
|
||||
<i class="pi pi-link text-emerald-600" />
|
||||
<div class="text-sm font-medium text-emerald-800">Link de assinatura gerado</div>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<InputText :modelValue="generatedShareUrl" readonly class="w-full !text-xs" />
|
||||
<Button icon="pi pi-copy" size="small" class="!h-8 shrink-0" v-tooltip.top="'Copiar link'" @click="copyShareUrl" />
|
||||
</div>
|
||||
<div class="text-[0.7rem] text-[var(--text-color-secondary)] mt-1.5">
|
||||
Envie este link para o(a) paciente. Eles podem assinar diretamente sem precisar criar conta.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Emails cadastrados do paciente -->
|
||||
<div class="p-3 rounded-lg border border-[var(--surface-border)] bg-[var(--surface-ground)]">
|
||||
<div class="text-xs font-semibold uppercase tracking-wider text-[var(--text-color-secondary)] mb-2">E-mails do paciente</div>
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Agência PSI
|
||||
|--------------------------------------------------------------------------
|
||||
| Arquivo: src/features/documents/composables/useDocumentSignatures.js
|
||||
| Composable Tipo A (thin wrapper) sobre DocumentSignatures.service.
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
import { ref } from 'vue';
|
||||
import {
|
||||
createSignatureRequests,
|
||||
listSignatures,
|
||||
getSignatureStatus,
|
||||
refuseSignature,
|
||||
signByPortal,
|
||||
signByToken,
|
||||
getSignableDocumentByToken,
|
||||
listMySignatures,
|
||||
hashDocument
|
||||
} from '@/services/DocumentSignatures.service';
|
||||
|
||||
export function useDocumentSignatures() {
|
||||
const signatures = ref([]);
|
||||
const loading = ref(false);
|
||||
const error = ref('');
|
||||
const status = ref(null); // { total, assinados, pendentes, status }
|
||||
|
||||
async function fetchForDocument(documentoId) {
|
||||
if (!documentoId) {
|
||||
signatures.value = [];
|
||||
status.value = null;
|
||||
return [];
|
||||
}
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const [list, st] = await Promise.all([
|
||||
listSignatures(documentoId),
|
||||
getSignatureStatus(documentoId)
|
||||
]);
|
||||
signatures.value = Array.isArray(list) ? list : [];
|
||||
status.value = st || null;
|
||||
return signatures.value;
|
||||
} catch (e) {
|
||||
error.value = e?.message || 'Falha ao carregar assinaturas.';
|
||||
signatures.value = [];
|
||||
status.value = null;
|
||||
throw e;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function requestSignatures(documentoId, signatarios = []) {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const rows = await createSignatureRequests(documentoId, signatarios);
|
||||
signatures.value = [...signatures.value, ...rows];
|
||||
return rows;
|
||||
} catch (e) {
|
||||
error.value = e?.message || 'Falha ao solicitar assinaturas.';
|
||||
throw e;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function sign(signatureId, { hashDocumento = null } = {}) {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const updated = await signByPortal(signatureId, hashDocumento);
|
||||
const idx = signatures.value.findIndex(s => s.id === signatureId);
|
||||
if (idx >= 0) signatures.value.splice(idx, 1, updated);
|
||||
return updated;
|
||||
} catch (e) {
|
||||
error.value = e?.message || 'Falha ao assinar documento.';
|
||||
throw e;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function refuse(signatureId) {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const updated = await refuseSignature(signatureId);
|
||||
const idx = signatures.value.findIndex(s => s.id === signatureId);
|
||||
if (idx >= 0) signatures.value.splice(idx, 1, updated);
|
||||
return updated;
|
||||
} catch (e) {
|
||||
error.value = e?.message || 'Falha ao recusar assinatura.';
|
||||
throw e;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function signWithToken(token, signatureId = null, { hashDocumento = null } = {}) {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
return await signByToken(token, signatureId, hashDocumento);
|
||||
} catch (e) {
|
||||
error.value = e?.message || 'Falha ao assinar via link.';
|
||||
throw e;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadMine(statusFilter = null) {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const rows = await listMySignatures(statusFilter);
|
||||
signatures.value = Array.isArray(rows) ? rows : [];
|
||||
return signatures.value;
|
||||
} catch (e) {
|
||||
error.value = e?.message || 'Falha ao carregar minhas assinaturas.';
|
||||
signatures.value = [];
|
||||
throw e;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadByToken(token) {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const payload = await getSignableDocumentByToken(token);
|
||||
if (!payload?.valid) {
|
||||
error.value = payload?.error === 'expired_or_invalid'
|
||||
? 'Link expirado ou inválido.'
|
||||
: payload?.error === 'document_not_found'
|
||||
? 'Documento não encontrado.'
|
||||
: 'Token inválido.';
|
||||
return null;
|
||||
}
|
||||
signatures.value = Array.isArray(payload.signatures) ? payload.signatures : [];
|
||||
return payload;
|
||||
} catch (e) {
|
||||
error.value = e?.message || 'Falha ao validar token.';
|
||||
throw e;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
signatures,
|
||||
status,
|
||||
loading,
|
||||
error,
|
||||
fetchForDocument,
|
||||
requestSignatures,
|
||||
sign,
|
||||
refuse,
|
||||
signWithToken,
|
||||
loadByToken,
|
||||
loadMine,
|
||||
hashDocument
|
||||
};
|
||||
}
|
||||
@@ -26,6 +26,11 @@ export default [
|
||||
items: [{ label: 'Sessões', icon: 'pi pi-fw pi-calendar', to: '/portal/sessoes' }]
|
||||
},
|
||||
|
||||
{
|
||||
label: 'Documentos',
|
||||
items: [{ label: 'Para assinar', icon: 'pi pi-fw pi-file-edit', to: '/portal/documentos' }]
|
||||
},
|
||||
|
||||
{
|
||||
label: 'Conta',
|
||||
items: [
|
||||
|
||||
@@ -27,6 +27,12 @@ export default {
|
||||
name: 'portal-sessoes',
|
||||
component: () => import('@/views/pages/portal/MinhasSessoes.vue')
|
||||
},
|
||||
{
|
||||
path: 'documentos',
|
||||
name: 'portal-documentos',
|
||||
component: () => import('@/views/pages/portal/PortalDocumentos.vue'),
|
||||
meta: { area: 'portal', requiresAuth: true }
|
||||
},
|
||||
|
||||
// ======================================================
|
||||
// 💳 MEU PLANO (assinatura pessoal do paciente)
|
||||
|
||||
@@ -170,3 +170,71 @@ export async function refuseSignature(signatureId) {
|
||||
if (error) throw error;
|
||||
return data;
|
||||
}
|
||||
|
||||
// ── Assinar via portal (paciente logado) ─────────────────────
|
||||
//
|
||||
// IP e user-agent são capturados SERVER-SIDE pela RPC via
|
||||
// inet_client_addr() e current_setting('request.headers'). O cliente
|
||||
// só passa o hash SHA-256 do PDF (gerado via hashDocument()) pra
|
||||
// garantir integridade do documento no momento da assinatura.
|
||||
//
|
||||
export async function signByPortal(signatureId, hashDocumento = null) {
|
||||
if (!signatureId) throw new Error('ID da assinatura inválido.');
|
||||
|
||||
const { data, error } = await supabase.rpc('sign_document_by_signature_id', {
|
||||
p_signature_id: signatureId,
|
||||
p_hash_documento: hashDocumento || null
|
||||
});
|
||||
if (error) throw error;
|
||||
return data;
|
||||
}
|
||||
|
||||
// ── Assinar via token público (share link) ──────────────────
|
||||
//
|
||||
// Para signatários não-logados acessando via /shared/document/:token.
|
||||
// p_signature_id é opcional — quando o documento tem múltiplos
|
||||
// signatários, identifica qual deles está assinando. Quando há apenas
|
||||
// um pendente, deixa null e o backend resolve.
|
||||
//
|
||||
export async function signByToken(token, signatureId = null, hashDocumento = null) {
|
||||
if (!token) throw new Error('Token inválido.');
|
||||
|
||||
const { data, error } = await supabase.rpc('sign_document_by_token', {
|
||||
p_token: token,
|
||||
p_signature_id: signatureId || null,
|
||||
p_hash_documento: hashDocumento || null
|
||||
});
|
||||
if (error) throw error;
|
||||
return data;
|
||||
}
|
||||
|
||||
// ── Listar minhas assinaturas (portal do paciente) ──────────
|
||||
//
|
||||
// Wrapper sobre RPC list_my_signatures. Resolve auth.uid() server-side
|
||||
// e cruza por signatario_id / email / patient.user_id pra encontrar
|
||||
// todas as assinaturas que pertencem ao usuário logado. Inclui
|
||||
// share_token p/ apontar direto pra /shared/document/:token.
|
||||
//
|
||||
export async function listMySignatures(statusFilter = null) {
|
||||
const { data, error } = await supabase.rpc('list_my_signatures', {
|
||||
p_status: Array.isArray(statusFilter) ? statusFilter : null
|
||||
});
|
||||
if (error) throw error;
|
||||
return data || [];
|
||||
}
|
||||
|
||||
// ── Pré-visualizar documento por token (sem assinar) ────────
|
||||
//
|
||||
// Usado pela página pública pra carregar info do documento +
|
||||
// signatários pendentes ANTES do click em "Assinar". Retorna
|
||||
// { valid, document, signatures, expira_em, usos_restantes }.
|
||||
//
|
||||
export async function getSignableDocumentByToken(token) {
|
||||
if (!token) throw new Error('Token inválido.');
|
||||
|
||||
const { data, error } = await supabase.rpc('get_signable_document_by_token', {
|
||||
p_token: token
|
||||
});
|
||||
if (error) throw error;
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
<!--
|
||||
|--------------------------------------------------------------------------
|
||||
| Agência PSI — Portal do Paciente · Documentos para assinatura
|
||||
|--------------------------------------------------------------------------
|
||||
| Lista as solicitações de assinatura do paciente logado:
|
||||
| - pendente/enviado → botão "Assinar agora" → /shared/document/:token
|
||||
| - assinado → mostra data + hash + IP (audit)
|
||||
| - recusado → mostra data + motivo (se houver)
|
||||
|--------------------------------------------------------------------------
|
||||
-->
|
||||
<script setup>
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useDocumentSignatures } from '@/features/documents/composables/useDocumentSignatures';
|
||||
|
||||
const router = useRouter();
|
||||
const { signatures, loading, error, loadMine } = useDocumentSignatures();
|
||||
|
||||
const statusFilter = ref('todos'); // todos | pendentes | assinados
|
||||
|
||||
const filtered = computed(() => {
|
||||
const all = signatures.value || [];
|
||||
if (statusFilter.value === 'pendentes') {
|
||||
return all.filter(s => s.status === 'pendente' || s.status === 'enviado');
|
||||
}
|
||||
if (statusFilter.value === 'assinados') {
|
||||
return all.filter(s => s.status === 'assinado');
|
||||
}
|
||||
return all;
|
||||
});
|
||||
|
||||
const counts = computed(() => {
|
||||
const all = signatures.value || [];
|
||||
return {
|
||||
total: all.length,
|
||||
pendentes: all.filter(s => s.status === 'pendente' || s.status === 'enviado').length,
|
||||
assinados: all.filter(s => s.status === 'assinado').length,
|
||||
recusados: all.filter(s => s.status === 'recusado').length
|
||||
};
|
||||
});
|
||||
|
||||
function fmtDate(iso) {
|
||||
if (!iso) return '—';
|
||||
const d = new Date(iso);
|
||||
return d.toLocaleDateString('pt-BR') + ' ' + d.toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
|
||||
function statusBadge(s) {
|
||||
const map = {
|
||||
pendente: { label: 'Pendente', class: 'bg-amber-100 text-amber-700 border-amber-200' },
|
||||
enviado: { label: 'Enviado', class: 'bg-blue-100 text-blue-700 border-blue-200' },
|
||||
assinado: { label: 'Assinado', class: 'bg-emerald-100 text-emerald-700 border-emerald-200' },
|
||||
recusado: { label: 'Recusado', class: 'bg-rose-100 text-rose-700 border-rose-200' },
|
||||
expirado: { label: 'Expirado', class: 'bg-zinc-100 text-zinc-600 border-zinc-200' }
|
||||
};
|
||||
return map[s] || { label: s, class: 'bg-zinc-100 text-zinc-600' };
|
||||
}
|
||||
|
||||
function openSignFlow(sig) {
|
||||
if (!sig.share_token) {
|
||||
// Sem share link válido — terapeuta precisa gerar um. Mostra aviso.
|
||||
return;
|
||||
}
|
||||
router.push({ name: 'shared.document', params: { token: sig.share_token } });
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
loadMine();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="p-4 md:p-6">
|
||||
<!-- Header -->
|
||||
<div class="mb-6 overflow-hidden rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-card)]">
|
||||
<div class="relative p-6">
|
||||
<div class="pointer-events-none absolute inset-0 opacity-80">
|
||||
<div class="absolute -top-16 -right-16 h-52 w-52 rounded-full bg-indigo-400/10 blur-3xl" />
|
||||
<div class="absolute bottom-0 left-10 h-44 w-44 rounded-full bg-emerald-400/10 blur-3xl" />
|
||||
</div>
|
||||
|
||||
<div class="relative flex items-center gap-4">
|
||||
<div class="grid h-14 w-14 place-items-center rounded-2xl bg-[var(--primary-color)]/10 text-[var(--primary-color)]">
|
||||
<i class="pi pi-file-edit text-2xl" />
|
||||
</div>
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="text-2xl font-semibold leading-none">Documentos para assinatura</div>
|
||||
<div class="mt-2 text-sm text-color-secondary">
|
||||
Termos e documentos solicitados pelo(a) seu(sua) terapeuta. Você pode assinar pelo link enviado ou clicar em "Assinar agora".
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- KPIs -->
|
||||
<div class="relative mt-6 grid grid-cols-2 gap-3 md:grid-cols-4">
|
||||
<button
|
||||
:class="['rounded-xl border p-3 text-left transition', statusFilter === 'todos' ? 'border-[var(--primary-color)] bg-[var(--primary-color)]/5' : 'border-[var(--surface-border)] hover:border-[var(--primary-color)]/40']"
|
||||
@click="statusFilter = 'todos'"
|
||||
>
|
||||
<div class="text-[0.7rem] uppercase tracking-wide text-color-secondary">Total</div>
|
||||
<div class="mt-1 text-xl font-bold">{{ counts.total }}</div>
|
||||
</button>
|
||||
<button
|
||||
:class="['rounded-xl border p-3 text-left transition', statusFilter === 'pendentes' ? 'border-amber-400 bg-amber-50/50' : 'border-[var(--surface-border)] hover:border-amber-300']"
|
||||
@click="statusFilter = 'pendentes'"
|
||||
>
|
||||
<div class="text-[0.7rem] uppercase tracking-wide text-color-secondary">Pendentes</div>
|
||||
<div class="mt-1 text-xl font-bold text-amber-700">{{ counts.pendentes }}</div>
|
||||
</button>
|
||||
<button
|
||||
:class="['rounded-xl border p-3 text-left transition', statusFilter === 'assinados' ? 'border-emerald-400 bg-emerald-50/50' : 'border-[var(--surface-border)] hover:border-emerald-300']"
|
||||
@click="statusFilter = 'assinados'"
|
||||
>
|
||||
<div class="text-[0.7rem] uppercase tracking-wide text-color-secondary">Assinados</div>
|
||||
<div class="mt-1 text-xl font-bold text-emerald-700">{{ counts.assinados }}</div>
|
||||
</button>
|
||||
<div class="rounded-xl border border-[var(--surface-border)] p-3">
|
||||
<div class="text-[0.7rem] uppercase tracking-wide text-color-secondary">Recusados</div>
|
||||
<div class="mt-1 text-xl font-bold text-rose-700">{{ counts.recusados }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Loading -->
|
||||
<div v-if="loading && !signatures.length" class="flex flex-col items-center justify-center py-20">
|
||||
<i class="pi pi-spinner pi-spin text-3xl text-color-secondary mb-3" />
|
||||
<p class="text-sm text-color-secondary">Carregando seus documentos…</p>
|
||||
</div>
|
||||
|
||||
<!-- Erro -->
|
||||
<div v-else-if="error" class="rounded-xl border border-rose-200 bg-rose-50/50 p-4 text-sm text-rose-700">
|
||||
<i class="pi pi-exclamation-triangle mr-2" />{{ error }}
|
||||
</div>
|
||||
|
||||
<!-- Empty -->
|
||||
<div v-else-if="!filtered.length" class="flex flex-col items-center justify-center rounded-2xl border border-dashed border-[var(--surface-border)] bg-[var(--surface-card)] py-16">
|
||||
<div class="mx-auto mb-4 grid h-16 w-16 place-items-center rounded-2xl bg-[var(--primary-color)]/10 text-[var(--primary-color)]">
|
||||
<i class="pi pi-inbox text-2xl" />
|
||||
</div>
|
||||
<div class="text-lg font-semibold">Nenhum documento {{ statusFilter === 'pendentes' ? 'pendente' : statusFilter === 'assinados' ? 'assinado' : '' }} no momento</div>
|
||||
<div class="mt-2 text-sm text-color-secondary">Quando seu(sua) terapeuta solicitar assinatura, o documento aparecerá aqui.</div>
|
||||
</div>
|
||||
|
||||
<!-- Lista -->
|
||||
<div v-else class="space-y-3">
|
||||
<div
|
||||
v-for="sig in filtered"
|
||||
:key="sig.signature_id"
|
||||
class="overflow-hidden rounded-xl border border-[var(--surface-border)] bg-[var(--surface-card)] transition hover:border-[var(--primary-color)]/30"
|
||||
>
|
||||
<div class="flex items-center gap-4 p-4">
|
||||
<!-- Icon -->
|
||||
<div class="grid h-12 w-12 shrink-0 place-items-center rounded-lg bg-blue-50">
|
||||
<i :class="sig.mime_type === 'application/pdf' ? 'pi pi-file-pdf text-red-500' : 'pi pi-file text-blue-500'" class="text-xl" />
|
||||
</div>
|
||||
|
||||
<!-- Info -->
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<div class="text-sm font-semibold text-[var(--text-color)] truncate">{{ sig.nome_original || 'Documento sem nome' }}</div>
|
||||
<span :class="['inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[0.65rem] font-medium', statusBadge(sig.status).class]">
|
||||
{{ statusBadge(sig.status).label }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-1 text-xs text-color-secondary">
|
||||
Tipo: <span class="font-medium">{{ sig.tipo_documento || 'outro' }}</span>
|
||||
· Solicitado em {{ fmtDate(sig.criado_em) }}
|
||||
<template v-if="sig.assinado_em">
|
||||
· Assinado em <span class="font-medium text-emerald-700">{{ fmtDate(sig.assinado_em) }}</span>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Ação -->
|
||||
<div class="shrink-0">
|
||||
<button
|
||||
v-if="sig.status === 'pendente' || sig.status === 'enviado'"
|
||||
:disabled="!sig.share_token"
|
||||
:title="!sig.share_token ? 'Link não gerado pelo terapeuta. Solicite que ele(a) compartilhe novamente.' : ''"
|
||||
class="inline-flex items-center gap-2 rounded-lg bg-[var(--primary-color)] px-3 py-2 text-xs font-semibold text-white shadow-sm transition hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
@click="openSignFlow(sig)"
|
||||
>
|
||||
<i class="pi pi-pencil" />
|
||||
Assinar agora
|
||||
</button>
|
||||
<div v-else-if="sig.status === 'assinado'" class="text-xs text-emerald-700 font-medium flex items-center gap-1">
|
||||
<i class="pi pi-check-circle" />
|
||||
Concluído
|
||||
</div>
|
||||
<div v-else class="text-xs text-color-secondary">—</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -9,9 +9,10 @@
|
||||
|--------------------------------------------------------------------------
|
||||
-->
|
||||
<script setup>
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { ref, computed, onMounted } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { validateShareToken } from '@/services/DocumentShareLinks.service'
|
||||
import { getSignableDocumentByToken, signByToken, hashDocument, refuseSignature } from '@/services/DocumentSignatures.service'
|
||||
import { supabase } from '@/lib/supabase/client'
|
||||
|
||||
const route = useRoute()
|
||||
@@ -21,6 +22,45 @@ const error = ref(null)
|
||||
const doc = ref(null)
|
||||
const previewUrl = ref('')
|
||||
|
||||
// Assinaturas associadas ao share link (vazio = só visualização)
|
||||
const signablePayload = ref(null) // { valid, document, signatures, expira_em, usos_restantes }
|
||||
const signing = ref(false)
|
||||
const signError = ref('')
|
||||
const signSuccess = ref(false)
|
||||
const refused = ref(false)
|
||||
const acceptedTerms = ref(false)
|
||||
const selectedSignatureId = ref(null) // pra desambiguar multi-signatário
|
||||
|
||||
const pendingSignatures = computed(() => {
|
||||
const list = signablePayload.value?.signatures || []
|
||||
return list.filter(s => s.status === 'pendente' || s.status === 'enviado')
|
||||
})
|
||||
|
||||
const completedSignatures = computed(() => {
|
||||
const list = signablePayload.value?.signatures || []
|
||||
return list.filter(s => s.status === 'assinado')
|
||||
})
|
||||
|
||||
const hasSignatureFlow = computed(() => {
|
||||
const list = signablePayload.value?.signatures || []
|
||||
return list.length > 0
|
||||
})
|
||||
|
||||
const activeSignature = computed(() => {
|
||||
if (pendingSignatures.value.length === 0) return null
|
||||
if (pendingSignatures.value.length === 1) return pendingSignatures.value[0]
|
||||
return pendingSignatures.value.find(s => s.id === selectedSignatureId.value) || null
|
||||
})
|
||||
|
||||
async function fetchSignedPreviewUrl(documentLike) {
|
||||
const bucket = documentLike.storage_bucket || 'documents'
|
||||
const { data, error: storageErr } = await supabase.storage
|
||||
.from(bucket)
|
||||
.createSignedUrl(documentLike.bucket_path, 300)
|
||||
if (storageErr) throw storageErr
|
||||
return data?.signedUrl || ''
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
const token = route.params.token
|
||||
if (!token) {
|
||||
@@ -30,23 +70,26 @@ onMounted(async () => {
|
||||
}
|
||||
|
||||
try {
|
||||
// 1) Tenta carregar via RPC enriquecida (inclui signatures pendentes do doc).
|
||||
const payload = await getSignableDocumentByToken(token)
|
||||
if (payload?.valid) {
|
||||
signablePayload.value = payload
|
||||
doc.value = payload.document
|
||||
previewUrl.value = await fetchSignedPreviewUrl(payload.document)
|
||||
// Auto-selecionar única assinatura pendente
|
||||
const pending = (payload.signatures || []).filter(s => s.status === 'pendente' || s.status === 'enviado')
|
||||
if (pending.length === 1) selectedSignatureId.value = pending[0].id
|
||||
} else {
|
||||
// Fallback: rota legacy (só visualização) — usa o validateShareToken antigo
|
||||
const result = await validateShareToken(token)
|
||||
if (!result?.document) {
|
||||
error.value = 'Este link expirou, atingiu o limite de acessos ou é inválido.'
|
||||
loading.value = false
|
||||
return
|
||||
}
|
||||
|
||||
doc.value = result.document
|
||||
|
||||
// Gerar URL assinada para download/visualizacao
|
||||
const bucket = result.document.storage_bucket || 'documents'
|
||||
const { data, error: storageErr } = await supabase.storage
|
||||
.from(bucket)
|
||||
.createSignedUrl(result.document.bucket_path, 300) // 5 min
|
||||
|
||||
if (storageErr) throw storageErr
|
||||
previewUrl.value = data?.signedUrl || ''
|
||||
previewUrl.value = await fetchSignedPreviewUrl(result.document)
|
||||
}
|
||||
} catch (e) {
|
||||
error.value = e?.message || 'Erro ao acessar o documento.'
|
||||
} finally {
|
||||
@@ -65,6 +108,66 @@ function downloadFile() {
|
||||
document.body.removeChild(a)
|
||||
}
|
||||
|
||||
// Hash SHA-256 do PDF baixado do storage. Garante integridade do que foi
|
||||
// efetivamente assinado (não cliente-side mutável).
|
||||
async function computeDocHash() {
|
||||
if (!previewUrl.value) return null
|
||||
try {
|
||||
const res = await fetch(previewUrl.value)
|
||||
const buf = await res.arrayBuffer()
|
||||
return await hashDocument(buf)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
async function onAssinar() {
|
||||
if (!acceptedTerms.value || signing.value) return
|
||||
if (pendingSignatures.value.length > 1 && !selectedSignatureId.value) {
|
||||
signError.value = 'Selecione qual signatário você é.'
|
||||
return
|
||||
}
|
||||
signing.value = true
|
||||
signError.value = ''
|
||||
try {
|
||||
const hash = await computeDocHash()
|
||||
await signByToken(
|
||||
route.params.token,
|
||||
selectedSignatureId.value || activeSignature.value?.id || null,
|
||||
hash
|
||||
)
|
||||
signSuccess.value = true
|
||||
// Recarrega payload pra refletir novo status
|
||||
const refreshed = await getSignableDocumentByToken(route.params.token)
|
||||
if (refreshed?.valid) signablePayload.value = refreshed
|
||||
} catch (e) {
|
||||
signError.value = e?.message || 'Falha ao registrar a assinatura.'
|
||||
} finally {
|
||||
signing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function onRecusar() {
|
||||
if (signing.value) return
|
||||
if (!activeSignature.value?.id) {
|
||||
signError.value = 'Não foi possível identificar a assinatura.'
|
||||
return
|
||||
}
|
||||
if (!confirm('Deseja realmente recusar a assinatura deste documento? Esta ação é registrada e o(a) terapeuta será notificado(a).')) return
|
||||
signing.value = true
|
||||
signError.value = ''
|
||||
try {
|
||||
await refuseSignature(activeSignature.value.id)
|
||||
refused.value = true
|
||||
const refreshed = await getSignableDocumentByToken(route.params.token)
|
||||
if (refreshed?.valid) signablePayload.value = refreshed
|
||||
} catch (e) {
|
||||
signError.value = e?.message || 'Falha ao recusar a assinatura.'
|
||||
} finally {
|
||||
signing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const isPdf = () => doc.value?.mime_type === 'application/pdf'
|
||||
const isImage = () => String(doc.value?.mime_type || '').startsWith('image/')
|
||||
</script>
|
||||
@@ -128,6 +231,113 @@ const isImage = () => String(doc.value?.mime_type || '').startsWith('image/')
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Painel de assinatura (só aparece se há signatures associadas) -->
|
||||
<div v-if="hasSignatureFlow" class="border-t border-gray-200 bg-blue-50/30 p-5">
|
||||
<!-- Estado: já assinou nesta sessão -->
|
||||
<div v-if="signSuccess" class="flex items-start gap-3 rounded-lg border border-emerald-200 bg-emerald-50 p-4">
|
||||
<i class="pi pi-check-circle text-2xl text-emerald-600 mt-0.5" />
|
||||
<div>
|
||||
<div class="text-sm font-semibold text-emerald-800">Assinatura registrada com sucesso!</div>
|
||||
<div class="mt-1 text-xs text-emerald-700">Sua assinatura foi registrada com IP, data/hora e hash do documento. O(a) terapeuta foi notificado(a).</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Estado: recusou -->
|
||||
<div v-else-if="refused" class="flex items-start gap-3 rounded-lg border border-zinc-200 bg-zinc-50 p-4">
|
||||
<i class="pi pi-times-circle text-2xl text-zinc-600 mt-0.5" />
|
||||
<div>
|
||||
<div class="text-sm font-semibold text-zinc-800">Assinatura recusada</div>
|
||||
<div class="mt-1 text-xs text-zinc-700">Sua recusa foi registrada. O(a) terapeuta será informado(a) e poderá entrar em contato.</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Estado: tem pendência -->
|
||||
<div v-else-if="pendingSignatures.length > 0">
|
||||
<div class="mb-3 flex items-center gap-2">
|
||||
<i class="pi pi-pencil text-blue-600" />
|
||||
<div class="text-sm font-semibold text-gray-800">Assinatura solicitada</div>
|
||||
</div>
|
||||
|
||||
<!-- Seleção de signatário (multi) -->
|
||||
<div v-if="pendingSignatures.length > 1" class="mb-3">
|
||||
<label class="block text-xs font-medium text-gray-700 mb-1">Selecione quem você é:</label>
|
||||
<select
|
||||
v-model="selectedSignatureId"
|
||||
class="w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm focus:border-blue-500 focus:outline-none"
|
||||
>
|
||||
<option :value="null">— escolha —</option>
|
||||
<option
|
||||
v-for="sig in pendingSignatures"
|
||||
:key="sig.id"
|
||||
:value="sig.id"
|
||||
>
|
||||
{{ sig.signatario_nome || sig.signatario_email || sig.signatario_tipo }}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- Aviso LGPD/CFP -->
|
||||
<div class="mb-3 rounded-md border border-blue-200 bg-blue-50 p-3 text-xs text-blue-800">
|
||||
<i class="pi pi-info-circle mr-1" />
|
||||
Ao assinar, ficarão registrados: data/hora, seu endereço IP, navegador e hash criptográfico (SHA-256) do documento. Esses dados garantem integridade e autenticidade conforme a LGPD (Lei nº 13.709/2018) e o Código de Ética do Psicólogo.
|
||||
</div>
|
||||
|
||||
<!-- Checkbox aceite -->
|
||||
<label class="flex items-start gap-2 cursor-pointer mb-3">
|
||||
<input
|
||||
v-model="acceptedTerms"
|
||||
type="checkbox"
|
||||
class="mt-0.5 h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
|
||||
/>
|
||||
<span class="text-sm text-gray-700">
|
||||
Li e compreendi o documento acima e <strong>concordo em assiná-lo eletronicamente</strong>.
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<!-- Erro -->
|
||||
<div v-if="signError" class="mb-3 rounded-md border border-rose-200 bg-rose-50 p-2 text-xs text-rose-700">
|
||||
<i class="pi pi-exclamation-triangle mr-1" />{{ signError }}
|
||||
</div>
|
||||
|
||||
<!-- Ações -->
|
||||
<div class="flex flex-col gap-2 sm:flex-row sm:justify-end">
|
||||
<button
|
||||
:disabled="signing"
|
||||
class="rounded-lg border border-rose-300 bg-white px-4 py-2 text-sm font-medium text-rose-700 transition hover:bg-rose-50 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
@click="onRecusar"
|
||||
>
|
||||
<i class="pi pi-times mr-1" />
|
||||
Recusar
|
||||
</button>
|
||||
<button
|
||||
:disabled="!acceptedTerms || signing"
|
||||
class="inline-flex items-center justify-center gap-2 rounded-lg bg-blue-600 px-5 py-2 text-sm font-semibold text-white shadow-sm transition hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
@click="onAssinar"
|
||||
>
|
||||
<i v-if="signing" class="pi pi-spinner pi-spin" />
|
||||
<i v-else class="pi pi-check" />
|
||||
{{ signing ? 'Registrando…' : 'Assinar agora' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Estado: tudo assinado -->
|
||||
<div v-else class="flex items-start gap-3 rounded-lg border border-emerald-200 bg-emerald-50 p-4">
|
||||
<i class="pi pi-check-circle text-2xl text-emerald-600 mt-0.5" />
|
||||
<div>
|
||||
<div class="text-sm font-semibold text-emerald-800">Documento já assinado</div>
|
||||
<div class="mt-1 text-xs text-emerald-700">
|
||||
<template v-if="completedSignatures.length">
|
||||
Última assinatura registrada em {{ new Date(completedSignatures[completedSignatures.length - 1].assinado_em).toLocaleString('pt-BR') }}.
|
||||
</template>
|
||||
<template v-else>
|
||||
Sem assinaturas pendentes para este documento.
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Footer -->
|
||||
<div class="p-3 text-center text-xs text-gray-400 border-t border-gray-200">
|
||||
Compartilhado com segurança via AgênciaPSI
|
||||
|
||||
Reference in New Issue
Block a user