Compare commits

...

13 Commits

12 changed files with 1218 additions and 419 deletions

View File

@ -0,0 +1,279 @@
"use client"
import { useState, useEffect } from "react"
import { useRouter, useParams } 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 { Save, Loader2, ArrowLeft } from "lucide-react"
import ManagerLayout from "@/components/manager-layout"
// Mock user service for demonstration. Replace with your actual API service.
const usersService = {
getById: async (id: string): Promise<any> => {
console.log(`API Call: Fetching user with ID ${id}`);
await new Promise(resolve => setTimeout(resolve, 500));
// This mock finds a user from a predefined list.
const mockUsers = [
{ id: 1, full_name: 'Alice Admin', email: 'alice.admin@example.com', phone: '(11) 98765-4321', role: 'admin' },
{ id: 2, full_name: 'Bruno Gestor', email: 'bruno.g@example.com', phone: '(21) 91234-5678', role: 'gestor' },
{ id: 3, full_name: 'Dr. Carlos Médico', email: 'carlos.med@example.com', phone: null, role: 'medico' },
{ id: 4, full_name: 'Daniela Secretaria', email: 'daniela.sec@example.com', phone: '(31) 99999-8888', role: 'secretaria' },
{ id: 5, full_name: 'Eduardo Usuário', email: 'edu.user@example.com', phone: '(41) 98888-7777', role: 'user' },
];
const user = mockUsers.find(u => u.id.toString() === id);
if (!user) throw new Error("Usuário não encontrado.");
return user;
},
update: async (id: string, payload: any): Promise<void> => {
console.log(`API Call: Updating user ${id} with payload:`, payload);
await new Promise(resolve => setTimeout(resolve, 1000));
// To simulate an error (e.g., duplicate email), you could throw an error here:
// if (payload.email === 'bruno.g@example.com') throw new Error("Este e-mail já está em uso por outro usuário.");
}
};
// Interface for the user form data
interface UserFormData {
nomeCompleto: string;
email: string;
telefone: string;
papel: string;
password?: string; // Optional for password updates
}
// Default state for the form
const defaultFormData: UserFormData = {
nomeCompleto: '',
email: '',
telefone: '',
papel: '',
password: '',
};
// Helper functions for phone formatting
const cleanNumber = (value: string): string => value.replace(/\D/g, '');
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');
};
export default function EditarUsuarioPage() {
const router = useRouter();
const params = useParams();
const id = Array.isArray(params.id) ? params.id[0] : params.id;
const [formData, setFormData] = useState<UserFormData>(defaultFormData);
const [loading, setLoading] = useState(true);
const [isSaving, setIsSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
// Map API field names to our form field names
const apiToFormMap: { [key: string]: keyof UserFormData } = {
'full_name': 'nomeCompleto',
'email': 'email',
'phone': 'telefone',
'role': 'papel'
};
// Fetch user data when the component mounts
useEffect(() => {
if (!id) return;
const fetchUser = async () => {
try {
const data = await usersService.getById(id);
if (!data) {
setError("Usuário não encontrado.");
setLoading(false);
return;
}
const initialData: Partial<UserFormData> = {};
Object.keys(data).forEach(key => {
const formKey = apiToFormMap[key];
if (formKey) {
initialData[formKey] = data[key] === null ? '' : String(data[key]);
}
});
setFormData(prev => ({ ...prev, ...initialData }));
} catch (e: any) {
console.error("Erro ao carregar dados do usuário:", e);
setError(e.message || "Não foi possível carregar os dados do usuário.");
} finally {
setLoading(false);
}
};
fetchUser();
}, [id]);
const handleInputChange = (key: keyof UserFormData, value: string) => {
const updatedValue = key === 'telefone' ? formatPhone(value) : value;
setFormData((prev) => ({ ...prev, [key]: updatedValue }));
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setIsSaving(true);
if (!id) {
setError("ID do usuário ausente.");
setIsSaving(false);
return;
}
// Prepare payload for the API
const payload: { [key: string]: any } = {
full_name: formData.nomeCompleto,
email: formData.email,
phone: formData.telefone.trim() || null,
role: formData.papel,
};
// Only include the password in the payload if it has been changed
if (formData.password && formData.password.trim() !== '') {
payload.password = formData.password;
}
try {
await usersService.update(id, payload);
router.push("/manager/usuario");
} catch (e: any) {
console.error("Erro ao salvar o usuário:", e);
setError(e.message || "Ocorreu um erro inesperado ao atualizar.");
} finally {
setIsSaving(false);
}
};
if (loading) {
return (
<ManagerLayout>
<div className="flex justify-center items-center h-full w-full py-16">
<Loader2 className="w-8 h-8 animate-spin text-green-600" />
<p className="ml-2 text-gray-600">Carregando dados do usuário...</p>
</div>
</ManagerLayout>
);
}
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">
Editar Usuário: <span className="text-green-600">{formData.nomeCompleto}</span>
</h1>
<p className="text-sm text-gray-500">
Atualize as informações do usuário (ID: {id}).
</p>
</div>
<Link href="/manager/usuario">
<Button variant="outline">
<ArrowLeft className="w-4 h-4 mr-2" />
Voltar
</Button>
</Link>
</div>
<form onSubmit={handleSubmit} className="space-y-8 bg-white p-8 border rounded-lg shadow-sm">
{error && (
<div className="p-3 bg-red-100 text-red-700 rounded-lg border border-red-300">
<p className="font-medium">Erro na Atualização:</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)}
/>
</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)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="password">Nova Senha</Label>
<Input
id="password"
type="password"
value={formData.password}
onChange={(e) => handleInputChange("password", e.target.value)}
placeholder="Deixe em branco para não alterar"
/>
</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)}>
<SelectTrigger id="papel">
<SelectValue placeholder="Selecione uma função" />
</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>
</div>
<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 Alterações"}
</Button>
</div>
</form>
</div>
</ManagerLayout>
);
}

View File

@ -0,0 +1,214 @@
"use client"
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 { Save, Loader2 } from "lucide-react"
import ManagerLayout from "@/components/manager-layout"
// 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.
}
// 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, '');
// 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');
};
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);
// 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,
};
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);
}
};
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
/>
</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>
);
}

View File

