Compare commits

..

3 Commits

Author SHA1 Message Date
Kailasdevdas fb298cb846 fix: add JWT middleware to private API routes 2026-04-08 16:44:41 +05:30
Kailasdevdas 9c44c66b22 feat: get doctors by department 2026-04-08 16:40:42 +05:30
Kailasdevdas 29d2ed6b96 feat: get department by name 2026-04-08 16:39:29 +05:30
12 changed files with 310 additions and 397 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,98 +71,19 @@ export const createAppointment = async (req, res) => {
export const getAppointments = async (req, res) => { export const getAppointments = async (req, res) => {
try { try {
const page = parseInt(req.query.page); const appointments = await prisma.appointment.findMany({
const limit = parseInt(req.query.limit); include: {
doctor: true,
department: true,
},
orderBy: {
createdAt: "desc",
},
});
const search = req.query.search || ""; res.status(200).json({
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);
@@ -177,7 +98,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: {
@@ -213,7 +134,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: {
@@ -245,7 +166,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: {
@@ -274,7 +195,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: {
@@ -305,7 +226,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,6 +29,53 @@ 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} =
+103 -91
View File
@@ -16,38 +16,35 @@ export const getAllDoctors = async (req, res) => {
orderBy: {name: "asc"}, orderBy: {name: "asc"},
}); });
const formatted = doctors.map((doc, index) => { const formatted = doctors.map((doc, index) => ({
return { SL_NO: String(index + 1),
SL_NO: String(index + 1), doctorId: doc.doctorId,
doctorId: doc.doctorId, name: doc.name,
name: doc.name, designation: doc.designation,
designation: doc.designation, workingStatus: doc.workingStatus,
workingStatus: doc.workingStatus, qualification: doc.qualification,
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,
@@ -113,6 +110,54 @@ 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 {
@@ -184,20 +229,14 @@ export const updateDoctor = async (req, res) => {
}); });
if (!doctor) { if (!doctor) {
return res.status(404).json({ return res
success: false, .status(404)
message: "Doctor not found", .json({success: false, message: "Doctor not found"});
});
} }
await prisma.doctor.update({ await prisma.doctor.update({
where: {id: doctor.id}, where: {id: doctor.id},
data: { data: {name, designation, workingStatus, qualification},
name,
designation,
workingStatus,
qualification,
},
}); });
const oldRelations = await prisma.doctorDepartment.findMany({ const oldRelations = await prisma.doctorDepartment.findMany({
@@ -229,25 +268,24 @@ 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,
...dep.timing, ...cleanTiming,
}, },
}); });
} }
} }
res.status(200).json({ res
success: true, .status(200)
message: "Doctor updated successfully", .json({success: true, message: "Doctor updated successfully"});
});
} catch (error) { } catch (error) {
console.error(error); console.error("Update Error:", error);
res.status(500).json({ res.status(500).json({success: false, message: "Failed to update doctor"});
success: false,
message: "Failed to update doctor",
});
} }
}; };
//delete doctor //delete doctor
@@ -256,13 +294,6 @@ 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},
}); });
@@ -270,7 +301,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 with ID ${doctorId} not found`, message: "Doctor not found",
}); });
} }
@@ -294,7 +325,7 @@ export const deleteDoctor = async (req, res) => {
res.status(200).json({ res.status(200).json({
success: true, success: true,
message: `Doctor ${doctorId} deleted successfully`, message: "Doctor deleted successfully",
}); });
} catch (error) { } catch (error) {
console.error(error); console.error(error);
@@ -320,23 +351,19 @@ export const getDoctorTimings = async (req, res) => {
}); });
const result = doctors.map((doc) => { const result = doctors.map((doc) => {
let timing = {}; const timing = doc.departments[0]?.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 || "",
}; };
}); });
@@ -380,26 +407,11 @@ 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) => ({
departments: doctor.departments.map((d) => { departmentId: d.department.departmentId,
const t = d.timing || {}; departmentName: d.department.name,
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", getAcademicsResearch); router.get("/getAll", jwtAuthMiddleware, getAcademicsResearch);
router.get("/:id", getSingleAcademicsResearch); router.get("/:id", jwtAuthMiddleware, 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", getAppointments); router.get("/getall", jwtAuthMiddleware, getAppointments);
router.post("/", createAppointment); router.post("/", createAppointment);
router.get("/:id", getAppointment); router.get("/:id", jwtAuthMiddleware, getAppointment);
router.patch("/:id", updateAppointment); router.patch("/:id", jwtAuthMiddleware, 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("/", createCareer); router.post("/", jwtAuthMiddleware, createCareer);
router.patch("/:id", updateCareer); router.patch("/:id", jwtAuthMiddleware, updateCareer);
router.delete("/:id", deleteCareer); router.delete("/:id", jwtAuthMiddleware, deleteCareer);
export default router; export default router;
+2
View File
@@ -1,6 +1,7 @@
import express from "express"; import express from "express";
import { import {
getAllDepartments, getAllDepartments,
getDepartmentByName,
createDepartment, createDepartment,
updateDepartment, updateDepartment,
deleteDepartment, deleteDepartment,
@@ -11,6 +12,7 @@ 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);
+3 -1
View File
@@ -7,6 +7,7 @@ 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";
@@ -14,9 +15,10 @@ import jwtAuthMiddleware from "../middleware/auth.js";
const router = express.Router(); const router = express.Router();
router.get("/getAll", getAllDoctors); router.get("/getAll", getAllDoctors);
router.get("/:doctorId", getDoctorByDoctorId); router.get("/search", getDoctorsByDepartmentId);
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", getInquiries); router.get("/getAll", jwtAuthMiddleware, getInquiries);
router.get("/:id", getInquiry); router.get("/:id", jwtAuthMiddleware, getInquiry);
router.delete("/:id", jwtAuthMiddleware, deleteInquiry); router.delete("/:id", jwtAuthMiddleware, deleteInquiry);
export default router; export default router;
+2 -17
View File
@@ -1,22 +1,7 @@
import apiClient from "@/api/client"; import apiClient from "@/api/client";
export const getAppointmentsApi = async ( export const getAppointmentsApi = async () => {
page?: number, const res = await apiClient.get("/appointments/getall");
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;
}; };
+119 -175
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,18 +12,12 @@ 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 { import {Button} from "@/components/ui/button";
Loader2, import {Input} from "@/components/ui/input";
Trash,
RefreshCw, import {Loader2, Trash, RefreshCw, Download} from "lucide-react";
Download,
ChevronLeft,
ChevronRight,
} from "lucide-react";
export default function AppointmentPage() { export default function AppointmentPage() {
const [appointments, setAppointments] = useState<any[]>([]); const [appointments, setAppointments] = useState<any[]>([]);
@@ -34,153 +28,106 @@ 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 = async () => { const handleExport = () => {
try { const exportData = filteredAppointments.map((item) => ({
const res = await getAppointmentsApi(); 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,
}));
let data = res?.data || []; exportToExcel(exportData, "appointments");
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 flex-wrap gap-3"> <div className="flex justify-between items-center gap-3 flex-wrap">
<h1 className="text-2xl font-bold">Appointments</h1> <h1 className="text-2xl font-bold">Appointments</h1>
<div className="flex flex-wrap gap-2 items-center"> <div className="flex flex-wrap gap-2">
<Input <Input
placeholder="Search..." placeholder="Search name / phone / email..."
value={searchText} value={searchText}
onChange={(e) => { onChange={(e) => setSearchText(e.target.value)}
setSearchText(e.target.value); className="w-[220px]"
setCurrentPage(1);
}}
className="w-[200px]"
/> />
<Input <Input
placeholder="Doctor" placeholder="Filter Doctor"
value={filterDoctor} value={filterDoctor}
onChange={(e) => setFilterDoctor(e.target.value)} onChange={(e) => setFilterDoctor(e.target.value)}
className="w-[160px]" className="w-[180px]"
/> />
<Input <Input
placeholder="Department" placeholder="Filter Department"
value={filterDepartment} value={filterDepartment}
onChange={(e) => setFilterDepartment(e.target.value)} onChange={(e) => setFilterDepartment(e.target.value)}
className="w-[160px]" className="w-[200px]"
/> />
<Input <Input
type="date" type="date"
value={filterDate} value={filterDate}
onChange={(e) => setFilterDate(e.target.value)} onChange={(e) => setFilterDate(e.target.value)}
className="w-[160px]" className="w-[180px]"
/> />
<select <Button variant="outline" onClick={fetchAll} disabled={loading}>
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 onClick={handleExport}> <Button variant="outline" onClick={handleExport}>
<Download className="mr-2 h-4 w-4" /> <Download className="mr-2 h-4 w-4" />
Export Export
</Button> </Button>
@@ -193,77 +140,74 @@ export default function AppointmentPage() {
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<Table> <div className="overflow-x-auto">
<TableHeader> <Table className="min-w-[700px]">
<TableRow> <TableHeader>
<TableHead>ID</TableHead> <TableRow>
<TableHead>Name</TableHead> <TableHead>ID</TableHead>
<TableHead>Phone</TableHead> <TableHead>Name</TableHead>
<TableHead>Doctor</TableHead> <TableHead>Phone</TableHead>
<TableHead>Department</TableHead> <TableHead>Email</TableHead>
<TableHead>Date</TableHead> <TableHead>Doctor</TableHead>
<TableHead>Actions</TableHead> <TableHead>Department</TableHead>
</TableRow> <TableHead>Appointment Date</TableHead>
</TableHeader> <TableHead>Message</TableHead>
<TableHead>Generated on</TableHead>
<TableBody> <TableHead>Actions</TableHead>
{loading ? (
<TableRow>
<TableCell colSpan={7} className="text-center">
<Loader2 className="animate-spin mx-auto" />
</TableCell>
</TableRow> </TableRow>
) : appointments.length === 0 ? ( </TableHeader>
<TableRow>
<TableCell <TableBody>
colSpan={7} {loading ? (
className="text-center py-6 text-gray-500"> <TableRow>
No appointments found <TableCell colSpan={9} className="text-center">
</TableCell> <Loader2 className="h-6 w-6 animate-spin mx-auto" />
</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>
</TableBody> <TableCell colSpan={9} className="text-center">
</Table> No appointments found
</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>
<div className="flex justify-between mt-4"> {/* ✅ DATE ONLY */}
<p> <TableCell>
Page {meta.page || 1} of {meta.totalPages || 1} {new Date(item.date).toLocaleDateString()}
</p> </TableCell>
<div className="flex gap-2"> <TableCell className="max-w-[250px] whitespace-normal">
<Button {item.message}
disabled={currentPage === 1} </TableCell>
onClick={() => setCurrentPage((p) => p - 1)}> <TableCell>
<ChevronLeft /> {" "}
</Button> {new Date(item.createdAt).toLocaleDateString()}
</TableCell>
<Button <TableCell>
disabled={currentPage === meta.totalPages} <Button
onClick={() => setCurrentPage((p) => p + 1)}> size="sm"
<ChevronRight /> variant="destructive"
</Button> onClick={() => handleDelete(item.id)}
</div> >
<Trash className="h-4 w-4" />
</Button>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div> </div>
</CardContent> </CardContent>
</Card> </Card>