Dashboard Update

This commit is contained in:
1tzEmerald committed 2026-08-10 20:14:47 +01:00
1 parent 6165f2d4f3
commit 676283cce9
17 files changed
+4280 -213

No files matched your search

+3096
View File
File diff suppressed because it is too large. Load diff
+31 -31
View File
@@ -11,42 +11,42 @@
"dependencies": {
"@hugeicons/core-free-icons": "^4.1.4",
"@hugeicons/react": "^1.1.6",
"@monaco-editor/react": "^4.7.0",
"@radix-ui/react-avatar": "^1.1.11",
"@radix-ui/react-checkbox": "^1.3.3",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-dropdown-menu": "^2.1.16",
"@radix-ui/react-label": "^2.1.8",
"@radix-ui/react-popover": "^1.1.15",
"@radix-ui/react-scroll-area": "^1.2.10",
"@radix-ui/react-select": "^2.2.6",
"@radix-ui/react-separator": "^1.1.8",
"@radix-ui/react-slot": "^1.2.4",
"@radix-ui/react-switch": "^1.2.6",
"@radix-ui/react-tabs": "^1.1.13",
"@radix-ui/react-tooltip": "^1.2.8",
"autoprefixer": "^10.5.0",
"@monaco-editor/react": "^4.6.0",
"@radix-ui/react-avatar": "^1.1.0",
"@radix-ui/react-checkbox": "^1.1.0",
"@radix-ui/react-dialog": "^1.1.0",
"@radix-ui/react-dropdown-menu": "^2.1.0",
"@radix-ui/react-label": "^2.1.0",
"@radix-ui/react-popover": "^1.1.0",
"@radix-ui/react-scroll-area": "^1.2.0",
"@radix-ui/react-select": "^2.1.0",
"@radix-ui/react-separator": "^1.1.0",
"@radix-ui/react-slot": "^1.1.0",
"@radix-ui/react-switch": "^1.1.0",
"@radix-ui/react-tabs": "^1.1.0",
"@radix-ui/react-tooltip": "^1.1.0",
"autoprefixer": "^10.4.20",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"emoji-picker-element": "^1.29.1",
"lucide-react": "^1.16.0",
"postcss": "^8.5.14",
"react": "^19.1.0",
"react-colorful": "^5.7.0",
"react-dom": "^19.1.0",
"react-router-dom": "^7.6.2",
"sonner": "^2.0.7",
"tailwind-merge": "^3.6.0",
"cmdk": "^1.0.0",
"emoji-picker-element": "^1.26.0",
"lucide-react": "^0.475.0",
"postcss": "^8.4.49",
"react": "^19.0.0",
"react-colorful": "^5.6.1",
"react-dom": "^19.0.0",
"react-router-dom": "^7.1.5",
"sonner": "^1.7.4",
"tailwind-merge": "^2.6.0",
"tailwindcss": "^3.4.17",
"tailwindcss-animate": "^1.0.7"
},
"devDependencies": {
"@types/node": "^25.8.0",
"@types/react": "^19.1.2",
"@types/react-dom": "^19.1.2",
"@vitejs/plugin-react": "^4.5.0",
"typescript": "^5.8.3",
"vite": "^6.3.5"
"@types/node": "^22.0.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@vitejs/plugin-react": "^4.3.0",
"typescript": "^5.7.0",
"vite": "^6.0.0"
}
}
+7
View File
@@ -184,6 +184,7 @@ export interface GuildEmojiResource {
export interface GuildResources {
guildId: string;
guildName: string;
guildIcon?: string | null;
roles: { id: string; name: string; color: string | null }[];
channels: { id: string; name: string; type: number }[];
categories: { id: string; name: string }[];
@@ -349,6 +350,12 @@ export const api = {
}>
>("/api/system/tickets/open"),
createTicket: (data: { department?: string; subject?: string; reason?: string; userId?: string }) =>
request<ApiResponse<{ message: string }>>("/api/system/tickets/create", {
method: "POST",
body: JSON.stringify(data),
}),
getTicketMessages: (ticketId: string) =>
request<
ApiResponse<{
+43 -9
View File
@@ -1,3 +1,4 @@
import { useEffect, useState } from "react";
import type { IconSvgElement } from "@hugeicons/react";
import {
AiBrain01Icon,
@@ -18,6 +19,7 @@ import {
import { NavLink, useSearchParams } from "react-router-dom";
import { useAuth } from "@/context/AuthContext";
import { useBranding } from "@/context/BrandingContext";
import { api, type GuildResources } from "@/api/client";
import { useBotStats } from "@/context/BotStatsContext";
import { useAddonConfigs } from "@/hooks/use-addon-configs";
import {
@@ -145,9 +147,27 @@ export function AppSidebar() {
? [...visibleSections, addonSection]
: visibleSections;
const serverLabel = stats
? `${stats.servers} server${stats.servers === 1 ? "" : "s"}`
: "Your server";
const [guildResources, setGuildResources] = useState<GuildResources | null>(null);
useEffect(() => {
let cancelled = false;
api
.getGuildResources()
.then((res) => {
if (!cancelled && res.data) {
setGuildResources(res.data);
}
})
.catch(() => {});
return () => {
cancelled = true;
};
}, []);
const serverName =
guildResources?.guildName ||
(stats ? `${stats.servers} Server${stats.servers === 1 ? "" : "s"}` : "Connected Guild");
const serverIcon = guildResources?.guildIcon;
return (
<Sidebar collapsible="icon" className="border-r border-sidebar-border">
@@ -171,17 +191,31 @@ export function AppSidebar() {
variant="outline"
className="h-10 w-full justify-between border-border bg-secondary/40 px-3 font-normal hover:bg-secondary/60"
>
<span className="flex items-center gap-2 truncate">
<Icon icon={PlusSignIcon} size={16} className="text-muted-foreground" />
<span className="truncate">{serverLabel}</span>
<span className="flex items-center gap-2 truncate min-w-0">
{serverIcon ? (
<img
src={serverIcon}
alt=""
className="size-5 rounded-full object-cover shrink-0"
/>
) : (
<div className="size-5 rounded-full bg-primary/20 text-primary flex items-center justify-center text-[10px] font-bold shrink-0">
{serverName.charAt(0).toUpperCase()}
</div>
)}
<span className="truncate text-xs font-semibold text-foreground">
{serverName}
</span>
</span>
<Icon icon={ArrowDown01Icon} size={16} className="text-muted-foreground" />
<Icon icon={ArrowDown01Icon} size={14} className="text-muted-foreground shrink-0 ml-1" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-[--radix-dropdown-menu-trigger-width]">
<DropdownMenuItem disabled>Connected via API</DropdownMenuItem>
<DropdownMenuItem disabled className="text-xs font-medium">
Connected Guild: {serverName}
</DropdownMenuItem>
{stats ? (
<DropdownMenuItem disabled>
<DropdownMenuItem disabled className="text-xs text-muted-foreground">
{stats.users.toLocaleString()} members tracked
</DropdownMenuItem>
) : null}
@@ -1,10 +1,12 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { useSearchParams } from "react-router-dom";
import { AlertCircleIcon, FloppyDiskIcon } from "@hugeicons/core-free-icons";
import { AlertCircleIcon, FloppyDiskIcon, Add01Icon, Delete02Icon } from "@hugeicons/core-free-icons";
import { api, maskConfigSecrets } from "@/api/client";
import { Icon } from "@/components/icon";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Card,
CardContent,
@@ -12,6 +14,14 @@ import {
CardHeader,
CardTitle,
} from "@/components/ui/card";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Skeleton } from "@/components/ui/skeleton";
import { getSchema, type ConfigSchema } from "@/lib/config-schemas";
import { getByPath, setByPath } from "@/lib/config-utils";
@@ -24,6 +34,8 @@ import Editor from "@monaco-editor/react";
import { ConfigFieldInput } from "./config-field";
import { CommandsEditor } from "./commands-editor";
import { hasPermission } from "@/lib/permissions";
type EditorMode = "visual" | "yaml";
interface ConfigVisualEditorProps {
@@ -79,8 +91,94 @@ function buildUpdates(
return updates;
}
interface GroupedFields {
standalone: ConfigField[];
groups: { key: string; name: string; fields: ConfigField[] }[];
}
function getGroupedSectionFields(
fields: ConfigField[],
data: Record<string, unknown> | null
): GroupedFields {
const subGroupMap = new Map<string, ConfigField[]>();
const standalone: ConfigField[] = [];
for (const field of fields) {
const parts = field.path.split(".");
if (parts.length >= 5 && parts[1] === "DepartmentSystem" && parts[2] === "Departments") {
const groupKey = parts[3];
const list = subGroupMap.get(groupKey) ?? [];
list.push(field);
subGroupMap.set(groupKey, list);
} else if (parts.length >= 3) {
const groupKey = parts[1];
const list = subGroupMap.get(groupKey) ?? [];
list.push(field);
subGroupMap.set(groupKey, list);
} else {
standalone.push(field);
}
}
if (subGroupMap.size === 0) {
return { standalone: fields, groups: [] };
}
const groups = [...subGroupMap.entries()].map(([groupKey, groupFields]) => {
const fieldOrder = [
"enabled",
"name",
"description",
"emoji",
"category",
"role",
"channelprefix",
"defaultpriority",
"questions",
];
groupFields.sort((a, b) => {
const aKey = a.path.split(".").pop()?.toLowerCase() || "";
const bKey = b.path.split(".").pop()?.toLowerCase() || "";
const aIdx = fieldOrder.indexOf(aKey);
const bIdx = fieldOrder.indexOf(bKey);
if (aIdx !== -1 && bIdx !== -1) return aIdx - bIdx;
if (aIdx !== -1) return -1;
if (bIdx !== -1) return 1;
return aKey.localeCompare(bKey);
});
const nameField = groupFields.find(
(f) => f.path.toLowerCase().endsWith(".name") || f.path.toLowerCase().endsWith(".title")
);
let displayName = "";
if (nameField && data) {
const val = getByPath(data, nameField.path);
if (typeof val === "string" && val.trim()) {
displayName = val.trim();
}
}
if (!displayName) {
displayName = groupKey
.replace(/_/g, " ")
.replace(/([a-z])([A-Z])/g, "$1 $2")
.replace(/\b\w/g, (c) => c.toUpperCase());
}
return {
key: groupKey,
name: displayName,
fields: groupFields,
};
});
return { standalone, groups };
}
export function ConfigVisualEditor({ configFile }: ConfigVisualEditorProps) {
const { canEditConfig } = useAuth();
const { permissions: effectivePermissions, canEditConfig } = useAuth();
const canRawYaml = hasPermission(effectivePermissions, "configs.raw_yaml");
const readOnly = !canEditConfig(configFile);
const [data, setData] = useState<Record<string, unknown> | null>(null);
const [original, setOriginal] = useState<Record<string, unknown> | null>(
@@ -91,6 +189,12 @@ export function ConfigVisualEditor({ configFile }: ConfigVisualEditorProps) {
const [error, setError] = useState("");
const [message, setMessage] = useState("");
const [mode, setMode] = useState<EditorMode>("visual");
useEffect(() => {
if (!canRawYaml && mode === "yaml") {
setMode("visual");
}
}, [canRawYaml, mode]);
const [rawYaml, setRawYaml] = useState("");
const [rawOriginal, setRawOriginal] = useState("");
const [searchParams] = useSearchParams();
@@ -98,6 +202,48 @@ export function ConfigVisualEditor({ configFile }: ConfigVisualEditorProps) {
() => searchParams.get("tab") || null
);
const [addDeptOpen, setAddDeptOpen] = useState(false);
const [newDeptKey, setNewDeptKey] = useState("");
const [newDeptName, setNewDeptName] = useState("");
const handleCreateDepartment = () => {
const key = newDeptKey.trim().toLowerCase().replace(/[^a-z0-9_-]/g, "");
if (!key || !data) return;
const name = newDeptName.trim() || key;
const prefix = `Ticket.DepartmentSystem.Departments.${key}`;
const next = { ...data };
setByPath(next, `${prefix}.Name`, name);
setByPath(next, `${prefix}.Description`, `Open a ${name} ticket`);
setByPath(next, `${prefix}.Emoji`, "🎫");
setByPath(next, `${prefix}.Category`, "CATEGORY_ID");
setByPath(next, `${prefix}.Role`, "ROLE_ID");
setByPath(next, `${prefix}.ChannelPrefix`, `${key}-`);
setByPath(next, `${prefix}.DefaultPriority`, "normal");
setByPath(next, `${prefix}.Questions`, ["What do you need assistance with?"]);
setData(next);
setAddDeptOpen(false);
setNewDeptKey("");
setNewDeptName("");
};
const handleDeleteDepartment = (deptKey: string) => {
if (!data) return;
const prefix = `Ticket.DepartmentSystem.Departments.${deptKey}`;
const next = JSON.parse(JSON.stringify(data));
Object.keys(next).forEach((k) => {
if (k.startsWith(prefix) || k === prefix) {
delete next[k];
}
});
if (next.Ticket && typeof next.Ticket === "object") {
const deptSys = (next.Ticket as any).DepartmentSystem;
if (deptSys && typeof deptSys === "object" && deptSys.Departments && typeof deptSys.Departments === "object") {
delete deptSys.Departments[deptKey];
}
}
setData(next);
};
const baseSchema = getSchema(configFile);
const effectiveSchema = useMemo(() => {
@@ -252,26 +398,28 @@ export function ConfigVisualEditor({ configFile }: ConfigVisualEditorProps) {
return (
<div className="space-y-4">
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="flex rounded-lg border border-border p-0.5">
<Button
type="button"
variant={mode === "visual" ? "secondary" : "ghost"}
size="sm"
className="h-8"
onClick={() => setMode("visual")}
>
Visual
</Button>
<Button
type="button"
variant={mode === "yaml" ? "secondary" : "ghost"}
size="sm"
className="h-8"
onClick={() => setMode("yaml")}
>
YAML
</Button>
</div>
{canRawYaml ? (
<div className="flex rounded-lg border border-border p-0.5">
<Button
type="button"
variant={mode === "visual" ? "secondary" : "ghost"}
size="sm"
className="h-8"
onClick={() => setMode("visual")}
>
Visual
</Button>
<Button
type="button"
variant={mode === "yaml" ? "secondary" : "ghost"}
size="sm"
className="h-8"
onClick={() => setMode("yaml")}
>
YAML
</Button>
</div>
) : null}
<div className="flex flex-wrap items-center gap-2">
{dirty ? (
<span className="text-xs text-amber-500">Unsaved changes</span>
@@ -363,36 +511,151 @@ export function ConfigVisualEditor({ configFile }: ConfigVisualEditorProps) {
.filter((section) => section.title === activeSectionTitle)
.map((section) => (
<Card key={section.title} className="border-border bg-card">
<CardHeader className="pb-3">
<CardTitle className="text-base">{section.title}</CardTitle>
{section.description ? (
<CardDescription>{section.description}</CardDescription>
) : null}
</CardHeader>
<CardContent className="grid gap-4 sm:grid-cols-2">
{section.fields.map((field) => (
<div
key={field.path}
className={
field.type === "textarea" || field.type === "stringList"
? "sm:col-span-2"
: ""
}
<CardHeader className="pb-3 flex flex-row items-center justify-between">
<div>
<CardTitle className="text-base">{section.title}</CardTitle>
{section.description ? (
<CardDescription>{section.description}</CardDescription>
) : null}
</div>
{section.title === "Ticket Departments" && !readOnly && (
<Button
type="button"
size="sm"
variant="outline"
onClick={() => setAddDeptOpen(true)}
className="gap-1.5 text-xs h-8 shrink-0"
>
<ConfigFieldInput
field={field}
value={getByPath(data, field.path)}
readOnly={readOnly}
onChange={(v) => patch(field.path, v)}
/>
</div>
))}
<Icon icon={Add01Icon} size={14} /> Add Department
</Button>
)}
</CardHeader>
<CardContent className="space-y-6">
{(() => {
const { standalone, groups } = getGroupedSectionFields(section.fields, data);
return (
<>
{standalone.length > 0 && (
<div className="grid gap-4 sm:grid-cols-2">
{standalone.map((field) => (
<div
key={field.path}
className={
field.type === "textarea" || field.type === "stringList"
? "sm:col-span-2"
: ""
}
>
<ConfigFieldInput
field={field}
value={getByPath(data, field.path)}
readOnly={readOnly}
onChange={(v) => patch(field.path, v)}
/>
</div>
))}
</div>
)}
{groups.map((group) => (
<div
key={group.key}
className="rounded-xl border border-border bg-card/60 p-4 space-y-4 shadow-sm transition-all hover:border-primary/40"
>
<div className="flex items-center justify-between border-b border-border/60 pb-3">
<div className="flex items-center gap-2">
<span className="font-semibold text-base text-foreground">
{group.name}
</span>
<span className="text-xs font-mono px-2.5 py-0.5 rounded-full bg-primary/10 text-primary border border-primary/20 font-medium">
{section.title === "Ticket Departments" ? `Ticket.${group.key}` : group.key}
</span>
</div>
{section.title === "Ticket Departments" && group.key !== "DepartmentSystem" && !readOnly && (
<Button
type="button"
size="sm"
variant="ghost"
onClick={() => handleDeleteDepartment(group.key)}
className="h-7 w-7 p-0 text-muted-foreground hover:text-destructive"
title="Delete Department"
>
<Icon icon={Delete02Icon} size={14} />
</Button>
)}
</div>
<div className="grid gap-4 sm:grid-cols-2">
{group.fields.map((field) => (
<div
key={field.path}
className={
field.type === "textarea" || field.type === "stringList"
? "sm:col-span-2"
: ""
}
>
<ConfigFieldInput
field={field}
value={getByPath(data, field.path)}
readOnly={readOnly}
onChange={(v) => patch(field.path, v)}
/>
</div>
))}
</div>
</div>
))}
</>
);
})()}
</CardContent>
</Card>
))}
</div>
</div>
) : null}
{/* Add Department Modal */}
<Dialog open={addDeptOpen} onOpenChange={setAddDeptOpen}>
<DialogContent className="sm:max-w-[400px]">
<DialogHeader>
<DialogTitle className="text-base">Add Ticket Department</DialogTitle>
<DialogDescription className="text-xs">
Create a new support department for ticket creation.
</DialogDescription>
</DialogHeader>
<div className="space-y-3 py-2">
<div className="space-y-1">
<Label className="text-xs font-semibold">Department Key (Internal ID)</Label>
<Input
placeholder="billing"
value={newDeptKey}
onChange={(e) => setNewDeptKey(e.target.value.toLowerCase().replace(/[^a-z0-9_-]/g, ""))}
className="text-xs font-mono border-border bg-secondary/30"
/>
<p className="text-[11px] text-muted-foreground">e.g. <code>billing</code>, <code>technical</code>, <code>sales</code></p>
</div>
<div className="space-y-1">
<Label className="text-xs font-semibold">Department Display Name</Label>
<Input
placeholder="Billing & Sales Support"
value={newDeptName}
onChange={(e) => setNewDeptName(e.target.value)}
className="text-xs border-border bg-secondary/30"
/>
</div>
</div>
<DialogFooter className="gap-2 sm:gap-0">
<Button variant="outline" size="sm" onClick={() => setAddDeptOpen(false)} className="text-xs">
Cancel
</Button>
<Button size="sm" onClick={handleCreateDepartment} disabled={!newDeptKey.trim()} className="text-xs bg-primary font-semibold">
Create Department
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}
@@ -1,14 +1,16 @@
import { useEffect, useMemo, useState } from "react";
import { api } from "@/api/client";
import { Search01Icon, UnfoldMoreIcon } from "@hugeicons/core-free-icons";
import { api, type GuildResources } from "@/api/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { Icon } from "@/components/icon";
import { cn } from "@/lib/utils";
export type DiscordResourceKind = "channel" | "role" | "category";
@@ -22,8 +24,6 @@ interface DiscordResourcePickerProps {
readOnly?: boolean;
}
import type { GuildResources } from "@/api/client";
export function DiscordResourcePicker({
id,
label,
@@ -36,6 +36,8 @@ export function DiscordResourcePicker({
const [resources, setResources] = useState<GuildResources | null>(null);
const [loadError, setLoadError] = useState("");
const [loading, setLoading] = useState(true);
const [open, setOpen] = useState(false);
const [search, setSearch] = useState("");
useEffect(() => {
let cancelled = false;
@@ -74,6 +76,14 @@ export function DiscordResourcePicker({
const current = String(value ?? "");
const matched = options.find((o) => o.id === current);
const filteredOptions = useMemo(() => {
if (!search.trim()) return options;
const q = search.toLowerCase().trim();
return options.filter(
(opt) => opt.name.toLowerCase().includes(q) || opt.id.includes(q),
);
}, [options, search]);
return (
<div className="space-y-2">
<Label htmlFor={id}>{label}</Label>
@@ -82,31 +92,77 @@ export function DiscordResourcePicker({
) : null}
{resources ? (
<Select
value={matched ? current : ""}
disabled={readOnly || loading}
onValueChange={(next) => onChange(next)}
>
<SelectTrigger id={id} className="border-border bg-secondary/30">
<SelectValue
placeholder={
loading
? "Loading…"
: `Select ${kind} from ${resources.guildName}…`
}
/>
</SelectTrigger>
<SelectContent className="max-h-64">
{options.map((opt) => (
<SelectItem key={opt.id} value={opt.id}>
{opt.name}
<span className="ml-2 font-mono text-xs text-muted-foreground">
{opt.id}
</span>
</SelectItem>
))}
</SelectContent>
</Select>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
id={id}
type="button"
variant="outline"
role="combobox"
aria-expanded={open}
disabled={readOnly || loading}
className="w-full justify-between border-border bg-secondary/30 text-left font-normal h-10 px-3 hover:bg-secondary/50"
>
<span className="truncate">
{matched ? (
<span className="flex items-center gap-2 min-w-0">
<span className="font-medium text-foreground truncate">{matched.name}</span>
<span className="font-mono text-[11px] text-muted-foreground shrink-0">{matched.id}</span>
</span>
) : (
<span className="text-muted-foreground">
{loading
? "Loading server list…"
: `Select ${kind} from ${resources.guildName}…`}
</span>
)}
</span>
<Icon icon={UnfoldMoreIcon} size={16} className="shrink-0 opacity-50 ml-2" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[var(--radix-popover-trigger-width)] p-2 bg-popover border-border shadow-2xl rounded-xl flex flex-col gap-2 z-50">
<div className="relative flex items-center">
<Icon icon={Search01Icon} size={14} className="absolute left-2.5 text-muted-foreground" />
<Input
placeholder={`Search ${kind}s by name or ID…`}
value={search}
onChange={(e) => setSearch(e.target.value)}
className="h-8 pl-8 text-xs border-border bg-secondary/20 focus-visible:ring-1"
autoFocus
/>
</div>
<div className="overflow-y-auto max-h-56 space-y-1 pr-1">
{filteredOptions.length === 0 ? (
<div className="p-3 text-center text-xs text-muted-foreground">
No {kind}s found matching "{search}"
</div>
) : (
filteredOptions.map((opt) => (
<button
key={opt.id}
type="button"
onClick={() => {
onChange(opt.id);
setOpen(false);
setSearch("");
}}
className={cn(
"w-full flex items-center justify-between px-2.5 py-1.5 rounded-lg text-xs transition-colors text-left",
opt.id === current
? "bg-primary/15 text-primary font-semibold border border-primary/20"
: "hover:bg-secondary/60 text-foreground"
)}
>
<span className="truncate mr-2 font-medium">{opt.name}</span>
<span className="font-mono text-[11px] text-muted-foreground shrink-0">
{opt.id}
</span>
</button>
))
)}
</div>
</PopoverContent>
</Popover>
) : null}
<Input
@@ -120,7 +176,7 @@ export function DiscordResourcePicker({
? "Category ID"
: "Channel ID"
}
className="border-border bg-secondary/30 font-mono text-sm"
className="border-border bg-secondary/30 font-mono text-xs"
/>
{loadError ? (
@@ -5,6 +5,7 @@ import {
BotIcon,
CheckmarkCircle02Icon,
Copy01Icon,
Database01Icon,
Key01Icon,
Link01Icon,
SecurityLockIcon,
@@ -22,6 +23,7 @@ import { cn } from "@/lib/utils";
export const SETUP_STEP_IDS = [
"botToken",
"database",
"secretKey",
"oauth",
"redirectUri",
@@ -43,6 +45,12 @@ export const SETUP_STEPS: {
subtitle: "Connect your Discord bot",
icon: BotIcon,
},
{
id: "database",
title: "Database",
subtitle: "SQLite or MySQL engine",
icon: Database01Icon,
},
{
id: "secretKey",
title: "Session secret",
@@ -696,3 +704,142 @@ export function EmeraldApiKeyStep({
</div>
);
}
export function DatabaseStep({
values,
setValues,
validation,
validating,
onValidate,
}: {
values: SetupFormValues;
setValues: React.Dispatch<React.SetStateAction<SetupFormValues>>;
validation: Record<string, FieldValidationResult>;
validating: boolean;
onValidate: () => void;
}) {
const result = validation.database;
const isMysql = values.dbDriver === "mysql";
return (
<div className="flex flex-1 flex-col gap-6">
<p className="text-sm leading-relaxed text-muted-foreground">
Choose your database storage engine. Select <strong>SQLite</strong> for instant zero-config local storage, or <strong>MySQL / MariaDB</strong> for external host databases.
</p>
<div className="grid gap-4 sm:grid-cols-2">
<div
onClick={() => setValues((v) => ({ ...v, dbDriver: "sqlite" }))}
className={cn(
"cursor-pointer rounded-xl border p-4 transition-all hover:border-primary",
values.dbDriver === "sqlite"
? "border-primary bg-primary/5 ring-2 ring-primary/20"
: "border-border bg-card",
)}
>
<div className="flex items-center justify-between mb-2">
<span className="font-semibold text-foreground">SQLite</span>
<span className="rounded-full bg-emerald-500/10 px-2.5 py-0.5 text-xs font-medium text-emerald-500">
Zero Config
</span>
</div>
<p className="text-xs text-muted-foreground">
Single-file SQL database stored locally at <code className="font-mono">./Data/supportbot.db</code>. Zero extra setup required.
</p>
</div>
<div
onClick={() => setValues((v) => ({ ...v, dbDriver: "mysql" }))}
className={cn(
"cursor-pointer rounded-xl border p-4 transition-all hover:border-primary",
values.dbDriver === "mysql"
? "border-primary bg-primary/5 ring-2 ring-primary/20"
: "border-border bg-card",
)}
>
<div className="flex items-center justify-between mb-2">
<span className="font-semibold text-foreground">MySQL / MariaDB</span>
<span className="rounded-full bg-blue-500/10 px-2.5 py-0.5 text-xs font-medium text-blue-500">
External Database
</span>
</div>
<p className="text-xs text-muted-foreground">
Connect to a remote or local MySQL database server.
</p>
</div>
</div>
{isMysql && (
<div className="space-y-4 rounded-xl border border-border bg-card/50 p-4">
<h4 className="text-sm font-semibold text-foreground">MySQL Connection Settings</h4>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2 sm:col-span-2">
<Label htmlFor="dbHost">Database Host</Label>
<Input
id="dbHost"
placeholder="127.0.0.1 or localhost"
value={values.dbHost}
onChange={(e) => setValues((v) => ({ ...v, dbHost: e.target.value }))}
className="h-11 text-sm"
/>
</div>
<div className="space-y-2">
<Label htmlFor="dbPort">Port</Label>
<Input
id="dbPort"
placeholder="3306"
value={values.dbPort}
onChange={(e) => setValues((v) => ({ ...v, dbPort: e.target.value }))}
className="h-11 text-sm font-mono"
/>
</div>
<div className="space-y-2">
<Label htmlFor="dbDatabase">Database Name</Label>
<Input
id="dbDatabase"
placeholder="supportbot"
value={values.dbDatabase}
onChange={(e) => setValues((v) => ({ ...v, dbDatabase: e.target.value }))}
className="h-11 text-sm"
/>
</div>
<div className="space-y-2">
<Label htmlFor="dbUser">Database User</Label>
<Input
id="dbUser"
placeholder="root"
value={values.dbUser}
onChange={(e) => setValues((v) => ({ ...v, dbUser: e.target.value }))}
className="h-11 text-sm font-mono"
/>
</div>
<div className="space-y-2">
<Label htmlFor="dbPassword">Password</Label>
<Input
id="dbPassword"
type="password"
placeholder="••••••••••••"
value={values.dbPassword}
onChange={(e) => setValues((v) => ({ ...v, dbPassword: e.target.value }))}
className="h-11 text-sm font-mono"
/>
</div>
</div>
</div>
)}
<ValidationBanner result={result} />
<div className="mt-auto">
<Button
type="button"
variant="secondary"
disabled={validating}
onClick={onValidate}
>
{validating ? "Testing Connection..." : "Test Connection & Validate"}
</Button>
</div>
</div>
);
}
+81 -10
View File
@@ -56,6 +56,65 @@ export const supportbotSchema: ConfigSchema = [
},
],
},
{
title: "Database",
fields: [
{
path: "Database.Driver",
label: "Database Engine",
type: "select",
options: [
{ value: "sqlite", label: "SQLite (Local File)" },
{ value: "mysql", label: "MySQL / MariaDB" },
],
description: "Select SQLite for zero-config file storage, or MySQL for external host servers.",
},
{
path: "Database.MySQL.Host",
label: "MySQL Host",
type: "text",
placeholder: "127.0.0.1 or localhost",
description: "Hostname or IP address of your MySQL database server.",
},
{
path: "Database.MySQL.Port",
label: "MySQL Port",
type: "number",
placeholder: "3306",
},
{
path: "Database.MySQL.Database",
label: "Database Name",
type: "text",
placeholder: "supportbot",
},
{
path: "Database.MySQL.User",
label: "Database User",
type: "text",
placeholder: "root",
},
{
path: "Database.MySQL.Password",
label: "Database Password",
type: "secret",
placeholder: "••••••••••••",
},
{
path: "Database.MySQL.ConnectionLimit",
label: "Connection Pool Limit",
type: "number",
placeholder: "10",
description: "Maximum simultaneous connections in the MySQL pool (default 10).",
},
{
path: "Database.SQLite.File",
label: "SQLite Database File Path",
type: "text",
placeholder: "./Data/supportbot.db",
},
],
},
{
title: "Activity",
fields: [
@@ -382,6 +441,22 @@ export const supportbotSchema: ConfigSchema = [
label: "AI welcome message",
type: "textarea",
},
{
path: "Ticket.Questions.Enabled",
label: "Ticket questions",
type: "boolean",
},
{
path: "Ticket.Questions.List",
label: "Default questions",
type: "stringList",
},
],
},
{
title: "Ticket Departments",
description: "Configure ticket department channels, emojis, staff roles, and custom department questions.",
fields: [
{
path: "Ticket.DepartmentSystem.Enabled",
label: "Departments enabled",
@@ -397,6 +472,12 @@ export const supportbotSchema: ConfigSchema = [
label: "Default department key",
type: "text",
},
],
},
{
title: "Ticket Priorities",
description: "Configure ticket priority levels and emojis.",
fields: [
{
path: "Ticket.PrioritySystem.Enabled",
label: "Priority system",
@@ -412,16 +493,6 @@ export const supportbotSchema: ConfigSchema = [
label: "User picks priority on open",
type: "boolean",
},
{
path: "Ticket.Questions.Enabled",
label: "Ticket questions",
type: "boolean",
},
{
path: "Ticket.Questions.List",
label: "Default questions",
type: "stringList",
},
],
},
{
@@ -14,6 +14,7 @@ function inferFieldType(key: string, value: unknown): FieldType {
if (typeof value === "string") {
const k = key.toLowerCase();
if (/prefix/.test(k)) return "text";
if (/emoji/.test(k)) return "emoji";
if (/guild.?id|guild_id/.test(k)) return "discordId";
if (/category/.test(k)) return "discordCategory";
+31 -15
View File
@@ -1,8 +1,12 @@
import type { ConfigField, ConfigSchema } from "@/lib/config-schemas";
import { collectConfigFields } from "@/lib/generic-config-schema";
function labelFromTopKey(key: string): string {
return key
function sectionTitleFromPath(path: string): string {
if (path.startsWith("Ticket.DepartmentSystem.")) return "Ticket Departments";
if (path.startsWith("Ticket.PrioritySystem.")) return "Ticket Priorities";
if (path.startsWith("Ticket.")) return "Tickets";
const top = path.split(".")[0] ?? "Other";
return top
.replace(/_/g, " ")
.replace(/([a-z])([A-Z])/g, "$1 $2")
.replace(/\b\w/g, (c) => c.toUpperCase());
@@ -18,22 +22,34 @@ export function mergeSchemaWithData(
if (discovered.length === 0) return schema;
const byTop = new Map<string, ConfigField[]>();
const result: ConfigSchema = schema.map((sec) => ({
...sec,
fields: [...sec.fields],
}));
const bySection = new Map<string, ConfigField[]>();
for (const field of discovered) {
const top = field.path.split(".")[0] ?? "Other";
const list = byTop.get(top) ?? [];
const title = sectionTitleFromPath(field.path);
const list = bySection.get(title) ?? [];
list.push(field);
byTop.set(top, list);
bySection.set(title, list);
}
const extraSections = [...byTop.entries()]
.sort(([a], [b]) => a.localeCompare(b))
.map(([top, fields]) => ({
title: labelFromTopKey(top),
description:
"These options exist in your config file but are not in the main editor sections.",
fields: fields.sort((a, b) => a.path.localeCompare(b.path)),
}));
for (const [title, fields] of bySection.entries()) {
const existing = result.find(
(s) => s.title.toLowerCase() === title.toLowerCase()
);
return [...schema, ...extraSections];
if (existing) {
existing.fields.push(...fields);
} else {
result.push({
title,
description: "These options exist in your config file but are not in the main editor sections.",
fields: fields.sort((a, b) => a.path.localeCompare(b.path)),
});
}
}
return result;
}
+15 -3
View File
@@ -26,6 +26,7 @@ export interface DashboardPermissions {
tickets: boolean;
logs: boolean;
transcripts: boolean;
rawYaml?: boolean;
settings: { view: boolean; update: boolean };
configs: Record<ConfigFile, ConfigFilePermission>;
users: { view: boolean; manage: boolean };
@@ -97,6 +98,9 @@ export function hasPermission(
if (key === "tickets") return permissions.tickets ?? permissions.overview;
if (key === "logs") return permissions.logs;
if (key === "transcripts") return permissions.transcripts;
if (key === "rawYaml" || key === "configs.raw_yaml" || key === "configs.rawYaml") {
return Boolean(permissions.rawYaml ?? (permissions.configs as unknown as Record<string, boolean>)?.rawYaml ?? false);
}
if (key === "settings.view") return permissions.settings.view;
if (key === "settings.update") return permissions.settings.update;
if (key === "users.view") return permissions.users.view;
@@ -147,15 +151,19 @@ function configMap(view: boolean, edit: boolean): Record<ConfigFile, ConfigFileP
);
}
export function fullPermissions(): DashboardPermissions {
export function fullPermissions(
rawYaml: boolean = true,
userManage: boolean = true,
): DashboardPermissions {
return {
overview: true,
tickets: true,
logs: true,
transcripts: true,
rawYaml,
settings: { view: true, update: true },
configs: configMap(true, true),
users: { view: true, manage: true },
users: { view: true, manage: userManage },
};
}
@@ -165,14 +173,16 @@ export function defaultPermissionsForRole(
): DashboardPermissions {
switch (role) {
case "owner":
return fullPermissions(true, true);
case "admin":
return fullPermissions();
return fullPermissions(false, false);
case "moderator":
return {
overview: true,
tickets: true,
logs: true,
transcripts: true,
rawYaml: false,
settings: { view: true, update: false },
configs: configMap(true, false),
users: { view: false, manage: false },
@@ -183,6 +193,7 @@ export function defaultPermissionsForRole(
tickets: true,
logs: true,
transcripts: false,
rawYaml: false,
settings: { view: true, update: false },
configs: configMap(true, true),
users: { view: false, manage: false },
@@ -193,6 +204,7 @@ export function defaultPermissionsForRole(
tickets: true,
logs: true,
transcripts: true,
rawYaml: false,
settings: { view: true, update: false },
configs: configMap(true, false),
users: { view: false, manage: false },
+6
View File
@@ -30,6 +30,12 @@ export interface SetupValidateResponse {
export interface SetupFormValues {
botToken: string;
dbDriver: "sqlite" | "mysql";
dbHost: string;
dbPort: string;
dbUser: string;
dbPassword: string;
dbDatabase: string;
secretKey: string;
clientId: string;
clientSecret: string;
+1 -2
View File
@@ -38,8 +38,7 @@ export function AddonBuilder() {
setLoading(true);
setSuccess(false);
try {
// NOTE: the endpoint isn't added to client.ts yet, we'll do that next
const res = await (api as any).buildAddon({
const res = await api.buildAddon({
name: commandName.toLowerCase(),
description: description || "A custom command",
permission,
+75 -45
View File
@@ -10,7 +10,8 @@ import {
import { api } from "@/api/client";
import { useAuth } from "@/context/AuthContext";
import type { DashboardGroup, DashboardPermissions } from "@/lib/permissions";
import { defaultPermissionsForRole } from "@/lib/permissions";
import { defaultPermissionsForRole, hasPermission } from "@/lib/permissions";
import { DiscordResourcePicker } from "@/components/config/discord-resource-picker";
import { Icon } from "@/components/icon";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
@@ -57,7 +58,7 @@ function PermissionEditor({
const set = (patch: Partial<DashboardPermissions>) =>
onChange({ ...permissions, ...patch });
const PERM_ITEMS: {
const MODULE_ITEMS: {
key: "overview" | "tickets" | "logs" | "transcripts";
title: string;
description: string;
@@ -69,17 +70,17 @@ function PermissionEditor({
},
{
key: "tickets",
title: "Tickets",
title: "Support Tickets",
description: "View open support tickets, live web chat, send staff replies, and close tickets.",
},
{
key: "transcripts",
title: "Transcripts",
title: "Ticket Transcripts",
description: "Access saved ticket HTML transcripts and configure public transcript options.",
},
{
key: "logs",
title: "Console Logs",
title: "Console Terminal Logs",
description: "View real-time bot terminal output, system logs, and runtime error traces.",
},
];
@@ -94,12 +95,13 @@ function PermissionEditor({
return (
<div className="space-y-6">
{/* Category 1: General & Modules */}
<div className="space-y-2.5">
<h4 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
General Capabilities
General & Modules Access
</h4>
<div className="grid gap-2.5">
{PERM_ITEMS.map(({ key, title, description }) => (
{MODULE_ITEMS.map(({ key, title, description }) => (
<label
key={key}
className="flex items-center justify-between gap-4 rounded-xl border border-border bg-secondary/20 p-3 transition-colors hover:bg-secondary/40"
@@ -116,7 +118,15 @@ function PermissionEditor({
/>
</label>
))}
</div>
</div>
{/* Category 2: Administration & System Settings */}
<div className="space-y-2.5">
<h4 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
Administration & Settings
</h4>
<div className="grid gap-2.5">
{/* Settings View */}
<label className="flex items-center justify-between gap-4 rounded-xl border border-border bg-secondary/20 p-3 transition-colors hover:bg-secondary/40">
<div className="space-y-0.5 min-w-0">
@@ -183,6 +193,7 @@ function PermissionEditor({
</div>
</div>
{/* Category 3: Configuration Files Access */}
<div className="space-y-2.5">
<h4 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
Configuration Files Access
@@ -237,6 +248,26 @@ function PermissionEditor({
</div>
);
})}
{/* Raw YAML Code Editor */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 rounded-xl border border-border bg-secondary/20 p-3 transition-colors hover:bg-secondary/40">
<div className="space-y-0.5 min-w-0">
<p className="text-sm font-semibold text-foreground">Raw YAML Code Editor</p>
<p className="text-xs text-muted-foreground leading-snug">
Access the raw YAML code editor tab to view or edit full raw configuration files.
</p>
</div>
<div className="flex items-center gap-4 shrink-0">
<label className="flex items-center gap-2 text-xs font-medium text-muted-foreground cursor-pointer">
<span>Access</span>
<Switch
checked={permissions.rawYaml ?? false}
disabled={disabled}
onCheckedChange={(rawYaml) => set({ rawYaml })}
/>
</label>
</div>
</div>
</div>
</div>
</div>
@@ -244,7 +275,8 @@ function PermissionEditor({
}
export function Groups() {
const { impersonateGroup, impersonatedGroup, stopImpersonation } = useAuth();
const { permissions: userPermissions, impersonateGroup, impersonatedGroup, stopImpersonation } = useAuth();
const canManage = hasPermission(userPermissions, "users.manage");
const [groups, setGroups] = useState<DashboardGroup[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
@@ -366,10 +398,12 @@ export function Groups() {
Create custom permission groups, assign staff members, and optionally sync with Discord Role IDs.
</p>
</div>
<Button onClick={openAddDialog} className="shrink-0 gap-2 bg-primary">
<Icon icon={Add01Icon} size={18} />
Create Group
</Button>
{canManage && (
<Button onClick={openAddDialog} className="shrink-0 gap-2 bg-primary">
<Icon icon={Add01Icon} size={18} />
Create Group
</Button>
)}
</div>
{/* Alerts */}
@@ -505,27 +539,27 @@ export function Groups() {
{impersonatedGroup?.id === group.id ? "Active Preview" : "View as Group"}
</Button>
{!group.isSystem && (
<>
<Button
size="sm"
variant="ghost"
className="h-7 px-2 text-xs gap-1 text-muted-foreground hover:text-foreground"
onClick={() => openEditDialog(group)}
>
<Icon icon={PencilEdit01Icon} size={13} />
Edit
</Button>
<Button
size="sm"
variant="ghost"
className="h-7 px-2 text-xs gap-1 text-muted-foreground hover:text-destructive"
onClick={() => handleDeleteGroup(group)}
>
<Icon icon={Delete02Icon} size={13} />
Delete
</Button>
</>
{canManage && group.id !== "owner" && (
<Button
size="sm"
variant="ghost"
className="h-7 px-2 text-xs gap-1 text-muted-foreground hover:text-foreground"
onClick={() => openEditDialog(group)}
>
<Icon icon={PencilEdit01Icon} size={13} />
Edit
</Button>
)}
{canManage && !group.isSystem && (
<Button
size="sm"
variant="ghost"
className="h-7 px-2 text-xs gap-1 text-muted-foreground hover:text-destructive"
onClick={() => handleDeleteGroup(group)}
>
<Icon icon={Delete02Icon} size={13} />
Delete
</Button>
)}
</div>
</td>
@@ -598,18 +632,14 @@ export function Groups() {
/>
</div>
<div className="space-y-2">
<Label htmlFor="discord-role-id">Discord Role ID (Optional Auto-Sync)</Label>
<Input
id="discord-role-id"
placeholder="e.g. 123456789012345678"
value={discordRoleId}
onChange={(e) => setDiscordRoleId(e.target.value)}
/>
<p className="text-xs text-muted-foreground">
If provided, Discord users with this Role ID will automatically inherit this group upon login.
</p>
</div>
<DiscordResourcePicker
id="discord-role-id"
label="Discord Role ID (Optional Auto-Sync)"
description="If provided, Discord users with this Role ID will automatically inherit this group upon login."
kind="role"
value={discordRoleId}
onChange={(val) => setDiscordRoleId(String(val ?? ""))}
/>
<div className="pt-2">
<h4 className="text-sm font-semibold mb-3">Group Permission Matrix</h4>
+21
View File
@@ -5,6 +5,7 @@ import { Alert, AlertDescription } from "@/components/ui/alert";
import { Skeleton } from "@/components/ui/skeleton";
import {
BotTokenStep,
DatabaseStep,
OAuthStep,
OwnersStep,
RedirectStep,
@@ -38,6 +39,7 @@ function parseOwnerIds(raw: string) {
function validationKeyForStep(id: SetupStepId): string {
if (id === "oauth") return "oauth";
if (id === "owners") return "owners";
if (id === "database") return "database";
if (id === "emeraldApi") return "emeraldApi";
return id;
}
@@ -50,6 +52,12 @@ export default function Setup() {
const [stepIndex, setStepIndex] = useState(0);
const [values, setValues] = useState<SetupFormValues>({
botToken: "",
dbDriver: "sqlite",
dbHost: "127.0.0.1",
dbPort: "3306",
dbUser: "",
dbPassword: "",
dbDatabase: "supportbot",
secretKey: "",
clientId: "",
clientSecret: "",
@@ -74,6 +82,12 @@ export default function Setup() {
const payload = useMemo(
() => ({
botToken: values.botToken,
dbDriver: values.dbDriver,
dbHost: values.dbHost,
dbPort: values.dbPort,
dbUser: values.dbUser,
dbPassword: values.dbPassword,
dbDatabase: values.dbDatabase,
secretKey: values.secretKey,
clientId: values.clientId,
clientSecret: values.clientSecret,
@@ -149,6 +163,13 @@ export default function Setup() {
onValidate={() => void validateCurrentStep()}
/>
);
case "database":
return (
<DatabaseStep
{...common}
onValidate={() => void validateCurrentStep()}
/>
);
case "secretKey":
return (
<SecretKeyStep
+290 -12
View File
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
RefreshIcon,
Link01Icon,
@@ -14,6 +14,9 @@ import {
Tick01Icon,
Attachment01Icon,
Image01Icon,
Ticket01Icon,
Search01Icon,
FilterIcon,
} from "@hugeicons/core-free-icons";
import { api, GuildResources } from "@/api/client";
import { Icon } from "@/components/icon";
@@ -23,6 +26,14 @@ import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { ScrollArea } from "@/components/ui/scroll-area";
import {
Sheet,
@@ -40,6 +51,7 @@ import {
DialogTitle,
} from "@/components/ui/dialog";
import { Skeleton } from "@/components/ui/skeleton";
import { getByPath } from "@/lib/config-utils";
import { formatUptime } from "@/api/client";
import {
useRealtimeStream,
@@ -124,6 +136,68 @@ export default function Tickets() {
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
// Department system enablement state
const [departmentsEnabled, setDepartmentsEnabled] = useState<boolean>(true);
useEffect(() => {
try {
api.getConfigJson("supportbot")
.then((res) => {
if (res && res.data && typeof res.data === "object") {
const deptVal = getByPath(res.data, "Ticket.DepartmentSystem.Enabled");
if (typeof deptVal === "boolean") {
setDepartmentsEnabled(deptVal);
}
}
})
.catch(() => {});
} catch {
// Fallback silently if config fetch fails
}
}, []);
// Filter state
const [selectedDeptFilter, setSelectedDeptFilter] = useState<string>("all");
const [selectedPriorityFilter, setSelectedPriorityFilter] = useState<string>("all");
const [searchQuery, setSearchQuery] = useState<string>("");
const availableDepartments = useMemo(() => {
const deptsSet = new Set<string>();
if (Array.isArray(list)) {
list.forEach((ticket) => {
if (ticket && ticket.department && typeof ticket.department === "string") {
const d = ticket.department.trim().toLowerCase();
if (d) deptsSet.add(d);
}
});
}
return Array.from(deptsSet).sort();
}, [list]);
const filteredTickets = useMemo(() => {
if (!Array.isArray(list)) return [];
return list.filter((ticket) => {
if (!ticket) return false;
if (departmentsEnabled && selectedDeptFilter !== "all" && ticket.department?.toLowerCase() !== selectedDeptFilter.toLowerCase()) {
return false;
}
if (selectedPriorityFilter !== "all" && ticket.priority?.toLowerCase() !== selectedPriorityFilter.toLowerCase()) {
return false;
}
if (searchQuery.trim()) {
const q = searchQuery.toLowerCase().trim();
const subjectMatch = ticket.subject?.toLowerCase().includes(q);
const idMatch = ticket.ticket_id?.toLowerCase().includes(q);
const userMatch = ticket.user_id?.toLowerCase().includes(q);
const deptMatch = departmentsEnabled && ticket.department?.toLowerCase().includes(q);
if (!subjectMatch && !idMatch && !userMatch && !deptMatch) {
return false;
}
}
return true;
});
}, [list, departmentsEnabled, selectedDeptFilter, selectedPriorityFilter, searchQuery]);
// Live Chat state
const [activeTicket, setActiveTicket] = useState<TicketItem | null>(null);
const [chatOpen, setChatOpen] = useState(false);
@@ -147,6 +221,37 @@ export default function Tickets() {
const [closeReason, setCloseReason] = useState("");
const [closingTicketId, setClosingTicketId] = useState<string | null>(null);
// Create Direct Ticket State
const [createModalOpen, setCreateModalOpen] = useState(false);
const [createDept, setCreateDept] = useState("general");
const [createSubject, setCreateSubject] = useState("");
const [createUserId, setCreateUserId] = useState("");
const [creating, setCreating] = useState(false);
const handleCreateTicket = async () => {
if (!createSubject.trim()) {
toast.error("Please enter a subject or reason for the ticket.");
return;
}
setCreating(true);
try {
const res = await api.createTicket({
department: createDept,
subject: createSubject.trim(),
userId: createUserId.trim() || undefined,
});
toast.success(res.message || "Ticket opened successfully!");
setCreateModalOpen(false);
setCreateSubject("");
setCreateUserId("");
void loadList();
} catch (err) {
toast.error(err instanceof Error ? err.message : "Failed to open ticket.");
} finally {
setCreating(false);
}
};
const promptCloseTicket = (ticket: TicketItem) => {
setTicketToClose(ticket);
setCloseReason("Closed via Web Dashboard");
@@ -1111,10 +1216,87 @@ export default function Tickets() {
Manage open support tickets & reply live to Discord channels from the web dashboard.
</p>
</div>
<Button onClick={() => void loadList()} disabled={loading} variant="outline" size="sm">
<Icon icon={RefreshIcon} size={16} className={loading ? "animate-spin mr-2" : "mr-2"} />
Refresh
</Button>
<div className="flex items-center gap-2">
<Button
onClick={() => setCreateModalOpen(true)}
className="gap-2 bg-primary font-semibold text-xs h-9"
>
<Icon icon={Ticket01Icon} size={15} /> Open Ticket
</Button>
<Button onClick={() => void loadList()} disabled={loading} variant="outline" size="sm">
<Icon icon={RefreshIcon} size={16} className={loading ? "animate-spin mr-2" : "mr-2"} />
Refresh
</Button>
</div>
</div>
{/* FILTER & SEARCH BAR */}
<div className="flex flex-col md:flex-row items-center justify-between gap-3 bg-card/60 p-3.5 rounded-xl border border-border/80 shadow-sm">
<div className="relative w-full md:w-80">
<Icon
icon={Search01Icon}
size={15}
className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"
/>
<Input
placeholder="Search tickets by ID, user, subject..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-9 text-xs h-9 bg-secondary/30 border-border"
/>
</div>
<div className="flex flex-wrap items-center gap-2.5 w-full md:w-auto justify-end">
{departmentsEnabled && (
<div className="flex items-center gap-1.5 shrink-0">
<span className="text-xs font-semibold text-muted-foreground">Department:</span>
<Select value={selectedDeptFilter} onValueChange={setSelectedDeptFilter}>
<SelectTrigger className="text-xs h-9 w-[160px] bg-secondary/30 border-border capitalize">
<SelectValue placeholder="All Departments" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Departments</SelectItem>
{availableDepartments.map((dept) => (
<SelectItem key={dept} value={dept} className="capitalize">
{dept}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
<div className="flex items-center gap-1.5 shrink-0">
<span className="text-xs font-semibold text-muted-foreground">Priority:</span>
<Select value={selectedPriorityFilter} onValueChange={setSelectedPriorityFilter}>
<SelectTrigger className="text-xs h-9 w-[140px] bg-secondary/30 border-border capitalize">
<SelectValue placeholder="All Priorities" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Priorities</SelectItem>
<SelectItem value="low">Low</SelectItem>
<SelectItem value="medium">Medium / Normal</SelectItem>
<SelectItem value="high">High</SelectItem>
<SelectItem value="urgent">Urgent</SelectItem>
</SelectContent>
</Select>
</div>
{(selectedDeptFilter !== "all" || selectedPriorityFilter !== "all" || searchQuery.trim()) && (
<Button
variant="ghost"
size="sm"
onClick={() => {
setSelectedDeptFilter("all");
setSelectedPriorityFilter("all");
setSearchQuery("");
}}
className="h-9 text-xs text-muted-foreground hover:text-foreground px-2"
>
Reset
</Button>
)}
</div>
</div>
<Card className="border-border bg-card">
@@ -1131,13 +1313,27 @@ export default function Tickets() {
<AlertDescription>{error}</AlertDescription>
</Alert>
</div>
) : list.length === 0 ? (
<div className="p-12 text-center text-muted-foreground">
No open tickets at the moment!
) : filteredTickets.length === 0 ? (
<div className="p-12 text-center text-muted-foreground space-y-2">
<p>No open tickets found matching your filter criteria.</p>
{(selectedDeptFilter !== "all" || selectedPriorityFilter !== "all" || searchQuery.trim()) && (
<Button
variant="outline"
size="sm"
onClick={() => {
setSelectedDeptFilter("all");
setSelectedPriorityFilter("all");
setSearchQuery("");
}}
className="text-xs mt-2"
>
Clear Filters
</Button>
)}
</div>
) : (
<div className="divide-y divide-border">
{list.map((ticket) => (
{filteredTickets.map((ticket) => (
<div
key={ticket.ticket_id}
className="flex flex-col sm:flex-row items-start sm:items-center justify-between p-4 hover:bg-secondary/10 transition-colors gap-4"
@@ -1150,9 +1346,11 @@ export default function Tickets() {
<span className="text-xs font-mono text-muted-foreground">
#{ticket.ticket_id}
</span>
<Badge variant="outline" className="text-xs capitalize">
{ticket.department}
</Badge>
{departmentsEnabled && ticket.department && (
<Badge variant="outline" className="text-xs capitalize">
{ticket.department}
</Badge>
)}
<Badge
variant={
ticket.priority === "high"
@@ -1401,6 +1599,86 @@ export default function Tickets() {
</DialogFooter>
</DialogContent>
</Dialog>
{/* Create Ticket Modal */}
<Dialog open={createModalOpen} onOpenChange={setCreateModalOpen}>
<DialogContent className="sm:max-w-[450px]">
<DialogHeader>
<DialogTitle className="text-base flex items-center gap-2">
<Icon icon={Ticket01Icon} size={18} className="text-primary" />
Open Direct Ticket
</DialogTitle>
<DialogDescription className="text-xs">
Select a support department to create a new ticket channel in Discord immediately.
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-2">
<div className="space-y-1.5">
<Label className="text-xs font-semibold">Department</Label>
<Select value={createDept} onValueChange={setCreateDept}>
<SelectTrigger className="text-xs border-border bg-secondary/30">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="general">🎫 General Support</SelectItem>
<SelectItem value="purchase">💳 Purchase & Billing Support</SelectItem>
<SelectItem value="reports">🚨 Player Report</SelectItem>
<SelectItem value="appeals">⚖️ Ban Appeals</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label className="text-xs font-semibold">Ticket Subject / Reason</Label>
<Input
value={createSubject}
onChange={(e) => setCreateSubject(e.target.value)}
placeholder="e.g. Assistance with server permissions"
className="text-xs border-border bg-secondary/30"
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs font-semibold">Discord User ID (Optional)</Label>
<Input
value={createUserId}
onChange={(e) => setCreateUserId(e.target.value)}
placeholder="e.g. 123456789012345678 (Leave blank for yourself)"
className="text-xs font-mono border-border bg-secondary/30"
/>
<p className="text-[11px] text-muted-foreground">
If specified, the ticket channel will be created for this user.
</p>
</div>
</div>
<DialogFooter className="gap-2 sm:gap-0">
<Button
variant="outline"
size="sm"
onClick={() => setCreateModalOpen(false)}
disabled={creating}
className="text-xs"
>
Cancel
</Button>
<Button
size="sm"
onClick={handleCreateTicket}
disabled={creating || !createSubject.trim()}
className="gap-1.5 text-xs bg-primary font-semibold"
>
{creating ? (
<Icon icon={RefreshIcon} size={14} className="animate-spin" />
) : (
<Icon icon={Ticket01Icon} size={14} />
)}
{creating ? "Opening Ticket..." : "Open Ticket"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}
+36 -6
View File
@@ -93,7 +93,7 @@ function PermissionEditor({
const set = (patch: Partial<DashboardPermissions>) =>
onChange({ ...permissions, ...patch });
const PERM_ITEMS: {
const MODULE_ITEMS: {
key: "overview" | "tickets" | "logs" | "transcripts";
title: string;
description: string;
@@ -105,17 +105,17 @@ function PermissionEditor({
},
{
key: "tickets",
title: "Tickets",
title: "Support Tickets",
description: "View open support tickets, live web chat, send staff replies, and close tickets.",
},
{
key: "transcripts",
title: "Transcripts",
title: "Ticket Transcripts",
description: "Access saved ticket HTML transcripts and configure public transcript options.",
},
{
key: "logs",
title: "Console Logs",
title: "Console Terminal Logs",
description: "View real-time bot terminal output, system logs, and runtime error traces.",
},
];
@@ -130,12 +130,13 @@ function PermissionEditor({
return (
<div className="space-y-6">
{/* Category 1: General & Modules */}
<div className="space-y-2.5">
<h4 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
General Capabilities
General & Modules Access
</h4>
<div className="grid gap-2.5">
{PERM_ITEMS.map(({ key, title, description }) => (
{MODULE_ITEMS.map(({ key, title, description }) => (
<label
key={key}
className="flex items-center justify-between gap-4 rounded-xl border border-border bg-secondary/20 p-3 transition-colors hover:bg-secondary/40"
@@ -152,7 +153,15 @@ function PermissionEditor({
/>
</label>
))}
</div>
</div>
{/* Category 2: Administration & System Settings */}
<div className="space-y-2.5">
<h4 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
Administration & Settings
</h4>
<div className="grid gap-2.5">
{/* Settings View */}
<label className="flex items-center justify-between gap-4 rounded-xl border border-border bg-secondary/20 p-3 transition-colors hover:bg-secondary/40">
<div className="space-y-0.5 min-w-0">
@@ -219,6 +228,7 @@ function PermissionEditor({
</div>
</div>
{/* Category 3: Configuration Files Access */}
<div className="space-y-2.5">
<h4 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
Configuration Files Access
@@ -273,6 +283,26 @@ function PermissionEditor({
</div>
);
})}
{/* Raw YAML Code Editor */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 rounded-xl border border-border bg-secondary/20 p-3 transition-colors hover:bg-secondary/40">
<div className="space-y-0.5 min-w-0">
<p className="text-sm font-semibold text-foreground">Raw YAML Code Editor</p>
<p className="text-xs text-muted-foreground leading-snug">
Access the raw YAML code editor tab to view or edit full raw configuration files.
</p>
</div>
<div className="flex items-center gap-4 shrink-0">
<label className="flex items-center gap-2 text-xs font-medium text-muted-foreground cursor-pointer">
<span>Access</span>
<Switch
checked={permissions.rawYaml ?? false}
disabled={disabled}
onCheckedChange={(rawYaml) => set({ rawYaml })}
/>
</label>
</div>
</div>
</div>
</div>
</div>