Files
hats-app/app/(dashboard)/task/error.tsx
T
Ichsan Kurniawan 47076b1d09 Improve task search and filtering
Search clients and assignments by employee, add end-user filters to client details, and refine filter options and sorting behavior.
2026-11-04 16:03:26 +07:00

365 lines
19 KiB
TypeScript

'use client';
import { useEffect, useState, useTransition } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { motion, AnimatePresence } from 'motion/react';
import {
RotateCw,
ArrowLeft,
Home,
AlertTriangle,
Terminal,
Copy,
Check,
ChevronDown,
ChevronUp,
ShieldCheck,
Server,
WifiOff,
LifeBuoy,
Info,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card900, CardContent } from '@/components/ui/card';
import { toast } from 'sonner';
import { clientLogger } from '@/lib/logger-client';
interface TaskErrorProps {
error: Error & { digest?: string };
reset: () => void;
}
export default function TaskError({ error, reset }: TaskErrorProps) {
const router = useRouter();
const [isPending, startTransition] = useTransition();
const [showDetails, setShowDetails] = useState(false);
const [copied, setCopied] = useState(false);
const [retrying, setRetrying] = useState(false);
useEffect(() => {
try {
console.error('[TaskPageError]', {
name: error?.name,
message: error?.message,
digest: error?.digest,
stack: error?.stack,
});
if (error?.stack) {
clientLogger.error(
`[TaskPageError] ${error.message} (digest: ${error.digest || 'none'})\n${error.stack}`
);
}
} catch {
// Ignore logging fallback errors
}
}, [error]);
const rawMessage = error?.message || '';
const digest = error?.digest;
// Detect if Next.js sanitized the error message in production
const isProductionOmitted =
rawMessage.includes('Server Components render') ||
rawMessage.includes('specific message is omitted in production') ||
rawMessage.includes('digest property is included');
const is500Error =
rawMessage.includes('500') ||
rawMessage.toLowerCase().includes('internal server error');
const isNetworkError =
rawMessage.toLowerCase().includes('fetch failed') ||
rawMessage.toLowerCase().includes('econnrefused') ||
rawMessage.toLowerCase().includes('network') ||
rawMessage.toLowerCase().includes('timeout');
// Context-sensitive status title and human-friendly explanation
let badgeText = 'Application Error';
let headline = 'Unable to Load Task & Client Data';
let friendlyDescription =
'The system was unable to retrieve client records and task assignments from the backend service. This usually occurs when the backend server is temporarily unreachable, restarting, or under maintenance.';
if (is500Error) {
badgeText = 'Backend Server Error (500)';
headline = 'Backend Service Encountered an Error';
friendlyDescription =
'The API server responded with an internal server error while fetching task records. Backend services may currently be undergoing a reload or processing a heavy task.';
} else if (isNetworkError) {
badgeText = 'Network Unreachable';
headline = 'Connection to API Server Lost';
friendlyDescription =
'A secure connection to the data server could not be established. Please check your internet connectivity or re-verify that your login session is still active.';
} else if (!isProductionOmitted && rawMessage.trim().length > 0) {
badgeText = 'Task Service Error';
headline = 'Failed to Retrieve Task Records';
friendlyDescription = rawMessage;
}
const handleRetry = () => {
setRetrying(true);
startTransition(() => {
try {
reset();
router.refresh();
} catch {
window.location.reload();
}
});
// Fallback hard refresh if soft reset doesn't resolve within 2.5 seconds
setTimeout(() => {
window.location.reload();
}, 2500);
};
const handleCopyDiagnostics = async () => {
const diagnosticsData = {
component: 'TaskDashboardError',
timestamp: new Date().toISOString(),
digest: digest || 'N/A',
errorName: error?.name || 'Error',
errorMessage: rawMessage,
detectedType: is500Error ? 'HTTP 500' : isNetworkError ? 'Network Timeout' : isProductionOmitted ? 'Production Sanitized' : 'Application Error',
stack: error?.stack || 'No stack trace available',
url: typeof window !== 'undefined' ? window.location.href : '',
userAgent: typeof navigator !== 'undefined' ? navigator.userAgent : '',
};
try {
await navigator.clipboard.writeText(JSON.stringify(diagnosticsData, null, 2));
setCopied(true);
toast.success('Diagnostic report copied to clipboard');
setTimeout(() => setCopied(false), 2500);
} catch {
toast.error('Failed to copy diagnostics');
}
};
return (
<div className="flex-1 w-full max-w-5xl mx-auto px-4 sm:px-6 py-6 sm:py-10 space-y-8 animate-in fade-in duration-300">
{/* Top Minimal Navigation Breadcrumb */}
<div className="flex items-center justify-between text-xs text-muted-foreground border-b border-border/50">
<div className="flex items-center gap-2">
<span className="text-amber-600 dark:text-amber-400 font-medium">Task Management</span>
</div>
{digest && (
<div className="hidden sm:flex items-center gap-1.5 font-mono text-[11px] text-muted-foreground bg-muted/50 dark:bg-zinc-800/60 px-2 py-0.5 rounded border border-border/60">
<span>Ref:</span>
<span className="text-foreground">{digest}</span>
</div>
)}
</div>
{/* Main Hero Error Card */}
<Card900 className="overflow-hidden border-border/80 shadow-lg rounded-3xl bg-card">
<CardContent className="p-6 sm:p-10">
<div className="flex flex-col lg:flex-row items-center gap-8 lg:gap-12">
{/* 3D Illustration Container */}
<motion.div
initial={{ scale: 0.95, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
transition={{ duration: 0.4 }}
className="relative shrink-0 flex items-center justify-center"
>
<div className="relative w-52 h-52 sm:w-64 sm:h-64 rounded-3xl bg-linear-to-b from-amber-500/10 via-orange-500/5 to-transparent border border-amber-500/20 p-4 flex items-center justify-center shadow-inner">
<motion.div
animate={{ y: [0, -6, 0] }}
transition={{ duration: 3.5, repeat: Infinity, ease: 'easeInOut' }}
className="w-full h-full flex items-center justify-center"
>
<Image
src="/assets/illustrations/server_task_error.webp"
alt="Task service connection illustration"
width={240}
height={240}
priority
className="object-contain drop-shadow-md select-none pointer-events-none"
/>
</motion.div>
</div>
</motion.div>
{/* Content & Action Area */}
<div className="flex-1 text-center lg:text-left space-y-4 min-w-0">
{/* Status Pill Badge */}
<div className="flex flex-wrap items-center justify-center lg:justify-start gap-2">
<div className="inline-flex items-center gap-2 px-3 py-1 rounded-full text-xs font-semibold bg-amber-500/10 text-amber-700 dark:text-amber-400 border border-amber-500/25">
<span className="relative flex h-2 w-2">
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-amber-400 opacity-75" />
<span className="relative inline-flex rounded-full h-2 w-2 bg-amber-500" />
</span>
<span>{badgeText}</span>
</div>
{isProductionOmitted && (
<Badge variant="outline" className="text-[11px] font-normal py-0.5 border-border/70 text-muted-foreground">
Production Mode
</Badge>
)}
</div>
{/* Headline */}
<h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-foreground leading-tight">
{headline}
</h1>
{/* Human-friendly description */}
<p className="text-sm sm:text-base text-muted-foreground leading-relaxed max-w-2xl">
{friendlyDescription}
</p>
{/* Actions Group */}
<div className="pt-2 flex flex-wrap items-center justify-center lg:justify-start gap-3">
<Button
onClick={handleRetry}
disabled={retrying || isPending}
className="bg-his text-white hover:bg-his/90 font-medium px-5 h-11 shadow-sm gap-2 transition-transform active:scale-[0.98]"
>
<RotateCw className={`w-4 h-4 ${retrying || isPending ? 'animate-spin' : ''}`} />
<span>{retrying || isPending ? 'Reconnecting Service...' : 'Retry Connection'}</span>
</Button>
<Button
variant="outline"
onClick={() => router.back()}
className="h-11 px-4 gap-2 hover:bg-muted transition-transform active:scale-[0.98]"
>
<ArrowLeft className="w-4 h-4" />
<span>Back to Previous Page</span>
</Button>
<Button
variant="ghost"
asChild
className="h-11 px-4 gap-2 text-muted-foreground hover:text-foreground"
>
<Link href="/">
<Home className="w-4 h-4" />
<span>Dashboard Home</span>
</Link>
</Button>
</div>
{/* Auto-reconnect advisory note */}
<p className="text-xs text-muted-foreground/80 pt-1 flex items-center justify-center lg:justify-start gap-1.5">
<Info className="w-3.5 h-3.5 text-muted-foreground shrink-0" />
<span>Tip: If the backend is restarting, retrying in 10-15 seconds usually resolves the issue.</span>
</p>
</div>
</div>
</CardContent>
</Card900>
{/* Collapsible Technical Diagnostics Drawer */}
<div className="rounded-2xl border border-border/80 bg-card overflow-hidden transition-all">
<button
type="button"
onClick={() => setShowDetails(!showDetails)}
className="w-full p-4 sm:px-6 flex items-center justify-between hover:bg-muted/40 transition-colors text-left"
>
<div className="flex items-center gap-2.5">
<Terminal className="w-4 h-4 text-muted-foreground" />
<span className="text-xs sm:text-sm font-semibold text-foreground">
Technical Diagnostics & Error Details
</span>
{digest && (
<Badge variant="outline" className="text-[10px] font-mono py-0 h-5 border-border">
Digest #{digest.slice(0, 8)}
</Badge>
)}
</div>
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<span>{showDetails ? 'Hide details' : 'Show details'}</span>
{showDetails ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
</div>
</button>
<AnimatePresence>
{showDetails && (
<motion.div
initial={{ height: 0, opacity: 0 }}
animate={{ height: 'auto', opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
transition={{ duration: 0.2 }}
className="border-t border-border/70 p-4 sm:p-6 bg-muted/20 dark:bg-zinc-950/40 space-y-4"
>
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 pb-3 border-b border-border/50">
<div className="space-y-0.5">
<h4 className="text-xs font-semibold text-foreground">Developer Information</h4>
<p className="text-[11px] text-muted-foreground">
Use this information when reporting bugs or inspecting backend server logs.
</p>
</div>
<Button
type="button"
size="sm"
variant="outline"
onClick={handleCopyDiagnostics}
className="h-8 gap-1.5 text-xs text-muted-foreground hover:text-foreground self-start sm:self-auto"
>
{copied ? <Check className="w-3.5 h-3.5 text-emerald-500" /> : <Copy className="w-3.5 h-3.5" />}
<span>{copied ? 'Copied to Clipboard' : 'Copy Report'}</span>
</Button>
</div>
{/* Summary Metadata Key-Values */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 text-xs font-mono">
<div className="p-3 rounded-xl bg-background border border-border/60 space-y-1">
<span className="text-[10px] uppercase text-muted-foreground font-sans font-semibold">Error Name</span>
<p className="text-foreground truncate font-medium">{error?.name || 'Error'}</p>
</div>
<div className="p-3 rounded-xl bg-background border border-border/60 space-y-1">
<span className="text-[10px] uppercase text-muted-foreground font-sans font-semibold">Digest ID</span>
<p className="text-foreground truncate font-medium">{digest || 'N/A'}</p>
</div>
<div className="p-3 rounded-xl bg-background border border-border/60 space-y-1">
<span className="text-[10px] uppercase text-muted-foreground font-sans font-semibold">Classification</span>
<p className="text-amber-600 dark:text-amber-400 truncate font-medium">
{is500Error ? 'HTTP 500' : isNetworkError ? 'Network Timeout' : isProductionOmitted ? 'Server Component' : 'API Failure'}
</p>
</div>
<div className="p-3 rounded-xl bg-background border border-border/60 space-y-1">
<span className="text-[10px] uppercase text-muted-foreground font-sans font-semibold">Timestamp</span>
<p className="text-foreground truncate font-medium">{new Date().toLocaleTimeString()}</p>
</div>
</div>
{/* Error Message Box */}
<div className="space-y-1.5">
<span className="text-[11px] font-medium text-muted-foreground">Original Message:</span>
<div className="p-3.5 rounded-xl bg-background border border-border/80 font-mono text-xs text-foreground/90 whitespace-pre-wrap break-all leading-relaxed">
{rawMessage || 'No specific error message provided.'}
</div>
</div>
{/* Stack Trace (if present) */}
{error?.stack && (
<div className="space-y-1.5">
<span className="text-[11px] font-medium text-muted-foreground">Stack Trace:</span>
<pre className="p-3.5 rounded-xl bg-zinc-950 text-zinc-300 border border-zinc-800 font-mono text-[11px] whitespace-pre-wrap break-all overflow-x-auto max-h-48 leading-relaxed">
{error.stack}
</pre>
</div>
)}
</motion.div>
)}
</AnimatePresence>
</div>
<div className="p-4 rounded-2xl border border-border/80 bg-card/60 backdrop-blur-xs space-y-1.5">
<div className="flex items-center gap-2 text-primary">
<LifeBuoy className="w-4 h-4 text-sky-500" />
<h3 className="text-xs font-semibold text-foreground">Technical Support</h3>
</div>
<p className="text-xs text-muted-foreground leading-relaxed">
If this message persists after several retries, copy the diagnostic report above and share it with the dev team.
</p>
</div>
</div>
);
}