260218:1712 20260218 TASK-BEFE-001n
All checks were successful
Build and Deploy / deploy (push) Successful in 4m55s

This commit is contained in:
admin
2026-02-18 17:12:11 +07:00
parent 01ce68acda
commit b84284f8a9
54 changed files with 1307 additions and 339 deletions

View File

@@ -63,6 +63,9 @@ ENV PORT=3000
RUN addgroup -g 1001 -S nextjs && \
adduser -S nextjs -u 1001
# Install curl for healthcheck
RUN apk add --no-cache curl
# Copy standalone output from build
COPY --from=build --chown=nextjs:nextjs /app/frontend/.next/standalone ./
COPY --from=build --chown=nextjs:nextjs /app/frontend/.next/static ./frontend/.next/static
@@ -71,7 +74,7 @@ USER nextjs
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=10s --retries=3 --start-period=20s \
CMD wget --no-verbose --tries=1 --spider http://localhost:3000/ || exit 1
HEALTHCHECK --interval=30s --timeout=10s --retries=3 --start-period=60s \
CMD curl -f http://localhost:3000/ || exit 1
CMD ["node", "frontend/server.js"]

View File

@@ -0,0 +1,119 @@
'use client';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { sessionService } from '@/lib/services/session.service';
import { Button } from '@/components/ui/button';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { toast } from 'sonner';
import { Loader2, Trash2, Monitor, Smartphone } from 'lucide-react';
import { format } from 'date-fns';
export default function SessionManagementPage() {
const queryClient = useQueryClient();
const {
data: sessions,
isLoading,
error,
} = useQuery({
queryKey: ['sessions'],
queryFn: sessionService.getActiveSessions,
});
const revokeMutation = useMutation({
mutationFn: sessionService.revokeSession,
onSuccess: () => {
toast.success('Session revoked successfully');
queryClient.invalidateQueries({ queryKey: ['sessions'] });
},
onError: (error) => {
toast.error('Failed to revoke session');
console.error(error);
},
});
const handleRevoke = (id: number) => {
if (confirm('Are you sure you want to revoke this session?')) {
revokeMutation.mutate(id);
}
};
if (isLoading) {
return (
<div className="flex h-[400px] w-full items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
);
}
if (error) {
return <div className="p-8 text-center text-red-500">Failed to load sessions. Please try again.</div>;
}
return (
<div className="space-y-6 p-6">
<div className="flex flex-col gap-2">
<h1 className="text-2xl font-bold tracking-tight">Active Sessions</h1>
<p className="text-sm text-muted-foreground">Monitor and manage active user sessions across all devices.</p>
</div>
<div className="rounded-md border bg-card">
<Table>
<TableHeader>
<TableRow>
<TableHead>User</TableHead>
<TableHead>Device Info</TableHead>
<TableHead>Last Active</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{sessions?.map((session: any) => (
<TableRow key={session.id}>
<TableCell>
<div className="flex flex-col">
<span className="font-medium">{session.user.username}</span>
<span className="text-xs text-muted-foreground">
{session.user.firstName} {session.user.lastName}
</span>
</div>
</TableCell>
<TableCell>
<div className="flex flex-col gap-1">
<div className="flex items-center gap-2 text-sm">
<Monitor className="h-3 w-3" />
{session.deviceName || 'Unknown Device'}
</div>
<span className="text-xs text-muted-foreground">{session.ipAddress || 'Unknown IP'}</span>
</div>
</TableCell>
<TableCell className="text-sm">
{session.lastActive ? format(new Date(session.lastActive), 'PP pp') : '-'}
</TableCell>
<TableCell className="text-right">
<Button
variant="destructive"
size="sm"
className="h-8"
onClick={() => handleRevoke(Number(session.id))}
disabled={revokeMutation.isPending}
>
<Trash2 className="mr-2 h-3.5 w-3.5" />
Revoke
</Button>
</TableCell>
</TableRow>
))}
{(!sessions || sessions.length === 0) && (
<TableRow>
<TableCell colSpan={4} className="h-24 text-center text-muted-foreground">
No active sessions found.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
</div>
);
}

View File

@@ -1,21 +1,12 @@
"use client";
'use client';
import { useOrganizations } from "@/hooks/use-master-data";
import { useUsers } from "@/hooks/use-users";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
Users,
Building2,
FileText,
Settings,
Shield,
Activity,
ArrowRight,
FileStack,
} from "lucide-react";
import Link from "next/link";
import { Skeleton } from "@/components/ui/skeleton";
import { Button } from "@/components/ui/button";
import { useOrganizations } from '@/hooks/use-master-data';
import { useUsers } from '@/hooks/use-users';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Users, Building2, FileText, Settings, Shield, Activity, ArrowRight, FileStack } from 'lucide-react';
import Link from 'next/link';
import { Skeleton } from '@/components/ui/skeleton';
import { Button } from '@/components/ui/button';
export default function AdminPage() {
const { data: organizations, isLoading: orgsLoading } = useOrganizations();
@@ -23,66 +14,66 @@ export default function AdminPage() {
const stats = [
{
title: "Total Users",
title: 'Total Users',
value: users?.length || 0,
icon: Users,
loading: usersLoading,
href: "/admin/users",
color: "text-blue-600",
href: '/admin/access-control/users',
color: 'text-blue-600',
},
{
title: "Organizations",
title: 'Organizations',
value: organizations?.length || 0,
icon: Building2,
loading: orgsLoading,
href: "/admin/organizations",
color: "text-green-600",
href: '/admin/access-control/organizations',
color: 'text-green-600',
},
{
title: "System Logs",
value: "View",
icon: Activity,
loading: false,
href: "/admin/system-logs",
color: "text-orange-600",
}
title: 'System Logs',
value: 'View',
icon: Activity,
loading: false,
href: '/admin/monitoring/system-logs',
color: 'text-orange-600',
},
];
const quickLinks = [
{
title: "User Management",
description: "Manage system users, roles, and permissions",
href: "/admin/users",
title: 'User Management',
description: 'Manage system users, roles, and permissions',
href: '/admin/access-control/users',
icon: Users,
},
{
title: "Organizations",
description: "Manage project organizations and companies",
href: "/admin/organizations",
title: 'Organizations',
description: 'Manage project organizations and companies',
href: '/admin/access-control/organizations',
icon: Building2,
},
{
title: "Workflow Config",
description: "Configure document approval workflows",
href: "/admin/workflows",
title: 'Workflow Config',
description: 'Configure document approval workflows',
href: '/admin/doc-control/workflows',
icon: FileText,
},
{
title: "Security & RBAC",
description: "Configure roles, permissions, and security settings",
href: "/admin/security/roles",
title: 'Security & RBAC',
description: 'Configure roles, permissions, and security settings',
href: '/admin/access-control/roles',
icon: Shield,
},
{
title: "Numbering System",
description: "Setup document numbering templates",
href: "/admin/numbering",
title: 'Numbering System',
description: 'Setup document numbering templates',
href: '/admin/doc-control/numbering',
icon: Settings,
},
{
title: "Drawing Master Data",
description: "Manage drawing categories, volumes, and classifications",
href: "/admin/drawings",
title: 'Drawing Master Data',
description: 'Manage drawing categories, volumes, and classifications',
href: '/admin/doc-control/drawings',
icon: FileStack,
},
];
@@ -91,18 +82,14 @@ export default function AdminPage() {
<div className="space-y-8 p-8">
<div>
<h1 className="text-3xl font-bold tracking-tight">Admin Dashboard</h1>
<p className="text-muted-foreground mt-2">
System overview and quick access to administrative functions.
</p>
<p className="text-muted-foreground mt-2">System overview and quick access to administrative functions.</p>
</div>
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{stats.map((stat, index) => (
<Card key={index} className="hover:shadow-md transition-shadow">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">
{stat.title}
</CardTitle>
<CardTitle className="text-sm font-medium">{stat.title}</CardTitle>
<stat.icon className={`h-4 w-4 ${stat.color}`} />
</CardHeader>
<CardContent>
@@ -112,10 +99,7 @@ export default function AdminPage() {
<div className="text-2xl font-bold">{stat.value}</div>
)}
{stat.href && (
<Link
href={stat.href}
className="text-xs text-muted-foreground hover:underline mt-1 inline-block"
>
<Link href={stat.href} className="text-xs text-muted-foreground hover:underline mt-1 inline-block">
View details
</Link>
)}
@@ -137,9 +121,7 @@ export default function AdminPage() {
</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground">
{link.description}
</p>
<p className="text-sm text-muted-foreground">{link.description}</p>
<Button variant="ghost" className="mt-4 p-0 h-auto font-normal text-primary hover:no-underline group">
Go to module <ArrowRight className="ml-1 h-3 w-3 group-hover:translate-x-1 transition-transform" />
</Button>

View File

@@ -1,131 +0,0 @@
"use client";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import apiClient from "@/lib/api/client";
import { DataTable } from "@/components/common/data-table";
import { ColumnDef } from "@tanstack/react-table";
import { Button } from "@/components/ui/button";
import { LogOut, Monitor, Smartphone, RefreshCw } from "lucide-react";
import { format } from "date-fns";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
interface Session {
id: string;
userId: number;
user: {
username: string;
firstName: string;
lastName: string;
};
deviceName: string; // e.g., "Chrome on Windows"
ipAddress: string;
lastActive: string;
isCurrent: boolean;
}
const sessionService = {
getAll: async () => {
const response = await apiClient.get("/auth/sessions");
return response.data.data || response.data;
},
revoke: async (sessionId: string) => (await apiClient.delete(`/auth/sessions/${sessionId}`)).data,
};
export default function SessionsPage() {
const queryClient = useQueryClient();
const { data: sessions = [], isLoading } = useQuery<Session[]>({
queryKey: ["sessions"],
queryFn: sessionService.getAll,
});
const revokeMutation = useMutation({
mutationFn: sessionService.revoke,
onSuccess: () => {
toast.success("Session revoked successfully");
queryClient.invalidateQueries({ queryKey: ["sessions"] });
},
onError: () => toast.error("Failed to revoke session"),
});
const columns: ColumnDef<Session>[] = [
{
accessorKey: "user",
header: "User",
cell: ({ row }) => {
const user = row.original.user;
return (
<div className="flex flex-col">
<span className="font-medium">{user.username}</span>
<span className="text-xs text-muted-foreground">
{user.firstName} {user.lastName}
</span>
</div>
);
},
},
{
accessorKey: "deviceName",
header: "Device / IP",
cell: ({ row }) => (
<div className="flex items-center gap-2">
{row.original.deviceName.toLowerCase().includes("mobile") ? (
<Smartphone className="h-4 w-4 text-muted-foreground" />
) : (
<Monitor className="h-4 w-4 text-muted-foreground" />
)}
<div className="flex flex-col">
<span>{row.original.deviceName}</span>
<span className="text-xs text-muted-foreground">{row.original.ipAddress}</span>
</div>
</div>
),
},
{
accessorKey: "lastActive",
header: "Last Active",
cell: ({ row }) => format(new Date(row.original.lastActive), "dd MMM yyyy, HH:mm"),
},
{
id: "status",
header: "Status",
cell: ({ row }) =>
row.original.isCurrent ? <Badge>Current</Badge> : <Badge variant="secondary">Active</Badge>,
},
{
id: "actions",
cell: ({ row }) => (
<Button
variant="destructive"
size="sm"
disabled={row.original.isCurrent || revokeMutation.isPending}
onClick={() => revokeMutation.mutate(row.original.id)}
>
<LogOut className="h-4 w-4 mr-2" />
Revoke
</Button>
),
},
];
if (isLoading) {
return (
<div className="flex justify-center p-12">
<RefreshCw className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
);
}
return (
<div className="p-6 space-y-6">
<div className="flex justify-between items-center">
<div>
<h1 className="text-2xl font-bold">Active Sessions</h1>
<p className="text-muted-foreground">Manage user sessions and force logout if needed</p>
</div>
</div>
<DataTable columns={columns} data={sessions} />
</div>
);
}

View File

@@ -1,28 +1,24 @@
import { AdminSidebar } from "@/components/admin/sidebar";
import { AdminSidebar } from '@/components/admin/sidebar';
import { auth } from "@/lib/auth";
import { auth } from '@/lib/auth';
import { redirect } from 'next/navigation';
export default async function AdminLayout({
children,
}: {
children: React.ReactNode;
}) {
export default async function AdminLayout({ children }: { children: React.ReactNode }) {
const session = await auth();
// Temporary bypass for UI testing
const isAdmin = true; // session?.user?.role === 'ADMIN';
// Validate Admin or DC role
const userRole = session?.user?.role;
const isAdmin = userRole === 'ADMIN' || userRole === 'DC';
if (!session || !isAdmin) {
// redirect("/");
redirect('/dashboard'); // Redirect unauthorized users to dashboard
}
return (
<div className="flex h-screen w-full bg-background">
<AdminSidebar />
<div className="flex-1 overflow-auto bg-muted/10 p-4">
{children}
</div>
<div className="flex-1 overflow-auto bg-muted/10 p-4">{children}</div>
</div>
);
}

View File

@@ -1,9 +1,9 @@
"use client";
'use client';
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useState } from "react";
import { cn } from "@/lib/utils";
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useState } from 'react';
import { cn } from '@/lib/utils';
import {
Users,
Building2,
@@ -16,7 +16,7 @@ import {
FileStack,
ChevronDown,
ChevronRight,
} from "lucide-react";
} from 'lucide-react';
interface MenuItem {
href?: string;
@@ -26,29 +26,47 @@ interface MenuItem {
}
const menuItems: MenuItem[] = [
{ href: "/admin/users", label: "Users", icon: Users },
{ href: "/admin/organizations", label: "Organizations", icon: Building2 },
{ href: "/admin/projects", label: "Projects", icon: FileText },
{ href: "/admin/contracts", label: "Contracts", icon: FileText },
{ href: "/admin/reference", label: "Reference Data", icon: BookOpen },
{
label: "Drawing Master Data",
label: 'Access Control',
icon: Shield,
children: [
{ href: '/admin/access-control/users', label: 'Users' },
{ href: '/admin/access-control/roles', label: 'Roles' },
{ href: '/admin/access-control/organizations', label: 'Organizations' },
],
},
{
label: 'Document Control',
icon: FileStack,
children: [
{ href: "/admin/drawings/contract/volumes", label: "Contract: Volumes" },
{ href: "/admin/drawings/contract/categories", label: "Contract: Categories" },
{ href: "/admin/drawings/contract/sub-categories", label: "Contract: Sub-categories" },
{ href: "/admin/drawings/shop/main-categories", label: "Shop: Main Categories" },
{ href: "/admin/drawings/shop/sub-categories", label: "Shop: Sub-categories" },
]
{ href: '/admin/doc-control/projects', label: 'Projects' },
{ href: '/admin/doc-control/contracts', label: 'Contracts' },
{ href: '/admin/doc-control/numbering', label: 'Numbering' },
{ href: '/admin/doc-control/reference', label: 'Reference Data' },
{ href: '/admin/doc-control/workflows', label: 'Workflows' },
],
},
{ href: "/admin/numbering", label: "Numbering", icon: FileText },
{ href: "/admin/workflows", label: "Workflows", icon: GitGraph },
{ href: "/admin/security/roles", label: "Security Roles", icon: Shield },
{ href: "/admin/security/sessions", label: "Active Sessions", icon: Users },
{ href: "/admin/system-logs/numbering", label: "System Logs", icon: Activity },
{ href: "/admin/audit-logs", label: "Audit Logs", icon: Activity },
{ href: "/admin/settings", label: "Settings", icon: Settings },
{
label: 'Drawing Master',
icon: FileStack, // Or another icon
children: [
{ href: '/admin/doc-control/drawings/contract/volumes', label: 'Contract: Volumes' },
{ href: '/admin/doc-control/drawings/contract/categories', label: 'Contract: Categories' },
{ href: '/admin/doc-control/drawings/contract/sub-categories', label: 'Contract: Sub-categories' },
{ href: '/admin/doc-control/drawings/shop/main-categories', label: 'Shop: Main Categories' },
{ href: '/admin/doc-control/drawings/shop/sub-categories', label: 'Shop: Sub-categories' },
],
},
{
label: 'Monitoring',
icon: Activity,
children: [
{ href: '/admin/monitoring/audit-logs', label: 'Audit Logs' },
{ href: '/admin/monitoring/system-logs/numbering', label: 'System Logs' },
{ href: '/admin/monitoring/sessions', label: 'Active Sessions' },
],
},
{ href: '/admin/settings', label: 'Settings', icon: Settings },
];
export function AdminSidebar() {
@@ -56,23 +74,19 @@ export function AdminSidebar() {
const [expandedMenus, setExpandedMenus] = useState<string[]>(
// Auto-expand if current path matches a child
menuItems
.filter(item => item.children?.some(child => pathname.startsWith(child.href)))
.map(item => item.label)
.filter((item) => item.children?.some((child) => pathname.startsWith(child.href)))
.map((item) => item.label)
);
const toggleMenu = (label: string) => {
setExpandedMenus(prev =>
prev.includes(label)
? prev.filter(l => l !== label)
: [...prev, label]
);
setExpandedMenus((prev) => (prev.includes(label) ? prev.filter((l) => l !== label) : [...prev, label]));
};
return (
<aside className="w-64 border-r bg-card p-4 hidden md:block">
<div className="mb-8 px-2">
<h2 className="text-xl font-bold tracking-tight">Admin Console</h2>
<p className="text-sm text-muted-foreground">LCBP3 DMS</p>
<h2 className="text-xl font-bold tracking-tight">Admin Console</h2>
<p className="text-sm text-muted-foreground">LCBP3 DMS</p>
</div>
<nav className="space-y-1">
@@ -82,28 +96,24 @@ export function AdminSidebar() {
// Has children - collapsible menu
if (item.children) {
const isExpanded = expandedMenus.includes(item.label);
const hasActiveChild = item.children.some(child => pathname.startsWith(child.href));
const hasActiveChild = item.children.some((child) => pathname.startsWith(child.href));
return (
<div key={item.label}>
<button
onClick={() => toggleMenu(item.label)}
className={cn(
"w-full flex items-center justify-between gap-3 px-3 py-2 rounded-lg transition-colors text-sm font-medium",
'w-full flex items-center justify-between gap-3 px-3 py-2 rounded-lg transition-colors text-sm font-medium',
hasActiveChild
? "bg-primary/10 text-primary"
: "text-muted-foreground hover:bg-muted hover:text-foreground"
? 'bg-primary/10 text-primary'
: 'text-muted-foreground hover:bg-muted hover:text-foreground'
)}
>
<span className="flex items-center gap-3">
<Icon className="h-4 w-4" />
<span>{item.label}</span>
</span>
{isExpanded ? (
<ChevronDown className="h-4 w-4" />
) : (
<ChevronRight className="h-4 w-4" />
)}
{isExpanded ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
</button>
{isExpanded && (
@@ -115,10 +125,10 @@ export function AdminSidebar() {
key={child.href}
href={child.href}
className={cn(
"block px-3 py-1.5 rounded-lg transition-colors text-sm",
'block px-3 py-1.5 rounded-lg transition-colors text-sm',
isActive
? "bg-primary text-primary-foreground shadow-sm"
: "text-muted-foreground hover:bg-muted hover:text-foreground"
? 'bg-primary text-primary-foreground shadow-sm'
: 'text-muted-foreground hover:bg-muted hover:text-foreground'
)}
>
{child.label}
@@ -138,10 +148,10 @@ export function AdminSidebar() {
key={item.href}
href={item.href!}
className={cn(
"flex items-center gap-3 px-3 py-2 rounded-lg transition-colors text-sm font-medium",
'flex items-center gap-3 px-3 py-2 rounded-lg transition-colors text-sm font-medium',
isActive
? "bg-primary text-primary-foreground shadow-sm"
: "text-muted-foreground hover:bg-muted hover:text-foreground"
? 'bg-primary text-primary-foreground shadow-sm'
: 'text-muted-foreground hover:bg-muted hover:text-foreground'
)}
>
<Icon className="h-4 w-4" />
@@ -152,9 +162,9 @@ export function AdminSidebar() {
</nav>
<div className="mt-auto pt-8 px-2 fixed bottom-4 w-56">
<Link href="/dashboard" className="text-sm text-muted-foreground hover:text-foreground flex items-center gap-2">
Back to Dashboard
</Link>
<Link href="/dashboard" className="text-sm text-muted-foreground hover:text-foreground flex items-center gap-2">
Back to Dashboard
</Link>
</div>
</aside>
);

View File

@@ -0,0 +1,173 @@
'use client';
import * as React from 'react';
import {
ColumnDef,
flexRender,
getCoreRowModel,
useReactTable,
PaginationState,
SortingState,
getPaginationRowModel,
OnChangeFn,
} from '@tanstack/react-table';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight } from 'lucide-react';
interface ServerDataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[];
data: TData[];
pageCount: number;
pagination: PaginationState;
onPaginationChange: OnChangeFn<PaginationState>;
sorting: SortingState;
onSortingChange: OnChangeFn<SortingState>;
isLoading?: boolean;
}
export function ServerDataTable<TData, TValue>({
columns,
data,
pageCount,
pagination,
onPaginationChange,
sorting,
onSortingChange,
isLoading,
}: ServerDataTableProps<TData, TValue>) {
const table = useReactTable({
data,
columns,
pageCount,
state: {
pagination,
sorting,
},
onPaginationChange,
onSortingChange,
getCoreRowModel: getCoreRowModel(),
manualPagination: true,
manualSorting: true,
});
return (
<div className="space-y-4">
<div className="rounded-md border">
<Table>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<TableHead key={header.id}>
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
</TableHead>
);
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{isLoading ? (
<TableRow>
<TableCell colSpan={columns.length} className="h-24 text-center">
Loading...
</TableCell>
</TableRow>
) : table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow key={row.id} data-state={row.getIsSelected() && 'selected'}>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={columns.length} className="h-24 text-center">
No results.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
<div className="flex items-center justify-between px-2">
<div className="flex-1 text-sm text-muted-foreground">
{table.getFilteredSelectedRowModel && table.getFilteredSelectedRowModel().rows.length > 0 && (
<>
{table.getFilteredSelectedRowModel().rows.length} of {table.getFilteredRowModel().rows.length} row(s)
selected.
</>
)}
</div>
<div className="flex items-center space-x-6 lg:space-x-8">
<div className="flex items-center space-x-2">
<p className="text-sm font-medium">Rows per page</p>
<Select
value={`${table.getState().pagination.pageSize}`}
onValueChange={(value) => {
table.setPageSize(Number(value));
}}
>
<SelectTrigger className="h-8 w-[70px]">
<SelectValue placeholder={table.getState().pagination.pageSize} />
</SelectTrigger>
<SelectContent side="top">
{[10, 20, 30, 40, 50].map((pageSize) => (
<SelectItem key={pageSize} value={`${pageSize}`}>
{pageSize}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex w-[100px] items-center justify-center text-sm font-medium">
Page {table.getState().pagination.pageIndex + 1} of {table.getPageCount()}
</div>
<div className="flex items-center space-x-2">
<Button
variant="outline"
className="hidden h-8 w-8 p-0 lg:flex"
onClick={() => table.setPageIndex(0)}
disabled={!table.getCanPreviousPage()}
>
<span className="sr-only">Go to first page</span>
<ChevronsLeft className="h-4 w-4" />
</Button>
<Button
variant="outline"
className="h-8 w-8 p-0"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
<span className="sr-only">Go to previous page</span>
<ChevronLeft className="h-4 w-4" />
</Button>
<Button
variant="outline"
className="h-8 w-8 p-0"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
<span className="sr-only">Go to next page</span>
<ChevronRight className="h-4 w-4" />
</Button>
<Button
variant="outline"
className="hidden h-8 w-8 p-0 lg:flex"
onClick={() => table.setPageIndex(table.getPageCount() - 1)}
disabled={!table.getCanNextPage()}
>
<span className="sr-only">Go to last page</span>
<ChevronsRight className="h-4 w-4" />
</Button>
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,76 @@
'use client';
import { ColumnDef } from '@tanstack/react-table';
import { Drawing } from '@/types/drawing';
import { Button } from '@/components/ui/button';
import { ArrowUpDown, MoreHorizontal } from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
export const columns: ColumnDef<Drawing>[] = [
{
accessorKey: 'drawingNumber',
header: ({ column }) => {
return (
<Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}>
Drawing No.
<ArrowUpDown className="ml-2 h-4 w-4" />
</Button>
);
},
},
{
accessorKey: 'title',
header: 'Title',
},
{
accessorKey: 'revision',
header: 'Revision',
cell: ({ row }) => row.original.revision || '-',
},
{
accessorKey: 'legacyDrawingNumber',
header: 'Legacy No.',
cell: ({ row }) => row.original.legacyDrawingNumber || '-',
},
{
accessorKey: 'updatedAt',
header: 'Last Updated',
cell: ({ row }) => {
const date = new Date(row.original.updatedAt || '');
return isNaN(date.getTime()) ? '-' : date.toLocaleDateString();
},
},
{
id: 'actions',
cell: ({ row }) => {
const drawing = row.original;
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="h-8 w-8 p-0">
<span className="sr-only">Open menu</span>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuLabel>Actions</DropdownMenuLabel>
<DropdownMenuItem onClick={() => navigator.clipboard.writeText(drawing.drawingNumber)}>
Copy Drawing No.
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem>View Details</DropdownMenuItem>
{/* Add download/view functionality later */}
</DropdownMenuContent>
</DropdownMenu>
);
},
},
];

View File

@@ -1,58 +1,60 @@
"use client";
'use client';
import { DrawingCard } from "@/components/drawings/card";
import { useDrawings } from "@/hooks/use-drawing";
import { Drawing } from "@/types/drawing";
import { Loader2 } from "lucide-react";
import { DrawingCard } from '@/components/drawings/card';
import { useDrawings } from '@/hooks/use-drawing';
import { Drawing } from '@/types/drawing';
import { Loader2 } from 'lucide-react';
import { useState } from 'react';
import { PaginationState, SortingState } from '@tanstack/react-table';
import { ServerDataTable } from '@/components/documents/common/server-data-table';
import { columns } from './columns';
import { SearchContractDrawingDto } from "@/types/dto/drawing/contract-drawing.dto";
import { SearchShopDrawingDto } from "@/types/dto/drawing/shop-drawing.dto";
import { SearchAsBuiltDrawingDto } from "@/types/dto/drawing/asbuilt-drawing.dto";
import { SearchContractDrawingDto } from '@/types/dto/drawing/contract-drawing.dto';
import { SearchShopDrawingDto } from '@/types/dto/drawing/shop-drawing.dto';
import { SearchAsBuiltDrawingDto } from '@/types/dto/drawing/asbuilt-drawing.dto';
type DrawingSearchParams = SearchContractDrawingDto | SearchShopDrawingDto | SearchAsBuiltDrawingDto;
interface DrawingListProps {
type: "CONTRACT" | "SHOP" | "AS_BUILT";
type: 'CONTRACT' | 'SHOP' | 'AS_BUILT';
projectId: number;
filters?: Partial<DrawingSearchParams>;
}
export function DrawingList({ type, projectId, filters }: DrawingListProps) {
const [pagination, setPagination] = useState<PaginationState>({
pageIndex: 0,
pageSize: 20,
});
const [sorting, setSorting] = useState<SortingState>([]);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const { data: drawings, isLoading, isError } = useDrawings(type, { projectId, ...filters } as any);
const {
data: response,
isLoading,
isError,
} = useDrawings(type, {
projectId,
...filters,
page: pagination.pageIndex + 1, // API is 1-based
pageSize: pagination.pageSize,
} as any);
// Note: The hook handles switching services based on type.
// The params { type } might be redundant if getAll doesn't use it, but safe to pass.
if (isLoading) {
return (
<div className="flex justify-center py-12">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
);
}
if (isError) {
return (
<div className="text-center py-12 text-red-500">
Failed to load drawings.
</div>
);
}
if (!drawings?.data || drawings.data.length === 0) {
return (
<div className="text-center py-12 text-muted-foreground border rounded-lg border-dashed">
No drawings found.
</div>
);
}
const drawings = response?.data || [];
const meta = response?.meta || { total: 0, page: 1, limit: 20, totalPages: 0 };
return (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-2 xl:grid-cols-3 gap-6">
{drawings.data.map((drawing: Drawing) => (
<DrawingCard key={drawing.drawingId} drawing={drawing} />
))}
<div>
<ServerDataTable
columns={columns}
data={drawings}
pageCount={meta.totalPages}
pagination={pagination}
onPaginationChange={setPagination}
sorting={sorting}
onSortingChange={setSorting}
isLoading={isLoading}
/>
</div>
);
}

View File

@@ -0,0 +1,27 @@
import apiClient from '@/lib/api/client';
export interface Session {
id: string; // tokenId
userId: number;
user: {
username: string;
firstName: string;
lastName: string;
};
deviceName: string;
ipAddress: string;
lastActive: string;
isCurrent: boolean;
}
export const sessionService = {
getActiveSessions: async () => {
const response = await apiClient.get<any>('/auth/sessions');
return response.data.data || response.data;
},
revokeSession: async (sessionId: number) => {
const response = await apiClient.delete(`/auth/sessions/${sessionId}`);
return response.data;
},
};

View File

@@ -1,17 +1,17 @@
// File: middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { auth } from "@/lib/auth";
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { auth } from '@/lib/auth';
// รายการ Route ที่ไม่ต้อง Login ก็เข้าได้ (Public Routes)
const publicRoutes = ["/login", "/register", "/"];
const publicRoutes = ['/login', '/register', '/'];
export default auth((req) => {
const isLoggedIn = !!req.auth;
const { nextUrl } = req;
const isPublicRoute = publicRoutes.includes(nextUrl.pathname);
const isAuthRoute = nextUrl.pathname.startsWith("/api/auth");
const isAuthRoute = nextUrl.pathname.startsWith('/api/auth');
// 1. ถ้าเป็น API Auth routes ให้ผ่านไปเลย
if (isAuthRoute) {
@@ -19,8 +19,8 @@ export default auth((req) => {
}
// 2. ถ้า Login อยู่แล้ว แต่พยายามเข้าหน้า Login -> ให้ไป Dashboard
if (isLoggedIn && nextUrl.pathname === "/login") {
return Response.redirect(new URL("/dashboard", nextUrl));
if (isLoggedIn && nextUrl.pathname === '/login') {
return Response.redirect(new URL('/dashboard', nextUrl));
}
// 3. ถ้ายังไม่ Login และพยายามเข้า Private Route -> ให้ไป Login
@@ -30,11 +30,19 @@ export default auth((req) => {
if (nextUrl.search) {
callbackUrl += nextUrl.search;
}
const encodedCallbackUrl = encodeURIComponent(callbackUrl);
return Response.redirect(new URL(`/login?callbackUrl=${encodedCallbackUrl}`, nextUrl));
}
// 4. Protect Admin Routes (Security Phase 1)
if (nextUrl.pathname.startsWith('/admin')) {
const userRole = req.auth?.user?.role as string | undefined;
if (userRole !== 'ADMIN' && userRole !== 'DC') {
return Response.redirect(new URL('/dashboard', nextUrl));
}
}
return NextResponse.next(); // แก้ไขจาก null
});
@@ -51,4 +59,4 @@ export const config = {
*/
'/((?!api|_next/static|_next/image|favicon.ico|images).*)',
],
};
};