compliance CFP #7: portal + fluxo de assinatura no SharedDocumentPage
ROADMAP #1.2 #7 — Assinatura eletronica no portal. Migration 20260521000007 cria RPC list_my_signatures (SECURITY DEFINER) que cruza auth.uid() por 3 caminhos (signatario_id, signatario_email, patient.user_id) e devolve solicitacoes pendentes + share_token pra link de assinatura. service.listMySignatures wrappa a RPC. Composable useDocumentSignatures ganha loadMine(). PortalDocumentos.vue (nova) — lista signatures do paciente logado com KPIs (total/pendentes/assinados/recusados), filtro, e botao "Assinar agora" que navega pra /shared/document/:token. Item no portal.menu "Documentos > Para assinar". SharedDocumentPage.vue estendida: agora chama getSignableDocumentBy Token primeiro (RPC nova). Quando o documento tem signatures pendentes, mostra painel azul abaixo do preview com: - Aviso LGPD/CFP explicando o que sera registrado (IP/UA/timestamp/hash) - Checkbox aceite obrigatorio - Selecao de signatario quando multi-signatario - Botoes Assinar/Recusar com loading state - Computacao SHA-256 server-fetched antes do click Fluxo: terapeuta gera doc -> cria signature + share_link -> link e listado em /portal/documentos -> paciente clica -> /shared/document/ :token mostra doc + painel -> aceite -> assinatura registrada via RPC sign_document_by_token (IP/UA capturados server-side). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -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;
|
||||||
@@ -15,6 +15,7 @@ import {
|
|||||||
signByPortal,
|
signByPortal,
|
||||||
signByToken,
|
signByToken,
|
||||||
getSignableDocumentByToken,
|
getSignableDocumentByToken,
|
||||||
|
listMySignatures,
|
||||||
hashDocument
|
hashDocument
|
||||||
} from '@/services/DocumentSignatures.service';
|
} from '@/services/DocumentSignatures.service';
|
||||||
|
|
||||||
@@ -110,6 +111,22 @@ export function useDocumentSignatures() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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) {
|
async function loadByToken(token) {
|
||||||
loading.value = true;
|
loading.value = true;
|
||||||
error.value = '';
|
error.value = '';
|
||||||
@@ -144,6 +161,7 @@ export function useDocumentSignatures() {
|
|||||||
refuse,
|
refuse,
|
||||||
signWithToken,
|
signWithToken,
|
||||||
loadByToken,
|
loadByToken,
|
||||||
|
loadMine,
|
||||||
hashDocument
|
hashDocument
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,6 +26,11 @@ export default [
|
|||||||
items: [{ label: 'Sessões', icon: 'pi pi-fw pi-calendar', to: '/portal/sessoes' }]
|
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',
|
label: 'Conta',
|
||||||
items: [
|
items: [
|
||||||
|
|||||||
@@ -27,6 +27,12 @@ export default {
|
|||||||
name: 'portal-sessoes',
|
name: 'portal-sessoes',
|
||||||
component: () => import('@/views/pages/portal/MinhasSessoes.vue')
|
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)
|
// 💳 MEU PLANO (assinatura pessoal do paciente)
|
||||||
|
|||||||
@@ -208,6 +208,21 @@ export async function signByToken(token, signatureId = null, hashDocumento = nul
|
|||||||
return data;
|
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) ────────
|
// ── Pré-visualizar documento por token (sem assinar) ────────
|
||||||
//
|
//
|
||||||
// Usado pela página pública pra carregar info do documento +
|
// Usado pela página pública pra carregar info do documento +
|
||||||
|
|||||||
@@ -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>
|
<script setup>
|
||||||
import { ref, onMounted } from 'vue'
|
import { ref, computed, onMounted } from 'vue'
|
||||||
import { useRoute } from 'vue-router'
|
import { useRoute } from 'vue-router'
|
||||||
import { validateShareToken } from '@/services/DocumentShareLinks.service'
|
import { validateShareToken } from '@/services/DocumentShareLinks.service'
|
||||||
|
import { getSignableDocumentByToken, signByToken, hashDocument, refuseSignature } from '@/services/DocumentSignatures.service'
|
||||||
import { supabase } from '@/lib/supabase/client'
|
import { supabase } from '@/lib/supabase/client'
|
||||||
|
|
||||||
const route = useRoute()
|
const route = useRoute()
|
||||||
@@ -21,6 +22,45 @@ const error = ref(null)
|
|||||||
const doc = ref(null)
|
const doc = ref(null)
|
||||||
const previewUrl = ref('')
|
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 () => {
|
onMounted(async () => {
|
||||||
const token = route.params.token
|
const token = route.params.token
|
||||||
if (!token) {
|
if (!token) {
|
||||||
@@ -30,23 +70,26 @@ onMounted(async () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await validateShareToken(token)
|
// 1) Tenta carregar via RPC enriquecida (inclui signatures pendentes do doc).
|
||||||
if (!result?.document) {
|
const payload = await getSignableDocumentByToken(token)
|
||||||
error.value = 'Este link expirou, atingiu o limite de acessos ou é inválido.'
|
if (payload?.valid) {
|
||||||
loading.value = false
|
signablePayload.value = payload
|
||||||
return
|
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
|
||||||
|
previewUrl.value = await fetchSignedPreviewUrl(result.document)
|
||||||
}
|
}
|
||||||
|
|
||||||
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 || ''
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
error.value = e?.message || 'Erro ao acessar o documento.'
|
error.value = e?.message || 'Erro ao acessar o documento.'
|
||||||
} finally {
|
} finally {
|
||||||
@@ -65,6 +108,66 @@ function downloadFile() {
|
|||||||
document.body.removeChild(a)
|
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 isPdf = () => doc.value?.mime_type === 'application/pdf'
|
||||||
const isImage = () => String(doc.value?.mime_type || '').startsWith('image/')
|
const isImage = () => String(doc.value?.mime_type || '').startsWith('image/')
|
||||||
</script>
|
</script>
|
||||||
@@ -128,6 +231,113 @@ const isImage = () => String(doc.value?.mime_type || '').startsWith('image/')
|
|||||||
</div>
|
</div>
|
||||||
</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 -->
|
<!-- Footer -->
|
||||||
<div class="p-3 text-center text-xs text-gray-400 border-t border-gray-200">
|
<div class="p-3 text-center text-xs text-gray-400 border-t border-gray-200">
|
||||||
Compartilhado com segurança via AgênciaPSI
|
Compartilhado com segurança via AgênciaPSI
|
||||||
|
|||||||
Reference in New Issue
Block a user