Compare commits

...

2 Commits

Author SHA1 Message Date
ARJUN S THAMPI c6a041ac10 feat: add pagination in appointment 2026-03-27 12:09:46 +05:30
arjunsthampi 661bf7a77f Merge pull request 'fix-department-ui' (#5) from fix-department-ui into dev
Reviewed-on: #5
2026-03-26 12:33:03 +00:00
3 changed files with 289 additions and 139 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 page = parseInt(req.query.page);
const limit = parseInt(req.query.limit);
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({ const appointments = await prisma.appointment.findMany({
include: { include: {
doctor: true, doctor: true,
department: true, department: true,
}, },
orderBy: { orderBy: { createdAt: "desc" },
createdAt: "desc",
},
}); });
res.status(200).json({ return res.status(200).json({
success: true, success: true,
data: appointments, 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,
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: {
+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;
}; };
+116 -60
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,30 +34,65 @@ 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) => { async function handleDelete(id: number) {
if (!confirm("Delete appointment?")) return;
await deleteAppointmentApi(id);
fetchAll();
}
const handleExport = async () => {
try {
const res = await getAppointmentsApi();
let data = res?.data || [];
data = data.filter((item: any) => {
const matchesSearch = const matchesSearch =
item.name?.toLowerCase().includes(searchText.toLowerCase()) || item.name?.toLowerCase().includes(searchText.toLowerCase()) ||
item.mobileNumber?.includes(searchText) || item.mobileNumber?.includes(searchText) ||
item.email?.toLowerCase().includes(searchText.toLowerCase()); item.email?.toLowerCase().includes(searchText.toLowerCase());
const matchesDoctor = filterDoctor const matchesDoctor = filterDoctor
? item.doctor?.name?.toLowerCase().includes(filterDoctor.toLowerCase()) ? item.doctor?.name
?.toLowerCase()
.includes(filterDoctor.toLowerCase())
: true; : true;
const matchesDepartment = filterDepartment const matchesDepartment = filterDepartment
@@ -64,17 +105,12 @@ export default function AppointmentPage() {
? new Date(item.date).toISOString().split("T")[0] === filterDate ? new Date(item.date).toISOString().split("T")[0] === filterDate
: true; : true;
return matchesSearch && matchesDoctor && matchesDepartment && matchesDate; return (
matchesSearch && matchesDoctor && matchesDepartment && matchesDate
);
}); });
async function handleDelete(id: number) { const exportData = data.map((item: any) => ({
if (!confirm("Delete appointment?")) return;
await deleteAppointmentApi(id);
fetchAll();
}
const handleExport = () => {
const exportData = filteredAppointments.map((item) => ({
ID: item.id, ID: item.id,
Name: item.name, Name: item.name,
Phone: item.mobileNumber, Phone: item.mobileNumber,
@@ -86,48 +122,65 @@ export default function AppointmentPage() {
})); }));
exportToExcel(exportData, "appointments"); 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,20 +193,15 @@ export default function AppointmentPage() {
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<div className="overflow-x-auto"> <Table>
<Table className="min-w-[700px]">
<TableHeader> <TableHeader>
<TableRow> <TableRow>
<TableHead>ID</TableHead> <TableHead>ID</TableHead>
<TableHead>Name</TableHead> <TableHead>Name</TableHead>
<TableHead>Phone</TableHead> <TableHead>Phone</TableHead>
<TableHead>Email</TableHead>
<TableHead>Doctor</TableHead> <TableHead>Doctor</TableHead>
<TableHead>Department</TableHead> <TableHead>Department</TableHead>
<TableHead>Appointment Date</TableHead> <TableHead>Date</TableHead>
<TableHead>Message</TableHead>
<TableHead>Generated on</TableHead>
<TableHead>Actions</TableHead> <TableHead>Actions</TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>
@@ -161,45 +209,34 @@ export default function AppointmentPage() {
<TableBody> <TableBody>
{loading ? ( {loading ? (
<TableRow> <TableRow>
<TableCell colSpan={9} className="text-center"> <TableCell colSpan={7} className="text-center">
<Loader2 className="h-6 w-6 animate-spin mx-auto" /> <Loader2 className="animate-spin mx-auto" />
</TableCell> </TableCell>
</TableRow> </TableRow>
) : filteredAppointments.length === 0 ? ( ) : appointments.length === 0 ? (
<TableRow> <TableRow>
<TableCell colSpan={9} className="text-center"> <TableCell
colSpan={7}
className="text-center py-6 text-gray-500">
No appointments found No appointments found
</TableCell> </TableCell>
</TableRow> </TableRow>
) : ( ) : (
filteredAppointments.map((item) => ( appointments.map((item) => (
<TableRow key={item.id}> <TableRow key={item.id}>
<TableCell>{item.id}</TableCell> <TableCell>{item.id}</TableCell>
<TableCell>{item.name}</TableCell> <TableCell>{item.name}</TableCell>
<TableCell>{item.mobileNumber}</TableCell> <TableCell>{item.mobileNumber}</TableCell>
<TableCell>{item.email}</TableCell>
<TableCell>{item.doctor?.name}</TableCell> <TableCell>{item.doctor?.name}</TableCell>
<TableCell>{item.department?.name}</TableCell> <TableCell>{item.department?.name}</TableCell>
{/* ✅ DATE ONLY */}
<TableCell> <TableCell>
{new Date(item.date).toLocaleDateString()} {new Date(item.date).toLocaleDateString()}
</TableCell> </TableCell>
<TableCell className="max-w-[250px] whitespace-normal">
{item.message}
</TableCell>
<TableCell>
{" "}
{new Date(item.createdAt).toLocaleDateString()}
</TableCell>
<TableCell> <TableCell>
<Button <Button
size="sm" size="sm"
variant="destructive" variant="destructive"
onClick={() => handleDelete(item.id)} onClick={() => handleDelete(item.id)}>
>
<Trash className="h-4 w-4" /> <Trash className="h-4 w-4" />
</Button> </Button>
</TableCell> </TableCell>
@@ -208,6 +245,25 @@ export default function AppointmentPage() {
)} )}
</TableBody> </TableBody>
</Table> </Table>
<div className="flex justify-between mt-4">
<p>
Page {meta.page || 1} of {meta.totalPages || 1}
</p>
<div className="flex gap-2">
<Button
disabled={currentPage === 1}
onClick={() => setCurrentPage((p) => p - 1)}>
<ChevronLeft />
</Button>
<Button
disabled={currentPage === meta.totalPages}
onClick={() => setCurrentPage((p) => p + 1)}>
<ChevronRight />
</Button>
</div>
</div> </div>
</CardContent> </CardContent>
</Card> </Card>