Merge branch 'StsDanilo-Disponibilidade'
This commit is contained in:
commit
20aeb3dafc
@ -1,10 +1,139 @@
|
||||
import DoctorLayout from "@/components/doctor-layout"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Calendar, Clock, User, Plus } from "lucide-react"
|
||||
import Link from "next/link"
|
||||
"use client";
|
||||
|
||||
import DoctorLayout from "@/components/doctor-layout";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Calendar, Clock, User, Trash2 } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useEffect, useState } from "react";
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
||||
import { AvailabilityService } from "@/services/availabilityApi.mjs";
|
||||
import { exceptionsService } from "@/services/exceptionApi.mjs";
|
||||
import { toast } from "@/hooks/use-toast";
|
||||
|
||||
type Availability = {
|
||||
id: string;
|
||||
doctor_id: string;
|
||||
weekday: string;
|
||||
start_time: string;
|
||||
end_time: string;
|
||||
slot_minutes: number;
|
||||
appointment_type: string;
|
||||
active: boolean;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
created_by: string;
|
||||
updated_by: string | null;
|
||||
};
|
||||
|
||||
type Schedule = {
|
||||
weekday: object;
|
||||
};
|
||||
|
||||
export default function PatientDashboard() {
|
||||
const userInfo = JSON.parse(localStorage.getItem("user_info") || "{}");
|
||||
const doctorId = "3bb9ee4a-cfdd-4d81-b628-383907dfa225"; //userInfo.id;
|
||||
const [availability, setAvailability] = useState<any | null>(null);
|
||||
const [exceptions, setExceptions] = useState<any | null>(null);
|
||||
const [schedule, setSchedule] = useState<Record<string, { start: string; end: string }[]>>({});
|
||||
const formatTime = (time: string) => time.split(":").slice(0, 2).join(":");
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [patientToDelete, setPatientToDelete] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Mapa de tradução
|
||||
const weekdaysPT: Record<string, string> = {
|
||||
sunday: "Domingo",
|
||||
monday: "Segunda",
|
||||
tuesday: "Terça",
|
||||
wednesday: "Quarta",
|
||||
thursday: "Quinta",
|
||||
friday: "Sexta",
|
||||
saturday: "Sábado",
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
// fetch para disponibilidade
|
||||
const response = await AvailabilityService.list();
|
||||
const filteredResponse = response.filter((disp: { doctor_id: any }) => disp.doctor_id == doctorId);
|
||||
setAvailability(filteredResponse);
|
||||
// fetch para exceções
|
||||
const res = await exceptionsService.list();
|
||||
const filteredRes = res.filter((disp: { doctor_id: any }) => disp.doctor_id == doctorId);
|
||||
setExceptions(filteredRes);
|
||||
} catch (e: any) {
|
||||
alert(`${e?.error} ${e?.message}`);
|
||||
}
|
||||
};
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
const openDeleteDialog = (patientId: string) => {
|
||||
setPatientToDelete(patientId);
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleDeletePatient = async (patientId: string) => {
|
||||
// Remove from current list (client-side deletion)
|
||||
try {
|
||||
const res = await exceptionsService.delete(patientId);
|
||||
|
||||
let message = "Exceção deletada com sucesso";
|
||||
try {
|
||||
if (res) {
|
||||
throw new Error(`${res.error} ${res.message}` || "A API retornou erro");
|
||||
} else {
|
||||
console.log(message);
|
||||
}
|
||||
} catch {}
|
||||
|
||||
toast({
|
||||
title: "Sucesso",
|
||||
description: message,
|
||||
});
|
||||
|
||||
setExceptions((prev: any[]) => prev.filter((p) => String(p.id) !== String(patientId)));
|
||||
} catch (e: any) {
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: e?.message || "Não foi possível deletar a exceção",
|
||||
});
|
||||
}
|
||||
setDeleteDialogOpen(false);
|
||||
setPatientToDelete(null);
|
||||
};
|
||||
|
||||
function formatAvailability(data: Availability[]) {
|
||||
// Agrupar os horários por dia da semana
|
||||
const schedule = data.reduce((acc: any, item) => {
|
||||
const { weekday, start_time, end_time } = item;
|
||||
|
||||
// Se o dia ainda não existe, cria o array
|
||||
if (!acc[weekday]) {
|
||||
acc[weekday] = [];
|
||||
}
|
||||
|
||||
// Adiciona o horário do dia
|
||||
acc[weekday].push({
|
||||
start: start_time,
|
||||
end: end_time,
|
||||
});
|
||||
|
||||
return acc;
|
||||
}, {} as Record<string, { start: string; end: string }[]>);
|
||||
|
||||
return schedule;
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (availability) {
|
||||
const formatted = formatAvailability(availability);
|
||||
setSchedule(formatted);
|
||||
}
|
||||
}, [availability]);
|
||||
|
||||
return (
|
||||
<DoctorLayout>
|
||||
<div className="space-y-6">
|
||||
@ -85,7 +214,102 @@ export default function PatientDashboard() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
<div className="grid md:grid-cols-1 gap-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Horário Semanal</CardTitle>
|
||||
<CardDescription>Confira rapidamente a sua disponibilidade da semana</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4 grid md:grid-cols-7 gap-2">
|
||||
{["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"].map((day) => {
|
||||
const times = schedule[day] || [];
|
||||
return (
|
||||
<div key={day} className="space-y-4">
|
||||
<div className="flex flex-col items-center justify-between p-3 bg-blue-50 rounded-lg">
|
||||
<div>
|
||||
<p className="font-medium capitalize">{weekdaysPT[day]}</p>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
{times.length > 0 ? (
|
||||
times.map((t, i) => (
|
||||
<p key={i} className="text-sm text-gray-600">
|
||||
{formatTime(t.start)} <br /> {formatTime(t.end)}
|
||||
</p>
|
||||
))
|
||||
) : (
|
||||
<p className="text-sm text-gray-400 italic">Sem horário</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
<div className="grid md:grid-cols-1 gap-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Exceções</CardTitle>
|
||||
<CardDescription>Bloqueios e liberações eventuais de agenda</CardDescription>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="space-y-4 grid md:grid-cols-7 gap-2">
|
||||
{exceptions && exceptions.length > 0 ? (
|
||||
exceptions.map((ex: any) => {
|
||||
// Formata data e hora
|
||||
const date = new Date(ex.date).toLocaleDateString("pt-BR", {
|
||||
weekday: "long",
|
||||
day: "2-digit",
|
||||
month: "long",
|
||||
});
|
||||
|
||||
const startTime = formatTime(ex.start_time);
|
||||
const endTime = formatTime(ex.end_time);
|
||||
|
||||
return (
|
||||
<div key={ex.id} className="space-y-4">
|
||||
<div className="flex flex-col items-center justify-between p-3 bg-blue-50 rounded-lg shadow-sm">
|
||||
<div className="text-center">
|
||||
<p className="font-semibold capitalize">{date}</p>
|
||||
<p className="text-sm text-gray-600">
|
||||
{startTime} - {endTime} <br/> -
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-center mt-2">
|
||||
<p className={`text-sm font-medium ${ex.kind === "bloqueio" ? "text-red-600" : "text-green-600"}`}>{ex.kind === "bloqueio" ? "Bloqueio" : "Liberação"}</p>
|
||||
<p className="text-xs text-gray-500 italic">{ex.reason || "Sem motivo especificado"}</p>
|
||||
</div>
|
||||
<div>
|
||||
<Button className="text-red-600" variant="outline" onClick={() => openDeleteDialog(String(ex.id))}>
|
||||
<Trash2></Trash2>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
) : (
|
||||
<p className="text-sm text-gray-400 italic col-span-7 text-center">Nenhuma exceção registrada.</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Confirmar exclusão</AlertDialogTitle>
|
||||
<AlertDialogDescription>Tem certeza que deseja excluir este paciente? Esta ação não pode ser desfeita.</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancelar</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={() => patientToDelete && handleDeletePatient(patientToDelete)} className="bg-red-600 hover:bg-red-700">
|
||||
Excluir
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
</DoctorLayout>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
218
app/doctor/disponibilidade/excecoes/page.tsx
Normal file
218
app/doctor/disponibilidade/excecoes/page.tsx
Normal file
@ -0,0 +1,218 @@
|
||||
"use client";
|
||||
|
||||
import type React from "react";
|
||||
import Link from "next/link";
|
||||
import { useState, useEffect } from "react";
|
||||
import DoctorLayout from "@/components/doctor-layout";
|
||||
import { Card, CardContent, 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 { Clock, Calendar as CalendarIcon, MapPin, Phone, User, X, RefreshCw } from "lucide-react";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { toast } from "@/hooks/use-toast";
|
||||
import { exceptionsService } from "@/services/exceptionApi.mjs";
|
||||
|
||||
// IMPORTAR O COMPONENTE CALENDÁRIO DA SHADCN
|
||||
import { Calendar } from "@/components/ui/calendar";
|
||||
import { format } from "date-fns"; // Usaremos o date-fns para formatação e comparação de datas
|
||||
|
||||
const APPOINTMENTS_STORAGE_KEY = "clinic-appointments";
|
||||
|
||||
// --- TIPAGEM DA CONSULTA SALVA NO LOCALSTORAGE ---
|
||||
interface LocalStorageAppointment {
|
||||
id: number;
|
||||
patientName: string;
|
||||
doctor: string;
|
||||
specialty: string;
|
||||
date: string; // Data no formato YYYY-MM-DD
|
||||
time: string; // Hora no formato HH:MM
|
||||
status: "agendada" | "confirmada" | "cancelada" | "realizada";
|
||||
location: string;
|
||||
phone: string;
|
||||
}
|
||||
|
||||
const LOGGED_IN_DOCTOR_NAME = "Dr. João Santos";
|
||||
|
||||
// Função auxiliar para comparar se duas datas (Date objects) são o mesmo dia
|
||||
const isSameDay = (date1: Date, date2: Date) => {
|
||||
return date1.getFullYear() === date2.getFullYear() && date1.getMonth() === date2.getMonth() && date1.getDate() === date2.getDate();
|
||||
};
|
||||
|
||||
// --- COMPONENTE PRINCIPAL ---
|
||||
|
||||
export default function ExceptionPage() {
|
||||
const [allAppointments, setAllAppointments] = useState<LocalStorageAppointment[]>([]);
|
||||
const router = useRouter();
|
||||
const [filteredAppointments, setFilteredAppointments] = useState<LocalStorageAppointment[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const userInfo = JSON.parse(localStorage.getItem("user_info") || "{}");
|
||||
const doctorIdTemp = "3bb9ee4a-cfdd-4d81-b628-383907dfa225";
|
||||
const [tipo, setTipo] = useState<string>("");
|
||||
|
||||
// NOVO ESTADO 1: Armazena os dias com consultas (para o calendário)
|
||||
const [bookedDays, setBookedDays] = useState<Date[]>([]);
|
||||
|
||||
// NOVO ESTADO 2: Armazena a data selecionada no calendário
|
||||
const [selectedCalendarDate, setSelectedCalendarDate] = useState<Date | undefined>(new Date());
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
if (isLoading) return;
|
||||
//setIsLoading(true);
|
||||
const form = e.currentTarget;
|
||||
const formData = new FormData(form);
|
||||
|
||||
const apiPayload = {
|
||||
doctor_id: doctorIdTemp,
|
||||
created_by: doctorIdTemp,
|
||||
date: selectedCalendarDate ? format(selectedCalendarDate, "yyyy-MM-dd") : "",
|
||||
start_time: ((formData.get("horarioEntrada") + ":00") as string) || undefined,
|
||||
end_time: ((formData.get("horarioSaida") + ":00") as string) || undefined,
|
||||
kind: tipo || undefined,
|
||||
reason: formData.get("reason"),
|
||||
};
|
||||
console.log(apiPayload);
|
||||
try {
|
||||
const res = await exceptionsService.create(apiPayload);
|
||||
console.log(res);
|
||||
|
||||
let message = "Exceção cadastrada com sucesso";
|
||||
try {
|
||||
if (!res[0].id) {
|
||||
throw new Error(`${res.error} ${res.message}` || "A API retornou erro");
|
||||
} else {
|
||||
console.log(message);
|
||||
}
|
||||
} catch {}
|
||||
|
||||
toast({
|
||||
title: "Sucesso",
|
||||
description: message,
|
||||
});
|
||||
router.push("/doctor/dashboard"); // adicionar página para listar a disponibilidade
|
||||
} catch (err: any) {
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: err?.message || "Não foi possível cadastrar a exceção",
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const displayDate = selectedCalendarDate ? new Date(selectedCalendarDate).toLocaleDateString("pt-BR", { weekday: "long", day: "2-digit", month: "long" }) : "Selecione uma data";
|
||||
|
||||
return (
|
||||
<DoctorLayout>
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-900">Adicione exceções</h1>
|
||||
<p className="text-gray-600">Altere a disponibilidade em casos especiais para o Dr. {userInfo.user_metadata.full_name}</p>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-between items-center">
|
||||
<h2 className="text-xl font-semibold">Consultas para: {displayDate}</h2>
|
||||
<Button disabled={isLoading} variant="outline" size="sm">
|
||||
<RefreshCw className={`mr-2 h-4 w-4 ${isLoading ? "animate-spin" : ""}`} />
|
||||
Atualizar Agenda
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* NOVO LAYOUT DE DUAS COLUNAS */}
|
||||
<div className="grid lg:grid-cols-3 gap-6">
|
||||
{/* COLUNA 1: CALENDÁRIO */}
|
||||
<div className="lg:col-span-1">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center">
|
||||
<CalendarIcon className="mr-2 h-5 w-5" />
|
||||
Calendário
|
||||
</CardTitle>
|
||||
<p className="text-sm text-gray-500">Selecione a data desejada.</p>
|
||||
</CardHeader>
|
||||
<CardContent className="flex justify-center p-2">
|
||||
<Calendar
|
||||
mode="single"
|
||||
selected={selectedCalendarDate}
|
||||
onSelect={setSelectedCalendarDate}
|
||||
autoFocus
|
||||
// A CHAVE DO HIGHLIGHT: Passa o array de datas agendadas
|
||||
modifiers={{ booked: bookedDays }}
|
||||
// Define o estilo CSS para o modificador 'booked'
|
||||
modifiersClassNames={{
|
||||
booked: "bg-blue-600 text-white aria-selected:!bg-blue-700 hover:!bg-blue-700/90",
|
||||
}}
|
||||
className="rounded-md border p-2"
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* COLUNA 2: FORM PARA ADICIONAR EXCEÇÃO */}
|
||||
<div className="lg:col-span-2 space-y-4">
|
||||
{isLoading ? (
|
||||
<p className="text-center text-lg text-gray-500">Carregando a agenda...</p>
|
||||
) : !selectedCalendarDate ? (
|
||||
<p className="text-center text-lg text-gray-500">Selecione uma data.</p>
|
||||
) : (
|
||||
<form className="space-y-6" onSubmit={handleSubmit}>
|
||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Dados </h2>
|
||||
<div className="space-y-6">
|
||||
<div className="grid md:grid-cols-5 gap-6">
|
||||
<div>
|
||||
<Label htmlFor="horarioEntrada" className="text-sm font-medium text-gray-700">
|
||||
Horario De Entrada
|
||||
</Label>
|
||||
<Input type="time" id="horarioEntrada" name="horarioEntrada" required className="mt-1" />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="horarioSaida" className="text-sm font-medium text-gray-700">
|
||||
Horario De Saida
|
||||
</Label>
|
||||
<Input type="time" id="horarioSaida" name="horarioSaida" required className="mt-1" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="tipo" className="text-sm font-medium text-gray-700">
|
||||
Tipo
|
||||
</Label>
|
||||
<Select onValueChange={(value) => setTipo(value)} value={tipo}>
|
||||
<SelectTrigger className="mt-1">
|
||||
<SelectValue placeholder="Selecione" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="bloqueio">Bloqueio </SelectItem>
|
||||
<SelectItem value="liberacao">Liberação</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="reason" className="text-sm font-medium text-gray-700">
|
||||
Motivo
|
||||
</Label>
|
||||
<Input type="textarea" id="reason" name="reason" required className="mt-1" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-4">
|
||||
<Link href="/doctor/disponibilidade">
|
||||
<Button variant="outline">Cancelar</Button>
|
||||
</Link>
|
||||
<Button type="submit" className="bg-green-600 hover:bg-green-700">
|
||||
Salvar Exceção
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</DoctorLayout>
|
||||
);
|
||||
}
|
||||
186
app/doctor/disponibilidade/page.tsx
Normal file
186
app/doctor/disponibilidade/page.tsx
Normal file
@ -0,0 +1,186 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
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 DoctorLayout from "@/components/doctor-layout";
|
||||
import { AvailabilityService } from "@/services/availabilityApi.mjs";
|
||||
import { toast } from "@/hooks/use-toast";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
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 [modalidadeConsulta, setModalidadeConsulta] = useState<string>("");
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
const response = await AvailabilityService.list();
|
||||
console.log(response);
|
||||
} catch (e: any) {
|
||||
alert(`${e?.error} ${e?.message}`);
|
||||
}
|
||||
};
|
||||
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
if (isLoading) return;
|
||||
setIsLoading(true);
|
||||
const form = e.currentTarget;
|
||||
const formData = new FormData(form);
|
||||
|
||||
const apiPayload = {
|
||||
doctor_id: doctorIdTemp,
|
||||
created_by: doctorIdTemp,
|
||||
weekday: (formData.get("weekday") as string) || undefined,
|
||||
start_time: (formData.get("horarioEntrada") as string) || undefined,
|
||||
end_time: (formData.get("horarioSaida") as string) || undefined,
|
||||
slot_minutes: Number(formData.get("duracaoConsulta")) || undefined,
|
||||
appointment_type: modalidadeConsulta || undefined,
|
||||
active: true,
|
||||
};
|
||||
console.log(apiPayload);
|
||||
|
||||
try {
|
||||
const res = await AvailabilityService.create(apiPayload);
|
||||
console.log(res);
|
||||
|
||||
let message = "disponibilidade cadastrada com sucesso";
|
||||
try {
|
||||
if (!res[0].id) {
|
||||
throw new Error(`${res.error} ${res.message}` || "A API retornou erro");
|
||||
} else {
|
||||
console.log(message);
|
||||
}
|
||||
} catch {}
|
||||
|
||||
toast({
|
||||
title: "Sucesso",
|
||||
description: message,
|
||||
});
|
||||
router.push("#"); // adicionar página para listar a disponibilidade
|
||||
} catch (err: any) {
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: err?.message || "Não foi possível cadastrar o paciente",
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<DoctorLayout>
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Definir Disponibilidade</h1>
|
||||
<p className="text-gray-600">Defina sua disponibilidade para consultas </p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form className="space-y-6" onSubmit={handleSubmit}>
|
||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Dados </h2>
|
||||
|
||||
<div className="space-y-6">
|
||||
<div className="grid md:grid-cols-3 gap-4">
|
||||
<div>
|
||||
<Label className="text-sm font-medium text-gray-700">Dia Da Semana</Label>
|
||||
<div className="flex gap-4 mt-2 flex-nowrap">
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="radio" name="weekday" value="monday" className="text-blue-600" />
|
||||
<span className="whitespace-nowrap text-sm">Segunda-Feira</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="radio" name="weekday" value="tuesday" className="text-blue-600" />
|
||||
<span className="whitespace-nowrap text-sm">Terça-Feira</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="radio" name="weekday" value="wednesday" className="text-blue-600" />
|
||||
<span className="whitespace-nowrap text-sm">Quarta-Feira</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="radio" name="weekday" value="thursday" className="text-blue-600" />
|
||||
<span className="whitespace-nowrap text-sm">Quinta-Feira</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="radio" name="weekday" value="friday" className="text-blue-600" />
|
||||
<span className="whitespace-nowrap text-sm">Sexta-Feira</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="radio" name="weekday" value="saturday" className="text-blue-600" />
|
||||
<span className="whitespace-nowrap text-sm">Sabado</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="radio" name="weekday" value="sunday" className="text-blue-600" />
|
||||
<span className="whitespace-nowrap text-sm">Domingo</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-5 gap-6">
|
||||
<div>
|
||||
<Label htmlFor="horarioEntrada" className="text-sm font-medium text-gray-700">
|
||||
Horario De Entrada
|
||||
</Label>
|
||||
<Input type="time" id="horarioEntrada" name="horarioEntrada" required className="mt-1" />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="horarioSaida" className="text-sm font-medium text-gray-700">
|
||||
Horario De Saida
|
||||
</Label>
|
||||
<Input type="time" id="horarioSaida" name="horarioSaida" required className="mt-1" />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="duracaoConsulta" className="text-sm font-medium text-gray-700">
|
||||
Duração Da Consulta (min)
|
||||
</Label>
|
||||
<Input type="number" id="duracaoConsulta" name="duracaoConsulta" required className="mt-1" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="modalidadeConsulta" className="text-sm font-medium text-gray-700">
|
||||
Modalidade De Consulta
|
||||
</Label>
|
||||
<Select onValueChange={(value) => setModalidadeConsulta(value)} value={modalidadeConsulta}>
|
||||
<SelectTrigger className="mt-1">
|
||||
<SelectValue placeholder="Selecione" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="presencial">Presencial </SelectItem>
|
||||
<SelectItem value="telemedicina">Telemedicina</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-4">
|
||||
<Link href="/doctor/disponibilidade/excecoes">
|
||||
<Button variant="outline">Adicionar Exceção</Button>
|
||||
</Link>
|
||||
<Link href="/doctor/dashboard">
|
||||
<Button variant="outline">Cancelar</Button>
|
||||
</Link>
|
||||
<Button type="submit" className="bg-green-600 hover:bg-green-700">
|
||||
Salvar Disponibilidade
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</DoctorLayout>
|
||||
);
|
||||
}
|
||||
@ -5,7 +5,7 @@ import { useState, useEffect } from "react";
|
||||
import { useRouter, usePathname } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import Cookies from "js-cookie"; // Manteremos para o logout, se necessário
|
||||
import { api } from '@/services/api.mjs';
|
||||
import { api } from "@/services/api.mjs";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
@ -48,7 +48,7 @@ export default function DoctorLayout({ children }: PatientLayoutProps) {
|
||||
|
||||
if (userInfoString && token) {
|
||||
const userInfo = JSON.parse(userInfoString);
|
||||
|
||||
|
||||
setDoctorData({
|
||||
id: userInfo.id || "",
|
||||
name: userInfo.user_metadata?.full_name || "Doutor(a)",
|
||||
@ -86,24 +86,23 @@ export default function DoctorLayout({ children }: PatientLayoutProps) {
|
||||
setShowLogoutDialog(true);
|
||||
};
|
||||
|
||||
|
||||
// --- ALTERAÇÃO 2: A função de logout agora é MUITO mais simples ---
|
||||
const confirmLogout = async () => {
|
||||
try {
|
||||
// Chama a função centralizada para fazer o logout no servidor
|
||||
await api.logout();
|
||||
} catch (error) {
|
||||
// O erro já é logado dentro da função api.logout, não precisamos fazer nada aqui
|
||||
} finally {
|
||||
// A responsabilidade do componente é apenas limpar o estado local e redirecionar
|
||||
localStorage.removeItem("user_info");
|
||||
localStorage.removeItem("token");
|
||||
Cookies.remove("access_token"); // Limpeza de segurança
|
||||
|
||||
setShowLogoutDialog(false);
|
||||
router.push("/"); // Redireciona para a home
|
||||
}
|
||||
};
|
||||
const confirmLogout = async () => {
|
||||
try {
|
||||
// Chama a função centralizada para fazer o logout no servidor
|
||||
await api.logout();
|
||||
} catch (error) {
|
||||
// O erro já é logado dentro da função api.logout, não precisamos fazer nada aqui
|
||||
} finally {
|
||||
// A responsabilidade do componente é apenas limpar o estado local e redirecionar
|
||||
localStorage.removeItem("user_info");
|
||||
localStorage.removeItem("token");
|
||||
Cookies.remove("access_token"); // Limpeza de segurança
|
||||
|
||||
setShowLogoutDialog(false);
|
||||
router.push("/"); // Redireciona para a home
|
||||
}
|
||||
};
|
||||
|
||||
const cancelLogout = () => {
|
||||
setShowLogoutDialog(false);
|
||||
@ -114,10 +113,36 @@ export default function DoctorLayout({ children }: PatientLayoutProps) {
|
||||
};
|
||||
|
||||
const menuItems = [
|
||||
{ href: "#", icon: Home, label: "Dashboard" },
|
||||
{ href: "/doctor/medicos/consultas", icon: Calendar, label: "Consultas" },
|
||||
{ href: "#", icon: Clock, label: "Editor de Laudo" },
|
||||
{ href: "/doctor/medicos", icon: User, label: "Pacientes" },
|
||||
{
|
||||
href: "/doctor/dashboard",
|
||||
icon: Home,
|
||||
label: "Dashboard",
|
||||
// Botão para o dashboard do médico
|
||||
},
|
||||
{
|
||||
href: "/doctor/medicos/consultas",
|
||||
icon: Calendar,
|
||||
label: "Consultas",
|
||||
// Botão para página de consultas marcadas do médico atual
|
||||
},
|
||||
{
|
||||
href: "#",
|
||||
icon: Clock,
|
||||
label: "Editor de Laudo",
|
||||
// Botão para página do editor de laudo
|
||||
},
|
||||
{
|
||||
href: "/doctor/medicos",
|
||||
icon: User,
|
||||
label: "Pacientes",
|
||||
// Botão para a página de visualização de todos os pacientes
|
||||
},
|
||||
{
|
||||
href: "/doctor/disponibilidade",
|
||||
icon: Calendar,
|
||||
label: "Disponibilidade",
|
||||
// Botão para o dashboard do médico
|
||||
},
|
||||
];
|
||||
|
||||
if (!doctorData) {
|
||||
@ -143,7 +168,6 @@ export default function DoctorLayout({ children }: PatientLayoutProps) {
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<nav className="flex-1 p-2 overflow-y-auto">
|
||||
{menuItems.map((item) => {
|
||||
const Icon = item.icon;
|
||||
@ -159,48 +183,62 @@ export default function DoctorLayout({ children }: PatientLayoutProps) {
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
|
||||
// ... (seu código anterior)
|
||||
|
||||
{/* Sidebar para desktop */}
|
||||
<div className={`bg-white border-r border-gray-200 transition-all duration-300 ${sidebarCollapsed ? "w-16" : "w-64"} fixed left-0 top-0 h-screen flex flex-col z-50`}>
|
||||
<div className="p-4 border-b border-gray-200">
|
||||
<div className="flex items-center justify-between">
|
||||
{!sidebarCollapsed && (
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center">
|
||||
<div className="w-4 h-4 bg-white rounded-sm"></div>
|
||||
{/* Sidebar para desktop */}
|
||||
<div className={`bg-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>
|
||||
<span className="font-semibold text-gray-900">MediConnect</span>
|
||||
</div>
|
||||
<span className="font-semibold text-gray-900">MediConnect</span>
|
||||
</div>
|
||||
)}
|
||||
<Button variant="ghost" size="sm" onClick={() => setSidebarCollapsed(!sidebarCollapsed)} className="p-1">
|
||||
{sidebarCollapsed ? <ChevronRight className="w-4 h-4" /> : <ChevronLeft className="w-4 h-4" />}
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="ghost" size="sm" onClick={() => setSidebarCollapsed(!sidebarCollapsed)} className="p-1">
|
||||
{sidebarCollapsed ? <ChevronRight className="w-4 h-4" /> : <ChevronLeft className="w-4 h-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<nav className="flex-1 p-2 overflow-y-auto">
|
||||
{menuItems.map((item) => {
|
||||
const Icon = item.icon;
|
||||
const isActive = pathname === item.href || (item.href !== "/" && pathname.startsWith(item.href));
|
||||
<nav className="flex-1 p-2 overflow-y-auto">
|
||||
{menuItems.map((item) => {
|
||||
const Icon = item.icon;
|
||||
const isActive = pathname === item.href || (item.href !== "/" && pathname.startsWith(item.href));
|
||||
|
||||
return (
|
||||
<Link key={item.href} href={item.href}>
|
||||
<div className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors ${isActive ? "bg-blue-50 text-blue-600 border-r-2 border-blue-600" : "text-gray-600 hover:bg-gray-50"}`}>
|
||||
<Icon className="w-5 h-5 flex-shrink-0" />
|
||||
{!sidebarCollapsed && <span className="font-medium">{item.label}</span>}
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
return (
|
||||
<Link key={item.href} href={item.href}>
|
||||
<div className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors ${isActive ? "bg-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">
|
||||
{!sidebarCollapsed && (
|
||||
<>
|
||||
<Avatar>
|
||||
<div className="border-t p-4 mt-auto">
|
||||
<div className="flex items-center space-x-3 mb-4">
|
||||
{!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-gray-900 truncate">{doctorData.name}</p>
|
||||
<p className="text-xs text-gray-500 truncate">{doctorData.specialty}</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{sidebarCollapsed && (
|
||||
<Avatar className="mx-auto">
|
||||
<AvatarImage src="/placeholder.svg?height=40&width=40" />
|
||||
<AvatarFallback>
|
||||
{doctorData.name
|
||||
@ -209,39 +247,17 @@ export default function DoctorLayout({ children }: PatientLayoutProps) {
|
||||
.join("")}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium text-gray-900 truncate">{doctorData.name}</p>
|
||||
<p className="text-xs text-gray-500 truncate">{doctorData.specialty}</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{sidebarCollapsed && (
|
||||
<Avatar className="mx-auto">
|
||||
<AvatarImage src="/placeholder.svg?height=40&width=40" />
|
||||
<AvatarFallback>
|
||||
{doctorData.name
|
||||
.split(" ")
|
||||
.map((n) => n[0])
|
||||
.join("")}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div
|
||||
className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors text-muted-foreground hover:bg-accent cursor-pointer ${sidebarCollapsed ? "justify-center" : ""}`}
|
||||
onClick={handleLogout}
|
||||
>
|
||||
<LogOut className="w-5 h-5 flex-shrink-0" />
|
||||
{!sidebarCollapsed && <span className="font-medium">Sair</span>}
|
||||
<div className={`flex items-center gap-3 px-3 py-2 rounded-lg mb-1 transition-colors text-muted-foreground hover:bg-accent cursor-pointer ${sidebarCollapsed ? "justify-center" : ""}`} onClick={handleLogout}>
|
||||
<LogOut className="w-5 h-5 flex-shrink-0" />
|
||||
{!sidebarCollapsed && <span className="font-medium">Sair</span>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
{isMobileMenuOpen && (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 z-40 md:hidden" onClick={toggleMobileMenu}></div>
|
||||
)}
|
||||
{isMobileMenuOpen && <div className="fixed inset-0 bg-black bg-opacity-50 z-40 md:hidden" onClick={toggleMobileMenu}></div>}
|
||||
<div className={`bg-white border-r border-gray-200 fixed left-0 top-0 h-screen flex flex-col z-50 transition-transform duration-300 md:hidden ${isMobileMenuOpen ? "translate-x-0 w-64" : "-translate-x-full w-64"}`}>
|
||||
<div className="p-4 border-b border-gray-200 flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
@ -287,7 +303,15 @@ export default function DoctorLayout({ children }: PatientLayoutProps) {
|
||||
<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(); }}>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-full bg-transparent"
|
||||
onClick={() => {
|
||||
handleLogout();
|
||||
toggleMobileMenu();
|
||||
}}
|
||||
>
|
||||
<LogOut className="mr-2 h-4 w-4" />
|
||||
Sair
|
||||
</Button>
|
||||
@ -335,4 +359,4 @@ export default function DoctorLayout({ children }: PatientLayoutProps) {
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
9
services/availabilityApi.mjs
Normal file
9
services/availabilityApi.mjs
Normal file
@ -0,0 +1,9 @@
|
||||
import { api } from "./api.mjs";
|
||||
|
||||
export const AvailabilityService = {
|
||||
list: () => api.get("/rest/v1/doctor_availability"),
|
||||
listById: (id) => api.get(`/rest/v1/doctor_availability?doctor_id=eq.${id}`),
|
||||
create: (data) => api.post("/rest/v1/doctor_availability", data),
|
||||
update: (id, data) => api.patch(`/rest/v1/doctor_availability?id=eq.${id}`, data),
|
||||
delete: (id) => api.delete(`/rest/v1/doctor_availability?id=eq.${id}`),
|
||||
};
|
||||
8
services/exceptionApi.mjs
Normal file
8
services/exceptionApi.mjs
Normal file
@ -0,0 +1,8 @@
|
||||
import { api } from "./api.mjs";
|
||||
|
||||
export const exceptionsService = {
|
||||
list: () => api.get("/rest/v1/doctor_exceptions"),
|
||||
listById: () => api.get(`/rest/v1/doctor_exceptions?id=eq.${id}`),
|
||||
create: (data) => api.post("/rest/v1/doctor_exceptions", data),
|
||||
delete: (id) => api.delete(`/rest/v1/doctor_exceptions?id=eq.${id}`),
|
||||
};
|
||||
@ -1,9 +1,9 @@
|
||||
import { api } from "./api.mjs";
|
||||
|
||||
export const patientsService = {
|
||||
list: () => api.get("/rest/v1/patients"),
|
||||
getById: (id) => api.get(`/rest/v1/patients?id=eq.${id}`),
|
||||
create: (data) => api.post("/rest/v1/patients", data),
|
||||
update: (id, data) => api.patch(`/rest/v1/patients?id=eq.${id}`, data),
|
||||
delete: (id) => api.delete(`/rest/v1/patients?id=eq.${id}`),
|
||||
list: () => api.get("/rest/v1/patients"),
|
||||
getById: (id) => api.get(`/rest/v1/patients?id=eq.${id}`),
|
||||
create: (data) => api.post("/rest/v1/patients", data),
|
||||
update: (id, data) => api.patch(`/rest/v1/patients?id=eq.${id}`, data),
|
||||
delete: (id) => api.delete(`/rest/v1/patients?id=eq.${id}`),
|
||||
};
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user