Compare commits

..

13 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
ARJUN S THAMPI 7bce00800b chore : remove comment 2026-03-26 18:01:57 +05:30
ARJUN S THAMPI 427775a038 fix: refresh button ui 2026-03-26 17:58:49 +05:30
ARJUN S THAMPI 8004a7a21c fix: ui department 2026-03-26 14:38:23 +05:30
arjunsthampi 57f95661cc Merge pull request 'feat/news-&-media' (#4) from feat/news-&-media into dev
Reviewed-on: #4
2026-03-26 06:08:25 +00:00
ARJUN S THAMPI 9d149e6abe feat: pagination in newMedia 2026-03-26 11:30:26 +05:30
ARJUN S THAMPI 2ed1bee149 feat: add page newMedia 2026-03-26 11:20:03 +05:30
ARJUN S THAMPI 24a8bc4113 feat: add news media api 2026-03-25 17:59:36 +05:30
arjunsthampi f35eab14e6 Merge pull request 'feat/inquiry' (#3) from feat/inquiry into dev
Reviewed-on: #3
2026-03-25 09:16:55 +00:00
ARJUN S THAMPI 380cb4d999 feat : add page academics & research 2026-03-25 12:48:01 +05:30
ARJUN S THAMPI e546519e7a feat: add inquiry page 2026-03-25 11:26:45 +05:30
arjunsthampi b9f372145b Merge pull request 'feat/appointment-page' (#2) from feat/appointment-page into dev
Reviewed-on: #2
2026-03-25 04:43:15 +00:00
19 changed files with 1517 additions and 239 deletions
@@ -0,0 +1,15 @@
-- CreateTable
CREATE TABLE "NewsMedia" (
"id" SERIAL NOT NULL,
"headline" TEXT NOT NULL,
"content" TEXT,
"firstPara" TEXT,
"secondPara" TEXT,
"author" TEXT,
"date" TIMESTAMP(3),
"isActive" BOOLEAN NOT NULL DEFAULT true,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "NewsMedia_pkey" PRIMARY KEY ("id")
);
+16
View File
@@ -185,4 +185,20 @@ model EmailConfig {
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
}
model NewsMedia {
id Int @id @default(autoincrement())
headline String
content String?
firstPara String?
secondPara String?
author String?
date DateTime?
isActive Boolean @default(true)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
} }
+2
View File
@@ -13,6 +13,7 @@ import appointmentRoutes from "./routes/appointment.routes.js";
import inquiryRoutes from "./routes/inquiry.routes.js"; import inquiryRoutes from "./routes/inquiry.routes.js";
import academicsResearchRoutes from "./routes/academicsResearch.routes.js"; import academicsResearchRoutes from "./routes/academicsResearch.routes.js";
import emailConfigRoutes from "./routes/emailConfig.routes.js"; import emailConfigRoutes from "./routes/emailConfig.routes.js";
import newsMediaRoutes from "./routes/newsMedia.routes.js";
dotenv.config(); dotenv.config();
@@ -49,6 +50,7 @@ app.use("/api/appointments", appointmentRoutes);
app.use("/api/inquiry", inquiryRoutes); app.use("/api/inquiry", inquiryRoutes);
app.use("/api/academics", academicsResearchRoutes); app.use("/api/academics", academicsResearchRoutes);
app.use("/api/email", emailConfigRoutes); app.use("/api/email", emailConfigRoutes);
app.use("/api/newsMedia", newsMediaRoutes);
const PORT = process.env.PORT || 3000; const PORT = process.env.PORT || 3000;
app.listen(PORT, () => { app.listen(PORT, () => {
@@ -1,10 +1,13 @@
import prisma from "../prisma/client.js"; import prisma from "../prisma/client.js";
import { sendEmail } from "../utils/sendEmail.js";
import { getEmailsByType } from "../utils/getEmailByTypes.js";
// CREATE ACADEMICS & RESEARCH // CREATE ACADEMICS & RESEARCH
export const createAcademicsResearch = async (req, res) => { export const createAcademicsResearch = async (req, res) => {
try { try {
const {fullName, number, emailId, subject, courseName, message} = req.body; const { fullName, number, emailId, subject, courseName, message } =
req.body;
if (!fullName || !number) { if (!fullName || !number) {
return res.status(400).json({ return res.status(400).json({
@@ -24,6 +27,32 @@ export const createAcademicsResearch = async (req, res) => {
}, },
}); });
try {
const emailList = await getEmailsByType("ACADEMICS");
if (emailList && emailList.length > 0) {
await sendEmail({
to: emailList,
subject: "New Academics & Research Inquiry",
html: `
<h2>New Academics & Research Inquiry</h2>
<p><b>Name:</b> ${fullName}</p>
<p><b>Phone:</b> ${number}</p>
<p><b>Email:</b> ${emailId || "-"}</p>
<p><b>Course:</b> ${courseName || "-"}</p>
<p><b>Subject:</b> ${subject || "-"}</p>
<p><b>Message:</b></p>
<p>${message || "-"}</p>
`,
});
}
} catch (err) {
console.error("Academics email failed:", err);
}
res.status(200).json({ res.status(200).json({
success: true, success: true,
status: 200, status: 200,
@@ -65,7 +94,7 @@ export const getAcademicsResearch = async (req, res) => {
export const getSingleAcademicsResearch = async (req, res) => { export const getSingleAcademicsResearch = async (req, res) => {
try { try {
const {id} = req.params; const { id } = req.params;
const data = await prisma.academicsResearch.findUnique({ const data = await prisma.academicsResearch.findUnique({
where: { where: {
@@ -96,7 +125,7 @@ export const getSingleAcademicsResearch = async (req, res) => {
export const deleteAcademicsResearch = async (req, res) => { export const deleteAcademicsResearch = async (req, res) => {
try { try {
const {id} = req.params; const { id } = req.params;
await prisma.academicsResearch.delete({ await prisma.academicsResearch.delete({
where: { where: {
@@ -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: {
@@ -0,0 +1,202 @@
import prisma from "../prisma/client.js";
// GET ALL NEWS
export const getAllNews = async (req, res) => {
try {
const page = parseInt(req.query.page);
const limit = parseInt(req.query.limit);
if (!page && !limit) {
const news = await prisma.newsMedia.findMany({
orderBy: { createdAt: "desc" },
});
const response = news.map((n) => ({
Id: n.id.toString(),
Headline: n.headline,
Content: n.content,
FirstPara: n.firstPara,
SecondPara: n.secondPara,
Date: n.date,
Author: n.author,
}));
return res.status(200).json({
success: true,
data: response,
meta: null,
});
}
const currentPage = page || 1;
const currentLimit = limit || 10;
const skip = (currentPage - 1) * currentLimit;
const [news, total] = await Promise.all([
prisma.newsMedia.findMany({
orderBy: { createdAt: "desc" },
skip,
take: currentLimit,
}),
prisma.newsMedia.count(),
]);
const response = news.map((n) => ({
Id: n.id.toString(),
Headline: n.headline,
Content: n.content,
FirstPara: n.firstPara,
SecondPara: n.secondPara,
Date: n.date,
Author: n.author,
}));
return res.status(200).json({
success: true,
data: response,
meta: {
total,
page: currentPage,
limit: currentLimit,
totalPages: Math.ceil(total / currentLimit),
},
});
} catch (error) {
console.error(error);
return res.status(500).json({
success: false,
message: "Failed to fetch news",
});
}
};
// GET NEWS BY ID
export const getNewsById = async (req, res) => {
try {
const { id } = req.params;
const n = await prisma.newsMedia.findUnique({
where: { id: Number(id) },
});
if (!n) {
return res.status(404).json({
success: false,
message: "News not found",
});
}
const response = {
Id: n.id.toString(),
Headline: n.headline,
Content: n.content,
FirstPara: n.firstPara,
SecondPara: n.secondPara,
Date: n.date,
Author: n.author,
};
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 news",
});
}
};
// CREATE NEWS
export const createNews = async (req, res) => {
try {
const { headline, content, firstPara, secondPara, date, author } = req.body;
if (!headline) {
return res.status(400).json({
success: false,
message: "Headline is required",
});
}
const news = await prisma.newsMedia.create({
data: {
headline,
content,
firstPara,
secondPara,
date: date ? new Date(date) : null,
author,
},
});
return res.status(201).json({
success: true,
message: "News created successfully",
data: news,
});
} catch (error) {
console.error(error);
return res.status(500).json({
success: false,
message: "Failed to create news",
});
}
};
// UPDATE NEWS
export const updateNews = async (req, res) => {
try {
const { id } = req.params;
const news = await prisma.newsMedia.update({
where: { id: Number(id) },
data: {
...req.body,
date: req.body.date ? new Date(req.body.date) : undefined,
},
});
return res.status(200).json({
success: true,
message: "News updated successfully",
data: news,
});
} catch (error) {
console.error(error);
return res.status(500).json({
success: false,
message: "Failed to update news",
});
}
};
// DELETE NEWS
export const deleteNews = async (req, res) => {
try {
const { id } = req.params;
await prisma.newsMedia.delete({
where: { id: Number(id) },
});
return res.status(200).json({
success: true,
message: "News deleted successfully",
});
} catch (error) {
console.error(error);
return res.status(500).json({
success: false,
message: "Failed to delete news",
});
}
};
+23
View File
@@ -0,0 +1,23 @@
import express from "express";
import {
createNews,
getAllNews,
getNewsById,
updateNews,
deleteNews,
} from "../controllers/newsMedia.controller.js";
import jwtAuthMiddleware from "../middleware/auth.js";
const router = express.Router();
// PUBLIC ROUTES
router.get("/getAll", getAllNews);
router.get("/:id", getNewsById);
// PROTECTED ROUTES
router.post("/", jwtAuthMiddleware, createNews);
router.patch("/:id", jwtAuthMiddleware, updateNews);
router.delete("/:id", jwtAuthMiddleware, deleteNews);
export default router;
+6
View File
@@ -17,6 +17,9 @@ import Appointment from "./pages/Appointment";
import EmailPage from "./pages/email"; import EmailPage from "./pages/email";
import CareerPage from "./pages/Career"; import CareerPage from "./pages/Career";
import CandidatePage from "./pages/candidates"; import CandidatePage from "./pages/candidates";
import InquiryPage from "./pages/inquiry";
import AcademicsPage from "./pages/Academics";
import NewsPage from "./pages/newsMedia";
export default function App() { export default function App() {
return ( return (
@@ -38,6 +41,9 @@ export default function App() {
<Route path="/email" element={<EmailPage />} /> <Route path="/email" element={<EmailPage />} />
<Route path="/career" element={<CareerPage />} /> <Route path="/career" element={<CareerPage />} />
<Route path="/candidate" element={<CandidatePage />} /> <Route path="/candidate" element={<CandidatePage />} />
<Route path="/inquiry" element={<InquiryPage />} />
<Route path="/academics" element={<AcademicsPage />} />
<Route path="/news" element={<NewsPage />} />
</Route> </Route>
</Route> </Route>
+11
View File
@@ -0,0 +1,11 @@
import apiClient from "@/api/client";
export const getAcademicsApi = async () => {
const res = await apiClient.get("/academics/getAll");
return res.data;
};
export const deleteAcademicsApi = async (id: number) => {
const res = await apiClient.delete(`/academics/${id}`);
return res.data;
};
+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;
}; };
+11
View File
@@ -0,0 +1,11 @@
import apiClient from "@/api/client";
export const getInquiriesApi = async () => {
const res = await apiClient.get("/inquiry/getAll");
return res.data;
};
export const deleteInquiryApi = async (id: number) => {
const res = await apiClient.delete(`/inquiry/${id}`);
return res.data;
};
+23
View File
@@ -0,0 +1,23 @@
import apiClient from "@/api/client";
export const getNewsApi = async (page = 1, limit = 10) => {
const res = await apiClient.get(
`/newsMedia/getAll?page=${page}&limit=${limit}`,
);
return res.data;
};
export const createNewsApi = async (data: any) => {
const res = await apiClient.post("/newsMedia", data);
return res.data;
};
export const updateNewsApi = async (id: number, data: any) => {
const res = await apiClient.patch(`/newsMedia/${id}`, data);
return res.data;
};
export const deleteNewsApi = async (id: number) => {
const res = await apiClient.delete(`/newsMedia/${id}`);
return res.data;
};
@@ -27,6 +27,18 @@ export default function Sidebar() {
name: "Candidates", name: "Candidates",
path: "/candidate", path: "/candidate",
}, },
{
name: "Inquiry",
path: "/inquiry",
},
{
name: "Academics & Research",
path: "/academics",
},
{
name: "News & Media",
path: "/news",
},
{ {
name: "Email", name: "Email",
path: "/email", path: "/email",
+172
View File
@@ -0,0 +1,172 @@
import { useState, useEffect, useCallback } from "react";
import { getAcademicsApi, deleteAcademicsApi } from "@/api/academics";
import { exportToExcel } from "@/utils/exportToExcel";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Loader2, Trash, RefreshCw, Download } from "lucide-react";
export default function AcademicsPage() {
const [records, setRecords] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const [searchText, setSearchText] = useState("");
const fetchAll = useCallback(async () => {
setLoading(true);
try {
const res = await getAcademicsApi();
setRecords(res?.data || []);
} catch (err) {
console.error(err);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchAll();
}, [fetchAll]);
const filteredRecords = records.filter((item) => {
return (
item.fullName?.toLowerCase().includes(searchText.toLowerCase()) ||
item.number?.includes(searchText) ||
item.emailId?.toLowerCase().includes(searchText.toLowerCase()) ||
item.subject?.toLowerCase().includes(searchText.toLowerCase()) ||
item.courseName?.toLowerCase().includes(searchText.toLowerCase())
);
});
async function handleDelete(id: number) {
if (!confirm("Delete record?")) return;
await deleteAcademicsApi(id);
fetchAll();
}
const handleExport = () => {
const exportData = filteredRecords.map((item) => ({
ID: item.id,
Name: item.fullName,
Phone: item.number,
Email: item.emailId,
Course: item.courseName,
Subject: item.subject,
Message: item.message,
Date: new Date(item.createdAt).toLocaleDateString(),
}));
exportToExcel(exportData, "academics");
};
return (
<div className="p-6 space-y-6">
<div className="flex justify-between items-center gap-3 flex-wrap">
<h1 className="text-2xl font-bold">Academics & Research</h1>
<div className="flex flex-wrap gap-2">
<Input
placeholder="Search name / phone / email / subject..."
value={searchText}
onChange={(e) => setSearchText(e.target.value)}
className="w-[260px]"
/>
<Button variant="outline" onClick={fetchAll} disabled={loading}>
<RefreshCw className="mr-2 h-4 w-4" />
Refresh
</Button>
<Button variant="outline" onClick={handleExport}>
<Download className="mr-2 h-4 w-4" />
Export
</Button>
</div>
</div>
<Card>
<CardHeader>
<CardTitle>Academics Records</CardTitle>
</CardHeader>
<CardContent>
<div className="overflow-x-auto">
<Table className="min-w-[1000px]">
<TableHeader>
<TableRow>
<TableHead>ID</TableHead>
<TableHead>Name</TableHead>
<TableHead>Phone</TableHead>
<TableHead>Email</TableHead>
<TableHead>Course</TableHead>
<TableHead>Subject</TableHead>
<TableHead>Message</TableHead>
<TableHead>Date</TableHead>
<TableHead>Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{loading ? (
<TableRow>
<TableCell colSpan={9} className="text-center">
<Loader2 className="h-6 w-6 animate-spin mx-auto" />
</TableCell>
</TableRow>
) : filteredRecords.length === 0 ? (
<TableRow>
<TableCell colSpan={9} className="text-center">
No records found
</TableCell>
</TableRow>
) : (
filteredRecords.map((item) => (
<TableRow key={item.id}>
<TableCell>{item.id}</TableCell>
<TableCell>{item.fullName}</TableCell>
<TableCell>{item.number}</TableCell>
<TableCell>{item.emailId}</TableCell>
<TableCell>{item.courseName}</TableCell>
<TableCell>{item.subject}</TableCell>
<TableCell className="max-w-[250px] whitespace-normal">
{item.message}
</TableCell>
<TableCell>
{new Date(item.createdAt).toLocaleDateString()}
</TableCell>
<TableCell>
<Button
size="sm"
variant="destructive"
onClick={() => handleDelete(item.id)}>
<Trash className="h-4 w-4" />
</Button>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div>
</CardContent>
</Card>
</div>
);
}
+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>
+125 -82
View File
@@ -1,5 +1,5 @@
import {useState, useEffect, useCallback} from "react"; import { useState, useEffect, useCallback } from "react";
import {AxiosError} from "axios"; import { AxiosError } from "axios";
import { import {
getDepartmentsApi, getDepartmentsApi,
@@ -17,8 +17,8 @@ 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 { Button } from "@/components/ui/button";
import { import {
Dialog, Dialog,
@@ -28,10 +28,10 @@ import {
DialogFooter, DialogFooter,
} from "@/components/ui/dialog"; } from "@/components/ui/dialog";
import {Input} from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import {Textarea} from "@/components/ui/textarea"; import { Textarea } from "@/components/ui/textarea";
import {Loader2, RefreshCw, Plus, Pencil, Trash} from "lucide-react"; import { Loader2, RefreshCw, Plus, Pencil, Trash, Eye } from "lucide-react";
interface Department { interface Department {
departmentId: string; departmentId: string;
@@ -51,6 +51,9 @@ export default function DepartmentPage() {
const [openModal, setOpenModal] = useState(false); const [openModal, setOpenModal] = useState(false);
const [editing, setEditing] = useState<Department | null>(null); const [editing, setEditing] = useState<Department | null>(null);
const [viewOpen, setViewOpen] = useState(false);
const [viewData, setViewData] = useState<Department | null>(null);
const [searchText, setSearchText] = useState(""); const [searchText, setSearchText] = useState("");
const [form, setForm] = useState<Department>({ const [form, setForm] = useState<Department>({
@@ -85,32 +88,21 @@ export default function DepartmentPage() {
fetchDepartments(); fetchDepartments();
}, [fetchDepartments]); }, [fetchDepartments]);
const filteredDepartments = departments.filter((dep) => { const filteredDepartments = departments.filter((dep) =>
const text = searchText.toLowerCase(); dep.name.toLowerCase().includes(searchText.toLowerCase()),
);
return ( function handleChange(e: any) {
dep.name.toLowerCase().includes(text) || setForm({ ...form, [e.target.name]: e.target.value });
dep.departmentId.toLowerCase().includes(text) || }
dep.para1.toLowerCase().includes(text) ||
dep.para2.toLowerCase().includes(text) ||
dep.para3.toLowerCase().includes(text) ||
dep.facilities.toLowerCase().includes(text) ||
dep.services.toLowerCase().includes(text)
);
});
function handleChange( function truncate(text: string, limit = 60) {
e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>, if (!text) return "-";
) { return text.length > limit ? text.substring(0, limit) + "..." : text;
setForm({
...form,
[e.target.name]: e.target.value,
});
} }
function openAdd() { function openAdd() {
setEditing(null); setEditing(null);
setForm({ setForm({
departmentId: "", departmentId: "",
name: "", name: "",
@@ -120,7 +112,6 @@ export default function DepartmentPage() {
facilities: "", facilities: "",
services: "", services: "",
}); });
setOpenModal(true); setOpenModal(true);
} }
@@ -130,10 +121,15 @@ export default function DepartmentPage() {
setOpenModal(true); setOpenModal(true);
} }
function openView(dep: Department) {
setViewData(dep);
setViewOpen(true);
}
async function handleSubmit() { async function handleSubmit() {
try { try {
if (editing) { if (editing) {
const {departmentId, ...updateData} = form; const { departmentId, ...updateData } = form;
await updateDepartmentApi(editing.departmentId, updateData); await updateDepartmentApi(editing.departmentId, updateData);
} else { } else {
await createDepartmentApi(form); await createDepartmentApi(form);
@@ -146,12 +142,11 @@ export default function DepartmentPage() {
} }
} }
async function handleDelete(departmentId: string) { async function handleDelete(id: string) {
const confirmDelete = confirm("Delete this department?"); if (!confirm("Delete this department?")) return;
if (!confirmDelete) return;
try { try {
await deleteDepartmentApi(departmentId); await deleteDepartmentApi(id);
fetchDepartments(); fetchDepartments();
} catch (error) { } catch (error) {
console.error(error); console.error(error);
@@ -160,7 +155,6 @@ export default function DepartmentPage() {
return ( return (
<div className="p-6 space-y-6"> <div className="p-6 space-y-6">
{/* HEADER */}
<div className="flex flex-col md:flex-row md:justify-between md:items-center gap-3"> <div className="flex flex-col md:flex-row md:justify-between md:items-center gap-3">
<h1 className="text-2xl font-bold">Departments</h1> <h1 className="text-2xl font-bold">Departments</h1>
@@ -175,8 +169,7 @@ export default function DepartmentPage() {
<Button <Button
variant="outline" variant="outline"
onClick={fetchDepartments} onClick={fetchDepartments}
disabled={loading} disabled={loading}>
>
<RefreshCw className="mr-2 h-4 w-4" /> <RefreshCw className="mr-2 h-4 w-4" />
Refresh Refresh
</Button> </Button>
@@ -200,31 +193,29 @@ export default function DepartmentPage() {
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<div className="border rounded-md overflow-x-auto max-w-full"> <div className="border rounded-md max-h-[500px] overflow-y-auto">
<Table> <Table className="w-full table-fixed">
<TableHeader> <TableHeader>
<TableRow> <TableRow>
<TableHead>ID</TableHead> <TableHead className="w-[80px]">ID</TableHead>
<TableHead>Name</TableHead> <TableHead className="w-[180px]">Name</TableHead>
<TableHead>Para1</TableHead> <TableHead className="w-[250px]">Para1</TableHead>
<TableHead>Para2</TableHead> <TableHead className="w-[220px]">Facilities</TableHead>
<TableHead>Para3</TableHead> <TableHead className="w-[220px]">Services</TableHead>
<TableHead>Facilities</TableHead> <TableHead className="w-[120px]">Actions</TableHead>
<TableHead>Services</TableHead>
<TableHead>Actions</TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody> <TableBody>
{loading ? ( {loading ? (
<TableRow> <TableRow>
<TableCell colSpan={8} className="text-center"> <TableCell colSpan={6} className="text-center">
<Loader2 className="h-6 w-6 animate-spin mx-auto" /> <Loader2 className="h-6 w-6 animate-spin mx-auto" />
</TableCell> </TableCell>
</TableRow> </TableRow>
) : filteredDepartments.length === 0 ? ( ) : filteredDepartments.length === 0 ? (
<TableRow> <TableRow>
<TableCell colSpan={8} className="text-center"> <TableCell colSpan={6} className="text-center">
No departments found No departments found
</TableCell> </TableCell>
</TableRow> </TableRow>
@@ -233,42 +224,47 @@ export default function DepartmentPage() {
<TableRow key={dep.departmentId}> <TableRow key={dep.departmentId}>
<TableCell>{dep.departmentId}</TableCell> <TableCell>{dep.departmentId}</TableCell>
<TableCell>{dep.name}</TableCell> <TableCell>
<div className="break-words">{dep.name}</div>
<TableCell className="max-w-[300px] whitespace-normal break-words">
{dep.para1}
</TableCell> </TableCell>
<TableCell className="max-w-[300px] whitespace-normal break-words"> <TableCell>
{dep.para2} <div className="break-words whitespace-normal">
{truncate(dep.para1)}
</div>
</TableCell> </TableCell>
<TableCell className="max-w-[300px] whitespace-normal break-words"> <TableCell>
{dep.para3} <div className="break-words whitespace-normal">
{truncate(dep.facilities)}
</div>
</TableCell> </TableCell>
<TableCell className="max-w-[300px] whitespace-normal break-words"> <TableCell>
{dep.facilities} <div className="break-words whitespace-normal">
{truncate(dep.services)}
</div>
</TableCell> </TableCell>
<TableCell className="max-w-[300px] whitespace-normal break-words"> <TableCell className="flex gap-2 whitespace-nowrap">
{dep.services}
</TableCell>
<TableCell className="flex gap-2">
<Button <Button
size="sm" size="sm"
variant="outline" variant="outline"
onClick={() => openEdit(dep)} onClick={() => openView(dep)}>
> <Eye className="h-4 w-4" />
</Button>
<Button
size="sm"
variant="outline"
onClick={() => openEdit(dep)}>
<Pencil className="h-4 w-4" /> <Pencil className="h-4 w-4" />
</Button> </Button>
<Button <Button
size="sm" size="sm"
variant="destructive" variant="destructive"
onClick={() => handleDelete(dep.departmentId)} onClick={() => handleDelete(dep.departmentId)}>
>
<Trash className="h-4 w-4" /> <Trash className="h-4 w-4" />
</Button> </Button>
</TableCell> </TableCell>
@@ -281,64 +277,59 @@ export default function DepartmentPage() {
</CardContent> </CardContent>
</Card> </Card>
{/* MODAL */}
<Dialog open={openModal} onOpenChange={setOpenModal}> <Dialog open={openModal} onOpenChange={setOpenModal}>
<DialogContent className="max-w-4xl"> <DialogContent className="w-full !max-w-5xl max-h-[90vh] overflow-y-auto">
<DialogHeader> <DialogHeader>
<DialogTitle> <DialogTitle>
{editing ? "Edit Department" : "Add Department"} {editing ? "Edit Department" : "Add Department"}
</DialogTitle> </DialogTitle>
</DialogHeader> </DialogHeader>
<div className="space-y-4 max-h-[70vh] overflow-y-auto pr-2"> <div className="space-y-4">
<Input <Input
name="departmentId" name="departmentId"
placeholder="Department ID"
value={form.departmentId} value={form.departmentId}
onChange={handleChange} onChange={handleChange}
disabled={!!editing} disabled={!!editing}
placeholder="Department ID"
/> />
<Input <Input
name="name" name="name"
placeholder="Department Name"
value={form.name} value={form.name}
onChange={handleChange} onChange={handleChange}
placeholder="Department Name"
/> />
<Textarea <Textarea
name="para1" name="para1"
placeholder="Paragraph 1"
value={form.para1} value={form.para1}
onChange={handleChange} onChange={handleChange}
placeholder="Para1"
/> />
<Textarea <Textarea
name="para2" name="para2"
placeholder="Paragraph 2"
value={form.para2} value={form.para2}
onChange={handleChange} onChange={handleChange}
placeholder="Para2"
/> />
<Textarea <Textarea
name="para3" name="para3"
placeholder="Paragraph 3"
value={form.para3} value={form.para3}
onChange={handleChange} onChange={handleChange}
placeholder="Para3"
/> />
<Textarea <Textarea
name="facilities" name="facilities"
placeholder="Facilities"
value={form.facilities} value={form.facilities}
onChange={handleChange} onChange={handleChange}
placeholder="Facilities"
/> />
<Textarea <Textarea
name="services" name="services"
placeholder="Services"
value={form.services} value={form.services}
onChange={handleChange} onChange={handleChange}
placeholder="Services"
/> />
</div> </div>
@@ -346,13 +337,65 @@ export default function DepartmentPage() {
<Button variant="outline" onClick={() => setOpenModal(false)}> <Button variant="outline" onClick={() => setOpenModal(false)}>
Cancel Cancel
</Button> </Button>
<Button onClick={handleSubmit}> <Button onClick={handleSubmit}>
{editing ? "Update" : "Create"} {editing ? "Update" : "Create"}
</Button> </Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
<Dialog open={viewOpen} onOpenChange={setViewOpen}>
<DialogContent className="w-full !max-w-5xl max-h-[90vh] overflow-y-auto">
{" "}
<DialogHeader>
<DialogTitle>Department Details</DialogTitle>
</DialogHeader>
{viewData && (
<div className="space-y-4 text-sm">
<p>
<b>ID:</b> {viewData.departmentId}
</p>
<p>
<b>Name:</b> {viewData.name}
</p>
<p>
<b>Para1:</b>
<br />
{viewData.para1}
</p>
<p>
<b>Para2:</b>
<br />
{viewData.para2}
</p>
<p>
<b>Para3:</b>
<br />
{viewData.para3}
</p>
<p>
<b>Facilities:</b>
<br />
{viewData.facilities}
</p>
<p>
<b>Services:</b>
<br />
{viewData.services}
</p>
</div>
)}
<DialogFooter>
<Button onClick={() => setViewOpen(false)}>Close</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div> </div>
); );
} }
+11 -15
View File
@@ -1,4 +1,4 @@
import {useState, useEffect, useCallback} from "react"; import { useState, useEffect, useCallback } from "react";
import { import {
getEmailConfigsApi, getEmailConfigsApi,
@@ -16,9 +16,9 @@ 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 { Button } from "@/components/ui/button";
import {Input} from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { import {
Dialog, Dialog,
@@ -28,7 +28,7 @@ import {
DialogFooter, DialogFooter,
} from "@/components/ui/dialog"; } from "@/components/ui/dialog";
import {Loader2, Plus, Pencil, Trash, RefreshCw} from "lucide-react"; import { Loader2, Plus, Pencil, Trash, RefreshCw } from "lucide-react";
export default function EmailPage() { export default function EmailPage() {
const [emails, setEmails] = useState<any[]>([]); const [emails, setEmails] = useState<any[]>([]);
@@ -69,7 +69,7 @@ export default function EmailPage() {
); );
function handleChange(e: any) { function handleChange(e: any) {
setForm({...form, [e.target.name]: e.target.value}); setForm({ ...form, [e.target.name]: e.target.value });
} }
function openAdd() { function openAdd() {
@@ -181,16 +181,14 @@ export default function EmailPage() {
<Button <Button
size="sm" size="sm"
variant="outline" variant="outline"
onClick={() => openEdit(item)} onClick={() => openEdit(item)}>
>
<Pencil className="h-4 w-4" /> <Pencil className="h-4 w-4" />
</Button> </Button>
<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>
@@ -227,11 +225,10 @@ export default function EmailPage() {
name="type" name="type"
value={form.type} value={form.type}
onChange={handleChange} onChange={handleChange}
className="border rounded px-2 py-2 w-full" className="border rounded px-2 py-2 w-full">
>
<option value="APPOINTMENT">APPOINTMENT</option> <option value="APPOINTMENT">APPOINTMENT</option>
<option value="CANDIDATE">CANDIDATE</option> <option value="CANDIDATE">CANDIDATE</option>
<option value="INQUIRY">INQUIRY</option> <option value="ACADEMICS">ACADEMICS</option>
</select> </select>
<select <select
@@ -243,8 +240,7 @@ export default function EmailPage() {
isActive: e.target.value === "true", isActive: e.target.value === "true",
}) })
} }
className="border rounded px-2 py-2 w-full" className="border rounded px-2 py-2 w-full">
>
<option value="true">Active</option> <option value="true">Active</option>
<option value="false">Inactive</option> <option value="false">Inactive</option>
</select> </select>
+167
View File
@@ -0,0 +1,167 @@
import { useState, useEffect, useCallback } from "react";
import { getInquiriesApi, deleteInquiryApi } from "@/api/inquiry";
import { exportToExcel } from "@/utils/exportToExcel";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Loader2, Trash, RefreshCw, Download } from "lucide-react";
export default function InquiryPage() {
const [inquiries, setInquiries] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const [searchText, setSearchText] = useState("");
const fetchAll = useCallback(async () => {
setLoading(true);
try {
const res = await getInquiriesApi();
setInquiries(res?.data || []);
} catch (err) {
console.error(err);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchAll();
}, [fetchAll]);
const filteredInquiries = inquiries.filter((item) => {
return (
item.fullName?.toLowerCase().includes(searchText.toLowerCase()) ||
item.number?.includes(searchText) ||
item.emailId?.toLowerCase().includes(searchText.toLowerCase()) ||
item.subject?.toLowerCase().includes(searchText.toLowerCase())
);
});
async function handleDelete(id: number) {
if (!confirm("Delete inquiry?")) return;
await deleteInquiryApi(id);
fetchAll();
}
const handleExport = () => {
const exportData = filteredInquiries.map((item) => ({
ID: item.id,
Name: item.fullName,
Phone: item.number,
Email: item.emailId,
Subject: item.subject,
Message: item.message,
Date: new Date(item.createdAt).toLocaleDateString(),
}));
exportToExcel(exportData, "inquiries");
};
return (
<div className="p-6 space-y-6">
<div className="flex justify-between items-center gap-3 flex-wrap">
<h1 className="text-2xl font-bold">Inquiries</h1>
<div className="flex flex-wrap gap-2">
<Input
placeholder="Search name / phone / email / subject..."
value={searchText}
onChange={(e) => setSearchText(e.target.value)}
className="w-[260px]"
/>
<Button variant="outline" onClick={fetchAll} disabled={loading}>
<RefreshCw className="mr-2 h-4 w-4" />
Refresh
</Button>
<Button variant="outline" onClick={handleExport}>
<Download className="mr-2 h-4 w-4" />
Export
</Button>
</div>
</div>
<Card>
<CardHeader>
<CardTitle>Inquiry List</CardTitle>
</CardHeader>
<CardContent>
<div className="overflow-x-auto">
<Table className="min-w-[900px]">
<TableHeader>
<TableRow>
<TableHead>ID</TableHead>
<TableHead>Name</TableHead>
<TableHead>Phone</TableHead>
<TableHead>Email</TableHead>
<TableHead>Subject</TableHead>
<TableHead>Message</TableHead>
<TableHead>Date</TableHead>
<TableHead>Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{loading ? (
<TableRow>
<TableCell colSpan={8} className="text-center">
<Loader2 className="h-6 w-6 animate-spin mx-auto" />
</TableCell>
</TableRow>
) : filteredInquiries.length === 0 ? (
<TableRow>
<TableCell colSpan={8} className="text-center">
No inquiries found
</TableCell>
</TableRow>
) : (
filteredInquiries.map((item) => (
<TableRow key={item.id}>
<TableCell>{item.id}</TableCell>
<TableCell>{item.fullName}</TableCell>
<TableCell>{item.number}</TableCell>
<TableCell>{item.emailId}</TableCell>
<TableCell>{item.subject}</TableCell>
<TableCell className="max-w-[250px] whitespace-normal">
{item.message}
</TableCell>
<TableCell>
{new Date(item.createdAt).toLocaleDateString()}
</TableCell>
<TableCell>
<Button
size="sm"
variant="destructive"
onClick={() => handleDelete(item.id)}>
<Trash className="h-4 w-4" />
</Button>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div>
</CardContent>
</Card>
</div>
);
}
+400
View File
@@ -0,0 +1,400 @@
import { useState, useEffect, useCallback } from "react";
import {
getNewsApi,
createNewsApi,
updateNewsApi,
deleteNewsApi,
} from "@/api/newsMedia";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from "@/components/ui/dialog";
import {
Loader2,
Plus,
Pencil,
Trash,
RefreshCw,
Eye,
ChevronLeft,
ChevronRight,
} from "lucide-react";
export default function NewsPage() {
const [news, setNews] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const [searchText, setSearchText] = useState("");
const [openModal, setOpenModal] = useState(false);
const [editing, setEditing] = useState<any>(null);
const [viewOpen, setViewOpen] = useState(false);
const [viewData, setViewData] = useState<any>(null);
const [currentPage, setCurrentPage] = useState(1);
const [itemsPerPage, setItemsPerPage] = useState(10);
const [form, setForm] = useState({
headline: "",
content: "",
firstPara: "",
secondPara: "",
date: "",
author: "",
});
const fetchAll = useCallback(async () => {
setLoading(true);
try {
const res = await getNewsApi();
setNews(res?.data || []);
} catch (err) {
console.error(err);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchAll();
}, [fetchAll]);
const filteredNews = news.filter((item) =>
item.Headline?.toLowerCase().includes(searchText.toLowerCase()),
);
const totalPages = Math.ceil(filteredNews.length / itemsPerPage);
const startIndex = (currentPage - 1) * itemsPerPage;
const paginatedData = filteredNews.slice(
startIndex,
startIndex + itemsPerPage,
);
function handleChange(e: any) {
setForm({ ...form, [e.target.name]: e.target.value });
}
function openAdd() {
setEditing(null);
setForm({
headline: "",
content: "",
firstPara: "",
secondPara: "",
date: "",
author: "",
});
setOpenModal(true);
}
function openEdit(item: any) {
setEditing(item);
setForm({
headline: item.Headline || "",
content: item.Content || "",
firstPara: item.FirstPara || "",
secondPara: item.SecondPara || "",
date: item.Date ? item.Date.split("T")[0] : "",
author: item.Author || "",
});
setOpenModal(true);
}
function openView(item: any) {
setViewData(item);
setViewOpen(true);
}
async function handleSubmit() {
try {
if (editing) {
await updateNewsApi(editing.Id, form);
} else {
await createNewsApi(form);
}
setOpenModal(false);
fetchAll();
} catch (err) {
console.error(err);
}
}
async function handleDelete(id: number) {
if (!confirm("Delete news?")) return;
await deleteNewsApi(id);
fetchAll();
}
return (
<div className="p-6 space-y-6">
<div className="flex justify-between items-center flex-wrap gap-3">
<h1 className="text-2xl font-bold">News Media</h1>
<div className="flex gap-2 flex-wrap items-center">
<Input
placeholder="Search headline..."
value={searchText}
onChange={(e) => {
setSearchText(e.target.value);
setCurrentPage(1);
}}
className="w-[250px]"
/>
<select
value={itemsPerPage}
onChange={(e) => {
setItemsPerPage(Number(e.target.value));
setCurrentPage(1);
}}
className="border px-2 py-1 rounded">
<option value={5}>5 / page</option>
<option value={10}>10 / page</option>
<option value={20}>20 / page</option>
</select>
<Button variant="outline" onClick={fetchAll} disabled={loading}>
<RefreshCw className="mr-2 h-4 w-4" />
Refresh
</Button>
<Button onClick={openAdd}>
<Plus className="mr-2 h-4 w-4" />
Add News
</Button>
</div>
</div>
<Card>
<CardHeader>
<CardTitle>News List</CardTitle>
</CardHeader>
<CardContent>
<div className="overflow-x-auto">
<Table className="min-w-[900px] table-fixed">
<TableHeader>
<TableRow>
<TableHead className="w-[60px]">ID</TableHead>
<TableHead className="w-[220px]">Headline</TableHead>
<TableHead className="w-[120px]">Author</TableHead>
<TableHead className="w-[120px]">Date</TableHead>
<TableHead className="w-[260px]">Content</TableHead>
<TableHead className="w-[150px]">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{loading ? (
<TableRow>
<TableCell colSpan={6} className="text-center">
<Loader2 className="animate-spin mx-auto" />
</TableCell>
</TableRow>
) : paginatedData.length === 0 ? (
<TableRow>
<TableCell colSpan={6} className="text-center">
No news found
</TableCell>
</TableRow>
) : (
paginatedData.map((item) => (
<TableRow key={item.Id}>
<TableCell>{item.Id}</TableCell>
<TableCell className="break-words whitespace-normal">
{item.Headline}
</TableCell>
<TableCell>{item.Author}</TableCell>
<TableCell>
{item.Date
? new Date(item.Date).toLocaleDateString()
: "-"}
</TableCell>
<TableCell className="break-words whitespace-normal">
{item.Content}
</TableCell>
<TableCell className="flex gap-2">
<Button
size="sm"
variant="outline"
onClick={() => openView(item)}>
<Eye className="h-4 w-4" />
</Button>
<Button
size="sm"
variant="outline"
onClick={() => openEdit(item)}>
<Pencil className="h-4 w-4" />
</Button>
<Button
size="sm"
variant="destructive"
onClick={() => handleDelete(Number(item.Id))}>
<Trash className="h-4 w-4" />
</Button>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div>
{/* PAGINATION */}
<div className="flex justify-between items-center mt-4">
<p className="text-sm">
Page {currentPage} of {totalPages}
</p>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
disabled={currentPage === 1}
onClick={() => setCurrentPage((p) => p - 1)}>
<ChevronLeft className="h-4 w-4" />
</Button>
<Button
variant="outline"
size="sm"
disabled={currentPage === totalPages}
onClick={() => setCurrentPage((p) => p + 1)}>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
</div>
</CardContent>
</Card>
{/* CREATE / EDIT MODAL */}
<Dialog open={openModal} onOpenChange={setOpenModal}>
<DialogContent className="w-[95vw] max-w-none max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>{editing ? "Edit News" : "Add News"}</DialogTitle>
</DialogHeader>
<div className="space-y-3">
<Input
name="headline"
placeholder="Headline"
value={form.headline}
onChange={handleChange}
/>
<Input
name="author"
placeholder="Author"
value={form.author}
onChange={handleChange}
/>
<Input
type="date"
name="date"
value={form.date}
onChange={handleChange}
/>
<textarea
name="firstPara"
placeholder="First Paragraph"
value={form.firstPara}
onChange={handleChange}
className="border rounded p-2 w-full min-h-[100px]"
/>
<textarea
name="secondPara"
placeholder="Second Paragraph"
value={form.secondPara}
onChange={handleChange}
className="border rounded p-2 w-full min-h-[100px]"
/>
<textarea
name="content"
placeholder="Content"
value={form.content}
onChange={handleChange}
className="border rounded p-2 w-full min-h-[150px]"
/>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setOpenModal(false)}>
Cancel
</Button>
<Button onClick={handleSubmit}>
{editing ? "Update" : "Create"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* VIEW MODAL */}
<Dialog open={viewOpen} onOpenChange={setViewOpen}>
<DialogContent className="w-[95vw] max-w-none max-h-[90vh] overflow-y-auto p-6">
<DialogHeader>
<DialogTitle>News Details</DialogTitle>
</DialogHeader>
{viewData && (
<div className="space-y-4 text-sm">
<b>Headline:</b>
<p>{viewData.Headline}</p>
<b>Author:</b>
<p>{viewData.Author}</p>
<b>Date:</b>
<p>
{viewData.Date
? new Date(viewData.Date).toLocaleDateString()
: "-"}
</p>
<b>First Para:</b>
<p className="whitespace-pre-line">{viewData.FirstPara}</p>
<b>Second Para:</b>
<p className="whitespace-pre-line">{viewData.SecondPara}</p>
<b>Content:</b>
<p className="whitespace-pre-line">{viewData.Content}</p>
</div>
)}
<DialogFooter>
<Button onClick={() => setViewOpen(false)}>Close</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}