forked from RiseUP/riseup-squad21
Compare commits
13 Commits
65087a9f51
...
55125f1c44
| Author | SHA1 | Date | |
|---|---|---|---|
| 55125f1c44 | |||
| c0f5239fbd | |||
| 8ec438169e | |||
|
|
009df09665 | ||
|
|
a82193af27 | ||
|
|
996ceabf25 | ||
| 1e658b5736 | |||
| befe6e16ce | |||
| 5b73a113ab | |||
| 296fc474a6 | |||
| faeedd469c | |||
| a76a4364fb | |||
| 117f5845d2 |
279
app/manager/usuario/[id]/editar/page.tsx
Normal file
279
app/manager/usuario/[id]/editar/page.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
214
app/manager/usuario/novo/page.tsx
Normal file
214
app/manager/usuario/novo/page.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
245
app/manager/usuario/page.tsx
Normal file
245
app/manager/usuario/page.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
@ -8,132 +8,145 @@ import { Badge } from "@/components/ui/badge";
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
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 Link from "next/link";
|
||||
|
||||
const APPOINTMENTS_STORAGE_KEY = "clinic-appointments";
|
||||
|
||||
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",
|
||||
},
|
||||
];
|
||||
import { appointmentsService } from "@/services/appointmentsApi.mjs";
|
||||
import { patientsService } from "@/services/patientsApi.mjs";
|
||||
import { doctorsService } from "@/services/doctorsApi.mjs";
|
||||
|
||||
export default function SecretaryAppointments() {
|
||||
const [appointments, setAppointments] = useState<any[]>([]);
|
||||
const [rescheduleModal, setRescheduleModal] = useState(false);
|
||||
const [cancelModal, setCancelModal] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
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(() => {
|
||||
const storedAppointments = localStorage.getItem(APPOINTMENTS_STORAGE_KEY);
|
||||
if (storedAppointments) {
|
||||
setAppointments(JSON.parse(storedAppointments));
|
||||
} else {
|
||||
setAppointments(initialAppointments);
|
||||
localStorage.setItem(APPOINTMENTS_STORAGE_KEY, JSON.stringify(initialAppointments));
|
||||
}
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
const updateAppointments = (updatedAppointments: any[]) => {
|
||||
setAppointments(updatedAppointments);
|
||||
localStorage.setItem(APPOINTMENTS_STORAGE_KEY, JSON.stringify(updatedAppointments));
|
||||
};
|
||||
|
||||
const handleReschedule = (appointment: any) => {
|
||||
// --- LÓGICA DE EDIÇÃO ---
|
||||
const handleEdit = (appointment: any) => {
|
||||
setSelectedAppointment(appointment);
|
||||
setRescheduleData({ date: "", time: "", reason: "" });
|
||||
setRescheduleModal(true);
|
||||
const appointmentDate = new Date(appointment.scheduled_at);
|
||||
|
||||
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) => {
|
||||
setSelectedAppointment(appointment);
|
||||
setCancelReason("");
|
||||
setCancelModal(true);
|
||||
};
|
||||
|
||||
const confirmReschedule = () => {
|
||||
if (!rescheduleData.date || !rescheduleData.time) {
|
||||
toast.error("Por favor, selecione uma nova data e horário");
|
||||
const confirmEdit = async () => {
|
||||
if (!selectedAppointment || !editFormData.date || !editFormData.time || !editFormData.status) {
|
||||
toast.error("Todos os campos são obrigatórios para a edição.");
|
||||
return;
|
||||
}
|
||||
const updated = appointments.map((apt) => (apt.id === selectedAppointment.id ? { ...apt, date: rescheduleData.date, time: rescheduleData.time } : apt));
|
||||
updateAppointments(updated);
|
||||
setRescheduleModal(false);
|
||||
toast.success("Consulta reagendada com sucesso!");
|
||||
};
|
||||
|
||||
const confirmCancel = () => {
|
||||
if (!cancelReason.trim() || cancelReason.trim().length < 10) {
|
||||
toast.error("O motivo do cancelamento é obrigatório e deve ter no mínimo 10 caracteres.");
|
||||
return;
|
||||
try {
|
||||
const newScheduledAt = new Date(`${editFormData.date}T${editFormData.time}:00Z`).toISOString();
|
||||
const updatePayload = {
|
||||
scheduled_at: newScheduledAt,
|
||||
status: editFormData.status,
|
||||
};
|
||||
|
||||
await appointmentsService.update(selectedAppointment.id, updatePayload);
|
||||
|
||||
setAppointments(prevAppointments =>
|
||||
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) => {
|
||||
switch (status) {
|
||||
case "agendada":
|
||||
return <Badge className="bg-blue-100 text-blue-800">Agendada</Badge>;
|
||||
case "realizada":
|
||||
case "requested":
|
||||
return <Badge className="bg-yellow-100 text-yellow-800">Solicitada</Badge>;
|
||||
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>;
|
||||
case "cancelada":
|
||||
case "cancelled":
|
||||
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:
|
||||
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 appointmentStatuses = ["requested", "confirmed", "checked_in", "completed", "cancelled", "no_show"];
|
||||
|
||||
return (
|
||||
<SecretaryLayout>
|
||||
@ -144,22 +157,19 @@ export default function SecretaryAppointments() {
|
||||
<p className="text-gray-600">Gerencie as consultas dos pacientes</p>
|
||||
</div>
|
||||
<Link href="/secretary/schedule">
|
||||
<Button>
|
||||
<Calendar className="mr-2 h-4 w-4" />
|
||||
Agendar Nova Consulta
|
||||
</Button>
|
||||
<Button><Calendar className="mr-2 h-4 w-4" /> Agendar Nova Consulta</Button>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6">
|
||||
{appointments.length > 0 ? (
|
||||
{isLoading ? <p>Carregando consultas...</p> : appointments.length > 0 ? (
|
||||
appointments.map((appointment) => (
|
||||
<Card key={appointment.id}>
|
||||
<CardHeader>
|
||||
<div className="flex justify-between items-start">
|
||||
<div>
|
||||
<CardTitle className="text-lg">{appointment.doctor}</CardTitle>
|
||||
<CardDescription>{appointment.specialty}</CardDescription>
|
||||
<CardTitle className="text-lg">{appointment.doctor.full_name}</CardTitle>
|
||||
<CardDescription>{appointment.doctor.specialty}</CardDescription>
|
||||
</div>
|
||||
{getStatusBadge(appointment.status)}
|
||||
</div>
|
||||
@ -169,41 +179,39 @@ export default function SecretaryAppointments() {
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center text-sm text-gray-800 font-medium">
|
||||
<User className="mr-2 h-4 w-4 text-gray-600" />
|
||||
{appointment.patientName}
|
||||
{appointment.patient.full_name}
|
||||
</div>
|
||||
<div className="flex items-center text-sm text-gray-600">
|
||||
<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 className="flex items-center text-sm text-gray-600">
|
||||
<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 className="space-y-3">
|
||||
<div className="flex items-center text-sm text-gray-600">
|
||||
<MapPin className="mr-2 h-4 w-4" />
|
||||
{appointment.location}
|
||||
{appointment.doctor.location || "Local a definir"}
|
||||
</div>
|
||||
<div className="flex items-center text-sm text-gray-600">
|
||||
<Phone className="mr-2 h-4 w-4" />
|
||||
{appointment.phone}
|
||||
{appointment.doctor.phone || "N/A"}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{appointment.status === "agendada" && (
|
||||
<div className="flex gap-2 mt-4 pt-4 border-t">
|
||||
<Button variant="outline" size="sm" onClick={() => handleReschedule(appointment)}>
|
||||
<CalendarDays className="mr-2 h-4 w-4" />
|
||||
Reagendar
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" className="text-red-600 hover:text-red-700 hover:bg-red-50 bg-transparent" onClick={() => handleCancel(appointment)}>
|
||||
<X className="mr-2 h-4 w-4" />
|
||||
Cancelar
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex gap-2 mt-4 pt-4 border-t">
|
||||
<Button variant="outline" size="sm" onClick={() => handleEdit(appointment)}>
|
||||
<Pencil className="mr-2 h-4 w-4" />
|
||||
Editar
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" className="text-red-600 hover:text-red-700 hover:bg-red-50 bg-transparent" onClick={() => handleDelete(appointment)}>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Deletar
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))
|
||||
@ -213,68 +221,58 @@ export default function SecretaryAppointments() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Dialog open={rescheduleModal} onOpenChange={setRescheduleModal}>
|
||||
{/* MODAL DE EDIÇÃO */}
|
||||
<Dialog open={editModal} onOpenChange={setEditModal}>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Reagendar Consulta</DialogTitle>
|
||||
<DialogDescription>Reagendar consulta com {selectedAppointment?.doctor} para {selectedAppointment?.patientName}</DialogDescription>
|
||||
<DialogTitle>Editar Consulta</DialogTitle>
|
||||
<DialogDescription>
|
||||
Altere os dados da consulta de <strong>{selectedAppointment?.patient.full_name}</strong>.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="grid gap-4 py-4">
|
||||
<div className="grid gap-2">
|
||||
<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 className="grid gap-2">
|
||||
<Label htmlFor="time">Novo Horário</Label>
|
||||
<Select value={rescheduleData.time} onValueChange={(value) => setRescheduleData((prev) => ({ ...prev, time: value }))}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Selecione um horário" />
|
||||
</SelectTrigger>
|
||||
<Select value={editFormData.time} onValueChange={(value) => setEditFormData(prev => ({ ...prev, time: value }))}>
|
||||
<SelectTrigger><SelectValue placeholder="Selecione um horário" /></SelectTrigger>
|
||||
<SelectContent>
|
||||
{timeSlots.map((time) => (
|
||||
<SelectItem key={time} value={time}>
|
||||
{time}
|
||||
</SelectItem>
|
||||
))}
|
||||
{timeSlots.map((time) => (<SelectItem key={time} value={time}>{time}</SelectItem>))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="reason">Motivo do Reagendamento (opcional)</Label>
|
||||
<Textarea id="reason" placeholder="Informe o motivo do reagendamento..." value={rescheduleData.reason} onChange={(e) => setRescheduleData((prev) => ({ ...prev, reason: e.target.value }))} />
|
||||
<Label htmlFor="status">Status da Consulta</Label>
|
||||
<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>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setRescheduleModal(false)}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button onClick={confirmReschedule}>Confirmar Reagendamento</Button>
|
||||
<Button variant="outline" onClick={() => setEditModal(false)}>Cancelar</Button>
|
||||
<Button onClick={confirmEdit}>Salvar Alterações</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={cancelModal} onOpenChange={setCancelModal}>
|
||||
{/* Modal de Deleção */}
|
||||
<Dialog open={deleteModal} onOpenChange={setDeleteModal}>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Cancelar Consulta</DialogTitle>
|
||||
<DialogDescription>Tem certeza que deseja cancelar a consulta de {selectedAppointment?.patientName} com {selectedAppointment?.doctor}?</DialogDescription>
|
||||
<DialogTitle>Deletar Consulta</DialogTitle>
|
||||
<DialogDescription>
|
||||
Tem certeza que deseja deletar a consulta de <strong>{selectedAppointment?.patient.full_name}</strong>?
|
||||
</DialogDescription>
|
||||
</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>
|
||||
<Button variant="outline" onClick={() => setCancelModal(false)}>
|
||||
Voltar
|
||||
</Button>
|
||||
<Button variant="destructive" onClick={confirmCancel} disabled={!cancelReason.trim() || cancelReason.trim().length < 10}>
|
||||
Confirmar Cancelamento
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => setDeleteModal(false)}>Cancelar</Button>
|
||||
<Button variant="destructive" onClick={confirmDelete}>Confirmar Deleção</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
@ -12,72 +12,104 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Calendar, Clock, User } from "lucide-react";
|
||||
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";
|
||||
|
||||
const APPOINTMENTS_STORAGE_KEY = "clinic-appointments";
|
||||
|
||||
export default function ScheduleAppointment() {
|
||||
const router = useRouter();
|
||||
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 [selectedDoctor, setSelectedDoctor] = useState("");
|
||||
const [selectedDate, setSelectedDate] = 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(() => {
|
||||
const fetchData = async () => {
|
||||
const fetchInitialData = async () => {
|
||||
try {
|
||||
// Carrega pacientes e médicos em paralelo para melhor performance
|
||||
const [patientList, doctorList] = await Promise.all([
|
||||
// Busca tudo em paralelo para melhor performance
|
||||
const [patientList, doctorList, currentUser] = await Promise.all([
|
||||
patientsService.list(),
|
||||
doctorsService.list()
|
||||
doctorsService.list(),
|
||||
usersService.summary_data() // 3. CHAMADA PARA BUSCAR O USUÁRIO
|
||||
]);
|
||||
|
||||
setPatients(patientList);
|
||||
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) {
|
||||
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 = (e: React.FormEvent) => {
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
const patientDetails = patients.find((p) => String(p.id) === selectedPatient);
|
||||
const doctorDetails = doctors.find((d) => String(d.id) === selectedDoctor);
|
||||
|
||||
if (!patientDetails || !doctorDetails) {
|
||||
toast.error("Erro ao encontrar detalhes do paciente ou médico.");
|
||||
// 4. ADICIONAR VALIDAÇÃO PARA O ID DO USUÁRIO
|
||||
if (!currentUserId) {
|
||||
toast.error("Sessão de usuário inválida. Por favor, faça login novamente.");
|
||||
return;
|
||||
}
|
||||
|
||||
const newAppointment = {
|
||||
id: new Date().getTime(), // ID único simples
|
||||
patientName: patientDetails.full_name,
|
||||
doctor: doctorDetails.full_name, // Usar full_name para consistência
|
||||
specialty: doctorDetails.specialty,
|
||||
date: selectedDate,
|
||||
time: selectedTime,
|
||||
status: "agendada",
|
||||
location: doctorDetails.location || "Consultório a definir", // Fallback
|
||||
phone: doctorDetails.phone || "N/A", // Fallback
|
||||
};
|
||||
if (!selectedPatient || !selectedDoctor || !selectedDate || !selectedTime) {
|
||||
toast.error("Paciente, médico, data e horário são obrigatórios.");
|
||||
return;
|
||||
}
|
||||
|
||||
const storedAppointmentsRaw = localStorage.getItem(APPOINTMENTS_STORAGE_KEY);
|
||||
const currentAppointments = storedAppointmentsRaw ? JSON.parse(storedAppointmentsRaw) : [];
|
||||
const updatedAppointments = [...currentAppointments, newAppointment];
|
||||
try {
|
||||
const scheduledAt = new Date(`${selectedDate}T${selectedTime}:00Z`).toISOString();
|
||||
|
||||
localStorage.setItem(APPOINTMENTS_STORAGE_KEY, JSON.stringify(updatedAppointments));
|
||||
const newAppointmentData = {
|
||||
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
|
||||
};
|
||||
|
||||
toast.success("Consulta agendada com sucesso!");
|
||||
router.push("/secretary/appointments");
|
||||
console.log("Enviando dados do agendamento:", newAppointmentData); // Log para depuração
|
||||
|
||||
await appointmentsService.create(newAppointmentData);
|
||||
|
||||
toast.success("Consulta agendada com sucesso!");
|
||||
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 (
|
||||
@ -85,7 +117,7 @@ export default function ScheduleAppointment() {
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<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 className="grid lg:grid-cols-3 gap-6">
|
||||
@ -97,48 +129,14 @@ export default function ScheduleAppointment() {
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
{/* O restante do formulário permanece exatamente o mesmo */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="patient">Paciente</Label>
|
||||
<Select value={selectedPatient} onValueChange={setSelectedPatient}>
|
||||
<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>
|
||||
<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>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="doctor">Médico</Label>
|
||||
<Select value={selectedDoctor} onValueChange={setSelectedDoctor}>
|
||||
<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>
|
||||
<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>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
@ -146,7 +144,6 @@ export default function ScheduleAppointment() {
|
||||
<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]} />
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="time">Horário</Label>
|
||||
<Select value={selectedTime} onValueChange={setSelectedTime}>
|
||||
@ -164,12 +161,34 @@ export default function ScheduleAppointment() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="appointmentType">Tipo de Consulta</Label>
|
||||
<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="notes">Observações (opcional)</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} />
|
||||
<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>
|
||||
|
||||
<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
|
||||
</Button>
|
||||
</form>
|
||||
@ -178,64 +197,10 @@ export default function ScheduleAppointment() {
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<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>
|
||||
{/* Card de Resumo e Informações Importantes */}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</SecretaryLayout>
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -1,10 +1,11 @@
|
||||
"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";
|
||||
@ -24,43 +25,63 @@ interface DoctorData {
|
||||
permissions: object;
|
||||
}
|
||||
|
||||
interface DoctorLayoutProps {
|
||||
interface PatientLayoutProps {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export default function DoctorLayout({ children }: DoctorLayoutProps) {
|
||||
export default function DoctorLayout({ children }: PatientLayoutProps) {
|
||||
const [doctorData, setDoctorData] = useState<DoctorData | null>(null);
|
||||
const [sidebarCollapsed, setSidebarCollapsed] = 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 isMobile = windowWidth < 1024; // breakpoint lg
|
||||
const isMobile = windowWidth < 1024;
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
|
||||
// ==================================================================
|
||||
// 2. BLOCO DE SEGURANÇA CORRIGIDO
|
||||
// ==================================================================
|
||||
useEffect(() => {
|
||||
const data = localStorage.getItem("doctorData");
|
||||
if (data) {
|
||||
setDoctorData(JSON.parse(data));
|
||||
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: {},
|
||||
});
|
||||
} 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);
|
||||
@ -82,7 +103,7 @@ export default function DoctorLayout({ children }: DoctorLayoutProps) {
|
||||
|
||||
const menuItems = [
|
||||
{
|
||||
href: "/doctor/dashboard",
|
||||
href: "#",
|
||||
icon: Home,
|
||||
label: "Dashboard",
|
||||
// Botão para o dashboard do médico
|
||||
@ -112,17 +133,17 @@ export default function DoctorLayout({ children }: DoctorLayoutProps) {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background flex">
|
||||
<div className="min-h-screen bg-gray-50 flex">
|
||||
{/* 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={`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-primary rounded-lg flex items-center justify-center">
|
||||
<div className="w-4 h-4 bg-primary-foreground rounded-sm"></div>
|
||||
<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>
|
||||
<span className="font-semibold text-foreground">MidConnecta</span>
|
||||
<span className="font-semibold text-gray-900">MidConnecta</span>
|
||||
</div>
|
||||
)}
|
||||
<Button variant="ghost" size="sm" onClick={() => setSidebarCollapsed(!sidebarCollapsed)} className="p-1">
|
||||
@ -138,7 +159,7 @@ export default function DoctorLayout({ children }: DoctorLayoutProps) {
|
||||
|
||||
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"}`}>
|
||||
<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>
|
||||
@ -149,62 +170,46 @@ export default function DoctorLayout({ children }: DoctorLayoutProps) {
|
||||
|
||||
// ... (seu código anterior)
|
||||
|
||||
{/* 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>
|
||||
{/* 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>
|
||||
</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>
|
||||
</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>
|
||||
</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-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>
|
||||
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>
|
||||
|
||||
<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 */}
|
||||
<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
|
||||
@ -213,33 +218,49 @@ export default function DoctorLayout({ children }: DoctorLayoutProps) {
|
||||
.join("")}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
)}
|
||||
</div>
|
||||
<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>
|
||||
|
||||
{/* 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>
|
||||
{/* 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>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
{/* Sidebar para mobile (apresentado como um menu overlay) */}
|
||||
{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="p-4 border-b border-border flex items-center justify-between">
|
||||
<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="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 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>
|
||||
<span className="font-semibold text-foreground">Hospital System</span>
|
||||
<span className="font-semibold text-gray-900">Hospital System</span>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" onClick={toggleMobileMenu} className="p-1">
|
||||
<X className="w-4 h-4" />
|
||||
@ -253,7 +274,7 @@ export default function DoctorLayout({ children }: DoctorLayoutProps) {
|
||||
|
||||
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-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" />
|
||||
<span className="font-medium">{item.label}</span>
|
||||
</div>
|
||||
@ -274,8 +295,8 @@ export default function DoctorLayout({ children }: DoctorLayoutProps) {
|
||||
</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>
|
||||
<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>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" className="w-full bg-transparent" onClick={() => { handleLogout(); toggleMobileMenu(); }}> {/* Fechar menu ao deslogar */}
|
||||
@ -287,21 +308,21 @@ export default function DoctorLayout({ children }: DoctorLayoutProps) {
|
||||
|
||||
|
||||
{/* 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-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 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-muted-foreground w-4 h-4" />
|
||||
<Input placeholder="Buscar paciente" className="pl-10 bg-background border-border" />
|
||||
<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" />
|
||||
</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-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>
|
||||
</div>
|
||||
</div>
|
||||
@ -331,4 +352,4 @@ export default function DoctorLayout({ children }: DoctorLayoutProps) {
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import Cookies from "js-cookie";
|
||||
import type React from "react";
|
||||
import { useState, useEffect } from "react";
|
||||
import { useRouter, usePathname } from "next/navigation";
|
||||
|
||||
@ -4,6 +4,8 @@ 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";
|
||||
@ -37,7 +39,7 @@ interface ManagerData {
|
||||
permissions: object;
|
||||
}
|
||||
|
||||
interface ManagerLayoutProps {
|
||||
interface ManagerLayoutProps { // Corrigi o nome da prop aqui
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
@ -48,15 +50,34 @@ export default function ManagerLayout({ children }: ManagerLayoutProps) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
|
||||
// ==================================================================
|
||||
// 2. BLOCO DE SEGURANÇA CORRIGIDO
|
||||
// ==================================================================
|
||||
useEffect(() => {
|
||||
const data = localStorage.getItem("managerData");
|
||||
if (data) {
|
||||
setManagerData(JSON.parse(data));
|
||||
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: {},
|
||||
});
|
||||
} 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 = () => {
|
||||
@ -84,7 +105,7 @@ export default function ManagerLayout({ children }: ManagerLayoutProps) {
|
||||
const cancelLogout = () => setShowLogoutDialog(false);
|
||||
|
||||
const menuItems = [
|
||||
{ href: "/manager/dashboard", icon: Home, label: "Dashboard" },
|
||||
{ href: "#", icon: Home, label: "Dashboard" },
|
||||
{ href: "#", icon: Calendar, label: "Relatórios gerenciais" },
|
||||
{ href: "#", icon: User, label: "Gestão de Usuários" },
|
||||
{ href: "#", icon: User, label: "Gestão de Médicos" },
|
||||
@ -96,20 +117,20 @@ export default function ManagerLayout({ children }: ManagerLayoutProps) {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background flex">
|
||||
<div className="min-h-screen bg-gray-50 flex">
|
||||
{/* Sidebar */}
|
||||
<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"}`}
|
||||
>
|
||||
{/* 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 && (
|
||||
<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 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>
|
||||
<span className="font-semibold text-foreground">
|
||||
<span className="font-semibold text-gray-900">
|
||||
MidConnecta
|
||||
</span>
|
||||
</div>
|
||||
@ -139,10 +160,11 @@ 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-accent text-accent-foreground"
|
||||
: "text-muted-foreground hover:bg-accent hover:text-accent-foreground"
|
||||
}`}
|
||||
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 && (
|
||||
@ -168,10 +190,10 @@ export default function ManagerLayout({ children }: ManagerLayoutProps) {
|
||||
</Avatar>
|
||||
{!sidebarCollapsed && (
|
||||
<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}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground truncate">
|
||||
<p className="text-xs text-gray-500 truncate">
|
||||
{managerData.department}
|
||||
</p>
|
||||
</div>
|
||||
@ -204,14 +226,14 @@ export default function ManagerLayout({ children }: ManagerLayoutProps) {
|
||||
${sidebarCollapsed ? "ml-16" : "ml-64"}`}
|
||||
>
|
||||
{/* 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 */}
|
||||
<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-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"
|
||||
className="pl-10 bg-gray-50 border-gray-200"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@ -220,7 +242,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-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
|
||||
</Badge>
|
||||
</Button>
|
||||
|
||||
@ -1,11 +1,12 @@
|
||||
"use client"
|
||||
|
||||
|
||||
import Cookies from "js-cookie";
|
||||
import type React from "react"
|
||||
import { useState, useEffect } from "react"
|
||||
import Link from "next/link"
|
||||
import { useRouter, usePathname } from "next/navigation"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import Cookies from "js-cookie"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
|
||||
|
||||
@ -4,7 +4,7 @@ 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";
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
|
||||
45
services/appointmentsApi.mjs
Normal file
45
services/appointmentsApi.mjs
Normal 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
8
services/usersApi.mjs
Normal 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')
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user