refactor(db): migrate app pages and APIs from Prisma facade to Drizzle (3)

Co-authored-by: Cursor <[email protected]>
This commit is contained in:
SimoandCursor committed 2026-08-01 14:15:32 +02:00
1 parent 2cd0863cb8
commit 580972c0a0
40 files changed
+1089 -808

No files matched your search

+34 -25
View File
@@ -1,6 +1,7 @@
import { count, desc, eq, inArray } from "drizzle-orm";
import { notFound, redirect } from "next/navigation";
import { Ban, db, SupportTickets, User } from "@/lib/db";
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
import { prisma } from "@/lib/prisma";
import { CfhDetail } from "./cfh-detail";
export default async function CfhDetailPage({
@@ -16,9 +17,11 @@ export default async function CfhDetailPage({
const ticketId = Number(id);
if (Number.isNaN(ticketId)) notFound();
const ticket = await prisma.supportTickets.findUnique({
where: { id: ticketId },
});
const [ticket] = await db
.select()
.from(SupportTickets)
.where(eq(SupportTickets.id, ticketId))
.limit(1);
if (!ticket) notFound();
const canEdit = canAccess(
@@ -30,36 +33,42 @@ export default async function CfhDetailPage({
// Fetch sender, reported, mod info
const userIds = [ticket.senderId, ticket.reportedId, ticket.modId].filter(
Boolean,
);
) as number[];
const users =
userIds.length > 0
? await prisma.user.findMany({
where: { id: { in: userIds } },
select: {
id: true,
username: true,
look: true,
rank: true,
online: true,
ipRegister: true,
mail: true,
},
})
? await db
.select({
id: User.id,
username: User.username,
look: User.look,
rank: User.rank,
online: User.online,
ipRegister: User.ipRegister,
mail: User.mail,
})
.from(User)
.where(inArray(User.id, userIds))
: [];
const userMap = Object.fromEntries(users.map((u) => [u.id, u]));
// Get ban/mute history for reported user
const reportedId = ticket.reportedId;
const [banCount, recentBans] = reportedId
const [banCountRows, recentBans] = reportedId
? await Promise.all([
prisma.ban.count({ where: { userId: reportedId } }),
prisma.ban.findMany({
where: { userId: reportedId },
orderBy: { id: "desc" },
take: 5,
}),
db
.select({ total: count() })
.from(Ban)
.where(eq(Ban.userId, reportedId)),
db
.select()
.from(Ban)
.where(eq(Ban.userId, reportedId))
.orderBy(desc(Ban.id))
.limit(5),
])
: [0, []];
: [[{ total: 0 }], []];
const banCount = Number(banCountRows[0]?.total ?? 0);
return (
<CfhDetail
+65 -54
View File
@@ -1,9 +1,20 @@
import {
and,
asc,
count,
desc,
eq,
inArray,
like,
or,
type SQL,
} from "drizzle-orm";
import { redirect } from "next/navigation";
import { getTranslations } from "next-intl/server";
import { calcPagination, parseListParams } from "@/lib/admin-helpers";
import { db, SupportTickets, User } from "@/lib/db";
import { formatDate } from "@/lib/format-date";
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
import { prisma } from "@/lib/prisma";
import { type CfhRow, CfhTable } from "./cfh-table";
export default async function CfhListPage({
@@ -23,9 +34,9 @@ export default async function CfhListPage({
const stateFilter =
stateRaw !== undefined && stateRaw !== "" ? Number(stateRaw) : -1;
const conditions: any[] = [];
const conditions: SQL[] = [];
if (stateFilter >= 0) {
conditions.push({ state: stateFilter });
conditions.push(eq(SupportTickets.state, stateFilter));
}
if (parsed.search.trim()) {
@@ -33,63 +44,63 @@ export default async function CfhListPage({
const asId = Number(q);
let userIds: number[] = [];
try {
const users = await prisma.user.findMany({
where: { username: { contains: q } },
select: { id: true },
take: 50,
});
const users = await db
.select({ id: User.id })
.from(User)
.where(like(User.username, `%${q}%`))
.limit(50);
userIds = users.map((u) => u.id);
} catch {
userIds = [];
}
conditions.push({
OR: [
{ issue: { contains: q } },
...(Number.isFinite(asId) && asId > 0 ? [{ id: asId }] : []),
...(userIds.length
? [
{ senderId: { in: userIds } },
{ reportedId: { in: userIds } },
{ modId: { in: userIds } },
]
: []),
],
});
const searchOr = [
like(SupportTickets.issue, `%${q}%`),
...(Number.isFinite(asId) && asId > 0
? [eq(SupportTickets.id, asId)]
: []),
...(userIds.length
? [
inArray(SupportTickets.senderId, userIds),
inArray(SupportTickets.reportedId, userIds),
inArray(SupportTickets.modId, userIds),
]
: []),
];
conditions.push(or(...searchOr)!);
}
const where: any =
conditions.length === 0
? {}
: conditions.length === 1
? conditions[0]
: { AND: conditions };
const where = conditions.length > 0 ? and(...conditions) : undefined;
const SORT_MAP: Record<string, any> = {
id: { id: "desc" },
issue: { issue: "asc" },
sender: { senderId: "asc" },
reported: { reportedId: "asc" },
mod: { modId: "asc" },
state: { state: "asc" },
};
const orderCol =
parsed.sort === "issue"
? SupportTickets.issue
: parsed.sort === "sender"
? SupportTickets.senderId
: parsed.sort === "reported"
? SupportTickets.reportedId
: parsed.sort === "mod"
? SupportTickets.modId
: parsed.sort === "state"
? SupportTickets.state
: SupportTickets.id;
const orderBy = parsed.order === "asc" ? asc(orderCol) : desc(orderCol);
const baseOrder = SORT_MAP[parsed.sort ?? "id"] ?? { id: "desc" };
const orderField = Object.keys(baseOrder)[0] as keyof typeof baseOrder;
const orderBy = {
[orderField]: parsed.order,
} as any;
const total = await prisma.supportTickets.count({ where }).catch(() => 0);
const [totalRows] = await db
.select({ total: count() })
.from(SupportTickets)
.where(where)
.catch(() => [{ total: 0 }]);
const total = Number(totalRows?.total ?? 0);
const pagination = calcPagination(total, parsed.page, parsed.perPage);
const tickets = await prisma.supportTickets
.findMany({
where,
orderBy,
skip: pagination.offset,
take: pagination.perPage,
})
const tickets = await db
.select()
.from(SupportTickets)
.where(where)
.orderBy(orderBy)
.limit(pagination.perPage)
.offset(pagination.offset)
.catch(() => []);
const userIds = [
@@ -98,15 +109,15 @@ export default async function CfhListPage({
...tickets.map((x) => x.reportedId),
...tickets.map((x) => x.modId),
]),
].filter(Boolean);
].filter(Boolean) as number[];
let userMap = new Map<number, string>();
if (userIds.length > 0) {
try {
const users = await prisma.user.findMany({
where: { id: { in: userIds } },
select: { id: true, username: true },
});
const users = await db
.select({ id: User.id, username: User.username })
.from(User)
.where(inArray(User.id, userIds));
userMap = new Map(users.map((u) => [u.id, u.username]));
} catch {
userMap = new Map();
+54 -33
View File
@@ -1,11 +1,12 @@
import { and, count, desc, eq, gte, inArray, like } from "drizzle-orm";
import {
AlertTriangle,
Ban,
Ban as BanIcon,
Clock,
Gavel,
Radio,
Shield,
User,
User as UserIcon,
} from "lucide-react";
import Link from "next/link";
import { redirect } from "next/navigation";
@@ -13,8 +14,8 @@ import { StatsCard } from "@/components/admin/stats-card";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { getMinStaffRank } from "@/lib/admin/min-staff-rank";
import { AdminAuditLog, Ban, db, SupportTickets, User } from "@/lib/db";
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
import { prisma } from "@/lib/prisma";
const CFH_STATES: Record<number, { label: string; class: string }> = {
0: {
@@ -38,33 +39,53 @@ export default async function ModerationDashboard() {
const minStaffRank = await getMinStaffRank();
const [
openCfh,
pickedCfh,
todayBans,
modsOnline,
openCfhRows,
pickedCfhRows,
todayBansRows,
modsOnlineRows,
recentCfh,
recentModActions,
] = await Promise.all([
prisma.supportTickets.count({ where: { state: 0 } }),
prisma.supportTickets.count({ where: { state: 1 } }),
prisma.ban.count({ where: { timestamp: { gte: todayStart } } }),
prisma.user.count({
where: { online: "1", rank: { gte: minStaffRank } },
}),
prisma.supportTickets.findMany({
orderBy: { id: "desc" },
take: 10,
}),
prisma.adminAuditLog.findMany({
where: {
action: { startsWith: "mod_" },
},
orderBy: { id: "desc" },
take: 10,
include: { user: { select: { username: true } } },
}),
db
.select({ total: count() })
.from(SupportTickets)
.where(eq(SupportTickets.state, 0)),
db
.select({ total: count() })
.from(SupportTickets)
.where(eq(SupportTickets.state, 1)),
db
.select({ total: count() })
.from(Ban)
.where(gte(Ban.timestamp, todayStart)),
db
.select({ total: count() })
.from(User)
.where(and(eq(User.online, "1"), gte(User.rank, minStaffRank))),
db.select().from(SupportTickets).orderBy(desc(SupportTickets.id)).limit(10),
db
.select({
id: AdminAuditLog.id,
action: AdminAuditLog.action,
details: AdminAuditLog.details,
createdAt: AdminAuditLog.createdAt,
userId: AdminAuditLog.userId,
target: AdminAuditLog.target,
targetId: AdminAuditLog.targetId,
username: User.username,
})
.from(AdminAuditLog)
.leftJoin(User, eq(AdminAuditLog.userId, User.id))
.where(like(AdminAuditLog.action, "mod_%"))
.orderBy(desc(AdminAuditLog.id))
.limit(10),
]);
const openCfh = Number(openCfhRows[0]?.total ?? 0);
const pickedCfh = Number(pickedCfhRows[0]?.total ?? 0);
const todayBans = Number(todayBansRows[0]?.total ?? 0);
const modsOnline = Number(modsOnlineRows[0]?.total ?? 0);
// Fetch usernames for CFH tickets
const userIds = [
...new Set([
@@ -72,14 +93,14 @@ export default async function ModerationDashboard() {
...recentCfh.map((t) => t.reportedId),
...recentCfh.map((t) => t.modId),
]),
].filter(Boolean);
].filter(Boolean) as number[];
const users =
userIds.length > 0
? await prisma.user.findMany({
where: { id: { in: userIds } },
select: { id: true, username: true },
})
? await db
.select({ id: User.id, username: User.username })
.from(User)
.where(inArray(User.id, userIds))
: [];
const userMap = new Map(users.map((u) => [u.id, u.username]));
@@ -97,7 +118,7 @@ export default async function ModerationDashboard() {
<StatsCard
title="Bans Today"
value={todayBans}
icon={<Ban className="h-4 w-4" />}
icon={<BanIcon className="h-4 w-4" />}
href="/admin/bans"
/>
<StatsCard
@@ -190,13 +211,13 @@ export default async function ModerationDashboard() {
key={log.id}
className="flex items-center gap-3 py-2.5 first:pt-0 last:pb-0"
>
<User className="h-3.5 w-3.5 text-muted-foreground shrink-0" />
<UserIcon className="h-3.5 w-3.5 text-muted-foreground shrink-0" />
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">
{log.action.replace("mod_", "").replace(/_/g, " ")}
</p>
<p className="text-xs text-muted-foreground">
by {log.user?.username ?? "?"} · {log.target}{" "}
by {log.username ?? "?"} · {log.target}{" "}
{log.targetId ? `#${log.targetId}` : ""}
</p>
</div>
+61 -35
View File
@@ -1,11 +1,18 @@
import { and, count, desc, gte, inArray, like } from "drizzle-orm";
import Link from "next/link";
import { redirect } from "next/navigation";
import { AvatarImage } from "@/components/shared/avatar-image";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent } from "@/components/ui/card";
import { getMinStaffRank } from "@/lib/admin/min-staff-rank";
import {
AdminAuditLog,
db,
SupportTickets,
User,
WebsiteTicket,
} from "@/lib/db";
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
import { prisma } from "@/lib/prisma";
export default async function ModTeamPage() {
const { session, permissions } = await getAdminContext();
@@ -13,48 +20,67 @@ export default async function ModTeamPage() {
redirect("/admin");
const minStaffRank = await getMinStaffRank();
const staff = await prisma.user.findMany({
where: { rank: { gte: minStaffRank } },
select: {
id: true,
username: true,
look: true,
rank: true,
online: true,
lastLogin: true,
lastOnline: true,
},
orderBy: [{ online: "desc" }, { rank: "desc" }],
});
const staff = await db
.select({
id: User.id,
username: User.username,
look: User.look,
rank: User.rank,
online: User.online,
lastLogin: User.lastLogin,
lastOnline: User.lastOnline,
})
.from(User)
.where(gte(User.rank, minStaffRank))
.orderBy(desc(User.online), desc(User.rank));
const staffIds = staff.map((s) => s.id);
// Get CFH ticket counts per mod and web ticket counts
const [cfhCounts, webTicketCounts, modActionCounts] = await Promise.all([
prisma.supportTickets.groupBy({
by: ["modId"],
where: { modId: { in: staff.map((s) => s.id) } },
_count: { _all: true },
}),
prisma.websiteTicket.groupBy({
by: ["assigneeId"],
where: { assigneeId: { in: staff.map((s) => s.id) } },
_count: { _all: true },
}),
prisma.adminAuditLog.groupBy({
by: ["userId"],
where: {
userId: { in: staff.map((s) => s.id) },
action: { startsWith: "mod_" },
},
_count: { _all: true },
}),
staffIds.length
? db
.select({
modId: SupportTickets.modId,
total: count(),
})
.from(SupportTickets)
.where(inArray(SupportTickets.modId, staffIds))
.groupBy(SupportTickets.modId)
: Promise.resolve([]),
staffIds.length
? db
.select({
assigneeId: WebsiteTicket.assigneeId,
total: count(),
})
.from(WebsiteTicket)
.where(inArray(WebsiteTicket.assigneeId, staffIds))
.groupBy(WebsiteTicket.assigneeId)
: Promise.resolve([]),
staffIds.length
? db
.select({
userId: AdminAuditLog.userId,
total: count(),
})
.from(AdminAuditLog)
.where(
and(
inArray(AdminAuditLog.userId, staffIds),
like(AdminAuditLog.action, "mod_%"),
),
)
.groupBy(AdminAuditLog.userId)
: Promise.resolve([]),
]);
const cfhMap = new Map(cfhCounts.map((c) => [c.modId, c._count._all]));
const cfhMap = new Map(cfhCounts.map((c) => [c.modId, Number(c.total)]));
const webMap = new Map(
webTicketCounts.map((c) => [c.assigneeId, c._count._all]),
webTicketCounts.map((c) => [c.assigneeId, Number(c.total)]),
);
const actionMap = new Map(
modActionCounts.map((c) => [c.userId, c._count._all]),
modActionCounts.map((c) => [c.userId, Number(c.total)]),
);
return (