feat(api): Standardizes CRUD for profiles and derivations
- Standardizes listing/searching/creating/updating/deleting for profiles - Adds UI for assigning professionals - Integrates UI into patient listing (menu item) - Corrects hydration mismatch in ProtectedRoute
This commit is contained in:
parent
2c774b8859
commit
5698a5faa9
File diff suppressed because it is too large
Load Diff
@ -12,6 +12,7 @@ import { MoreHorizontal, Plus, Search, Eye, Edit, Trash2, ArrowLeft } from "luci
|
|||||||
|
|
||||||
import { Paciente, Endereco, listarPacientes, buscarPacientes, buscarPacientePorId, excluirPaciente } from "@/lib/api";
|
import { Paciente, Endereco, listarPacientes, buscarPacientes, buscarPacientePorId, excluirPaciente } from "@/lib/api";
|
||||||
import { PatientRegistrationForm } from "@/components/forms/patient-registration-form";
|
import { PatientRegistrationForm } from "@/components/forms/patient-registration-form";
|
||||||
|
import AssignmentForm from "@/components/admin/AssignmentForm";
|
||||||
|
|
||||||
|
|
||||||
function normalizePaciente(p: any): Paciente {
|
function normalizePaciente(p: any): Paciente {
|
||||||
@ -46,6 +47,8 @@ export default function PacientesPage() {
|
|||||||
const [showForm, setShowForm] = useState(false);
|
const [showForm, setShowForm] = useState(false);
|
||||||
const [editingId, setEditingId] = useState<string | null>(null);
|
const [editingId, setEditingId] = useState<string | null>(null);
|
||||||
const [viewingPatient, setViewingPatient] = useState<Paciente | null>(null);
|
const [viewingPatient, setViewingPatient] = useState<Paciente | null>(null);
|
||||||
|
const [assignDialogOpen, setAssignDialogOpen] = useState(false);
|
||||||
|
const [assignPatientId, setAssignPatientId] = useState<string | null>(null);
|
||||||
|
|
||||||
async function loadAll() {
|
async function loadAll() {
|
||||||
try {
|
try {
|
||||||
@ -254,6 +257,10 @@ export default function PacientesPage() {
|
|||||||
<Trash2 className="mr-2 h-4 w-4" />
|
<Trash2 className="mr-2 h-4 w-4" />
|
||||||
Excluir
|
Excluir
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem onClick={() => { setAssignPatientId(String(p.id)); setAssignDialogOpen(true); }}>
|
||||||
|
<Edit className="mr-2 h-4 w-4" />
|
||||||
|
Atribuir profissional
|
||||||
|
</DropdownMenuItem>
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
|
|||||||
@ -1,5 +1,5 @@
|
|||||||
'use client'
|
'use client'
|
||||||
import { useEffect, useRef } from 'react'
|
import { useEffect, useRef, useState } from 'react'
|
||||||
import { useRouter } from 'next/navigation'
|
import { useRouter } from 'next/navigation'
|
||||||
import { useAuth } from '@/hooks/useAuth'
|
import { useAuth } from '@/hooks/useAuth'
|
||||||
import type { UserType } from '@/types/auth'
|
import type { UserType } from '@/types/auth'
|
||||||
@ -17,8 +17,12 @@ export default function ProtectedRoute({
|
|||||||
const { authStatus, user } = useAuth()
|
const { authStatus, user } = useAuth()
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const isRedirecting = useRef(false)
|
const isRedirecting = useRef(false)
|
||||||
|
const [mounted, setMounted] = useState(false)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
// marca que o componente já montou no cliente
|
||||||
|
setMounted(true)
|
||||||
|
|
||||||
// Evitar múltiplos redirects
|
// Evitar múltiplos redirects
|
||||||
if (isRedirecting.current) return
|
if (isRedirecting.current) return
|
||||||
|
|
||||||
@ -85,6 +89,9 @@ export default function ProtectedRoute({
|
|||||||
|
|
||||||
// Durante loading, mostrar spinner
|
// Durante loading, mostrar spinner
|
||||||
if (authStatus === 'loading') {
|
if (authStatus === 'loading') {
|
||||||
|
// evitar render no servidor para não causar mismatch de hidratação
|
||||||
|
if (!mounted) return null
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen flex items-center justify-center">
|
<div className="min-h-screen flex items-center justify-center">
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
@ -97,6 +104,9 @@ export default function ProtectedRoute({
|
|||||||
|
|
||||||
// Se não autenticado ou redirecionando, mostrar spinner
|
// Se não autenticado ou redirecionando, mostrar spinner
|
||||||
if (authStatus === 'unauthenticated' || isRedirecting.current) {
|
if (authStatus === 'unauthenticated' || isRedirecting.current) {
|
||||||
|
// evitar render no servidor para não causar mismatch de hidratação
|
||||||
|
if (!mounted) return null
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen flex items-center justify-center">
|
<div className="min-h-screen flex items-center justify-center">
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
|
|||||||
113
susconecta/components/admin/AssignmentForm.tsx
Normal file
113
susconecta/components/admin/AssignmentForm.tsx
Normal file
@ -0,0 +1,113 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { useToast } from "@/hooks/use-toast";
|
||||||
|
|
||||||
|
import { assignRoleToUser, listAssignmentsForPatient } from "@/lib/assignment";
|
||||||
|
import { listarProfissionais } from "@/lib/api";
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
patientId: string;
|
||||||
|
open: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
onSaved?: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function AssignmentForm({ patientId, open, onClose, onSaved }: Props) {
|
||||||
|
const { toast } = useToast();
|
||||||
|
const [professionals, setProfessionals] = useState<any[]>([]);
|
||||||
|
const [selectedProfessional, setSelectedProfessional] = useState<string | null>(null);
|
||||||
|
const [role, setRole] = useState<string>("doctor");
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [existing, setExisting] = useState<any[]>([]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
async function load() {
|
||||||
|
try {
|
||||||
|
const pros = await listarProfissionais();
|
||||||
|
setProfessionals(pros || []);
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('Erro ao carregar profissionais', e);
|
||||||
|
setProfessionals([]);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const a = await listAssignmentsForPatient(patientId);
|
||||||
|
setExisting(a || []);
|
||||||
|
} catch (e) {
|
||||||
|
setExisting([]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (open) load();
|
||||||
|
}, [open, patientId]);
|
||||||
|
|
||||||
|
async function handleSave() {
|
||||||
|
if (!selectedProfessional) return toast({ title: 'Selecione um profissional', variant: 'warning' });
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
await assignRoleToUser({ patient_id: patientId, user_id: selectedProfessional, role });
|
||||||
|
toast({ title: 'Atribuição criada', variant: 'success' });
|
||||||
|
onSaved && onSaved();
|
||||||
|
onClose();
|
||||||
|
} catch (err: any) {
|
||||||
|
console.error(err);
|
||||||
|
toast({ title: 'Erro ao criar atribuição', description: err?.message });
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={(v) => { if (!v) onClose(); }}>
|
||||||
|
<DialogContent className="max-w-lg">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Atribuir profissional ao paciente</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="grid gap-4 py-4">
|
||||||
|
<div>
|
||||||
|
<Label>Profissional</Label>
|
||||||
|
<Select onValueChange={(v) => setSelectedProfessional(v)}>
|
||||||
|
<SelectTrigger className="w-full">
|
||||||
|
<SelectValue placeholder="Selecione um profissional" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{professionals.map((p) => (
|
||||||
|
<SelectItem key={p.id} value={String(p.id)}>{p.full_name || p.name || p.email || p.id}</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<Label>Role</Label>
|
||||||
|
<Input value={role} onChange={(e) => setRole(e.target.value)} />
|
||||||
|
<div className="text-xs text-muted-foreground mt-1">Ex: doctor, nurse</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{existing && existing.length > 0 && (
|
||||||
|
<div>
|
||||||
|
<Label>Atribuições existentes</Label>
|
||||||
|
<ul className="pl-4 list-disc text-sm text-muted-foreground">
|
||||||
|
{existing.map((it) => (
|
||||||
|
<li key={it.id}>{it.user_id} — {it.role}</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="ghost" onClick={onClose}>Cancelar</Button>
|
||||||
|
<Button onClick={handleSave} disabled={loading}>{loading ? 'Salvando...' : 'Salvar'}</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -1481,12 +1481,67 @@ export async function uploadFotoMedico(_id: string | number, _file: File): Promi
|
|||||||
export async function removerFotoMedico(_id: string | number): Promise<void> {}
|
export async function removerFotoMedico(_id: string | number): Promise<void> {}
|
||||||
|
|
||||||
// ===== PERFIS DE USUÁRIOS =====
|
// ===== PERFIS DE USUÁRIOS =====
|
||||||
export async function listarPerfis(): Promise<Profile[]> {
|
export async function listarPerfis(params?: { page?: number; limit?: number; q?: string; }): Promise<Profile[]> {
|
||||||
const url = `https://yuanq1/1053378-0-default/rest/v1/profiles`;
|
const qs = new URLSearchParams();
|
||||||
|
if (params?.q) qs.set('q', params.q);
|
||||||
|
const url = `${REST}/profiles${qs.toString() ? `?${qs.toString()}` : ''}`;
|
||||||
const res = await fetch(url, {
|
const res = await fetch(url, {
|
||||||
method: "GET",
|
method: 'GET',
|
||||||
headers: baseHeaders(),
|
headers: { ...baseHeaders(), ...rangeHeaders(params?.page, params?.limit) },
|
||||||
});
|
});
|
||||||
return await parse<Profile[]>(res);
|
return await parse<Profile[]>(res);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function buscarPerfilPorId(id: string | number): Promise<Profile> {
|
||||||
|
const idParam = String(id);
|
||||||
|
const headers = baseHeaders();
|
||||||
|
|
||||||
|
// 1) tentar por id
|
||||||
|
try {
|
||||||
|
const url = `${REST}/profiles?id=eq.${encodeURIComponent(idParam)}`;
|
||||||
|
const arr = await fetchWithFallback<Profile[]>(url, headers);
|
||||||
|
if (arr && arr.length) return arr[0];
|
||||||
|
} catch (e) {
|
||||||
|
// continuar para próxima estratégia
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2) tentar por full_name quando for string legível
|
||||||
|
if (typeof id === 'string' && isNaN(Number(id))) {
|
||||||
|
const q = encodeURIComponent(String(id));
|
||||||
|
const url = `${REST}/profiles?full_name=ilike.*${q}*&limit=5`;
|
||||||
|
const alt = `${REST}/profiles?email=ilike.*${q}*&limit=5`;
|
||||||
|
const arr2 = await fetchWithFallback<Profile[]>(url, headers, [alt]);
|
||||||
|
if (arr2 && arr2.length) return arr2[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error('404: Perfil não encontrado');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function criarPerfil(input: ProfileInput): Promise<Profile> {
|
||||||
|
const url = `${REST}/profiles`;
|
||||||
|
const res = await fetch(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: withPrefer({ ...baseHeaders(), 'Content-Type': 'application/json' }, 'return=representation'),
|
||||||
|
body: JSON.stringify(input),
|
||||||
|
});
|
||||||
|
const arr = await parse<Profile[] | Profile>(res);
|
||||||
|
return Array.isArray(arr) ? arr[0] : (arr as Profile);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function atualizarPerfil(id: string | number, input: ProfileInput): Promise<Profile> {
|
||||||
|
const url = `${REST}/profiles?id=eq.${id}`;
|
||||||
|
const res = await fetch(url, {
|
||||||
|
method: 'PATCH',
|
||||||
|
headers: withPrefer({ ...baseHeaders(), 'Content-Type': 'application/json' }, 'return=representation'),
|
||||||
|
body: JSON.stringify(input),
|
||||||
|
});
|
||||||
|
const arr = await parse<Profile[] | Profile>(res);
|
||||||
|
return Array.isArray(arr) ? arr[0] : (arr as Profile);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function excluirPerfil(id: string | number): Promise<void> {
|
||||||
|
const url = `${REST}/profiles?id=eq.${id}`;
|
||||||
|
const res = await fetch(url, { method: 'DELETE', headers: baseHeaders() });
|
||||||
|
await parse<any>(res);
|
||||||
|
}
|
||||||
|
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user