feat(admin): add admin panel with dashboard, users, and codes management

- Add admin layout with sidebar navigation and session guard
- Create AdminSidebar client component with role-based nav links
- Add dashboard page showing stats (admin count, code counts)
- Add users management page (SuperAdmin only): list, create, delete,
  and reset passwords for admin users
- Add codes management page: list all codes, generate new codes,
  delete unused codes
- Add API routes for admin user CRUD (GET, POST, DELETE, PUT)
- Add API routes for code management (GET, POST, DELETE)
- All UI in Macedonian
This commit is contained in:
dimitar 2026-07-29 18:56:49 +02:00
parent 14d0b533af
commit 9ca66fc753
9 changed files with 610 additions and 0 deletions

View File

@ -0,0 +1,57 @@
"use client";
import Link from "next/link";
import { useRouter, usePathname } from "next/navigation";
interface Props {
username: string;
role: "SUPER_ADMIN" | "ADMIN";
}
export default function AdminSidebar({ username, role }: Props) {
const router = useRouter();
const pathname = usePathname();
const handleLogout = async () => {
await fetch("/api/admin/logout", { method: "POST" });
router.push("/admin/login");
};
const links = [
{ href: "/admin/dashboard", label: "Контролна табла" },
...(role === "SUPER_ADMIN" ? [{ href: "/admin/users", label: "Администратори" }] : []),
{ href: "/admin/codes", label: "Кодови" },
];
return (
<aside className="flex w-64 flex-col bg-primary text-white">
<div className="border-b border-white/10 px-6 py-5">
<h2 className="text-lg font-semibold">СпоменQR</h2>
<p className="mt-1 text-xs text-white/60">
{username} {role === "SUPER_ADMIN" ? "(SuperAdmin)" : "(Admin)"}
</p>
</div>
<nav className="flex-1 space-y-1 px-3 py-4">
{links.map((link) => (
<Link
key={link.href}
href={link.href}
className={`block rounded-md px-3 py-2 text-sm transition-colors ${
pathname === link.href ? "bg-white/15 text-white" : "text-white/70 hover:bg-white/10 hover:text-white"
}`}
>
{link.label}
</Link>
))}
</nav>
<div className="border-t border-white/10 px-3 py-4">
<button
onClick={handleLogout}
className="block w-full rounded-md px-3 py-2 text-left text-sm text-white/70 transition-colors hover:bg-white/10 hover:text-white"
>
Одјави се
</button>
</div>
</aside>
);
}

View File

