Sessoes 6cont-10: hardening em 6 areas + scan completo do SaaS

Continuacao de 7c20b51. Esta etapa fechou TODA revisao senior do SaaS
(15 areas auditadas) + refator parcial de pacientes.

Ver commit.md para descricao completa por sessao.

# Estado final do projeto
- A# auditoria abertos: 1 (A#31 Deploy real)
- V# verificacoes abertos: 14 (todos medios/baixos adiados com plano)
- Criticos: 0
- Altos: 0
- Vitest: 208/208 (era 192, +16 nos novos composables)
- SQL integration: 33/33
- E2E (Playwright): 5/5
- Areas auditadas: 15

# Highlights
- Documentos 100% fechado (V#50/51/52: portal-paciente policy + content_sha256 + 4 cron jobs retention)
- Tenants V#1 P0: tenant_invites com RLS off + 0 policies (mesmo padrao A#30)
- Calendario 100% fechado: feriados WITH CHECK
- Addons V#1 P0 (dinheiro): addon_transactions WITH CHECK saas_admin
- Central SaaS V#1: faq write so saas_admin (era tenant_admin)
- Servicos/Prontuarios 100% fechado: services/medicos/insurance_plans + cascades
- Pacientes V#9: 2 composables novos (useCep, usePatientSupportContacts) + repo estendido + script extraido (template intocado, fica para quando houver E2E)

# 8 migrations novas neste commit
- 20260419000011_documents_portal_patient_policy.sql
- 20260419000012_documents_content_hash.sql
- 20260419000013_cron_retention_jobs.sql
- 20260419000014_financial_security_hardening.sql
- 20260419000015_communication_security_hardening.sql
- 20260419000016_tenants_calendario_hardening.sql
- 20260419000017_addons_central_saas_hardening.sql
- 20260419000018_servicos_prontuarios_hardening.sql

Total acumulado: 18 migrations (Sessoes 1-10).

# A#31 reformulado pra proxima sessao
"Deploy real" muda escopo: como nao ha cloud Supabase nem secrets reais
ainda (MVP), proxima sessao vira "Preparacao completa pra deploy" (DEPLOY.md,
validar migrations num container limpo, audit edge functions, listar env vars,
script db.cjs deploy-check).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Leonardo
2026-04-19 22:00:06 -03:00
parent 7c20b518d4
commit d6eb992f71
18 changed files with 1699 additions and 313 deletions
@@ -0,0 +1,67 @@
/**
* useCep.spec.js — V#9 (composable extraído)
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
const fetchMock = vi.fn();
globalThis.fetch = fetchMock;
const { useCep } = await import('../useCep.js');
beforeEach(() => fetchMock.mockReset());
afterEach(() => fetchMock.mockReset());
describe('useCep — busca ViaCEP', () => {
it('retorna null se CEP tem menos de 8 dígitos (no-op)', async () => {
const { fetchCep } = useCep();
expect(await fetchCep('123')).toBe(null);
expect(await fetchCep('')).toBe(null);
expect(await fetchCep(null)).toBe(null);
expect(fetchMock).not.toHaveBeenCalled();
});
it('aceita CEP com máscara (digitsOnly normaliza)', async () => {
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ localidade: 'São Paulo', uf: 'SP', logradouro: 'Av Paulista', bairro: 'Bela Vista', complemento: '' }) });
const { fetchCep } = useCep();
const r = await fetchCep('01310-100');
expect(r).toEqual({
cidade: 'São Paulo',
uf: 'SP',
bairro: 'Bela Vista',
endereco: 'Av Paulista',
complemento: ''
});
expect(fetchMock).toHaveBeenCalledWith('https://viacep.com.br/ws/01310100/json/');
});
it('retorna null se ViaCEP devolve {erro: true}', async () => {
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ erro: true }) });
const { fetchCep } = useCep();
expect(await fetchCep('00000000')).toBe(null);
});
it('retorna null se HTTP falha (sem propagar erro)', async () => {
fetchMock.mockResolvedValue({ ok: false, status: 500 });
const { fetchCep, error } = useCep();
expect(await fetchCep('01310100')).toBe(null);
expect(error.value).toContain('500');
});
it('captura exception de rede como null', async () => {
fetchMock.mockRejectedValue(new Error('network'));
const { fetchCep, error } = useCep();
expect(await fetchCep('01310100')).toBe(null);
expect(error.value).toBe('network');
});
it('loading reflete o ciclo da request', async () => {
let resolveIt;
fetchMock.mockReturnValue(new Promise((res) => { resolveIt = res; }));
const { fetchCep, loading } = useCep();
const p = fetchCep('01310100');
expect(loading.value).toBe(true);
resolveIt({ ok: true, json: async () => ({ localidade: 'A', uf: 'B' }) });
await p;
expect(loading.value).toBe(false);
});
});
@@ -0,0 +1,152 @@
/**
* usePatientSupportContacts.spec.js — V#9
*
* Cobre add/remove/reset/load/save/iniciaisFor + sanitização do save.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
// Builder thenable: cada chamada (.select/.eq/.order/.delete/.insert) retorna um
// objeto thenable. Pra testes, configuramos o resultado final via setNext(value).
let nextResult = { data: [], error: null };
let lastInsertArg = null;
let deleteCalled = false;
function makeChain() {
const chain = {};
const passthrough = (..._a) => chain;
chain.select = passthrough;
chain.eq = passthrough;
chain.order = passthrough;
chain.delete = (...a) => { deleteCalled = true; return chain; };
chain.insert = (rows) => { lastInsertArg = rows; return chain; };
chain.then = (onFulfilled, onRejected) => Promise.resolve(nextResult).then(onFulfilled, onRejected);
return chain;
}
const fromMock = vi.fn(() => makeChain());
vi.mock('@/lib/supabase/client', () => ({
supabase: { from: (...a) => fromMock(...a) }
}));
const { usePatientSupportContacts } = await import('../usePatientSupportContacts.js');
beforeEach(() => {
fromMock.mockClear();
nextResult = { data: [], error: null };
lastInsertArg = null;
deleteCalled = false;
});
describe('add / remove / reset', () => {
it('add cria contato com defaults e _k único', () => {
const c = usePatientSupportContacts();
expect(c.contatos.value).toEqual([]);
c.add();
c.add();
expect(c.contatos.value).toHaveLength(2);
expect(c.contatos.value[0]._k).not.toBe(c.contatos.value[1]._k);
expect(c.contatos.value[0]).toMatchObject({ nome: '', telefone: '', is_primario: false });
});
it('remove pelo índice', () => {
const c = usePatientSupportContacts();
c.add(); c.add(); c.add();
const middleK = c.contatos.value[1]._k;
c.remove(1);
expect(c.contatos.value).toHaveLength(2);
expect(c.contatos.value.find((x) => x._k === middleK)).toBeUndefined();
});
it('reset esvazia', () => {
const c = usePatientSupportContacts();
c.add(); c.add();
c.reset();
expect(c.contatos.value).toEqual([]);
});
});
describe('iniciaisFor', () => {
it('extrai 2 primeiras iniciais maiúsculas', () => {
const { iniciaisFor } = usePatientSupportContacts();
expect(iniciaisFor('joão pedro silva')).toBe('JP');
expect(iniciaisFor('Maria')).toBe('M');
expect(iniciaisFor('')).toBe('');
expect(iniciaisFor(null)).toBe('');
expect(iniciaisFor('A B C D')).toBe('AB');
});
});
describe('load — popula contatos do paciente', () => {
it('sem patientId, esvazia', async () => {
const c = usePatientSupportContacts();
c.add();
await c.load(null);
expect(c.contatos.value).toEqual([]);
expect(fromMock).not.toHaveBeenCalled();
});
it('mapeia rows do banco para shape do composable (com fmtPhone)', async () => {
nextResult = {
data: [
{ id: 'a', nome: 'Maria', relacao: 'mãe', tipo: 'familiar', telefone: '11987654321', email: 'maria@x.com', is_primario: true },
{ id: 'b', nome: 'Bia', relacao: 'amiga', tipo: null, telefone: null, email: null, is_primario: false }
],
error: null
};
const c = usePatientSupportContacts();
await c.load('p-1');
expect(fromMock).toHaveBeenCalledWith('patient_support_contacts');
expect(c.contatos.value).toHaveLength(2);
expect(c.contatos.value[0]).toMatchObject({
_k: 'a', nome: 'Maria', is_primario: true, telefone: '(11) 98765-4321'
});
expect(c.contatos.value[1]).toMatchObject({ _k: 'b', telefone: '', is_primario: false });
});
it('em erro, esvazia silenciosamente', async () => {
nextResult = { data: null, error: new Error('rls') };
const c = usePatientSupportContacts();
c.add();
await c.load('p-1');
expect(c.contatos.value).toEqual([]);
});
});
describe('save — sanitização e regras', () => {
it('exige patientId', async () => {
const c = usePatientSupportContacts();
await expect(c.save(null, 't', 'o')).rejects.toThrow(/patientId/);
});
it('descarta contatos com nome vazio', async () => {
nextResult = { error: null };
const c = usePatientSupportContacts();
c.add(); c.add();
c.contatos.value[0].nome = 'Maria';
c.contatos.value[0].telefone = '(11) 98765-4321';
// contato 2 fica com nome vazio → descartado
await c.save('p-1', 't-1', 'o-1');
expect(deleteCalled).toBe(true);
expect(lastInsertArg).toHaveLength(1);
expect(lastInsertArg[0]).toMatchObject({
patient_id: 'p-1', tenant_id: 't-1', owner_id: 'o-1',
nome: 'Maria', telefone: '11987654321'
});
});
it('se todos contatos têm nome vazio, não chama insert (só delete)', async () => {
nextResult = { error: null };
const c = usePatientSupportContacts();
c.add();
await c.save('p-1', 't-1', 'o-1');
expect(deleteCalled).toBe(true);
expect(lastInsertArg).toBe(null);
});
});
@@ -0,0 +1,51 @@
/*
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Arquivo: src/features/patients/composables/useCep.js
| V#9 — composable de busca CEP via ViaCEP. Reutilizável em qualquer form
| que precise auto-completar endereço.
|--------------------------------------------------------------------------
*/
import { ref } from 'vue';
import { digitsOnly } from '@/utils/validators';
const VIACEP_URL = (cep) => `https://viacep.com.br/ws/${cep}/json/`;
export function useCep() {
const loading = ref(false);
const error = ref(null);
/**
* Consulta CEP no ViaCEP. Retorna {cidade, uf, bairro, endereco, complemento}
* ou null se CEP inválido / não encontrado.
*/
async function fetchCep(cepRaw) {
const cep = digitsOnly(cepRaw);
if (cep.length !== 8) return null;
loading.value = true;
error.value = null;
try {
const res = await fetch(VIACEP_URL(cep));
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
if (!data || data.erro) return null;
return {
cidade: data.localidade || '',
uf: data.uf || '',
bairro: data.bairro || '',
endereco: data.logradouro || '',
complemento: data.complemento || ''
};
} catch (e) {
error.value = e?.message || 'Falha na consulta CEP';
return null;
} finally {
loading.value = false;
}
}
return { loading, error, fetchCep };
}
@@ -0,0 +1,116 @@
/*
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Arquivo: src/features/patients/composables/usePatientSupportContacts.js
| V#9 — composable de contatos de suporte do paciente (responsável, parente,
| amigo). Encapsula CRUD + estado reativo.
|--------------------------------------------------------------------------
*/
import { ref } from 'vue';
import { supabase } from '@/lib/supabase/client';
import { digitsOnly, fmtPhone } from '@/utils/validators';
function novoContato() {
return {
_k: Date.now() + Math.random(),
nome: '',
relacao: '',
tipo: '',
telefone: '',
email: '',
is_primario: false
};
}
export function usePatientSupportContacts() {
const contatos = ref([]);
const loading = ref(false);
function add() {
contatos.value.push(novoContato());
}
function remove(idx) {
contatos.value.splice(idx, 1);
}
function reset() {
contatos.value = [];
}
function iniciaisFor(nome) {
return (nome || '')
.split(' ')
.filter(Boolean)
.map((w) => w[0].toUpperCase())
.slice(0, 2)
.join('');
}
async function load(patientId) {
if (!patientId) {
contatos.value = [];
return;
}
loading.value = true;
try {
const { data, error } = await supabase
.from('patient_support_contacts')
.select('*')
.eq('patient_id', patientId)
.order('is_primario', { ascending: false });
if (error) throw error;
contatos.value = (data || []).map((c) => ({
_k: c.id,
nome: c.nome || '',
relacao: c.relacao || '',
tipo: c.tipo || '',
telefone: fmtPhone(c.telefone || ''),
email: c.email || '',
is_primario: !!c.is_primario
}));
} catch {
contatos.value = [];
} finally {
loading.value = false;
}
}
/**
* Substitui contatos do paciente: deleta tudo do owner + reinserta os com nome.
* @param {string} patientId
* @param {string} tenantId
* @param {string} ownerId
*/
async function save(patientId, tenantId, ownerId) {
if (!patientId) throw new Error('patientId obrigatório');
const { error: del } = await supabase
.from('patient_support_contacts')
.delete()
.eq('patient_id', patientId)
.eq('owner_id', ownerId);
if (del) throw del;
const rows = contatos.value
.filter((c) => c.nome.trim())
.map((c) => ({
patient_id: patientId,
owner_id: ownerId,
tenant_id: tenantId,
nome: c.nome.trim() || null,
relacao: c.relacao || null,
tipo: c.tipo || null,
telefone: c.telefone ? digitsOnly(c.telefone) : null,
email: c.email || null,
is_primario: !!c.is_primario
}));
if (!rows.length) return;
const { error: ins } = await supabase.from('patient_support_contacts').insert(rows);
if (ins) throw ins;
}
return { contatos, loading, add, remove, reset, iniciaisFor, load, save };
}
@@ -0,0 +1,54 @@
/*
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Arquivo: src/features/patients/composables/usePatients.js
| V#3 — composable que agrega estado reativo (rows/loading/error) e delega
| toda I/O ao patientsRepository. Mesmo padrão de useAgendaEvents.
|--------------------------------------------------------------------------
*/
import { ref } from 'vue';
import {
listPatients,
getPatientById,
createPatient,
updatePatient,
softDeletePatient
} from '@/features/patients/services/patientsRepository';
export function usePatients() {
const rows = ref([]);
const loading = ref(false);
const error = ref(null);
async function load(opts) {
loading.value = true;
error.value = null;
try {
rows.value = await listPatients(opts);
} catch (e) {
error.value = e?.message || 'Erro ao carregar pacientes';
rows.value = [];
} finally {
loading.value = false;
}
}
async function getById(id, opts) {
return getPatientById(id, opts);
}
async function create(payload) {
return createPatient(payload);
}
async function update(id, patch, opts) {
return updatePatient(id, patch, opts);
}
async function remove(id, opts) {
await softDeletePatient(id, opts);
}
return { rows, loading, error, load, getById, create, update, remove };
}