260223:1415 20260223 nextJS & nestJS Best pratices
All checks were successful
Build and Deploy / deploy (push) Successful in 4m44s

This commit is contained in:
admin
2026-02-23 14:15:06 +07:00
parent c90a664f53
commit ef16817f38
164 changed files with 24815 additions and 311 deletions

View File

@@ -1,17 +1,21 @@
"use client";
'use client';
import { useState, useEffect } from "react";
import { TemplateEditor } from "@/components/numbering/template-editor";
import { SequenceViewer } from "@/components/numbering/sequence-viewer";
import { numberingApi } from "@/lib/api/numbering";
import { NumberingTemplate } from "@/lib/api/numbering"; // Correct import
import { useRouter } from "next/navigation";
import { Loader2 } from "lucide-react";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useCorrespondenceTypes, useContracts, useDisciplines } from "@/hooks/use-master-data";
import { useProjects } from "@/hooks/use-projects";
import { useState, useEffect } from 'react';
import { useParams } from 'next/navigation';
import { TemplateEditor } from '@/components/numbering/template-editor';
import { SequenceViewer } from '@/components/numbering/sequence-viewer';
import { numberingApi } from '@/lib/api/numbering';
import { NumberingTemplate } from '@/lib/api/numbering';
import { useRouter } from 'next/navigation';
import { Loader2 } from 'lucide-react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useCorrespondenceTypes, useContracts, useDisciplines } from '@/hooks/use-master-data';
import { useProjects } from '@/hooks/use-projects';
import { toast } from 'sonner';
export default function EditTemplatePage({ params }: { params: { id: string } }) {
export default function EditTemplatePage() {
const params = useParams();
const id = params['id'] as string;
const router = useRouter();
const [loading, setLoading] = useState(true);
const [template, setTemplate] = useState<NumberingTemplate | null>(null);
@@ -24,33 +28,36 @@ export default function EditTemplatePage({ params }: { params: { id: string } })
const contractId = contracts[0]?.id;
const { data: disciplines = [] } = useDisciplines(contractId);
const selectedProjectName = projects.find((p: { id: number; projectName: string }) => p.id === projectId)?.projectName || 'LCBP3';
const selectedProjectName =
projects.find((p: { id: number; projectName: string }) => p.id === projectId)?.projectName ||
'LCBP3';
useEffect(() => {
const fetchTemplate = async () => {
setLoading(true);
try {
const data = await numberingApi.getTemplate(parseInt(params.id));
const data = await numberingApi.getTemplate(parseInt(id));
if (data) {
setTemplate(data);
}
} catch (error) {
console.error("Failed to fetch template", error);
toast.error('Failed to load template');
console.error('[EditTemplatePage] fetchTemplate:', error);
} finally {
setLoading(false);
}
};
fetchTemplate();
}, [params.id]);
}, [id]);
const handleSave = async (data: Partial<NumberingTemplate>) => {
try {
await numberingApi.saveTemplate({ ...data, id: parseInt(params.id) });
router.push("/admin/numbering");
await numberingApi.saveTemplate({ ...data, id: parseInt(id) });
router.push('/admin/doc-control/numbering');
} catch (error) {
console.error("Failed to update template", error);
alert("Failed to update template");
toast.error('Failed to update template');
console.error('[EditTemplatePage] handleSave:', error);
}
};

View File

