Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 33 additions & 3 deletions apps/api/src/controllers/adminController.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,36 @@
import { ok } from "../utils/response.js";
import { getAdminMetrics } from "../services/adminService.js";
import { ok, fail } from "../utils/response.js";
import * as admin from "../services/adminService.js";

export async function metrics(req, res) {
return ok(res, await getAdminMetrics());
try { return ok(res, await admin.getAdminMetrics()); } catch (e) { return fail(res, e.message, 500); }
}
export async function listUsers(req, res) {
try { return ok(res, await admin.listUsers(req.query)); } catch (e) { return fail(res, e.message, 500); }
}
export async function getUserDetail(req, res) {
try { return ok(res, await admin.getUserDetail(req.params.id)); } catch (e) { return fail(res, e.message, 404); }
}
export async function updateUserStatus(req, res) {
try { return ok(res, await admin.updateUserStatus(req.params.id, req.body.status)); } catch (e) { return fail(res, e.message, 500); }
}
export async function listFlaggedJobs(req, res) {
try { return ok(res, await admin.listFlaggedJobs(req.query)); } catch (e) { return fail(res, e.message, 500); }
}
export async function moderateJob(req, res) {
try { return ok(res, await admin.moderateJob(req.params.id, req.body.action)); } catch (e) { return fail(res, e.message, 500); }
}
export async function listDisputes(req, res) {
try { return ok(res, await admin.listDisputes(req.query)); } catch (e) { return fail(res, e.message, 500); }
}
export async function getDisputeDetail(req, res) {
try { return ok(res, await admin.getDisputeDetail(req.params.id)); } catch (e) { return fail(res, e.message, 404); }
}
export async function resolveDispute(req, res) {
try { return ok(res, await admin.resolveDispute(req.params.id, req.body.ruling)); } catch (e) { return fail(res, e.message, 500); }
}
export async function getControls(req, res) {
try { return ok(res, await admin.getPlatformControls()); } catch (e) { return fail(res, e.message, 500); }
}
export async function updateControls(req, res) {
try { return ok(res, await admin.updatePlatformControls(req.body)); } catch (e) { return fail(res, e.message, 500); }
}
20 changes: 17 additions & 3 deletions apps/api/src/routes/adminRoutes.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,22 @@
import { Router } from "express";
import { metrics } from "../controllers/adminController.js";
import * as ctrl from "../controllers/adminController.js";
import { authMiddleware } from "../middleware/auth.js";

export const adminRoutes = Router();

adminRoutes.use(authMiddleware);
adminRoutes.get("/metrics", metrics);
adminRoutes.use((req, res, next) => {
if (!req.user || req.user.role !== "admin") return res.status(403).json({ error: "Admin access required" });
next();
});

adminRoutes.get("/metrics", ctrl.metrics);
adminRoutes.get("/users", ctrl.listUsers);
adminRoutes.get("/users/:id", ctrl.getUserDetail);
adminRoutes.patch("/users/:id/status", ctrl.updateUserStatus);
adminRoutes.get("/jobs/flagged", ctrl.listFlaggedJobs);
adminRoutes.post("/jobs/:id/moderate", ctrl.moderateJob);
adminRoutes.get("/disputes", ctrl.listDisputes);
adminRoutes.get("/disputes/:id", ctrl.getDisputeDetail);
adminRoutes.post("/disputes/:id/resolve", ctrl.resolveDispute);
adminRoutes.get("/controls", ctrl.getControls);
adminRoutes.put("/controls", ctrl.updateControls);
76 changes: 70 additions & 6 deletions apps/api/src/services/adminService.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,72 @@
import { prisma } from "../config/db.js";

export async function getAdminMetrics() {
return {
openJobs: 42,
activeFreelancers: 185,
flaggedAccounts: 3,
monthlyVolume: 128900
};
const [users, jobs, openJobs, disputes, openDisputes] = await Promise.all([
prisma.user.count(), prisma.job.count(),
prisma.job.count({ where: { status: "OPEN" } }),
prisma.dispute.count(),
prisma.dispute.count({ where: { status: { in: ["OPEN", "UNDER_REVIEW"] } } }),
]);
return { totalUsers: users, totalJobs: jobs, openJobs, totalDisputes: disputes, openDisputes };
}

export async function listUsers({ page = "1", limit = "20", role, search }) {
const where = {};
if (role) where.role = role;
if (search) where.OR = [{ name: { contains: search } }, { email: { contains: search } }];
const skip = (Number(page) - 1) * Number(limit);
const [users, total] = await Promise.all([
prisma.user.findMany({ where, skip, take: Number(limit), orderBy: { createdAt: "desc" },
select: { id: true, name: true, email: true, role: true, status: true, createdAt: true } }),
prisma.user.count({ where }),
]);
return { users, total, page: Number(page), pages: Math.ceil(total / Number(limit)) };
}

