Redesign: Linear-inspired dark mode frontend

Complete rewrite of all pages:
- layout.tsx: App shell with 240px sidebar (saved views, queue list, admin link)
- app-shell.tsx: Client sidebar component with route highlighting + counts
- page.tsx: Sleek ticket list with filter chips (All/Open/In progress/Resolved), search bar, status dots, assignee avatars, skeleton loading
- tickets/[id]/page.tsx: Two-panel conversation layout — message thread (left) + properties sidebar (right) with status change, scrip preview, reply box
- admin/page.tsx: Suspense-wrapped admin with tabs in sheet panels
- command-palette.tsx: Cmd+K search with keyboard navigation

Design tokens from Linear:
- bg-[#08090a] canvas, bg-[#0f1011] panels, bg-[#191a1b] cards
- text-[#f7f8f8] primary, text-[#d0d6e0] secondary, text-[#8a8f98] tertiary
- borders: rgba(255,255,255,0.08) standard, rgba(255,255,255,0.05) subtle
- accent: #5e6ad2 primary, #7170ff interactive
- status colors: new=gray, open=indigo, in_progress=amber, resolved=green
- Inter font, weights 400/510/590, no pure white

Fixed: Suspense boundaries for useSearchParams in layout and admin pages
Build: passes with zero errors
This commit is contained in:
Gjermund Høsøien Wiggen
2026-06-07 22:16:18 +02:00
parent df677cb37f
commit 77860eb6c4
7 changed files with 2118 additions and 1256 deletions

View File

@@ -0,0 +1,745 @@
"use client";
import { useEffect, useState, useCallback } from "react";
import { Plus, RefreshCw } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import {
Table,
TableHeader,
TableBody,
TableRow,
TableHead,
TableCell,
} from "@/components/ui/table";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
Tabs,
TabsList,
TabsTrigger,
TabsContent,
} from "@/components/ui/tabs";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from "@/components/ui/dialog";
import {
getQueues,
createQueue,
getLifecycles,
createLifecycle,
getScrips,
createScrip,
getCustomFields,
createCustomField,
} from "@/lib/api";
import type { Queue, Lifecycle, Scrip, CustomField } from "@/lib/types";
const LIFECYCLE_PLACEHOLDER = `{
"statuses": {
"initial": ["new"],
"active": ["open", "in_progress"],
"inactive": ["resolved", "closed"]
},
"transitions": {
"new": ["open"],
"open": ["in_progress", "resolved"],
"in_progress": ["resolved"],
"*": ["closed"]
}
}`;
export default function AdminPage() {
return (
<div className="flex flex-col gap-6">
<h1 className="text-2xl font-semibold tracking-tight">Admin</h1>
<Tabs defaultValue="queues">
<TabsList>
<TabsTrigger value="queues">Queues</TabsTrigger>
<TabsTrigger value="lifecycles">Lifecycles</TabsTrigger>
<TabsTrigger value="scrips">Scrips</TabsTrigger>
<TabsTrigger value="customfields">Custom Fields</TabsTrigger>
</TabsList>
<TabsContent value="queues">
<QueuesTab />
</TabsContent>
<TabsContent value="lifecycles">
<LifecyclesTab />
</TabsContent>
<TabsContent value="scrips">
<ScripsTab />
</TabsContent>
<TabsContent value="customfields">
<CustomFieldsTab />
</TabsContent>
</Tabs>
</div>
);
}
function QueuesTab() {
const [queues, setQueues] = useState<Queue[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [dialogOpen, setDialogOpen] = useState(false);
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const [saving, setSaving] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);
const fetchQueues = useCallback(async () => {
setLoading(true);
setError(null);
const { data, error } = await getQueues();
if (error) setError(error);
else setQueues(data ?? []);
setLoading(false);
}, []);
useEffect(() => {
fetchQueues();
}, [fetchQueues]);
const handleCreate = async () => {
if (!name.trim()) return;
setSaving(true);
setSaveError(null);
const { error } = await createQueue({ name: name.trim(), description: description.trim() || undefined });
setSaving(false);
if (error) {
setSaveError(error);
} else {
setDialogOpen(false);
setName("");
setDescription("");
fetchQueues();
}
};
return (
<div className="flex flex-col gap-4 pt-4">
<div className="flex items-center justify-between">
<h2 className="text-lg font-medium">Queues</h2>
<Button size="sm" onClick={() => setDialogOpen(true)}>
<Plus className="size-4" />
Add Queue
</Button>
</div>
{error && <div className="text-sm text-red-400">{error}</div>}
{loading ? (
<div className="text-sm text-neutral-400 py-6">Loading...</div>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>Name</TableHead>
<TableHead>Description</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{queues.length === 0 ? (
<TableRow>
<TableCell colSpan={2} className="text-neutral-400 text-center py-6">
No queues yet.
</TableCell>
</TableRow>
) : (
queues.map((q) => (
<TableRow key={q.id}>
<TableCell className="font-medium">{q.name}</TableCell>
<TableCell className="text-neutral-400">{q.description ?? "-"}</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
)}
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Add Queue</DialogTitle>
<DialogDescription>Create a new ticket queue.</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-2">
<Label htmlFor="q-name">Name</Label>
<Input
id="q-name"
placeholder="Queue name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="q-desc">Description</Label>
<Textarea
id="q-desc"
placeholder="Optional description"
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
</div>
{saveError && <div className="text-sm text-red-400">{saveError}</div>}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setDialogOpen(false)}>
Cancel
</Button>
<Button onClick={handleCreate} disabled={!name.trim() || saving}>
{saving ? "Saving..." : "Create"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}
function LifecyclesTab() {
const [lifecycles, setLifecycles] = useState<Lifecycle[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [dialogOpen, setDialogOpen] = useState(false);
const [name, setName] = useState("");
const [definition, setDefinition] = useState("");
const [saving, setSaving] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);
const fetchLifecycles = useCallback(async () => {
setLoading(true);
setError(null);
const { data, error } = await getLifecycles();
if (error) setError(error);
else setLifecycles(data ?? []);
setLoading(false);
}, []);
useEffect(() => {
fetchLifecycles();
}, [fetchLifecycles]);
const handleCreate = async () => {
if (!name.trim() || !definition.trim()) return;
let parsed: Record<string, unknown>;
try {
parsed = JSON.parse(definition);
} catch {
setSaveError("Invalid JSON definition.");
return;
}
setSaving(true);
setSaveError(null);
const { error } = await createLifecycle({ name: name.trim(), definition: parsed });
setSaving(false);
if (error) {
setSaveError(error);
} else {
setDialogOpen(false);
setName("");
setDefinition("");
fetchLifecycles();
}
};
return (
<div className="flex flex-col gap-4 pt-4">
<div className="flex items-center justify-between">
<h2 className="text-lg font-medium">Lifecycles</h2>
<Button size="sm" onClick={() => setDialogOpen(true)}>
<Plus className="size-4" />
Add Lifecycle
</Button>
</div>
{error && <div className="text-sm text-red-400">{error}</div>}
{loading ? (
<div className="text-sm text-neutral-400 py-6">Loading...</div>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>Name</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{lifecycles.length === 0 ? (
<TableRow>
<TableCell className="text-neutral-400 text-center py-6">
No lifecycles yet.
</TableCell>
</TableRow>
) : (
lifecycles.map((l) => (
<TableRow key={l.id}>
<TableCell className="font-medium">{l.name}</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
)}
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Add Lifecycle</DialogTitle>
<DialogDescription>Create a new lifecycle with a JSON definition.</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-2">
<Label htmlFor="lc-name">Name</Label>
<Input
id="lc-name"
placeholder="Lifecycle name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="lc-def">Definition (JSON)</Label>
<Textarea
id="lc-def"
placeholder={LIFECYCLE_PLACEHOLDER}
value={definition}
onChange={(e) => setDefinition(e.target.value)}
className="min-h-40 font-mono text-xs"
/>
</div>
{saveError && <div className="text-sm text-red-400">{saveError}</div>}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setDialogOpen(false)}>
Cancel
</Button>
<Button onClick={handleCreate} disabled={!name.trim() || !definition.trim() || saving}>
{saving ? "Saving..." : "Create"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}
function ScripsTab() {
const [scrips, setScrips] = useState<Scrip[]>([]);
const [queues, setQueues] = useState<Queue[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [dialogOpen, setDialogOpen] = useState(false);
const [name, setName] = useState("");
const [queueId, setQueueId] = useState("");
const [conditionType, setConditionType] = useState("OnCreate");
const [actionType, setActionType] = useState("SendEmail");
const [actionConfig, setActionConfig] = useState("");
const [stage, setStage] = useState("TransactionCreate");
const [sortOrder, setSortOrder] = useState(0);
const [disabled, setDisabled] = useState(false);
const [saving, setSaving] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);
const fetchScrips = useCallback(async () => {
setLoading(true);
setError(null);
const [sRes, qRes] = await Promise.all([getScrips(), getQueues()]);
if (sRes.error) setError(sRes.error);
else setScrips(sRes.data ?? []);
if (qRes.error) setError(qRes.error);
else setQueues(qRes.data ?? []);
setLoading(false);
}, []);
useEffect(() => {
fetchScrips();
}, [fetchScrips]);
const handleCreate = async () => {
if (!name.trim()) return;
let parsedConfig: Record<string, unknown> | undefined;
if (actionConfig.trim()) {
try {
parsedConfig = JSON.parse(actionConfig);
} catch {
setSaveError("Invalid JSON in action config.");
return;
}
}
setSaving(true);
setSaveError(null);
const { error } = await createScrip({
name: name.trim(),
queue_id: queueId || null,
condition_type: conditionType,
action_type: actionType,
action_config: parsedConfig,
stage,
sort_order: sortOrder,
disabled,
});
setSaving(false);
if (error) {
setSaveError(error);
} else {
setDialogOpen(false);
setName("");
setQueueId("");
setConditionType("OnCreate");
setActionType("SendEmail");
setActionConfig("");
setStage("TransactionCreate");
setSortOrder(0);
setDisabled(false);
fetchScrips();
}
};
const queueName = (id: string | null) => {
if (!id) return "Global";
return queues.find((q) => q.id === id)?.name ?? id;
};
return (
<div className="flex flex-col gap-4 pt-4">
<div className="flex items-center justify-between">
<h2 className="text-lg font-medium">Scrips</h2>
<Button size="sm" onClick={() => setDialogOpen(true)}>
<Plus className="size-4" />
Add Scrip
</Button>
</div>
{error && <div className="text-sm text-red-400">{error}</div>}
{loading ? (
<div className="text-sm text-neutral-400 py-6">Loading...</div>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>Name</TableHead>
<TableHead>Queue</TableHead>
<TableHead>Condition</TableHead>
<TableHead>Action</TableHead>
<TableHead>Enabled</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{scrips.length === 0 ? (
<TableRow>
<TableCell colSpan={5} className="text-neutral-400 text-center py-6">
No scrips yet.
</TableCell>
</TableRow>
) : (
scrips.map((s) => (
<TableRow key={s.id}>
<TableCell className="font-medium">{s.name}</TableCell>
<TableCell>{queueName(s.queue_id)}</TableCell>
<TableCell>{s.condition_type}</TableCell>
<TableCell>{s.action_type}</TableCell>
<TableCell>
<Badge variant={s.disabled ? "outline" : "default"}>
{s.disabled ? "Disabled" : "Enabled"}
</Badge>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
)}
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Add Scrip</DialogTitle>
<DialogDescription>Create a new automation scrip.</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-3">
<div className="flex flex-col gap-1.5">
<Label htmlFor="s-name">Name</Label>
<Input
id="s-name"
placeholder="Scrip name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="s-queue">Queue</Label>
<Select value={queueId} onValueChange={(v) => setQueueId(v === "_global" || !v ? "" : v)}>
<SelectTrigger id="s-queue">
<SelectValue placeholder="Global" />
</SelectTrigger>
<SelectContent>
<SelectItem value="_global">Global</SelectItem>
{queues.map((q) => (
<SelectItem key={q.id} value={q.id}>
{q.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="s-cond">Condition Type</Label>
<Select value={conditionType} onValueChange={(v) => setConditionType(v ?? "OnCreate")}>
<SelectTrigger id="s-cond">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="OnCreate">OnCreate</SelectItem>
<SelectItem value="OnStatusChange">OnStatusChange</SelectItem>
<SelectItem value="OnResolve">OnResolve</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="s-action">Action Type</Label>
<Select value={actionType} onValueChange={(v) => setActionType(v ?? "SendEmail")}>
<SelectTrigger id="s-action">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="SendEmail">SendEmail</SelectItem>
<SelectItem value="Webhook">Webhook</SelectItem>
<SelectItem value="SetCustomField">SetCustomField</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="s-config">Action Config (JSON)</Label>
<Textarea
id="s-config"
placeholder='{"key": "value"}'
value={actionConfig}
onChange={(e) => setActionConfig(e.target.value)}
className="min-h-20 font-mono text-xs"
/>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="s-stage">Stage</Label>
<Select value={stage} onValueChange={(v) => setStage(v ?? "TransactionCreate")}>
<SelectTrigger id="s-stage">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="TransactionCreate">TransactionCreate</SelectItem>
<SelectItem value="TransactionBatch">TransactionBatch</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="s-order">Sort Order</Label>
<Input
id="s-order"
type="number"
value={sortOrder}
onChange={(e) => setSortOrder(Number(e.target.value))}
/>
</div>
<div className="flex items-center gap-2">
<input
id="s-disabled"
type="checkbox"
checked={disabled}
onChange={(e) => setDisabled(e.target.checked)}
className="size-4 rounded border-neutral-700 bg-neutral-800 accent-primary"
/>
<Label htmlFor="s-disabled" className="cursor-pointer">
Disabled
</Label>
</div>
{saveError && <div className="text-sm text-red-400">{saveError}</div>}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setDialogOpen(false)}>
Cancel
</Button>
<Button onClick={handleCreate} disabled={!name.trim() || saving}>
{saving ? "Saving..." : "Create"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}
function CustomFieldsTab() {
const [fields, setFields] = useState<CustomField[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [dialogOpen, setDialogOpen] = useState(false);
const [name, setName] = useState("");
const [fieldType, setFieldType] = useState("Freeform");
const [values, setValues] = useState("");
const [maxValues, setMaxValues] = useState(0);
const [saving, setSaving] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);
const fetchFields = useCallback(async () => {
setLoading(true);
setError(null);
const { data, error } = await getCustomFields();
if (error) setError(error);
else setFields(data ?? []);
setLoading(false);
}, []);
useEffect(() => {
fetchFields();
}, [fetchFields]);
const handleCreate = async () => {
if (!name.trim()) return;
let parsedValues: unknown = null;
if (values.trim()) {
try {
parsedValues = JSON.parse(values);
} catch {
setSaveError("Invalid JSON in values.");
return;
}
}
setSaving(true);
setSaveError(null);
const { error } = await createCustomField({
name: name.trim(),
field_type: fieldType,
values: parsedValues,
max_values: maxValues,
});
setSaving(false);
if (error) {
setSaveError(error);
} else {
setDialogOpen(false);
setName("");
setFieldType("Freeform");
setValues("");
setMaxValues(0);
fetchFields();
}
};
return (
<div className="flex flex-col gap-4 pt-4">
<div className="flex items-center justify-between">
<h2 className="text-lg font-medium">Custom Fields</h2>
<Button size="sm" onClick={() => setDialogOpen(true)}>
<Plus className="size-4" />
Add Custom Field
</Button>
</div>
{error && <div className="text-sm text-red-400">{error}</div>}
{loading ? (
<div className="text-sm text-neutral-400 py-6">Loading...</div>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>Name</TableHead>
<TableHead>Type</TableHead>
<TableHead>Max Values</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{fields.length === 0 ? (
<TableRow>
<TableCell colSpan={3} className="text-neutral-400 text-center py-6">
No custom fields yet.
</TableCell>
</TableRow>
) : (
fields.map((f) => (
<TableRow key={f.id}>
<TableCell className="font-medium">{f.name}</TableCell>
<TableCell>{f.field_type}</TableCell>
<TableCell>{f.max_values === 0 ? "Unlimited" : f.max_values}</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
)}
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Add Custom Field</DialogTitle>
<DialogDescription>Create a new custom field definition.</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-3">
<div className="flex flex-col gap-1.5">
<Label htmlFor="cf-name">Name</Label>
<Input
id="cf-name"
placeholder="Field name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="cf-type">Field Type</Label>
<Select value={fieldType} onValueChange={(v) => setFieldType(v ?? "Freeform")}>
<SelectTrigger id="cf-type">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="Freeform">Freeform</SelectItem>
<SelectItem value="SelectSingle">SelectSingle</SelectItem>
<SelectItem value="SelectMulti">SelectMulti</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="cf-values">Values (JSON array, for select types)</Label>
<Textarea
id="cf-values"
placeholder='["Option A", "Option B"]'
value={values}
onChange={(e) => setValues(e.target.value)}
className="min-h-20 font-mono text-xs"
/>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="cf-max">Max Values (0 = unlimited)</Label>
<Input
id="cf-max"
type="number"
min={0}
value={maxValues}
onChange={(e) => setMaxValues(Number(e.target.value))}
/>
</div>
{saveError && <div className="text-sm text-red-400">{saveError}</div>}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setDialogOpen(false)}>
Cancel
</Button>
<Button onClick={handleCreate} disabled={!name.trim() || saving}>
{saving ? "Saving..." : "Create"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}

View File

@@ -1,745 +1,10 @@
"use client"; import { Suspense } from "react";
import AdminPage from "./page-content";
import { useEffect, useState, useCallback } from "react"; export default function AdminPageWrapper() {
import { Plus, RefreshCw } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import {
Table,
TableHeader,
TableBody,
TableRow,
TableHead,
TableCell,
} from "@/components/ui/table";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
Tabs,
TabsList,
TabsTrigger,
TabsContent,
} from "@/components/ui/tabs";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from "@/components/ui/dialog";
import {
getQueues,
createQueue,
getLifecycles,
createLifecycle,
getScrips,
createScrip,
getCustomFields,
createCustomField,
} from "@/lib/api";
import type { Queue, Lifecycle, Scrip, CustomField } from "@/lib/types";
const LIFECYCLE_PLACEHOLDER = `{
"statuses": {
"initial": ["new"],
"active": ["open", "in_progress"],
"inactive": ["resolved", "closed"]
},
"transitions": {
"new": ["open"],
"open": ["in_progress", "resolved"],
"in_progress": ["resolved"],
"*": ["closed"]
}
}`;
export default function AdminPage() {
return ( return (
<div className="flex flex-col gap-6"> <Suspense fallback={<div className="text-[#8a8f98] p-6">Loading admin...</div>}>
<h1 className="text-2xl font-semibold tracking-tight">Admin</h1> <AdminPage />
<Tabs defaultValue="queues"> </Suspense>
<TabsList>
<TabsTrigger value="queues">Queues</TabsTrigger>
<TabsTrigger value="lifecycles">Lifecycles</TabsTrigger>
<TabsTrigger value="scrips">Scrips</TabsTrigger>
<TabsTrigger value="customfields">Custom Fields</TabsTrigger>
</TabsList>
<TabsContent value="queues">
<QueuesTab />
</TabsContent>
<TabsContent value="lifecycles">
<LifecyclesTab />
</TabsContent>
<TabsContent value="scrips">
<ScripsTab />
</TabsContent>
<TabsContent value="customfields">
<CustomFieldsTab />
</TabsContent>
</Tabs>
</div>
);
}
function QueuesTab() {
const [queues, setQueues] = useState<Queue[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [dialogOpen, setDialogOpen] = useState(false);
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const [saving, setSaving] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);
const fetchQueues = useCallback(async () => {
setLoading(true);
setError(null);
const { data, error } = await getQueues();
if (error) setError(error);
else setQueues(data ?? []);
setLoading(false);
}, []);
useEffect(() => {
fetchQueues();
}, [fetchQueues]);
const handleCreate = async () => {
if (!name.trim()) return;
setSaving(true);
setSaveError(null);
const { error } = await createQueue({ name: name.trim(), description: description.trim() || undefined });
setSaving(false);
if (error) {
setSaveError(error);
} else {
setDialogOpen(false);
setName("");
setDescription("");
fetchQueues();
}
};
return (
<div className="flex flex-col gap-4 pt-4">
<div className="flex items-center justify-between">
<h2 className="text-lg font-medium">Queues</h2>
<Button size="sm" onClick={() => setDialogOpen(true)}>
<Plus className="size-4" />
Add Queue
</Button>
</div>
{error && <div className="text-sm text-red-400">{error}</div>}
{loading ? (
<div className="text-sm text-neutral-400 py-6">Loading...</div>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>Name</TableHead>
<TableHead>Description</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{queues.length === 0 ? (
<TableRow>
<TableCell colSpan={2} className="text-neutral-400 text-center py-6">
No queues yet.
</TableCell>
</TableRow>
) : (
queues.map((q) => (
<TableRow key={q.id}>
<TableCell className="font-medium">{q.name}</TableCell>
<TableCell className="text-neutral-400">{q.description ?? "-"}</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
)}
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Add Queue</DialogTitle>
<DialogDescription>Create a new ticket queue.</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-2">
<Label htmlFor="q-name">Name</Label>
<Input
id="q-name"
placeholder="Queue name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="q-desc">Description</Label>
<Textarea
id="q-desc"
placeholder="Optional description"
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
</div>
{saveError && <div className="text-sm text-red-400">{saveError}</div>}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setDialogOpen(false)}>
Cancel
</Button>
<Button onClick={handleCreate} disabled={!name.trim() || saving}>
{saving ? "Saving..." : "Create"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}
function LifecyclesTab() {
const [lifecycles, setLifecycles] = useState<Lifecycle[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [dialogOpen, setDialogOpen] = useState(false);
const [name, setName] = useState("");
const [definition, setDefinition] = useState("");
const [saving, setSaving] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);
const fetchLifecycles = useCallback(async () => {
setLoading(true);
setError(null);
const { data, error } = await getLifecycles();
if (error) setError(error);
else setLifecycles(data ?? []);
setLoading(false);
}, []);
useEffect(() => {
fetchLifecycles();
}, [fetchLifecycles]);
const handleCreate = async () => {
if (!name.trim() || !definition.trim()) return;
let parsed: Record<string, unknown>;
try {
parsed = JSON.parse(definition);
} catch {
setSaveError("Invalid JSON definition.");
return;
}
setSaving(true);
setSaveError(null);
const { error } = await createLifecycle({ name: name.trim(), definition: parsed });
setSaving(false);
if (error) {
setSaveError(error);
} else {
setDialogOpen(false);
setName("");
setDefinition("");
fetchLifecycles();
}
};
return (
<div className="flex flex-col gap-4 pt-4">
<div className="flex items-center justify-between">
<h2 className="text-lg font-medium">Lifecycles</h2>
<Button size="sm" onClick={() => setDialogOpen(true)}>
<Plus className="size-4" />
Add Lifecycle
</Button>
</div>
{error && <div className="text-sm text-red-400">{error}</div>}
{loading ? (
<div className="text-sm text-neutral-400 py-6">Loading...</div>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>Name</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{lifecycles.length === 0 ? (
<TableRow>
<TableCell className="text-neutral-400 text-center py-6">
No lifecycles yet.
</TableCell>
</TableRow>
) : (
lifecycles.map((l) => (
<TableRow key={l.id}>
<TableCell className="font-medium">{l.name}</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
)}
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Add Lifecycle</DialogTitle>
<DialogDescription>Create a new lifecycle with a JSON definition.</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-2">
<Label htmlFor="lc-name">Name</Label>
<Input
id="lc-name"
placeholder="Lifecycle name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="lc-def">Definition (JSON)</Label>
<Textarea
id="lc-def"
placeholder={LIFECYCLE_PLACEHOLDER}
value={definition}
onChange={(e) => setDefinition(e.target.value)}
className="min-h-40 font-mono text-xs"
/>
</div>
{saveError && <div className="text-sm text-red-400">{saveError}</div>}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setDialogOpen(false)}>
Cancel
</Button>
<Button onClick={handleCreate} disabled={!name.trim() || !definition.trim() || saving}>
{saving ? "Saving..." : "Create"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}
function ScripsTab() {
const [scrips, setScrips] = useState<Scrip[]>([]);
const [queues, setQueues] = useState<Queue[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [dialogOpen, setDialogOpen] = useState(false);
const [name, setName] = useState("");
const [queueId, setQueueId] = useState("");
const [conditionType, setConditionType] = useState("OnCreate");
const [actionType, setActionType] = useState("SendEmail");
const [actionConfig, setActionConfig] = useState("");
const [stage, setStage] = useState("TransactionCreate");
const [sortOrder, setSortOrder] = useState(0);
const [disabled, setDisabled] = useState(false);
const [saving, setSaving] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);
const fetchScrips = useCallback(async () => {
setLoading(true);
setError(null);
const [sRes, qRes] = await Promise.all([getScrips(), getQueues()]);
if (sRes.error) setError(sRes.error);
else setScrips(sRes.data ?? []);
if (qRes.error) setError(qRes.error);
else setQueues(qRes.data ?? []);
setLoading(false);
}, []);
useEffect(() => {
fetchScrips();
}, [fetchScrips]);
const handleCreate = async () => {
if (!name.trim()) return;
let parsedConfig: Record<string, unknown> | undefined;
if (actionConfig.trim()) {
try {
parsedConfig = JSON.parse(actionConfig);
} catch {
setSaveError("Invalid JSON in action config.");
return;
}
}
setSaving(true);
setSaveError(null);
const { error } = await createScrip({
name: name.trim(),
queue_id: queueId || null,
condition_type: conditionType,
action_type: actionType,
action_config: parsedConfig,
stage,
sort_order: sortOrder,
disabled,
});
setSaving(false);
if (error) {
setSaveError(error);
} else {
setDialogOpen(false);
setName("");
setQueueId("");
setConditionType("OnCreate");
setActionType("SendEmail");
setActionConfig("");
setStage("TransactionCreate");
setSortOrder(0);
setDisabled(false);
fetchScrips();
}
};
const queueName = (id: string | null) => {
if (!id) return "Global";
return queues.find((q) => q.id === id)?.name ?? id;
};
return (
<div className="flex flex-col gap-4 pt-4">
<div className="flex items-center justify-between">
<h2 className="text-lg font-medium">Scrips</h2>
<Button size="sm" onClick={() => setDialogOpen(true)}>
<Plus className="size-4" />
Add Scrip
</Button>
</div>
{error && <div className="text-sm text-red-400">{error}</div>}
{loading ? (
<div className="text-sm text-neutral-400 py-6">Loading...</div>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>Name</TableHead>
<TableHead>Queue</TableHead>
<TableHead>Condition</TableHead>
<TableHead>Action</TableHead>
<TableHead>Enabled</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{scrips.length === 0 ? (
<TableRow>
<TableCell colSpan={5} className="text-neutral-400 text-center py-6">
No scrips yet.
</TableCell>
</TableRow>
) : (
scrips.map((s) => (
<TableRow key={s.id}>
<TableCell className="font-medium">{s.name}</TableCell>
<TableCell>{queueName(s.queue_id)}</TableCell>
<TableCell>{s.condition_type}</TableCell>
<TableCell>{s.action_type}</TableCell>
<TableCell>
<Badge variant={s.disabled ? "outline" : "default"}>
{s.disabled ? "Disabled" : "Enabled"}
</Badge>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
)}
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Add Scrip</DialogTitle>
<DialogDescription>Create a new automation scrip.</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-3">
<div className="flex flex-col gap-1.5">
<Label htmlFor="s-name">Name</Label>
<Input
id="s-name"
placeholder="Scrip name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="s-queue">Queue</Label>
<Select value={queueId} onValueChange={(v) => setQueueId(v === "_global" || !v ? "" : v)}>
<SelectTrigger id="s-queue">
<SelectValue placeholder="Global" />
</SelectTrigger>
<SelectContent>
<SelectItem value="_global">Global</SelectItem>
{queues.map((q) => (
<SelectItem key={q.id} value={q.id}>
{q.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="s-cond">Condition Type</Label>
<Select value={conditionType} onValueChange={(v) => setConditionType(v ?? "OnCreate")}>
<SelectTrigger id="s-cond">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="OnCreate">OnCreate</SelectItem>
<SelectItem value="OnStatusChange">OnStatusChange</SelectItem>
<SelectItem value="OnResolve">OnResolve</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="s-action">Action Type</Label>
<Select value={actionType} onValueChange={(v) => setActionType(v ?? "SendEmail")}>
<SelectTrigger id="s-action">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="SendEmail">SendEmail</SelectItem>
<SelectItem value="Webhook">Webhook</SelectItem>
<SelectItem value="SetCustomField">SetCustomField</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="s-config">Action Config (JSON)</Label>
<Textarea
id="s-config"
placeholder='{"key": "value"}'
value={actionConfig}
onChange={(e) => setActionConfig(e.target.value)}
className="min-h-20 font-mono text-xs"
/>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="s-stage">Stage</Label>
<Select value={stage} onValueChange={(v) => setStage(v ?? "TransactionCreate")}>
<SelectTrigger id="s-stage">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="TransactionCreate">TransactionCreate</SelectItem>
<SelectItem value="TransactionBatch">TransactionBatch</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="s-order">Sort Order</Label>
<Input
id="s-order"
type="number"
value={sortOrder}
onChange={(e) => setSortOrder(Number(e.target.value))}
/>
</div>
<div className="flex items-center gap-2">
<input
id="s-disabled"
type="checkbox"
checked={disabled}
onChange={(e) => setDisabled(e.target.checked)}
className="size-4 rounded border-neutral-700 bg-neutral-800 accent-primary"
/>
<Label htmlFor="s-disabled" className="cursor-pointer">
Disabled
</Label>
</div>
{saveError && <div className="text-sm text-red-400">{saveError}</div>}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setDialogOpen(false)}>
Cancel
</Button>
<Button onClick={handleCreate} disabled={!name.trim() || saving}>
{saving ? "Saving..." : "Create"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}
function CustomFieldsTab() {
const [fields, setFields] = useState<CustomField[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [dialogOpen, setDialogOpen] = useState(false);
const [name, setName] = useState("");
const [fieldType, setFieldType] = useState("Freeform");
const [values, setValues] = useState("");
const [maxValues, setMaxValues] = useState(0);
const [saving, setSaving] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);
const fetchFields = useCallback(async () => {
setLoading(true);
setError(null);
const { data, error } = await getCustomFields();
if (error) setError(error);
else setFields(data ?? []);
setLoading(false);
}, []);
useEffect(() => {
fetchFields();
}, [fetchFields]);
const handleCreate = async () => {
if (!name.trim()) return;
let parsedValues: unknown = null;
if (values.trim()) {
try {
parsedValues = JSON.parse(values);
} catch {
setSaveError("Invalid JSON in values.");
return;
}
}
setSaving(true);
setSaveError(null);
const { error } = await createCustomField({
name: name.trim(),
field_type: fieldType,
values: parsedValues,
max_values: maxValues,
});
setSaving(false);
if (error) {
setSaveError(error);
} else {
setDialogOpen(false);
setName("");
setFieldType("Freeform");
setValues("");
setMaxValues(0);
fetchFields();
}
};
return (
<div className="flex flex-col gap-4 pt-4">
<div className="flex items-center justify-between">
<h2 className="text-lg font-medium">Custom Fields</h2>
<Button size="sm" onClick={() => setDialogOpen(true)}>
<Plus className="size-4" />
Add Custom Field
</Button>
</div>
{error && <div className="text-sm text-red-400">{error}</div>}
{loading ? (
<div className="text-sm text-neutral-400 py-6">Loading...</div>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>Name</TableHead>
<TableHead>Type</TableHead>
<TableHead>Max Values</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{fields.length === 0 ? (
<TableRow>
<TableCell colSpan={3} className="text-neutral-400 text-center py-6">
No custom fields yet.
</TableCell>
</TableRow>
) : (
fields.map((f) => (
<TableRow key={f.id}>
<TableCell className="font-medium">{f.name}</TableCell>
<TableCell>{f.field_type}</TableCell>
<TableCell>{f.max_values === 0 ? "Unlimited" : f.max_values}</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
)}
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Add Custom Field</DialogTitle>
<DialogDescription>Create a new custom field definition.</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-3">
<div className="flex flex-col gap-1.5">
<Label htmlFor="cf-name">Name</Label>
<Input
id="cf-name"
placeholder="Field name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="cf-type">Field Type</Label>
<Select value={fieldType} onValueChange={(v) => setFieldType(v ?? "Freeform")}>
<SelectTrigger id="cf-type">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="Freeform">Freeform</SelectItem>
<SelectItem value="SelectSingle">SelectSingle</SelectItem>
<SelectItem value="SelectMulti">SelectMulti</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="cf-values">Values (JSON array, for select types)</Label>
<Textarea
id="cf-values"
placeholder='["Option A", "Option B"]'
value={values}
onChange={(e) => setValues(e.target.value)}
className="min-h-20 font-mono text-xs"
/>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="cf-max">Max Values (0 = unlimited)</Label>
<Input
id="cf-max"
type="number"
min={0}
value={maxValues}
onChange={(e) => setMaxValues(Number(e.target.value))}
/>
</div>
{saveError && <div className="text-sm text-red-400">{saveError}</div>}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setDialogOpen(false)}>
Cancel
</Button>
<Button onClick={handleCreate} disabled={!name.trim() || saving}>
{saving ? "Saving..." : "Create"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
); );
} }

View File

@@ -1,49 +1,30 @@
"use client";
import type { Metadata } from "next"; import type { Metadata } from "next";
import { Inter } from "next/font/google"; import { Inter } from "next/font/google";
import Link from "next/link"; import { Suspense } from "react";
import { usePathname } from "next/navigation";
import "./globals.css"; import "./globals.css";
import { AppShell } from "@/components/app-shell";
const inter = Inter({ const inter = Inter({
subsets: ["latin"], subsets: ["latin"],
variable: "--font-inter", variable: "--font-inter",
}); });
function NavLink({ href, children }: { href: string; children: React.ReactNode }) { export const metadata: Metadata = {
const pathname = usePathname(); title: "Tessera",
const isActive = pathname === href || (href !== "/" && pathname.startsWith(href)); description: "Ticket management system",
return ( };
<Link
href={href}
className={`text-sm font-medium transition-colors ${
isActive ? "text-white" : "text-neutral-400 hover:text-neutral-200"
}`}
>
{children}
</Link>
);
}
export default function RootLayout({ export default function RootLayout({
children, children,
}: Readonly<{ }: Readonly<{ children: React.ReactNode }>) {
children: React.ReactNode;
}>) {
return ( return (
<html lang="en" className={`dark ${inter.variable} h-full antialiased`}> <html lang="en" className="dark">
<body className="min-h-full flex flex-col bg-neutral-950 text-neutral-100"> <body
<nav className="sticky top-0 z-40 h-14 bg-neutral-900/80 backdrop-blur-md border-b border-neutral-800 px-6 flex items-center justify-between"> className={`${inter.variable} font-sans antialiased bg-[#08090a] text-[#f7f8f8]`}
<Link href="/" className="font-bold text-lg text-white"> >
Tessera <Suspense fallback={<div className="flex items-center justify-center h-screen text-[#8a8f98]">Loading...</div>}>
</Link> <AppShell>{children}</AppShell>
<div className="flex items-center gap-6"> </Suspense>
<NavLink href="/">Tickets</NavLink>
<NavLink href="/admin">Admin</NavLink>
</div>
</nav>
<main className="container mx-auto px-6 py-8 flex-1">{children}</main>
</body> </body>
</html> </html>
); );

View File

@@ -1,27 +1,13 @@
"use client"; "use client";
import { useEffect, useState, useCallback } from "react"; import { useState, useEffect, useCallback } from "react";
import { useRouter } from "next/navigation"; import { useRouter, useSearchParams } from "next/navigation";
import { Plus, Filter } from "lucide-react"; import { PlusIcon, SearchIcon } from "lucide-react";
import { formatDistanceToNow } from "date-fns";
import { getTickets, getQueues, createTicket } from "@/lib/api";
import type { Ticket, Queue } from "@/lib/types";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import {
Table,
TableHeader,
TableBody,
TableRow,
TableHead,
TableCell,
} from "@/components/ui/table";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { import {
Dialog, Dialog,
DialogContent, DialogContent,
@@ -30,234 +16,389 @@ import {
DialogDescription, DialogDescription,
DialogFooter, DialogFooter,
} from "@/components/ui/dialog"; } from "@/components/ui/dialog";
import { getTickets, getQueues, createTicket } from "@/lib/api"; import {
import type { Ticket, Queue } from "@/lib/types"; Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { cn } from "@/lib/utils";
const STATUS_COLORS: Record<string, string> = { const STATUS_COLORS: Record<string, string> = {
new: "bg-blue-500/10 text-blue-400 border-blue-500/30", new: "#8a8f98",
open: "bg-sky-500/10 text-sky-400 border-sky-500/30", open: "#7170ff",
in_progress: "bg-yellow-500/10 text-yellow-400 border-yellow-500/30", in_progress: "#f59e0b",
resolved: "bg-green-500/10 text-green-400 border-green-500/30", resolved: "#22c55e",
closed: "bg-neutral-500/10 text-neutral-400 border-neutral-500/30", closed: "#6b7280",
}; };
function formatDate(iso: string) { const STATUS_LABELS: Record<string, string> = {
return new Date(iso).toLocaleDateString("en-US", { new: "New",
month: "short", open: "Open",
day: "numeric", in_progress: "In progress",
year: "numeric", resolved: "Resolved",
}); closed: "Closed",
};
const FILTERS = [
{ key: null, label: "All" },
{ key: "open", label: "Open" },
{ key: "in_progress", label: "In progress" },
{ key: "resolved", label: "Resolved" },
{ key: "my", label: "My tickets" },
{ key: "unassigned", label: "Unassigned" },
] as const;
type FilterKey = (typeof FILTERS)[number]["key"];
function TicketRow({ ticket, onClick }: { ticket: Ticket; onClick: () => void }) {
const statusColor = STATUS_COLORS[ticket.status] || STATUS_COLORS.new;
const shortId = ticket.id.slice(0, 8);
const timeAgo = formatDistanceToNow(new Date(ticket.updated_at), { addSuffix: true });
return (
<button
onClick={onClick}
className="w-full flex items-center gap-3 px-4 py-2.5 text-left hover:bg-[rgba(255,255,255,0.02)] transition-colors border-b border-[rgba(255,255,255,0.04)]"
>
<span
className="w-2 h-2 rounded-full flex-shrink-0"
style={{ backgroundColor: statusColor }}
/>
<span className="font-mono text-xs text-[#8a8f98] w-16 flex-shrink-0">
{shortId}
</span>
<span className="text-sm text-[#f7f8f8] flex-1 truncate font-medium">
{ticket.subject}
</span>
<span className="text-xs text-[#8a8f98] bg-[#191a1b] px-1.5 py-0.5 rounded font-medium flex-shrink-0">
{ticket.queue_id.slice(0, 8)}
</span>
{ticket.owner_id ? (
<span className="w-5 h-5 rounded-full bg-[#5e6ad2] flex items-center justify-center flex-shrink-0">
<span className="text-[#f7f8f8] text-[10px] font-semibold leading-none">
{ticket.owner_id.charAt(0).toUpperCase()}
</span>
</span>
) : (
<span className="w-5 h-5 rounded-full border border-[rgba(255,255,255,0.08)] flex items-center justify-center flex-shrink-0">
<span className="text-[#8a8f98] text-[10px]">?</span>
</span>
)}
<span className="text-xs text-[#8a8f98] w-24 text-right flex-shrink-0 tabular-nums">
{timeAgo}
</span>
</button>
);
} }
export default function TicketsPage() { function SkeletonRow() {
return (
<div className="flex items-center gap-3 px-4 py-2.5 border-b border-[rgba(255,255,255,0.04)]">
<div className="w-2 h-2 rounded-full bg-[#191a1b] animate-pulse" />
<div className="w-16 h-3 bg-[#191a1b] rounded animate-pulse" />
<div className="flex-1 h-3 bg-[#191a1b] rounded animate-pulse" />
<div className="w-12 h-4 bg-[#191a1b] rounded animate-pulse" />
<div className="w-5 h-5 rounded-full bg-[#191a1b] animate-pulse" />
<div className="w-20 h-3 bg-[#191a1b] rounded animate-pulse" />
</div>
);
}
export default function TicketListPage() {
const router = useRouter(); const router = useRouter();
const searchParams = useSearchParams();
const [tickets, setTickets] = useState<Ticket[]>([]); const [tickets, setTickets] = useState<Ticket[]>([]);
const [queues, setQueues] = useState<Queue[]>([]); const [queues, setQueues] = useState<Queue[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [filterQueue, setFilterQueue] = useState<string>("");
const [filterStatus, setFilterStatus] = useState<string>(""); const [activeFilter, setActiveFilter] = useState<FilterKey>(null);
const [searchQuery, setSearchQuery] = useState("");
// New ticket dialog
const [dialogOpen, setDialogOpen] = useState(false); const [dialogOpen, setDialogOpen] = useState(false);
const [newSubject, setNewSubject] = useState(""); const [newSubject, setNewSubject] = useState("");
const [newQueueId, setNewQueueId] = useState(""); const [newQueueId, setNewQueueId] = useState("");
const [creating, setCreating] = useState(false); const [newDescription, setNewDescription] = useState("");
const [submitting, setSubmitting] = useState(false);
const [createError, setCreateError] = useState<string | null>(null); const [createError, setCreateError] = useState<string | null>(null);
const fetchData = useCallback(async (queueId?: string, status?: string) => { const initialQueueId = searchParams.get("queue") || "";
const fetchData = useCallback(async () => {
setLoading(true); setLoading(true);
setError(null); setError(null);
const params: { queue_id?: string; status?: string } = {};
if (queueId) params.queue_id = queueId; const statusParam = activeFilter && activeFilter !== "my" && activeFilter !== "unassigned"
if (status) params.status = status; ? activeFilter
const [tRes, qRes] = await Promise.all([getTickets(params), getQueues()]); : undefined;
if (tRes.error) setError(tRes.error);
else setTickets(tRes.data ?? []); const [ticketsRes, queuesRes] = await Promise.all([
if (qRes.error && !error) setError(qRes.error); getTickets(statusParam ? { status: statusParam } : undefined),
else setQueues(qRes.data ?? []); getQueues(),
]);
if (ticketsRes.error) {
setError(ticketsRes.error);
setTickets([]);
} else {
let result = ticketsRes.data ?? [];
if (activeFilter === "my") {
result = result.filter((t) => t.owner_id);
} else if (activeFilter === "unassigned") {
result = result.filter((t) => !t.owner_id);
}
if (initialQueueId && !activeFilter) {
result = result.filter((t) => t.queue_id === initialQueueId);
}
if (searchQuery) {
const q = searchQuery.toLowerCase();
result = result.filter((t) => t.subject.toLowerCase().includes(q));
}
setTickets(result);
}
if (queuesRes.data) {
setQueues(queuesRes.data);
}
setLoading(false); setLoading(false);
}, []); }, [activeFilter, searchQuery, initialQueueId]);
useEffect(() => { useEffect(() => {
fetchData(); fetchData();
}, [fetchData]); }, [fetchData]);
const handleFilter = () => { // Check for "new" query param to open dialog
fetchData(filterQueue || undefined, filterStatus || undefined); useEffect(() => {
}; if (searchParams.get("new") === "true") {
setDialogOpen(true);
const url = new URL(window.location.href);
url.searchParams.delete("new");
window.history.replaceState({}, "", url.toString());
}
}, [searchParams]);
const handleCreate = async () => { const handleCreate = async () => {
if (!newSubject.trim() || !newQueueId) return; if (!newSubject.trim() || !newQueueId) return;
setCreating(true); setSubmitting(true);
setCreateError(null); setCreateError(null);
const { data, error } = await createTicket({ subject: newSubject.trim(), queue_id: newQueueId });
setCreating(false); const { data, error } = await createTicket({
subject: newSubject.trim(),
queue_id: newQueueId,
});
setSubmitting(false);
if (error) { if (error) {
setCreateError(error); setCreateError(error);
} else { } else if (data) {
setDialogOpen(false); setDialogOpen(false);
setNewSubject(""); setNewSubject("");
setNewQueueId(""); setNewQueueId("");
fetchData(filterQueue || undefined, filterStatus || undefined); setNewDescription("");
if (data) router.push(`/tickets/${data.id}`); router.push(`/tickets/${data.id}`);
} }
}; };
const queueName = (id: string) => queues.find((q) => q.id === id)?.name ?? id;
return ( return (
<div className="flex flex-col gap-6"> <div className="flex flex-col h-full">
<div className="flex items-center justify-between"> {/* Top bar */}
<h1 className="text-2xl font-semibold tracking-tight">Tickets</h1> <div className="flex items-center gap-3 px-4 py-3 border-b border-[rgba(255,255,255,0.05)]">
<Button onClick={() => setDialogOpen(true)}> <div className="relative flex-1">
<Plus className="size-4" /> <SearchIcon className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-[#8a8f98]" />
New Ticket <input
</Button> value={searchQuery}
</div> onChange={(e) => setSearchQuery(e.target.value)}
placeholder="Search tickets..."
<div className="flex items-center gap-3 flex-wrap"> className="w-full h-8 pl-9 pr-3 rounded-lg bg-[#0f1011] border border-[rgba(255,255,255,0.08)] text-sm text-[#f7f8f8] placeholder:text-[#8a8f98] outline-none focus:border-[#5e6ad2] focus:ring-1 focus:ring-[#5e6ad2] transition-colors"
<Select value={filterQueue} onValueChange={(v) => setFilterQueue(!v || v === "_all" ? "" : v)}> />
<SelectTrigger className="w-44">
<SelectValue placeholder="All queues" />
</SelectTrigger>
<SelectContent>
<SelectItem value="_all">All queues</SelectItem>
{queues.map((q) => (
<SelectItem key={q.id} value={q.id}>
{q.name}
</SelectItem>
))}
</SelectContent>
</Select>
<Select value={filterStatus} onValueChange={(v) => setFilterStatus(!v || v === "_all" ? "" : v)}>
<SelectTrigger className="w-40">
<SelectValue placeholder="All statuses" />
</SelectTrigger>
<SelectContent>
<SelectItem value="_all">All statuses</SelectItem>
<SelectItem value="new">New</SelectItem>
<SelectItem value="open">Open</SelectItem>
<SelectItem value="in_progress">In Progress</SelectItem>
<SelectItem value="resolved">Resolved</SelectItem>
<SelectItem value="closed">Closed</SelectItem>
</SelectContent>
</Select>
<Button variant="outline" onClick={handleFilter}>
<Filter className="size-4" />
Filter
</Button>
</div>
{error && (
<div className="rounded-lg border border-red-500/30 bg-red-500/10 p-4 text-sm text-red-400">
{error}
</div> </div>
)} <Button
onClick={() => setDialogOpen(true)}
className="h-8 px-3 rounded-lg text-sm font-medium bg-[#5e6ad2] hover:bg-[#7170ff] text-[#f7f8f8] border-0 transition-colors"
>
<PlusIcon className="w-4 h-4 mr-1.5" />
New ticket
</Button>
</div>
{loading ? ( {/* Filter chips */}
<div className="text-sm text-neutral-400 py-12 text-center">Loading tickets...</div> <div className="flex items-center gap-1.5 px-4 py-2 border-b border-[rgba(255,255,255,0.04)]">
) : tickets.length === 0 ? ( {FILTERS.map((filter) => (
<div className="text-sm text-neutral-400 py-12 text-center">
No tickets yet.{" "}
<button <button
onClick={() => setDialogOpen(true)} key={filter.key ?? "all"}
className="text-blue-400 hover:underline" onClick={() => setActiveFilter(filter.key)}
className={cn(
"px-2.5 py-1 rounded-md text-xs font-medium transition-colors",
activeFilter === filter.key
? "bg-[#5e6ad2] text-[#f7f8f8]"
: "text-[#8a8f98] hover:text-[#d0d6e0] hover:bg-[rgba(255,255,255,0.04)]"
)}
> >
Create your first ticket {filter.label}
</button> </button>
</div> ))}
) : ( </div>
<div className="rounded-lg border border-neutral-800 overflow-hidden">
<Table>
<TableHeader>
<TableRow>
<TableHead>ID</TableHead>
<TableHead>Subject</TableHead>
<TableHead>Queue</TableHead>
<TableHead>Status</TableHead>
<TableHead>Created</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{tickets.map((t) => (
<TableRow
key={t.id}
className="cursor-pointer hover:bg-neutral-800/50"
onClick={() => router.push(`/tickets/${t.id}`)}
>
<TableCell className="font-mono text-xs text-neutral-400">
{t.id.slice(0, 8)}
</TableCell>
<TableCell className="font-medium">{t.subject}</TableCell>
<TableCell>
<Badge variant="outline">{queueName(t.queue_id)}</Badge>
</TableCell>
<TableCell>
<Badge
className={`border ${STATUS_COLORS[t.status] ?? "bg-neutral-500/10 text-neutral-400 border-neutral-500/30"}`}
variant="outline"
>
{t.status.replace("_", " ")}
</Badge>
</TableCell>
<TableCell className="text-neutral-400 text-xs">
{formatDate(t.created_at)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
)}
{/* Ticket list */}
<div className="flex-1 overflow-y-auto">
{error && (
<div className="px-4 py-3 text-sm text-red-400 bg-red-400/5 border-b border-red-400/10">
{error}{" "}
<button
onClick={fetchData}
className="underline hover:text-red-300"
>
Retry
</button>
</div>
)}
{loading &&
Array.from({ length: 12 }).map((_, i) => <SkeletonRow key={i} />)}
{!loading &&
!error &&
tickets.length === 0 && (
<div className="flex flex-col items-center justify-center py-20 px-4">
<div className="w-12 h-12 rounded-full bg-[#191a1b] flex items-center justify-center mb-4">
<SearchIcon className="w-5 h-5 text-[#8a8f98]" />
</div>
<p className="text-sm text-[#d0d6e0] font-medium">
No tickets match your filters
</p>
<p className="text-xs text-[#8a8f98] mt-1">
Try adjusting your search or filter criteria
</p>
<Button
onClick={() => setDialogOpen(true)}
className="mt-4 h-8 px-3 rounded-lg text-sm font-medium bg-[#5e6ad2] hover:bg-[#7170ff] text-[#f7f8f8] border-0"
>
<PlusIcon className="w-4 h-4 mr-1.5" />
Create a ticket
</Button>
</div>
)}
{!loading &&
!error &&
tickets.map((ticket) => (
<TicketRow
key={ticket.id}
ticket={ticket}
onClick={() => router.push(`/tickets/${ticket.id}`)}
/>
))}
</div>
{/* Create ticket dialog */}
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}> <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
<DialogContent> <DialogContent
className="sm:max-w-md"
style={{
backgroundColor: "#191a1b",
borderColor: "rgba(255,255,255,0.08)",
color: "#f7f8f8",
}}
showCloseButton={true}
>
<DialogHeader> <DialogHeader>
<DialogTitle>New Ticket</DialogTitle> <DialogTitle className="text-[#f7f8f8]">New ticket</DialogTitle>
<DialogDescription> <DialogDescription className="text-[#8a8f98]">
Create a new ticket by providing a subject and queue. Create a new ticket to track an issue or request.
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-3">
<Label htmlFor="subject">Subject</Label> <div>
<Input <label className="block text-xs font-medium text-[#d0d6e0] mb-1">
id="subject" Subject
placeholder="Enter ticket subject" </label>
<input
value={newSubject} value={newSubject}
onChange={(e) => setNewSubject(e.target.value)} onChange={(e) => setNewSubject(e.target.value)}
placeholder="Ticket subject"
className="w-full h-8 px-2.5 rounded-lg bg-[#0f1011] border border-[rgba(255,255,255,0.08)] text-sm text-[#f7f8f8] placeholder:text-[#8a8f98] outline-none focus:border-[#5e6ad2] focus:ring-1 focus:ring-[#5e6ad2]"
autoFocus
/> />
</div> </div>
<div className="flex flex-col gap-2">
<Label htmlFor="queue">Queue</Label> <div>
<Select value={newQueueId} onValueChange={(v) => setNewQueueId(v ?? "")}> <label className="block text-xs font-medium text-[#d0d6e0] mb-1">
<SelectTrigger id="queue"> Queue
<SelectValue placeholder="Select a queue" /> </label>
</SelectTrigger> <div className="relative">
<SelectContent> <select
value={newQueueId}
onChange={(e) => setNewQueueId(e.target.value)}
className="w-full h-8 px-2.5 rounded-lg bg-[#0f1011] border border-[rgba(255,255,255,0.08)] text-sm text-[#f7f8f8] outline-none focus:border-[#5e6ad2] focus:ring-1 focus:ring-[#5e6ad2] appearance-none"
>
<option value="" disabled>
Select a queue...
</option>
{queues.map((q) => ( {queues.map((q) => (
<SelectItem key={q.id} value={q.id}> <option key={q.id} value={q.id}>
{q.name} {q.name}
</SelectItem> </option>
))} ))}
</SelectContent> </select>
</Select> <svg
className="absolute right-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-[#8a8f98] pointer-events-none"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M19 9l-7 7-7-7"
/>
</svg>
</div>
</div>
<div>
<label className="block text-xs font-medium text-[#d0d6e0] mb-1">
Description{" "}
<span className="text-[#8a8f98] font-normal">(optional)</span>
</label>
<textarea
value={newDescription}
onChange={(e) => setNewDescription(e.target.value)}
placeholder="Add a description..."
rows={3}
className="w-full px-2.5 py-2 rounded-lg bg-[#0f1011] border border-[rgba(255,255,255,0.08)] text-sm text-[#f7f8f8] placeholder:text-[#8a8f98] outline-none focus:border-[#5e6ad2] focus:ring-1 focus:ring-[#5e6ad2] resize-none"
/>
</div> </div>
{createError && (
<div className="text-sm text-red-400">{createError}</div>
)}
</div> </div>
<DialogFooter>
<Button variant="outline" onClick={() => setDialogOpen(false)}> {createError && (
Cancel <p className="text-xs text-red-400">{createError}</p>
</Button> )}
<Button
<DialogFooter showCloseButton={false}>
<button
onClick={handleCreate} onClick={handleCreate}
disabled={!newSubject.trim() || !newQueueId || creating} disabled={!newSubject.trim() || !newQueueId || submitting}
className={cn(
"h-8 px-4 rounded-lg text-sm font-medium transition-colors",
"bg-[#5e6ad2] hover:bg-[#7170ff] text-[#f7f8f8]",
"disabled:opacity-40 disabled:cursor-not-allowed"
)}
> >
{creating ? "Creating..." : "Create Ticket"} {submitting ? "Creating..." : "Create ticket"}
</Button> </button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
</Dialog> </Dialog>

View File

@@ -1,39 +1,10 @@
"use client"; "use client";
import { useEffect, useState, useCallback } from "react"; import { useState, useEffect, use } from "react";
import { useParams } from "next/navigation"; import { useRouter } from "next/navigation";
import Link from "next/link"; import Link from "next/link";
import { formatDistanceToNow } from "date-fns"; import { formatDistanceToNow } from "date-fns";
import { import { ArrowLeftIcon, SendIcon, PaperclipIcon } from "lucide-react";
ArrowLeft,
Plus,
ArrowRightLeft,
MessageSquare,
Pencil,
RefreshCw,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
Card,
CardHeader,
CardTitle,
CardContent,
} from "@/components/ui/card";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
} from "@/components/ui/dialog";
import { import {
getTicket, getTicket,
getTicketTransactions, getTicketTransactions,
@@ -41,335 +12,657 @@ import {
previewTicket, previewTicket,
updateTicket, updateTicket,
} from "@/lib/api"; } from "@/lib/api";
import type { Ticket, Transaction, Queue, PreviewResult, UpdateResult } from "@/lib/types"; import type {
Ticket,
Transaction,
Queue,
PreviewResult,
UpdateResult,
} from "@/lib/types";
import { cn } from "@/lib/utils";
const STATUS_COLORS: Record<string, string> = { const STATUS_COLORS: Record<string, string> = {
new: "bg-blue-500/10 text-blue-400 border-blue-500/30", new: "#8a8f98",
open: "bg-sky-500/10 text-sky-400 border-sky-500/30", open: "#7170ff",
in_progress: "bg-yellow-500/10 text-yellow-400 border-yellow-500/30", in_progress: "#f59e0b",
resolved: "bg-green-500/10 text-green-400 border-green-500/30", resolved: "#22c55e",
closed: "bg-neutral-500/10 text-neutral-400 border-neutral-500/30", closed: "#6b7280",
}; };
const TX_ICONS: Record<string, React.ElementType> = { const STATUS_LABELS: Record<string, string> = {
Create: Plus, new: "New",
StatusChange: ArrowRightLeft, open: "Open",
Comment: MessageSquare, in_progress: "In progress",
CustomField: Pencil, resolved: "Resolved",
closed: "Closed",
}; };
const TX_COLORS: Record<string, string> = { const ALL_STATUSES = ["new", "open", "in_progress", "resolved", "closed"];
Create: "bg-green-500/10 text-green-400 border-green-500/30",
StatusChange: "bg-blue-500/10 text-blue-400 border-blue-500/30",
Comment: "bg-neutral-500/10 text-neutral-400 border-neutral-500/30",
CustomField: "bg-purple-500/10 text-purple-400 border-purple-500/30",
};
function formatDate(iso: string) { function getInitial(name: string): string {
return new Date(iso).toLocaleDateString("en-US", { if (!name) return "?";
month: "short", return name.charAt(0).toUpperCase();
day: "numeric",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
});
} }
export default function TicketDetailPage() { function getInitialColor(name: string): string {
const { id } = useParams<{ id: string }>(); const colors = ["#5e6ad2", "#7170ff", "#828fff", "#f59e0b", "#22c55e"];
let hash = 0;
for (let i = 0; i < name.length; i++) {
hash = name.charCodeAt(i) + ((hash << 5) - hash);
}
return colors[Math.abs(hash) % colors.length];
}
function TransactionBubble({
tx,
}: {
tx: Transaction;
}) {
const isSystem =
tx.transaction_type === "status_change" ||
tx.transaction_type === "assignment" ||
tx.transaction_type === "create";
const isAgent = tx.transaction_type === "agent_reply" || tx.transaction_type === "internal_note";
if (isSystem) {
const timeAgo = formatDistanceToNow(new Date(tx.created_at), {
addSuffix: true,
});
let message = "";
if (tx.transaction_type === "create") {
message = `Ticket created`;
} else if (tx.transaction_type === "status_change") {
const oldLabel = tx.old_value ? STATUS_LABELS[tx.old_value] || tx.old_value : "?";
const newLabel = tx.new_value ? STATUS_LABELS[tx.new_value] || tx.new_value : "?";
message = `${getInitial(tx.creator_id)} changed status from ${oldLabel} to ${newLabel}`;
} else if (tx.transaction_type === "assignment") {
message = tx.new_value
? `${getInitial(tx.creator_id)} assigned to ${tx.new_value}`
: `${getInitial(tx.creator_id)} unassigned`;
} else {
message = tx.transaction_type;
}
return (
<div className="flex justify-center py-2">
<span className="text-xs text-[#8a8f98]">
{message} · {timeAgo}
</span>
</div>
);
}
const isInternal = tx.transaction_type === "internal_note";
const timeAgo = formatDistanceToNow(new Date(tx.created_at), {
addSuffix: true,
});
return (
<div
className={cn(
"flex gap-3 py-3 px-4",
isAgent ? "flex-row-reverse" : ""
)}
>
<div
className="w-6 h-6 rounded-full flex items-center justify-center flex-shrink-0"
style={{
backgroundColor: isAgent
? getInitialColor(tx.creator_id)
: "#191a1b",
}}
>
<span
className="text-[11px] font-semibold"
style={{ color: isAgent ? "#f7f8f8" : "#8a8f98" }}
>
{getInitial(tx.creator_id)}
</span>
</div>
<div
className={cn(
"max-w-[75%] rounded-lg px-3 py-2",
isAgent
? "bg-[#5e6ad2]/15 text-[#f7f8f8]"
: isInternal
? "bg-[#191a1b] border border-[rgba(255,255,255,0.05)] text-[#f7f8f8]"
: "bg-[#191a1b] text-[#f7f8f8]"
)}
>
{isInternal && (
<div className="text-[10px] font-semibold text-[#f59e0b] mb-0.5 uppercase tracking-wider">
Internal note
</div>
)}
<p className="text-sm whitespace-pre-wrap">
{typeof tx.data === "object" && tx.data !== null && "body" in (tx.data as Record<string, unknown>)
? String((tx.data as Record<string, unknown>).body)
: tx.transaction_type}
</p>
<p className="text-[10px] text-[#8a8f98] mt-1">{timeAgo}</p>
</div>
</div>
);
}
export default function TicketDetailPage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = use(params);
const router = useRouter();
const [ticket, setTicket] = useState<Ticket | null>(null); const [ticket, setTicket] = useState<Ticket | null>(null);
const [transactions, setTransactions] = useState<Transaction[]>([]); const [transactions, setTransactions] = useState<Transaction[]>([]);
const [queues, setQueues] = useState<Queue[]>([]); const [queue, setQueue] = useState<Queue | null>(null);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [selectedStatus, setSelectedStatus] = useState<string>("");
const [previewing, setPreviewing] = useState(false);
const [applying, setApplying] = useState(false);
const [previewDialogOpen, setPreviewDialogOpen] = useState(false);
const [previewResult, setPreviewResult] = useState<PreviewResult | null>(null);
const [previewError, setPreviewError] = useState<string | null>(null);
const [applyResult, setApplyResult] = useState<UpdateResult | null>(null);
const [applyError, setApplyError] = useState<string | null>(null);
const fetchData = useCallback(async () => { // Reply
const [replyText, setReplyText] = useState("");
const [replyMode, setReplyMode] = useState<"public" | "internal">("public");
// Status change
const [statusSelectOpen, setStatusSelectOpen] = useState(false);
const [pendingStatus, setPendingStatus] = useState<string | null>(null);
const [preview, setPreview] = useState<PreviewResult | null>(null);
const [previewLoading, setPreviewLoading] = useState(false);
const [previewError, setPreviewError] = useState<string | null>(null);
const [applyLoading, setApplyLoading] = useState(false);
const [scripResults, setScripResults] = useState<UpdateResult["scrip_results"] | null>(null);
const fetchData = async () => {
setLoading(true); setLoading(true);
setError(null); setError(null);
const [tRes, txRes, qRes] = await Promise.all([
const [ticketRes, txRes, queuesRes] = await Promise.all([
getTicket(id), getTicket(id),
getTicketTransactions(id), getTicketTransactions(id),
getQueues(), getQueues(),
]); ]);
if (tRes.error) setError(tRes.error);
else { if (ticketRes.error) {
setTicket(tRes.data); setError(ticketRes.error);
setSelectedStatus(tRes.data?.status ?? ""); } else {
setTicket(ticketRes.data);
} }
if (txRes.error) setError(txRes.error);
else setTransactions(txRes.data ?? []); if (txRes.error) {
if (qRes.error && !error) setError(qRes.error); setError((prev) => prev || txRes.error);
else setQueues(qRes.data ?? []); } else {
setTransactions(txRes.data ?? []);
}
if (queuesRes.data && ticketRes.data) {
const q = queuesRes.data.find((q) => q.id === ticketRes.data!.queue_id);
if (q) setQueue(q);
}
setLoading(false); setLoading(false);
}, [id]); };
useEffect(() => { useEffect(() => {
fetchData(); fetchData();
}, [fetchData]); }, [id]);
const handlePreview = async () => { const handleStatusSelect = async (newStatus: string) => {
if (!selectedStatus) return; setPendingStatus(newStatus);
setPreviewing(true); setStatusSelectOpen(false);
setPreview(null);
setPreviewError(null); setPreviewError(null);
const { data, error } = await previewTicket(id, { status: selectedStatus }); setScripResults(null);
setPreviewing(false);
if (newStatus === ticket?.status) return;
setPreviewLoading(true);
const { data, error } = await previewTicket(id, { status: newStatus });
setPreviewLoading(false);
if (error) { if (error) {
setPreviewError(error); setPreviewError(error);
setPendingStatus(null);
} else { } else {
setPreviewResult(data); setPreview(data);
} }
setPreviewDialogOpen(true);
}; };
const handleApply = async () => { const handleApplyStatus = async () => {
if (!selectedStatus) return; if (!pendingStatus) return;
setApplying(true); setApplyLoading(true);
setApplyError(null); setPreviewError(null);
setApplyResult(null);
const { data, error } = await updateTicket(id, { status: selectedStatus }); const { data, error } = await updateTicket(id, { status: pendingStatus });
setApplying(false);
setApplyLoading(false);
if (error) { if (error) {
setApplyError(error); setPreviewError(error);
} else { } else if (data) {
setApplyResult(data); setTicket(data.ticket);
await fetchData(); setScripResults(data.scrip_results);
setPreview(null);
setPendingStatus(null);
// Refresh transactions
const txRes = await getTicketTransactions(id);
if (txRes.data) setTransactions(txRes.data);
} }
}; };
const queueName = queues.find((q) => q.id === ticket?.queue_id)?.name ?? ticket?.queue_id ?? "Unknown"; const handleCancelStatus = () => {
setPendingStatus(null);
setPreview(null);
setPreviewError(null);
setScripResults(null);
};
if (loading) { if (loading) {
return <div className="text-sm text-neutral-400 py-12 text-center">Loading ticket...</div>; return (
<div className="flex h-full">
<div className="flex-1 p-4 space-y-4">
{Array.from({ length: 6 }).map((_, i) => (
<div key={i} className="flex gap-3">
<div className="w-6 h-6 rounded-full bg-[#191a1b] animate-pulse" />
<div className="flex-1 space-y-2">
<div className="h-3 bg-[#191a1b] rounded animate-pulse w-3/4" />
<div className="h-3 bg-[#191a1b] rounded animate-pulse w-1/2" />
</div>
</div>
))}
</div>
<div className="w-80 bg-[#0f1011] border-l border-[rgba(255,255,255,0.05)] p-4 space-y-3">
{Array.from({ length: 5 }).map((_, i) => (
<div key={i} className="h-6 bg-[#191a1b] rounded animate-pulse" />
))}
</div>
</div>
);
} }
if (error && !ticket) { if (error && !ticket) {
return ( return (
<div className="flex flex-col items-center gap-4 py-12"> <div className="flex flex-col items-center justify-center h-full">
<div className="rounded-lg border border-red-500/30 bg-red-500/10 p-4 text-sm text-red-400"> <p className="text-red-400 text-sm">{error}</p>
{error} <button
</div> onClick={fetchData}
<Link href="/" className="text-sm text-blue-400 hover:underline"> className="mt-2 text-sm text-[#7170ff] hover:text-[#828fff]"
Back to tickets >
</Link> Retry
</button>
</div> </div>
); );
} }
if (!ticket) { if (!ticket) {
return ( return (
<div className="text-sm text-neutral-400 py-12 text-center"> <div className="flex flex-col items-center justify-center h-full">
Ticket not found.{" "} <p className="text-[#8a8f98] text-sm">Ticket not found</p>
<Link href="/" className="text-blue-400 hover:underline">
Back to tickets
</Link>
</div> </div>
); );
} }
const currentStatusColor =
STATUS_COLORS[ticket.status] || STATUS_COLORS.new;
const currentStatusLabel =
STATUS_LABELS[ticket.status] || ticket.status;
return ( return (
<div className="flex flex-col gap-6"> <div className="flex h-full">
<Link {/* Left panel — conversation */}
href="/" <div className="flex-1 flex flex-col min-w-0">
className="inline-flex items-center gap-1.5 text-sm text-neutral-400 hover:text-neutral-200 transition-colors w-fit" {/* Header */}
> <div className="flex items-center gap-3 px-4 py-2.5 border-b border-[rgba(255,255,255,0.05)]">
<ArrowLeft className="size-4" /> <Link
All tickets href="/"
</Link> className="w-7 h-7 flex items-center justify-center rounded-md hover:bg-[rgba(255,255,255,0.05)] text-[#8a8f98] hover:text-[#d0d6e0] transition-colors flex-shrink-0"
>
<Card> <ArrowLeftIcon className="w-4 h-4" />
<CardHeader> </Link>
<div className="flex items-start justify-between gap-4"> <div className="flex-1 min-w-0">
<div className="flex flex-col gap-1.5"> <h1 className="text-sm font-semibold text-[#f7f8f8] truncate">
<CardTitle className="text-xl font-semibold">{ticket.subject}</CardTitle> {ticket.subject}
<div className="flex items-center gap-3 text-sm text-neutral-400"> </h1>
<span>{queueName}</span> <p className="text-xs text-[#8a8f98]">
<span>Created {formatDate(ticket.created_at)}</span> {ticket.id.slice(0, 8)} · {queue?.name || ticket.queue_id}
<span>Updated {formatDate(ticket.updated_at)}</span> </p>
</div>
</div>
<Badge className={`border ${STATUS_COLORS[ticket.status] ?? "bg-neutral-500/10 text-neutral-400 border-neutral-500/30"}`}>
{ticket.status.replace("_", " ")}
</Badge>
</div> </div>
<div className="text-sm text-neutral-400 mt-1"> </div>
Owner: {ticket.owner_id ?? "Unassigned"}
</div>
</CardHeader>
</Card>
<Card> {/* Conversation */}
<CardHeader> <div className="flex-1 overflow-y-auto">
<CardTitle className="text-base">Change Status</CardTitle> {transactions.length === 0 && (
</CardHeader> <div className="flex flex-col items-center justify-center py-20">
<CardContent className="flex items-center gap-3 flex-wrap"> <p className="text-sm text-[#8a8f98]">
<Select value={selectedStatus} onValueChange={(v) => setSelectedStatus(!v || v === "_none" ? "" : v)}> No activity yet
<SelectTrigger className="w-44"> </p>
<SelectValue placeholder="Select status" />
</SelectTrigger>
<SelectContent>
{["new", "open", "in_progress", "resolved", "closed"].map((s) => (
<SelectItem key={s} value={s}>
{s.replace("_", " ")}
</SelectItem>
))}
</SelectContent>
</Select>
<Button variant="outline" onClick={handlePreview} disabled={!selectedStatus || selectedStatus === ticket.status || previewing}>
{previewing ? (
<>
<RefreshCw className="size-4 animate-spin" />
Previewing...
</>
) : (
"Preview"
)}
</Button>
<Button onClick={handleApply} disabled={!selectedStatus || selectedStatus === ticket.status || applying}>
{applying ? (
<>
<RefreshCw className="size-4 animate-spin" />
Applying...
</>
) : (
"Apply"
)}
</Button>
{applyError && <span className="text-sm text-red-400">{applyError}</span>}
{applyResult && (
<div className="flex flex-col gap-1 w-full mt-2">
<span className="text-sm text-green-400">Status updated successfully.</span>
{applyResult.scrip_results.map((r) => (
<div
key={r.scripId}
className={`text-xs rounded-md px-2 py-1 ${
r.success
? "bg-green-500/10 text-green-400"
: "bg-red-500/10 text-red-400"
}`}
>
{r.scripId}: {r.message}
</div>
))}
</div> </div>
)} )}
</CardContent> {transactions.map((tx) => (
</Card> <TransactionBubble key={tx.id} tx={tx} />
))}
</div>
<Card> {/* Reply box */}
<CardHeader> <div className="border-t border-[rgba(255,255,255,0.05)] bg-[#0f1011] p-3">
<CardTitle className="text-base">Transaction Timeline</CardTitle> {/* Toggle tabs */}
</CardHeader> <div className="flex gap-0.5 mb-2 p-0.5 rounded-lg bg-[#08090a] w-fit">
<CardContent> <button
{transactions.length === 0 ? ( onClick={() => setReplyMode("public")}
<div className="text-sm text-neutral-400 py-4">No transactions yet.</div> className={cn(
) : ( "px-2.5 py-1 rounded-md text-xs font-medium transition-colors",
<div className="flex flex-col gap-3"> replyMode === "public"
{transactions.map((tx) => { ? "bg-[#5e6ad2] text-[#f7f8f8]"
const Icon = TX_ICONS[tx.transaction_type] ?? MessageSquare; : "text-[#8a8f98] hover:text-[#d0d6e0]"
return ( )}
<div key={tx.id} className="flex gap-3"> >
<div className="mt-0.5 flex-shrink-0"> Reply
<Icon className="size-4 text-neutral-500" /> </button>
</div> <button
<div className="flex flex-col gap-0.5 min-w-0"> onClick={() => setReplyMode("internal")}
<div className="flex items-center gap-2 flex-wrap"> className={cn(
<Badge "px-2.5 py-1 rounded-md text-xs font-medium transition-colors",
className={`border text-[10px] px-1.5 ${TX_COLORS[tx.transaction_type] ?? "bg-neutral-500/10 text-neutral-400 border-neutral-500/30"}`} replyMode === "internal"
> ? "bg-[#5e6ad2] text-[#f7f8f8]"
{tx.transaction_type} : "text-[#8a8f98] hover:text-[#d0d6e0]"
</Badge> )}
{tx.field && ( >
<span className="text-xs text-neutral-300"> Internal note
{tx.field} </button>
{tx.old_value && tx.new_value ? ( </div>
<>
{" "} <div className="flex items-end gap-2">
<span className="text-neutral-500">{tx.old_value}</span> {" "} <textarea
<span className="text-neutral-200">{tx.new_value}</span> value={replyText}
</> onChange={(e) => setReplyText(e.target.value)}
) : tx.new_value ? ( placeholder="Reply to this ticket..."
<> rows={2}
{" "} className="flex-1 px-3 py-2 rounded-lg bg-[#08090a] border border-[rgba(255,255,255,0.08)] text-sm text-[#f7f8f8] placeholder:text-[#8a8f98] outline-none focus:border-[#5e6ad2] focus:ring-1 focus:ring-[#5e6ad2] resize-none"
set to <span className="text-neutral-200">{tx.new_value}</span> />
</> <div className="flex items-center gap-1">
) : null} <button className="w-8 h-8 flex items-center justify-center rounded-lg text-[#8a8f98] hover:text-[#d0d6e0] hover:bg-[rgba(255,255,255,0.05)] transition-colors" title="Attach file (coming soon)">
<PaperclipIcon className="w-4 h-4" />
</button>
<button
disabled={!replyText.trim()}
className={cn(
"w-8 h-8 flex items-center justify-center rounded-lg transition-colors",
replyText.trim()
? "bg-[#5e6ad2] text-[#f7f8f8] hover:bg-[#7170ff]"
: "bg-[#191a1b] text-[#8a8f98] cursor-not-allowed"
)}
>
<SendIcon className="w-4 h-4" />
</button>
</div>
</div>
</div>
</div>
{/* Right panel — properties */}
<div className="w-80 flex-shrink-0 bg-[#0f1011] border-l border-[rgba(255,255,255,0.05)] flex flex-col overflow-y-auto">
<div className="p-4 space-y-4">
{/* Status */}
<div>
<label className="block text-xs font-medium text-[#8a8f98] mb-1.5 uppercase tracking-wider">
Status
</label>
<div className="relative">
<button
onClick={() => setStatusSelectOpen(!statusSelectOpen)}
className="w-full flex items-center gap-2 px-3 py-2 rounded-lg border border-[rgba(255,255,255,0.08)] bg-[#08090a] text-sm hover:border-[rgba(255,255,255,0.15)] transition-colors"
>
<span
className="w-2.5 h-2.5 rounded-full flex-shrink-0"
style={{ backgroundColor: currentStatusColor }}
/>
<span className="text-[#f7f8f8] font-medium flex-1 text-left">
{currentStatusLabel}
</span>
<svg
className="w-4 h-4 text-[#8a8f98]"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M19 9l-7 7-7-7"
/>
</svg>
</button>
{statusSelectOpen && (
<div className="absolute top-full left-0 right-0 mt-1 z-10 bg-[#191a1b] border border-[rgba(255,255,255,0.08)] rounded-lg shadow-xl overflow-hidden">
{ALL_STATUSES.map((status) => {
const color = STATUS_COLORS[status];
const label = STATUS_LABELS[status];
const isCurrent = status === ticket.status;
return (
<button
key={status}
onClick={() => handleStatusSelect(status)}
disabled={isCurrent}
className={cn(
"w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors",
isCurrent
? "bg-[rgba(255,255,255,0.03)] text-[#8a8f98] cursor-default"
: "text-[#d0d6e0] hover:bg-[rgba(255,255,255,0.05)]"
)}
>
<span
className="w-2.5 h-2.5 rounded-full flex-shrink-0"
style={{ backgroundColor: color }}
/>
{label}
{isCurrent && (
<span className="text-xs text-[#8a8f98] ml-auto">
current
</span> </span>
)} )}
</div> </button>
<span className="text-xs text-neutral-500"> );
{formatDistanceToNow(new Date(tx.created_at), { addSuffix: true })} })}
</span> </div>
)}
</div>
</div>
{/* Status change preview */}
{preview && (
<div className="p-3 rounded-lg bg-[#08090a] border border-[rgba(255,255,255,0.08)]">
<p className="text-xs text-[#8a8f98] mb-2">
Preview: changing to{" "}
<span className="text-[#f7f8f8] font-medium">
{STATUS_LABELS[pendingStatus || ""]}
</span>
</p>
{preview.prepared_scrips.length > 0 ? (
<div className="space-y-1 mb-3">
{preview.prepared_scrips.map((scrip) => (
<div
key={scrip.scripId}
className="text-xs text-[#d0d6e0] flex items-center gap-1.5"
>
<span className="w-2 h-2 rounded-full bg-[#f59e0b] flex-shrink-0" />
{scrip.scripName}
</div> </div>
</div> ))}
); </div>
})} ) : (
<p className="text-xs text-[#8a8f98] mb-3">
No scrips will fire
</p>
)}
<div className="flex items-center gap-2">
<button
onClick={handleApplyStatus}
disabled={applyLoading}
className="px-2.5 py-1 rounded-md text-xs font-medium bg-[#5e6ad2] hover:bg-[#7170ff] text-[#f7f8f8] disabled:opacity-50 transition-colors"
>
{applyLoading
? "Applying..."
: `Apply — ${preview.prepared_scrips.length} scrip${preview.prepared_scrips.length !== 1 ? "s" : ""} will fire`}
</button>
<button
onClick={handleCancelStatus}
disabled={applyLoading}
className="px-2.5 py-1 rounded-md text-xs font-medium text-[#8a8f98] hover:text-[#d0d6e0] transition-colors"
>
Cancel
</button>
</div>
</div> </div>
)} )}
</CardContent>
</Card>
{ticket.custom_fields && ticket.custom_fields.length > 0 && ( {previewError && (
<Card> <div className="p-2 rounded-lg bg-red-400/5 border border-red-400/10">
<CardHeader> <p className="text-xs text-red-400">{previewError}</p>
<CardTitle className="text-base">Custom Fields</CardTitle>
</CardHeader>
<CardContent>
<div className="flex flex-col gap-2">
{ticket.custom_fields.map((cf) => (
<div key={cf.id} className="flex gap-2 text-sm">
<span className="text-neutral-400">
{cf.custom_field?.name ?? cf.custom_field_id}:
</span>
<span className="text-neutral-200">{cf.value}</span>
</div>
))}
</div> </div>
</CardContent> )}
</Card>
)}
<Dialog open={previewDialogOpen} onOpenChange={setPreviewDialogOpen}> {scripResults && (
<DialogContent showCloseButton={true}> <div className="p-3 rounded-lg bg-[#08090a] border border-[rgba(255,255,255,0.08)]">
<DialogHeader> <p className="text-xs text-[#8a8f98] mb-2">Scrip results:</p>
<DialogTitle>Preview Status Change</DialogTitle> <div className="space-y-1">
<DialogDescription> {scripResults.map((result) => (
The following scrips would execute when changing status to{" "} <div
<span className="text-neutral-200 font-medium"> key={result.scripId}
{selectedStatus.replace("_", " ")} className={cn(
</span> "text-xs flex items-center gap-1.5",
. result.success ? "text-[#22c55e]" : "text-red-400"
</DialogDescription> )}
</DialogHeader> >
<div className="flex flex-col gap-2"> <span
{previewError && ( className={cn(
<div className="text-sm text-red-400">{previewError}</div> "w-2 h-2 rounded-full flex-shrink-0",
)} result.success ? "bg-[#22c55e]" : "bg-red-400"
{previewResult && previewResult.prepared_scrips.length === 0 && ( )}
<div className="text-sm text-neutral-400">No scrips would be triggered.</div> />
)} {result.message}
{previewResult?.prepared_scrips.map((ps) => ( </div>
<div ))}
key={ps.scripId}
className="rounded-lg border border-neutral-800 bg-neutral-900 p-3 text-sm"
>
<div className="font-medium text-neutral-200">{ps.scripName}</div>
<div className="text-neutral-400 text-xs mt-0.5">
Action: {ps.actionType}
{ps.dryRun ? " (dry run)" : " (would execute)"}
</div>
</div> </div>
))} <button
onClick={() => setScripResults(null)}
className="mt-2 text-xs text-[#8a8f98] hover:text-[#d0d6e0]"
>
Dismiss
</button>
</div>
)}
{/* Priority (placeholder) */}
<div>
<label className="block text-xs font-medium text-[#8a8f98] mb-1.5 uppercase tracking-wider">
Priority
</label>
<div className="px-3 py-2 rounded-lg border border-[rgba(255,255,255,0.05)] bg-[#08090a] text-sm text-[#8a8f98]">
Not set
</div>
</div> </div>
</DialogContent>
</Dialog> {/* Assignee */}
<div>
<label className="block text-xs font-medium text-[#8a8f98] mb-1.5 uppercase tracking-wider">
Assignee
</label>
{ticket.owner_id ? (
<div className="flex items-center gap-2 px-3 py-2 rounded-lg border border-[rgba(255,255,255,0.08)] bg-[#08090a]">
<div
className="w-5 h-5 rounded-full flex items-center justify-center flex-shrink-0"
style={{
backgroundColor: getInitialColor(ticket.owner_id),
}}
>
<span className="text-[10px] font-semibold text-[#f7f8f8]">
{getInitial(ticket.owner_id)}
</span>
</div>
<span className="text-sm text-[#f7f8f8]">
{ticket.owner_id}
</span>
</div>
) : (
<div className="px-3 py-2 rounded-lg border border-[rgba(255,255,255,0.05)] bg-[#08090a] text-sm text-[#8a8f98]">
Unassigned
</div>
)}
</div>
{/* Queue */}
<div>
<label className="block text-xs font-medium text-[#8a8f98] mb-1.5 uppercase tracking-wider">
Queue
</label>
<div className="px-3 py-2 rounded-lg border border-[rgba(255,255,255,0.08)] bg-[#08090a]">
<span className="text-sm text-[#f7f8f8]">
{queue?.name || ticket.queue_id}
</span>
</div>
</div>
{/* Custom fields */}
{ticket.custom_fields && ticket.custom_fields.length > 0 && (
<div>
<label className="block text-xs font-medium text-[#8a8f98] mb-1.5 uppercase tracking-wider">
Custom fields
</label>
<div className="space-y-1.5">
{ticket.custom_fields.map((cf) => (
<div
key={cf.id}
className="flex justify-between items-center px-3 py-1.5 rounded-lg border border-[rgba(255,255,255,0.05)] bg-[#08090a]"
>
<span className="text-xs text-[#8a8f98]">
{cf.custom_field?.name || cf.custom_field_id}
</span>
<span className="text-xs text-[#f7f8f8] font-medium">
{cf.value}
</span>
</div>
))}
</div>
</div>
)}
{/* Dates */}
<div>
<label className="block text-xs font-medium text-[#8a8f98] mb-1.5 uppercase tracking-wider">
Dates
</label>
<div className="space-y-1 text-xs">
<div className="flex justify-between px-1">
<span className="text-[#8a8f98]">Created</span>
<span className="text-[#d0d6e0] tabular-nums">
{formatDistanceToNow(new Date(ticket.created_at), {
addSuffix: true,
})}
</span>
</div>
<div className="flex justify-between px-1">
<span className="text-[#8a8f98]">Updated</span>
<span className="text-[#d0d6e0] tabular-nums">
{formatDistanceToNow(new Date(ticket.updated_at), {
addSuffix: true,
})}
</span>
</div>
{ticket.resolved_at && (
<div className="flex justify-between px-1">
<span className="text-[#8a8f98]">Resolved</span>
<span className="text-[#d0d6e0] tabular-nums">
{formatDistanceToNow(new Date(ticket.resolved_at), {
addSuffix: true,
})}
</span>
</div>
)}
</div>
</div>
</div>
</div>
</div> </div>
); );
} }

View File

@@ -0,0 +1,265 @@
"use client";
import { useState, useEffect, Suspense } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import Link from "next/link";
import {
LayoutGridIcon,
UserIcon,
InboxIcon,
ClockIcon,
SettingsIcon,
} from "lucide-react";
import { getTickets, getQueues } from "@/lib/api";
import type { Queue } from "@/lib/types";
import { CommandPalette } from "@/components/command-palette";
import { cn } from "@/lib/utils";
interface ViewCounts {
all: number;
my: number;
unassigned: number;
recent: number;
}
function SidebarNav() {
const pathname = usePathname();
const searchParams = useSearchParams();
const [counts, setCounts] = useState<ViewCounts>({
all: 0,
my: 0,
unassigned: 0,
recent: 0,
});
const [queues, setQueues] = useState<(Queue & { count: number })[]>([]);
useEffect(() => {
getTickets().then(({ data }) => {
if (data) {
const now = Date.now();
const week = 7 * 24 * 60 * 60 * 1000;
setCounts({
all: data.length,
my: data.filter((t) => t.owner_id).length,
unassigned: data.filter((t) => !t.owner_id).length,
recent: data.filter(
(t) => new Date(t.updated_at).getTime() > now - week
).length,
});
}
});
getQueues().then(({ data }) => {
if (data) {
Promise.all(
data.map((q) =>
getTickets({ queue_id: q.id }).then(({ data: tickets }) => ({
...q,
count: tickets?.length ?? 0,
}))
)
).then(setQueues);
}
});
}, []);
const views = [
{
label: "All tickets",
href: "/",
param: null,
count: counts.all,
icon: LayoutGridIcon,
},
{
label: "My tickets",
href: "/?view=my",
param: "my",
count: counts.my,
icon: UserIcon,
},
{
label: "Unassigned",
href: "/?view=unassigned",
param: "unassigned",
count: counts.unassigned,
icon: InboxIcon,
},
{
label: "Recently updated",
href: "/?view=recent",
param: "recent",
count: counts.recent,
icon: ClockIcon,
},
];
const currentView = searchParams.get("view");
return (
<>
<div className="mb-4">
{views.map((view) => {
const Icon = view.icon;
const active =
pathname === "/" &&
(view.param ? currentView === view.param : !currentView);
return (
<Link
key={view.label}
href={view.href}
className={cn(
"flex items-center justify-between px-2 py-1.5 rounded-md text-[13px] transition-colors mb-0.5",
active
? "bg-[rgba(255,255,255,0.05)] text-[#f7f8f8] font-medium"
: "text-[#8a8f98] hover:text-[#d0d6e0] hover:bg-[rgba(255,255,255,0.03)] font-normal"
)}
>
<span className="flex items-center gap-2.5">
<Icon className="w-4 h-4 flex-shrink-0" />
{view.label}
</span>
{view.count > 0 && (
<span className="text-xs tabular-nums text-[#8a8f98]">
{view.count}
</span>
)}
</Link>
);
})}
</div>
{queues.length > 0 && (
<div>
<div className="px-2 py-1.5 text-[11px] font-semibold text-[#8a8f98] uppercase tracking-wider">
Queues
</div>
{queues.map((queue) => {
const active =
pathname === "/" && searchParams.get("queue") === queue.id;
return (
<Link
key={queue.id}
href={`/?queue=${queue.id}`}
className={cn(
"flex items-center justify-between px-2 py-1.5 rounded-md text-[13px] transition-colors",
active
? "bg-[rgba(255,255,255,0.05)] text-[#f7f8f8] font-medium"
: "text-[#8a8f98] hover:text-[#d0d6e0] hover:bg-[rgba(255,255,255,0.03)] font-normal"
)}
>
<span className="flex items-center gap-2.5">
<span className="w-2 h-2 rounded-full bg-[#8a8f98] flex-shrink-0" />
{queue.name}
</span>
{queue.count > 0 && (
<span className="text-xs tabular-nums text-[#8a8f98]">
{queue.count}
</span>
)}
</Link>
);
})}
</div>
)}
</>
);
}
function SidebarBottom() {
const pathname = usePathname();
return (
<div className="border-t border-[rgba(255,255,255,0.05)] p-2">
<Link
href="/admin"
className={cn(
"flex items-center gap-2.5 px-2 py-1.5 rounded-md text-[13px] transition-colors",
pathname === "/admin"
? "bg-[rgba(255,255,255,0.05)] text-[#f7f8f8] font-medium"
: "text-[#8a8f98] hover:text-[#d0d6e0] hover:bg-[rgba(255,255,255,0.03)] font-normal"
)}
>
<SettingsIcon className="w-4 h-4 flex-shrink-0" />
Admin
</Link>
<div className="flex items-center gap-2 px-2 py-1.5 mt-0.5">
<div className="w-5 h-5 rounded-full bg-[#5e6ad2] flex items-center justify-center flex-shrink-0">
<span className="text-[#f7f8f8] text-[10px] font-semibold">U</span>
</div>
<span className="text-[13px] text-[#8a8f98] truncate">User</span>
</div>
</div>
);
}
export function AppShell({ children }: { children: React.ReactNode }) {
const [commandOpen, setCommandOpen] = useState(false);
useEffect(() => {
const down = (e: KeyboardEvent) => {
if ((e.key === "k" && (e.metaKey || e.ctrlKey)) || e.key === "/") {
if (
e.target instanceof HTMLInputElement ||
e.target instanceof HTMLTextAreaElement ||
(e.target instanceof HTMLElement && e.target.isContentEditable)
) {
return;
}
e.preventDefault();
setCommandOpen((o) => !o);
}
};
document.addEventListener("keydown", down);
return () => document.removeEventListener("keydown", down);
}, []);
return (
<div className="flex h-screen overflow-hidden">
{/* Sidebar */}
<aside className="w-60 flex-shrink-0 flex flex-col bg-[#0f1011] border-r border-[rgba(255,255,255,0.05)]">
{/* Brand */}
<div className="h-11 flex items-center px-3 border-b border-[rgba(255,255,255,0.05)]">
<Link href="/" className="flex items-center gap-2">
<div className="w-5 h-5 rounded-md bg-[#5e6ad2] flex items-center justify-center">
<span className="text-[#f7f8f8] text-[11px] font-semibold">
T
</span>
</div>
<span className="font-semibold text-[#f7f8f8] text-sm tracking-tight">
Tessera
</span>
</Link>
</div>
{/* Nav */}
<nav className="flex-1 overflow-y-auto py-2 px-2">
<Suspense
fallback={
<div className="space-y-1.5 px-2">
{Array.from({ length: 6 }).map((_, i) => (
<div
key={i}
className="h-7 bg-[#191a1b] rounded-md animate-pulse"
/>
))}
</div>
}
>
<SidebarNav />
</Suspense>
</nav>
{/* Bottom */}
<SidebarBottom />
</aside>
{/* Main */}
<main className="flex-1 overflow-y-auto">{children}</main>
{/* Command Palette */}
<CommandPalette open={commandOpen} onOpenChange={setCommandOpen} />
</div>
);
}

View File

@@ -0,0 +1,172 @@
"use client";
import { useState, useEffect, useRef, useCallback } from "react";
import { useRouter } from "next/navigation";
import {
SearchIcon,
PlusIcon,
LayoutGridIcon,
SettingsIcon,
} from "lucide-react";
interface CommandItem {
id: string;
label: string;
icon: React.ComponentType<{ className?: string }>;
action: () => void;
category?: string;
}
interface CommandPaletteProps {
open: boolean;
onOpenChange: (open: boolean) => void;
}
export function CommandPalette({ open, onOpenChange }: CommandPaletteProps) {
const router = useRouter();
const inputRef = useRef<HTMLInputElement>(null);
const listRef = useRef<HTMLDivElement>(null);
const [query, setQuery] = useState("");
const [selectedIndex, setSelectedIndex] = useState(0);
const commands: CommandItem[] = [
{
id: "new-ticket",
label: "New ticket",
icon: PlusIcon,
action: () => {
onOpenChange(false);
router.push("/?new=true");
},
category: "Actions",
},
{
id: "all-tickets",
label: "All tickets",
icon: LayoutGridIcon,
action: () => {
onOpenChange(false);
router.push("/");
},
category: "Navigate",
},
{
id: "admin",
label: "Go to admin",
icon: SettingsIcon,
action: () => {
onOpenChange(false);
router.push("/admin");
},
category: "Navigate",
},
];
const filtered = commands.filter((cmd) =>
cmd.label.toLowerCase().includes(query.toLowerCase())
);
const grouped = filtered.reduce<Record<string, CommandItem[]>>((acc, cmd) => {
const cat = cmd.category || "Other";
if (!acc[cat]) acc[cat] = [];
acc[cat].push(cmd);
return acc;
}, {});
useEffect(() => {
if (open) {
setQuery("");
setSelectedIndex(0);
setTimeout(() => inputRef.current?.focus(), 50);
}
}, [open]);
useEffect(() => {
setSelectedIndex(0);
}, [query]);
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
if (e.key === "ArrowDown") {
e.preventDefault();
setSelectedIndex((i) => Math.min(i + 1, filtered.length - 1));
} else if (e.key === "ArrowUp") {
e.preventDefault();
setSelectedIndex((i) => Math.max(i - 1, 0));
} else if (e.key === "Enter") {
e.preventDefault();
if (filtered[selectedIndex]) {
filtered[selectedIndex].action();
}
} else if (e.key === "Escape") {
onOpenChange(false);
}
},
[filtered, selectedIndex, onOpenChange]
);
if (!open) return null;
return (
<div className="fixed inset-0 z-50">
<div
className="fixed inset-0 bg-black/60 backdrop-blur-sm"
onClick={() => onOpenChange(false)}
/>
<div className="fixed top-[20%] left-1/2 -translate-x-1/2 w-full max-w-md">
<div className="bg-[#191a1b] rounded-xl shadow-2xl border border-[rgba(255,255,255,0.08)] overflow-hidden">
<div className="flex items-center gap-2 px-3 border-b border-[rgba(255,255,255,0.05)]">
<SearchIcon className="w-4 h-4 text-[#8a8f98] flex-shrink-0" />
<input
ref={inputRef}
value={query}
onChange={(e) => setQuery(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Type a command or search..."
className="w-full h-10 bg-transparent text-sm text-[#f7f8f8] placeholder:text-[#8a8f98] outline-none"
/>
</div>
<div ref={listRef} className="max-h-64 overflow-y-auto p-1">
{filtered.length === 0 && (
<div className="px-3 py-6 text-center text-sm text-[#8a8f98]">
No results found
</div>
)}
{Object.entries(grouped).map(([category, items]) => (
<div key={category}>
<div className="px-2 py-1.5 text-xs font-medium text-[#8a8f98]">
{category}
</div>
{items.map((item) => {
const idx = filtered.indexOf(item);
const isSelected = idx === selectedIndex;
const Icon = item.icon;
return (
<button
key={item.id}
className={`w-full flex items-center gap-2.5 px-2 py-2 rounded-lg text-sm text-left transition-colors ${
isSelected
? "bg-[#5e6ad2] text-white"
: "text-[#d0d6e0] hover:bg-[rgba(255,255,255,0.05)]"
}`}
onClick={item.action}
onMouseEnter={() => setSelectedIndex(idx)}
>
<Icon className="w-4 h-4 flex-shrink-0" />
{item.label}
</button>
);
})}
</div>
))}
</div>
<div className="border-t border-[rgba(255,255,255,0.05)] px-3 py-2 flex items-center justify-between text-xs text-[#8a8f98]">
<span> Navigate</span>
<span> Select</span>
<span>Esc Dismiss</span>
</div>
</div>
</div>
</div>
);
}