Compare commits

..

1 Commits

Author SHA1 Message Date
ARJUN S THAMPI c6a041ac10 feat: add pagination in appointment 2026-03-27 12:09:46 +05:30
12 changed files with 397 additions and 310 deletions
@@ -1,10 +1,10 @@
import prisma from "../prisma/client.js"; import prisma from "../prisma/client.js";
import {sendEmail} from "../utils/sendEmail.js"; import { sendEmail } from "../utils/sendEmail.js";
import {getEmailsByType} from "../utils/getEmailByTypes.js"; import { getEmailsByType } from "../utils/getEmailByTypes.js";
export const createAppointment = async (req, res) => { export const createAppointment = async (req, res) => {
try { try {
const {name, mobileNumber, email, message, date, doctorId, departmentId} = const { name, mobileNumber, email, message, date, doctorId, departmentId } =
req.body; req.body;
if (!name || !mobileNumber || !doctorId || !departmentId || !date) { if (!name || !mobileNumber || !doctorId || !departmentId || !date) {
@@ -71,19 +71,98 @@ export const createAppointment = async (req, res) => {
export const getAppointments = async (req, res) => { export const getAppointments = async (req, res) => {
try { try {
const appointments = await prisma.appointment.findMany({ const page = parseInt(req.query.page);
include: { const limit = parseInt(req.query.limit);
doctor: true,
department: true,
},
orderBy: {
createdAt: "desc",
},
});
res.status(200).json({ const search = req.query.search || "";
const doctor = req.query.doctor || "";
const department = req.query.department || "";
const date = req.query.date || "";
if (!page && !limit) {
const appointments = await prisma.appointment.findMany({
include: {
doctor: true,
department: true,
},
orderBy: { createdAt: "desc" },
});
return res.status(200).json({
success: true,
data: appointments,
meta: null,
});
}
const currentPage = page || 1;
const currentLimit = limit || 10;
const skip = (currentPage - 1) * currentLimit;
const where = {
AND: [
search
? {
OR: [
{ name: { contains: search, mode: "insensitive" } },
{ mobileNumber: { contains: search } },
{ email: { contains: search, mode: "insensitive" } },
],
}
: {},
doctor
? {
doctor: {
name: { contains: doctor, mode: "insensitive" },
},
}
: {},
department
? {
department: {
name: { contains: department, mode: "insensitive" },
},
}
: {},
date
? {
date: {
gte: new Date(date),
lt: new Date(
new Date(date).setDate(new Date(date).getDate() + 1),
),
},
}
: {},
],
};
const [appointments, total] = await Promise.all([
prisma.appointment.findMany({
where,
include: {
doctor: true,
department: true,
},
orderBy: { createdAt: "desc" },
skip,
take: currentLimit,
}),
prisma.appointment.count({ where }),
]);
return res.status(200).json({
success: true, success: true,
data: appointments, data: appointments,
meta: {
total,
page: currentPage,
limit: currentLimit,
totalPages: Math.ceil(total / currentLimit),
},
}); });
} catch (error) { } catch (error) {
console.error(error); console.error(error);
@@ -98,7 +177,7 @@ export const getAppointments = async (req, res) => {
export const getAppointment = async (req, res) => { export const getAppointment = async (req, res) => {
try { try {
const {id} = req.params; const { id } = req.params;
const appointment = await prisma.appointment.findUnique({ const appointment = await prisma.appointment.findUnique({
where: { where: {
@@ -134,7 +213,7 @@ export const getAppointment = async (req, res) => {
export const getAppointmentsByDoctor = async (req, res) => { export const getAppointmentsByDoctor = async (req, res) => {
try { try {
const {doctorId} = req.params; const { doctorId } = req.params;
const appointments = await prisma.appointment.findMany({ const appointments = await prisma.appointment.findMany({
where: { where: {
@@ -166,7 +245,7 @@ export const getAppointmentsByDoctor = async (req, res) => {
export const getAppointmentsByDepartment = async (req, res) => { export const getAppointmentsByDepartment = async (req, res) => {
try { try {
const {departmentId} = req.params; const { departmentId } = req.params;
const appointments = await prisma.appointment.findMany({ const appointments = await prisma.appointment.findMany({
where: { where: {
@@ -195,7 +274,7 @@ export const getAppointmentsByDepartment = async (req, res) => {
export const updateAppointment = async (req, res) => { export const updateAppointment = async (req, res) => {
try { try {
const {id} = req.params; const { id } = req.params;
const appointment = await prisma.appointment.update({ const appointment = await prisma.appointment.update({
where: { where: {
@@ -226,7 +305,7 @@ export const updateAppointment = async (req, res) => {
export const deleteAppointment = async (req, res) => { export const deleteAppointment = async (req, res) => {
try { try {
const {id} = req.params; const { id } = req.params;
await prisma.appointment.delete({ await prisma.appointment.delete({
where: { where: {
@@ -29,53 +29,6 @@ export const getAllDepartments = async (req, res) => {
} }
}; };
export const getDepartmentByName = async (req, res) => {
try {
const {name} = req.query;
if (!name) {
return res.status(400).json({
success: false,
message: "Department name is required",
});
}
const department = await prisma.department.findFirst({
where: {
name: name,
},
});
if (!department) {
return res.status(404).json({
success: false,
message: "Department not found",
});
}
const response = {
departmentId: department.departmentId,
name: department.name,
para1: department.para1 ?? "",
para2: department.para2 ?? "",
para3: department.para3 ?? "",
facilities: department.facilities ?? "",
services: department.services ?? "",
};
return res.status(200).json({
success: true,
data: [response],
});
} catch (error) {
console.error(error);
return res.status(500).json({
success: false,
message: "Failed to fetch department",
});
}
};
export async function createDepartment(req, res) { export async function createDepartment(req, res) {
try { try {
const {departmentId, name, para1, para2, para3, facilities, services} = const {departmentId, name, para1, para2, para3, facilities, services} =
+91 -103
View File
@@ -16,35 +16,38 @@ export const getAllDoctors = async (req, res) => {
orderBy: {name: "asc"}, orderBy: {name: "asc"},
}); });
const formatted = doctors.map((doc, index) => ({ const formatted = doctors.map((doc, index) => {
SL_NO: String(index + 1), return {
doctorId: doc.doctorId, SL_NO: String(index + 1),
name: doc.name, doctorId: doc.doctorId,
designation: doc.designation, name: doc.name,
workingStatus: doc.workingStatus, designation: doc.designation,
qualification: doc.qualification, workingStatus: doc.workingStatus,
qualification: doc.qualification,
departments: doc.departments.map((d) => { departments: doc.departments.map((d) => {
const t = d.timing || {}; const t = d.timing || {};
const timingArray = [ const timingArray = [
t.monday && `Monday ${t.monday}`, t.monday && `Monday ${t.monday}`,
t.tuesday && `Tuesday ${t.tuesday}`, t.tuesday && `Tuesday ${t.tuesday}`,
t.wednesday && `Wednesday ${t.wednesday}`, t.wednesday && `Wednesday ${t.wednesday}`,
t.thursday && `Thursday ${t.thursday}`, t.thursday && `Thursday ${t.thursday}`,
t.friday && `Friday ${t.friday}`, t.friday && `Friday ${t.friday}`,
t.saturday && `Saturday ${t.saturday}`, t.saturday && `Saturday ${t.saturday}`,
t.sunday && `Sunday ${t.sunday}`, t.sunday && `Sunday ${t.sunday}`,
t.additional && t.additional, t.additional && t.additional,
].filter(Boolean); ].filter(Boolean);
return { return {
departmentId: d.department.departmentId, departmentId: d.department.departmentId,
departmentName: d.department.name, departmentName: d.department.name,
timing: timingArray.join(" & "),
}; timing: timingArray.join(" & "),
}), };
})); }),
};
});
res.status(200).json({ res.status(200).json({
success: true, success: true,
@@ -110,54 +113,6 @@ export const getDoctorByDoctorId = async (req, res) => {
} }
}; };
// get doctors by department
export const getDoctorsByDepartmentId = async (req, res) => {
try {
const {Department_ID} = req.query;
if (!Department_ID) {
return res.status(400).json({
success: false,
message: "Department_ID is required",
});
}
const department = await prisma.department.findUnique({
where: {departmentId: Department_ID},
});
if (!department) {
return res.status(404).json({
success: false,
message: "Department not found",
});
}
const doctors = await prisma.doctorDepartment.findMany({
where: {departmentId: department.id},
include: {
doctor: true,
},
});
const result = doctors.map((d) => ({
GG_ID: d.doctor.doctorId,
Name: d.doctor.name,
}));
res.status(200).json({
success: true,
data: result,
});
} catch (error) {
console.error(error);
res.status(500).json({
success: false,
message: "Failed to fetch doctors",
});
}
};
// add doctors // add doctors
export const createDoctor = async (req, res) => { export const createDoctor = async (req, res) => {
try { try {
@@ -229,14 +184,20 @@ export const updateDoctor = async (req, res) => {
}); });
if (!doctor) { if (!doctor) {
return res return res.status(404).json({
.status(404) success: false,
.json({success: false, message: "Doctor not found"}); message: "Doctor not found",
});
} }
await prisma.doctor.update({ await prisma.doctor.update({
where: {id: doctor.id}, where: {id: doctor.id},
data: {name, designation, workingStatus, qualification}, data: {
name,
designation,
workingStatus,
qualification,
},
}); });
const oldRelations = await prisma.doctorDepartment.findMany({ const oldRelations = await prisma.doctorDepartment.findMany({
@@ -268,24 +229,25 @@ export const updateDoctor = async (req, res) => {
}); });
if (dep.timing) { if (dep.timing) {
const {id, doctorDepartmentId, createdAt, updatedAt, ...cleanTiming} =
dep.timing;
await prisma.doctorTiming.create({ await prisma.doctorTiming.create({
data: { data: {
doctorDepartmentId: doctorDepartment.id, doctorDepartmentId: doctorDepartment.id,
...cleanTiming, ...dep.timing,
}, },
}); });
} }
} }
res res.status(200).json({
.status(200) success: true,
.json({success: true, message: "Doctor updated successfully"}); message: "Doctor updated successfully",
});
} catch (error) { } catch (error) {
console.error("Update Error:", error); console.error(error);
res.status(500).json({success: false, message: "Failed to update doctor"}); res.status(500).json({
success: false,
message: "Failed to update doctor",
});
} }
}; };
//delete doctor //delete doctor
@@ -294,6 +256,13 @@ export const deleteDoctor = async (req, res) => {
try { try {
const {doctorId} = req.params; const {doctorId} = req.params;
if (!doctorId) {
return res.status(400).json({
success: false,
message: "Doctor ID is required",
});
}
const doctor = await prisma.doctor.findUnique({ const doctor = await prisma.doctor.findUnique({
where: {doctorId}, where: {doctorId},
}); });
@@ -301,7 +270,7 @@ export const deleteDoctor = async (req, res) => {
if (!doctor) { if (!doctor) {
return res.status(404).json({ return res.status(404).json({
success: false, success: false,
message: "Doctor not found", message: `Doctor with ID ${doctorId} not found`,
}); });
} }
@@ -325,7 +294,7 @@ export const deleteDoctor = async (req, res) => {
res.status(200).json({ res.status(200).json({
success: true, success: true,
message: "Doctor deleted successfully", message: `Doctor ${doctorId} deleted successfully`,
}); });
} catch (error) { } catch (error) {
console.error(error); console.error(error);
@@ -351,19 +320,23 @@ export const getDoctorTimings = async (req, res) => {
}); });
const result = doctors.map((doc) => { const result = doctors.map((doc) => {
const timing = doc.departments[0]?.timing || {}; let timing = {};
if (doc.departments.length > 0) {
timing = doc.departments[0].timing ?? {};
}
return { return {
Doctor_ID: doc.doctorId, Doctor_ID: doc.doctorId,
Doctor: doc.name, Doctor: doc.name,
Monday: timing.monday || "", Monday: timing?.monday ?? "",
Tuesday: timing.tuesday || "", Tuesday: timing?.tuesday ?? "",
Wednesday: timing.wednesday || "", Wednesday: timing?.wednesday ?? "",
Thursday: timing.thursday || "", Thursday: timing?.thursday ?? "",
Friday: timing.friday || "", Friday: timing?.friday ?? "",
Saturday: timing.saturday || "", Saturday: timing?.saturday ?? "",
Sunday: timing.sunday || "", Sunday: timing?.sunday ?? "",
Additional: timing.additional || "", Additional: timing?.additional ?? "",
}; };
}); });
@@ -407,11 +380,26 @@ export const getDoctorTimingById = async (req, res) => {
const result = { const result = {
doctorId: doctor.doctorId, doctorId: doctor.doctorId,
doctorName: doctor.name, doctorName: doctor.name,
departments: doctor.departments.map((d) => ({
departmentId: d.department.departmentId, departments: doctor.departments.map((d) => {
departmentName: d.department.name, const t = d.timing || {};
timing: d.timing || {},
})), return {
departmentId: d.department.departmentId,
departmentName: d.department.name,
timing: {
monday: t.monday || "",
tuesday: t.tuesday || "",
wednesday: t.wednesday || "",
thursday: t.thursday || "",
friday: t.friday || "",
saturday: t.saturday || "",
sunday: t.sunday || "",
additional: t.additional || "",
},
};
}),
}; };
res.status(200).json({ res.status(200).json({
@@ -11,8 +11,8 @@ import jwtAuthMiddleware from "../middleware/auth.js";
const router = express.Router(); const router = express.Router();
router.post("/", createAcademicsResearch); router.post("/", createAcademicsResearch);
router.get("/getAll", jwtAuthMiddleware, getAcademicsResearch); router.get("/getAll", getAcademicsResearch);
router.get("/:id", jwtAuthMiddleware, getSingleAcademicsResearch); router.get("/:id", getSingleAcademicsResearch);
router.delete("/:id", jwtAuthMiddleware, deleteAcademicsResearch); router.delete("/:id", jwtAuthMiddleware, deleteAcademicsResearch);
export default router; export default router;
+3 -3
View File
@@ -13,11 +13,11 @@ const router = express.Router();
/* PUBLIC */ /* PUBLIC */
router.get("/getall", jwtAuthMiddleware, getAppointments); router.get("/getall", getAppointments);
router.post("/", createAppointment); router.post("/", createAppointment);
router.get("/:id", jwtAuthMiddleware, getAppointment); router.get("/:id", getAppointment);
router.patch("/:id", jwtAuthMiddleware, updateAppointment); router.patch("/:id", updateAppointment);
router.delete("/:id", jwtAuthMiddleware, deleteAppointment); router.delete("/:id", jwtAuthMiddleware, deleteAppointment);
export default router; export default router;
+6 -6
View File
@@ -13,13 +13,13 @@ import jwtAuthMiddleware from "../middleware/auth.js";
const router = express.Router(); const router = express.Router();
/* PUBLIC */ /* PUBLIC */
router.get("/getAll", getCandidates);
router.get("/:id", getCandidate);
router.get("/career/:careerId", getCandidatesByCareer);
router.post("/", createCandidate); router.post("/", createCandidate);
router.patch("/:id", updateCandidate);
router.get("/getAll", jwtAuthMiddleware, getCandidates);
router.get("/:id", jwtAuthMiddleware, getCandidate);
router.get("/career/:careerId", jwtAuthMiddleware, getCandidatesByCareer);
router.patch("/:id", jwtAuthMiddleware, updateCandidate);
router.delete("/:id", jwtAuthMiddleware, deleteCandidate); router.delete("/:id", jwtAuthMiddleware, deleteCandidate);
export default router; export default router;
+3 -3
View File
@@ -10,8 +10,8 @@ const router = express.Router();
router.get("/getAll", getAllCareers); router.get("/getAll", getAllCareers);
router.post("/", jwtAuthMiddleware, createCareer); router.post("/", createCareer);
router.patch("/:id", jwtAuthMiddleware, updateCareer); router.patch("/:id", updateCareer);
router.delete("/:id", jwtAuthMiddleware, deleteCareer); router.delete("/:id", deleteCareer);
export default router; export default router;
-2
View File
@@ -1,7 +1,6 @@
import express from "express"; import express from "express";
import { import {
getAllDepartments, getAllDepartments,
getDepartmentByName,
createDepartment, createDepartment,
updateDepartment, updateDepartment,
deleteDepartment, deleteDepartment,
@@ -12,7 +11,6 @@ const router = express.Router();
// Public // Public
router.get("/getAll", getAllDepartments); router.get("/getAll", getAllDepartments);
router.get("/search", getDepartmentByName);
// Protected // Protected
router.post("/", jwtAuthMiddleware, createDepartment); router.post("/", jwtAuthMiddleware, createDepartment);
+1 -3
View File
@@ -7,7 +7,6 @@ import {
getDoctorTimings, getDoctorTimings,
getDoctorTimingById, getDoctorTimingById,
getDoctorByDoctorId, getDoctorByDoctorId,
getDoctorsByDepartmentId,
} from "../controllers/doctor.controller.js"; } from "../controllers/doctor.controller.js";
import jwtAuthMiddleware from "../middleware/auth.js"; import jwtAuthMiddleware from "../middleware/auth.js";
@@ -15,10 +14,9 @@ import jwtAuthMiddleware from "../middleware/auth.js";
const router = express.Router(); const router = express.Router();
router.get("/getAll", getAllDoctors); router.get("/getAll", getAllDoctors);
router.get("/search", getDoctorsByDepartmentId); router.get("/:doctorId", getDoctorByDoctorId);
router.get("/getTimings", getDoctorTimings); router.get("/getTimings", getDoctorTimings);
router.get("/getTimings/:doctorId", getDoctorTimingById); router.get("/getTimings/:doctorId", getDoctorTimingById);
router.get("/:doctorId", getDoctorByDoctorId);
router.post("/", jwtAuthMiddleware, createDoctor); router.post("/", jwtAuthMiddleware, createDoctor);
router.patch("/:doctorId", jwtAuthMiddleware, updateDoctor); router.patch("/:doctorId", jwtAuthMiddleware, updateDoctor);
+2 -2
View File
@@ -12,8 +12,8 @@ const router = express.Router();
router.post("/", createInquiry); router.post("/", createInquiry);
router.get("/getAll", jwtAuthMiddleware, getInquiries); router.get("/getAll", getInquiries);
router.get("/:id", jwtAuthMiddleware, getInquiry); router.get("/:id", getInquiry);
router.delete("/:id", jwtAuthMiddleware, deleteInquiry); router.delete("/:id", jwtAuthMiddleware, deleteInquiry);
export default router; export default router;
+17 -2
View File
@@ -1,7 +1,22 @@
import apiClient from "@/api/client"; import apiClient from "@/api/client";
export const getAppointmentsApi = async () => { export const getAppointmentsApi = async (
const res = await apiClient.get("/appointments/getall"); page?: number,
limit?: number,
search?: string,
doctor?: string,
department?: string,
date?: string,
) => {
let url = "/appointments/getAll";
if (page && limit) {
url += `?page=${page}&limit=${limit}&search=${search || ""}&doctor=${
doctor || ""
}&department=${department || ""}&date=${date || ""}`;
}
const res = await apiClient.get(url);
return res.data; return res.data;
}; };
+175 -119
View File
@@ -1,7 +1,7 @@
import {useState, useEffect, useCallback} from "react"; import { useState, useEffect, useCallback } from "react";
import {getAppointmentsApi, deleteAppointmentApi} from "@/api/appointment"; import { getAppointmentsApi, deleteAppointmentApi } from "@/api/appointment";
import {exportToExcel} from "@/utils/exportToExcel"; import { exportToExcel } from "@/utils/exportToExcel";
import { import {
Table, Table,
@@ -12,12 +12,18 @@ import {
TableRow, TableRow,
} from "@/components/ui/table"; } from "@/components/ui/table";
import {Card, CardContent, CardHeader, CardTitle} from "@/components/ui/card"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {Button} from "@/components/ui/button"; import {
import {Input} from "@/components/ui/input"; Loader2,
Trash,
import {Loader2, Trash, RefreshCw, Download} from "lucide-react"; RefreshCw,
Download,
ChevronLeft,
ChevronRight,
} from "lucide-react";
export default function AppointmentPage() { export default function AppointmentPage() {
const [appointments, setAppointments] = useState<any[]>([]); const [appointments, setAppointments] = useState<any[]>([]);
@@ -28,106 +34,153 @@ export default function AppointmentPage() {
const [filterDepartment, setFilterDepartment] = useState(""); const [filterDepartment, setFilterDepartment] = useState("");
const [filterDate, setFilterDate] = useState(""); const [filterDate, setFilterDate] = useState("");
const [currentPage, setCurrentPage] = useState(1);
const [itemsPerPage, setItemsPerPage] = useState(10);
const [meta, setMeta] = useState<any>({});
const fetchAll = useCallback(async () => { const fetchAll = useCallback(async () => {
setLoading(true); setLoading(true);
try { try {
const res = await getAppointmentsApi(); const res = await getAppointmentsApi(
currentPage,
itemsPerPage,
searchText,
filterDoctor,
filterDepartment,
filterDate,
);
setAppointments(res?.data || []); setAppointments(res?.data || []);
setMeta(res?.meta || {});
} catch (err) { } catch (err) {
console.error(err); console.error(err);
} finally { } finally {
setLoading(false); setLoading(false);
} }
}, []); }, [
currentPage,
itemsPerPage,
searchText,
filterDoctor,
filterDepartment,
filterDate,
]);
useEffect(() => { useEffect(() => {
fetchAll(); fetchAll();
}, [fetchAll]); }, [fetchAll]);
const filteredAppointments = appointments.filter((item) => {
const matchesSearch =
item.name?.toLowerCase().includes(searchText.toLowerCase()) ||
item.mobileNumber?.includes(searchText) ||
item.email?.toLowerCase().includes(searchText.toLowerCase());
const matchesDoctor = filterDoctor
? item.doctor?.name?.toLowerCase().includes(filterDoctor.toLowerCase())
: true;
const matchesDepartment = filterDepartment
? item.department?.name
?.toLowerCase()
.includes(filterDepartment.toLowerCase())
: true;
const matchesDate = filterDate
? new Date(item.date).toISOString().split("T")[0] === filterDate
: true;
return matchesSearch && matchesDoctor && matchesDepartment && matchesDate;
});
async function handleDelete(id: number) { async function handleDelete(id: number) {
if (!confirm("Delete appointment?")) return; if (!confirm("Delete appointment?")) return;
await deleteAppointmentApi(id); await deleteAppointmentApi(id);
fetchAll(); fetchAll();
} }
const handleExport = () => { const handleExport = async () => {
const exportData = filteredAppointments.map((item) => ({ try {
ID: item.id, const res = await getAppointmentsApi();
Name: item.name,
Phone: item.mobileNumber,
Email: item.email,
Doctor: item.doctor?.name,
Department: item.department?.name,
Date: new Date(item.date).toLocaleDateString(),
Message: item.message,
}));
exportToExcel(exportData, "appointments"); let data = res?.data || [];
data = data.filter((item: any) => {
const matchesSearch =
item.name?.toLowerCase().includes(searchText.toLowerCase()) ||
item.mobileNumber?.includes(searchText) ||
item.email?.toLowerCase().includes(searchText.toLowerCase());
const matchesDoctor = filterDoctor
? item.doctor?.name
?.toLowerCase()
.includes(filterDoctor.toLowerCase())
: true;
const matchesDepartment = filterDepartment
? item.department?.name
?.toLowerCase()
.includes(filterDepartment.toLowerCase())
: true;
const matchesDate = filterDate
? new Date(item.date).toISOString().split("T")[0] === filterDate
: true;
return (
matchesSearch && matchesDoctor && matchesDepartment && matchesDate
);
});
const exportData = data.map((item: any) => ({
ID: item.id,
Name: item.name,
Phone: item.mobileNumber,
Email: item.email,
Doctor: item.doctor?.name,
Department: item.department?.name,
Date: new Date(item.date).toLocaleDateString(),
Message: item.message,
}));
exportToExcel(exportData, "appointments");
} catch (err) {
console.error(err);
}
}; };
return ( return (
<div className="p-6 space-y-6"> <div className="p-6 space-y-6">
<div className="flex justify-between items-center gap-3 flex-wrap"> <div className="flex justify-between items-center flex-wrap gap-3">
<h1 className="text-2xl font-bold">Appointments</h1> <h1 className="text-2xl font-bold">Appointments</h1>
<div className="flex flex-wrap gap-2"> <div className="flex flex-wrap gap-2 items-center">
<Input <Input
placeholder="Search name / phone / email..." placeholder="Search..."
value={searchText} value={searchText}
onChange={(e) => setSearchText(e.target.value)} onChange={(e) => {
className="w-[220px]" setSearchText(e.target.value);
setCurrentPage(1);
}}
className="w-[200px]"
/> />
<Input <Input
placeholder="Filter Doctor" placeholder="Doctor"
value={filterDoctor} value={filterDoctor}
onChange={(e) => setFilterDoctor(e.target.value)} onChange={(e) => setFilterDoctor(e.target.value)}
className="w-[180px]" className="w-[160px]"
/> />
<Input <Input
placeholder="Filter Department" placeholder="Department"
value={filterDepartment} value={filterDepartment}
onChange={(e) => setFilterDepartment(e.target.value)} onChange={(e) => setFilterDepartment(e.target.value)}
className="w-[200px]" className="w-[160px]"
/> />
<Input <Input
type="date" type="date"
value={filterDate} value={filterDate}
onChange={(e) => setFilterDate(e.target.value)} onChange={(e) => setFilterDate(e.target.value)}
className="w-[180px]" className="w-[160px]"
/> />
<Button variant="outline" onClick={fetchAll} disabled={loading}> <select
value={itemsPerPage}
onChange={(e) => {
setItemsPerPage(Number(e.target.value));
setCurrentPage(1);
}}
className="border px-2 py-1 rounded">
<option value={5}>5</option>
<option value={10}>10</option>
<option value={20}>20</option>
</select>
<Button onClick={fetchAll}>
<RefreshCw className="mr-2 h-4 w-4" /> <RefreshCw className="mr-2 h-4 w-4" />
Refresh
</Button> </Button>
<Button variant="outline" onClick={handleExport}> <Button onClick={handleExport}>
<Download className="mr-2 h-4 w-4" /> <Download className="mr-2 h-4 w-4" />
Export Export
</Button> </Button>
@@ -140,74 +193,77 @@ export default function AppointmentPage() {
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<div className="overflow-x-auto"> <Table>
<Table className="min-w-[700px]"> <TableHeader>
<TableHeader> <TableRow>
<TableHead>ID</TableHead>
<TableHead>Name</TableHead>
<TableHead>Phone</TableHead>
<TableHead>Doctor</TableHead>
<TableHead>Department</TableHead>
<TableHead>Date</TableHead>
<TableHead>Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{loading ? (
<TableRow> <TableRow>
<TableHead>ID</TableHead> <TableCell colSpan={7} className="text-center">
<TableHead>Name</TableHead> <Loader2 className="animate-spin mx-auto" />
<TableHead>Phone</TableHead> </TableCell>
<TableHead>Email</TableHead>
<TableHead>Doctor</TableHead>
<TableHead>Department</TableHead>
<TableHead>Appointment Date</TableHead>
<TableHead>Message</TableHead>
<TableHead>Generated on</TableHead>
<TableHead>Actions</TableHead>
</TableRow> </TableRow>
</TableHeader> ) : appointments.length === 0 ? (
<TableRow>
<TableBody> <TableCell
{loading ? ( colSpan={7}
<TableRow> className="text-center py-6 text-gray-500">
<TableCell colSpan={9} className="text-center"> No appointments found
<Loader2 className="h-6 w-6 animate-spin mx-auto" /> </TableCell>
</TableRow>
) : (
appointments.map((item) => (
<TableRow key={item.id}>
<TableCell>{item.id}</TableCell>
<TableCell>{item.name}</TableCell>
<TableCell>{item.mobileNumber}</TableCell>
<TableCell>{item.doctor?.name}</TableCell>
<TableCell>{item.department?.name}</TableCell>
<TableCell>
{new Date(item.date).toLocaleDateString()}
</TableCell>
<TableCell>
<Button
size="sm"
variant="destructive"
onClick={() => handleDelete(item.id)}>
<Trash className="h-4 w-4" />
</Button>
</TableCell> </TableCell>
</TableRow> </TableRow>
) : filteredAppointments.length === 0 ? ( ))
<TableRow> )}
<TableCell colSpan={9} className="text-center"> </TableBody>
No appointments found </Table>
</TableCell>
</TableRow>
) : (
filteredAppointments.map((item) => (
<TableRow key={item.id}>
<TableCell>{item.id}</TableCell>
<TableCell>{item.name}</TableCell>
<TableCell>{item.mobileNumber}</TableCell>
<TableCell>{item.email}</TableCell>
<TableCell>{item.doctor?.name}</TableCell>
<TableCell>{item.department?.name}</TableCell>
{/* ✅ DATE ONLY */} <div className="flex justify-between mt-4">
<TableCell> <p>
{new Date(item.date).toLocaleDateString()} Page {meta.page || 1} of {meta.totalPages || 1}
</TableCell> </p>
<TableCell className="max-w-[250px] whitespace-normal"> <div className="flex gap-2">
{item.message} <Button
</TableCell> disabled={currentPage === 1}
<TableCell> onClick={() => setCurrentPage((p) => p - 1)}>
{" "} <ChevronLeft />
{new Date(item.createdAt).toLocaleDateString()} </Button>
</TableCell>
<TableCell> <Button
<Button disabled={currentPage === meta.totalPages}
size="sm" onClick={() => setCurrentPage((p) => p + 1)}>
variant="destructive" <ChevronRight />
onClick={() => handleDelete(item.id)} </Button>
> </div>
<Trash className="h-4 w-4" />
</Button>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div> </div>
</CardContent> </CardContent>
</Card> </Card>