@ -0,0 +1,245 @@
"use client";
import React, { useEffect, useState, useCallback } from "react"
import ManagerLayout from "@/components/manager-layout";
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 {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} 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' },
];
},
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;
email: 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<User[]>([]);
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 [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [userToDeleteId, setUserToDeleteId] = useState<number | null>(null);
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.");
setUsers([]);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchUsers();
}, [fetchUsers]);
const openDetailsDialog = (user: User) => {
setUserDetails(user);
setDetailsDialogOpen(true);
};
const handleDelete = async () => {
if (userToDeleteId === null) return;
setLoading(true);
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 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`);
};
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>
)}
</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>
{/* 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 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>
</ManagerLayout>
);
}

View File

@ -8,132 +8,145 @@ import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
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 { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Calendar, Clock, MapPin, Phone, CalendarDays, X, User } from "lucide-react"; import { Calendar, Clock, MapPin, Phone, User, Trash2, Pencil } from "lucide-react";
import { toast } from "sonner"; import { toast } from "sonner";
import Link from "next/link"; import Link from "next/link";
import { appointmentsService } from "@/services/appointmentsApi.mjs";
const APPOINTMENTS_STORAGE_KEY = "clinic-appointments"; import { patientsService } from "@/services/patientsApi.mjs";
import { doctorsService } from "@/services/doctorsApi.mjs";
const initialAppointments = [
{
id: 1,
patientName: "Carlos Pereira",
doctor: "Dr. João Silva",
specialty: "Cardiologia",
date: "2024-01-15",
time: "14:30",
status: "agendada",
location: "Consultório A - 2º andar",
phone: "(11) 3333-4444",
},
{
id: 2,
patientName: "Ana Beatriz Costa",
doctor: "Dra. Maria Santos",
specialty: "Dermatologia",
date: "2024-01-22",
time: "10:00",
status: "agendada",
location: "Consultório B - 1º andar",
phone: "(11) 3333-5555",
},
{
id: 3,
patientName: "Roberto Almeida",
doctor: "Dr. Pedro Costa",
specialty: "Ortopedia",
date: "2024-01-08",
time: "16:00",
status: "realizada",
location: "Consultório C - 3º andar",
phone: "(11) 3333-6666",
},
{
id: 4,
patientName: "Fernanda Lima",
doctor: "Dra. Ana Lima",
specialty: "Ginecologia",
date: "2024-01-05",
time: "09:30",
status: "realizada",
location: "Consultório D - 2º andar",
phone: "(11) 3333-7777",
},
];
export default function SecretaryAppointments() { export default function SecretaryAppointments() {
const [appointments, setAppointments] = useState<any[]>([]); const [appointments, setAppointments] = useState<any[]>([]);
const [rescheduleModal, setRescheduleModal] = useState(false); const [isLoading, setIsLoading] = useState(true);
const [cancelModal, setCancelModal] = useState(false);
const [selectedAppointment, setSelectedAppointment] = useState<any>(null); const [selectedAppointment, setSelectedAppointment] = useState<any>(null);
const [rescheduleData, setRescheduleData] = useState({ date: "", time: "", reason: "" });
const [cancelReason, setCancelReason] = useState(""); // Estados dos Modais
const [deleteModal, setDeleteModal] = useState(false);
const [editModal, setEditModal] = useState(false);
// Estado para o formulário de edição
const [editFormData, setEditFormData] = useState({
date: "",
time: "",
status: "",
});
const fetchData = async () => {
setIsLoading(true);
try {
const [appointmentList, patientList, doctorList] = await Promise.all([
appointmentsService.list(),
patientsService.list(),
doctorsService.list(),
]);
const patientMap = new Map(patientList.map((p: any) => [p.id, p]));
const doctorMap = new Map(doctorList.map((d: any) => [d.id, d]));
const enrichedAppointments = appointmentList.map((apt: any) => ({
...apt,
patient: patientMap.get(apt.patient_id) || { full_name: "Paciente não encontrado" },
doctor: doctorMap.get(apt.doctor_id) || { full_name: "Médico não encontrado", specialty: "N/A" },
}));
setAppointments(enrichedAppointments);
} catch (error) {
console.error("Falha ao buscar agendamentos:", error);
toast.error("Não foi possível carregar a lista de agendamentos.");
} finally {
setIsLoading(false);
}
};
useEffect(() => { useEffect(() => {
const storedAppointments = localStorage.getItem(APPOINTMENTS_STORAGE_KEY); fetchData();
if (storedAppointments) {
setAppointments(JSON.parse(storedAppointments));
} else {
setAppointments(initialAppointments);
localStorage.setItem(APPOINTMENTS_STORAGE_KEY, JSON.stringify(initialAppointments));
}
}, []); }, []);
const updateAppointments = (updatedAppointments: any[]) => { // --- LÓGICA DE EDIÇÃO ---
setAppointments(updatedAppointments); const handleEdit = (appointment: any) => {
localStorage.setItem(APPOINTMENTS_STORAGE_KEY, JSON.stringify(updatedAppointments));
};
const handleReschedule = (appointment: any) => {
setSelectedAppointment(appointment); setSelectedAppointment(appointment);
setRescheduleData({ date: "", time: "", reason: "" }); const appointmentDate = new Date(appointment.scheduled_at);
setRescheduleModal(true);
setEditFormData({
date: appointmentDate.toISOString().split('T')[0],
time: appointmentDate.toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit', timeZone: 'UTC' }),
status: appointment.status,
});
setEditModal(true);
}; };
const handleCancel = (appointment: any) => { const confirmEdit = async () => {
setSelectedAppointment(appointment); if (!selectedAppointment || !editFormData.date || !editFormData.time || !editFormData.status) {
setCancelReason(""); toast.error("Todos os campos são obrigatórios para a edição.");
setCancelModal(true);
};
const confirmReschedule = () => {
if (!rescheduleData.date || !rescheduleData.time) {
toast.error("Por favor, selecione uma nova data e horário");
return; return;
} }
const updated = appointments.map((apt) => (apt.id === selectedAppointment.id ? { ...apt, date: rescheduleData.date, time: rescheduleData.time } : apt));
updateAppointments(updated); try {
setRescheduleModal(false); const newScheduledAt = new Date(`${editFormData.date}T${editFormData.time}:00Z`).toISOString();
toast.success("Consulta reagendada com sucesso!"); const updatePayload = {
scheduled_at: newScheduledAt,
status: editFormData.status,
}; };
const confirmCancel = () => { await appointmentsService.update(selectedAppointment.id, updatePayload);
if (!cancelReason.trim() || cancelReason.trim().length < 10) {
toast.error("O motivo do cancelamento é obrigatório e deve ter no mínimo 10 caracteres."); setAppointments(prevAppointments =>
return; prevAppointments.map(apt =>
apt.id === selectedAppointment.id ? { ...apt, scheduled_at: newScheduledAt, status: editFormData.status } : apt
)
);
setEditModal(false);
toast.success("Consulta atualizada com sucesso!");
} catch (error) {
console.error("Erro ao atualizar consulta:", error);
toast.error("Não foi possível atualizar a consulta.");
} }
const updated = appointments.map((apt) => (apt.id === selectedAppointment.id ? { ...apt, status: "cancelada" } : apt));
updateAppointments(updated);
setCancelModal(false);
toast.success("Consulta cancelada com sucesso!");
}; };
// --- LÓGICA DE DELEÇÃO ---
const handleDelete = (appointment: any) => {
setSelectedAppointment(appointment);
setDeleteModal(true);
};
const confirmDelete = async () => {
if (!selectedAppointment) return;
try {
await appointmentsService.delete(selectedAppointment.id);
setAppointments((prev) => prev.filter((apt) => apt.id !== selectedAppointment.id));
setDeleteModal(false);
toast.success("Consulta deletada com sucesso!");
} catch (error) {
console.error("Erro ao deletar consulta:", error);
toast.error("Não foi possível deletar a consulta.");
}
};
// ** FUNÇÃO CORRIGIDA E MELHORADA **
const getStatusBadge = (status: string) => { const getStatusBadge = (status: string) => {
switch (status) { switch (status) {
case "agendada": case "requested":
return <Badge className="bg-blue-100 text-blue-800">Agendada</Badge>; return <Badge className="bg-yellow-100 text-yellow-800">Solicitada</Badge>;
case "realizada": case "confirmed":
return <Badge className="bg-blue-100 text-blue-800">Confirmada</Badge>;
case "checked_in":
return <Badge className="bg-indigo-100 text-indigo-800">Check-in</Badge>;
case "completed":
return <Badge className="bg-green-100 text-green-800">Realizada</Badge>; return <Badge className="bg-green-100 text-green-800">Realizada</Badge>;
case "cancelada": case "cancelled":
return <Badge className="bg-red-100 text-red-800">Cancelada</Badge>; return <Badge className="bg-red-100 text-red-800">Cancelada</Badge>;
case "no_show":
return <Badge className="bg-gray-100 text-gray-800">Não Compareceu</Badge>;
default: default:
return <Badge variant="secondary">{status}</Badge>; return <Badge variant="secondary">{status}</Badge>;
} }
}; };
const timeSlots = ["08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "11:00", "11:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00", "17:30"]; const timeSlots = ["08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "11:00", "11:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00", "17:30"];
const appointmentStatuses = ["requested", "confirmed", "checked_in", "completed", "cancelled", "no_show"];
return ( return (
<SecretaryLayout> <SecretaryLayout>
@ -144,22 +157,19 @@ export default function SecretaryAppointments() {
<p className="text-gray-600">Gerencie as consultas dos pacientes</p> <p className="text-gray-600">Gerencie as consultas dos pacientes</p>
</div> </div>
<Link href="/secretary/schedule"> <Link href="/secretary/schedule">
<Button> <Button><Calendar className="mr-2 h-4 w-4" /> Agendar Nova Consulta</Button>
<Calendar className="mr-2 h-4 w-4" />
Agendar Nova Consulta
</Button>
</Link> </Link>
</div> </div>
<div className="grid gap-6"> <div className="grid gap-6">
{appointments.length > 0 ? ( {isLoading ? <p>Carregando consultas...</p> : appointments.length > 0 ? (
appointments.map((appointment) => ( appointments.map((appointment) => (
<Card key={appointment.id}> <Card key={appointment.id}>
<CardHeader> <CardHeader>
<div className="flex justify-between items-start"> <div className="flex justify-between items-start">
<div> <div>
<CardTitle className="text-lg">{appointment.doctor}</CardTitle> <CardTitle className="text-lg">{appointment.doctor.full_name}</CardTitle>
<CardDescription>{appointment.specialty}</CardDescription> <CardDescription>{appointment.doctor.specialty}</CardDescription>
</div> </div>
{getStatusBadge(appointment.status)} {getStatusBadge(appointment.status)}
</div> </div>
@ -169,41 +179,39 @@ export default function SecretaryAppointments() {
<div className="space-y-3"> <div className="space-y-3">
<div className="flex items-center text-sm text-gray-800 font-medium"> <div className="flex items-center text-sm text-gray-800 font-medium">
<User className="mr-2 h-4 w-4 text-gray-600" /> <User className="mr-2 h-4 w-4 text-gray-600" />
{appointment.patientName} {appointment.patient.full_name}
</div> </div>
<div className="flex items-center text-sm text-gray-600"> <div className="flex items-center text-sm text-gray-600">
<Calendar className="mr-2 h-4 w-4" /> <Calendar className="mr-2 h-4 w-4" />
{new Date(appointment.date).toLocaleDateString("pt-BR", { timeZone: "UTC" })} {new Date(appointment.scheduled_at).toLocaleDateString("pt-BR", { timeZone: "UTC" })}
</div> </div>
<div className="flex items-center text-sm text-gray-600"> <div className="flex items-center text-sm text-gray-600">
<Clock className="mr-2 h-4 w-4" /> <Clock className="mr-2 h-4 w-4" />
{appointment.time} {new Date(appointment.scheduled_at).toLocaleTimeString("pt-BR", { hour: '2-digit', minute: '2-digit', timeZone: "UTC" })}
</div> </div>
</div> </div>
<div className="space-y-3"> <div className="space-y-3">
<div className="flex items-center text-sm text-gray-600"> <div className="flex items-center text-sm text-gray-600">
<MapPin className="mr-2 h-4 w-4" /> <MapPin className="mr-2 h-4 w-4" />
{appointment.location} {appointment.doctor.location || "Local a definir"}
</div> </div>
<div className="flex items-center text-sm text-gray-600"> <div className="flex items-center text-sm text-gray-600">
<Phone className="mr-2 h-4 w-4" /> <Phone className="mr-2 h-4 w-4" />
{appointment.phone} {appointment.doctor.phone || "N/A"}
</div> </div>
</div> </div>
</div> </div>
{appointment.status === "agendada" && (
<div className="flex gap-2 mt-4 pt-4 border-t"> <div className="flex gap-2 mt-4 pt-4 border-t">
<Button variant="outline" size="sm" onClick={() => handleReschedule(appointment)}> <Button variant="outline" size="sm" onClick={() => handleEdit(appointment)}>
<CalendarDays className="mr-2 h-4 w-4" /> <Pencil className="mr-2 h-4 w-4" />
Reagendar Editar
</Button> </Button>
<Button variant="outline" size="sm" className="text-red-600 hover:text-red-700 hover:bg-red-50 bg-transparent" onClick={() => handleCancel(appointment)}> <Button variant="outline" size="sm" className="text-red-600 hover:text-red-700 hover:bg-red-50 bg-transparent" onClick={() => handleDelete(appointment)}>
<X className="mr-2 h-4 w-4" /> <Trash2 className="mr-2 h-4 w-4" />
Cancelar Deletar
</Button> </Button>
</div> </div>
)}
</CardContent> </CardContent>
</Card> </Card>
)) ))
@ -213,68 +221,58 @@ export default function SecretaryAppointments() {
</div> </div>
</div> </div>
<Dialog open={rescheduleModal} onOpenChange={setRescheduleModal}> {/* MODAL DE EDIÇÃO */}
<Dialog open={editModal} onOpenChange={setEditModal}>
<DialogContent className="sm:max-w-[425px]"> <DialogContent className="sm:max-w-[425px]">
<DialogHeader> <DialogHeader>
<DialogTitle>Reagendar Consulta</DialogTitle> <DialogTitle>Editar Consulta</DialogTitle>
<DialogDescription>Reagendar consulta com {selectedAppointment?.doctor} para {selectedAppointment?.patientName}</DialogDescription> <DialogDescription>
Altere os dados da consulta de <strong>{selectedAppointment?.patient.full_name}</strong>.
</DialogDescription>
</DialogHeader> </DialogHeader>
<div className="grid gap-4 py-4"> <div className="grid gap-4 py-4">
<div className="grid gap-2"> <div className="grid gap-2">
<Label htmlFor="date">Nova Data</Label> <Label htmlFor="date">Nova Data</Label>
<Input id="date" type="date" value={rescheduleData.date} onChange={(e) => setRescheduleData((prev) => ({ ...prev, date: e.target.value }))} min={new Date().toISOString().split("T")[0]} /> <Input id="date" type="date" value={editFormData.date} onChange={(e) => setEditFormData(prev => ({ ...prev, date: e.target.value }))} min={new Date().toISOString().split("T")[0]} />
</div> </div>
<div className="grid gap-2"> <div className="grid gap-2">
<Label htmlFor="time">Novo Horário</Label> <Label htmlFor="time">Novo Horário</Label>
<Select value={rescheduleData.time} onValueChange={(value) => setRescheduleData((prev) => ({ ...prev, time: value }))}> <Select value={editFormData.time} onValueChange={(value) => setEditFormData(prev => ({ ...prev, time: value }))}>
<SelectTrigger> <SelectTrigger><SelectValue placeholder="Selecione um horário" /></SelectTrigger>
<SelectValue placeholder="Selecione um horário" />
</SelectTrigger>
<SelectContent> <SelectContent>
{timeSlots.map((time) => ( {timeSlots.map((time) => (<SelectItem key={time} value={time}>{time}</SelectItem>))}
<SelectItem key={time} value={time}>
{time}
</SelectItem>
))}
</SelectContent> </SelectContent>
</Select> </Select>
</div> </div>
<div className="grid gap-2"> <div className="grid gap-2">
<Label htmlFor="reason">Motivo do Reagendamento (opcional)</Label> <Label htmlFor="status">Status da Consulta</Label>
<Textarea id="reason" placeholder="Informe o motivo do reagendamento..." value={rescheduleData.reason} onChange={(e) => setRescheduleData((prev) => ({ ...prev, reason: e.target.value }))} /> <Select value={editFormData.status} onValueChange={(value) => setEditFormData(prev => ({ ...prev, status: value }))}>
<SelectTrigger><SelectValue placeholder="Selecione um status" /></SelectTrigger>
<SelectContent>
{appointmentStatuses.map((status) => (<SelectItem key={status} value={status}>{status}</SelectItem>))}
</SelectContent>
</Select>
</div> </div>
</div> </div>
<DialogFooter> <DialogFooter>
<Button variant="outline" onClick={() => setRescheduleModal(false)}> <Button variant="outline" onClick={() => setEditModal(false)}>Cancelar</Button>
Cancelar <Button onClick={confirmEdit}>Salvar Alterações</Button>
</Button>
<Button onClick={confirmReschedule}>Confirmar Reagendamento</Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
<Dialog open={cancelModal} onOpenChange={setCancelModal}> {/* Modal de Deleção */}
<Dialog open={deleteModal} onOpenChange={setDeleteModal}>
<DialogContent className="sm:max-w-[425px]"> <DialogContent className="sm:max-w-[425px]">
<DialogHeader> <DialogHeader>
<DialogTitle>Cancelar Consulta</DialogTitle> <DialogTitle>Deletar Consulta</DialogTitle>
<DialogDescription>Tem certeza que deseja cancelar a consulta de {selectedAppointment?.patientName} com {selectedAppointment?.doctor}?</DialogDescription> <DialogDescription>
Tem certeza que deseja deletar a consulta de <strong>{selectedAppointment?.patient.full_name}</strong>?
</DialogDescription>
</DialogHeader> </DialogHeader>
<div className="grid gap-4 py-4">
<div className="grid gap-2">
<Label htmlFor="cancel-reason" className="text-sm font-medium">
Motivo do Cancelamento <span className="text-red-500">*</span>
</Label>
<Textarea id="cancel-reason" placeholder="Por favor, informe o motivo do cancelamento... (obrigatório)" value={cancelReason} onChange={(e) => setCancelReason(e.target.value)} required className={`min-h-[100px] ${!cancelReason.trim() && cancelModal ? "border-red-300 focus:border-red-500" : ""}`} />
<p className="text-xs text-gray-500">Mínimo de 10 caracteres. Este campo é obrigatório.</p>
</div>
</div>
<DialogFooter> <DialogFooter>
<Button variant="outline" onClick={() => setCancelModal(false)}> <Button variant="outline" onClick={() => setDeleteModal(false)}>Cancelar</Button>
Voltar <Button variant="destructive" onClick={confirmDelete}>Confirmar Deleção</Button>
</Button>
<Button variant="destructive" onClick={confirmCancel} disabled={!cancelReason.trim() || cancelReason.trim().length < 10}>
Confirmar Cancelamento
</Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
</Dialog> </Dialog>

View File

@ -12,72 +12,104 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@
import { Textarea } from "@/components/ui/textarea"; import { Textarea } from "@/components/ui/textarea";
import { Calendar, Clock, User } from "lucide-react"; import { Calendar, Clock, User } from "lucide-react";
import { patientsService } from "@/services/patientsApi.mjs"; import { patientsService } from "@/services/patientsApi.mjs";
import { doctorsService } from "@/services/doctorsApi.mjs"; // Importar o serviço de médicos import { doctorsService } from "@/services/doctorsApi.mjs";
import { appointmentsService } from "@/services/appointmentsApi.mjs";
import { usersService } from "@/services/usersApi.mjs"; // 1. IMPORTAR O SERVIÇO DE USUÁRIOS
import { toast } from "sonner"; import { toast } from "sonner";
const APPOINTMENTS_STORAGE_KEY = "clinic-appointments";
export default function ScheduleAppointment() { export default function ScheduleAppointment() {
const router = useRouter(); const router = useRouter();
const [patients, setPatients] = useState<any[]>([]); const [patients, setPatients] = useState<any[]>([]);
const [doctors, setDoctors] = useState<any[]>([]); // Estado para armazenar os médicos da API const [doctors, setDoctors] = useState<any[]>([]);
const [currentUserId, setCurrentUserId] = useState<string | null>(null); // 2. NOVO ESTADO PARA O ID DO USUÁRIO
// Estados do formulário
const [selectedPatient, setSelectedPatient] = useState(""); const [selectedPatient, setSelectedPatient] = useState("");
const [selectedDoctor, setSelectedDoctor] = useState(""); const [selectedDoctor, setSelectedDoctor] = useState("");
const [selectedDate, setSelectedDate] = useState(""); const [selectedDate, setSelectedDate] = useState("");
const [selectedTime, setSelectedTime] = useState(""); const [selectedTime, setSelectedTime] = useState("");
const [notes, setNotes] = useState(""); const [appointmentType, setAppointmentType] = useState("presencial");
const [durationMinutes, setDurationMinutes] = useState("30");
const [chiefComplaint, setChiefComplaint] = useState("");
const [patientNotes, setPatientNotes] = useState("");
const [internalNotes, setInternalNotes] = useState("");
const [insuranceProvider, setInsuranceProvider] = useState("");
const availableTimes = [
"08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "11:00", "11:30",
"14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00", "17:30"
];
// Efeito para carregar todos os dados iniciais (pacientes, médicos e usuário atual)
useEffect(() => { useEffect(() => {
const fetchData = async () => { const fetchInitialData = async () => {
try { try {
// Carrega pacientes e médicos em paralelo para melhor performance // Busca tudo em paralelo para melhor performance
const [patientList, doctorList] = await Promise.all([ const [patientList, doctorList, currentUser] = await Promise.all([
patientsService.list(), patientsService.list(),
doctorsService.list() doctorsService.list(),
usersService.summary_data() // 3. CHAMADA PARA BUSCAR O USUÁRIO
]); ]);
setPatients(patientList); setPatients(patientList);
setDoctors(doctorList); setDoctors(doctorList);
if (currentUser && currentUser.id) {
setCurrentUserId(currentUser.id); // Armazena o ID do usuário no estado
console.log("Usuário logado identificado:", currentUser.id);
} else {
toast.error("Não foi possível identificar o usuário logado. O agendamento pode falhar.");
}
} catch (error) { } catch (error) {
console.error("Falha ao buscar dados iniciais:", error); console.error("Falha ao buscar dados iniciais:", error);
toast.error("Não foi possível carregar os dados de pacientes e médicos."); toast.error("Não foi possível carregar os dados necessários para a página.");
} }
}; };
fetchData(); fetchInitialData();
}, []); }, []);
const availableTimes = ["08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30"]; const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault(); e.preventDefault();
const patientDetails = patients.find((p) => String(p.id) === selectedPatient); // 4. ADICIONAR VALIDAÇÃO PARA O ID DO USUÁRIO
const doctorDetails = doctors.find((d) => String(d.id) === selectedDoctor); if (!currentUserId) {
toast.error("Sessão de usuário inválida. Por favor, faça login novamente.");
if (!patientDetails || !doctorDetails) {
toast.error("Erro ao encontrar detalhes do paciente ou médico.");
return; return;
} }
const newAppointment = { if (!selectedPatient || !selectedDoctor || !selectedDate || !selectedTime) {
id: new Date().getTime(), // ID único simples toast.error("Paciente, médico, data e horário são obrigatórios.");
patientName: patientDetails.full_name, return;
doctor: doctorDetails.full_name, // Usar full_name para consistência }
specialty: doctorDetails.specialty,
date: selectedDate, try {
time: selectedTime, const scheduledAt = new Date(`${selectedDate}T${selectedTime}:00Z`).toISOString();
status: "agendada",
location: doctorDetails.location || "Consultório a definir", // Fallback const newAppointmentData = {
phone: doctorDetails.phone || "N/A", // Fallback patient_id: selectedPatient,
doctor_id: selectedDoctor,
scheduled_at: scheduledAt,
duration_minutes: parseInt(durationMinutes, 10),
appointment_type: appointmentType,
status: "requested",
chief_complaint: chiefComplaint || null,
patient_notes: patientNotes || null,
notes: internalNotes || null,
insurance_provider: insuranceProvider || null,
created_by: currentUserId, // 5. INCLUIR O ID DO USUÁRIO NO OBJETO
}; };
const storedAppointmentsRaw = localStorage.getItem(APPOINTMENTS_STORAGE_KEY); console.log("Enviando dados do agendamento:", newAppointmentData); // Log para depuração
const currentAppointments = storedAppointmentsRaw ? JSON.parse(storedAppointmentsRaw) : [];
const updatedAppointments = [...currentAppointments, newAppointment];
localStorage.setItem(APPOINTMENTS_STORAGE_KEY, JSON.stringify(updatedAppointments)); await appointmentsService.create(newAppointmentData);
toast.success("Consulta agendada com sucesso!"); toast.success("Consulta agendada com sucesso!");
router.push("/secretary/appointments"); router.push("/secretary/appointments");
} catch (error) {
console.error("Erro ao criar agendamento:", error);
toast.error("Ocorreu um erro ao agendar a consulta. Tente novamente.");
}
}; };
return ( return (
@ -85,7 +117,7 @@ export default function ScheduleAppointment() {
<div className="space-y-6"> <div className="space-y-6">
<div> <div>
<h1 className="text-3xl font-bold text-gray-900">Agendar Consulta</h1> <h1 className="text-3xl font-bold text-gray-900">Agendar Consulta</h1>
<p className="text-gray-600">Escolha o paciente, médico, data e horário para a consulta</p> <p className="text-gray-600">Preencha os detalhes para criar um novo agendamento</p>
</div> </div>
<div className="grid lg:grid-cols-3 gap-6"> <div className="grid lg:grid-cols-3 gap-6">
@ -97,48 +129,14 @@ export default function ScheduleAppointment() {
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<form onSubmit={handleSubmit} className="space-y-6"> <form onSubmit={handleSubmit} className="space-y-6">
{/* O restante do formulário permanece exatamente o mesmo */}
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="patient">Paciente</Label> <Label htmlFor="patient">Paciente</Label>
<Select value={selectedPatient} onValueChange={setSelectedPatient}> <Select value={selectedPatient} onValueChange={setSelectedPatient}><SelectTrigger><SelectValue placeholder="Selecione um paciente" /></SelectTrigger><SelectContent>{patients.map((p) => (<SelectItem key={p.id} value={p.id}>{p.full_name}</SelectItem>))}</SelectContent></Select>
<SelectTrigger>
<SelectValue placeholder="Selecione um paciente" />
</SelectTrigger>
<SelectContent>
{patients.length > 0 ? (
patients.map((patient) => (
<SelectItem key={patient.id} value={String(patient.id)}>
{patient.full_name}
</SelectItem>
))
) : (
<SelectItem value="loading" disabled>
Carregando pacientes...
</SelectItem>
)}
</SelectContent>
</Select>
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="doctor">Médico</Label> <Label htmlFor="doctor">Médico</Label>
<Select value={selectedDoctor} onValueChange={setSelectedDoctor}> <Select value={selectedDoctor} onValueChange={setSelectedDoctor}><SelectTrigger><SelectValue placeholder="Selecione um médico" /></SelectTrigger><SelectContent>{doctors.map((d) => (<SelectItem key={d.id} value={d.id}>{d.full_name} - {d.specialty}</SelectItem>))}</SelectContent></Select>
<SelectTrigger>
<SelectValue placeholder="Selecione um médico" />
</SelectTrigger>
<SelectContent>
{doctors.length > 0 ? (
doctors.map((doctor) => (
<SelectItem key={doctor.id} value={String(doctor.id)}>
{doctor.full_name} - {doctor.specialty}
</SelectItem>
))
) : (
<SelectItem value="loading" disabled>
Carregando médicos...
</SelectItem>
)}
</SelectContent>
</Select>
</div> </div>
<div className="grid md:grid-cols-2 gap-4"> <div className="grid md:grid-cols-2 gap-4">
@ -146,7 +144,6 @@ export default function ScheduleAppointment() {
<Label htmlFor="date">Data</Label> <Label htmlFor="date">Data</Label>
<Input id="date" type="date" value={selectedDate} onChange={(e) => setSelectedDate(e.target.value)} min={new Date().toISOString().split("T")[0]} /> <Input id="date" type="date" value={selectedDate} onChange={(e) => setSelectedDate(e.target.value)} min={new Date().toISOString().split("T")[0]} />
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="time">Horário</Label> <Label htmlFor="time">Horário</Label>
<Select value={selectedTime} onValueChange={setSelectedTime}> <Select value={selectedTime} onValueChange={setSelectedTime}>
@ -164,12 +161,34 @@ export default function ScheduleAppointment() {
</div> </div>
</div> </div>
<div className="grid md:grid-cols-2 gap-4">
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="notes">Observações (opcional)</Label> <Label htmlFor="appointmentType">Tipo de Consulta</Label>
<Textarea id="notes" placeholder="Descreva brevemente o motivo da consulta ou observações importantes" value={notes} onChange={(e) => setNotes(e.target.value)} rows={3} /> <Select value={appointmentType} onValueChange={setAppointmentType}><SelectTrigger><SelectValue /></SelectTrigger><SelectContent><SelectItem value="presencial">Presencial</SelectItem><SelectItem value="telemedicina">Telemedicina</SelectItem></SelectContent></Select>
</div>
<div className="space-y-2">
<Label htmlFor="duration">Duração (minutos)</Label>
<Input id="duration" type="number" value={durationMinutes} onChange={(e) => setDurationMinutes(e.target.value)} placeholder="Ex: 30" />
</div>
</div>
<div className="space-y-2">
<Label htmlFor="insurance">Convênio (opcional)</Label>
<Input id="insurance" placeholder="Nome do convênio do paciente" value={insuranceProvider} onChange={(e) => setInsuranceProvider(e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="chiefComplaint">Queixa Principal (opcional)</Label>
<Textarea id="chiefComplaint" placeholder="Descreva brevemente o motivo da consulta..." value={chiefComplaint} onChange={(e) => setChiefComplaint(e.target.value)} rows={2} />
</div>
<div className="space-y-2">
<Label htmlFor="patientNotes">Observações do Paciente (opcional)</Label>
<Textarea id="patientNotes" placeholder="Anotações relevantes informadas pelo paciente..." value={patientNotes} onChange={(e) => setPatientNotes(e.target.value)} rows={2} />
</div>
<div className="space-y-2">
<Label htmlFor="internalNotes">Observações Internas (opcional)</Label>
<Textarea id="internalNotes" placeholder="Anotações para a equipe da clínica..." value={internalNotes} onChange={(e) => setInternalNotes(e.target.value)} rows={2} />
</div> </div>
<Button type="submit" className="w-full" disabled={!selectedPatient || !selectedDoctor || !selectedDate || !selectedTime}> <Button type="submit" className="w-full" disabled={!selectedPatient || !selectedDoctor || !selectedDate || !selectedTime || !currentUserId}>
Agendar Consulta Agendar Consulta
</Button> </Button>
</form> </form>
@ -178,61 +197,7 @@ export default function ScheduleAppointment() {
</div> </div>
<div className="space-y-6"> <div className="space-y-6">
<Card> {/* Card de Resumo e Informações Importantes */}
<CardHeader>
<CardTitle className="flex items-center">
<Calendar className="mr-2 h-5 w-5" />
Resumo
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{selectedPatient && (
<div className="flex items-start space-x-2">
<User className="h-4 w-4 text-gray-500 mt-1 flex-shrink-0" />
<div className="text-sm">
<span className="font-semibold text-gray-800">Paciente:</span>
<p className="text-gray-600">{patients.find((p) => String(p.id) === selectedPatient)?.full_name}</p>
</div>
</div>
)}
{selectedDoctor && (
<div className="flex items-start space-x-2">
<User className="h-4 w-4 text-gray-500 mt-1 flex-shrink-0" />
<div className="text-sm">
<span className="font-semibold text-gray-800">Médico:</span>
<p className="text-gray-600">{doctors.find((d) => String(d.id) === selectedDoctor)?.full_name}</p>
</div>
</div>
)}
{selectedDate && (
<div className="flex items-center space-x-2">
<Calendar className="h-4 w-4 text-gray-500" />
<span className="text-sm">{new Date(selectedDate).toLocaleDateString("pt-BR", { timeZone: "UTC" })}</span>
</div>
)}
{selectedTime && (
<div className="flex items-center space-x-2">
<Clock className="h-4 w-4 text-gray-500" />
<span className="text-sm">{selectedTime}</span>
</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Informações Importantes</CardTitle>
</CardHeader>
<CardContent className="text-sm text-gray-600 space-y-2">
<p> Chegue com 15 minutos de antecedência</p>
<p> Traga documento com foto</p>
<p> Traga carteirinha do convênio</p>
<p> Traga exames anteriores, se houver</p>
</CardContent>
</Card>
</div> </div>
</div> </div>
</div> </div>

View File

@ -1,10 +1,11 @@
"use client"; "use client";
import type React from "react"; import type React from "react";
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { useRouter, usePathname } from "next/navigation"; import { useRouter, usePathname } from "next/navigation";
import Link from "next/link"; import Link from "next/link";
import Cookies from "js-cookie"; // <-- 1. IMPORTAÇÃO ADICIONADA
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 { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
@ -24,25 +25,45 @@ interface DoctorData {
permissions: object; permissions: object;
} }
interface DoctorLayoutProps { interface PatientLayoutProps {
children: React.ReactNode; children: React.ReactNode;
} }
export default function DoctorLayout({ children }: DoctorLayoutProps) { export default function DoctorLayout({ children }: PatientLayoutProps) {
const [doctorData, setDoctorData] = useState<DoctorData | null>(null); const [doctorData, setDoctorData] = useState<DoctorData | null>(null);
const [sidebarCollapsed, setSidebarCollapsed] = useState(false); const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
const [showLogoutDialog, setShowLogoutDialog] = useState(false); const [showLogoutDialog, setShowLogoutDialog] = useState(false);
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false); // Novo estado para menu mobile const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
const [windowWidth, setWindowWidth] = useState(0); const [windowWidth, setWindowWidth] = useState(0);
const isMobile = windowWidth < 1024; // breakpoint lg const isMobile = windowWidth < 1024;
const router = useRouter(); const router = useRouter();
const pathname = usePathname(); const pathname = usePathname();
// ==================================================================
// 2. BLOCO DE SEGURANÇA CORRIGIDO
// ==================================================================
useEffect(() => { useEffect(() => {
const data = localStorage.getItem("doctorData"); const userInfoString = localStorage.getItem("user_info");
if (data) { const token = Cookies.get("access_token");
setDoctorData(JSON.parse(data));
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: {},
});
} else { } else {
// Se faltar o token ou os dados, volta para o login
router.push("/doctor/login"); router.push("/doctor/login");
} }
}, [router]); }, [router]);
@ -52,15 +73,15 @@ export default function DoctorLayout({ children }: DoctorLayoutProps) {
handleResize(); // inicializa com a largura atual handleResize(); // inicializa com a largura atual
window.addEventListener("resize", handleResize); window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize); return () => window.removeEventListener("resize", handleResize);
}, []); }, []);
useEffect(() => { useEffect(() => {
if (isMobile) { if (isMobile) {
setSidebarCollapsed(true); setSidebarCollapsed(true);
} else { } else {
setSidebarCollapsed(false); setSidebarCollapsed(false);
} }
}, [isMobile]); }, [isMobile]);
const handleLogout = () => { const handleLogout = () => {
setShowLogoutDialog(true); setShowLogoutDialog(true);
@ -82,7 +103,7 @@ export default function DoctorLayout({ children }: DoctorLayoutProps) {
const menuItems = [ const menuItems = [
{ {
href: "/doctor/dashboard", href: "#",
icon: Home, icon: Home,
label: "Dashboard", label: "Dashboard",
// Botão para o dashboard do médico // Botão para o dashboard do médico
@ -112,17 +133,17 @@ export default function DoctorLayout({ children }: DoctorLayoutProps) {
} }
return ( return (
<div className="min-h-screen bg-background flex"> <div className="min-h-screen bg-gray-50 flex">
{/* Sidebar para desktop */} {/* 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={`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-border"> <div className="p-4 border-b border-gray-200">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
{!sidebarCollapsed && ( {!sidebarCollapsed && (
<div className="flex items-center gap-2"> <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-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center">
<div className="w-4 h-4 bg-primary-foreground rounded-sm"></div> <div className="w-4 h-4 bg-white rounded-sm"></div>
</div> </div>
<span className="font-semibold text-foreground">MidConnecta</span> <span className="font-semibold text-gray-900">MidConnecta</span>
</div> </div>
)} )}
<Button variant="ghost" size="sm" onClick={() => setSidebarCollapsed(!sidebarCollapsed)} className="p-1"> <Button variant="ghost" size="sm" onClick={() => setSidebarCollapsed(!sidebarCollapsed)} className="p-1">
@ -138,7 +159,7 @@ export default function DoctorLayout({ children }: DoctorLayoutProps) {
return ( return (
<Link key={item.href} href={item.href}> <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"}`}> <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" /> <Icon className="w-5 h-5 flex-shrink-0" />
{!sidebarCollapsed && <span className="font-medium">{item.label}</span>} {!sidebarCollapsed && <span className="font-medium">{item.label}</span>}
</div> </div>
@ -150,15 +171,15 @@ export default function DoctorLayout({ children }: DoctorLayoutProps) {
// ... (seu código anterior) // ... (seu código anterior)
{/* Sidebar para desktop */} {/* 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={`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-border"> <div className="p-4 border-b border-gray-200">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
{!sidebarCollapsed && ( {!sidebarCollapsed && (
<div className="flex items-center gap-2"> <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-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center">
<div className="w-4 h-4 bg-primary-foreground rounded-sm"></div> <div className="w-4 h-4 bg-white rounded-sm"></div>
</div> </div>
<span className="font-semibold text-foreground">MedConnect</span> <span className="font-semibold text-gray-900">MedConnect</span>
</div> </div>
)} )}
<Button variant="ghost" size="sm" onClick={() => setSidebarCollapsed(!sidebarCollapsed)} className="p-1"> <Button variant="ghost" size="sm" onClick={() => setSidebarCollapsed(!sidebarCollapsed)} className="p-1">
@ -174,7 +195,7 @@ export default function DoctorLayout({ children }: DoctorLayoutProps) {
return ( return (
<Link key={item.href} href={item.href}> <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"}`}> <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" /> <Icon className="w-5 h-5 flex-shrink-0" />
{!sidebarCollapsed && <span className="font-medium">{item.label}</span>} {!sidebarCollapsed && <span className="font-medium">{item.label}</span>}
</div> </div>
@ -198,8 +219,8 @@ export default function DoctorLayout({ children }: DoctorLayoutProps) {
</AvatarFallback> </AvatarFallback>
</Avatar> </Avatar>
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<p className="text-sm font-medium text-foreground truncate">{doctorData.name}</p> <p className="text-sm font-medium text-gray-900 truncate">{doctorData.name}</p>
<p className="text-xs text-muted-foreground truncate">{doctorData.specialty}</p> <p className="text-xs text-gray-500 truncate">{doctorData.specialty}</p>
</div> </div>
</> </>
)} )}
@ -218,7 +239,7 @@ export default function DoctorLayout({ children }: DoctorLayoutProps) {
{/* Novo botão de sair, usando a mesma estrutura dos itens de menu */} {/* Novo botão de sair, usando a mesma estrutura dos itens de menu */}
<div <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" : ""}`} 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} onClick={handleLogout}
> >
<LogOut className="w-5 h-5 flex-shrink-0" /> <LogOut className="w-5 h-5 flex-shrink-0" />
@ -231,15 +252,15 @@ export default function DoctorLayout({ children }: DoctorLayoutProps) {
{/* Sidebar para mobile (apresentado como um menu overlay) */} {/* Sidebar para mobile (apresentado como um menu overlay) */}
{isMobileMenuOpen && ( {isMobileMenuOpen && (
<div className="fixed inset-0 bg-background/50 z-40 md:hidden" onClick={toggleMobileMenu}></div> <div className="fixed inset-0 bg-black bg-opacity-50 z-40 md:hidden" onClick={toggleMobileMenu}></div>
)} )}
<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={`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-border flex items-center justify-between"> <div className="p-4 border-b border-gray-200 flex items-center justify-between">
<div className="flex items-center gap-2"> <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-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center">
<div className="w-4 h-4 bg-primary-foreground rounded-sm"></div> <div className="w-4 h-4 bg-white rounded-sm"></div>
</div> </div>
<span className="font-semibold text-foreground">Hospital System</span> <span className="font-semibold text-gray-900">Hospital System</span>
</div> </div>
<Button variant="ghost" size="sm" onClick={toggleMobileMenu} className="p-1"> <Button variant="ghost" size="sm" onClick={toggleMobileMenu} className="p-1">
<X className="w-4 h-4" /> <X className="w-4 h-4" />
@ -253,7 +274,7 @@ export default function DoctorLayout({ children }: DoctorLayoutProps) {
return ( return (
<Link key={item.href} href={item.href} onClick={toggleMobileMenu}> {/* Fechar menu ao clicar */} <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-accent text-accent-foreground" : "text-muted-foreground hover:bg-accent hover:text-accent-foreground"}`}> <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" /> <Icon className="w-5 h-5 flex-shrink-0" />
<span className="font-medium">{item.label}</span> <span className="font-medium">{item.label}</span>
</div> </div>
@ -274,8 +295,8 @@ export default function DoctorLayout({ children }: DoctorLayoutProps) {
</AvatarFallback> </AvatarFallback>
</Avatar> </Avatar>
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<p className="text-sm font-medium text-foreground truncate">{doctorData.name}</p> <p className="text-sm font-medium text-gray-900 truncate">{doctorData.name}</p>
<p className="text-xs text-muted-foreground truncate">{doctorData.specialty}</p> <p className="text-xs text-gray-500 truncate">{doctorData.specialty}</p>
</div> </div>
</div> </div>
<Button variant="outline" size="sm" className="w-full bg-transparent" onClick={() => { handleLogout(); toggleMobileMenu(); }}> {/* Fechar menu ao deslogar */} <Button variant="outline" size="sm" className="w-full bg-transparent" onClick={() => { handleLogout(); toggleMobileMenu(); }}> {/* Fechar menu ao deslogar */}
@ -289,19 +310,19 @@ export default function DoctorLayout({ children }: DoctorLayoutProps) {
{/* Main Content */} {/* 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 */}
<header className="bg-card border-b border-border px-6 py-4"> <header className="bg-white border-b border-gray-200 px-6 py-4">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div className="flex items-center gap-4 flex-1"> <div className="flex items-center gap-4 flex-1">
<div className="relative flex-1 max-w-md"> <div className="relative flex-1 max-w-md">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground w-4 h-4" /> <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-background border-border" /> <Input placeholder="Buscar paciente" className="pl-10 bg-gray-50 border-gray-200" />
</div> </div>
</div> </div>
<div className="flex items-center gap-4"> <div className="flex items-center gap-4">
<Button variant="ghost" size="sm" className="relative"> <Button variant="ghost" size="sm" className="relative">
<Bell className="w-5 h-5" /> <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-destructive text-destructive-foreground text-xs">1</Badge> <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>
</Button> </Button>
</div> </div>
</div> </div>

View File

@ -1,5 +1,6 @@
"use client"; "use client";
import Cookies from "js-cookie";
import type React from "react"; import type React from "react";
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { useRouter, usePathname } from "next/navigation"; import { useRouter, usePathname } from "next/navigation";

View File

@ -4,6 +4,8 @@ import type React from "react";
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { useRouter, usePathname } from "next/navigation"; import { useRouter, usePathname } from "next/navigation";
import Link from "next/link"; import Link from "next/link";
import Cookies from "js-cookie"; // <-- 1. IMPORTAÇÃO ADICIONADA
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 { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
@ -37,7 +39,7 @@ interface ManagerData {
permissions: object; permissions: object;
} }
interface ManagerLayoutProps { interface ManagerLayoutProps { // Corrigi o nome da prop aqui
children: React.ReactNode; children: React.ReactNode;
} }
@ -48,15 +50,34 @@ export default function ManagerLayout({ children }: ManagerLayoutProps) {
const router = useRouter(); const router = useRouter();
const pathname = usePathname(); const pathname = usePathname();
// ==================================================================
// 2. BLOCO DE SEGURANÇA CORRIGIDO
// ==================================================================
useEffect(() => { useEffect(() => {
const data = localStorage.getItem("managerData"); const userInfoString = localStorage.getItem("user_info");
if (data) { const token = Cookies.get("access_token");
setManagerData(JSON.parse(data));
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: {},
});
} else { } else {
// Se faltar o token ou os dados, volta para o login
router.push("/manager/login"); router.push("/manager/login");
} }
}, [router]); }, [router]);
// 🔥 Responsividade automática da sidebar // 🔥 Responsividade automática da sidebar
useEffect(() => { useEffect(() => {
const handleResize = () => { const handleResize = () => {
@ -84,7 +105,7 @@ export default function ManagerLayout({ children }: ManagerLayoutProps) {
const cancelLogout = () => setShowLogoutDialog(false); const cancelLogout = () => setShowLogoutDialog(false);
const menuItems = [ const menuItems = [
{ href: "/manager/dashboard", icon: Home, label: "Dashboard" }, { href: "#", icon: Home, label: "Dashboard" },
{ href: "#", icon: Calendar, label: "Relatórios gerenciais" }, { href: "#", icon: Calendar, label: "Relatórios gerenciais" },
{ href: "#", icon: User, label: "Gestão de Usuários" }, { href: "#", icon: User, label: "Gestão de Usuários" },
{ href: "#", icon: User, label: "Gestão de Médicos" }, { href: "#", icon: User, label: "Gestão de Médicos" },
@ -96,20 +117,20 @@ export default function ManagerLayout({ children }: ManagerLayoutProps) {
} }
return ( return (
<div className="min-h-screen bg-background flex"> <div className="min-h-screen bg-gray-50 flex">
{/* Sidebar */} {/* Sidebar */}
<div <div
className={`bg-card border-r border-border transition-all duration-300 fixed top-0 h-screen flex flex-col z-30 className={`bg-white border-r border-gray-200 transition-all duration-300 fixed top-0 h-screen flex flex-col z-30
${sidebarCollapsed ? "w-16" : "w-64"}`} ${sidebarCollapsed ? "w-16" : "w-64"}`}
> >
{/* Logo + collapse button */} {/* Logo + collapse button */}
<div className="p-4 border-b border-border flex items-center justify-between"> <div className="p-4 border-b border-gray-200 flex items-center justify-between">
{!sidebarCollapsed && ( {!sidebarCollapsed && (
<div className="flex items-center gap-2"> <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-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center">
<div className="w-4 h-4 bg-primary-foreground rounded-sm"></div> <div className="w-4 h-4 bg-white rounded-sm"></div>
</div> </div>
<span className="font-semibold text-foreground"> <span className="font-semibold text-gray-900">
MidConnecta MidConnecta
</span> </span>
</div> </div>
@ -139,9 +160,10 @@ export default function ManagerLayout({ children }: ManagerLayoutProps) {
return ( return (
<Link key={item.href} href={item.href}> <Link key={item.href} href={item.href}>
<div <div
className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors ${isActive className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors ${
? "bg-accent text-accent-foreground" isActive
: "text-muted-foreground hover:bg-accent hover:text-accent-foreground" ? "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" /> <Icon className="w-5 h-5 flex-shrink-0" />
@ -168,10 +190,10 @@ export default function ManagerLayout({ children }: ManagerLayoutProps) {
</Avatar> </Avatar>
{!sidebarCollapsed && ( {!sidebarCollapsed && (
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<p className="text-sm font-medium text-foreground truncate"> <p className="text-sm font-medium text-gray-900 truncate">
{managerData.name} {managerData.name}
</p> </p>
<p className="text-xs text-muted-foreground truncate"> <p className="text-xs text-gray-500 truncate">
{managerData.department} {managerData.department}
</p> </p>
</div> </div>
@ -204,14 +226,14 @@ export default function ManagerLayout({ children }: ManagerLayoutProps) {
${sidebarCollapsed ? "ml-16" : "ml-64"}`} ${sidebarCollapsed ? "ml-16" : "ml-64"}`}
> >
{/* Header */} {/* Header */}
<header className="bg-card border-b border-border px-4 md:px-6 py-4 flex items-center justify-between"> <header className="bg-white border-b border-gray-200 px-4 md:px-6 py-4 flex items-center justify-between">
{/* Search */} {/* Search */}
<div className="flex items-center gap-4 flex-1 max-w-md"> <div className="flex items-center gap-4 flex-1 max-w-md">
<div className="relative flex-1"> <div className="relative flex-1">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground w-4 h-4" /> <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
<Input <Input
placeholder="Buscar paciente" placeholder="Buscar paciente"
className="pl-10 bg-background border-border" className="pl-10 bg-gray-50 border-gray-200"
/> />
</div> </div>
</div> </div>
@ -220,7 +242,7 @@ export default function ManagerLayout({ children }: ManagerLayoutProps) {
<div className="flex items-center gap-4 ml-auto"> <div className="flex items-center gap-4 ml-auto">
<Button variant="ghost" size="sm" className="relative"> <Button variant="ghost" size="sm" className="relative">
<Bell className="w-5 h-5" /> <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-destructive text-destructive-foreground text-xs"> <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 1
</Badge> </Badge>
</Button> </Button>

View File

@ -1,11 +1,12 @@
"use client" "use client"
import Cookies from "js-cookie";
import type React from "react" import type React from "react"
import { useState, useEffect } from "react" import { useState, useEffect } from "react"
import Link from "next/link" import Link from "next/link"
import { useRouter, usePathname } from "next/navigation" import { useRouter, usePathname } from "next/navigation"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import Cookies from "js-cookie"
import { Input } from "@/components/ui/input" import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge" import { Badge } from "@/components/ui/badge"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar" import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"

View File

@ -4,7 +4,7 @@ import type React from "react"
import { useState, useEffect } from "react" import { useState, useEffect } from "react"
import { useRouter, usePathname } from "next/navigation" import { useRouter, usePathname } from "next/navigation"
import Link from "next/link" import Link from "next/link"
import Cookies from "js-cookie";
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 { Badge } from "@/components/ui/badge" import { Badge } from "@/components/ui/badge"

View File

@ -0,0 +1,45 @@
import { api } from "./api.mjs";
export const appointmentsService = {
/**
* Busca por horários disponíveis para agendamento.
* @param {object} data - Critérios da busca (ex: { doctor_id, date }).
* @returns {Promise<Array>} - Uma promessa que resolve para uma lista de horários disponíveis.
*/
search_h: (data) => api.post('/functions/v1/get-available-slots', data),
/**
* Lista todos os agendamentos.
* @returns {Promise<Array>} - Uma promessa que resolve para a lista de agendamentos.
*/
list: () => api.get('/rest/v1/appointments'),
/**
* Cria um novo agendamento.
* @param {object} data - Os dados do agendamento a ser criado.
* @returns {Promise<object>} - Uma promessa que resolve para o agendamento criado.
*/
create: (data) => api.post('/rest/v1/appointments', data),
/**
* Busca agendamentos com base em parâmetros de consulta.
* @param {string} queryParams - A string de consulta (ex: 'patient_id=eq.123&status=eq.scheduled').
* @returns {Promise<Array>} - Uma promessa que resolve para a lista de agendamentos encontrados.
*/
search_appointment: (queryParams) => api.get(`/rest/v1/appointments?${queryParams}`),
/**
* Atualiza um agendamento existente.
* @param {string|number} id - O ID do agendamento a ser atualizado.
* @param {object} data - Os novos dados para o agendamento.
* @returns {Promise<object>} - Uma promessa que resolve com a resposta da API.
*/
update: (id, data) => api.patch(`/rest/v1/appointments?id=eq.${id}`, data),
/**
* Deleta um agendamento.
* @param {string|number} id - O ID do agendamento a ser deletado.
* @returns {Promise<object>} - Uma promessa que resolve com a resposta da API.
*/
delete: (id) => api.delete(`/rest/v1/appointments?id=eq.${id}`),
};

8
services/usersApi.mjs Normal file
View File

@ -0,0 +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')
}