@ -0,0 +1,144 @@
"use client";
import { useEffect, useState } from "react";
interface Code {
id: string;
code: string;
usedByUserId: string | null;
usedAt: string | null;
createdAt: string;
createdBy: { username: string };
}
export default function AdminCodesPage() {
const [codes, setCodes] = useState<Code[]>([]);
const [loading, setLoading] = useState(true);
const [generating, setGenerating] = useState(false);
const [newCode, setNewCode] = useState("");
const [error, setError] = useState("");
const fetchCodes = async () => {
setLoading(true);
try {
const res = await fetch("/api/admin/codes");
if (res.ok) {
setCodes(await res.json());
}
} catch {
// ignore
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchCodes();
}, []);
const handleGenerate = async () => {
setGenerating(true);
setError("");
setNewCode("");
try {
const res = await fetch("/api/admin/codes", { method: "POST" });
const data = await res.json();
if (!res.ok) {
throw new Error(data.error || "Грешка при генерирање");
}
setNewCode(data.code);
fetchCodes();
} catch (err) {
setError(err instanceof Error ? err.message : "Грешка при генерирање");
} finally {
setGenerating(false);
}
};
const handleDelete = async (id: string) => {
if (!confirm("Дали сте сигурни?")) return;
try {
await fetch(`/api/admin/codes/${id}`, { method: "DELETE" });
fetchCodes();
} catch {
// ignore
}
};
return (
<div>
<div className="mb-8 flex items-center justify-between">
<h1 className="text-2xl font-semibold text-stone-900">Кодови</h1>
<button
onClick={handleGenerate}
disabled={generating}
className="rounded-lg bg-primary px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-primary-light disabled:cursor-not-allowed disabled:opacity-50"
>
{generating ? "Генерирање..." : "Генерирај код"}
</button>
</div>
{newCode && (
<div className="mb-8 rounded-lg border border-green-200 bg-green-50 p-4">
<p className="text-sm font-medium text-green-800">Нов код:</p>
<p className="mt-1 text-2xl font-bold tracking-widest text-green-900">{newCode}</p>
<p className="mt-1 text-xs text-green-600">Копирајте го кодот. Ќе биде прикажан само еднаш.</p>
</div>
)}
{error && (
<div className="mb-8 rounded-lg bg-red-50 p-4 text-sm text-red-700">{error}</div>
)}
<div className="rounded-lg bg-white shadow-sm">
{loading ? (
<p className="p-6 text-sm text-stone-500">Вчитување...</p>
) : codes.length === 0 ? (
<p className="p-6 text-sm text-stone-500">Нема генерирани кодови</p>
) : (
<table className="w-full text-left text-sm">
<thead className="border-b border-stone-200">
<tr>
<th className="px-6 py-3 font-medium text-stone-500">Код</th>
<th className="px-6 py-3 font-medium text-stone-500">Креиран од</th>
<th className="px-6 py-3 font-medium text-stone-500">Креиран</th>
<th className="px-6 py-3 font-medium text-stone-500">Статус</th>
<th className="px-6 py-3 font-medium text-stone-500">Акции</th>
</tr>
</thead>
<tbody className="divide-y divide-stone-100">
{codes.map((item) => (
<tr key={item.id} className="hover:bg-stone-50">
<td className="px-6 py-4 font-mono text-stone-900">{item.code}</td>
<td className="px-6 py-4 text-stone-600">{item.createdBy.username}</td>
<td className="px-6 py-4 text-stone-600">{new Date(item.createdAt).toLocaleDateString("mk-MK")}</td>
<td className="px-6 py-4">
{item.usedByUserId ? (
<span className="inline-flex rounded-full bg-green-100 px-2.5 py-0.5 text-xs font-medium text-green-800">
Искористен
</span>
) : (
<span className="inline-flex rounded-full bg-stone-100 px-2.5 py-0.5 text-xs font-medium text-stone-600">
Неискористен
</span>
)}
</td>
<td className="px-6 py-4">
{!item.usedByUserId && (
<button
onClick={() => handleDelete(item.id)}
className="text-sm text-red-600 hover:underline"
>
Избриши
</button>
)}
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
</div>
);
}

View File

@ -0,0 +1,29 @@
import { prisma } from "@/lib/prisma";
export default async function AdminDashboardPage() {
const [adminCount, codeCount, usedCodeCount] = await Promise.all([
prisma.adminUser.count(),
prisma.code.count(),
prisma.code.count({ where: { usedByUserId: { not: null } } }),
]);
return (
<div>
<h1 className="mb-8 text-2xl font-semibold text-stone-900">Контролна табла</h1>
<div className="grid gap-6 sm:grid-cols-3">
<div className="rounded-lg bg-white p-6 shadow-sm">
<p className="text-sm text-stone-500">Администратори</p>
<p className="mt-1 text-3xl font-semibold text-stone-900">{adminCount}</p>
</div>
<div className="rounded-lg bg-white p-6 shadow-sm">
<p className="text-sm text-stone-500">Генерирани кодови</p>
<p className="mt-1 text-3xl font-semibold text-stone-900">{codeCount}</p>
</div>
<div className="rounded-lg bg-white p-6 shadow-sm">
<p className="text-sm text-stone-500">Искористени кодови</p>
<p className="mt-1 text-3xl font-semibold text-stone-900">{usedCodeCount}</p>
</div>
</div>
</div>
);
}

17
src/app/admin/layout.tsx Normal file
View File

@ -0,0 +1,17 @@
import { getAdminSession } from "@/lib/admin-session";
import { redirect } from "next/navigation";
import AdminSidebar from "./AdminSidebar";
export default async function AdminLayout({ children }: { children: React.ReactNode }) {
const session = await getAdminSession();
if (!session) {
redirect("/admin/login");
}
return (
<div className="flex min-h-screen bg-stone-100">
<AdminSidebar username={session.username} role={session.role} />
<main className="flex-1 p-8">{children}</main>
</div>
);
}

View File

@ -0,0 +1,187 @@
"use client";
import { useEffect, useState } from "react";
interface AdminUser {
id: string;
username: string;
role: string;
createdAt: string;
}
export default function AdminUsersPage() {
const [users, setUsers] = useState<AdminUser[]>([]);
const [loading, setLoading] = useState(true);
const [showCreate, setShowCreate] = useState(false);
const [newUsername, setNewUsername] = useState("");
const [newPassword, setNewPassword] = useState("");
const [error, setError] = useState("");
const fetchUsers = async () => {
setLoading(true);
try {
const res = await fetch("/api/admin/users");
if (res.ok) {
setUsers(await res.json());
}
} catch {
// ignore
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchUsers();
}, []);
const handleCreate = async (e: React.FormEvent) => {
e.preventDefault();
setError("");
try {
const res = await fetch("/api/admin/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username: newUsername, password: newPassword }),
});
if (!res.ok) {
const data = await res.json();
throw new Error(data.error || "Грешка при креирање");
}
setShowCreate(false);
setNewUsername("");
setNewPassword("");
fetchUsers();
} catch (err) {
setError(err instanceof Error ? err.message : "Грешка при креирање");
}
};
const handleDelete = async (id: string) => {
if (!confirm("Дали сте сигурни дека сакате да го избришете овој администратор?")) return;
try {
const res = await fetch(`/api/admin/users/${id}`, { method: "DELETE" });
if (res.ok) {
fetchUsers();
}
} catch {
// ignore
}
};
const handleResetPassword = async (id: string) => {
const newPw = prompt("Внесете нова лозинка:");
if (!newPw || newPw.length < 6) {
alert("Лозинката мора да има најмалку 6 карактери");
return;
}
try {
const res = await fetch(`/api/admin/users/${id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password: newPw }),
});
if (res.ok) {
alert("Лозинката е променета");
} else {
const data = await res.json();
alert(data.error || "Грешка");
}
} catch {
alert("Грешка");
}
};
return (
<div>
<div className="mb-8 flex items-center justify-between">
<h1 className="text-2xl font-semibold text-stone-900">Администратори</h1>
<button
onClick={() => setShowCreate(!showCreate)}
className="rounded-lg bg-primary px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-primary-light"
>
{showCreate ? "Откажи" : "Креирај администратор"}
</button>
</div>
{showCreate && (
<form onSubmit={handleCreate} className="mb-8 rounded-lg bg-white p-6 shadow-sm">
<div className="mb-4 grid gap-4 sm:grid-cols-2">
<div>
<label className="block text-sm font-medium text-stone-700">Корисничко име</label>
<input
type="text"
value={newUsername}
onChange={(e) => setNewUsername(e.target.value)}
className="mt-1 block w-full rounded-lg border border-stone-200 px-3 py-2.5 text-stone-900 focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
required
/>
</div>
<div>
<label className="block text-sm font-medium text-stone-700">Лозинка</label>
<input
type="password"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
className="mt-1 block w-full rounded-lg border border-stone-200 px-3 py-2.5 text-stone-900 focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
required
minLength={6}
/>
</div>
</div>
{error && <p className="mb-4 text-sm text-red-600">{error}</p>}
<button
type="submit"
className="rounded-lg bg-primary px-6 py-2 text-sm font-medium text-white transition-colors hover:bg-primary-light"
>
Креирај
</button>
</form>
)}
<div className="rounded-lg bg-white shadow-sm">
{loading ? (
<p className="p-6 text-sm text-stone-500">Вчитување...</p>
) : users.length === 0 ? (
<p className="p-6 text-sm text-stone-500">Нема администратори</p>
) : (
<table className="w-full text-left text-sm">
<thead className="border-b border-stone-200">
<tr>
<th className="px-6 py-3 font-medium text-stone-500">Корисничко име</th>
<th className="px-6 py-3 font-medium text-stone-500">Улога</th>
<th className="px-6 py-3 font-medium text-stone-500">Креиран</th>
<th className="px-6 py-3 font-medium text-stone-500">Акции</th>
</tr>
</thead>
<tbody className="divide-y divide-stone-100">
{users.map((user) => (
<tr key={user.id} className="hover:bg-stone-50">
<td className="px-6 py-4 text-stone-900">{user.username}</td>
<td className="px-6 py-4 text-stone-600">{user.role === "SUPER_ADMIN" ? "SuperAdmin" : "Admin"}</td>
<td className="px-6 py-4 text-stone-600">{new Date(user.createdAt).toLocaleDateString("mk-MK")}</td>
<td className="space-x-2 px-6 py-4">
<button
onClick={() => handleResetPassword(user.id)}
className="text-sm text-primary hover:underline"
>
Промени лозинка
</button>
{user.role !== "SUPER_ADMIN" && (
<button
onClick={() => handleDelete(user.id)}
className="text-sm text-red-600 hover:underline"
>
Избриши
</button>
)}
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
</div>
);
}

View File

@ -0,0 +1,29 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { getAdminSession } from "@/lib/admin-session";
export async function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const session = await getAdminSession();
if (!session) {
return NextResponse.json({ error: "Неавторизирано" }, { status: 401 });
}
const { id } = await params;
const code = await prisma.code.findUnique({ where: { id } });
if (!code) {
return NextResponse.json({ error: "Кодот не е пронајден" }, { status: 404 });
}
if (code.usedByUserId) {
return NextResponse.json({ error: "Не можете да избришете искористен код" }, { status: 400 });
}
if (session.role !== "SUPER_ADMIN") {
const admin = await prisma.adminUser.findUnique({ where: { username: session.username } });
if (!admin || code.createdById !== admin.id) {
return NextResponse.json({ error: "Немате дозвола" }, { status: 403 });
}
}
await prisma.code.delete({ where: { id } });
return NextResponse.json({ success: true });
}

View File

@ -0,0 +1,44 @@
import { NextRequest, NextResponse } from "next/server";
import { randomBytes } from "crypto";
import { prisma } from "@/lib/prisma";
import { getAdminSession } from "@/lib/admin-session";
export async function GET() {
const session = await getAdminSession();
if (!session) {
return NextResponse.json({ error: "Неавторизирано" }, { status: 401 });
}
const where = session.role === "SUPER_ADMIN" ? {} : { createdBy: { username: session.username } };
const codes = await prisma.code.findMany({
where,
orderBy: { createdAt: "desc" },
include: { createdBy: { select: { username: true } } },
});
return NextResponse.json(codes);
}
export async function POST() {
const session = await getAdminSession();
if (!session) {
return NextResponse.json({ error: "Неавторизирано" }, { status: 401 });
}
const admin = await prisma.adminUser.findUnique({ where: { username: session.username } });
if (!admin) {
return NextResponse.json({ error: "Администраторот не е пронајден" }, { status: 404 });
}
const code = randomBytes(6).toString("hex").toUpperCase();
const created = await prisma.code.create({
data: {
code,
createdById: admin.id,
},
});
return NextResponse.json(created, { status: 201 });
}

View File

@ -0,0 +1,54 @@
import { NextRequest, NextResponse } from "next/server";
import { hash } from "bcryptjs";
import { prisma } from "@/lib/prisma";
import { getAdminSession } from "@/lib/admin-session";
export async function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const session = await getAdminSession();
if (!session || session.role !== "SUPER_ADMIN") {
return NextResponse.json({ error: "Немате дозвола" }, { status: 403 });
}
const { id } = await params;
const user = await prisma.adminUser.findUnique({ where: { id } });
if (!user) {
return NextResponse.json({ error: "Администраторот не е пронајден" }, { status: 404 });
}
if (user.role === "SUPER_ADMIN") {
return NextResponse.json({ error: "Не можете да избришете SuperAdmin" }, { status: 400 });
}
await prisma.adminUser.delete({ where: { id } });
return NextResponse.json({ success: true });
}
export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const session = await getAdminSession();
if (!session || session.role !== "SUPER_ADMIN") {
return NextResponse.json({ error: "Немате дозвола" }, { status: 403 });
}
try {
const { id } = await params;
const { password } = await req.json();
if (!password || password.length < 6) {
return NextResponse.json({ error: "Лозинката мора да има најмалку 6 карактери" }, { status: 400 });
}
const user = await prisma.adminUser.findUnique({ where: { id } });
if (!user) {
return NextResponse.json({ error: "Администраторот не е пронајден" }, { status: 404 });
}
const passwordHash = await hash(password, 12);
await prisma.adminUser.update({
where: { id },
data: { passwordHash },
});
return NextResponse.json({ success: true });
} catch (error) {
console.error("Update admin error:", error);
return NextResponse.json({ error: "Внатрешна грешка на серверот" }, { status: 500 });
}
}

View File

@ -0,0 +1,49 @@
import { NextRequest, NextResponse } from "next/server";
import { hash } from "bcryptjs";
import { prisma } from "@/lib/prisma";
import { getAdminSession } from "@/lib/admin-session";
export async function GET() {
const session = await getAdminSession();
if (!session || session.role !== "SUPER_ADMIN") {
return NextResponse.json({ error: "Немате дозвола" }, { status: 403 });
}
const users = await prisma.adminUser.findMany({
orderBy: { createdAt: "desc" },
});
return NextResponse.json(users);
}
export async function POST(req: NextRequest) {
const session = await getAdminSession();
if (!session || session.role !== "SUPER_ADMIN") {
return NextResponse.json({ error: "Немате дозвола" }, { status: 403 });
}
try {
const { username, password } = await req.json();
if (!username || !password) {
return NextResponse.json({ error: "Корисничко име и лозинка се задолжителни" }, { status: 400 });
}
if (password.length < 6) {
return NextResponse.json({ error: "Лозинката мора да има најмалку 6 карактери" }, { status: 400 });
}
const existing = await prisma.adminUser.findUnique({ where: { username } });
if (existing) {
return NextResponse.json({ error: "Корисничкото име веќе постои" }, { status: 409 });
}
const passwordHash = await hash(password, 12);
const user = await prisma.adminUser.create({
data: { username, passwordHash, role: "ADMIN" },
});
return NextResponse.json(user, { status: 201 });
} catch (error) {
console.error("Create admin error:", error);
return NextResponse.json({ error: "Внатрешна грешка на серверот" }, { status: 500 });
}
}