Merge branch 'develop' into feature/patiente-medical-assignment

This commit is contained in:
João Gustavo 2025-10-15 15:19:13 -03:00
commit 597bcbc007
3 changed files with 31 additions and 6 deletions

View File

@ -694,7 +694,7 @@ export default function PacientePage() {
// Renderização principal
return (
<ProtectedRoute requiredUserType={["paciente"]}>
<ProtectedRoute>
<div className="min-h-screen bg-background text-foreground flex flex-col">
{/* Header só com título e botão de sair */}
<header className="flex items-center justify-between px-4 py-2 border-b bg-card">

View File

@ -865,21 +865,40 @@ export async function atualizarPaciente(id: string | number, input: PacienteInpu
}
export async function excluirPaciente(id: string | number): Promise<void> {
// Antes de excluir, verificar se existem relatórios vinculados a este paciente
// Antes de excluir, verificar se existem relatórios ou atribuições vinculadas a este paciente
let reportsCount = 0;
let assignmentsCount = 0;
try {
// Import dinâmico para evitar ciclos durante bundling
const reportsMod = await import('./reports');
if (reportsMod && typeof reportsMod.listarRelatoriosPorPaciente === 'function') {
const rels = await reportsMod.listarRelatoriosPorPaciente(String(id)).catch(() => []);
if (Array.isArray(rels) && rels.length > 0) {
throw new Error('Não é possível excluir este paciente: existem relatórios vinculados. Remova ou reatribua esses relatórios antes de excluir o paciente.');
}
if (Array.isArray(rels)) reportsCount = rels.length;
}
} catch (err) {
// Se a checagem falhar por algum motivo, apenas logamos e continuamos para a tentativa de exclusão
console.warn('[API] Falha ao checar relatórios vinculados antes da exclusão:', err);
}
try {
const assignMod = await import('./assignment');
if (assignMod && typeof assignMod.listAssignmentsForPatient === 'function') {
const assigns = await assignMod.listAssignmentsForPatient(String(id)).catch(() => []);
if (Array.isArray(assigns)) assignmentsCount = assigns.length;
}
} catch (err) {
console.warn('[API] Falha ao checar atribuições de paciente antes da exclusão:', err);
}
const totalDeps = (reportsCount || 0) + (assignmentsCount || 0);
if (totalDeps > 0) {
const parts: string[] = [];
if (reportsCount > 0) parts.push(`${reportsCount} relatório${reportsCount !== 1 ? 's' : ''}`);
if (assignmentsCount > 0) parts.push(`${assignmentsCount} atribuição${assignmentsCount !== 1 ? 'ões' : ''}`);
const depsText = parts.join(' e ');
throw new Error(`Não é possível excluir este paciente: existem ${depsText} vinculad${totalDeps !== 1 ? 'os' : 'o'}. Remova ou reatribua essas dependências antes de excluir o paciente.`);
}
const url = `${REST}/patients?id=eq.${id}`;
const res = await fetch(url, { method: "DELETE", headers: baseHeaders() });
await parse<any>(res);

View File

@ -25,6 +25,12 @@ export async function POST(req: Request) {
const body = (await req.json()) as Body
if (!body || !body.user_id || !body.role) return NextResponse.json({ error: 'user_id and role required' }, { status: 400 })
// Business rule: there is no separate 'paciente' role — patients are any user.
// Prevent creation/assignment of a 'paciente' role to avoid confusion.
if (body.role === 'paciente') {
return NextResponse.json({ error: "role 'paciente' must not be created or assigned; patients are regular users" }, { status: 400 })
}
const authHeader = req.headers.get('authorization')
const token = authHeader?.startsWith('Bearer ') ? authHeader.split(' ')[1] : null