fix: TypeScript 타입 오류 수정 및 설정 페이지 추가
- BOMItem Omit 타입 시그니처 통일 (useTemplateManagement, SectionsTab, ItemMasterContext) - HeadersInit → Record<string, string> 타입 변경 - Zustand useShallow 마이그레이션 (zustand/react/shallow) - DataTable, ListPageTemplate 제네릭 타입 제약 추가 - 설정 관리 페이지 추가 (직급, 직책, 휴가정책, 근무일정, 권한) - HR 관리 페이지 추가 (급여, 휴가) - 단가관리 페이지 리팩토링 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,482 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { ChevronDown, ChevronRight, Shield, ArrowLeft } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import { PageHeader } from '@/components/organisms/PageHeader';
|
||||
import { PageLayout } from '@/components/organisms/PageLayout';
|
||||
import type { Permission, MenuPermission, PermissionType } from './types';
|
||||
|
||||
interface PermissionDetailProps {
|
||||
permission: Permission;
|
||||
onBack: () => void;
|
||||
onSave: (permission: Permission) => void;
|
||||
onDelete?: (permission: Permission) => void;
|
||||
}
|
||||
|
||||
// 메뉴 구조 타입 (localStorage user.menu와 동일한 구조)
|
||||
interface SerializableMenuItem {
|
||||
id: string;
|
||||
label: string;
|
||||
iconName: string;
|
||||
path: string;
|
||||
children?: SerializableMenuItem[];
|
||||
}
|
||||
|
||||
// 권한 타입 (기획서 기준: 전체 제외)
|
||||
const PERMISSION_TYPES: PermissionType[] = ['view', 'create', 'update', 'delete', 'approve', 'export', 'manage'];
|
||||
const PERMISSION_LABELS_MAP: Record<PermissionType, string> = {
|
||||
view: '조회',
|
||||
create: '생성',
|
||||
update: '수정',
|
||||
delete: '삭제',
|
||||
approve: '승인',
|
||||
export: '내보내기',
|
||||
manage: '관리',
|
||||
};
|
||||
|
||||
// 제외할 메뉴 ID 목록 (시스템 설정 하위 메뉴)
|
||||
const EXCLUDED_MENU_IDS = ['database', 'system-monitoring', 'security-management', 'system-settings'];
|
||||
|
||||
// 메뉴 필터링 함수 (제외 목록에 있는 메뉴 제거)
|
||||
const filterExcludedMenus = (menus: SerializableMenuItem[]): SerializableMenuItem[] => {
|
||||
return menus
|
||||
.filter(menu => !EXCLUDED_MENU_IDS.includes(menu.id))
|
||||
.map(menu => {
|
||||
if (menu.children && menu.children.length > 0) {
|
||||
const filteredChildren = menu.children.filter(
|
||||
child => !EXCLUDED_MENU_IDS.includes(child.id)
|
||||
);
|
||||
// 자식이 모두 필터링되면 부모도 제거
|
||||
if (filteredChildren.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return { ...menu, children: filteredChildren };
|
||||
}
|
||||
return menu;
|
||||
})
|
||||
.filter((menu): menu is SerializableMenuItem => menu !== null);
|
||||
};
|
||||
|
||||
// localStorage에서 메뉴 데이터 가져오기
|
||||
const getMenuFromLocalStorage = (): SerializableMenuItem[] => {
|
||||
if (typeof window === 'undefined') return [];
|
||||
|
||||
try {
|
||||
const userDataStr = localStorage.getItem('user');
|
||||
if (userDataStr) {
|
||||
const userData = JSON.parse(userDataStr);
|
||||
if (userData.menu && Array.isArray(userData.menu)) {
|
||||
// 제외 목록 필터링 적용
|
||||
return filterExcludedMenus(userData.menu);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load menu from localStorage:', error);
|
||||
}
|
||||
|
||||
// 기본 메뉴 (user.menu가 없는 경우)
|
||||
return [
|
||||
{ id: 'dashboard', label: '대시보드', iconName: 'layout-dashboard', path: '/dashboard' },
|
||||
{
|
||||
id: 'sales',
|
||||
label: '판매관리',
|
||||
iconName: 'shopping-cart',
|
||||
path: '#',
|
||||
children: [
|
||||
{ id: 'customer-management', label: '거래처관리', iconName: 'building-2', path: '/sales/client-management-sales-admin' },
|
||||
{ id: 'quote-management', label: '견적관리', iconName: 'receipt', path: '/sales/quote-management' },
|
||||
{ id: 'pricing-management', label: '단가관리', iconName: 'dollar-sign', path: '/sales/pricing-management' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'master-data',
|
||||
label: '기준정보',
|
||||
iconName: 'settings',
|
||||
path: '#',
|
||||
children: [
|
||||
{ id: 'item-master', label: '품목기준관리', iconName: 'package', path: '/master-data/item-master-data-management' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'hr',
|
||||
label: '인사관리',
|
||||
iconName: 'users',
|
||||
path: '#',
|
||||
children: [
|
||||
{ id: 'vacation-management', label: '휴가관리', iconName: 'calendar', path: '/hr/vacation-management' },
|
||||
{ id: 'salary-management', label: '급여관리', iconName: 'wallet', path: '/hr/salary-management' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'settings',
|
||||
label: '기준정보 설정',
|
||||
iconName: 'settings-2',
|
||||
path: '#',
|
||||
children: [
|
||||
{ id: 'ranks', label: '직급관리', iconName: 'badge', path: '/settings/ranks' },
|
||||
{ id: 'titles', label: '직책관리', iconName: 'user-cog', path: '/settings/titles' },
|
||||
{ id: 'permissions', label: '권한관리', iconName: 'shield', path: '/settings/permissions' },
|
||||
],
|
||||
},
|
||||
];
|
||||
};
|
||||
|
||||
// 메뉴 구조를 flat한 MenuPermission 배열로 변환
|
||||
const convertMenuToPermissions = (
|
||||
menus: SerializableMenuItem[],
|
||||
existingPermissions: MenuPermission[]
|
||||
): MenuPermission[] => {
|
||||
const result: MenuPermission[] = [];
|
||||
|
||||
const processMenu = (menu: SerializableMenuItem, parentId?: string) => {
|
||||
// 기존 권한 데이터 찾기
|
||||
const existing = existingPermissions.find(ep => ep.menuId === menu.id);
|
||||
|
||||
result.push({
|
||||
menuId: menu.id,
|
||||
menuName: menu.label,
|
||||
parentMenuId: parentId,
|
||||
permissions: existing?.permissions || {},
|
||||
});
|
||||
|
||||
// 자식 메뉴 처리
|
||||
if (menu.children && menu.children.length > 0) {
|
||||
menu.children.forEach(child => processMenu(child, menu.id));
|
||||
}
|
||||
};
|
||||
|
||||
menus.forEach(menu => processMenu(menu));
|
||||
return result;
|
||||
};
|
||||
|
||||
export function PermissionDetail({ permission, onBack, onSave, onDelete }: PermissionDetailProps) {
|
||||
const [name, setName] = useState(permission.name);
|
||||
const [status, setStatus] = useState(permission.status);
|
||||
const [menuStructure, setMenuStructure] = useState<SerializableMenuItem[]>([]);
|
||||
const [menuPermissions, setMenuPermissions] = useState<MenuPermission[]>([]);
|
||||
const [expandedMenus, setExpandedMenus] = useState<Set<string>>(new Set());
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
|
||||
// 메뉴 구조 로드 (localStorage에서)
|
||||
useEffect(() => {
|
||||
const menus = getMenuFromLocalStorage();
|
||||
setMenuStructure(menus);
|
||||
|
||||
// 기존 권한 데이터와 메뉴 구조 병합
|
||||
const permissions = convertMenuToPermissions(menus, permission.menuPermissions);
|
||||
setMenuPermissions(permissions);
|
||||
|
||||
// 기본적으로 모든 부모 메뉴 접힌 상태로 시작
|
||||
setExpandedMenus(new Set());
|
||||
}, [permission.menuPermissions]);
|
||||
|
||||
// 부모 메뉴 접기/펼치기
|
||||
const toggleMenuExpand = (menuId: string) => {
|
||||
setExpandedMenus(prev => {
|
||||
const newSet = new Set(prev);
|
||||
if (newSet.has(menuId)) {
|
||||
newSet.delete(menuId);
|
||||
} else {
|
||||
newSet.add(menuId);
|
||||
}
|
||||
return newSet;
|
||||
});
|
||||
};
|
||||
|
||||
// 메뉴가 부모 메뉴인지 확인
|
||||
const isParentMenu = (menuId: string): boolean => {
|
||||
const menu = menuStructure.find(m => m.id === menuId);
|
||||
return !!(menu?.children && menu.children.length > 0);
|
||||
};
|
||||
|
||||
// 권한 토글 (자동 저장)
|
||||
const handlePermissionToggle = (menuId: string, permType: PermissionType) => {
|
||||
const newMenuPermissions = menuPermissions.map(mp =>
|
||||
mp.menuId === menuId
|
||||
? {
|
||||
...mp,
|
||||
permissions: {
|
||||
...mp.permissions,
|
||||
[permType]: !mp.permissions[permType],
|
||||
},
|
||||
}
|
||||
: mp
|
||||
);
|
||||
setMenuPermissions(newMenuPermissions);
|
||||
|
||||
onSave({
|
||||
...permission,
|
||||
name,
|
||||
status,
|
||||
menuPermissions: newMenuPermissions,
|
||||
updatedAt: new Date().toISOString(),
|
||||
});
|
||||
};
|
||||
|
||||
// 전체 선택/해제 (열 기준) - 헤더 체크박스
|
||||
const handleColumnSelectAll = (permType: PermissionType, checked: boolean) => {
|
||||
const newMenuPermissions = menuPermissions.map(mp => ({
|
||||
...mp,
|
||||
permissions: {
|
||||
...mp.permissions,
|
||||
[permType]: checked,
|
||||
},
|
||||
}));
|
||||
setMenuPermissions(newMenuPermissions);
|
||||
|
||||
onSave({
|
||||
...permission,
|
||||
name,
|
||||
status,
|
||||
menuPermissions: newMenuPermissions,
|
||||
updatedAt: new Date().toISOString(),
|
||||
});
|
||||
};
|
||||
|
||||
// 기본 정보 변경
|
||||
const handleNameChange = (newName: string) => setName(newName);
|
||||
|
||||
const handleNameBlur = () => {
|
||||
if (name !== permission.name) {
|
||||
onSave({
|
||||
...permission,
|
||||
name,
|
||||
status,
|
||||
menuPermissions,
|
||||
updatedAt: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleStatusChange = (newStatus: 'active' | 'hidden') => {
|
||||
setStatus(newStatus);
|
||||
onSave({
|
||||
...permission,
|
||||
name,
|
||||
status: newStatus,
|
||||
menuPermissions,
|
||||
updatedAt: new Date().toISOString(),
|
||||
});
|
||||
};
|
||||
|
||||
// 삭제
|
||||
const handleDelete = () => setDeleteDialogOpen(true);
|
||||
|
||||
const confirmDelete = () => {
|
||||
onDelete?.(permission);
|
||||
setDeleteDialogOpen(false);
|
||||
onBack();
|
||||
};
|
||||
|
||||
// 메뉴 행 렌더링 (재귀적으로 부모-자식 처리)
|
||||
const renderMenuRows = () => {
|
||||
const rows: React.ReactElement[] = [];
|
||||
|
||||
menuStructure.forEach(menu => {
|
||||
const mp = menuPermissions.find(p => p.menuId === menu.id);
|
||||
if (!mp) return;
|
||||
|
||||
const hasChildren = menu.children && menu.children.length > 0;
|
||||
const isExpanded = expandedMenus.has(menu.id);
|
||||
|
||||
// 부모 메뉴 행
|
||||
rows.push(
|
||||
<TableRow key={menu.id} className="hover:bg-muted/50">
|
||||
<TableCell className="font-medium">
|
||||
<div className="flex items-center gap-2">
|
||||
{hasChildren && (
|
||||
<button
|
||||
onClick={() => toggleMenuExpand(menu.id)}
|
||||
className="p-0.5 hover:bg-accent rounded"
|
||||
>
|
||||
{isExpanded ? (
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
) : (
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
<span>{menu.label}</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
{PERMISSION_TYPES.map(pt => (
|
||||
<TableCell key={pt} className="text-center">
|
||||
<Checkbox
|
||||
checked={mp.permissions[pt] || false}
|
||||
onCheckedChange={() => handlePermissionToggle(menu.id, pt)}
|
||||
/>
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
);
|
||||
|
||||
// 자식 메뉴 행 (펼쳐진 경우에만)
|
||||
if (hasChildren && isExpanded) {
|
||||
menu.children?.forEach(child => {
|
||||
const childMp = menuPermissions.find(p => p.menuId === child.id);
|
||||
if (!childMp) return;
|
||||
|
||||
rows.push(
|
||||
<TableRow key={child.id} className="hover:bg-muted/50">
|
||||
<TableCell className="pl-10 text-muted-foreground">
|
||||
- {child.label}
|
||||
</TableCell>
|
||||
{PERMISSION_TYPES.map(pt => (
|
||||
<TableCell key={pt} className="text-center">
|
||||
<Checkbox
|
||||
checked={childMp.permissions[pt] || false}
|
||||
onCheckedChange={() => handlePermissionToggle(child.id, pt)}
|
||||
/>
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return rows;
|
||||
};
|
||||
|
||||
return (
|
||||
<PageLayout>
|
||||
{/* 페이지 헤더 */}
|
||||
<PageHeader
|
||||
title="권한 상세"
|
||||
description="권한 상세 정보를 관리합니다"
|
||||
icon={Shield}
|
||||
actions={
|
||||
<Button variant="ghost" size="sm" onClick={onBack}>
|
||||
<ArrowLeft className="h-4 w-4 mr-2" />
|
||||
목록으로
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* 삭제/수정 버튼 (타이틀 아래, 기본정보 위) */}
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="outline" onClick={handleDelete}>
|
||||
삭제
|
||||
</Button>
|
||||
<Button onClick={() => onBack()}>
|
||||
수정
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 기본 정보 */}
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<h3 className="text-lg font-semibold mb-4">기본 정보</h3>
|
||||
<div className="grid grid-cols-2 gap-6">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="perm-name">권한명</Label>
|
||||
<Input
|
||||
id="perm-name"
|
||||
value={name}
|
||||
onChange={(e) => handleNameChange(e.target.value)}
|
||||
onBlur={handleNameBlur}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="perm-status">상태</Label>
|
||||
<Select value={status} onValueChange={handleStatusChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="active">공개</SelectItem>
|
||||
<SelectItem value="hidden">숨김</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 메뉴별 권한 설정 테이블 */}
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<h3 className="text-lg font-semibold mb-4">메뉴</h3>
|
||||
<div className="overflow-x-auto">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow className="border-b">
|
||||
<TableHead className="w-64 py-4">메뉴</TableHead>
|
||||
{PERMISSION_TYPES.map(pt => (
|
||||
<TableHead key={pt} className="text-center w-24 py-4">
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<span className="text-sm font-medium">{PERMISSION_LABELS_MAP[pt]}</span>
|
||||
<Checkbox
|
||||
checked={menuPermissions.length > 0 && menuPermissions.every(mp => mp.permissions[pt])}
|
||||
onCheckedChange={(checked) => handleColumnSelectAll(pt, !!checked)}
|
||||
/>
|
||||
</div>
|
||||
</TableHead>
|
||||
))}
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{renderMenuRows()}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 삭제 확인 다이얼로그 */}
|
||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>권한 삭제</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
"{permission.name}" 권한을 삭제하시겠습니까?
|
||||
<br />
|
||||
<span className="text-destructive">
|
||||
이 권한을 사용 중인 사원이 있으면 해당 사원의 권한이 초기화됩니다.
|
||||
</span>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>취소</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={confirmDelete}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
삭제
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,659 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState, useEffect, useCallback } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { ChevronDown, ChevronRight, Shield, ArrowLeft, Trash2, Save } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import { PageHeader } from '@/components/organisms/PageHeader';
|
||||
import { PageLayout } from '@/components/organisms/PageLayout';
|
||||
import type { Permission, MenuPermission, PermissionType } from './types';
|
||||
|
||||
interface PermissionDetailClientProps {
|
||||
permissionId: string;
|
||||
isNew?: boolean;
|
||||
}
|
||||
|
||||
// 메뉴 구조 타입 (localStorage user.menu와 동일한 구조)
|
||||
interface SerializableMenuItem {
|
||||
id: string;
|
||||
label: string;
|
||||
iconName: string;
|
||||
path: string;
|
||||
children?: SerializableMenuItem[];
|
||||
}
|
||||
|
||||
// 권한 타입 (기획서 기준: 전체 제외)
|
||||
const PERMISSION_TYPES: PermissionType[] = ['view', 'create', 'update', 'delete', 'approve', 'export', 'manage'];
|
||||
const PERMISSION_LABELS_MAP: Record<PermissionType, string> = {
|
||||
view: '조회',
|
||||
create: '생성',
|
||||
update: '수정',
|
||||
delete: '삭제',
|
||||
approve: '승인',
|
||||
export: '내보내기',
|
||||
manage: '관리',
|
||||
};
|
||||
|
||||
// 제외할 메뉴 ID 목록 (시스템 설정 하위 메뉴)
|
||||
const EXCLUDED_MENU_IDS = ['database', 'system-monitoring', 'security-management', 'system-settings'];
|
||||
|
||||
// 메뉴 필터링 함수 (제외 목록에 있는 메뉴 제거)
|
||||
const filterExcludedMenus = (menus: SerializableMenuItem[]): SerializableMenuItem[] => {
|
||||
return menus
|
||||
.filter(menu => !EXCLUDED_MENU_IDS.includes(menu.id))
|
||||
.map(menu => {
|
||||
if (menu.children && menu.children.length > 0) {
|
||||
const filteredChildren = menu.children.filter(
|
||||
child => !EXCLUDED_MENU_IDS.includes(child.id)
|
||||
);
|
||||
// 자식이 모두 필터링되면 부모도 제거
|
||||
if (filteredChildren.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return { ...menu, children: filteredChildren };
|
||||
}
|
||||
return menu;
|
||||
})
|
||||
.filter((menu): menu is SerializableMenuItem => menu !== null);
|
||||
};
|
||||
|
||||
// localStorage에서 메뉴 데이터 가져오기
|
||||
const getMenuFromLocalStorage = (): SerializableMenuItem[] => {
|
||||
if (typeof window === 'undefined') return [];
|
||||
|
||||
try {
|
||||
const userDataStr = localStorage.getItem('user');
|
||||
if (userDataStr) {
|
||||
const userData = JSON.parse(userDataStr);
|
||||
if (userData.menu && Array.isArray(userData.menu)) {
|
||||
// 제외 목록 필터링 적용
|
||||
return filterExcludedMenus(userData.menu);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load menu from localStorage:', error);
|
||||
}
|
||||
|
||||
// 기본 메뉴 (user.menu가 없는 경우)
|
||||
return [
|
||||
{ id: 'dashboard', label: '대시보드', iconName: 'layout-dashboard', path: '/dashboard' },
|
||||
{
|
||||
id: 'sales',
|
||||
label: '판매관리',
|
||||
iconName: 'shopping-cart',
|
||||
path: '#',
|
||||
children: [
|
||||
{ id: 'customer-management', label: '거래처관리', iconName: 'building-2', path: '/sales/client-management-sales-admin' },
|
||||
{ id: 'quote-management', label: '견적관리', iconName: 'receipt', path: '/sales/quote-management' },
|
||||
{ id: 'pricing-management', label: '단가관리', iconName: 'dollar-sign', path: '/sales/pricing-management' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'master-data',
|
||||
label: '기준정보',
|
||||
iconName: 'settings',
|
||||
path: '#',
|
||||
children: [
|
||||
{ id: 'item-master', label: '품목기준관리', iconName: 'package', path: '/master-data/item-master-data-management' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'hr',
|
||||
label: '인사관리',
|
||||
iconName: 'users',
|
||||
path: '#',
|
||||
children: [
|
||||
{ id: 'vacation-management', label: '휴가관리', iconName: 'calendar', path: '/hr/vacation-management' },
|
||||
{ id: 'salary-management', label: '급여관리', iconName: 'wallet', path: '/hr/salary-management' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'settings',
|
||||
label: '기준정보 설정',
|
||||
iconName: 'settings-2',
|
||||
path: '#',
|
||||
children: [
|
||||
{ id: 'ranks', label: '직급관리', iconName: 'badge', path: '/settings/ranks' },
|
||||
{ id: 'titles', label: '직책관리', iconName: 'user-cog', path: '/settings/titles' },
|
||||
{ id: 'permissions', label: '권한관리', iconName: 'shield', path: '/settings/permissions' },
|
||||
],
|
||||
},
|
||||
];
|
||||
};
|
||||
|
||||
// 메뉴 구조를 flat한 MenuPermission 배열로 변환
|
||||
const convertMenuToPermissions = (
|
||||
menus: SerializableMenuItem[],
|
||||
existingPermissions: MenuPermission[]
|
||||
): MenuPermission[] => {
|
||||
const result: MenuPermission[] = [];
|
||||
|
||||
const processMenu = (menu: SerializableMenuItem, parentId?: string) => {
|
||||
// 기존 권한 데이터 찾기
|
||||
const existing = existingPermissions.find(ep => ep.menuId === menu.id);
|
||||
|
||||
result.push({
|
||||
menuId: menu.id,
|
||||
menuName: menu.label,
|
||||
parentMenuId: parentId,
|
||||
permissions: existing?.permissions || {},
|
||||
});
|
||||
|
||||
// 자식 메뉴 처리
|
||||
if (menu.children && menu.children.length > 0) {
|
||||
menu.children.forEach(child => processMenu(child, menu.id));
|
||||
}
|
||||
};
|
||||
|
||||
menus.forEach(menu => processMenu(menu));
|
||||
return result;
|
||||
};
|
||||
|
||||
// localStorage 키
|
||||
const PERMISSIONS_STORAGE_KEY = 'buddy_permissions';
|
||||
|
||||
// 기본 권한 데이터
|
||||
const defaultPermissions: Permission[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: '관리자',
|
||||
status: 'active',
|
||||
menuPermissions: [],
|
||||
createdAt: '2025-01-01T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: '일반사용자',
|
||||
status: 'active',
|
||||
menuPermissions: [],
|
||||
createdAt: '2025-01-15T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
name: '인사담당자',
|
||||
status: 'active',
|
||||
menuPermissions: [],
|
||||
createdAt: '2025-02-01T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
name: '결재담당자',
|
||||
status: 'active',
|
||||
menuPermissions: [],
|
||||
createdAt: '2025-02-15T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 5,
|
||||
name: '게스트',
|
||||
status: 'hidden',
|
||||
menuPermissions: [],
|
||||
createdAt: '2025-03-01T00:00:00Z',
|
||||
},
|
||||
];
|
||||
|
||||
// localStorage에서 권한 데이터 로드
|
||||
const loadPermissions = (): Permission[] => {
|
||||
if (typeof window === 'undefined') return defaultPermissions;
|
||||
|
||||
try {
|
||||
const stored = localStorage.getItem(PERMISSIONS_STORAGE_KEY);
|
||||
if (stored) {
|
||||
return JSON.parse(stored);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load permissions:', error);
|
||||
}
|
||||
return defaultPermissions;
|
||||
};
|
||||
|
||||
// localStorage에 권한 데이터 저장
|
||||
const savePermissions = (permissions: Permission[]) => {
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
try {
|
||||
localStorage.setItem(PERMISSIONS_STORAGE_KEY, JSON.stringify(permissions));
|
||||
// 커스텀 이벤트 발생 (목록 페이지에서 감지)
|
||||
window.dispatchEvent(new CustomEvent('permissionsUpdated', { detail: permissions }));
|
||||
} catch (error) {
|
||||
console.error('Failed to save permissions:', error);
|
||||
}
|
||||
};
|
||||
|
||||
export function PermissionDetailClient({ permissionId, isNew = false }: PermissionDetailClientProps) {
|
||||
const router = useRouter();
|
||||
const [permission, setPermission] = useState<Permission | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
const [status, setStatus] = useState<'active' | 'hidden'>('active');
|
||||
const [menuStructure, setMenuStructure] = useState<SerializableMenuItem[]>([]);
|
||||
const [menuPermissions, setMenuPermissions] = useState<MenuPermission[]>([]);
|
||||
const [expandedMenus, setExpandedMenus] = useState<Set<string>>(new Set());
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isSaved, setIsSaved] = useState(!isNew); // 새 권한은 저장 전 상태
|
||||
|
||||
// 권한 데이터 로드
|
||||
useEffect(() => {
|
||||
const menus = getMenuFromLocalStorage();
|
||||
setMenuStructure(menus);
|
||||
|
||||
if (isNew) {
|
||||
// 새 권한 등록 모드
|
||||
setName('');
|
||||
setStatus('active');
|
||||
const emptyPermissions = convertMenuToPermissions(menus, []);
|
||||
setMenuPermissions(emptyPermissions);
|
||||
setPermission(null);
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// 기존 권한 수정 모드
|
||||
const permissions = loadPermissions();
|
||||
const found = permissions.find(p => p.id.toString() === permissionId);
|
||||
|
||||
if (found) {
|
||||
setPermission(found);
|
||||
setName(found.name);
|
||||
setStatus(found.status);
|
||||
|
||||
// 기존 권한 데이터와 메뉴 구조 병합
|
||||
const mergedPermissions = convertMenuToPermissions(menus, found.menuPermissions);
|
||||
setMenuPermissions(mergedPermissions);
|
||||
}
|
||||
|
||||
setIsLoading(false);
|
||||
}, [permissionId, isNew]);
|
||||
|
||||
// 뒤로가기
|
||||
const handleBack = useCallback(() => {
|
||||
router.push('/settings/permissions');
|
||||
}, [router]);
|
||||
|
||||
// 부모 메뉴 접기/펼치기
|
||||
const toggleMenuExpand = (menuId: string) => {
|
||||
setExpandedMenus(prev => {
|
||||
const newSet = new Set(prev);
|
||||
if (newSet.has(menuId)) {
|
||||
newSet.delete(menuId);
|
||||
} else {
|
||||
newSet.add(menuId);
|
||||
}
|
||||
return newSet;
|
||||
});
|
||||
};
|
||||
|
||||
// 권한 저장 (기존 권한 수정 시)
|
||||
const savePermission = useCallback((updatedPermission: Permission) => {
|
||||
const permissions = loadPermissions();
|
||||
const updatedPermissions = permissions.map(p =>
|
||||
p.id === updatedPermission.id ? updatedPermission : p
|
||||
);
|
||||
savePermissions(updatedPermissions);
|
||||
setPermission(updatedPermission);
|
||||
}, []);
|
||||
|
||||
// 새 권한 저장
|
||||
const handleSaveNew = useCallback(() => {
|
||||
if (!name.trim()) {
|
||||
alert('권한명을 입력해주세요.');
|
||||
return;
|
||||
}
|
||||
|
||||
const permissions = loadPermissions();
|
||||
const newId = Math.max(...permissions.map(p => p.id), 0) + 1;
|
||||
const newPermission: Permission = {
|
||||
id: newId,
|
||||
name: name.trim(),
|
||||
status,
|
||||
menuPermissions,
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
const updatedPermissions = [...permissions, newPermission];
|
||||
savePermissions(updatedPermissions);
|
||||
setPermission(newPermission);
|
||||
setIsSaved(true);
|
||||
|
||||
// 저장 후 상세 페이지로 이동 (URL 변경)
|
||||
router.replace(`/settings/permissions/${newId}`);
|
||||
}, [name, status, menuPermissions, router]);
|
||||
|
||||
// 권한 토글 (기존 권한은 자동 저장, 새 권한은 상태만 업데이트)
|
||||
const handlePermissionToggle = (menuId: string, permType: PermissionType) => {
|
||||
const newMenuPermissions = menuPermissions.map(mp =>
|
||||
mp.menuId === menuId
|
||||
? {
|
||||
...mp,
|
||||
permissions: {
|
||||
...mp.permissions,
|
||||
[permType]: !mp.permissions[permType],
|
||||
},
|
||||
}
|
||||
: mp
|
||||
);
|
||||
setMenuPermissions(newMenuPermissions);
|
||||
|
||||
// 기존 권한인 경우에만 자동 저장
|
||||
if (permission && isSaved) {
|
||||
const updatedPermission = {
|
||||
...permission,
|
||||
name,
|
||||
status,
|
||||
menuPermissions: newMenuPermissions,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
savePermission(updatedPermission);
|
||||
}
|
||||
};
|
||||
|
||||
// 전체 선택/해제 (열 기준) - 헤더 체크박스
|
||||
const handleColumnSelectAll = (permType: PermissionType, checked: boolean) => {
|
||||
const newMenuPermissions = menuPermissions.map(mp => ({
|
||||
...mp,
|
||||
permissions: {
|
||||
...mp.permissions,
|
||||
[permType]: checked,
|
||||
},
|
||||
}));
|
||||
setMenuPermissions(newMenuPermissions);
|
||||
|
||||
// 기존 권한인 경우에만 자동 저장
|
||||
if (permission && isSaved) {
|
||||
const updatedPermission = {
|
||||
...permission,
|
||||
name,
|
||||
status,
|
||||
menuPermissions: newMenuPermissions,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
savePermission(updatedPermission);
|
||||
}
|
||||
};
|
||||
|
||||
// 기본 정보 변경
|
||||
const handleNameBlur = () => {
|
||||
// 새 권한 모드에서는 저장하지 않음
|
||||
if (!permission || !isSaved || name === permission.name) return;
|
||||
|
||||
const updatedPermission = {
|
||||
...permission,
|
||||
name,
|
||||
status,
|
||||
menuPermissions,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
savePermission(updatedPermission);
|
||||
};
|
||||
|
||||
const handleStatusChange = (newStatus: 'active' | 'hidden') => {
|
||||
setStatus(newStatus);
|
||||
|
||||
// 기존 권한인 경우에만 자동 저장
|
||||
if (permission && isSaved) {
|
||||
const updatedPermission = {
|
||||
...permission,
|
||||
name,
|
||||
status: newStatus,
|
||||
menuPermissions,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
savePermission(updatedPermission);
|
||||
}
|
||||
};
|
||||
|
||||
// 삭제
|
||||
const handleDelete = () => setDeleteDialogOpen(true);
|
||||
|
||||
const confirmDelete = () => {
|
||||
if (!permission) return;
|
||||
|
||||
const permissions = loadPermissions();
|
||||
const updatedPermissions = permissions.filter(p => p.id !== permission.id);
|
||||
savePermissions(updatedPermissions);
|
||||
setDeleteDialogOpen(false);
|
||||
handleBack();
|
||||
};
|
||||
|
||||
// 메뉴 행 렌더링 (재귀적으로 부모-자식 처리)
|
||||
const renderMenuRows = () => {
|
||||
const rows: React.ReactElement[] = [];
|
||||
|
||||
menuStructure.forEach(menu => {
|
||||
const mp = menuPermissions.find(p => p.menuId === menu.id);
|
||||
if (!mp) return;
|
||||
|
||||
const hasChildren = menu.children && menu.children.length > 0;
|
||||
const isExpanded = expandedMenus.has(menu.id);
|
||||
|
||||
// 부모 메뉴 행
|
||||
rows.push(
|
||||
<TableRow key={menu.id} className="hover:bg-muted/50">
|
||||
<TableCell className="font-medium">
|
||||
<div className="flex items-center gap-2">
|
||||
{hasChildren && (
|
||||
<button
|
||||
onClick={() => toggleMenuExpand(menu.id)}
|
||||
className="p-0.5 hover:bg-accent rounded"
|
||||
>
|
||||
{isExpanded ? (
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
) : (
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
<span>{menu.label}</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
{PERMISSION_TYPES.map(pt => (
|
||||
<TableCell key={pt} className="text-center">
|
||||
<Checkbox
|
||||
checked={mp.permissions[pt] || false}
|
||||
onCheckedChange={() => handlePermissionToggle(menu.id, pt)}
|
||||
/>
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
);
|
||||
|
||||
// 자식 메뉴 행 (펼쳐진 경우에만)
|
||||
if (hasChildren && isExpanded) {
|
||||
menu.children?.forEach(child => {
|
||||
const childMp = menuPermissions.find(p => p.menuId === child.id);
|
||||
if (!childMp) return;
|
||||
|
||||
rows.push(
|
||||
<TableRow key={child.id} className="hover:bg-muted/50">
|
||||
<TableCell className="pl-10 text-muted-foreground">
|
||||
- {child.label}
|
||||
</TableCell>
|
||||
{PERMISSION_TYPES.map(pt => (
|
||||
<TableCell key={pt} className="text-center">
|
||||
<Checkbox
|
||||
checked={childMp.permissions[pt] || false}
|
||||
onCheckedChange={() => handlePermissionToggle(child.id, pt)}
|
||||
/>
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return rows;
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<PageLayout>
|
||||
<div className="flex items-center justify-center h-64">
|
||||
<div className="text-muted-foreground">로딩 중...</div>
|
||||
</div>
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
// 새 권한 등록 모드가 아닌데 권한을 찾지 못한 경우
|
||||
if (!permission && !isNew) {
|
||||
return (
|
||||
<PageLayout>
|
||||
<div className="flex flex-col items-center justify-center h-64 gap-4">
|
||||
<div className="text-muted-foreground">권한을 찾을 수 없습니다.</div>
|
||||
<Button onClick={handleBack}>
|
||||
<ArrowLeft className="h-4 w-4 mr-2" />
|
||||
목록으로 돌아가기
|
||||
</Button>
|
||||
</div>
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<PageLayout>
|
||||
{/* 페이지 헤더 */}
|
||||
<PageHeader
|
||||
title={isNew ? '권한 등록' : '권한 상세'}
|
||||
description={isNew ? '새 권한을 등록합니다' : '권한 상세 정보를 관리합니다'}
|
||||
icon={Shield}
|
||||
actions={
|
||||
<Button variant="ghost" size="sm" onClick={handleBack}>
|
||||
<ArrowLeft className="h-4 w-4 mr-2" />
|
||||
목록으로
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* 저장/삭제 버튼 */}
|
||||
<div className="flex justify-end gap-2">
|
||||
{isNew ? (
|
||||
<Button onClick={handleSaveNew}>
|
||||
<Save className="h-4 w-4 mr-2" />
|
||||
저장
|
||||
</Button>
|
||||
) : (
|
||||
<Button variant="destructive" onClick={handleDelete}>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
삭제
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 기본 정보 */}
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<h3 className="text-lg font-semibold mb-4">기본 정보</h3>
|
||||
<div className="grid grid-cols-2 gap-6">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="perm-name">권한명</Label>
|
||||
<Input
|
||||
id="perm-name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
onBlur={handleNameBlur}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="perm-status">상태</Label>
|
||||
<Select value={status} onValueChange={handleStatusChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="active">공개</SelectItem>
|
||||
<SelectItem value="hidden">숨김</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 메뉴별 권한 설정 테이블 */}
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<h3 className="text-lg font-semibold mb-4">메뉴</h3>
|
||||
<div className="overflow-x-auto">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow className="border-b">
|
||||
<TableHead className="w-64 py-4">메뉴</TableHead>
|
||||
{PERMISSION_TYPES.map(pt => (
|
||||
<TableHead key={pt} className="text-center w-24 py-4">
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<span className="text-sm font-medium">{PERMISSION_LABELS_MAP[pt]}</span>
|
||||
<Checkbox
|
||||
checked={menuPermissions.length > 0 && menuPermissions.every(mp => mp.permissions[pt])}
|
||||
onCheckedChange={(checked) => handleColumnSelectAll(pt, !!checked)}
|
||||
/>
|
||||
</div>
|
||||
</TableHead>
|
||||
))}
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{renderMenuRows()}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 삭제 확인 다이얼로그 */}
|
||||
{!isNew && permission && (
|
||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>권한 삭제</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
"{permission.name}" 권한을 삭제하시겠습니까?
|
||||
<br />
|
||||
<span className="text-destructive">
|
||||
이 권한을 사용 중인 사원이 있으면 해당 사원의 권한이 초기화됩니다.
|
||||
</span>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>취소</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={confirmDelete}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
삭제
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
)}
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import type { PermissionDialogProps } from './types';
|
||||
|
||||
/**
|
||||
* 권한 추가/수정 다이얼로그
|
||||
*/
|
||||
export function PermissionDialog({
|
||||
isOpen,
|
||||
onOpenChange,
|
||||
mode,
|
||||
permission,
|
||||
onSubmit
|
||||
}: PermissionDialogProps) {
|
||||
const [name, setName] = useState('');
|
||||
const [status, setStatus] = useState<'active' | 'hidden'>('active');
|
||||
|
||||
// 다이얼로그 열릴 때 초기값 설정
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
if (mode === 'edit' && permission) {
|
||||
setName(permission.name);
|
||||
setStatus(permission.status);
|
||||
} else {
|
||||
setName('');
|
||||
setStatus('active');
|
||||
}
|
||||
}
|
||||
}, [isOpen, mode, permission]);
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (name.trim()) {
|
||||
onSubmit({ name: name.trim(), status });
|
||||
setName('');
|
||||
setStatus('active');
|
||||
}
|
||||
};
|
||||
|
||||
const dialogTitle = mode === 'add' ? '권한 등록' : '권한 수정';
|
||||
const submitText = mode === 'add' ? '등록' : '수정';
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{dialogTitle}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="space-y-4 py-4">
|
||||
{/* 권한명 입력 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="permission-name">권한명</Label>
|
||||
<Input
|
||||
id="permission-name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="권한명을 입력하세요"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 상태 선택 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="permission-status">상태</Label>
|
||||
<Select value={status} onValueChange={(value: 'active' | 'hidden') => setStatus(value)}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="active">공개</SelectItem>
|
||||
<SelectItem value="hidden">숨김</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="submit" disabled={!name.trim()}>
|
||||
{submitText}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
492
src/components/settings/PermissionManagement/index.tsx
Normal file
492
src/components/settings/PermissionManagement/index.tsx
Normal file
@@ -0,0 +1,492 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useMemo, useCallback, useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { format } from 'date-fns';
|
||||
import {
|
||||
Shield,
|
||||
Plus,
|
||||
Pencil,
|
||||
Trash2,
|
||||
Settings,
|
||||
Eye,
|
||||
EyeOff,
|
||||
} from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { TableRow, TableCell } from '@/components/ui/table';
|
||||
import {
|
||||
IntegratedListTemplateV2,
|
||||
type TableColumn,
|
||||
type StatCard,
|
||||
type TabOption,
|
||||
} from '@/components/templates/IntegratedListTemplateV2';
|
||||
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import type { Permission } from './types';
|
||||
|
||||
// localStorage 키
|
||||
const PERMISSIONS_STORAGE_KEY = 'buddy_permissions';
|
||||
|
||||
/**
|
||||
* 기본 권한 데이터 (PDF 54페이지 기준)
|
||||
*/
|
||||
const defaultPermissions: Permission[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: '관리자',
|
||||
status: 'active',
|
||||
menuPermissions: [],
|
||||
createdAt: '2025-01-01T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: '일반사용자',
|
||||
status: 'active',
|
||||
menuPermissions: [],
|
||||
createdAt: '2025-01-15T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
name: '인사담당자',
|
||||
status: 'active',
|
||||
menuPermissions: [],
|
||||
createdAt: '2025-02-01T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
name: '결재담당자',
|
||||
status: 'active',
|
||||
menuPermissions: [],
|
||||
createdAt: '2025-02-15T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 5,
|
||||
name: '게스트',
|
||||
status: 'hidden',
|
||||
menuPermissions: [],
|
||||
createdAt: '2025-03-01T00:00:00Z',
|
||||
},
|
||||
];
|
||||
|
||||
// localStorage에서 권한 데이터 로드
|
||||
const loadPermissions = (): Permission[] => {
|
||||
if (typeof window === 'undefined') return defaultPermissions;
|
||||
|
||||
try {
|
||||
const stored = localStorage.getItem(PERMISSIONS_STORAGE_KEY);
|
||||
if (stored) {
|
||||
return JSON.parse(stored);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load permissions:', error);
|
||||
}
|
||||
return defaultPermissions;
|
||||
};
|
||||
|
||||
// localStorage에 권한 데이터 저장
|
||||
const savePermissions = (permissions: Permission[]) => {
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
try {
|
||||
localStorage.setItem(PERMISSIONS_STORAGE_KEY, JSON.stringify(permissions));
|
||||
} catch (error) {
|
||||
console.error('Failed to save permissions:', error);
|
||||
}
|
||||
};
|
||||
|
||||
export function PermissionManagement() {
|
||||
const router = useRouter();
|
||||
|
||||
// ===== 상태 관리 =====
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const itemsPerPage = 20;
|
||||
|
||||
// 권한 데이터
|
||||
const [permissions, setPermissions] = useState<Permission[]>(defaultPermissions);
|
||||
|
||||
// 삭제 확인 다이얼로그
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [permissionToDelete, setPermissionToDelete] = useState<Permission | null>(null);
|
||||
const [isBulkDelete, setIsBulkDelete] = useState(false);
|
||||
|
||||
// localStorage에서 초기 데이터 로드
|
||||
useEffect(() => {
|
||||
setPermissions(loadPermissions());
|
||||
}, []);
|
||||
|
||||
// 권한 변경 감지 (상세 페이지에서 변경 시)
|
||||
useEffect(() => {
|
||||
const handlePermissionsUpdated = (event: CustomEvent<Permission[]>) => {
|
||||
setPermissions(event.detail);
|
||||
};
|
||||
|
||||
window.addEventListener('permissionsUpdated', handlePermissionsUpdated as EventListener);
|
||||
return () => {
|
||||
window.removeEventListener('permissionsUpdated', handlePermissionsUpdated as EventListener);
|
||||
};
|
||||
}, []);
|
||||
|
||||
// ===== 탭 상태 =====
|
||||
const [activeTab, setActiveTab] = useState('all');
|
||||
|
||||
// ===== 체크박스 핸들러 =====
|
||||
const toggleSelection = useCallback((id: string) => {
|
||||
setSelectedItems(prev => {
|
||||
const newSet = new Set(prev);
|
||||
if (newSet.has(id)) newSet.delete(id);
|
||||
else newSet.add(id);
|
||||
return newSet;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const toggleSelectAll = useCallback(() => {
|
||||
if (selectedItems.size === filteredData.length && filteredData.length > 0) {
|
||||
setSelectedItems(new Set());
|
||||
} else {
|
||||
setSelectedItems(new Set(filteredData.map(item => item.id.toString())));
|
||||
}
|
||||
}, [selectedItems.size]);
|
||||
|
||||
// ===== 필터링된 데이터 =====
|
||||
const filteredData = useMemo(() => {
|
||||
let result = permissions;
|
||||
|
||||
// 탭 필터
|
||||
if (activeTab === 'active') {
|
||||
result = result.filter(item => item.status === 'active');
|
||||
} else if (activeTab === 'hidden') {
|
||||
result = result.filter(item => item.status === 'hidden');
|
||||
}
|
||||
|
||||
// 검색 필터
|
||||
if (searchQuery) {
|
||||
result = result.filter(item =>
|
||||
item.name.toLowerCase().includes(searchQuery.toLowerCase())
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
}, [permissions, searchQuery, activeTab]);
|
||||
|
||||
const paginatedData = useMemo(() => {
|
||||
const startIndex = (currentPage - 1) * itemsPerPage;
|
||||
return filteredData.slice(startIndex, startIndex + itemsPerPage);
|
||||
}, [filteredData, currentPage, itemsPerPage]);
|
||||
|
||||
const totalPages = Math.ceil(filteredData.length / itemsPerPage);
|
||||
|
||||
// ===== 핸들러 =====
|
||||
const handleAdd = () => {
|
||||
// 새 권한 등록 페이지로 이동 (저장 전까지 목록에 추가 안됨)
|
||||
router.push('/settings/permissions/new');
|
||||
};
|
||||
|
||||
const handleEdit = (permission: Permission, e?: React.MouseEvent) => {
|
||||
e?.stopPropagation();
|
||||
// 상세 페이지로 라우팅
|
||||
router.push(`/settings/permissions/${permission.id}`);
|
||||
};
|
||||
|
||||
const handleViewDetail = (permission: Permission) => {
|
||||
// 상세 페이지로 라우팅
|
||||
router.push(`/settings/permissions/${permission.id}`);
|
||||
};
|
||||
|
||||
const handleDelete = (permission: Permission, e?: React.MouseEvent) => {
|
||||
e?.stopPropagation();
|
||||
setPermissionToDelete(permission);
|
||||
setIsBulkDelete(false);
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleBulkDelete = () => {
|
||||
if (selectedItems.size === 0) return;
|
||||
setIsBulkDelete(true);
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
const confirmDelete = () => {
|
||||
let updatedPermissions: Permission[];
|
||||
if (isBulkDelete) {
|
||||
updatedPermissions = permissions.filter(p => !selectedItems.has(p.id.toString()));
|
||||
setSelectedItems(new Set());
|
||||
} else if (permissionToDelete) {
|
||||
updatedPermissions = permissions.filter(p => p.id !== permissionToDelete.id);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
setPermissions(updatedPermissions);
|
||||
savePermissions(updatedPermissions);
|
||||
setDeleteDialogOpen(false);
|
||||
setPermissionToDelete(null);
|
||||
};
|
||||
|
||||
// ===== 날짜 포맷 =====
|
||||
const formatDate = (dateStr: string) => {
|
||||
return format(new Date(dateStr), 'yyyy-MM-dd');
|
||||
};
|
||||
|
||||
// ===== 탭 설정 =====
|
||||
const tabs: TabOption[] = useMemo(() => {
|
||||
const activeCount = permissions.filter(p => p.status === 'active').length;
|
||||
const hiddenCount = permissions.filter(p => p.status === 'hidden').length;
|
||||
|
||||
return [
|
||||
{ value: 'all', label: '전체', count: permissions.length, color: 'blue' },
|
||||
{ value: 'active', label: '공개', count: activeCount, color: 'green' },
|
||||
{ value: 'hidden', label: '숨김', count: hiddenCount, color: 'gray' },
|
||||
];
|
||||
}, [permissions]);
|
||||
|
||||
// ===== 통계 카드 =====
|
||||
const statCards: StatCard[] = useMemo(() => {
|
||||
const totalCount = permissions.length;
|
||||
const activeCount = permissions.filter(p => p.status === 'active').length;
|
||||
const hiddenCount = permissions.filter(p => p.status === 'hidden').length;
|
||||
|
||||
return [
|
||||
{
|
||||
label: '전체 권한',
|
||||
value: totalCount,
|
||||
icon: Shield,
|
||||
iconColor: 'text-blue-500',
|
||||
},
|
||||
{
|
||||
label: '공개',
|
||||
value: activeCount,
|
||||
icon: Eye,
|
||||
iconColor: 'text-green-500',
|
||||
},
|
||||
{
|
||||
label: '숨김',
|
||||
value: hiddenCount,
|
||||
icon: EyeOff,
|
||||
iconColor: 'text-gray-500',
|
||||
},
|
||||
];
|
||||
}, [permissions]);
|
||||
|
||||
// ===== 테이블 컬럼 =====
|
||||
const tableColumns: TableColumn[] = useMemo(() => {
|
||||
const baseColumns: TableColumn[] = [
|
||||
{ key: 'index', label: '번호', className: 'text-center w-[80px]' },
|
||||
{ key: 'name', label: '권한', className: 'flex-1' },
|
||||
{ key: 'status', label: '상태', className: 'text-center flex-1' },
|
||||
{ key: 'createdAt', label: '등록일시', className: 'text-center flex-1' },
|
||||
];
|
||||
|
||||
// 체크박스 선택 시에만 작업 컬럼 표시
|
||||
if (selectedItems.size > 0) {
|
||||
baseColumns.push({ key: 'action', label: '작업', className: 'text-center flex-1' });
|
||||
}
|
||||
|
||||
return baseColumns;
|
||||
}, [selectedItems.size]);
|
||||
|
||||
// ===== 테이블 행 렌더링 =====
|
||||
const renderTableRow = useCallback((item: Permission, index: number, globalIndex: number) => {
|
||||
const isSelected = selectedItems.has(item.id.toString());
|
||||
const hasSelection = selectedItems.size > 0;
|
||||
|
||||
return (
|
||||
<TableRow
|
||||
key={item.id}
|
||||
className="hover:bg-muted/50 cursor-pointer"
|
||||
onClick={() => handleViewDetail(item)}
|
||||
>
|
||||
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
|
||||
<Checkbox
|
||||
checked={isSelected}
|
||||
onCheckedChange={() => toggleSelection(item.id.toString())}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="text-center text-muted-foreground">
|
||||
{globalIndex}
|
||||
</TableCell>
|
||||
<TableCell className="font-medium">{item.name}</TableCell>
|
||||
<TableCell className="text-center">
|
||||
<Badge variant={item.status === 'active' ? 'default' : 'secondary'}>
|
||||
{item.status === 'active' ? '공개' : '숨김'}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="text-center">{formatDate(item.createdAt)}</TableCell>
|
||||
{hasSelection && (
|
||||
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="flex justify-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleViewDetail(item)}
|
||||
className="h-8 w-8 p-0"
|
||||
title="권한 설정"
|
||||
>
|
||||
<Settings className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={(e) => handleEdit(item, e)}
|
||||
className="h-8 w-8 p-0"
|
||||
title="수정"
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={(e) => handleDelete(item, e)}
|
||||
className="h-8 w-8 p-0 text-destructive hover:text-destructive"
|
||||
title="삭제"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
)}
|
||||
</TableRow>
|
||||
);
|
||||
}, [selectedItems, toggleSelection]);
|
||||
|
||||
// ===== 모바일 카드 렌더링 =====
|
||||
const renderMobileCard = useCallback((
|
||||
item: Permission,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
isSelected: boolean,
|
||||
onToggle: () => void
|
||||
) => {
|
||||
return (
|
||||
<ListMobileCard
|
||||
id={item.id.toString()}
|
||||
title={item.name}
|
||||
headerBadges={
|
||||
<Badge variant={item.status === 'active' ? 'default' : 'secondary'}>
|
||||
{item.status === 'active' ? '공개' : '숨김'}
|
||||
</Badge>
|
||||
}
|
||||
isSelected={isSelected}
|
||||
onToggleSelection={onToggle}
|
||||
infoGrid={
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<InfoField label="상태" value={item.status === 'active' ? '공개' : '숨김'} />
|
||||
<InfoField label="등록일" value={formatDate(item.createdAt)} />
|
||||
</div>
|
||||
}
|
||||
actions={
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1"
|
||||
onClick={() => handleViewDetail(item)}
|
||||
>
|
||||
<Settings className="h-4 w-4 mr-2" />
|
||||
권한 설정
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleEdit(item)}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}, []);
|
||||
|
||||
// ===== 헤더 액션 =====
|
||||
const headerActions = (
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
{selectedItems.size > 0 && (
|
||||
<Button variant="destructive" onClick={handleBulkDelete}>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
선택 삭제 ({selectedItems.size})
|
||||
</Button>
|
||||
)}
|
||||
<Button onClick={handleAdd}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
권한 등록
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
|
||||
// ===== 목록 화면 =====
|
||||
return (
|
||||
<>
|
||||
<IntegratedListTemplateV2
|
||||
title="권한관리"
|
||||
description="사용자 권한을 관리합니다"
|
||||
icon={Shield}
|
||||
headerActions={headerActions}
|
||||
stats={statCards}
|
||||
searchValue={searchQuery}
|
||||
onSearchChange={setSearchQuery}
|
||||
searchPlaceholder="권한명 검색..."
|
||||
tabs={tabs}
|
||||
activeTab={activeTab}
|
||||
onTabChange={setActiveTab}
|
||||
tableColumns={tableColumns}
|
||||
data={paginatedData}
|
||||
totalCount={filteredData.length}
|
||||
allData={filteredData}
|
||||
selectedItems={selectedItems}
|
||||
onToggleSelection={toggleSelection}
|
||||
onToggleSelectAll={toggleSelectAll}
|
||||
getItemId={(item: Permission) => item.id.toString()}
|
||||
onBulkDelete={handleBulkDelete}
|
||||
renderTableRow={renderTableRow}
|
||||
renderMobileCard={renderMobileCard}
|
||||
pagination={{
|
||||
currentPage,
|
||||
totalPages,
|
||||
totalItems: filteredData.length,
|
||||
itemsPerPage,
|
||||
onPageChange: setCurrentPage,
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* 삭제 확인 다이얼로그 */}
|
||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>권한 삭제</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{isBulkDelete
|
||||
? `선택한 ${selectedItems.size}개의 권한을 삭제하시겠습니까?`
|
||||
: `"${permissionToDelete?.name}" 권한을 삭제하시겠습니까?`
|
||||
}
|
||||
<br />
|
||||
<span className="text-destructive">
|
||||
이 권한을 사용 중인 사원이 있으면 해당 사원의 권한이 초기화됩니다.
|
||||
</span>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>취소</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={confirmDelete}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
삭제
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
45
src/components/settings/PermissionManagement/types.ts
Normal file
45
src/components/settings/PermissionManagement/types.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* 권한 타입 정의 (PDF 54-55페이지 기준)
|
||||
*/
|
||||
|
||||
// 권한 유형
|
||||
export type PermissionType = 'view' | 'create' | 'update' | 'delete' | 'approve' | 'export' | 'manage';
|
||||
|
||||
// 메뉴별 권한 설정
|
||||
export interface MenuPermission {
|
||||
menuId: string;
|
||||
menuName: string;
|
||||
parentMenuId?: string;
|
||||
permissions: {
|
||||
[key in PermissionType]?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
// 권한 그룹
|
||||
export interface Permission {
|
||||
id: number;
|
||||
name: string;
|
||||
status: 'active' | 'hidden'; // 공개/숨김
|
||||
menuPermissions: MenuPermission[];
|
||||
createdAt: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
export interface PermissionDialogProps {
|
||||
isOpen: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
mode: 'add' | 'edit';
|
||||
permission?: Permission;
|
||||
onSubmit: (data: { name: string; status: 'active' | 'hidden' }) => void;
|
||||
}
|
||||
|
||||
// 권한 라벨 매핑
|
||||
export const PERMISSION_LABELS: Record<PermissionType, string> = {
|
||||
view: '조회',
|
||||
create: '생성',
|
||||
update: '수정',
|
||||
delete: '삭제',
|
||||
approve: '승인',
|
||||
export: '내보내기',
|
||||
manage: '관리',
|
||||
};
|
||||
Reference in New Issue
Block a user