Ticket IDs, audit log, markdown comments, tabbed detail page

- Tickets get a random display ID (V + 9 digits, e.g. V325813929)
- Ticket detail page has Overview / Comments / Audit Log tabs
- Audit log records every action (create, status, assignee, severity,
  reroute, title/overview edit, comment add/delete) with who and when
- Comments redesigned: avatar (initials + color), markdown rendering
  via react-markdown + remark-gfm, Write/Preview toggle
- Dashboard shows displayId and assignee avatar
- URLs now use displayId (/tickets/V325813929)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-30 20:53:37 -04:00
parent 429a530fc8
commit f65c259a71
11 changed files with 2157 additions and 309 deletions

1475
client/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -16,7 +16,9 @@
"react": "^18.3.1", "react": "^18.3.1",
"react-dom": "^18.3.1", "react-dom": "^18.3.1",
"react-hook-form": "^7.54.2", "react-hook-form": "^7.54.2",
"react-markdown": "^9.0.1",
"react-router-dom": "^6.28.0", "react-router-dom": "^6.28.0",
"remark-gfm": "^4.0.0",
"zod": "^3.23.8" "zod": "^3.23.8"
}, },
"devDependencies": { "devDependencies": {

View File

@@ -0,0 +1,44 @@
const PALETTE = [
'#ef4444', '#f97316', '#f59e0b', '#10b981',
'#06b6d4', '#3b82f6', '#8b5cf6', '#ec4899',
]
function nameToColor(name: string): string {
let hash = 0
for (let i = 0; i < name.length; i++) {
hash = name.charCodeAt(i) + ((hash << 5) - hash)
}
return PALETTE[Math.abs(hash) % PALETTE.length]
}
function initials(name: string): string {
return name
.split(' ')
.slice(0, 2)
.map((n) => n[0])
.join('')
.toUpperCase()
}
const SIZES = {
sm: 'w-6 h-6 text-xs',
md: 'w-8 h-8 text-sm',
lg: 'w-10 h-10 text-base',
}
interface AvatarProps {
name: string
size?: keyof typeof SIZES
}
export default function Avatar({ name, size = 'md' }: AvatarProps) {
return (
<div
className={`${SIZES[size]} rounded-full flex items-center justify-center font-semibold text-white flex-shrink-0 select-none`}
style={{ backgroundColor: nameToColor(name) }}
title={name}
>
{initials(name)}
</div>
)
}

View File

@@ -1,3 +1,24 @@
@tailwind base; @tailwind base;
@tailwind components; @tailwind components;
@tailwind utilities; @tailwind utilities;
/* Markdown prose styles */
.prose p { @apply mb-3 last:mb-0 leading-relaxed; }
.prose h1 { @apply text-xl font-bold mb-3 mt-5; }
.prose h2 { @apply text-lg font-semibold mb-2 mt-4; }
.prose h3 { @apply text-base font-semibold mb-2 mt-3; }
.prose ul { @apply list-disc pl-5 mb-3 space-y-1; }
.prose ol { @apply list-decimal pl-5 mb-3 space-y-1; }
.prose li > ul,
.prose li > ol { @apply mt-1 mb-0; }
.prose a { @apply text-blue-600 underline hover:text-blue-800; }
.prose strong { @apply font-semibold; }
.prose em { @apply italic; }
.prose blockquote { @apply border-l-4 border-gray-200 pl-4 text-gray-500 my-3 italic; }
.prose code { @apply bg-gray-100 text-gray-800 px-1.5 py-0.5 rounded text-xs font-mono; }
.prose pre { @apply bg-gray-900 text-gray-100 p-4 rounded-lg my-3 overflow-x-auto text-sm; }
.prose pre code { @apply bg-transparent text-gray-100 p-0; }
.prose hr { @apply border-gray-200 my-4; }
.prose table { @apply w-full border-collapse text-sm my-3; }
.prose th { @apply bg-gray-50 border border-gray-200 px-3 py-2 text-left font-semibold; }
.prose td { @apply border border-gray-200 px-3 py-2; }

View File

@@ -6,6 +6,7 @@ import api from '../api/client'
import Layout from '../components/Layout' import Layout from '../components/Layout'
import SeverityBadge from '../components/SeverityBadge' import SeverityBadge from '../components/SeverityBadge'
import StatusBadge from '../components/StatusBadge' import StatusBadge from '../components/StatusBadge'
import Avatar from '../components/Avatar'
import { Ticket, TicketStatus } from '../types' import { Ticket, TicketStatus } from '../types'
const STATUSES: { value: TicketStatus | ''; label: string }[] = [ const STATUSES: { value: TicketStatus | ''; label: string }[] = [
@@ -102,7 +103,7 @@ export default function Dashboard() {
{tickets.map((ticket) => ( {tickets.map((ticket) => (
<Link <Link
key={ticket.id} key={ticket.id}
to={`/tickets/${ticket.id}`} to={`/tickets/${ticket.displayId}`}
className="flex items-center gap-4 bg-white border border-gray-200 rounded-lg px-4 py-3 hover:border-blue-400 hover:shadow-sm transition-all group" className="flex items-center gap-4 bg-white border border-gray-200 rounded-lg px-4 py-3 hover:border-blue-400 hover:shadow-sm transition-all group"
> >
{/* Severity stripe */} {/* Severity stripe */}
@@ -122,6 +123,9 @@ export default function Dashboard() {
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-0.5"> <div className="flex items-center gap-2 mb-0.5">
<span className="text-xs font-mono font-medium text-gray-400">
{ticket.displayId}
</span>
<SeverityBadge severity={ticket.severity} /> <SeverityBadge severity={ticket.severity} />
<StatusBadge status={ticket.status} /> <StatusBadge status={ticket.status} />
<span className="text-xs text-gray-400"> <span className="text-xs text-gray-400">
@@ -131,15 +135,24 @@ export default function Dashboard() {
<p className="text-sm font-medium text-gray-900 truncate group-hover:text-blue-700"> <p className="text-sm font-medium text-gray-900 truncate group-hover:text-blue-700">
{ticket.title} {ticket.title}
</p> </p>
<p className="text-xs text-gray-400 truncate mt-0.5">{ticket.overview}</p>
</div> </div>
<div className="text-right text-xs text-gray-400 flex-shrink-0 space-y-0.5"> <div className="flex items-center gap-3 flex-shrink-0">
<div className="font-medium text-gray-600"> {ticket.assignee && (
{ticket.assignee?.displayName ?? 'Unassigned'} <div className="flex items-center gap-1.5 text-xs text-gray-500">
</div> <Avatar name={ticket.assignee.displayName} size="sm" />
<div>{ticket._count?.comments ?? 0} comments</div> <span>{ticket.assignee.displayName}</span>
<div>{formatDistanceToNow(new Date(ticket.createdAt), { addSuffix: true })}</div> </div>
)}
{!ticket.assignee && (
<span className="text-xs text-gray-400">Unassigned</span>
)}
<span className="text-xs text-gray-400">
{ticket._count?.comments ?? 0} comments
</span>
<span className="text-xs text-gray-400">
{formatDistanceToNow(new Date(ticket.createdAt), { addSuffix: true })}
</span>
</div> </div>
</Link> </Link>
))} ))}

View File

@@ -49,7 +49,7 @@ export default function NewTicket() {
if (form.assigneeId) payload.assigneeId = form.assigneeId if (form.assigneeId) payload.assigneeId = form.assigneeId
const res = await api.post('/tickets', payload) const res = await api.post('/tickets', payload)
navigate(`/tickets/${res.data.id}`) navigate(`/tickets/${res.data.displayId}`)
} catch { } catch {
setError('Failed to create ticket') setError('Failed to create ticket')
} finally { } finally {

View File

@@ -1,15 +1,23 @@
import { useState, useEffect, useRef } from 'react' import { useState, useEffect } from 'react'
import { useParams, useNavigate } from 'react-router-dom' import { useParams, useNavigate } from 'react-router-dom'
import { format } from 'date-fns' import { format, formatDistanceToNow } from 'date-fns'
import { Pencil, Trash2, Send, X, Check } from 'lucide-react' import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import {
Pencil, Trash2, Send, X, Check,
MessageSquare, ClipboardList, FileText,
} from 'lucide-react'
import api from '../api/client' import api from '../api/client'
import Layout from '../components/Layout' import Layout from '../components/Layout'
import SeverityBadge from '../components/SeverityBadge' import SeverityBadge from '../components/SeverityBadge'
import StatusBadge from '../components/StatusBadge' import StatusBadge from '../components/StatusBadge'
import CTISelect from '../components/CTISelect' import CTISelect from '../components/CTISelect'
import { Ticket, TicketStatus, User, Comment } from '../types' import Avatar from '../components/Avatar'
import { Ticket, TicketStatus, User, Comment, AuditLog } from '../types'
import { useAuth } from '../contexts/AuthContext' import { useAuth } from '../contexts/AuthContext'
type Tab = 'overview' | 'comments' | 'audit'
const STATUS_OPTIONS: { value: TicketStatus; label: string }[] = [ const STATUS_OPTIONS: { value: TicketStatus; label: string }[] = [
{ value: 'OPEN', label: 'Open' }, { value: 'OPEN', label: 'Open' },
{ value: 'IN_PROGRESS', label: 'In Progress' }, { value: 'IN_PROGRESS', label: 'In Progress' },
@@ -17,6 +25,30 @@ const STATUS_OPTIONS: { value: TicketStatus; label: string }[] = [
{ value: 'CLOSED', label: 'Closed' }, { value: 'CLOSED', label: 'Closed' },
] ]
const AUDIT_LABELS: Record<string, string> = {
CREATED: 'Ticket created',
STATUS_CHANGED: 'Status changed',
ASSIGNEE_CHANGED: 'Assignee changed',
SEVERITY_CHANGED: 'Severity changed',
REROUTED: 'Rerouted',
TITLE_CHANGED: 'Title updated',
OVERVIEW_CHANGED: 'Overview updated',
COMMENT_ADDED: 'Comment added',
COMMENT_DELETED: 'Comment deleted',
}
const AUDIT_COLORS: Record<string, string> = {
CREATED: 'bg-green-500',
STATUS_CHANGED: 'bg-blue-500',
ASSIGNEE_CHANGED: 'bg-purple-500',
SEVERITY_CHANGED: 'bg-orange-500',
REROUTED: 'bg-cyan-500',
TITLE_CHANGED: 'bg-gray-400',
OVERVIEW_CHANGED: 'bg-gray-400',
COMMENT_ADDED: 'bg-gray-400',
COMMENT_DELETED: 'bg-red-400',
}
export default function TicketDetail() { export default function TicketDetail() {
const { id } = useParams<{ id: string }>() const { id } = useParams<{ id: string }>()
const navigate = useNavigate() const navigate = useNavigate()
@@ -24,11 +56,13 @@ export default function TicketDetail() {
const [ticket, setTicket] = useState<Ticket | null>(null) const [ticket, setTicket] = useState<Ticket | null>(null)
const [users, setUsers] = useState<User[]>([]) const [users, setUsers] = useState<User[]>([])
const [auditLogs, setAuditLogs] = useState<AuditLog[]>([])
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [tab, setTab] = useState<Tab>('overview')
const [editing, setEditing] = useState(false) const [editing, setEditing] = useState(false)
const [commentBody, setCommentBody] = useState('') const [commentBody, setCommentBody] = useState('')
const [submittingComment, setSubmittingComment] = useState(false) const [submittingComment, setSubmittingComment] = useState(false)
const commentRef = useRef<HTMLTextAreaElement>(null) const [preview, setPreview] = useState(false)
const [editForm, setEditForm] = useState({ const [editForm, setEditForm] = useState({
title: '', title: '',
@@ -50,6 +84,15 @@ export default function TicketDetail() {
}).finally(() => setLoading(false)) }).finally(() => setLoading(false))
}, [id]) }, [id])
const fetchAudit = () => {
if (!ticket) return
api.get<AuditLog[]>(`/tickets/${id}/audit`).then((r) => setAuditLogs(r.data))
}
useEffect(() => {
if (tab === 'audit') fetchAudit()
}, [tab, ticket])
const startEdit = () => { const startEdit = () => {
if (!ticket) return if (!ticket) return
setEditForm({ setEditForm({
@@ -66,7 +109,7 @@ export default function TicketDetail() {
const saveEdit = async () => { const saveEdit = async () => {
if (!ticket) return if (!ticket) return
const payload: Record<string, unknown> = { const res = await api.patch<Ticket>(`/tickets/${ticket.displayId}`, {
title: editForm.title, title: editForm.title,
overview: editForm.overview, overview: editForm.overview,
severity: editForm.severity, severity: editForm.severity,
@@ -74,21 +117,20 @@ export default function TicketDetail() {
typeId: editForm.typeId, typeId: editForm.typeId,
itemId: editForm.itemId, itemId: editForm.itemId,
assigneeId: editForm.assigneeId || null, assigneeId: editForm.assigneeId || null,
} })
const res = await api.patch<Ticket>(`/tickets/${ticket.id}`, payload)
setTicket(res.data) setTicket(res.data)
setEditing(false) setEditing(false)
} }
const updateStatus = async (status: TicketStatus) => { const updateStatus = async (status: TicketStatus) => {
if (!ticket) return if (!ticket) return
const res = await api.patch<Ticket>(`/tickets/${ticket.id}`, { status }) const res = await api.patch<Ticket>(`/tickets/${ticket.displayId}`, { status })
setTicket(res.data) setTicket(res.data)
} }
const updateAssignee = async (assigneeId: string) => { const updateAssignee = async (assigneeId: string) => {
if (!ticket) return if (!ticket) return
const res = await api.patch<Ticket>(`/tickets/${ticket.id}`, { const res = await api.patch<Ticket>(`/tickets/${ticket.displayId}`, {
assigneeId: assigneeId || null, assigneeId: assigneeId || null,
}) })
setTicket(res.data) setTicket(res.data)
@@ -96,7 +138,7 @@ export default function TicketDetail() {
const deleteTicket = async () => { const deleteTicket = async () => {
if (!ticket || !confirm('Delete this ticket?')) return if (!ticket || !confirm('Delete this ticket?')) return
await api.delete(`/tickets/${ticket.id}`) await api.delete(`/tickets/${ticket.displayId}`)
navigate('/') navigate('/')
} }
@@ -105,13 +147,12 @@ export default function TicketDetail() {
if (!ticket || !commentBody.trim()) return if (!ticket || !commentBody.trim()) return
setSubmittingComment(true) setSubmittingComment(true)
try { try {
const res = await api.post<Comment>(`/tickets/${ticket.id}/comments`, { const res = await api.post<Comment>(`/tickets/${ticket.displayId}/comments`, {
body: commentBody.trim(), body: commentBody.trim(),
}) })
setTicket((t) => setTicket((t) => t ? { ...t, comments: [...(t.comments ?? []), res.data] } : t)
t ? { ...t, comments: [...(t.comments ?? []), res.data] } : t
)
setCommentBody('') setCommentBody('')
setPreview(false)
} finally { } finally {
setSubmittingComment(false) setSubmittingComment(false)
} }
@@ -119,272 +160,378 @@ export default function TicketDetail() {
const deleteComment = async (commentId: string) => { const deleteComment = async (commentId: string) => {
if (!ticket) return if (!ticket) return
await api.delete(`/tickets/${ticket.id}/comments/${commentId}`) await api.delete(`/tickets/${ticket.displayId}/comments/${commentId}`)
setTicket((t) => setTicket((t) => t ? { ...t, comments: t.comments?.filter((c) => c.id !== commentId) } : t)
t ? { ...t, comments: t.comments?.filter((c) => c.id !== commentId) } : t
)
} }
const inputClass = const inputClass =
'w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500' 'w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500'
if (loading) { if (loading) {
return ( return <Layout><div className="text-center py-16 text-gray-400 text-sm">Loading...</div></Layout>
<Layout>
<div className="text-center py-16 text-gray-400 text-sm">Loading...</div>
</Layout>
)
} }
if (!ticket) { if (!ticket) {
return ( return <Layout><div className="text-center py-16 text-gray-400 text-sm">Ticket not found</div></Layout>
<Layout>
<div className="text-center py-16 text-gray-400 text-sm">Ticket not found</div>
</Layout>
)
} }
const commentCount = ticket.comments?.length ?? 0
return ( return (
<Layout <Layout>
title={ticket.title} <div className="max-w-3xl">
action={ {/* Ticket header */}
authUser?.role === 'ADMIN' ? ( <div className="bg-white border border-gray-200 rounded-xl mb-4">
<button <div className="px-5 pt-5 pb-4">
onClick={deleteTicket} {/* ID + actions row */}
className="flex items-center gap-2 text-sm text-red-600 hover:text-red-800 border border-red-200 hover:border-red-400 px-3 py-1.5 rounded-lg transition-colors" <div className="flex items-start justify-between gap-4 mb-3">
>
<Trash2 size={14} />
Delete
</button>
) : undefined
}
>
<div className="max-w-3xl space-y-5">
{/* Ticket card */}
<div className="bg-white border border-gray-200 rounded-xl">
{/* Header bar */}
<div className="flex items-center justify-between px-5 py-3 border-b border-gray-100">
<div className="flex items-center gap-2">
<SeverityBadge severity={ticket.severity} />
<StatusBadge status={ticket.status} />
{!editing && (
<span className="text-xs text-gray-400">
{ticket.category.name} {ticket.type.name} {ticket.item.name}
</span>
)}
</div>
{!editing ? (
<button
onClick={startEdit}
className="flex items-center gap-1.5 text-xs text-gray-500 hover:text-gray-800 border border-gray-200 hover:border-gray-400 px-2.5 py-1 rounded-lg transition-colors"
>
<Pencil size={12} />
Edit
</button>
) : (
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<button <span className="font-mono text-xs font-semibold text-gray-400 bg-gray-100 px-2 py-0.5 rounded">
onClick={() => setEditing(false)} {ticket.displayId}
className="flex items-center gap-1.5 text-xs text-gray-500 hover:text-gray-700 border border-gray-200 px-2.5 py-1 rounded-lg transition-colors" </span>
> <SeverityBadge severity={ticket.severity} />
<X size={12} /> <StatusBadge status={ticket.status} />
Cancel </div>
</button> <div className="flex items-center gap-2">
<button {!editing ? (
onClick={saveEdit} <button
className="flex items-center gap-1.5 text-xs bg-blue-600 text-white px-2.5 py-1 rounded-lg hover:bg-blue-700 transition-colors" onClick={startEdit}
> className="flex items-center gap-1.5 text-xs text-gray-500 hover:text-gray-800 border border-gray-200 hover:border-gray-400 px-2.5 py-1 rounded-lg transition-colors"
<Check size={12} /> >
Save <Pencil size={12} />
</button> Edit
</button>
) : (
<>
<button
onClick={() => setEditing(false)}
className="flex items-center gap-1.5 text-xs text-gray-500 border border-gray-200 px-2.5 py-1 rounded-lg hover:bg-gray-50 transition-colors"
>
<X size={12} /> Cancel
</button>
<button
onClick={saveEdit}
className="flex items-center gap-1.5 text-xs bg-blue-600 text-white px-2.5 py-1 rounded-lg hover:bg-blue-700 transition-colors"
>
<Check size={12} /> Save
</button>
</>
)}
{authUser?.role === 'ADMIN' && (
<button
onClick={deleteTicket}
className="flex items-center gap-1.5 text-xs text-red-500 hover:text-red-700 border border-red-200 hover:border-red-400 px-2.5 py-1 rounded-lg transition-colors"
>
<Trash2 size={12} />
Delete
</button>
)}
</div>
</div>
{/* Title */}
{editing ? (
<input
type="text"
value={editForm.title}
onChange={(e) => setEditForm((f) => ({ ...f, title: e.target.value }))}
className={`${inputClass} text-lg font-semibold mb-3`}
/>
) : (
<h1 className="text-lg font-semibold text-gray-900 mb-3">{ticket.title}</h1>
)}
{/* CTI breadcrumb / edit */}
{editing ? (
<div className="mb-3">
<label className="block text-xs font-medium text-gray-500 mb-1">Routing (CTI)</label>
<CTISelect
value={{ categoryId: editForm.categoryId, typeId: editForm.typeId, itemId: editForm.itemId }}
onChange={(cti) => setEditForm((f) => ({ ...f, ...cti }))}
/>
</div>
) : (
<p className="text-xs text-gray-400 mb-3">
{ticket.category.name} {ticket.type.name} {ticket.item.name}
</p>
)}
{/* Status + Assignee quick controls (when not editing) */}
{!editing && (
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-xs font-medium text-gray-500 mb-1">Status</label>
<select
value={ticket.status}
onChange={(e) => updateStatus(e.target.value as TicketStatus)}
className={inputClass}
>
{STATUS_OPTIONS.map((s) => (
<option key={s.value} value={s.value}>{s.label}</option>
))}
</select>
</div>
<div>
<label className="block text-xs font-medium text-gray-500 mb-1">Assignee</label>
<select
value={ticket.assigneeId ?? ''}
onChange={(e) => updateAssignee(e.target.value)}
className={inputClass}
>
<option value="">Unassigned</option>
{users.filter((u) => u.role !== 'SERVICE').map((u) => (
<option key={u.id} value={u.id}>{u.displayName}</option>
))}
</select>
</div>
</div>
)}
{/* Severity + Assignee edit controls */}
{editing && (
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-xs font-medium text-gray-500 mb-1">Severity</label>
<select
value={editForm.severity}
onChange={(e) => setEditForm((f) => ({ ...f, severity: Number(e.target.value) }))}
className={inputClass}
>
<option value={1}>SEV 1 Critical</option>
<option value={2}>SEV 2 High</option>
<option value={3}>SEV 3 Medium</option>
<option value={4}>SEV 4 Low</option>
<option value={5}>SEV 5 Minimal</option>
</select>
</div>
<div>
<label className="block text-xs font-medium text-gray-500 mb-1">Assignee</label>
<select
value={editForm.assigneeId}
onChange={(e) => setEditForm((f) => ({ ...f, assigneeId: e.target.value }))}
className={inputClass}
>
<option value="">Unassigned</option>
{users.filter((u) => u.role !== 'SERVICE').map((u) => (
<option key={u.id} value={u.id}>{u.displayName}</option>
))}
</select>
</div>
</div> </div>
)} )}
</div> </div>
<div className="p-5 space-y-4"> {/* Meta footer */}
{editing ? ( <div className="px-5 py-2.5 bg-gray-50 rounded-b-xl border-t border-gray-100 flex items-center gap-5 text-xs text-gray-400">
<> <span>
<div> Opened by <strong className="text-gray-600">{ticket.createdBy.displayName}</strong>
<label className="block text-xs font-medium text-gray-500 mb-1">Title</label> </span>
<input
type="text"
value={editForm.title}
onChange={(e) => setEditForm((f) => ({ ...f, title: e.target.value }))}
className={inputClass}
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-500 mb-1">Overview</label>
<textarea
value={editForm.overview}
onChange={(e) => setEditForm((f) => ({ ...f, overview: e.target.value }))}
rows={4}
className={inputClass}
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-xs font-medium text-gray-500 mb-1">Severity</label>
<select
value={editForm.severity}
onChange={(e) => setEditForm((f) => ({ ...f, severity: Number(e.target.value) }))}
className={inputClass}
>
<option value={1}>SEV 1 Critical</option>
<option value={2}>SEV 2 High</option>
<option value={3}>SEV 3 Medium</option>
<option value={4}>SEV 4 Low</option>
<option value={5}>SEV 5 Minimal</option>
</select>
</div>
<div>
<label className="block text-xs font-medium text-gray-500 mb-1">Assignee</label>
<select
value={editForm.assigneeId}
onChange={(e) => setEditForm((f) => ({ ...f, assigneeId: e.target.value }))}
className={inputClass}
>
<option value="">Unassigned</option>
{users
.filter((u) => u.role !== 'SERVICE')
.map((u) => (
<option key={u.id} value={u.id}>
{u.displayName}
</option>
))}
</select>
</div>
</div>
<div>
<label className="block text-xs font-medium text-gray-500 mb-1">Routing (CTI)</label>
<CTISelect
value={{ categoryId: editForm.categoryId, typeId: editForm.typeId, itemId: editForm.itemId }}
onChange={(cti) => setEditForm((f) => ({ ...f, ...cti }))}
/>
</div>
</>
) : (
<>
<p className="text-sm text-gray-700 whitespace-pre-wrap">{ticket.overview}</p>
{/* Quick controls */}
<div className="grid grid-cols-2 gap-4 pt-2">
<div>
<label className="block text-xs font-medium text-gray-500 mb-1">Status</label>
<select
value={ticket.status}
onChange={(e) => updateStatus(e.target.value as TicketStatus)}
className={inputClass}
>
{STATUS_OPTIONS.map((s) => (
<option key={s.value} value={s.value}>
{s.label}
</option>
))}
</select>
</div>
<div>
<label className="block text-xs font-medium text-gray-500 mb-1">Assignee</label>
<select
value={ticket.assigneeId ?? ''}
onChange={(e) => updateAssignee(e.target.value)}
className={inputClass}
>
<option value="">Unassigned</option>
{users
.filter((u) => u.role !== 'SERVICE')
.map((u) => (
<option key={u.id} value={u.id}>
{u.displayName}
</option>
))}
</select>
</div>
</div>
</>
)}
</div>
{/* Metadata footer */}
<div className="px-5 py-3 bg-gray-50 rounded-b-xl border-t border-gray-100 flex items-center gap-6 text-xs text-gray-400">
<span>Created by <strong className="text-gray-600">{ticket.createdBy.displayName}</strong></span>
<span>{format(new Date(ticket.createdAt), 'MMM d, yyyy HH:mm')}</span> <span>{format(new Date(ticket.createdAt), 'MMM d, yyyy HH:mm')}</span>
{ticket.resolvedAt && ( {ticket.resolvedAt && (
<span>Resolved {format(new Date(ticket.resolvedAt), 'MMM d, yyyy')}</span> <span>Resolved {format(new Date(ticket.resolvedAt), 'MMM d, yyyy')}</span>
)} )}
<span>Updated {format(new Date(ticket.updatedAt), 'MMM d, yyyy HH:mm')}</span> <span className="ml-auto">
Updated {formatDistanceToNow(new Date(ticket.updatedAt), { addSuffix: true })}
</span>
</div> </div>
</div> </div>
{/* Comments */} {/* Tab bar */}
<div className="bg-white border border-gray-200 rounded-xl"> <div className="flex border-b border-gray-200 mb-4 bg-white rounded-t-xl border border-gray-200 border-b-0">
<div className="px-5 py-3 border-b border-gray-100"> {(
<h3 className="text-sm font-semibold text-gray-700"> [
Comments ({ticket.comments?.length ?? 0}) { key: 'overview', icon: FileText, label: 'Overview' },
</h3> { key: 'comments', icon: MessageSquare, label: `Comments${commentCount > 0 ? ` (${commentCount})` : ''}` },
</div> { key: 'audit', icon: ClipboardList, label: 'Audit Log' },
] as const
).map(({ key, icon: Icon, label }) => (
<button
key={key}
onClick={() => setTab(key)}
className={`flex items-center gap-2 px-5 py-3 text-sm font-medium border-b-2 transition-colors ${
tab === key
? 'border-blue-600 text-blue-600'
: 'border-transparent text-gray-500 hover:text-gray-800'
}`}
>
<Icon size={14} />
{label}
</button>
))}
</div>
{ticket.comments && ticket.comments.length > 0 ? ( {/* ── Overview tab ── */}
<div className="divide-y divide-gray-100"> {tab === 'overview' && (
{ticket.comments.map((comment) => ( <div className="bg-white border border-gray-200 rounded-xl p-5">
<div key={comment.id} className="px-5 py-4 group"> {editing ? (
<div className="flex items-start justify-between gap-3"> <textarea
<div className="flex-1"> value={editForm.overview}
<div className="flex items-center gap-2 mb-1"> onChange={(e) => setEditForm((f) => ({ ...f, overview: e.target.value }))}
<span className="text-xs font-medium text-gray-700"> rows={8}
{comment.author.displayName} className={inputClass}
</span> />
<span className="text-xs text-gray-400"> ) : (
{format(new Date(comment.createdAt), 'MMM d, yyyy HH:mm')} <div className="prose text-sm text-gray-700">
</span> <ReactMarkdown remarkPlugins={[remarkGfm]}>
{ticket.overview}
</ReactMarkdown>
</div>
)}
</div>
)}
{/* ── Comments tab ── */}
{tab === 'comments' && (
<div className="space-y-4">
{ticket.comments && ticket.comments.length > 0 ? (
ticket.comments.map((comment) => (
<div
key={comment.id}
className="bg-white border border-gray-200 rounded-xl p-5 group"
>
<div className="flex items-start gap-3">
<Avatar name={comment.author.displayName} size="md" />
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between mb-2">
<div className="flex items-center gap-2">
<span className="text-sm font-semibold text-gray-900">
{comment.author.displayName}
</span>
<span className="text-xs text-gray-400">
{formatDistanceToNow(new Date(comment.createdAt), { addSuffix: true })}
</span>
<span className="text-xs text-gray-300" title={format(new Date(comment.createdAt), 'MMM d, yyyy HH:mm')}>
· {format(new Date(comment.createdAt), 'MMM d, yyyy')}
</span>
</div>
{(comment.authorId === authUser?.id || authUser?.role === 'ADMIN') && (
<button
onClick={() => deleteComment(comment.id)}
className="opacity-0 group-hover:opacity-100 text-gray-300 hover:text-red-500 transition-all"
>
<Trash2 size={13} />
</button>
)}
</div>
<div className="prose text-sm text-gray-700">
<ReactMarkdown remarkPlugins={[remarkGfm]}>
{comment.body}
</ReactMarkdown>
</div> </div>
<p className="text-sm text-gray-700 whitespace-pre-wrap">{comment.body}</p>
</div> </div>
{(comment.authorId === authUser?.id || authUser?.role === 'ADMIN') && (
<button
onClick={() => deleteComment(comment.id)}
className="opacity-0 group-hover:opacity-100 text-gray-300 hover:text-red-500 transition-all flex-shrink-0"
>
<Trash2 size={13} />
</button>
)}
</div> </div>
</div> </div>
))} ))
</div> ) : (
) : ( <div className="bg-white border border-gray-200 rounded-xl px-5 py-10 text-center text-sm text-gray-400">
<div className="px-5 py-8 text-center text-xs text-gray-400">No comments yet</div> No comments yet
)} </div>
)}
{/* Comment form */} {/* Comment composer */}
<form onSubmit={submitComment} className="px-5 py-4 border-t border-gray-100"> <div className="bg-white border border-gray-200 rounded-xl">
<textarea <div className="flex items-center gap-3 px-4 pt-4">
ref={commentRef} <Avatar name={authUser?.displayName ?? '?'} size="md" />
value={commentBody} <div className="flex gap-3 border-b border-gray-100 pb-0 flex-1">
onChange={(e) => setCommentBody(e.target.value)} <button
placeholder="Add a comment..." onClick={() => setPreview(false)}
rows={3} className={`text-xs pb-2 border-b-2 transition-colors ${
className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none" !preview ? 'border-blue-600 text-blue-600' : 'border-transparent text-gray-400 hover:text-gray-600'
onKeyDown={(e) => { }`}
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { >
e.preventDefault() Write
submitComment(e as unknown as React.FormEvent) </button>
} <button
}} onClick={() => setPreview(true)}
/> className={`text-xs pb-2 border-b-2 transition-colors ${
<div className="flex justify-between items-center mt-2"> preview ? 'border-blue-600 text-blue-600' : 'border-transparent text-gray-400 hover:text-gray-600'
<span className="text-xs text-gray-400">Ctrl+Enter to submit</span> }`}
<button >
type="submit" Preview
disabled={submittingComment || !commentBody.trim()} </button>
className="flex items-center gap-2 px-3 py-1.5 bg-blue-600 text-white text-xs rounded-lg hover:bg-blue-700 disabled:opacity-50 transition-colors" </div>
> </div>
<Send size={12} />
Comment <form onSubmit={submitComment} className="p-4">
</button> {preview ? (
<div className="prose text-sm text-gray-700 min-h-[80px] px-1">
{commentBody.trim() ? (
<ReactMarkdown remarkPlugins={[remarkGfm]}>{commentBody}</ReactMarkdown>
) : (
<span className="text-gray-400 italic">Nothing to preview</span>
)}
</div>
) : (
<textarea
value={commentBody}
onChange={(e) => setCommentBody(e.target.value)}
placeholder="Leave a comment… Markdown supported"
rows={4}
className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"
onKeyDown={(e) => {
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
e.preventDefault()
submitComment(e as unknown as React.FormEvent)
}
}}
/>
)}
<div className="flex justify-between items-center mt-3">
<span className="text-xs text-gray-400">Markdown supported · Ctrl+Enter to submit</span>
<button
type="submit"
disabled={submittingComment || !commentBody.trim()}
className="flex items-center gap-2 px-4 py-1.5 bg-blue-600 text-white text-xs rounded-lg hover:bg-blue-700 disabled:opacity-50 transition-colors"
>
<Send size={12} />
Comment
</button>
</div>
</form>
</div> </div>
</form> </div>
</div> )}
{/* ── Audit Log tab ── */}
{tab === 'audit' && (
<div className="bg-white border border-gray-200 rounded-xl divide-y divide-gray-100">
{auditLogs.length === 0 ? (
<div className="px-5 py-10 text-center text-sm text-gray-400">No audit entries</div>
) : (
auditLogs.map((log, i) => (
<div key={log.id} className="flex items-start gap-4 px-5 py-4">
{/* Timeline dot */}
<div className="flex flex-col items-center flex-shrink-0 pt-0.5">
<div
className={`w-2.5 h-2.5 rounded-full ${AUDIT_COLORS[log.action] ?? 'bg-gray-400'}`}
/>
{i < auditLogs.length - 1 && (
<div className="w-px flex-1 bg-gray-100 mt-1" style={{ minHeight: '16px' }} />
)}
</div>
<div className="flex-1 min-w-0 pb-1">
<div className="flex items-baseline justify-between gap-3">
<span className="text-sm text-gray-800">
<strong className="font-medium">{log.user.displayName}</strong>
{' '}{AUDIT_LABELS[log.action]?.toLowerCase() ?? log.action.toLowerCase()}
{log.detail && (
<span className="text-gray-500"> {log.detail}</span>
)}
</span>
<span
className="text-xs text-gray-400 flex-shrink-0"
title={format(new Date(log.createdAt), 'MMM d, yyyy HH:mm:ss')}
>
{formatDistanceToNow(new Date(log.createdAt), { addSuffix: true })}
</span>
</div>
</div>
</div>
))
)}
</div>
)}
</div> </div>
</Layout> </Layout>
) )

View File

@@ -39,8 +39,19 @@ export interface Comment {
createdAt: string createdAt: string
} }
export interface AuditLog {
id: string
ticketId: string
userId: string
action: string
detail: string | null
createdAt: string
user: Pick<User, 'id' | 'username' | 'displayName'>
}
export interface Ticket { export interface Ticket {
id: string id: string
displayId: string
title: string title: string
overview: string overview: string
severity: number severity: number

View File

@@ -31,9 +31,10 @@ model User {
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
assignedTickets Ticket[] @relation("AssignedTickets") assignedTickets Ticket[] @relation("AssignedTickets")
createdTickets Ticket[] @relation("CreatedTickets") createdTickets Ticket[] @relation("CreatedTickets")
comments Comment[] comments Comment[]
auditLogs AuditLog[]
} }
model Category { model Category {
@@ -65,27 +66,29 @@ model Item {
} }
model Ticket { model Ticket {
id String @id @default(cuid()) id String @id @default(cuid())
title String displayId String @unique
overview String title String
severity Int overview String
status TicketStatus @default(OPEN) severity Int
categoryId String status TicketStatus @default(OPEN)
typeId String categoryId String
itemId String typeId String
assigneeId String? itemId String
assigneeId String?
createdById String createdById String
resolvedAt DateTime? resolvedAt DateTime?
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
category Category @relation(fields: [categoryId], references: [id]) category Category @relation(fields: [categoryId], references: [id])
type Type @relation(fields: [typeId], references: [id]) type Type @relation(fields: [typeId], references: [id])
item Item @relation(fields: [itemId], references: [id]) item Item @relation(fields: [itemId], references: [id])
assignee User? @relation("AssignedTickets", fields: [assigneeId], references: [id]) assignee User? @relation("AssignedTickets", fields: [assigneeId], references: [id])
createdBy User @relation("CreatedTickets", fields: [createdById], references: [id]) createdBy User @relation("CreatedTickets", fields: [createdById], references: [id])
comments Comment[] comments Comment[]
auditLogs AuditLog[]
} }
model Comment { model Comment {
@@ -98,3 +101,15 @@ model Comment {
ticket Ticket @relation(fields: [ticketId], references: [id], onDelete: Cascade) ticket Ticket @relation(fields: [ticketId], references: [id], onDelete: Cascade)
author User @relation(fields: [authorId], references: [id]) author User @relation(fields: [authorId], references: [id])
} }
model AuditLog {
id String @id @default(cuid())
ticketId String
userId String
action String
detail String?
createdAt DateTime @default(now())
ticket Ticket @relation(fields: [ticketId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id])
}

View File

@@ -3,7 +3,6 @@ import { z } from 'zod'
import prisma from '../lib/prisma' import prisma from '../lib/prisma'
import { AuthRequest } from '../middleware/auth' import { AuthRequest } from '../middleware/auth'
// mergeParams: true so req.params.ticketId is accessible from the parent router
const router = Router({ mergeParams: true }) const router = Router({ mergeParams: true })
const commentSchema = z.object({ const commentSchema = z.object({
@@ -12,22 +11,22 @@ const commentSchema = z.object({
router.post('/', async (req: AuthRequest, res) => { router.post('/', async (req: AuthRequest, res) => {
const { body } = commentSchema.parse(req.body) const { body } = commentSchema.parse(req.body)
const ticketId = (req.params as Record<string, string>).ticketId
const ticket = await prisma.ticket.findUnique({ const ticket = await prisma.ticket.findFirst({
where: { id: (req.params as any).ticketId }, where: { OR: [{ id: ticketId }, { displayId: ticketId }] },
}) })
if (!ticket) return res.status(404).json({ error: 'Ticket not found' }) if (!ticket) return res.status(404).json({ error: 'Ticket not found' })
const comment = await prisma.comment.create({ const [comment] = await prisma.$transaction([
data: { prisma.comment.create({
body, data: { body, ticketId: ticket.id, authorId: req.user!.id },
ticketId: (req.params as any).ticketId, include: { author: { select: { id: true, username: true, displayName: true } } },
authorId: req.user!.id, }),
}, prisma.auditLog.create({
include: { data: { ticketId: ticket.id, userId: req.user!.id, action: 'COMMENT_ADDED' },
author: { select: { id: true, username: true, displayName: true } }, }),
}, ])
})
res.status(201).json(comment) res.status(201).json(comment)
}) })
@@ -42,7 +41,13 @@ router.delete('/:commentId', async (req: AuthRequest, res) => {
return res.status(403).json({ error: 'Not allowed' }) return res.status(403).json({ error: 'Not allowed' })
} }
await prisma.comment.delete({ where: { id: req.params.commentId } }) await prisma.$transaction([
prisma.comment.delete({ where: { id: req.params.commentId } }),
prisma.auditLog.create({
data: { ticketId: comment.ticketId, userId: req.user!.id, action: 'COMMENT_DELETED' },
}),
])
res.status(204).send() res.status(204).send()
}) })

View File

@@ -18,6 +18,29 @@ const ticketInclude = {
}, },
} as const } as const
const STATUS_LABELS: Record<string, string> = {
OPEN: 'Open',
IN_PROGRESS: 'In Progress',
RESOLVED: 'Resolved',
CLOSED: 'Closed',
}
async function generateDisplayId(): Promise<string> {
while (true) {
const num = Math.floor(Math.random() * 900_000_000) + 100_000_000
const displayId = `V${num}`
const exists = await prisma.ticket.findUnique({ where: { displayId } })
if (!exists) return displayId
}
}
// Look up ticket by internal id or displayId
function findByIdOrDisplay(idOrDisplay: string) {
return prisma.ticket.findFirst({
where: { OR: [{ id: idOrDisplay }, { displayId: idOrDisplay }] },
})
}
const createSchema = z.object({ const createSchema = z.object({
title: z.string().min(1).max(255), title: z.string().min(1).max(255),
overview: z.string().min(1), overview: z.string().min(1),
@@ -46,7 +69,7 @@ router.use('/:ticketId/comments', commentRouter)
router.get('/', async (req: AuthRequest, res) => { router.get('/', async (req: AuthRequest, res) => {
const { status, severity, assigneeId, categoryId, search } = req.query const { status, severity, assigneeId, categoryId, search } = req.query
const where: Record<string, any> = {} const where: Record<string, unknown> = {}
if (status) where.status = status if (status) where.status = status
if (severity) where.severity = Number(severity) if (severity) where.severity = Number(severity)
if (assigneeId) where.assigneeId = assigneeId if (assigneeId) where.assigneeId = assigneeId
@@ -55,6 +78,7 @@ router.get('/', async (req: AuthRequest, res) => {
where.OR = [ where.OR = [
{ title: { contains: search as string, mode: 'insensitive' } }, { title: { contains: search as string, mode: 'insensitive' } },
{ overview: { contains: search as string, mode: 'insensitive' } }, { overview: { contains: search as string, mode: 'insensitive' } },
{ displayId: { contains: search as string, mode: 'insensitive' } },
] ]
} }
@@ -76,21 +100,41 @@ router.get('/', async (req: AuthRequest, res) => {
// GET /api/tickets/:id // GET /api/tickets/:id
router.get('/:id', async (req, res) => { router.get('/:id', async (req, res) => {
const ticket = await prisma.ticket.findUnique({ const ticket = await prisma.ticket.findFirst({
where: { id: req.params.id }, where: { OR: [{ id: req.params.id }, { displayId: req.params.id }] },
include: ticketInclude, include: ticketInclude,
}) })
if (!ticket) return res.status(404).json({ error: 'Ticket not found' }) if (!ticket) return res.status(404).json({ error: 'Ticket not found' })
res.json(ticket) res.json(ticket)
}) })
// GET /api/tickets/:id/audit
router.get('/:id/audit', async (req, res) => {
const ticket = await findByIdOrDisplay(req.params.id)
if (!ticket) return res.status(404).json({ error: 'Ticket not found' })
const logs = await prisma.auditLog.findMany({
where: { ticketId: ticket.id },
include: { user: { select: { id: true, username: true, displayName: true } } },
orderBy: { createdAt: 'desc' },
})
res.json(logs)
})
// POST /api/tickets // POST /api/tickets
router.post('/', async (req: AuthRequest, res) => { router.post('/', async (req: AuthRequest, res) => {
const data = createSchema.parse(req.body) const data = createSchema.parse(req.body)
const displayId = await generateDisplayId()
const ticket = await prisma.ticket.create({ const ticket = await prisma.$transaction(async (tx) => {
data: { ...data, createdById: req.user!.id }, const created = await tx.ticket.create({
include: ticketInclude, data: { displayId, ...data, createdById: req.user!.id },
})
await tx.auditLog.create({
data: { ticketId: created.id, userId: req.user!.id, action: 'CREATED' },
})
return tx.ticket.findUnique({ where: { id: created.id }, include: ticketInclude })
}) })
res.status(201).json(ticket) res.status(201).json(ticket)
@@ -100,22 +144,103 @@ router.post('/', async (req: AuthRequest, res) => {
router.patch('/:id', async (req: AuthRequest, res) => { router.patch('/:id', async (req: AuthRequest, res) => {
const data = updateSchema.parse(req.body) const data = updateSchema.parse(req.body)
const existing = await prisma.ticket.findUnique({ where: { id: req.params.id } }) const existing = await prisma.ticket.findFirst({
where: { OR: [{ id: req.params.id }, { displayId: req.params.id }] },
include: {
category: true,
type: true,
item: true,
assignee: { select: { displayName: true } },
},
})
if (!existing) return res.status(404).json({ error: 'Ticket not found' }) if (!existing) return res.status(404).json({ error: 'Ticket not found' })
const update: Record<string, any> = { ...data } // Build audit entries
const auditEntries: { action: string; detail?: string }[] = []
if (data.status && data.status !== existing.status) {
auditEntries.push({
action: 'STATUS_CHANGED',
detail: `${STATUS_LABELS[existing.status]}${STATUS_LABELS[data.status]}`,
})
}
if ('assigneeId' in data && data.assigneeId !== existing.assigneeId) {
const newAssignee = data.assigneeId
? await prisma.user.findUnique({
where: { id: data.assigneeId },
select: { displayName: true },
})
: null
auditEntries.push({
action: 'ASSIGNEE_CHANGED',
detail: `${existing.assignee?.displayName ?? 'Unassigned'}${newAssignee?.displayName ?? 'Unassigned'}`,
})
}
if (data.severity && data.severity !== existing.severity) {
auditEntries.push({
action: 'SEVERITY_CHANGED',
detail: `SEV ${existing.severity} → SEV ${data.severity}`,
})
}
// CTI rerouting — only log if any CTI field actually changed
const ctiChanged =
(data.categoryId && data.categoryId !== existing.categoryId) ||
(data.typeId && data.typeId !== existing.typeId) ||
(data.itemId && data.itemId !== existing.itemId)
if (ctiChanged) {
const [newCat, newType, newItem] = await Promise.all([
data.categoryId && data.categoryId !== existing.categoryId
? prisma.category.findUnique({ where: { id: data.categoryId } })
: Promise.resolve(existing.category),
data.typeId && data.typeId !== existing.typeId
? prisma.type.findUnique({ where: { id: data.typeId } })
: Promise.resolve(existing.type),
data.itemId && data.itemId !== existing.itemId
? prisma.item.findUnique({ where: { id: data.itemId } })
: Promise.resolve(existing.item),
])
auditEntries.push({
action: 'REROUTED',
detail: `${existing.category.name} ${existing.type.name} ${existing.item.name}${newCat?.name} ${newType?.name} ${newItem?.name}`,
})
}
if (data.title && data.title !== existing.title) {
auditEntries.push({ action: 'TITLE_CHANGED', detail: data.title })
}
if (data.overview && data.overview !== existing.overview) {
auditEntries.push({ action: 'OVERVIEW_CHANGED' })
}
// Handle resolvedAt tracking
const update: Record<string, unknown> = { ...data }
if (data.status === 'RESOLVED' && existing.status !== 'RESOLVED') { if (data.status === 'RESOLVED' && existing.status !== 'RESOLVED') {
update.resolvedAt = new Date() update.resolvedAt = new Date()
} else if (data.status && data.status !== 'RESOLVED' && existing.status === 'RESOLVED') { } else if (data.status && data.status !== 'RESOLVED' && existing.status === 'RESOLVED') {
// Re-opening a resolved ticket resets the 2-week auto-close timer
update.resolvedAt = null update.resolvedAt = null
} }
const ticket = await prisma.ticket.update({ const ticket = await prisma.$transaction(async (tx) => {
where: { id: req.params.id }, const updated = await tx.ticket.update({
data: update, where: { id: existing.id },
include: ticketInclude, data: update,
})
if (auditEntries.length > 0) {
await tx.auditLog.createMany({
data: auditEntries.map((e) => ({
ticketId: existing.id,
userId: req.user!.id,
action: e.action,
detail: e.detail ?? null,
})),
})
}
return tx.ticket.findUnique({ where: { id: updated.id }, include: ticketInclude })
}) })
res.json(ticket) res.json(ticket)
@@ -123,7 +248,9 @@ router.patch('/:id', async (req: AuthRequest, res) => {
// DELETE /api/tickets/:id — admin only // DELETE /api/tickets/:id — admin only
router.delete('/:id', requireAdmin, async (req, res) => { router.delete('/:id', requireAdmin, async (req, res) => {
await prisma.ticket.delete({ where: { id: req.params.id } }) const ticket = await findByIdOrDisplay(req.params.id)
if (!ticket) return res.status(404).json({ error: 'Ticket not found' })
await prisma.ticket.delete({ where: { id: ticket.id } })
res.status(204).send() res.status(204).send()
}) })