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:
38
src/app/[locale]/(protected)/hr/salary-management/page.tsx
Normal file
38
src/app/[locale]/(protected)/hr/salary-management/page.tsx
Normal file
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* 급여관리 페이지 (Salary Management)
|
||||
*
|
||||
* 직원 급여 정보를 관리하는 시스템
|
||||
* - 급여 목록 조회/검색/필터
|
||||
* - 지급완료/지급예정 상태 변경
|
||||
* - 급여 상세 정보 조회
|
||||
* - 엑셀 다운로드
|
||||
*/
|
||||
|
||||
import { Suspense } from 'react';
|
||||
import { SalaryManagement } from '@/components/hr/SalaryManagement';
|
||||
import type { Metadata } from 'next';
|
||||
|
||||
/**
|
||||
* 메타데이터 설정
|
||||
*/
|
||||
export const metadata: Metadata = {
|
||||
title: '급여관리',
|
||||
description: '직원 급여 정보를 관리합니다',
|
||||
};
|
||||
|
||||
export default function SalaryManagementPage() {
|
||||
return (
|
||||
<div>
|
||||
<Suspense fallback={
|
||||
<div className="flex items-center justify-center min-h-[400px]">
|
||||
<div className="text-center">
|
||||
<div className="inline-block h-8 w-8 animate-spin rounded-full border-4 border-solid border-primary border-r-transparent mb-4"></div>
|
||||
<p className="text-muted-foreground">로딩 중...</p>
|
||||
</div>
|
||||
</div>
|
||||
}>
|
||||
<SalaryManagement />
|
||||
</Suspense>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
38
src/app/[locale]/(protected)/hr/vacation-management/page.tsx
Normal file
38
src/app/[locale]/(protected)/hr/vacation-management/page.tsx
Normal file
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* 휴가관리 페이지 (Vacation Management)
|
||||
*
|
||||
* 직원 휴가 정보를 관리하는 시스템
|
||||
* - 휴가 목록 조회/검색/필터
|
||||
* - 휴가 등록/조정
|
||||
* - 휴가 종류 설정
|
||||
* - 엑셀 다운로드
|
||||
*/
|
||||
|
||||
import { Suspense } from 'react';
|
||||
import { VacationManagement } from '@/components/hr/VacationManagement';
|
||||
import type { Metadata } from 'next';
|
||||
|
||||
/**
|
||||
* 메타데이터 설정
|
||||
*/
|
||||
export const metadata: Metadata = {
|
||||
title: '휴가관리',
|
||||
description: '직원 휴가 정보를 관리합니다',
|
||||
};
|
||||
|
||||
export default function VacationManagementPage() {
|
||||
return (
|
||||
<div>
|
||||
<Suspense fallback={
|
||||
<div className="flex items-center justify-center min-h-[400px]">
|
||||
<div className="text-center">
|
||||
<div className="inline-block h-8 w-8 animate-spin rounded-full border-4 border-solid border-primary border-r-transparent mb-4"></div>
|
||||
<p className="text-muted-foreground">로딩 중...</p>
|
||||
</div>
|
||||
</div>
|
||||
}>
|
||||
<VacationManagement />
|
||||
</Suspense>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
* 품목 수정 페이지
|
||||
*
|
||||
* API 연동:
|
||||
* - GET /api/proxy/items/code/{itemCode}?include_bom=true (품목 조회)
|
||||
* - GET /api/proxy/items/{id} (품목 조회 - id 기반 통일)
|
||||
* - PUT /api/proxy/items/{id} (품목 수정)
|
||||
*/
|
||||
|
||||
@@ -71,6 +71,9 @@ interface ItemApiResponse {
|
||||
function mapApiResponseToFormData(data: ItemApiResponse): DynamicFormData {
|
||||
const formData: DynamicFormData = {};
|
||||
|
||||
// attributes 객체 추출 (조립부품 등의 동적 필드가 여기에 저장됨)
|
||||
const attributes = (data.attributes || {}) as Record<string, unknown>;
|
||||
|
||||
// 백엔드 Product 모델 필드: code, name, product_type
|
||||
// 프론트엔드 폼 필드: item_name, item_code 등 (snake_case)
|
||||
|
||||
@@ -86,19 +89,29 @@ function mapApiResponseToFormData(data: ItemApiResponse): DynamicFormData {
|
||||
if (data.remarks) formData['note'] = data.remarks; // Material remarks → note 매핑
|
||||
formData['is_active'] = data.is_active ?? true;
|
||||
|
||||
// 부품 관련 필드 (PT)
|
||||
if (data.part_type) formData['part_type'] = data.part_type;
|
||||
if (data.part_usage) formData['part_usage'] = data.part_usage;
|
||||
if (data.material) formData['material'] = data.material;
|
||||
if (data.length) formData['length'] = data.length;
|
||||
if (data.thickness) formData['thickness'] = data.thickness;
|
||||
// 부품 관련 필드 (PT) - data와 attributes 둘 다에서 찾음
|
||||
const partType = data.part_type || attributes.part_type;
|
||||
const partUsage = data.part_usage || attributes.part_usage;
|
||||
const material = data.material || attributes.material;
|
||||
const length = data.length || attributes.length;
|
||||
const thickness = data.thickness || attributes.thickness;
|
||||
if (partType) formData['part_type'] = String(partType);
|
||||
if (partUsage) formData['part_usage'] = String(partUsage);
|
||||
if (material) formData['material'] = String(material);
|
||||
if (length) formData['length'] = String(length);
|
||||
if (thickness) formData['thickness'] = String(thickness);
|
||||
|
||||
// 조립 부품 관련
|
||||
if (data.installation_type) formData['installation_type'] = data.installation_type;
|
||||
if (data.assembly_type) formData['assembly_type'] = data.assembly_type;
|
||||
if (data.assembly_length) formData['assembly_length'] = data.assembly_length;
|
||||
if (data.side_spec_width) formData['side_spec_width'] = data.side_spec_width;
|
||||
if (data.side_spec_height) formData['side_spec_height'] = data.side_spec_height;
|
||||
// 조립 부품 관련 - data와 attributes 둘 다에서 찾음
|
||||
const installationType = data.installation_type || attributes.installation_type;
|
||||
const assemblyType = data.assembly_type || attributes.assembly_type;
|
||||
const assemblyLength = data.assembly_length || attributes.assembly_length;
|
||||
const sideSpecWidth = data.side_spec_width || attributes.side_spec_width;
|
||||
const sideSpecHeight = data.side_spec_height || attributes.side_spec_height;
|
||||
if (installationType) formData['installation_type'] = String(installationType);
|
||||
if (assemblyType) formData['assembly_type'] = String(assemblyType);
|
||||
if (assemblyLength) formData['assembly_length'] = String(assemblyLength);
|
||||
if (sideSpecWidth) formData['side_spec_width'] = String(sideSpecWidth);
|
||||
if (sideSpecHeight) formData['side_spec_height'] = String(sideSpecHeight);
|
||||
|
||||
// 제품 관련 필드 (FG)
|
||||
if (data.product_category) formData['product_category'] = data.product_category;
|
||||
@@ -110,11 +123,11 @@ function mapApiResponseToFormData(data: ItemApiResponse): DynamicFormData {
|
||||
if (data.certification_end_date) formData['certification_end_date'] = data.certification_end_date;
|
||||
|
||||
// 파일 관련 필드 (edit 모드에서 기존 파일 표시용)
|
||||
if (data.bending_diagram) formData['bending_diagram'] = data.bending_diagram;
|
||||
if (data.specification_file) formData['specification_file'] = data.specification_file;
|
||||
if (data.specification_file_name) formData['specification_file_name'] = data.specification_file_name;
|
||||
if (data.certification_file) formData['certification_file'] = data.certification_file;
|
||||
if (data.certification_file_name) formData['certification_file_name'] = data.certification_file_name;
|
||||
if (data.bending_diagram) formData['bending_diagram'] = String(data.bending_diagram);
|
||||
if (data.specification_file) formData['specification_file'] = String(data.specification_file);
|
||||
if (data.specification_file_name) formData['specification_file_name'] = String(data.specification_file_name);
|
||||
if (data.certification_file) formData['certification_file'] = String(data.certification_file);
|
||||
if (data.certification_file_name) formData['certification_file_name'] = String(data.certification_file_name);
|
||||
|
||||
// Material(SM, RM, CS) options 필드 매핑
|
||||
// 백엔드에서 options: [{label: "standard_1", value: "옵션값"}, ...] 형태로 저장됨
|
||||
@@ -179,17 +192,25 @@ export default function EditItemPage() {
|
||||
|
||||
let response: Response;
|
||||
|
||||
// Materials (SM, RM, CS)는 다른 API 엔드포인트 사용
|
||||
if (MATERIAL_TYPES.includes(urlItemType) && urlItemId) {
|
||||
// GET /api/proxy/items/{id}?item_type=MATERIAL
|
||||
// console.log('[EditItem] Using Material API');
|
||||
response = await fetch(`/api/proxy/items/${urlItemId}?item_type=MATERIAL`);
|
||||
} else {
|
||||
// Products (FG, PT): GET /api/proxy/items/code/{itemCode}?include_bom=true
|
||||
// console.log('[EditItem] Using Product API');
|
||||
response = await fetch(`/api/proxy/items/code/${encodeURIComponent(itemCode)}?include_bom=true`);
|
||||
// 모든 품목: GET /api/proxy/items/{id} (id 기반 통일)
|
||||
if (!urlItemId) {
|
||||
setError('품목 ID가 없습니다.');
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Materials (SM, RM, CS)는 item_type=MATERIAL 쿼리 파라미터 추가
|
||||
const isMaterial = isMaterialType(urlItemType);
|
||||
const queryParams = new URLSearchParams();
|
||||
if (isMaterial) {
|
||||
queryParams.append('item_type', 'MATERIAL');
|
||||
} else {
|
||||
queryParams.append('include_bom', 'true');
|
||||
}
|
||||
|
||||
console.log('[EditItem] Fetching:', { urlItemId, urlItemType, isMaterial });
|
||||
response = await fetch(`/api/proxy/items/${urlItemId}?${queryParams.toString()}`);
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 404) {
|
||||
setError('품목을 찾을 수 없습니다.');
|
||||
@@ -206,12 +227,13 @@ export default function EditItemPage() {
|
||||
|
||||
if (result.success && result.data) {
|
||||
const apiData = result.data as ItemApiResponse;
|
||||
// console.log('========== [EditItem] API 원본 데이터 ==========');
|
||||
// console.log('is_active:', apiData.is_active);
|
||||
// console.log('specification:', apiData.specification);
|
||||
// console.log('unit:', apiData.unit);
|
||||
// console.log('전체 데이터:', JSON.stringify(apiData, null, 2));
|
||||
// console.log('================================================');
|
||||
console.log('========== [EditItem] API 원본 데이터 (백엔드 응답) ==========');
|
||||
console.log('id:', apiData.id);
|
||||
console.log('specification:', apiData.specification);
|
||||
console.log('unit:', apiData.unit);
|
||||
console.log('is_active:', apiData.is_active);
|
||||
console.log('전체:', apiData);
|
||||
console.log('==============================================================');
|
||||
|
||||
// ID, 품목 유형 저장
|
||||
// Product: product_type, Material: material_type 또는 type_code
|
||||
@@ -222,12 +244,12 @@ export default function EditItemPage() {
|
||||
|
||||
// 폼 데이터로 변환
|
||||
const formData = mapApiResponseToFormData(apiData);
|
||||
// console.log('========== [EditItem] Mapped form data ==========');
|
||||
// console.log('is_active:', formData['is_active']);
|
||||
// console.log('specification:', formData['specification']);
|
||||
// console.log('unit:', formData['unit']);
|
||||
// console.log('전체 매핑 데이터:', JSON.stringify(formData, null, 2));
|
||||
// console.log('=================================================');
|
||||
console.log('========== [EditItem] 폼에 전달되는 initialData ==========');
|
||||
console.log('specification:', formData['specification']);
|
||||
console.log('unit:', formData['unit']);
|
||||
console.log('is_active:', formData['is_active']);
|
||||
console.log('전체:', formData);
|
||||
console.log('==========================================================');
|
||||
setInitialData(formData);
|
||||
} else {
|
||||
setError(result.message || '품목 정보를 불러올 수 없습니다.');
|
||||
@@ -261,7 +283,7 @@ export default function EditItemPage() {
|
||||
|
||||
// Materials (SM, RM, CS)는 /products/materials 엔드포인트 + PATCH 메서드 사용
|
||||
// Products (FG, PT)는 /items 엔드포인트 + PUT 메서드 사용
|
||||
const isMaterial = itemType ? MATERIAL_TYPES.includes(itemType) : false;
|
||||
const isMaterial = isMaterialType(itemType);
|
||||
|
||||
// 디버깅: material_code 생성 관련 변수 확인 (필요 시 주석 해제)
|
||||
// console.log('========== [EditItem] handleSubmit 디버깅 ==========');
|
||||
@@ -312,11 +334,14 @@ export default function EditItemPage() {
|
||||
}
|
||||
|
||||
// API 호출
|
||||
// console.log('========== [EditItem] PUT 요청 데이터 ==========');
|
||||
// console.log('URL:', updateUrl);
|
||||
// console.log('Method:', method);
|
||||
// console.log('전송 데이터:', JSON.stringify(submitData, null, 2));
|
||||
// console.log('================================================');
|
||||
console.log('========== [EditItem] 수정 요청 데이터 ==========');
|
||||
console.log('URL:', updateUrl);
|
||||
console.log('Method:', method);
|
||||
console.log('specification:', submitData.specification);
|
||||
console.log('unit:', submitData.unit);
|
||||
console.log('is_active:', submitData.is_active);
|
||||
console.log('전체:', submitData);
|
||||
console.log('=================================================');
|
||||
|
||||
const response = await fetch(updateUrl, {
|
||||
method,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* 품목 상세 조회 페이지
|
||||
*
|
||||
* API 연동: GET /api/proxy/items/code/{itemCode}?include_bom=true
|
||||
* API 연동: GET /api/proxy/items/{id} (id 기반 통일)
|
||||
*/
|
||||
|
||||
'use client';
|
||||
@@ -10,7 +10,7 @@ import { useEffect, useState } from 'react';
|
||||
import { useParams, useRouter, useSearchParams } from 'next/navigation';
|
||||
import { notFound } from 'next/navigation';
|
||||
import ItemDetailClient from '@/components/items/ItemDetailClient';
|
||||
import type { ItemMaster } from '@/types/item';
|
||||
import type { ItemMaster, ItemType, ProductCategory, PartType, PartUsage } from '@/types/item';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
|
||||
// Materials 타입 (SM, RM, CS는 Material 테이블 사용)
|
||||
@@ -20,6 +20,9 @@ const MATERIAL_TYPES = ['SM', 'RM', 'CS'];
|
||||
* API 응답을 ItemMaster 타입으로 변환
|
||||
*/
|
||||
function mapApiResponseToItemMaster(data: Record<string, unknown>): ItemMaster {
|
||||
// attributes 객체 추출 (조립부품 등의 동적 필드가 여기에 저장됨)
|
||||
const attributes = (data.attributes || {}) as Record<string, unknown>;
|
||||
|
||||
return {
|
||||
id: String(data.id || ''),
|
||||
// 백엔드 필드 매핑:
|
||||
@@ -27,7 +30,7 @@ function mapApiResponseToItemMaster(data: Record<string, unknown>): ItemMaster {
|
||||
// - Material: material_code, name, material_type (또는 type_code)
|
||||
itemCode: String(data.code || data.material_code || data.item_code || data.itemCode || ''),
|
||||
itemName: String(data.name || data.item_name || data.itemName || ''),
|
||||
itemType: String(data.product_type || data.material_type || data.type_code || data.item_type || data.itemType || 'FG'),
|
||||
itemType: (data.product_type || data.material_type || data.type_code || data.item_type || data.itemType || 'FG') as ItemType,
|
||||
unit: String(data.unit || 'EA'),
|
||||
specification: data.specification ? String(data.specification) : undefined,
|
||||
isActive: Boolean(data.is_active ?? data.isActive ?? true),
|
||||
@@ -40,7 +43,7 @@ function mapApiResponseToItemMaster(data: Record<string, unknown>): ItemMaster {
|
||||
processingCost: data.processing_cost ? Number(data.processing_cost) : undefined,
|
||||
laborCost: data.labor_cost ? Number(data.labor_cost) : undefined,
|
||||
installCost: data.install_cost ? Number(data.install_cost) : undefined,
|
||||
productCategory: data.product_category ? String(data.product_category) : undefined,
|
||||
productCategory: data.product_category ? (data.product_category as ProductCategory) : undefined,
|
||||
lotAbbreviation: data.lot_abbreviation ? String(data.lot_abbreviation) : undefined,
|
||||
note: data.note ? String(data.note) : undefined,
|
||||
description: data.description ? String(data.description) : undefined,
|
||||
@@ -50,18 +53,18 @@ function mapApiResponseToItemMaster(data: Record<string, unknown>): ItemMaster {
|
||||
isFinal: Boolean(data.is_final ?? false),
|
||||
createdAt: String(data.created_at || data.createdAt || ''),
|
||||
updatedAt: data.updated_at ? String(data.updated_at) : undefined,
|
||||
// 부품 관련
|
||||
partType: data.part_type ? String(data.part_type) : undefined,
|
||||
partUsage: data.part_usage ? String(data.part_usage) : undefined,
|
||||
installationType: data.installation_type ? String(data.installation_type) : undefined,
|
||||
assemblyType: data.assembly_type ? String(data.assembly_type) : undefined,
|
||||
assemblyLength: data.assembly_length ? String(data.assembly_length) : undefined,
|
||||
material: data.material ? String(data.material) : undefined,
|
||||
sideSpecWidth: data.side_spec_width ? String(data.side_spec_width) : undefined,
|
||||
sideSpecHeight: data.side_spec_height ? String(data.side_spec_height) : undefined,
|
||||
guideRailModelType: data.guide_rail_model_type ? String(data.guide_rail_model_type) : undefined,
|
||||
guideRailModel: data.guide_rail_model ? String(data.guide_rail_model) : undefined,
|
||||
length: data.length ? String(data.length) : undefined,
|
||||
// 부품 관련 - data와 attributes 둘 다에서 찾음
|
||||
partType: (data.part_type || attributes.part_type) ? ((data.part_type || attributes.part_type) as PartType) : undefined,
|
||||
partUsage: (data.part_usage || attributes.part_usage) ? ((data.part_usage || attributes.part_usage) as PartUsage) : undefined,
|
||||
installationType: (data.installation_type || attributes.installation_type) ? String(data.installation_type || attributes.installation_type) : undefined,
|
||||
assemblyType: (data.assembly_type || attributes.assembly_type) ? String(data.assembly_type || attributes.assembly_type) : undefined,
|
||||
assemblyLength: (data.assembly_length || attributes.assembly_length || attributes.length) ? String(data.assembly_length || attributes.assembly_length || attributes.length) : undefined,
|
||||
material: (data.material || attributes.material) ? String(data.material || attributes.material) : undefined,
|
||||
sideSpecWidth: (data.side_spec_width || attributes.side_spec_width) ? String(data.side_spec_width || attributes.side_spec_width) : undefined,
|
||||
sideSpecHeight: (data.side_spec_height || attributes.side_spec_height) ? String(data.side_spec_height || attributes.side_spec_height) : undefined,
|
||||
guideRailModelType: (data.guide_rail_model_type || attributes.guide_rail_model_type) ? String(data.guide_rail_model_type || attributes.guide_rail_model_type) : undefined,
|
||||
guideRailModel: (data.guide_rail_model || attributes.guide_rail_model) ? String(data.guide_rail_model || attributes.guide_rail_model) : undefined,
|
||||
length: (data.length || attributes.length) ? String(data.length || attributes.length) : undefined,
|
||||
// BOM (있으면)
|
||||
bom: Array.isArray(data.bom) ? data.bom.map((bomItem: Record<string, unknown>) => ({
|
||||
id: String(bomItem.id || ''),
|
||||
@@ -117,17 +120,25 @@ export default function ItemDetailPage() {
|
||||
|
||||
let response: Response;
|
||||
|
||||
// Materials (SM, RM, CS)는 다른 API 엔드포인트 사용
|
||||
if (MATERIAL_TYPES.includes(itemType) && itemId) {
|
||||
// GET /api/proxy/items/{id}?item_type=MATERIAL
|
||||
console.log('[ItemDetail] Using Material API');
|
||||
response = await fetch(`/api/proxy/items/${itemId}?item_type=MATERIAL`);
|
||||
} else {
|
||||
// Products (FG, PT): GET /api/proxy/items/code/{itemCode}?include_bom=true
|
||||
console.log('[ItemDetail] Using Product API');
|
||||
response = await fetch(`/api/proxy/items/code/${encodeURIComponent(itemCode)}?include_bom=true`);
|
||||
// 모든 품목: GET /api/proxy/items/{id} (id 기반 통일)
|
||||
if (!itemId) {
|
||||
setError('품목 ID가 없습니다.');
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Materials (SM, RM, CS)는 item_type=MATERIAL 쿼리 파라미터 추가
|
||||
const isMaterial = MATERIAL_TYPES.includes(itemType);
|
||||
const queryParams = new URLSearchParams();
|
||||
if (isMaterial) {
|
||||
queryParams.append('item_type', 'MATERIAL');
|
||||
} else {
|
||||
queryParams.append('include_bom', 'true');
|
||||
}
|
||||
|
||||
console.log('[ItemDetail] Fetching:', { itemId, itemType, isMaterial });
|
||||
response = await fetch(`/api/proxy/items/${itemId}?${queryParams.toString()}`);
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 404) {
|
||||
setError('품목을 찾을 수 없습니다.');
|
||||
|
||||
@@ -147,7 +147,7 @@ export default async function ItemsPage() {
|
||||
return (
|
||||
<div className="p-6">
|
||||
<Suspense fallback={<div className="text-center py-8">로딩 중...</div>}>
|
||||
<ItemListClient items={items} />
|
||||
<ItemListClient />
|
||||
</Suspense>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
CheckCircle,
|
||||
XCircle,
|
||||
Eye,
|
||||
Loader2,
|
||||
} from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
@@ -71,6 +72,18 @@ export default function CustomerAccountManagementPage() {
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const itemsPerPage = 20;
|
||||
|
||||
// 초기 로딩 완료 여부 (첫 데이터 로드 완료 시 true)
|
||||
const [isInitialLoaded, setIsInitialLoaded] = useState(false);
|
||||
|
||||
// 전체 통계 (검색과 무관하게 고정)
|
||||
const [totalStats, setTotalStats] = useState({
|
||||
total: 0,
|
||||
purchase: 0,
|
||||
sales: 0,
|
||||
active: 0,
|
||||
inactive: 0,
|
||||
});
|
||||
|
||||
// 삭제 확인 다이얼로그 state
|
||||
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
|
||||
const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
|
||||
@@ -82,15 +95,52 @@ export default function CustomerAccountManagementPage() {
|
||||
const [mobileDisplayCount, setMobileDisplayCount] = useState(20);
|
||||
const sentinelRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// 전체 통계 로드 (최초 1회만)
|
||||
const loadTotalStats = useCallback(async () => {
|
||||
try {
|
||||
// 전체 데이터 조회 (검색 조건 없이)
|
||||
const response = await fetch("/api/proxy/clients?size=1000");
|
||||
if (response.ok) {
|
||||
const result = await response.json();
|
||||
if (result.success && result.data) {
|
||||
const allClients = result.data.data || [];
|
||||
setTotalStats({
|
||||
total: result.data.total || allClients.length,
|
||||
purchase: allClients.filter((c: { client_type?: string }) =>
|
||||
c.client_type === "매입" || c.client_type === "매입매출"
|
||||
).length,
|
||||
sales: allClients.filter((c: { client_type?: string }) =>
|
||||
c.client_type === "매출" || c.client_type === "매입매출"
|
||||
).length,
|
||||
active: allClients.filter((c: { is_active?: boolean }) => c.is_active === true).length,
|
||||
inactive: allClients.filter((c: { is_active?: boolean }) => c.is_active === false).length,
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("전체 통계 로드 실패:", err);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 초기 데이터 로드
|
||||
useEffect(() => {
|
||||
fetchClients({
|
||||
page: currentPage,
|
||||
size: itemsPerPage,
|
||||
q: searchTerm || undefined,
|
||||
onlyActive: filterType === "active" ? true : filterType === "inactive" ? false : undefined,
|
||||
});
|
||||
}, [currentPage, filterType, fetchClients]);
|
||||
const loadData = async () => {
|
||||
// 최초 로드 시 전체 통계도 함께 로드
|
||||
if (!isInitialLoaded) {
|
||||
await loadTotalStats();
|
||||
}
|
||||
await fetchClients({
|
||||
page: currentPage,
|
||||
size: itemsPerPage,
|
||||
q: searchTerm || undefined,
|
||||
onlyActive: filterType === "active" ? true : filterType === "inactive" ? false : undefined,
|
||||
});
|
||||
if (!isInitialLoaded) {
|
||||
setIsInitialLoaded(true);
|
||||
}
|
||||
};
|
||||
loadData();
|
||||
}, [currentPage, filterType, fetchClients, isInitialLoaded, loadTotalStats]);
|
||||
|
||||
// 검색어 변경 시 디바운스 처리
|
||||
const searchTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
||||
@@ -119,6 +169,8 @@ export default function CustomerAccountManagementPage() {
|
||||
const filteredClients = clients.filter((client) => {
|
||||
if (filterType === "active") return client.status === "활성";
|
||||
if (filterType === "inactive") return client.status === "비활성";
|
||||
if (filterType === "purchase") return client.clientType === "매입" || client.clientType === "매입매출";
|
||||
if (filterType === "sales") return client.clientType === "매출" || client.clientType === "매입매출";
|
||||
return true;
|
||||
});
|
||||
|
||||
@@ -165,41 +217,44 @@ export default function CustomerAccountManagementPage() {
|
||||
setMobileDisplayCount(20);
|
||||
}, [searchTerm, filterType]);
|
||||
|
||||
// 통계 (API에서 가져온 전체 데이터 기반)
|
||||
const totalCustomers = pagination?.total || clients.length;
|
||||
const activeCustomers = clients.filter((c) => c.status === "활성").length;
|
||||
const inactiveCustomers = clients.filter((c) => c.status === "비활성").length;
|
||||
|
||||
// 통계 카드 (전체 통계 기준 - 검색과 무관하게 고정)
|
||||
const stats = [
|
||||
{
|
||||
label: "전체 거래처",
|
||||
value: totalCustomers,
|
||||
value: totalStats.total,
|
||||
icon: Users,
|
||||
iconColor: "text-blue-600",
|
||||
},
|
||||
{
|
||||
label: "매입 거래처",
|
||||
value: totalStats.purchase,
|
||||
icon: Building2,
|
||||
iconColor: "text-orange-600",
|
||||
},
|
||||
{
|
||||
label: "매출 거래처",
|
||||
value: totalStats.sales,
|
||||
icon: Building2,
|
||||
iconColor: "text-rose-600",
|
||||
},
|
||||
{
|
||||
label: "활성 거래처",
|
||||
value: activeCustomers,
|
||||
value: totalStats.active,
|
||||
icon: CheckCircle,
|
||||
iconColor: "text-green-600",
|
||||
},
|
||||
{
|
||||
label: "비활성 거래처",
|
||||
value: inactiveCustomers,
|
||||
icon: XCircle,
|
||||
iconColor: "text-gray-600",
|
||||
},
|
||||
];
|
||||
|
||||
// 데이터 새로고침 함수
|
||||
const refreshData = useCallback(() => {
|
||||
// 데이터 새로고침 함수 (삭제/등록 후 통계도 다시 로드)
|
||||
const refreshData = useCallback(async () => {
|
||||
await loadTotalStats(); // 통계 다시 로드
|
||||
fetchClients({
|
||||
page: currentPage,
|
||||
size: itemsPerPage,
|
||||
q: searchTerm || undefined,
|
||||
onlyActive: filterType === "active" ? true : filterType === "inactive" ? false : undefined,
|
||||
});
|
||||
}, [currentPage, itemsPerPage, searchTerm, filterType, fetchClients]);
|
||||
}, [currentPage, itemsPerPage, searchTerm, filterType, fetchClients, loadTotalStats]);
|
||||
|
||||
// 핸들러 - 페이지 기반 네비게이션
|
||||
const handleAddNew = () => {
|
||||
@@ -297,39 +352,74 @@ export default function CustomerAccountManagementPage() {
|
||||
);
|
||||
};
|
||||
|
||||
// 탭 구성
|
||||
// 탭 구성 (전체 | 매입 | 매출 | 활성 | 비활성) - 전체 통계 기준으로 고정
|
||||
const tabs: TabOption[] = [
|
||||
{
|
||||
value: "all",
|
||||
label: "전체",
|
||||
count: totalCustomers,
|
||||
count: totalStats.total,
|
||||
color: "blue",
|
||||
},
|
||||
{
|
||||
value: "purchase",
|
||||
label: "매입",
|
||||
count: totalStats.purchase,
|
||||
color: "orange",
|
||||
},
|
||||
{
|
||||
value: "sales",
|
||||
label: "매출",
|
||||
count: totalStats.sales,
|
||||
color: "rose",
|
||||
},
|
||||
{
|
||||
value: "active",
|
||||
label: "활성",
|
||||
count: activeCustomers,
|
||||
count: totalStats.active,
|
||||
color: "green",
|
||||
},
|
||||
{
|
||||
value: "inactive",
|
||||
label: "비활성",
|
||||
count: inactiveCustomers,
|
||||
count: totalStats.inactive,
|
||||
color: "gray",
|
||||
},
|
||||
];
|
||||
|
||||
// 거래처 유형 배지
|
||||
const getClientTypeBadge = (clientType: Client["clientType"]) => {
|
||||
switch (clientType) {
|
||||
case "매출":
|
||||
return (
|
||||
<Badge className="bg-red-500 text-white hover:bg-red-600">
|
||||
매출
|
||||
</Badge>
|
||||
);
|
||||
case "매입매출":
|
||||
return (
|
||||
<Badge className="bg-yellow-500 text-white hover:bg-yellow-600">
|
||||
매입매출
|
||||
</Badge>
|
||||
);
|
||||
case "매입":
|
||||
default:
|
||||
return (
|
||||
<Badge variant="outline" className="bg-gray-100 text-gray-700 border-gray-200">
|
||||
매입
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
// 테이블 컬럼 정의
|
||||
const tableColumns: TableColumn[] = [
|
||||
{ key: "rowNumber", label: "번호", className: "px-4" },
|
||||
{ key: "code", label: "코드", className: "px-4" },
|
||||
{ key: "clientType", label: "구분", className: "px-4" },
|
||||
{ key: "name", label: "거래처명", className: "px-4" },
|
||||
{ key: "businessNo", label: "사업자번호", className: "px-4" },
|
||||
{ key: "representative", label: "대표자", className: "px-4" },
|
||||
{ key: "manager", label: "담당자", className: "px-4" },
|
||||
{ key: "phone", label: "전화번호", className: "px-4" },
|
||||
{ key: "businessType", label: "업태", className: "px-4" },
|
||||
{ key: "businessItem", label: "업종", className: "px-4" },
|
||||
{ key: "status", label: "상태", className: "px-4" },
|
||||
{ key: "actions", label: "작업", className: "px-4" },
|
||||
];
|
||||
|
||||
@@ -360,16 +450,21 @@ export default function CustomerAccountManagementPage() {
|
||||
{customer.code}
|
||||
</code>
|
||||
</TableCell>
|
||||
<TableCell>{getClientTypeBadge(customer.clientType)}</TableCell>
|
||||
<TableCell className="font-medium">{customer.name}</TableCell>
|
||||
<TableCell>{customer.businessNo}</TableCell>
|
||||
<TableCell>{customer.representative}</TableCell>
|
||||
<TableCell>{customer.managerName || "-"}</TableCell>
|
||||
<TableCell>{customer.phone}</TableCell>
|
||||
<TableCell>{customer.businessType}</TableCell>
|
||||
<TableCell>{customer.businessItem}</TableCell>
|
||||
<TableCell>{getStatusBadge(customer.status)}</TableCell>
|
||||
<TableCell onClick={(e) => e.stopPropagation()}>
|
||||
{isSelected && (
|
||||
<div className="flex gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleView(customer)}
|
||||
>
|
||||
<Eye className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
@@ -417,19 +512,17 @@ export default function CustomerAccountManagementPage() {
|
||||
<code className="inline-block text-xs bg-gray-100 text-gray-700 px-2.5 py-0.5 rounded-md font-mono whitespace-nowrap">
|
||||
{customer.code}
|
||||
</code>
|
||||
{getClientTypeBadge(customer.clientType)}
|
||||
</>
|
||||
}
|
||||
title={customer.name}
|
||||
statusBadge={getStatusBadge(customer.status)}
|
||||
infoGrid={
|
||||
<div className="grid grid-cols-2 gap-x-4 gap-y-3">
|
||||
<InfoField label="사업자번호" value={customer.businessNo} />
|
||||
<InfoField label="대표자" value={customer.representative} />
|
||||
<InfoField label="담당자" value={customer.managerName || "-"} />
|
||||
<InfoField label="전화번호" value={customer.phone} />
|
||||
<InfoField label="이메일" value={customer.email || "-"} />
|
||||
<InfoField label="업태" value={customer.businessType || "-"} />
|
||||
<InfoField label="업종" value={customer.businessItem || "-"} />
|
||||
<InfoField label="등록일" value={customer.registeredDate} />
|
||||
<InfoField label="사업자번호" value={customer.businessNo} />
|
||||
</div>
|
||||
}
|
||||
actions={
|
||||
@@ -466,6 +559,18 @@ export default function CustomerAccountManagementPage() {
|
||||
);
|
||||
};
|
||||
|
||||
// 초기 로딩 중일 때 전체 화면 스피너 표시
|
||||
if (!isInitialLoaded) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-[60vh]">
|
||||
<div className="flex flex-col items-center gap-4">
|
||||
<Loader2 className="h-10 w-10 animate-spin text-primary" />
|
||||
<p className="text-muted-foreground">거래처 목록을 불러오는 중...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<IntegratedListTemplateV2
|
||||
@@ -502,7 +607,6 @@ export default function CustomerAccountManagementPage() {
|
||||
getItemId={(customer) => customer.id}
|
||||
renderTableRow={renderTableRow}
|
||||
renderMobileCard={renderMobileCard}
|
||||
isLoading={isLoading}
|
||||
pagination={{
|
||||
currentPage,
|
||||
totalPages,
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
* 단가 수정 페이지
|
||||
*
|
||||
* 경로: /sales/pricing-management/[id]/edit
|
||||
* API: GET /api/v1/pricing/{id}, PUT /api/v1/pricing/{id}
|
||||
*/
|
||||
|
||||
import { PricingFormClient } from '@/components/pricing';
|
||||
import { getPricingById, updatePricing, finalizePricing } from '@/components/pricing/actions';
|
||||
import type { PricingData } from '@/components/pricing';
|
||||
|
||||
interface EditPricingPageProps {
|
||||
@@ -13,197 +15,10 @@ interface EditPricingPageProps {
|
||||
}>;
|
||||
}
|
||||
|
||||
// TODO: API 연동 시 실제 단가 조회로 교체
|
||||
async function getPricingById(id: string): Promise<PricingData | null> {
|
||||
// 임시 목(Mock) 데이터
|
||||
const mockPricings: Record<string, PricingData> = {
|
||||
'pricing-4': {
|
||||
id: 'pricing-4',
|
||||
itemId: 'item-4',
|
||||
itemCode: 'GR-001',
|
||||
itemName: '가이드레일 130×80',
|
||||
itemType: 'PT',
|
||||
specification: '130×80×2438',
|
||||
unit: 'EA',
|
||||
effectiveDate: '2025-11-24',
|
||||
purchasePrice: 45000,
|
||||
processingCost: 5000,
|
||||
loss: 0,
|
||||
roundingRule: 'round',
|
||||
roundingUnit: 1,
|
||||
marginRate: 20,
|
||||
salesPrice: 60000,
|
||||
supplier: '가이드레일 공급사',
|
||||
note: '스크린용 가이드레일',
|
||||
currentRevision: 1,
|
||||
isFinal: false,
|
||||
revisions: [
|
||||
{
|
||||
revisionNumber: 1,
|
||||
revisionDate: '2025-11-20T10:00:00Z',
|
||||
revisionBy: '관리자',
|
||||
revisionReason: '초기 가격 조정',
|
||||
previousData: {
|
||||
id: 'pricing-4',
|
||||
itemId: 'item-4',
|
||||
itemCode: 'GR-001',
|
||||
itemName: '가이드레일 130×80',
|
||||
itemType: 'PT',
|
||||
specification: '130×80×2438',
|
||||
unit: 'EA',
|
||||
effectiveDate: '2025-11-15',
|
||||
purchasePrice: 40000,
|
||||
processingCost: 5000,
|
||||
marginRate: 15,
|
||||
salesPrice: 51750,
|
||||
currentRevision: 0,
|
||||
isFinal: false,
|
||||
status: 'draft',
|
||||
createdAt: '2025-11-15T09:00:00Z',
|
||||
createdBy: '관리자',
|
||||
},
|
||||
},
|
||||
],
|
||||
status: 'active',
|
||||
createdAt: '2025-11-15T09:00:00Z',
|
||||
createdBy: '관리자',
|
||||
updatedAt: '2025-11-24T14:30:00Z',
|
||||
updatedBy: '관리자',
|
||||
},
|
||||
'pricing-5': {
|
||||
id: 'pricing-5',
|
||||
itemId: 'item-5',
|
||||
itemCode: 'CASE-001',
|
||||
itemName: '케이스 철재',
|
||||
itemType: 'PT',
|
||||
specification: '표준형',
|
||||
unit: 'EA',
|
||||
effectiveDate: '2025-11-20',
|
||||
purchasePrice: 35000,
|
||||
processingCost: 10000,
|
||||
loss: 0,
|
||||
roundingRule: 'round',
|
||||
roundingUnit: 10,
|
||||
marginRate: 25,
|
||||
salesPrice: 56250,
|
||||
currentRevision: 0,
|
||||
isFinal: false,
|
||||
revisions: [],
|
||||
status: 'active',
|
||||
createdAt: '2025-11-20T10:00:00Z',
|
||||
createdBy: '관리자',
|
||||
},
|
||||
'pricing-6': {
|
||||
id: 'pricing-6',
|
||||
itemId: 'item-6',
|
||||
itemCode: 'MOTOR-001',
|
||||
itemName: '모터 0.4KW',
|
||||
itemType: 'PT',
|
||||
specification: '0.4KW',
|
||||
unit: 'EA',
|
||||
effectiveDate: '2025-11-15',
|
||||
purchasePrice: 120000,
|
||||
processingCost: 10000,
|
||||
loss: 0,
|
||||
roundingRule: 'round',
|
||||
roundingUnit: 100,
|
||||
marginRate: 15,
|
||||
salesPrice: 149500,
|
||||
currentRevision: 2,
|
||||
isFinal: false,
|
||||
revisions: [
|
||||
{
|
||||
revisionNumber: 2,
|
||||
revisionDate: '2025-11-12T10:00:00Z',
|
||||
revisionBy: '관리자',
|
||||
revisionReason: '공급가 변동',
|
||||
previousData: {
|
||||
id: 'pricing-6',
|
||||
itemId: 'item-6',
|
||||
itemCode: 'MOTOR-001',
|
||||
itemName: '모터 0.4KW',
|
||||
itemType: 'PT',
|
||||
specification: '0.4KW',
|
||||
unit: 'EA',
|
||||
effectiveDate: '2025-11-10',
|
||||
purchasePrice: 115000,
|
||||
processingCost: 10000,
|
||||
marginRate: 15,
|
||||
salesPrice: 143750,
|
||||
currentRevision: 1,
|
||||
isFinal: false,
|
||||
status: 'active',
|
||||
createdAt: '2025-11-05T09:00:00Z',
|
||||
createdBy: '관리자',
|
||||
},
|
||||
},
|
||||
{
|
||||
revisionNumber: 1,
|
||||
revisionDate: '2025-11-10T10:00:00Z',
|
||||
revisionBy: '관리자',
|
||||
revisionReason: '초기 등록',
|
||||
previousData: {
|
||||
id: 'pricing-6',
|
||||
itemId: 'item-6',
|
||||
itemCode: 'MOTOR-001',
|
||||
itemName: '모터 0.4KW',
|
||||
itemType: 'PT',
|
||||
specification: '0.4KW',
|
||||
unit: 'EA',
|
||||
effectiveDate: '2025-11-05',
|
||||
purchasePrice: 110000,
|
||||
processingCost: 10000,
|
||||
marginRate: 15,
|
||||
salesPrice: 138000,
|
||||
currentRevision: 0,
|
||||
isFinal: false,
|
||||
status: 'draft',
|
||||
createdAt: '2025-11-05T09:00:00Z',
|
||||
createdBy: '관리자',
|
||||
},
|
||||
},
|
||||
],
|
||||
status: 'active',
|
||||
createdAt: '2025-11-05T09:00:00Z',
|
||||
createdBy: '관리자',
|
||||
updatedAt: '2025-11-15T11:00:00Z',
|
||||
updatedBy: '관리자',
|
||||
},
|
||||
'pricing-7': {
|
||||
id: 'pricing-7',
|
||||
itemId: 'item-7',
|
||||
itemCode: 'CTL-001',
|
||||
itemName: '제어기 기본형',
|
||||
itemType: 'PT',
|
||||
specification: '기본형',
|
||||
unit: 'EA',
|
||||
effectiveDate: '2025-11-10',
|
||||
purchasePrice: 80000,
|
||||
processingCost: 5000,
|
||||
loss: 0,
|
||||
roundingRule: 'round',
|
||||
roundingUnit: 1000,
|
||||
marginRate: 20,
|
||||
salesPrice: 102000,
|
||||
currentRevision: 3,
|
||||
isFinal: true,
|
||||
finalizedDate: '2025-11-25T10:00:00Z',
|
||||
finalizedBy: '관리자',
|
||||
revisions: [],
|
||||
status: 'finalized',
|
||||
createdAt: '2025-11-01T09:00:00Z',
|
||||
createdBy: '관리자',
|
||||
updatedAt: '2025-11-25T10:00:00Z',
|
||||
updatedBy: '관리자',
|
||||
},
|
||||
};
|
||||
|
||||
return mockPricings[id] || null;
|
||||
}
|
||||
|
||||
export default async function EditPricingPage({ params }: EditPricingPageProps) {
|
||||
const { id } = await params;
|
||||
|
||||
// 기존 단가 데이터 조회
|
||||
const pricingData = await getPricingById(id);
|
||||
|
||||
if (!pricingData) {
|
||||
@@ -219,15 +34,38 @@ export default async function EditPricingPage({ params }: EditPricingPageProps)
|
||||
);
|
||||
}
|
||||
|
||||
// 서버 액션: 단가 수정
|
||||
async function handleSave(data: PricingData, isRevision?: boolean, revisionReason?: string) {
|
||||
'use server';
|
||||
|
||||
const result = await updatePricing(id, data, revisionReason);
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error(result.error || '단가 수정에 실패했습니다.');
|
||||
}
|
||||
|
||||
console.log('[EditPricingPage] 단가 수정 성공:', result.data, { isRevision, revisionReason });
|
||||
}
|
||||
|
||||
// 서버 액션: 단가 확정
|
||||
async function handleFinalize(priceId: string) {
|
||||
'use server';
|
||||
|
||||
const result = await finalizePricing(priceId);
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error(result.error || '단가 확정에 실패했습니다.');
|
||||
}
|
||||
|
||||
console.log('[EditPricingPage] 단가 확정 성공:', result.data);
|
||||
}
|
||||
|
||||
return (
|
||||
<PricingFormClient
|
||||
mode="edit"
|
||||
initialData={pricingData}
|
||||
onSave={async (data, isRevision, revisionReason) => {
|
||||
'use server';
|
||||
// TODO: API 연동 시 실제 수정 로직으로 교체
|
||||
console.log('단가 수정:', data, isRevision, revisionReason);
|
||||
}}
|
||||
onSave={handleSave}
|
||||
onFinalize={handleFinalize}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,60 +1,31 @@
|
||||
/**
|
||||
* 단가 등록 페이지
|
||||
*
|
||||
* 경로: /sales/pricing-management/create?itemId=xxx&itemCode=xxx
|
||||
* 경로: /sales/pricing-management/create?itemId=xxx&itemTypeCode=MATERIAL|PRODUCT
|
||||
* API: POST /api/v1/pricing
|
||||
*/
|
||||
|
||||
import { PricingFormClient } from '@/components/pricing';
|
||||
import type { ItemInfo } from '@/components/pricing';
|
||||
import { getItemInfo, createPricing } from '@/components/pricing/actions';
|
||||
import type { PricingData } from '@/components/pricing';
|
||||
|
||||
interface CreatePricingPageProps {
|
||||
searchParams: Promise<{
|
||||
itemId?: string;
|
||||
itemCode?: string;
|
||||
itemTypeCode?: 'PRODUCT' | 'MATERIAL'; // PRODUCT 또는 MATERIAL (API 등록 시 필요)
|
||||
}>;
|
||||
}
|
||||
|
||||
// TODO: API 연동 시 실제 품목 조회로 교체
|
||||
async function getItemInfo(itemId: string, itemCode: string): Promise<ItemInfo | null> {
|
||||
// 임시 목(Mock) 데이터
|
||||
const mockItems: Record<string, ItemInfo> = {
|
||||
'item-1': {
|
||||
id: 'item-1',
|
||||
itemCode: 'SCREEN-001',
|
||||
itemName: '스크린 셔터 기본형',
|
||||
itemType: 'FG',
|
||||
specification: '표준형',
|
||||
unit: 'SET',
|
||||
},
|
||||
'item-2': {
|
||||
id: 'item-2',
|
||||
itemCode: 'SCREEN-002',
|
||||
itemName: '스크린 셔터 오픈형',
|
||||
itemType: 'FG',
|
||||
specification: '오픈형',
|
||||
unit: 'SET',
|
||||
},
|
||||
'item-3': {
|
||||
id: 'item-3',
|
||||
itemCode: 'STEEL-001',
|
||||
itemName: '철재 셔터 기본형',
|
||||
itemType: 'FG',
|
||||
specification: '표준형',
|
||||
unit: 'SET',
|
||||
},
|
||||
};
|
||||
|
||||
return mockItems[itemId] || null;
|
||||
}
|
||||
|
||||
export default async function CreatePricingPage({ searchParams }: CreatePricingPageProps) {
|
||||
const params = await searchParams;
|
||||
const itemId = params.itemId || '';
|
||||
const itemCode = params.itemCode || '';
|
||||
const itemTypeCode = params.itemTypeCode || 'MATERIAL';
|
||||
|
||||
const itemInfo = await getItemInfo(itemId, itemCode);
|
||||
// 품목 정보 조회
|
||||
const itemInfo = itemId ? await getItemInfo(itemId) : null;
|
||||
|
||||
if (!itemInfo) {
|
||||
if (!itemInfo && itemId) {
|
||||
return (
|
||||
<div className="container mx-auto py-6 px-4">
|
||||
<div className="text-center py-12">
|
||||
@@ -67,15 +38,38 @@ export default async function CreatePricingPage({ searchParams }: CreatePricingP
|
||||
);
|
||||
}
|
||||
|
||||
// 품목 정보 없이 접근한 경우 (목록에서 바로 등록)
|
||||
if (!itemInfo) {
|
||||
return (
|
||||
<div className="container mx-auto py-6 px-4">
|
||||
<div className="text-center py-12">
|
||||
<h2 className="text-xl font-semibold mb-2">품목을 선택해주세요</h2>
|
||||
<p className="text-muted-foreground">
|
||||
단가 목록에서 품목을 선택한 후 등록해주세요.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 서버 액션: 단가 등록
|
||||
async function handleSave(data: PricingData) {
|
||||
'use server';
|
||||
|
||||
const result = await createPricing(data, itemTypeCode);
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error(result.error || '단가 등록에 실패했습니다.');
|
||||
}
|
||||
|
||||
console.log('[CreatePricingPage] 단가 등록 성공:', result.data);
|
||||
}
|
||||
|
||||
return (
|
||||
<PricingFormClient
|
||||
mode="create"
|
||||
itemInfo={itemInfo}
|
||||
onSave={async (data) => {
|
||||
'use server';
|
||||
// TODO: API 연동 시 실제 저장 로직으로 교체
|
||||
console.log('단가 등록:', data);
|
||||
}}
|
||||
onSave={handleSave}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,177 +2,312 @@
|
||||
* 단가 목록 페이지
|
||||
*
|
||||
* 경로: /sales/pricing-management
|
||||
* API:
|
||||
* - GET /api/v1/items - 품목 목록 (품목기준관리에서 등록한 전체 품목)
|
||||
* - GET /api/v1/pricing - 단가 목록 (등록된 단가 정보)
|
||||
*
|
||||
* 데이터 흐름:
|
||||
* 품목 목록 + 단가 목록 → 병합 → 품목별 단가 현황 표시
|
||||
*/
|
||||
|
||||
import { PricingListClient } from '@/components/pricing';
|
||||
import type { PricingListItem } from '@/components/pricing';
|
||||
import type { PricingListItem, PricingStatus } from '@/components/pricing';
|
||||
import { cookies } from 'next/headers';
|
||||
|
||||
// TODO: API 연동 시 실제 데이터 fetching으로 교체
|
||||
async function getPricingList(): Promise<PricingListItem[]> {
|
||||
// 임시 목(Mock) 데이터
|
||||
return [
|
||||
{
|
||||
id: 'pricing-1',
|
||||
itemId: 'item-1',
|
||||
itemCode: 'SCREEN-001',
|
||||
itemName: '스크린 셔터 기본형',
|
||||
itemType: 'FG',
|
||||
specification: '표준형',
|
||||
unit: 'SET',
|
||||
purchasePrice: undefined,
|
||||
processingCost: undefined,
|
||||
salesPrice: undefined,
|
||||
marginRate: undefined,
|
||||
effectiveDate: undefined,
|
||||
status: 'not_registered',
|
||||
currentRevision: 0,
|
||||
isFinal: false,
|
||||
},
|
||||
{
|
||||
id: 'pricing-2',
|
||||
itemId: 'item-2',
|
||||
itemCode: 'SCREEN-002',
|
||||
itemName: '스크린 셔터 오픈형',
|
||||
itemType: 'FG',
|
||||
specification: '오픈형',
|
||||
unit: 'SET',
|
||||
purchasePrice: undefined,
|
||||
processingCost: undefined,
|
||||
salesPrice: undefined,
|
||||
marginRate: undefined,
|
||||
effectiveDate: undefined,
|
||||
status: 'not_registered',
|
||||
currentRevision: 0,
|
||||
isFinal: false,
|
||||
},
|
||||
{
|
||||
id: 'pricing-3',
|
||||
itemId: 'item-3',
|
||||
itemCode: 'STEEL-001',
|
||||
itemName: '철재 셔터 기본형',
|
||||
itemType: 'FG',
|
||||
specification: '표준형',
|
||||
unit: 'SET',
|
||||
purchasePrice: undefined,
|
||||
processingCost: undefined,
|
||||
salesPrice: undefined,
|
||||
marginRate: undefined,
|
||||
effectiveDate: undefined,
|
||||
status: 'not_registered',
|
||||
currentRevision: 0,
|
||||
isFinal: false,
|
||||
},
|
||||
{
|
||||
id: 'pricing-4',
|
||||
itemId: 'item-4',
|
||||
itemCode: 'GR-001',
|
||||
itemName: '가이드레일 130×80',
|
||||
itemType: 'PT',
|
||||
specification: '130×80×2438',
|
||||
unit: 'EA',
|
||||
purchasePrice: 45000,
|
||||
processingCost: 5000,
|
||||
salesPrice: 60000,
|
||||
marginRate: 20,
|
||||
effectiveDate: '2025-11-24',
|
||||
status: 'active',
|
||||
currentRevision: 1,
|
||||
isFinal: false,
|
||||
},
|
||||
{
|
||||
id: 'pricing-5',
|
||||
itemId: 'item-5',
|
||||
itemCode: 'CASE-001',
|
||||
itemName: '케이스 철재',
|
||||
itemType: 'PT',
|
||||
specification: '표준형',
|
||||
unit: 'EA',
|
||||
purchasePrice: 35000,
|
||||
processingCost: 10000,
|
||||
salesPrice: 56250,
|
||||
marginRate: 25,
|
||||
effectiveDate: '2025-11-20',
|
||||
status: 'active',
|
||||
currentRevision: 0,
|
||||
isFinal: false,
|
||||
},
|
||||
{
|
||||
id: 'pricing-6',
|
||||
itemId: 'item-6',
|
||||
itemCode: 'MOTOR-001',
|
||||
itemName: '모터 0.4KW',
|
||||
itemType: 'PT',
|
||||
specification: '0.4KW',
|
||||
unit: 'EA',
|
||||
purchasePrice: 120000,
|
||||
processingCost: 10000,
|
||||
salesPrice: 149500,
|
||||
marginRate: 15,
|
||||
effectiveDate: '2025-11-15',
|
||||
status: 'active',
|
||||
currentRevision: 2,
|
||||
isFinal: false,
|
||||
},
|
||||
{
|
||||
id: 'pricing-7',
|
||||
itemId: 'item-7',
|
||||
itemCode: 'CTL-001',
|
||||
itemName: '제어기 기본형',
|
||||
itemType: 'PT',
|
||||
specification: '기본형',
|
||||
unit: 'EA',
|
||||
purchasePrice: 80000,
|
||||
processingCost: 5000,
|
||||
salesPrice: 102000,
|
||||
marginRate: 20,
|
||||
effectiveDate: '2025-11-10',
|
||||
status: 'finalized',
|
||||
currentRevision: 3,
|
||||
isFinal: true,
|
||||
},
|
||||
{
|
||||
id: 'pricing-8',
|
||||
itemId: 'item-8',
|
||||
itemCode: '가이드레일wall12*30*12',
|
||||
itemName: '가이드레일',
|
||||
itemType: 'PT',
|
||||
specification: '가이드레일',
|
||||
unit: 'M',
|
||||
purchasePrice: undefined,
|
||||
processingCost: undefined,
|
||||
salesPrice: undefined,
|
||||
marginRate: undefined,
|
||||
effectiveDate: undefined,
|
||||
status: 'not_registered',
|
||||
currentRevision: 0,
|
||||
isFinal: false,
|
||||
},
|
||||
{
|
||||
id: 'pricing-9',
|
||||
itemId: 'item-9',
|
||||
itemCode: '소모품 테스트-소모품 규격 테스트',
|
||||
itemName: '소모품 테스트',
|
||||
itemType: 'CS',
|
||||
specification: '소모품 규격 테스트',
|
||||
unit: 'M',
|
||||
purchasePrice: undefined,
|
||||
processingCost: undefined,
|
||||
salesPrice: undefined,
|
||||
marginRate: undefined,
|
||||
effectiveDate: undefined,
|
||||
status: 'not_registered',
|
||||
currentRevision: 0,
|
||||
isFinal: false,
|
||||
},
|
||||
];
|
||||
// ============================================
|
||||
// API 응답 타입 정의
|
||||
// ============================================
|
||||
|
||||
// 품목 API 응답 타입 (GET /api/v1/items)
|
||||
interface ItemApiData {
|
||||
id: number;
|
||||
item_type: 'PRODUCT' | 'MATERIAL';
|
||||
code: string;
|
||||
name: string;
|
||||
unit: string;
|
||||
category_id: number | null;
|
||||
type_code: string; // FG, PT, SM, RM, CS
|
||||
created_at: string;
|
||||
deleted_at: string | null;
|
||||
}
|
||||
|
||||
interface ItemsApiResponse {
|
||||
success: boolean;
|
||||
data: {
|
||||
current_page: number;
|
||||
data: ItemApiData[];
|
||||
total: number;
|
||||
per_page: number;
|
||||
last_page: number;
|
||||
};
|
||||
message: string;
|
||||
}
|
||||
|
||||
// 단가 API 응답 타입 (GET /api/v1/pricing)
|
||||
interface PriceApiItem {
|
||||
id: number;
|
||||
tenant_id: number;
|
||||
item_type_code: 'PRODUCT' | 'MATERIAL';
|
||||
item_id: number;
|
||||
client_group_id: number | null;
|
||||
purchase_price: string | null;
|
||||
processing_cost: string | null;
|
||||
loss_rate: string | null;
|
||||
margin_rate: string | null;
|
||||
sales_price: string | null;
|
||||
rounding_rule: 'round' | 'ceil' | 'floor';
|
||||
rounding_unit: number;
|
||||
supplier: string | null;
|
||||
effective_from: string;
|
||||
effective_to: string | null;
|
||||
status: 'draft' | 'active' | 'finalized';
|
||||
is_final: boolean;
|
||||
finalized_at: string | null;
|
||||
finalized_by: number | null;
|
||||
note: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
deleted_at: string | null;
|
||||
client_group?: {
|
||||
id: number;
|
||||
name: string;
|
||||
};
|
||||
product?: {
|
||||
id: number;
|
||||
product_code: string;
|
||||
product_name: string;
|
||||
specification: string | null;
|
||||
unit: string;
|
||||
product_type: string;
|
||||
};
|
||||
material?: {
|
||||
id: number;
|
||||
item_code: string;
|
||||
item_name: string;
|
||||
specification: string | null;
|
||||
unit: string;
|
||||
product_type: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface PricingApiResponse {
|
||||
success: boolean;
|
||||
data: {
|
||||
current_page: number;
|
||||
data: PriceApiItem[];
|
||||
total: number;
|
||||
per_page: number;
|
||||
last_page: number;
|
||||
};
|
||||
message: string;
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 헬퍼 함수
|
||||
// ============================================
|
||||
|
||||
// API 헤더 생성
|
||||
async function getApiHeaders(): Promise<HeadersInit> {
|
||||
const cookieStore = await cookies();
|
||||
const token = cookieStore.get('access_token')?.value;
|
||||
|
||||
return {
|
||||
'Accept': 'application/json',
|
||||
'Authorization': token ? `Bearer ${token}` : '',
|
||||
'X-API-KEY': process.env.NEXT_PUBLIC_API_KEY || '',
|
||||
};
|
||||
}
|
||||
|
||||
// 품목 유형 매핑 (type_code → 프론트엔드 ItemType)
|
||||
function mapItemType(typeCode?: string): string {
|
||||
switch (typeCode) {
|
||||
case 'FG': return 'FG'; // 제품
|
||||
case 'PT': return 'PT'; // 부품
|
||||
case 'SM': return 'SM'; // 부자재
|
||||
case 'RM': return 'RM'; // 원자재
|
||||
case 'CS': return 'CS'; // 소모품
|
||||
default: return 'PT';
|
||||
}
|
||||
}
|
||||
|
||||
// API 상태 → 프론트엔드 상태 매핑
|
||||
function mapStatus(apiStatus: string, isFinal: boolean): PricingStatus | 'not_registered' {
|
||||
if (isFinal) return 'finalized';
|
||||
switch (apiStatus) {
|
||||
case 'draft': return 'draft';
|
||||
case 'active': return 'active';
|
||||
case 'finalized': return 'finalized';
|
||||
default: return 'draft';
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// API 호출 함수
|
||||
// ============================================
|
||||
|
||||
// 품목 목록 조회
|
||||
async function getItemsList(): Promise<ItemApiData[]> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/items?size=100`,
|
||||
{
|
||||
method: 'GET',
|
||||
headers,
|
||||
cache: 'no-store',
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
console.error('[PricingPage] Items API Error:', response.status, response.statusText);
|
||||
return [];
|
||||
}
|
||||
|
||||
const result: ItemsApiResponse = await response.json();
|
||||
console.log('[PricingPage] Items API Response count:', result.data?.data?.length || 0);
|
||||
|
||||
if (!result.success || !result.data?.data) {
|
||||
console.warn('[PricingPage] No items data in response');
|
||||
return [];
|
||||
}
|
||||
|
||||
return result.data.data;
|
||||
} catch (error) {
|
||||
console.error('[PricingPage] Items fetch error:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// 단가 목록 조회
|
||||
async function getPricingList(): Promise<PriceApiItem[]> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/pricing?size=100`,
|
||||
{
|
||||
method: 'GET',
|
||||
headers,
|
||||
cache: 'no-store',
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
console.error('[PricingPage] Pricing API Error:', response.status, response.statusText);
|
||||
return [];
|
||||
}
|
||||
|
||||
const result: PricingApiResponse = await response.json();
|
||||
console.log('[PricingPage] Pricing API Response count:', result.data?.data?.length || 0);
|
||||
|
||||
if (!result.success || !result.data?.data) {
|
||||
console.warn('[PricingPage] No pricing data in response');
|
||||
return [];
|
||||
}
|
||||
|
||||
return result.data.data;
|
||||
} catch (error) {
|
||||
console.error('[PricingPage] Pricing fetch error:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 데이터 병합 함수
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* 품목 목록 + 단가 목록 병합
|
||||
*
|
||||
* - 품목 목록을 기준으로 순회
|
||||
* - 각 품목에 해당하는 단가 정보를 매핑
|
||||
* - 단가 미등록 품목은 'not_registered' 상태로 표시
|
||||
*/
|
||||
function mergeItemsWithPricing(
|
||||
items: ItemApiData[],
|
||||
pricings: PriceApiItem[]
|
||||
): PricingListItem[] {
|
||||
// 단가 정보를 빠르게 찾기 위한 Map 생성
|
||||
// key: "PRODUCT_123" 또는 "MATERIAL_456"
|
||||
const pricingMap = new Map<string, PriceApiItem>();
|
||||
|
||||
for (const pricing of pricings) {
|
||||
const key = `${pricing.item_type_code}_${pricing.item_id}`;
|
||||
// 같은 품목에 여러 단가가 있을 수 있으므로 최신 것만 사용
|
||||
if (!pricingMap.has(key)) {
|
||||
pricingMap.set(key, pricing);
|
||||
}
|
||||
}
|
||||
|
||||
// 품목 목록을 기준으로 병합
|
||||
return items.map((item) => {
|
||||
const key = `${item.item_type}_${item.id}`;
|
||||
const pricing = pricingMap.get(key);
|
||||
|
||||
if (pricing) {
|
||||
// 단가 등록된 품목
|
||||
return {
|
||||
id: String(pricing.id),
|
||||
itemId: String(item.id),
|
||||
itemCode: item.code,
|
||||
itemName: item.name,
|
||||
itemType: mapItemType(item.type_code),
|
||||
specification: undefined, // items API에서는 specification 미제공
|
||||
unit: item.unit || 'EA',
|
||||
purchasePrice: pricing.purchase_price ? parseFloat(pricing.purchase_price) : undefined,
|
||||
processingCost: pricing.processing_cost ? parseFloat(pricing.processing_cost) : undefined,
|
||||
salesPrice: pricing.sales_price ? parseFloat(pricing.sales_price) : undefined,
|
||||
marginRate: pricing.margin_rate ? parseFloat(pricing.margin_rate) : undefined,
|
||||
effectiveDate: pricing.effective_from,
|
||||
status: mapStatus(pricing.status, pricing.is_final),
|
||||
currentRevision: 0,
|
||||
isFinal: pricing.is_final,
|
||||
itemTypeCode: item.item_type, // PRODUCT 또는 MATERIAL (등록 시 필요)
|
||||
};
|
||||
} else {
|
||||
// 단가 미등록 품목
|
||||
return {
|
||||
id: `item_${item.id}`, // 임시 ID (단가 ID가 없으므로)
|
||||
itemId: String(item.id),
|
||||
itemCode: item.code,
|
||||
itemName: item.name,
|
||||
itemType: mapItemType(item.type_code),
|
||||
specification: undefined,
|
||||
unit: item.unit || 'EA',
|
||||
purchasePrice: undefined,
|
||||
processingCost: undefined,
|
||||
salesPrice: undefined,
|
||||
marginRate: undefined,
|
||||
effectiveDate: undefined,
|
||||
status: 'not_registered' as const,
|
||||
currentRevision: 0,
|
||||
isFinal: false,
|
||||
itemTypeCode: item.item_type, // PRODUCT 또는 MATERIAL (등록 시 필요)
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 페이지 컴포넌트
|
||||
// ============================================
|
||||
|
||||
export default async function PricingManagementPage() {
|
||||
const pricingList = await getPricingList();
|
||||
// 품목 목록과 단가 목록을 병렬로 조회
|
||||
const [items, pricings] = await Promise.all([
|
||||
getItemsList(),
|
||||
getPricingList(),
|
||||
]);
|
||||
|
||||
console.log('[PricingPage] Items count:', items.length);
|
||||
console.log('[PricingPage] Pricings count:', pricings.length);
|
||||
|
||||
// 데이터 병합
|
||||
const mergedData = mergeItemsWithPricing(items, pricings);
|
||||
console.log('[PricingPage] Merged data count:', mergedData.length);
|
||||
|
||||
return (
|
||||
<div className="container mx-auto py-6 px-4">
|
||||
<PricingListClient initialData={pricingList} />
|
||||
</div>
|
||||
<PricingListClient initialData={mergedData} />
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { LeavePolicyManagement } from '@/components/settings/LeavePolicyManagement';
|
||||
|
||||
export default function LeavePolicyPage() {
|
||||
return <LeavePolicyManagement />;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { PermissionDetailClient } from '@/components/settings/PermissionManagement/PermissionDetailClient';
|
||||
|
||||
interface PageProps {
|
||||
params: Promise<{ id: string }>;
|
||||
}
|
||||
|
||||
export default async function PermissionDetailPage({ params }: PageProps) {
|
||||
const { id } = await params;
|
||||
return <PermissionDetailClient permissionId={id} />;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { PermissionDetailClient } from '@/components/settings/PermissionManagement/PermissionDetailClient';
|
||||
|
||||
export default function NewPermissionPage() {
|
||||
return <PermissionDetailClient permissionId="new" isNew />;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { PermissionManagement } from '@/components/settings/PermissionManagement';
|
||||
|
||||
export default function PermissionsPage() {
|
||||
return <PermissionManagement />;
|
||||
}
|
||||
5
src/app/[locale]/(protected)/settings/ranks/page.tsx
Normal file
5
src/app/[locale]/(protected)/settings/ranks/page.tsx
Normal file
@@ -0,0 +1,5 @@
|
||||
import { RankManagement } from '@/components/settings/RankManagement';
|
||||
|
||||
export default function RanksPage() {
|
||||
return <RankManagement />;
|
||||
}
|
||||
5
src/app/[locale]/(protected)/settings/titles/page.tsx
Normal file
5
src/app/[locale]/(protected)/settings/titles/page.tsx
Normal file
@@ -0,0 +1,5 @@
|
||||
import { TitleManagement } from '@/components/settings/TitleManagement';
|
||||
|
||||
export default function TitlesPage() {
|
||||
return <TitleManagement />;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { WorkScheduleManagement } from '@/components/settings/WorkScheduleManagement';
|
||||
|
||||
export default function WorkSchedulePage() {
|
||||
return <WorkScheduleManagement />;
|
||||
}
|
||||
@@ -400,4 +400,57 @@
|
||||
|
||||
html {
|
||||
font-size: var(--font-size);
|
||||
}
|
||||
|
||||
/* ==========================================
|
||||
Sheet/Dialog Slide Animations
|
||||
========================================== */
|
||||
|
||||
/* Keyframes */
|
||||
@keyframes slideInFromRight {
|
||||
from { transform: translateX(100%); }
|
||||
to { transform: translateX(0); }
|
||||
}
|
||||
|
||||
@keyframes slideOutToRight {
|
||||
from { transform: translateX(0); }
|
||||
to { transform: translateX(100%); }
|
||||
}
|
||||
|
||||
@keyframes slideInFromLeft {
|
||||
from { transform: translateX(-100%); }
|
||||
to { transform: translateX(0); }
|
||||
}
|
||||
|
||||
@keyframes slideOutToLeft {
|
||||
from { transform: translateX(0); }
|
||||
to { transform: translateX(-100%); }
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from { opacity: 0; }
|
||||
to { opacity: 1; }
|
||||
}
|
||||
|
||||
@keyframes fadeOut {
|
||||
from { opacity: 1; }
|
||||
to { opacity: 0; }
|
||||
}
|
||||
|
||||
/* Sheet Content - Right side slide animation */
|
||||
[data-slot="sheet-content"][data-state="open"] {
|
||||
animation: slideInFromRight 300ms cubic-bezier(0.16, 1, 0.3, 1) forwards;
|
||||
}
|
||||
|
||||
[data-slot="sheet-content"][data-state="closed"] {
|
||||
animation: slideOutToRight 200ms cubic-bezier(0.16, 1, 0.3, 1) forwards;
|
||||
}
|
||||
|
||||
/* Sheet Overlay - Fade animation */
|
||||
[data-slot="sheet-overlay"][data-state="open"] {
|
||||
animation: fadeIn 300ms ease-out forwards;
|
||||
}
|
||||
|
||||
[data-slot="sheet-overlay"][data-state="closed"] {
|
||||
animation: fadeOut 200ms ease-out forwards;
|
||||
}
|
||||
@@ -10,7 +10,6 @@
|
||||
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Button } from "../ui/button";
|
||||
import { Badge } from "../ui/badge";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
|
||||
@@ -26,6 +25,8 @@ import {
|
||||
Mail,
|
||||
} from "lucide-react";
|
||||
import { Client } from "../../hooks/useClientList";
|
||||
import { PageLayout } from "../organisms/PageLayout";
|
||||
import { PageHeader } from "../organisms/PageHeader";
|
||||
|
||||
interface ClientDetailProps {
|
||||
client: Client;
|
||||
@@ -63,8 +64,6 @@ export function ClientDetail({
|
||||
onEdit,
|
||||
onDelete,
|
||||
}: ClientDetailProps) {
|
||||
const router = useRouter();
|
||||
|
||||
// 금액 포맷
|
||||
const formatCurrency = (amount: string) => {
|
||||
if (!amount) return "-";
|
||||
@@ -73,30 +72,32 @@ export function ClientDetail({
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* 헤더 */}
|
||||
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<Building2 className="h-6 w-6 text-primary" />
|
||||
<h1 className="text-2xl font-bold">{client.name}</h1>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" onClick={onBack}>
|
||||
<ArrowLeft className="h-4 w-4 mr-2" />
|
||||
목록
|
||||
</Button>
|
||||
<Button variant="outline" onClick={onEdit}>
|
||||
<Pencil className="h-4 w-4 mr-2" />
|
||||
수정
|
||||
</Button>
|
||||
<Button variant="destructive" onClick={onDelete}>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
삭제
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<PageLayout maxWidth="2xl">
|
||||
{/* 헤더 - PageHeader 사용으로 등록/수정과 동일한 레이아웃 */}
|
||||
<PageHeader
|
||||
title={client.name}
|
||||
description="거래처 상세 정보"
|
||||
icon={Building2}
|
||||
actions={
|
||||
<>
|
||||
<Button variant="outline" onClick={onBack}>
|
||||
<ArrowLeft className="h-4 w-4 mr-2" />
|
||||
목록
|
||||
</Button>
|
||||
<Button variant="outline" onClick={onEdit}>
|
||||
<Pencil className="h-4 w-4 mr-2" />
|
||||
수정
|
||||
</Button>
|
||||
<Button variant="destructive" onClick={onDelete}>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
삭제
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* 1. 기본 정보 */}
|
||||
<div className="space-y-6">
|
||||
{/* 1. 기본 정보 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
@@ -242,6 +243,7 @@ export function ClientDetail({
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
@@ -12,24 +12,13 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Input } from "../ui/input";
|
||||
import { Textarea } from "../ui/textarea";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "../ui/select";
|
||||
import { RadioGroup, RadioGroupItem } from "../ui/radio-group";
|
||||
import { Checkbox } from "../ui/checkbox";
|
||||
import { Label } from "../ui/label";
|
||||
import {
|
||||
Building2,
|
||||
UserCircle,
|
||||
Phone,
|
||||
CreditCard,
|
||||
FileText,
|
||||
AlertTriangle,
|
||||
Calculator,
|
||||
} from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
@@ -42,7 +31,6 @@ import {
|
||||
ClientFormData,
|
||||
INITIAL_CLIENT_FORM,
|
||||
ClientType,
|
||||
BadDebtProgress,
|
||||
} from "../../hooks/useClientList";
|
||||
|
||||
interface ClientRegistrationProps {
|
||||
@@ -52,15 +40,33 @@ interface ClientRegistrationProps {
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
// 4자리 영문+숫자 조합 코드 생성 (중복 방지를 위해 타임스탬프 기반)
|
||||
const generateClientCode = (): string => {
|
||||
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
const timestamp = Date.now().toString(36).toUpperCase().slice(-2); // 타임스탬프 2자리
|
||||
let random = "";
|
||||
for (let i = 0; i < 2; i++) {
|
||||
random += chars.charAt(Math.floor(Math.random() * chars.length));
|
||||
}
|
||||
return timestamp + random;
|
||||
};
|
||||
|
||||
export function ClientRegistration({
|
||||
onBack,
|
||||
onSave,
|
||||
editingClient,
|
||||
isLoading = false,
|
||||
}: ClientRegistrationProps) {
|
||||
const [formData, setFormData] = useState<ClientFormData>(
|
||||
editingClient || INITIAL_CLIENT_FORM
|
||||
);
|
||||
const [formData, setFormData] = useState<ClientFormData>(() => {
|
||||
if (editingClient) {
|
||||
return editingClient;
|
||||
}
|
||||
// 신규 등록 시 클라이언트 코드 자동 생성
|
||||
return {
|
||||
...INITIAL_CLIENT_FORM,
|
||||
clientCode: generateClientCode(),
|
||||
};
|
||||
});
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
|
||||
@@ -79,7 +85,15 @@ export function ClientRegistration({
|
||||
newErrors.name = "거래처명은 2자 이상 입력해주세요";
|
||||
}
|
||||
|
||||
if (!formData.businessNo || !/^\d{10}$/.test(formData.businessNo)) {
|
||||
// 하이픈 제거 후 10자리 숫자 검증 (123-45-67890 또는 1234567890 허용)
|
||||
const businessNoDigits = formData.businessNo.replace(/-/g, "").trim();
|
||||
console.log("[ClientRegistration] businessNo 검증:", {
|
||||
원본: formData.businessNo,
|
||||
하이픈제거: businessNoDigits,
|
||||
길이: businessNoDigits.length,
|
||||
숫자만: /^\d{10}$/.test(businessNoDigits),
|
||||
});
|
||||
if (!formData.businessNo || !/^\d{10}$/.test(businessNoDigits)) {
|
||||
newErrors.businessNo = "사업자등록번호는 10자리 숫자여야 합니다";
|
||||
}
|
||||
|
||||
@@ -125,6 +139,7 @@ export function ClientRegistration({
|
||||
field: keyof ClientFormData,
|
||||
value: string | boolean
|
||||
) => {
|
||||
console.log("[ClientRegistration] handleFieldChange:", field, value);
|
||||
setFormData({ ...formData, [field]: value });
|
||||
if (errors[field]) {
|
||||
setErrors((prev) => {
|
||||
@@ -160,10 +175,11 @@ export function ClientRegistration({
|
||||
required
|
||||
error={errors.businessNo}
|
||||
htmlFor="businessNo"
|
||||
type="custom"
|
||||
>
|
||||
<Input
|
||||
id="businessNo"
|
||||
placeholder="10자리 숫자"
|
||||
placeholder="10자리 숫자 (예: 123-45-67890)"
|
||||
value={formData.businessNo}
|
||||
onChange={(e) => handleFieldChange("businessNo", e.target.value)}
|
||||
/>
|
||||
@@ -173,6 +189,7 @@ export function ClientRegistration({
|
||||
label="거래처 코드"
|
||||
htmlFor="clientCode"
|
||||
helpText="자동 생성됩니다"
|
||||
type="custom"
|
||||
>
|
||||
<Input
|
||||
id="clientCode"
|
||||
@@ -189,6 +206,7 @@ export function ClientRegistration({
|
||||
required
|
||||
error={errors.name}
|
||||
htmlFor="name"
|
||||
type="custom"
|
||||
>
|
||||
<Input
|
||||
id="name"
|
||||
@@ -203,6 +221,7 @@ export function ClientRegistration({
|
||||
required
|
||||
error={errors.representative}
|
||||
htmlFor="representative"
|
||||
type="custom"
|
||||
>
|
||||
<Input
|
||||
id="representative"
|
||||
@@ -239,7 +258,7 @@ export function ClientRegistration({
|
||||
</FormField>
|
||||
|
||||
<FormFieldGrid columns={2}>
|
||||
<FormField label="업태" htmlFor="businessType">
|
||||
<FormField label="업태" htmlFor="businessType" type="custom">
|
||||
<Input
|
||||
id="businessType"
|
||||
placeholder="제조업, 도소매업 등"
|
||||
@@ -250,7 +269,7 @@ export function ClientRegistration({
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField label="종목" htmlFor="businessItem">
|
||||
<FormField label="종목" htmlFor="businessItem" type="custom">
|
||||
<Input
|
||||
id="businessItem"
|
||||
placeholder="철강, 건설 등"
|
||||
@@ -269,7 +288,7 @@ export function ClientRegistration({
|
||||
description="거래처의 연락처 정보를 입력하세요"
|
||||
icon={Phone}
|
||||
>
|
||||
<FormField label="주소" htmlFor="address">
|
||||
<FormField label="주소" htmlFor="address" type="custom">
|
||||
<Input
|
||||
id="address"
|
||||
placeholder="주소 입력"
|
||||
@@ -279,7 +298,7 @@ export function ClientRegistration({
|
||||
</FormField>
|
||||
|
||||
<FormFieldGrid columns={3}>
|
||||
<FormField label="전화번호" error={errors.phone} htmlFor="phone">
|
||||
<FormField label="전화번호" error={errors.phone} htmlFor="phone" type="custom">
|
||||
<Input
|
||||
id="phone"
|
||||
placeholder="02-1234-5678"
|
||||
@@ -288,7 +307,7 @@ export function ClientRegistration({
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField label="모바일" htmlFor="mobile">
|
||||
<FormField label="모바일" htmlFor="mobile" type="custom">
|
||||
<Input
|
||||
id="mobile"
|
||||
placeholder="010-1234-5678"
|
||||
@@ -297,7 +316,7 @@ export function ClientRegistration({
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField label="팩스" htmlFor="fax">
|
||||
<FormField label="팩스" htmlFor="fax" type="custom">
|
||||
<Input
|
||||
id="fax"
|
||||
placeholder="02-1234-5678"
|
||||
@@ -307,7 +326,7 @@ export function ClientRegistration({
|
||||
</FormField>
|
||||
</FormFieldGrid>
|
||||
|
||||
<FormField label="이메일" error={errors.email} htmlFor="email">
|
||||
<FormField label="이메일" error={errors.email} htmlFor="email" type="custom">
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
@@ -325,7 +344,7 @@ export function ClientRegistration({
|
||||
icon={UserCircle}
|
||||
>
|
||||
<FormFieldGrid columns={2}>
|
||||
<FormField label="담당자명" htmlFor="managerName">
|
||||
<FormField label="담당자명" htmlFor="managerName" type="custom">
|
||||
<Input
|
||||
id="managerName"
|
||||
placeholder="담당자명 입력"
|
||||
@@ -334,7 +353,7 @@ export function ClientRegistration({
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField label="담당자 전화" htmlFor="managerTel">
|
||||
<FormField label="담당자 전화" htmlFor="managerTel" type="custom">
|
||||
<Input
|
||||
id="managerTel"
|
||||
placeholder="010-1234-5678"
|
||||
@@ -344,7 +363,7 @@ export function ClientRegistration({
|
||||
</FormField>
|
||||
</FormFieldGrid>
|
||||
|
||||
<FormField label="시스템 관리자" htmlFor="systemManager">
|
||||
<FormField label="시스템 관리자" htmlFor="systemManager" type="custom">
|
||||
<Input
|
||||
id="systemManager"
|
||||
placeholder="시스템 관리자명"
|
||||
@@ -356,224 +375,22 @@ export function ClientRegistration({
|
||||
</FormField>
|
||||
</FormSection>
|
||||
|
||||
{/* 4. 발주처 설정 */}
|
||||
<FormSection
|
||||
title="발주처 설정"
|
||||
description="발주처로 사용할 경우 계정 정보를 입력하세요"
|
||||
icon={CreditCard}
|
||||
>
|
||||
<FormFieldGrid columns={2}>
|
||||
<FormField label="계정 ID" htmlFor="accountId">
|
||||
<Input
|
||||
id="accountId"
|
||||
placeholder="계정 ID"
|
||||
value={formData.accountId}
|
||||
onChange={(e) => handleFieldChange("accountId", e.target.value)}
|
||||
/>
|
||||
</FormField>
|
||||
{/*
|
||||
TODO: 기획 확정 후 활성화 (2025-12-09)
|
||||
- 발주처 설정: 계정ID, 비밀번호, 매입/매출 결제일
|
||||
- 약정 세금: 약정 여부, 금액, 시작/종료일
|
||||
- 악성채권 정보: 악성채권 여부, 금액, 발생/만료일, 진행상태
|
||||
|
||||
<FormField label="비밀번호" htmlFor="accountPassword">
|
||||
<Input
|
||||
id="accountPassword"
|
||||
type="password"
|
||||
placeholder="비밀번호"
|
||||
value={formData.accountPassword}
|
||||
onChange={(e) =>
|
||||
handleFieldChange("accountPassword", e.target.value)
|
||||
}
|
||||
/>
|
||||
</FormField>
|
||||
</FormFieldGrid>
|
||||
백엔드 API에서는 이미 지원됨 (nullable 필드)
|
||||
*/}
|
||||
|
||||
<FormFieldGrid columns={2}>
|
||||
<FormField label="매입 결제일" htmlFor="purchasePaymentDay">
|
||||
<Select
|
||||
value={formData.purchasePaymentDay}
|
||||
onValueChange={(value) =>
|
||||
handleFieldChange("purchasePaymentDay", value)
|
||||
}
|
||||
>
|
||||
<SelectTrigger id="purchasePaymentDay">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="말일">말일</SelectItem>
|
||||
<SelectItem value="익월 10일">익월 10일</SelectItem>
|
||||
<SelectItem value="익월 15일">익월 15일</SelectItem>
|
||||
<SelectItem value="익월 20일">익월 20일</SelectItem>
|
||||
<SelectItem value="익월 25일">익월 25일</SelectItem>
|
||||
<SelectItem value="익월 말일">익월 말일</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormField>
|
||||
|
||||
<FormField label="매출 결제일" htmlFor="salesPaymentDay">
|
||||
<Select
|
||||
value={formData.salesPaymentDay}
|
||||
onValueChange={(value) =>
|
||||
handleFieldChange("salesPaymentDay", value)
|
||||
}
|
||||
>
|
||||
<SelectTrigger id="salesPaymentDay">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="말일">말일</SelectItem>
|
||||
<SelectItem value="익월 10일">익월 10일</SelectItem>
|
||||
<SelectItem value="익월 15일">익월 15일</SelectItem>
|
||||
<SelectItem value="익월 20일">익월 20일</SelectItem>
|
||||
<SelectItem value="익월 25일">익월 25일</SelectItem>
|
||||
<SelectItem value="익월 말일">익월 말일</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormField>
|
||||
</FormFieldGrid>
|
||||
</FormSection>
|
||||
|
||||
{/* 5. 약정 세금 */}
|
||||
<FormSection
|
||||
title="약정 세금"
|
||||
description="세금 약정이 있는 경우 입력하세요"
|
||||
icon={Calculator}
|
||||
>
|
||||
<FormField label="약정 여부" type="custom">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="taxAgreement"
|
||||
checked={formData.taxAgreement}
|
||||
onCheckedChange={(checked) =>
|
||||
handleFieldChange("taxAgreement", checked as boolean)
|
||||
}
|
||||
/>
|
||||
<Label htmlFor="taxAgreement">세금 약정 있음</Label>
|
||||
</div>
|
||||
</FormField>
|
||||
|
||||
{formData.taxAgreement && (
|
||||
<>
|
||||
<FormField label="약정 금액" htmlFor="taxAmount">
|
||||
<Input
|
||||
id="taxAmount"
|
||||
type="number"
|
||||
placeholder="약정 금액"
|
||||
value={formData.taxAmount}
|
||||
onChange={(e) => handleFieldChange("taxAmount", e.target.value)}
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormFieldGrid columns={2}>
|
||||
<FormField label="약정 시작일" htmlFor="taxStartDate">
|
||||
<Input
|
||||
id="taxStartDate"
|
||||
type="date"
|
||||
value={formData.taxStartDate}
|
||||
onChange={(e) =>
|
||||
handleFieldChange("taxStartDate", e.target.value)
|
||||
}
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField label="약정 종료일" htmlFor="taxEndDate">
|
||||
<Input
|
||||
id="taxEndDate"
|
||||
type="date"
|
||||
value={formData.taxEndDate}
|
||||
onChange={(e) =>
|
||||
handleFieldChange("taxEndDate", e.target.value)
|
||||
}
|
||||
/>
|
||||
</FormField>
|
||||
</FormFieldGrid>
|
||||
</>
|
||||
)}
|
||||
</FormSection>
|
||||
|
||||
{/* 6. 악성채권 */}
|
||||
<FormSection
|
||||
title="악성채권 정보"
|
||||
description="악성채권이 있는 경우 입력하세요"
|
||||
icon={AlertTriangle}
|
||||
>
|
||||
<FormField label="악성채권 여부" type="custom">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="badDebt"
|
||||
checked={formData.badDebt}
|
||||
onCheckedChange={(checked) =>
|
||||
handleFieldChange("badDebt", checked as boolean)
|
||||
}
|
||||
/>
|
||||
<Label htmlFor="badDebt">악성채권 있음</Label>
|
||||
</div>
|
||||
</FormField>
|
||||
|
||||
{formData.badDebt && (
|
||||
<>
|
||||
<FormField label="악성채권 금액" htmlFor="badDebtAmount">
|
||||
<Input
|
||||
id="badDebtAmount"
|
||||
type="number"
|
||||
placeholder="채권 금액"
|
||||
value={formData.badDebtAmount}
|
||||
onChange={(e) =>
|
||||
handleFieldChange("badDebtAmount", e.target.value)
|
||||
}
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormFieldGrid columns={2}>
|
||||
<FormField label="채권 발생일" htmlFor="badDebtReceiveDate">
|
||||
<Input
|
||||
id="badDebtReceiveDate"
|
||||
type="date"
|
||||
value={formData.badDebtReceiveDate}
|
||||
onChange={(e) =>
|
||||
handleFieldChange("badDebtReceiveDate", e.target.value)
|
||||
}
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField label="채권 만료일" htmlFor="badDebtEndDate">
|
||||
<Input
|
||||
id="badDebtEndDate"
|
||||
type="date"
|
||||
value={formData.badDebtEndDate}
|
||||
onChange={(e) =>
|
||||
handleFieldChange("badDebtEndDate", e.target.value)
|
||||
}
|
||||
/>
|
||||
</FormField>
|
||||
</FormFieldGrid>
|
||||
|
||||
<FormField label="진행 상태" htmlFor="badDebtProgress">
|
||||
<Select
|
||||
value={formData.badDebtProgress}
|
||||
onValueChange={(value) =>
|
||||
handleFieldChange("badDebtProgress", value as BadDebtProgress)
|
||||
}
|
||||
>
|
||||
<SelectTrigger id="badDebtProgress">
|
||||
<SelectValue placeholder="진행 상태 선택" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="협의중">협의중</SelectItem>
|
||||
<SelectItem value="소송중">소송중</SelectItem>
|
||||
<SelectItem value="회수완료">회수완료</SelectItem>
|
||||
<SelectItem value="대손처리">대손처리</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormField>
|
||||
</>
|
||||
)}
|
||||
</FormSection>
|
||||
|
||||
{/* 7. 기타 */}
|
||||
{/* 4. 기타 */}
|
||||
<FormSection
|
||||
title="기타 정보"
|
||||
description="추가 정보를 입력하세요"
|
||||
icon={FileText}
|
||||
>
|
||||
<FormField label="메모" htmlFor="memo">
|
||||
<FormField label="메모" htmlFor="memo" type="custom">
|
||||
<Textarea
|
||||
id="memo"
|
||||
placeholder="메모 입력"
|
||||
|
||||
@@ -378,10 +378,10 @@ export function DataTable<T extends BaseDataItem>({
|
||||
: col.render
|
||||
? col.render(value, row, index)
|
||||
: value;
|
||||
if (rendered === null) return null;
|
||||
if (rendered === null || rendered === undefined) return null;
|
||||
return (
|
||||
<div key={col.key}>
|
||||
{rendered}
|
||||
{rendered as React.ReactNode}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
* 모든 목록 페이지에서 재사용 가능한 테이블 컴포넌트
|
||||
*/
|
||||
|
||||
import { DataTable } from './DataTable';
|
||||
|
||||
export { DataTable } from './DataTable';
|
||||
export { SearchFilter } from './SearchFilter';
|
||||
export { Pagination } from './Pagination';
|
||||
|
||||
287
src/components/hr/SalaryManagement/SalaryDetailDialog.tsx
Normal file
287
src/components/hr/SalaryManagement/SalaryDetailDialog.tsx
Normal file
@@ -0,0 +1,287 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { Plus, Save } from 'lucide-react';
|
||||
import type { SalaryDetail, PaymentStatus } from './types';
|
||||
import {
|
||||
PAYMENT_STATUS_LABELS,
|
||||
PAYMENT_STATUS_COLORS,
|
||||
formatCurrency,
|
||||
} from './types';
|
||||
|
||||
interface SalaryDetailDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
salaryDetail: SalaryDetail | null;
|
||||
onSave?: (updatedDetail: SalaryDetail) => void;
|
||||
onAddPaymentItem?: () => void;
|
||||
}
|
||||
|
||||
export function SalaryDetailDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
salaryDetail,
|
||||
onSave,
|
||||
onAddPaymentItem,
|
||||
}: SalaryDetailDialogProps) {
|
||||
const [editedStatus, setEditedStatus] = useState<PaymentStatus>('scheduled');
|
||||
const [hasChanges, setHasChanges] = useState(false);
|
||||
|
||||
// 다이얼로그가 열릴 때 상태 초기화
|
||||
useEffect(() => {
|
||||
if (salaryDetail) {
|
||||
setEditedStatus(salaryDetail.status);
|
||||
setHasChanges(false);
|
||||
}
|
||||
}, [salaryDetail]);
|
||||
|
||||
if (!salaryDetail) return null;
|
||||
|
||||
const handleStatusChange = (newStatus: PaymentStatus) => {
|
||||
setEditedStatus(newStatus);
|
||||
setHasChanges(newStatus !== salaryDetail.status);
|
||||
};
|
||||
|
||||
const handleSave = () => {
|
||||
if (onSave && salaryDetail) {
|
||||
onSave({
|
||||
...salaryDetail,
|
||||
status: editedStatus,
|
||||
});
|
||||
}
|
||||
setHasChanges(false);
|
||||
};
|
||||
|
||||
const handleAddPaymentItem = () => {
|
||||
if (onAddPaymentItem) {
|
||||
onAddPaymentItem();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
급여 수정 - {salaryDetail.employeeName}
|
||||
</div>
|
||||
{/* 상태 변경 셀렉트 박스 */}
|
||||
<Select
|
||||
value={editedStatus}
|
||||
onValueChange={(value) => handleStatusChange(value as PaymentStatus)}
|
||||
>
|
||||
<SelectTrigger className="w-[140px]">
|
||||
<SelectValue>
|
||||
<Badge className={PAYMENT_STATUS_COLORS[editedStatus]}>
|
||||
{PAYMENT_STATUS_LABELS[editedStatus]}
|
||||
</Badge>
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="scheduled">
|
||||
<Badge className={PAYMENT_STATUS_COLORS.scheduled}>
|
||||
{PAYMENT_STATUS_LABELS.scheduled}
|
||||
</Badge>
|
||||
</SelectItem>
|
||||
<SelectItem value="completed">
|
||||
<Badge className={PAYMENT_STATUS_COLORS.completed}>
|
||||
{PAYMENT_STATUS_LABELS.completed}
|
||||
</Badge>
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-6">
|
||||
{/* 기본 정보 */}
|
||||
<div className="bg-muted/50 rounded-lg p-4">
|
||||
<h3 className="font-semibold mb-3">기본 정보</h3>
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
|
||||
<div>
|
||||
<span className="text-muted-foreground">사번</span>
|
||||
<p className="font-medium">{salaryDetail.employeeId}</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">이름</span>
|
||||
<p className="font-medium">{salaryDetail.employeeName}</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">부서</span>
|
||||
<p className="font-medium">{salaryDetail.department}</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">직급</span>
|
||||
<p className="font-medium">{salaryDetail.rank}</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">직책</span>
|
||||
<p className="font-medium">{salaryDetail.position}</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">지급월</span>
|
||||
<p className="font-medium">{salaryDetail.year}년 {salaryDetail.month}월</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">지급일</span>
|
||||
<p className="font-medium">{salaryDetail.paymentDate}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 급여 항목 */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
{/* 수당 내역 */}
|
||||
<div className="border rounded-lg p-4">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<h3 className="font-semibold text-blue-600">수당 내역</h3>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleAddPaymentItem}
|
||||
className="h-7 text-xs"
|
||||
>
|
||||
<Plus className="h-3 w-3 mr-1" />
|
||||
지급항목 추가
|
||||
</Button>
|
||||
</div>
|
||||
<div className="space-y-2 text-sm">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">본봉</span>
|
||||
<span className="font-medium">{formatCurrency(salaryDetail.baseSalary)}원</span>
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">직책수당</span>
|
||||
<span>{formatCurrency(salaryDetail.allowances.positionAllowance)}원</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">초과근무수당</span>
|
||||
<span>{formatCurrency(salaryDetail.allowances.overtimeAllowance)}원</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">식대</span>
|
||||
<span>{formatCurrency(salaryDetail.allowances.mealAllowance)}원</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">교통비</span>
|
||||
<span>{formatCurrency(salaryDetail.allowances.transportAllowance)}원</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">기타수당</span>
|
||||
<span>{formatCurrency(salaryDetail.allowances.otherAllowance)}원</span>
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="flex justify-between font-semibold text-blue-600">
|
||||
<span>수당 합계</span>
|
||||
<span>{formatCurrency(salaryDetail.totalAllowance)}원</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 공제 내역 */}
|
||||
<div className="border rounded-lg p-4">
|
||||
<h3 className="font-semibold mb-3 text-red-600">공제 내역</h3>
|
||||
<div className="space-y-2 text-sm">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">국민연금</span>
|
||||
<span className="text-red-600">-{formatCurrency(salaryDetail.deductions.nationalPension)}원</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">건강보험</span>
|
||||
<span className="text-red-600">-{formatCurrency(salaryDetail.deductions.healthInsurance)}원</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">장기요양보험</span>
|
||||
<span className="text-red-600">-{formatCurrency(salaryDetail.deductions.longTermCare)}원</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">고용보험</span>
|
||||
<span className="text-red-600">-{formatCurrency(salaryDetail.deductions.employmentInsurance)}원</span>
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">소득세</span>
|
||||
<span className="text-red-600">-{formatCurrency(salaryDetail.deductions.incomeTax)}원</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">지방소득세</span>
|
||||
<span className="text-red-600">-{formatCurrency(salaryDetail.deductions.localIncomeTax)}원</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">기타공제</span>
|
||||
<span className="text-red-600">-{formatCurrency(salaryDetail.deductions.otherDeduction)}원</span>
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="flex justify-between font-semibold text-red-600">
|
||||
<span>공제 합계</span>
|
||||
<span>-{formatCurrency(salaryDetail.totalDeduction)}원</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 지급 합계 */}
|
||||
<div className="bg-primary/5 border-2 border-primary/20 rounded-lg p-4">
|
||||
<div className="grid grid-cols-3 gap-4 text-center">
|
||||
<div>
|
||||
<span className="text-sm text-muted-foreground block">급여 총액</span>
|
||||
<span className="text-lg font-semibold text-blue-600">
|
||||
{formatCurrency(salaryDetail.baseSalary + salaryDetail.totalAllowance)}원
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-sm text-muted-foreground block">공제 총액</span>
|
||||
<span className="text-lg font-semibold text-red-600">
|
||||
-{formatCurrency(salaryDetail.totalDeduction)}원
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-sm text-muted-foreground block">실지급액</span>
|
||||
<span className="text-xl font-bold text-primary">
|
||||
{formatCurrency(salaryDetail.netPayment)}원
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 저장 버튼 */}
|
||||
<DialogFooter className="mt-6">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
>
|
||||
취소
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
disabled={!hasChanges}
|
||||
className="gap-2"
|
||||
>
|
||||
<Save className="h-4 w-4" />
|
||||
저장
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
509
src/components/hr/SalaryManagement/index.tsx
Normal file
509
src/components/hr/SalaryManagement/index.tsx
Normal file
@@ -0,0 +1,509 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useMemo, useCallback } from 'react';
|
||||
import { format } from 'date-fns';
|
||||
import {
|
||||
Download,
|
||||
DollarSign,
|
||||
Check,
|
||||
Clock,
|
||||
Pencil,
|
||||
Banknote,
|
||||
Briefcase,
|
||||
Timer,
|
||||
Gift,
|
||||
MinusCircle,
|
||||
} from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { TableRow, TableCell } from '@/components/ui/table';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import {
|
||||
IntegratedListTemplateV2,
|
||||
type TableColumn,
|
||||
type StatCard,
|
||||
type TabOption,
|
||||
} from '@/components/templates/IntegratedListTemplateV2';
|
||||
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
|
||||
import { SalaryDetailDialog } from './SalaryDetailDialog';
|
||||
import type {
|
||||
SalaryRecord,
|
||||
SalaryDetail,
|
||||
PaymentStatus,
|
||||
SortOption,
|
||||
} from './types';
|
||||
import {
|
||||
PAYMENT_STATUS_LABELS,
|
||||
PAYMENT_STATUS_COLORS,
|
||||
SORT_OPTIONS,
|
||||
formatCurrency,
|
||||
} from './types';
|
||||
|
||||
// ===== Mock 데이터 생성 =====
|
||||
const generateSalaryData = (): SalaryRecord[] => {
|
||||
const departments = ['개발팀', '디자인팀', '기획팀', '영업팀', '인사팀'];
|
||||
const positions = ['팀장', '파트장', '선임', '주임', '사원'];
|
||||
const ranks = ['부장', '차장', '과장', '대리', '사원'];
|
||||
const statuses: PaymentStatus[] = ['scheduled', 'completed'];
|
||||
const names = ['김철수', '이영희', '박민수', '정수진', '최동현', '강미영', '윤상호', '임지현', '한승우', '송예진'];
|
||||
|
||||
return Array.from({ length: 10 }, (_, i) => {
|
||||
const baseSalary = 3000000 + Math.floor(Math.random() * 2000000);
|
||||
const allowance = 300000 + Math.floor(Math.random() * 500000);
|
||||
const overtime = Math.floor(Math.random() * 500000);
|
||||
const bonus = Math.floor(Math.random() * 1000000);
|
||||
const deduction = 200000 + Math.floor(Math.random() * 300000);
|
||||
const netPayment = baseSalary + allowance + overtime + bonus - deduction;
|
||||
|
||||
return {
|
||||
id: `salary-${i + 1}`,
|
||||
employeeId: `EMP${String(i + 1).padStart(3, '0')}`,
|
||||
employeeName: names[i],
|
||||
department: departments[i % departments.length],
|
||||
position: positions[i % positions.length],
|
||||
rank: ranks[i % ranks.length],
|
||||
baseSalary,
|
||||
allowance,
|
||||
overtime,
|
||||
bonus,
|
||||
deduction,
|
||||
netPayment,
|
||||
paymentDate: format(new Date(2025, 11, 25), 'yyyy-MM-dd'),
|
||||
status: statuses[i % statuses.length],
|
||||
year: 2025,
|
||||
month: 12,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
// Mock 상세 데이터 생성
|
||||
const generateSalaryDetail = (record: SalaryRecord): SalaryDetail => {
|
||||
const positionAllowance = 100000 + Math.floor(Math.random() * 200000);
|
||||
const overtimeAllowance = Math.floor(Math.random() * 300000);
|
||||
const mealAllowance = 100000;
|
||||
const transportAllowance = 100000;
|
||||
const otherAllowance = Math.floor(Math.random() * 100000);
|
||||
|
||||
const totalAllowance = positionAllowance + overtimeAllowance + mealAllowance + transportAllowance + otherAllowance;
|
||||
|
||||
const nationalPension = Math.floor(record.baseSalary * 0.045);
|
||||
const healthInsurance = Math.floor(record.baseSalary * 0.0343);
|
||||
const longTermCare = Math.floor(healthInsurance * 0.1227);
|
||||
const employmentInsurance = Math.floor(record.baseSalary * 0.009);
|
||||
const incomeTax = Math.floor((record.baseSalary + totalAllowance) * 0.08);
|
||||
const localIncomeTax = Math.floor(incomeTax * 0.1);
|
||||
const otherDeduction = Math.floor(Math.random() * 50000);
|
||||
|
||||
const totalDeduction = nationalPension + healthInsurance + longTermCare + employmentInsurance + incomeTax + localIncomeTax + otherDeduction;
|
||||
|
||||
return {
|
||||
employeeId: record.employeeId,
|
||||
employeeName: record.employeeName,
|
||||
department: record.department,
|
||||
position: record.position,
|
||||
rank: record.rank,
|
||||
baseSalary: record.baseSalary,
|
||||
allowances: {
|
||||
positionAllowance,
|
||||
overtimeAllowance,
|
||||
mealAllowance,
|
||||
transportAllowance,
|
||||
otherAllowance,
|
||||
},
|
||||
deductions: {
|
||||
nationalPension,
|
||||
healthInsurance,
|
||||
longTermCare,
|
||||
employmentInsurance,
|
||||
incomeTax,
|
||||
localIncomeTax,
|
||||
otherDeduction,
|
||||
},
|
||||
totalAllowance,
|
||||
totalDeduction,
|
||||
netPayment: record.baseSalary + totalAllowance - totalDeduction,
|
||||
paymentDate: record.paymentDate,
|
||||
status: record.status,
|
||||
year: record.year,
|
||||
month: record.month,
|
||||
};
|
||||
};
|
||||
|
||||
export function SalaryManagement() {
|
||||
// ===== 상태 관리 =====
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [sortOption, setSortOption] = useState<SortOption>('rank');
|
||||
const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const itemsPerPage = 20;
|
||||
|
||||
// 날짜 범위 상태
|
||||
const [startDate, setStartDate] = useState('2025-12-01');
|
||||
const [endDate, setEndDate] = useState('2025-12-31');
|
||||
|
||||
// 다이얼로그 상태
|
||||
const [detailDialogOpen, setDetailDialogOpen] = useState(false);
|
||||
const [selectedSalaryDetail, setSelectedSalaryDetail] = useState<SalaryDetail | null>(null);
|
||||
|
||||
// Mock 데이터
|
||||
const [salaryData, setSalaryData] = useState<SalaryRecord[]>(generateSalaryData);
|
||||
|
||||
// ===== 체크박스 핸들러 =====
|
||||
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)));
|
||||
}
|
||||
}, [selectedItems.size]);
|
||||
|
||||
// ===== 필터링된 데이터 =====
|
||||
const filteredData = useMemo(() => {
|
||||
return salaryData.filter(item =>
|
||||
item.employeeName.includes(searchQuery) ||
|
||||
item.department.includes(searchQuery)
|
||||
);
|
||||
}, [salaryData, searchQuery]);
|
||||
|
||||
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 handleMarkCompleted = useCallback(() => {
|
||||
if (selectedItems.size === 0) return;
|
||||
|
||||
setSalaryData(prev => prev.map(item => {
|
||||
if (selectedItems.has(item.id)) {
|
||||
return { ...item, status: 'completed' as PaymentStatus };
|
||||
}
|
||||
return item;
|
||||
}));
|
||||
|
||||
setSelectedItems(new Set());
|
||||
console.log('지급완료 처리:', Array.from(selectedItems));
|
||||
}, [selectedItems]);
|
||||
|
||||
// ===== 지급예정 핸들러 =====
|
||||
const handleMarkScheduled = useCallback(() => {
|
||||
if (selectedItems.size === 0) return;
|
||||
|
||||
setSalaryData(prev => prev.map(item => {
|
||||
if (selectedItems.has(item.id)) {
|
||||
return { ...item, status: 'scheduled' as PaymentStatus };
|
||||
}
|
||||
return item;
|
||||
}));
|
||||
|
||||
setSelectedItems(new Set());
|
||||
console.log('지급예정 처리:', Array.from(selectedItems));
|
||||
}, [selectedItems]);
|
||||
|
||||
// ===== 상세보기 핸들러 =====
|
||||
const handleViewDetail = useCallback((record: SalaryRecord) => {
|
||||
const detail = generateSalaryDetail(record);
|
||||
setSelectedSalaryDetail(detail);
|
||||
setDetailDialogOpen(true);
|
||||
}, []);
|
||||
|
||||
// ===== 급여 상세 저장 핸들러 =====
|
||||
const handleSaveDetail = useCallback((updatedDetail: SalaryDetail) => {
|
||||
setSalaryData(prev => prev.map(item => {
|
||||
if (item.employeeId === updatedDetail.employeeId) {
|
||||
return {
|
||||
...item,
|
||||
status: updatedDetail.status,
|
||||
};
|
||||
}
|
||||
return item;
|
||||
}));
|
||||
setDetailDialogOpen(false);
|
||||
console.log('급여 상세 저장:', updatedDetail);
|
||||
}, []);
|
||||
|
||||
// ===== 지급항목 추가 핸들러 =====
|
||||
const handleAddPaymentItem = useCallback(() => {
|
||||
// TODO: 지급항목 추가 다이얼로그 또는 로직 구현
|
||||
console.log('지급항목 추가 클릭');
|
||||
}, []);
|
||||
|
||||
// ===== 탭 (단일 탭) =====
|
||||
const [activeTab, setActiveTab] = useState('all');
|
||||
const tabs: TabOption[] = useMemo(() => [
|
||||
{ value: 'all', label: '전체', count: salaryData.length, color: 'blue' },
|
||||
], [salaryData.length]);
|
||||
|
||||
// ===== 통계 카드 (총 실지급액, 총 기본급, 총 수당, 초과근무, 상여, 총공제) =====
|
||||
const statCards: StatCard[] = useMemo(() => {
|
||||
const totalNetPayment = salaryData.reduce((sum, s) => sum + s.netPayment, 0);
|
||||
const totalBaseSalary = salaryData.reduce((sum, s) => sum + s.baseSalary, 0);
|
||||
const totalAllowance = salaryData.reduce((sum, s) => sum + s.allowance, 0);
|
||||
const totalOvertime = salaryData.reduce((sum, s) => sum + s.overtime, 0);
|
||||
const totalBonus = salaryData.reduce((sum, s) => sum + s.bonus, 0);
|
||||
const totalDeduction = salaryData.reduce((sum, s) => sum + s.deduction, 0);
|
||||
|
||||
return [
|
||||
{
|
||||
label: '총 실지급액',
|
||||
value: `${formatCurrency(totalNetPayment)}원`,
|
||||
icon: DollarSign,
|
||||
iconColor: 'text-green-500',
|
||||
},
|
||||
{
|
||||
label: '총 기본급',
|
||||
value: `${formatCurrency(totalBaseSalary)}원`,
|
||||
icon: Banknote,
|
||||
iconColor: 'text-blue-500',
|
||||
},
|
||||
{
|
||||
label: '총 수당',
|
||||
value: `${formatCurrency(totalAllowance)}원`,
|
||||
icon: Briefcase,
|
||||
iconColor: 'text-purple-500',
|
||||
},
|
||||
{
|
||||
label: '초과근무',
|
||||
value: `${formatCurrency(totalOvertime)}원`,
|
||||
icon: Timer,
|
||||
iconColor: 'text-orange-500',
|
||||
},
|
||||
{
|
||||
label: '상여',
|
||||
value: `${formatCurrency(totalBonus)}원`,
|
||||
icon: Gift,
|
||||
iconColor: 'text-pink-500',
|
||||
},
|
||||
{
|
||||
label: '총 공제',
|
||||
value: `${formatCurrency(totalDeduction)}원`,
|
||||
icon: MinusCircle,
|
||||
iconColor: 'text-red-500',
|
||||
},
|
||||
];
|
||||
}, [salaryData]);
|
||||
|
||||
// ===== 테이블 컬럼 (부서, 직책, 이름, 직급, 기본급, 수당, 초과근무, 상여, 공제, 실지급액, 일자, 상태, 작업) =====
|
||||
const tableColumns: TableColumn[] = useMemo(() => [
|
||||
{ key: 'department', label: '부서' },
|
||||
{ key: 'position', label: '직책' },
|
||||
{ key: 'name', label: '이름' },
|
||||
{ key: 'rank', label: '직급' },
|
||||
{ key: 'baseSalary', label: '기본급', className: 'text-right' },
|
||||
{ key: 'allowance', label: '수당', className: 'text-right' },
|
||||
{ key: 'overtime', label: '초과근무', className: 'text-right' },
|
||||
{ key: 'bonus', label: '상여', className: 'text-right' },
|
||||
{ key: 'deduction', label: '공제', className: 'text-right' },
|
||||
{ key: 'netPayment', label: '실지급액', className: 'text-right' },
|
||||
{ key: 'paymentDate', label: '일자', className: 'text-center' },
|
||||
{ key: 'status', label: '상태', className: 'text-center' },
|
||||
{ key: 'action', label: '작업', className: 'text-center w-[80px]' },
|
||||
], []);
|
||||
|
||||
// ===== 테이블 행 렌더링 =====
|
||||
const renderTableRow = useCallback((item: SalaryRecord, index: number, globalIndex: number) => {
|
||||
const isSelected = selectedItems.has(item.id);
|
||||
|
||||
return (
|
||||
<TableRow key={item.id} className="hover:bg-muted/50">
|
||||
<TableCell className="text-center">
|
||||
<Checkbox checked={isSelected} onCheckedChange={() => toggleSelection(item.id)} />
|
||||
</TableCell>
|
||||
<TableCell>{item.department}</TableCell>
|
||||
<TableCell>{item.position}</TableCell>
|
||||
<TableCell className="font-medium">{item.employeeName}</TableCell>
|
||||
<TableCell>{item.rank}</TableCell>
|
||||
<TableCell className="text-right">{formatCurrency(item.baseSalary)}원</TableCell>
|
||||
<TableCell className="text-right">{formatCurrency(item.allowance)}원</TableCell>
|
||||
<TableCell className="text-right">{formatCurrency(item.overtime)}원</TableCell>
|
||||
<TableCell className="text-right">{formatCurrency(item.bonus)}원</TableCell>
|
||||
<TableCell className="text-right text-red-600">-{formatCurrency(item.deduction)}원</TableCell>
|
||||
<TableCell className="text-right font-medium text-green-600">{formatCurrency(item.netPayment)}원</TableCell>
|
||||
<TableCell className="text-center">{item.paymentDate}</TableCell>
|
||||
<TableCell className="text-center">
|
||||
<Badge className={PAYMENT_STATUS_COLORS[item.status]}>
|
||||
{PAYMENT_STATUS_LABELS[item.status]}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="text-center">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleViewDetail(item)}
|
||||
title="수정"
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
}, [selectedItems, toggleSelection, handleViewDetail]);
|
||||
|
||||
// ===== 모바일 카드 렌더링 =====
|
||||
const renderMobileCard = useCallback((
|
||||
item: SalaryRecord,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
isSelected: boolean,
|
||||
onToggle: () => void
|
||||
) => {
|
||||
return (
|
||||
<ListMobileCard
|
||||
id={item.id}
|
||||
title={item.employeeName}
|
||||
headerBadges={
|
||||
<Badge className={PAYMENT_STATUS_COLORS[item.status]}>
|
||||
{PAYMENT_STATUS_LABELS[item.status]}
|
||||
</Badge>
|
||||
}
|
||||
isSelected={isSelected}
|
||||
onToggleSelection={onToggle}
|
||||
infoGrid={
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<InfoField label="부서" value={item.department} />
|
||||
<InfoField label="직급" value={item.rank} />
|
||||
<InfoField label="기본급" value={`${formatCurrency(item.baseSalary)}원`} />
|
||||
<InfoField label="수당" value={`${formatCurrency(item.allowance)}원`} />
|
||||
<InfoField label="초과근무" value={`${formatCurrency(item.overtime)}원`} />
|
||||
<InfoField label="상여" value={`${formatCurrency(item.bonus)}원`} />
|
||||
<InfoField label="공제" value={`-${formatCurrency(item.deduction)}원`} />
|
||||
<InfoField label="실지급액" value={`${formatCurrency(item.netPayment)}원`} />
|
||||
<InfoField label="지급일" value={item.paymentDate} />
|
||||
</div>
|
||||
}
|
||||
actions={
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-full"
|
||||
onClick={() => handleViewDetail(item)}
|
||||
>
|
||||
<Pencil className="h-4 w-4 mr-2" />
|
||||
수정
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}, [handleViewDetail]);
|
||||
|
||||
// ===== 헤더 액션 =====
|
||||
const headerActions = (
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
{/* 날짜 범위 선택 */}
|
||||
<div className="flex items-center gap-1">
|
||||
<Input
|
||||
type="date"
|
||||
value={startDate}
|
||||
onChange={(e) => setStartDate(e.target.value)}
|
||||
className="w-[140px]"
|
||||
/>
|
||||
<span className="text-muted-foreground">~</span>
|
||||
<Input
|
||||
type="date"
|
||||
value={endDate}
|
||||
onChange={(e) => setEndDate(e.target.value)}
|
||||
className="w-[140px]"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 지급완료/지급예정 버튼 - 선택된 항목이 있을 때만 표시 */}
|
||||
{selectedItems.size > 0 && (
|
||||
<>
|
||||
<Button variant="default" onClick={handleMarkCompleted}>
|
||||
<Check className="h-4 w-4 mr-2" />
|
||||
지급완료
|
||||
</Button>
|
||||
<Button variant="outline" onClick={handleMarkScheduled}>
|
||||
<Clock className="h-4 w-4 mr-2" />
|
||||
지급예정
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
|
||||
<Button variant="outline" onClick={() => console.log('엑셀 다운로드')}>
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
엑셀 다운로드
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
|
||||
// ===== 정렬 필터 =====
|
||||
const extraFilters = (
|
||||
<Select value={sortOption} onValueChange={(v) => setSortOption(v as SortOption)}>
|
||||
<SelectTrigger className="w-[120px]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{Object.entries(SORT_OPTIONS).map(([key, label]) => (
|
||||
<SelectItem key={key} value={key}>{label}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<IntegratedListTemplateV2
|
||||
title="급여관리"
|
||||
description="직원들의 급여 현황을 관리합니다"
|
||||
icon={DollarSign}
|
||||
headerActions={headerActions}
|
||||
stats={statCards}
|
||||
searchValue={searchQuery}
|
||||
onSearchChange={setSearchQuery}
|
||||
searchPlaceholder="이름, 부서 검색..."
|
||||
extraFilters={extraFilters}
|
||||
tabs={tabs}
|
||||
activeTab={activeTab}
|
||||
onTabChange={setActiveTab}
|
||||
tableColumns={tableColumns}
|
||||
data={paginatedData}
|
||||
totalCount={filteredData.length}
|
||||
allData={filteredData}
|
||||
selectedItems={selectedItems}
|
||||
onToggleSelection={toggleSelection}
|
||||
onToggleSelectAll={toggleSelectAll}
|
||||
getItemId={(item: SalaryRecord) => item.id}
|
||||
renderTableRow={renderTableRow}
|
||||
renderMobileCard={renderMobileCard}
|
||||
pagination={{
|
||||
currentPage,
|
||||
totalPages,
|
||||
totalItems: filteredData.length,
|
||||
itemsPerPage,
|
||||
onPageChange: setCurrentPage,
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* 급여 상세 다이얼로그 */}
|
||||
<SalaryDetailDialog
|
||||
open={detailDialogOpen}
|
||||
onOpenChange={setDetailDialogOpen}
|
||||
salaryDetail={selectedSalaryDetail}
|
||||
onSave={handleSaveDetail}
|
||||
onAddPaymentItem={handleAddPaymentItem}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
100
src/components/hr/SalaryManagement/types.ts
Normal file
100
src/components/hr/SalaryManagement/types.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* 급여관리 타입 정의
|
||||
*/
|
||||
|
||||
// 급여 상태 타입
|
||||
export type PaymentStatus = 'scheduled' | 'completed';
|
||||
|
||||
// 정렬 옵션 타입
|
||||
export type SortOption = 'rank' | 'name' | 'department' | 'paymentDate';
|
||||
|
||||
// 급여 레코드 인터페이스
|
||||
export interface SalaryRecord {
|
||||
id: string;
|
||||
employeeId: string;
|
||||
employeeName: string;
|
||||
department: string;
|
||||
position: string;
|
||||
rank: string;
|
||||
baseSalary: number; // 기본급
|
||||
allowance: number; // 수당
|
||||
overtime: number; // 초과근무
|
||||
bonus: number; // 상여
|
||||
deduction: number; // 공제
|
||||
netPayment: number; // 실지급액
|
||||
paymentDate: string; // 지급일
|
||||
status: PaymentStatus; // 상태
|
||||
year: number; // 년도
|
||||
month: number; // 월
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
// 급여 상세 정보 인터페이스
|
||||
export interface SalaryDetail {
|
||||
// 기본 정보
|
||||
employeeId: string;
|
||||
employeeName: string;
|
||||
department: string;
|
||||
position: string;
|
||||
rank: string;
|
||||
|
||||
// 급여 정보
|
||||
baseSalary: number; // 본봉
|
||||
|
||||
// 수당 내역
|
||||
allowances: {
|
||||
positionAllowance: number; // 직책수당
|
||||
overtimeAllowance: number; // 초과근무수당
|
||||
mealAllowance: number; // 식대
|
||||
transportAllowance: number; // 교통비
|
||||
otherAllowance: number; // 기타수당
|
||||
};
|
||||
|
||||
// 공제 내역
|
||||
deductions: {
|
||||
nationalPension: number; // 국민연금
|
||||
healthInsurance: number; // 건강보험
|
||||
longTermCare: number; // 장기요양보험
|
||||
employmentInsurance: number; // 고용보험
|
||||
incomeTax: number; // 소득세
|
||||
localIncomeTax: number; // 지방소득세
|
||||
otherDeduction: number; // 기타공제
|
||||
};
|
||||
|
||||
// 합계
|
||||
totalAllowance: number; // 수당 합계
|
||||
totalDeduction: number; // 공제 합계
|
||||
netPayment: number; // 실지급액
|
||||
|
||||
// 추가 정보
|
||||
paymentDate: string;
|
||||
status: PaymentStatus;
|
||||
year: number;
|
||||
month: number;
|
||||
}
|
||||
|
||||
// 상태 라벨
|
||||
export const PAYMENT_STATUS_LABELS: Record<PaymentStatus, string> = {
|
||||
scheduled: '지급예정',
|
||||
completed: '지급완료',
|
||||
};
|
||||
|
||||
// 상태 색상
|
||||
export const PAYMENT_STATUS_COLORS: Record<PaymentStatus, string> = {
|
||||
scheduled: 'bg-blue-100 text-blue-800',
|
||||
completed: 'bg-green-100 text-green-800',
|
||||
};
|
||||
|
||||
// 정렬 옵션 라벨
|
||||
export const SORT_OPTIONS: Record<SortOption, string> = {
|
||||
rank: '직급순',
|
||||
name: '이름순',
|
||||
department: '부서순',
|
||||
paymentDate: '지급일순',
|
||||
};
|
||||
|
||||
// 금액 포맷 유틸리티
|
||||
export const formatCurrency = (amount: number): string => {
|
||||
return new Intl.NumberFormat('ko-KR').format(amount);
|
||||
};
|
||||
224
src/components/hr/VacationManagement/VacationAdjustDialog.tsx
Normal file
224
src/components/hr/VacationManagement/VacationAdjustDialog.tsx
Normal file
@@ -0,0 +1,224 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Plus, Minus } from 'lucide-react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import type { VacationUsageRecord, VacationAdjustment, VacationType } from './types';
|
||||
import { VACATION_TYPE_LABELS } from './types';
|
||||
|
||||
interface VacationAdjustDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
record: VacationUsageRecord | null;
|
||||
onSave: (adjustments: VacationAdjustment[]) => void;
|
||||
}
|
||||
|
||||
interface AdjustmentState {
|
||||
annual: number;
|
||||
monthly: number;
|
||||
reward: number;
|
||||
other: number;
|
||||
}
|
||||
|
||||
export function VacationAdjustDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
record,
|
||||
onSave,
|
||||
}: VacationAdjustDialogProps) {
|
||||
const [adjustments, setAdjustments] = useState<AdjustmentState>({
|
||||
annual: 0,
|
||||
monthly: 0,
|
||||
reward: 0,
|
||||
other: 0,
|
||||
});
|
||||
|
||||
// 다이얼로그가 열릴 때 조정값 초기화
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setAdjustments({
|
||||
annual: 0,
|
||||
monthly: 0,
|
||||
reward: 0,
|
||||
other: 0,
|
||||
});
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
// 조정값 증가
|
||||
const handleIncrease = (type: VacationType) => {
|
||||
setAdjustments(prev => ({
|
||||
...prev,
|
||||
[type]: prev[type] + 1,
|
||||
}));
|
||||
};
|
||||
|
||||
// 조정값 감소
|
||||
const handleDecrease = (type: VacationType) => {
|
||||
setAdjustments(prev => ({
|
||||
...prev,
|
||||
[type]: prev[type] - 1,
|
||||
}));
|
||||
};
|
||||
|
||||
// 조정값 직접 입력
|
||||
const handleInputChange = (type: VacationType, value: string) => {
|
||||
const numValue = parseInt(value, 10);
|
||||
if (!isNaN(numValue)) {
|
||||
setAdjustments(prev => ({
|
||||
...prev,
|
||||
[type]: numValue,
|
||||
}));
|
||||
} else if (value === '' || value === '-') {
|
||||
setAdjustments(prev => ({
|
||||
...prev,
|
||||
[type]: 0,
|
||||
}));
|
||||
}
|
||||
};
|
||||
|
||||
// 저장 핸들러
|
||||
const handleSave = () => {
|
||||
const adjustmentList: VacationAdjustment[] = [];
|
||||
|
||||
(Object.keys(adjustments) as VacationType[]).forEach((type) => {
|
||||
if (adjustments[type] !== 0) {
|
||||
adjustmentList.push({
|
||||
vacationType: type,
|
||||
adjustment: adjustments[type],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
onSave(adjustmentList);
|
||||
};
|
||||
|
||||
// 취소 핸들러
|
||||
const handleCancel = () => {
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
if (!record) return null;
|
||||
|
||||
const vacationTypes: VacationType[] = ['annual', 'monthly', 'reward', 'other'];
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[600px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>휴가 조정</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{/* 사원 정보 */}
|
||||
<div className="bg-muted/50 rounded-lg p-4 mb-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{record.department} / {record.employeeName} / {record.rank}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* 조정 테이블 */}
|
||||
<div className="py-2">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-[100px]">휴가종류</TableHead>
|
||||
<TableHead className="text-center">총일수</TableHead>
|
||||
<TableHead className="text-center">사용일수</TableHead>
|
||||
<TableHead className="text-center">잔여일수</TableHead>
|
||||
<TableHead className="text-center w-[150px]">조정</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{vacationTypes.map((type) => {
|
||||
const info = record[type];
|
||||
const adjustment = adjustments[type];
|
||||
const newTotal = info.total + adjustment;
|
||||
const newRemaining = info.remaining + adjustment;
|
||||
|
||||
return (
|
||||
<TableRow key={type}>
|
||||
<TableCell className="font-medium">
|
||||
{VACATION_TYPE_LABELS[type]}
|
||||
</TableCell>
|
||||
<TableCell className="text-center">
|
||||
<span className={adjustment !== 0 ? 'line-through text-muted-foreground mr-2' : ''}>
|
||||
{info.total}
|
||||
</span>
|
||||
{adjustment !== 0 && (
|
||||
<span className={adjustment > 0 ? 'text-green-600' : 'text-red-600'}>
|
||||
{newTotal}
|
||||
</span>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-center">{info.used}</TableCell>
|
||||
<TableCell className="text-center">
|
||||
<span className={adjustment !== 0 ? 'line-through text-muted-foreground mr-2' : ''}>
|
||||
{info.remaining}
|
||||
</span>
|
||||
{adjustment !== 0 && (
|
||||
<span className={adjustment > 0 ? 'text-green-600' : 'text-red-600'}>
|
||||
{newRemaining}
|
||||
</span>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex items-center justify-center gap-1">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={() => handleDecrease(type)}
|
||||
>
|
||||
<Minus className="h-4 w-4" />
|
||||
</Button>
|
||||
<Input
|
||||
type="text"
|
||||
value={adjustment}
|
||||
onChange={(e) => handleInputChange(type, e.target.value)}
|
||||
className="w-16 h-8 text-center"
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={() => handleIncrease(type)}
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={handleCancel}>
|
||||
취소
|
||||
</Button>
|
||||
<Button onClick={handleSave}>
|
||||
저장
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
162
src/components/hr/VacationManagement/VacationGrantDialog.tsx
Normal file
162
src/components/hr/VacationManagement/VacationGrantDialog.tsx
Normal file
@@ -0,0 +1,162 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import type { VacationGrantFormData, VacationType } from './types';
|
||||
import { VACATION_TYPE_LABELS } from './types';
|
||||
|
||||
interface VacationGrantDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onSave: (data: VacationGrantFormData) => void;
|
||||
}
|
||||
|
||||
const mockEmployees = [
|
||||
{ id: '1', name: '김철수', department: '개발팀' },
|
||||
{ id: '2', name: '이영희', department: '디자인팀' },
|
||||
{ id: '3', name: '박민수', department: '기획팀' },
|
||||
{ id: '4', name: '정수진', department: '영업팀' },
|
||||
{ id: '5', name: '최동현', department: '인사팀' },
|
||||
];
|
||||
|
||||
export function VacationGrantDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onSave,
|
||||
}: VacationGrantDialogProps) {
|
||||
const [formData, setFormData] = useState<VacationGrantFormData>({
|
||||
employeeId: '',
|
||||
vacationType: 'annual',
|
||||
grantDays: 1,
|
||||
reason: '',
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setFormData({
|
||||
employeeId: '',
|
||||
vacationType: 'annual',
|
||||
grantDays: 1,
|
||||
reason: '',
|
||||
});
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const handleSave = () => {
|
||||
if (!formData.employeeId) {
|
||||
alert('사원을 선택해주세요.');
|
||||
return;
|
||||
}
|
||||
if (formData.grantDays < 1) {
|
||||
alert('부여 일수는 1 이상이어야 합니다.');
|
||||
return;
|
||||
}
|
||||
onSave(formData);
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>휴가 부여 등록</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="grid gap-4 py-4">
|
||||
{/* 사원 선택 */}
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="employee">사원 선택</Label>
|
||||
<Select
|
||||
value={formData.employeeId}
|
||||
onValueChange={(value) => setFormData(prev => ({ ...prev, employeeId: value }))}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="사원을 선택하세요" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{mockEmployees.map((emp) => (
|
||||
<SelectItem key={emp.id} value={emp.id}>
|
||||
{emp.name} ({emp.department})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* 휴가 유형 */}
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="vacationType">휴가 유형</Label>
|
||||
<Select
|
||||
value={formData.vacationType}
|
||||
onValueChange={(value) => setFormData(prev => ({ ...prev, vacationType: value as VacationType }))}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{Object.entries(VACATION_TYPE_LABELS).map(([key, label]) => (
|
||||
<SelectItem key={key} value={key}>
|
||||
{label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* 부여 일수 */}
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="grantDays">부여 일수</Label>
|
||||
<Input
|
||||
id="grantDays"
|
||||
type="number"
|
||||
min={1}
|
||||
value={formData.grantDays}
|
||||
onChange={(e) => setFormData(prev => ({ ...prev, grantDays: parseInt(e.target.value) || 1 }))}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 사유 */}
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="reason">사유</Label>
|
||||
<Textarea
|
||||
id="reason"
|
||||
placeholder="부여 사유를 입력하세요 (선택)"
|
||||
value={formData.reason || ''}
|
||||
onChange={(e) => setFormData(prev => ({ ...prev, reason: e.target.value }))}
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={handleCancel}>
|
||||
취소
|
||||
</Button>
|
||||
<Button onClick={handleSave}>
|
||||
등록
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
200
src/components/hr/VacationManagement/VacationRegisterDialog.tsx
Normal file
200
src/components/hr/VacationManagement/VacationRegisterDialog.tsx
Normal file
@@ -0,0 +1,200 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import type {
|
||||
VacationFormData,
|
||||
VacationTypeConfig,
|
||||
EmployeeOption,
|
||||
VacationType,
|
||||
} from './types';
|
||||
|
||||
interface VacationRegisterDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
employees: EmployeeOption[];
|
||||
vacationTypes: VacationTypeConfig[];
|
||||
onSave: (data: VacationFormData) => void;
|
||||
}
|
||||
|
||||
export function VacationRegisterDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
employees,
|
||||
vacationTypes,
|
||||
onSave,
|
||||
}: VacationRegisterDialogProps) {
|
||||
const [formData, setFormData] = useState<VacationFormData>({
|
||||
employeeId: '',
|
||||
vacationType: 'annual',
|
||||
days: 0,
|
||||
memo: '',
|
||||
});
|
||||
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
|
||||
// 다이얼로그가 열릴 때 폼 초기화
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setFormData({
|
||||
employeeId: '',
|
||||
vacationType: 'annual',
|
||||
days: 0,
|
||||
memo: '',
|
||||
});
|
||||
setErrors({});
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
// 폼 유효성 검사
|
||||
const validateForm = (): boolean => {
|
||||
const newErrors: Record<string, string> = {};
|
||||
|
||||
if (!formData.employeeId) {
|
||||
newErrors.employeeId = '사원을 선택해주세요';
|
||||
}
|
||||
|
||||
if (!formData.vacationType) {
|
||||
newErrors.vacationType = '휴가 종류를 선택해주세요';
|
||||
}
|
||||
|
||||
if (formData.days <= 0) {
|
||||
newErrors.days = '지급 일수를 입력해주세요';
|
||||
}
|
||||
|
||||
setErrors(newErrors);
|
||||
return Object.keys(newErrors).length === 0;
|
||||
};
|
||||
|
||||
// 저장 핸들러
|
||||
const handleSave = () => {
|
||||
if (validateForm()) {
|
||||
onSave(formData);
|
||||
}
|
||||
};
|
||||
|
||||
// 취소 핸들러
|
||||
const handleCancel = () => {
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[500px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>휴가 등록</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="grid gap-4 py-4">
|
||||
{/* 사원 선택 */}
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="employee">
|
||||
사원 선택 <span className="text-red-500">*</span>
|
||||
</Label>
|
||||
<Select
|
||||
value={formData.employeeId}
|
||||
onValueChange={(value) => setFormData((prev: VacationFormData) => ({ ...prev, employeeId: value }))}
|
||||
>
|
||||
<SelectTrigger id="employee" className={errors.employeeId ? 'border-red-500' : ''}>
|
||||
<SelectValue placeholder="사원을 선택하세요" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{employees.map((employee) => (
|
||||
<SelectItem key={employee.id} value={employee.id}>
|
||||
{employee.department} / {employee.name} / {employee.rank}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{errors.employeeId && (
|
||||
<p className="text-sm text-red-500">{errors.employeeId}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 휴가 종류 */}
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="vacationType">
|
||||
휴가 종류 <span className="text-red-500">*</span>
|
||||
</Label>
|
||||
<Select
|
||||
value={formData.vacationType}
|
||||
onValueChange={(value) => setFormData((prev: VacationFormData) => ({ ...prev, vacationType: value as VacationType }))}
|
||||
>
|
||||
<SelectTrigger id="vacationType" className={errors.vacationType ? 'border-red-500' : ''}>
|
||||
<SelectValue placeholder="휴가 종류를 선택하세요" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{vacationTypes.map((type) => (
|
||||
<SelectItem key={type.id} value={type.type}>
|
||||
{type.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{errors.vacationType && (
|
||||
<p className="text-sm text-red-500">{errors.vacationType}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 지급 일수 */}
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="days">
|
||||
지급 일수 <span className="text-red-500">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="days"
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.5"
|
||||
value={formData.days || ''}
|
||||
onChange={(e) => setFormData((prev: VacationFormData) => ({ ...prev, days: parseFloat(e.target.value) || 0 }))}
|
||||
className={errors.days ? 'border-red-500' : ''}
|
||||
placeholder="일수를 입력하세요"
|
||||
/>
|
||||
{errors.days && (
|
||||
<p className="text-sm text-red-500">{errors.days}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 비고 */}
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="memo">비고</Label>
|
||||
<Textarea
|
||||
id="memo"
|
||||
value={formData.memo || ''}
|
||||
onChange={(e) => setFormData((prev: VacationFormData) => ({ ...prev, memo: e.target.value }))}
|
||||
placeholder="비고를 입력하세요 (선택)"
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={handleCancel}>
|
||||
취소
|
||||
</Button>
|
||||
<Button onClick={handleSave}>
|
||||
등록
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
232
src/components/hr/VacationManagement/VacationRequestDialog.tsx
Normal file
232
src/components/hr/VacationManagement/VacationRequestDialog.tsx
Normal file
@@ -0,0 +1,232 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { format, differenceInDays } from 'date-fns';
|
||||
import { CalendarIcon } from 'lucide-react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Calendar } from '@/components/ui/calendar';
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from '@/components/ui/popover';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { VacationRequestFormData, VacationType } from './types';
|
||||
import { VACATION_TYPE_LABELS } from './types';
|
||||
|
||||
interface VacationRequestDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onSave: (data: VacationRequestFormData) => void;
|
||||
}
|
||||
|
||||
const mockEmployees = [
|
||||
{ id: '1', name: '김철수', department: '개발팀' },
|
||||
{ id: '2', name: '이영희', department: '디자인팀' },
|
||||
{ id: '3', name: '박민수', department: '기획팀' },
|
||||
{ id: '4', name: '정수진', department: '영업팀' },
|
||||
{ id: '5', name: '최동현', department: '인사팀' },
|
||||
];
|
||||
|
||||
export function VacationRequestDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onSave,
|
||||
}: VacationRequestDialogProps) {
|
||||
const [formData, setFormData] = useState<VacationRequestFormData>({
|
||||
employeeId: '',
|
||||
vacationType: 'annual',
|
||||
startDate: '',
|
||||
endDate: '',
|
||||
vacationDays: 1,
|
||||
});
|
||||
const [startDate, setStartDate] = useState<Date | undefined>();
|
||||
const [endDate, setEndDate] = useState<Date | undefined>();
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setFormData({
|
||||
employeeId: '',
|
||||
vacationType: 'annual',
|
||||
startDate: '',
|
||||
endDate: '',
|
||||
vacationDays: 1,
|
||||
});
|
||||
setStartDate(undefined);
|
||||
setEndDate(undefined);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (startDate && endDate) {
|
||||
const days = differenceInDays(endDate, startDate) + 1;
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
startDate: format(startDate, 'yyyy-MM-dd'),
|
||||
endDate: format(endDate, 'yyyy-MM-dd'),
|
||||
vacationDays: days > 0 ? days : 1,
|
||||
}));
|
||||
}
|
||||
}, [startDate, endDate]);
|
||||
|
||||
const handleSave = () => {
|
||||
if (!formData.employeeId) {
|
||||
alert('사원을 선택해주세요.');
|
||||
return;
|
||||
}
|
||||
if (!startDate || !endDate) {
|
||||
alert('휴가 기간을 선택해주세요.');
|
||||
return;
|
||||
}
|
||||
if (endDate < startDate) {
|
||||
alert('종료일은 시작일 이후여야 합니다.');
|
||||
return;
|
||||
}
|
||||
onSave(formData);
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>휴가 신청</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="grid gap-4 py-4">
|
||||
{/* 사원 선택 */}
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="employee">사원 선택</Label>
|
||||
<Select
|
||||
value={formData.employeeId}
|
||||
onValueChange={(value) => setFormData(prev => ({ ...prev, employeeId: value }))}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="사원을 선택하세요" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{mockEmployees.map((emp) => (
|
||||
<SelectItem key={emp.id} value={emp.id}>
|
||||
{emp.name} ({emp.department})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* 휴가 유형 */}
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="vacationType">휴가 유형</Label>
|
||||
<Select
|
||||
value={formData.vacationType}
|
||||
onValueChange={(value) => setFormData(prev => ({ ...prev, vacationType: value as VacationType }))}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{Object.entries(VACATION_TYPE_LABELS).map(([key, label]) => (
|
||||
<SelectItem key={key} value={key}>
|
||||
{label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* 시작일 */}
|
||||
<div className="grid gap-2">
|
||||
<Label>시작일</Label>
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
className={cn(
|
||||
'w-full justify-start text-left font-normal',
|
||||
!startDate && 'text-muted-foreground'
|
||||
)}
|
||||
>
|
||||
<CalendarIcon className="mr-2 h-4 w-4" />
|
||||
{startDate ? format(startDate, 'yyyy-MM-dd') : '시작일 선택'}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-0" align="start">
|
||||
<Calendar
|
||||
mode="single"
|
||||
selected={startDate}
|
||||
onSelect={setStartDate}
|
||||
initialFocus
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
|
||||
{/* 종료일 */}
|
||||
<div className="grid gap-2">
|
||||
<Label>종료일</Label>
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
className={cn(
|
||||
'w-full justify-start text-left font-normal',
|
||||
!endDate && 'text-muted-foreground'
|
||||
)}
|
||||
>
|
||||
<CalendarIcon className="mr-2 h-4 w-4" />
|
||||
{endDate ? format(endDate, 'yyyy-MM-dd') : '종료일 선택'}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-0" align="start">
|
||||
<Calendar
|
||||
mode="single"
|
||||
selected={endDate}
|
||||
onSelect={setEndDate}
|
||||
disabled={(date) => startDate ? date < startDate : false}
|
||||
initialFocus
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
|
||||
{/* 휴가 일수 (자동 계산) */}
|
||||
{startDate && endDate && (
|
||||
<div className="grid gap-2">
|
||||
<Label>휴가 일수</Label>
|
||||
<div className="p-3 bg-muted rounded-md text-center font-medium">
|
||||
{formData.vacationDays}일
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={handleCancel}>
|
||||
취소
|
||||
</Button>
|
||||
<Button onClick={handleSave}>
|
||||
신청
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Plus, Trash2 } from 'lucide-react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import type { VacationTypeConfig, VacationType } from './types';
|
||||
|
||||
interface VacationTypeSettingsDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
vacationTypes: VacationTypeConfig[];
|
||||
onSave: (types: VacationTypeConfig[]) => void;
|
||||
}
|
||||
|
||||
export function VacationTypeSettingsDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
vacationTypes,
|
||||
onSave,
|
||||
}: VacationTypeSettingsDialogProps) {
|
||||
const [localTypes, setLocalTypes] = useState<VacationTypeConfig[]>([]);
|
||||
|
||||
// 다이얼로그가 열릴 때 로컬 상태 초기화
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setLocalTypes([...vacationTypes]);
|
||||
}
|
||||
}, [open, vacationTypes]);
|
||||
|
||||
// 사용여부 토글
|
||||
const handleToggleActive = (id: string) => {
|
||||
setLocalTypes(prev =>
|
||||
prev.map(type =>
|
||||
type.id === id ? { ...type, isActive: !type.isActive } : type
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
// 이름 변경
|
||||
const handleNameChange = (id: string, name: string) => {
|
||||
setLocalTypes(prev =>
|
||||
prev.map(type =>
|
||||
type.id === id ? { ...type, name } : type
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
// 설명 변경
|
||||
const handleDescriptionChange = (id: string, description: string) => {
|
||||
setLocalTypes(prev =>
|
||||
prev.map(type =>
|
||||
type.id === id ? { ...type, description } : type
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
// 휴가종류 추가
|
||||
const handleAddType = () => {
|
||||
const newId = String(Date.now());
|
||||
const newType: VacationTypeConfig = {
|
||||
id: newId,
|
||||
name: '새 휴가종류',
|
||||
type: 'other' as VacationType,
|
||||
isActive: true,
|
||||
description: '',
|
||||
};
|
||||
setLocalTypes(prev => [...prev, newType]);
|
||||
};
|
||||
|
||||
// 휴가종류 삭제
|
||||
const handleDeleteType = (id: string) => {
|
||||
// 기본 4개 타입은 삭제 불가
|
||||
const defaultTypeIds = ['1', '2', '3', '4'];
|
||||
if (defaultTypeIds.includes(id)) {
|
||||
return;
|
||||
}
|
||||
setLocalTypes(prev => prev.filter(type => type.id !== id));
|
||||
};
|
||||
|
||||
// 저장 핸들러
|
||||
const handleSave = () => {
|
||||
onSave(localTypes);
|
||||
};
|
||||
|
||||
// 취소 핸들러
|
||||
const handleCancel = () => {
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
// 기본 타입인지 확인 (삭제 불가)
|
||||
const isDefaultType = (id: string) => {
|
||||
return ['1', '2', '3', '4'].includes(id);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[700px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>휴가 종류 설정</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="py-4">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-[150px]">휴가종류명</TableHead>
|
||||
<TableHead className="w-[100px] text-center">사용여부</TableHead>
|
||||
<TableHead>설명</TableHead>
|
||||
<TableHead className="w-[60px] text-center">삭제</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{localTypes.map((type) => (
|
||||
<TableRow key={type.id}>
|
||||
<TableCell>
|
||||
<Input
|
||||
value={type.name}
|
||||
onChange={(e) => handleNameChange(type.id, e.target.value)}
|
||||
className="h-8"
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="text-center">
|
||||
<div className="flex justify-center">
|
||||
<Switch
|
||||
checked={type.isActive}
|
||||
onCheckedChange={() => handleToggleActive(type.id)}
|
||||
/>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Input
|
||||
value={type.description || ''}
|
||||
onChange={(e) => handleDescriptionChange(type.id, e.target.value)}
|
||||
placeholder="설명을 입력하세요"
|
||||
className="h-8"
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="text-center">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleDeleteType(type.id)}
|
||||
disabled={isDefaultType(type.id)}
|
||||
className={isDefaultType(type.id) ? 'opacity-30 cursor-not-allowed' : 'text-red-500 hover:text-red-700'}
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
|
||||
{/* 휴가종류 추가 버튼 */}
|
||||
<div className="mt-4">
|
||||
<Button variant="outline" onClick={handleAddType} className="w-full">
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
휴가종류 추가
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={handleCancel}>
|
||||
취소
|
||||
</Button>
|
||||
<Button onClick={handleSave}>
|
||||
저장
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
571
src/components/hr/VacationManagement/index.tsx
Normal file
571
src/components/hr/VacationManagement/index.tsx
Normal file
@@ -0,0 +1,571 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useMemo, useCallback } from 'react';
|
||||
import { format } from 'date-fns';
|
||||
import {
|
||||
Download,
|
||||
Plus,
|
||||
Calendar,
|
||||
Check,
|
||||
X,
|
||||
} from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { TableRow, TableCell } from '@/components/ui/table';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import {
|
||||
IntegratedListTemplateV2,
|
||||
type TableColumn,
|
||||
type StatCard,
|
||||
type TabOption,
|
||||
} from '@/components/templates/IntegratedListTemplateV2';
|
||||
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
|
||||
import { VacationGrantDialog } from './VacationGrantDialog';
|
||||
import { VacationRequestDialog } from './VacationRequestDialog';
|
||||
import type {
|
||||
MainTabType,
|
||||
VacationUsageRecord,
|
||||
VacationGrantRecord,
|
||||
VacationRequestRecord,
|
||||
SortOption,
|
||||
VacationType,
|
||||
RequestStatus,
|
||||
} from './types';
|
||||
import {
|
||||
MAIN_TAB_LABELS,
|
||||
SORT_OPTIONS,
|
||||
VACATION_TYPE_LABELS,
|
||||
REQUEST_STATUS_LABELS,
|
||||
REQUEST_STATUS_COLORS,
|
||||
} from './types';
|
||||
|
||||
// ===== Mock 데이터 생성 =====
|
||||
const generateUsageData = (): VacationUsageRecord[] => {
|
||||
const departments = ['개발팀', '디자인팀', '기획팀', '영업팀', '인사팀'];
|
||||
const positions = ['팀장', '파트장', '선임', '주임', '사원'];
|
||||
const ranks = ['부장', '차장', '과장', '대리', '사원'];
|
||||
|
||||
// 휴가 일수 포맷: "15일", "12일3시간" 등
|
||||
const usedVacations = ['12일3시간', '8일', '5일4시간', '10일', '3일2시간', '7일5시간', '9일', '6일1시간', '4일', '11일6시간'];
|
||||
const remainingVacations = ['2일5시간', '7일', '9일4시간', '5일', '11일6시간', '7일3시간', '6일', '8일7시간', '11일', '3일2시간'];
|
||||
const grantedVacations = ['0일', '3일', '2일', '1일', '4일', '0일', '2일', '3일', '1일', '0일'];
|
||||
|
||||
return Array.from({ length: 10 }, (_, i) => ({
|
||||
id: `usage-${i + 1}`,
|
||||
employeeId: `EMP${String(i + 1).padStart(3, '0')}`,
|
||||
employeeName: ['김철수', '이영희', '박민수', '정수진', '최동현', '강미영', '윤상호', '임지현', '한승우', '송예진'][i],
|
||||
department: departments[i % departments.length],
|
||||
position: positions[i % positions.length],
|
||||
rank: ranks[i % ranks.length],
|
||||
hireDate: format(new Date(2020 + (i % 5), i % 12, (i % 28) + 1), 'yyyy-MM-dd'),
|
||||
baseVacation: '15일',
|
||||
grantedVacation: grantedVacations[i],
|
||||
usedVacation: usedVacations[i],
|
||||
remainingVacation: remainingVacations[i],
|
||||
// 휴가 유형별 상세 (조정 다이얼로그용)
|
||||
annual: { total: 15, used: 10 + (i % 5), remaining: 5 - (i % 5) },
|
||||
monthly: { total: 3, used: i % 3, remaining: 3 - (i % 3) },
|
||||
reward: { total: i % 4, used: 0, remaining: i % 4 },
|
||||
other: { total: 0, used: 0, remaining: 0 },
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}));
|
||||
};
|
||||
|
||||
const generateGrantData = (): VacationGrantRecord[] => {
|
||||
const departments = ['개발팀', '디자인팀', '기획팀', '영업팀', '인사팀'];
|
||||
const positions = ['팀장', '파트장', '선임', '주임', '사원'];
|
||||
const ranks = ['부장', '차장', '과장', '대리', '사원'];
|
||||
const vacationTypes: VacationType[] = ['annual', 'monthly', 'reward', 'other'];
|
||||
const reasons = ['연차 부여', '포상 휴가', '특별 휴가', '경조사 휴가', ''];
|
||||
|
||||
return Array.from({ length: 8 }, (_, i) => ({
|
||||
id: `grant-${i + 1}`,
|
||||
employeeId: `EMP${String(i + 1).padStart(3, '0')}`,
|
||||
employeeName: ['김철수', '이영희', '박민수', '정수진', '최동현', '강미영', '윤상호', '임지현'][i],
|
||||
department: departments[i % departments.length],
|
||||
position: positions[i % positions.length],
|
||||
rank: ranks[i % ranks.length],
|
||||
vacationType: vacationTypes[i % vacationTypes.length],
|
||||
grantDate: format(new Date(2025, 11, (i % 28) + 1), 'yyyy-MM-dd'),
|
||||
grantDays: Math.floor(Math.random() * 5) + 1,
|
||||
reason: reasons[i % reasons.length],
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}));
|
||||
};
|
||||
|
||||
const generateRequestData = (): VacationRequestRecord[] => {
|
||||
const departments = ['개발팀', '디자인팀', '기획팀', '영업팀', '인사팀'];
|
||||
const positions = ['팀장', '파트장', '선임', '주임', '사원'];
|
||||
const ranks = ['부장', '차장', '과장', '대리', '사원'];
|
||||
const statuses: RequestStatus[] = ['pending', 'approved', 'rejected'];
|
||||
|
||||
return Array.from({ length: 7 }, (_, i) => {
|
||||
const startDate = new Date(2025, 11, (i % 28) + 1);
|
||||
const endDate = new Date(startDate);
|
||||
endDate.setDate(endDate.getDate() + Math.floor(Math.random() * 5) + 1);
|
||||
|
||||
return {
|
||||
id: `request-${i + 1}`,
|
||||
employeeId: `EMP${String(i + 1).padStart(3, '0')}`,
|
||||
employeeName: ['김철수', '이영희', '박민수', '정수진', '최동현', '강미영', '윤상호'][i],
|
||||
department: departments[i % departments.length],
|
||||
position: positions[i % positions.length],
|
||||
rank: ranks[i % ranks.length],
|
||||
startDate: format(startDate, 'yyyy-MM-dd'),
|
||||
endDate: format(endDate, 'yyyy-MM-dd'),
|
||||
vacationDays: Math.floor(Math.random() * 5) + 1,
|
||||
status: statuses[i % statuses.length],
|
||||
requestDate: format(new Date(2025, 11, i + 1), 'yyyy-MM-dd'),
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
export function VacationManagement() {
|
||||
// ===== 상태 관리 =====
|
||||
const [mainTab, setMainTab] = useState<MainTabType>('usage');
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [sortOption, setSortOption] = useState<SortOption>('rank');
|
||||
const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const itemsPerPage = 20;
|
||||
|
||||
// 날짜 범위 상태 (input type="date" 용)
|
||||
const [startDate, setStartDate] = useState('2025-12-01');
|
||||
const [endDate, setEndDate] = useState('2025-12-31');
|
||||
|
||||
// 다이얼로그 상태
|
||||
const [grantDialogOpen, setGrantDialogOpen] = useState(false);
|
||||
const [requestDialogOpen, setRequestDialogOpen] = useState(false);
|
||||
|
||||
// Mock 데이터
|
||||
const [usageData] = useState<VacationUsageRecord[]>(generateUsageData);
|
||||
const [grantData] = useState<VacationGrantRecord[]>(generateGrantData);
|
||||
const [requestData] = useState<VacationRequestRecord[]>(generateRequestData);
|
||||
|
||||
// ===== 탭 변경 핸들러 =====
|
||||
const handleMainTabChange = useCallback((value: string) => {
|
||||
setMainTab(value as MainTabType);
|
||||
setSelectedItems(new Set());
|
||||
setSearchQuery('');
|
||||
setCurrentPage(1);
|
||||
}, []);
|
||||
|
||||
// ===== 체크박스 핸들러 =====
|
||||
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(() => {
|
||||
const currentData = mainTab === 'usage' ? filteredUsageData : mainTab === 'grant' ? filteredGrantData : filteredRequestData;
|
||||
if (selectedItems.size === currentData.length && currentData.length > 0) {
|
||||
setSelectedItems(new Set());
|
||||
} else {
|
||||
setSelectedItems(new Set(currentData.map(item => item.id)));
|
||||
}
|
||||
}, [mainTab, selectedItems.size]);
|
||||
|
||||
// ===== 필터링된 데이터 =====
|
||||
const filteredUsageData = useMemo(() => {
|
||||
return usageData.filter(item =>
|
||||
item.employeeName.includes(searchQuery) ||
|
||||
item.department.includes(searchQuery)
|
||||
);
|
||||
}, [usageData, searchQuery]);
|
||||
|
||||
const filteredGrantData = useMemo(() => {
|
||||
return grantData.filter(item =>
|
||||
item.employeeName.includes(searchQuery) ||
|
||||
item.department.includes(searchQuery)
|
||||
);
|
||||
}, [grantData, searchQuery]);
|
||||
|
||||
const filteredRequestData = useMemo(() => {
|
||||
return requestData.filter(item =>
|
||||
item.employeeName.includes(searchQuery) ||
|
||||
item.department.includes(searchQuery)
|
||||
);
|
||||
}, [requestData, searchQuery]);
|
||||
|
||||
// ===== 현재 탭 데이터 =====
|
||||
const currentData = useMemo(() => {
|
||||
switch (mainTab) {
|
||||
case 'usage': return filteredUsageData;
|
||||
case 'grant': return filteredGrantData;
|
||||
case 'request': return filteredRequestData;
|
||||
default: return [];
|
||||
}
|
||||
}, [mainTab, filteredUsageData, filteredGrantData, filteredRequestData]);
|
||||
|
||||
const paginatedData = useMemo(() => {
|
||||
const startIndex = (currentPage - 1) * itemsPerPage;
|
||||
return currentData.slice(startIndex, startIndex + itemsPerPage);
|
||||
}, [currentData, currentPage, itemsPerPage]);
|
||||
|
||||
const totalPages = Math.ceil(currentData.length / itemsPerPage);
|
||||
|
||||
// ===== 승인/거절 핸들러 =====
|
||||
const handleApprove = useCallback(() => {
|
||||
console.log('승인:', Array.from(selectedItems));
|
||||
setSelectedItems(new Set());
|
||||
}, [selectedItems]);
|
||||
|
||||
const handleReject = useCallback(() => {
|
||||
console.log('거절:', Array.from(selectedItems));
|
||||
setSelectedItems(new Set());
|
||||
}, [selectedItems]);
|
||||
|
||||
// ===== 통계 카드 (스크린샷: 연차 N명, 월차 N명, 포상휴가 N명, 기타휴가 N명) =====
|
||||
const statCards: StatCard[] = useMemo(() => [
|
||||
{ label: '연차', value: `${usageData.length}명`, icon: Calendar, iconColor: 'text-blue-500' },
|
||||
{ label: '월차', value: `${usageData.filter(u => u.grantedVacation !== '0일').length}명`, icon: Calendar, iconColor: 'text-green-500' },
|
||||
{ label: '포상휴가', value: `${grantData.filter(g => g.vacationType === 'reward').length}명`, icon: Calendar, iconColor: 'text-purple-500' },
|
||||
{ label: '기타휴가', value: `${grantData.filter(g => g.vacationType === 'other').length}명`, icon: Calendar, iconColor: 'text-orange-500' },
|
||||
], [usageData, grantData]);
|
||||
|
||||
// ===== 탭 옵션 (카드 아래에 표시됨) =====
|
||||
const tabs: TabOption[] = useMemo(() => [
|
||||
{ value: 'usage', label: MAIN_TAB_LABELS.usage, count: usageData.length, color: 'blue' },
|
||||
{ value: 'grant', label: MAIN_TAB_LABELS.grant, count: grantData.length, color: 'green' },
|
||||
{ value: 'request', label: MAIN_TAB_LABELS.request, count: requestData.length, color: 'purple' },
|
||||
], [usageData.length, grantData.length, requestData.length]);
|
||||
|
||||
// ===== 테이블 컬럼 (탭별) =====
|
||||
const tableColumns: TableColumn[] = useMemo(() => {
|
||||
if (mainTab === 'usage') {
|
||||
// 휴가 사용현황: 부서|직책|이름|직급|입사일|기본|부여|사용|잔액
|
||||
return [
|
||||
{ key: 'department', label: '부서' },
|
||||
{ key: 'position', label: '직책' },
|
||||
{ key: 'name', label: '이름' },
|
||||
{ key: 'rank', label: '직급' },
|
||||
{ key: 'hireDate', label: '입사일' },
|
||||
{ key: 'base', label: '기본', className: 'text-center' },
|
||||
{ key: 'granted', label: '부여', className: 'text-center' },
|
||||
{ key: 'used', label: '사용', className: 'text-center' },
|
||||
{ key: 'remaining', label: '잔여', className: 'text-center' },
|
||||
];
|
||||
} else if (mainTab === 'grant') {
|
||||
// 휴가 부여현황: 부서|직책|이름|직급|유형|부여일|부여휴가일수|사유
|
||||
return [
|
||||
{ key: 'department', label: '부서' },
|
||||
{ key: 'position', label: '직책' },
|
||||
{ key: 'name', label: '이름' },
|
||||
{ key: 'rank', label: '직급' },
|
||||
{ key: 'type', label: '유형' },
|
||||
{ key: 'grantDate', label: '부여일' },
|
||||
{ key: 'grantDays', label: '부여휴가일수', className: 'text-center' },
|
||||
{ key: 'reason', label: '사유' },
|
||||
];
|
||||
} else {
|
||||
// 휴가 신청현황: 부서|직책|이름|직급|휴가기간|휴가일수|상태|신청일
|
||||
return [
|
||||
{ key: 'department', label: '부서' },
|
||||
{ key: 'position', label: '직책' },
|
||||
{ key: 'name', label: '이름' },
|
||||
{ key: 'rank', label: '직급' },
|
||||
{ key: 'period', label: '휴가기간' },
|
||||
{ key: 'days', label: '휴가일수', className: 'text-center' },
|
||||
{ key: 'status', label: '상태', className: 'text-center' },
|
||||
{ key: 'requestDate', label: '신청일' },
|
||||
];
|
||||
}
|
||||
}, [mainTab]);
|
||||
|
||||
// ===== 테이블 행 렌더링 =====
|
||||
const renderTableRow = useCallback((item: any, index: number, globalIndex: number) => {
|
||||
const isSelected = selectedItems.has(item.id);
|
||||
|
||||
if (mainTab === 'usage') {
|
||||
const record = item as VacationUsageRecord;
|
||||
return (
|
||||
<TableRow key={record.id} className="hover:bg-muted/50">
|
||||
<TableCell className="text-center">
|
||||
<Checkbox checked={isSelected} onCheckedChange={() => toggleSelection(record.id)} />
|
||||
</TableCell>
|
||||
<TableCell>{record.department}</TableCell>
|
||||
<TableCell>{record.position}</TableCell>
|
||||
<TableCell className="font-medium">{record.employeeName}</TableCell>
|
||||
<TableCell>{record.rank}</TableCell>
|
||||
<TableCell>{format(new Date(record.hireDate), 'yyyy-MM-dd')}</TableCell>
|
||||
<TableCell className="text-center">{record.baseVacation}</TableCell>
|
||||
<TableCell className="text-center">{record.grantedVacation}</TableCell>
|
||||
<TableCell className="text-center">{record.usedVacation}</TableCell>
|
||||
<TableCell className="text-center font-medium">{record.remainingVacation}</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
} else if (mainTab === 'grant') {
|
||||
const record = item as VacationGrantRecord;
|
||||
return (
|
||||
<TableRow key={record.id} className="hover:bg-muted/50">
|
||||
<TableCell className="text-center">
|
||||
<Checkbox checked={isSelected} onCheckedChange={() => toggleSelection(record.id)} />
|
||||
</TableCell>
|
||||
<TableCell>{record.department}</TableCell>
|
||||
<TableCell>{record.position}</TableCell>
|
||||
<TableCell className="font-medium">{record.employeeName}</TableCell>
|
||||
<TableCell>{record.rank}</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant="outline">{VACATION_TYPE_LABELS[record.vacationType]}</Badge>
|
||||
</TableCell>
|
||||
<TableCell>{format(new Date(record.grantDate), 'yyyy-MM-dd')}</TableCell>
|
||||
<TableCell className="text-center">{record.grantDays}일</TableCell>
|
||||
<TableCell className="text-muted-foreground">{record.reason || '-'}</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
} else {
|
||||
const record = item as VacationRequestRecord;
|
||||
return (
|
||||
<TableRow key={record.id} className="hover:bg-muted/50">
|
||||
<TableCell className="text-center">
|
||||
<Checkbox checked={isSelected} onCheckedChange={() => toggleSelection(record.id)} />
|
||||
</TableCell>
|
||||
<TableCell>{record.department}</TableCell>
|
||||
<TableCell>{record.position}</TableCell>
|
||||
<TableCell className="font-medium">{record.employeeName}</TableCell>
|
||||
<TableCell>{record.rank}</TableCell>
|
||||
<TableCell>
|
||||
{format(new Date(record.startDate), 'yyyy-MM-dd')} ~ {format(new Date(record.endDate), 'yyyy-MM-dd')}
|
||||
</TableCell>
|
||||
<TableCell className="text-center">{record.vacationDays}일</TableCell>
|
||||
<TableCell className="text-center">
|
||||
<Badge className={REQUEST_STATUS_COLORS[record.status]}>
|
||||
{REQUEST_STATUS_LABELS[record.status]}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell>{format(new Date(record.requestDate), 'yyyy-MM-dd')}</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
}
|
||||
}, [mainTab, selectedItems, toggleSelection]);
|
||||
|
||||
// ===== 모바일 카드 렌더링 =====
|
||||
const renderMobileCard = useCallback((
|
||||
item: any,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
isSelected: boolean,
|
||||
onToggle: () => void
|
||||
) => {
|
||||
if (mainTab === 'usage') {
|
||||
const record = item as VacationUsageRecord;
|
||||
return (
|
||||
<ListMobileCard
|
||||
id={record.id}
|
||||
title={record.employeeName}
|
||||
headerBadges={<Badge variant="outline">{record.department}</Badge>}
|
||||
isSelected={isSelected}
|
||||
onToggleSelection={onToggle}
|
||||
infoGrid={
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<InfoField label="직급" value={record.rank} />
|
||||
<InfoField label="입사일" value={record.hireDate} />
|
||||
<InfoField label="기본" value={record.baseVacation} />
|
||||
<InfoField label="부여" value={record.grantedVacation} />
|
||||
<InfoField label="사용" value={record.usedVacation} />
|
||||
<InfoField label="잔여" value={record.remainingVacation} />
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
);
|
||||
} else if (mainTab === 'grant') {
|
||||
const record = item as VacationGrantRecord;
|
||||
return (
|
||||
<ListMobileCard
|
||||
id={record.id}
|
||||
title={record.employeeName}
|
||||
headerBadges={<Badge variant="outline">{VACATION_TYPE_LABELS[record.vacationType]}</Badge>}
|
||||
isSelected={isSelected}
|
||||
onToggleSelection={onToggle}
|
||||
infoGrid={
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<InfoField label="부서" value={record.department} />
|
||||
<InfoField label="직급" value={record.rank} />
|
||||
<InfoField label="부여일" value={record.grantDate} />
|
||||
<InfoField label="일수" value={`${record.grantDays}일`} />
|
||||
{record.reason && <InfoField label="사유" value={record.reason} />}
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
);
|
||||
} else {
|
||||
const record = item as VacationRequestRecord;
|
||||
return (
|
||||
<ListMobileCard
|
||||
id={record.id}
|
||||
title={record.employeeName}
|
||||
headerBadges={
|
||||
<Badge className={REQUEST_STATUS_COLORS[record.status]}>
|
||||
{REQUEST_STATUS_LABELS[record.status]}
|
||||
</Badge>
|
||||
}
|
||||
isSelected={isSelected}
|
||||
onToggleSelection={onToggle}
|
||||
infoGrid={
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<InfoField label="부서" value={record.department} />
|
||||
<InfoField label="직급" value={record.rank} />
|
||||
<InfoField label="기간" value={`${record.startDate} ~ ${record.endDate}`} />
|
||||
<InfoField label="일수" value={`${record.vacationDays}일`} />
|
||||
<InfoField label="신청일" value={record.requestDate} />
|
||||
</div>
|
||||
}
|
||||
actions={
|
||||
record.status === 'pending' && (
|
||||
<div className="flex gap-2">
|
||||
<Button variant="default" className="flex-1" onClick={handleApprove}>
|
||||
<Check className="w-4 h-4 mr-2" /> 승인
|
||||
</Button>
|
||||
<Button variant="outline" className="flex-1" onClick={handleReject}>
|
||||
<X className="w-4 h-4 mr-2" /> 거절
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}, [mainTab, handleApprove, handleReject]);
|
||||
|
||||
// ===== 헤더 액션 (달력 + 버튼들) =====
|
||||
const headerActions = (
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
{/* 날짜 범위 선택 - 브라우저 기본 달력 사용 */}
|
||||
<div className="flex items-center gap-1">
|
||||
<Input
|
||||
type="date"
|
||||
value={startDate}
|
||||
onChange={(e) => setStartDate(e.target.value)}
|
||||
className="w-[140px]"
|
||||
/>
|
||||
<span className="text-muted-foreground">~</span>
|
||||
<Input
|
||||
type="date"
|
||||
value={endDate}
|
||||
onChange={(e) => setEndDate(e.target.value)}
|
||||
className="w-[140px]"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 탭별 액션 버튼 */}
|
||||
{mainTab === 'grant' && (
|
||||
<Button onClick={() => setGrantDialogOpen(true)}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
부여등록
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{mainTab === 'request' && (
|
||||
<>
|
||||
<Button onClick={() => setRequestDialogOpen(true)}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
휴가신청
|
||||
</Button>
|
||||
{selectedItems.size > 0 && (
|
||||
<>
|
||||
<Button variant="default" onClick={handleApprove}>
|
||||
<Check className="h-4 w-4 mr-2" />
|
||||
승인
|
||||
</Button>
|
||||
<Button variant="destructive" onClick={handleReject}>
|
||||
<X className="h-4 w-4 mr-2" />
|
||||
거절
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
<Button variant="outline" onClick={() => console.log('엑셀 다운로드')}>
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
엑셀 다운로드
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
|
||||
// ===== 정렬 필터 =====
|
||||
const extraFilters = (
|
||||
<Select value={sortOption} onValueChange={(v) => setSortOption(v as SortOption)}>
|
||||
<SelectTrigger className="w-[120px]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{Object.entries(SORT_OPTIONS).map(([key, label]) => (
|
||||
<SelectItem key={key} value={key}>{label}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* IntegratedListTemplateV2 - 카드 아래에 탭 표시됨 */}
|
||||
<IntegratedListTemplateV2
|
||||
title="휴가관리"
|
||||
description="직원들의 휴가 현황을 관리합니다"
|
||||
icon={Calendar}
|
||||
headerActions={headerActions}
|
||||
stats={statCards}
|
||||
searchValue={searchQuery}
|
||||
onSearchChange={setSearchQuery}
|
||||
searchPlaceholder="이름, 부서 검색..."
|
||||
extraFilters={extraFilters}
|
||||
tabs={tabs}
|
||||
activeTab={mainTab}
|
||||
onTabChange={handleMainTabChange}
|
||||
tableColumns={tableColumns}
|
||||
data={paginatedData}
|
||||
totalCount={currentData.length}
|
||||
allData={currentData}
|
||||
selectedItems={selectedItems}
|
||||
onToggleSelection={toggleSelection}
|
||||
onToggleSelectAll={toggleSelectAll}
|
||||
getItemId={(item: any) => item.id}
|
||||
renderTableRow={renderTableRow}
|
||||
renderMobileCard={renderMobileCard}
|
||||
pagination={{
|
||||
currentPage,
|
||||
totalPages,
|
||||
totalItems: currentData.length,
|
||||
itemsPerPage,
|
||||
onPageChange: setCurrentPage,
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* 다이얼로그 */}
|
||||
<VacationGrantDialog
|
||||
open={grantDialogOpen}
|
||||
onOpenChange={setGrantDialogOpen}
|
||||
onSave={(data) => {
|
||||
console.log('부여 등록:', data);
|
||||
setGrantDialogOpen(false);
|
||||
}}
|
||||
/>
|
||||
|
||||
<VacationRequestDialog
|
||||
open={requestDialogOpen}
|
||||
onOpenChange={setRequestDialogOpen}
|
||||
onSave={(data) => {
|
||||
console.log('휴가 신청:', data);
|
||||
setRequestDialogOpen(false);
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
175
src/components/hr/VacationManagement/types.ts
Normal file
175
src/components/hr/VacationManagement/types.ts
Normal file
@@ -0,0 +1,175 @@
|
||||
/**
|
||||
* 휴가관리 타입 정의
|
||||
* 3개 메인 탭: 휴가 사용현황, 휴가 부여현황, 휴가 신청현황
|
||||
*/
|
||||
|
||||
// ===== 메인 탭 타입 =====
|
||||
export type MainTabType = 'usage' | 'grant' | 'request';
|
||||
|
||||
// 휴가 유형
|
||||
export type VacationType = 'annual' | 'monthly' | 'reward' | 'other';
|
||||
|
||||
// 정렬 옵션
|
||||
export type SortOption = 'rank' | 'deptAsc' | 'deptDesc' | 'nameAsc' | 'nameDesc';
|
||||
|
||||
// 휴가 신청 상태
|
||||
export type RequestStatus = 'pending' | 'approved' | 'rejected';
|
||||
|
||||
// ===== 탭 1: 휴가 사용현황 =====
|
||||
// 휴가 유형별 상세 정보
|
||||
export interface VacationTypeDetail {
|
||||
total: number;
|
||||
used: number;
|
||||
remaining: number;
|
||||
}
|
||||
|
||||
// 테이블 컬럼: 부서 | 직책 | 이름 | 직급 | 입사일 | 기본 | 부여 | 사용 | 잔여
|
||||
export interface VacationUsageRecord {
|
||||
id: string;
|
||||
employeeId: string;
|
||||
employeeName: string;
|
||||
department: string;
|
||||
position: string; // 직책
|
||||
rank: string; // 직급
|
||||
hireDate: string; // 입사일
|
||||
baseVacation: string; // 기본 (예: "15일")
|
||||
grantedVacation: string; // 부여 (예: "3일")
|
||||
usedVacation: string; // 사용 (예: "12일3시간")
|
||||
remainingVacation: string; // 잔여 (예: "2일5시간")
|
||||
// 휴가 유형별 상세 (조정 다이얼로그용)
|
||||
annual: VacationTypeDetail;
|
||||
monthly: VacationTypeDetail;
|
||||
reward: VacationTypeDetail;
|
||||
other: VacationTypeDetail;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
// ===== 탭 2: 휴가 부여현황 =====
|
||||
// 테이블 컬럼: 부서 | 직책 | 이름 | 직급 | 유형 | 부여일 | 부여휴가일수 | 사유
|
||||
export interface VacationGrantRecord {
|
||||
id: string;
|
||||
employeeId: string;
|
||||
employeeName: string;
|
||||
department: string;
|
||||
position: string; // 직책
|
||||
rank: string; // 직급
|
||||
vacationType: VacationType; // 유형
|
||||
grantDate: string; // 부여일
|
||||
grantDays: number; // 부여휴가일수
|
||||
reason?: string; // 사유
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
// ===== 탭 3: 휴가 신청현황 =====
|
||||
// 테이블 컬럼: 부서 | 직책 | 이름 | 직급 | 휴가기간 | 휴가일수 | 상태 | 신청일
|
||||
export interface VacationRequestRecord {
|
||||
id: string;
|
||||
employeeId: string;
|
||||
employeeName: string;
|
||||
department: string;
|
||||
position: string; // 직책
|
||||
rank: string; // 직급
|
||||
startDate: string; // 휴가기간 시작
|
||||
endDate: string; // 휴가기간 종료
|
||||
vacationDays: number; // 휴가일수
|
||||
status: RequestStatus; // 상태
|
||||
requestDate: string; // 신청일
|
||||
vacationType?: VacationType;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
// ===== 폼 데이터 =====
|
||||
export interface VacationFormData {
|
||||
employeeId: string;
|
||||
vacationType: VacationType;
|
||||
days: number;
|
||||
memo?: string;
|
||||
}
|
||||
|
||||
export interface VacationGrantFormData {
|
||||
employeeId: string;
|
||||
vacationType: VacationType;
|
||||
grantDays: number;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
export interface VacationRequestFormData {
|
||||
employeeId: string;
|
||||
vacationType: VacationType;
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
vacationDays: number;
|
||||
}
|
||||
|
||||
export interface VacationAdjustment {
|
||||
vacationType: VacationType;
|
||||
adjustment: number;
|
||||
}
|
||||
|
||||
export interface VacationTypeConfig {
|
||||
id: string;
|
||||
name: string;
|
||||
type: VacationType;
|
||||
isActive: boolean;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export interface EmployeeOption {
|
||||
id: string;
|
||||
name: string;
|
||||
department: string;
|
||||
position: string;
|
||||
rank: string;
|
||||
}
|
||||
|
||||
// ===== 상수 정의 =====
|
||||
|
||||
export const MAIN_TAB_LABELS: Record<MainTabType, string> = {
|
||||
usage: '휴가 사용현황',
|
||||
grant: '휴가 부여현황',
|
||||
request: '휴가 신청현황',
|
||||
};
|
||||
|
||||
export const VACATION_TYPE_LABELS: Record<VacationType, string> = {
|
||||
annual: '연차',
|
||||
monthly: '월차',
|
||||
reward: '포상휴가',
|
||||
other: '기타',
|
||||
};
|
||||
|
||||
export const VACATION_TYPE_COLORS: Record<VacationType, string> = {
|
||||
annual: 'blue',
|
||||
monthly: 'green',
|
||||
reward: 'purple',
|
||||
other: 'orange',
|
||||
};
|
||||
|
||||
export const REQUEST_STATUS_LABELS: Record<RequestStatus, string> = {
|
||||
pending: '대기',
|
||||
approved: '승인',
|
||||
rejected: '반려',
|
||||
};
|
||||
|
||||
export const REQUEST_STATUS_COLORS: Record<RequestStatus, string> = {
|
||||
pending: 'bg-yellow-100 text-yellow-800',
|
||||
approved: 'bg-green-100 text-green-800',
|
||||
rejected: 'bg-red-100 text-red-800',
|
||||
};
|
||||
|
||||
export const SORT_OPTIONS: Record<SortOption, string> = {
|
||||
rank: '직급순',
|
||||
deptAsc: '부서명 오름차순',
|
||||
deptDesc: '부서명 내림차순',
|
||||
nameAsc: '이름 오름차순',
|
||||
nameDesc: '이름 내림차순',
|
||||
};
|
||||
|
||||
export const DEFAULT_VACATION_TYPES: VacationTypeConfig[] = [
|
||||
{ id: '1', name: '연차', type: 'annual', isActive: true, description: '연간 유급 휴가' },
|
||||
{ id: '2', name: '월차', type: 'monthly', isActive: true, description: '월간 유급 휴가' },
|
||||
{ id: '3', name: '포상휴가', type: 'reward', isActive: true, description: '성과에 따른 포상 휴가' },
|
||||
{ id: '4', name: '기타', type: 'other', isActive: true, description: '기타 휴가' },
|
||||
];
|
||||
@@ -136,9 +136,12 @@ export function DrawingCanvas({
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas) return { x: 0, y: 0 };
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
// 실제 캔버스 크기와 표시 크기의 비율 계산
|
||||
const scaleX = canvas.width / rect.width;
|
||||
const scaleY = canvas.height / rect.height;
|
||||
return {
|
||||
x: e.clientX - rect.left,
|
||||
y: e.clientY - rect.top,
|
||||
x: (e.clientX - rect.left) * scaleX,
|
||||
y: (e.clientY - rect.top) * scaleY,
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -80,22 +80,6 @@ export function DropdownField({
|
||||
// 옵션이 없으면 드롭다운을 disabled로 표시
|
||||
const hasOptions = options.length > 0;
|
||||
|
||||
// 디버깅: 단위 필드 값 추적
|
||||
if (isUnitField) {
|
||||
console.log('[DropdownField] 단위 필드 디버깅:', {
|
||||
fieldKey,
|
||||
fieldName: field.field_name,
|
||||
rawValue: value,
|
||||
stringValue,
|
||||
isUnitField,
|
||||
unitOptionsCount: unitOptions?.length || 0,
|
||||
unitOptions: unitOptions?.slice(0, 3), // 처음 3개만
|
||||
optionsCount: options.length,
|
||||
options: options.slice(0, 3), // 처음 3개만
|
||||
valueInOptions: options.some(o => o.value === stringValue),
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Label htmlFor={fieldKey}>
|
||||
|
||||
@@ -72,17 +72,6 @@ export function useConditionalDisplay(
|
||||
}
|
||||
});
|
||||
|
||||
// 디버깅: 조건부 표시 설정 확인
|
||||
console.log('[useConditionalDisplay] 트리거 필드 목록:', triggers.map(t => ({
|
||||
fieldKey: t.fieldKey,
|
||||
fieldId: t.fieldId,
|
||||
fieldConditions: t.condition.fieldConditions?.map(fc => ({
|
||||
expectedValue: fc.expectedValue,
|
||||
targetFieldIds: fc.targetFieldIds,
|
||||
targetSectionIds: fc.targetSectionIds,
|
||||
})),
|
||||
})));
|
||||
|
||||
return triggers;
|
||||
}, [structure]);
|
||||
|
||||
@@ -102,15 +91,6 @@ export function useConditionalDisplay(
|
||||
// 현재 값과 기대값이 일치하는지 확인
|
||||
const isMatch = String(currentValue) === fc.expectedValue;
|
||||
|
||||
// 디버깅: 조건 매칭 확인
|
||||
console.log('[useConditionalDisplay] 조건 매칭 체크:', {
|
||||
triggerFieldKey: trigger.fieldKey,
|
||||
currentValue: String(currentValue),
|
||||
expectedValue: fc.expectedValue,
|
||||
isMatch,
|
||||
targetFieldIds: fc.targetFieldIds,
|
||||
});
|
||||
|
||||
if (isMatch) {
|
||||
// 일치하면 타겟 섹션/필드 활성화
|
||||
if (fc.targetSectionIds) {
|
||||
@@ -124,8 +104,6 @@ export function useConditionalDisplay(
|
||||
}
|
||||
});
|
||||
|
||||
console.log('[useConditionalDisplay] 활성화된 필드 ID:', [...activeFieldIds]);
|
||||
|
||||
return { activeSectionIds, activeFieldIds };
|
||||
}, [triggerFields, formData]);
|
||||
|
||||
|
||||
@@ -178,7 +178,6 @@ export function useDynamicFormState(
|
||||
|
||||
// 폼 초기화
|
||||
const resetForm = useCallback((newInitialData?: DynamicFormData) => {
|
||||
console.log('[useDynamicFormState] resetForm 호출됨:', newInitialData);
|
||||
setFormData(newInitialData || {});
|
||||
setErrors({});
|
||||
setIsSubmitting(false);
|
||||
|
||||
@@ -398,127 +398,38 @@ export default function DynamicItemForm({
|
||||
}
|
||||
}, [selectedItemType, structure, mode, resetForm]);
|
||||
|
||||
// Edit 모드: structure 로드 후 initialData를 field_key 형식으로 변환
|
||||
// 2025-12-04: initialData 키(item_name)와 structure의 field_key(98_item_name)가 다른 문제 해결
|
||||
// Edit 모드: initialData를 폼에 직접 로드
|
||||
// 2025-12-09: field_key 통일로 복잡한 매핑 로직 제거
|
||||
// 백엔드에서 field_key 그대로 응답하므로 직접 사용 가능
|
||||
const [isEditDataMapped, setIsEditDataMapped] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (mode !== 'edit' || !structure || !initialData) return;
|
||||
console.log('[DynamicItemForm] Edit useEffect 체크:', {
|
||||
mode,
|
||||
hasStructure: !!structure,
|
||||
hasInitialData: !!initialData,
|
||||
isEditDataMapped,
|
||||
structureSections: structure?.sections?.length,
|
||||
});
|
||||
|
||||
// 이미 매핑된 데이터가 formData에 있으면 스킵 (98_unit 같은 field_key 형식)
|
||||
// StrictMode 리렌더에서도 안전하게 동작
|
||||
const hasFieldKeyData = Object.keys(formData).some(key => /^\d+_/.test(key));
|
||||
if (hasFieldKeyData) {
|
||||
console.log('[DynamicItemForm] Edit mode: 이미 field_key 형식 데이터 있음, 매핑 스킵');
|
||||
return;
|
||||
}
|
||||
if (mode !== 'edit' || !structure || !initialData || isEditDataMapped) return;
|
||||
|
||||
console.log('[DynamicItemForm] Edit mode: mapping initialData to field_key format');
|
||||
console.log('[DynamicItemForm] Edit mode: initialData 직접 로드 (field_key 통일됨)');
|
||||
console.log('[DynamicItemForm] initialData:', initialData);
|
||||
|
||||
// initialData의 간단한 키를 structure의 field_key로 매핑
|
||||
// 예: { item_name: '테스트' } → { '98_item_name': '테스트' }
|
||||
const mappedData: DynamicFormData = {};
|
||||
|
||||
// field_key에서 실제 필드명 추출하는 함수
|
||||
// 예: '98_item_name' → 'item_name', '110_품목명' → '품목명'
|
||||
const extractFieldName = (fieldKey: string): string => {
|
||||
const underscoreIndex = fieldKey.indexOf('_');
|
||||
if (underscoreIndex > 0) {
|
||||
return fieldKey.substring(underscoreIndex + 1);
|
||||
}
|
||||
return fieldKey;
|
||||
};
|
||||
|
||||
// structure에서 모든 필드의 field_key 수집
|
||||
const fieldKeyMap: Record<string, string> = {}; // 간단한 키 → field_key 매핑
|
||||
|
||||
// 영문 → 한글 필드명 별칭 (API 응답 키 → structure field_name 매핑)
|
||||
// API는 영문 키(unit, note)로 응답하지만, structure field_key는 한글(단위, 비고) 포함
|
||||
const fieldAliases: Record<string, string> = {
|
||||
'unit': '단위',
|
||||
'note': '비고',
|
||||
'remarks': '비고', // Material 모델은 remarks 사용
|
||||
'item_name': '품목명',
|
||||
'specification': '규격',
|
||||
'description': '설명',
|
||||
};
|
||||
|
||||
// structure의 field_key들 확인
|
||||
const fieldKeys: string[] = [];
|
||||
structure.sections.forEach((section) => {
|
||||
section.fields.forEach((f) => {
|
||||
const field = f.field;
|
||||
const fieldKey = field.field_key || `field_${field.id}`;
|
||||
const simpleName = extractFieldName(fieldKey);
|
||||
fieldKeyMap[simpleName] = fieldKey;
|
||||
|
||||
// field_name도 매핑에 추가 (한글 필드명 지원)
|
||||
if (field.field_name) {
|
||||
fieldKeyMap[field.field_name] = fieldKey;
|
||||
}
|
||||
fieldKeys.push(f.field.field_key || `field_${f.field.id}`);
|
||||
});
|
||||
});
|
||||
console.log('[DynamicItemForm] structure field_keys:', fieldKeys);
|
||||
console.log('[DynamicItemForm] initialData keys:', Object.keys(initialData));
|
||||
|
||||
structure.directFields.forEach((f) => {
|
||||
const field = f.field;
|
||||
const fieldKey = field.field_key || `field_${field.id}`;
|
||||
const simpleName = extractFieldName(fieldKey);
|
||||
fieldKeyMap[simpleName] = fieldKey;
|
||||
|
||||
if (field.field_name) {
|
||||
fieldKeyMap[field.field_name] = fieldKey;
|
||||
}
|
||||
});
|
||||
|
||||
console.log('[DynamicItemForm] fieldKeyMap:', fieldKeyMap);
|
||||
|
||||
// initialData를 field_key 형식으로 변환
|
||||
Object.entries(initialData).forEach(([key, value]) => {
|
||||
// 이미 field_key 형식인 경우 그대로 사용
|
||||
if (key.includes('_') && /^\d+_/.test(key)) {
|
||||
mappedData[key] = value;
|
||||
}
|
||||
// 간단한 키인 경우 field_key로 변환
|
||||
else if (fieldKeyMap[key]) {
|
||||
mappedData[fieldKeyMap[key]] = value;
|
||||
}
|
||||
// 영문 → 한글 별칭으로 시도 (API 응답 키 → structure field_name)
|
||||
else if (fieldAliases[key] && fieldKeyMap[fieldAliases[key]]) {
|
||||
mappedData[fieldKeyMap[fieldAliases[key]]] = value;
|
||||
console.log(`[DynamicItemForm] 별칭 매핑: ${key} → ${fieldAliases[key]} → ${fieldKeyMap[fieldAliases[key]]}`);
|
||||
}
|
||||
// 매핑 없는 경우 그대로 유지
|
||||
else {
|
||||
mappedData[key] = value;
|
||||
}
|
||||
});
|
||||
|
||||
// 추가: 폼 구조의 모든 필드를 순회하면서, initialData에서 해당 값 직접 찾아서 설정
|
||||
// (fieldKeyMap에 매핑이 없는 경우를 위한 fallback)
|
||||
Object.entries(fieldKeyMap).forEach(([simpleName, fieldKey]) => {
|
||||
// 아직 매핑 안된 필드인데 initialData에 값이 있으면 설정
|
||||
if (mappedData[fieldKey] === undefined && initialData[simpleName] !== undefined) {
|
||||
mappedData[fieldKey] = initialData[simpleName];
|
||||
}
|
||||
});
|
||||
|
||||
// 추가: 영문 별칭을 역으로 검색하여 매핑 (한글 field_name → 영문 API 키)
|
||||
// 예: fieldKeyMap에 '단위'가 있고, initialData에 'unit'이 있으면 매핑
|
||||
Object.entries(fieldAliases).forEach(([englishKey, koreanKey]) => {
|
||||
const targetFieldKey = fieldKeyMap[koreanKey];
|
||||
if (targetFieldKey && mappedData[targetFieldKey] === undefined && initialData[englishKey] !== undefined) {
|
||||
mappedData[targetFieldKey] = initialData[englishKey];
|
||||
console.log(`[DynamicItemForm] 별칭 fallback 매핑: ${englishKey} → ${koreanKey} → ${targetFieldKey}`);
|
||||
}
|
||||
});
|
||||
|
||||
console.log('========== [DynamicItemForm] Edit 모드 데이터 매핑 ==========');
|
||||
console.log('specification 관련 키:', Object.keys(mappedData).filter(k => k.includes('specification') || k.includes('규격')));
|
||||
console.log('is_active 관련 키:', Object.keys(mappedData).filter(k => k.includes('active') || k.includes('상태')));
|
||||
console.log('매핑된 데이터:', mappedData);
|
||||
console.log('==============================================================');
|
||||
|
||||
// 변환된 데이터로 폼 리셋
|
||||
resetForm(mappedData);
|
||||
// field_key가 통일되었으므로 initialData를 그대로 사용
|
||||
// 기존 레거시 데이터(98_unit 형식)도 그대로 동작
|
||||
resetForm(initialData);
|
||||
setIsEditDataMapped(true);
|
||||
}, [mode, structure, initialData, isEditDataMapped, resetForm]);
|
||||
|
||||
@@ -1202,82 +1113,22 @@ export default function DynamicItemForm({
|
||||
return;
|
||||
}
|
||||
|
||||
// field_key → 백엔드 필드명 매핑
|
||||
// field_key 형식: "{id}_{key}" (예: "98_item_name", "110_품목명")
|
||||
// 백엔드 필드명으로 변환 필요
|
||||
// 2025-12-03: 한글 field_key 지원 추가
|
||||
const fieldKeyToBackendKey: Record<string, string> = {
|
||||
'item_name': 'name',
|
||||
'productName': 'name', // FG(제품) 품목명 필드
|
||||
'품목명': 'name', // 한글 field_key 지원
|
||||
'specification': 'spec',
|
||||
'standard': 'spec', // 규격 대체 필드명
|
||||
'규격': 'spec', // 한글 field_key 지원
|
||||
'사양': 'spec', // 한글 대체
|
||||
'unit': 'unit',
|
||||
'단위': 'unit', // 한글 field_key 지원
|
||||
'note': 'note',
|
||||
'비고': 'note', // 한글 field_key 지원
|
||||
'description': 'description',
|
||||
'설명': 'description', // 한글 field_key 지원
|
||||
'part_type': 'part_type',
|
||||
'부품유형': 'part_type', // 한글 field_key 지원
|
||||
'부품 유형': 'part_type', // 공백 포함 한글
|
||||
'is_active': 'is_active',
|
||||
'status': 'is_active',
|
||||
'active': 'is_active',
|
||||
'품목상태': 'is_active', // 한글 field_key 지원
|
||||
'품목 상태': 'is_active', // 공백 포함 한글
|
||||
'상태': 'is_active', // 짧은 한글
|
||||
};
|
||||
// 2025-12-09: field_key 통일로 변환 로직 제거
|
||||
// formData의 field_key가 백엔드 필드명과 일치하므로 직접 사용
|
||||
console.log('[DynamicItemForm] 저장 시 formData:', formData);
|
||||
|
||||
// formData를 백엔드 필드명으로 변환
|
||||
console.log('========== [DynamicItemForm] 저장 시 formData ==========');
|
||||
console.log('specification 관련:', Object.entries(formData).filter(([k]) => k.includes('specification') || k.includes('규격')));
|
||||
console.log('is_active 관련:', Object.entries(formData).filter(([k]) => k.includes('active') || k.includes('상태')));
|
||||
console.log('전체 formData:', formData);
|
||||
console.log('=========================================================');
|
||||
// is_active 필드만 boolean 변환 (드롭다운 값 → boolean)
|
||||
const convertedData: Record<string, any> = {};
|
||||
Object.entries(formData).forEach(([key, value]) => {
|
||||
// "{id}_{fieldKey}" 형식 체크: 숫자로 시작하고 _가 있는 경우
|
||||
// 예: "98_item_name" → true, "item_name" → false
|
||||
const isFieldKeyFormat = /^\d+_/.test(key);
|
||||
|
||||
if (isFieldKeyFormat) {
|
||||
// "{id}_{fieldKey}" 형식에서 fieldKey 추출
|
||||
const underscoreIndex = key.indexOf('_');
|
||||
const fieldKey = key.substring(underscoreIndex + 1);
|
||||
const backendKey = fieldKeyToBackendKey[fieldKey] || fieldKey;
|
||||
|
||||
// is_active 필드는 boolean으로 변환
|
||||
if (backendKey === 'is_active') {
|
||||
// "활성", true, "true", "1", 1 등을 true로, 나머지는 false로
|
||||
const isActive = value === true || value === 'true' || value === '1' ||
|
||||
value === 1 || value === '활성' || value === 'active';
|
||||
console.log(`[DynamicItemForm] is_active 변환: key=${key}, value=${value}(${typeof value}) → isActive=${isActive}`);
|
||||
convertedData[backendKey] = isActive;
|
||||
} else {
|
||||
convertedData[backendKey] = value;
|
||||
}
|
||||
if (key === 'is_active' || key.endsWith('_is_active')) {
|
||||
// "활성", true, "true", "1", 1 등을 true로, 나머지는 false로
|
||||
const isActive = value === true || value === 'true' || value === '1' ||
|
||||
value === 1 || value === '활성' || value === 'active';
|
||||
convertedData[key] = isActive;
|
||||
} else {
|
||||
// field_key 형식이 아닌 경우, 매핑 테이블에서 변환 시도
|
||||
const backendKey = fieldKeyToBackendKey[key] || key;
|
||||
|
||||
if (backendKey === 'is_active') {
|
||||
const isActive = value === true || value === 'true' || value === '1' ||
|
||||
value === 1 || value === '활성' || value === 'active';
|
||||
console.log(`[DynamicItemForm] is_active 변환 (non-field_key): key=${key}, value=${value}(${typeof value}) → isActive=${isActive}`);
|
||||
convertedData[backendKey] = isActive;
|
||||
} else {
|
||||
convertedData[backendKey] = value;
|
||||
}
|
||||
convertedData[key] = value;
|
||||
}
|
||||
});
|
||||
console.log('========== [DynamicItemForm] convertedData 결과 ==========');
|
||||
console.log('is_active:', convertedData.is_active);
|
||||
console.log('specification:', convertedData.spec || convertedData.specification);
|
||||
console.log('전체:', convertedData);
|
||||
console.log('===========================================================');
|
||||
|
||||
// 품목명 값 추출 (품목코드와 품목명 모두 필요)
|
||||
// 2025-12-04: 절곡 부품은 별도 품목명 필드(bendingFieldKeys.itemName) 사용
|
||||
@@ -1333,7 +1184,8 @@ export default function DynamicItemForm({
|
||||
}
|
||||
|
||||
// 품목 유형 및 BOM 데이터 추가
|
||||
const submitData: DynamicFormData = {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const submitData = {
|
||||
...convertedData,
|
||||
// 백엔드 필드명 사용
|
||||
product_type: selectedItemType, // item_type → product_type
|
||||
@@ -1373,7 +1225,7 @@ export default function DynamicItemForm({
|
||||
...(selectedItemType === 'FG' && !convertedData.unit ? {
|
||||
unit: 'EA',
|
||||
} : {}),
|
||||
};
|
||||
} as DynamicFormData;
|
||||
|
||||
// console.log('[DynamicItemForm] 제출 데이터:', submitData);
|
||||
|
||||
@@ -1392,9 +1244,9 @@ export default function DynamicItemForm({
|
||||
console.log('[DynamicItemForm] 전개도 파일 업로드 시작:', bendingDiagramFile.name);
|
||||
await uploadItemFile(itemId, bendingDiagramFile, 'bending_diagram', {
|
||||
bendingDetails: bendingDetails.length > 0 ? bendingDetails.map(d => ({
|
||||
angle: d.angle || 0,
|
||||
length: d.width || 0,
|
||||
type: d.direction || '',
|
||||
angle: d.aAngle || 0,
|
||||
length: d.input || 0,
|
||||
type: d.shaded ? 'shaded' : 'normal',
|
||||
})) : undefined,
|
||||
});
|
||||
console.log('[DynamicItemForm] 전개도 파일 업로드 성공');
|
||||
@@ -1924,6 +1776,25 @@ export default function DynamicItemForm({
|
||||
onOpenChange={setIsDrawingOpen}
|
||||
onSave={(imageData) => {
|
||||
setBendingDiagram(imageData);
|
||||
|
||||
// Base64 string을 File 객체로 변환 (업로드용)
|
||||
// 2025-12-06: 드로잉 방식에서도 파일 업로드 지원
|
||||
try {
|
||||
const byteString = atob(imageData.split(',')[1]);
|
||||
const mimeType = imageData.split(',')[0].split(':')[1].split(';')[0];
|
||||
const arrayBuffer = new ArrayBuffer(byteString.length);
|
||||
const uint8Array = new Uint8Array(arrayBuffer);
|
||||
for (let i = 0; i < byteString.length; i++) {
|
||||
uint8Array[i] = byteString.charCodeAt(i);
|
||||
}
|
||||
const blob = new Blob([uint8Array], { type: mimeType });
|
||||
const file = new File([blob], `bending_diagram_${Date.now()}.png`, { type: mimeType });
|
||||
setBendingDiagramFile(file);
|
||||
console.log('[DynamicItemForm] 드로잉 캔버스 → File 변환 성공:', file.name);
|
||||
} catch (error) {
|
||||
console.error('[DynamicItemForm] 드로잉 캔버스 → File 변환 실패:', error);
|
||||
}
|
||||
|
||||
setIsDrawingOpen(false);
|
||||
}}
|
||||
initialImage={bendingDiagram}
|
||||
|
||||
@@ -118,7 +118,7 @@ export interface BOMSearchState {
|
||||
/**
|
||||
* 동적 폼 필드 값 타입
|
||||
*/
|
||||
export type DynamicFieldValue = string | number | boolean | null | undefined | Record<string, unknown>[] | Record<string, unknown>;
|
||||
export type DynamicFieldValue = string | number | boolean | string[] | null | undefined | Record<string, unknown>[] | Record<string, unknown>;
|
||||
|
||||
/**
|
||||
* 동적 폼 데이터 (field_key를 key로 사용)
|
||||
|
||||
@@ -256,23 +256,20 @@ export default function ItemDetailClient({ item }: ItemDetailClientProps) {
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
|
||||
{item.category1 && (
|
||||
<div>
|
||||
<Label className="text-muted-foreground">품목명</Label>
|
||||
<p className="mt-1">
|
||||
<Badge variant="outline" className="bg-indigo-50 text-indigo-700">
|
||||
{item.category1 === 'guide_rail' ? '가이드레일' :
|
||||
item.category1 === 'case' ? '케이스' :
|
||||
item.category1 === 'bottom_finish' ? '하단마감재' :
|
||||
item.category1}
|
||||
</Badge>
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{item.installationType && (
|
||||
<div>
|
||||
<Label className="text-muted-foreground">설치 유형</Label>
|
||||
<p className="mt-1">
|
||||
{/* 품목명 - itemName 표시 */}
|
||||
<div>
|
||||
<Label className="text-muted-foreground">품목명</Label>
|
||||
<p className="mt-1">
|
||||
<Badge variant="outline" className="bg-indigo-50 text-indigo-700">
|
||||
{item.itemName}
|
||||
</Badge>
|
||||
</p>
|
||||
</div>
|
||||
{/* 설치 유형 */}
|
||||
<div>
|
||||
<Label className="text-muted-foreground">설치 유형</Label>
|
||||
<p className="mt-1">
|
||||
{item.installationType ? (
|
||||
<Badge variant="outline" className="bg-green-50 text-green-700">
|
||||
{item.installationType === 'wall' ? '벽면형 (R)' :
|
||||
item.installationType === 'side' ? '측면형 (S)' :
|
||||
@@ -280,19 +277,41 @@ export default function ItemDetailClient({ item }: ItemDetailClientProps) {
|
||||
item.installationType === 'iron' ? '철재 (T)' :
|
||||
item.installationType}
|
||||
</Badge>
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{item.assemblyType && (
|
||||
<div>
|
||||
<Label className="text-muted-foreground">마감</Label>
|
||||
<p className="mt-1">
|
||||
) : (
|
||||
<span className="text-muted-foreground">-</span>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
{/* 마감 */}
|
||||
<div>
|
||||
<Label className="text-muted-foreground">마감</Label>
|
||||
<p className="mt-1">
|
||||
{item.assemblyType ? (
|
||||
<code className="text-sm bg-gray-100 px-2 py-1 rounded">
|
||||
{item.assemblyType}
|
||||
</code>
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
) : (
|
||||
<span className="text-muted-foreground">-</span>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
{/* 길이 */}
|
||||
<div>
|
||||
<Label className="text-muted-foreground">길이</Label>
|
||||
<p className="mt-1 font-medium">
|
||||
{item.assemblyLength || item.length ? `${item.assemblyLength || item.length}mm` : '-'}
|
||||
</p>
|
||||
</div>
|
||||
{/* 측면 규격 */}
|
||||
<div>
|
||||
<Label className="text-muted-foreground">측면 규격</Label>
|
||||
<p className="mt-1">
|
||||
{item.sideSpecWidth && item.sideSpecHeight
|
||||
? `${item.sideSpecWidth} × ${item.sideSpecHeight}mm`
|
||||
: '-'}
|
||||
</p>
|
||||
</div>
|
||||
{/* 재질 (있으면) */}
|
||||
{item.material && (
|
||||
<div>
|
||||
<Label className="text-muted-foreground">재질</Label>
|
||||
@@ -303,20 +322,6 @@ export default function ItemDetailClient({ item }: ItemDetailClientProps) {
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{item.assemblyLength && (
|
||||
<div>
|
||||
<Label className="text-muted-foreground">길이</Label>
|
||||
<p className="mt-1 font-medium">{item.assemblyLength}mm</p>
|
||||
</div>
|
||||
)}
|
||||
{item.sideSpecWidth && item.sideSpecHeight && (
|
||||
<div>
|
||||
<Label className="text-muted-foreground">측면 규격</Label>
|
||||
<p className="mt-1">
|
||||
{item.sideSpecWidth} × {item.sideSpecHeight}mm
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -355,10 +360,9 @@ export default function ItemDetailClient({ item }: ItemDetailClientProps) {
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 절곡품/조립품 전개도 정보 */}
|
||||
{/* 절곡품/조립품 전개도 정보 - 조립부품은 항상 표시 */}
|
||||
{item.itemType === 'PT' &&
|
||||
(item.partType === 'BENDING' || item.partType === 'ASSEMBLY') &&
|
||||
(item.bendingDiagram || (item.bendingDetails && item.bendingDetails.length > 0)) && (
|
||||
(item.partType === 'BENDING' || item.partType === 'ASSEMBLY') && (
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="flex items-center gap-2 text-base md:text-lg">
|
||||
|
||||
@@ -172,7 +172,7 @@ export default function PartForm({
|
||||
value={selectedPartType}
|
||||
onValueChange={handlePartTypeChange}
|
||||
>
|
||||
<SelectTrigger className={errors.partType ? 'border-red-500' : ''}>
|
||||
<SelectTrigger className={(errors as any).partType ? 'border-red-500' : ''}>
|
||||
<SelectValue placeholder="부품 유형을 선택하세요" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
@@ -181,12 +181,12 @@ export default function PartForm({
|
||||
<SelectItem value="PURCHASED">구매 부품 (Purchased Part)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{errors.partType && (
|
||||
{(errors as any).partType && (
|
||||
<p className="text-xs text-red-500 mt-1">
|
||||
{errors.partType.message}
|
||||
{(errors as any).partType.message}
|
||||
</p>
|
||||
)}
|
||||
{!errors.partType && selectedPartType === 'BENDING' && (
|
||||
{!(errors as any).partType && selectedPartType === 'BENDING' && (
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
* 절곡 부품은 전개도(바라시)만 있으며, 부품 구성(BOM)은 사용하지 않습니다.
|
||||
</p>
|
||||
|
||||
@@ -18,6 +18,11 @@ import { X } from 'lucide-react';
|
||||
import type { UseFormRegister, UseFormSetValue, UseFormGetValues, FieldErrors } from 'react-hook-form';
|
||||
import type { CreateItemFormData } from '@/lib/utils/validation';
|
||||
|
||||
// ProductForm에서 사용하는 확장 타입 (productName 포함)
|
||||
type ProductFormErrors = FieldErrors<CreateItemFormData> & {
|
||||
productName?: { message?: string };
|
||||
};
|
||||
|
||||
interface ProductFormProps {
|
||||
productName: string;
|
||||
setProductName: (value: string) => void;
|
||||
@@ -35,7 +40,7 @@ interface ProductFormProps {
|
||||
register: UseFormRegister<CreateItemFormData>;
|
||||
setValue: UseFormSetValue<CreateItemFormData>;
|
||||
getValues: UseFormGetValues<CreateItemFormData>;
|
||||
errors: FieldErrors<CreateItemFormData>;
|
||||
errors: ProductFormErrors;
|
||||
}
|
||||
|
||||
export default function ProductForm({
|
||||
|
||||
@@ -134,7 +134,7 @@ export default function BendingPartForm({
|
||||
setValue('material', value);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className={errors.material ? 'border-red-500' : ''}>
|
||||
<SelectTrigger className={(errors as any).material ? 'border-red-500' : ''}>
|
||||
<SelectValue placeholder="재질을 선택하세요" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
@@ -144,9 +144,9 @@ export default function BendingPartForm({
|
||||
<SelectItem value="SUS 1.5T">SUS 1.5T</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{errors.material && (
|
||||
{(errors as any).material && (
|
||||
<p className="text-xs text-red-500 mt-1">
|
||||
{errors.material.message}
|
||||
{(errors as any).material.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
@@ -165,16 +165,16 @@ export default function BendingPartForm({
|
||||
}}
|
||||
placeholder="전개도 상세를 입력해주세요"
|
||||
readOnly={bendingDetailsLength > 0}
|
||||
className={`${bendingDetailsLength > 0 ? "bg-blue-50 font-medium" : ""} ${errors.length ? 'border-red-500' : ''}`}
|
||||
className={`${bendingDetailsLength > 0 ? "bg-blue-50 font-medium" : ""} ${(errors as any).length ? 'border-red-500' : ''}`}
|
||||
/>
|
||||
<span className="text-sm text-muted-foreground">mm</span>
|
||||
</div>
|
||||
{errors.length && (
|
||||
{(errors as any).length && (
|
||||
<p className="text-xs text-red-500 mt-1">
|
||||
{errors.length.message}
|
||||
{(errors as any).length.message}
|
||||
</p>
|
||||
)}
|
||||
{!errors.length && bendingDetailsLength > 0 && (
|
||||
{!(errors as any).length && bendingDetailsLength > 0 && (
|
||||
<p className="text-xs text-blue-600 mt-1">
|
||||
* 전개도 상세 입력의 합계가 자동 반영됩니다
|
||||
</p>
|
||||
@@ -192,7 +192,7 @@ export default function BendingPartForm({
|
||||
setValue('bendingLength', value);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className={errors.bendingLength ? 'border-red-500' : ''}>
|
||||
<SelectTrigger className={(errors as any).bendingLength ? 'border-red-500' : ''}>
|
||||
<SelectValue placeholder="모양&길이를 선택하세요" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
@@ -210,9 +210,9 @@ export default function BendingPartForm({
|
||||
<SelectItem value="4300">4300mm</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{errors.bendingLength && (
|
||||
{(errors as any).bendingLength && (
|
||||
<p className="text-xs text-red-500 mt-1">
|
||||
{errors.bendingLength.message}
|
||||
{(errors as any).bendingLength.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -119,7 +119,7 @@ export default function PurchasedPartForm({
|
||||
setValue('electricOpenerPower', value);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className={errors.electricOpenerPower ? 'border-red-500' : ''}>
|
||||
<SelectTrigger className={(errors as any).electricOpenerPower ? 'border-red-500' : ''}>
|
||||
<SelectValue placeholder="전원을 선택하세요" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
@@ -127,9 +127,9 @@ export default function PurchasedPartForm({
|
||||
<SelectItem value="380V">380V</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{errors.electricOpenerPower && (
|
||||
{(errors as any).electricOpenerPower && (
|
||||
<p className="text-xs text-red-500 mt-1">
|
||||
{errors.electricOpenerPower.message}
|
||||
{(errors as any).electricOpenerPower.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
@@ -144,7 +144,7 @@ export default function PurchasedPartForm({
|
||||
setValue('electricOpenerCapacity', value);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className={errors.electricOpenerCapacity ? 'border-red-500' : ''}>
|
||||
<SelectTrigger className={(errors as any).electricOpenerCapacity ? 'border-red-500' : ''}>
|
||||
<SelectValue placeholder="용량을 선택하세요" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
@@ -157,9 +157,9 @@ export default function PurchasedPartForm({
|
||||
<SelectItem value="1000">1000 KG</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{errors.electricOpenerCapacity && (
|
||||
{(errors as any).electricOpenerCapacity && (
|
||||
<p className="text-xs text-red-500 mt-1">
|
||||
{errors.electricOpenerCapacity.message}
|
||||
{(errors as any).electricOpenerCapacity.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
@@ -182,7 +182,7 @@ export default function PurchasedPartForm({
|
||||
setValue('motorVoltage', value);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className={errors.motorVoltage ? 'border-red-500' : ''}>
|
||||
<SelectTrigger className={(errors as any).motorVoltage ? 'border-red-500' : ''}>
|
||||
<SelectValue placeholder="전압을 선택하세요" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
@@ -190,9 +190,9 @@ export default function PurchasedPartForm({
|
||||
<SelectItem value="380">380V</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{errors.motorVoltage && (
|
||||
{(errors as any).motorVoltage && (
|
||||
<p className="text-xs text-red-500 mt-1">
|
||||
{errors.motorVoltage.message}
|
||||
{(errors as any).motorVoltage.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
@@ -211,7 +211,7 @@ export default function PurchasedPartForm({
|
||||
setValue('chainSpec', value);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className={errors.chainSpec ? 'border-red-500' : ''}>
|
||||
<SelectTrigger className={(errors as any).chainSpec ? 'border-red-500' : ''}>
|
||||
<SelectValue placeholder="규격을 선택하세요" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
@@ -221,9 +221,9 @@ export default function PurchasedPartForm({
|
||||
<SelectItem value="80">80</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{errors.chainSpec && (
|
||||
{(errors as any).chainSpec && (
|
||||
<p className="text-xs text-red-500 mt-1">
|
||||
{errors.chainSpec.message}
|
||||
{(errors as any).chainSpec.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -194,7 +194,6 @@ export default function ItemListClient() {
|
||||
console.log('[Delete] 응답:', { status: response.status, result });
|
||||
|
||||
if (response.ok && result.success) {
|
||||
alert('품목이 삭제되었습니다.');
|
||||
refresh();
|
||||
} else {
|
||||
throw new Error(result.message || '삭제에 실패했습니다.');
|
||||
|
||||
@@ -62,7 +62,7 @@ export interface Column<T> {
|
||||
format?: (value: any) => string | number;
|
||||
}
|
||||
|
||||
interface DataTableProps<T> {
|
||||
interface DataTableProps<T extends object> {
|
||||
columns: Column<T>[];
|
||||
data: T[];
|
||||
keyField: keyof T;
|
||||
@@ -203,7 +203,7 @@ function getAlignClass(column: Column<any>): string {
|
||||
}
|
||||
}
|
||||
|
||||
export function DataTable<T>({
|
||||
export function DataTable<T extends object>({
|
||||
columns,
|
||||
data,
|
||||
keyField,
|
||||
|
||||
@@ -20,7 +20,7 @@ export function PageLayout({ children, maxWidth = "full", versionInfo }: PageLay
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={`p-4 md:p-6 space-y-4 md:space-y-6 ${maxWidthClasses[maxWidth]} mx-auto w-full relative`}>
|
||||
<div className={`p-3 md:p-6 pb-0 space-y-3 md:space-y-6 flex flex-col ${maxWidthClasses[maxWidth]} mx-auto w-full relative`}>
|
||||
{versionInfo && (
|
||||
<div className="absolute top-4 right-4 z-10">
|
||||
{versionInfo}
|
||||
|
||||
@@ -65,6 +65,7 @@ interface PricingFormClientProps {
|
||||
itemInfo?: ItemInfo;
|
||||
initialData?: PricingData;
|
||||
onSave?: (data: PricingData, isRevision?: boolean, revisionReason?: string) => Promise<void>;
|
||||
onFinalize?: (id: string) => Promise<void>;
|
||||
}
|
||||
|
||||
export function PricingFormClient({
|
||||
@@ -72,6 +73,7 @@ export function PricingFormClient({
|
||||
itemInfo,
|
||||
initialData,
|
||||
onSave,
|
||||
onFinalize,
|
||||
}: PricingFormClientProps) {
|
||||
const router = useRouter();
|
||||
const isEditMode = mode === 'edit';
|
||||
@@ -264,30 +266,9 @@ export function PricingFormClient({
|
||||
|
||||
setIsSaving(true);
|
||||
try {
|
||||
const finalizedData: PricingData = {
|
||||
...initialData,
|
||||
effectiveDate,
|
||||
receiveDate: receiveDate || undefined,
|
||||
author: author || undefined,
|
||||
purchasePrice: purchasePrice || undefined,
|
||||
processingCost: processingCost || undefined,
|
||||
loss: loss || undefined,
|
||||
roundingRule: roundingRule || undefined,
|
||||
roundingUnit: roundingUnit || undefined,
|
||||
marginRate: marginRate || undefined,
|
||||
salesPrice: salesPrice || undefined,
|
||||
supplier: supplier || undefined,
|
||||
note: note || undefined,
|
||||
isFinal: true,
|
||||
finalizedDate: new Date().toISOString(),
|
||||
finalizedBy: '관리자',
|
||||
status: 'finalized',
|
||||
updatedAt: new Date().toISOString(),
|
||||
updatedBy: '관리자',
|
||||
};
|
||||
|
||||
if (onSave) {
|
||||
await onSave(finalizedData);
|
||||
if (onFinalize) {
|
||||
// 서버 액션으로 확정 처리
|
||||
await onFinalize(initialData.id);
|
||||
}
|
||||
|
||||
toast.success('단가가 최종 확정되었습니다.');
|
||||
@@ -295,6 +276,7 @@ export function PricingFormClient({
|
||||
router.push('/sales/pricing-management');
|
||||
} catch (error) {
|
||||
toast.error('확정 중 오류가 발생했습니다.');
|
||||
console.error(error);
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
|
||||
@@ -153,7 +153,9 @@ export function PricingListClient({
|
||||
|
||||
// 네비게이션 핸들러
|
||||
const handleRegister = (item: PricingListItem) => {
|
||||
router.push(`/sales/pricing-management/create?itemId=${item.itemId}&itemCode=${item.itemCode}`);
|
||||
// itemTypeCode를 URL 파라미터에 포함 (PRODUCT 또는 MATERIAL)
|
||||
const itemTypeCode = item.itemTypeCode || 'MATERIAL';
|
||||
router.push(`/sales/pricing-management/create?itemId=${item.itemId}&itemCode=${item.itemCode}&itemTypeCode=${itemTypeCode}`);
|
||||
};
|
||||
|
||||
const handleEdit = (item: PricingListItem) => {
|
||||
@@ -414,7 +416,7 @@ export function PricingListClient({
|
||||
|
||||
return (
|
||||
<IntegratedListTemplateV2<PricingListItem>
|
||||
title="단가 관리"
|
||||
title="단가 목록"
|
||||
description="품목별 매입단가, 판매단가 및 마진을 관리합니다"
|
||||
icon={DollarSign}
|
||||
headerActions={headerActions}
|
||||
|
||||
511
src/components/pricing/actions.ts
Normal file
511
src/components/pricing/actions.ts
Normal file
@@ -0,0 +1,511 @@
|
||||
/**
|
||||
* 단가관리 서버 액션
|
||||
*
|
||||
* API Endpoints:
|
||||
* - GET /api/v1/pricing - 목록 조회
|
||||
* - GET /api/v1/pricing/{id} - 상세 조회
|
||||
* - POST /api/v1/pricing - 등록
|
||||
* - PUT /api/v1/pricing/{id} - 수정
|
||||
* - DELETE /api/v1/pricing/{id} - 삭제
|
||||
* - POST /api/v1/pricing/{id}/finalize - 확정
|
||||
* - GET /api/v1/pricing/{id}/revisions - 이력 조회
|
||||
*/
|
||||
|
||||
'use server';
|
||||
|
||||
import { cookies } from 'next/headers';
|
||||
import type { PricingData, ItemInfo } from './types';
|
||||
|
||||
// API 응답 타입
|
||||
interface ApiResponse<T> {
|
||||
success: boolean;
|
||||
data: T;
|
||||
message: string;
|
||||
}
|
||||
|
||||
// 단가 API 응답 데이터 타입
|
||||
interface PriceApiData {
|
||||
id: number;
|
||||
tenant_id: number;
|
||||
item_type_code: 'PRODUCT' | 'MATERIAL';
|
||||
item_id: number;
|
||||
client_group_id: number | null;
|
||||
purchase_price: string | null;
|
||||
processing_cost: string | null;
|
||||
loss_rate: string | null;
|
||||
margin_rate: string | null;
|
||||
sales_price: string | null;
|
||||
rounding_rule: 'round' | 'ceil' | 'floor';
|
||||
rounding_unit: number;
|
||||
supplier: string | null;
|
||||
effective_from: string;
|
||||
effective_to: string | null;
|
||||
status: 'draft' | 'active' | 'finalized';
|
||||
is_final: boolean;
|
||||
finalized_at: string | null;
|
||||
finalized_by: number | null;
|
||||
note: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
deleted_at: string | null;
|
||||
client_group?: {
|
||||
id: number;
|
||||
name: string;
|
||||
};
|
||||
product?: {
|
||||
id: number;
|
||||
product_code: string;
|
||||
product_name: string;
|
||||
specification: string | null;
|
||||
unit: string;
|
||||
product_type: string;
|
||||
};
|
||||
material?: {
|
||||
id: number;
|
||||
item_code: string;
|
||||
item_name: string;
|
||||
specification: string | null;
|
||||
unit: string;
|
||||
product_type: string;
|
||||
};
|
||||
revisions?: Array<{
|
||||
id: number;
|
||||
revision_number: number;
|
||||
changed_at: string;
|
||||
changed_by: number;
|
||||
change_reason: string | null;
|
||||
before_snapshot: Record<string, unknown> | null;
|
||||
after_snapshot: Record<string, unknown>;
|
||||
changed_by_user?: {
|
||||
id: number;
|
||||
name: string;
|
||||
};
|
||||
}>;
|
||||
}
|
||||
|
||||
/**
|
||||
* API 헤더 생성
|
||||
*/
|
||||
async function getApiHeaders(): Promise<HeadersInit> {
|
||||
const cookieStore = await cookies();
|
||||
const token = cookieStore.get('access_token')?.value;
|
||||
|
||||
return {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': token ? `Bearer ${token}` : '',
|
||||
'X-API-KEY': process.env.NEXT_PUBLIC_API_KEY || '',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* API 데이터 → 프론트엔드 타입 변환
|
||||
*/
|
||||
function transformApiToFrontend(apiData: PriceApiData): PricingData {
|
||||
const product = apiData.product;
|
||||
const material = apiData.material;
|
||||
|
||||
const itemCode = product?.product_code || material?.item_code || `ITEM-${apiData.item_id}`;
|
||||
const itemName = product?.product_name || material?.item_name || '품목명 없음';
|
||||
const specification = product?.specification || material?.specification || undefined;
|
||||
const unit = product?.unit || material?.unit || 'EA';
|
||||
const itemType = product?.product_type || material?.product_type || 'PT';
|
||||
|
||||
// 리비전 변환
|
||||
const revisions = apiData.revisions?.map((rev) => ({
|
||||
revisionNumber: rev.revision_number,
|
||||
revisionDate: rev.changed_at,
|
||||
revisionBy: rev.changed_by_user?.name || `User ${rev.changed_by}`,
|
||||
revisionReason: rev.change_reason || undefined,
|
||||
previousData: rev.before_snapshot as unknown as PricingData,
|
||||
})) || [];
|
||||
|
||||
return {
|
||||
id: String(apiData.id),
|
||||
itemId: String(apiData.item_id),
|
||||
itemCode,
|
||||
itemName,
|
||||
itemType,
|
||||
specification,
|
||||
unit,
|
||||
effectiveDate: apiData.effective_from,
|
||||
purchasePrice: apiData.purchase_price ? parseFloat(apiData.purchase_price) : undefined,
|
||||
processingCost: apiData.processing_cost ? parseFloat(apiData.processing_cost) : undefined,
|
||||
loss: apiData.loss_rate ? parseFloat(apiData.loss_rate) : undefined,
|
||||
roundingRule: apiData.rounding_rule || 'round',
|
||||
roundingUnit: apiData.rounding_unit || 1,
|
||||
marginRate: apiData.margin_rate ? parseFloat(apiData.margin_rate) : undefined,
|
||||
salesPrice: apiData.sales_price ? parseFloat(apiData.sales_price) : undefined,
|
||||
supplier: apiData.supplier || undefined,
|
||||
note: apiData.note || undefined,
|
||||
currentRevision: revisions.length,
|
||||
isFinal: apiData.is_final,
|
||||
revisions,
|
||||
finalizedDate: apiData.finalized_at || undefined,
|
||||
status: apiData.status,
|
||||
createdAt: apiData.created_at,
|
||||
createdBy: '관리자',
|
||||
updatedAt: apiData.updated_at,
|
||||
updatedBy: '관리자',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 프론트엔드 데이터 → API 요청 형식 변환
|
||||
*/
|
||||
function transformFrontendToApi(data: PricingData, itemTypeCode: 'PRODUCT' | 'MATERIAL' = 'MATERIAL'): Record<string, unknown> {
|
||||
return {
|
||||
item_type_code: itemTypeCode,
|
||||
item_id: parseInt(data.itemId),
|
||||
purchase_price: data.purchasePrice || null,
|
||||
processing_cost: data.processingCost || null,
|
||||
loss_rate: data.loss || null,
|
||||
margin_rate: data.marginRate || null,
|
||||
sales_price: data.salesPrice || null,
|
||||
rounding_rule: data.roundingRule || 'round',
|
||||
rounding_unit: data.roundingUnit || 1,
|
||||
supplier: data.supplier || null,
|
||||
effective_from: data.effectiveDate,
|
||||
effective_to: null,
|
||||
note: data.note || null,
|
||||
status: data.status || 'draft',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 단가 상세 조회
|
||||
*/
|
||||
export async function getPricingById(id: string): Promise<PricingData | null> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/pricing/${id}`,
|
||||
{
|
||||
method: 'GET',
|
||||
headers,
|
||||
cache: 'no-store',
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
console.error('[PricingActions] GET pricing error:', response.status);
|
||||
return null;
|
||||
}
|
||||
|
||||
const result: ApiResponse<PriceApiData> = await response.json();
|
||||
console.log('[PricingActions] GET pricing response:', result);
|
||||
|
||||
if (!result.success || !result.data) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return transformApiToFrontend(result.data);
|
||||
} catch (error) {
|
||||
console.error('[PricingActions] getPricingById error:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 품목 정보 조회 (품목기준관리 API)
|
||||
*/
|
||||
export async function getItemInfo(itemId: string): Promise<ItemInfo | null> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
// materials API로 자재 정보 조회
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/materials/${itemId}`,
|
||||
{
|
||||
method: 'GET',
|
||||
headers,
|
||||
cache: 'no-store',
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
// materials에서 못 찾으면 products에서 조회
|
||||
const productResponse = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/products/${itemId}`,
|
||||
{
|
||||
method: 'GET',
|
||||
headers,
|
||||
cache: 'no-store',
|
||||
}
|
||||
);
|
||||
|
||||
if (!productResponse.ok) {
|
||||
console.error('[PricingActions] Item not found:', itemId);
|
||||
return null;
|
||||
}
|
||||
|
||||
const productResult = await productResponse.json();
|
||||
if (!productResult.success || !productResult.data) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const product = productResult.data;
|
||||
return {
|
||||
id: String(product.id),
|
||||
itemCode: product.product_code,
|
||||
itemName: product.product_name,
|
||||
itemType: product.product_type || 'FG',
|
||||
specification: product.specification || undefined,
|
||||
unit: product.unit || 'EA',
|
||||
};
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
if (!result.success || !result.data) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const material = result.data;
|
||||
return {
|
||||
id: String(material.id),
|
||||
itemCode: material.item_code,
|
||||
itemName: material.item_name,
|
||||
itemType: material.product_type || 'RM',
|
||||
specification: material.specification || undefined,
|
||||
unit: material.unit || 'EA',
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[PricingActions] getItemInfo error:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 단가 등록
|
||||
*/
|
||||
export async function createPricing(
|
||||
data: PricingData,
|
||||
itemTypeCode: 'PRODUCT' | 'MATERIAL' = 'MATERIAL'
|
||||
): Promise<{ success: boolean; data?: PricingData; error?: string }> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
const apiData = transformFrontendToApi(data, itemTypeCode);
|
||||
|
||||
console.log('[PricingActions] POST pricing request:', apiData);
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/pricing`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify(apiData),
|
||||
}
|
||||
);
|
||||
|
||||
const result = await response.json();
|
||||
console.log('[PricingActions] POST pricing response:', result);
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: result.message || '단가 등록에 실패했습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: transformApiToFrontend(result.data),
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[PricingActions] createPricing error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 단가 수정
|
||||
*/
|
||||
export async function updatePricing(
|
||||
id: string,
|
||||
data: PricingData,
|
||||
changeReason?: string
|
||||
): Promise<{ success: boolean; data?: PricingData; error?: string }> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
const apiData = {
|
||||
...transformFrontendToApi(data),
|
||||
change_reason: changeReason || null,
|
||||
};
|
||||
|
||||
console.log('[PricingActions] PUT pricing request:', apiData);
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/pricing/${id}`,
|
||||
{
|
||||
method: 'PUT',
|
||||
headers,
|
||||
body: JSON.stringify(apiData),
|
||||
}
|
||||
);
|
||||
|
||||
const result = await response.json();
|
||||
console.log('[PricingActions] PUT pricing response:', result);
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: result.message || '단가 수정에 실패했습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: transformApiToFrontend(result.data),
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[PricingActions] updatePricing error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 단가 삭제
|
||||
*/
|
||||
export async function deletePricing(id: string): Promise<{ success: boolean; error?: string }> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/pricing/${id}`,
|
||||
{
|
||||
method: 'DELETE',
|
||||
headers,
|
||||
}
|
||||
);
|
||||
|
||||
const result = await response.json();
|
||||
console.log('[PricingActions] DELETE pricing response:', result);
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: result.message || '단가 삭제에 실패했습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error('[PricingActions] deletePricing error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 단가 확정
|
||||
*/
|
||||
export async function finalizePricing(id: string): Promise<{ success: boolean; data?: PricingData; error?: string }> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/pricing/${id}/finalize`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers,
|
||||
}
|
||||
);
|
||||
|
||||
const result = await response.json();
|
||||
console.log('[PricingActions] POST finalize response:', result);
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: result.message || '단가 확정에 실패했습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: transformApiToFrontend(result.data),
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[PricingActions] finalizePricing error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 단가 이력 조회
|
||||
*/
|
||||
export async function getPricingRevisions(priceId: string): Promise<{
|
||||
success: boolean;
|
||||
data?: Array<{
|
||||
revisionNumber: number;
|
||||
revisionDate: string;
|
||||
revisionBy: string;
|
||||
revisionReason?: string;
|
||||
beforeSnapshot: Record<string, unknown> | null;
|
||||
afterSnapshot: Record<string, unknown>;
|
||||
}>;
|
||||
error?: string;
|
||||
}> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/pricing/${priceId}/revisions`,
|
||||
{
|
||||
method: 'GET',
|
||||
headers,
|
||||
cache: 'no-store',
|
||||
}
|
||||
);
|
||||
|
||||
const result = await response.json();
|
||||
console.log('[PricingActions] GET revisions response:', result);
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: result.message || '이력 조회에 실패했습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
const revisions = result.data.data?.map((rev: {
|
||||
revision_number: number;
|
||||
changed_at: string;
|
||||
changed_by: number;
|
||||
change_reason: string | null;
|
||||
before_snapshot: Record<string, unknown> | null;
|
||||
after_snapshot: Record<string, unknown>;
|
||||
changed_by_user?: { name: string };
|
||||
}) => ({
|
||||
revisionNumber: rev.revision_number,
|
||||
revisionDate: rev.changed_at,
|
||||
revisionBy: rev.changed_by_user?.name || `User ${rev.changed_by}`,
|
||||
revisionReason: rev.change_reason || undefined,
|
||||
beforeSnapshot: rev.before_snapshot,
|
||||
afterSnapshot: rev.after_snapshot,
|
||||
})) || [];
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: revisions,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[PricingActions] getPricingRevisions error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -8,3 +8,14 @@ export { PricingFormClient } from './PricingFormClient';
|
||||
export { PricingHistoryDialog } from './PricingHistoryDialog';
|
||||
export { PricingRevisionDialog } from './PricingRevisionDialog';
|
||||
export { PricingFinalizeDialog } from './PricingFinalizeDialog';
|
||||
|
||||
// Server Actions
|
||||
export {
|
||||
getPricingById,
|
||||
getItemInfo,
|
||||
createPricing,
|
||||
updatePricing,
|
||||
deletePricing,
|
||||
finalizePricing,
|
||||
getPricingRevisions,
|
||||
} from './actions';
|
||||
|
||||
@@ -122,6 +122,7 @@ export interface PricingListItem {
|
||||
status: PricingStatus | 'not_registered';
|
||||
currentRevision: number;
|
||||
isFinal: boolean;
|
||||
itemTypeCode?: 'PRODUCT' | 'MATERIAL'; // API 등록 시 필요 (PRODUCT 또는 MATERIAL)
|
||||
}
|
||||
|
||||
// ===== 유틸리티 타입 =====
|
||||
|
||||
@@ -52,6 +52,9 @@ export interface QuoteItem {
|
||||
quantity: number; // 수량 (QTY)
|
||||
wingSize: string; // 마구리 날개치수 (WS)
|
||||
inspectionFee: number; // 검사비 (INSP)
|
||||
unitPrice?: number; // 단가
|
||||
totalAmount?: number; // 합계
|
||||
installType?: string; // 설치유형
|
||||
}
|
||||
|
||||
// 견적 폼 데이터 타입
|
||||
|
||||
138
src/components/settings/LeavePolicyManagement/index.tsx
Normal file
138
src/components/settings/LeavePolicyManagement/index.tsx
Normal file
@@ -0,0 +1,138 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { PageLayout } from '@/components/organisms/PageLayout';
|
||||
import { PageHeader } from '@/components/organisms/PageHeader';
|
||||
import { CalendarDays } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
// 기준 타입
|
||||
type StandardType = 'fiscal' | 'hire';
|
||||
|
||||
// 월 옵션 (1~12월)
|
||||
const MONTH_OPTIONS = Array.from({ length: 12 }, (_, i) => ({
|
||||
value: (i + 1).toString(),
|
||||
label: `${i + 1}월`,
|
||||
}));
|
||||
|
||||
// 일 옵션 (1~31일)
|
||||
const DAY_OPTIONS = Array.from({ length: 31 }, (_, i) => ({
|
||||
value: (i + 1).toString(),
|
||||
label: `${i + 1}일`,
|
||||
}));
|
||||
|
||||
export function LeavePolicyManagement() {
|
||||
// 기준 설정 (회계연도 / 입사일)
|
||||
const [standardType, setStandardType] = useState<StandardType>('fiscal');
|
||||
// 기준일 (월, 일)
|
||||
const [month, setMonth] = useState('1');
|
||||
const [day, setDay] = useState('1');
|
||||
|
||||
// 저장
|
||||
const handleSave = () => {
|
||||
const settings = {
|
||||
standardType,
|
||||
month: parseInt(month),
|
||||
day: parseInt(day),
|
||||
};
|
||||
console.log('저장할 설정:', settings);
|
||||
toast.success('휴가 정책이 저장되었습니다.');
|
||||
};
|
||||
|
||||
return (
|
||||
<PageLayout>
|
||||
{/* 헤더 + 저장 버튼 */}
|
||||
<div className="flex items-start justify-between">
|
||||
<PageHeader
|
||||
title="휴가관리"
|
||||
description="휴가 항목을 관리합니다"
|
||||
icon={CalendarDays}
|
||||
/>
|
||||
<Button onClick={handleSave}>
|
||||
저장
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 기본 정보 카드 */}
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<h3 className="text-lg font-semibold mb-6">기본 정보</h3>
|
||||
|
||||
<div className="grid grid-cols-2 gap-6">
|
||||
{/* 기준 셀렉트 */}
|
||||
<div className="space-y-2">
|
||||
<Label>기준</Label>
|
||||
<Select value={standardType} onValueChange={(v: StandardType) => setStandardType(v)}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="fiscal">회계연도</SelectItem>
|
||||
<SelectItem value="hire">입사일</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* 기준일 셀렉트 (월/일) */}
|
||||
<div className="space-y-2">
|
||||
<Label>기준일</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<Select
|
||||
value={month}
|
||||
onValueChange={setMonth}
|
||||
disabled={standardType === 'hire'}
|
||||
>
|
||||
<SelectTrigger className="w-24">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{MONTH_OPTIONS.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select
|
||||
value={day}
|
||||
onValueChange={setDay}
|
||||
disabled={standardType === 'hire'}
|
||||
>
|
||||
<SelectTrigger className="w-24">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{DAY_OPTIONS.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 안내 문구 */}
|
||||
<div className="mt-6 text-sm text-muted-foreground space-y-1">
|
||||
<p>! 휴가 기준일 설정에 따라서 휴가 조회 범위 및 자동 휴가 부여 정책의 기본 값이 변경됩니다.</p>
|
||||
<ul className="list-disc list-inside ml-2 space-y-1">
|
||||
<li>입사일 기준: 사원의 입사일 기준으로 휴가를 부여하고 조회할 수 있습니다.</li>
|
||||
<li>회계연도 기준: 회사의 회계연도 기준으로 휴가를 부여하고 조회할 수 있습니다.</li>
|
||||
</ul>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
49
src/components/settings/LeavePolicyManagement/types.ts
Normal file
49
src/components/settings/LeavePolicyManagement/types.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* 휴가관리(기준정보) 타입 정의 (PDF 57페이지 기준)
|
||||
*/
|
||||
|
||||
// 휴가 기준 유형
|
||||
export type LeaveStandardType = 'fiscal' | 'hire'; // 회계연도 / 입사일
|
||||
|
||||
export const LEAVE_STANDARD_TYPE_LABELS: Record<LeaveStandardType, string> = {
|
||||
fiscal: '회계연도',
|
||||
hire: '입사일',
|
||||
};
|
||||
|
||||
// 휴가 정책 설정
|
||||
export interface LeavePolicySettings {
|
||||
standardType: LeaveStandardType; // 기준
|
||||
fiscalStartMonth: number; // 기준일 (월) - 회계연도 기준일 때만 사용
|
||||
fiscalStartDay: number; // 기준일 (일)
|
||||
defaultAnnualLeave: number; // 기본 연차 일수
|
||||
additionalLeavePerYear: number; // 근속년수당 추가 연차
|
||||
maxAnnualLeave: number; // 최대 연차 일수
|
||||
carryOverEnabled: boolean; // 이월 허용 여부
|
||||
carryOverMaxDays: number; // 최대 이월 일수
|
||||
carryOverExpiryMonths: number; // 이월 연차 소멸 기간 (개월)
|
||||
}
|
||||
|
||||
// 기본 설정값
|
||||
export const DEFAULT_LEAVE_POLICY: LeavePolicySettings = {
|
||||
standardType: 'fiscal',
|
||||
fiscalStartMonth: 1,
|
||||
fiscalStartDay: 1,
|
||||
defaultAnnualLeave: 15,
|
||||
additionalLeavePerYear: 1,
|
||||
maxAnnualLeave: 25,
|
||||
carryOverEnabled: true,
|
||||
carryOverMaxDays: 10,
|
||||
carryOverExpiryMonths: 3,
|
||||
};
|
||||
|
||||
// 월 옵션
|
||||
export const MONTH_OPTIONS = Array.from({ length: 12 }, (_, i) => ({
|
||||
value: i + 1,
|
||||
label: `${i + 1}월`,
|
||||
}));
|
||||
|
||||
// 일 옵션
|
||||
export const DAY_OPTIONS = Array.from({ length: 31 }, (_, i) => ({
|
||||
value: i + 1,
|
||||
label: `${i + 1}일`,
|
||||
}));
|
||||
@@ -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: '관리',
|
||||
};
|
||||
84
src/components/settings/RankManagement/RankDialog.tsx
Normal file
84
src/components/settings/RankManagement/RankDialog.tsx
Normal file
@@ -0,0 +1,84 @@
|
||||
'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 type { RankDialogProps } from './types';
|
||||
|
||||
/**
|
||||
* 직급 추가/수정 다이얼로그
|
||||
*/
|
||||
export function RankDialog({
|
||||
isOpen,
|
||||
onOpenChange,
|
||||
mode,
|
||||
rank,
|
||||
onSubmit
|
||||
}: RankDialogProps) {
|
||||
const [name, setName] = useState('');
|
||||
|
||||
// 다이얼로그 열릴 때 초기값 설정
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
if (mode === 'edit' && rank) {
|
||||
setName(rank.name);
|
||||
} else {
|
||||
setName('');
|
||||
}
|
||||
}
|
||||
}, [isOpen, mode, rank]);
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (name.trim()) {
|
||||
onSubmit(name.trim());
|
||||
setName('');
|
||||
}
|
||||
};
|
||||
|
||||
const title = mode === 'add' ? '직급 추가' : '직급 수정';
|
||||
const submitText = mode === 'add' ? '등록' : '수정';
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="space-y-4 py-4">
|
||||
{/* 직급명 입력 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="rank-name">직급명</Label>
|
||||
<Input
|
||||
id="rank-name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="직급명을 입력하세요"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="submit" disabled={!name.trim()}>
|
||||
{submitText}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
272
src/components/settings/RankManagement/index.tsx
Normal file
272
src/components/settings/RankManagement/index.tsx
Normal file
@@ -0,0 +1,272 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useCallback } from 'react';
|
||||
import { PageLayout } from '@/components/organisms/PageLayout';
|
||||
import { PageHeader } from '@/components/organisms/PageHeader';
|
||||
import { Award, Plus, GripVertical, Pencil, Trash2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { RankDialog } from './RankDialog';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import type { Rank } from './types';
|
||||
|
||||
/**
|
||||
* 기본 직급 데이터 (PDF 51페이지 기준)
|
||||
*/
|
||||
const defaultRanks: Rank[] = [
|
||||
{ id: 1, name: '사원', order: 1 },
|
||||
{ id: 2, name: '대리', order: 2 },
|
||||
{ id: 3, name: '과장', order: 3 },
|
||||
{ id: 4, name: '차장', order: 4 },
|
||||
{ id: 5, name: '부장', order: 5 },
|
||||
{ id: 6, name: '이사', order: 6 },
|
||||
{ id: 7, name: '상무', order: 7 },
|
||||
{ id: 8, name: '전무', order: 8 },
|
||||
{ id: 9, name: '부사장', order: 9 },
|
||||
{ id: 10, name: '사장', order: 10 },
|
||||
{ id: 11, name: '회장', order: 11 },
|
||||
];
|
||||
|
||||
export function RankManagement() {
|
||||
// 직급 데이터
|
||||
const [ranks, setRanks] = useState<Rank[]>(defaultRanks);
|
||||
|
||||
// 입력 필드
|
||||
const [newRankName, setNewRankName] = useState('');
|
||||
|
||||
// 다이얼로그 상태
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [dialogMode, setDialogMode] = useState<'add' | 'edit'>('add');
|
||||
const [selectedRank, setSelectedRank] = useState<Rank | undefined>();
|
||||
|
||||
// 삭제 확인 다이얼로그
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [rankToDelete, setRankToDelete] = useState<Rank | null>(null);
|
||||
|
||||
// 드래그 상태
|
||||
const [draggedItem, setDraggedItem] = useState<number | null>(null);
|
||||
|
||||
// 직급 추가 (입력 필드에서 직접)
|
||||
const handleQuickAdd = () => {
|
||||
if (!newRankName.trim()) return;
|
||||
|
||||
const newId = Math.max(...ranks.map(r => r.id), 0) + 1;
|
||||
const newOrder = Math.max(...ranks.map(r => r.order), 0) + 1;
|
||||
|
||||
setRanks(prev => [...prev, {
|
||||
id: newId,
|
||||
name: newRankName.trim(),
|
||||
order: newOrder,
|
||||
}]);
|
||||
setNewRankName('');
|
||||
};
|
||||
|
||||
// 직급 수정 다이얼로그 열기
|
||||
const handleEdit = (rank: Rank) => {
|
||||
setSelectedRank(rank);
|
||||
setDialogMode('edit');
|
||||
setDialogOpen(true);
|
||||
};
|
||||
|
||||
// 직급 삭제 확인
|
||||
const handleDelete = (rank: Rank) => {
|
||||
setRankToDelete(rank);
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
// 삭제 실행
|
||||
const confirmDelete = () => {
|
||||
if (rankToDelete) {
|
||||
setRanks(prev => prev.filter(r => r.id !== rankToDelete.id));
|
||||
}
|
||||
setDeleteDialogOpen(false);
|
||||
setRankToDelete(null);
|
||||
};
|
||||
|
||||
// 다이얼로그 제출
|
||||
const handleDialogSubmit = (name: string) => {
|
||||
if (dialogMode === 'edit' && selectedRank) {
|
||||
setRanks(prev => prev.map(r =>
|
||||
r.id === selectedRank.id ? { ...r, name } : r
|
||||
));
|
||||
}
|
||||
setDialogOpen(false);
|
||||
};
|
||||
|
||||
// 드래그 시작
|
||||
const handleDragStart = (e: React.DragEvent, index: number) => {
|
||||
setDraggedItem(index);
|
||||
e.dataTransfer.effectAllowed = 'move';
|
||||
};
|
||||
|
||||
// 드래그 종료
|
||||
const handleDragEnd = () => {
|
||||
setDraggedItem(null);
|
||||
};
|
||||
|
||||
// 드래그 오버
|
||||
const handleDragOver = (e: React.DragEvent, index: number) => {
|
||||
e.preventDefault();
|
||||
if (draggedItem === null || draggedItem === index) return;
|
||||
|
||||
const newRanks = [...ranks];
|
||||
const draggedRank = newRanks[draggedItem];
|
||||
newRanks.splice(draggedItem, 1);
|
||||
newRanks.splice(index, 0, draggedRank);
|
||||
|
||||
// 순서 업데이트
|
||||
const reorderedRanks = newRanks.map((rank, idx) => ({
|
||||
...rank,
|
||||
order: idx + 1
|
||||
}));
|
||||
|
||||
setRanks(reorderedRanks);
|
||||
setDraggedItem(index);
|
||||
};
|
||||
|
||||
// 키보드로 추가 (한글 IME 조합 중에는 무시)
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter' && !e.nativeEvent.isComposing) {
|
||||
handleQuickAdd();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<PageLayout>
|
||||
<PageHeader
|
||||
title="직급관리"
|
||||
description="사원의 직급을 관리합니다. 드래그하여 순서를 변경할 수 있습니다."
|
||||
icon={Award}
|
||||
/>
|
||||
|
||||
<div className="space-y-4">
|
||||
{/* 직급 추가 입력 영역 */}
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={newRankName}
|
||||
onChange={(e) => setNewRankName(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="직급명을 입력하세요"
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button onClick={handleQuickAdd} disabled={!newRankName.trim()}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
추가
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 직급 목록 */}
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
<div className="divide-y">
|
||||
{ranks.map((rank, index) => (
|
||||
<div
|
||||
key={rank.id}
|
||||
draggable
|
||||
onDragStart={(e) => handleDragStart(e, index)}
|
||||
onDragEnd={handleDragEnd}
|
||||
onDragOver={(e) => handleDragOver(e, index)}
|
||||
className={`flex items-center gap-3 px-4 py-3 hover:bg-muted/50 transition-colors cursor-move ${
|
||||
draggedItem === index ? 'opacity-50 bg-muted' : ''
|
||||
}`}
|
||||
>
|
||||
{/* 드래그 핸들 */}
|
||||
<GripVertical className="h-5 w-5 text-muted-foreground flex-shrink-0" />
|
||||
|
||||
{/* 순서 번호 */}
|
||||
<span className="text-sm text-muted-foreground w-8">
|
||||
{index + 1}
|
||||
</span>
|
||||
|
||||
{/* 직급명 */}
|
||||
<span className="flex-1 font-medium">{rank.name}</span>
|
||||
|
||||
{/* 액션 버튼 */}
|
||||
<div className="flex gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleEdit(rank)}
|
||||
className="h-8 w-8 p-0"
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
<span className="sr-only">수정</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleDelete(rank)}
|
||||
className="h-8 w-8 p-0 text-destructive hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
<span className="sr-only">삭제</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{ranks.length === 0 && (
|
||||
<div className="px-4 py-8 text-center text-muted-foreground">
|
||||
등록된 직급이 없습니다.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 안내 문구 */}
|
||||
<p className="text-sm text-muted-foreground">
|
||||
※ 직급 순서는 드래그 앤 드롭으로 변경할 수 있습니다.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* 수정 다이얼로그 */}
|
||||
<RankDialog
|
||||
isOpen={dialogOpen}
|
||||
onOpenChange={setDialogOpen}
|
||||
mode={dialogMode}
|
||||
rank={selectedRank}
|
||||
onSubmit={handleDialogSubmit}
|
||||
/>
|
||||
|
||||
{/* 삭제 확인 다이얼로그 */}
|
||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>직급 삭제</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
"{rankToDelete?.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>
|
||||
);
|
||||
}
|
||||
18
src/components/settings/RankManagement/types.ts
Normal file
18
src/components/settings/RankManagement/types.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* 직급 타입 정의
|
||||
*/
|
||||
export interface Rank {
|
||||
id: number;
|
||||
name: string;
|
||||
order: number;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
export interface RankDialogProps {
|
||||
isOpen: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
mode: 'add' | 'edit';
|
||||
rank?: Rank;
|
||||
onSubmit: (name: string) => void;
|
||||
}
|
||||
84
src/components/settings/TitleManagement/TitleDialog.tsx
Normal file
84
src/components/settings/TitleManagement/TitleDialog.tsx
Normal file
@@ -0,0 +1,84 @@
|
||||
'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 type { TitleDialogProps } from './types';
|
||||
|
||||
/**
|
||||
* 직책 추가/수정 다이얼로그
|
||||
*/
|
||||
export function TitleDialog({
|
||||
isOpen,
|
||||
onOpenChange,
|
||||
mode,
|
||||
title,
|
||||
onSubmit
|
||||
}: TitleDialogProps) {
|
||||
const [name, setName] = useState('');
|
||||
|
||||
// 다이얼로그 열릴 때 초기값 설정
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
if (mode === 'edit' && title) {
|
||||
setName(title.name);
|
||||
} else {
|
||||
setName('');
|
||||
}
|
||||
}
|
||||
}, [isOpen, mode, title]);
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (name.trim()) {
|
||||
onSubmit(name.trim());
|
||||
setName('');
|
||||
}
|
||||
};
|
||||
|
||||
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="title-name">직책명</Label>
|
||||
<Input
|
||||
id="title-name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="직책명을 입력하세요"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="submit" disabled={!name.trim()}>
|
||||
{submitText}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
270
src/components/settings/TitleManagement/index.tsx
Normal file
270
src/components/settings/TitleManagement/index.tsx
Normal file
@@ -0,0 +1,270 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { PageLayout } from '@/components/organisms/PageLayout';
|
||||
import { PageHeader } from '@/components/organisms/PageHeader';
|
||||
import { Briefcase, Plus, GripVertical, Pencil, Trash2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { TitleDialog } from './TitleDialog';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import type { Title } from './types';
|
||||
|
||||
/**
|
||||
* 기본 직책 데이터 (PDF 52페이지 기준)
|
||||
*/
|
||||
const defaultTitles: Title[] = [
|
||||
{ id: 1, name: '없음(기본)', order: 1 },
|
||||
{ id: 2, name: '팀장', order: 2 },
|
||||
{ id: 3, name: '파트장', order: 3 },
|
||||
{ id: 4, name: '실장', order: 4 },
|
||||
{ id: 5, name: '부서장', order: 5 },
|
||||
{ id: 6, name: '본부장', order: 6 },
|
||||
{ id: 7, name: '센터장', order: 7 },
|
||||
{ id: 8, name: '매니저', order: 8 },
|
||||
{ id: 9, name: '리더', order: 9 },
|
||||
];
|
||||
|
||||
export function TitleManagement() {
|
||||
// 직책 데이터
|
||||
const [titles, setTitles] = useState<Title[]>(defaultTitles);
|
||||
|
||||
// 입력 필드
|
||||
const [newTitleName, setNewTitleName] = useState('');
|
||||
|
||||
// 다이얼로그 상태
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [dialogMode, setDialogMode] = useState<'add' | 'edit'>('add');
|
||||
const [selectedTitle, setSelectedTitle] = useState<Title | undefined>();
|
||||
|
||||
// 삭제 확인 다이얼로그
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [titleToDelete, setTitleToDelete] = useState<Title | null>(null);
|
||||
|
||||
// 드래그 상태
|
||||
const [draggedItem, setDraggedItem] = useState<number | null>(null);
|
||||
|
||||
// 직책 추가 (입력 필드에서 직접)
|
||||
const handleQuickAdd = () => {
|
||||
if (!newTitleName.trim()) return;
|
||||
|
||||
const newId = Math.max(...titles.map(t => t.id), 0) + 1;
|
||||
const newOrder = Math.max(...titles.map(t => t.order), 0) + 1;
|
||||
|
||||
setTitles(prev => [...prev, {
|
||||
id: newId,
|
||||
name: newTitleName.trim(),
|
||||
order: newOrder,
|
||||
}]);
|
||||
setNewTitleName('');
|
||||
};
|
||||
|
||||
// 직책 수정 다이얼로그 열기
|
||||
const handleEdit = (title: Title) => {
|
||||
setSelectedTitle(title);
|
||||
setDialogMode('edit');
|
||||
setDialogOpen(true);
|
||||
};
|
||||
|
||||
// 직책 삭제 확인
|
||||
const handleDelete = (title: Title) => {
|
||||
setTitleToDelete(title);
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
// 삭제 실행
|
||||
const confirmDelete = () => {
|
||||
if (titleToDelete) {
|
||||
setTitles(prev => prev.filter(t => t.id !== titleToDelete.id));
|
||||
}
|
||||
setDeleteDialogOpen(false);
|
||||
setTitleToDelete(null);
|
||||
};
|
||||
|
||||
// 다이얼로그 제출
|
||||
const handleDialogSubmit = (name: string) => {
|
||||
if (dialogMode === 'edit' && selectedTitle) {
|
||||
setTitles(prev => prev.map(t =>
|
||||
t.id === selectedTitle.id ? { ...t, name } : t
|
||||
));
|
||||
}
|
||||
setDialogOpen(false);
|
||||
};
|
||||
|
||||
// 드래그 시작
|
||||
const handleDragStart = (e: React.DragEvent, index: number) => {
|
||||
setDraggedItem(index);
|
||||
e.dataTransfer.effectAllowed = 'move';
|
||||
};
|
||||
|
||||
// 드래그 종료
|
||||
const handleDragEnd = () => {
|
||||
setDraggedItem(null);
|
||||
};
|
||||
|
||||
// 드래그 오버
|
||||
const handleDragOver = (e: React.DragEvent, index: number) => {
|
||||
e.preventDefault();
|
||||
if (draggedItem === null || draggedItem === index) return;
|
||||
|
||||
const newTitles = [...titles];
|
||||
const draggedTitle = newTitles[draggedItem];
|
||||
newTitles.splice(draggedItem, 1);
|
||||
newTitles.splice(index, 0, draggedTitle);
|
||||
|
||||
// 순서 업데이트
|
||||
const reorderedTitles = newTitles.map((title, idx) => ({
|
||||
...title,
|
||||
order: idx + 1
|
||||
}));
|
||||
|
||||
setTitles(reorderedTitles);
|
||||
setDraggedItem(index);
|
||||
};
|
||||
|
||||
// 키보드로 추가 (한글 IME 조합 중에는 무시)
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter' && !e.nativeEvent.isComposing) {
|
||||
handleQuickAdd();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<PageLayout>
|
||||
<PageHeader
|
||||
title="직책관리"
|
||||
description="사원의 직책을 관리합니다. 드래그하여 순서를 변경할 수 있습니다."
|
||||
icon={Briefcase}
|
||||
/>
|
||||
|
||||
<div className="space-y-4">
|
||||
{/* 직책 추가 입력 영역 */}
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={newTitleName}
|
||||
onChange={(e) => setNewTitleName(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="직책명을 입력하세요"
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button onClick={handleQuickAdd} disabled={!newTitleName.trim()}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
추가
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 직책 목록 */}
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
<div className="divide-y">
|
||||
{titles.map((title, index) => (
|
||||
<div
|
||||
key={title.id}
|
||||
draggable
|
||||
onDragStart={(e) => handleDragStart(e, index)}
|
||||
onDragEnd={handleDragEnd}
|
||||
onDragOver={(e) => handleDragOver(e, index)}
|
||||
className={`flex items-center gap-3 px-4 py-3 hover:bg-muted/50 transition-colors cursor-move ${
|
||||
draggedItem === index ? 'opacity-50 bg-muted' : ''
|
||||
}`}
|
||||
>
|
||||
{/* 드래그 핸들 */}
|
||||
<GripVertical className="h-5 w-5 text-muted-foreground flex-shrink-0" />
|
||||
|
||||
{/* 순서 번호 */}
|
||||
<span className="text-sm text-muted-foreground w-8">
|
||||
{index + 1}
|
||||
</span>
|
||||
|
||||
{/* 직책명 */}
|
||||
<span className="flex-1 font-medium">{title.name}</span>
|
||||
|
||||
{/* 액션 버튼 */}
|
||||
<div className="flex gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleEdit(title)}
|
||||
className="h-8 w-8 p-0"
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
<span className="sr-only">수정</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleDelete(title)}
|
||||
className="h-8 w-8 p-0 text-destructive hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
<span className="sr-only">삭제</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{titles.length === 0 && (
|
||||
<div className="px-4 py-8 text-center text-muted-foreground">
|
||||
등록된 직책이 없습니다.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 안내 문구 */}
|
||||
<p className="text-sm text-muted-foreground">
|
||||
※ 직책 순서는 드래그 앤 드롭으로 변경할 수 있습니다.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* 수정 다이얼로그 */}
|
||||
<TitleDialog
|
||||
isOpen={dialogOpen}
|
||||
onOpenChange={setDialogOpen}
|
||||
mode={dialogMode}
|
||||
title={selectedTitle}
|
||||
onSubmit={handleDialogSubmit}
|
||||
/>
|
||||
|
||||
{/* 삭제 확인 다이얼로그 */}
|
||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>직책 삭제</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
"{titleToDelete?.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>
|
||||
);
|
||||
}
|
||||
18
src/components/settings/TitleManagement/types.ts
Normal file
18
src/components/settings/TitleManagement/types.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* 직책 타입 정의
|
||||
*/
|
||||
export interface Title {
|
||||
id: number;
|
||||
name: string;
|
||||
order: number;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
export interface TitleDialogProps {
|
||||
isOpen: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
mode: 'add' | 'edit';
|
||||
title?: Title;
|
||||
onSubmit: (name: string) => void;
|
||||
}
|
||||
286
src/components/settings/WorkScheduleManagement/index.tsx
Normal file
286
src/components/settings/WorkScheduleManagement/index.tsx
Normal file
@@ -0,0 +1,286 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { PageLayout } from '@/components/organisms/PageLayout';
|
||||
import { PageHeader } from '@/components/organisms/PageHeader';
|
||||
import { Clock, Save } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { TimePicker } from '@/components/ui/time-picker';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { toast } from 'sonner';
|
||||
import type {
|
||||
WorkScheduleSettings,
|
||||
EmploymentType,
|
||||
DayOfWeek,
|
||||
} from './types';
|
||||
import {
|
||||
DEFAULT_WORK_SCHEDULE,
|
||||
EMPLOYMENT_TYPE_LABELS,
|
||||
DAY_OF_WEEK_LABELS,
|
||||
} from './types';
|
||||
|
||||
// 고용 형태별 기본 설정
|
||||
const EMPLOYMENT_TYPE_DEFAULTS: Record<EmploymentType, Partial<WorkScheduleSettings>> = {
|
||||
regular: {
|
||||
workDays: ['mon', 'tue', 'wed', 'thu', 'fri'],
|
||||
workStartTime: '09:00',
|
||||
workEndTime: '18:00',
|
||||
weeklyWorkHours: 40,
|
||||
weeklyOvertimeHours: 12,
|
||||
},
|
||||
contract: {
|
||||
workDays: ['mon', 'tue', 'wed', 'thu', 'fri'],
|
||||
workStartTime: '09:00',
|
||||
workEndTime: '18:00',
|
||||
weeklyWorkHours: 40,
|
||||
weeklyOvertimeHours: 12,
|
||||
},
|
||||
dispatch: {
|
||||
workDays: ['mon', 'tue', 'wed', 'thu', 'fri'],
|
||||
workStartTime: '09:00',
|
||||
workEndTime: '18:00',
|
||||
weeklyWorkHours: 40,
|
||||
weeklyOvertimeHours: 12,
|
||||
},
|
||||
outsourcing: {
|
||||
workDays: ['mon', 'tue', 'wed', 'thu', 'fri'],
|
||||
workStartTime: '09:00',
|
||||
workEndTime: '18:00',
|
||||
weeklyWorkHours: 40,
|
||||
weeklyOvertimeHours: 12,
|
||||
},
|
||||
partTime: {
|
||||
workDays: ['mon', 'tue', 'wed'],
|
||||
workStartTime: '10:00',
|
||||
workEndTime: '15:00',
|
||||
weeklyWorkHours: 15,
|
||||
weeklyOvertimeHours: 0,
|
||||
},
|
||||
};
|
||||
|
||||
export function WorkScheduleManagement() {
|
||||
// 현재 선택된 고용 형태
|
||||
const [selectedEmploymentType, setSelectedEmploymentType] = useState<EmploymentType>('regular');
|
||||
|
||||
// 근무 설정
|
||||
const [settings, setSettings] = useState<WorkScheduleSettings>(DEFAULT_WORK_SCHEDULE);
|
||||
|
||||
// 고용 형태 변경 시 기본값 로드
|
||||
useEffect(() => {
|
||||
const defaults = EMPLOYMENT_TYPE_DEFAULTS[selectedEmploymentType];
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
employmentType: selectedEmploymentType,
|
||||
...defaults,
|
||||
}));
|
||||
}, [selectedEmploymentType]);
|
||||
|
||||
// 근무일 토글
|
||||
const toggleWorkDay = (day: DayOfWeek) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
workDays: prev.workDays.includes(day)
|
||||
? prev.workDays.filter(d => d !== day)
|
||||
: [...prev.workDays, day],
|
||||
}));
|
||||
};
|
||||
|
||||
// 저장
|
||||
const handleSave = () => {
|
||||
// 실제로는 API 호출
|
||||
console.log('저장할 설정:', settings);
|
||||
toast.success(`${EMPLOYMENT_TYPE_LABELS[selectedEmploymentType]} 근무 설정이 저장되었습니다.`);
|
||||
};
|
||||
|
||||
const ALL_DAYS: DayOfWeek[] = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];
|
||||
|
||||
return (
|
||||
<PageLayout>
|
||||
<PageHeader
|
||||
title="근무관리"
|
||||
description="고용 형태별 근무 시간을 설정합니다."
|
||||
icon={Clock}
|
||||
/>
|
||||
|
||||
<div className="space-y-6">
|
||||
{/* 고용 형태 선택 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">고용 형태 선택</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="employment-type">고용 형태</Label>
|
||||
<Select
|
||||
value={selectedEmploymentType}
|
||||
onValueChange={(value: EmploymentType) => setSelectedEmploymentType(value)}
|
||||
>
|
||||
<SelectTrigger className="w-64">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{Object.entries(EMPLOYMENT_TYPE_LABELS).map(([key, label]) => (
|
||||
<SelectItem key={key} value={key}>
|
||||
{label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 주간 근무일 설정 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">주간 근무일</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex flex-wrap gap-4">
|
||||
{ALL_DAYS.map((day) => (
|
||||
<label
|
||||
key={day}
|
||||
className="flex items-center gap-2 cursor-pointer"
|
||||
>
|
||||
<Checkbox
|
||||
checked={settings.workDays.includes(day)}
|
||||
onCheckedChange={() => toggleWorkDay(day)}
|
||||
/>
|
||||
<span className="text-sm font-medium">
|
||||
{DAY_OF_WEEK_LABELS[day]}
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 1일 기준 근로시간 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">1일 기준 근로시간</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-2 gap-6">
|
||||
<div className="space-y-2">
|
||||
<Label>출근 시간</Label>
|
||||
<TimePicker
|
||||
value={settings.workStartTime}
|
||||
onChange={(value) => setSettings(prev => ({ ...prev, workStartTime: value }))}
|
||||
className="w-40"
|
||||
minuteStep={1}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>퇴근 시간</Label>
|
||||
<TimePicker
|
||||
value={settings.workEndTime}
|
||||
onChange={(value) => setSettings(prev => ({ ...prev, workEndTime: value }))}
|
||||
className="w-40"
|
||||
minuteStep={1}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 주당 근로시간 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">주당 근로시간</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-2 gap-6">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="weekly-hours">주당 기준 근로시간</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
id="weekly-hours"
|
||||
type="number"
|
||||
min={0}
|
||||
max={52}
|
||||
value={settings.weeklyWorkHours}
|
||||
onChange={(e) =>
|
||||
setSettings(prev => ({ ...prev, weeklyWorkHours: parseInt(e.target.value) || 0 }))
|
||||
}
|
||||
className="w-24"
|
||||
/>
|
||||
<span className="text-sm text-muted-foreground">시간</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="overtime-hours">주당 연장 근로시간</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
id="overtime-hours"
|
||||
type="number"
|
||||
min={0}
|
||||
max={52}
|
||||
value={settings.weeklyOvertimeHours}
|
||||
onChange={(e) =>
|
||||
setSettings(prev => ({ ...prev, weeklyOvertimeHours: parseInt(e.target.value) || 0 }))
|
||||
}
|
||||
className="w-24"
|
||||
/>
|
||||
<span className="text-sm text-muted-foreground">시간</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 1일 기준 휴게시간 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">1일 기준 휴게시간</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-2 gap-6">
|
||||
<div className="space-y-2">
|
||||
<Label>휴게 시작</Label>
|
||||
<TimePicker
|
||||
value={settings.breakStartTime}
|
||||
onChange={(value) => setSettings(prev => ({ ...prev, breakStartTime: value }))}
|
||||
className="w-40"
|
||||
minuteStep={1}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>휴게 종료</Label>
|
||||
<TimePicker
|
||||
value={settings.breakEndTime}
|
||||
onChange={(value) => setSettings(prev => ({ ...prev, breakEndTime: value }))}
|
||||
className="w-40"
|
||||
minuteStep={1}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 저장 버튼 */}
|
||||
<div className="flex justify-end">
|
||||
<Button onClick={handleSave} size="lg">
|
||||
<Save className="h-4 w-4 mr-2" />
|
||||
저장
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 안내 문구 */}
|
||||
<p className="text-sm text-muted-foreground">
|
||||
※ 근무 설정은 고용 형태별로 저장됩니다. 설정 변경 후 반드시 저장 버튼을 클릭하세요.
|
||||
</p>
|
||||
</div>
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
51
src/components/settings/WorkScheduleManagement/types.ts
Normal file
51
src/components/settings/WorkScheduleManagement/types.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* 근무관리 타입 정의 (PDF 56페이지 기준)
|
||||
*/
|
||||
|
||||
// 고용 형태
|
||||
export type EmploymentType = 'regular' | 'contract' | 'dispatch' | 'outsourcing' | 'partTime';
|
||||
|
||||
export const EMPLOYMENT_TYPE_LABELS: Record<EmploymentType, string> = {
|
||||
regular: '정규직',
|
||||
contract: '계약직',
|
||||
dispatch: '파견직',
|
||||
outsourcing: '용역직',
|
||||
partTime: '시간제 근로자',
|
||||
};
|
||||
|
||||
// 요일
|
||||
export type DayOfWeek = 'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat' | 'sun';
|
||||
|
||||
export const DAY_OF_WEEK_LABELS: Record<DayOfWeek, string> = {
|
||||
mon: '월',
|
||||
tue: '화',
|
||||
wed: '수',
|
||||
thu: '목',
|
||||
fri: '금',
|
||||
sat: '토',
|
||||
sun: '일',
|
||||
};
|
||||
|
||||
// 근무 설정
|
||||
export interface WorkScheduleSettings {
|
||||
employmentType: EmploymentType;
|
||||
workDays: DayOfWeek[]; // 주간 근무일
|
||||
workStartTime: string; // 출근 시간 (HH:mm)
|
||||
workEndTime: string; // 퇴근 시간 (HH:mm)
|
||||
weeklyWorkHours: number; // 주당 기준 근로시간
|
||||
weeklyOvertimeHours: number; // 주당 연장 근로시간
|
||||
breakStartTime: string; // 휴게 시작 시간 (HH:mm)
|
||||
breakEndTime: string; // 휴게 종료 시간 (HH:mm)
|
||||
}
|
||||
|
||||
// 기본 설정값
|
||||
export const DEFAULT_WORK_SCHEDULE: WorkScheduleSettings = {
|
||||
employmentType: 'regular',
|
||||
workDays: ['mon', 'tue', 'wed', 'thu', 'fri'],
|
||||
workStartTime: '09:00',
|
||||
workEndTime: '18:00',
|
||||
weeklyWorkHours: 40,
|
||||
weeklyOvertimeHours: 12,
|
||||
breakStartTime: '12:00',
|
||||
breakEndTime: '13:00',
|
||||
};
|
||||
@@ -181,7 +181,7 @@ export function IntegratedListTemplateV2<T = any>({
|
||||
};
|
||||
|
||||
return (
|
||||
<PageLayout devMetadata={devMetadata}>
|
||||
<PageLayout>
|
||||
{/* 페이지 헤더 */}
|
||||
<PageHeader
|
||||
title={title}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { ReactNode } from "react";
|
||||
import { ReactNode, ComponentType } from "react";
|
||||
import { LucideIcon } from "lucide-react";
|
||||
import { PageLayout } from "@/components/organisms/PageLayout";
|
||||
import { PageHeader } from "@/components/organisms/PageHeader";
|
||||
@@ -10,7 +10,7 @@ import { DataTable, Column } from "@/components/organisms/DataTable";
|
||||
import { EmptyState } from "@/components/organisms/EmptyState";
|
||||
import { MobileCard } from "@/components/organisms/MobileCard";
|
||||
|
||||
interface ListPageTemplateProps<T> {
|
||||
interface ListPageTemplateProps<T extends object> {
|
||||
// Header
|
||||
title: string;
|
||||
description?: string;
|
||||
@@ -50,7 +50,7 @@ interface ListPageTemplateProps<T> {
|
||||
icon?: ReactNode;
|
||||
badge?: { label: string; variant?: "default" | "secondary" | "destructive" | "outline" };
|
||||
fields: Array<{ label: string; value: string; badge?: boolean; badgeVariant?: string }>;
|
||||
actions?: Array<{ label: string; onClick: () => void; icon?: ReactNode; variant?: "default" | "outline" | "destructive" }>;
|
||||
actions?: Array<{ label: string; onClick: () => void; icon?: LucideIcon | ComponentType<any>; variant?: "default" | "outline" | "destructive" }>;
|
||||
};
|
||||
|
||||
// Empty State
|
||||
@@ -67,7 +67,7 @@ interface ListPageTemplateProps<T> {
|
||||
};
|
||||
}
|
||||
|
||||
export function ListPageTemplate<T>({
|
||||
export function ListPageTemplate<T extends object>({
|
||||
title,
|
||||
description,
|
||||
icon,
|
||||
|
||||
@@ -64,11 +64,10 @@ export function ResponsiveFormTemplate({
|
||||
<PageLayout maxWidth={maxWidth} versionInfo={versionInfo}>
|
||||
{/* 헤더 */}
|
||||
<PageHeader
|
||||
title={title}
|
||||
title={isEditMode ? `${title} 수정` : title}
|
||||
description={description}
|
||||
icon={icon}
|
||||
rightActions={headerActions}
|
||||
isEditMode={isEditMode}
|
||||
actions={headerActions}
|
||||
/>
|
||||
|
||||
{/* 메인 컨텐츠 */}
|
||||
|
||||
52
src/components/ui/scroll-area.tsx
Normal file
52
src/components/ui/scroll-area.tsx
Normal file
@@ -0,0 +1,52 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area";
|
||||
|
||||
import { cn } from "./utils";
|
||||
|
||||
function ScrollArea({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.Root
|
||||
data-slot="scroll-area"
|
||||
className={cn("relative overflow-hidden", className)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
|
||||
{children}
|
||||
</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollBar />
|
||||
<ScrollAreaPrimitive.Corner />
|
||||
</ScrollAreaPrimitive.Root>
|
||||
);
|
||||
}
|
||||
|
||||
function ScrollBar({
|
||||
className,
|
||||
orientation = "vertical",
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.ScrollAreaScrollbar
|
||||
data-slot="scroll-bar"
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"flex touch-none select-none transition-colors",
|
||||
orientation === "vertical" &&
|
||||
"h-full w-2.5 border-l border-l-transparent p-[1px]",
|
||||
orientation === "horizontal" &&
|
||||
"h-2.5 flex-col border-t border-t-transparent p-[1px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
|
||||
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
);
|
||||
}
|
||||
|
||||
export { ScrollArea, ScrollBar };
|
||||
@@ -13,8 +13,8 @@ import { cn } from "@/lib/utils";
|
||||
function Select({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
||||
// modal={false}로 설정하여 aria-hidden 충돌 방지
|
||||
return <SelectPrimitive.Root data-slot="select" modal={false} {...props} />;
|
||||
// aria-hidden 충돌 방지를 위해 props만 전달
|
||||
return <SelectPrimitive.Root data-slot="select" {...props} />;
|
||||
}
|
||||
|
||||
function SelectGroup({
|
||||
|
||||
@@ -6,11 +6,14 @@ import { XIcon } from "lucide-react";
|
||||
|
||||
import { cn } from "./utils";
|
||||
|
||||
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
|
||||
// modal={false}: aria-hidden이 sibling 요소에 설정되지 않도록 함
|
||||
// 사이드바 용도로는 modal 모드가 필요하지 않음 (focus trap 불필요)
|
||||
// 이렇게 하면 Select, Dialog 등 다른 Radix 컴포넌트와 충돌 방지
|
||||
return <SheetPrimitive.Root data-slot="sheet" modal={false} {...props} />;
|
||||
function Sheet({
|
||||
modal = true, // 기본값을 true로 변경 (딤 처리 및 포커스 트랩 활성화)
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Root> & { modal?: boolean }) {
|
||||
// modal={true}: 딤 처리, 포커스 트랩, ESC 키로 닫기 등 모달 동작 활성화
|
||||
// modal={false}: aria-hidden이 sibling 요소에 설정되지 않음, 다른 Radix 컴포넌트와 충돌 방지
|
||||
// 모바일 사이드바에서는 modal={true}가 필요 (딤 클릭으로 닫기 기능)
|
||||
return <SheetPrimitive.Root data-slot="sheet" modal={modal} {...props} />;
|
||||
}
|
||||
|
||||
function SheetTrigger({
|
||||
|
||||
190
src/components/ui/time-picker.tsx
Normal file
190
src/components/ui/time-picker.tsx
Normal file
@@ -0,0 +1,190 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { Clock } from "lucide-react";
|
||||
import { cn } from "./utils";
|
||||
import { Button } from "./button";
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "./popover";
|
||||
import { ScrollArea } from "./scroll-area";
|
||||
|
||||
interface TimePickerProps {
|
||||
value?: string; // "HH:mm" format
|
||||
onChange?: (value: string) => void;
|
||||
placeholder?: string;
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
/** 분 단위 간격 (기본값: 5) */
|
||||
minuteStep?: number;
|
||||
}
|
||||
|
||||
function TimePicker({
|
||||
value,
|
||||
onChange,
|
||||
placeholder = "시간 선택",
|
||||
disabled = false,
|
||||
className,
|
||||
minuteStep = 5,
|
||||
}: TimePickerProps) {
|
||||
const [open, setOpen] = React.useState(false);
|
||||
|
||||
// 현재 선택된 시/분 파싱
|
||||
const [selectedHour, selectedMinute] = React.useMemo(() => {
|
||||
if (!value) return [null, null];
|
||||
const [h, m] = value.split(":").map(Number);
|
||||
return [h, m];
|
||||
}, [value]);
|
||||
|
||||
// 시간 배열 생성 (0-23)
|
||||
const hours = Array.from({ length: 24 }, (_, i) => i);
|
||||
|
||||
// 분 배열 생성 (minuteStep 간격)
|
||||
const minutes = Array.from(
|
||||
{ length: Math.ceil(60 / minuteStep) },
|
||||
(_, i) => i * minuteStep
|
||||
);
|
||||
|
||||
// 시간 선택 핸들러
|
||||
const handleHourSelect = (hour: number) => {
|
||||
const minute = selectedMinute ?? 0;
|
||||
const newValue = `${hour.toString().padStart(2, "0")}:${minute.toString().padStart(2, "0")}`;
|
||||
onChange?.(newValue);
|
||||
};
|
||||
|
||||
// 분 선택 핸들러
|
||||
const handleMinuteSelect = (minute: number) => {
|
||||
const hour = selectedHour ?? 0;
|
||||
const newValue = `${hour.toString().padStart(2, "0")}:${minute.toString().padStart(2, "0")}`;
|
||||
onChange?.(newValue);
|
||||
};
|
||||
|
||||
// 표시할 시간 텍스트
|
||||
const displayValue = value || placeholder;
|
||||
|
||||
// 스크롤 영역 ref
|
||||
const hourScrollRef = React.useRef<HTMLDivElement>(null);
|
||||
const minuteScrollRef = React.useRef<HTMLDivElement>(null);
|
||||
|
||||
// 팝오버 열릴 때 선택된 시간으로 스크롤
|
||||
React.useEffect(() => {
|
||||
if (open) {
|
||||
setTimeout(() => {
|
||||
if (selectedHour !== null && hourScrollRef.current) {
|
||||
const hourElement = hourScrollRef.current.querySelector(
|
||||
`[data-hour="${selectedHour}"]`
|
||||
);
|
||||
hourElement?.scrollIntoView({ block: "center" });
|
||||
}
|
||||
if (selectedMinute !== null && minuteScrollRef.current) {
|
||||
const minuteElement = minuteScrollRef.current.querySelector(
|
||||
`[data-minute="${selectedMinute}"]`
|
||||
);
|
||||
minuteElement?.scrollIntoView({ block: "center" });
|
||||
}
|
||||
}, 0);
|
||||
}
|
||||
}, [open, selectedHour, selectedMinute]);
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={disabled}
|
||||
className={cn(
|
||||
"w-full justify-start text-left font-normal",
|
||||
!value && "text-muted-foreground",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<Clock className="mr-2 h-4 w-4" />
|
||||
{displayValue}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-0" align="start">
|
||||
<div className="p-3">
|
||||
{/* 헤더 */}
|
||||
<div className="text-center mb-3">
|
||||
<span className="text-lg font-bold">시간 선택</span>
|
||||
</div>
|
||||
|
||||
{/* 시간/분 선택 영역 */}
|
||||
<div className="flex gap-2">
|
||||
{/* 시간 선택 */}
|
||||
<div className="flex flex-col">
|
||||
<span className="text-xs text-muted-foreground text-center mb-1 font-semibold">
|
||||
시
|
||||
</span>
|
||||
<ScrollArea className="h-[200px] w-[70px] rounded-md border">
|
||||
<div className="p-1" ref={hourScrollRef}>
|
||||
{hours.map((hour) => (
|
||||
<button
|
||||
key={hour}
|
||||
data-hour={hour}
|
||||
onClick={() => handleHourSelect(hour)}
|
||||
className={cn(
|
||||
"w-full px-3 py-2 text-sm rounded-md transition-colors",
|
||||
"hover:bg-primary/10",
|
||||
selectedHour === hour
|
||||
? "bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground"
|
||||
: "text-foreground"
|
||||
)}
|
||||
>
|
||||
{hour.toString().padStart(2, "0")}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
{/* 구분자 */}
|
||||
<div className="flex items-center justify-center pt-5">
|
||||
<span className="text-2xl font-bold text-muted-foreground">:</span>
|
||||
</div>
|
||||
|
||||
{/* 분 선택 */}
|
||||
<div className="flex flex-col">
|
||||
<span className="text-xs text-muted-foreground text-center mb-1 font-semibold">
|
||||
분
|
||||
</span>
|
||||
<ScrollArea className="h-[200px] w-[70px] rounded-md border">
|
||||
<div className="p-1" ref={minuteScrollRef}>
|
||||
{minutes.map((minute) => (
|
||||
<button
|
||||
key={minute}
|
||||
data-minute={minute}
|
||||
onClick={() => handleMinuteSelect(minute)}
|
||||
className={cn(
|
||||
"w-full px-3 py-2 text-sm rounded-md transition-colors",
|
||||
"hover:bg-primary/10",
|
||||
selectedMinute === minute
|
||||
? "bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground"
|
||||
: "text-foreground"
|
||||
)}
|
||||
>
|
||||
{minute.toString().padStart(2, "0")}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 현재 선택된 시간 표시 */}
|
||||
{value && (
|
||||
<div className="mt-3 pt-3 border-t text-center">
|
||||
<span className="text-sm text-muted-foreground">선택: </span>
|
||||
<span className="text-sm font-semibold">{value}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
export { TimePicker };
|
||||
export type { TimePickerProps };
|
||||
@@ -460,7 +460,7 @@ interface ItemMasterContextType {
|
||||
reorderFields: (sectionId: number, fieldIds: number[]) => Promise<void>;
|
||||
|
||||
// BOM 관리
|
||||
addBOMItem: (sectionId: number, bomData: Omit<BOMItem, 'id' | 'created_at' | 'updated_at'>) => Promise<void>;
|
||||
addBOMItem: (sectionId: number, bomData: Omit<BOMItem, 'id' | 'created_at' | 'updated_at' | 'tenant_id' | 'section_id'>) => Promise<void>;
|
||||
updateBOMItem: (bomId: number, updates: Partial<BOMItem>) => Promise<void>;
|
||||
deleteBOMItem: (bomId: number) => Promise<void>;
|
||||
|
||||
@@ -1928,7 +1928,7 @@ export function ItemMasterProvider({ children }: { children: ReactNode }) {
|
||||
};
|
||||
|
||||
// BOM CRUD with API
|
||||
const addBOMItem = async (sectionId: number, bomData: Omit<BOMItem, 'id' | 'created_at' | 'updated_at'>) => {
|
||||
const addBOMItem = async (sectionId: number, bomData: Omit<BOMItem, 'id' | 'created_at' | 'updated_at' | 'tenant_id' | 'section_id'>) => {
|
||||
try {
|
||||
// API 호출 (null → undefined 변환)
|
||||
const response = await itemMasterApi.bomItems.create(sectionId, {
|
||||
|
||||
@@ -26,7 +26,7 @@ export interface ClientApiResponse {
|
||||
business_no: string | null;
|
||||
business_type: string | null;
|
||||
business_item: string | null;
|
||||
is_active: "Y" | "N";
|
||||
is_active: boolean;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
// 2차 추가 필드 (백엔드 완료 시 활성화)
|
||||
@@ -195,7 +195,7 @@ export function transformClientFromApi(api: ClientApiResponse): Client {
|
||||
businessType: api.business_type || "",
|
||||
businessItem: api.business_item || "",
|
||||
registeredDate: api.created_at ? api.created_at.split(" ")[0] : "",
|
||||
status: api.is_active === "Y" ? "활성" : "비활성",
|
||||
status: api.is_active ? "활성" : "비활성",
|
||||
groupId: api.client_group_id ? String(api.client_group_id) : null,
|
||||
// 2차 추가 필드
|
||||
clientType: api.client_type || "매입",
|
||||
@@ -234,7 +234,7 @@ export function transformClientToApiCreate(form: ClientFormData): Record<string,
|
||||
business_type: form.businessType || null,
|
||||
business_item: form.businessItem || null,
|
||||
client_group_id: form.groupId ? Number(form.groupId) : null,
|
||||
is_active: form.isActive ? "Y" : "N",
|
||||
is_active: form.isActive,
|
||||
// 2차 추가 필드
|
||||
client_type: form.clientType,
|
||||
mobile: form.mobile || null,
|
||||
@@ -271,7 +271,7 @@ export function transformClientToApiUpdate(form: ClientFormData): Record<string,
|
||||
business_type: form.businessType || null,
|
||||
business_item: form.businessItem || null,
|
||||
client_group_id: form.groupId ? Number(form.groupId) : null,
|
||||
is_active: form.isActive ? "Y" : "N",
|
||||
is_active: form.isActive,
|
||||
// 2차 추가 필드
|
||||
client_type: form.clientType,
|
||||
mobile: form.mobile || null,
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import type { ItemMaster } from '@/types/item';
|
||||
import type { ItemMaster, ItemType, PartType } from '@/types/item';
|
||||
import type { CustomTabResponse, TabColumnResponse } from '@/types/item-master-api';
|
||||
import { itemMasterApi } from '@/lib/api/item-master';
|
||||
|
||||
@@ -133,8 +133,8 @@ export function useItemList(): UseItemListResult {
|
||||
id: String(itemId ?? ''),
|
||||
itemCode: (item.code ?? item.item_code ?? '') as string,
|
||||
itemName: (item.name ?? item.item_name ?? '') as string,
|
||||
itemType: (item.type_code ?? item.item_type ?? '') as string,
|
||||
partType: item.part_type as string | undefined,
|
||||
itemType: (item.type_code ?? item.item_type ?? '') as ItemType,
|
||||
partType: item.part_type as PartType | undefined,
|
||||
unit: (item.unit ?? '') as string,
|
||||
specification: (item.specification ?? '') as string,
|
||||
// is_active가 null/undefined면 deleted_at 기준으로 판단 (삭제 안됐으면 활성)
|
||||
@@ -146,6 +146,7 @@ export function useItemList(): UseItemListResult {
|
||||
salesPrice: (item.sales_price ?? 0) as number,
|
||||
purchasePrice: (item.purchase_price ?? 0) as number,
|
||||
currentRevision: (item.current_revision ?? 0) as number,
|
||||
isFinal: Boolean(item.is_final ?? false),
|
||||
createdAt: (item.created_at ?? '') as string,
|
||||
updatedAt: (item.updated_at ?? '') as string,
|
||||
};
|
||||
|
||||
@@ -20,10 +20,13 @@ import {
|
||||
Package,
|
||||
Settings,
|
||||
DollarSign,
|
||||
ChevronLeft,
|
||||
Home,
|
||||
X,
|
||||
} from 'lucide-react';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet';
|
||||
import { Sheet, SheetContent, SheetTrigger, SheetHeader, SheetTitle } from '@/components/ui/sheet';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
@@ -195,6 +198,140 @@ export default function DashboardLayout({ children }: DashboardLayoutProps) {
|
||||
// By removing this check, we allow the component to render immediately with default values
|
||||
// and update once hydration completes through the useEffect above.
|
||||
|
||||
// 현재 페이지가 대시보드인지 확인
|
||||
const isDashboard = pathname?.includes('/dashboard') || activeMenu === 'dashboard';
|
||||
|
||||
// 이전 페이지로 이동
|
||||
const handleGoBack = () => {
|
||||
router.back();
|
||||
};
|
||||
|
||||
// 홈(대시보드)으로 이동
|
||||
const handleGoHome = () => {
|
||||
router.push('/dashboard');
|
||||
};
|
||||
|
||||
// 모바일 레이아웃
|
||||
if (isMobile) {
|
||||
return (
|
||||
<div className="min-h-screen flex flex-col">
|
||||
{/* 모바일 헤더 - sam-design 스타일 */}
|
||||
<header className="clean-glass sticky top-0 z-40 px-4 py-4 m-3 rounded-2xl clean-shadow">
|
||||
<div className="flex items-center justify-between">
|
||||
{/* 좌측 영역: 대시보드일 때는 로고, 다른 페이지일 때는 이전/홈 버튼 */}
|
||||
<div className="flex items-center space-x-3">
|
||||
{isDashboard ? (
|
||||
// 대시보드: 로고만 표시
|
||||
<div className="flex items-center space-x-3 ml-4">
|
||||
<div className="w-10 h-10 min-w-10 min-h-10 flex-shrink-0 aspect-square rounded-xl flex items-center justify-center shadow-md relative overflow-hidden bg-gradient-to-br from-blue-500 to-blue-600">
|
||||
<div className="text-white font-bold text-lg">S</div>
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="font-bold text-gray-900 text-left">SAM</h1>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
// 다른 페이지: 이전/홈 버튼 표시
|
||||
<div className="flex items-center space-x-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="min-w-[44px] min-h-[44px] p-0 rounded-xl hover:bg-accent transition-all duration-200 flex items-center justify-center"
|
||||
onClick={handleGoBack}
|
||||
title="이전 페이지"
|
||||
>
|
||||
<ChevronLeft className="h-5 w-5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="min-w-[44px] min-h-[44px] p-0 rounded-xl hover:bg-accent transition-all duration-200 flex items-center justify-center"
|
||||
onClick={handleGoHome}
|
||||
title="홈으로"
|
||||
>
|
||||
<Home className="h-5 w-5" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 우측 영역: 검색, 테마, 유저, 메뉴 */}
|
||||
<div className="flex items-center space-x-1">
|
||||
{/* 검색 아이콘 */}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="min-w-[44px] min-h-[44px] p-0 rounded-xl hover:bg-accent transition-all duration-200 flex items-center justify-center"
|
||||
>
|
||||
<Search className="h-5 w-5" />
|
||||
</Button>
|
||||
|
||||
{/* 테마 토글 */}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="min-w-[44px] min-h-[44px] p-0 rounded-xl hover:bg-accent transition-all duration-200 flex items-center justify-center">
|
||||
{theme === 'light' && <Sun className="h-5 w-5" />}
|
||||
{theme === 'dark' && <Moon className="h-5 w-5" />}
|
||||
{theme === 'senior' && <Accessibility className="h-5 w-5" />}
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => setTheme('light')}>
|
||||
<Sun className="mr-2 h-4 w-4" />
|
||||
일반모드
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setTheme('dark')}>
|
||||
<Moon className="mr-2 h-4 w-4" />
|
||||
다크모드
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setTheme('senior')}>
|
||||
<Accessibility className="mr-2 h-4 w-4" />
|
||||
시니어모드
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
{/* 유저 아이콘 */}
|
||||
<div className="min-w-[44px] min-h-[44px] w-11 h-11 bg-muted rounded-xl flex items-center justify-center clean-shadow-sm">
|
||||
<User className="h-4 w-4 text-primary" />
|
||||
</div>
|
||||
|
||||
{/* 햄버거 메뉴 - 맨 우측 */}
|
||||
<Sheet open={isMobileSidebarOpen} onOpenChange={setIsMobileSidebarOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="min-w-[44px] min-h-[44px] p-0 rounded-xl hover:bg-accent transition-all duration-200 flex items-center justify-center">
|
||||
<Menu className="h-6 w-6" />
|
||||
</Button>
|
||||
</SheetTrigger>
|
||||
<SheetContent side="right" className="w-80 p-1 bg-transparent border-none">
|
||||
<SheetHeader className="sr-only">
|
||||
<SheetTitle>메뉴</SheetTitle>
|
||||
</SheetHeader>
|
||||
<Sidebar
|
||||
menuItems={menuItems}
|
||||
activeMenu={activeMenu}
|
||||
expandedMenus={expandedMenus}
|
||||
sidebarCollapsed={false}
|
||||
isMobile={true}
|
||||
onMenuClick={handleMenuClick}
|
||||
onToggleSubmenu={toggleSubmenu}
|
||||
onCloseMobileSidebar={() => setIsMobileSidebarOpen(false)}
|
||||
/>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* 모바일 콘텐츠 */}
|
||||
<main className="flex-1 overflow-auto px-3">
|
||||
{children}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 데스크톱 레이아웃
|
||||
return (
|
||||
<div className="min-h-screen flex flex-col w-full">
|
||||
{/* 헤더 - 전체 너비 상단 고정 */}
|
||||
@@ -212,37 +349,15 @@ export default function DashboardLayout({ children }: DashboardLayoutProps) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Menu 버튼 - 모바일: Sheet 열기, 데스크톱: 사이드바 토글 */}
|
||||
{isMobile ? (
|
||||
<Sheet open={isMobileSidebarOpen} onOpenChange={setIsMobileSidebarOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="rounded-xl transition-all duration-200 hover:bg-accent p-3 md:hidden">
|
||||
<Menu className="h-5 w-5" />
|
||||
</Button>
|
||||
</SheetTrigger>
|
||||
<SheetContent side="left" className="w-64 p-4 bg-sidebar">
|
||||
<Sidebar
|
||||
menuItems={menuItems}
|
||||
activeMenu={activeMenu}
|
||||
expandedMenus={expandedMenus}
|
||||
sidebarCollapsed={false}
|
||||
isMobile={true}
|
||||
onMenuClick={handleMenuClick}
|
||||
onToggleSubmenu={toggleSubmenu}
|
||||
onCloseMobileSidebar={() => setIsMobileSidebarOpen(false)}
|
||||
/>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
) : (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={toggleSidebar}
|
||||
className="rounded-xl transition-all duration-200 hover:bg-accent p-3 hidden md:block"
|
||||
>
|
||||
<Menu className="h-5 w-5" />
|
||||
</Button>
|
||||
)}
|
||||
{/* Menu 버튼 - 사이드바 토글 */}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={toggleSidebar}
|
||||
className="rounded-xl transition-all duration-200 hover:bg-accent p-3"
|
||||
>
|
||||
<Menu className="h-5 w-5" />
|
||||
</Button>
|
||||
|
||||
{/* 검색바 */}
|
||||
<div className="relative hidden lg:block">
|
||||
@@ -310,9 +425,9 @@ export default function DashboardLayout({ children }: DashboardLayoutProps) {
|
||||
|
||||
{/* 사이드바 + 메인 콘텐츠 영역 */}
|
||||
<div className="flex flex-1 gap-3 px-3 pb-3">
|
||||
{/* 데스크톱 사이드바 (모바일에서 숨김) */}
|
||||
{/* 데스크톱 사이드바 */}
|
||||
<div
|
||||
className={`sticky top-[106px] self-start h-[calc(100vh-118px)] mt-3 border-none bg-transparent hidden md:block transition-all duration-300 flex-shrink-0 ${
|
||||
className={`sticky top-[106px] self-start h-[calc(100vh-118px)] mt-3 border-none bg-transparent transition-all duration-300 flex-shrink-0 ${
|
||||
sidebarCollapsed ? 'w-24' : 'w-64'
|
||||
}`}
|
||||
>
|
||||
|
||||
@@ -36,11 +36,15 @@ function getAuthToken(): string | null {
|
||||
*/
|
||||
function createFetchOptions(options: RequestInit = {}): RequestInit {
|
||||
const token = getAuthToken();
|
||||
const headers: HeadersInit = {
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers,
|
||||
};
|
||||
|
||||
// Merge existing headers if they are a plain object
|
||||
if (options.headers && typeof options.headers === 'object' && !Array.isArray(options.headers)) {
|
||||
Object.assign(headers, options.headers);
|
||||
}
|
||||
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
@@ -14,8 +14,9 @@ export type MaterialType = typeof MATERIAL_TYPES[number];
|
||||
/**
|
||||
* Material 타입인지 확인
|
||||
*/
|
||||
export function isMaterialType(itemType: string | null | undefined): boolean {
|
||||
return itemType ? MATERIAL_TYPES.includes(itemType as MaterialType) : false;
|
||||
export function isMaterialType(itemType: string | null | undefined): itemType is MaterialType {
|
||||
if (!itemType) return false;
|
||||
return (MATERIAL_TYPES as readonly string[]).includes(itemType);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -34,11 +35,13 @@ export function convertStandardFieldsToOptions(data: DynamicFormData): {
|
||||
const remainingData: DynamicFormData = {};
|
||||
|
||||
Object.entries(data).forEach(([key, value]) => {
|
||||
// standard_로 시작하는 필드 또는 옵션 관련 필드 탐지
|
||||
const isStandardField = key.startsWith('standard_') ||
|
||||
key.startsWith('option_') ||
|
||||
/^[0-9]+_standard_/.test(key) || // "{id}_standard_1" 형식
|
||||
/^[0-9]+_option_/.test(key); // "{id}_option_1" 형식
|
||||
// 규격 옵션 필드 탐지 (specification_*, standard_*, option_* 패턴)
|
||||
const isStandardField = key.startsWith('specification_') || // specification_1, specification_2
|
||||
key.startsWith('standard_') || // standard_1, standard_2
|
||||
key.startsWith('option_') || // option_1, option_2
|
||||
/^[0-9]+_specification_/.test(key) || // "{id}_specification_1" 형식
|
||||
/^[0-9]+_standard_/.test(key) || // "{id}_standard_1" 형식
|
||||
/^[0-9]+_option_/.test(key); // "{id}_option_1" 형식
|
||||
|
||||
if (isStandardField && value && typeof value === 'string' && value.trim()) {
|
||||
// standard_* 필드는 options 배열로 변환
|
||||
@@ -82,18 +85,29 @@ export function convertOptionsToStandardFields(
|
||||
* Material 저장 데이터 변환 (등록/수정 공통)
|
||||
*
|
||||
* 프론트엔드 폼 데이터를 백엔드 Material API 형식으로 변환
|
||||
*
|
||||
* - SM(철판), RM(원자재): standard_* 필드 조합으로 specification 자동 생성
|
||||
* - CS(소모품): spec 필드에 직접 입력한 값 사용
|
||||
*/
|
||||
export function transformMaterialDataForSave(
|
||||
data: DynamicFormData,
|
||||
itemType: string
|
||||
): DynamicFormData {
|
||||
// standard_* 필드들을 options 배열로 변환
|
||||
const { options, specification, remainingData } = convertStandardFieldsToOptions(data);
|
||||
const { options, specification: optionSpecification, remainingData } = convertStandardFieldsToOptions(data);
|
||||
|
||||
// Material 품목코드 생성: 품목명-규격(옵션조합)
|
||||
// CS(소모품)은 spec 필드 직접 입력, SM/RM은 옵션 조합
|
||||
const isConsumable = itemType === 'CS';
|
||||
const directSpec = (remainingData.spec || remainingData.specification || '') as string;
|
||||
const finalSpecification = isConsumable
|
||||
? (directSpec || null) // CS: 직접 입력한 spec 값 사용
|
||||
: (optionSpecification || null); // SM, RM: 옵션 조합값 사용
|
||||
|
||||
// Material 품목코드 생성: 품목명-규격
|
||||
const materialName = (remainingData.name || remainingData.item_name || '') as string;
|
||||
const specForCode = finalSpecification || '';
|
||||
const materialCode = remainingData.code ||
|
||||
(specification ? `${materialName}-${specification}` : materialName);
|
||||
(specForCode ? `${materialName}-${specForCode}` : materialName);
|
||||
|
||||
return {
|
||||
...remainingData,
|
||||
@@ -101,11 +115,12 @@ export function transformMaterialDataForSave(
|
||||
material_type: (remainingData.product_type as string) || itemType,
|
||||
remarks: remainingData.note as string, // note → remarks 변환
|
||||
material_code: materialCode,
|
||||
specification: specification || null, // 옵션 조합값을 specification으로 저장
|
||||
specification: finalSpecification, // CS: 직접 입력값, SM/RM: 옵션 조합값
|
||||
options: options.length > 0 ? options : null, // options 배열로 저장
|
||||
// 불필요한 필드 제거
|
||||
code: undefined,
|
||||
product_type: undefined,
|
||||
note: undefined,
|
||||
spec: undefined, // spec → specification으로 통합됨
|
||||
};
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ const itemNameSchema = z.preprocess(
|
||||
* 품목 유형 검증
|
||||
*/
|
||||
const itemTypeSchema = z.enum(['FG', 'PT', 'SM', 'RM', 'CS'], {
|
||||
errorMap: () => ({ message: '품목 유형을 선택해주세요' }),
|
||||
message: '품목 유형을 선택해주세요',
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
import { create } from 'zustand';
|
||||
import { devtools } from 'zustand/middleware';
|
||||
import { shallow } from 'zustand/shallow';
|
||||
import { useShallow } from 'zustand/react/shallow';
|
||||
import type { PageConfig, PageType, DynamicFormData } from '@/types/master-data';
|
||||
import { fetchPageConfigByType, invalidatePageConfigCache } from '@/lib/api/master-data';
|
||||
|
||||
@@ -63,12 +63,20 @@ interface MasterDataStore {
|
||||
|
||||
// ===== 초기 상태 =====
|
||||
|
||||
const createEmptyPageConfigs = (): Record<PageType, PageConfig | null> => ({
|
||||
'item-master': null,
|
||||
'quotation': null,
|
||||
'sales-order': null,
|
||||
'formula': null,
|
||||
'pricing': null,
|
||||
});
|
||||
|
||||
const initialState = {
|
||||
pageConfigs: {} as Record<PageType, PageConfig | null>,
|
||||
pageConfigs: createEmptyPageConfigs(),
|
||||
loading: {} as Record<PageType, boolean>,
|
||||
errors: {} as Record<PageType, string | null>,
|
||||
selectedPageType: null,
|
||||
formData: {},
|
||||
selectedPageType: null as PageType | null,
|
||||
formData: {} as Record<string, DynamicFormData>,
|
||||
};
|
||||
|
||||
// ===== sessionStorage 유틸리티 =====
|
||||
@@ -278,7 +286,7 @@ export const useMasterDataStore = create<MasterDataStore>()(
|
||||
});
|
||||
|
||||
set(
|
||||
{ pageConfigs: {} },
|
||||
{ pageConfigs: createEmptyPageConfigs() },
|
||||
false,
|
||||
'invalidateAllConfigs'
|
||||
);
|
||||
@@ -401,7 +409,7 @@ export const useSelectedPageType = () =>
|
||||
*/
|
||||
export const useMasterDataActions = () =>
|
||||
useMasterDataStore(
|
||||
(state) => ({
|
||||
useShallow((state) => ({
|
||||
fetchPageConfig: state.fetchPageConfig,
|
||||
invalidateConfig: state.invalidateConfig,
|
||||
invalidateAllConfigs: state.invalidateAllConfigs,
|
||||
@@ -410,8 +418,7 @@ export const useMasterDataActions = () =>
|
||||
getFormData: state.getFormData,
|
||||
clearFormData: state.clearFormData,
|
||||
reset: state.reset,
|
||||
}),
|
||||
shallow
|
||||
}))
|
||||
);
|
||||
|
||||
// ===== 타입 추출 =====
|
||||
|
||||
@@ -133,6 +133,7 @@ export interface ItemMaster {
|
||||
productCategory?: ProductCategory; // 제품 카테고리
|
||||
lotAbbreviation?: string; // 로트 약자 (예: "KD")
|
||||
note?: string; // 비고
|
||||
description?: string; // 설명
|
||||
|
||||
// === 부품(PT) 전용 필드 ===
|
||||
partType?: PartType; // 부품 유형
|
||||
|
||||
Reference in New Issue
Block a user