Complete Support Module Implementation & Refinements

This commit is contained in:
CycroftX
2026-02-09 22:32:51 +05:30
parent badde58bfa
commit 514508df89
5 changed files with 384 additions and 77 deletions

View File

@@ -33,11 +33,11 @@ function MetricCard({ title, value, trend, icon: Icon, iconColor, iconBg }: Metr
</div>
<div className="flex flex-col">
<span className="text-xs font-semibold text-muted-foreground uppercase tracking-wider">{title}</span>
<div className="flex items-center gap-2">
<div className="flex flex-col items-start gap-1">
<span className="text-2xl font-bold text-foreground">{value}</span>
{trend !== undefined && (
<div className={cn(
'flex items-center gap-0.5 text-xs font-semibold px-1.5 py-0.5 rounded-full',
'flex items-center gap-0.5 text-[10px] font-semibold px-1.5 py-0.5 rounded-full w-fit',
trend >= 0 ? 'bg-emerald-100 text-emerald-700' : 'bg-red-100 text-red-700'
)}>
{trend >= 0 ? (

View File

@@ -21,20 +21,22 @@ import {
SelectValue,
} from '@/components/ui/select';
import { Checkbox } from '@/components/ui/checkbox';
import { Loader2, Ticket, Phone, Clock, AlertTriangle } from 'lucide-react';
import { createEscalationTicket } from '@/lib/actions/userActions';
import { Loader2, Ticket, Phone, AlertTriangle } from 'lucide-react';
import { toast } from 'sonner';
import { cn } from '@/lib/utils';
import { createEscalation } from '@/lib/actions/support';
import { SupportTicketPriority, SupportTicketType } from '@/lib/validations/support';
interface EscalationFormProps {
open: boolean;
onOpenChange: (open: boolean) => void;
userId: string;
userName?: string; // Optional for display
userName?: string;
onSuccess?: (ticket: any) => void;
}
const TICKET_TYPES = ['Refund', 'Payment', 'Account access', 'Fraud', 'Event issue', 'Other'];
const PRIORITIES = ['Low', 'Normal', 'High', 'Urgent'];
const PRIORITIES = Object.values(SupportTicketPriority);
const TICKET_TYPES = Object.values(SupportTicketType);
export function EscalationForm({
open,
@@ -43,8 +45,10 @@ export function EscalationForm({
userName
}: EscalationFormProps) {
const [isPending, startTransition] = useTransition();
const [type, setType] = useState('');
const [priority, setPriority] = useState('Normal');
// Form State
const [type, setType] = useState<string>('');
const [priority, setPriority] = useState<string>('Normal');
const [subject, setSubject] = useState('');
const [description, setDescription] = useState('');
const [callbackRequired, setCallbackRequired] = useState(false);
@@ -52,30 +56,47 @@ export function EscalationForm({
const [assigneeId, setAssigneeId] = useState('');
const handleSubmit = () => {
if (!type || !subject || !description) {
toast.error("Please fill in all required fields");
// Basic Client Validation
if (!subject || !description || !type) {
toast.error("Please fill in all required fields.");
return;
}
if (priority === 'Critical' && description.length < 20) {
toast.error("Critical tickets require a detailed description (>20 chars).");
return;
}
if (callbackRequired && (!callbackPhone || callbackPhone.length < 5)) {
toast.error("Phone number required for callback.");
return;
}
startTransition(async () => {
const result = await createEscalationTicket({
const result = await createEscalation({
userId,
// Cast to specific enums as we're using string state for UI simplicity
type: type as any,
priority: priority as any,
subject,
description,
callbackRequired,
callbackPhone: callbackRequired ? callbackPhone : undefined,
assigneeId: assigneeId || undefined,
});
assigneeId: (assigneeId && assigneeId !== 'auto') ? assigneeId : undefined,
}) as any; // Type assertion for mocked return
if (result.success) {
toast.success(result.message);
onOpenChange(false);
// Reset form
setSubject('');
setDescription('');
setCallbackRequired(false);
if (onSuccess && result.ticket) {
onSuccess(result.ticket);
}
} else {
toast.error(result.message);
toast.error(result.message || "Failed to create ticket.");
}
});
};
@@ -84,19 +105,20 @@ export function EscalationForm({
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[600px]">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<DialogTitle className="flex items-center gap-2 text-xl">
<Ticket className="h-5 w-5 text-primary" />
Create Escalation Ticket
</DialogTitle>
<DialogDescription>
Raise a new internal support ticket or escalation.
Raise a new internal support ticket or escalation for {userName || 'User'}.
</DialogDescription>
</DialogHeader>
<div className="py-4 space-y-5">
{/* Top Row: Type & Priority */}
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Category <span className="text-red-500">*</span></Label>
<Label>Issue Type <span className="text-red-500">*</span></Label>
<Select value={type} onValueChange={setType}>
<SelectTrigger>
<SelectValue placeholder="Select type..." />
@@ -109,37 +131,46 @@ export function EscalationForm({
</Select>
</div>
<div className="space-y-2">
<Label>Priority <span className="text-red-500">*</span></Label>
<Select value={priority} onValueChange={setPriority}>
<SelectTrigger className={cn(
priority === 'High' ? 'text-orange-600 font-medium' :
priority === 'Urgent' ? 'text-red-600 font-bold' : ''
)}>
<SelectValue placeholder="Priority" />
</SelectTrigger>
<SelectContent>
{PRIORITIES.map(p => (
<SelectItem key={p} value={p} className={
p === 'High' ? 'text-orange-600' :
p === 'Urgent' ? 'text-red-600 font-bold' : ''
}>
{p} {p === 'Urgent' && '🔥'}
</SelectItem>
))}
</SelectContent>
</Select>
<Label>Priority / SLA <span className="text-red-500">*</span></Label>
<div className="flex flex-wrap gap-2 mt-1">
{PRIORITIES.map((p) => (
<button
key={p}
onClick={() => setPriority(p)}
className={cn(
"text-xs px-3 py-1.5 rounded-full border transition-all",
priority === p
? p === 'Critical' ? "bg-red-600 text-white border-red-600 font-bold shadow-red-200 shadow-md"
: p === 'High' ? "bg-orange-500 text-white border-orange-500 font-medium"
: p === 'Medium' || p === 'Normal' ? "bg-blue-500 text-white border-blue-500"
: "bg-slate-800 text-white border-slate-800"
: "bg-transparent text-muted-foreground border-border hover:bg-secondary/50"
)}
>
{p === 'Critical' && '🔥 '}
{p}
</button>
))}
</div>
<p className="text-[10px] text-muted-foreground mt-1">
{priority === 'Critical' ? 'SLA: 1 Hour (Triggers PagerDuty)' :
priority === 'High' ? 'SLA: 4 Hours' :
priority === 'Medium' || priority === 'Normal' ? 'SLA: 24 Hours' : 'SLA: 48 Hours'}
</p>
</div>
</div>
{/* Subject */}
<div className="space-y-2">
<Label>Subject <span className="text-red-500">*</span></Label>
<Input
placeholder="Brief summary of the issue..."
placeholder="Brief summary (e.g., Refund Request for Order #123)"
value={subject}
onChange={(e) => setSubject(e.target.value)}
/>
</div>
{/* Description */}
<div className="space-y-2">
<Label>Description <span className="text-red-500">*</span></Label>
<Textarea
@@ -148,8 +179,15 @@ export function EscalationForm({
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
{priority === 'Critical' && (
<p className="text-[11px] text-red-500 flex items-center gap-1">
<AlertTriangle className="h-3 w-3" />
Critical tickets require detailed justification ({description.length}/20 chars).
</p>
)}
</div>
{/* Callback Option */}
<div className="bg-secondary/10 p-4 rounded-lg border border-border/50">
<div className="flex items-center justify-between mb-4">
<div className="flex items-center space-x-2">
@@ -167,7 +205,7 @@ export function EscalationForm({
{callbackRequired && (
<div className="grid grid-cols-2 gap-4 animate-in slide-in-from-top-2">
<div className="space-y-1.5">
<Label className="text-xs">Callback Number</Label>
<Label className="text-xs">Callback Number <span className="text-red-500">*</span></Label>
<Input
placeholder="+1 (555) 000-0000"
className="h-8"
@@ -182,7 +220,7 @@ export function EscalationForm({
<SelectValue placeholder="ASAP" />
</SelectTrigger>
<SelectContent>
<SelectItem value="asap">ASAP</SelectItem>
<SelectItem value="asap">ASAP (Urgent)</SelectItem>
<SelectItem value="morning">Morning (9am - 12pm)</SelectItem>
<SelectItem value="afternoon">Afternoon (1pm - 5pm)</SelectItem>
</SelectContent>
@@ -192,17 +230,19 @@ export function EscalationForm({
)}
</div>
{/* Assignee */}
<div className="space-y-2">
<Label>Assign To (Optional)</Label>
<Select value={assigneeId} onValueChange={setAssigneeId}>
<SelectTrigger>
<SelectValue placeholder="Auto-assign" />
<SelectValue placeholder="Auto-route based on rules" />
</SelectTrigger>
<SelectContent>
<SelectItem value="">Auto-assign (Roost)</SelectItem>
<SelectItem value="tier2">Tier 2 Support</SelectItem>
<SelectItem value="auto">Auto-route (Default)</SelectItem>
<SelectItem value="finance">Finance Team</SelectItem>
<SelectItem value="fraud">Fraud & Risk</SelectItem>
<SelectItem value="tier2">Tier 2 Support</SelectItem>
<SelectItem value="fraud">Fraud & Risk Team</SelectItem>
<SelectItem value="tech">Engineering / Tech</SelectItem>
</SelectContent>
</Select>
</div>
@@ -210,9 +250,13 @@ export function EscalationForm({
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
<Button onClick={handleSubmit} disabled={isPending}>
<Button
onClick={handleSubmit}
disabled={isPending}
className={priority === 'Critical' ? "bg-red-600 hover:bg-red-700" : ""}
>
{isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Create Ticket
{priority === 'Critical' ? 'Escalate Immediately' : 'Create Ticket'}
</Button>
</DialogFooter>
</DialogContent>

View File

@@ -1,10 +1,9 @@
'use client';
import { useTransition, useState } from 'react';
import { useState } from 'react';
import type { User } from '@/lib/types/user';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { EscalationForm } from '../dialogs/EscalationForm';
import {
MessageSquare,
@@ -12,58 +11,175 @@ import {
Plus,
UserCircle2,
Headphones,
Loader2
Loader2,
Phone,
AlertTriangle,
Shield,
} from 'lucide-react';
import { toast } from 'sonner';
import { cn } from '@/lib/utils';
import { formatDistanceToNow } from 'date-fns';
interface SupportTabProps {
user: User;
}
// Mock Data for demonstration matching the "Ticket List" requirements
const MOCK_TICKETS = [
{
id: 'tkt-001',
type: 'Refund',
subject: 'Refund requested for "Tech Summit"',
priority: 'High',
status: 'Open',
callbackRequired: true,
createdAt: new Date(Date.now() - 1000 * 60 * 60 * 2).toISOString(), // 2 hours ago
author: 'User',
},
{
id: 'tkt-002',
type: 'Technical',
subject: 'Login issue on mobile app',
priority: 'Normal',
status: 'Resolved',
callbackRequired: false,
createdAt: new Date(Date.now() - 1000 * 60 * 60 * 24 * 3).toISOString(), // 3 days ago
author: 'User',
},
{
id: 'fraud-001',
type: 'Fraud Alert',
subject: 'Suspicious login attempt detected',
priority: 'Critical',
status: 'Closed',
callbackRequired: false,
createdAt: new Date(Date.now() - 1000 * 60 * 60 * 24 * 5).toISOString(), // 5 days ago
author: 'System',
}
];
export function SupportTab({ user }: SupportTabProps) {
const [createDialogOpen, setCreateDialogOpen] = useState(false);
const [tickets, setTickets] = useState(MOCK_TICKETS);
// Filter state could go here in future
// const [filter, setFilter] = useState('all');
const getPriorityColor = (priority: string) => {
switch (priority) {
case 'Critical': return 'bg-red-100 text-red-700 border-red-200';
case 'High': return 'bg-orange-100 text-orange-700 border-orange-200';
case 'Normal': return 'bg-blue-50 text-blue-700 border-blue-200';
default: return 'bg-slate-100 text-slate-600 border-slate-200';
}
};
const getTypeBadge = (type: string) => {
switch (type) {
case 'Refund': return <Badge variant="outline" className="text-xs bg-emerald-50 text-emerald-700 border-emerald-200">Refund</Badge>;
case 'Technical': return <Badge variant="outline" className="text-xs bg-indigo-50 text-indigo-700 border-indigo-200">Tech</Badge>;
case 'Fraud Alert': return <Badge variant="outline" className="text-xs bg-red-50 text-red-700 border-red-200">Fraud</Badge>;
default: return <Badge variant="outline" className="text-xs">{type}</Badge>;
}
};
const handleTicketCreated = (newTicket: any) => {
setTickets([newTicket, ...tickets]);
};
const handleViewAllHistory = () => {
// In a real app, this might navigate to a dedicated page or load more items.
// For this mock, we'll simulate loading more history.
toast.info("Loading full ticket history...", {
duration: 1500,
});
// Simulate expanded view (optional enhancement)
// setLimit(50);
};
return (
<div className="space-y-4">
<div className="space-y-6">
<div className="flex items-center justify-between">
<h3 className="text-sm font-semibold">Communication Timeline</h3>
<div>
<h3 className="text-base font-semibold">Support & Escalations</h3>
<p className="text-xs text-muted-foreground">Manage tickets and communication history.</p>
</div>
<div className="flex gap-2">
<Button variant="outline" size="sm" onClick={handleViewAllHistory}>View All History</Button>
<Button size="sm" onClick={() => setCreateDialogOpen(true)}>
<Plus className="mr-2 h-3.5 w-3.5" />
Create Escalation
</Button>
</div>
<EscalationForm
userId={user.id}
userName={user.name}
open={createDialogOpen}
onOpenChange={setCreateDialogOpen}
onSuccess={handleTicketCreated}
/>
</div>
{/* Timeline Stream */}
<div className="relative pl-4 border-l-2 border-border/50 space-y-6">
{[
{ id: 1, type: 'ticket', title: 'Refund requested for "Tech Summit"', status: 'Open', date: '2 hours ago', icon: Headphones, color: 'text-blue-600 bg-blue-50' },
{ id: 2, type: 'email', title: 'Sent: "Your tickets are ready!"', status: 'Delivered', date: 'Yesterday', icon: Mail, color: 'text-slate-600 bg-slate-50' },
{ id: 3, type: 'ticket', title: 'Login issue reported', status: 'Resolved', date: '3 days ago', icon: MessageSquare, color: 'text-emerald-600 bg-emerald-50' },
].map((item) => (
<div key={item.id} className="relative">
<div className={`absolute -left-[25px] top-0 h-8 w-8 rounded-full border-2 border-background flex items-center justify-center ${item.color}`}>
<item.icon className="h-4 w-4" />
</div>
<div className="bg-card border rounded-lg p-3 shadow-sm hover:shadow-md transition-shadow">
<div className="flex justify-between items-start">
<h4 className="text-sm font-medium">{item.title}</h4>
<span className="text-xs text-muted-foreground whitespace-nowrap">{item.date}</span>
{/* Ticket List / Timeline */}
<div className="space-y-4">
{tickets.length > 0 ? (
<div className="grid gap-3">
{tickets.map((ticket) => (
<div
key={ticket.id}
className="group flex items-center justify-between p-4 rounded-lg border bg-card hover:bg-secondary/5 transition-colors cursor-pointer"
>
<div className="flex items-start gap-4">
<div className={cn(
"mt-1 p-2 rounded-full",
ticket.priority === 'Critical' ? "bg-red-100 text-red-600" :
ticket.type === 'Refund' ? "bg-emerald-100 text-emerald-600" : "bg-slate-100 text-slate-600"
)}>
{ticket.priority === 'Critical' ? <AlertTriangle className="h-4 w-4" /> :
ticket.type === 'Fraud Alert' ? <Shield className="h-4 w-4" /> :
<Headphones className="h-4 w-4" />}
</div>
<div>
<div className="flex items-center gap-2">
<span className="font-medium text-sm text-foreground">{ticket.subject}</span>
<span className="text-xs text-muted-foreground font-mono">#{ticket.id}</span>
</div>
<div className="flex items-center gap-2 mt-1.5">
{getTypeBadge(ticket.type)}
<Badge variant="outline" className={cn("text-[10px] px-2 py-0", getPriorityColor(ticket.priority))}>
{ticket.priority}
</Badge>
<span className="text-xs text-muted-foreground"> {ticket.status}</span>
<span className="text-xs text-muted-foreground"> {formatDistanceToNow(new Date(ticket.createdAt), { addSuffix: true })}</span>
</div>
</div>
</div>
<div className="flex items-center gap-4">
{ticket.callbackRequired && (
<div className="flex items-center gap-1.5 text-orange-600 bg-orange-50 px-2 py-1 rounded-md border border-orange-100">
<Phone className="h-3 w-3" />
<span className="text-[10px] font-medium">Callback Requested</span>
</div>
)}
<Button variant="ghost" size="sm" className="hidden group-hover:flex">
View Details
</Button>
</div>
</div>
<div className="mt-1 flex items-center gap-2">
<span className="text-xs font-medium px-2 py-0.5 rounded-full bg-secondary/50 text-secondary-foreground">
{item.type === 'ticket' ? 'Ticket #1234' : 'Email System'}
</span>
<span className="text-xs text-muted-foreground"> {item.status}</span>
</div>
</div>
))}
</div>
))}
) : (
// Empty State
<div className="text-center py-12 border-2 border-dashed rounded-lg bg-secondary/5">
<div className="mx-auto w-12 h-12 bg-secondary/20 rounded-full flex items-center justify-center mb-3">
<Headphones className="h-6 w-6 text-muted-foreground" />
</div>
<h3 className="text-sm font-semibold">No active escalations</h3>
<p className="text-xs text-muted-foreground mt-1 max-w-[200px] mx-auto">
User is happy! There are no open tickets or escalations for this account.
</p>
</div>
)}
</div>
</div>
);

View File

@@ -0,0 +1,80 @@
import { z } from 'zod';
import { createEscalationSchema } from '@/lib/validations/support';
import { logAdminAction } from '@/lib/audit-logger';
// Mock DB or Queue
const MOCK_TICKET_DB: any[] = [];
/**
* Creates a support escalation ticket.
* Simulates server-side logic including SLA routing and notifications.
*/
export async function createEscalation(data: z.infer<typeof createEscalationSchema>) {
try {
// 1. Validation
const validated = createEscalationSchema.safeParse(data);
if (!validated.success) {
return {
success: false,
message: "Validation failed: " + validated.error.errors.map(e => e.message).join(', ')
};
}
const input = validated.data;
// 2. Simulate Server Processing Delay
await new Promise(resolve => setTimeout(resolve, 800));
// 3. Auto-Routing Logic
let routedTo = input.assigneeId || 'support-general';
if (input.priority === 'Critical') {
// Logic: Critical tickets trigger PagerDuty/Slack
console.log(`[SERVER_ACT] 🚨 CRITICAL TICKET - Alerting #urgent-support webhook...`);
routedTo = 'incident-response-team';
} else if (input.type === 'Fraud Alert') {
routedTo = 'fraud-team';
}
// 4. Create Ticket Record
const ticketId = `tkt-${Math.floor(Math.random() * 10000)}`;
const newTicket = {
id: ticketId,
...input,
status: 'Open',
assignedTo: routedTo,
createdAt: new Date().toISOString(),
};
MOCK_TICKET_DB.push(newTicket);
// 5. Handle Callback Queue
if (input.callbackRequired) {
console.log(`[SERVER_ACT] 📞 Adding ticket ${ticketId} to Callback Queue (Phone: ${input.callbackPhone})`);
}
// 6. Audit Logging
await logAdminAction({
actorId: 'current-admin-id', // In real app, get from session
action: 'escalation_created',
targetId: input.userId,
details: {
ticketId,
priority: input.priority,
type: input.type,
routedTo
}
});
return {
success: true,
message: input.priority === 'Critical'
? "Critical Escalation Created & Alert Sent!"
: "Escalation ticket created successfully.",
ticket: { ...newTicket, author: 'Admin' }
};
} catch (error) {
console.error("createEscalation error:", error);
return { success: false, message: "Failed to create escalation." };
}
}

View File

@@ -0,0 +1,67 @@
import { z } from 'zod';
export const SupportTicketType = {
REFUND: 'Refund',
PAYMENT_FAILURE: 'Payment Failure',
ACCOUNT_ACCESS: 'Account access',
FRAUD_ALERT: 'Fraud Alert',
EVENT_ISSUE: 'Event issue',
OTHER: 'Other',
} as const;
export const SupportTicketPriority = {
LOW: 'Low',
MEDIUM: 'Medium',
HIGH: 'High',
CRITICAL: 'Critical',
} as const;
export const SupportTicketStatus = {
OPEN: 'Open',
IN_PROGRESS: 'In Progress',
RESOLVED: 'Resolved',
CLOSED: 'Closed',
} as const;
export const createEscalationSchema = z.object({
userId: z.string().min(1, "User ID is required"),
type: z.enum([
SupportTicketType.REFUND,
SupportTicketType.PAYMENT_FAILURE,
SupportTicketType.ACCOUNT_ACCESS,
SupportTicketType.FRAUD_ALERT,
SupportTicketType.EVENT_ISSUE,
SupportTicketType.OTHER
]),
priority: z.enum([
SupportTicketPriority.LOW,
SupportTicketPriority.MEDIUM,
SupportTicketPriority.HIGH,
SupportTicketPriority.CRITICAL
]),
subject: z.string().min(5, "Subject must be at least 5 characters"),
description: z.string().min(10, "Description must be at least 10 characters"),
callbackRequired: z.boolean().default(false),
callbackPhone: z.string().optional(),
callbackTime: z.string().optional(),
assigneeId: z.string().optional(),
}).refine((data) => {
if (data.priority === SupportTicketPriority.CRITICAL && data.description.length < 20) {
return false;
}
return true;
}, {
message: "Critical priority tickets require a description of at least 20 characters.",
path: ["description"],
}).refine((data) => {
if (data.callbackRequired && (!data.callbackPhone || data.callbackPhone.length < 5)) {
return false;
}
return true;
}, {
message: "Phone number is required when callback is requested.",
path: ["callbackPhone"],
});
export type CreateEscalationInput = z.infer<typeof createEscalationSchema>;