correção de erros #30

Merged
LiraS2 merged 1 commits from StsDanilo/riseup-squad21:main into main 2025-10-30 22:13:57 +00:00
7 changed files with 1003 additions and 1225 deletions

View File

@ -8,15 +8,45 @@ import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import DoctorLayout from "@/components/doctor-layout";
import { AvailabilityService } from "@/services/availabilityApi.mjs";
import { usersService } from "@/services/usersApi.mjs";
import { toast } from "@/hooks/use-toast";
import { useRouter } from "next/navigation";
interface UserPermissions {
isAdmin: boolean;
isManager: boolean;
isDoctor: boolean;
isSecretary: boolean;
isAdminOrManager: boolean;
}
interface UserData {
user: {
id: string;
email: string;
email_confirmed_at: string | null;
created_at: string | null;
last_sign_in_at: string | null;
};
profile: {
id: string;
full_name: string;
email: string;
phone: string;
avatar_url: string | null;
disabled: boolean;
created_at: string | null;
updated_at: string | null;
};
roles: string[];
permissions: UserPermissions;
}
export default function AvailabilityPage() {
const [error, setError] = useState<string | null>(null);
const router = useRouter();
const [isLoading, setIsLoading] = useState(false);
const userInfo = JSON.parse(localStorage.getItem("user_info") || "{}");
const doctorIdTemp = "3bb9ee4a-cfdd-4d81-b628-383907dfa225";
const [userData, setUserData] = useState<UserData>();
const [modalidadeConsulta, setModalidadeConsulta] = useState<string>("");
useEffect(() => {
@ -24,6 +54,9 @@ export default function AvailabilityPage() {
try {
const response = await AvailabilityService.list();
console.log(response);
const user = await usersService.getMe();
console.log(user);
setUserData(user);
} catch (e: any) {
alert(`${e?.error} ${e?.message}`);
}
@ -40,8 +73,7 @@ export default function AvailabilityPage() {
const formData = new FormData(form);
const apiPayload = {
doctor_id: doctorIdTemp,
created_by: doctorIdTemp,
doctor_id: userData?.user.id,
weekday: (formData.get("weekday") as string) || undefined,
start_time: (formData.get("horarioEntrada") as string) || undefined,
end_time: (formData.get("horarioSaida") as string) || undefined,

View File

@ -6,267 +6,176 @@ 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Save, Loader2, Pause } from "lucide-react";
import ManagerLayout from "@/components/manager-layout";
import { usersService } from "services/usersApi.mjs";
import { login } from "services/api.mjs";
interface UserFormData {
email: string;
nomeCompleto: string;
telefone: string;
papel: string;
senha: string;
confirmarSenha: string;
cpf : string
email: string;
nomeCompleto: string;
telefone: string;
papel: string;
senha: string;
confirmarSenha: string;
cpf: string;
}
const defaultFormData: UserFormData = {
email: "",
nomeCompleto: "",
telefone: "",
papel: "",
senha: "",
confirmarSenha: "",
cpf : ""
email: "",
nomeCompleto: "",
telefone: "",
papel: "",
senha: "",
confirmarSenha: "",
cpf: "",
};
const cleanNumber = (value: string): string => value.replace(/\D/g, "");
const formatPhone = (value: string): string => {
const cleaned = cleanNumber(value).substring(0, 11);
if (cleaned.length === 11)
return cleaned.replace(/(\d{2})(\d{5})(\d{4})/, "($1) $2-$3");
if (cleaned.length === 10)
return cleaned.replace(/(\d{2})(\d{4})(\d{4})/, "($1) $2-$3");
return cleaned;
const cleaned = cleanNumber(value).substring(0, 11);
if (cleaned.length === 11) return cleaned.replace(/(\d{2})(\d{5})(\d{4})/, "($1) $2-$3");
if (cleaned.length === 10) return cleaned.replace(/(\d{2})(\d{4})(\d{4})/, "($1) $2-$3");
return cleaned;
};
export default function NovoUsuarioPage() {
const router = useRouter();
const [formData, setFormData] = useState<UserFormData>(defaultFormData);
const [isSaving, setIsSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const router = useRouter();
const [formData, setFormData] = useState<UserFormData>(defaultFormData);
const [isSaving, setIsSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleInputChange = (key: keyof UserFormData, value: string) => {
const updatedValue = key === "telefone" ? formatPhone(value) : value;
setFormData((prev) => ({ ...prev, [key]: updatedValue }));
};
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);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
if (
!formData.email ||
!formData.nomeCompleto ||
!formData.papel ||
!formData.senha ||
!formData.confirmarSenha
) {
setError("Por favor, preencha todos os campos obrigatórios.");
return;
}
if (!formData.email || !formData.nomeCompleto || !formData.papel || !formData.senha || !formData.confirmarSenha) {
setError("Por favor, preencha todos os campos obrigatórios.");
return;
}
if (formData.senha !== formData.confirmarSenha) {
setError("A Senha e a Confirmação de Senha não coincidem.");
return;
}
if (formData.senha !== formData.confirmarSenha) {
setError("A Senha e a Confirmação de Senha não coincidem.");
return;
}
setIsSaving(true);
setIsSaving(true);
try {
await login();
try {
const payload = {
full_name: formData.nomeCompleto,
email: formData.email.trim().toLowerCase(),
phone: formData.telefone || null,
role: formData.papel,
password: formData.senha,
cpf: formData.cpf,
};
const payload = {
full_name: formData.nomeCompleto,
email: formData.email.trim().toLowerCase(),
phone: formData.telefone || null,
role: formData.papel,
password: formData.senha,
cpf : formData.cpf
};
console.log("📤 Enviando payload:");
console.log(payload);
console.log("📤 Enviando payload:", payload);
await usersService.create_user(payload);
await usersService.create_user(payload);
router.push("/manager/usuario");
} catch (e: any) {
console.error("Erro ao criar usuário:", e);
setError(e?.message || "Não foi possível criar o usuário. Verifique os dados e tente novamente.");
} finally {
setIsSaving(false);
}
};
router.push("/manager/usuario");
} catch (e: any) {
console.error("Erro ao criar usuário:", e);
setError(
e?.message ||
"Não foi possível criar o usuário. Verifique os dados e tente novamente."
);
} finally {
setIsSaving(false);
}
};
return (
<ManagerLayout>
<div className="w-full h-full p-4 md:p-8 flex justify-center items-start">
<div className="w-full max-w-screen-lg space-y-8">
<div className="flex items-center justify-between border-b pb-4">
<div>
<h1 className="text-3xl font-extrabold text-gray-900">Novo Usuário</h1>
<p className="text-md 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>
return (
<ManagerLayout>
<div className="w-full h-full p-4 md:p-8 flex justify-center items-start">
<div className="w-full max-w-screen-lg space-y-8">
<div className="flex items-center justify-between border-b pb-4">
<div>
<h1 className="text-3xl font-extrabold text-gray-900">
Novo Usuário
</h1>
<p className="text-md text-gray-500">
Preencha os dados para cadastrar um novo usuário no sistema.
</p>
<form onSubmit={handleSubmit} className="space-y-6 bg-white p-6 md:p-10 border rounded-xl shadow-lg">
{error && (
<div className="p-4 bg-red-50 text-red-700 rounded-lg border border-red-300">
<p className="font-semibold">Erro no Cadastro:</p>
<p className="text-sm break-words">{error}</p>
</div>
)}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="space-y-2 md:col-span-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="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="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="admin">Administrador</SelectItem>
<SelectItem value="gestor">Gestor</SelectItem>
<SelectItem value="medico">Médico</SelectItem>
<SelectItem value="secretaria">Secretária</SelectItem>
<SelectItem value="paciente">Usuário</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="senha">Senha *</Label>
<Input id="senha" type="password" value={formData.senha} onChange={(e) => handleInputChange("senha", e.target.value)} placeholder="Mínimo 8 caracteres" minLength={8} required />
</div>
<div className="space-y-2">
<Label htmlFor="confirmarSenha">Confirmar Senha *</Label>
<Input id="confirmarSenha" type="password" value={formData.confirmarSenha} onChange={(e) => handleInputChange("confirmarSenha", e.target.value)} placeholder="Repita a senha" required />
{formData.senha && formData.confirmarSenha && formData.senha !== formData.confirmarSenha && <p className="text-xs text-red-500">As senhas não coincidem.</p>}
</div>
<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>
<div className="space-y-2">
<Label htmlFor="cpf">Cpf *</Label>
<Input id="cpf" type="cpf" value={formData.cpf} onChange={(e) => handleInputChange("cpf", e.target.value)} placeholder="xxx.xxx.xxx-xx" required />
</div>
<div className="flex justify-end gap-4 pt-6 border-t mt-6">
<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>
</div>
<Link href="/manager/usuario">
<Button variant="outline">Cancelar</Button>
</Link>
</div>
<form
onSubmit={handleSubmit}
className="space-y-6 bg-white p-6 md:p-10 border rounded-xl shadow-lg"
>
{error && (
<div className="p-4 bg-red-50 text-red-700 rounded-lg border border-red-300">
<p className="font-semibold">Erro no Cadastro:</p>
<p className="text-sm break-words">{error}</p>
</div>
)}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="space-y-2 md:col-span-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="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="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="admin">Administrador</SelectItem>
<SelectItem value="gestor">Gestor</SelectItem>
<SelectItem value="medico">Médico</SelectItem>
<SelectItem value="secretaria">Secretária</SelectItem>
<SelectItem value="user">Usuário</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="senha">Senha *</Label>
<Input
id="senha"
type="password"
value={formData.senha}
onChange={(e) => handleInputChange("senha", e.target.value)}
placeholder="Mínimo 8 caracteres"
minLength={8}
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="confirmarSenha">Confirmar Senha *</Label>
<Input
id="confirmarSenha"
type="password"
value={formData.confirmarSenha}
onChange={(e) =>
handleInputChange("confirmarSenha", e.target.value)
}
placeholder="Repita a senha"
required
/>
{formData.senha &&
formData.confirmarSenha &&
formData.senha !== formData.confirmarSenha && (
<p className="text-xs text-red-500">
As senhas não coincidem.
</p>
)}
</div>
<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>
<div className="space-y-2">
<Label htmlFor="cpf">Cpf *</Label>
<Input
id="cpf"
type="cpf"
value={formData.cpf}
onChange={(e) => handleInputChange("cpf", e.target.value)}
placeholder="xxx.xxx.xxx-xx"
required
/>
</div>
<div className="flex justify-end gap-4 pt-6 border-t mt-6">
<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>
</div>
</ManagerLayout>
);
}
</ManagerLayout>
);
}

View File

@ -16,328 +16,309 @@ import { toast } from "sonner";
import { appointmentsService } from "@/services/appointmentsApi.mjs";
import { patientsService } from "@/services/patientsApi.mjs";
import { doctorsService } from "@/services/doctorsApi.mjs";
import { usersService } from "@/services/usersApi.mjs";
const APPOINTMENTS_STORAGE_KEY = "clinic-appointments";
// Simulação do paciente logado
const LOGGED_PATIENT_ID = "P001";
interface UserPermissions {
isAdmin: boolean;
isManager: boolean;
isDoctor: boolean;
isSecretary: boolean;
isAdminOrManager: boolean;
}
interface UserData {
user: {
id: string;
email: string;
email_confirmed_at: string | null;
created_at: string | null;
last_sign_in_at: string | null;
};
profile: {
id: string;
full_name: string;
email: string;
phone: string;
avatar_url: string | null;
disabled: boolean;
created_at: string | null;
updated_at: string | null;
};
roles: string[];
permissions: UserPermissions;
}
export default function PatientAppointments() {
const [appointments, setAppointments] = useState<any[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [selectedAppointment, setSelectedAppointment] = useState<any>(null);
const [appointments, setAppointments] = useState<any[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [selectedAppointment, setSelectedAppointment] = useState<any>(null);
const [userData, setUserData] = useState<UserData>();
// Modais
const [rescheduleModal, setRescheduleModal] = useState(false);
const [cancelModal, setCancelModal] = useState(false);
// Modais
const [rescheduleModal, setRescheduleModal] = useState(false);
const [cancelModal, setCancelModal] = useState(false);
// Formulário de reagendamento/cancelamento
const [rescheduleData, setRescheduleData] = useState({ date: "", time: "", reason: "" });
const [cancelReason, setCancelReason] = useState("");
// Formulário de reagendamento/cancelamento
const [rescheduleData, setRescheduleData] = useState({ date: "", time: "", reason: "" });
const [cancelReason, setCancelReason] = useState("");
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 fetchData = async () => {
setIsLoading(true);
try {
const [appointmentList, patientList, doctorList] = await Promise.all([
appointmentsService.list(),
patientsService.list(),
doctorsService.list(),
]);
const fetchData = async () => {
setIsLoading(true);
try {
const queryParams = "order=scheduled_at.desc";
const appointmentList = await appointmentsService.search_appointment(queryParams);
const patientList = await patientsService.list();
const doctorList = await doctorsService.list();
const doctorMap = new Map(doctorList.map((d: any) => [d.id, d]));
const patientMap = new Map(patientList.map((p: any) => [p.id, p]));
const user = await usersService.getMe();
setUserData(user);
// Filtra apenas as consultas do paciente logado
const patientAppointments = appointmentList
.filter((apt: any) => apt.patient_id === LOGGED_PATIENT_ID)
.map((apt: any) => ({
...apt,
doctor: doctorMap.get(apt.doctor_id) || { full_name: "Médico não encontrado", specialty: "N/A" },
patient: patientMap.get(apt.patient_id) || { full_name: "Paciente não encontrado" },
}));
const doctorMap = new Map(doctorList.map((d: any) => [d.id, d]));
const patientMap = new Map(patientList.map((p: any) => [p.id, p]));
setAppointments(patientAppointments);
} catch (error) {
console.error("Erro ao carregar consultas:", error);
toast.error("Não foi possível carregar suas consultas.");
} finally {
setIsLoading(false);
}
};
console.log(appointmentList);
useEffect(() => {
fetchData();
}, []);
// Filtra apenas as consultas do paciente logado
const patientAppointments = appointmentList
.filter((apt: any) => apt.patient_id === userData?.user.id)
.map((apt: any) => ({
...apt,
doctor: doctorMap.get(apt.doctor_id) || { full_name: "Médico não encontrado", specialty: "N/A" },
patient: patientMap.get(apt.patient_id) || { full_name: "Paciente não encontrado" },
}));
const getStatusBadge = (status: string) => {
switch (status) {
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 "cancelled":
return <Badge className="bg-red-100 text-red-800">Cancelada</Badge>;
default:
return <Badge variant="secondary">{status}</Badge>;
}
};
setAppointments(patientAppointments);
} catch (error) {
console.error("Erro ao carregar consultas:", error);
toast.error("Não foi possível carregar suas consultas.");
} finally {
setIsLoading(false);
}
};
const handleReschedule = (appointment: any) => {
setSelectedAppointment(appointment);
setRescheduleData({ date: "", time: "", reason: "" });
setRescheduleModal(true);
};
useEffect(() => {
fetchData();
}, []);
const handleCancel = (appointment: any) => {
setSelectedAppointment(appointment);
setCancelReason("");
setCancelModal(true);
};
const getStatusBadge = (status: string) => {
switch (status) {
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 "cancelled":
return <Badge className="bg-red-100 text-red-800">Cancelada</Badge>;
default:
return <Badge variant="secondary">{status}</Badge>;
}
};
const confirmReschedule = async () => {
if (!rescheduleData.date || !rescheduleData.time) {
toast.error("Por favor, selecione uma nova data e horário.");
return;
}
try {
const newScheduledAt = new Date(`${rescheduleData.date}T${rescheduleData.time}:00Z`).toISOString();
const handleReschedule = (appointment: any) => {
setSelectedAppointment(appointment);
setRescheduleData({ date: "", time: "", reason: "" });
setRescheduleModal(true);
};
await appointmentsService.update(selectedAppointment.id, {
scheduled_at: newScheduledAt,
status: "requested",
});
const handleCancel = (appointment: any) => {
setSelectedAppointment(appointment);
setCancelReason("");
setCancelModal(true);
};
setAppointments((prev) =>
prev.map((apt) =>
apt.id === selectedAppointment.id ? { ...apt, scheduled_at: newScheduledAt, status: "requested" } : apt
)
);
const confirmReschedule = async () => {
if (!rescheduleData.date || !rescheduleData.time) {
toast.error("Por favor, selecione uma nova data e horário.");
return;
}
try {
const newScheduledAt = new Date(`${rescheduleData.date}T${rescheduleData.time}:00Z`).toISOString();
setRescheduleModal(false);
toast.success("Consulta reagendada com sucesso!");
} catch (error) {
console.error("Erro ao reagendar consulta:", error);
toast.error("Não foi possível reagendar a consulta.");
}
};
await appointmentsService.update(selectedAppointment.id, {
scheduled_at: newScheduledAt,
status: "requested",
});
const confirmCancel = async () => {
if (!cancelReason.trim() || cancelReason.trim().length < 10) {
toast.error("Por favor, informe um motivo de cancelamento (mínimo 10 caracteres).");
return;
}
try {
await appointmentsService.update(selectedAppointment.id, {
status: "cancelled",
cancel_reason: cancelReason,
});
setAppointments((prev) => prev.map((apt) => (apt.id === selectedAppointment.id ? { ...apt, scheduled_at: newScheduledAt, status: "requested" } : apt)));
setAppointments((prev) =>
prev.map((apt) =>
apt.id === selectedAppointment.id ? { ...apt, status: "cancelled" } : apt
)
);
setRescheduleModal(false);
toast.success("Consulta reagendada com sucesso!");
} catch (error) {
console.error("Erro ao reagendar consulta:", error);
toast.error("Não foi possível reagendar a consulta.");
}
};
setCancelModal(false);
toast.success("Consulta cancelada com sucesso!");
} catch (error) {
console.error("Erro ao cancelar consulta:", error);
toast.error("Não foi possível cancelar a consulta.");
}
};
const confirmCancel = async () => {
if (!cancelReason.trim() || cancelReason.trim().length < 10) {
toast.error("Por favor, informe um motivo de cancelamento (mínimo 10 caracteres).");
return;
}
try {
await appointmentsService.update(selectedAppointment.id, {
status: "cancelled",
cancel_reason: cancelReason,
});
return (
<PatientLayout>
<div className="space-y-6">
<div className="flex justify-between items-center">
<div>
<h1 className="text-3xl font-bold text-gray-900">Minhas Consultas</h1>
<p className="text-gray-600">Veja, reagende ou cancele suas consultas</p>
</div>
</div>
setAppointments((prev) => prev.map((apt) => (apt.id === selectedAppointment.id ? { ...apt, status: "cancelled" } : apt)));
<div className="grid gap-6">
{isLoading ? (
<p>Carregando suas consultas...</p>
) : appointments.length > 0 ? (
appointments.map((appointment) => (
<Card key={appointment.id}>
<CardHeader>
<div className="flex justify-between items-start">
setCancelModal(false);
toast.success("Consulta cancelada com sucesso!");
} catch (error) {
console.error("Erro ao cancelar consulta:", error);
toast.error("Não foi possível cancelar a consulta.");
}
};
return (
<PatientLayout>
<div className="space-y-6">
<div className="flex justify-between items-center">
<div>
<CardTitle className="text-lg">{appointment.doctor.full_name}</CardTitle>
<CardDescription>{appointment.doctor.specialty}</CardDescription>
<h1 className="text-3xl font-bold text-gray-900">Minhas Consultas</h1>
<p className="text-gray-600">Veja, reagende ou cancele suas consultas</p>
</div>
{getStatusBadge(appointment.status)}
</div>
</CardHeader>
<CardContent>
<div className="grid md:grid-cols-2 gap-3">
<div className="space-y-2 text-sm text-gray-700">
<div className="flex items-center">
<Calendar className="mr-2 h-4 w-4 text-gray-500" />
{new Date(appointment.scheduled_at).toLocaleDateString("pt-BR", { timeZone: "UTC" })}
</div>
<div className="flex items-center">
<Clock className="mr-2 h-4 w-4 text-gray-500" />
{new Date(appointment.scheduled_at).toLocaleTimeString("pt-BR", {
hour: "2-digit",
minute: "2-digit",
timeZone: "UTC",
})}
</div>
<div className="flex items-center">
<MapPin className="mr-2 h-4 w-4 text-gray-500" />
{appointment.doctor.location || "Local a definir"}
</div>
<div className="flex items-center">
<Phone className="mr-2 h-4 w-4 text-gray-500" />
{appointment.doctor.phone || "N/A"}
</div>
</div>
<div className="grid gap-6">
{isLoading ? (
<p>Carregando suas 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.full_name}</CardTitle>
<CardDescription>{appointment.doctor.specialty}</CardDescription>
</div>
{getStatusBadge(appointment.status)}
</div>
</CardHeader>
<CardContent>
<div className="grid md:grid-cols-2 gap-3">
<div className="space-y-2 text-sm text-gray-700">
<div className="flex items-center">
<Calendar className="mr-2 h-4 w-4 text-gray-500" />
{new Date(appointment.scheduled_at).toLocaleDateString("pt-BR", { timeZone: "UTC" })}
</div>
<div className="flex items-center">
<Clock className="mr-2 h-4 w-4 text-gray-500" />
{new Date(appointment.scheduled_at).toLocaleTimeString("pt-BR", {
hour: "2-digit",
minute: "2-digit",
timeZone: "UTC",
})}
</div>
<div className="flex items-center">
<MapPin className="mr-2 h-4 w-4 text-gray-500" />
{appointment.doctor.location || "Local a definir"}
</div>
<div className="flex items-center">
<Phone className="mr-2 h-4 w-4 text-gray-500" />
{appointment.doctor.phone || "N/A"}
</div>
</div>
</div>
{appointment.status !== "cancelled" && (
<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" onClick={() => handleCancel(appointment)}>
<X className="mr-2 h-4 w-4" />
Cancelar
</Button>
</div>
)}
</CardContent>
</Card>
))
) : (
<p className="text-gray-600">Você ainda não possui consultas agendadas.</p>
)}
</div>
</div>
{/* MODAL DE REAGENDAMENTO */}
<Dialog open={rescheduleModal} onOpenChange={setRescheduleModal}>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>Reagendar Consulta</DialogTitle>
<DialogDescription>
Escolha uma nova data e horário para sua consulta com <strong>{selectedAppointment?.doctor?.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]} />
</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>
<SelectContent>
{timeSlots.map((time) => (
<SelectItem key={time} value={time}>
{time}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="grid gap-2">
<Label htmlFor="reason">Motivo (opcional)</Label>
<Textarea id="reason" placeholder="Explique brevemente o motivo do reagendamento..." value={rescheduleData.reason} onChange={(e) => setRescheduleData((prev) => ({ ...prev, reason: e.target.value }))} />
</div>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setRescheduleModal(false)}>
Cancelar
</Button>
<Button onClick={confirmReschedule}>Confirmar</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{appointment.status !== "cancelled" && (
<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"
onClick={() => handleCancel(appointment)}
>
<X className="mr-2 h-4 w-4" />
Cancelar
</Button>
{/* MODAL DE CANCELAMENTO */}
<Dialog open={cancelModal} onOpenChange={setCancelModal}>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>Cancelar Consulta</DialogTitle>
<DialogDescription>
Deseja realmente cancelar sua consulta com <strong>{selectedAppointment?.doctor?.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="Informe o motivo do cancelamento (mínimo 10 caracteres)" value={cancelReason} onChange={(e) => setCancelReason(e.target.value)} className="min-h-[100px]" />
</div>
</div>
)}
</CardContent>
</Card>
))
) : (
<p className="text-gray-600">Você ainda não possui consultas agendadas.</p>
)}
</div>
</div>
{/* MODAL DE REAGENDAMENTO */}
<Dialog open={rescheduleModal} onOpenChange={setRescheduleModal}>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>Reagendar Consulta</DialogTitle>
<DialogDescription>
Escolha uma nova data e horário para sua consulta com{" "}
<strong>{selectedAppointment?.doctor?.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]}
/>
</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>
<SelectContent>
{timeSlots.map((time) => (
<SelectItem key={time} value={time}>
{time}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="grid gap-2">
<Label htmlFor="reason">Motivo (opcional)</Label>
<Textarea
id="reason"
placeholder="Explique brevemente o motivo do reagendamento..."
value={rescheduleData.reason}
onChange={(e) => setRescheduleData((prev) => ({ ...prev, reason: e.target.value }))}
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setRescheduleModal(false)}>
Cancelar
</Button>
<Button onClick={confirmReschedule}>Confirmar</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* MODAL DE CANCELAMENTO */}
<Dialog open={cancelModal} onOpenChange={setCancelModal}>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>Cancelar Consulta</DialogTitle>
<DialogDescription>
Deseja realmente cancelar sua consulta com{" "}
<strong>{selectedAppointment?.doctor?.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="Informe o motivo do cancelamento (mínimo 10 caracteres)"
value={cancelReason}
onChange={(e) => setCancelReason(e.target.value)}
className="min-h-[100px]"
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setCancelModal(false)}>
Voltar
</Button>
<Button variant="destructive" onClick={confirmCancel}>
Confirmar Cancelamento
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</PatientLayout>
);
<DialogFooter>
<Button variant="outline" onClick={() => setCancelModal(false)}>
Voltar
</Button>
<Button variant="destructive" onClick={confirmCancel}>
Confirmar Cancelamento
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</PatientLayout>
);
}

View File

@ -1,354 +1,293 @@
"use client"
"use client";
import { useState, useEffect, useCallback } from "react"
import { Calendar, Clock, User } from "lucide-react"
import PatientLayout from "@/components/patient-layout"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
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 { Textarea } from "@/components/ui/textarea"
import { doctorsService } from "services/doctorsApi.mjs"
import { useState, useEffect, useCallback } from "react";
import { Calendar, Clock, User } from "lucide-react";
import PatientLayout from "@/components/patient-layout";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
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 { Textarea } from "@/components/ui/textarea";
import { doctorsService } from "services/doctorsApi.mjs";
interface Doctor {
id: string
full_name: string
specialty: string
phone_mobile: string
id: string;
full_name: string;
specialty: string;
phone_mobile: string;
}
const APPOINTMENTS_STORAGE_KEY = "clinic-appointments"
const APPOINTMENTS_STORAGE_KEY = "clinic-appointments";
export default function ScheduleAppointment() {
const [selectedDoctor, setSelectedDoctor] = useState("")
const [selectedDate, setSelectedDate] = useState("")
const [selectedTime, setSelectedTime] = useState("")
const [notes, setNotes] = useState("")
const [selectedDoctor, setSelectedDoctor] = useState("");
const [selectedDate, setSelectedDate] = useState("");
const [selectedTime, setSelectedTime] = useState("");
const [notes, setNotes] = useState("");
// novos campos
const [tipoConsulta, setTipoConsulta] = useState("presencial")
const [duracao, setDuracao] = useState("30")
const [convenio, setConvenio] = useState("")
const [queixa, setQueixa] = useState("")
const [obsPaciente, setObsPaciente] = useState("")
const [obsInternas, setObsInternas] = useState("")
// novos campos
const [tipoConsulta, setTipoConsulta] = useState("presencial");
const [duracao, setDuracao] = useState("30");
const [convenio, setConvenio] = useState("");
const [queixa, setQueixa] = useState("");
const [obsPaciente, setObsPaciente] = useState("");
const [obsInternas, setObsInternas] = useState("");
const [doctors, setDoctors] = useState<Doctor[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [doctors, setDoctors] = useState<Doctor[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const fetchDoctors = useCallback(async () => {
setLoading(true)
setError(null)
try {
const data: Doctor[] = await doctorsService.list()
setDoctors(data || [])
} catch (e: any) {
console.error("Erro ao carregar lista de médicos:", e)
setError("Não foi possível carregar a lista de médicos. Verifique a conexão com a API.")
setDoctors([])
} finally {
setLoading(false)
}
}, [])
const fetchDoctors = useCallback(async () => {
setLoading(true);
setError(null);
try {
const data: Doctor[] = await doctorsService.list();
console.log(data);
setDoctors(data || []);
} catch (e: any) {
console.error("Erro ao carregar lista de médicos:", e);
setError("Não foi possível carregar a lista de médicos. Verifique a conexão com a API.");
setDoctors([]);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchDoctors()
}, [fetchDoctors])
useEffect(() => {
fetchDoctors();
}, [fetchDoctors]);
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 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) => {
e.preventDefault()
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
const doctorDetails = doctors.find((d) => d.id === selectedDoctor)
const patientDetails = {
id: "P001",
full_name: "Paciente Exemplo Único",
location: "Clínica Geral",
phone: "(11) 98765-4321",
}
const doctorDetails = doctors.find((d) => d.id === selectedDoctor);
const patientDetails = {
id: "P001",
full_name: "Paciente Exemplo Único",
location: "Clínica Geral",
phone: "(11) 98765-4321",
};
if (!patientDetails || !doctorDetails) {
alert("Erro: Selecione o médico ou dados do paciente indisponíveis.")
return
}
if (!patientDetails || !doctorDetails) {
alert("Erro: Selecione o médico ou dados do paciente indisponíveis.");
return;
}
const newAppointment = {
id: new Date().getTime(),
patientName: patientDetails.full_name,
doctor: doctorDetails.full_name,
specialty: doctorDetails.specialty,
date: selectedDate,
time: selectedTime,
tipoConsulta,
duracao,
convenio,
queixa,
obsPaciente,
obsInternas,
notes,
status: "agendada",
phone: patientDetails.phone,
}
const newAppointment = {
id: new Date().getTime(),
patientName: patientDetails.full_name,
doctor: doctorDetails.full_name,
specialty: doctorDetails.specialty,
date: selectedDate,
time: selectedTime,
tipoConsulta,
duracao,
convenio,
queixa,
obsPaciente,
obsInternas,
notes,
status: "agendada",
phone: patientDetails.phone,
};
const storedAppointmentsRaw = localStorage.getItem(APPOINTMENTS_STORAGE_KEY)
const currentAppointments = storedAppointmentsRaw ? JSON.parse(storedAppointmentsRaw) : []
const updatedAppointments = [...currentAppointments, newAppointment]
localStorage.setItem(APPOINTMENTS_STORAGE_KEY, JSON.stringify(updatedAppointments))
const storedAppointmentsRaw = localStorage.getItem(APPOINTMENTS_STORAGE_KEY);
const currentAppointments = storedAppointmentsRaw ? JSON.parse(storedAppointmentsRaw) : [];
const updatedAppointments = [...currentAppointments, newAppointment];
localStorage.setItem(APPOINTMENTS_STORAGE_KEY, JSON.stringify(updatedAppointments));
alert(`Consulta com ${doctorDetails.full_name} agendada com sucesso!`)
alert(`Consulta com ${doctorDetails.full_name} agendada com sucesso!`);
// resetar campos
setSelectedDoctor("")
setSelectedDate("")
setSelectedTime("")
setNotes("")
setTipoConsulta("presencial")
setDuracao("30")
setConvenio("")
setQueixa("")
setObsPaciente("")
setObsInternas("")
}
// resetar campos
setSelectedDoctor("");
setSelectedDate("");
setSelectedTime("");
setNotes("");
setTipoConsulta("presencial");
setDuracao("30");
setConvenio("");
setQueixa("");
setObsPaciente("");
setObsInternas("");
};
return (
<PatientLayout>
<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 médico, data e horário para sua consulta</p>
</div>
return (
<PatientLayout>
<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 médico, data e horário para sua consulta</p>
</div>
<div className="grid lg:grid-cols-3 gap-6">
<div className="lg:col-span-2">
<Card>
<CardHeader>
<CardTitle>Dados da Consulta</CardTitle>
<CardDescription>Preencha as informações para agendar sua consulta</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="space-y-6">
<div className="grid lg:grid-cols-3 gap-6">
<div className="lg:col-span-2">
<Card>
<CardHeader>
<CardTitle>Dados da Consulta</CardTitle>
<CardDescription>Preencha as informações para agendar sua consulta</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="space-y-6">
{/* Médico */}
<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>
{loading ? (
<SelectItem value="loading" disabled>
Carregando médicos...
</SelectItem>
) : error ? (
<SelectItem value="error" disabled>
Erro ao carregar
</SelectItem>
) : (
doctors.map((doctor) => (
<SelectItem key={doctor.id} value={doctor.id}>
{doctor.full_name} - {doctor.specialty}
</SelectItem>
))
)}
</SelectContent>
</Select>
</div>
{/* Data e horário */}
<div className="grid md:grid-cols-2 gap-4">
<div className="space-y-2">
<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>
{/* Médico */}
<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>
{loading ? (
<SelectItem value="loading" disabled>
Carregando médicos...
</SelectItem>
) : error ? (
<SelectItem value="error" disabled>
Erro ao carregar
</SelectItem>
) : (
doctors.map((doctor) => (
<SelectItem key={doctor.id} value={doctor.id}>
{doctor.full_name} - {doctor.specialty}
</SelectItem>
))
)}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="time">Horário</Label>
<Select value={selectedTime} onValueChange={setSelectedTime}>
<SelectTrigger>
<SelectValue placeholder="Selecione um horário" />
</SelectTrigger>
<SelectContent>
{availableTimes.map((time) => (
<SelectItem key={time} value={time}>
{time}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
{/* Tipo e Duração */}
<div className="grid md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="tipoConsulta">Tipo de Consulta</Label>
<Select value={tipoConsulta} onValueChange={setTipoConsulta}>
<SelectTrigger id="tipoConsulta">
<SelectValue placeholder="Selecione o tipo" />
</SelectTrigger>
<SelectContent>
<SelectItem value="presencial">Presencial</SelectItem>
<SelectItem value="online">Telemedicina</SelectItem>
</SelectContent>
</Select>
</div>
{/* Data e horário */}
<div className="grid md:grid-cols-2 gap-4">
<div className="space-y-2">
<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 className="space-y-2">
<Label htmlFor="duracao">Duração (minutos)</Label>
<Input id="duracao" type="number" min={10} max={120} value={duracao} onChange={(e) => setDuracao(e.target.value)} />
</div>
</div>
{/* Convênio */}
<div className="space-y-2">
<Label htmlFor="convenio">Convênio (opcional)</Label>
<Input id="convenio" placeholder="Nome do convênio do paciente" value={convenio} onChange={(e) => setConvenio(e.target.value)} />
</div>
{/* Queixa Principal */}
<div className="space-y-2">
<Label htmlFor="queixa">Queixa Principal (opcional)</Label>
<Textarea id="queixa" placeholder="Descreva brevemente o motivo da consulta..." value={queixa} onChange={(e) => setQueixa(e.target.value)} />
</div>
{/* Observações do Paciente */}
<div className="space-y-2">
<Label htmlFor="obsPaciente">Observações do Paciente (opcional)</Label>
<Textarea id="obsPaciente" placeholder="Anotações relevantes informadas pelo paciente..." value={obsPaciente} onChange={(e) => setObsPaciente(e.target.value)} />
</div>
{/* Observações Internas */}
<div className="space-y-2">
<Label htmlFor="obsInternas">Observações Internas (opcional)</Label>
<Textarea id="obsInternas" placeholder="Anotações para a equipe da clínica..." value={obsInternas} onChange={(e) => setObsInternas(e.target.value)} />
</div>
{/* Observações gerais */}
<div className="space-y-2">
<Label htmlFor="notes">Observações gerais (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} />
</div>
{/* Botão */}
<Button type="submit" className="w-full" disabled={!selectedDoctor || !selectedDate || !selectedTime}>
Agendar Consulta
</Button>
</form>
</CardContent>
</Card>
</div>
<div className="space-y-2">
<Label htmlFor="time">Horário</Label>
<Select value={selectedTime} onValueChange={setSelectedTime}>
<SelectTrigger>
<SelectValue placeholder="Selecione um horário" />
</SelectTrigger>
<SelectContent>
{availableTimes.map((time) => (
<SelectItem key={time} value={time}>
{time}
</SelectItem>
))}
</SelectContent>
</Select>
{/* Resumo */}
<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">
{selectedDoctor && (
<div className="flex items-center space-x-2">
<User className="h-4 w-4 text-gray-500" />
<span className="text-sm">{doctors.find((d) => d.id === selectedDoctor)?.full_name}</span>
</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")}</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>
{/* Tipo e Duração */}
<div className="grid md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="tipoConsulta">Tipo de Consulta</Label>
<Select value={tipoConsulta} onValueChange={setTipoConsulta}>
<SelectTrigger id="tipoConsulta">
<SelectValue placeholder="Selecione o tipo" />
</SelectTrigger>
<SelectContent>
<SelectItem value="presencial">Presencial</SelectItem>
<SelectItem value="online">Telemedicina</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="duracao">Duração (minutos)</Label>
<Input
id="duracao"
type="number"
min={10}
max={120}
value={duracao}
onChange={(e) => setDuracao(e.target.value)}
/>
</div>
</div>
{/* Convênio */}
<div className="space-y-2">
<Label htmlFor="convenio">Convênio (opcional)</Label>
<Input
id="convenio"
placeholder="Nome do convênio do paciente"
value={convenio}
onChange={(e) => setConvenio(e.target.value)}
/>
</div>
{/* Queixa Principal */}
<div className="space-y-2">
<Label htmlFor="queixa">Queixa Principal (opcional)</Label>
<Textarea
id="queixa"
placeholder="Descreva brevemente o motivo da consulta..."
value={queixa}
onChange={(e) => setQueixa(e.target.value)}
/>
</div>
{/* Observações do Paciente */}
<div className="space-y-2">
<Label htmlFor="obsPaciente">Observações do Paciente (opcional)</Label>
<Textarea
id="obsPaciente"
placeholder="Anotações relevantes informadas pelo paciente..."
value={obsPaciente}
onChange={(e) => setObsPaciente(e.target.value)}
/>
</div>
{/* Observações Internas */}
<div className="space-y-2">
<Label htmlFor="obsInternas">Observações Internas (opcional)</Label>
<Textarea
id="obsInternas"
placeholder="Anotações para a equipe da clínica..."
value={obsInternas}
onChange={(e) => setObsInternas(e.target.value)}
/>
</div>
{/* Observações gerais */}
<div className="space-y-2">
<Label htmlFor="notes">Observações gerais (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}
/>
</div>
{/* Botão */}
<Button
type="submit"
className="w-full"
disabled={!selectedDoctor || !selectedDate || !selectedTime}
>
Agendar Consulta
</Button>
</form>
</CardContent>
</Card>
</div>
{/* Resumo */}
<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">
{selectedDoctor && (
<div className="flex items-center space-x-2">
<User className="h-4 w-4 text-gray-500" />
<span className="text-sm">
{doctors.find((d) => d.id === selectedDoctor)?.full_name}
</span>
</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")}
</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>
</PatientLayout>
)
</div>
</div>
</PatientLayout>
);
}

View File

@ -1,9 +1,9 @@
// Caminho: components/LoginForm.tsx
"use client"
"use client";
import type React from "react"
import { useState } from "react"
import { useRouter } from "next/navigation"
import type React from "react";
import { useState } from "react";
import { useRouter } from "next/navigation";
// Nossos serviços de API centralizados e limpos
import { login, api } from "@/services/api.mjs";
@ -16,202 +16,196 @@ import { useToast } from "@/hooks/use-toast";
import { Eye, EyeOff, Mail, Lock, Loader2 } from "lucide-react";
interface LoginFormProps {
children?: React.ReactNode
children?: React.ReactNode;
}
interface FormState {
email: string
password: string
email: string;
password: string;
}
export function LoginForm({ children }: LoginFormProps) {
const [form, setForm] = useState<FormState>({ email: "", password: "" })
const [showPassword, setShowPassword] = useState(false)
const [isLoading, setIsLoading] = useState(false)
const router = useRouter()
const { toast } = useToast()
const [form, setForm] = useState<FormState>({ email: "", password: "" });
const [showPassword, setShowPassword] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const router = useRouter();
const { toast } = useToast();
// --- NOVOS ESTADOS PARA CONTROLE DE MÚLTIPLOS PERFIS ---
const [userRoles, setUserRoles] = useState<string[]>([]);
const [authenticatedUser, setAuthenticatedUser] = useState<any>(null);
// --- NOVOS ESTADOS PARA CONTROLE DE MÚLTIPLOS PERFIS ---
const [userRoles, setUserRoles] = useState<string[]>([]);
const [authenticatedUser, setAuthenticatedUser] = useState<any>(null);
/**
* --- NOVA FUNÇÃO ---
* Finaliza o login com o perfil de dashboard escolhido e redireciona.
*/
const handleRoleSelection = (selectedDashboardRole: string) => {
const user = authenticatedUser;
if (!user) {
toast({ title: "Erro de Sessão", description: "Não foi possível encontrar os dados do usuário. Tente novamente.", variant: "destructive" });
setUserRoles([]); // Volta para a tela de login
return;
}
const completeUserInfo = { ...user, user_metadata: { ...user.user_metadata, role: selectedDashboardRole } };
localStorage.setItem('user_info', JSON.stringify(completeUserInfo));
let redirectPath = "";
switch (selectedDashboardRole) {
case "manager": redirectPath = "/manager/home"; break;
case "doctor": redirectPath = "/doctor/medicos"; break;
case "secretary": redirectPath = "/secretary/pacientes"; break;
case "patient": redirectPath = "/patient/dashboard"; break;
case "finance": redirectPath = "/finance/home"; break;
}
if (redirectPath) {
toast({ title: `Entrando como ${selectedDashboardRole}...` });
router.push(redirectPath);
} else {
toast({ title: "Erro", description: "Perfil selecionado inválido.", variant: "destructive" });
}
};
/**
* --- FUNÇÃO ATUALIZADA ---
* Lida com a submissão do formulário, busca os perfis e decide o próximo passo.
*/
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setIsLoading(true);
localStorage.removeItem("token");
localStorage.removeItem("user_info");
try {
// A chamada de login continua a mesma
const authData = await login();
const user = authData.user;
if (!user || !user.id) {
throw new Error("Resposta de autenticação inválida.");
}
// Armazena o usuário para uso posterior na seleção de perfil
setAuthenticatedUser(user);
// A busca de roles também continua a mesma, usando nosso 'api.get'
const rolesData = await api.get(`/rest/v1/user_roles?user_id=eq.${user.id}&select=role`);
if (!rolesData || rolesData.length === 0) {
throw new Error("Nenhum perfil de acesso foi encontrado para este usuário.");
}
const rolesFromApi: string[] = rolesData.map((r: any) => r.role);
// --- AQUI COMEÇA A NOVA LÓGICA DE DECISÃO ---
// Caso 1: Usuário é ADMIN, mostra todos os dashboards possíveis.
if (rolesFromApi.includes('admin')) {
setUserRoles(["manager", "doctor", "secretary", "patient", "finance"]);
setIsLoading(false); // Para o loading para mostrar a tela de seleção
/**
* --- NOVA FUNÇÃO ---
* Finaliza o login com o perfil de dashboard escolhido e redireciona.
*/
const handleRoleSelection = (selectedDashboardRole: string) => {
const user = authenticatedUser;
if (!user) {
toast({ title: "Erro de Sessão", description: "Não foi possível encontrar os dados do usuário. Tente novamente.", variant: "destructive" });
setUserRoles([]); // Volta para a tela de login
return;
}
// Mapeia os roles da API para os perfis de dashboard que o usuário pode acessar
const displayRoles = new Set<string>();
rolesFromApi.forEach(role => {
switch (role) {
case 'gestor':
displayRoles.add('manager');
displayRoles.add('finance');
break;
case 'medico':
displayRoles.add('doctor');
break;
case 'secretaria':
displayRoles.add('secretary');
break;
case 'patient': // Mapeamento de 'patient' (ou outro nome que você use para paciente)
displayRoles.add('patient');
break;
}
});
const completeUserInfo = { ...user, user_metadata: { ...user.user_metadata, role: selectedDashboardRole } };
localStorage.setItem("user_info", JSON.stringify(completeUserInfo));
const finalRoles = Array.from(displayRoles);
// Caso 2: Se o usuário tem apenas UM perfil de dashboard, redireciona direto.
if (finalRoles.length === 1) {
handleRoleSelection(finalRoles[0]);
}
// Caso 3: Se tem múltiplos perfis (ex: 'gestor'), mostra a tela de seleção.
else {
setUserRoles(finalRoles);
let redirectPath = "";
switch (selectedDashboardRole) {
case "manager":
redirectPath = "/manager/home";
break;
case "doctor":
redirectPath = "/doctor/medicos";
break;
case "secretary":
redirectPath = "/secretary/pacientes";
break;
case "patient":
redirectPath = "/patient/dashboard";
break;
case "finance":
redirectPath = "/finance/home";
break;
}
} catch (error) {
if (redirectPath) {
toast({ title: `Entrando como ${selectedDashboardRole}...` });
router.push(redirectPath);
} else {
toast({ title: "Erro", description: "Perfil selecionado inválido.", variant: "destructive" });
}
};
/**
* --- FUNÇÃO ATUALIZADA ---
* Lida com a submissão do formulário, busca os perfis e decide o próximo passo.
*/
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setIsLoading(true);
localStorage.removeItem("token");
localStorage.removeItem("user_info");
toast({
title: "Erro no Login",
description: error instanceof Error ? error.message : "Ocorreu um erro inesperado.",
variant: "destructive",
});
} finally {
// Apenas para o loading se não houver redirecionamento ou seleção de perfil
if (userRoles.length === 0) {
setIsLoading(false);
try {
// A chamada de login continua a mesma
const authData = await login(form.email, form.password);
const user = authData.user;
if (!user || !user.id) {
throw new Error("Resposta de autenticação inválida.");
}
// Armazena o usuário para uso posterior na seleção de perfil
setAuthenticatedUser(user);
// A busca de roles também continua a mesma, usando nosso 'api.get'
const rolesData = await api.get(`/rest/v1/user_roles?user_id=eq.${user.id}&select=role`);
if (!rolesData || rolesData.length === 0) {
throw new Error("Nenhum perfil de acesso foi encontrado para este usuário.");
}
const rolesFromApi: string[] = rolesData.map((r: any) => r.role);
// --- AQUI COMEÇA A NOVA LÓGICA DE DECISÃO ---
// Caso 1: Usuário é ADMIN, mostra todos os dashboards possíveis.
if (rolesFromApi.includes("admin")) {
setUserRoles(["manager", "doctor", "secretary", "paciente", "finance"]);
setIsLoading(false); // Para o loading para mostrar a tela de seleção
return;
}
// Mapeia os roles da API para os perfis de dashboard que o usuário pode acessar
const displayRoles = new Set<string>();
rolesFromApi.forEach((role) => {
switch (role) {
case "gestor":
displayRoles.add("manager");
displayRoles.add("finance");
break;
case "medico":
displayRoles.add("doctor");
break;
case "secretaria":
displayRoles.add("secretary");
break;
case "paciente": // Mapeamento de 'patient' (ou outro nome que você use para paciente)
displayRoles.add("patient");
break;
}
});
const finalRoles = Array.from(displayRoles);
// Caso 2: Se o usuário tem apenas UM perfil de dashboard, redireciona direto.
if (finalRoles.length === 1) {
handleRoleSelection(finalRoles[0]);
}
// Caso 3: Se tem múltiplos perfis (ex: 'gestor'), mostra a tela de seleção.
else {
setUserRoles(finalRoles);
setIsLoading(false);
}
} catch (error) {
localStorage.removeItem("token");
localStorage.removeItem("user_info");
toast({
title: "Erro no Login",
description: error instanceof Error ? error.message : "Ocorreu um erro inesperado.",
variant: "destructive",
});
}
}
};
// --- JSX ATUALIZADO COM RENDERIZAÇÃO CONDICIONAL ---
return (
<Card className="w-full bg-transparent border-0 shadow-none">
<CardContent className="p-0">
{userRoles.length === 0 ? (
// VISÃO 1: Formulário de Login (se nenhum perfil foi carregado ainda)
<form onSubmit={handleSubmit} className="space-y-6">
<div className="space-y-2">
<Label htmlFor="email">E-mail</Label>
<div className="relative">
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground w-5 h-5" />
<Input
id="email" type="email" placeholder="seu.email@exemplo.com"
value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })}
className="pl-10 h-11" required disabled={isLoading} autoComplete="username"
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="password">Senha</Label>
<div className="relative">
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground w-5 h-5" />
<Input
id="password" type={showPassword ? "text" : "password"} placeholder="Digite sua senha"
value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })}
className="pl-10 pr-12 h-11" required disabled={isLoading} autoComplete="current-password"
/>
<button type="button" onClick={() => setShowPassword(!showPassword)} className="absolute right-2 top-1/2 -translate-y-1/2 h-8 w-8 p-0 text-muted-foreground hover:text-foreground" disabled={isLoading}>
{showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
</button>
</div>
</div>
<Button type="submit" className="w-full h-11 text-base font-semibold" disabled={isLoading}>
{isLoading ? <Loader2 className="w-5 h-5 animate-spin" /> : "Entrar"}
</Button>
</form>
) : (
// VISÃO 2: Tela de Seleção de Perfil (se múltiplos perfis foram encontrados)
<div className="space-y-4 animate-in fade-in-50">
<h3 className="text-lg font-medium text-center text-foreground">Você tem múltiplos perfis</h3>
<p className="text-sm text-muted-foreground text-center">Selecione com qual perfil deseja entrar:</p>
<div className="flex flex-col space-y-3 pt-2">
{userRoles.map((role) => (
<Button
key={role}
variant="outline"
className="h-11 text-base"
onClick={() => handleRoleSelection(role)}
>
Entrar como: {role.charAt(0).toUpperCase() + role.slice(1)}
</Button>
))}
</div>
</div>
)}
setIsLoading(false);
};
{children}
</CardContent>
</Card>
)
}
// --- JSX ATUALIZADO COM RENDERIZAÇÃO CONDICIONAL ---
return (
<Card className="w-full bg-transparent border-0 shadow-none">
<CardContent className="p-0">
{userRoles.length === 0 ? (
// VISÃO 1: Formulário de Login (se nenhum perfil foi carregado ainda)
<form onSubmit={handleSubmit} className="space-y-6">
<div className="space-y-2">
<Label htmlFor="email">E-mail</Label>
<div className="relative">
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground w-5 h-5" />
<Input id="email" type="email" placeholder="seu.email@exemplo.com" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} className="pl-10 h-11" required disabled={isLoading} autoComplete="username" />
</div>
</div>
<div className="space-y-2">
<Label htmlFor="password">Senha</Label>
<div className="relative">
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground w-5 h-5" />
<Input id="password" type={showPassword ? "text" : "password"} placeholder="Digite sua senha" value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} className="pl-10 pr-12 h-11" required disabled={isLoading} autoComplete="current-password" />
<button type="button" onClick={() => setShowPassword(!showPassword)} className="absolute right-2 top-1/2 -translate-y-1/2 h-8 w-8 p-0 text-muted-foreground hover:text-foreground" disabled={isLoading}>
{showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
</button>
</div>
</div>
<Button type="submit" className="w-full h-11 text-base font-semibold" disabled={isLoading}>
{isLoading ? <Loader2 className="w-5 h-5 animate-spin" /> : "Entrar"}
</Button>
</form>
) : (
// VISÃO 2: Tela de Seleção de Perfil (se múltiplos perfis foram encontrados)
<div className="space-y-4 animate-in fade-in-50">
<h3 className="text-lg font-medium text-center text-foreground">Você tem múltiplos perfis</h3>
<p className="text-sm text-muted-foreground text-center">Selecione com qual perfil deseja entrar:</p>
<div className="flex flex-col space-y-3 pt-2">
{userRoles.map((role) => (
<Button key={role} variant="outline" className="h-11 text-base" onClick={() => handleRoleSelection(role)}>
Entrar como: {role.charAt(0).toUpperCase() + role.slice(1)}
</Button>
))}
</div>
</div>
)}
{children}
</CardContent>
</Card>
);
}

View File

@ -1,129 +1,52 @@
'use client'
"use client";
import * as React from 'react'
import * as ToastPrimitives from '@radix-ui/react-toast'
import { cva, type VariantProps } from 'class-variance-authority'
import { X } from 'lucide-react'
import * as React from "react";
import * as ToastPrimitives from "@radix-ui/react-toast";
import { cva, type VariantProps } from "class-variance-authority";
import { X } from "lucide-react";
import { cn } from '@/lib/utils'
import { cn } from "@/lib/utils";
const ToastProvider = ToastPrimitives.Provider
const ToastProvider = ToastPrimitives.Provider;
const ToastViewport = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Viewport>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Viewport
ref={ref}
className={cn(
'fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]',
className,
)}
{...props}
/>
))
ToastViewport.displayName = ToastPrimitives.Viewport.displayName
const ToastViewport = React.forwardRef<React.ElementRef<typeof ToastPrimitives.Viewport>, React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>>(({ className, ...props }, ref) => <ToastPrimitives.Viewport ref={ref} className={cn("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]", className)} {...props} />);
ToastViewport.displayName = ToastPrimitives.Viewport.displayName;
const toastVariants = cva(
'group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full',
{
const toastVariants = cva("group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full", {
variants: {
variant: {
default: 'border bg-background text-foreground',
destructive:
'destructive group border-destructive bg-destructive text-destructive-foreground',
},
variant: {
default: "border bg-background text-foreground",
destructive: "destructive group border-destructive bg-destructive text-foreground",
},
},
defaultVariants: {
variant: 'default',
variant: "default",
},
},
)
});
const Toast = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> &
VariantProps<typeof toastVariants>
>(({ className, variant, ...props }, ref) => {
return (
<ToastPrimitives.Root
ref={ref}
className={cn(toastVariants({ variant }), className)}
{...props}
/>
)
})
Toast.displayName = ToastPrimitives.Root.displayName
const Toast = React.forwardRef<React.ElementRef<typeof ToastPrimitives.Root>, React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> & VariantProps<typeof toastVariants>>(({ className, variant, ...props }, ref) => {
return <ToastPrimitives.Root ref={ref} className={cn(toastVariants({ variant }), className)} {...props} />;
});
Toast.displayName = ToastPrimitives.Root.displayName;
const ToastAction = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Action>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Action
ref={ref}
className={cn(
'inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive',
className,
)}
{...props}
/>
))
ToastAction.displayName = ToastPrimitives.Action.displayName
const ToastAction = React.forwardRef<React.ElementRef<typeof ToastPrimitives.Action>, React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>>(({ className, ...props }, ref) => <ToastPrimitives.Action ref={ref} className={cn("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive", className)} {...props} />);
ToastAction.displayName = ToastPrimitives.Action.displayName;
const ToastClose = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Close>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Close
ref={ref}
className={cn(
'absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600',
className,
)}
toast-close=""
{...props}
>
<X className="h-4 w-4" />
</ToastPrimitives.Close>
))
ToastClose.displayName = ToastPrimitives.Close.displayName
const ToastClose = React.forwardRef<React.ElementRef<typeof ToastPrimitives.Close>, React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>>(({ className, ...props }, ref) => (
<ToastPrimitives.Close ref={ref} className={cn("absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600", className)} toast-close="" {...props}>
<X className="h-4 w-4" />
</ToastPrimitives.Close>
));
ToastClose.displayName = ToastPrimitives.Close.displayName;
const ToastTitle = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Title>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Title
ref={ref}
className={cn('text-sm font-semibold', className)}
{...props}
/>
))
ToastTitle.displayName = ToastPrimitives.Title.displayName
const ToastTitle = React.forwardRef<React.ElementRef<typeof ToastPrimitives.Title>, React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>>(({ className, ...props }, ref) => <ToastPrimitives.Title ref={ref} className={cn("text-sm font-semibold", className)} {...props} />);
ToastTitle.displayName = ToastPrimitives.Title.displayName;
const ToastDescription = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Description>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Description
ref={ref}
className={cn('text-sm opacity-90', className)}
{...props}
/>
))
ToastDescription.displayName = ToastPrimitives.Description.displayName
const ToastDescription = React.forwardRef<React.ElementRef<typeof ToastPrimitives.Description>, React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>>(({ className, ...props }, ref) => <ToastPrimitives.Description ref={ref} className={cn("text-sm opacity-90", className)} {...props} />);
ToastDescription.displayName = ToastPrimitives.Description.displayName;
type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>
type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>;
type ToastActionElement = React.ReactElement<typeof ToastAction>
type ToastActionElement = React.ReactElement<typeof ToastAction>;
export {
type ToastProps,
type ToastActionElement,
ToastProvider,
ToastViewport,
Toast,
ToastTitle,
ToastDescription,
ToastClose,
ToastAction,
}
export { type ToastProps, type ToastActionElement, ToastProvider, ToastViewport, Toast, ToastTitle, ToastDescription, ToastClose, ToastAction };

