Adionando os endpoints de users

This commit is contained in:
Lucas Rodrigues 2025-10-10 14:59:42 -03:00
parent a82193af27
commit c4ca03cf48
4 changed files with 274 additions and 228 deletions

View File

@ -3,54 +3,51 @@
import { useState } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Button } from "components/ui/button"
import { Input } from "components/ui/input"
import { Label } from "components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "components/ui/select"
import { Save, Loader2 } from "lucide-react"
import ManagerLayout from "@/components/manager-layout"
import ManagerLayout from "components/manager-layout"
import { usersService } from "services/usersApi.mjs";
// Mock user service for demonstration. Replace with your actual API service.
const usersService = {
create: async (payload: any) => {
console.log("API Call: Creating user with payload:", payload);
// Simulate network delay
await new Promise(resolve => setTimeout(resolve, 1000));
// Simulate a success response
return { id: Date.now(), ...payload };
// To simulate an error, you could throw an error here:
// throw new Error("O e-mail informado já está em uso.");
}
};
// Define the structure for our form data
interface UserFormData {
email: string;
password: string;
nomeCompleto: string;
telefone: string;
papel: string; // e.g., 'admin', 'gestor', 'medico', etc.
cargo: string;
}
// Define the initial state for the form
const defaultFormData: UserFormData = {
email: '',
password: '',
nomeCompleto: '',
telefone: '',
papel: '',
cargo: '',
};
// Helper function to remove non-digit characters
const cleanNumber = (value: string): string => value.replace(/\D/g, '');
// Helper function to format a phone number
const formatPhone = (value: string): string => {
const cleaned = cleanNumber(value).substring(0, 11);
if (cleaned.length > 10) {
return cleaned.replace(/(\d{2})(\d{5})(\d{4})/, '($1) $2-$3');
}
return cleaned.replace(/(\d{2})(\d{4})(\d{4})/, '($1) $2-$3');
const cleaned = cleanNumber(value).substring(0, 11);
if (cleaned.length === 11) {
return cleaned.replace(/(\d{2})(\d{5})(\d{4})/, '($1) $2-$3');
}
if (cleaned.length === 10) {
return cleaned.replace(/(\d{2})(\d{4})(\d{4})/, '($1) $2-$3');
}
return cleaned;
};
export default function NovoUsuarioPage() {
@ -59,7 +56,7 @@ export default function NovoUsuarioPage() {
const [isSaving, setIsSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
// Handles changes in form inputs
const handleInputChange = (key: keyof UserFormData, value: string) => {
const updatedValue = key === 'telefone' ? formatPhone(value) : value;
setFormData((prev) => ({ ...prev, [key]: updatedValue }));
@ -71,7 +68,7 @@ export default function NovoUsuarioPage() {
setError(null);
// Basic validation
if (!formData.email || !formData.password || !formData.nomeCompleto || !formData.papel) {
if (!formData.email || !formData.password || !formData.nomeCompleto || !formData.cargo) {
setError("Por favor, preencha todos os campos obrigatórios.");
return;
}
@ -83,13 +80,12 @@ export default function NovoUsuarioPage() {
email: formData.email,
password: formData.password,
full_name: formData.nomeCompleto,
phone: formData.telefone.trim() || null, // Send null if empty
role: formData.papel,
phone: formData.telefone.trim() || null,
role: formData.cargo,
};
try {
await usersService.create(payload);
// On success, redirect to the main user list page
await usersService.create_user(payload);
router.push("/manager/usuario");
} catch (e: any) {
console.error("Erro ao criar usuário:", e);
@ -174,7 +170,7 @@ export default function NovoUsuarioPage() {
</div>
<div className="space-y-2">
<Label htmlFor="papel">Papel (Função) *</Label>
<Select value={formData.papel} onValueChange={(v) => handleInputChange("papel", v)} required>
<Select value={formData.cargo} onValueChange={(v) => handleInputChange("cargo", v)} required>
<SelectTrigger id="papel">
<SelectValue placeholder="Selecione uma função" />
</SelectTrigger>

View File

@ -1,12 +1,12 @@
"use client";
import React, { useEffect, useState, useCallback } from "react"
import React, { useEffect, useState, useCallback } from "react";
import ManagerLayout from "@/components/manager-layout";
import Link from "next/link"
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Plus, Edit, Trash2, Eye, Filter, Loader2 } from "lucide-react"
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Plus, Edit, Trash2, Eye, Filter, Loader2 } from "lucide-react";
import {
AlertDialog,
AlertDialogAction,
@ -16,57 +16,79 @@ import {
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog"
} from "@/components/ui/alert-dialog";
// Mock user service for demonstration. Replace with your actual API service.
const usersService = {
list: async (): Promise<User[]> => {
console.log("API Call: Fetching users...");
await new Promise(resolve => setTimeout(resolve, 500)); // Simulate network delay
return [
{ id: 1, full_name: 'Alice Admin', email: 'alice.admin@example.com', phone: '(11) 98765-4321', role: 'user' },
import { usersService } from "services/usersApi.mjs";
];
},
delete: async (id: number): Promise<void> => {
console.log(`API Call: Deleting user with ID ${id}`);
await new Promise(resolve => setTimeout(resolve, 700));
// In a real app, you'd handle potential errors here
}
};
// Interface for a User object
interface User {
id: number;
full_name: string;
user: {
id: string;
email: string;
phone: string | null;
role: 'admin' | 'gestor' | 'medico' | 'secretaria' | 'user';
email_confirmed_at?: string;
created_at?: string;
last_sign_in_at?: string;
};
profile: {
id?: string;
full_name?: string;
email?: string;
phone?: string | null;
avatar_url?: string;
disabled?: boolean;
created_at?: string;
updated_at?: string;
};
roles: string[];
permissions: {
isAdmin?: boolean;
isManager?: boolean;
isDoctor?: boolean;
isSecretary?: boolean;
isAdminOrManager?: boolean;
[key: string]: boolean | undefined;
};
}
interface FlatUser {
id: string;
full_name?: string;
email: string;
phone?: string | null;
role: string;
}
// Interface for User Details (can be the same as User for this case)
interface UserDetails extends User {}
export default function UsersPage() {
const router = useRouter();
const [users, setUsers] = useState<User[]>([]);
const [users, setUsers] = useState<FlatUser[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
const [userDetails, setUserDetails] = useState<UserDetails | null>(null);
const [userDetails, setUserDetails] = useState<User | null>(null);
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [userToDeleteId, setUserToDeleteId] = useState<number | null>(null);
const [selectedRole, setSelectedRole] = useState<string>("");
const fetchUsers = useCallback(async () => {
setLoading(true);
setError(null);
try {
const data: User[] = await usersService.list();
setUsers(data || []);
} catch (e: any) {
console.error("Erro ao carregar lista de usuários:", e);
setError("Não foi possível carregar a lista de usuários. Tente novamente.");
const { data, error } = await usersService.list_roles();
if (error) throw error;
if (Array.isArray(data)) {
setUsers(data as FlatUser[]);
} else {
console.warn("Formato inesperado recebido:", data);
setUsers([]);
}
} catch (err: any) {
console.error("Erro ao buscar usuários:", err);
setError("Não foi possível carregar os usuários. Tente novamente.");
setUsers([]);
} finally {
setLoading(false);
@ -77,169 +99,197 @@ export default function UsersPage() {
fetchUsers();
}, [fetchUsers]);
const openDetailsDialog = (user: User) => {
setUserDetails(user);
const openDetailsDialog = async (flatUser: FlatUser) => {
setDetailsDialogOpen(true);
};
const handleDelete = async () => {
if (userToDeleteId === null) return;
setLoading(true);
setUserDetails(null);
try {
await usersService.delete(userToDeleteId);
console.log(`Usuário com ID ${userToDeleteId} excluído com sucesso!`);
setDeleteDialogOpen(false);
setUserToDeleteId(null);
await fetchUsers(); // Refresh the list after deletion
} catch (e) {
console.error("Erro ao excluir:", e);
alert("Erro ao excluir usuário.");
} finally {
setLoading(false);
const fullUserData: User = await usersService.full_data(flatUser.id);
setUserDetails(fullUserData);
} catch (err: any) {
console.error("Erro ao buscar detalhes do usuário:", err);
setUserDetails({
user: {
id: flatUser.id,
email: flatUser.email || "",
created_at: "Erro ao Carregar",
last_sign_in_at: "Erro ao Carregar",
},
profile: {
full_name: "Erro ao Carregar Detalhes",
phone: "—",
},
roles: [],
permissions: {},
} as any);
}
};
const openDeleteDialog = (userId: number) => {
setUserToDeleteId(userId);
setDeleteDialogOpen(true);
};
const handleEdit = (userId: number) => {
// Assuming the edit page is at a similar path
router.push(`/manager/usuario/${userId}/editar`);
};
const filteredUsers = selectedRole
? users.filter((u) => u.role === selectedRole)
: users;
return (
<ManagerLayout>
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-gray-900">Usuários Cadastrados</h1>
<p className="text-sm text-gray-500">Gerencie todos os usuários do sistema.</p>
</div>
<Link href="/manager/usuario/novo">
<Button className="bg-green-600 hover:bg-green-700">
<Plus className="w-4 h-4 mr-2" />
Adicionar Novo
</Button>
</Link>
</div>
{/* Filters Section */}
<div className="flex items-center space-x-4 bg-white p-4 rounded-lg border border-gray-200">
<Filter className="w-5 h-5 text-gray-400" />
<Select>
<SelectTrigger className="w-[180px]">
<SelectValue placeholder="Filtrar por Papel" />
</SelectTrigger>
<SelectContent>
<SelectItem value="admin">Admin</SelectItem>
<SelectItem value="gestor">Gestor</SelectItem>
<SelectItem value="medico">Médico</SelectItem>
<SelectItem value="secretaria">Secretaria</SelectItem>
<SelectItem value="user">Usuário</SelectItem>
</SelectContent>
</Select>
</div>
{/* Users Table */}
<div className="bg-white rounded-lg border border-gray-200 shadow-md overflow-hidden">
{loading ? (
<div className="p-8 text-center text-gray-500">
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-green-600" />
Carregando usuários...
</div>
) : error ? (
<div className="p-8 text-center text-red-600">
{error}
</div>
) : users.length === 0 ? (
<div className="p-8 text-center text-gray-500">
Nenhum usuário cadastrado. <Link href="/manager/usuario/novo" className="text-green-600 hover:underline">Adicione um novo</Link>.
</div>
) : (
<div className="overflow-x-auto">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Nome Completo</th>
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">E-mail</th>
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Telefone</th>
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Papel</th>
<th scope="col" className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Ações</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{users.map((user) => (
<tr key={user.id} className="hover:bg-gray-50">
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{user.full_name}</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{user.email}</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{user.phone || "N/A"}</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 capitalize">{user.role}</td>
<td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
<div className="flex justify-end space-x-1">
<Button variant="outline" size="icon" onClick={() => openDetailsDialog(user)} title="Visualizar Detalhes">
<Eye className="h-4 w-4" />
</Button>
<Button variant="outline" size="icon" onClick={() => handleEdit(user.id)} title="Editar">
<Edit className="h-4 w-4 text-blue-600" />
</Button>
<Button variant="outline" size="icon" onClick={() => openDeleteDialog(user.id)} title="Excluir">
<Trash2 className="h-4 w-4 text-red-600" />
</Button>
</div>
</td>
</tr>
))}
</tbody>
</table>
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-gray-900">Usuários Cadastrados</h1>
<p className="text-sm text-gray-500">Gerencie todos os usuários e seus papéis no sistema.</p>
</div>
)}
</div>
{/* Delete Confirmation Dialog */}
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Confirma a exclusão?</AlertDialogTitle>
<AlertDialogDescription>
Esta ação é irreversível e excluirá permanentemente o registro deste usuário.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={loading}>Cancelar</AlertDialogCancel>
<AlertDialogAction onClick={handleDelete} className="bg-red-600 hover:bg-red-700" disabled={loading}>
{loading ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : null}
Excluir
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<Link href="/manager/usuario/novo">
<Button className="bg-green-600 hover:bg-green-700">
<Plus className="w-4 h-4 mr-2" /> Adicionar Novo
</Button>
</Link>
</div>
{/* User Details Dialog */}
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle className="text-2xl">{userDetails?.full_name}</AlertDialogTitle>
<AlertDialogDescription>
{userDetails && (
<div className="flex items-center space-x-4 bg-white p-4 rounded-lg border border-gray-200">
<Filter className="w-5 h-5 text-gray-400" />
<Select onValueChange={setSelectedRole} value={selectedRole}>
<SelectTrigger className="w-[180px]">
<SelectValue placeholder="Filtrar por Papel" />
</SelectTrigger>
<SelectContent>
<SelectItem value="">Todos</SelectItem>
<SelectItem value="admin">Admin</SelectItem>
<SelectItem value="gestor">Gestor</SelectItem>
<SelectItem value="medico">Médico</SelectItem>
<SelectItem value="secretaria">Secretaria</SelectItem>
<SelectItem value="user">Usuário</SelectItem>
</SelectContent>
</Select>
</div>
<div className="bg-white rounded-lg border border-gray-200 shadow-md overflow-hidden">
{loading ? (
<div className="p-8 text-center text-gray-500">
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-green-600" />
Carregando usuários...
</div>
) : error ? (
<div className="p-8 text-center text-red-600">{error}</div>
) : filteredUsers.length === 0 ? (
<div className="p-8 text-center text-gray-500">
Nenhum usuário encontrado.{" "}
<Link href="/manager/usuario/novo" className="text-green-600 hover:underline">
Adicione um novo
</Link>
.
</div>
) : (
<div className="overflow-x-auto">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">ID</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Nome</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">E-mail</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Telefone</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Papel</th>
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">Ações</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{filteredUsers.map((user) => (
<tr key={user.id} className="hover:bg-gray-50">
<td className="px-6 py-4 text-sm text-gray-700">{user.id}</td>
<td className="px-6 py-4 text-sm text-gray-900">{user.full_name || "—"}</td>
<td className="px-6 py-4 text-sm text-gray-500">{user.email || "—"}</td>
<td className="px-6 py-4 text-sm text-gray-500">{user.phone || "—"}</td>
<td className="px-6 py-4 text-sm text-gray-500 capitalize">{user.role || "—"}</td>
<td className="px-6 py-4 text-right">
<div className="flex justify-end space-x-1">
<Button
variant="outline"
size="icon"
onClick={() => openDetailsDialog(user)}
title="Visualizar"
>
<Eye className="h-4 w-4" />
</Button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle className="text-2xl">
{userDetails?.profile?.full_name || userDetails?.user?.email || "Detalhes do Usuário"}
</AlertDialogTitle>
<AlertDialogDescription>
{!userDetails ? (
<div className="p-4 text-center text-gray-500">
<Loader2 className="w-6 h-6 animate-spin mx-auto mb-3 text-green-600" />
Buscando dados completos...
</div>
) : (
<div className="space-y-3 pt-2 text-left text-gray-700">
<div className="grid grid-cols-1 gap-y-2 text-sm">
<div><strong>E-mail:</strong> {userDetails.email}</div>
<div><strong>Telefone:</strong> {userDetails.phone || 'Não informado'}</div>
<div className="capitalize"><strong>Papel:</strong> {userDetails.role}</div>
<div><strong>ID:</strong> {userDetails.user.id}</div>
<div><strong>E-mail:</strong> {userDetails.user.email}</div>
<div><strong>Email confirmado em:</strong> {userDetails.user.email_confirmed_at || "—"}</div>
<div><strong>Último login:</strong> {userDetails.user.last_sign_in_at || "—"}</div>
<div><strong>Criado em:</strong> {userDetails.user.created_at || "—"}</div>
<div><strong>Nome completo:</strong> {userDetails.profile.full_name || "—"}</div>
<div><strong>Telefone:</strong> {userDetails.profile.phone || "—"}</div>
{userDetails.profile.avatar_url && (
<div><strong>Avatar:</strong> <img src={userDetails.profile.avatar_url} className="w-16 h-16 rounded-full mt-1" /></div>
)}
<div><strong>Conta desativada:</strong> {userDetails.profile.disabled ? "Sim" : "Não"}</div>
<div><strong>Profile criado em:</strong> {userDetails.profile.created_at || "—"}</div>
<div><strong>Profile atualizado em:</strong> {userDetails.profile.updated_at || "—"}</div>
<div>
<strong>Roles:</strong>
<ul className="list-disc list-inside">
{userDetails.roles.map((role, idx) => <li key={idx}>{role}</li>)}
</ul>
</div>
<div>
<strong>Permissões:</strong>
<ul className="list-disc list-inside">
{Object.entries(userDetails.permissions).map(([key, value]) => (
<li key={key}>{key}: {value ? "Sim" : "Não"}</li>
))}
</ul>
</div>
</div>
)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Fechar</AlertDialogCancel>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Fechar</AlertDialogCancel>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</ManagerLayout>
);
}

View File

@ -9,7 +9,7 @@ import Cookies from "js-cookie";
import { jwtDecode } from "jwt-decode";
import { cn } from "@/lib/utils";
// Componentes Shadcn UI
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
@ -17,10 +17,10 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/com
import { Separator } from "@/components/ui/separator";
import { apikey } from "@/services/api.mjs";
// Hook customizado
import { useToast } from "@/hooks/use-toast";
// Ícones
import { Eye, EyeOff, Mail, Lock, Loader2, UserCheck, Stethoscope, IdCard, Receipt } from "lucide-react";
interface LoginFormProps {

View File

@ -1,8 +1,8 @@
import { api } from "./api.mjs";
export const usersService = {
create_user: (data) => api.post('/functions/v1/create-user'),
list_roles: () => api.get("/rest/v1/user_roles"),
full_data: () => api.get(`/functions/v1/user-info`),
summary_data: () => api.get('/auth/v1/user')
create_user: (data) => api.post(`/functions/v1/create-user`),
list_roles: () => api.get(`/rest/v1/user_roles`),
full_data: (id) => api.get(`/functions/v1/user-info?user_id=${id}`),
summary_data: () => api.get(`/auth/v1/user`)
}