feat: Substitui calendário antigo pelo novo EventManager

This commit is contained in:
Jonas Francisco 2025-10-31 00:27:48 -03:00
parent 5b3faab1bd
commit 44ddc4d03a
4 changed files with 3265 additions and 214 deletions

View File

@ -1,246 +1,297 @@
"use client"; "use client";
// Imports mantidos
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import dynamic from "next/dynamic"; import dynamic from "next/dynamic";
import pt_br_locale from "@fullcalendar/core/locales/pt-br"; import Link from "next/link";
import FullCalendar from "@fullcalendar/react";
import dayGridPlugin from "@fullcalendar/daygrid"; // --- Imports do FullCalendar (ANTIGO) - REMOVIDOS ---
import interactionPlugin from "@fullcalendar/interaction"; // import pt_br_locale from "@fullcalendar/core/locales/pt-br";
import timeGridPlugin from "@fullcalendar/timegrid"; // import FullCalendar from "@fullcalendar/react";
import { EventInput } from "@fullcalendar/core/index.js"; // import dayGridPlugin from "@fullcalendar/daygrid";
// import interactionPlugin from "@fullcalendar/interaction";
// import timeGridPlugin from "@fullcalendar/timegrid";
// import { EventInput } from "@fullcalendar/core/index.js";
// --- Imports do EventManager (NOVO) - ADICIONADOS ---
import { EventManager, type Event } from "@/components/event-manager";
import { v4 as uuidv4 } from 'uuid';
// Imports mantidos
import { Sidebar } from "@/components/dashboard/sidebar"; import { Sidebar } from "@/components/dashboard/sidebar";
import { PagesHeader } from "@/components/dashboard/header"; import { PagesHeader } from "@/components/dashboard/header";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { mockWaitingList } from "@/lib/mocks/appointment-mocks"; import { mockWaitingList } from "@/lib/mocks/appointment-mocks";
import "./index.css"; import "./index.css";
import Link from "next/link";
import { import {
DropdownMenu,   DropdownMenu,
DropdownMenuContent,   DropdownMenuContent,
DropdownMenuItem,   DropdownMenuItem,
DropdownMenuTrigger,   DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"; } from "@/components/ui/dropdown-menu";
import { ThreeDWallCalendar, CalendarEvent } from "@/components/ui/three-dwall-calendar"; import { ThreeDWallCalendar, CalendarEvent } from "@/components/ui/three-dwall-calendar"; // Calendário 3D mantido
const ListaEspera = dynamic( const ListaEspera = dynamic(
() => import("@/components/agendamento/ListaEspera"),   () => import("@/components/agendamento/ListaEspera"),
{ ssr: false }   { ssr: false }
); );
export default function AgendamentoPage() { export default function AgendamentoPage() {
const [appointments, setAppointments] = useState<any[]>([]);   const [appointments, setAppointments] = useState<any[]>([]);
const [waitingList, setWaitingList] = useState(mockWaitingList);   const [waitingList, setWaitingList] = useState(mockWaitingList);
const [activeTab, setActiveTab] = useState<"calendar" | "espera" | "3d">("calendar");   const [activeTab, setActiveTab] = useState<"calendar" | "espera" | "3d">("calendar");
const [requestsList, setRequestsList] = useState<EventInput[]>();  
// O 'requestsList' do FullCalendar foi removido.
// const [requestsList, setRequestsList] = useState<EventInput[]>();
 
const [threeDEvents, setThreeDEvents] = useState<CalendarEvent[]>([]); const [threeDEvents, setThreeDEvents] = useState<CalendarEvent[]>([]);
useEffect(() => { // --- Dados de Exemplo para o NOVO Calendário ---
document.addEventListener("keydown", (event) => { // (Colado do exemplo do 21st.dev)
if (event.key === "c") { const demoEvents: Event[] = [
setActiveTab("calendar"); {
} id: uuidv4(),
if (event.key === "f") { title: "Team Standup",
setActiveTab("espera"); description: "Daily sync with the engineering team.",
} startTime: new Date(2025, 9, 20, 9, 0, 0), // Mês 9 = Outubro
if (event.key === "3") { endTime: new Date(2025, 9, 20, 9, 30, 0),
setActiveTab("3d"); color: "blue",
} },
}); {
}, []); id: uuidv4(),
title: "Code Review",
useEffect(() => { description: "Review PRs for the new feature.",
// Fetch real appointments and map to calendar events startTime: new Date(2025, 9, 21, 14, 0, 0),
let mounted = true; endTime: new Date(2025, 9, 21, 15, 0, 0),
(async () => { color: "green",
try { },
// listarAgendamentos accepts a query string; request a reasonable limit and order {
const api = await import('@/lib/api'); id: uuidv4(),
const arr = await api.listarAgendamentos('select=*&order=scheduled_at.desc&limit=500').catch(() => []); title: "Client Presentation",
if (!mounted) return; description: "Present the new designs to the client.",
if (!arr || !arr.length) { startTime: new Date(2025, 9, 22, 11, 0, 0),
setAppointments([]); endTime: new Date(2025, 9, 22, 12, 0, 0),
setRequestsList([]); color: "orange",
setThreeDEvents([]); },
return; {
} id: uuidv4(),
title: "Sprint Planning",
// Batch-fetch patient names for display description: "Plan the next sprint tasks.",
const patientIds = Array.from(new Set(arr.map((a: any) => a.patient_id).filter(Boolean))); startTime: new Date(2025, 9, 23, 10, 0, 0),
const patients = (patientIds && patientIds.length) ? await api.buscarPacientesPorIds(patientIds) : []; endTime: new Date(2025, 9, 23, 11, 30, 0),
const patientsById: Record<string, any> = {}; color: "purple",
(patients || []).forEach((p: any) => { if (p && p.id) patientsById[String(p.id)] = p; }); },
{
setAppointments(arr || []); id: uuidv4(),
title: "Doctor Appointment",
const events: EventInput[] = (arr || []).map((obj: any) => { description: "Annual check-up.",
const scheduled = obj.scheduled_at || obj.scheduledAt || obj.time || null; startTime: new Date(2025, 9, 24, 16, 0, 0),
const start = scheduled ? new Date(scheduled) : null; endTime: new Date(2025, 9, 24, 17, 0, 0),
const duration = Number(obj.duration_minutes ?? obj.duration ?? 30) || 30; color: "red",
const patient = (patientsById[String(obj.patient_id)]?.full_name) || obj.patient_name || obj.patient_full_name || obj.patient || 'Paciente'; },
const title = `${patient}: ${obj.appointment_type ?? obj.type ?? ''}`.trim(); {
const color = obj.status === 'confirmed' ? '#68d68a' : obj.status === 'pending' ? '#ffe55f' : '#ff5f5fff'; id: uuidv4(),
return { title: "Deploy to Production",
title, description: "Deploy the new release.",
start: start || new Date(), startTime: new Date(2025, 9, 25, 15, 0, 0),
end: start ? new Date(start.getTime() + duration * 60 * 1000) : undefined, endTime: new Date(2025, 9, 25, 16, 0, 0),
color, color: "teal",
extendedProps: { raw: obj }, },
} as EventInput; {
}); id: uuidv4(),
setRequestsList(events || []); title: "Product Design Review",
description: "Review the new product design mockups.",
// Convert to 3D calendar events startTime: new Date(2025, 9, 20, 13, 0, 0),
const threeDEvents: CalendarEvent[] = (arr || []).map((obj: any) => { endTime: new Date(2025, 9, 20, 14, 30, 0),
const scheduled = obj.scheduled_at || obj.scheduledAt || obj.time || null; color: "pink",
const patient = (patientsById[String(obj.patient_id)]?.full_name) || obj.patient_name || obj.patient_full_name || obj.patient || 'Paciente'; },
const title = `${patient}: ${obj.appointment_type ?? obj.type ?? ''}`.trim(); {
return { id: uuidv4(),
id: obj.id || String(Date.now()), title: "Gym Session",
title, description: "Leg day.",
date: scheduled ? new Date(scheduled).toISOString() : new Date().toISOString(), startTime: new Date(2025, 9, 20, 18, 0, 0),
}; endTime: new Date(2025, 9, 20, 19, 0, 0),
}); color: "gray",
setThreeDEvents(threeDEvents); },
} catch (err) { ];
console.warn('[AgendamentoPage] falha ao carregar agendamentos', err); // --- Fim dos Dados de Exemplo ---
setAppointments([]);
setRequestsList([]);   useEffect(() => {
setThreeDEvents([]);     document.addEventListener("keydown", (event) => {
}       if (event.key === "c") {
})();         setActiveTab("calendar");
return () => { mounted = false; };       }
}, []);       if (event.key === "f") {
        setActiveTab("espera");
// mantive para caso a lógica de salvar consulta passe a funcionar       }
const handleSaveAppointment = (appointment: any) => {       if (event.key === "3") {
if (appointment.id) {         setActiveTab("3d");
setAppointments((prev) =>       }
prev.map((a) => (a.id === appointment.id ? appointment : a))     });
);   }, []);
} else {
const newAppointment = {   useEffect(() => {
...appointment, // Este useEffect foi mantido, pois ele busca dados para o Calendário 3D
id: Date.now().toString(),     let mounted = true;
};     (async () => {
setAppointments((prev) => [...prev, newAppointment]);       try {
}         const api = await import('@/lib/api');
};         const arr = await api.listarAgendamentos('select=*&order=scheduled_at.desc&limit=500').catch(() => []);
        if (!mounted) return;
const handleNotifyPatient = (patientId: string) => {         if (!arr || !arr.length) {
console.log(`Notificando paciente ${patientId}`);           setAppointments([]);
};           // setRequestsList([]); // Removido
          setThreeDEvents([]);
const handleAddEvent = (event: CalendarEvent) => {           return;
setThreeDEvents((prev) => [...prev, event]);         }
};
        const patientIds = Array.from(new Set(arr.map((a: any) => a.patient_id).filter(Boolean)));
const handleRemoveEvent = (id: string) => {         const patients = (patientIds && patientIds.length) ? await api.buscarPacientesPorIds(patientIds) : [];
setThreeDEvents((prev) => prev.filter((e) => e.id !== id));         const patientsById: Record<string, any> = {};
};         (patients || []).forEach((p: any) => { if (p && p.id) patientsById[String(p.id)] = p; });
return (         setAppointments(arr || []);
<div className="flex flex-row bg-background">
<div className="flex w-full flex-col"> // --- Mapeamento para o FullCalendar (ANTIGO) - REMOVIDO ---
<div className="flex w-full flex-col gap-10 p-6">         // const events: EventInput[] = (arr || []).map((obj: any) => {
<div className="flex flex-row justify-between items-center">         //   ...
<div>         // });
<h1 className="text-2xl font-bold text-foreground">         // setRequestsList(events || []);
{activeTab === "calendar" ? "Calendário" : activeTab === "3d" ? "Calendário 3D" : "Lista de Espera"}
</h1>         // Convert to 3D calendar events (MANTIDO)
<p className="text-muted-foreground">         const threeDEvents: CalendarEvent[] = (arr || []).map((obj: any) => {
Navegue através dos atalhos: Calendário (C), Fila de espera (F) ou 3D (3).           const scheduled = obj.scheduled_at || obj.scheduledAt || obj.time || null;
</p>           const patient = (patientsById[String(obj.patient_id)]?.full_name) || obj.patient_name || obj.patient_full_name || obj.patient || 'Paciente';
</div>           const title = `${patient}: ${obj.appointment_type ?? obj.type ?? ''}`.trim();
<div className="flex space-x-2">           return {
{/* <Link href={"/agenda"}>             id: obj.id || String(Date.now()),
<Button className="bg-blue-600 hover:bg-blue-700">             title,
Agenda             date: scheduled ? new Date(scheduled).toISOString() : new Date().toISOString(),
</Button>           };
</Link> */}         });
<DropdownMenu>         setThreeDEvents(threeDEvents);
<DropdownMenuTrigger className="bg-primary hover:bg-primary/90 px-5 py-1 text-primary-foreground rounded-sm">       } catch (err) {
Opções &#187;         console.warn('[AgendamentoPage] falha ao carregar agendamentos', err);
</DropdownMenuTrigger>         setAppointments([]);
<DropdownMenuContent>         // setRequestsList([]); // Removido
<Link href={"/agenda"}>         setThreeDEvents([]);
<DropdownMenuItem>Agendamento</DropdownMenuItem>       }
</Link>     })();
<Link href={"/procedimento"}>     return () => { mounted = false; };
<DropdownMenuItem>Procedimento</DropdownMenuItem>   }, []);
</Link>
<Link href={"/financeiro"}>   // Handlers mantidos
<DropdownMenuItem>Financeiro</DropdownMenuItem>   const handleSaveAppointment = (appointment: any) => {
</Link>     if (appointment.id) {
</DropdownMenuContent>       setAppointments((prev) =>
</DropdownMenu>         prev.map((a) => (a.id === appointment.id ? appointment : a))
      );
<div className="flex flex-row">     } else {
<Button       const newAppointment = {
variant={"outline"}         ...appointment,
className="bg-muted hover:!bg-primary hover:!text-white transition-colors rounded-l-[100px] rounded-r-[0px]"         id: Date.now().toString(),
onClick={() => setActiveTab("calendar")}       };
>       setAppointments((prev) => [...prev, newAppointment]);
Calendário     }
</Button>   };
<Button   const handleNotifyPatient = (patientId: string) => {
variant={"outline"}     console.log(`Notificando paciente ${patientId}`);
className="bg-muted hover:!bg-primary hover:!text-white transition-colors rounded-none"   };
onClick={() => setActiveTab("3d")}
>   const handleAddEvent = (event: CalendarEvent) => {
3D     setThreeDEvents((prev) => [...prev, event]);
</Button>   };
<Button   const handleRemoveEvent = (id: string) => {
variant={"outline"}     setThreeDEvents((prev) => prev.filter((e) => e.id !== id));
className="bg-muted hover:!bg-primary hover:!text-white transition-colors rounded-r-[100px] rounded-l-[0px]"   };
onClick={() => setActiveTab("espera")}
>   return (
Lista de espera     <div className="flex flex-row bg-background">
</Button>       <div className="flex w-full flex-col">
</div>         <div className="flex w-full flex-col gap-10 p-6">
</div>           <div className="flex flex-row justify-between items-center">
</div> {/* Todo o cabeçalho foi mantido */}
            <div>
{activeTab === "calendar" ? (               <h1 className="text-2xl font-bold text-foreground">
<div className="flex w-full">                 {activeTab === "calendar" ? "Calendário" : activeTab === "3d" ? "Calendário 3D" : "Lista de Espera"}
<FullCalendar               </h1>
plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}               <p className="text-muted-foreground">
initialView="dayGridMonth"                 Navegue através dos atalhos: Calendário (C), Fila de espera (F) ou 3D (3).
locale={pt_br_locale}               </p>
timeZone={"America/Sao_Paulo"}             </div>
events={requestsList}             <div className="flex space-x-2">
headerToolbar={{               <DropdownMenu>
left: "prev,next today",                 <DropdownMenuTrigger className="bg-primary hover:bg-primary/90 px-5 py-1 text-primary-foreground rounded-sm">
center: "title",                   Opções &#187;
right: "dayGridMonth,timeGridWeek,timeGridDay",                 </DropdownMenuTrigger>
}}                 <DropdownMenuContent>
dateClick={(info) => {                   <Link href={"/agenda"}>
info.view.calendar.changeView("timeGridDay", info.dateStr);                     <DropdownMenuItem>Agendamento</DropdownMenuItem>
}}                   </Link>
selectable={true}                   <Link href={"/procedimento"}>
selectMirror={true}                     <DropdownMenuItem>Procedimento</DropdownMenuItem>
dayMaxEvents={true}                   </Link>
dayMaxEventRows={3}                   <Link href={"/financeiro"}>
/>                     <DropdownMenuItem>Financeiro</DropdownMenuItem>
</div>                   </Link>
) : activeTab === "3d" ? (                 </DropdownMenuContent>
<div className="flex w-full">               </DropdownMenu>
<ThreeDWallCalendar
events={threeDEvents}               <div className="flex flex-row">
onAddEvent={handleAddEvent}                 <Button
onRemoveEvent={handleRemoveEvent}                   variant={"outline"}
/>                   className="bg-muted hover:!bg-primary hover:!text-white transition-colors rounded-l-[100px] rounded-r-[0px]"
</div>                   onClick={() => setActiveTab("calendar")}
) : (                 >
<ListaEspera                   Calendário
patients={waitingList}                 </Button>
onNotify={handleNotifyPatient}
onAddToWaitlist={() => {}}                 <Button
/>                   variant={"outline"}
)}                   className="bg-muted hover:!bg-primary hover:!text-white transition-colors rounded-none"
</div>                   onClick={() => setActiveTab("3d")}
</div>                 >
</div>                   3D
);                 </Button>
                <Button
                  variant={"outline"}
                  className="bg-muted hover:!bg-primary hover:!text-white transition-colors rounded-r-[100px] rounded-l-[0px]"
                  onClick={() => setActiveTab("espera")}
                >
                  Lista de espera
                </Button>
              </div>
            </div>
          </div>
{/* --- AQUI ESTÁ A MUDANÇA --- */}
          {activeTab === "calendar" ? (
            <div className="flex w-full">
{/* O FullCalendar antigo foi substituído por este */}
<EventManager events={demoEvents} />
            </div>
          ) : activeTab === "3d" ? (
// O calendário 3D foi mantido intacto
            <div className="flex w-full">
              <ThreeDWallCalendar
                events={threeDEvents}
                onAddEvent={handleAddEvent}
                onRemoveEvent={handleRemoveEvent}
              />
            </div>
          ) : (
// A Lista de Espera foi mantida intacta
            <ListaEspera
              patients={waitingList}
              onNotify={handleNotifyPatient}
              onAddToWaitlist={() => {}}
            />
          )}
        </div>
      </div>
    </div>
  );
} }

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -65,6 +65,7 @@
"sonner": "latest", "sonner": "latest",
"tailwind-merge": "^2.5.5", "tailwind-merge": "^2.5.5",
"tailwindcss-animate": "^1.0.7", "tailwindcss-animate": "^1.0.7",
"uuid": "^13.0.0",
"vaul": "latest", "vaul": "latest",
"zod": "3.25.67" "zod": "3.25.67"
}, },
@ -9175,6 +9176,19 @@
"base64-arraybuffer": "^1.0.2" "base64-arraybuffer": "^1.0.2"
} }
}, },
"node_modules/uuid": {
"version": "13.0.0",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-13.0.0.tgz",
"integrity": "sha512-XQegIaBTVUjSHliKqcnFqYypAd4S+WCYt5NIeRs6w/UAry7z8Y9j5ZwRRL4kzq9U3sD6v+85er9FvkEaBpji2w==",
"funding": [
"https://github.com/sponsors/broofa",
"https://github.com/sponsors/ctavan"
],
"license": "MIT",
"bin": {
"uuid": "dist-node/bin/uuid"
}
},
"node_modules/vaul": { "node_modules/vaul": {
"version": "1.1.2", "version": "1.1.2",
"resolved": "https://registry.npmjs.org/vaul/-/vaul-1.1.2.tgz", "resolved": "https://registry.npmjs.org/vaul/-/vaul-1.1.2.tgz",