@@ -5,6 +5,7 @@ import { numberingApi, NumberingTemplate } from "@/lib/api/numbering";
import { useRouter } from "next/navigation";
import { useCorrespondenceTypes, useContracts, useDisciplines } from "@/hooks/use-master-data";
import { useProjects } from "@/hooks/use-projects";
import { toast } from 'sonner';
export default function NewTemplatePage() {
const router = useRouter();
@@ -17,20 +18,21 @@ export default function NewTemplatePage() {
const contractId = contracts[0]?.id;
const { data: disciplines = [] } = useDisciplines(contractId);
const selectedProjectName = projects.find((p: any) => p.id === projectId)?.projectName || 'LCBP3';
const selectedProjectName =
projects.find((p: { id: number; projectName: string }) => p.id === projectId)?.projectName || 'LCBP3';
const handleSave = async (data: Partial<NumberingTemplate>) => {
try {
await numberingApi.saveTemplate(data);
router.push("/admin/numbering");
} catch (error) {
console.error("Failed to create template", error);
alert("Failed to create template");
toast.error('Failed to create template');
console.error('[NewTemplatePage]', error);
}
};
const handleCancel = () => {
router.push("/admin/numbering");
router.push('/admin/doc-control/numbering');
};
return (

View File

@@ -14,6 +14,7 @@ import { workflowApi } from '@/lib/api/workflows';
import { WorkflowType } from '@/types/workflow';
import { useRouter } from 'next/navigation';
import { Loader2 } from 'lucide-react';
import { toast } from 'sonner';
export default function NewWorkflowPage() {
const router = useRouter();
@@ -31,8 +32,8 @@ export default function NewWorkflowPage() {
await workflowApi.createWorkflow(workflowData);
router.push('/admin/doc-control/workflows');
} catch (error) {
console.error('Failed to create workflow', error);
alert('Failed to create workflow');
toast.error('Failed to create workflow');
console.error('[NewWorkflowPage]', error);
} finally {
setSaving(false);
}

View File

@@ -8,6 +8,7 @@ import { Plus, Edit, Copy, Trash, Loader2 } from 'lucide-react';
import Link from 'next/link';
import { Workflow } from '@/types/workflow';
import { workflowApi } from '@/lib/api/workflows';
import { toast } from 'sonner';
export default function WorkflowsPage() {
const [workflows, setWorkflows] = useState<Workflow[]>([]);
@@ -20,7 +21,8 @@ export default function WorkflowsPage() {
const data = await workflowApi.getWorkflows();
setWorkflows(data);
} catch (error) {
console.error('Failed to fetch workflows', error);
toast.error('Failed to load workflows');
console.error('[WorkflowsPage]', error);
} finally {
setLoading(false);
}

View File

@@ -0,0 +1,42 @@
'use client';
import { useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { AlertTriangle, RefreshCw } from 'lucide-react';
import Link from 'next/link';
export default function AdminError({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
useEffect(() => {
console.error('[Admin Error Boundary]', error);
}, [error]);
return (
<div className="flex flex-col items-center justify-center min-h-[60vh] gap-4 text-center px-4">
<AlertTriangle className="h-10 w-10 text-amber-500" />
<div>
<h2 className="text-lg font-semibold">Admin Panel Error</h2>
<p className="text-muted-foreground mt-1 text-sm max-w-md">
{error.message || 'An error occurred in the admin panel.'}
</p>
{error.digest && (
<p className="text-xs text-muted-foreground mt-2">Error ID: {error.digest}</p>
)}
</div>
<div className="flex gap-3">
<Button onClick={reset} variant="outline" size="sm">
<RefreshCw className="mr-2 h-4 w-4" />
Try again
</Button>
<Button asChild variant="ghost" size="sm">
<Link href="/admin">Back to Admin</Link>
</Button>
</div>
</div>
);
}

View File

@@ -12,9 +12,10 @@ import { format } from "date-fns";
export default async function DrawingDetailPage({
params,
}: {
params: { id: string };
params: Promise<{ id: string }>;
}) {
const id = parseInt(params.id);
const { id: rawId } = await params;
const id = parseInt(rawId);
if (isNaN(id)) {
notFound();
}

View File

@@ -0,0 +1,42 @@
'use client';
import { useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { AlertCircle, RefreshCw } from 'lucide-react';
import Link from 'next/link';
export default function DashboardError({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
useEffect(() => {
console.error('[Dashboard Error Boundary]', error);
}, [error]);
return (
<div className="flex flex-col items-center justify-center min-h-[60vh] gap-4 text-center px-4">
<AlertCircle className="h-10 w-10 text-destructive" />
<div>
<h2 className="text-lg font-semibold">Something went wrong</h2>
<p className="text-muted-foreground mt-1 text-sm max-w-md">
{error.message || 'An error occurred while loading this page.'}
</p>
{error.digest && (
<p className="text-xs text-muted-foreground mt-2">Error ID: {error.digest}</p>
)}
</div>
<div className="flex gap-3">
<Button onClick={reset} variant="outline" size="sm">
<RefreshCw className="mr-2 h-4 w-4" />
Try again
</Button>
<Button asChild variant="ghost" size="sm">
<Link href="/dashboard">Back to Dashboard</Link>
</Button>
</div>
</div>
);
}

View File

@@ -23,6 +23,7 @@ import {
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Switch } from "@/components/ui/switch";
import apiClient from "@/lib/api/client";
import { toast } from "sonner";
// -----------------------------------------------------------------------------
// Schemas
@@ -63,12 +64,12 @@ export default function ProfilePage() {
currentPassword: data.currentPassword,
newPassword: data.newPassword,
});
alert("เปลี่ยนรหัสผ่านสำเร็จ"); // ในอนาคตใช้ Toast
toast.success('เปลี่ยนรหัสผ่านสำเร็จ');
reset();
} catch (error) {
console.error(error);
alert("ไม่สามารถเปลี่ยนรหัสผ่านได้: รหัสผ่านปัจจุบันไม่ถูกต้อง");
toast.error('ไม่สามารถเปลี่ยนรหัสผ่านได้: รหัสผ่านปัจจุบันไม่ถูกต้อง');
console.error('[ProfilePage] onPasswordSubmit:', error);
} finally {
setIsLoading(false);
}
@@ -159,8 +160,8 @@ export default function ProfilePage() {
</div>
</CardContent>
{/* <CardFooter>
<Button>บันทึกการเปลี่ยนแปลง</Button>
</CardFooter>
<Button>บันทึกการเปลี่ยนแปลง</Button>
</CardFooter>
*/}
</Card>
</TabsContent>
@@ -243,7 +244,7 @@ export default function ProfilePage() {
onCheckedChange={setNotifyEmail}
/>
</div>
<div className="flex items-center justify-between space-x-2">
<Label htmlFor="notify-line" className="flex flex-col space-y-1">
<span>LINE Notifications</span>
@@ -273,7 +274,7 @@ export default function ProfilePage() {
</div>
</CardContent>
<CardFooter>
<Button variant="outline" onClick={() => alert("บันทึกการตั้งค่าแจ้งเตือนแล้ว")}>
<Button variant="outline" onClick={() => toast.success('บันทึกการตั้งค่าแจ้งเตือนแล้ว')}>
</Button>
</CardFooter>
@@ -282,4 +283,4 @@ export default function ProfilePage() {
</Tabs>
</div>
);
}
}

View File

@@ -27,7 +27,7 @@ import {
CardHeader,
CardTitle,
} from "@/components/ui/card";
import apiClient from "@/lib/api/client";
import { toast } from "sonner";
// 1. กำหนด Schema สำหรับตรวจสอบข้อมูล (Validation)
// อ้างอิงจาก Data Dictionary ตาราง projects
@@ -58,7 +58,6 @@ export default function CreateProjectPage() {
register,
handleSubmit,
setValue, // ใช้สำหรับ manual set value (เช่น Select)
watch, // ใช้ดูค่า (สำหรับ Debug หรือ Conditional Logic)
formState: { errors },
} = useForm<ProjectValues>({
resolver: zodResolver(projectSchema),
@@ -82,12 +81,12 @@ export default function CreateProjectPage() {
// await apiClient.post("/projects", data);
alert("สร้างโครงการสำเร็จ"); // TODO: เปลี่ยนเป็น Toast
router.push("/projects");
toast.success('สร้างโครงการสำเร็จ');
router.push('/projects');
router.refresh();
} catch (error) {
console.error("Failed to create project:", error);
alert("เกิดข้อผิดพลาดในการสร้างโครงการ");
toast.error('เกิดข้อผิดพลาดในการสร้างโครงการ');
console.error('[CreateProjectPage]', error);
} finally {
setIsLoading(false);
}
@@ -202,7 +201,7 @@ export default function CreateProjectPage() {
เราต้องใช้ onValueChange เพื่อเชื่อมกับ React Hook Form
*/}
<Select
onValueChange={(value: any) => setValue("status", value)}
onValueChange={(value: 'Active' | 'Inactive' | 'On Hold') => setValue('status', value)}
defaultValue="Active"
>
<SelectTrigger>

35
frontend/app/error.tsx Normal file
View File

@@ -0,0 +1,35 @@
'use client';
import { useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { AlertCircle } from 'lucide-react';
export default function Error({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
useEffect(() => {
console.error('[App Error Boundary]', error);
}, [error]);
return (
<div className="flex flex-col items-center justify-center min-h-[60vh] gap-4 text-center px-4">
<AlertCircle className="h-12 w-12 text-destructive" />
<div>
<h2 className="text-xl font-semibold">Something went wrong</h2>
<p className="text-muted-foreground mt-1 text-sm max-w-md">
{error.message || 'An unexpected error occurred. Please try again.'}
</p>
{error.digest && (
<p className="text-xs text-muted-foreground mt-2">Error ID: {error.digest}</p>
)}
</div>
<Button onClick={reset} variant="outline">
Try again
</Button>
</div>
);
}

View File

@@ -0,0 +1,60 @@
'use client';
import { useEffect } from 'react';
// global-error.tsx catches errors in the root layout.tsx itself.
// It MUST include its own <html> and <body> tags per Next.js spec.
export default function GlobalError({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
useEffect(() => {
console.error('[Global Error Boundary]', error);
}, [error]);
return (
<html lang="en">
<body style={{ margin: 0, fontFamily: 'system-ui, sans-serif' }}>
<div
style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
minHeight: '100vh',
gap: '16px',
textAlign: 'center',
padding: '16px',
}}
>
<h2 style={{ fontSize: '1.25rem', fontWeight: 600 }}>
Application Error
</h2>
<p style={{ color: '#6b7280', fontSize: '0.875rem', maxWidth: '400px' }}>
{error.message || 'A critical error occurred. Please refresh the page.'}
</p>
{error.digest && (
<p style={{ fontSize: '0.75rem', color: '#9ca3af' }}>
Error ID: {error.digest}
</p>
)}
<button
onClick={reset}
style={{
padding: '8px 16px',
border: '1px solid #d1d5db',
borderRadius: '6px',
cursor: 'pointer',
backgroundColor: 'white',
}}
>
Try again
</button>
</div>
</body>
</html>
);
}

View File

@@ -19,6 +19,8 @@ const nextConfig = {
],
// ลดขนาดไฟล์รูปภาพที่จะถูก optimize
deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
// Cache optimized images for 24h (reduces re-optimization on containers)
minimumCacheTTL: 86400,
},
// 4. (Optional) Rewrites: กรณีต้องการ Proxy API ผ่าน Next.js เพื่อเลี่ยง CORS ใน Dev
@@ -33,7 +35,7 @@ const nextConfig = {
]
},
*/
// 5. Security Headers (แนะนำ)
async headers() {
return [
@@ -62,4 +64,4 @@ const nextConfig = {
},
};
export default nextConfig;
export default nextConfig;