feat(housekeeping): cut over administration to ase
This commit is contained in:
1 parent
c9e35cf602
commit
2b8f73a91d
457 files changed
+589
-55936
No files matched your search
@@ -1,449 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
ArrowLeft,
|
||||
Calendar,
|
||||
Globe,
|
||||
Loader2,
|
||||
Mail,
|
||||
Send,
|
||||
Shield,
|
||||
User,
|
||||
} from "lucide-react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import {
|
||||
adminReplyTicket,
|
||||
assignTicket,
|
||||
updateTicketPriority,
|
||||
updateTicketStatus,
|
||||
} from "@/actions/tickets";
|
||||
import Link from "@/components/link";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { useServerAction } from "@/hooks/use-server-action";
|
||||
import { TICKET_PRIORITIES, TICKET_STATUSES } from "@/lib/validators/ticket";
|
||||
|
||||
interface TicketMessage {
|
||||
id: number;
|
||||
message: string;
|
||||
isStaff: boolean;
|
||||
createdAt: string;
|
||||
user: { id: number; username: string; look: string; rank: number };
|
||||
}
|
||||
|
||||
interface TicketInfo {
|
||||
id: number;
|
||||
subject: string;
|
||||
category: string;
|
||||
priority: string;
|
||||
status: string;
|
||||
createdAt: string;
|
||||
closedAt: string | null;
|
||||
creator: {
|
||||
id: number;
|
||||
username: string;
|
||||
look: string;
|
||||
rank: number;
|
||||
mail: string;
|
||||
ipRegister: string;
|
||||
accountCreated: number;
|
||||
};
|
||||
assignee: { id: number; username: string } | null;
|
||||
}
|
||||
|
||||
interface StaffMember {
|
||||
id: number;
|
||||
username: string;
|
||||
}
|
||||
|
||||
const STATUS_COLORS: Record<string, string> = {
|
||||
open: "bg-[var(--admin-info-subtle)] text-[var(--admin-info)]",
|
||||
in_progress: "bg-[var(--admin-warning-subtle)] text-[var(--admin-warning)]",
|
||||
waiting: "bg-[var(--admin-warning-subtle)] text-[var(--admin-warning)]",
|
||||
closed: "bg-muted text-muted-foreground",
|
||||
};
|
||||
|
||||
const PRIORITY_COLORS: Record<string, string> = {
|
||||
low: "text-muted-foreground",
|
||||
normal: "text-[var(--admin-info)]",
|
||||
high: "text-[var(--admin-warning)]",
|
||||
urgent: "text-[var(--admin-error)]",
|
||||
};
|
||||
|
||||
export function AdminTicketDetail({
|
||||
ticket,
|
||||
messages: initialMessages,
|
||||
staffMembers,
|
||||
currentUserId,
|
||||
canEdit,
|
||||
listHref = "/admin/tickets",
|
||||
userLinkMode = "admin",
|
||||
}: {
|
||||
ticket: TicketInfo;
|
||||
messages: TicketMessage[];
|
||||
staffMembers: StaffMember[];
|
||||
currentUserId: number;
|
||||
canEdit: boolean;
|
||||
listHref?: string;
|
||||
userLinkMode?: "admin" | "public";
|
||||
}) {
|
||||
const [messages] = useState(initialMessages);
|
||||
const [reply, setReply] = useState("");
|
||||
const { run, isPending } = useServerAction();
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
function creatorHref() {
|
||||
if (userLinkMode === "public") {
|
||||
return `/u/${encodeURIComponent(ticket.creator.username)}`;
|
||||
}
|
||||
return `/admin/users/show/${ticket.creator.id}`;
|
||||
}
|
||||
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: explicitly chosen here, see surrounding code
|
||||
useEffect(() => {
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
|
||||
}, [messages]);
|
||||
|
||||
function handleReply() {
|
||||
if (!reply.trim() || isPending) return;
|
||||
run(
|
||||
() => adminReplyTicket({ ticketId: ticket.id, message: reply.trim() }),
|
||||
{
|
||||
successMessage: "Reply sent!",
|
||||
onSuccess: () => setReply(""),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function handleStatusChange(status: string) {
|
||||
run(
|
||||
() =>
|
||||
updateTicketStatus({
|
||||
ticketId: ticket.id,
|
||||
status: status as (typeof TICKET_STATUSES)[number],
|
||||
}),
|
||||
{
|
||||
successMessage: `Status changed to ${status}`,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function handleAssign(assigneeId: string) {
|
||||
const id = assigneeId === "unassign" ? null : Number(assigneeId);
|
||||
run(() => assignTicket({ ticketId: ticket.id, assigneeId: id }), {
|
||||
successMessage: id ? "Ticket assigned" : "Ticket unassigned",
|
||||
});
|
||||
}
|
||||
|
||||
function handlePriorityChange(priority: string) {
|
||||
run(
|
||||
() =>
|
||||
updateTicketPriority({
|
||||
ticketId: ticket.id,
|
||||
priority: priority as (typeof TICKET_PRIORITIES)[number],
|
||||
}),
|
||||
{
|
||||
successMessage: `Priority changed to ${priority}`,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const isClosed = ticket.status === "closed";
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-start gap-4">
|
||||
<Link href={listHref}>
|
||||
<Button variant="ghost" size="icon">
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
</Link>
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<span className="text-sm text-muted-foreground font-mono">
|
||||
#{ticket.id}
|
||||
</span>
|
||||
<Badge className={STATUS_COLORS[ticket.status]}>
|
||||
{ticket.status.replace("_", " ")}
|
||||
</Badge>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={`capitalize ${PRIORITY_COLORS[ticket.priority]}`}
|
||||
>
|
||||
{ticket.priority}
|
||||
</Badge>
|
||||
<Badge variant="outline" className="capitalize">
|
||||
{ticket.category}
|
||||
</Badge>
|
||||
</div>
|
||||
<h1 className="text-2xl font-bold">{ticket.subject}</h1>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6 lg:grid-cols-[1fr_300px]">
|
||||
{/* Messages */}
|
||||
<div className="space-y-4">
|
||||
<Card className="overflow-hidden">
|
||||
<div className="max-h-[600px] overflow-y-auto p-4 space-y-4">
|
||||
{messages.map((msg) => (
|
||||
<div key={msg.id} className="flex gap-3">
|
||||
<div className="shrink-0">
|
||||
<div className="w-9 h-9 rounded-full bg-accent flex items-center justify-center text-xs font-bold">
|
||||
{msg.isStaff ? (
|
||||
<Shield className="h-4 w-4 text-primary" />
|
||||
) : (
|
||||
<User className="h-4 w-4" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<span
|
||||
className={`text-xs font-semibold ${msg.isStaff ? "text-primary" : ""}`}
|
||||
>
|
||||
{msg.user.username}
|
||||
{msg.isStaff && " (Staff)"}
|
||||
</span>
|
||||
<span className="text-[10px] text-muted-foreground">
|
||||
{new Date(msg.createdAt).toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
className={`rounded-lg px-4 py-2.5 text-sm leading-relaxed ${
|
||||
msg.isStaff
|
||||
? "bg-primary/10 border border-primary/20"
|
||||
: "bg-muted"
|
||||
}`}
|
||||
>
|
||||
<p className="whitespace-pre-wrap break-words">
|
||||
{msg.message}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
<div ref={messagesEndRef} />
|
||||
</div>
|
||||
|
||||
{/* Reply */}
|
||||
{canEdit && !isClosed && (
|
||||
<div className="border-t p-4">
|
||||
<div className="flex gap-2">
|
||||
<Textarea
|
||||
value={reply}
|
||||
onChange={(e) => setReply(e.target.value)}
|
||||
placeholder="Reply as staff..."
|
||||
rows={3}
|
||||
maxLength={5000}
|
||||
className="resize-none"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
|
||||
e.preventDefault();
|
||||
handleReply();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
onClick={handleReply}
|
||||
disabled={isPending || !reply.trim()}
|
||||
size="icon"
|
||||
className="shrink-0 h-auto"
|
||||
>
|
||||
{isPending ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Send className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-[10px] text-muted-foreground mt-1">
|
||||
Ctrl+Enter to send. Your reply will be marked as staff.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isClosed && (
|
||||
<div className="border-t p-4 text-center text-sm text-muted-foreground">
|
||||
Ticket closed{" "}
|
||||
{ticket.closedAt
|
||||
? `on ${new Date(ticket.closedAt).toLocaleDateString()}`
|
||||
: ""}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Sidebar */}
|
||||
<div className="space-y-4">
|
||||
{/* Actions */}
|
||||
{canEdit && (
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm">Actions</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div>
|
||||
<span className="text-xs text-muted-foreground mb-1 block">
|
||||
Status
|
||||
</span>
|
||||
<Select
|
||||
value={ticket.status}
|
||||
onValueChange={handleStatusChange}
|
||||
>
|
||||
<SelectTrigger className="h-8 text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{TICKET_STATUSES.map((s) => (
|
||||
<SelectItem
|
||||
key={s}
|
||||
value={s}
|
||||
className="text-xs capitalize"
|
||||
>
|
||||
{s.replace("_", " ")}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<span className="text-xs text-muted-foreground mb-1 block">
|
||||
Priority
|
||||
</span>
|
||||
<Select
|
||||
value={ticket.priority}
|
||||
onValueChange={handlePriorityChange}
|
||||
>
|
||||
<SelectTrigger className="h-8 text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{TICKET_PRIORITIES.map((p) => (
|
||||
<SelectItem
|
||||
key={p}
|
||||
value={p}
|
||||
className="text-xs capitalize"
|
||||
>
|
||||
{p}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<span className="text-xs text-muted-foreground mb-1 block">
|
||||
Assign to
|
||||
</span>
|
||||
<Select
|
||||
value={
|
||||
ticket.assignee ? String(ticket.assignee.id) : "unassign"
|
||||
}
|
||||
onValueChange={handleAssign}
|
||||
>
|
||||
<SelectTrigger className="h-8 text-xs">
|
||||
<SelectValue placeholder="Unassigned" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="unassign" className="text-xs">
|
||||
Unassigned
|
||||
</SelectItem>
|
||||
{staffMembers.map((s) => (
|
||||
<SelectItem
|
||||
key={s.id}
|
||||
value={String(s.id)}
|
||||
className="text-xs"
|
||||
>
|
||||
{s.username}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-full"
|
||||
onClick={() => {
|
||||
handleAssign(String(currentUserId));
|
||||
}}
|
||||
>
|
||||
Assign to me
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* User info */}
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm">Requester</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2">
|
||||
<Link
|
||||
href={creatorHref()}
|
||||
className="flex items-center gap-2 text-sm font-medium hover:text-primary"
|
||||
>
|
||||
<User className="h-3.5 w-3.5" />
|
||||
{ticket.creator.username}
|
||||
<Badge variant="outline" className="text-[10px]">
|
||||
Rank {ticket.creator.rank}
|
||||
</Badge>
|
||||
</Link>
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<Mail className="h-3 w-3" />
|
||||
{ticket.creator.mail}
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<Globe className="h-3 w-3" />
|
||||
{ticket.creator.ipRegister}
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<Calendar className="h-3 w-3" />
|
||||
Registered{" "}
|
||||
{new Date(
|
||||
ticket.creator.accountCreated * 1000,
|
||||
).toLocaleDateString()}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Ticket info */}
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm">Details</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2 text-xs text-muted-foreground">
|
||||
<div className="flex justify-between">
|
||||
<span>Created</span>
|
||||
<span>{new Date(ticket.createdAt).toLocaleString()}</span>
|
||||
</div>
|
||||
{ticket.closedAt && (
|
||||
<div className="flex justify-between">
|
||||
<span>Closed</span>
|
||||
<span>{new Date(ticket.closedAt).toLocaleString()}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex justify-between">
|
||||
<span>Messages</span>
|
||||
<span>{messages.length}</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
import { asc, eq, gte } from "drizzle-orm";
|
||||
import { notFound, redirect } from "next/navigation";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import { TicketQueueBanner } from "@/components/admin/ticket-queue-banner";
|
||||
import { getMinStaffRank } from "@/lib/admin/min-staff-rank";
|
||||
import { fetchTicketQueueOpenCounts } from "@/lib/admin/ticket-queue-counts";
|
||||
import { db, User, WebsiteTicket } from "@/lib/db";
|
||||
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
|
||||
import { AdminTicketDetail } from "./admin-ticket-detail";
|
||||
|
||||
export default async function AdminTicketDetailPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string }>;
|
||||
}) {
|
||||
const { session, permissions } = await getAdminContext();
|
||||
if (!canAccess(permissions, PERMS.TICKETS_VIEW, session.user.rank)) {
|
||||
redirect("/admin");
|
||||
}
|
||||
|
||||
const t = await getTranslations("pages.admin.tickets");
|
||||
const { id } = await params;
|
||||
const ticketId = Number(id);
|
||||
if (Number.isNaN(ticketId)) notFound();
|
||||
|
||||
const ticket = await db.query.WebsiteTicket.findFirst({
|
||||
where: eq(WebsiteTicket.id, ticketId),
|
||||
with: {
|
||||
creator: {
|
||||
columns: {
|
||||
id: true,
|
||||
username: true,
|
||||
look: true,
|
||||
rank: true,
|
||||
ipRegister: true,
|
||||
mail: true,
|
||||
accountCreated: true,
|
||||
},
|
||||
},
|
||||
assignee: { columns: { id: true, username: true } },
|
||||
messages: {
|
||||
orderBy: (m, { asc: a }) => [a(m.createdAt)],
|
||||
with: {
|
||||
user: {
|
||||
columns: { id: true, username: true, look: true, rank: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!ticket) notFound();
|
||||
|
||||
// Staff assignees: min_staff_rank and above
|
||||
const minStaffRank = await getMinStaffRank();
|
||||
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.TICKETS_EDIT, session.user.rank);
|
||||
const queues = await fetchTicketQueueOpenCounts();
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<TicketQueueBanner
|
||||
hint={t("queueHint")}
|
||||
otherHref="/admin/help-tickets"
|
||||
otherLabel={t("queueOtherCta")}
|
||||
countsLine={t("queueCounts", {
|
||||
here: queues.cmsOpen,
|
||||
other: queues.helpOpen,
|
||||
})}
|
||||
/>
|
||||
<AdminTicketDetail
|
||||
ticket={{
|
||||
id: ticket.id,
|
||||
subject: ticket.subject,
|
||||
category: ticket.category,
|
||||
priority: ticket.priority,
|
||||
status: ticket.status,
|
||||
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,
|
||||
},
|
||||
assignee: ticket.assignee
|
||||
? { id: ticket.assignee.id, username: ticket.assignee.username }
|
||||
: null,
|
||||
}}
|
||||
messages={ticket.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,
|
||||
},
|
||||
}))}
|
||||
staffMembers={staffMembers}
|
||||
currentUserId={session.user.id}
|
||||
canEdit={canEdit}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,204 +0,0 @@
|
||||
import {
|
||||
and,
|
||||
asc,
|
||||
count,
|
||||
desc,
|
||||
eq,
|
||||
like,
|
||||
ne,
|
||||
or,
|
||||
type SQL,
|
||||
sql,
|
||||
} from "drizzle-orm";
|
||||
import { alias } from "drizzle-orm/mysql-core";
|
||||
import { redirect } from "next/navigation";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import { StatusCard } from "@/components/admin/dashboard";
|
||||
import { TicketQueueBanner } from "@/components/admin/ticket-queue-banner";
|
||||
import { fetchTicketQueueOpenCounts } from "@/lib/admin/ticket-queue-counts";
|
||||
import { calcPagination, parseListParams } from "@/lib/admin-helpers";
|
||||
import { db, User, WebsiteTicket } from "@/lib/db";
|
||||
import { formatDate } from "@/lib/format-date";
|
||||
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
|
||||
import { type TicketRow, TicketsTable } from "../tickets-table";
|
||||
|
||||
export default async function AdminTicketsDeskPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<Record<string, string>>;
|
||||
}) {
|
||||
const { session, permissions } = await getAdminContext();
|
||||
if (!canAccess(permissions, PERMS.TICKETS_VIEW, session.user.rank)) {
|
||||
redirect("/admin");
|
||||
}
|
||||
|
||||
const t = await getTranslations("pages.admin.tickets");
|
||||
const raw = await searchParams;
|
||||
const parsed = parseListParams(new URLSearchParams(raw));
|
||||
const statusFilter = raw.filter_status || raw.status || "active";
|
||||
|
||||
const Creator = alias(User, "ticket_creator");
|
||||
const Assignee = alias(User, "ticket_assignee");
|
||||
|
||||
const conditions: SQL[] = [];
|
||||
|
||||
if (statusFilter === "active") {
|
||||
conditions.push(ne(WebsiteTicket.status, "closed"));
|
||||
} else if (statusFilter && statusFilter !== "all") {
|
||||
conditions.push(eq(WebsiteTicket.status, statusFilter));
|
||||
}
|
||||
|
||||
if (parsed.search.trim()) {
|
||||
const q = parsed.search.trim();
|
||||
const asId = Number(q);
|
||||
const searchFilter = or(
|
||||
like(WebsiteTicket.subject, `%${q}%`),
|
||||
like(WebsiteTicket.category, `%${q}%`),
|
||||
like(Creator.username, `%${q}%`),
|
||||
like(Assignee.username, `%${q}%`),
|
||||
...(Number.isFinite(asId) && asId > 0
|
||||
? [eq(WebsiteTicket.id, asId)]
|
||||
: []),
|
||||
);
|
||||
if (searchFilter) conditions.push(searchFilter);
|
||||
}
|
||||
|
||||
const where = conditions.length > 0 ? and(...conditions) : undefined;
|
||||
|
||||
const orderCol =
|
||||
parsed.sort === "subject"
|
||||
? WebsiteTicket.subject
|
||||
: parsed.sort === "status"
|
||||
? WebsiteTicket.status
|
||||
: parsed.sort === "priority"
|
||||
? WebsiteTicket.priority
|
||||
: parsed.sort === "assignee"
|
||||
? WebsiteTicket.assigneeId
|
||||
: parsed.sort === "id"
|
||||
? WebsiteTicket.id
|
||||
: WebsiteTicket.createdAt;
|
||||
const orderBy = parsed.order === "asc" ? asc(orderCol) : desc(orderCol);
|
||||
|
||||
const [totalRows, openRows, inProgressRows, waitingRows, closedRows, queues] =
|
||||
await Promise.all([
|
||||
db
|
||||
.select({ total: count() })
|
||||
.from(WebsiteTicket)
|
||||
.leftJoin(Creator, eq(WebsiteTicket.creatorId, Creator.id))
|
||||
.leftJoin(Assignee, eq(WebsiteTicket.assigneeId, Assignee.id))
|
||||
.where(where)
|
||||
.catch(() => [{ total: 0 }]),
|
||||
db
|
||||
.select({ total: count() })
|
||||
.from(WebsiteTicket)
|
||||
.where(eq(WebsiteTicket.status, "open"))
|
||||
.catch(() => [{ total: 0 }]),
|
||||
db
|
||||
.select({ total: count() })
|
||||
.from(WebsiteTicket)
|
||||
.where(eq(WebsiteTicket.status, "in_progress"))
|
||||
.catch(() => [{ total: 0 }]),
|
||||
db
|
||||
.select({ total: count() })
|
||||
.from(WebsiteTicket)
|
||||
.where(eq(WebsiteTicket.status, "waiting"))
|
||||
.catch(() => [{ total: 0 }]),
|
||||
db
|
||||
.select({ total: count() })
|
||||
.from(WebsiteTicket)
|
||||
.where(eq(WebsiteTicket.status, "closed"))
|
||||
.catch(() => [{ total: 0 }]),
|
||||
fetchTicketQueueOpenCounts(),
|
||||
]);
|
||||
|
||||
const total = Number(totalRows[0]?.total ?? 0);
|
||||
const openCount = Number(openRows[0]?.total ?? 0);
|
||||
const inProgressCount = Number(inProgressRows[0]?.total ?? 0);
|
||||
const waitingCount = Number(waitingRows[0]?.total ?? 0);
|
||||
const closedCount = Number(closedRows[0]?.total ?? 0);
|
||||
|
||||
const pagination = calcPagination(total, parsed.page, parsed.perPage);
|
||||
|
||||
const tickets = await db
|
||||
.select({
|
||||
id: WebsiteTicket.id,
|
||||
subject: WebsiteTicket.subject,
|
||||
creatorId: WebsiteTicket.creatorId,
|
||||
category: WebsiteTicket.category,
|
||||
status: WebsiteTicket.status,
|
||||
priority: WebsiteTicket.priority,
|
||||
createdAt: WebsiteTicket.createdAt,
|
||||
creatorUsername: Creator.username,
|
||||
assigneeUsername: Assignee.username,
|
||||
messageCount: sql<number>`(
|
||||
SELECT COUNT(*) FROM website_ticket_messages m
|
||||
WHERE m.ticket_id = ${WebsiteTicket.id}
|
||||
)`.mapWith(Number),
|
||||
})
|
||||
.from(WebsiteTicket)
|
||||
.leftJoin(Creator, eq(WebsiteTicket.creatorId, Creator.id))
|
||||
.leftJoin(Assignee, eq(WebsiteTicket.assigneeId, Assignee.id))
|
||||
.where(where)
|
||||
.orderBy(orderBy)
|
||||
.limit(pagination.perPage)
|
||||
.offset(pagination.offset)
|
||||
.catch(() => []);
|
||||
|
||||
const rows: TicketRow[] = tickets.map((ticket) => ({
|
||||
id: ticket.id,
|
||||
subject: ticket.subject,
|
||||
creator: ticket.creatorUsername ?? "—",
|
||||
creatorId: ticket.creatorId,
|
||||
category: ticket.category,
|
||||
messages: Number(ticket.messageCount ?? 0),
|
||||
status: ticket.status,
|
||||
priority: ticket.priority,
|
||||
assignee: ticket.assigneeUsername ?? "—",
|
||||
date: formatDate(ticket.createdAt, "date"),
|
||||
}));
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<TicketQueueBanner
|
||||
hint={t("queueHint")}
|
||||
otherHref="/admin/help-tickets"
|
||||
otherLabel={t("queueOtherCta")}
|
||||
countsLine={t("queueCounts", {
|
||||
here: queues.cmsOpen,
|
||||
other: queues.helpOpen,
|
||||
})}
|
||||
/>
|
||||
<div className="grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] gap-3.5">
|
||||
<StatusCard label={t("statusOpen")} value={openCount} icon="🎫" />
|
||||
<StatusCard
|
||||
label={t("statusInProgress")}
|
||||
value={inProgressCount}
|
||||
state={inProgressCount > 0 ? "warn" : "neutral"}
|
||||
icon="⏳"
|
||||
/>
|
||||
<StatusCard
|
||||
label={t("statusWaiting")}
|
||||
value={waitingCount}
|
||||
state={waitingCount > 0 ? "warn" : "neutral"}
|
||||
icon="🕒"
|
||||
/>
|
||||
<StatusCard label={t("statusClosed")} value={closedCount} icon="✅" />
|
||||
</div>
|
||||
|
||||
{total === 0 && !parsed.search && statusFilter === "active" ? (
|
||||
<div className="admin-empty">{t("noTickets")}</div>
|
||||
) : (
|
||||
<TicketsTable
|
||||
basePath="/admin/tickets"
|
||||
data={{
|
||||
rows,
|
||||
total,
|
||||
page: pagination.page,
|
||||
perPage: pagination.perPage,
|
||||
lastPage: pagination.lastPage,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import { StatusCard } from "@/components/admin/dashboard";
|
||||
import { UnifiedTicketsTable } from "@/components/admin/unified-tickets-table";
|
||||
import {
|
||||
fetchUnifiedTicketInbox,
|
||||
type TicketInboxTypeFilter,
|
||||
} from "@/lib/admin/ticket-inbox";
|
||||
import { fetchTicketQueueOpenCounts } from "@/lib/admin/ticket-queue-counts";
|
||||
import { parseListParams } from "@/lib/admin-helpers";
|
||||
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
|
||||
|
||||
export default async function AdminTicketInboxPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<Record<string, string>>;
|
||||
}) {
|
||||
const { session, permissions } = await getAdminContext();
|
||||
if (!canAccess(permissions, PERMS.TICKETS_VIEW, session.user.rank)) {
|
||||
redirect("/admin");
|
||||
}
|
||||
|
||||
const t = await getTranslations("pages.admin.ticketInbox");
|
||||
const raw = await searchParams;
|
||||
const parsed = parseListParams(new URLSearchParams(raw));
|
||||
const typeRaw = raw.filter_type || "all";
|
||||
const type: TicketInboxTypeFilter =
|
||||
typeRaw === "cms" || typeRaw === "help" ? typeRaw : "all";
|
||||
const statusFilter = raw.filter_status || "open";
|
||||
const openOnly = statusFilter !== "all";
|
||||
|
||||
const [inbox, queues] = await Promise.all([
|
||||
fetchUnifiedTicketInbox({
|
||||
page: parsed.page,
|
||||
perPage: parsed.perPage,
|
||||
search: parsed.search,
|
||||
type,
|
||||
openOnly,
|
||||
base: "admin",
|
||||
}),
|
||||
fetchTicketQueueOpenCounts(),
|
||||
]);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<p className="m-0 text-sm text-[var(--admin-text-muted)]">{t("hint")}</p>
|
||||
<div className="grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] gap-3.5">
|
||||
<StatusCard label={t("statCmsOpen")} value={queues.cmsOpen} icon="🎫" />
|
||||
<StatusCard
|
||||
label={t("statHelpOpen")}
|
||||
value={queues.helpOpen}
|
||||
state={queues.helpOpen > 0 ? "warn" : "neutral"}
|
||||
icon="🛟"
|
||||
/>
|
||||
<StatusCard
|
||||
label={t("statTotal")}
|
||||
value={queues.cmsOpen + queues.helpOpen}
|
||||
icon="📥"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{inbox.total === 0 && !parsed.search ? (
|
||||
<div className="admin-empty">{t("noTickets")}</div>
|
||||
) : (
|
||||
<UnifiedTicketsTable
|
||||
data={{
|
||||
rows: inbox.rows,
|
||||
total: inbox.total,
|
||||
page: inbox.page,
|
||||
perPage: inbox.perPage,
|
||||
lastPage: inbox.lastPage,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
import { asc } from "drizzle-orm";
|
||||
import { redirect } from "next/navigation";
|
||||
import { db, WebsiteTicketTemplate } from "@/lib/db";
|
||||
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
|
||||
import { TicketTemplatesManager } from "./templates-manager";
|
||||
|
||||
export default async function TicketTemplatesPage() {
|
||||
const { session, permissions } = await getAdminContext();
|
||||
if (!canAccess(permissions, PERMS.TICKETS_EDIT, session.user.rank)) {
|
||||
redirect("/admin/tickets");
|
||||
}
|
||||
|
||||
const templates = await db
|
||||
.select()
|
||||
.from(WebsiteTicketTemplate)
|
||||
.orderBy(asc(WebsiteTicketTemplate.sortOrder));
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<TicketTemplatesManager templates={templates} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,205 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { Copy, Pencil, Plus, Trash2 } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import {
|
||||
createTemplate,
|
||||
deleteTemplate,
|
||||
updateTemplate,
|
||||
} from "@/actions/ticket-templates";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { useServerAction } from "@/hooks/use-server-action";
|
||||
|
||||
interface Template {
|
||||
id: number;
|
||||
title: string;
|
||||
content: string;
|
||||
category: string;
|
||||
sortOrder: number;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
templates: Template[];
|
||||
}
|
||||
|
||||
export function TicketTemplatesManager({ templates }: Props) {
|
||||
const { run, isPending } = useServerAction();
|
||||
const [showForm, setShowForm] = useState(false);
|
||||
const [editingId, setEditingId] = useState<number | null>(null);
|
||||
const [form, setForm] = useState({
|
||||
title: "",
|
||||
content: "",
|
||||
category: "general",
|
||||
sortOrder: 0,
|
||||
});
|
||||
|
||||
function resetForm() {
|
||||
setForm({ title: "", content: "", category: "general", sortOrder: 0 });
|
||||
setEditingId(null);
|
||||
setShowForm(false);
|
||||
}
|
||||
|
||||
function handleEdit(t: Template) {
|
||||
setForm({
|
||||
title: t.title,
|
||||
content: t.content,
|
||||
category: t.category,
|
||||
sortOrder: t.sortOrder,
|
||||
});
|
||||
setEditingId(t.id);
|
||||
setShowForm(true);
|
||||
}
|
||||
|
||||
function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (editingId) {
|
||||
run(() => updateTemplate({ id: editingId, ...form }), {
|
||||
successMessage: "Template updated!",
|
||||
onSuccess: resetForm,
|
||||
});
|
||||
} else {
|
||||
run(() => createTemplate(form), {
|
||||
successMessage: "Template created!",
|
||||
onSuccess: resetForm,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
onClick={() => {
|
||||
resetForm();
|
||||
setShowForm(!showForm);
|
||||
}}
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-2" /> New Template
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{showForm && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>
|
||||
{editingId ? "Edit Template" : "New Template"}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Title</Label>
|
||||
<Input
|
||||
value={form.title}
|
||||
onChange={(e) =>
|
||||
setForm({ ...form, title: e.target.value })
|
||||
}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Category</Label>
|
||||
<Input
|
||||
value={form.category}
|
||||
onChange={(e) =>
|
||||
setForm({ ...form, category: e.target.value })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Sort Order</Label>
|
||||
<Input
|
||||
type="number"
|
||||
value={form.sortOrder}
|
||||
onChange={(e) =>
|
||||
setForm({ ...form, sortOrder: Number(e.target.value) })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Content</Label>
|
||||
<textarea
|
||||
className="w-full rounded-md border bg-transparent px-3 py-2 text-sm min-h-[120px]"
|
||||
value={form.content}
|
||||
onChange={(e) =>
|
||||
setForm({ ...form, content: e.target.value })
|
||||
}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="flex gap-2 justify-end">
|
||||
<Button type="button" variant="outline" onClick={resetForm}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={isPending}>
|
||||
{editingId ? "Update" : "Create"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
{templates.length === 0 && (
|
||||
<p className="text-muted-foreground text-center py-8">
|
||||
No templates yet.
|
||||
</p>
|
||||
)}
|
||||
{templates.map((t) => (
|
||||
<Card key={t.id}>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<span className="font-medium text-sm">{t.title}</span>
|
||||
<Badge variant="secondary">{t.category}</Badge>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground whitespace-pre-wrap">
|
||||
{t.content}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex gap-1 shrink-0 ml-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7"
|
||||
onClick={() => navigator.clipboard.writeText(t.content)}
|
||||
>
|
||||
<Copy className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7"
|
||||
onClick={() => handleEdit(t)}
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7"
|
||||
onClick={() =>
|
||||
run(() => deleteTemplate({ id: t.id }), {
|
||||
successMessage: "Deleted",
|
||||
})
|
||||
}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useTranslations } from "next-intl";
|
||||
import { DataTable } from "@/components/admin/data-table";
|
||||
import Link from "@/components/link";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import type { DataTableColumn, PaginatedResult } from "@/types/common";
|
||||
|
||||
export interface TicketRow {
|
||||
id: number;
|
||||
subject: string;
|
||||
creator: string;
|
||||
creatorId: number;
|
||||
category: string;
|
||||
messages: number;
|
||||
status: string;
|
||||
priority: string;
|
||||
assignee: string;
|
||||
date: string;
|
||||
}
|
||||
|
||||
const STATUS_VARIANT: Record<
|
||||
string,
|
||||
"default" | "secondary" | "destructive" | "outline"
|
||||
> = {
|
||||
open: "default",
|
||||
in_progress: "secondary",
|
||||
waiting: "outline",
|
||||
closed: "secondary",
|
||||
};
|
||||
|
||||
export function TicketsTable({
|
||||
data,
|
||||
basePath = "/admin/tickets",
|
||||
}: {
|
||||
data: PaginatedResult<TicketRow>;
|
||||
basePath?: string;
|
||||
}) {
|
||||
const t = useTranslations("pages.admin.tickets");
|
||||
|
||||
const statusLabel: Record<string, string> = {
|
||||
open: t("statusOpen"),
|
||||
in_progress: t("statusInProgress"),
|
||||
waiting: t("statusWaiting"),
|
||||
closed: t("statusClosed"),
|
||||
};
|
||||
|
||||
const columns: DataTableColumn<TicketRow>[] = [
|
||||
{
|
||||
key: "subject",
|
||||
label: t("colTicket"),
|
||||
sortable: true,
|
||||
render: (_value, row) => (
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-muted-foreground font-mono">
|
||||
#{row.id}
|
||||
</span>
|
||||
<Link
|
||||
href={`${basePath}/${row.id}`}
|
||||
className="font-medium truncate hover:underline"
|
||||
>
|
||||
{row.subject}
|
||||
</Link>
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{t("meta", {
|
||||
user: row.creator,
|
||||
count: row.messages,
|
||||
category: row.category,
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "status",
|
||||
label: t("colStatus"),
|
||||
sortable: true,
|
||||
filterKey: "filter_status",
|
||||
filterOptions: [
|
||||
{ label: t("statusOpen"), value: "open" },
|
||||
{ label: t("statusInProgress"), value: "in_progress" },
|
||||
{ label: t("statusWaiting"), value: "waiting" },
|
||||
{ label: t("statusClosed"), value: "closed" },
|
||||
],
|
||||
render: (value) => {
|
||||
const status = String(value);
|
||||
return (
|
||||
<Badge
|
||||
variant={STATUS_VARIANT[status] ?? "secondary"}
|
||||
className="text-[0.7rem]"
|
||||
>
|
||||
{statusLabel[status] ?? status.replace("_", " ")}
|
||||
</Badge>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
key: "priority",
|
||||
label: t("colPriority"),
|
||||
sortable: true,
|
||||
render: (value) => {
|
||||
const p = String(value);
|
||||
const className =
|
||||
p === "urgent"
|
||||
? "text-[var(--admin-error)] font-bold"
|
||||
: p === "high"
|
||||
? "text-[var(--admin-warning)]"
|
||||
: p === "normal"
|
||||
? "text-[var(--admin-info)]"
|
||||
: "";
|
||||
return <span className={`text-xs capitalize ${className}`}>{p}</span>;
|
||||
},
|
||||
},
|
||||
{ key: "assignee", label: t("colAssigned"), sortable: true },
|
||||
{ key: "date", label: t("colDate"), sortable: true },
|
||||
];
|
||||
|
||||
return (
|
||||
<DataTable
|
||||
data={data}
|
||||
columns={columns}
|
||||
searchPlaceholder={t("searchPlaceholder")}
|
||||
presets={[
|
||||
{ label: t("presetActive"), params: { filter_status: "active" } },
|
||||
{ label: t("statusOpen"), params: { filter_status: "open" } },
|
||||
{
|
||||
label: t("statusInProgress"),
|
||||
params: { filter_status: "in_progress" },
|
||||
},
|
||||
{ label: t("statusWaiting"), params: { filter_status: "waiting" } },
|
||||
{ label: t("statusClosed"), params: { filter_status: "closed" } },
|
||||
]}
|
||||
/>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user