export async function getUserDetail(userId) {
return prisma.user.findUnique({ where: { id: Number(userId) }, include: { jobs: true, proposals: true } });
}

export async function updateUserStatus(userId, status) {
return prisma.user.update({ where: { id: Number(userId) }, data: { status } });
}

export async function listFlaggedJobs({ page = "1", limit = "20" }) {
const skip = (Number(page) - 1) * Number(limit);
const [jobs, total] = await Promise.all([
prisma.job.findMany({ where: { isFlagged: true }, skip, take: Number(limit),
include: { user: { select: { id: true, name: true } } }, orderBy: { createdAt: "desc" } }),
prisma.job.count({ where: { isFlagged: true } }),
]);
return { jobs, total, page: Number(page), pages: Math.ceil(total / Number(limit)) };
}

export async function moderateJob(jobId, action) {
const update = action === "reject" ? { isFlagged: false, status: "REJECTED" }
: action === "approve" ? { isFlagged: false } : {};
return prisma.job.update({ where: { id: Number(jobId) }, data: update });
}

export async function listDisputes({ page = "1", limit = "20", status }) {
const where = {};
if (status) where.status = status;
const skip = (Number(page) - 1) * Number(limit);
const [disputes, total] = await Promise.all([
prisma.dispute.findMany({ where, skip, take: Number(limit), orderBy: { createdAt: "desc" } }),
prisma.dispute.count({ where }),
]);
return { disputes, total, page: Number(page), pages: Math.ceil(total / Number(limit)) };
}

export async function getDisputeDetail(disputeId) {
return prisma.dispute.findUnique({ where: { id: Number(disputeId) }, include: { job: true } });
}

export async function resolveDispute(disputeId, ruling) {
return prisma.dispute.update({ where: { id: Number(disputeId) },
data: { status: "RESOLVED", resolution: ruling, resolvedAt: new Date() } });
}

let controls = { registrationOpen: true, jobPostingOpen: true };
export async function getPlatformControls() { return controls; }
export async function updatePlatformControls(data) { controls = { ...controls, ...data }; return controls; }
101 changes: 100 additions & 1 deletion apps/web/app/admin/page.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,107 @@
'use client';
import { useState, useEffect } from 'react';

