chore: file formatting

This commit is contained in:
Kailasdevdas
2026-05-26 15:48:01 +05:30
parent 8a21e0bf38
commit 78e2618a29
117 changed files with 12775 additions and 14638 deletions
+46 -139
View File
@@ -1,44 +1,22 @@
import { useState, useEffect, useCallback } from "react";
import { useState, useEffect, useCallback } from 'react';
import { getAcademicsApi, deleteAcademicsApi } from "@/api/academics";
import { exportToExcel } from "@/utils/exportToExcel";
import { getAcademicsApi, deleteAcademicsApi } from '@/api/academics';
import { exportToExcel } from '@/utils/exportToExcel';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
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 { 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,
Trash,
RefreshCw,
Download,
ChevronLeft,
ChevronRight,
Eye,
BookOpen,
} from "lucide-react";
import { Loader2, Trash, RefreshCw, Download, ChevronLeft, ChevronRight, Eye, BookOpen } from 'lucide-react';
export default function AcademicsPage() {
const [records, setRecords] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const [searchText, setSearchText] = useState("");
const [searchText, setSearchText] = useState('');
const [viewOpen, setViewOpen] = useState(false);
const [viewData, setViewData] = useState<any>(null);
@@ -87,7 +65,7 @@ export default function AcademicsPage() {
}
async function handleDelete(id: number) {
if (!confirm("Delete record?")) return;
if (!confirm('Delete record?')) return;
await deleteAcademicsApi(id);
fetchAll();
}
@@ -104,7 +82,7 @@ export default function AcademicsPage() {
Date: new Date(item.createdAt).toLocaleDateString(),
}));
exportToExcel(exportData, "academics");
exportToExcel(exportData, 'academics');
};
return (
@@ -120,12 +98,7 @@ export default function AcademicsPage() {
className="w-[280px] text-base"
/>
<Button
variant="outline"
onClick={fetchAll}
disabled={loading}
className="text-base"
>
<Button variant="outline" onClick={fetchAll} disabled={loading} className="text-base">
<RefreshCw className="mr-2 h-5 w-5" />
Refresh
</Button>
@@ -147,27 +120,13 @@ export default function AcademicsPage() {
<Table className="w-full min-w-[1100px] table-fixed border-separate border-spacing-0">
<TableHeader className="sticky top-0 z-20 bg-background shadow-sm">
<TableRow>
<TableHead className="w-[60px] bg-background font-bold text-sm">
ID
</TableHead>
<TableHead className="w-[220px] bg-background font-bold text-sm">
Full Name
</TableHead>
<TableHead className="w-[180px] bg-background font-bold text-sm">
Course
</TableHead>
<TableHead className="w-[180px] bg-background font-bold text-sm">
Subject
</TableHead>
<TableHead className="w-[140px] bg-background font-bold text-sm">
Applied Date
</TableHead>
<TableHead className="w-[220px] bg-background font-bold text-sm">
Message
</TableHead>
<TableHead className="w-[120px] bg-background font-bold text-right text-sm">
Actions
</TableHead>
<TableHead className="w-[60px] bg-background font-bold text-sm">ID</TableHead>
<TableHead className="w-[220px] bg-background font-bold text-sm">Full Name</TableHead>
<TableHead className="w-[180px] bg-background font-bold text-sm">Course</TableHead>
<TableHead className="w-[180px] bg-background font-bold text-sm">Subject</TableHead>
<TableHead className="w-[140px] bg-background font-bold text-sm">Applied Date</TableHead>
<TableHead className="w-[220px] bg-background font-bold text-sm">Message</TableHead>
<TableHead className="w-[120px] bg-background font-bold text-right text-sm">Actions</TableHead>
</TableRow>
</TableHeader>
@@ -180,56 +139,32 @@ export default function AcademicsPage() {
</TableRow>
) : currentItems.length === 0 ? (
<TableRow>
<TableCell
colSpan={7}
className="text-center text-muted-foreground py-10 text-base"
>
<TableCell colSpan={7} className="text-center text-muted-foreground py-10 text-base">
No records found
</TableCell>
</TableRow>
) : (
currentItems.map((item) => (
<TableRow key={item.id} className="hover:bg-muted/50">
<TableCell className="font-mono text-xs">
{item.id}
<TableCell className="font-mono text-xs">{item.id}</TableCell>
<TableCell>
<div className="font-semibold text-base truncate">{item.fullName}</div>
<div className="text-xs text-muted-foreground truncate">{item.emailId}</div>
<div className="text-[11px] font-medium">{item.number}</div>
</TableCell>
<TableCell>
<div className="font-semibold text-base truncate">
{item.fullName}
</div>
<div className="text-xs text-muted-foreground truncate">
{item.emailId}
</div>
<div className="text-[11px] font-medium">
{item.number}
</div>
<div className="text-sm font-medium line-clamp-2">{item.courseName || '-'}</div>
</TableCell>
<TableCell>
<div className="text-sm font-medium line-clamp-2">
{item.courseName || "-"}
</div>
<div className="text-sm line-clamp-2">{item.subject || '-'}</div>
</TableCell>
<TableCell className="text-sm">{new Date(item.createdAt).toLocaleDateString()}</TableCell>
<TableCell>
<div className="text-sm line-clamp-2">
{item.subject || "-"}
</div>
</TableCell>
<TableCell className="text-sm">
{new Date(item.createdAt).toLocaleDateString()}
</TableCell>
<TableCell>
<div className="text-sm line-clamp-2 text-muted-foreground italic">
{item.message || "-"}
</div>
<div className="text-sm line-clamp-2 text-muted-foreground italic">{item.message || '-'}</div>
</TableCell>
<TableCell className="text-right">
<div className="flex justify-end gap-2">
<Button
size="icon"
variant="ghost"
className="h-9 w-9"
onClick={() => openView(item)}
>
<Button size="icon" variant="ghost" className="h-9 w-9" onClick={() => openView(item)}>
<Eye className="h-4 w-4" />
</Button>
<Button
@@ -252,14 +187,9 @@ export default function AcademicsPage() {
{!loading && filteredRecords.length > 0 && (
<div className="flex items-center justify-between px-2 py-6 border-t">
<div className="text-base text-muted-foreground">
Showing{" "}
<span className="font-semibold">{indexOfFirstItem + 1}</span> to{" "}
<span className="font-semibold">
{Math.min(indexOfLastItem, filteredRecords.length)}
</span>{" "}
of{" "}
<span className="font-semibold">{filteredRecords.length}</span>{" "}
records
Showing <span className="font-semibold">{indexOfFirstItem + 1}</span> to{' '}
<span className="font-semibold">{Math.min(indexOfLastItem, filteredRecords.length)}</span> of{' '}
<span className="font-semibold">{filteredRecords.length}</span> records
</div>
<div className="flex items-center gap-6">
<div className="text-base font-semibold">
@@ -270,9 +200,7 @@ export default function AcademicsPage() {
variant="outline"
size="icon"
className="h-10 w-10"
onClick={() =>
setCurrentPage((prev) => Math.max(prev - 1, 1))
}
onClick={() => setCurrentPage((prev) => Math.max(prev - 1, 1))}
disabled={currentPage === 1}
>
<ChevronLeft className="h-5 w-5" />
@@ -281,9 +209,7 @@ export default function AcademicsPage() {
variant="outline"
size="icon"
className="h-10 w-10"
onClick={() =>
setCurrentPage((prev) => Math.min(prev + 1, totalPages))
}
onClick={() => setCurrentPage((prev) => Math.min(prev + 1, totalPages))}
disabled={currentPage === totalPages || totalPages === 0}
>
<ChevronRight className="h-5 w-5" />
@@ -307,42 +233,26 @@ export default function AcademicsPage() {
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="space-y-4">
<div>
<p className="text-xs uppercase font-bold text-muted-foreground">
Applicant Information
</p>
<p className="text-lg font-bold text-primary">
{viewData.fullName}
</p>
<p className="text-xs uppercase font-bold text-muted-foreground">Applicant Information</p>
<p className="text-lg font-bold text-primary">{viewData.fullName}</p>
<p className="text-sm font-medium">{viewData.emailId}</p>
<p className="text-sm">{viewData.number}</p>
</div>
<div>
<p className="text-xs uppercase font-bold text-muted-foreground">
Course & Subject
</p>
<p className="text-base font-semibold">
{viewData.courseName || "N/A"}
</p>
<p className="text-sm text-muted-foreground">
{viewData.subject}
</p>
<p className="text-xs uppercase font-bold text-muted-foreground">Course & Subject</p>
<p className="text-base font-semibold">{viewData.courseName || 'N/A'}</p>
<p className="text-sm text-muted-foreground">{viewData.subject}</p>
</div>
<div>
<p className="text-xs uppercase font-bold text-muted-foreground">
Submission Date
</p>
<p className="text-sm">
{new Date(viewData.createdAt).toLocaleString()}
</p>
<p className="text-xs uppercase font-bold text-muted-foreground">Submission Date</p>
<p className="text-sm">{new Date(viewData.createdAt).toLocaleString()}</p>
</div>
</div>
<div className="space-y-4">
<div className="p-4 bg-muted/30 rounded-lg border">
<p className="text-xs uppercase font-bold text-muted-foreground mb-2">
Message / Research Inquiry
</p>
<p className="text-xs uppercase font-bold text-muted-foreground mb-2">Message / Research Inquiry</p>
<p className="text-sm leading-relaxed whitespace-pre-wrap italic">
{viewData.message || "No message content provided."}
{viewData.message || 'No message content provided.'}
</p>
</div>
</div>
@@ -350,10 +260,7 @@ export default function AcademicsPage() {
</div>
)}
<DialogFooter>
<Button
onClick={() => setViewOpen(false)}
className="w-full md:w-auto"
>
<Button onClick={() => setViewOpen(false)} className="w-full md:w-auto">
Close
</Button>
</DialogFooter>
+57 -166
View File
@@ -1,47 +1,26 @@
import { useState, useEffect, useCallback } from "react";
import { useState, useEffect, useCallback } from 'react';
import { getAppointmentsApi, deleteAppointmentApi } from "@/api/appointment";
import { exportToExcel } from "@/utils/exportToExcel";
import { getAppointmentsApi, deleteAppointmentApi } from '@/api/appointment';
import { exportToExcel } from '@/utils/exportToExcel';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
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 { 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,
Trash,
RefreshCw,
Download,
ChevronLeft,
ChevronRight,
Eye,
} from "lucide-react";
import { Loader2, Trash, RefreshCw, Download, ChevronLeft, ChevronRight, Eye } from 'lucide-react';
export default function AppointmentPage() {
const [appointments, setAppointments] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const [searchText, setSearchText] = useState("");
const [filterDoctor, setFilterDoctor] = useState("");
const [filterDate, setFilterDate] = useState("");
const [startDate, setStartDate] = useState("");
const [endDate, setEndDate] = useState("");
const [searchText, setSearchText] = useState('');
const [filterDoctor, setFilterDoctor] = useState('');
const [filterDate, setFilterDate] = useState('');
const [startDate, setStartDate] = useState('');
const [endDate, setEndDate] = useState('');
const [viewOpen, setViewOpen] = useState(false);
const [viewData, setViewData] = useState<any>(null);
@@ -53,14 +32,7 @@ export default function AppointmentPage() {
const fetchAll = useCallback(async () => {
setLoading(true);
try {
const res = await getAppointmentsApi(
currentPage,
itemsPerPage,
filterDate,
startDate,
endDate,
searchText,
);
const res = await getAppointmentsApi(currentPage, itemsPerPage, filterDate, startDate, endDate, searchText);
setAppointments(res?.data || []);
setTotalPages(res?.pagination?.totalPages || 1);
setTotalItems(res?.pagination?.total || 0);
@@ -76,9 +48,7 @@ export default function AppointmentPage() {
}, [fetchAll]);
const filteredAppointments = appointments.filter((item) => {
const matchesDoctor = filterDoctor
? item.doctor?.name?.toLowerCase().includes(filterDoctor.toLowerCase())
: true;
const matchesDoctor = filterDoctor ? item.doctor?.name?.toLowerCase().includes(filterDoctor.toLowerCase()) : true;
return matchesDoctor;
});
@@ -95,7 +65,7 @@ export default function AppointmentPage() {
}
async function handleDelete(id: number) {
if (!confirm("Delete appointment?")) return;
if (!confirm('Delete appointment?')) return;
await deleteAppointmentApi(id);
fetchAll();
}
@@ -111,7 +81,7 @@ export default function AppointmentPage() {
Date: new Date(item.date).toLocaleDateString(),
Message: item.message,
}));
exportToExcel(exportData, "appointments");
exportToExcel(exportData, 'appointments');
};
return (
@@ -121,9 +91,7 @@ export default function AppointmentPage() {
<div className="flex flex-wrap gap-4 items-end">
<div className="flex flex-col gap-1">
<label className="text-xs font-medium text-muted-foreground">
Search
</label>
<label className="text-xs font-medium text-muted-foreground">Search</label>
<Input
placeholder="Search name / phone..."
value={searchText}
@@ -136,9 +104,7 @@ export default function AppointmentPage() {
</div>
<div className="flex flex-col gap-1">
<label className="text-xs font-medium text-muted-foreground">
Date
</label>
<label className="text-xs font-medium text-muted-foreground">Date</label>
<Input
type="date"
value={filterDate}
@@ -152,9 +118,7 @@ export default function AppointmentPage() {
</div>
<div className="flex flex-col gap-1">
<label className="text-xs font-medium text-muted-foreground">
From
</label>
<label className="text-xs font-medium text-muted-foreground">From</label>
<Input
type="date"
value={startDate}
@@ -168,9 +132,7 @@ export default function AppointmentPage() {
</div>
<div className="flex flex-col gap-1">
<label className="text-xs font-medium text-muted-foreground">
To
</label>
<label className="text-xs font-medium text-muted-foreground">To</label>
<Input
type="date"
value={endDate}
@@ -184,9 +146,7 @@ export default function AppointmentPage() {
</div>
<div className="flex flex-col gap-1">
<label className="text-xs font-medium text-muted-foreground">
Rows
</label>
<label className="text-xs font-medium text-muted-foreground">Rows</label>
<select
value={itemsPerPage}
onChange={(e) => {
@@ -201,12 +161,7 @@ export default function AppointmentPage() {
</select>
</div>
<Button
variant="outline"
onClick={fetchAll}
disabled={loading}
className="text-base"
>
<Button variant="outline" onClick={fetchAll} disabled={loading} className="text-base">
<RefreshCw className="mr-2 h-5 w-5" />
Refresh
</Button>
@@ -228,24 +183,12 @@ export default function AppointmentPage() {
<Table className="w-full min-w-[1000px] table-fixed border-separate border-spacing-0">
<TableHeader className="sticky top-0 z-20 bg-background shadow-sm">
<TableRow>
<TableHead className="w-[60px] bg-background font-bold text-sm">
ID
</TableHead>
<TableHead className="w-[200px] bg-background font-bold text-sm">
Patient
</TableHead>
<TableHead className="w-[180px] bg-background font-bold text-sm">
Doctor
</TableHead>
<TableHead className="w-[150px] bg-background font-bold text-sm">
Date
</TableHead>
<TableHead className="w-[250px] bg-background font-bold text-sm">
Message
</TableHead>
<TableHead className="w-[120px] bg-background font-bold text-right text-sm">
Actions
</TableHead>
<TableHead className="w-[60px] bg-background font-bold text-sm">ID</TableHead>
<TableHead className="w-[200px] bg-background font-bold text-sm">Patient</TableHead>
<TableHead className="w-[180px] bg-background font-bold text-sm">Doctor</TableHead>
<TableHead className="w-[150px] bg-background font-bold text-sm">Date</TableHead>
<TableHead className="w-[250px] bg-background font-bold text-sm">Message</TableHead>
<TableHead className="w-[120px] bg-background font-bold text-right text-sm">Actions</TableHead>
</TableRow>
</TableHeader>
@@ -258,53 +201,31 @@ export default function AppointmentPage() {
</TableRow>
) : filteredAppointments.length === 0 ? (
<TableRow>
<TableCell
colSpan={6}
className="text-center text-muted-foreground py-10 text-base"
>
<TableCell colSpan={6} className="text-center text-muted-foreground py-10 text-base">
No appointments found
</TableCell>
</TableRow>
) : (
filteredAppointments.map((item) => (
<TableRow key={item.id} className="hover:bg-muted/50">
<TableCell className="font-mono text-xs">
{item.id}
<TableCell className="font-mono text-xs">{item.id}</TableCell>
<TableCell>
<div className="font-semibold text-base truncate">{item.name}</div>
<div className="text-xs text-muted-foreground">{item.mobileNumber}</div>
</TableCell>
<TableCell>
<div className="font-semibold text-base truncate">
{item.name}
</div>
<div className="text-xs text-muted-foreground">
{item.mobileNumber}
</div>
<div className="text-sm font-medium">{item.doctor?.name || '-'}</div>
<div className="text-[10px] text-muted-foreground truncate">{item.department?.name}</div>
</TableCell>
<TableCell>
<div className="text-sm font-medium">
{item.doctor?.name || "-"}
</div>
<div className="text-[10px] text-muted-foreground truncate">
{item.department?.name}
</div>
<div className="text-sm">{new Date(item.date).toLocaleDateString()}</div>
</TableCell>
<TableCell>
<div className="text-sm">
{new Date(item.date).toLocaleDateString()}
</div>
</TableCell>
<TableCell>
<div className="text-sm line-clamp-2 text-muted-foreground italic">
{item.message || "-"}
</div>
<div className="text-sm line-clamp-2 text-muted-foreground italic">{item.message || '-'}</div>
</TableCell>
<TableCell className="text-right">
<div className="flex justify-end gap-2">
<Button
size="icon"
variant="ghost"
className="h-9 w-9"
onClick={() => openView(item)}
>
<Button size="icon" variant="ghost" className="h-9 w-9" onClick={() => openView(item)}>
<Eye className="h-4 w-4" />
</Button>
<Button
@@ -327,12 +248,9 @@ export default function AppointmentPage() {
{!loading && totalItems > 0 && (
<div className="flex items-center justify-between px-2 py-6 border-t">
<div className="text-base text-muted-foreground">
Showing{" "}
<span className="font-semibold">{indexOfFirstItem + 1}</span> to{" "}
<span className="font-semibold">
{Math.min(currentPage * itemsPerPage, totalItems)}
</span>{" "}
of <span className="font-semibold">{totalItems}</span>
Showing <span className="font-semibold">{indexOfFirstItem + 1}</span> to{' '}
<span className="font-semibold">{Math.min(currentPage * itemsPerPage, totalItems)}</span> of{' '}
<span className="font-semibold">{totalItems}</span>
</div>
<div className="flex items-center gap-6">
<div className="text-base font-semibold">
@@ -343,9 +261,7 @@ export default function AppointmentPage() {
variant="outline"
size="icon"
className="h-10 w-10"
onClick={() =>
setCurrentPage((prev) => Math.max(prev - 1, 1))
}
onClick={() => setCurrentPage((prev) => Math.max(prev - 1, 1))}
disabled={currentPage === 1}
>
<ChevronLeft className="h-5 w-5" />
@@ -354,9 +270,7 @@ export default function AppointmentPage() {
variant="outline"
size="icon"
className="h-10 w-10"
onClick={() =>
setCurrentPage((prev) => Math.min(prev + 1, totalPages))
}
onClick={() => setCurrentPage((prev) => Math.min(prev + 1, totalPages))}
disabled={currentPage === totalPages || totalPages === 0}
>
<ChevronRight className="h-5 w-5" />
@@ -371,33 +285,21 @@ export default function AppointmentPage() {
<Dialog open={viewOpen} onOpenChange={setViewOpen}>
<DialogContent className="w-full !max-w-3xl max-h-[85vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="text-2xl border-b pb-2">
Appointment Details
</DialogTitle>
<DialogTitle className="text-2xl border-b pb-2">Appointment Details</DialogTitle>
</DialogHeader>
{viewData && (
<div className="space-y-6 py-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="space-y-4">
<div>
<p className="text-xs uppercase font-bold text-muted-foreground">
Patient Information
</p>
<p className="text-lg font-bold text-primary">
{viewData.name}
</p>
<p className="text-xs uppercase font-bold text-muted-foreground">Patient Information</p>
<p className="text-lg font-bold text-primary">{viewData.name}</p>
<p className="text-sm">{viewData.mobileNumber}</p>
<p className="text-sm">
{viewData.email || "No email provided"}
</p>
<p className="text-sm">{viewData.email || 'No email provided'}</p>
</div>
<div>
<p className="text-xs uppercase font-bold text-muted-foreground">
Appointment Date
</p>
<p className="text-base font-semibold">
{new Date(viewData.date).toLocaleDateString()}
</p>
<p className="text-xs uppercase font-bold text-muted-foreground">Appointment Date</p>
<p className="text-base font-semibold">{new Date(viewData.date).toLocaleDateString()}</p>
<p className="text-[10px] text-muted-foreground">
Booked on: {new Date(viewData.createdAt).toLocaleString()}
</p>
@@ -405,22 +307,14 @@ export default function AppointmentPage() {
</div>
<div className="space-y-4">
<div>
<p className="text-xs uppercase font-bold text-muted-foreground">
Doctor / Department
</p>
<p className="text-base font-bold">
{viewData.doctor?.name || "Not Assigned"}
</p>
<p className="text-sm text-muted-foreground">
{viewData.department?.name || "General"}
</p>
<p className="text-xs uppercase font-bold text-muted-foreground">Doctor / Department</p>
<p className="text-base font-bold">{viewData.doctor?.name || 'Not Assigned'}</p>
<p className="text-sm text-muted-foreground">{viewData.department?.name || 'General'}</p>
</div>
<div className="p-4 bg-muted/30 rounded-lg">
<p className="text-xs uppercase font-bold text-muted-foreground mb-2">
Message from Patient
</p>
<p className="text-xs uppercase font-bold text-muted-foreground mb-2">Message from Patient</p>
<p className="text-sm italic leading-relaxed whitespace-pre-wrap">
{viewData.message || "No message provided."}
{viewData.message || 'No message provided.'}
</p>
</div>
</div>
@@ -428,10 +322,7 @@ export default function AppointmentPage() {
</div>
)}
<DialogFooter>
<Button
onClick={() => setViewOpen(false)}
className="w-full md:w-auto"
>
<Button onClick={() => setViewOpen(false)} className="w-full md:w-auto">
Close
</Button>
</DialogFooter>
+21 -47
View File
@@ -1,23 +1,16 @@
import {useState, useEffect, useCallback} from "react";
import {AxiosError} from "axios";
import {useNavigate} from "react-router-dom";
import { useState, useEffect, useCallback } from 'react';
import { AxiosError } from 'axios';
import { useNavigate } from 'react-router-dom';
import {getAllBlogsApi, deleteBlogApi} from "@/api/blog";
import { getAllBlogsApi, deleteBlogApi } from '@/api/blog';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
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 { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {Loader2, RefreshCw, Plus, Pencil, Trash, Eye} from "lucide-react";
import { Loader2, RefreshCw, Plus, Pencil, Trash, Eye } from 'lucide-react';
interface Blog {
id: number;
@@ -29,14 +22,14 @@ interface Blog {
export default function BlogPage() {
const [blogs, setBlogs] = useState<Blog[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const [searchText, setSearchText] = useState("");
const [error, setError] = useState('');
const [searchText, setSearchText] = useState('');
const navigate = useNavigate();
const fetchBlogs = useCallback(async () => {
setLoading(true);
setError("");
setError('');
try {
const res = await getAllBlogsApi();
@@ -48,9 +41,9 @@ export default function BlogPage() {
}
} catch (err) {
if (err instanceof AxiosError) {
setError(err.response?.data?.message || "Failed to load blogs");
setError(err.response?.data?.message || 'Failed to load blogs');
} else {
setError("Something went wrong");
setError('Something went wrong');
}
} finally {
setLoading(false);
@@ -64,14 +57,11 @@ export default function BlogPage() {
const filteredBlogs = blogs.filter((b) => {
const text = searchText.toLowerCase();
return (
b.title?.toLowerCase().includes(text) ||
b.writer?.toLowerCase().includes(text)
);
return b.title?.toLowerCase().includes(text) || b.writer?.toLowerCase().includes(text);
});
async function handleDelete(id: number) {
const confirmDelete = confirm("Delete this blog?");
const confirmDelete = confirm('Delete this blog?');
if (!confirmDelete) return;
try {
@@ -100,18 +90,14 @@ export default function BlogPage() {
Refresh
</Button>
<Button onClick={() => navigate("/blog/create")}>
<Button onClick={() => navigate('/blog/create')}>
<Plus className="mr-2 h-4 w-4" />
Add Blog
</Button>
</div>
</div>
{error && (
<div className="p-4 text-red-600 bg-red-50 border rounded-md">
{error}
</div>
)}
{error && <div className="p-4 text-red-600 bg-red-50 border rounded-md">{error}</div>}
<Card>
<CardHeader>
@@ -153,26 +139,14 @@ export default function BlogPage() {
<TableCell>{blog.writer}</TableCell>
<TableCell className="flex gap-2">
<Button
size="sm"
variant="outline"
onClick={() => navigate(`/blog/edit/${blog.id}`)}
>
<Button size="sm" variant="outline" onClick={() => navigate(`/blog/edit/${blog.id}`)}>
<Pencil className="h-4 w-4" />
</Button>
<Button
size="sm"
variant="secondary"
onClick={() => navigate(`/blog/${blog.id}`)}
>
<Button size="sm" variant="secondary" onClick={() => navigate(`/blog/${blog.id}`)}>
<Eye className="h-4 w-4" />
</Button>
<Button
size="sm"
variant="destructive"
onClick={() => handleDelete(blog.id)}
>
<Button size="sm" variant="destructive" onClick={() => handleDelete(blog.id)}>
<Trash className="h-4 w-4" />
</Button>
</TableCell>
+30 -64
View File
@@ -1,26 +1,22 @@
import React, {useEffect, useState} from "react";
import {useParams, useNavigate} from "react-router-dom";
import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {Button} from "@/components/ui/button";
import {getBlogByIdApi} from "@/api/blog";
import { Button } from '@/components/ui/button';
import { getBlogByIdApi } from '@/api/blog';
/* ---------------- LIST RENDERER ---------------- */
const renderList = (items, style) => {
// ✅ Checklist
if (style === "checklist") {
if (style === 'checklist') {
return (
<div className="mb-4 space-y-2">
{items.map((item, i) => (
<div key={i} className="flex items-center gap-2">
<input
type="checkbox"
checked={item.meta?.checked || false}
readOnly
/>
<input type="checkbox" checked={item.meta?.checked || false} readOnly />
<span
className={item.meta?.checked ? "line-through opacity-60" : ""}
className={item.meta?.checked ? 'line-through opacity-60' : ''}
dangerouslySetInnerHTML={{
__html: item.content || "",
__html: item.content || '',
}}
/>
</div>
@@ -30,14 +26,10 @@ const renderList = (items, style) => {
}
// ✅ Ordered / Unordered
const ListTag = style === "ordered" ? "ol" : "ul";
const ListTag = style === 'ordered' ? 'ol' : 'ul';
return (
<ListTag
className={`pl-6 mb-4 ${
style === "ordered" ? "list-decimal" : "list-disc"
}`}
>
<ListTag className={`pl-6 mb-4 ${style === 'ordered' ? 'list-decimal' : 'list-disc'}`}>
{items
.filter((item) => item.content)
.map((item, i) => (
@@ -57,60 +49,44 @@ const renderList = (items, style) => {
/* ---------------- BLOCK RENDERER ---------------- */
const renderBlock = (block, index) => {
switch (block.type) {
case "paragraph":
case 'paragraph':
return (
<p
key={index}
className="mb-4 leading-7 text-gray-800"
dangerouslySetInnerHTML={{__html: block.data.text}}
/>
<p key={index} className="mb-4 leading-7 text-gray-800" dangerouslySetInnerHTML={{ __html: block.data.text }} />
);
case "header":
case 'header':
return (
<h2
key={index}
className="text-2xl font-semibold mb-4"
dangerouslySetInnerHTML={{__html: block.data.text}}
/>
<h2 key={index} className="text-2xl font-semibold mb-4" dangerouslySetInnerHTML={{ __html: block.data.text }} />
);
case "image":
case 'image':
return (
<img
key={index}
src={block.data.file?.url}
alt={block.data.caption || "blog-image"}
alt={block.data.caption || 'blog-image'}
className="w-full rounded-lg mb-4"
/>
);
case "list":
return (
<div key={index}>{renderList(block.data.items, block.data.style)}</div>
);
case 'list':
return <div key={index}>{renderList(block.data.items, block.data.style)}</div>;
case "quote":
case 'quote':
return (
<blockquote
key={index}
className="border-l-4 border-gray-300 pl-4 italic my-4 text-gray-600"
>
<blockquote key={index} className="border-l-4 border-gray-300 pl-4 italic my-4 text-gray-600">
{block.data.text}
</blockquote>
);
case "code":
case 'code':
return (
<pre
key={index}
className="bg-gray-100 p-4 rounded-md overflow-x-auto text-sm mb-4"
>
<pre key={index} className="bg-gray-100 p-4 rounded-md overflow-x-auto text-sm mb-4">
<code>{block.data.code}</code>
</pre>
);
case "table":
case 'table':
return (
<div key={index} className="overflow-x-auto mb-6">
<table className="w-full border border-gray-200">
@@ -133,7 +109,7 @@ const renderBlock = (block, index) => {
</div>
);
case "delimiter":
case 'delimiter':
return <hr key={index} className="my-6 border-gray-300" />;
default:
@@ -143,17 +119,17 @@ const renderBlock = (block, index) => {
/* ---------------- MAIN COMPONENT ---------------- */
const BlogDetail = () => {
const {id} = useParams();
const { id } = useParams();
const navigate = useNavigate();
const [blog, setBlog] = useState(null);
const fetchBlog = async () => {
try {
const res = await getBlogByIdApi(Number(id));
console.log({res});
console.log({ res });
setBlog(res);
} catch (err) {
console.error("Error fetching blog", err);
console.error('Error fetching blog', err);
}
};
@@ -168,11 +144,7 @@ const BlogDetail = () => {
return (
<div className="mx-auto flex flex-col ">
{/* Back Button */}
<Button
variant="ghost"
className="mb-4 w-fit text-black px-0"
onClick={() => navigate(-1)}
>
<Button variant="ghost" className="mb-4 w-fit text-black px-0" onClick={() => navigate(-1)}>
Back
</Button>
@@ -186,17 +158,11 @@ const BlogDetail = () => {
{/* Image (only if exists) */}
{blog.image?.trim() && (
<img
src={blog.image}
alt="blog"
className="w-full h-[220px] md:h-[400px] object-cover rounded-lg mb-6"
/>
<img src={blog.image} alt="blog" className="w-full h-[220px] md:h-[400px] object-cover rounded-lg mb-6" />
)}
{/* Content */}
<div>
{blog.content?.blocks?.map((block, index) => renderBlock(block, index))}
</div>
<div>{blog.content?.blocks?.map((block, index) => renderBlock(block, index))}</div>
</div>
);
};
+46 -75
View File
@@ -1,40 +1,35 @@
import {useEffect, useRef, useState} from "react";
import {useNavigate, useParams} from "react-router-dom";
import {BytescaleUploader} from "@/components/BytescaleUploader/BytescaleUploader";
import EditorJS, {OutputData} from "@editorjs/editorjs";
import Header from "@editorjs/header";
import List from "@editorjs/list";
import ImageTool from "@editorjs/image";
import Quote from "@editorjs/quote";
import Table from "@editorjs/table";
import CodeTool from "@editorjs/code";
import Embed from "@editorjs/embed";
import Delimiter from "@editorjs/delimiter";
import axios from "axios";
import { useEffect, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { BytescaleUploader } from '@/components/BytescaleUploader/BytescaleUploader';
import EditorJS, { OutputData } from '@editorjs/editorjs';
import Header from '@editorjs/header';
import List from '@editorjs/list';
import ImageTool from '@editorjs/image';
import Quote from '@editorjs/quote';
import Table from '@editorjs/table';
import CodeTool from '@editorjs/code';
import Embed from '@editorjs/embed';
import Delimiter from '@editorjs/delimiter';
import axios from 'axios';
import {
createBlogApi,
updateBlogApi,
getBlogByIdApi,
uploadImageApi,
} from "@/api/blog";
import { createBlogApi, updateBlogApi, getBlogByIdApi, uploadImageApi } from '@/api/blog';
import {Card, CardContent, CardHeader, CardTitle} from "@/components/ui/card";
import {Input} from "@/components/ui/input";
import {Button} from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
export default function BlogEditorPage() {
const baseURL = import.meta.env.VITE_API_URL;
const {id} = useParams();
const { id } = useParams();
const navigate = useNavigate();
const editorRef = useRef<EditorJS | null>(null);
const hasInitialized = useRef(false);
const hasRenderedContent = useRef(false);
const [title, setTitle] = useState("");
const [writer, setWriter] = useState("");
const [coverImage, setCoverImage] = useState("");
const [title, setTitle] = useState('');
const [writer, setWriter] = useState('');
const [coverImage, setCoverImage] = useState('');
const [loading, setLoading] = useState(false);
const isEdit = Boolean(id);
@@ -47,16 +42,16 @@ export default function BlogEditorPage() {
const initEditor = async () => {
editor = new EditorJS({
holder: "editorjs",
holder: 'editorjs',
placeholder: "Write blog content...",
placeholder: 'Write blog content...',
tools: {
header: {
class: Header,
inlineToolbar: true,
config: {
placeholder: "Enter heading",
placeholder: 'Enter heading',
levels: [1, 2, 3, 4],
defaultLevel: 2,
},
@@ -66,7 +61,7 @@ export default function BlogEditorPage() {
class: List,
inlineToolbar: true,
config: {
defaultStyle: "unordered",
defaultStyle: 'unordered',
},
},
@@ -82,38 +77,33 @@ export default function BlogEditorPage() {
uploader: {
uploadByFile: async (file: File) => {
if (file.size > 5 * 1024 * 1024) {
alert("File is too large (Max 5MB)");
return {success: 0, file: {url: ""}};
alert('File is too large (Max 5MB)');
return { success: 0, file: { url: '' } };
}
const formData = new FormData();
formData.append("file", file);
formData.append("folderPath", "/blog");
formData.append('file', file);
formData.append('folderPath', '/blog');
try {
const response = await axios.post(
`${baseURL}/upload`,
formData,
{
headers: {
"Content-Type": "multipart/form-data",
},
const response = await axios.post(`${baseURL}/upload`, formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
);
});
return {
success: 1,
file: {url: response.data.fileUrl},
file: { url: response.data.fileUrl },
};
} catch (e: any) {
console.error("EditorJS Image Upload Error:", e);
const errorMessage =
e.response?.data?.error || e.message || "Upload failed";
console.error('EditorJS Image Upload Error:', e);
const errorMessage = e.response?.data?.error || e.message || 'Upload failed';
alert(`Upload Error: ${errorMessage}`);
return {
success: 0,
file: {url: ""},
file: { url: '' },
};
}
},
@@ -132,7 +122,7 @@ export default function BlogEditorPage() {
setTitle(res.title);
setWriter(res.writer);
setCoverImage(res.image || "");
setCoverImage(res.image || '');
if (res.content) {
await editor.blocks.clear();
@@ -170,7 +160,7 @@ export default function BlogEditorPage() {
await createBlogApi(payload);
}
navigate("/blog");
navigate('/blog');
} catch (err) {
console.error(err);
} finally {
@@ -182,47 +172,28 @@ export default function BlogEditorPage() {
<div className="p-6 max-w-5xl mx-auto space-y-6">
<Card>
<CardHeader>
<CardTitle>{isEdit ? "Edit Blog" : "Create Blog"}</CardTitle>
<CardTitle>{isEdit ? 'Edit Blog' : 'Create Blog'}</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<Input
placeholder="Blog Title"
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<Input placeholder="Blog Title" value={title} onChange={(e) => setTitle(e.target.value)} />
<Input
placeholder="Writer Name"
value={writer}
onChange={(e) => setWriter(e.target.value)}
/>
<Input placeholder="Writer Name" value={writer} onChange={(e) => setWriter(e.target.value)} />
<div className="space-y-2">
<label className="text-sm font-medium">Cover Image</label>
<BytescaleUploader
value={coverImage}
folderPath="/blog"
onChange={(url) => setCoverImage(url)}
/>
<BytescaleUploader value={coverImage} folderPath="/blog" onChange={(url) => setCoverImage(url)} />
{coverImage && (
<img
src={coverImage}
alt="cover"
className="w-full max-h-[250px] object-cover rounded-md"
/>
<img src={coverImage} alt="cover" className="w-full max-h-[250px] object-cover rounded-md" />
)}
</div>
<div
id="editorjs"
className="border rounded-md p-4 bg-white min-h-[300px]"
/>
<div id="editorjs" className="border rounded-md p-4 bg-white min-h-[300px]" />
<Button onClick={handleSave} disabled={loading}>
{loading ? "Saving..." : "Save Blog"}
{loading ? 'Saving...' : 'Save Blog'}
</Button>
</CardContent>
</Card>
+61 -137
View File
@@ -1,39 +1,19 @@
import { useState, useEffect, useCallback } from "react";
import { useState, useEffect, useCallback } from 'react';
import { getCareersApi, updateCareerApi, createCareerApi } from "@/api/career";
import { getCareersApi, updateCareerApi, createCareerApi } from '@/api/career';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
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 {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from "@/components/ui/dialog";
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import {
Loader2,
Plus,
Pencil,
RefreshCw,
ChevronLeft,
ChevronRight,
} from "lucide-react";
import { Loader2, Plus, Pencil, RefreshCw, ChevronLeft, ChevronRight } from 'lucide-react';
export default function CareerPage() {
const [careers, setCareers] = useState<any[]>([]);
@@ -42,19 +22,19 @@ export default function CareerPage() {
const [openModal, setOpenModal] = useState(false);
const [editing, setEditing] = useState<any>(null);
const [searchText, setSearchText] = useState("");
const [searchText, setSearchText] = useState('');
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 10;
const [form, setForm] = useState({
post: "",
designation: "",
qualification: "",
experienceNeed: "",
email: "",
number: "",
status: "new",
post: '',
designation: '',
qualification: '',
experienceNeed: '',
email: '',
number: '',
status: 'new',
isActive: true,
sortOrder: 0,
});
@@ -78,7 +58,7 @@ export default function CareerPage() {
const filteredCareers = careers.filter(
(item) =>
item.post?.toLowerCase().includes(searchText.toLowerCase()) ||
item.designation?.toLowerCase().includes(searchText.toLowerCase()),
item.designation?.toLowerCase().includes(searchText.toLowerCase())
);
useEffect(() => {
@@ -102,20 +82,20 @@ export default function CareerPage() {
} as any);
fetchAll();
} catch (error) {
console.error("Failed to toggle status", error);
console.error('Failed to toggle status', error);
}
};
function openAdd() {
setEditing(null);
setForm({
post: "",
designation: "",
qualification: "",
experienceNeed: "",
email: "",
number: "",
status: "new",
post: '',
designation: '',
qualification: '',
experienceNeed: '',
email: '',
number: '',
status: 'new',
isActive: true,
sortOrder: 0,
});
@@ -125,13 +105,13 @@ export default function CareerPage() {
function openEdit(item: any) {
setEditing(item);
setForm({
post: item.post || "",
designation: item.designation || "",
qualification: item.qualification || "",
experienceNeed: item.experienceNeed || "",
email: item.email || "",
number: item.number || "",
status: item.status || "new",
post: item.post || '',
designation: item.designation || '',
qualification: item.qualification || '',
experienceNeed: item.experienceNeed || '',
email: item.email || '',
number: item.number || '',
status: item.status || 'new',
isActive: item.isActive ?? true,
sortOrder: item.sortOrder ?? 0,
});
@@ -166,12 +146,7 @@ export default function CareerPage() {
className="w-[250px] text-base"
/>
<Button
variant="outline"
onClick={fetchAll}
disabled={loading}
className="text-base"
>
<Button variant="outline" onClick={fetchAll} disabled={loading} className="text-base">
<RefreshCw className="mr-2 h-5 w-5" />
Refresh
</Button>
@@ -193,24 +168,12 @@ export default function CareerPage() {
<Table className="w-full min-w-[800px] table-fixed border-separate border-spacing-0">
<TableHeader className="sticky top-0 z-20 bg-background shadow-sm">
<TableRow>
<TableHead className="w-[80px] bg-background font-bold text-sm">
Priority
</TableHead>
<TableHead className="w-[250px] bg-background font-bold text-sm">
Post & Designation
</TableHead>
<TableHead className="w-[200px] bg-background font-bold text-sm">
Qualification
</TableHead>
<TableHead className="w-[120px] bg-background font-bold text-sm">
Experience
</TableHead>
<TableHead className="w-[80px] bg-background font-bold text-sm">
Status (Active)
</TableHead>
<TableHead className="w-[80px] bg-background font-bold text-right text-sm">
Actions
</TableHead>
<TableHead className="w-[80px] bg-background font-bold text-sm">Priority</TableHead>
<TableHead className="w-[250px] bg-background font-bold text-sm">Post & Designation</TableHead>
<TableHead className="w-[200px] bg-background font-bold text-sm">Qualification</TableHead>
<TableHead className="w-[120px] bg-background font-bold text-sm">Experience</TableHead>
<TableHead className="w-[80px] bg-background font-bold text-sm">Status (Active)</TableHead>
<TableHead className="w-[80px] bg-background font-bold text-right text-sm">Actions</TableHead>
</TableRow>
</TableHeader>
@@ -223,58 +186,34 @@ export default function CareerPage() {
</TableRow>
) : currentItems.length === 0 ? (
<TableRow>
<TableCell
colSpan={6}
className="text-center text-muted-foreground py-10 text-base"
>
<TableCell colSpan={6} className="text-center text-muted-foreground py-10 text-base">
No careers found
</TableCell>
</TableRow>
) : (
currentItems.map((item) => (
<TableRow key={item.id} className="hover:bg-muted/50">
<TableCell className="font-mono text-xs">
{item.sortOrder}
<TableCell className="font-mono text-xs">{item.sortOrder}</TableCell>
<TableCell>
<div className="font-semibold text-base truncate">{item.post}</div>
<div className="text-xs text-muted-foreground truncate">{item.designation}</div>
</TableCell>
<TableCell>
<div className="font-semibold text-base truncate">
{item.post}
</div>
<div className="text-xs text-muted-foreground truncate">
{item.designation}
</div>
</TableCell>
<TableCell>
<div className="text-sm line-clamp-2">
{item.qualification}
</div>
</TableCell>
<TableCell className="text-sm">
{item.experienceNeed}
<div className="text-sm line-clamp-2">{item.qualification}</div>
</TableCell>
<TableCell className="text-sm">{item.experienceNeed}</TableCell>
<TableCell>
<div className="flex items-center gap-2">
<Switch
checked={item.isActive}
onCheckedChange={() => handleToggleStatus(item)}
/>
<Badge
variant={item.isActive ? "default" : "secondary"}
className="capitalize"
>
{item.isActive ? "Active" : "Hidden"}
<Switch checked={item.isActive} onCheckedChange={() => handleToggleStatus(item)} />
<Badge variant={item.isActive ? 'default' : 'secondary'} className="capitalize">
{item.isActive ? 'Active' : 'Hidden'}
</Badge>
</div>
</TableCell>
<TableCell className="text-right">
<div className="flex justify-end gap-2">
<Button
size="icon"
variant="ghost"
className="h-9 w-9"
onClick={() => openEdit(item)}
>
<Button size="icon" variant="ghost" className="h-9 w-9" onClick={() => openEdit(item)}>
<Pencil className="h-4 w-4" />
</Button>
</div>
@@ -289,14 +228,9 @@ export default function CareerPage() {
{!loading && filteredCareers.length > 0 && (
<div className="flex items-center justify-between px-2 py-6 border-t">
<div className="text-base text-muted-foreground">
Showing{" "}
<span className="font-semibold">{indexOfFirstItem + 1}</span> to{" "}
<span className="font-semibold">
{Math.min(indexOfLastItem, filteredCareers.length)}
</span>{" "}
of{" "}
<span className="font-semibold">{filteredCareers.length}</span>{" "}
careers
Showing <span className="font-semibold">{indexOfFirstItem + 1}</span> to{' '}
<span className="font-semibold">{Math.min(indexOfLastItem, filteredCareers.length)}</span> of{' '}
<span className="font-semibold">{filteredCareers.length}</span> careers
</div>
<div className="flex items-center gap-6">
<div className="text-base font-semibold">
@@ -307,9 +241,7 @@ export default function CareerPage() {
variant="outline"
size="icon"
className="h-10 w-10"
onClick={() =>
setCurrentPage((prev) => Math.max(prev - 1, 1))
}
onClick={() => setCurrentPage((prev) => Math.max(prev - 1, 1))}
disabled={currentPage === 1}
>
<ChevronLeft className="h-5 w-5" />
@@ -318,9 +250,7 @@ export default function CareerPage() {
variant="outline"
size="icon"
className="h-10 w-10"
onClick={() =>
setCurrentPage((prev) => Math.min(prev + 1, totalPages))
}
onClick={() => setCurrentPage((prev) => Math.min(prev + 1, totalPages))}
disabled={currentPage === totalPages || totalPages === 0}
>
<ChevronRight className="h-5 w-5" />
@@ -335,9 +265,7 @@ export default function CareerPage() {
<Dialog open={openModal} onOpenChange={setOpenModal}>
<DialogContent className="w-full max-w-lg">
<DialogHeader>
<DialogTitle className="text-2xl">
{editing ? "Edit Career" : "Add New Career"}
</DialogTitle>
<DialogTitle className="text-2xl">{editing ? 'Edit Career' : 'Add New Career'}</DialogTitle>
</DialogHeader>
<div className="space-y-4 py-4">
@@ -420,15 +348,11 @@ export default function CareerPage() {
</div>
<DialogFooter className="pt-4 border-t">
<Button
variant="ghost"
onClick={() => setOpenModal(false)}
className="text-base"
>
<Button variant="ghost" onClick={() => setOpenModal(false)} className="text-base">
Cancel
</Button>
<Button onClick={handleSubmit} className="px-8 text-base">
{editing ? "Save Changes" : "Create Career"}
{editing ? 'Save Changes' : 'Create Career'}
</Button>
</DialogFooter>
</DialogContent>
+76 -197
View File
@@ -1,48 +1,23 @@
import {useState, useEffect, useCallback} from "react";
import {AxiosError} from "axios";
import {BytescaleUploader} from "@/components/BytescaleUploader/BytescaleUploader";
import { useState, useEffect, useCallback } from 'react';
import { AxiosError } from 'axios';
import { BytescaleUploader } from '@/components/BytescaleUploader/BytescaleUploader';
import {
getDepartmentsApi,
createDepartmentApi,
updateDepartmentApi,
} from "@/api/department";
import { getDepartmentsApi, createDepartmentApi, updateDepartmentApi } from '@/api/department';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
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 { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from "@/components/ui/dialog";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import {Input} from "@/components/ui/input";
import {Textarea} from "@/components/ui/textarea";
import {Switch} from "@/components/ui/switch";
import {Label} from "@/components/ui/label";
import {Badge} from "@/components/ui/badge";
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import {
Loader2,
RefreshCw,
Plus,
Pencil,
Eye,
ChevronLeft,
ChevronRight,
} from "lucide-react";
import { Loader2, RefreshCw, Plus, Pencil, Eye, ChevronLeft, ChevronRight } from 'lucide-react';
interface Department {
departmentId: string;
@@ -60,7 +35,7 @@ interface Department {
export default function DepartmentPage() {
const [departments, setDepartments] = useState<Department[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const [error, setError] = useState('');
const [openModal, setOpenModal] = useState(false);
const [editing, setEditing] = useState<Department | null>(null);
@@ -68,36 +43,36 @@ export default function DepartmentPage() {
const [viewOpen, setViewOpen] = useState(false);
const [viewData, setViewData] = useState<Department | null>(null);
const [searchText, setSearchText] = useState("");
const [searchText, setSearchText] = useState('');
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 10;
const [form, setForm] = useState<Department>({
departmentId: "",
name: "",
image: "",
para1: "",
para2: "",
para3: "",
facilities: "",
services: "",
departmentId: '',
name: '',
image: '',
para1: '',
para2: '',
para3: '',
facilities: '',
services: '',
isActive: true,
sortOrder: 0,
});
const fetchDepartments = useCallback(async () => {
setLoading(true);
setError("");
setError('');
try {
const res = await getDepartmentsApi();
setDepartments(res?.data || []);
} catch (err) {
if (err instanceof AxiosError) {
setError(err.response?.data?.message || "Failed to load departments");
setError(err.response?.data?.message || 'Failed to load departments');
} else {
setError("Something went wrong");
setError('Something went wrong');
}
} finally {
setLoading(false);
@@ -111,7 +86,7 @@ export default function DepartmentPage() {
const filteredDepartments = departments.filter(
(dep) =>
dep.name.toLowerCase().includes(searchText.toLowerCase()) ||
dep.departmentId.toLowerCase().includes(searchText.toLowerCase()),
dep.departmentId.toLowerCase().includes(searchText.toLowerCase())
);
useEffect(() => {
@@ -121,41 +96,37 @@ export default function DepartmentPage() {
const totalPages = Math.ceil(filteredDepartments.length / itemsPerPage);
const indexOfLastItem = currentPage * itemsPerPage;
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
const currentItems = filteredDepartments.slice(
indexOfFirstItem,
indexOfLastItem,
);
const currentItems = filteredDepartments.slice(indexOfFirstItem, indexOfLastItem);
function handleChange(e: any) {
const value =
e.target.type === "number" ? Number(e.target.value) : e.target.value;
setForm({...form, [e.target.name]: value});
const value = e.target.type === 'number' ? Number(e.target.value) : e.target.value;
setForm({ ...form, [e.target.name]: value });
}
const handleToggleStatus = async (dep: Department) => {
try {
const {departmentId, ...updateData} = dep;
const { departmentId, ...updateData } = dep;
await updateDepartmentApi(departmentId, {
...updateData,
isActive: !dep.isActive,
} as any);
fetchDepartments();
} catch (error) {
console.error("Failed to toggle status", error);
console.error('Failed to toggle status', error);
}
};
function openAdd() {
setEditing(null);
setForm({
departmentId: "",
name: "",
image: "",
para1: "",
para2: "",
para3: "",
facilities: "",
services: "",
departmentId: '',
name: '',
image: '',
para1: '',
para2: '',
para3: '',
facilities: '',
services: '',
isActive: true,
sortOrder: 0,
});
@@ -180,7 +151,7 @@ export default function DepartmentPage() {
async function handleSubmit() {
try {
if (editing) {
const {departmentId, ...updateData} = form;
const { departmentId, ...updateData } = form;
await updateDepartmentApi(editing.departmentId, form as any);
} else {
await createDepartmentApi(form);
@@ -206,12 +177,7 @@ export default function DepartmentPage() {
className="w-[250px] text-base"
/>
<Button
variant="outline"
onClick={fetchDepartments}
disabled={loading}
className="text-base"
>
<Button variant="outline" onClick={fetchDepartments} disabled={loading} className="text-base">
<RefreshCw className="mr-2 h-5 w-5" />
Refresh
</Button>
@@ -223,11 +189,7 @@ export default function DepartmentPage() {
</div>
</div>
{error && (
<div className="p-4 text-red-600 bg-red-50 border rounded-md text-base">
{error}
</div>
)}
{error && <div className="p-4 text-red-600 bg-red-50 border rounded-md text-base">{error}</div>}
<Card>
<CardHeader>
@@ -239,18 +201,10 @@ export default function DepartmentPage() {
<Table className="w-full min-w-[700px] table-fixed border-separate border-spacing-0">
<TableHeader className="sticky top-0 z-20 bg-background shadow-sm">
<TableRow>
<TableHead className="w-[100px] bg-background text-sm font-bold">
Priority
</TableHead>
<TableHead className="w-[300px] bg-background text-sm font-bold">
Name
</TableHead>
<TableHead className="w-[80px] bg-background text-sm font-bold">
Status (Active)
</TableHead>
<TableHead className="w-[80px] bg-background text-right text-sm font-bold">
Actions
</TableHead>
<TableHead className="w-[100px] bg-background text-sm font-bold">Priority</TableHead>
<TableHead className="w-[300px] bg-background text-sm font-bold">Name</TableHead>
<TableHead className="w-[80px] bg-background text-sm font-bold">Status (Active)</TableHead>
<TableHead className="w-[80px] bg-background text-right text-sm font-bold">Actions</TableHead>
</TableRow>
</TableHeader>
@@ -263,65 +217,37 @@ export default function DepartmentPage() {
</TableRow>
) : currentItems.length === 0 ? (
<TableRow>
<TableCell
colSpan={4}
className="text-center text-muted-foreground py-10 text-base"
>
<TableCell colSpan={4} className="text-center text-muted-foreground py-10 text-base">
No departments found
</TableCell>
</TableRow>
) : (
currentItems.map((dep) => (
<TableRow
key={dep.departmentId}
className="hover:bg-muted/50"
>
<TableCell className="font-mono text-sm">
{dep.sortOrder}
</TableCell>
<TableRow key={dep.departmentId} className="hover:bg-muted/50">
<TableCell className="font-mono text-sm">{dep.sortOrder}</TableCell>
<TableCell>
<div
className="font-semibold text-base truncate"
title={dep.name}
>
<div className="font-semibold text-base truncate" title={dep.name}>
{dep.name}
</div>
<div className="text-xs text-muted-foreground">
{dep.departmentId}
</div>
<div className="text-xs text-muted-foreground">{dep.departmentId}</div>
</TableCell>
<TableCell>
<div className="flex items-center gap-2">
<Switch
checked={dep.isActive}
onCheckedChange={() => handleToggleStatus(dep)}
/>
<Badge
variant={dep.isActive ? "default" : "secondary"}
>
{dep.isActive ? "Active" : "Hidden"}
<Switch checked={dep.isActive} onCheckedChange={() => handleToggleStatus(dep)} />
<Badge variant={dep.isActive ? 'default' : 'secondary'}>
{dep.isActive ? 'Active' : 'Hidden'}
</Badge>
</div>
</TableCell>
<TableCell className="text-right">
<div className="flex justify-end gap-2">
<Button
size="icon"
variant="ghost"
className="h-9 w-9"
onClick={() => openView(dep)}
>
<Button size="icon" variant="ghost" className="h-9 w-9" onClick={() => openView(dep)}>
<Eye className="h-4 w-4" />
</Button>
<Button
size="icon"
variant="ghost"
className="h-9 w-9"
onClick={() => openEdit(dep)}
>
<Button size="icon" variant="ghost" className="h-9 w-9" onClick={() => openEdit(dep)}>
<Pencil className="h-4 w-4" />
</Button>
</div>
@@ -336,16 +262,9 @@ export default function DepartmentPage() {
{!loading && filteredDepartments.length > 0 && (
<div className="flex items-center justify-between px-2 py-6 border-t">
<div className="text-base text-muted-foreground">
Showing{" "}
<span className="font-semibold">{indexOfFirstItem + 1}</span> to{" "}
<span className="font-semibold">
{Math.min(indexOfLastItem, filteredDepartments.length)}
</span>{" "}
of{" "}
<span className="font-semibold">
{filteredDepartments.length}
</span>{" "}
departments
Showing <span className="font-semibold">{indexOfFirstItem + 1}</span> to{' '}
<span className="font-semibold">{Math.min(indexOfLastItem, filteredDepartments.length)}</span> of{' '}
<span className="font-semibold">{filteredDepartments.length}</span> departments
</div>
<div className="flex items-center gap-6">
<div className="text-base font-semibold">
@@ -356,9 +275,7 @@ export default function DepartmentPage() {
variant="outline"
size="icon"
className="h-10 w-10"
onClick={() =>
setCurrentPage((prev) => Math.max(prev - 1, 1))
}
onClick={() => setCurrentPage((prev) => Math.max(prev - 1, 1))}
disabled={currentPage === 1}
>
<ChevronLeft className="h-5 w-5" />
@@ -367,9 +284,7 @@ export default function DepartmentPage() {
variant="outline"
size="icon"
className="h-10 w-10"
onClick={() =>
setCurrentPage((prev) => Math.min(prev + 1, totalPages))
}
onClick={() => setCurrentPage((prev) => Math.min(prev + 1, totalPages))}
disabled={currentPage === totalPages || totalPages === 0}
>
<ChevronRight className="h-5 w-5" />
@@ -384,9 +299,7 @@ export default function DepartmentPage() {
<Dialog open={openModal} onOpenChange={setOpenModal}>
<DialogContent className="w-full !max-w-5xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>
{editing ? "Edit Department" : "Add Department"}
</DialogTitle>
<DialogTitle>{editing ? 'Edit Department' : 'Add Department'}</DialogTitle>
</DialogHeader>
<div className="space-y-4">
@@ -395,7 +308,7 @@ export default function DepartmentPage() {
<BytescaleUploader
value={form.image}
folderPath="/departments"
onChange={(url) => setForm({...form, image: url})}
onChange={(url) => setForm({ ...form, image: url })}
/>
</div>
<Input
@@ -406,43 +319,13 @@ export default function DepartmentPage() {
placeholder="Department ID"
/>
<Input
name="name"
value={form.name}
onChange={handleChange}
placeholder="Department Name"
/>
<Input name="name" value={form.name} onChange={handleChange} placeholder="Department Name" />
<Textarea
name="para1"
value={form.para1}
onChange={handleChange}
placeholder="Para1"
/>
<Textarea
name="para2"
value={form.para2}
onChange={handleChange}
placeholder="Para2"
/>
<Textarea
name="para3"
value={form.para3}
onChange={handleChange}
placeholder="Para3"
/>
<Textarea
name="facilities"
value={form.facilities}
onChange={handleChange}
placeholder="Facilities"
/>
<Textarea
name="services"
value={form.services}
onChange={handleChange}
placeholder="Services"
/>
<Textarea name="para1" value={form.para1} onChange={handleChange} placeholder="Para1" />
<Textarea name="para2" value={form.para2} onChange={handleChange} placeholder="Para2" />
<Textarea name="para3" value={form.para3} onChange={handleChange} placeholder="Para3" />
<Textarea name="facilities" value={form.facilities} onChange={handleChange} placeholder="Facilities" />
<Textarea name="services" value={form.services} onChange={handleChange} placeholder="Services" />
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 border-t pt-4">
<div className="flex items-center justify-between p-3 border rounded-md">
@@ -452,13 +335,11 @@ export default function DepartmentPage() {
<Switch
id="isActive"
checked={form.isActive}
onCheckedChange={(val) => setForm({...form, isActive: val})}
onCheckedChange={(val) => setForm({ ...form, isActive: val })}
/>
</div>
<div className="space-y-1">
<Label htmlFor="sortOrder">
Sort Priority (Lower numbers show first)
</Label>
<Label htmlFor="sortOrder">Sort Priority (Lower numbers show first)</Label>
<Input
id="sortOrder"
name="sortOrder"
@@ -475,9 +356,7 @@ export default function DepartmentPage() {
<Button variant="outline" onClick={() => setOpenModal(false)}>
Cancel
</Button>
<Button onClick={handleSubmit}>
{editing ? "Save Changes" : "Create"}
</Button>
<Button onClick={handleSubmit}>{editing ? 'Save Changes' : 'Create'}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
@@ -490,8 +369,8 @@ export default function DepartmentPage() {
{viewData && (
<div className="space-y-4 text-sm">
<div className="flex gap-4 items-center border-b pb-4">
<Badge variant={viewData.isActive ? "default" : "secondary"}>
{viewData.isActive ? "ACTIVE" : "HIDDEN"}
<Badge variant={viewData.isActive ? 'default' : 'secondary'}>
{viewData.isActive ? 'ACTIVE' : 'HIDDEN'}
</Badge>
<p>
<b>Sort Order:</b> {viewData.sortOrder}
File diff suppressed because it is too large Load Diff
+127 -293
View File
@@ -1,6 +1,6 @@
import { useState, useEffect, useCallback, useMemo } from "react";
import toast from "react-hot-toast";
import { AxiosError } from "axios";
import { useState, useEffect, useCallback, useMemo } from 'react';
import toast from 'react-hot-toast';
import { AxiosError } from 'axios';
import {
getHealthPackagesApi,
@@ -11,52 +11,30 @@ import {
updateCategoryApi,
HealthPackage,
HealthCategory,
} from "@/api/healthCheck";
} from '@/api/healthCheck';
import PackageInquiriesTab from "@/components/PackageInquiriesTab/PackageInquiriesTab";
import HealthPackageModal from "@/components/HealthPackageModal/HealthPackageModal";
import SeoPreview from "@/components/SeoPreview/SeoPreview";
import PackageInquiriesTab from '@/components/PackageInquiriesTab/PackageInquiriesTab';
import HealthPackageModal from '@/components/HealthPackageModal/HealthPackageModal';
import SeoPreview from '@/components/SeoPreview/SeoPreview';
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 {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
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 { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
Loader2,
RefreshCw,
Plus,
Pencil,
ChevronLeft,
ChevronRight,
LayoutGrid,
Eye,
} from "lucide-react";
import { Loader2, RefreshCw, Plus, Pencil, ChevronLeft, ChevronRight, LayoutGrid, Eye } from 'lucide-react';
export default function HealthPackagePage() {
const WEBSITE_URL = import.meta.env.VITE_WEBSITE_URL;
const [packages, setPackages] = useState<HealthPackage[]>([]);
const [categories, setCategories] = useState<HealthCategory[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const [error, setError] = useState('');
// Modals
const [packageModal, setPackageModal] = useState(false);
@@ -64,68 +42,57 @@ export default function HealthPackagePage() {
const [viewModal, setViewModal] = useState(false);
// States
const [selectedPackage, setSelectedPackage] = useState<HealthPackage | null>(
null,
);
const [editingPackage, setEditingPackage] = useState<HealthPackage | null>(
null,
);
const [editingCategory, setEditingCategory] = useState<HealthCategory | null>(
null,
);
const [selectedPackage, setSelectedPackage] = useState<HealthPackage | null>(null);
const [editingPackage, setEditingPackage] = useState<HealthPackage | null>(null);
const [editingCategory, setEditingCategory] = useState<HealthCategory | null>(null);
// Filters & Pagination
const [searchText, setSearchText] = useState("");
const [filterCategory, setFilterCategory] = useState("");
const [searchText, setSearchText] = useState('');
const [filterCategory, setFilterCategory] = useState('');
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 10;
// Forms
const [pkgForm, setPkgForm] = useState<Partial<HealthPackage>>({
name: "",
slug: "",
description: "",
image: "",
name: '',
slug: '',
description: '',
image: '',
price: undefined,
discountedPrice: undefined,
categoryId: 0,
isActive: true,
sortOrder: 1000,
seo: {
seoTitle: "",
metaDescription: "",
focusKeyphrase: "",
seoTitle: '',
metaDescription: '',
focusKeyphrase: '',
tags: [],
ogTitle: "",
ogDescription: "",
ogImage: "",
ogTitle: '',
ogDescription: '',
ogImage: '',
},
});
const [inclusionsList, setInclusionsList] = useState([
{ id: Date.now(), category: "", items: "" },
]);
const [inclusionsList, setInclusionsList] = useState([{ id: Date.now(), category: '', items: '' }]);
const [catForm, setCatForm] = useState({
name: "",
slug: "",
name: '',
slug: '',
sortOrder: 1000,
isActive: true,
});
const fetchData = useCallback(async () => {
setLoading(true);
setError("");
setError('');
try {
const [p, c] = await Promise.all([
getHealthPackagesApi(),
getHealthCategoriesApi(),
]);
const [p, c] = await Promise.all([getHealthPackagesApi(), getHealthCategoriesApi()]);
setPackages(p.data || []);
setCategories(c.data || []);
} catch (err) {
if (err instanceof AxiosError) {
setError(err.response?.data?.message || "Failed to load data");
setError(err.response?.data?.message || 'Failed to load data');
} else {
setError("Something went wrong");
setError('Something went wrong');
}
} finally {
setLoading(false);
@@ -142,9 +109,7 @@ export default function HealthPackagePage() {
const matchesSearch =
pkg.name.toLowerCase().includes(searchText.toLowerCase()) ||
pkg.category?.name.toLowerCase().includes(searchText.toLowerCase());
const matchesCat = filterCategory
? pkg.categoryId === Number(filterCategory)
: true;
const matchesCat = filterCategory ? pkg.categoryId === Number(filterCategory) : true;
return matchesSearch && matchesCat;
});
}, [packages, searchText, filterCategory]);
@@ -156,71 +121,64 @@ export default function HealthPackagePage() {
const totalPages = Math.ceil(filteredPackages.length / itemsPerPage);
const indexOfLastItem = currentPage * itemsPerPage;
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
const currentItems = filteredPackages.slice(
indexOfFirstItem,
indexOfLastItem,
);
const currentItems = filteredPackages.slice(indexOfFirstItem, indexOfLastItem);
// --- Actions ---
const handleToggleStatus = async (pkg: HealthPackage) => {
if (!pkg.id) return;
try {
await updateHealthPackageApi(pkg.id, { isActive: !pkg.isActive });
toast.success(`Package ${pkg.isActive ? "hidden" : "activated"}`);
toast.success(`Package ${pkg.isActive ? 'hidden' : 'activated'}`);
fetchData();
} catch (err) {
console.error("Failed to update status", err);
toast.error("Failed to update status");
console.error('Failed to update status', err);
toast.error('Failed to update status');
}
};
const handleToggleCategoryStatus = async (cat: HealthCategory) => {
if (!cat.id) return;
try {
if (cat.isActive) {
const proceed = window.confirm(
"Hiding this category will also hide all packages inside it. Proceed?",
);
const proceed = window.confirm('Hiding this category will also hide all packages inside it. Proceed?');
if (!proceed) return;
}
await updateCategoryApi(cat.id, { isActive: !cat.isActive });
toast.success(`Category ${cat.isActive ? "hidden" : "activated"}`);
toast.success(`Category ${cat.isActive ? 'hidden' : 'activated'}`);
fetchData();
} catch (err) {
console.error("Failed to update category status", err);
toast.error("Failed to update category status");
console.error('Failed to update category status', err);
toast.error('Failed to update category status');
}
};
const openAddPackage = () => {
if (categories.length === 0) {
toast.error(
"Please create at least one category before attempting to add a health package.",
);
toast.error('Please create at least one category before attempting to add a health package.');
return;
}
setEditingPackage(null);
setPkgForm({
name: "",
slug: "",
description: "",
image: "",
name: '',
slug: '',
description: '',
image: '',
price: undefined,
discountedPrice: undefined,
categoryId: categories[0]?.id || 0,
isActive: true,
sortOrder: 1000,
seo: {
seoTitle: "",
metaDescription: "",
focusKeyphrase: "",
seoTitle: '',
metaDescription: '',
focusKeyphrase: '',
tags: [],
ogTitle: "",
ogDescription: "",
ogImage: "",
ogTitle: '',
ogDescription: '',
ogImage: '',
},
});
setInclusionsList([{ id: Date.now(), category: "", items: "" }]);
setInclusionsList([{ id: Date.now(), category: '', items: '' }]);
setPackageModal(true);
};
@@ -228,46 +186,30 @@ export default function HealthPackagePage() {
setEditingPackage(pkg);
setPkgForm(pkg);
if (
pkg.inclusions &&
typeof pkg.inclusions === "object" &&
!Array.isArray(pkg.inclusions)
) {
const formattedList = Object.entries(pkg.inclusions).map(
([cat, items], idx) => ({
id: Date.now() + idx,
category: cat,
items: (items as string[]).join(", "),
}),
);
setInclusionsList(
formattedList.length
? formattedList
: [{ id: Date.now(), category: "", items: "" }],
);
if (pkg.inclusions && typeof pkg.inclusions === 'object' && !Array.isArray(pkg.inclusions)) {
const formattedList = Object.entries(pkg.inclusions).map(([cat, items], idx) => ({
id: Date.now() + idx,
category: cat,
items: (items as string[]).join(', '),
}));
setInclusionsList(formattedList.length ? formattedList : [{ id: Date.now(), category: '', items: '' }]);
} else {
setInclusionsList([{ id: Date.now(), category: "", items: "" }]);
setInclusionsList([{ id: Date.now(), category: '', items: '' }]);
}
setPackageModal(true);
};
const savePackage = async () => {
if (!pkgForm.image) return toast.error("Package image is required.");
if (!pkgForm.name?.trim()) return toast.error("Package Name is required.");
if (!pkgForm.slug?.trim()) return toast.error("URL Slug is required.");
if (!pkgForm.categoryId)
return toast.error("Please select a valid category.");
if (!pkgForm.description?.trim())
return toast.error("Description is required.");
if (!pkgForm.image) return toast.error('Package image is required.');
if (!pkgForm.name?.trim()) return toast.error('Package Name is required.');
if (!pkgForm.slug?.trim()) return toast.error('URL Slug is required.');
if (!pkgForm.categoryId) return toast.error('Please select a valid category.');
if (!pkgForm.description?.trim()) return toast.error('Description is required.');
const structureFilled = inclusionsList.some(
(item) => item.category.trim() !== "" && item.items.trim() !== "",
);
const structureFilled = inclusionsList.some((item) => item.category.trim() !== '' && item.items.trim() !== '');
if (!structureFilled) {
return toast.error(
"Please provide at least one valid Category Group with tests inside it.",
);
return toast.error('Please provide at least one valid Category Group with tests inside it.');
}
try {
@@ -276,7 +218,7 @@ export default function HealthPackagePage() {
const catName = entry.category.trim();
if (catName) {
parsedInclusions[catName] = entry.items
.split(",")
.split(',')
.map((i) => i.trim())
.filter(Boolean);
}
@@ -287,14 +229,10 @@ export default function HealthPackagePage() {
inclusions: parsedInclusions,
};
finalData.price =
finalData.price !== undefined && finalData.price !== null
? Number(finalData.price)
: null;
finalData.price = finalData.price !== undefined && finalData.price !== null ? Number(finalData.price) : null;
finalData.discountedPrice =
finalData.discountedPrice !== undefined &&
finalData.discountedPrice !== null
finalData.discountedPrice !== undefined && finalData.discountedPrice !== null
? Number(finalData.discountedPrice)
: null;
@@ -302,9 +240,7 @@ export default function HealthPackagePage() {
const changedFields: Record<string, any> = {};
Object.keys(finalData).forEach((key) => {
const k = key as keyof HealthPackage;
if (
JSON.stringify(finalData[k]) !== JSON.stringify(editingPackage[k])
) {
if (JSON.stringify(finalData[k]) !== JSON.stringify(editingPackage[k])) {
changedFields[k] = finalData[k];
}
});
@@ -326,14 +262,12 @@ export default function HealthPackagePage() {
fetchData();
} catch (err) {
console.error(err);
toast.error(
"An unexpected system error occurred while trying to save the package.",
);
toast.error('An unexpected system error occurred while trying to save the package.');
}
};
const saveCategory = async () => {
if (!catForm.name?.trim()) return toast.error("Category Name is required.");
if (!catForm.name?.trim()) return toast.error('Category Name is required.');
try {
if (editingCategory?.id) {
@@ -354,10 +288,7 @@ export default function HealthPackagePage() {
return;
}
await updateCategoryApi(
editingCategory.id,
changedFields as Partial<HealthCategory>,
);
await updateCategoryApi(editingCategory.id, changedFields as Partial<HealthCategory>);
} else {
await createCategoryApi(catForm as any);
}
@@ -366,7 +297,7 @@ export default function HealthPackagePage() {
fetchData();
} catch (err) {
console.error(err);
toast.error("An error occurred while saving the category.");
toast.error('An error occurred while saving the category.');
}
};
@@ -398,12 +329,7 @@ export default function HealthPackagePage() {
))}
</select>
<Button
variant="outline"
onClick={fetchData}
disabled={loading}
className="text-base"
>
<Button variant="outline" onClick={fetchData} disabled={loading} className="text-base">
<RefreshCw className="mr-2 h-5 w-5" />
Refresh
</Button>
@@ -415,11 +341,7 @@ export default function HealthPackagePage() {
</div>
</div>
{error && (
<div className="p-4 text-red-600 bg-red-50 border rounded-md text-base">
{error}
</div>
)}
{error && <div className="p-4 text-red-600 bg-red-50 border rounded-md text-base">{error}</div>}
<Tabs defaultValue="packages" className="w-full">
<TabsList className="mb-4">
@@ -439,24 +361,12 @@ export default function HealthPackagePage() {
<Table className="w-full min-w-[1000px] table-fixed border-separate border-spacing-0">
<TableHeader className="sticky top-0 z-20 bg-background shadow-sm">
<TableRow>
<TableHead className="w-[80px] bg-background text-sm font-bold">
Priority
</TableHead>
<TableHead className="w-[250px] bg-background text-sm font-bold">
Package Details
</TableHead>
<TableHead className="w-[150px] bg-background text-sm font-bold">
Category
</TableHead>
<TableHead className="w-[150px] bg-background text-sm font-bold">
Pricing
</TableHead>
<TableHead className="w-[120px] bg-background text-sm font-bold">
Status
</TableHead>
<TableHead className="w-[120px] bg-background text-right text-sm font-bold">
Actions
</TableHead>
<TableHead className="w-[80px] bg-background text-sm font-bold">Priority</TableHead>
<TableHead className="w-[250px] bg-background text-sm font-bold">Package Details</TableHead>
<TableHead className="w-[150px] bg-background text-sm font-bold">Category</TableHead>
<TableHead className="w-[150px] bg-background text-sm font-bold">Pricing</TableHead>
<TableHead className="w-[120px] bg-background text-sm font-bold">Status</TableHead>
<TableHead className="w-[120px] bg-background text-right text-sm font-bold">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -468,29 +378,19 @@ export default function HealthPackagePage() {
</TableRow>
) : currentItems.length === 0 ? (
<TableRow>
<TableCell
colSpan={6}
className="text-center text-muted-foreground py-10 text-base"
>
<TableCell colSpan={6} className="text-center text-muted-foreground py-10 text-base">
No packages found
</TableCell>
</TableRow>
) : (
currentItems.map((pkg) => (
<TableRow key={pkg.id} className="hover:bg-muted/50">
<TableCell className="font-mono text-sm">
{pkg.sortOrder}
</TableCell>
<TableCell className="font-mono text-sm">{pkg.sortOrder}</TableCell>
<TableCell>
<div
className="font-semibold text-base truncate"
title={pkg.name}
>
<div className="font-semibold text-base truncate" title={pkg.name}>
{pkg.name}
</div>
<div className="text-xs text-muted-foreground truncate font-mono mt-0.5">
/{pkg.slug}
</div>
<div className="text-xs text-muted-foreground truncate font-mono mt-0.5">/{pkg.slug}</div>
</TableCell>
<TableCell>
<Badge variant="secondary" className="text-xs">
@@ -503,27 +403,18 @@ export default function HealthPackagePage() {
? `${pkg.discountedPrice}`
: pkg.price != null
? `${pkg.price}`
: "Not Entered"}
: 'Not Entered'}
</div>
{pkg.discountedPrice != null &&
pkg.price != null &&
pkg.discountedPrice < pkg.price && (
<div className="text-xs text-muted-foreground line-through">
{pkg.price}
</div>
)}
{pkg.discountedPrice != null && pkg.price != null && pkg.discountedPrice < pkg.price && (
<div className="text-xs text-muted-foreground line-through">{pkg.price}</div>
)}
</TableCell>
<TableCell>
<div className="flex items-center gap-2">
<Switch
checked={pkg.isActive}
onCheckedChange={() => handleToggleStatus(pkg)}
/>
<Badge
variant={pkg.isActive ? "default" : "secondary"}
>
{pkg.isActive ? "Active" : "Hidden"}
<Switch checked={pkg.isActive} onCheckedChange={() => handleToggleStatus(pkg)} />
<Badge variant={pkg.isActive ? 'default' : 'secondary'}>
{pkg.isActive ? 'Active' : 'Hidden'}
</Badge>
</div>
</TableCell>
@@ -560,19 +451,9 @@ export default function HealthPackagePage() {
{!loading && filteredPackages.length > 0 && (
<div className="flex items-center justify-between px-2 py-6 border-t">
<div className="text-base text-muted-foreground">
Showing{" "}
<span className="font-semibold">
{indexOfFirstItem + 1}
</span>{" "}
to{" "}
<span className="font-semibold">
{Math.min(indexOfLastItem, filteredPackages.length)}
</span>{" "}
of{" "}
<span className="font-semibold">
{filteredPackages.length}
</span>{" "}
packages
Showing <span className="font-semibold">{indexOfFirstItem + 1}</span> to{' '}
<span className="font-semibold">{Math.min(indexOfLastItem, filteredPackages.length)}</span> of{' '}
<span className="font-semibold">{filteredPackages.length}</span> packages
</div>
<div className="flex items-center gap-6">
<div className="text-base font-semibold">
@@ -583,9 +464,7 @@ export default function HealthPackagePage() {
variant="outline"
size="icon"
className="h-10 w-10"
onClick={() =>
setCurrentPage((prev) => Math.max(prev - 1, 1))
}
onClick={() => setCurrentPage((prev) => Math.max(prev - 1, 1))}
disabled={currentPage === 1}
>
<ChevronLeft className="h-5 w-5" />
@@ -594,14 +473,8 @@ export default function HealthPackagePage() {
variant="outline"
size="icon"
className="h-10 w-10"
onClick={() =>
setCurrentPage((prev) =>
Math.min(prev + 1, totalPages),
)
}
disabled={
currentPage === totalPages || totalPages === 0
}
onClick={() => setCurrentPage((prev) => Math.min(prev + 1, totalPages))}
disabled={currentPage === totalPages || totalPages === 0}
>
<ChevronRight className="h-5 w-5" />
</Button>
@@ -623,8 +496,8 @@ export default function HealthPackagePage() {
onClick={() => {
setEditingCategory(null);
setCatForm({
name: "",
slug: "",
name: '',
slug: '',
sortOrder: 1000,
isActive: true,
});
@@ -639,42 +512,23 @@ export default function HealthPackagePage() {
<Table className="w-full table-fixed border-separate border-spacing-0">
<TableHeader className="sticky top-0 z-20 bg-background shadow-sm">
<TableRow>
<TableHead className="w-[100px] bg-background text-sm font-bold">
Priority
</TableHead>
<TableHead className="bg-background text-sm font-bold">
Category Name
</TableHead>
<TableHead className="w-[100px] bg-background text-sm font-bold">
Status
</TableHead>
<TableHead className="w-[100px] bg-background text-right text-sm font-bold">
Actions
</TableHead>
<TableHead className="w-[100px] bg-background text-sm font-bold">Priority</TableHead>
<TableHead className="bg-background text-sm font-bold">Category Name</TableHead>
<TableHead className="w-[100px] bg-background text-sm font-bold">Status</TableHead>
<TableHead className="w-[100px] bg-background text-right text-sm font-bold">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{categories.map((cat) => (
<TableRow key={cat.id} className="hover:bg-muted/50">
<TableCell className="font-mono text-sm">
{cat.sortOrder}
</TableCell>
<TableCell className="font-semibold text-base">
{cat.name}
</TableCell>
<TableCell className="font-mono text-sm">{cat.sortOrder}</TableCell>
<TableCell className="font-semibold text-base">{cat.name}</TableCell>
<TableCell>
<div className="flex items-center gap-2">
<Switch
checked={cat.isActive}
onCheckedChange={() =>
handleToggleCategoryStatus(cat)
}
/>
<Badge
variant={cat.isActive ? "default" : "secondary"}
>
{cat.isActive ? "Active" : "Hidden"}
<Switch checked={cat.isActive} onCheckedChange={() => handleToggleCategoryStatus(cat)} />
<Badge variant={cat.isActive ? 'default' : 'secondary'}>
{cat.isActive ? 'Active' : 'Hidden'}
</Badge>
</div>
</TableCell>
@@ -724,18 +578,14 @@ export default function HealthPackagePage() {
<Dialog open={categoryModal} onOpenChange={setCategoryModal}>
<DialogContent className="w-full !max-w-2xl flex flex-col p-0 overflow-hidden">
<DialogHeader className="p-6 border-b">
<DialogTitle>
{editingCategory ? "Edit Category" : "Add Category"}
</DialogTitle>
<DialogTitle>{editingCategory ? 'Edit Category' : 'Add Category'}</DialogTitle>
</DialogHeader>
<div className="p-6 space-y-4">
<div className="space-y-1">
<Label className="text-sm font-semibold">Category Name</Label>
<Input
value={catForm.name}
onChange={(e) =>
setCatForm({ ...catForm, name: e.target.value })
}
onChange={(e) => setCatForm({ ...catForm, name: e.target.value })}
className="text-base"
/>
</div>
@@ -745,41 +595,25 @@ export default function HealthPackagePage() {
<Input
type="number"
value={catForm.sortOrder}
onChange={(e) =>
setCatForm({ ...catForm, sortOrder: Number(e.target.value) })
}
onChange={(e) => setCatForm({ ...catForm, sortOrder: Number(e.target.value) })}
className="text-base"
/>
</div>
<div className="flex items-center justify-between p-3 border rounded-md bg-muted/30 mb-2">
<Label className="text-base font-semibold cursor-pointer">
Active Visibility
</Label>
<Switch
checked={catForm.isActive}
onCheckedChange={(val) =>
setCatForm({ ...catForm, isActive: val })
}
/>
<Label className="text-base font-semibold cursor-pointer">Active Visibility</Label>
<Switch checked={catForm.isActive} onCheckedChange={(val) => setCatForm({ ...catForm, isActive: val })} />
</div>
</div>
<DialogFooter className="p-6 border-t">
<Button variant="ghost" onClick={() => setCategoryModal(false)}>
Cancel
</Button>
<Button onClick={saveCategory}>
{editingCategory ? "Save Category" : "Create Category"}
</Button>
<Button onClick={saveCategory}>{editingCategory ? 'Save Category' : 'Create Category'}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<SeoPreview
open={viewModal}
onOpenChange={setViewModal}
previewData={selectedPackage}
url={previewUrl}
/>
<SeoPreview open={viewModal} onOpenChange={setViewModal} previewData={selectedPackage} url={previewUrl} />
</div>
);
}
+58 -62
View File
@@ -1,6 +1,6 @@
import React, { useState, ChangeEvent } from "react";
import * as XLSX from "xlsx";
import apiClient from "@/api/client";
import React, { useState, ChangeEvent } from 'react';
import * as XLSX from 'xlsx';
import apiClient from '@/api/client';
interface ImportPayload {
departments: any[];
@@ -16,58 +16,56 @@ interface ImportPayload {
const ImportData: React.FC = () => {
const [loading, setLoading] = useState<boolean>(false);
const [status, setStatus] = useState<string>("");
const [status, setStatus] = useState<string>('');
const handleFileUpload = (e: ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setLoading(true);
setStatus("Reading Excel file...");
setStatus('Reading Excel file...');
const reader = new FileReader();
reader.onload = async (evt: ProgressEvent<FileReader>) => {
try {
const bstr = evt.target?.result;
if (!bstr) throw new Error("Failed to read file content.");
if (!bstr) throw new Error('Failed to read file content.');
const wb = XLSX.read(bstr, { type: "binary" });
const wb = XLSX.read(bstr, { type: 'binary' });
const payload: ImportPayload = {
departments: XLSX.utils.sheet_to_json(wb.Sheets["Departments"]) || [],
doctors: XLSX.utils.sheet_to_json(wb.Sheets["Doctors"]) || [],
timings: XLSX.utils.sheet_to_json(wb.Sheets["Doctor Timings"]) || [],
careers: XLSX.utils.sheet_to_json(wb.Sheets["Careers"]) || [],
inquiries: XLSX.utils.sheet_to_json(wb.Sheets["Inquiry"]) || [],
academics:
XLSX.utils.sheet_to_json(wb.Sheets["Academics & Research"]) || [],
appointments:
XLSX.utils.sheet_to_json(wb.Sheets["Appointment"]) || [],
candidates: XLSX.utils.sheet_to_json(wb.Sheets["Candidate"]) || [],
news: XLSX.utils.sheet_to_json(wb.Sheets["News & Media"]) || [],
departments: XLSX.utils.sheet_to_json(wb.Sheets['Departments']) || [],
doctors: XLSX.utils.sheet_to_json(wb.Sheets['Doctors']) || [],
timings: XLSX.utils.sheet_to_json(wb.Sheets['Doctor Timings']) || [],
careers: XLSX.utils.sheet_to_json(wb.Sheets['Careers']) || [],
inquiries: XLSX.utils.sheet_to_json(wb.Sheets['Inquiry']) || [],
academics: XLSX.utils.sheet_to_json(wb.Sheets['Academics & Research']) || [],
appointments: XLSX.utils.sheet_to_json(wb.Sheets['Appointment']) || [],
candidates: XLSX.utils.sheet_to_json(wb.Sheets['Candidate']) || [],
news: XLSX.utils.sheet_to_json(wb.Sheets['News & Media']) || [],
};
setStatus("Uploading data to server (this may take a moment)...");
setStatus('Uploading data to server (this may take a moment)...');
const response = await apiClient.post("/import/bulk", payload);
const response = await apiClient.post('/import/bulk', payload);
if (response.status === 200) {
setStatus("✅ ALL DATA IMPORT COMPLETED SUCCESSFULLY!");
setStatus('✅ ALL DATA IMPORT COMPLETED SUCCESSFULLY!');
} else {
setStatus("❌ Server responded with an error.");
setStatus('❌ Server responded with an error.');
}
} catch (err: any) {
console.error("Import Error:", err);
const errorMsg = err.response?.data?.error || "Error processing file.";
console.error('Import Error:', err);
const errorMsg = err.response?.data?.error || 'Error processing file.';
setStatus(`${errorMsg}`);
} finally {
setLoading(false);
if (e.target) e.target.value = "";
if (e.target) e.target.value = '';
}
};
reader.onerror = () => {
setStatus("❌ Failed to read the file.");
setStatus('❌ Failed to read the file.');
setLoading(false);
};
@@ -77,45 +75,43 @@ const ImportData: React.FC = () => {
return (
<div style={containerStyle}>
<div style={cardStyle}>
<h2 style={{ color: "#333", marginBottom: "10px" }}>
Database Bulk Import
</h2>
<p style={{ color: "#666", marginBottom: "30px" }}>
<h2 style={{ color: '#333', marginBottom: '10px' }}>Database Bulk Import</h2>
<p style={{ color: '#666', marginBottom: '30px' }}>
Select the <b>gg_hospital.xlsx</b> file. This will update all tables.
</p>
<div style={{ marginBottom: "20px" }}>
<div style={{ marginBottom: '20px' }}>
<input
type="file"
accept=".xlsx, .xls"
onChange={handleFileUpload}
id="excel-upload"
style={{ display: "none" }}
style={{ display: 'none' }}
disabled={loading}
/>
<label
htmlFor="excel-upload"
style={{
...buttonStyle,
backgroundColor: loading ? "#a0aec0" : "#3182ce",
cursor: loading ? "not-allowed" : "pointer",
backgroundColor: loading ? '#a0aec0' : '#3182ce',
cursor: loading ? 'not-allowed' : 'pointer',
}}
>
{loading ? "⌛ Processing..." : "📂 Choose Excel File"}
{loading ? '⌛ Processing...' : '📂 Choose Excel File'}
</label>
</div>
{status && (
<div
style={{
marginTop: "25px",
padding: "15px",
borderRadius: "8px",
backgroundColor: status.includes("✅") ? "#f0fff4" : "#fff5f5",
color: status.includes("✅") ? "#2f855a" : "#c53030",
border: `1px solid ${status.includes("✅") ? "#c6f6d5" : "#fed7d7"}`,
fontWeight: "500",
whiteSpace: "pre-wrap",
marginTop: '25px',
padding: '15px',
borderRadius: '8px',
backgroundColor: status.includes('✅') ? '#f0fff4' : '#fff5f5',
color: status.includes('✅') ? '#2f855a' : '#c53030',
border: `1px solid ${status.includes('✅') ? '#c6f6d5' : '#fed7d7'}`,
fontWeight: '500',
whiteSpace: 'pre-wrap',
}}
>
{status}
@@ -127,32 +123,32 @@ const ImportData: React.FC = () => {
};
const containerStyle: React.CSSProperties = {
display: "flex",
justifyContent: "center",
alignItems: "center",
minHeight: "80vh",
backgroundColor: "#f7fafc",
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
minHeight: '80vh',
backgroundColor: '#f7fafc',
fontFamily: "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif",
};
const cardStyle: React.CSSProperties = {
backgroundColor: "white",
padding: "40px",
borderRadius: "12px",
boxShadow: "0 4px 6px rgba(0,0,0,0.1)",
maxWidth: "500px",
width: "100%",
textAlign: "center",
backgroundColor: 'white',
padding: '40px',
borderRadius: '12px',
boxShadow: '0 4px 6px rgba(0,0,0,0.1)',
maxWidth: '500px',
width: '100%',
textAlign: 'center',
};
const buttonStyle: React.CSSProperties = {
padding: "12px 24px",
color: "white",
borderRadius: "6px",
fontSize: "16px",
fontWeight: "bold",
transition: "all 0.2s ease",
display: "inline-block",
padding: '12px 24px',
color: 'white',
borderRadius: '6px',
fontSize: '16px',
fontWeight: 'bold',
transition: 'all 0.2s ease',
display: 'inline-block',
};
export default ImportData;
+20 -34
View File
@@ -1,31 +1,31 @@
import {useState, ChangeEvent} from "react";
import {useNavigate} from "react-router-dom";
import {useAuth} from "@/context/AuthContext";
import { useState, ChangeEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '@/context/AuthContext';
import {Card, CardContent, CardHeader, CardTitle} from "@/components/ui/card";
import {Input} from "@/components/ui/input";
import {Label} from "@/components/ui/label";
import {Button} from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
export default function Login() {
const navigate = useNavigate();
const {login} = useAuth();
const { login } = useAuth();
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const [error, setError] = useState('');
async function handleLogin() {
try {
setLoading(true);
setError("");
setError('');
await login(username, password);
navigate("/dashboard");
navigate('/dashboard');
} catch (err) {
setError("Invalid credentials");
setError('Invalid credentials');
}
setLoading(false);
@@ -37,17 +37,11 @@ export default function Login() {
<CardHeader className="space-y-1 text-center">
<CardTitle className="text-2xl font-semibold">Admin Login</CardTitle>
<p className="text-sm text-muted-foreground">
Enter your credentials to access the dashboard
</p>
<p className="text-sm text-muted-foreground">Enter your credentials to access the dashboard</p>
</CardHeader>
<CardContent className="space-y-5">
{error && (
<div className="p-3 text-sm text-red-600 bg-red-100 rounded-md">
{error}
</div>
)}
{error && <div className="p-3 text-sm text-red-600 bg-red-100 rounded-md">{error}</div>}
<div className="space-y-2">
<Label htmlFor="username">Username</Label>
@@ -56,9 +50,7 @@ export default function Login() {
id="username"
placeholder="Enter username"
value={username}
onChange={(e: ChangeEvent<HTMLInputElement>) =>
setUsername(e.target.value)
}
onChange={(e: ChangeEvent<HTMLInputElement>) => setUsername(e.target.value)}
disabled={loading}
/>
</div>
@@ -71,19 +63,13 @@ export default function Login() {
type="password"
placeholder="Enter password"
value={password}
onChange={(e: ChangeEvent<HTMLInputElement>) =>
setPassword(e.target.value)
}
onChange={(e: ChangeEvent<HTMLInputElement>) => setPassword(e.target.value)}
disabled={loading}
/>
</div>
<Button
onClick={handleLogin}
className="w-full"
disabled={loading || !username || !password}
>
{loading ? "Logging in..." : "Login"}
<Button onClick={handleLogin} className="w-full" disabled={loading || !username || !password}>
{loading ? 'Logging in...' : 'Login'}
</Button>
</CardContent>
</Card>
+50 -149
View File
@@ -1,45 +1,23 @@
import { useState, useEffect, useCallback } from "react";
import { useState, useEffect, useCallback } from 'react';
import { getCandidatesApi, deleteCandidateApi } from "@/api/candidates";
import { exportToExcel } from "@/utils/exportToExcel";
import { getCandidatesApi, deleteCandidateApi } from '@/api/candidates';
import { exportToExcel } from '@/utils/exportToExcel';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
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 { 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,
Trash,
RefreshCw,
Download,
ChevronLeft,
ChevronRight,
Eye,
User,
} from "lucide-react";
import { Loader2, Trash, RefreshCw, Download, ChevronLeft, ChevronRight, Eye, User } from 'lucide-react';
export default function CandidatePage() {
const [candidates, setCandidates] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const [searchText, setSearchText] = useState("");
const [filterCareer, setFilterCareer] = useState("");
const [searchText, setSearchText] = useState('');
const [filterCareer, setFilterCareer] = useState('');
const [viewOpen, setViewOpen] = useState(false);
const [viewData, setViewData] = useState<any>(null);
@@ -69,9 +47,7 @@ export default function CandidatePage() {
item.mobile?.includes(searchText) ||
item.email?.toLowerCase().includes(searchText.toLowerCase());
const matchesCareer = filterCareer
? item.career?.post?.toLowerCase().includes(filterCareer.toLowerCase())
: true;
const matchesCareer = filterCareer ? item.career?.post?.toLowerCase().includes(filterCareer.toLowerCase()) : true;
return matchesSearch && matchesCareer;
});
@@ -83,10 +59,7 @@ export default function CandidatePage() {
const totalPages = Math.ceil(filteredCandidates.length / itemsPerPage);
const indexOfLastItem = currentPage * itemsPerPage;
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
const currentItems = filteredCandidates.slice(
indexOfFirstItem,
indexOfLastItem,
);
const currentItems = filteredCandidates.slice(indexOfFirstItem, indexOfLastItem);
function openView(item: any) {
setViewData(item);
@@ -94,7 +67,7 @@ export default function CandidatePage() {
}
async function handleDelete(id: number) {
if (!confirm("Delete candidate?")) return;
if (!confirm('Delete candidate?')) return;
await deleteCandidateApi(id);
fetchAll();
}
@@ -112,7 +85,7 @@ export default function CandidatePage() {
AppliedDate: new Date(item.createdAt).toLocaleDateString(),
}));
exportToExcel(exportData, "candidates");
exportToExcel(exportData, 'candidates');
};
return (
@@ -135,12 +108,7 @@ export default function CandidatePage() {
className="w-[200px] text-base"
/>
<Button
variant="outline"
onClick={fetchAll}
disabled={loading}
className="text-base"
>
<Button variant="outline" onClick={fetchAll} disabled={loading} className="text-base">
<RefreshCw className="mr-2 h-5 w-5" />
Refresh
</Button>
@@ -162,27 +130,13 @@ export default function CandidatePage() {
<Table className="w-full min-w-[1100px] table-fixed border-separate border-spacing-0">
<TableHeader className="sticky top-0 z-20 bg-background shadow-sm">
<TableRow>
<TableHead className="w-[60px] bg-background font-bold text-sm">
ID
</TableHead>
<TableHead className="w-[220px] bg-background font-bold text-sm">
Full Name
</TableHead>
<TableHead className="w-[180px] bg-background font-bold text-sm">
Career & Post
</TableHead>
<TableHead className="w-[150px] bg-background font-bold text-sm">
Contact
</TableHead>
<TableHead className="w-[140px] bg-background font-bold text-sm">
Applied On
</TableHead>
<TableHead className="w-[250px] bg-background font-bold text-sm">
Cover Letter
</TableHead>
<TableHead className="w-[120px] bg-background font-bold text-right text-sm">
Actions
</TableHead>
<TableHead className="w-[60px] bg-background font-bold text-sm">ID</TableHead>
<TableHead className="w-[220px] bg-background font-bold text-sm">Full Name</TableHead>
<TableHead className="w-[180px] bg-background font-bold text-sm">Career & Post</TableHead>
<TableHead className="w-[150px] bg-background font-bold text-sm">Contact</TableHead>
<TableHead className="w-[140px] bg-background font-bold text-sm">Applied On</TableHead>
<TableHead className="w-[250px] bg-background font-bold text-sm">Cover Letter</TableHead>
<TableHead className="w-[120px] bg-background font-bold text-right text-sm">Actions</TableHead>
</TableRow>
</TableHeader>
@@ -195,52 +149,32 @@ export default function CandidatePage() {
</TableRow>
) : currentItems.length === 0 ? (
<TableRow>
<TableCell
colSpan={7}
className="text-center text-muted-foreground py-10 text-base"
>
<TableCell colSpan={7} className="text-center text-muted-foreground py-10 text-base">
No candidates found
</TableCell>
</TableRow>
) : (
currentItems.map((item) => (
<TableRow key={item.id} className="hover:bg-muted/50">
<TableCell className="font-mono text-xs">
{item.id}
<TableCell className="font-mono text-xs">{item.id}</TableCell>
<TableCell>
<div className="font-semibold text-base truncate">{item.fullName}</div>
<div className="text-xs text-muted-foreground truncate">{item.email}</div>
</TableCell>
<TableCell>
<div className="font-semibold text-base truncate">
{item.fullName}
</div>
<div className="text-xs text-muted-foreground truncate">
{item.email}
</div>
</TableCell>
<TableCell>
<div className="text-sm font-medium">
{item.career?.post || "-"}
</div>
<div className="text-[10px] text-muted-foreground truncate">
{item.career?.designation}
</div>
<div className="text-sm font-medium">{item.career?.post || '-'}</div>
<div className="text-[10px] text-muted-foreground truncate">{item.career?.designation}</div>
</TableCell>
<TableCell className="text-sm">{item.mobile}</TableCell>
<TableCell className="text-sm">
{new Date(item.createdAt).toLocaleDateString()}
</TableCell>
<TableCell className="text-sm">{new Date(item.createdAt).toLocaleDateString()}</TableCell>
<TableCell>
<div className="text-sm line-clamp-2 text-muted-foreground italic">
{item.coverLetter || "No cover letter provided."}
{item.coverLetter || 'No cover letter provided.'}
</div>
</TableCell>
<TableCell className="text-right">
<div className="flex justify-end gap-2">
<Button
size="icon"
variant="ghost"
className="h-9 w-9"
onClick={() => openView(item)}
>
<Button size="icon" variant="ghost" className="h-9 w-9" onClick={() => openView(item)}>
<Eye className="h-4 w-4" />
</Button>
<Button
@@ -263,15 +197,9 @@ export default function CandidatePage() {
{!loading && filteredCandidates.length > 0 && (
<div className="flex items-center justify-between px-2 py-6 border-t">
<div className="text-base text-muted-foreground">
Showing{" "}
<span className="font-semibold">{indexOfFirstItem + 1}</span> to{" "}
<span className="font-semibold">
{Math.min(indexOfLastItem, filteredCandidates.length)}
</span>{" "}
of{" "}
<span className="font-semibold">
{filteredCandidates.length}
</span>
Showing <span className="font-semibold">{indexOfFirstItem + 1}</span> to{' '}
<span className="font-semibold">{Math.min(indexOfLastItem, filteredCandidates.length)}</span> of{' '}
<span className="font-semibold">{filteredCandidates.length}</span>
</div>
<div className="flex items-center gap-6">
<div className="text-base font-semibold">
@@ -282,9 +210,7 @@ export default function CandidatePage() {
variant="outline"
size="icon"
className="h-10 w-10"
onClick={() =>
setCurrentPage((prev) => Math.max(prev - 1, 1))
}
onClick={() => setCurrentPage((prev) => Math.max(prev - 1, 1))}
disabled={currentPage === 1}
>
<ChevronLeft className="h-5 w-5" />
@@ -293,9 +219,7 @@ export default function CandidatePage() {
variant="outline"
size="icon"
className="h-10 w-10"
onClick={() =>
setCurrentPage((prev) => Math.min(prev + 1, totalPages))
}
onClick={() => setCurrentPage((prev) => Math.min(prev + 1, totalPages))}
disabled={currentPage === totalPages || totalPages === 0}
>
<ChevronRight className="h-5 w-5" />
@@ -319,50 +243,30 @@ export default function CandidatePage() {
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="space-y-4">
<div>
<p className="text-xs uppercase font-bold text-muted-foreground">
Personal Information
</p>
<p className="text-lg font-bold text-primary">
{viewData.fullName}
</p>
<p className="text-xs uppercase font-bold text-muted-foreground">Personal Information</p>
<p className="text-lg font-bold text-primary">{viewData.fullName}</p>
<p className="text-sm font-medium">{viewData.email}</p>
<p className="text-sm">{viewData.mobile}</p>
</div>
<div>
<p className="text-xs uppercase font-bold text-muted-foreground">
Applied For
</p>
<p className="text-base font-semibold">
{viewData.career?.post || "General Application"}
</p>
<p className="text-sm text-muted-foreground">
{viewData.career?.designation}
</p>
<p className="text-xs uppercase font-bold text-muted-foreground">Applied For</p>
<p className="text-base font-semibold">{viewData.career?.post || 'General Application'}</p>
<p className="text-sm text-muted-foreground">{viewData.career?.designation}</p>
</div>
<div>
<p className="text-xs uppercase font-bold text-muted-foreground">
Application Date
</p>
<p className="text-sm">
{new Date(viewData.createdAt).toLocaleString()}
</p>
<p className="text-xs uppercase font-bold text-muted-foreground">Application Date</p>
<p className="text-sm">{new Date(viewData.createdAt).toLocaleString()}</p>
</div>
</div>
<div className="space-y-4">
<div>
<p className="text-xs uppercase font-bold text-muted-foreground">
Subject
</p>
<p className="text-sm font-semibold">
{viewData.subject || "N/A"}
</p>
<p className="text-xs uppercase font-bold text-muted-foreground">Subject</p>
<p className="text-sm font-semibold">{viewData.subject || 'N/A'}</p>
</div>
<div className="p-4 bg-muted/30 rounded-lg">
<p className="text-xs uppercase font-bold text-muted-foreground mb-2">
Cover Letter / Message
</p>
<p className="text-xs uppercase font-bold text-muted-foreground mb-2">Cover Letter / Message</p>
<p className="text-sm leading-relaxed whitespace-pre-wrap italic">
{viewData.coverLetter || "No cover letter provided."}
{viewData.coverLetter || 'No cover letter provided.'}
</p>
</div>
</div>
@@ -370,10 +274,7 @@ export default function CandidatePage() {
</div>
)}
<DialogFooter>
<Button
onClick={() => setViewOpen(false)}
className="w-full md:w-auto"
>
<Button onClick={() => setViewOpen(false)} className="w-full md:w-auto">
Close
</Button>
</DialogFooter>
+28 -73
View File
@@ -1,34 +1,16 @@
import {useState, useEffect, useCallback} from "react";
import { useState, useEffect, useCallback } from 'react';
import {
getEmailConfigsApi,
createEmailConfigApi,
updateEmailConfigApi,
deleteEmailConfigApi,
} from "@/api/email";
import { getEmailConfigsApi, createEmailConfigApi, updateEmailConfigApi, deleteEmailConfigApi } from '@/api/email';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
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 { 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 { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } 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() {
const [emails, setEmails] = useState<any[]>([]);
@@ -37,12 +19,12 @@ export default function EmailPage() {
const [openModal, setOpenModal] = useState(false);
const [editing, setEditing] = useState<any>(null);
const [searchText, setSearchText] = useState("");
const [searchText, setSearchText] = useState('');
const [form, setForm] = useState({
name: "",
email: "",
type: "APPOINTMENT",
name: '',
email: '',
type: 'APPOINTMENT',
isActive: true,
});
@@ -65,19 +47,19 @@ export default function EmailPage() {
const filtered = emails.filter(
(e) =>
e.email.toLowerCase().includes(searchText.toLowerCase()) ||
e.name.toLowerCase().includes(searchText.toLowerCase()),
e.name.toLowerCase().includes(searchText.toLowerCase())
);
function handleChange(e: any) {
setForm({...form, [e.target.name]: e.target.value});
setForm({ ...form, [e.target.name]: e.target.value });
}
function openAdd() {
setEditing(null);
setForm({
name: "",
email: "",
type: "APPOINTMENT",
name: '',
email: '',
type: 'APPOINTMENT',
isActive: true,
});
setOpenModal(true);
@@ -105,7 +87,7 @@ export default function EmailPage() {
}
async function handleDelete(id: number) {
if (!confirm("Delete email config?")) return;
if (!confirm('Delete email config?')) return;
await deleteEmailConfigApi(id);
fetchAll();
}
@@ -173,24 +155,14 @@ export default function EmailPage() {
<TableCell>{item.name}</TableCell>
<TableCell>{item.email}</TableCell>
<TableCell>{item.type}</TableCell>
<TableCell>
{item.isActive ? "Active" : "Inactive"}
</TableCell>
<TableCell>{item.isActive ? 'Active' : 'Inactive'}</TableCell>
<TableCell className="flex gap-2">
<Button
size="sm"
variant="outline"
onClick={() => openEdit(item)}
>
<Button size="sm" variant="outline" onClick={() => openEdit(item)}>
<Pencil className="h-4 w-4" />
</Button>
<Button
size="sm"
variant="destructive"
onClick={() => handleDelete(item.id)}
>
<Button size="sm" variant="destructive" onClick={() => handleDelete(item.id)}>
<Trash className="h-4 w-4" />
</Button>
</TableCell>
@@ -205,30 +177,15 @@ export default function EmailPage() {
<Dialog open={openModal} onOpenChange={setOpenModal}>
<DialogContent>
<DialogHeader>
<DialogTitle>{editing ? "Edit Email" : "Add Email"}</DialogTitle>
<DialogTitle>{editing ? 'Edit Email' : 'Add Email'}</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<Input
name="name"
placeholder="Name"
value={form.name}
onChange={handleChange}
/>
<Input name="name" placeholder="Name" value={form.name} onChange={handleChange} />
<Input
name="email"
placeholder="Email"
value={form.email}
onChange={handleChange}
/>
<Input name="email" placeholder="Email" value={form.email} onChange={handleChange} />
<select
name="type"
value={form.type}
onChange={handleChange}
className="border rounded px-2 py-2 w-full"
>
<select name="type" value={form.type} onChange={handleChange} className="border rounded px-2 py-2 w-full">
<option value="APPOINTMENT">APPOINTMENT</option>
<option value="CANDIDATE">CANDIDATE</option>
<option value="ACADEMICS">ACADEMICS</option>
@@ -238,11 +195,11 @@ export default function EmailPage() {
<select
name="isActive"
value={form.isActive ? "true" : "false"}
value={form.isActive ? 'true' : 'false'}
onChange={(e) =>
setForm({
...form,
isActive: e.target.value === "true",
isActive: e.target.value === 'true',
})
}
className="border rounded px-2 py-2 w-full"
@@ -256,9 +213,7 @@ export default function EmailPage() {
<Button variant="outline" onClick={() => setOpenModal(false)}>
Cancel
</Button>
<Button onClick={handleSubmit}>
{editing ? "Update" : "Create"}
</Button>
<Button onClick={handleSubmit}>{editing ? 'Update' : 'Create'}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
+44 -135
View File
@@ -1,44 +1,22 @@
import { useState, useEffect, useCallback } from "react";
import { useState, useEffect, useCallback } from 'react';
import { getInquiriesApi, deleteInquiryApi } from "@/api/inquiry";
import { exportToExcel } from "@/utils/exportToExcel";
import { getInquiriesApi, deleteInquiryApi } from '@/api/inquiry';
import { exportToExcel } from '@/utils/exportToExcel';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
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 { 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,
Trash,
RefreshCw,
Download,
ChevronLeft,
ChevronRight,
Eye,
Mail,
} from "lucide-react";
import { Loader2, Trash, RefreshCw, Download, ChevronLeft, ChevronRight, Eye, Mail } from 'lucide-react';
export default function InquiryPage() {
const [inquiries, setInquiries] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const [searchText, setSearchText] = useState("");
const [searchText, setSearchText] = useState('');
const [viewOpen, setViewOpen] = useState(false);
const [viewData, setViewData] = useState<any>(null);
@@ -78,10 +56,7 @@ export default function InquiryPage() {
const totalPages = Math.ceil(filteredInquiries.length / itemsPerPage);
const indexOfLastItem = currentPage * itemsPerPage;
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
const currentItems = filteredInquiries.slice(
indexOfFirstItem,
indexOfLastItem,
);
const currentItems = filteredInquiries.slice(indexOfFirstItem, indexOfLastItem);
function openView(item: any) {
setViewData(item);
@@ -89,7 +64,7 @@ export default function InquiryPage() {
}
async function handleDelete(id: number) {
if (!confirm("Delete inquiry?")) return;
if (!confirm('Delete inquiry?')) return;
await deleteInquiryApi(id);
fetchAll();
}
@@ -105,7 +80,7 @@ export default function InquiryPage() {
Date: new Date(item.createdAt).toLocaleDateString(),
}));
exportToExcel(exportData, "inquiries");
exportToExcel(exportData, 'inquiries');
};
return (
@@ -121,12 +96,7 @@ export default function InquiryPage() {
className="w-[280px] text-base"
/>
<Button
variant="outline"
onClick={fetchAll}
disabled={loading}
className="text-base"
>
<Button variant="outline" onClick={fetchAll} disabled={loading} className="text-base">
<RefreshCw className="mr-2 h-5 w-5" />
Refresh
</Button>
@@ -148,24 +118,12 @@ export default function InquiryPage() {
<Table className="w-full min-w-[1000px] table-fixed border-separate border-spacing-0">
<TableHeader className="sticky top-0 z-20 bg-background shadow-sm">
<TableRow>
<TableHead className="w-[60px] bg-background font-bold text-sm">
ID
</TableHead>
<TableHead className="w-[220px] bg-background font-bold text-sm">
Customer Details
</TableHead>
<TableHead className="w-[200px] bg-background font-bold text-sm">
Subject
</TableHead>
<TableHead className="w-[150px] bg-background font-bold text-sm">
Date
</TableHead>
<TableHead className="w-[280px] bg-background font-bold text-sm">
Message Snippet
</TableHead>
<TableHead className="w-[120px] bg-background font-bold text-right text-sm">
Actions
</TableHead>
<TableHead className="w-[60px] bg-background font-bold text-sm">ID</TableHead>
<TableHead className="w-[220px] bg-background font-bold text-sm">Customer Details</TableHead>
<TableHead className="w-[200px] bg-background font-bold text-sm">Subject</TableHead>
<TableHead className="w-[150px] bg-background font-bold text-sm">Date</TableHead>
<TableHead className="w-[280px] bg-background font-bold text-sm">Message Snippet</TableHead>
<TableHead className="w-[120px] bg-background font-bold text-right text-sm">Actions</TableHead>
</TableRow>
</TableHeader>
@@ -178,51 +136,29 @@ export default function InquiryPage() {
</TableRow>
) : currentItems.length === 0 ? (
<TableRow>
<TableCell
colSpan={6}
className="text-center text-muted-foreground py-10 text-base"
>
<TableCell colSpan={6} className="text-center text-muted-foreground py-10 text-base">
No inquiries found
</TableCell>
</TableRow>
) : (
currentItems.map((item) => (
<TableRow key={item.id} className="hover:bg-muted/50">
<TableCell className="font-mono text-xs">
{item.id}
<TableCell className="font-mono text-xs">{item.id}</TableCell>
<TableCell>
<div className="font-semibold text-base truncate">{item.fullName}</div>
<div className="text-xs text-muted-foreground truncate">{item.emailId}</div>
<div className="text-[11px] font-medium">{item.number}</div>
</TableCell>
<TableCell>
<div className="font-semibold text-base truncate">
{item.fullName}
</div>
<div className="text-xs text-muted-foreground truncate">
{item.emailId}
</div>
<div className="text-[11px] font-medium">
{item.number}
</div>
<div className="text-sm font-medium line-clamp-2">{item.subject || '-'}</div>
</TableCell>
<TableCell className="text-sm">{new Date(item.createdAt).toLocaleDateString()}</TableCell>
<TableCell>
<div className="text-sm font-medium line-clamp-2">
{item.subject || "-"}
</div>
</TableCell>
<TableCell className="text-sm">
{new Date(item.createdAt).toLocaleDateString()}
</TableCell>
<TableCell>
<div className="text-sm line-clamp-2 text-muted-foreground italic">
{item.message || "-"}
</div>
<div className="text-sm line-clamp-2 text-muted-foreground italic">{item.message || '-'}</div>
</TableCell>
<TableCell className="text-right">
<div className="flex justify-end gap-2">
<Button
size="icon"
variant="ghost"
className="h-9 w-9"
onClick={() => openView(item)}
>
<Button size="icon" variant="ghost" className="h-9 w-9" onClick={() => openView(item)}>
<Eye className="h-4 w-4" />
</Button>
<Button
@@ -245,15 +181,9 @@ export default function InquiryPage() {
{!loading && filteredInquiries.length > 0 && (
<div className="flex items-center justify-between px-2 py-6 border-t">
<div className="text-base text-muted-foreground">
Showing{" "}
<span className="font-semibold">{indexOfFirstItem + 1}</span> to{" "}
<span className="font-semibold">
{Math.min(indexOfLastItem, filteredInquiries.length)}
</span>{" "}
of{" "}
<span className="font-semibold">
{filteredInquiries.length}
</span>
Showing <span className="font-semibold">{indexOfFirstItem + 1}</span> to{' '}
<span className="font-semibold">{Math.min(indexOfLastItem, filteredInquiries.length)}</span> of{' '}
<span className="font-semibold">{filteredInquiries.length}</span>
</div>
<div className="flex items-center gap-6">
<div className="text-base font-semibold">
@@ -264,9 +194,7 @@ export default function InquiryPage() {
variant="outline"
size="icon"
className="h-10 w-10"
onClick={() =>
setCurrentPage((prev) => Math.max(prev - 1, 1))
}
onClick={() => setCurrentPage((prev) => Math.max(prev - 1, 1))}
disabled={currentPage === 1}
>
<ChevronLeft className="h-5 w-5" />
@@ -275,9 +203,7 @@ export default function InquiryPage() {
variant="outline"
size="icon"
className="h-10 w-10"
onClick={() =>
setCurrentPage((prev) => Math.min(prev + 1, totalPages))
}
onClick={() => setCurrentPage((prev) => Math.min(prev + 1, totalPages))}
disabled={currentPage === totalPages || totalPages === 0}
>
<ChevronRight className="h-5 w-5" />
@@ -301,39 +227,25 @@ export default function InquiryPage() {
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="space-y-4">
<div>
<p className="text-xs uppercase font-bold text-muted-foreground">
Customer Information
</p>
<p className="text-lg font-bold text-primary">
{viewData.fullName}
</p>
<p className="text-xs uppercase font-bold text-muted-foreground">Customer Information</p>
<p className="text-lg font-bold text-primary">{viewData.fullName}</p>
<p className="text-sm font-medium">{viewData.emailId}</p>
<p className="text-sm">{viewData.number}</p>
</div>
<div>
<p className="text-xs uppercase font-bold text-muted-foreground">
Received Date
</p>
<p className="text-sm">
{new Date(viewData.createdAt).toLocaleString()}
</p>
<p className="text-xs uppercase font-bold text-muted-foreground">Received Date</p>
<p className="text-sm">{new Date(viewData.createdAt).toLocaleString()}</p>
</div>
</div>
<div className="space-y-4">
<div>
<p className="text-xs uppercase font-bold text-muted-foreground">
Subject
</p>
<p className="text-base font-semibold">
{viewData.subject || "No Subject"}
</p>
<p className="text-xs uppercase font-bold text-muted-foreground">Subject</p>
<p className="text-base font-semibold">{viewData.subject || 'No Subject'}</p>
</div>
<div className="p-4 bg-muted/30 rounded-lg border">
<p className="text-xs uppercase font-bold text-muted-foreground mb-2">
Message
</p>
<p className="text-xs uppercase font-bold text-muted-foreground mb-2">Message</p>
<p className="text-sm leading-relaxed whitespace-pre-wrap">
{viewData.message || "No message content."}
{viewData.message || 'No message content.'}
</p>
</div>
</div>
@@ -341,10 +253,7 @@ export default function InquiryPage() {
</div>
)}
<DialogFooter>
<Button
onClick={() => setViewOpen(false)}
className="w-full md:w-auto"
>
<Button onClick={() => setViewOpen(false)} className="w-full md:w-auto">
Close
</Button>
</DialogFooter>
+70 -185
View File
@@ -1,34 +1,16 @@
import { useState, useEffect, useCallback } from "react";
import { BytescaleUploader } from "@/components/BytescaleUploader/BytescaleUploader";
import { useState, useEffect, useCallback } from 'react';
import { BytescaleUploader } from '@/components/BytescaleUploader/BytescaleUploader';
import {
getNewsApi,
createNewsApi,
updateNewsApi,
deleteNewsApi,
} from "@/api/newsMedia";
import { getNewsApi, createNewsApi, updateNewsApi, deleteNewsApi } from '@/api/newsMedia';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
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 { Textarea } from "@/components/ui/textarea";
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from "@/components/ui/dialog";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import {
Loader2,
@@ -42,14 +24,14 @@ import {
Newspaper,
ImageIcon,
X,
} from "lucide-react";
} from 'lucide-react';
export default function NewsPage() {
const [news, setNews] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const [totalItems, setTotalItems] = useState(0);
const [searchText, setSearchText] = useState("");
const [searchText, setSearchText] = useState('');
const [openModal, setOpenModal] = useState(false);
const [editing, setEditing] = useState<any>(null);
@@ -61,13 +43,13 @@ export default function NewsPage() {
const [itemsPerPage, setItemsPerPage] = useState(10);
const [form, setForm] = useState({
headline: "",
content: "",
headline: '',
content: '',
imageUrls: [] as string[],
firstPara: "",
secondPara: "",
date: "",
author: "",
firstPara: '',
secondPara: '',
date: '',
author: '',
});
const fetchAll = useCallback(async () => {
@@ -104,13 +86,13 @@ export default function NewsPage() {
function openAdd() {
setEditing(null);
setForm({
headline: "",
content: "",
headline: '',
content: '',
imageUrls: [],
firstPara: "",
secondPara: "",
date: "",
author: "",
firstPara: '',
secondPara: '',
date: '',
author: '',
});
setOpenModal(true);
}
@@ -118,13 +100,13 @@ export default function NewsPage() {
function openEdit(item: any) {
setEditing(item);
setForm({
headline: item.Headline || "",
content: item.Content || "",
headline: item.Headline || '',
content: item.Content || '',
imageUrls: item.Images ? item.Images.map((img: any) => img.image) : [],
firstPara: item.FirstPara || "",
secondPara: item.SecondPara || "",
date: item.Date ? item.Date.split("T")[0] : "",
author: item.Author || "",
firstPara: item.FirstPara || '',
secondPara: item.SecondPara || '',
date: item.Date ? item.Date.split('T')[0] : '',
author: item.Author || '',
});
setOpenModal(true);
}
@@ -139,10 +121,7 @@ export default function NewsPage() {
const submissionData = {
...form,
firstPara: form.headline,
content:
form.secondPara.length > 100
? form.secondPara.substring(0, 100) + "..."
: form.secondPara,
content: form.secondPara.length > 100 ? form.secondPara.substring(0, 100) + '...' : form.secondPara,
};
if (editing) {
@@ -158,7 +137,7 @@ export default function NewsPage() {
}
async function handleDelete(id: number) {
if (!confirm("Delete news?")) return;
if (!confirm('Delete news?')) return;
await deleteNewsApi(id);
fetchAll();
}
@@ -166,9 +145,7 @@ export default function NewsPage() {
return (
<div className="p-6 space-y-6">
<div className="flex flex-col md:flex-row md:justify-between md:items-center gap-4">
<h1 className="text-3xl font-bold font-sans tracking-tight">
News Media
</h1>
<h1 className="text-3xl font-bold font-sans tracking-tight">News Media</h1>
<div className="flex flex-wrap gap-3 items-center">
<Input
@@ -193,12 +170,7 @@ export default function NewsPage() {
<option value={20}>20 / page</option>
</select>
<Button
variant="outline"
onClick={fetchAll}
disabled={loading}
className="text-base"
>
<Button variant="outline" onClick={fetchAll} disabled={loading} className="text-base">
<RefreshCw className="mr-2 h-5 w-5" />
Refresh
</Button>
@@ -220,27 +192,13 @@ export default function NewsPage() {
<Table className="w-full min-w-[1000px] table-fixed border-separate border-spacing-0">
<TableHeader className="sticky top-0 z-20 bg-background shadow-sm">
<TableRow>
<TableHead className="w-[80px] bg-background font-bold">
ID
</TableHead>
<TableHead className="w-[100px] bg-background font-bold">
Cover
</TableHead>
<TableHead className="w-[280px] bg-background font-bold">
Headline
</TableHead>
<TableHead className="w-[150px] bg-background font-bold">
Author
</TableHead>
<TableHead className="w-[140px] bg-background font-bold">
Date
</TableHead>
<TableHead className="w-[250px] bg-background font-bold">
Content Preview
</TableHead>
<TableHead className="w-[150px] bg-background font-bold text-right">
Actions
</TableHead>
<TableHead className="w-[80px] bg-background font-bold">ID</TableHead>
<TableHead className="w-[100px] bg-background font-bold">Cover</TableHead>
<TableHead className="w-[280px] bg-background font-bold">Headline</TableHead>
<TableHead className="w-[150px] bg-background font-bold">Author</TableHead>
<TableHead className="w-[140px] bg-background font-bold">Date</TableHead>
<TableHead className="w-[250px] bg-background font-bold">Content Preview</TableHead>
<TableHead className="w-[150px] bg-background font-bold text-right">Actions</TableHead>
</TableRow>
</TableHeader>
@@ -253,19 +211,14 @@ export default function NewsPage() {
</TableRow>
) : news.length === 0 ? (
<TableRow>
<TableCell
colSpan={7}
className="text-center text-muted-foreground py-10 text-base"
>
<TableCell colSpan={7} className="text-center text-muted-foreground py-10 text-base">
No news articles found
</TableCell>
</TableRow>
) : (
news.map((item) => (
<TableRow key={item.Id} className="hover:bg-muted/50">
<TableCell className="font-mono text-xs">
{item.Id}
</TableCell>
<TableCell className="font-mono text-xs">{item.Id}</TableCell>
<TableCell>
{item.Images?.[0] ? (
<img
@@ -280,42 +233,23 @@ export default function NewsPage() {
)}
</TableCell>
<TableCell>
<div
className="font-semibold text-base line-clamp-2"
title={item.Headline}
>
<div className="font-semibold text-base line-clamp-2" title={item.Headline}>
{item.Headline}
</div>
</TableCell>
<TableCell className="text-sm font-medium">
{item.Author || "-"}
</TableCell>
<TableCell className="text-sm font-medium">{item.Author || '-'}</TableCell>
<TableCell className="text-sm">
{item.Date
? new Date(item.Date).toLocaleDateString()
: "-"}
{item.Date ? new Date(item.Date).toLocaleDateString() : '-'}
</TableCell>
<TableCell>
<div className="text-sm line-clamp-2 text-muted-foreground">
{item.Content}
</div>
<div className="text-sm line-clamp-2 text-muted-foreground">{item.Content}</div>
</TableCell>
<TableCell className="text-right">
<div className="flex justify-end gap-2">
<Button
size="icon"
variant="ghost"
className="h-9 w-9"
onClick={() => openView(item)}
>
<Button size="icon" variant="ghost" className="h-9 w-9" onClick={() => openView(item)}>
<Eye className="h-4 w-4" />
</Button>
<Button
size="icon"
variant="ghost"
className="h-9 w-9"
onClick={() => openEdit(item)}
>
<Button size="icon" variant="ghost" className="h-9 w-9" onClick={() => openEdit(item)}>
<Pencil className="h-4 w-4" />
</Button>
<Button
@@ -338,9 +272,8 @@ export default function NewsPage() {
{!loading && totalItems > 0 && (
<div className="flex items-center justify-between px-2 py-4 border-t">
<div className="text-sm text-muted-foreground">
Total <span className="font-bold">{totalItems}</span> articles
(Page <span className="font-bold">{currentPage}</span> of{" "}
{totalPages})
Total <span className="font-bold">{totalItems}</span> articles (Page{' '}
<span className="font-bold">{currentPage}</span> of {totalPages})
</div>
<div className="flex items-center gap-6">
<div className="text-base font-semibold">
@@ -351,9 +284,7 @@ export default function NewsPage() {
variant="outline"
size="icon"
className="h-10 w-10"
onClick={() =>
setCurrentPage((prev) => Math.max(prev - 1, 1))
}
onClick={() => setCurrentPage((prev) => Math.max(prev - 1, 1))}
disabled={currentPage === 1}
>
<ChevronLeft className="h-5 w-5" />
@@ -362,9 +293,7 @@ export default function NewsPage() {
variant="outline"
size="icon"
className="h-10 w-10"
onClick={() =>
setCurrentPage((prev) => Math.min(prev + 1, totalPages))
}
onClick={() => setCurrentPage((prev) => Math.min(prev + 1, totalPages))}
disabled={currentPage === totalPages || totalPages === 0}
>
<ChevronRight className="h-5 w-5" />
@@ -380,43 +309,25 @@ export default function NewsPage() {
<DialogContent className="w-full !max-w-6xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="text-2xl font-bold">
{editing ? "Edit News Article" : "Add New News Article"}
{editing ? 'Edit News Article' : 'Add New News Article'}
</DialogTitle>
</DialogHeader>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8 mt-6">
<div className="lg:col-span-2 space-y-6">
<h3 className="font-bold text-base border-b pb-2 text-primary">
Article Information
</h3>
<h3 className="font-bold text-base border-b pb-2 text-primary">Article Information</h3>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-1 col-span-2">
<label className="text-sm font-semibold">Headline</label>
<Input
name="headline"
value={form.headline}
onChange={handleChange}
className="text-base"
/>
<Input name="headline" value={form.headline} onChange={handleChange} className="text-base" />
</div>
<div className="space-y-1">
<label className="text-sm font-semibold">Author</label>
<Input
name="author"
value={form.author}
onChange={handleChange}
className="text-base"
/>
<Input name="author" value={form.author} onChange={handleChange} className="text-base" />
</div>
<div className="space-y-1">
<label className="text-sm font-semibold">Publish Date</label>
<Input
type="date"
name="date"
value={form.date}
onChange={handleChange}
className="text-base"
/>
<Input type="date" name="date" value={form.date} onChange={handleChange} className="text-base" />
</div>
</div>
<div className="space-y-1">
@@ -453,15 +364,8 @@ export default function NewsPage() {
<div className="grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto pr-2 mt-4">
{form.imageUrls.map((url, index) => (
<div
key={index}
className="relative group border rounded-lg overflow-hidden h-24 bg-muted"
>
<img
src={url}
alt="upload"
className="w-full h-full object-cover"
/>
<div key={index} className="relative group border rounded-lg overflow-hidden h-24 bg-muted">
<img src={url} alt="upload" className="w-full h-full object-cover" />
<button
type="button"
onClick={() => removeImageUrl(index)}
@@ -482,18 +386,11 @@ export default function NewsPage() {
</div>
<DialogFooter className="mt-10 pt-6 border-t">
<Button
variant="ghost"
onClick={() => setOpenModal(false)}
className="text-base"
>
<Button variant="ghost" onClick={() => setOpenModal(false)} className="text-base">
Cancel
</Button>
<Button
onClick={handleSubmit}
className="px-10 text-base bg-primary text-white"
>
{editing ? "Save Changes" : "Publish Now"}
<Button onClick={handleSubmit} className="px-10 text-base bg-primary text-white">
{editing ? 'Save Changes' : 'Publish Now'}
</Button>
</DialogFooter>
</DialogContent>
@@ -510,30 +407,23 @@ export default function NewsPage() {
{viewData && (
<div className="space-y-6 py-4">
<div className="space-y-2">
<h2 className="text-2xl font-bold leading-tight">
{viewData.Headline}
</h2>
<h2 className="text-2xl font-bold leading-tight">{viewData.Headline}</h2>
<div className="flex gap-4 text-sm text-muted-foreground font-medium italic">
<span>By: {viewData.Author || "Anonymous"}</span>
<span>By: {viewData.Author || 'Anonymous'}</span>
<span></span>
<span>
{viewData.Date
? new Date(viewData.Date).toLocaleDateString("en-IN", {
dateStyle: "long",
? new Date(viewData.Date).toLocaleDateString('en-IN', {
dateStyle: 'long',
})
: "No Date"}
: 'No Date'}
</span>
</div>
</div>
<div className="grid grid-cols-3 md:grid-cols-4 gap-2">
{viewData.Images?.map((img: any, i: number) => (
<img
key={i}
src={img.image}
className="w-full h-24 object-cover rounded-md border"
alt="gallery"
/>
<img key={i} src={img.image} className="w-full h-24 object-cover rounded-md border" alt="gallery" />
))}
</div>
@@ -544,19 +434,14 @@ export default function NewsPage() {
<div className="space-y-4 px-1">
<p className="whitespace-pre-line">{viewData.SecondPara}</p>
<hr />
<p className="whitespace-pre-line text-muted-foreground">
{viewData.Content}
</p>
<p className="whitespace-pre-line text-muted-foreground">{viewData.Content}</p>
</div>
</div>
</div>
)}
<DialogFooter>
<Button
onClick={() => setViewOpen(false)}
className="w-full md:w-auto"
>
<Button onClick={() => setViewOpen(false)} className="w-full md:w-auto">
Close Preview
</Button>
</DialogFooter>