Compare commits
No commits in common. "1b477c10f00a4a8d04e486708f4aa7fabdf53730" and "a82193af27364f820c2562b91bb42e150bd302d9" have entirely different histories.
1b477c10f0
...
a82193af27
@ -9,223 +9,206 @@ 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 { usersService } from "services/usersApi.mjs";
|
||||
|
||||
interface UserFormData {
|
||||
email: string;
|
||||
password: string;
|
||||
nomeCompleto: string;
|
||||
telefone: string;
|
||||
papel: string;
|
||||
}
|
||||
|
||||
const defaultFormData: UserFormData = {
|
||||
email: '',
|
||||
password: '',
|
||||
nomeCompleto: '',
|
||||
telefone: '',
|
||||
papel: '',
|
||||
// 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.");
|
||||
}
|
||||
};
|
||||
|
||||
// Remove todos os caracteres não numéricos
|
||||
// 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.
|
||||
}
|
||||
|
||||
// Define the initial state for the form
|
||||
const defaultFormData: UserFormData = {
|
||||
email: '',
|
||||
password: '',
|
||||
nomeCompleto: '',
|
||||
telefone: '',
|
||||
papel: '',
|
||||
};
|
||||
|
||||
// Helper function to remove non-digit characters
|
||||
const cleanNumber = (value: string): string => value.replace(/\D/g, '');
|
||||
|
||||
// Definição do requisito mínimo de senha
|
||||
const MIN_PASSWORD_LENGTH = 8;
|
||||
|
||||
|
||||
// Helper function to format a phone number
|
||||
const formatPhone = (value: string): string => {
|
||||
const cleaned = cleanNumber(value).substring(0, 11);
|
||||
|
||||
if (cleaned.length === 11) {
|
||||
if (cleaned.length > 10) {
|
||||
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;
|
||||
return cleaned.replace(/(\d{2})(\d{4})(\d{4})/, '($1) $2-$3');
|
||||
};
|
||||
|
||||
|
||||
export default function NovoUsuarioPage() {
|
||||
const router = useRouter();
|
||||
const [formData, setFormData] = useState<UserFormData>(defaultFormData);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const router = useRouter();
|
||||
const [formData, setFormData] = useState<UserFormData>(defaultFormData);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleInputChange = (key: keyof UserFormData, value: string) => {
|
||||
const updatedValue = key === 'telefone' ? formatPhone(value) : value;
|
||||
setFormData((prev) => ({ ...prev, [key]: updatedValue }));
|
||||
// Handles changes in form inputs
|
||||
const handleInputChange = (key: keyof UserFormData, value: string) => {
|
||||
const updatedValue = key === 'telefone' ? formatPhone(value) : value;
|
||||
setFormData((prev) => ({ ...prev, [key]: updatedValue }));
|
||||
};
|
||||
|
||||
// Handles form submission
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
|
||||
// Basic validation
|
||||
if (!formData.email || !formData.password || !formData.nomeCompleto || !formData.papel) {
|
||||
setError("Por favor, preencha todos os campos obrigatórios.");
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSaving(true);
|
||||
|
||||
// Prepare payload for the API
|
||||
const payload = {
|
||||
email: formData.email,
|
||||
password: formData.password,
|
||||
full_name: formData.nomeCompleto,
|
||||
phone: formData.telefone.trim() || null, // Send null if empty
|
||||
role: formData.papel,
|
||||
};
|
||||
|
||||
// Handles form submission
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
try {
|
||||
await usersService.create(payload);
|
||||
// On success, redirect to the main user list page
|
||||
router.push("/manager/usuario");
|
||||
} catch (e: any) {
|
||||
console.error("Erro ao criar usuário:", e);
|
||||
setError(e.message || "Ocorreu um erro inesperado. Tente novamente.");
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Basic validation
|
||||
if (!formData.email || !formData.password || !formData.nomeCompleto || !formData.papel) {
|
||||
setError("Por favor, preencha todos os campos obrigatórios.");
|
||||
return;
|
||||
}
|
||||
return (
|
||||
<ManagerLayout>
|
||||
<div className="w-full max-w-2xl mx-auto space-y-6 p-4 md:p-8">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Novo Usuário</h1>
|
||||
<p className="text-sm text-gray-500">
|
||||
Preencha os dados para cadastrar um novo usuário no sistema.
|
||||
</p>
|
||||
</div>
|
||||
<Link href="/manager/usuario">
|
||||
<Button variant="outline">Cancelar</Button>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
// Validação de comprimento mínimo da senha
|
||||
if (formData.password.length < MIN_PASSWORD_LENGTH) {
|
||||
setError(`A senha deve ter no mínimo ${MIN_PASSWORD_LENGTH} caracteres.`);
|
||||
return;
|
||||
}
|
||||
<form onSubmit={handleSubmit} className="space-y-8 bg-white p-8 border rounded-lg shadow-sm">
|
||||
|
||||
setIsSaving(true);
|
||||
{/* Error Message Display */}
|
||||
{error && (
|
||||
<div className="p-3 bg-red-100 text-red-700 rounded-lg border border-red-300">
|
||||
<p className="font-medium">Erro no Cadastro:</p>
|
||||
<p className="text-sm">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// CORREÇÃO FINAL: Usa o formato de telefone que o mock API comprovadamente aceitou.
|
||||
// ----------------------------------------------------------------------
|
||||
const phoneValue = formData.telefone.trim();
|
||||
|
||||
// Prepara o payload com os campos obrigatórios
|
||||
const payload: any = {
|
||||
email: formData.email,
|
||||
password: formData.password,
|
||||
full_name: formData.nomeCompleto,
|
||||
role: formData.papel,
|
||||
};
|
||||
|
||||
// Adiciona o telefone APENAS se estiver preenchido, enviando o formato FORMATADO.
|
||||
if (phoneValue.length > 0) {
|
||||
payload.phone = phoneValue;
|
||||
}
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
try {
|
||||
await usersService.create_user(payload);
|
||||
router.push("/manager/usuario");
|
||||
} catch (e: any) {
|
||||
console.error("Erro ao criar usuário:", e);
|
||||
// Melhorando a mensagem de erro para o usuário final
|
||||
const apiErrorMsg = e.message?.includes("500")
|
||||
? "Erro interno do servidor. Verifique os logs do backend ou tente novamente mais tarde. (Possível problema: E-mail já em uso ou falha de conexão.)"
|
||||
: e.message || "Ocorreu um erro inesperado. Tente novamente.";
|
||||
|
||||
setError(apiErrorMsg);
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<ManagerLayout>
|
||||
<div className="w-full max-w-2xl mx-auto space-y-6 p-4 md:p-8">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Novo Usuário</h1>
|
||||
<p className="text-sm text-gray-500">
|
||||
Preencha os dados para cadastrar um novo usuário no sistema.
|
||||
</p>
|
||||
</div>
|
||||
<Link href="/manager/usuario">
|
||||
<Button variant="outline">Cancelar</Button>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-8 bg-white p-8 border rounded-lg shadow-sm">
|
||||
|
||||
{/* Error Message Display */}
|
||||
{error && (
|
||||
<div className="p-3 bg-red-100 text-red-700 rounded-lg border border-red-300">
|
||||
<p className="font-medium">Erro no Cadastro:</p>
|
||||
<p className="text-sm">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="nomeCompleto">Nome Completo *</Label>
|
||||
<Input
|
||||
id="nomeCompleto"
|
||||
value={formData.nomeCompleto}
|
||||
onChange={(e) => handleInputChange("nomeCompleto", e.target.value)}
|
||||
placeholder="Nome e Sobrenome"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">E-mail *</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
value={formData.email}
|
||||
onChange={(e) => handleInputChange("email", e.target.value)}
|
||||
placeholder="exemplo@dominio.com"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Senha *</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
value={formData.password}
|
||||
onChange={(e) => handleInputChange("password", e.target.value)}
|
||||
placeholder="••••••••"
|
||||
required
|
||||
minLength={MIN_PASSWORD_LENGTH} // Adiciona validação HTML
|
||||
/>
|
||||
{/* MENSAGEM DE AJUDA PARA SENHA */}
|
||||
<p className="text-xs text-gray-500">Mínimo de {MIN_PASSWORD_LENGTH} caracteres.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="telefone">Telefone</Label>
|
||||
<Input
|
||||
id="telefone"
|
||||
value={formData.telefone}
|
||||
onChange={(e) => handleInputChange("telefone", e.target.value)}
|
||||
placeholder="(00) 00000-0000"
|
||||
maxLength={15}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="papel">Papel (Função) *</Label>
|
||||
<Select value={formData.papel} onValueChange={(v) => handleInputChange("papel", v)} required>
|
||||
<SelectTrigger id="papel">
|
||||
<SelectValue placeholder="Selecione uma função" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="gestor">Gestor</SelectItem>
|
||||
<SelectItem value="secretaria">Secretaria</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Action Buttons */}
|
||||
<div className="flex justify-end gap-4 pt-4">
|
||||
<Link href="/manager/usuario">
|
||||
<Button type="button" variant="outline" disabled={isSaving}>
|
||||
Cancelar
|
||||
</Button>
|
||||
</Link>
|
||||
<Button
|
||||
type="submit"
|
||||
className="bg-green-600 hover:bg-green-700"
|
||||
disabled={isSaving}
|
||||
>
|
||||
{isSaving ? (
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<Save className="w-4 h-4 mr-2" />
|
||||
)}
|
||||
{isSaving ? "Salvando..." : "Salvar Usuário"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="nomeCompleto">Nome Completo *</Label>
|
||||
<Input
|
||||
id="nomeCompleto"
|
||||
value={formData.nomeCompleto}
|
||||
onChange={(e) => handleInputChange("nomeCompleto", e.target.value)}
|
||||
placeholder="Nome e Sobrenome"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</ManagerLayout>
|
||||
);
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">E-mail *</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
value={formData.email}
|
||||
onChange={(e) => handleInputChange("email", e.target.value)}
|
||||
placeholder="exemplo@dominio.com"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Senha *</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
value={formData.password}
|
||||
onChange={(e) => handleInputChange("password", e.target.value)}
|
||||
placeholder="••••••••"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="telefone">Telefone</Label>
|
||||
<Input
|
||||
id="telefone"
|
||||
value={formData.telefone}
|
||||
onChange={(e) => handleInputChange("telefone", e.target.value)}
|
||||
placeholder="(00) 00000-0000"
|
||||
maxLength={15}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="papel">Papel (Função) *</Label>
|
||||
<Select value={formData.papel} onValueChange={(v) => handleInputChange("papel", v)} required>
|
||||
<SelectTrigger id="papel">
|
||||
<SelectValue placeholder="Selecione uma função" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="gestor">Gestor</SelectItem>
|
||||
<SelectItem value="secretaria">Secretaria</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Action Buttons */}
|
||||
<div className="flex justify-end gap-4 pt-4">
|
||||
<Link href="/manager/usuario">
|
||||
<Button type="button" variant="outline" disabled={isSaving}>
|
||||
Cancelar
|
||||
</Button>
|
||||
</Link>
|
||||
<Button
|
||||
type="submit"
|
||||
className="bg-green-600 hover:bg-green-700"
|
||||
disabled={isSaving}
|
||||
>
|
||||
{isSaving ? (
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<Save className="w-4 h-4 mr-2" />
|
||||
)}
|
||||
{isSaving ? "Salvando..." : "Salvar Usuário"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</ManagerLayout>
|
||||
);
|
||||
}
|
||||
@ -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,79 +16,57 @@ import {
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
} from "@/components/ui/alert-dialog"
|
||||
|
||||
import { usersService } from "services/usersApi.mjs";
|
||||
// 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' },
|
||||
|
||||
];
|
||||
},
|
||||
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 {
|
||||
user: {
|
||||
id: string;
|
||||
id: number;
|
||||
full_name: string;
|
||||
email: string;
|
||||
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;
|
||||
phone: string | null;
|
||||
role: 'admin' | 'gestor' | 'medico' | 'secretaria' | 'user';
|
||||
}
|
||||
|
||||
// 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<FlatUser[]>([]);
|
||||
const [users, setUsers] = useState<User[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
||||
const [userDetails, setUserDetails] = useState<User | null>(null);
|
||||
const [userDetails, setUserDetails] = useState<UserDetails | 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, 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.");
|
||||
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.");
|
||||
setUsers([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
@ -99,197 +77,169 @@ export default function UsersPage() {
|
||||
fetchUsers();
|
||||
}, [fetchUsers]);
|
||||
|
||||
|
||||
const openDetailsDialog = async (flatUser: FlatUser) => {
|
||||
const openDetailsDialog = (user: User) => {
|
||||
setUserDetails(user);
|
||||
setDetailsDialogOpen(true);
|
||||
setUserDetails(null);
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (userToDeleteId === null) return;
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
|
||||
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);
|
||||
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 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 (
|
||||
<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 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 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>
|
||||
|
||||
<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 ? (
|
||||
{/* 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...
|
||||
<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 ? (
|
||||
) : 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 encontrado.{" "}
|
||||
<Link href="/manager/usuario/novo" className="text-green-600 hover:underline">
|
||||
Adicione um novo
|
||||
</Link>
|
||||
.
|
||||
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 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" />
|
||||
) : (
|
||||
<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>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<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>
|
||||
|
||||
{/* 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>
|
||||
|
||||
<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>
|
||||
) : (
|
||||
{/* User Details Dialog */}
|
||||
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="text-2xl">{userDetails?.full_name}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{userDetails && (
|
||||
<div className="space-y-3 pt-2 text-left text-gray-700">
|
||||
|
||||
<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 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>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Fechar</AlertDialogCancel>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Fechar</AlertDialogCancel>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
</ManagerLayout>
|
||||
);
|
||||
}
|
||||
@ -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 {
|
||||
|
||||
@ -1,11 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import type React from "react";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { useRouter, usePathname } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import Cookies from "js-cookie"; // <-- 1. IMPORTAÇÃO ADICIONADA
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
@ -25,63 +24,43 @@ interface DoctorData {
|
||||
permissions: object;
|
||||
}
|
||||
|
||||
interface PatientLayoutProps {
|
||||
interface DoctorLayoutProps {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export default function DoctorLayout({ children }: PatientLayoutProps) {
|
||||
export default function DoctorLayout({ children }: DoctorLayoutProps) {
|
||||
const [doctorData, setDoctorData] = useState<DoctorData | null>(null);
|
||||
const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
|
||||
const [showLogoutDialog, setShowLogoutDialog] = useState(false);
|
||||
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
|
||||
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false); // Novo estado para menu mobile
|
||||
const [windowWidth, setWindowWidth] = useState(0);
|
||||
const isMobile = windowWidth < 1024;
|
||||
const isMobile = windowWidth < 1024; // breakpoint lg
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
|
||||
// ==================================================================
|
||||
// 2. BLOCO DE SEGURANÇA CORRIGIDO
|
||||
// ==================================================================
|
||||
useEffect(() => {
|
||||
const userInfoString = localStorage.getItem("user_info");
|
||||
const token = Cookies.get("access_token");
|
||||
|
||||
if (userInfoString && token) {
|
||||
const userInfo = JSON.parse(userInfoString);
|
||||
|
||||
// 3. "TRADUZIMOS" os dados da API para o formato que o layout espera
|
||||
setDoctorData({
|
||||
id: userInfo.id || "",
|
||||
name: userInfo.user_metadata?.full_name || "Doutor(a)",
|
||||
email: userInfo.email || "",
|
||||
specialty: userInfo.user_metadata?.specialty || "Especialidade",
|
||||
// Campos que não vêm do login, definidos como vazios para não quebrar
|
||||
phone: userInfo.phone || "",
|
||||
cpf: "",
|
||||
crm: "",
|
||||
department: "",
|
||||
permissions: {},
|
||||
});
|
||||
const data = localStorage.getItem("doctorData");
|
||||
if (data) {
|
||||
setDoctorData(JSON.parse(data));
|
||||
} else {
|
||||
// Se faltar o token ou os dados, volta para o login
|
||||
router.push("/doctor/login");
|
||||
}
|
||||
}, [router]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleResize = () => setWindowWidth(window.innerWidth);
|
||||
handleResize(); // inicializa com a largura atual
|
||||
window.addEventListener("resize", handleResize);
|
||||
return () => window.removeEventListener("resize", handleResize);
|
||||
}, []);
|
||||
const handleResize = () => setWindowWidth(window.innerWidth);
|
||||
handleResize(); // inicializa com a largura atual
|
||||
window.addEventListener("resize", handleResize);
|
||||
return () => window.removeEventListener("resize", handleResize);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (isMobile) {
|
||||
setSidebarCollapsed(true);
|
||||
} else {
|
||||
setSidebarCollapsed(false);
|
||||
}
|
||||
}, [isMobile]);
|
||||
useEffect(() => {
|
||||
if (isMobile) {
|
||||
setSidebarCollapsed(true);
|
||||
} else {
|
||||
setSidebarCollapsed(false);
|
||||
}
|
||||
}, [isMobile]);
|
||||
|
||||
const handleLogout = () => {
|
||||
setShowLogoutDialog(true);
|
||||
@ -103,7 +82,7 @@ useEffect(() => {
|
||||
|
||||
const menuItems = [
|
||||
{
|
||||
href: "#",
|
||||
href: "/doctor/dashboard",
|
||||
icon: Home,
|
||||
label: "Dashboard",
|
||||
// Botão para o dashboard do médico
|
||||
@ -133,17 +112,17 @@ useEffect(() => {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 flex">
|
||||
<div className="min-h-screen bg-background flex">
|
||||
{/* Sidebar para desktop */}
|
||||
<div className={`bg-white border-r border-gray-200 transition-all duration-300 ${sidebarCollapsed ? "w-16" : "w-64"} fixed left-0 top-0 h-screen flex flex-col z-50`}>
|
||||
<div className="p-4 border-b border-gray-200">
|
||||
<div className={`bg-card border-r border-border transition-all duration-300 ${sidebarCollapsed ? "w-16" : "w-64"} fixed left-0 top-0 h-screen flex flex-col z-50`}>
|
||||
<div className="p-4 border-b border-border">
|
||||
<div className="flex items-center justify-between">
|
||||
{!sidebarCollapsed && (
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center">
|
||||
<div className="w-4 h-4 bg-white rounded-sm"></div>
|
||||
<div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center">
|
||||
<div className="w-4 h-4 bg-primary-foreground rounded-sm"></div>
|
||||
</div>
|
||||
<span className="font-semibold text-gray-900">MidConnecta</span>
|
||||
<span className="font-semibold text-foreground">MidConnecta</span>
|
||||
</div>
|
||||
)}
|
||||
<Button variant="ghost" size="sm" onClick={() => setSidebarCollapsed(!sidebarCollapsed)} className="p-1">
|
||||
@ -159,7 +138,7 @@ useEffect(() => {
|
||||
|
||||
return (
|
||||
<Link key={item.href} href={item.href}>
|
||||
<div className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors ${isActive ? "bg-blue-50 text-blue-600 border-r-2 border-blue-600" : "text-gray-600 hover:bg-gray-50"}`}>
|
||||
<div className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors ${isActive ? "bg-accent text-accent-foreground" : "text-muted-foreground hover:bg-accent hover:text-accent-foreground"}`}>
|
||||
<Icon className="w-5 h-5 flex-shrink-0" />
|
||||
{!sidebarCollapsed && <span className="font-medium">{item.label}</span>}
|
||||
</div>
|
||||
@ -170,46 +149,62 @@ useEffect(() => {
|
||||
|
||||
// ... (seu código anterior)
|
||||
|
||||
{/* Sidebar para desktop */}
|
||||
<div className={`bg-white border-r border-gray-200 transition-all duration-300 ${sidebarCollapsed ? "w-16" : "w-64"} fixed left-0 top-0 h-screen flex flex-col z-50`}>
|
||||
<div className="p-4 border-b border-gray-200">
|
||||
<div className="flex items-center justify-between">
|
||||
{!sidebarCollapsed && (
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center">
|
||||
<div className="w-4 h-4 bg-white rounded-sm"></div>
|
||||
{/* Sidebar para desktop */}
|
||||
<div className={`bg-card border-r border-border transition-all duration-300 ${sidebarCollapsed ? "w-16" : "w-64"} fixed left-0 top-0 h-screen flex flex-col z-50`}>
|
||||
<div className="p-4 border-b border-border">
|
||||
<div className="flex items-center justify-between">
|
||||
{!sidebarCollapsed && (
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center">
|
||||
<div className="w-4 h-4 bg-primary-foreground rounded-sm"></div>
|
||||
</div>
|
||||
<span className="font-semibold text-foreground">MedConnect</span>
|
||||
</div>
|
||||
<span className="font-semibold text-gray-900">MedConnect</span>
|
||||
</div>
|
||||
)}
|
||||
<Button variant="ghost" size="sm" onClick={() => setSidebarCollapsed(!sidebarCollapsed)} className="p-1">
|
||||
{sidebarCollapsed ? <ChevronRight className="w-4 h-4" /> : <ChevronLeft className="w-4 h-4" />}
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="ghost" size="sm" onClick={() => setSidebarCollapsed(!sidebarCollapsed)} className="p-1">
|
||||
{sidebarCollapsed ? <ChevronRight className="w-4 h-4" /> : <ChevronLeft className="w-4 h-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<nav className="flex-1 p-2 overflow-y-auto">
|
||||
{menuItems.map((item) => {
|
||||
const Icon = item.icon;
|
||||
const isActive = pathname === item.href || (item.href !== "/" && pathname.startsWith(item.href));
|
||||
<nav className="flex-1 p-2 overflow-y-auto">
|
||||
{menuItems.map((item) => {
|
||||
const Icon = item.icon;
|
||||
const isActive = pathname === item.href || (item.href !== "/" && pathname.startsWith(item.href));
|
||||
|
||||
return (
|
||||
<Link key={item.href} href={item.href}>
|
||||
<div className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors ${isActive ? "bg-blue-50 text-blue-600 border-r-2 border-blue-600" : "text-gray-600 hover:bg-gray-50"}`}>
|
||||
<Icon className="w-5 h-5 flex-shrink-0" />
|
||||
{!sidebarCollapsed && <span className="font-medium">{item.label}</span>}
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
return (
|
||||
<Link key={item.href} href={item.href}>
|
||||
<div className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors ${isActive ? "bg-accent text-accent-foreground" : "text-muted-foreground hover:bg-accent hover:text-accent-foreground"}`}>
|
||||
<Icon className="w-5 h-5 flex-shrink-0" />
|
||||
{!sidebarCollapsed && <span className="font-medium">{item.label}</span>}
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
|
||||
<div className="border-t p-4 mt-auto">
|
||||
<div className="flex items-center space-x-3 mb-4">
|
||||
{/* Se a sidebar estiver recolhida, o avatar e o texto do usuário também devem ser condensados ou ocultados */}
|
||||
{!sidebarCollapsed && (
|
||||
<>
|
||||
<Avatar>
|
||||
<div className="border-t p-4 mt-auto">
|
||||
<div className="flex items-center space-x-3 mb-4">
|
||||
{/* Se a sidebar estiver recolhida, o avatar e o texto do usuário também devem ser condensados ou ocultados */}
|
||||
{!sidebarCollapsed && (
|
||||
<>
|
||||
<Avatar>
|
||||
<AvatarImage src="/placeholder.svg?height=40&width=40" />
|
||||
<AvatarFallback>
|
||||
{doctorData.name
|
||||
.split(" ")
|
||||
.map((n) => n[0])
|
||||
.join("")}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium text-foreground truncate">{doctorData.name}</p>
|
||||
<p className="text-xs text-muted-foreground truncate">{doctorData.specialty}</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{sidebarCollapsed && (
|
||||
<Avatar className="mx-auto"> {/* Centraliza o avatar quando recolhido */}
|
||||
<AvatarImage src="/placeholder.svg?height=40&width=40" />
|
||||
<AvatarFallback>
|
||||
{doctorData.name
|
||||
@ -218,49 +213,33 @@ useEffect(() => {
|
||||
.join("")}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium text-gray-900 truncate">{doctorData.name}</p>
|
||||
<p className="text-xs text-gray-500 truncate">{doctorData.specialty}</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{sidebarCollapsed && (
|
||||
<Avatar className="mx-auto"> {/* Centraliza o avatar quando recolhido */}
|
||||
<AvatarImage src="/placeholder.svg?height=40&width=40" />
|
||||
<AvatarFallback>
|
||||
{doctorData.name
|
||||
.split(" ")
|
||||
.map((n) => n[0])
|
||||
.join("")}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Novo botão de sair, usando a mesma estrutura dos itens de menu */}
|
||||
<div
|
||||
className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors text-gray-600 hover:bg-gray-50 cursor-pointer ${sidebarCollapsed ? "justify-center" : ""}`}
|
||||
onClick={handleLogout}
|
||||
>
|
||||
<LogOut className="w-5 h-5 flex-shrink-0" />
|
||||
{!sidebarCollapsed && <span className="font-medium">Sair</span>}
|
||||
{/* Novo botão de sair, usando a mesma estrutura dos itens de menu */}
|
||||
<div
|
||||
className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors text-muted-foreground hover:bg-accent hover:text-accent-foreground cursor-pointer ${sidebarCollapsed ? "justify-center" : ""}`}
|
||||
onClick={handleLogout}
|
||||
>
|
||||
<LogOut className="w-5 h-5 flex-shrink-0" />
|
||||
{!sidebarCollapsed && <span className="font-medium">Sair</span>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
{/* Sidebar para mobile (apresentado como um menu overlay) */}
|
||||
{isMobileMenuOpen && (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 z-40 md:hidden" onClick={toggleMobileMenu}></div>
|
||||
<div className="fixed inset-0 bg-background/50 z-40 md:hidden" onClick={toggleMobileMenu}></div>
|
||||
)}
|
||||
<div className={`bg-white border-r border-gray-200 fixed left-0 top-0 h-screen flex flex-col z-50 transition-transform duration-300 md:hidden ${isMobileMenuOpen ? "translate-x-0 w-64" : "-translate-x-full w-64"}`}>
|
||||
<div className="p-4 border-b border-gray-200 flex items-center justify-between">
|
||||
<div className={`bg-card border-r border-border fixed left-0 top-0 h-screen flex flex-col z-50 transition-transform duration-300 md:hidden ${isMobileMenuOpen ? "translate-x-0 w-64" : "-translate-x-full w-64"}`}>
|
||||
<div className="p-4 border-b border-border flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center">
|
||||
<div className="w-4 h-4 bg-white rounded-sm"></div>
|
||||
<div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center">
|
||||
<div className="w-4 h-4 bg-primary-foreground rounded-sm"></div>
|
||||
</div>
|
||||
<span className="font-semibold text-gray-900">Hospital System</span>
|
||||
<span className="font-semibold text-foreground">Hospital System</span>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" onClick={toggleMobileMenu} className="p-1">
|
||||
<X className="w-4 h-4" />
|
||||
@ -274,7 +253,7 @@ useEffect(() => {
|
||||
|
||||
return (
|
||||
<Link key={item.href} href={item.href} onClick={toggleMobileMenu}> {/* Fechar menu ao clicar */}
|
||||
<div className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors ${isActive ? "bg-blue-50 text-blue-600 border-r-2 border-blue-600" : "text-gray-600 hover:bg-gray-50"}`}>
|
||||
<div className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors ${isActive ? "bg-accent text-accent-foreground" : "text-muted-foreground hover:bg-accent hover:text-accent-foreground"}`}>
|
||||
<Icon className="w-5 h-5 flex-shrink-0" />
|
||||
<span className="font-medium">{item.label}</span>
|
||||
</div>
|
||||
@ -295,8 +274,8 @@ useEffect(() => {
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium text-gray-900 truncate">{doctorData.name}</p>
|
||||
<p className="text-xs text-gray-500 truncate">{doctorData.specialty}</p>
|
||||
<p className="text-sm font-medium text-foreground truncate">{doctorData.name}</p>
|
||||
<p className="text-xs text-muted-foreground truncate">{doctorData.specialty}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" className="w-full bg-transparent" onClick={() => { handleLogout(); toggleMobileMenu(); }}> {/* Fechar menu ao deslogar */}
|
||||
@ -308,21 +287,21 @@ useEffect(() => {
|
||||
|
||||
|
||||
{/* Main Content */}
|
||||
<div className={`flex-1 flex flex-col transition-all duration-300 ${sidebarCollapsed ? "ml-16" : "ml-64"}`}>
|
||||
<div className={`flex-1 flex flex-col transition-all duration-300 ${sidebarCollapsed ? "ml-16" : "ml-64"}`}>
|
||||
{/* Header */}
|
||||
<header className="bg-white border-b border-gray-200 px-6 py-4">
|
||||
<header className="bg-card border-b border-border px-6 py-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-4 flex-1">
|
||||
<div className="relative flex-1 max-w-md">
|
||||
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
|
||||
<Input placeholder="Buscar paciente" className="pl-10 bg-gray-50 border-gray-200" />
|
||||
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground w-4 h-4" />
|
||||
<Input placeholder="Buscar paciente" className="pl-10 bg-background border-border" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
<Button variant="ghost" size="sm" className="relative">
|
||||
<Bell className="w-5 h-5" />
|
||||
<Badge className="absolute -top-1 -right-1 w-5 h-5 p-0 flex items-center justify-center bg-red-500 text-white text-xs">1</Badge>
|
||||
<Badge className="absolute -top-1 -right-1 w-5 h-5 p-0 flex items-center justify-center bg-destructive text-destructive-foreground text-xs">1</Badge>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@ -4,8 +4,6 @@ import type React from "react";
|
||||
import { useState, useEffect } from "react";
|
||||
import { useRouter, usePathname } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import Cookies from "js-cookie"; // <-- 1. IMPORTAÇÃO ADICIONADA
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
@ -39,7 +37,7 @@ interface ManagerData {
|
||||
permissions: object;
|
||||
}
|
||||
|
||||
interface ManagerLayoutProps { // Corrigi o nome da prop aqui
|
||||
interface ManagerLayoutProps {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
@ -50,34 +48,15 @@ export default function ManagerLayout({ children }: ManagerLayoutProps) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
|
||||
// ==================================================================
|
||||
// 2. BLOCO DE SEGURANÇA CORRIGIDO
|
||||
// ==================================================================
|
||||
useEffect(() => {
|
||||
const userInfoString = localStorage.getItem("user_info");
|
||||
const token = Cookies.get("access_token");
|
||||
|
||||
if (userInfoString && token) {
|
||||
const userInfo = JSON.parse(userInfoString);
|
||||
|
||||
// 3. "TRADUZIMOS" os dados da API para o formato que o layout espera
|
||||
setManagerData({
|
||||
id: userInfo.id || "",
|
||||
name: userInfo.user_metadata?.full_name || "Gestor(a)",
|
||||
email: userInfo.email || "",
|
||||
department: userInfo.user_metadata?.role || "Gestão",
|
||||
// Campos que não vêm do login, definidos como vazios para não quebrar
|
||||
phone: userInfo.phone || "",
|
||||
cpf: "",
|
||||
permissions: {},
|
||||
});
|
||||
const data = localStorage.getItem("managerData");
|
||||
if (data) {
|
||||
setManagerData(JSON.parse(data));
|
||||
} else {
|
||||
// Se faltar o token ou os dados, volta para o login
|
||||
router.push("/manager/login");
|
||||
}
|
||||
}, [router]);
|
||||
|
||||
|
||||
// 🔥 Responsividade automática da sidebar
|
||||
useEffect(() => {
|
||||
const handleResize = () => {
|
||||
@ -105,9 +84,9 @@ export default function ManagerLayout({ children }: ManagerLayoutProps) {
|
||||
const cancelLogout = () => setShowLogoutDialog(false);
|
||||
|
||||
const menuItems = [
|
||||
{ href: "/manager/dashboard/", icon: Home, label: "Dashboard" },
|
||||
{ href: "/manager/dashboard", icon: Home, label: "Dashboard" },
|
||||
{ href: "#", icon: Calendar, label: "Relatórios gerenciais" },
|
||||
{ href: "/manager/usuario/", icon: User, label: "Gestão de Usuários" },
|
||||
{ href: "/manager/usuario", icon: User, label: "Gestão de Usuários" },
|
||||
{ href: "/manager/home", icon: User, label: "Gestão de Médicos" },
|
||||
{ href: "#", icon: Calendar, label: "Configurações" },
|
||||
];
|
||||
@ -117,20 +96,20 @@ export default function ManagerLayout({ children }: ManagerLayoutProps) {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 flex">
|
||||
<div className="min-h-screen bg-background flex">
|
||||
{/* Sidebar */}
|
||||
<div
|
||||
className={`bg-white border-r border-gray-200 transition-all duration-300 fixed top-0 h-screen flex flex-col z-30
|
||||
className={`bg-card border-r border-border transition-all duration-300 fixed top-0 h-screen flex flex-col z-30
|
||||
${sidebarCollapsed ? "w-16" : "w-64"}`}
|
||||
>
|
||||
{/* Logo + collapse button */}
|
||||
<div className="p-4 border-b border-gray-200 flex items-center justify-between">
|
||||
<div className="p-4 border-b border-border flex items-center justify-between">
|
||||
{!sidebarCollapsed && (
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center">
|
||||
<div className="w-4 h-4 bg-white rounded-sm"></div>
|
||||
<div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center">
|
||||
<div className="w-4 h-4 bg-primary-foreground rounded-sm"></div>
|
||||
</div>
|
||||
<span className="font-semibold text-gray-900">
|
||||
<span className="font-semibold text-foreground">
|
||||
MidConnecta
|
||||
</span>
|
||||
</div>
|
||||
@ -160,11 +139,10 @@ export default function ManagerLayout({ children }: ManagerLayoutProps) {
|
||||
return (
|
||||
<Link key={item.href} href={item.href}>
|
||||
<div
|
||||
className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors ${
|
||||
isActive
|
||||
? "bg-blue-50 text-blue-600 border-r-2 border-blue-600"
|
||||
: "text-gray-600 hover:bg-gray-50"
|
||||
}`}
|
||||
className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors ${isActive
|
||||
? "bg-accent text-accent-foreground"
|
||||
: "text-muted-foreground hover:bg-accent hover:text-accent-foreground"
|
||||
}`}
|
||||
>
|
||||
<Icon className="w-5 h-5 flex-shrink-0" />
|
||||
{!sidebarCollapsed && (
|
||||
@ -190,10 +168,10 @@ export default function ManagerLayout({ children }: ManagerLayoutProps) {
|
||||
</Avatar>
|
||||
{!sidebarCollapsed && (
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium text-gray-900 truncate">
|
||||
<p className="text-sm font-medium text-foreground truncate">
|
||||
{managerData.name}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 truncate">
|
||||
<p className="text-xs text-muted-foreground truncate">
|
||||
{managerData.department}
|
||||
</p>
|
||||
</div>
|
||||
@ -226,14 +204,14 @@ export default function ManagerLayout({ children }: ManagerLayoutProps) {
|
||||
${sidebarCollapsed ? "ml-16" : "ml-64"}`}
|
||||
>
|
||||
{/* Header */}
|
||||
<header className="bg-white border-b border-gray-200 px-4 md:px-6 py-4 flex items-center justify-between">
|
||||
<header className="bg-card border-b border-border px-4 md:px-6 py-4 flex items-center justify-between">
|
||||
{/* Search */}
|
||||
<div className="flex items-center gap-4 flex-1 max-w-md">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
|
||||
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground w-4 h-4" />
|
||||
<Input
|
||||
placeholder="Buscar paciente"
|
||||
className="pl-10 bg-gray-50 border-gray-200"
|
||||
className="pl-10 bg-background border-border"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@ -242,7 +220,7 @@ export default function ManagerLayout({ children }: ManagerLayoutProps) {
|
||||
<div className="flex items-center gap-4 ml-auto">
|
||||
<Button variant="ghost" size="sm" className="relative">
|
||||
<Bell className="w-5 h-5" />
|
||||
<Badge className="absolute -top-1 -right-1 w-5 h-5 p-0 flex items-center justify-center bg-red-500 text-white text-xs">
|
||||
<Badge className="absolute -top-1 -right-1 w-5 h-5 p-0 flex items-center justify-center bg-destructive text-destructive-foreground text-xs">
|
||||
1
|
||||
</Badge>
|
||||
</Button>
|
||||
|
||||
@ -1,23 +1,8 @@
|
||||
// services/usersApi.mjs (Versão Corrigida)
|
||||
|
||||
import { api } from "./api.mjs";
|
||||
|
||||
export const usersService = {
|
||||
create_user: (data) => api.post(`/functions/v1/create-user`),
|
||||
|
||||
// CORREÇÃO: Voltamos a pedir apenas os campos que sabemos que a view 'user_roles' tem
|
||||
// (id ou user_id, e role), e usamos o endpoint 'full_data' para obter os detalhes de nome/telefone.
|
||||
// SE a sua view 'user_roles' contiver uma coluna chamada 'user_id', tente a próxima linha:
|
||||
// list_roles: () => api.get(`/rest/v1/user_roles?select=user_id,role,profiles(full_name,phone)`),
|
||||
//
|
||||
// PORÉM, VAMOS ASSUMIR QUE A RELAÇÃO ESTÁ REALMENTE QUEBRADA E SIMPLIFICAR A CHAMADA INICIAL:
|
||||
list_roles: () => api.get(`/rest/v1/user_roles?select=id,user_id,email,role`),
|
||||
// Se o email também não estiver em 'user_roles', apenas use 'id,user_id,role'.
|
||||
// O importante é que esta chamada de API NÃO DÊ ERRO 400.
|
||||
|
||||
full_data: (id) => {
|
||||
const endpoint = `/functions/v1/user-info?user_id=${id}`;
|
||||
return api.get(endpoint);
|
||||
},
|
||||
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: () => api.get(`/functions/v1/user-info`),
|
||||
summary_data: () => api.get('/auth/v1/user')
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user