export default function AdminPanelPage() {
const [tab, setTab] = useState('metrics');
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');

useEffect(() => { fetchData(); }, [tab]);

async function fetchData() {
setLoading(true); setError('');
try {
const token = localStorage.getItem('token');
const urls = { metrics: '/api/admin/metrics', users: '/api/admin/users?limit=50', flagged: '/api/admin/jobs/flagged?limit=50', disputes: '/api/admin/disputes?limit=50', controls: '/api/admin/controls' };
const res = await fetch(urls[tab] || '/api/admin/metrics', { headers: { Authorization: 'Bearer ' + token } });
if (res.status === 403) { setError('Admin access required — you are not an admin'); return; }
if (!res.ok) throw new Error('Failed to load');
const json = await res.json();
setData(json.data || json);
} catch (e) { setError(e.message); }
finally { setLoading(false); }
}

const tabs = ['metrics', 'users', 'flagged', 'disputes', 'controls'];

return (
<section className="card">
<h2>Admin Panel</h2>
<p>Moderation queues, trust metrics, and platform controls are available here.</p>
<p style={{ color: '#666', marginBottom: 16 }}>User management, moderation queues, dispute resolution, and platform controls</p>

<div style={{ display: 'flex', gap: 4, borderBottom: '1px solid #ddd', marginBottom: 16 }}>
{tabs.map(t => (
<button key={t} onClick={() => setTab(t)}
style={{ padding: '8px 16px', border: 'none', background: tab === t ? '#fff' : 'transparent', borderBottom: tab === t ? '2px solid #2563eb' : '2px solid transparent', color: tab === t ? '#2563eb' : '#666', fontWeight: tab === t ? 600 : 400, cursor: 'pointer' }}>
{t.charAt(0).toUpperCase() + t.slice(1)}
</button>
))}
</div>

{error && <div style={{ background: '#fef2f2', border: '1px solid #fecaca', color: '#991b1b', padding: 12, borderRadius: 8, marginBottom: 12 }}>{error}</div>}
{loading && <p style={{ color: '#999' }}>Loading...</p>}

{!loading && !error && data && (
<div>
{tab === 'metrics' && (
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(160px, 1fr))', gap: 12 }}>
{Object.entries(data).map(([k, v]) => (
<div key={k} style={{ background: '#f9fafb', padding: 16, borderRadius: 8, textAlign: 'center' }}>
<div style={{ fontSize: 28, fontWeight: 700, color: '#2563eb' }}>{String(v)}</div>
<div style={{ fontSize: 13, color: '#666', marginTop: 4 }}>{k.replace(/([A-Z])/g, ' $1').replace(/^./, c => c.toUpperCase())}</div>
</div>
))}
</div>
)}
{tab === 'users' && data.users && (
<table style={{ width: '100%', fontSize: 14, borderCollapse: 'collapse' }}>
<thead><tr style={{ borderBottom: '1px solid #e5e7eb', textAlign: 'left', color: '#666' }}><th style={{ padding: 8 }}>ID</th><th>Name</th><th>Email</th><th>Role</th><th>Status</th></tr></thead>
<tbody>{data.users.map(u => (
<tr key={u.id} style={{ borderBottom: '1px solid #f3f4f6' }}>
<td style={{ padding: 8 }}>{u.id}</td><td style={{ fontWeight: 500 }}>{u.name}</td><td>{u.email}</td>
<td><span style={{ padding: '2px 8px', borderRadius: 4, fontSize: 12, background: '#dbeafe', color: '#1e40af' }}>{u.role}</span></td>
<td><span style={{ padding: '2px 8px', borderRadius: 4, fontSize: 12, background: u.status === 'ACTIVE' ? '#dcfce7' : '#fee2e2', color: u.status === 'ACTIVE' ? '#166534' : '#991b1b' }}>{u.status}</span></td>
</tr>
))}</tbody>
</table>
)}
{tab === 'flagged' && (
<table style={{ width: '100%', fontSize: 14, borderCollapse: 'collapse' }}>
<thead><tr style={{ borderBottom: '1px solid #e5e7eb', textAlign: 'left', color: '#666' }}><th style={{ padding: 8 }}>ID</th><th>Title</th><th>Posted By</th><th>Actions</th></tr></thead>
<tbody>{(data.jobs || []).map(j => (
<tr key={j.id} style={{ borderBottom: '1px solid #f3f4f6' }}>
<td style={{ padding: 8 }}>{j.id}</td><td style={{ fontWeight: 500 }}>{j.title}</td><td>{j.user?.name || 'N/A'}</td>
<td><span style={{ padding: '2px 8px', borderRadius: 4, fontSize: 12, background: '#fef3c7', color: '#92400e' }}>FLAGGED</span></td>
</tr>
))}</tbody>
</table>
)}
{tab === 'disputes' && (
<table style={{ width: '100%', fontSize: 14, borderCollapse: 'collapse' }}>
<thead><tr style={{ borderBottom: '1px solid #e5e7eb', textAlign: 'left', color: '#666' }}><th style={{ padding: 8 }}>ID</th><th>Status</th><th>Created</th></tr></thead>
<tbody>{(data.disputes || []).map(d => (
<tr key={d.id} style={{ borderBottom: '1px solid #f3f4f6' }}>
<td style={{ padding: 8 }}>{d.id}</td>
<td><span style={{ padding: '2px 8px', borderRadius: 4, fontSize: 12, background: d.status === 'OPEN' ? '#fee2e2' : d.status === 'UNDER_REVIEW' ? '#fef3c7' : '#dcfce7', color: d.status === 'OPEN' ? '#991b1b' : d.status === 'UNDER_REVIEW' ? '#92400e' : '#166534' }}>{d.status}</span></td>
<td style={{ color: '#999' }}>{new Date(d.createdAt).toLocaleDateString()}</td>
</tr>
))}</tbody>
</table>
)}
{tab === 'controls' && (
<div>
{Object.entries(data).map(([k, v]) => (
<div key={k} style={{ display: 'flex', justifyContent: 'space-between', padding: '10px 0', borderBottom: '1px solid #f3f4f6' }}>
<span style={{ textTransform: 'capitalize' }}>{k.replace(/([A-Z])/g, ' $1')}</span>
<span style={{ padding: '2px 12px', borderRadius: 4, fontSize: 13, fontWeight: 600, background: v ? '#dcfce7' : '#fee2e2', color: v ? '#166534' : '#991b1b' }}>{v ? 'ENABLED' : 'DISABLED'}</span>
</div>
))}
</div>
)}
<p style={{ fontSize: 11, color: '#aaa', marginTop: 16 }}>{data.total ? data.total + ' total' : Object.keys(data).length + ' items'}</p>
</div>
)}
</section>
);
}
Loading