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:
@@ -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 {
|
||||
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
|
||||
// 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
|
||||
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) {
|
||||
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