Adionando os endpoints de users
This commit is contained in:
parent
a82193af27
commit
c4ca03cf48
@ -3,54 +3,51 @@
|
|||||||
import { useState } from "react"
|
import { useState } from "react"
|
||||||
import { useRouter } from "next/navigation"
|
import { useRouter } from "next/navigation"
|
||||||
import Link from "next/link"
|
import Link from "next/link"
|
||||||
import { Button } from "@/components/ui/button"
|
import { Button } from "components/ui/button"
|
||||||
import { Input } from "@/components/ui/input"
|
import { Input } from "components/ui/input"
|
||||||
import { Label } from "@/components/ui/label"
|
import { Label } from "components/ui/label"
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "components/ui/select"
|
||||||
import { Save, Loader2 } from "lucide-react"
|
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 {
|
interface UserFormData {
|
||||||
email: string;
|
email: string;
|
||||||
password: string;
|
password: string;
|
||||||
nomeCompleto: string;
|
nomeCompleto: string;
|
||||||
telefone: string;
|
telefone: string;
|
||||||
papel: string; // e.g., 'admin', 'gestor', 'medico', etc.
|
cargo: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Define the initial state for the form
|
|
||||||
const defaultFormData: UserFormData = {
|
const defaultFormData: UserFormData = {
|
||||||
email: '',
|
email: '',
|
||||||
password: '',
|
password: '',
|
||||||
nomeCompleto: '',
|
nomeCompleto: '',
|
||||||
telefone: '',
|
telefone: '',
|
||||||
papel: '',
|
cargo: '',
|
||||||
};
|
};
|
||||||
|
|
||||||
// Helper function to remove non-digit characters
|
|
||||||
const cleanNumber = (value: string): string => value.replace(/\D/g, '');
|
const cleanNumber = (value: string): string => value.replace(/\D/g, '');
|
||||||
|
|
||||||
// Helper function to format a phone number
|
|
||||||
|
|
||||||
const formatPhone = (value: string): string => {
|
const formatPhone = (value: string): string => {
|
||||||
const cleaned = cleanNumber(value).substring(0, 11);
|
const cleaned = cleanNumber(value).substring(0, 11);
|
||||||
if (cleaned.length > 10) {
|
|
||||||
return cleaned.replace(/(\d{2})(\d{5})(\d{4})/, '($1) $2-$3');
|
|
||||||
}
|
if (cleaned.length === 11) {
|
||||||
return cleaned.replace(/(\d{2})(\d{4})(\d{4})/, '($1) $2-$3');
|
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() {
|
export default function NovoUsuarioPage() {
|
||||||
@ -59,7 +56,7 @@ export default function NovoUsuarioPage() {
|
|||||||
const [isSaving, setIsSaving] = useState(false);
|
const [isSaving, setIsSaving] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
// Handles changes in form inputs
|
|
||||||
const handleInputChange = (key: keyof UserFormData, value: string) => {
|
const handleInputChange = (key: keyof UserFormData, value: string) => {
|
||||||
const updatedValue = key === 'telefone' ? formatPhone(value) : value;
|
const updatedValue = key === 'telefone' ? formatPhone(value) : value;
|
||||||
setFormData((prev) => ({ ...prev, [key]: updatedValue }));
|
setFormData((prev) => ({ ...prev, [key]: updatedValue }));
|
||||||
@ -71,7 +68,7 @@ export default function NovoUsuarioPage() {
|
|||||||
setError(null);
|
setError(null);
|
||||||
|
|
||||||
// Basic validation
|
// 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.");
|
setError("Por favor, preencha todos os campos obrigatórios.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -83,13 +80,12 @@ export default function NovoUsuarioPage() {
|
|||||||
email: formData.email,
|
email: formData.email,
|
||||||
password: formData.password,
|
password: formData.password,
|
||||||
full_name: formData.nomeCompleto,
|
full_name: formData.nomeCompleto,
|
||||||
phone: formData.telefone.trim() || null, // Send null if empty
|
phone: formData.telefone.trim() || null,
|
||||||
role: formData.papel,
|
role: formData.cargo,
|
||||||
};
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await usersService.create(payload);
|
await usersService.create_user(payload);
|
||||||
// On success, redirect to the main user list page
|
|
||||||
router.push("/manager/usuario");
|
router.push("/manager/usuario");
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
console.error("Erro ao criar usuário:", e);
|
console.error("Erro ao criar usuário:", e);
|
||||||
@ -174,7 +170,7 @@ export default function NovoUsuarioPage() {
|
|||||||
</div>
|
</div>
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="papel">Papel (Função) *</Label>
|
<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">
|
<SelectTrigger id="papel">
|
||||||
<SelectValue placeholder="Selecione uma função" />
|
<SelectValue placeholder="Selecione uma função" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
|
|||||||
@ -1,12 +1,12 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import React, { useEffect, useState, useCallback } from "react"
|
import React, { useEffect, useState, useCallback } from "react";
|
||||||
import ManagerLayout from "@/components/manager-layout";
|
import ManagerLayout from "@/components/manager-layout";
|
||||||
import Link from "next/link"
|
import Link from "next/link";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { Button } from "@/components/ui/button"
|
import { Button } from "@/components/ui/button";
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
import { Plus, Edit, Trash2, Eye, Filter, Loader2 } from "lucide-react"
|
import { Plus, Edit, Trash2, Eye, Filter, Loader2 } from "lucide-react";
|
||||||
import {
|
import {
|
||||||
AlertDialog,
|
AlertDialog,
|
||||||
AlertDialogAction,
|
AlertDialogAction,
|
||||||
@ -16,57 +16,79 @@ import {
|
|||||||
AlertDialogFooter,
|
AlertDialogFooter,
|
||||||
AlertDialogHeader,
|
AlertDialogHeader,
|
||||||
AlertDialogTitle,
|
AlertDialogTitle,
|
||||||
} from "@/components/ui/alert-dialog"
|
} from "@/components/ui/alert-dialog";
|
||||||
|
|
||||||
// Mock user service for demonstration. Replace with your actual API service.
|
import { usersService } from "services/usersApi.mjs";
|
||||||
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' },
|
|
||||||
|
|
||||||
];
|
|
||||||
},
|
|
||||||
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 {
|
interface User {
|
||||||
id: number;
|
user: {
|
||||||
full_name: string;
|
id: string;
|
||||||
email: string;
|
email: string;
|
||||||
phone: string | null;
|
email_confirmed_at?: string;
|
||||||
role: 'admin' | 'gestor' | 'medico' | 'secretaria' | 'user';
|
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() {
|
export default function UsersPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
const [users, setUsers] = useState<User[]>([]);
|
|
||||||
|
const [users, setUsers] = useState<FlatUser[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
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 [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||||
const [userToDeleteId, setUserToDeleteId] = useState<number | null>(null);
|
const [userToDeleteId, setUserToDeleteId] = useState<number | null>(null);
|
||||||
|
const [selectedRole, setSelectedRole] = useState<string>("");
|
||||||
|
|
||||||
const fetchUsers = useCallback(async () => {
|
const fetchUsers = useCallback(async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const data: User[] = await usersService.list();
|
|
||||||
setUsers(data || []);
|
const { data, error } = await usersService.list_roles();
|
||||||
} catch (e: any) {
|
if (error) throw error;
|
||||||
console.error("Erro ao carregar lista de usuários:", e);
|
|
||||||
setError("Não foi possível carregar a lista de usuários. Tente novamente.");
|
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([]);
|
setUsers([]);
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
@ -77,169 +99,197 @@ export default function UsersPage() {
|
|||||||
fetchUsers();
|
fetchUsers();
|
||||||
}, [fetchUsers]);
|
}, [fetchUsers]);
|
||||||
|
|
||||||
const openDetailsDialog = (user: User) => {
|
|
||||||
setUserDetails(user);
|
const openDetailsDialog = async (flatUser: FlatUser) => {
|
||||||
setDetailsDialogOpen(true);
|
setDetailsDialogOpen(true);
|
||||||
};
|
setUserDetails(null);
|
||||||
|
|
||||||
const handleDelete = async () => {
|
|
||||||
if (userToDeleteId === null) return;
|
|
||||||
|
|
||||||
setLoading(true);
|
|
||||||
try {
|
try {
|
||||||
await usersService.delete(userToDeleteId);
|
|
||||||
console.log(`Usuário com ID ${userToDeleteId} excluído com sucesso!`);
|
const fullUserData: User = await usersService.full_data(flatUser.id);
|
||||||
setDeleteDialogOpen(false);
|
|
||||||
setUserToDeleteId(null);
|
|
||||||
await fetchUsers(); // Refresh the list after deletion
|
setUserDetails(fullUserData);
|
||||||
} catch (e) {
|
|
||||||
console.error("Erro ao excluir:", e);
|
} catch (err: any) {
|
||||||
alert("Erro ao excluir usuário.");
|
console.error("Erro ao buscar detalhes do usuário:", err);
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
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 filteredUsers = selectedRole
|
||||||
};
|
? users.filter((u) => u.role === selectedRole)
|
||||||
|
: users;
|
||||||
const handleEdit = (userId: number) => {
|
|
||||||
// Assuming the edit page is at a similar path
|
|
||||||
router.push(`/manager/usuario/${userId}/editar`);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ManagerLayout>
|
<ManagerLayout>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold text-gray-900">Usuários Cadastrados</h1>
|
<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>
|
<p className="text-sm text-gray-500">Gerencie todos os usuários e seus papéis no 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>
|
</div>
|
||||||
)}
|
<Link href="/manager/usuario/novo">
|
||||||
</div>
|
<Button className="bg-green-600 hover:bg-green-700">
|
||||||
|
<Plus className="w-4 h-4 mr-2" /> Adicionar Novo
|
||||||
{/* Delete Confirmation Dialog */}
|
</Button>
|
||||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
</Link>
|
||||||
<AlertDialogContent>
|
</div>
|
||||||
<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>
|
|
||||||
|
|
||||||
{/* User Details Dialog */}
|
|
||||||
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
|
<div className="flex items-center space-x-4 bg-white p-4 rounded-lg border border-gray-200">
|
||||||
<AlertDialogContent>
|
<Filter className="w-5 h-5 text-gray-400" />
|
||||||
<AlertDialogHeader>
|
<Select onValueChange={setSelectedRole} value={selectedRole}>
|
||||||
<AlertDialogTitle className="text-2xl">{userDetails?.full_name}</AlertDialogTitle>
|
<SelectTrigger className="w-[180px]">
|
||||||
<AlertDialogDescription>
|
<SelectValue placeholder="Filtrar por Papel" />
|
||||||
{userDetails && (
|
</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="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>ID:</strong> {userDetails.user.id}</div>
|
||||||
<div><strong>Telefone:</strong> {userDetails.phone || 'Não informado'}</div>
|
<div><strong>E-mail:</strong> {userDetails.user.email}</div>
|
||||||
<div className="capitalize"><strong>Papel:</strong> {userDetails.role}</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>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</AlertDialogDescription>
|
|
||||||
</AlertDialogHeader>
|
|
||||||
<AlertDialogFooter>
|
</AlertDialogDescription>
|
||||||
<AlertDialogCancel>Fechar</AlertDialogCancel>
|
</AlertDialogHeader>
|
||||||
</AlertDialogFooter>
|
<AlertDialogFooter>
|
||||||
</AlertDialogContent>
|
<AlertDialogCancel>Fechar</AlertDialogCancel>
|
||||||
</AlertDialog>
|
</AlertDialogFooter>
|
||||||
</div>
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
</div>
|
||||||
</ManagerLayout>
|
</ManagerLayout>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -9,7 +9,7 @@ import Cookies from "js-cookie";
|
|||||||
import { jwtDecode } from "jwt-decode";
|
import { jwtDecode } from "jwt-decode";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
// Componentes Shadcn UI
|
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Label } from "@/components/ui/label";
|
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 { Separator } from "@/components/ui/separator";
|
||||||
import { apikey } from "@/services/api.mjs";
|
import { apikey } from "@/services/api.mjs";
|
||||||
|
|
||||||
// Hook customizado
|
|
||||||
import { useToast } from "@/hooks/use-toast";
|
import { useToast } from "@/hooks/use-toast";
|
||||||
|
|
||||||
// Ícones
|
|
||||||
import { Eye, EyeOff, Mail, Lock, Loader2, UserCheck, Stethoscope, IdCard, Receipt } from "lucide-react";
|
import { Eye, EyeOff, Mail, Lock, Loader2, UserCheck, Stethoscope, IdCard, Receipt } from "lucide-react";
|
||||||
|
|
||||||
interface LoginFormProps {
|
interface LoginFormProps {
|
||||||
|
|||||||
@ -1,8 +1,8 @@
|
|||||||
import { api } from "./api.mjs";
|
import { api } from "./api.mjs";
|
||||||
|
|
||||||
export const usersService = {
|
export const usersService = {
|
||||||
create_user: (data) => api.post('/functions/v1/create-user'),
|
create_user: (data) => api.post(`/functions/v1/create-user`),
|
||||||
list_roles: () => api.get("/rest/v1/user_roles"),
|
list_roles: () => api.get(`/rest/v1/user_roles`),
|
||||||
full_data: () => api.get(`/functions/v1/user-info`),
|
full_data: (id) => api.get(`/functions/v1/user-info?user_id=${id}`),
|
||||||
summary_data: () => api.get('/auth/v1/user')
|
summary_data: () => api.get(`/auth/v1/user`)
|
||||||
}
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user