refactor(db): migrate app pages and APIs from Prisma facade to Drizzle (5)
Co-authored-by: Cursor <[email protected]>
This commit is contained in:
1 parent
9aa4f331bf
commit
30b54e99e7
40 files changed
+1183
-784
No files matched your search
@@ -1,23 +1,39 @@
|
||||
import { desc, eq, gt, or } from "drizzle-orm";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import { StatusCard } from "@/components/admin/dashboard";
|
||||
import { requireModPermission } from "@/lib/admin/guard";
|
||||
import { activeBanWhere, unixNow } from "@/lib/bans";
|
||||
import { unixNow } from "@/lib/bans";
|
||||
import { Ban, db } from "@/lib/db";
|
||||
import { formatDate } from "@/lib/format-date";
|
||||
import { PERMS } from "@/lib/permissions";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
type BanRow = {
|
||||
id: number;
|
||||
userId: number;
|
||||
type: "account" | "ip" | "machine" | "super";
|
||||
banReason: string;
|
||||
banExpire: number;
|
||||
};
|
||||
|
||||
export default async function ModBansPage() {
|
||||
await requireModPermission([PERMS.MOD_BANS_VIEW, PERMS.BANS_VIEW]);
|
||||
|
||||
const t = await getTranslations("pages.admin.bans");
|
||||
const now = unixNow();
|
||||
let bans: Awaited<ReturnType<typeof prisma.ban.findMany>> = [];
|
||||
let bans: BanRow[] = [];
|
||||
try {
|
||||
bans = await prisma.ban.findMany({
|
||||
where: activeBanWhere(now),
|
||||
orderBy: { timestamp: "desc" },
|
||||
take: 100,
|
||||
});
|
||||
bans = await db
|
||||
.select({
|
||||
id: Ban.id,
|
||||
userId: Ban.userId,
|
||||
type: Ban.type,
|
||||
banReason: Ban.banReason,
|
||||
banExpire: Ban.banExpire,
|
||||
})
|
||||
.from(Ban)
|
||||
.where(or(eq(Ban.banExpire, 0), gt(Ban.banExpire, now)))
|
||||
.orderBy(desc(Ban.timestamp))
|
||||
.limit(100);
|
||||
} catch {
|
||||
bans = [];
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { count, desc, eq, inArray } from "drizzle-orm";
|
||||
import { notFound } from "next/navigation";
|
||||
import { CfhDetail } from "@/app/admin/moderation/cfh/[id]/cfh-detail";
|
||||
import { requireModPermission } from "@/lib/admin/guard";
|
||||
import { Ban, db, SupportTickets, User } from "@/lib/db";
|
||||
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
export default async function ModCfhDetailPage({
|
||||
params,
|
||||
@@ -16,9 +17,11 @@ export default async function ModCfhDetailPage({
|
||||
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 =
|
||||
@@ -30,32 +33,49 @@ export default async function ModCfhDetailPage({
|
||||
);
|
||||
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]));
|
||||
|
||||
const reportedId = ticket.reportedId;
|
||||
const [banCount, recentBans] = reportedId
|
||||
? await Promise.all([
|
||||
prisma.ban.count({ where: { userId: reportedId } }),
|
||||
prisma.ban.findMany({
|
||||
where: { userId: reportedId },
|
||||
orderBy: { id: "desc" },
|
||||
take: 5,
|
||||
}),
|
||||
])
|
||||
: [0, []];
|
||||
let banCount = 0;
|
||||
let recentBans: {
|
||||
id: number;
|
||||
banReason: string;
|
||||
type: string;
|
||||
userStaffId: number;
|
||||
timestamp: number;
|
||||
}[] = [];
|
||||
if (reportedId) {
|
||||
const [countRows, bans] = await Promise.all([
|
||||
db.select({ total: count() }).from(Ban).where(eq(Ban.userId, reportedId)),
|
||||
db
|
||||
.select({
|
||||
id: Ban.id,
|
||||
banReason: Ban.banReason,
|
||||
type: Ban.type,
|
||||
userStaffId: Ban.userStaffId,
|
||||
timestamp: Ban.timestamp,
|
||||
})
|
||||
.from(Ban)
|
||||
.where(eq(Ban.userId, reportedId))
|
||||
.orderBy(desc(Ban.id))
|
||||
.limit(5),
|
||||
]);
|
||||
banCount = countRows[0]?.total ?? 0;
|
||||
recentBans = bans;
|
||||
}
|
||||
|
||||
return (
|
||||
<CfhDetail
|
||||
|
||||
+67
-53
@@ -1,9 +1,29 @@
|
||||
import {
|
||||
and,
|
||||
asc,
|
||||
count,
|
||||
desc,
|
||||
eq,
|
||||
inArray,
|
||||
like,
|
||||
or,
|
||||
type SQL,
|
||||
} from "drizzle-orm";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import { type CfhRow, CfhTable } from "@/app/admin/moderation/cfh/cfh-table";
|
||||
import { requireModPermission } from "@/lib/admin/guard";
|
||||
import { calcPagination, parseListParams } from "@/lib/admin-helpers";
|
||||
import { db, SupportTickets, User } from "@/lib/db";
|
||||
import { PERMS } from "@/lib/permissions";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
const SORT_COLS = {
|
||||
id: SupportTickets.id,
|
||||
issue: SupportTickets.issue,
|
||||
sender: SupportTickets.senderId,
|
||||
reported: SupportTickets.reportedId,
|
||||
mod: SupportTickets.modId,
|
||||
state: SupportTickets.state,
|
||||
} as const;
|
||||
|
||||
export default async function ModCfhListPage({
|
||||
searchParams,
|
||||
@@ -19,9 +39,9 @@ export default async function ModCfhListPage({
|
||||
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()) {
|
||||
@@ -29,63 +49,57 @@ export default async function ModCfhListPage({
|
||||
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 ors: SQL[] = [like(SupportTickets.issue, `%${q}%`)];
|
||||
if (Number.isFinite(asId) && asId > 0) {
|
||||
ors.push(eq(SupportTickets.id, asId));
|
||||
}
|
||||
if (userIds.length) {
|
||||
ors.push(inArray(SupportTickets.senderId, userIds));
|
||||
ors.push(inArray(SupportTickets.reportedId, userIds));
|
||||
ors.push(inArray(SupportTickets.modId, userIds));
|
||||
}
|
||||
conditions.push(or(...ors)!);
|
||||
}
|
||||
|
||||
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 sortKey =
|
||||
parsed.sort && parsed.sort in SORT_COLS
|
||||
? (parsed.sort as keyof typeof SORT_COLS)
|
||||
: "id";
|
||||
const sortCol = SORT_COLS[sortKey];
|
||||
const finalOrder =
|
||||
parsed.sort && parsed.sort in SORT_COLS
|
||||
? parsed.order === "asc"
|
||||
? asc(sortCol)
|
||||
: desc(sortCol)
|
||||
: desc(SupportTickets.id);
|
||||
|
||||
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 total = await db
|
||||
.select({ total: count() })
|
||||
.from(SupportTickets)
|
||||
.where(where)
|
||||
.then((rows) => rows[0]?.total ?? 0)
|
||||
.catch(() => 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(finalOrder)
|
||||
.offset(pagination.offset)
|
||||
.limit(pagination.perPage)
|
||||
.catch(() => []);
|
||||
|
||||
const userIds = [
|
||||
@@ -99,10 +113,10 @@ export default async function ModCfhListPage({
|
||||
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();
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
import { asc, eq, inArray } from "drizzle-orm";
|
||||
import { notFound } from "next/navigation";
|
||||
import { AdminHelpTicketDetail } from "@/app/admin/help-tickets/[id]/admin-help-ticket-detail";
|
||||
import { requireModPermission } from "@/lib/admin/guard";
|
||||
import { getMinStaffRank } from "@/lib/admin/min-staff-rank";
|
||||
import { positiveBigInt } from "@/lib/api";
|
||||
import {
|
||||
db,
|
||||
User,
|
||||
WebsiteHelpCenterTicketReplies,
|
||||
WebsiteHelpCenterTickets,
|
||||
} from "@/lib/db";
|
||||
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
export default async function ModHelpTicketDetailPage({
|
||||
params,
|
||||
@@ -18,31 +24,32 @@ export default async function ModHelpTicketDetailPage({
|
||||
const ticketId = positiveBigInt(id);
|
||||
if (!ticketId) notFound();
|
||||
|
||||
const ticket = await prisma.websiteHelpCenterTickets.findUnique({
|
||||
where: { id: ticketId },
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
title: true,
|
||||
content: true,
|
||||
open: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
});
|
||||
const [ticket] = await db
|
||||
.select({
|
||||
id: WebsiteHelpCenterTickets.id,
|
||||
userId: WebsiteHelpCenterTickets.userId,
|
||||
title: WebsiteHelpCenterTickets.title,
|
||||
content: WebsiteHelpCenterTickets.content,
|
||||
open: WebsiteHelpCenterTickets.open,
|
||||
createdAt: WebsiteHelpCenterTickets.createdAt,
|
||||
updatedAt: WebsiteHelpCenterTickets.updatedAt,
|
||||
})
|
||||
.from(WebsiteHelpCenterTickets)
|
||||
.where(eq(WebsiteHelpCenterTickets.id, ticketId))
|
||||
.limit(1);
|
||||
|
||||
if (!ticket) notFound();
|
||||
|
||||
const replies = await prisma.websiteHelpCenterTicketReplies.findMany({
|
||||
where: { ticketId: ticket.id },
|
||||
orderBy: { id: "asc" },
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
content: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
const replies = await db
|
||||
.select({
|
||||
id: WebsiteHelpCenterTicketReplies.id,
|
||||
userId: WebsiteHelpCenterTicketReplies.userId,
|
||||
content: WebsiteHelpCenterTicketReplies.content,
|
||||
createdAt: WebsiteHelpCenterTicketReplies.createdAt,
|
||||
})
|
||||
.from(WebsiteHelpCenterTicketReplies)
|
||||
.where(eq(WebsiteHelpCenterTicketReplies.ticketId, ticket.id))
|
||||
.orderBy(asc(WebsiteHelpCenterTicketReplies.id));
|
||||
|
||||
const authorIds = [
|
||||
...new Set([
|
||||
@@ -53,15 +60,15 @@ export default async function ModHelpTicketDetailPage({
|
||||
|
||||
const users =
|
||||
authorIds.length > 0
|
||||
? await prisma.user.findMany({
|
||||
where: { id: { in: authorIds } },
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
rank: true,
|
||||
mail: true,
|
||||
},
|
||||
})
|
||||
? await db
|
||||
.select({
|
||||
id: User.id,
|
||||
username: User.username,
|
||||
rank: User.rank,
|
||||
mail: User.mail,
|
||||
})
|
||||
.from(User)
|
||||
.where(inArray(User.id, authorIds))
|
||||
: [];
|
||||
|
||||
const userById = new Map(users.map((u) => [u.id, u]));
|
||||
|
||||
@@ -1,3 +1,14 @@
|
||||
import {
|
||||
and,
|
||||
asc,
|
||||
count,
|
||||
desc,
|
||||
eq,
|
||||
inArray,
|
||||
like,
|
||||
or,
|
||||
type SQL,
|
||||
} from "drizzle-orm";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import {
|
||||
type HelpTicketRow,
|
||||
@@ -8,9 +19,23 @@ import { TicketQueueBanner } from "@/components/admin/ticket-queue-banner";
|
||||
import { requireModPermission } from "@/lib/admin/guard";
|
||||
import { fetchTicketQueueOpenCounts } from "@/lib/admin/ticket-queue-counts";
|
||||
import { calcPagination, parseListParams } from "@/lib/admin-helpers";
|
||||
import {
|
||||
db,
|
||||
User,
|
||||
WebsiteHelpCenterTicketReplies,
|
||||
WebsiteHelpCenterTickets,
|
||||
} from "@/lib/db";
|
||||
import { formatDate } from "@/lib/format-date";
|
||||
import { PERMS } from "@/lib/permissions";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
const SORT_COLS = {
|
||||
title: WebsiteHelpCenterTickets.title,
|
||||
open: WebsiteHelpCenterTickets.open,
|
||||
user: WebsiteHelpCenterTickets.userId,
|
||||
date: WebsiteHelpCenterTickets.createdAt,
|
||||
updated: WebsiteHelpCenterTickets.updatedAt,
|
||||
id: WebsiteHelpCenterTickets.id,
|
||||
} as const;
|
||||
|
||||
export default async function ModHelpTicketsPage({
|
||||
searchParams,
|
||||
@@ -24,87 +49,94 @@ export default async function ModHelpTicketsPage({
|
||||
const parsed = parseListParams(new URLSearchParams(raw));
|
||||
const statusFilter = raw.filter_status || "open";
|
||||
|
||||
const conditions: any[] = [];
|
||||
const conditions: SQL[] = [];
|
||||
|
||||
if (statusFilter === "open") {
|
||||
conditions.push({ open: true });
|
||||
conditions.push(eq(WebsiteHelpCenterTickets.open, true));
|
||||
} else if (statusFilter === "closed") {
|
||||
conditions.push({ open: false });
|
||||
conditions.push(eq(WebsiteHelpCenterTickets.open, false));
|
||||
}
|
||||
|
||||
if (parsed.search.trim()) {
|
||||
const q = parsed.search.trim();
|
||||
const asId = /^\d+$/.test(q) ? BigInt(q) : null;
|
||||
const matchingUsers = await prisma.user
|
||||
.findMany({
|
||||
where: { username: { contains: q } },
|
||||
select: { id: true },
|
||||
take: 50,
|
||||
})
|
||||
const matchingUsers = await db
|
||||
.select({ id: User.id })
|
||||
.from(User)
|
||||
.where(like(User.username, `%${q}%`))
|
||||
.limit(50)
|
||||
.catch(() => []);
|
||||
|
||||
conditions.push({
|
||||
OR: [
|
||||
{ title: { contains: q } },
|
||||
{ content: { contains: q } },
|
||||
...(matchingUsers.length > 0
|
||||
? [{ userId: { in: matchingUsers.map((u) => u.id) } }]
|
||||
: []),
|
||||
...(asId !== null ? [{ id: asId }] : []),
|
||||
],
|
||||
});
|
||||
const ors: SQL[] = [
|
||||
like(WebsiteHelpCenterTickets.title, `%${q}%`),
|
||||
like(WebsiteHelpCenterTickets.content, `%${q}%`),
|
||||
];
|
||||
if (matchingUsers.length > 0) {
|
||||
ors.push(
|
||||
inArray(
|
||||
WebsiteHelpCenterTickets.userId,
|
||||
matchingUsers.map((u) => u.id),
|
||||
),
|
||||
);
|
||||
}
|
||||
if (asId !== null) {
|
||||
ors.push(eq(WebsiteHelpCenterTickets.id, asId));
|
||||
}
|
||||
conditions.push(or(...ors)!);
|
||||
}
|
||||
|
||||
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> = {
|
||||
title: { title: "asc" },
|
||||
open: { open: "desc" },
|
||||
user: { userId: "asc" },
|
||||
date: { createdAt: "desc" },
|
||||
updated: { updatedAt: "desc" },
|
||||
id: { id: "desc" },
|
||||
};
|
||||
|
||||
const baseOrder = SORT_MAP[parsed.sort ?? "updated"] ?? { updatedAt: "desc" };
|
||||
const orderField = Object.keys(baseOrder)[0] as keyof typeof baseOrder;
|
||||
const orderBy = {
|
||||
[orderField]: parsed.order,
|
||||
} as any;
|
||||
const sortKey =
|
||||
parsed.sort && parsed.sort in SORT_COLS
|
||||
? (parsed.sort as keyof typeof SORT_COLS)
|
||||
: "updated";
|
||||
const sortCol = SORT_COLS[sortKey];
|
||||
const finalOrder =
|
||||
parsed.sort && parsed.sort in SORT_COLS
|
||||
? parsed.order === "asc"
|
||||
? asc(sortCol)
|
||||
: desc(sortCol)
|
||||
: desc(WebsiteHelpCenterTickets.updatedAt);
|
||||
|
||||
const [total, openCount, closedCount, queues] = await Promise.all([
|
||||
prisma.websiteHelpCenterTickets.count({ where }).catch(() => 0),
|
||||
prisma.websiteHelpCenterTickets
|
||||
.count({ where: { open: true } })
|
||||
db
|
||||
.select({ total: count() })
|
||||
.from(WebsiteHelpCenterTickets)
|
||||
.where(where)
|
||||
.then((rows) => rows[0]?.total ?? 0)
|
||||
.catch(() => 0),
|
||||
prisma.websiteHelpCenterTickets
|
||||
.count({ where: { open: false } })
|
||||
db
|
||||
.select({ total: count() })
|
||||
.from(WebsiteHelpCenterTickets)
|
||||
.where(eq(WebsiteHelpCenterTickets.open, true))
|
||||
.then((rows) => rows[0]?.total ?? 0)
|
||||
.catch(() => 0),
|
||||
db
|
||||
.select({ total: count() })
|
||||
.from(WebsiteHelpCenterTickets)
|
||||
.where(eq(WebsiteHelpCenterTickets.open, false))
|
||||
.then((rows) => rows[0]?.total ?? 0)
|
||||
.catch(() => 0),
|
||||
fetchTicketQueueOpenCounts(),
|
||||
]);
|
||||
|
||||
const pagination = calcPagination(total, parsed.page, parsed.perPage);
|
||||
|
||||
const tickets = await prisma.websiteHelpCenterTickets
|
||||
.findMany({
|
||||
where,
|
||||
orderBy,
|
||||
skip: pagination.offset,
|
||||
take: pagination.perPage,
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
title: true,
|
||||
open: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
const tickets = await db
|
||||
.select({
|
||||
id: WebsiteHelpCenterTickets.id,
|
||||
userId: WebsiteHelpCenterTickets.userId,
|
||||
title: WebsiteHelpCenterTickets.title,
|
||||
open: WebsiteHelpCenterTickets.open,
|
||||
createdAt: WebsiteHelpCenterTickets.createdAt,
|
||||
updatedAt: WebsiteHelpCenterTickets.updatedAt,
|
||||
})
|
||||
.from(WebsiteHelpCenterTickets)
|
||||
.where(where)
|
||||
.orderBy(finalOrder)
|
||||
.offset(pagination.offset)
|
||||
.limit(pagination.perPage)
|
||||
.catch(() => []);
|
||||
|
||||
const ticketIds = tickets.map((ticket) => ticket.id);
|
||||
@@ -118,26 +150,27 @@ export default async function ModHelpTicketsPage({
|
||||
|
||||
const [replyGroups, users] = await Promise.all([
|
||||
ticketIds.length > 0
|
||||
? prisma.websiteHelpCenterTicketReplies
|
||||
.groupBy({
|
||||
by: ["ticketId"],
|
||||
where: { ticketId: { in: ticketIds } },
|
||||
_count: true,
|
||||
? db
|
||||
.select({
|
||||
ticketId: WebsiteHelpCenterTicketReplies.ticketId,
|
||||
total: count(),
|
||||
})
|
||||
.from(WebsiteHelpCenterTicketReplies)
|
||||
.where(inArray(WebsiteHelpCenterTicketReplies.ticketId, ticketIds))
|
||||
.groupBy(WebsiteHelpCenterTicketReplies.ticketId)
|
||||
.catch(() => [])
|
||||
: Promise.resolve([]),
|
||||
userIds.length > 0
|
||||
? prisma.user
|
||||
.findMany({
|
||||
where: { id: { in: userIds } },
|
||||
select: { id: true, username: true },
|
||||
})
|
||||
? db
|
||||
.select({ id: User.id, username: User.username })
|
||||
.from(User)
|
||||
.where(inArray(User.id, userIds))
|
||||
.catch(() => [])
|
||||
: Promise.resolve([]),
|
||||
]);
|
||||
|
||||
const replyCountByTicket = new Map(
|
||||
replyGroups.map((g) => [String(g.ticketId), g._count]),
|
||||
replyGroups.map((g) => [String(g.ticketId), g.total]),
|
||||
);
|
||||
const usernameById = new Map(users.map((u) => [u.id, u.username]));
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import {
|
||||
Ban,
|
||||
Gavel,
|
||||
@@ -16,9 +17,9 @@ import type { ReactNode } from "react";
|
||||
import { LanguageSwitcher } from "@/components/language-switcher";
|
||||
import { ThemeSwitcher } from "@/components/theme-switcher";
|
||||
import { requireMod } from "@/lib/admin/guard";
|
||||
import { db, User } from "@/lib/db";
|
||||
import { setCsrfCookie } from "@/lib/foundation/security";
|
||||
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { siteSettings } from "@/lib/services/site-settings";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
@@ -32,12 +33,12 @@ export default async function ModLayout({ children }: { children: ReactNode }) {
|
||||
csrfToken = "";
|
||||
}
|
||||
if (await siteSettings.getBool("force_staff_2fa", false)) {
|
||||
const u = await prisma.user
|
||||
.findUnique({
|
||||
where: { id: staff.id },
|
||||
select: { twoFactorConfirmedAt: true },
|
||||
})
|
||||
.catch(() => null);
|
||||
const [u] = await db
|
||||
.select({ twoFactorConfirmedAt: User.twoFactorConfirmedAt })
|
||||
.from(User)
|
||||
.where(eq(User.id, staff.id))
|
||||
.limit(1)
|
||||
.catch(() => [] as { twoFactorConfirmedAt: Date | null }[]);
|
||||
if (!u?.twoFactorConfirmedAt) redirect("/settings/2fa?error=staffrequired");
|
||||
}
|
||||
|
||||
|
||||
+35
-10
@@ -1,3 +1,4 @@
|
||||
import { and, count, eq, gte, ne } from "drizzle-orm";
|
||||
import {
|
||||
Ban,
|
||||
Gavel,
|
||||
@@ -11,8 +12,15 @@ import Link from "next/link";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import { StatsCard } from "@/components/admin/stats-card";
|
||||
import { getMinStaffRank } from "@/lib/admin/min-staff-rank";
|
||||
import {
|
||||
Ban as BanTable,
|
||||
db,
|
||||
SupportTickets,
|
||||
User,
|
||||
WebsiteHelpCenterTickets,
|
||||
WebsiteTicket,
|
||||
} from "@/lib/db";
|
||||
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
export default async function ModDashboardPage() {
|
||||
const t = await getTranslations("pages.mod");
|
||||
@@ -44,24 +52,41 @@ export default async function ModDashboardPage() {
|
||||
const [openCfh, todayBans, modsOnline, openTickets, openHelpTickets] =
|
||||
await Promise.all([
|
||||
showCfh
|
||||
? prisma.supportTickets.count({ where: { state: 0 } }).catch(() => 0)
|
||||
? db
|
||||
.select({ total: count() })
|
||||
.from(SupportTickets)
|
||||
.where(eq(SupportTickets.state, 0))
|
||||
.then((rows) => rows[0]?.total ?? 0)
|
||||
.catch(() => 0)
|
||||
: Promise.resolve(0),
|
||||
showBans
|
||||
? prisma.ban
|
||||
.count({ where: { timestamp: { gte: todayStart } } })
|
||||
? db
|
||||
.select({ total: count() })
|
||||
.from(BanTable)
|
||||
.where(gte(BanTable.timestamp, todayStart))
|
||||
.then((rows) => rows[0]?.total ?? 0)
|
||||
.catch(() => 0)
|
||||
: Promise.resolve(0),
|
||||
prisma.user
|
||||
.count({ where: { online: "1", rank: { gte: minStaffRank } } })
|
||||
db
|
||||
.select({ total: count() })
|
||||
.from(User)
|
||||
.where(and(eq(User.online, "1"), gte(User.rank, minStaffRank)))
|
||||
.then((rows) => rows[0]?.total ?? 0)
|
||||
.catch(() => 0),
|
||||
showTickets
|
||||
? prisma.websiteTicket
|
||||
.count({ where: { status: { not: "closed" } } })
|
||||
? db
|
||||
.select({ total: count() })
|
||||
.from(WebsiteTicket)
|
||||
.where(ne(WebsiteTicket.status, "closed"))
|
||||
.then((rows) => rows[0]?.total ?? 0)
|
||||
.catch(() => 0)
|
||||
: Promise.resolve(0),
|
||||
showTickets
|
||||
? prisma.websiteHelpCenterTickets
|
||||
.count({ where: { open: true } })
|
||||
? db
|
||||
.select({ total: count() })
|
||||
.from(WebsiteHelpCenterTickets)
|
||||
.where(eq(WebsiteHelpCenterTickets.open, true))
|
||||
.then((rows) => rows[0]?.total ?? 0)
|
||||
.catch(() => 0)
|
||||
: Promise.resolve(0),
|
||||
]);
|
||||
|
||||
+60
-41
@@ -1,58 +1,77 @@
|
||||
import { and, count, desc, gte, inArray, like } from "drizzle-orm";
|
||||
import Link from "next/link";
|
||||
import { AvatarImage } from "@/components/shared/avatar-image";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { requireModPermission } from "@/lib/admin/guard";
|
||||
import { getMinStaffRank } from "@/lib/admin/min-staff-rank";
|
||||
import {
|
||||
AdminAuditLog,
|
||||
db,
|
||||
SupportTickets,
|
||||
User,
|
||||
WebsiteTicket,
|
||||
} from "@/lib/db";
|
||||
import { PERMS } from "@/lib/permissions";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
export default async function ModTeamLitePage() {
|
||||
await requireModPermission([PERMS.MOD_TEAM_VIEW, PERMS.MODERATION_VIEW]);
|
||||
|
||||
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 [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 },
|
||||
}),
|
||||
]);
|
||||
const staffIds = staff.map((s) => s.id);
|
||||
|
||||
const cfhMap = new Map(cfhCounts.map((c) => [c.modId, c._count._all]));
|
||||
const webMap = new Map(
|
||||
webTicketCounts.map((c) => [c.assigneeId, c._count._all]),
|
||||
);
|
||||
const actionMap = new Map(
|
||||
modActionCounts.map((c) => [c.userId, c._count._all]),
|
||||
);
|
||||
const [cfhCounts, webTicketCounts, modActionCounts] =
|
||||
staffIds.length === 0
|
||||
? [[], [], []]
|
||||
: await Promise.all([
|
||||
db
|
||||
.select({
|
||||
modId: SupportTickets.modId,
|
||||
total: count(),
|
||||
})
|
||||
.from(SupportTickets)
|
||||
.where(inArray(SupportTickets.modId, staffIds))
|
||||
.groupBy(SupportTickets.modId),
|
||||
db
|
||||
.select({
|
||||
assigneeId: WebsiteTicket.assigneeId,
|
||||
total: count(),
|
||||
})
|
||||
.from(WebsiteTicket)
|
||||
.where(inArray(WebsiteTicket.assigneeId, staffIds))
|
||||
.groupBy(WebsiteTicket.assigneeId),
|
||||
db
|
||||
.select({
|
||||
userId: AdminAuditLog.userId,
|
||||
total: count(),
|
||||
})
|
||||
.from(AdminAuditLog)
|
||||
.where(
|
||||
and(
|
||||
inArray(AdminAuditLog.userId, staffIds),
|
||||
like(AdminAuditLog.action, "mod_%"),
|
||||
),
|
||||
)
|
||||
.groupBy(AdminAuditLog.userId),
|
||||
]);
|
||||
|
||||
const cfhMap = new Map(cfhCounts.map((c) => [c.modId, c.total]));
|
||||
const webMap = new Map(webTicketCounts.map((c) => [c.assigneeId, c.total]));
|
||||
const actionMap = new Map(modActionCounts.map((c) => [c.userId, c.total]));
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import { asc, eq, gte } from "drizzle-orm";
|
||||
import { alias } from "drizzle-orm/mysql-core";
|
||||
import { notFound } from "next/navigation";
|
||||
import { AdminTicketDetail } from "@/app/admin/tickets/[id]/admin-ticket-detail";
|
||||
import { requireModPermission } from "@/lib/admin/guard";
|
||||
import { getMinStaffRank } from "@/lib/admin/min-staff-rank";
|
||||
import { db, User, WebsiteTicket, WebsiteTicketMessage } from "@/lib/db";
|
||||
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
const Creator = alias(User, "ticket_creator");
|
||||
const Assignee = alias(User, "ticket_assignee");
|
||||
const MessageUser = alias(User, "ticket_message_user");
|
||||
|
||||
export default async function ModTicketDetailPage({
|
||||
params,
|
||||
@@ -17,40 +23,55 @@ export default async function ModTicketDetailPage({
|
||||
const ticketId = Number(id);
|
||||
if (Number.isNaN(ticketId)) notFound();
|
||||
|
||||
const ticket = await prisma.websiteTicket.findUnique({
|
||||
where: { id: ticketId },
|
||||
include: {
|
||||
creator: {
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
look: true,
|
||||
rank: true,
|
||||
ipRegister: true,
|
||||
mail: true,
|
||||
accountCreated: true,
|
||||
},
|
||||
},
|
||||
assignee: { select: { id: true, username: true } },
|
||||
messages: {
|
||||
orderBy: { createdAt: "asc" },
|
||||
include: {
|
||||
user: {
|
||||
select: { id: true, username: true, look: true, rank: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const [ticket] = await db
|
||||
.select({
|
||||
id: WebsiteTicket.id,
|
||||
subject: WebsiteTicket.subject,
|
||||
category: WebsiteTicket.category,
|
||||
priority: WebsiteTicket.priority,
|
||||
status: WebsiteTicket.status,
|
||||
createdAt: WebsiteTicket.createdAt,
|
||||
closedAt: WebsiteTicket.closedAt,
|
||||
creatorId: Creator.id,
|
||||
creatorUsername: Creator.username,
|
||||
creatorLook: Creator.look,
|
||||
creatorRank: Creator.rank,
|
||||
creatorIpRegister: Creator.ipRegister,
|
||||
creatorMail: Creator.mail,
|
||||
creatorAccountCreated: Creator.accountCreated,
|
||||
assigneeId: Assignee.id,
|
||||
assigneeUsername: Assignee.username,
|
||||
})
|
||||
.from(WebsiteTicket)
|
||||
.innerJoin(Creator, eq(WebsiteTicket.creatorId, Creator.id))
|
||||
.leftJoin(Assignee, eq(WebsiteTicket.assigneeId, Assignee.id))
|
||||
.where(eq(WebsiteTicket.id, ticketId))
|
||||
.limit(1);
|
||||
|
||||
if (!ticket) notFound();
|
||||
|
||||
const messages = await db
|
||||
.select({
|
||||
id: WebsiteTicketMessage.id,
|
||||
message: WebsiteTicketMessage.message,
|
||||
isStaff: WebsiteTicketMessage.isStaff,
|
||||
createdAt: WebsiteTicketMessage.createdAt,
|
||||
userId: MessageUser.id,
|
||||
username: MessageUser.username,
|
||||
look: MessageUser.look,
|
||||
rank: MessageUser.rank,
|
||||
})
|
||||
.from(WebsiteTicketMessage)
|
||||
.innerJoin(MessageUser, eq(WebsiteTicketMessage.userId, MessageUser.id))
|
||||
.where(eq(WebsiteTicketMessage.ticketId, ticketId))
|
||||
.orderBy(asc(WebsiteTicketMessage.createdAt));
|
||||
|
||||
const minStaffRank = await getMinStaffRank();
|
||||
const staffMembers = await prisma.user.findMany({
|
||||
where: { rank: { gte: minStaffRank } },
|
||||
select: { id: true, username: true },
|
||||
orderBy: { username: "asc" },
|
||||
});
|
||||
const staffMembers = await db
|
||||
.select({ id: User.id, username: User.username })
|
||||
.from(User)
|
||||
.where(gte(User.rank, minStaffRank))
|
||||
.orderBy(asc(User.username));
|
||||
|
||||
const canEdit =
|
||||
canAccess(permissions, PERMS.MOD_TICKETS_EDIT, session.user.rank) ||
|
||||
@@ -67,28 +88,29 @@ export default async function ModTicketDetailPage({
|
||||
createdAt: ticket.createdAt.toISOString(),
|
||||
closedAt: ticket.closedAt?.toISOString() ?? null,
|
||||
creator: {
|
||||
id: ticket.creator.id,
|
||||
username: ticket.creator.username,
|
||||
look: ticket.creator.look,
|
||||
rank: ticket.creator.rank,
|
||||
mail: ticket.creator.mail ?? "",
|
||||
ipRegister: ticket.creator.ipRegister,
|
||||
accountCreated: ticket.creator.accountCreated,
|
||||
id: ticket.creatorId,
|
||||
username: ticket.creatorUsername,
|
||||
look: ticket.creatorLook,
|
||||
rank: ticket.creatorRank,
|
||||
mail: ticket.creatorMail ?? "",
|
||||
ipRegister: ticket.creatorIpRegister,
|
||||
accountCreated: ticket.creatorAccountCreated,
|
||||
},
|
||||
assignee: ticket.assignee
|
||||
? { id: ticket.assignee.id, username: ticket.assignee.username }
|
||||
: null,
|
||||
assignee:
|
||||
ticket.assigneeId != null && ticket.assigneeUsername
|
||||
? { id: ticket.assigneeId, username: ticket.assigneeUsername }
|
||||
: null,
|
||||
}}
|
||||
messages={ticket.messages.map((m) => ({
|
||||
messages={messages.map((m) => ({
|
||||
id: m.id,
|
||||
message: m.message,
|
||||
isStaff: m.isStaff === 1,
|
||||
createdAt: m.createdAt.toISOString(),
|
||||
user: {
|
||||
id: m.user.id,
|
||||
username: m.user.username,
|
||||
look: m.user.look,
|
||||
rank: m.user.rank,
|
||||
id: m.userId,
|
||||
username: m.username,
|
||||
look: m.look,
|
||||
rank: m.rank,
|
||||
},
|
||||
}))}
|
||||
staffMembers={staffMembers}
|
||||
|
||||
+116
-55
@@ -1,3 +1,16 @@
|
||||
import {
|
||||
and,
|
||||
asc,
|
||||
count,
|
||||
desc,
|
||||
eq,
|
||||
inArray,
|
||||
like,
|
||||
ne,
|
||||
or,
|
||||
type SQL,
|
||||
} from "drizzle-orm";
|
||||
import { alias } from "drizzle-orm/mysql-core";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import {
|
||||
type TicketRow,
|
||||
@@ -8,9 +21,21 @@ import { TicketQueueBanner } from "@/components/admin/ticket-queue-banner";
|
||||
import { requireModPermission } from "@/lib/admin/guard";
|
||||
import { fetchTicketQueueOpenCounts } from "@/lib/admin/ticket-queue-counts";
|
||||
import { calcPagination, parseListParams } from "@/lib/admin-helpers";
|
||||
import { db, User, WebsiteTicket, WebsiteTicketMessage } from "@/lib/db";
|
||||
import { formatDate } from "@/lib/format-date";
|
||||
import { PERMS } from "@/lib/permissions";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
const Creator = alias(User, "ticket_creator");
|
||||
const Assignee = alias(User, "ticket_assignee");
|
||||
|
||||
const SORT_COLS = {
|
||||
subject: WebsiteTicket.subject,
|
||||
status: WebsiteTicket.status,
|
||||
priority: WebsiteTicket.priority,
|
||||
assignee: WebsiteTicket.assigneeId,
|
||||
date: WebsiteTicket.createdAt,
|
||||
id: WebsiteTicket.id,
|
||||
} as const;
|
||||
|
||||
export default async function ModTicketsPage({
|
||||
searchParams,
|
||||
@@ -24,92 +49,128 @@ export default async function ModTicketsPage({
|
||||
const parsed = parseListParams(new URLSearchParams(raw));
|
||||
const statusFilter = raw.filter_status || raw.status || "active";
|
||||
|
||||
const conditions: any[] = [];
|
||||
const conditions: SQL[] = [];
|
||||
|
||||
if (statusFilter === "active") {
|
||||
conditions.push({ status: { not: "closed" } });
|
||||
conditions.push(ne(WebsiteTicket.status, "closed"));
|
||||
} else if (statusFilter && statusFilter !== "all") {
|
||||
conditions.push({ status: statusFilter });
|
||||
conditions.push(eq(WebsiteTicket.status, statusFilter));
|
||||
}
|
||||
|
||||
if (parsed.search.trim()) {
|
||||
const q = parsed.search.trim();
|
||||
const asId = Number(q);
|
||||
conditions.push({
|
||||
OR: [
|
||||
{ subject: { contains: q } },
|
||||
{ category: { contains: q } },
|
||||
{ creator: { username: { contains: q } } },
|
||||
{ assignee: { username: { contains: q } } },
|
||||
...(Number.isFinite(asId) && asId > 0 ? [{ id: asId }] : []),
|
||||
],
|
||||
});
|
||||
const ors: SQL[] = [
|
||||
like(WebsiteTicket.subject, `%${q}%`),
|
||||
like(WebsiteTicket.category, `%${q}%`),
|
||||
like(Creator.username, `%${q}%`),
|
||||
like(Assignee.username, `%${q}%`),
|
||||
];
|
||||
if (Number.isFinite(asId) && asId > 0) {
|
||||
ors.push(eq(WebsiteTicket.id, asId));
|
||||
}
|
||||
conditions.push(or(...ors)!);
|
||||
}
|
||||
|
||||
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> = {
|
||||
subject: { subject: "asc" },
|
||||
status: { status: "asc" },
|
||||
priority: { priority: "asc" },
|
||||
assignee: { assigneeId: "asc" },
|
||||
date: { createdAt: "desc" },
|
||||
id: { id: "desc" },
|
||||
};
|
||||
|
||||
const baseOrder = SORT_MAP[parsed.sort ?? "date"] ?? { createdAt: "desc" };
|
||||
const orderField = Object.keys(baseOrder)[0] as keyof typeof baseOrder;
|
||||
const orderBy = {
|
||||
[orderField]: parsed.order,
|
||||
} as any;
|
||||
const sortKey =
|
||||
parsed.sort && parsed.sort in SORT_COLS
|
||||
? (parsed.sort as keyof typeof SORT_COLS)
|
||||
: "date";
|
||||
const sortCol = SORT_COLS[sortKey];
|
||||
const finalOrder =
|
||||
parsed.sort && parsed.sort in SORT_COLS
|
||||
? parsed.order === "asc"
|
||||
? asc(sortCol)
|
||||
: desc(sortCol)
|
||||
: desc(WebsiteTicket.createdAt);
|
||||
|
||||
const [total, openCount, inProgressCount, waitingCount, closedCount, queues] =
|
||||
await Promise.all([
|
||||
prisma.websiteTicket.count({ where }).catch(() => 0),
|
||||
prisma.websiteTicket.count({ where: { status: "open" } }).catch(() => 0),
|
||||
prisma.websiteTicket
|
||||
.count({ where: { status: "in_progress" } })
|
||||
db
|
||||
.select({ total: count() })
|
||||
.from(WebsiteTicket)
|
||||
.leftJoin(Creator, eq(WebsiteTicket.creatorId, Creator.id))
|
||||
.leftJoin(Assignee, eq(WebsiteTicket.assigneeId, Assignee.id))
|
||||
.where(where)
|
||||
.then((rows) => rows[0]?.total ?? 0)
|
||||
.catch(() => 0),
|
||||
prisma.websiteTicket
|
||||
.count({ where: { status: "waiting" } })
|
||||
db
|
||||
.select({ total: count() })
|
||||
.from(WebsiteTicket)
|
||||
.where(eq(WebsiteTicket.status, "open"))
|
||||
.then((rows) => rows[0]?.total ?? 0)
|
||||
.catch(() => 0),
|
||||
prisma.websiteTicket
|
||||
.count({ where: { status: "closed" } })
|
||||
db
|
||||
.select({ total: count() })
|
||||
.from(WebsiteTicket)
|
||||
.where(eq(WebsiteTicket.status, "in_progress"))
|
||||
.then((rows) => rows[0]?.total ?? 0)
|
||||
.catch(() => 0),
|
||||
db
|
||||
.select({ total: count() })
|
||||
.from(WebsiteTicket)
|
||||
.where(eq(WebsiteTicket.status, "waiting"))
|
||||
.then((rows) => rows[0]?.total ?? 0)
|
||||
.catch(() => 0),
|
||||
db
|
||||
.select({ total: count() })
|
||||
.from(WebsiteTicket)
|
||||
.where(eq(WebsiteTicket.status, "closed"))
|
||||
.then((rows) => rows[0]?.total ?? 0)
|
||||
.catch(() => 0),
|
||||
fetchTicketQueueOpenCounts(),
|
||||
]);
|
||||
|
||||
const pagination = calcPagination(total, parsed.page, parsed.perPage);
|
||||
|
||||
const tickets = await prisma.websiteTicket
|
||||
.findMany({
|
||||
where,
|
||||
orderBy,
|
||||
skip: pagination.offset,
|
||||
take: pagination.perPage,
|
||||
include: {
|
||||
creator: { select: { id: true, username: true } },
|
||||
assignee: { select: { id: true, username: true } },
|
||||
_count: { select: { messages: true } },
|
||||
},
|
||||
const tickets = await db
|
||||
.select({
|
||||
id: WebsiteTicket.id,
|
||||
subject: WebsiteTicket.subject,
|
||||
category: WebsiteTicket.category,
|
||||
status: WebsiteTicket.status,
|
||||
priority: WebsiteTicket.priority,
|
||||
creatorId: WebsiteTicket.creatorId,
|
||||
createdAt: WebsiteTicket.createdAt,
|
||||
creatorUsername: Creator.username,
|
||||
assigneeUsername: Assignee.username,
|
||||
})
|
||||
.from(WebsiteTicket)
|
||||
.leftJoin(Creator, eq(WebsiteTicket.creatorId, Creator.id))
|
||||
.leftJoin(Assignee, eq(WebsiteTicket.assigneeId, Assignee.id))
|
||||
.where(where)
|
||||
.orderBy(finalOrder)
|
||||
.offset(pagination.offset)
|
||||
.limit(pagination.perPage)
|
||||
.catch(() => []);
|
||||
|
||||
const ticketIds = tickets.map((ticket) => ticket.id);
|
||||
const msgRows =
|
||||
ticketIds.length > 0
|
||||
? await db
|
||||
.select({
|
||||
ticketId: WebsiteTicketMessage.ticketId,
|
||||
total: count(),
|
||||
})
|
||||
.from(WebsiteTicketMessage)
|
||||
.where(inArray(WebsiteTicketMessage.ticketId, ticketIds))
|
||||
.groupBy(WebsiteTicketMessage.ticketId)
|
||||
.catch(() => [])
|
||||
: [];
|
||||
const msgMap = new Map(msgRows.map((m) => [m.ticketId, m.total]));
|
||||
|
||||
const rows: TicketRow[] = tickets.map((ticket) => ({
|
||||
id: ticket.id,
|
||||
subject: ticket.subject,
|
||||
creator: ticket.creator.username,
|
||||
creator: ticket.creatorUsername ?? "—",
|
||||
creatorId: ticket.creatorId,
|
||||
category: ticket.category,
|
||||
messages: ticket._count.messages,
|
||||
messages: msgMap.get(ticket.id) ?? 0,
|
||||
status: ticket.status,
|
||||
priority: ticket.priority,
|
||||
assignee: ticket.assignee?.username ?? "—",
|
||||
assignee: ticket.assigneeUsername ?? "—",
|
||||
date: formatDate(ticket.createdAt, "date"),
|
||||
}));
|
||||
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { requireModPermission } from "@/lib/admin/guard";
|
||||
import { db, User } from "@/lib/db";
|
||||
import { formatDate } from "@/lib/format-date";
|
||||
import { getAvatarUrl } from "@/lib/imager";
|
||||
import { PERMS } from "@/lib/permissions";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
export default async function ModUserDetailPage({
|
||||
params,
|
||||
@@ -19,20 +20,21 @@ export default async function ModUserDetailPage({
|
||||
const id = Number(rawId);
|
||||
if (!Number.isFinite(id) || id <= 0) notFound();
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id },
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
rank: true,
|
||||
online: true,
|
||||
motto: true,
|
||||
look: true,
|
||||
accountCreated: true,
|
||||
lastLogin: true,
|
||||
lastOnline: true,
|
||||
},
|
||||
});
|
||||
const [user] = await db
|
||||
.select({
|
||||
id: User.id,
|
||||
username: User.username,
|
||||
rank: User.rank,
|
||||
online: User.online,
|
||||
motto: User.motto,
|
||||
look: User.look,
|
||||
accountCreated: User.accountCreated,
|
||||
lastLogin: User.lastLogin,
|
||||
lastOnline: User.lastOnline,
|
||||
})
|
||||
.from(User)
|
||||
.where(eq(User.id, id))
|
||||
.limit(1);
|
||||
if (!user) notFound();
|
||||
|
||||
return (
|
||||
|
||||
+55
-34
@@ -1,12 +1,13 @@
|
||||
import { and, asc, count, desc, eq, like, or, type SQL } from "drizzle-orm";
|
||||
import Link from "next/link";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import { DataTable } from "@/components/admin/data-table";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { requireModPermission } from "@/lib/admin/guard";
|
||||
import { calcPagination, parseListParams } from "@/lib/admin-helpers";
|
||||
import { db, User } from "@/lib/db";
|
||||
import { getAvatarUrl } from "@/lib/imager";
|
||||
import { PERMS } from "@/lib/permissions";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import type { DataTableColumn } from "@/types/common";
|
||||
|
||||
type ModUserRow = {
|
||||
@@ -89,6 +90,15 @@ const columns: DataTableColumn<ModUserRow>[] = [
|
||||
},
|
||||
];
|
||||
|
||||
const SORT_COLS = {
|
||||
id: User.id,
|
||||
username: User.username,
|
||||
rank: User.rank,
|
||||
online: User.online,
|
||||
motto: User.motto,
|
||||
lastLogin: User.lastLogin,
|
||||
} as const;
|
||||
|
||||
export default async function ModUsersPage({
|
||||
searchParams,
|
||||
}: {
|
||||
@@ -99,44 +109,55 @@ export default async function ModUsersPage({
|
||||
const raw = await searchParams;
|
||||
const parsed = parseListParams(new URLSearchParams(raw));
|
||||
|
||||
const where = parsed.search.trim()
|
||||
? {
|
||||
OR: [
|
||||
{ username: { contains: parsed.search.trim() } },
|
||||
{ motto: { contains: parsed.search.trim() } },
|
||||
...(Number.isFinite(Number(parsed.search)) &&
|
||||
Number(parsed.search) > 0
|
||||
? [{ id: Number(parsed.search) }]
|
||||
: []),
|
||||
],
|
||||
}
|
||||
: {};
|
||||
const conditions: SQL[] = [];
|
||||
if (parsed.search.trim()) {
|
||||
const q = parsed.search.trim();
|
||||
const ors = [like(User.username, `%${q}%`), like(User.motto, `%${q}%`)];
|
||||
if (Number.isFinite(Number(q)) && Number(q) > 0) {
|
||||
ors.push(eq(User.id, Number(q)));
|
||||
}
|
||||
conditions.push(or(...ors)!);
|
||||
}
|
||||
const where = conditions.length > 0 ? and(...conditions) : undefined;
|
||||
|
||||
const orderBy = parsed.sort
|
||||
? { [parsed.sort]: parsed.order }
|
||||
: { id: "desc" as const };
|
||||
const sortKey =
|
||||
parsed.sort && parsed.sort in SORT_COLS
|
||||
? (parsed.sort as keyof typeof SORT_COLS)
|
||||
: "id";
|
||||
const sortCol = SORT_COLS[sortKey];
|
||||
const finalOrder =
|
||||
parsed.sort && parsed.sort in SORT_COLS
|
||||
? parsed.order === "asc"
|
||||
? asc(sortCol)
|
||||
: desc(sortCol)
|
||||
: desc(User.id);
|
||||
|
||||
const [total, users] = await Promise.all([
|
||||
prisma.user.count({ where }).catch(() => 0),
|
||||
prisma.user
|
||||
.findMany({
|
||||
where,
|
||||
orderBy,
|
||||
skip: (parsed.page - 1) * parsed.perPage,
|
||||
take: parsed.perPage,
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
rank: true,
|
||||
online: true,
|
||||
motto: true,
|
||||
look: true,
|
||||
lastLogin: true,
|
||||
},
|
||||
const [totals, users] = await Promise.all([
|
||||
db
|
||||
.select({ total: count() })
|
||||
.from(User)
|
||||
.where(where)
|
||||
.then((rows) => rows[0]?.total ?? 0)
|
||||
.catch(() => 0),
|
||||
db
|
||||
.select({
|
||||
id: User.id,
|
||||
username: User.username,
|
||||
rank: User.rank,
|
||||
online: User.online,
|
||||
motto: User.motto,
|
||||
look: User.look,
|
||||
lastLogin: User.lastLogin,
|
||||
})
|
||||
.catch(() => []),
|
||||
.from(User)
|
||||
.where(where)
|
||||
.orderBy(finalOrder)
|
||||
.offset((parsed.page - 1) * parsed.perPage)
|
||||
.limit(parsed.perPage)
|
||||
.catch(() => [] as ModUserRow[]),
|
||||
]);
|
||||
|
||||
const total = totals;
|
||||
const pagination = calcPagination(total, parsed.page, parsed.perPage);
|
||||
const rows: ModUserRow[] = users;
|
||||
|
||||
|
||||
Reference in new issue
Block a user