added admin dashboard

This commit is contained in:
fISHIE
2026-02-08 14:40:35 +05:00
parent a27bd536ba
commit a9db71b234
16 changed files with 787 additions and 170 deletions

View File

@@ -2,6 +2,8 @@ import { BrowserRouter, Routes, Route } from "react-router-dom";
import { HomePage } from "@/pages/HomePage";
import { PetitionPage } from "@/pages/PetitionPage";
import { CreatePetitionPage } from "@/pages/CreatePetitionPage";
import { AdminLoginPage } from "@/pages/AdminLoginPage";
import { AdminDashboardPage } from "@/pages/AdminDashboardPage";
import { Layout } from "@/components/layout/Layout";
function App() {
@@ -12,6 +14,8 @@ function App() {
<Route path="/" element={<HomePage />} />
<Route path="/Petition/:slug" element={<PetitionPage />} />
<Route path="/CreatePetition" element={<CreatePetitionPage />} />
<Route path="/admin/login" element={<AdminLoginPage />} />
<Route path="/admin" element={<AdminDashboardPage />} />
</Routes>
</Layout>
</BrowserRouter>

View File

@@ -0,0 +1,117 @@
const API_BASE_URL = "";
const TOKEN_KEY = "adminToken";
export function getToken(): string | null {
return localStorage.getItem(TOKEN_KEY);
}
export function setToken(token: string): void {
localStorage.setItem(TOKEN_KEY, token);
}
export function clearToken(): void {
localStorage.removeItem(TOKEN_KEY);
}
export async function login(
username: string,
password: string,
): Promise<string> {
const response = await fetch(`${API_BASE_URL}/api/auth/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password }),
});
if (response.status === 401) {
throw new Error("Invalid credentials");
}
if (!response.ok) {
throw new Error(`Login failed: ${response.status}`);
}
const data = await response.json();
setToken(data.token);
return data.token;
}
export async function adminFetch(
url: string,
options: RequestInit = {},
): Promise<Response> {
const token = getToken();
if (!token) {
window.location.href = "/admin/login";
throw new Error("No token");
}
const res = await fetch(url, {
...options,
headers: {
...options.headers,
Authorization: `Bearer ${token}`,
},
});
if (res.status === 401) {
clearToken();
window.location.href = "/admin/login";
throw new Error("Unauthorized");
}
return res;
}
export interface AdminPetition {
id: string;
slug: string;
nameEng: string;
nameDhiv: string;
signatureCount: number;
startDate: string;
isApproved: boolean;
authorDetails?: { name: string };
}
export async function fetchAdminPetitions(): Promise<AdminPetition[]> {
const res = await adminFetch(`${API_BASE_URL}/api/admin/petitions`);
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err.detail || `HTTP error: ${res.status}`);
}
return res.json();
}
export async function createPetitionFolder(): Promise<string> {
const res = await adminFetch(
`${API_BASE_URL}/api/admin/create-petition-folder`,
);
if (!res.ok) {
throw new Error(`HTTP error: ${res.status}`);
}
return res.text();
}
export async function updatePetitionApproval(
petitionId: string,
isApproved: boolean,
): Promise<void> {
const res = await adminFetch(
`${API_BASE_URL}/api/admin/petitions/${petitionId}/approve`,
{
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ isApproved }),
},
);
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err.detail || `HTTP error: ${res.status}`);
}
}
export function getExportUrl(petitionId: string): string {
return `${API_BASE_URL}/api/admin/export/${petitionId}`;
}

View File

@@ -0,0 +1,278 @@
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import {
fetchAdminPetitions,
createPetitionFolder,
getExportUrl,
getToken,
clearToken,
updatePetitionApproval,
type AdminPetition,
} from "@/lib/adminApi";
import {
Loader2,
LogOut,
FileDown,
FolderPlus,
Users,
ShieldCheck,
CheckCircle,
Clock,
Eye,
XCircle,
} from "lucide-react";
export function AdminDashboardPage() {
const navigate = useNavigate();
const [petitions, setPetitions] = useState<AdminPetition[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [folderMsg, setFolderMsg] = useState<string | null>(null);
const [togglingId, setTogglingId] = useState<string | null>(null);
useEffect(() => {
if (!getToken()) {
navigate("/admin/login");
return;
}
loadPetitions();
}, [navigate]);
async function loadPetitions() {
setLoading(true);
setError(null);
try {
const data = await fetchAdminPetitions();
setPetitions(data);
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to load petitions");
} finally {
setLoading(false);
}
}
async function handleCreateFolder() {
setFolderMsg(null);
try {
const msg = await createPetitionFolder();
setFolderMsg(msg);
} catch (err) {
setFolderMsg(
err instanceof Error ? err.message : "Failed to create folder",
);
}
}
async function handleToggleApproval(petition: AdminPetition) {
setTogglingId(petition.id);
try {
await updatePetitionApproval(petition.id, !petition.isApproved);
await loadPetitions();
} catch (err) {
setError(
err instanceof Error ? err.message : "Failed to update approval",
);
} finally {
setTogglingId(null);
}
}
function handleLogout() {
clearToken();
navigate("/admin/login");
}
function handleExport(petitionId: string) {
const token = getToken();
if (!token) return;
fetch(getExportUrl(petitionId), {
headers: { Authorization: `Bearer ${token}` },
})
.then((res) => {
if (res.status === 401) {
clearToken();
navigate("/admin/login");
return;
}
if (!res.ok) throw new Error("Export failed");
return res.blob();
})
.then((blob) => {
if (!blob) return;
const url = URL.createObjectURL(blob);
window.open(url, "_blank");
})
.catch(() => {
setError("Failed to export petition");
});
}
return (
<div className="min-h-screen bg-gradient-to-b from-slate-50 to-slate-100 font-sans">
{/* Header */}
<div className="bg-white border-b border-slate-200 shadow-sm">
<div className="max-w-5xl mx-auto px-4 py-3 flex items-center justify-between">
<div className="flex items-center gap-2.5">
<ShieldCheck className="w-5 h-5 text-slate-700" />
<h1 className="text-lg font-semibold text-slate-900">
Admin Dashboard
</h1>
</div>
<div className="flex items-center gap-2">
<button
onClick={handleCreateFolder}
className="inline-flex items-center gap-1.5 text-xs text-slate-500 hover:text-slate-800 border border-slate-200 hover:border-slate-300 rounded-md px-2.5 py-1.5 transition-colors"
>
<FolderPlus className="w-3.5 h-3.5" />
Create Folder
</button>
<button
onClick={handleLogout}
className="inline-flex items-center gap-1.5 text-xs text-red-500 hover:text-red-600 border border-red-200 hover:border-red-300 rounded-md px-2.5 py-1.5 transition-colors"
>
<LogOut className="w-3.5 h-3.5" />
Logout
</button>
</div>
</div>
</div>
<div className="max-w-5xl mx-auto px-4 py-6">
{folderMsg && (
<div className="bg-blue-50 border border-blue-200 text-blue-700 text-sm rounded-lg px-4 py-2.5 mb-4">
{folderMsg}
</div>
)}
{error && (
<div className="bg-red-50 border border-red-200 text-red-700 text-sm rounded-lg px-4 py-2.5 mb-4">
{error}
</div>
)}
<div className="flex items-center justify-between mb-4">
<h2 className="text-sm font-medium text-slate-500 uppercase tracking-wide">
All Petitions
</h2>
<span className="text-xs text-slate-400">
{petitions.length} total
</span>
</div>
{loading ? (
<div className="flex items-center justify-center py-16">
<Loader2 className="w-6 h-6 text-slate-400 animate-spin" />
</div>
) : petitions.length === 0 ? (
<div className="bg-white rounded-xl border border-slate-200 p-8 text-center">
<p className="text-slate-500 text-sm">No petitions found.</p>
</div>
) : (
<div className="bg-white rounded-xl border border-slate-200 overflow-hidden shadow-sm">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-slate-200 bg-slate-50/80">
<th className="text-left px-4 py-2.5 text-xs font-medium text-slate-500 uppercase tracking-wide">
Petition
</th>
<th className="text-left px-4 py-2.5 text-xs font-medium text-slate-500 uppercase tracking-wide hidden md:table-cell">
Slug
</th>
<th className="text-center px-4 py-2.5 text-xs font-medium text-slate-500 uppercase tracking-wide">
Sigs
</th>
<th className="text-center px-4 py-2.5 text-xs font-medium text-slate-500 uppercase tracking-wide">
Status
</th>
<th className="text-center px-4 py-2.5 text-xs font-medium text-slate-500 uppercase tracking-wide">
Actions
</th>
</tr>
</thead>
<tbody>
{petitions.map((p) => (
<tr
key={p.id}
className="border-b border-slate-100 last:border-0 hover:bg-slate-50/50 transition-colors"
>
<td className="px-4 py-3">
<div className="font-medium text-slate-900 text-sm">
{p.nameEng}
</div>
<div
className="text-xs text-slate-400 dhivehi mt-0.5"
dir="rtl"
>
{p.nameDhiv}
</div>
</td>
<td className="px-4 py-3 hidden md:table-cell">
<span className="text-xs text-slate-400 font-mono bg-slate-50 px-1.5 py-0.5 rounded">
{p.slug}
</span>
</td>
<td className="px-4 py-3 text-center">
<span className="inline-flex items-center gap-1 text-slate-600 text-xs">
<Users className="w-3 h-3" />
{p.signatureCount}
</span>
</td>
<td className="px-4 py-3 text-center">
{p.isApproved ? (
<span className="inline-flex items-center gap-1 text-xs font-medium text-emerald-700 bg-emerald-50 rounded-full px-2 py-0.5">
<CheckCircle className="w-3 h-3" />
Approved
</span>
) : (
<span className="inline-flex items-center gap-1 text-xs font-medium text-amber-700 bg-amber-50 rounded-full px-2 py-0.5">
<Clock className="w-3 h-3" />
Pending
</span>
)}
</td>
<td className="px-4 py-3">
<div className="flex items-center justify-center gap-1">
<button
onClick={() => navigate(`/Petition/${p.slug || p.id}`)}
className="p-1.5 rounded-md text-slate-400 hover:text-slate-700 hover:bg-slate-100 transition-colors"
title="View petition"
>
<Eye className="w-4 h-4" />
</button>
<button
onClick={() => handleToggleApproval(p)}
disabled={togglingId === p.id}
className={`p-1.5 rounded-md transition-colors disabled:opacity-50 ${
p.isApproved
? "text-red-500 hover:text-red-700 hover:bg-red-50"
: "text-emerald-500 hover:text-emerald-700 hover:bg-emerald-50"
}`}
title={p.isApproved ? "Disapprove" : "Approve"}
>
{togglingId === p.id ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : p.isApproved ? (
<XCircle className="w-4 h-4" />
) : (
<CheckCircle className="w-4 h-4" />
)}
</button>
<button
onClick={() => handleExport(p.id)}
className="p-1.5 rounded-md text-slate-400 hover:text-blue-600 hover:bg-blue-50 transition-colors"
title="Export signatures"
>
<FileDown className="w-4 h-4" />
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,103 @@
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { login } from "@/lib/adminApi";
import { Lock, Loader2 } from "lucide-react";
export function AdminLoginPage() {
const navigate = useNavigate();
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setError(null);
setLoading(true);
try {
await login(username, password);
navigate("/admin");
} catch (err) {
setError(err instanceof Error ? err.message : "Login failed");
} finally {
setLoading(false);
}
}
return (
<div className="min-h-screen bg-gradient-to-b from-slate-50 to-slate-100 flex items-center justify-center px-4">
<div className="w-full max-w-sm">
<div className="bg-white rounded-xl border border-slate-200 shadow-sm p-8">
<div className="flex justify-center mb-6">
<div className="bg-slate-100 p-3 rounded-full">
<Lock className="w-8 h-8 text-slate-600" />
</div>
</div>
<h1 className="text-xl font-bold text-slate-900 text-center mb-6">
Admin Login
</h1>
{error && (
<div className="bg-red-50 border border-red-200 text-red-700 text-sm rounded-lg px-4 py-3 mb-4">
{error}
</div>
)}
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label
htmlFor="username"
className="block text-sm font-medium text-slate-700 mb-1"
>
Username
</label>
<input
id="username"
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
autoFocus
className="w-full px-3 py-2 border border-slate-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
/>
</div>
<div>
<label
htmlFor="password"
className="block text-sm font-medium text-slate-700 mb-1"
>
Password
</label>
<input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
className="w-full px-3 py-2 border border-slate-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
/>
</div>
<button
type="submit"
disabled={loading}
className="w-full bg-slate-900 hover:bg-slate-800 text-white font-medium py-2.5 rounded-lg transition-colors disabled:opacity-50 flex items-center justify-center gap-2"
>
{loading ? (
<>
<Loader2 className="w-4 h-4 animate-spin" />
Signing in...
</>
) : (
"Sign in"
)}
</button>
</form>
</div>
</div>
</div>
);
}

View File

@@ -85,7 +85,7 @@ function GuidelinesModal({ onAccept }: { onAccept: () => void }) {
I Understand, Continue
</button>
<a
href="https://majlis.gov.mv/en/pes/petitions"
href="https://epetition.majlis.gov.mv/petition-rules"
target="_blank"
rel="noopener noreferrer"
className="w-full bg-slate-100 hover:bg-slate-200 text-slate-700 font-medium py-3 px-6 rounded-lg transition-colors text-center"

View File

@@ -11,7 +11,8 @@ import { AuthorCard } from "@/components/petition/AuthorCard";
import { PetitionBody } from "@/components/petition/PetitionBody";
import { SignatureForm } from "@/components/signature/SignatureForm";
import { TweetModal } from "@/components/TweetModal";
import { PenLine } from "lucide-react";
import { PenLine, ArrowLeft } from "lucide-react";
import { Link } from "react-router-dom";
export function PetitionPage() {
const { slug } = useParams<{ slug: string }>();
@@ -58,7 +59,27 @@ export function PetitionPage() {
}
return (
<div className="min-h-screen bg-slate-50/50 p-4 md:p-8 font-sans">
<div className="min-h-screen bg-slate-50/50 font-sans">
<div className="sticky top-0 z-10 bg-white/90 backdrop-blur-sm border-b border-slate-200 shadow-sm">
<div className="max-w-3xl mx-auto px-4 py-2.5 flex items-center gap-3">
<Link
to="/"
className="inline-flex items-center gap-1.5 text-sm text-slate-500 hover:text-slate-900 transition-colors"
>
<ArrowLeft className="w-4 h-4" />
Home
</Link>
{petition && (
<>
<span className="text-slate-300">/</span>
<span className="text-sm text-slate-700 font-medium truncate">
{language === "dv" ? petition.nameDhiv : petition.nameEng}
</span>
</>
)}
</div>
</div>
<div className="p-4 md:p-8">
<div className="max-w-3xl mx-auto bg-white rounded-xl shadow-sm border border-slate-100 p-6 md:p-10 animate-in fade-in duration-500 slide-in-from-bottom-4">
{loading ? (
<div className="min-h-[400px] flex flex-col justify-center">
@@ -111,6 +132,7 @@ export function PetitionPage() {
</>
)}
</div>
</div>
</div>
);
}

View File

@@ -14,7 +14,7 @@ export default defineConfig({
server: {
proxy: {
"/api": {
target: "http://localhost:9755",
target: "http://localhost:5299",
changeOrigin: true,
},
},