View File

@ -9,58 +9,58 @@ const API_KEY = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
* Função de login que o seu formulário usa.
* Ela continua exatamente como era.
*/
export async function login() {
console.log("🔐 Iniciando login...");
const res = await fetch(`${BASE_URL}/auth/v1/token?grant_type=password`, {
method: "POST",
headers: {
"Content-Type": "application/json",
apikey: API_KEY,
Prefer: "return=representation",
},
body: JSON.stringify({
email: "riseup@popcode.com.br",
password: "riseup",
}),
});
export async function login(email, senha) {
console.log("🔐 Iniciando login...");
const res = await fetch(`${BASE_URL}/auth/v1/token?grant_type=password`, {
method: "POST",
headers: {
"Content-Type": "application/json",
apikey: API_KEY,
Prefer: "return=representation",
},
body: JSON.stringify({
email: email,
password: senha,
}),
});
if (!res.ok) {
const msg = await res.text();
console.error("❌ Erro no login:", res.status, msg);
throw new Error(`Erro ao autenticar: ${res.status} - ${msg}`);
}
if (!res.ok) {
const msg = await res.text();
console.error("❌ Erro no login:", res.status, msg);
throw new Error(`Erro ao autenticar: ${res.status} - ${msg}`);
}
const data = await res.json();
console.log("✅ Login bem-sucedido:", data);
const data = await res.json();
console.log("✅ Login bem-sucedido:", data);
if (typeof window !== "undefined" && data.access_token) {
localStorage.setItem("token", data.access_token);
}
if (typeof window !== "undefined" && data.access_token) {
localStorage.setItem("token", data.access_token);
}
return data;
return data;
}
/**
* Função de logout.
*/
async function logout() {
const token = localStorage.getItem("token");
if (!token) return;
const token = localStorage.getItem("token");
if (!token) return;
try {
await fetch(`${BASE_URL}/auth/v1/logout`, {
method: "POST",
headers: {
"apikey": API_KEY,
"Authorization": `Bearer ${token}`,
},
});
} catch (error) {
console.error("Falha ao invalidar token no servidor:", error);
} finally {
localStorage.removeItem("token");
localStorage.removeItem("user_info");
}
try {
await fetch(`${BASE_URL}/auth/v1/logout`, {
method: "POST",
headers: {
apikey: API_KEY,
Authorization: `Bearer ${token}`,
},
});
} catch (error) {
console.error("Falha ao invalidar token no servidor:", error);
} finally {
localStorage.removeItem("token");
localStorage.removeItem("user_info");
}
}
/**
@ -68,40 +68,40 @@ async function logout() {
* Agora com a correção para respostas vazias.
*/
async function request(endpoint, options = {}) {
const token = typeof window !== 'undefined' ? localStorage.getItem("token") : null;
const token = typeof window !== "undefined" ? localStorage.getItem("token") : null;
const headers = {
"Content-Type": "application/json",
"apikey": API_KEY,
...(token && { "Authorization": `Bearer ${token}` }),
...options.headers,
};
const headers = {
"Content-Type": "application/json",
apikey: API_KEY,
...(token && { Authorization: `Bearer ${token}` }),
...options.headers,
};
const response = await fetch(`${BASE_URL}${endpoint}`, { ...options, headers });
const response = await fetch(`${BASE_URL}${endpoint}`, { ...options, headers });
if (!response.ok) {
const errorBody = await response.json().catch(() => response.text());
console.error("Erro na requisição:", response.status, errorBody);
throw new Error(`Erro na API: ${errorBody.message || JSON.stringify(errorBody)}`);
}
if (!response.ok) {
const errorBody = await response.json().catch(() => response.text());
console.error("Erro na requisição:", response.status, errorBody);
throw new Error(`Erro na API: ${errorBody.message || JSON.stringify(errorBody)}`);
}
// --- CORREÇÃO 1: PARA O SUBMIT DO AGENDAMENTO ---
// Se a resposta for um sucesso de criação (201) ou sem conteúdo (204), não quebra.
if (response.status === 201 || response.status === 204) {
return null;
}
// --- CORREÇÃO 1: PARA O SUBMIT DO AGENDAMENTO ---
// Se a resposta for um sucesso de criação (201) ou sem conteúdo (204), não quebra.
if (response.status === 201 || response.status === 204) {
return null;
}
return response.json();
return response.json();
}
// Exportamos o objeto 'api' com os métodos que os componentes vão usar.
export const api = {
// --- CORREÇÃO 2: PARA CARREGAR O ID DO USUÁRIO ---
getSession: () => request('/auth/v1/user'),
// --- CORREÇÃO 2: PARA CARREGAR O ID DO USUÁRIO ---
getSession: () => request("/auth/v1/user"),
get: (endpoint, options) => request(endpoint, { method: "GET", ...options }),
post: (endpoint, data, options) => request(endpoint, { method: "POST", body: JSON.stringify(data), ...options }),
patch: (endpoint, data, options) => request(endpoint, { method: "PATCH", body: JSON.stringify(data), ...options }),
delete: (endpoint, options) => request(endpoint, { method: "DELETE", ...options }),
logout: logout,
};
get: (endpoint, options) => request(endpoint, { method: "GET", ...options }),
post: (endpoint, data, options) => request(endpoint, { method: "POST", body: JSON.stringify(data), ...options }),
patch: (endpoint, data, options) => request(endpoint, { method: "PATCH", body: JSON.stringify(data), ...options }),
delete: (endpoint, options) => request(endpoint, { method: "DELETE", ...options }),
logout: logout,
};