Merge remote-tracking branch 'origin/master'

# Conflicts:
#	src/components/hr/SalaryManagement/index.tsx
#	src/components/production/WorkResults/WorkResultList.tsx
#	tsconfig.tsbuildinfo
This commit is contained in:
2026-01-16 15:47:13 +09:00
91 changed files with 21969 additions and 20128 deletions

View File

@@ -20,13 +20,13 @@ import { TableRow, TableCell } from '@/components/ui/table';
import { format } from 'date-fns';
import { ko } from 'date-fns/locale';
import {
IntegratedListTemplateV2,
type TableColumn,
UniversalListPage,
type UniversalListConfig,
type StatCard,
type TabOption,
type FilterFieldConfig,
type FilterValues,
} from '@/components/templates/IntegratedListTemplateV2';
} from '@/components/templates/UniversalListPage';
import { DateRangeSelector } from '@/components/molecules/DateRangeSelector';
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
import { AttendanceInfoDialog } from './AttendanceInfoDialog';
@@ -260,7 +260,7 @@ export function AttendanceManagement() {
], [mergedRecords.length, stats]);
// 테이블 컬럼 정의
const tableColumns: TableColumn[] = useMemo(() => [
const tableColumns = useMemo(() => [
{ key: 'no', label: '번호', className: 'w-[60px] text-center' },
{ key: 'department', label: '부서', className: 'min-w-[80px]' },
{ key: 'position', label: '직책', className: 'min-w-[100px]' },
@@ -361,147 +361,6 @@ export function AttendanceManagement() {
}
}, [router]);
// 테이블 행 렌더링
const renderTableRow = useCallback((item: AttendanceRecord, index: number, globalIndex: number) => {
const isSelected = selectedItems.has(item.id);
return (
<TableRow
key={item.id}
className="hover:bg-muted/50"
>
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
<Checkbox
checked={isSelected}
onCheckedChange={() => toggleSelection(item.id)}
/>
</TableCell>
<TableCell className="text-center">{globalIndex}</TableCell>
<TableCell>{item.department || '-'}</TableCell>
<TableCell>{item.position || '-'}</TableCell>
<TableCell>{item.employeeName}</TableCell>
<TableCell>{item.rank || '-'}</TableCell>
<TableCell>
{item.baseDate ? format(new Date(item.baseDate), 'yyyy-MM-dd (E)', { locale: ko }) : '-'}
</TableCell>
<TableCell>{item.checkIn ? item.checkIn.substring(0, 5) : '-'}</TableCell>
<TableCell>{item.checkOut ? item.checkOut.substring(0, 5) : '-'}</TableCell>
<TableCell>{item.breakTime || '-'}</TableCell>
<TableCell>{item.overtimeHours || '-'}</TableCell>
<TableCell>
{item.reason ? (
<Button
variant="link"
size="sm"
className="p-0 h-auto text-blue-600 hover:text-blue-800"
onClick={() => handleReasonClick(item)}
>
{item.reason.label}
</Button>
) : '-'}
</TableCell>
<TableCell className="text-center">
{isSelected && (
<Button
variant="ghost"
size="sm"
onClick={() => handleEditAttendance(item)}
title="수정"
>
<Edit className="w-4 h-4" />
</Button>
)}
</TableCell>
</TableRow>
);
}, [selectedItems, toggleSelection, handleEditAttendance, handleReasonClick]);
// 모바일 카드 렌더링
const renderMobileCard = useCallback((
item: AttendanceRecord,
index: number,
globalIndex: number,
isSelected: boolean,
onToggle: () => void
) => {
return (
<ListMobileCard
id={item.id}
title={item.employeeName}
headerBadges={
<div className="flex items-center gap-2 flex-wrap">
<Badge variant="outline" className="text-xs">
{item.department || '-'}
</Badge>
<Badge variant="outline" className="text-xs">
{item.rank || '-'}
</Badge>
</div>
}
statusBadge={
<Badge className={ATTENDANCE_STATUS_COLORS[item.status]}>
{ATTENDANCE_STATUS_LABELS[item.status]}
</Badge>
}
isSelected={isSelected}
onToggleSelection={onToggle}
infoGrid={
<div className="grid grid-cols-2 gap-x-4 gap-y-3">
<InfoField label="직책" value={item.position || '-'} />
<InfoField
label="기준일"
value={item.baseDate ? format(new Date(item.baseDate), 'yyyy-MM-dd') : '-'}
/>
<InfoField label="출근" value={item.checkIn ? item.checkIn.substring(0, 5) : '-'} />
<InfoField label="퇴근" value={item.checkOut ? item.checkOut.substring(0, 5) : '-'} />
<InfoField label="휴게" value={item.breakTime || '-'} />
<InfoField label="연장근무" value={item.overtimeHours || '-'} />
{item.reason && (
<InfoField label="사유" value={item.reason.label} />
)}
</div>
}
actions={
isSelected ? (
<div className="flex gap-2 flex-wrap">
<Button
variant="default"
size="default"
className="flex-1 min-w-[100px] h-11"
onClick={(e) => { e.stopPropagation(); handleEditAttendance(item); }}
>
<Edit className="h-4 w-4 mr-2" />
</Button>
</div>
) : undefined
}
/>
);
}, [handleEditAttendance]);
// 헤더 액션 (DateRangeSelector + 버튼들)
const headerActions = (
<>
<DateRangeSelector
startDate={startDate}
endDate={endDate}
onStartDateChange={setStartDate}
onEndDateChange={setEndDate}
/>
<div className="ml-auto flex gap-2">
<Button variant="outline" onClick={handleExcelDownload}>
<Download className="w-4 h-4 mr-2" />
</Button>
<Button onClick={handleAddAttendance}>
<Plus className="w-4 h-4 mr-2" />
</Button>
</div>
</>
);
// ===== filterConfig 기반 통합 필터 시스템 =====
const filterConfig: FilterFieldConfig[] = useMemo(() => [
{
@@ -548,18 +407,271 @@ export function AttendanceManagement() {
setCurrentPage(1);
}, []);
// 검색 옆 추가 필터 (사유 등록 버튼)
const extraFilters = (
<div className="flex items-center gap-2 flex-wrap">
<Button variant="outline" onClick={handleAddReason}>
<FileText className="w-4 h-4 mr-2" />
</Button>
</div>
);
// ===== UniversalListPage 설정 =====
const attendanceConfig: UniversalListConfig<AttendanceRecord> = useMemo(() => ({
title: '근태관리',
description: '직원 출퇴근 및 근태 정보를 관리합니다',
icon: Clock,
basePath: '/hr/attendance-management',
// 페이지네이션 설정
const totalPages = Math.ceil(filteredRecords.length / itemsPerPage);
idField: 'id',
actions: {
getList: async () => ({
success: true,
data: mergedRecords,
totalCount: mergedRecords.length,
}),
},
columns: tableColumns,
tabs: tabs,
defaultTab: activeTab,
filterConfig: filterConfig,
initialFilters: filterValues,
filterTitle: '근태 필터',
computeStats: () => statCards,
dateRangeSelector: {
enabled: true,
showPresets: true,
startDate,
endDate,
onStartDateChange: setStartDate,
onEndDateChange: setEndDate,
},
createButton: {
label: '근태 등록',
icon: Plus,
onClick: handleAddAttendance,
},
searchPlaceholder: '이름, 부서 검색...',
extraFilters: (
<div className="flex items-center gap-2 flex-wrap">
<Button variant="outline" onClick={handleExcelDownload}>
<Download className="w-4 h-4 mr-2" />
</Button>
<Button variant="outline" onClick={handleAddReason}>
<FileText className="w-4 h-4 mr-2" />
</Button>
</div>
),
itemsPerPage: itemsPerPage,
clientSideFiltering: true,
searchFilter: (item, searchValue) => {
const search = searchValue.toLowerCase();
return (
item.employeeName.toLowerCase().includes(search) ||
item.department.toLowerCase().includes(search)
);
},
tabFilter: (item, activeTab) => {
if (activeTab === 'all') return true;
return item.status === activeTab;
},
customFilterFn: (items, filterValues) => {
let filtered = items;
const filterOption = filterValues.filter as string;
if (filterOption && filterOption !== 'all') {
filtered = filtered.filter(r => r.status === filterOption);
}
return filtered;
},
customSortFn: (items, filterValues) => {
const sortOption = filterValues.sort as SortOption || 'dateDesc';
return [...items].sort((a, b) => {
switch (sortOption) {
case 'dateDesc':
return new Date(b.baseDate).getTime() - new Date(a.baseDate).getTime();
case 'dateAsc':
return new Date(a.baseDate).getTime() - new Date(b.baseDate).getTime();
case 'rank':
return a.rank.localeCompare(b.rank, 'ko');
case 'deptAsc':
return a.department.localeCompare(b.department, 'ko');
case 'deptDesc':
return b.department.localeCompare(a.department, 'ko');
case 'nameAsc':
return a.employeeName.localeCompare(b.employeeName, 'ko');
case 'nameDesc':
return b.employeeName.localeCompare(a.employeeName, 'ko');
default:
return 0;
}
});
},
renderTableRow: (item, index, globalIndex, handlers) => {
const { isSelected, onToggle } = handlers;
return (
<TableRow
key={item.id}
className="hover:bg-muted/50"
>
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
<Checkbox
checked={isSelected}
onCheckedChange={onToggle}
/>
</TableCell>
<TableCell className="text-center">{globalIndex}</TableCell>
<TableCell>{item.department || '-'}</TableCell>
<TableCell>{item.position || '-'}</TableCell>
<TableCell>{item.employeeName}</TableCell>
<TableCell>{item.rank || '-'}</TableCell>
<TableCell>
{item.baseDate ? format(new Date(item.baseDate), 'yyyy-MM-dd (E)', { locale: ko }) : '-'}
</TableCell>
<TableCell>{item.checkIn ? item.checkIn.substring(0, 5) : '-'}</TableCell>
<TableCell>{item.checkOut ? item.checkOut.substring(0, 5) : '-'}</TableCell>
<TableCell>{item.breakTime || '-'}</TableCell>
<TableCell>{item.overtimeHours || '-'}</TableCell>
<TableCell>
{item.reason ? (
<Button
variant="link"
size="sm"
className="p-0 h-auto text-blue-600 hover:text-blue-800"
onClick={() => handleReasonClick(item)}
>
{item.reason.label}
</Button>
) : '-'}
</TableCell>
<TableCell className="text-center">
{isSelected && (
<Button
variant="ghost"
size="sm"
onClick={() => handleEditAttendance(item)}
title="수정"
>
<Edit className="w-4 h-4" />
</Button>
)}
</TableCell>
</TableRow>
);
},
renderMobileCard: (item, index, globalIndex, handlers) => {
const { isSelected, onToggle } = handlers;
return (
<ListMobileCard
id={item.id}
title={item.employeeName}
headerBadges={
<div className="flex items-center gap-2 flex-wrap">
<Badge variant="outline" className="text-xs">
{item.department || '-'}
</Badge>
<Badge variant="outline" className="text-xs">
{item.rank || '-'}
</Badge>
</div>
}
statusBadge={
<Badge className={ATTENDANCE_STATUS_COLORS[item.status]}>
{ATTENDANCE_STATUS_LABELS[item.status]}
</Badge>
}
isSelected={isSelected}
onToggleSelection={onToggle}
infoGrid={
<div className="grid grid-cols-2 gap-x-4 gap-y-3">
<InfoField label="직책" value={item.position || '-'} />
<InfoField
label="기준일"
value={item.baseDate ? format(new Date(item.baseDate), 'yyyy-MM-dd') : '-'}
/>
<InfoField label="출근" value={item.checkIn ? item.checkIn.substring(0, 5) : '-'} />
<InfoField label="퇴근" value={item.checkOut ? item.checkOut.substring(0, 5) : '-'} />
<InfoField label="휴게" value={item.breakTime || '-'} />
<InfoField label="연장근무" value={item.overtimeHours || '-'} />
{item.reason && (
<InfoField label="사유" value={item.reason.label} />
)}
</div>
}
actions={
isSelected ? (
<div className="flex gap-2 flex-wrap">
<Button
variant="default"
size="default"
className="flex-1 min-w-[100px] h-11"
onClick={(e) => { e.stopPropagation(); handleEditAttendance(item); }}
>
<Edit className="h-4 w-4 mr-2" />
</Button>
</div>
) : undefined
}
/>
);
},
renderDialogs: () => (
<>
{/* 근태 정보 다이얼로그 */}
<AttendanceInfoDialog
open={attendanceDialogOpen}
onOpenChange={setAttendanceDialogOpen}
mode={attendanceDialogMode}
attendance={selectedAttendance}
employees={employees}
onSave={handleSaveAttendance}
/>
{/* 사유 정보 다이얼로그 */}
<ReasonInfoDialog
open={reasonDialogOpen}
onOpenChange={setReasonDialogOpen}
employees={employees}
onSubmit={handleSubmitReason}
/>
</>
),
}), [
mergedRecords,
tableColumns,
tabs,
activeTab,
filterConfig,
filterValues,
statCards,
startDate,
endDate,
handleAddAttendance,
handleExcelDownload,
handleAddReason,
handleReasonClick,
handleEditAttendance,
attendanceDialogOpen,
attendanceDialogMode,
selectedAttendance,
employees,
handleSaveAttendance,
reasonDialogOpen,
handleSubmitReason,
]);
// 로딩 상태
if (isLoading) {
@@ -567,61 +679,10 @@ export function AttendanceManagement() {
}
return (
<>
<IntegratedListTemplateV2<AttendanceRecord>
title="근태관리"
description="직원 출퇴근 및 근태 정보를 관리합니다"
icon={Clock}
headerActions={headerActions}
stats={statCards}
searchValue={searchValue}
onSearchChange={setSearchValue}
searchPlaceholder="이름, 부서 검색..."
extraFilters={extraFilters}
filterConfig={filterConfig}
filterValues={filterValues}
onFilterChange={handleFilterChange}
onFilterReset={handleFilterReset}
filterTitle="근태 필터"
tabs={tabs}
activeTab={activeTab}
onTabChange={setActiveTab}
tableColumns={tableColumns}
data={paginatedData}
totalCount={filteredRecords.length}
allData={filteredRecords}
selectedItems={selectedItems}
onToggleSelection={toggleSelection}
onToggleSelectAll={toggleSelectAll}
getItemId={(item) => item.id}
renderTableRow={renderTableRow}
renderMobileCard={renderMobileCard}
pagination={{
currentPage,
totalPages,
totalItems: filteredRecords.length,
itemsPerPage,
onPageChange: setCurrentPage,
}}
/>
{/* 근태 정보 다이얼로그 */}
<AttendanceInfoDialog
open={attendanceDialogOpen}
onOpenChange={setAttendanceDialogOpen}
mode={attendanceDialogMode}
attendance={selectedAttendance}
employees={employees}
onSave={handleSaveAttendance}
/>
{/* 사유 정보 다이얼로그 */}
<ReasonInfoDialog
open={reasonDialogOpen}
onOpenChange={setReasonDialogOpen}
employees={employees}
onSubmit={handleSubmitReason}
/>
</>
<UniversalListPage<AttendanceRecord>
config={attendanceConfig}
initialData={mergedRecords}
initialTotalCount={mergedRecords.length}
/>
);
}

View File

@@ -0,0 +1,266 @@
'use client';
import { useMemo } from 'react';
import { CreditCard, Edit, Trash2, Plus } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { TableRow, TableCell } from '@/components/ui/table';
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
import {
UniversalListPage,
type UniversalListConfig,
type SelectionHandlers,
type RowClickHandlers,
} from '@/components/templates/UniversalListPage';
import type { Card } from './types';
import {
CARD_STATUS_LABELS,
CARD_STATUS_COLORS,
getCardCompanyLabel,
} from './types';
import { getCards, deleteCard, deleteCards } from './actions';
// 카드번호는 이미 마스킹되어 있음 (****-****-****-1234)
const maskCardNumber = (cardNumber: string): string => {
return cardNumber;
};
interface CardManagementUnifiedProps {
initialData?: Card[];
}
export function CardManagementUnified({ initialData }: CardManagementUnifiedProps) {
// UniversalListPage Config 정의
const config: UniversalListConfig<Card> = useMemo(() => ({
// ===== 페이지 기본 정보 =====
title: '카드관리',
description: '카드 목록을 관리합니다',
icon: CreditCard,
basePath: '/hr/card-management',
// ===== ID 추출 =====
idField: 'id',
// ===== API 액션 =====
actions: {
getList: async () => {
const result = await getCards({ per_page: 100 });
return {
success: result.success,
data: result.data,
totalCount: result.data?.length || 0,
error: result.error,
};
},
deleteItem: async (id: string) => {
return await deleteCard(id);
},
deleteBulk: async (ids: string[]) => {
return await deleteCards(ids);
},
},
// ===== 테이블 컬럼 =====
columns: [
{ key: 'rowNumber', label: '번호', className: 'w-[60px] text-center' },
{ key: 'cardCompany', label: '카드사', className: 'min-w-[100px]' },
{ key: 'cardNumber', label: '카드번호', className: 'min-w-[160px]' },
{ key: 'cardName', label: '카드명', className: 'min-w-[120px]' },
{ key: 'status', label: '상태', className: 'min-w-[80px]' },
{ key: 'department', label: '부서', className: 'min-w-[100px]' },
{ key: 'userName', label: '사용자', className: 'min-w-[100px]' },
{ key: 'position', label: '직책', className: 'min-w-[100px]' },
{ key: 'actions', label: '작업', className: 'w-[100px] text-right' },
],
// ===== 클라이언트 사이드 필터링 =====
clientSideFiltering: true,
// 탭 필터 함수
tabFilter: (item: Card, activeTab: string) => {
if (activeTab === 'all') return true;
return item.status === activeTab;
},
// 검색 필터 함수
searchFilter: (item: Card, searchValue: string) => {
const search = searchValue.toLowerCase();
return (
item.cardName.toLowerCase().includes(search) ||
item.cardNumber.includes(search) ||
getCardCompanyLabel(item.cardCompany).toLowerCase().includes(search) ||
(item.user?.employeeName.toLowerCase().includes(search) || false)
);
},
// ===== 탭 설정 (데이터 기반으로 count 업데이트) =====
tabs: [
{ value: 'all', label: '전체', count: 0, color: 'gray' },
{ value: 'active', label: '사용', count: 0, color: 'green' },
{ value: 'suspended', label: '정지', count: 0, color: 'red' },
],
// ===== 검색 설정 =====
searchPlaceholder: '카드명, 카드번호, 카드사, 사용자 검색...',
// ===== 상세 보기 모드 =====
detailMode: 'page',
// ===== 헤더 액션 =====
headerActions: ({ onCreate }) => (
<Button className="ml-auto" onClick={onCreate}>
<Plus className="w-4 h-4 mr-2" />
</Button>
),
// ===== 삭제 확인 메시지 =====
deleteConfirmMessage: {
title: '카드 삭제',
description: '삭제된 카드 정보는 복구할 수 없습니다.',
},
// ===== 테이블 행 렌더링 =====
renderTableRow: (
item: Card,
index: number,
globalIndex: number,
handlers: SelectionHandlers & RowClickHandlers<Card>
) => {
const { isSelected, onToggle, onRowClick, onEdit, onDelete } = handlers;
return (
<TableRow
key={item.id}
className="hover:bg-muted/50 cursor-pointer"
onClick={() => onRowClick(item)}
>
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
<Checkbox
checked={isSelected}
onCheckedChange={onToggle}
/>
</TableCell>
<TableCell className="text-muted-foreground text-center">
{globalIndex}
</TableCell>
<TableCell>{getCardCompanyLabel(item.cardCompany)}</TableCell>
<TableCell className="font-mono">{maskCardNumber(item.cardNumber)}</TableCell>
<TableCell>{item.cardName}</TableCell>
<TableCell>
<Badge className={CARD_STATUS_COLORS[item.status]}>
{CARD_STATUS_LABELS[item.status]}
</Badge>
</TableCell>
<TableCell>{item.user?.departmentName || '-'}</TableCell>
<TableCell>{item.user?.employeeName || '-'}</TableCell>
<TableCell>{item.user?.positionName || '-'}</TableCell>
<TableCell className="text-right" onClick={(e) => e.stopPropagation()}>
{isSelected && (
<div className="flex items-center justify-end gap-1">
<Button
variant="ghost"
size="sm"
onClick={() => onEdit?.(item)}
title="수정"
>
<Edit className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => onDelete?.(item)}
title="삭제"
>
<Trash2 className="w-4 h-4 text-red-500" />
</Button>
</div>
)}
</TableCell>
</TableRow>
);
},
// ===== 모바일 카드 렌더링 =====
renderMobileCard: (
item: Card,
index: number,
globalIndex: number,
handlers: SelectionHandlers & RowClickHandlers<Card>
) => {
const { isSelected, onToggle, onRowClick, onEdit, onDelete } = handlers;
return (
<ListMobileCard
key={item.id}
id={item.id}
title={item.cardName}
headerBadges={
<div className="flex items-center gap-2 flex-wrap">
<Badge variant="outline" className="text-xs">
#{globalIndex}
</Badge>
<span className="text-xs text-muted-foreground">
{getCardCompanyLabel(item.cardCompany)}
</span>
</div>
}
statusBadge={
<Badge className={CARD_STATUS_COLORS[item.status]}>
{CARD_STATUS_LABELS[item.status]}
</Badge>
}
isSelected={isSelected}
onToggleSelection={onToggle}
onCardClick={() => onRowClick(item)}
infoGrid={
<div className="grid grid-cols-2 gap-x-4 gap-y-3">
<InfoField label="카드번호" value={maskCardNumber(item.cardNumber)} />
<InfoField label="유효기간" value={`${item.expiryDate.slice(0, 2)}/${item.expiryDate.slice(2)}`} />
<InfoField label="부서" value={item.user?.departmentName || '-'} />
<InfoField label="사용자" value={item.user?.employeeName || '-'} />
<InfoField label="직책" value={item.user?.positionName || '-'} />
</div>
}
actions={
isSelected ? (
<div className="flex gap-2 flex-wrap">
<Button
variant="default"
size="default"
className="flex-1 min-w-[100px] h-11"
onClick={(e) => { e.stopPropagation(); onEdit?.(item); }}
>
<Edit className="h-4 w-4 mr-2" />
</Button>
<Button
variant="outline"
size="default"
className="flex-1 min-w-[100px] h-11 border-red-200 text-red-600 hover:border-red-300 bg-transparent"
onClick={(e) => { e.stopPropagation(); onDelete?.(item); }}
>
<Trash2 className="h-4 w-4 mr-2" />
</Button>
</div>
) : undefined
}
/>
);
},
// ===== 추가 옵션 =====
showCheckbox: true,
showRowNumber: true,
itemsPerPage: 20,
}), []);
return (
<UniversalListPage<Card>
config={config}
initialData={initialData}
/>
);
}

View File

@@ -18,10 +18,10 @@ import {
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import {
IntegratedListTemplateV2,
UniversalListPage,
type UniversalListConfig,
type TabOption,
type TableColumn,
} from '@/components/templates/IntegratedListTemplateV2';
} from '@/components/templates/UniversalListPage';
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
import { toast } from 'sonner';
import type { Card } from './types';
@@ -121,7 +121,7 @@ export function CardManagement({ initialData }: CardManagementProps) {
], [cards.length, stats]);
// 테이블 컬럼 정의
const tableColumns: TableColumn[] = useMemo(() => [
const tableColumns = useMemo(() => [
{ key: 'rowNumber', label: '번호', className: 'w-[60px] text-center' },
{ key: 'cardCompany', label: '카드사', className: 'min-w-[100px]' },
{ key: 'cardNumber', label: '카드번호', className: 'min-w-[160px]' },
@@ -201,174 +201,184 @@ export function CardManagement({ initialData }: CardManagementProps) {
setDeleteDialogOpen(true);
}, []);
// 테이블 행 렌더링
const renderTableRow = useCallback((item: Card, index: number, globalIndex: number) => {
const isSelected = selectedItems.has(item.id);
// ===== UniversalListPage 설정 =====
const cardManagementConfig: UniversalListConfig<Card> = useMemo(() => ({
title: '카드관리',
description: '카드 목록을 관리합니다',
icon: CreditCard,
basePath: '/hr/card-management',
return (
<TableRow
key={item.id}
className="hover:bg-muted/50 cursor-pointer"
onClick={() => handleRowClick(item)}
>
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
<Checkbox
checked={isSelected}
onCheckedChange={() => toggleSelection(item.id)}
/>
</TableCell>
<TableCell className="text-muted-foreground text-center">
{globalIndex}
</TableCell>
<TableCell>{getCardCompanyLabel(item.cardCompany)}</TableCell>
<TableCell className="font-mono">{maskCardNumber(item.cardNumber)}</TableCell>
<TableCell>{item.cardName}</TableCell>
<TableCell>
<Badge className={CARD_STATUS_COLORS[item.status]}>
{CARD_STATUS_LABELS[item.status]}
</Badge>
</TableCell>
<TableCell>{item.user?.departmentName || '-'}</TableCell>
<TableCell>{item.user?.employeeName || '-'}</TableCell>
<TableCell>{item.user?.positionName || '-'}</TableCell>
<TableCell className="text-right" onClick={(e) => e.stopPropagation()}>
{isSelected && (
<div className="flex items-center justify-end gap-1">
<Button
variant="ghost"
size="sm"
onClick={() => handleEdit(item.id)}
title="수정"
>
<Edit className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => openDeleteDialog(item)}
title="삭제"
>
<Trash2 className="w-4 h-4 text-red-500" />
</Button>
</div>
)}
</TableCell>
</TableRow>
);
}, [selectedItems, toggleSelection, handleRowClick, handleEdit, openDeleteDialog]);
idField: 'id',
// 모바일 카드 렌더링
const renderMobileCard = useCallback((
item: Card,
index: number,
globalIndex: number,
isSelected: boolean,
onToggle: () => void
) => {
return (
<ListMobileCard
id={item.id}
title={item.cardName}
headerBadges={
<div className="flex items-center gap-2 flex-wrap">
<Badge variant="outline" className="text-xs">
#{globalIndex}
actions: {
getList: async () => ({
success: true,
data: cards,
totalCount: cards.length,
}),
deleteBulk: async (ids) => {
const result = await deleteCards(ids);
if (result.success) {
setCards(prev => prev.filter(card => !ids.includes(card.id)));
setSelectedItems(new Set());
toast.success('선택한 카드가 삭제되었습니다.');
} else {
toast.error(result.error || '삭제에 실패했습니다.');
}
return result;
},
},
columns: tableColumns,
tabs: tabs,
defaultTab: activeTab,
createButton: {
label: '카드 등록',
icon: Plus,
onClick: handleAddCard,
},
searchPlaceholder: '카드명, 카드번호, 카드사, 사용자 검색...',
itemsPerPage: itemsPerPage,
clientSideFiltering: true,
searchFilter: (item, searchValue) => {
const search = searchValue.toLowerCase();
return (
item.cardName.toLowerCase().includes(search) ||
item.cardNumber.includes(search) ||
getCardCompanyLabel(item.cardCompany).toLowerCase().includes(search) ||
(item.user?.employeeName?.toLowerCase().includes(search) ?? false)
);
},
tabFilter: (item, activeTab) => {
if (activeTab === 'all') return true;
return item.status === activeTab;
},
renderTableRow: (item, index, globalIndex, handlers) => {
const { isSelected, onToggle, onRowClick } = handlers;
return (
<TableRow
key={item.id}
className="hover:bg-muted/50 cursor-pointer"
onClick={() => handleRowClick(item)}
>
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
<Checkbox
checked={isSelected}
onCheckedChange={onToggle}
/>
</TableCell>
<TableCell className="text-muted-foreground text-center">
{globalIndex}
</TableCell>
<TableCell>{getCardCompanyLabel(item.cardCompany)}</TableCell>
<TableCell className="font-mono">{maskCardNumber(item.cardNumber)}</TableCell>
<TableCell>{item.cardName}</TableCell>
<TableCell>
<Badge className={CARD_STATUS_COLORS[item.status]}>
{CARD_STATUS_LABELS[item.status]}
</Badge>
<span className="text-xs text-muted-foreground">
{getCardCompanyLabel(item.cardCompany)}
</span>
</div>
}
statusBadge={
<Badge className={CARD_STATUS_COLORS[item.status]}>
{CARD_STATUS_LABELS[item.status]}
</Badge>
}
isSelected={isSelected}
onToggleSelection={onToggle}
onCardClick={() => handleRowClick(item)}
infoGrid={
<div className="grid grid-cols-2 gap-x-4 gap-y-3">
<InfoField label="카드번호" value={maskCardNumber(item.cardNumber)} />
<InfoField label="유효기간" value={`${item.expiryDate.slice(0, 2)}/${item.expiryDate.slice(2)}`} />
<InfoField label="부서" value={item.user?.departmentName || '-'} />
<InfoField label="사용자" value={item.user?.employeeName || '-'} />
<InfoField label="직책" value={item.user?.positionName || '-'} />
</div>
}
actions={
isSelected ? (
<div className="flex gap-2 flex-wrap">
<Button
variant="default"
size="default"
className="flex-1 min-w-[100px] h-11"
onClick={(e) => { e.stopPropagation(); handleEdit(item.id); }}
>
<Edit className="h-4 w-4 mr-2" />
</Button>
<Button
variant="outline"
size="default"
className="flex-1 min-w-[100px] h-11 border-red-200 text-red-600 hover:border-red-300 bg-transparent"
onClick={(e) => { e.stopPropagation(); openDeleteDialog(item); }}
>
<Trash2 className="h-4 w-4 mr-2" />
</Button>
</TableCell>
<TableCell>{item.user?.departmentName || '-'}</TableCell>
<TableCell>{item.user?.employeeName || '-'}</TableCell>
<TableCell>{item.user?.positionName || '-'}</TableCell>
<TableCell className="text-right" onClick={(e) => e.stopPropagation()}>
{isSelected && (
<div className="flex items-center justify-end gap-1">
<Button
variant="ghost"
size="sm"
onClick={() => handleEdit(item.id)}
title="수정"
>
<Edit className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => openDeleteDialog(item)}
title="삭제"
>
<Trash2 className="w-4 h-4 text-red-500" />
</Button>
</div>
)}
</TableCell>
</TableRow>
);
},
renderMobileCard: (item, index, globalIndex, handlers) => {
const { isSelected, onToggle } = handlers;
return (
<ListMobileCard
id={item.id}
title={item.cardName}
headerBadges={
<div className="flex items-center gap-2 flex-wrap">
<Badge variant="outline" className="text-xs">
#{globalIndex}
</Badge>
<span className="text-xs text-muted-foreground">
{getCardCompanyLabel(item.cardCompany)}
</span>
</div>
) : undefined
}
/>
);
}, [handleRowClick, handleEdit, openDeleteDialog]);
}
statusBadge={
<Badge className={CARD_STATUS_COLORS[item.status]}>
{CARD_STATUS_LABELS[item.status]}
</Badge>
}
isSelected={isSelected}
onToggleSelection={onToggle}
onCardClick={() => handleRowClick(item)}
infoGrid={
<div className="grid grid-cols-2 gap-x-4 gap-y-3">
<InfoField label="카드번호" value={maskCardNumber(item.cardNumber)} />
<InfoField label="유효기간" value={`${item.expiryDate.slice(0, 2)}/${item.expiryDate.slice(2)}`} />
<InfoField label="부서" value={item.user?.departmentName || '-'} />
<InfoField label="사용자" value={item.user?.employeeName || '-'} />
<InfoField label="직책" value={item.user?.positionName || '-'} />
</div>
}
actions={
isSelected ? (
<div className="flex gap-2 flex-wrap">
<Button
variant="default"
size="default"
className="flex-1 min-w-[100px] h-11"
onClick={(e) => { e.stopPropagation(); handleEdit(item.id); }}
>
<Edit className="h-4 w-4 mr-2" />
</Button>
<Button
variant="outline"
size="default"
className="flex-1 min-w-[100px] h-11 border-red-200 text-red-600 hover:border-red-300 bg-transparent"
onClick={(e) => { e.stopPropagation(); openDeleteDialog(item); }}
>
<Trash2 className="h-4 w-4 mr-2" />
</Button>
</div>
) : undefined
}
/>
);
},
// 헤더 액션
const headerActions = (
<Button className="ml-auto" onClick={handleAddCard}>
<Plus className="w-4 h-4 mr-2" />
</Button>
);
// 페이지네이션 설정
const totalPages = Math.ceil(filteredCards.length / itemsPerPage);
return (
<>
<IntegratedListTemplateV2<Card>
title="카드관리"
description="카드 목록을 관리합니다"
icon={CreditCard}
headerActions={headerActions}
searchValue={searchValue}
onSearchChange={setSearchValue}
searchPlaceholder="카드명, 카드번호, 카드사, 사용자 검색..."
tabs={tabs}
activeTab={activeTab}
onTabChange={setActiveTab}
tableColumns={tableColumns}
data={paginatedData}
totalCount={filteredCards.length}
allData={filteredCards}
selectedItems={selectedItems}
onToggleSelection={toggleSelection}
onToggleSelectAll={toggleSelectAll}
onBulkDelete={handleBulkDelete}
getItemId={(item) => item.id}
renderTableRow={renderTableRow}
renderMobileCard={renderMobileCard}
pagination={{
currentPage,
totalPages,
totalItems: filteredCards.length,
itemsPerPage,
onPageChange: setCurrentPage,
}}
/>
{/* 삭제 확인 다이얼로그 */}
renderDialogs: () => (
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
@@ -392,6 +402,26 @@ export function CardManagement({ initialData }: CardManagementProps) {
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
),
}), [
cards,
tableColumns,
tabs,
activeTab,
handleAddCard,
handleRowClick,
handleEdit,
openDeleteDialog,
deleteDialogOpen,
cardToDelete,
handleDeleteCard,
]);
return (
<UniversalListPage<Card>
config={cardManagementConfig}
initialData={cards}
initialTotalCount={cards.length}
/>
);
}

View File

@@ -19,13 +19,13 @@ import {
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import {
IntegratedListTemplateV2,
UniversalListPage,
type UniversalListConfig,
type TabOption,
type TableColumn,
type StatCard,
type FilterFieldConfig,
type FilterValues,
} from '@/components/templates/IntegratedListTemplateV2';
} from '@/components/templates/UniversalListPage';
import { DateRangeSelector } from '@/components/molecules/DateRangeSelector';
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
import { FieldSettingsDialog } from './FieldSettingsDialog';
@@ -255,7 +255,7 @@ export function EmployeeManagement() {
], [employees.length, stats]);
// 테이블 컬럼 정의
const tableColumns: TableColumn[] = useMemo(() => [
const tableColumns = useMemo(() => [
{ key: 'rowNumber', label: '번호', className: 'w-[60px] text-center' },
{ key: 'employeeCode', label: '사원코드', className: 'min-w-[100px]' },
{ key: 'department', label: '부서', className: 'min-w-[100px]' },
@@ -359,194 +359,6 @@ export function EmployeeManagement() {
setDeleteDialogOpen(true);
}, []);
// 테이블 행 렌더링
const renderTableRow = useCallback((item: Employee, index: number, globalIndex: number) => {
const isSelected = selectedItems.has(item.id);
return (
<TableRow
key={item.id}
className="hover:bg-muted/50 cursor-pointer"
onClick={() => handleRowClick(item)}
>
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
<Checkbox
checked={isSelected}
onCheckedChange={() => toggleSelection(item.id)}
/>
</TableCell>
<TableCell className="text-muted-foreground text-center">
{globalIndex}
</TableCell>
<TableCell>{item.employeeCode || '-'}</TableCell>
<TableCell>
{item.departmentPositions?.length > 0
? item.departmentPositions.map(dp => dp.departmentName).join(', ')
: '-'}
</TableCell>
<TableCell>
{item.departmentPositions?.length > 0
? item.departmentPositions.map(dp => dp.positionName).join(', ')
: '-'}
</TableCell>
<TableCell>{item.name}</TableCell>
<TableCell>{item.rank || '-'}</TableCell>
<TableCell>{item.phone || '-'}</TableCell>
<TableCell>{item.email || '-'}</TableCell>
<TableCell>
{item.hireDate ? new Date(item.hireDate).toLocaleDateString('ko-KR') : '-'}
</TableCell>
<TableCell>
<Badge className={EMPLOYEE_STATUS_COLORS[item.status]}>
{EMPLOYEE_STATUS_LABELS[item.status]}
</Badge>
</TableCell>
<TableCell>{item.userInfo?.userId || '-'}</TableCell>
<TableCell>
{item.userInfo ? USER_ROLE_LABELS[item.userInfo.role] : '-'}
</TableCell>
<TableCell className="text-right" onClick={(e) => e.stopPropagation()}>
{isSelected && (
<div className="flex items-center justify-end gap-1">
<Button
variant="ghost"
size="sm"
onClick={() => handleEdit(item.id)}
title="수정"
>
<Edit className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => openDeleteDialog(item)}
title="삭제"
>
<Trash2 className="w-4 h-4 text-red-500" />
</Button>
</div>
)}
</TableCell>
</TableRow>
);
}, [selectedItems, toggleSelection, handleRowClick, handleEdit, openDeleteDialog]);
// 모바일 카드 렌더링
const renderMobileCard = useCallback((
item: Employee,
index: number,
globalIndex: number,
isSelected: boolean,
onToggle: () => void
) => {
return (
<ListMobileCard
id={item.id}
title={item.name}
headerBadges={
<div className="flex items-center gap-2 flex-wrap">
<Badge variant="outline" className="text-xs">
#{globalIndex}
</Badge>
<code className="text-xs bg-gray-100 px-2 py-1 rounded">
{item.employeeCode}
</code>
</div>
}
statusBadge={
<Badge className={EMPLOYEE_STATUS_COLORS[item.status]}>
{EMPLOYEE_STATUS_LABELS[item.status]}
</Badge>
}
isSelected={isSelected}
onToggleSelection={onToggle}
onCardClick={() => handleRowClick(item)}
infoGrid={
<div className="grid grid-cols-2 gap-x-4 gap-y-3">
<InfoField
label="부서"
value={item.departmentPositions?.length > 0
? item.departmentPositions.map(dp => dp.departmentName).join(', ')
: '-'}
/>
<InfoField
label="직책"
value={item.departmentPositions?.length > 0
? item.departmentPositions.map(dp => dp.positionName).join(', ')
: '-'}
/>
<InfoField label="직급" value={item.rank || '-'} />
<InfoField label="휴대폰" value={item.phone || '-'} />
<InfoField label="이메일" value={item.email || '-'} />
<InfoField
label="입사일"
value={item.hireDate ? new Date(item.hireDate).toLocaleDateString('ko-KR') : '-'}
/>
{item.userInfo && (
<>
<InfoField label="사용자ID" value={item.userInfo.userId || '-'} />
<InfoField label="권한" value={USER_ROLE_LABELS[item.userInfo.role]} />
</>
)}
</div>
}
actions={
isSelected ? (
<div className="flex gap-2 flex-wrap">
<Button
variant="default"
size="default"
className="flex-1 min-w-[100px] h-11"
onClick={(e) => { e.stopPropagation(); handleEdit(item.id); }}
>
<Edit className="h-4 w-4 mr-2" />
</Button>
<Button
variant="outline"
size="default"
className="flex-1 min-w-[100px] h-11 border-red-200 text-red-600 hover:border-red-300 bg-transparent"
onClick={(e) => { e.stopPropagation(); openDeleteDialog(item); }}
>
<Trash2 className="h-4 w-4 mr-2" />
</Button>
</div>
) : undefined
}
/>
);
}, [handleRowClick, handleEdit, openDeleteDialog]);
// 헤더 액션 (DateRangeSelector + 버튼들)
const headerActions = (
<>
<DateRangeSelector
startDate={startDate}
endDate={endDate}
onStartDateChange={setStartDate}
onEndDateChange={setEndDate}
/>
<div className="ml-auto flex gap-2">
<Button
variant="outline"
onClick={() => setUserInviteOpen(true)}
>
<Mail className="w-4 h-4 mr-2" />
</Button>
<Button variant="outline" onClick={handleCSVUpload}>
<Upload className="w-4 h-4 mr-2" />
CSV
</Button>
<Button onClick={handleAddEmployee}>
<Plus className="w-4 h-4 mr-2" />
</Button>
</div>
</>
);
// ===== filterConfig 기반 통합 필터 시스템 =====
const filterConfig: FilterFieldConfig[] = useMemo(() => [
{
@@ -593,99 +405,389 @@ export function EmployeeManagement() {
setCurrentPage(1);
}, []);
// 페이지네이션 설정
const totalPages = Math.ceil(filteredEmployees.length / itemsPerPage);
// ===== UniversalListPage 설정 =====
const employeeConfig: UniversalListConfig<Employee> = useMemo(() => ({
title: '사원관리',
description: '사원 정보를 관리합니다',
icon: Users,
basePath: '/hr/employee-management',
idField: 'id',
actions: {
getList: async () => ({
success: true,
data: employees,
totalCount: employees.length,
}),
deleteBulk: async (ids) => {
setIsDeleting(true);
try {
const result = await deleteEmployees(ids);
if (result.success) {
setEmployees(prev => prev.filter(emp => !ids.includes(emp.id)));
setSelectedItems(new Set());
}
return result;
} finally {
setIsDeleting(false);
}
},
},
columns: tableColumns,
tabs: tabs,
defaultTab: activeTab,
filterConfig: filterConfig,
initialFilters: filterValues,
filterTitle: '사원 필터',
computeStats: () => statCards,
dateRangeSelector: {
enabled: true,
showPresets: true,
startDate,
endDate,
onStartDateChange: setStartDate,
onEndDateChange: setEndDate,
},
createButton: {
label: '사원 등록',
icon: Plus,
onClick: handleAddEmployee,
},
searchPlaceholder: '이름, 사원코드, 이메일 검색...',
extraFilters: (
<div className="flex gap-2">
<Button
variant="outline"
onClick={() => setUserInviteOpen(true)}
>
<Mail className="w-4 h-4 mr-2" />
</Button>
<Button variant="outline" onClick={handleCSVUpload}>
<Upload className="w-4 h-4 mr-2" />
CSV
</Button>
</div>
),
itemsPerPage: itemsPerPage,
clientSideFiltering: true,
searchFilter: (item, searchValue) => {
const search = searchValue.toLowerCase();
return (
item.name.toLowerCase().includes(search) ||
(item.employeeCode?.toLowerCase().includes(search) ?? false) ||
(item.email?.toLowerCase().includes(search) ?? false)
);
},
tabFilter: (item, activeTab) => {
if (activeTab === 'all') return true;
return item.status === activeTab;
},
customFilterFn: (items, filterValues) => {
let filtered = items;
const filterOption = filterValues.filter as FilterOption;
if (filterOption && filterOption !== 'all') {
switch (filterOption) {
case 'hasUserId':
filtered = filtered.filter(e => e.userInfo?.userId);
break;
case 'noUserId':
filtered = filtered.filter(e => !e.userInfo?.userId);
break;
case 'active':
filtered = filtered.filter(e => e.status === 'active');
break;
case 'leave':
filtered = filtered.filter(e => e.status === 'leave');
break;
case 'resigned':
filtered = filtered.filter(e => e.status === 'resigned');
break;
}
}
return filtered;
},
customSortFn: (items, filterValues) => {
const sortOption = filterValues.sort as SortOption || 'rank';
const rankOrder: Record<string, number> = { '회장': 1, '사장': 2, '부사장': 3, '전무': 4, '상무': 5, '이사': 6, '부장': 7, '차장': 8, '과장': 9, '대리': 10, '주임': 11, '사원': 12 };
return [...items].sort((a, b) => {
switch (sortOption) {
case 'rank':
return (rankOrder[a.rank || ''] || 99) - (rankOrder[b.rank || ''] || 99);
case 'hireDateDesc':
return new Date(b.hireDate || 0).getTime() - new Date(a.hireDate || 0).getTime();
case 'hireDateAsc':
return new Date(a.hireDate || 0).getTime() - new Date(b.hireDate || 0).getTime();
case 'departmentAsc':
const deptA = a.departmentPositions?.[0]?.departmentName || '';
const deptB = b.departmentPositions?.[0]?.departmentName || '';
return deptA.localeCompare(deptB, 'ko');
case 'departmentDesc':
const deptA2 = a.departmentPositions?.[0]?.departmentName || '';
const deptB2 = b.departmentPositions?.[0]?.departmentName || '';
return deptB2.localeCompare(deptA2, 'ko');
case 'nameAsc':
return a.name.localeCompare(b.name, 'ko');
case 'nameDesc':
return b.name.localeCompare(a.name, 'ko');
default:
return 0;
}
});
},
renderTableRow: (item, index, globalIndex, handlers) => {
const { isSelected, onToggle, onRowClick } = handlers;
return (
<TableRow
key={item.id}
className="hover:bg-muted/50 cursor-pointer"
onClick={() => handleRowClick(item)}
>
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
<Checkbox
checked={isSelected}
onCheckedChange={onToggle}
/>
</TableCell>
<TableCell className="text-muted-foreground text-center">
{globalIndex}
</TableCell>
<TableCell>{item.employeeCode || '-'}</TableCell>
<TableCell>
{item.departmentPositions?.length > 0
? item.departmentPositions.map(dp => dp.departmentName).join(', ')
: '-'}
</TableCell>
<TableCell>
{item.departmentPositions?.length > 0
? item.departmentPositions.map(dp => dp.positionName).join(', ')
: '-'}
</TableCell>
<TableCell>{item.name}</TableCell>
<TableCell>{item.rank || '-'}</TableCell>
<TableCell>{item.phone || '-'}</TableCell>
<TableCell>{item.email || '-'}</TableCell>
<TableCell>
{item.hireDate ? new Date(item.hireDate).toLocaleDateString('ko-KR') : '-'}
</TableCell>
<TableCell>
<Badge className={EMPLOYEE_STATUS_COLORS[item.status]}>
{EMPLOYEE_STATUS_LABELS[item.status]}
</Badge>
</TableCell>
<TableCell>{item.userInfo?.userId || '-'}</TableCell>
<TableCell>
{item.userInfo ? USER_ROLE_LABELS[item.userInfo.role] : '-'}
</TableCell>
<TableCell className="text-right" onClick={(e) => e.stopPropagation()}>
{isSelected && (
<div className="flex items-center justify-end gap-1">
<Button
variant="ghost"
size="sm"
onClick={() => handleEdit(item.id)}
title="수정"
>
<Edit className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => openDeleteDialog(item)}
title="삭제"
>
<Trash2 className="w-4 h-4 text-red-500" />
</Button>
</div>
)}
</TableCell>
</TableRow>
);
},
renderMobileCard: (item, index, globalIndex, handlers) => {
const { isSelected, onToggle } = handlers;
return (
<ListMobileCard
id={item.id}
title={item.name}
headerBadges={
<div className="flex items-center gap-2 flex-wrap">
<Badge variant="outline" className="text-xs">
#{globalIndex}
</Badge>
<code className="text-xs bg-gray-100 px-2 py-1 rounded">
{item.employeeCode}
</code>
</div>
}
statusBadge={
<Badge className={EMPLOYEE_STATUS_COLORS[item.status]}>
{EMPLOYEE_STATUS_LABELS[item.status]}
</Badge>
}
isSelected={isSelected}
onToggleSelection={onToggle}
onCardClick={() => handleRowClick(item)}
infoGrid={
<div className="grid grid-cols-2 gap-x-4 gap-y-3">
<InfoField
label="부서"
value={item.departmentPositions?.length > 0
? item.departmentPositions.map(dp => dp.departmentName).join(', ')
: '-'}
/>
<InfoField
label="직책"
value={item.departmentPositions?.length > 0
? item.departmentPositions.map(dp => dp.positionName).join(', ')
: '-'}
/>
<InfoField label="직급" value={item.rank || '-'} />
<InfoField label="휴대폰" value={item.phone || '-'} />
<InfoField label="이메일" value={item.email || '-'} />
<InfoField
label="입사일"
value={item.hireDate ? new Date(item.hireDate).toLocaleDateString('ko-KR') : '-'}
/>
{item.userInfo && (
<>
<InfoField label="사용자ID" value={item.userInfo.userId || '-'} />
<InfoField label="권한" value={USER_ROLE_LABELS[item.userInfo.role]} />
</>
)}
</div>
}
actions={
isSelected ? (
<div className="flex gap-2 flex-wrap">
<Button
variant="default"
size="default"
className="flex-1 min-w-[100px] h-11"
onClick={(e) => { e.stopPropagation(); handleEdit(item.id); }}
>
<Edit className="h-4 w-4 mr-2" />
</Button>
<Button
variant="outline"
size="default"
className="flex-1 min-w-[100px] h-11 border-red-200 text-red-600 hover:border-red-300 bg-transparent"
onClick={(e) => { e.stopPropagation(); openDeleteDialog(item); }}
>
<Trash2 className="h-4 w-4 mr-2" />
</Button>
</div>
) : undefined
}
/>
);
},
renderDialogs: () => (
<>
{/* 필드 설정 다이얼로그 */}
<FieldSettingsDialog
open={fieldSettingsOpen}
onOpenChange={setFieldSettingsOpen}
settings={fieldSettings}
onSave={setFieldSettings}
/>
{/* 사용자 초대 다이얼로그 */}
<UserInviteDialog
open={userInviteOpen}
onOpenChange={setUserInviteOpen}
onInvite={(data) => {
console.log('[EmployeeManagement] Invite user - API 미구현:', data);
setUserInviteOpen(false);
}}
/>
{/* 삭제 확인 다이얼로그 */}
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle> </AlertDialogTitle>
<AlertDialogDescription>
&quot;{employeeToDelete?.name}&quot; ?
<br />
<span className="text-destructive">
.
</span>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isDeleting}></AlertDialogCancel>
<AlertDialogAction
onClick={handleDeleteEmployee}
disabled={isDeleting}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{isDeleting ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
...
</>
) : (
'삭제'
)}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
),
}), [
employees,
tableColumns,
tabs,
activeTab,
filterConfig,
filterValues,
statCards,
startDate,
endDate,
handleAddEmployee,
handleCSVUpload,
handleRowClick,
handleEdit,
openDeleteDialog,
fieldSettingsOpen,
fieldSettings,
userInviteOpen,
deleteDialogOpen,
employeeToDelete,
isDeleting,
handleDeleteEmployee,
]);
return (
<>
<IntegratedListTemplateV2<Employee>
title="사원관리"
description="사원 정보를 관리합니다"
icon={Users}
headerActions={headerActions}
stats={statCards}
searchValue={searchValue}
onSearchChange={setSearchValue}
searchPlaceholder="이름, 사원코드, 이메일 검색..."
tabs={tabs}
activeTab={activeTab}
onTabChange={setActiveTab}
filterConfig={filterConfig}
filterValues={filterValues}
onFilterChange={handleFilterChange}
onFilterReset={handleFilterReset}
filterTitle="사원 필터"
tableColumns={tableColumns}
data={paginatedData}
totalCount={filteredEmployees.length}
allData={filteredEmployees}
selectedItems={selectedItems}
onToggleSelection={toggleSelection}
onToggleSelectAll={toggleSelectAll}
onBulkDelete={handleBulkDelete}
getItemId={(item) => item.id}
renderTableRow={renderTableRow}
renderMobileCard={renderMobileCard}
pagination={{
currentPage,
totalPages,
totalItems: filteredEmployees.length,
itemsPerPage,
onPageChange: setCurrentPage,
}}
/>
{/* 필드 설정 다이얼로그 */}
<FieldSettingsDialog
open={fieldSettingsOpen}
onOpenChange={setFieldSettingsOpen}
settings={fieldSettings}
onSave={setFieldSettings}
/>
{/* 사용자 초대 다이얼로그 */}
<UserInviteDialog
open={userInviteOpen}
onOpenChange={setUserInviteOpen}
onInvite={(data) => {
// TODO: API 개발 필요 - POST /api/v1/employees/invite
console.log('[EmployeeManagement] Invite user - API 미구현:', data);
setUserInviteOpen(false);
}}
/>
{/* 삭제 확인 다이얼로그 */}
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle> </AlertDialogTitle>
<AlertDialogDescription>
&quot;{employeeToDelete?.name}&quot; ?
<br />
<span className="text-destructive">
.
</span>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isDeleting}></AlertDialogCancel>
<AlertDialogAction
onClick={handleDeleteEmployee}
disabled={isDeleting}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{isDeleting ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
...
</>
) : (
'삭제'
)}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
<UniversalListPage<Employee>
config={employeeConfig}
initialData={employees}
initialTotalCount={employees.length}
/>
);
}

View File

@@ -18,16 +18,14 @@ import { toast } from 'sonner';
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 {
IntegratedListTemplateV2,
type TableColumn,
UniversalListPage,
type UniversalListConfig,
type StatCard,
type TabOption,
type FilterFieldConfig,
type FilterValues,
} from '@/components/templates/IntegratedListTemplateV2';
} from '@/components/templates/UniversalListPage';
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
import { SalaryDetailDialog } from './SalaryDetailDialog';
import {
@@ -243,6 +241,12 @@ export function SalaryManagement() {
}
}, [selectedSalaryId, loadSalaries]);
// ===== 지급항목 추가 핸들러 =====
const handleAddPaymentItem = useCallback(() => {
// TODO: 지급항목 추가 다이얼로그 또는 로직 구현
toast.info('지급항목 추가 기능은 준비 중입니다.');
}, []);
// ===== 탭 (단일 탭) =====
const [activeTab, setActiveTab] = useState('all');
const tabs: TabOption[] = useMemo(() => [
@@ -299,7 +303,7 @@ export function SalaryManagement() {
}, [salaryData]);
// ===== 테이블 컬럼 (부서, 직책, 이름, 직급, 기본급, 수당, 초과근무, 상여, 공제, 실지급액, 일자, 상태, 작업) =====
const tableColumns: TableColumn[] = useMemo(() => [
const tableColumns = useMemo(() => [
{ key: 'department', label: '부서' },
{ key: 'position', label: '직책' },
{ key: 'name', label: '이름' },
@@ -315,151 +319,6 @@ export function SalaryManagement() {
{ 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="수정"
disabled={isActionLoading}
>
<Pencil className="h-4 w-4" />
</Button>
</TableCell>
</TableRow>
);
}, [selectedItems, toggleSelection, handleViewDetail, isActionLoading]);
// ===== 모바일 카드 렌더링 =====
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)}
disabled={isActionLoading}
>
<Pencil className="h-4 w-4 mr-2" />
</Button>
}
/>
);
}, [handleViewDetail, isActionLoading]);
// ===== 헤더 액션 =====
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}
disabled={isActionLoading}
>
{isActionLoading ? (
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
) : (
<Check className="h-4 w-4 mr-2" />
)}
</Button>
<Button
variant="outline"
onClick={handleMarkScheduled}
disabled={isActionLoading}
>
{isActionLoading ? (
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
) : (
<Clock className="h-4 w-4 mr-2" />
)}
</Button>
</>
)}
<Button variant="outline" onClick={() => toast.info('엑셀 다운로드 기능은 준비 중입니다.')}>
<Download className="h-4 w-4 mr-2" />
</Button>
</div>
);
// ===== filterConfig 기반 통합 필터 시스템 =====
const filterConfig: FilterFieldConfig[] = useMemo(() => [
{
@@ -491,52 +350,215 @@ export function SalaryManagement() {
setCurrentPage(1);
}, []);
return (
<>
<IntegratedListTemplateV2
title="급여관리"
description="직원들의 급여 현황을 관리합니다"
icon={DollarSign}
headerActions={headerActions}
stats={statCards}
searchValue={searchQuery}
onSearchChange={setSearchQuery}
searchPlaceholder="이름, 부서 검색..."
filterConfig={filterConfig}
filterValues={filterValues}
onFilterChange={handleFilterChange}
onFilterReset={handleFilterReset}
filterTitle="급여 필터"
tabs={tabs}
activeTab={activeTab}
onTabChange={setActiveTab}
tableColumns={tableColumns}
data={salaryData}
totalCount={totalCount}
allData={salaryData}
selectedItems={selectedItems}
onToggleSelection={toggleSelection}
onToggleSelectAll={toggleSelectAll}
getItemId={(item: SalaryRecord) => item.id}
renderTableRow={renderTableRow}
renderMobileCard={renderMobileCard}
isLoading={isLoading}
pagination={{
currentPage,
totalPages,
totalItems: totalCount,
itemsPerPage,
onPageChange: setCurrentPage,
}}
/>
// ===== UniversalListPage 설정 =====
const salaryConfig: UniversalListConfig<SalaryRecord> = useMemo(() => ({
title: '급여관리',
description: '직원들의 급여 현황을 관리합니다',
icon: DollarSign,
basePath: '/hr/salary-management',
{/* 급여 상세 다이얼로그 */}
idField: 'id',
actions: {
getList: async () => ({
success: true,
data: salaryData,
totalCount: totalCount,
totalPages: totalPages,
}),
},
columns: tableColumns,
filterConfig: filterConfig,
initialFilters: filterValues,
filterTitle: '급여 필터',
computeStats: () => statCards,
searchPlaceholder: '이름, 부서 검색...',
itemsPerPage: itemsPerPage,
// 날짜 범위 선택 (DateRangeSelector 사용)
dateRangeSelector: {
enabled: true,
showPresets: false,
startDate,
endDate,
onStartDateChange: setStartDate,
onEndDateChange: setEndDate,
},
headerActions: ({ selectedItems: selected }) => (
<div className="flex items-center gap-2 flex-wrap">
{/* 지급완료/지급예정 버튼 - 선택된 항목이 있을 때만 표시 */}
{selected.size > 0 && (
<>
<Button
variant="default"
onClick={handleMarkCompleted}
disabled={isActionLoading}
>
{isActionLoading ? (
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
) : (
<Check className="h-4 w-4 mr-2" />
)}
</Button>
<Button
variant="outline"
onClick={handleMarkScheduled}
disabled={isActionLoading}
>
{isActionLoading ? (
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
) : (
<Clock className="h-4 w-4 mr-2" />
)}
</Button>
</>
)}
<Button variant="outline" onClick={() => toast.info('엑셀 다운로드 기능은 준비 중입니다.')}>
<Download className="h-4 w-4 mr-2" />
</Button>
</div>
),
renderTableRow: (item, index, globalIndex, handlers) => {
const { isSelected, onToggle } = handlers;
return (
<TableRow key={item.id} className="hover:bg-muted/50">
<TableCell className="text-center">
<Checkbox checked={isSelected} onCheckedChange={onToggle} />
</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="수정"
disabled={isActionLoading}
>
<Pencil className="h-4 w-4" />
</Button>
</TableCell>
</TableRow>
);
},
renderMobileCard: (item, index, globalIndex, handlers) => {
const { isSelected, onToggle } = handlers;
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)}
disabled={isActionLoading}
>
<Pencil className="h-4 w-4 mr-2" />
</Button>
}
/>
);
},
renderDialogs: () => (
<SalaryDetailDialog
open={detailDialogOpen}
onOpenChange={setDetailDialogOpen}
salaryDetail={selectedSalaryDetail}
onSave={handleSaveDetail}
onAddPaymentItem={handleAddPaymentItem}
/>
</>
),
}), [
salaryData,
totalCount,
totalPages,
tableColumns,
filterConfig,
filterValues,
statCards,
startDate,
endDate,
handleMarkCompleted,
handleMarkScheduled,
isActionLoading,
handleViewDetail,
detailDialogOpen,
selectedSalaryDetail,
handleSaveDetail,
handleAddPaymentItem,
]);
return (
<UniversalListPage<SalaryRecord>
config={salaryConfig}
initialData={salaryData}
initialTotalCount={totalCount}
externalPagination={{
currentPage,
totalPages,
totalItems: totalCount,
itemsPerPage,
onPageChange: setCurrentPage,
}}
externalSelection={{
selectedItems,
onToggleSelection: toggleSelection,
onToggleSelectAll: toggleSelectAll,
getItemId: (item) => item.id,
}}
onSearchChange={setSearchQuery}
/>
);
}

View File

@@ -3,7 +3,6 @@
import { useState, useMemo, useCallback, useEffect } from 'react';
import { format } from 'date-fns';
import {
Download,
Plus,
Calendar,
Check,
@@ -40,13 +39,14 @@ import {
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import {
IntegratedListTemplateV2,
UniversalListPage,
type UniversalListConfig,
type TableColumn,
type StatCard,
type TabOption,
type FilterFieldConfig,
type FilterValues,
} from '@/components/templates/IntegratedListTemplateV2';
} from '@/components/templates/UniversalListPage';
import { DateRangeSelector } from '@/components/molecules/DateRangeSelector';
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
import { VacationGrantDialog } from './VacationGrantDialog';
@@ -109,7 +109,6 @@ export function VacationManagement() {
const [filterOption, setFilterOption] = useState<FilterOption>('all');
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" 용)
@@ -263,28 +262,8 @@ export function VacationManagement() {
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 =>
@@ -317,18 +296,12 @@ export function VacationManagement() {
}
}, [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 handleApproveClick = useCallback(() => {
if (selectedItems.size === 0) return;
const handleApproveClick = useCallback((selected: Set<string>) => {
// 버튼 클릭 시 UniversalListPage의 선택 상태를 내부 state로 복사
setSelectedItems(selected);
setApproveDialogOpen(true);
}, [selectedItems.size]);
}, []);
const handleApproveConfirm = useCallback(async () => {
if (isProcessing) return;
@@ -352,10 +325,11 @@ export function VacationManagement() {
}
}, [selectedItems, isProcessing, fetchLeaveRequests, fetchUsageData]);
const handleRejectClick = useCallback(() => {
if (selectedItems.size === 0) return;
const handleRejectClick = useCallback((selected: Set<string>) => {
// 버튼 클릭 시 UniversalListPage의 선택 상태를 내부 state로 복사
setSelectedItems(selected);
setRejectDialogOpen(true);
}, [selectedItems.size]);
}, []);
const handleRejectConfirm = useCallback(async () => {
if (isProcessing) return;
@@ -455,22 +429,28 @@ export function VacationManagement() {
}, [mainTab]);
// ===== 테이블 행 렌더링 =====
const renderTableRow = useCallback((item: any, index: number, globalIndex: number) => {
const isSelected = selectedItems.has(item.id);
const renderTableRow = useCallback((
item: any,
index: number,
globalIndex: number,
handlers: { isSelected: boolean; onToggle: () => void; onRowClick?: () => void }
) => {
const { isSelected, onToggle } = handlers;
if (mainTab === 'usage') {
const record = item as VacationUsageRecord;
const hireDateStr = record.hireDate && record.hireDate !== '-' ? format(new Date(record.hireDate), 'yyyy-MM-dd') : '-';
return (
<TableRow key={record.id} className="hover:bg-muted/50">
<TableCell className="text-center">
<Checkbox checked={isSelected} onCheckedChange={() => toggleSelection(record.id)} />
<Checkbox checked={isSelected} onCheckedChange={onToggle} />
</TableCell>
<TableCell className="text-center">{globalIndex}</TableCell>
<TableCell>{record.department}</TableCell>
<TableCell>{record.position}</TableCell>
<TableCell className="font-medium">{record.employeeName}</TableCell>
<TableCell>{record.rank}</TableCell>
<TableCell>{record.hireDate !== '-' ? format(new Date(record.hireDate), 'yyyy-MM-dd') : '-'}</TableCell>
<TableCell>{hireDateStr}</TableCell>
<TableCell className="text-center">{record.baseVacation}</TableCell>
<TableCell className="text-center">{record.grantedVacation}</TableCell>
<TableCell className="text-center">{record.usedVacation}</TableCell>
@@ -479,10 +459,11 @@ export function VacationManagement() {
);
} else if (mainTab === 'grant') {
const record = item as VacationGrantRecord;
const grantDateStr = record.grantDate ? format(new Date(record.grantDate), 'yyyy-MM-dd') : '-';
return (
<TableRow key={record.id} className="hover:bg-muted/50">
<TableCell className="text-center">
<Checkbox checked={isSelected} onCheckedChange={() => toggleSelection(record.id)} />
<Checkbox checked={isSelected} onCheckedChange={onToggle} />
</TableCell>
<TableCell className="text-center">{globalIndex}</TableCell>
<TableCell>{record.department}</TableCell>
@@ -492,17 +473,20 @@ export function VacationManagement() {
<TableCell>
<Badge variant="outline">{VACATION_TYPE_LABELS[record.vacationType]}</Badge>
</TableCell>
<TableCell>{format(new Date(record.grantDate), 'yyyy-MM-dd')}</TableCell>
<TableCell>{grantDateStr}</TableCell>
<TableCell className="text-center">{record.grantDays}</TableCell>
<TableCell className="text-muted-foreground">{record.reason || '-'}</TableCell>
</TableRow>
);
} else {
const record = item as VacationRequestRecord;
const startDateStr = record.startDate ? format(new Date(record.startDate), 'yyyy-MM-dd') : '-';
const endDateStr = record.endDate ? format(new Date(record.endDate), 'yyyy-MM-dd') : '-';
const requestDateStr = record.requestDate ? format(new Date(record.requestDate), 'yyyy-MM-dd') : '-';
return (
<TableRow key={record.id} className="hover:bg-muted/50">
<TableCell className="text-center">
<Checkbox checked={isSelected} onCheckedChange={() => toggleSelection(record.id)} />
<Checkbox checked={isSelected} onCheckedChange={onToggle} />
</TableCell>
<TableCell className="text-center">{globalIndex}</TableCell>
<TableCell>{record.department}</TableCell>
@@ -510,7 +494,7 @@ export function VacationManagement() {
<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')}
{startDateStr} ~ {endDateStr}
</TableCell>
<TableCell className="text-center">{record.vacationDays}</TableCell>
<TableCell className="text-center">
@@ -518,20 +502,20 @@ export function VacationManagement() {
{REQUEST_STATUS_LABELS[record.status]}
</Badge>
</TableCell>
<TableCell>{format(new Date(record.requestDate), 'yyyy-MM-dd')}</TableCell>
<TableCell>{requestDateStr}</TableCell>
</TableRow>
);
}
}, [mainTab, selectedItems, toggleSelection]);
}, [mainTab]);
// ===== 모바일 카드 렌더링 =====
const renderMobileCard = useCallback((
item: any,
index: number,
globalIndex: number,
isSelected: boolean,
onToggle: () => void
handlers: { isSelected: boolean; onToggle: () => void; onRowClick?: () => void }
) => {
const { isSelected, onToggle } = handlers;
if (mainTab === 'usage') {
const record = item as VacationUsageRecord;
return (
@@ -598,10 +582,10 @@ export function VacationManagement() {
actions={
record.status === 'pending' && (
<div className="flex gap-2">
<Button variant="default" className="flex-1" onClick={handleApproveClick}>
<Button variant="default" className="flex-1" onClick={() => handleApproveClick(new Set([record.id]))}>
<Check className="w-4 h-4 mr-2" />
</Button>
<Button variant="outline" className="flex-1" onClick={handleRejectClick}>
<Button variant="outline" className="flex-1" onClick={() => handleRejectClick(new Set([record.id]))}>
<X className="w-4 h-4 mr-2" />
</Button>
</div>
@@ -613,7 +597,7 @@ export function VacationManagement() {
}, [mainTab, handleApproveClick, handleRejectClick]);
// ===== 헤더 액션 (DateRangeSelector + 버튼들) =====
const headerActions = (
const headerActions = useCallback(({ selectedItems: selected }: { selectedItems: Set<string>; onClearSelection?: () => void; onRefresh?: () => void }) => (
<>
<DateRangeSelector
startDate={startDate}
@@ -633,13 +617,13 @@ export function VacationManagement() {
{mainTab === 'request' && (
<>
{/* 버튼 순서: 승인 → 거절 → 휴가신청 (휴가신청 버튼 위치 고정) */}
{selectedItems.size > 0 && (
{selected.size > 0 && (
<>
<Button variant="default" onClick={handleApproveClick}>
<Button variant="default" onClick={() => handleApproveClick(selected)}>
<Check className="h-4 w-4 mr-2" />
</Button>
<Button variant="destructive" onClick={handleRejectClick}>
<Button variant="destructive" onClick={() => handleRejectClick(selected)}>
<X className="h-4 w-4 mr-2" />
</Button>
@@ -651,15 +635,9 @@ export function VacationManagement() {
</Button>
</>
)}
{/* 엑셀 다운로드 버튼 - 주석처리 */}
{/* <Button variant="outline" onClick={() => console.log('엑셀 다운로드')}>
<Download className="h-4 w-4 mr-2" />
엑셀 다운로드
</Button> */}
</div>
</>
);
), [startDate, endDate, mainTab, handleApproveClick, handleRejectClick]);
// ===== filterConfig 기반 통합 필터 시스템 =====
const filterConfig: FilterFieldConfig[] = useMemo(() => [
@@ -698,153 +676,193 @@ export function VacationManagement() {
setSortOption(value as SortOption);
break;
}
setCurrentPage(1);
}, []);
const handleFilterReset = useCallback(() => {
setFilterOption('all');
setSortOption('rank');
setCurrentPage(1);
}, []);
// ===== UniversalListPage 설정 =====
const vacationConfig: UniversalListConfig<any> = useMemo(() => ({
title: '휴가관리',
description: '직원들의 휴가 현황을 관리합니다',
icon: Calendar,
basePath: '/hr/vacation-management',
idField: 'id',
actions: {
getList: async () => ({
success: true,
data: currentData,
totalCount: currentData.length,
}),
},
columns: tableColumns,
tabs: tabs,
defaultTab: mainTab,
searchPlaceholder: '이름, 부서 검색...',
itemsPerPage: itemsPerPage,
clientSideFiltering: true,
searchFilter: (item, searchValue) => {
return (
item.employeeName?.includes(searchValue) ||
item.department?.includes(searchValue)
);
},
// tabFilter 제거: 탭별로 다른 데이터를 사용하므로 원래 tabs.count 유지
computeStats: () => statCards,
filterConfig: filterConfig,
headerActions: headerActions,
renderTableRow: renderTableRow,
renderMobileCard: renderMobileCard,
renderDialogs: () => (
<>
{/* 휴가 부여 다이얼로그 */}
<VacationGrantDialog
open={grantDialogOpen}
onOpenChange={setGrantDialogOpen}
onSave={async (data) => {
try {
const result = await createLeaveGrant({
userId: parseInt(data.employeeId, 10),
grantType: data.vacationType as LeaveGrantType,
grantDate: data.grantDate,
grantDays: data.grantDays,
reason: data.reason,
});
if (result.success) {
await fetchGrantData();
await fetchUsageData();
} else {
alert(`휴가 부여 실패: ${result.error}`);
console.error('[VacationManagement] 휴가 부여 실패:', result.error);
}
} catch (error) {
if (isNextRedirectError(error)) throw error;
console.error('[VacationManagement] 휴가 부여 에러:', error);
alert('휴가 부여 중 오류가 발생했습니다.');
} finally {
setGrantDialogOpen(false);
}
}}
/>
{/* 휴가 신청 다이얼로그 */}
<VacationRequestDialog
open={requestDialogOpen}
onOpenChange={setRequestDialogOpen}
onSave={async (data) => {
try {
const result = await createLeave({
userId: parseInt(data.employeeId, 10),
leaveType: data.leaveType,
startDate: data.startDate,
endDate: data.endDate,
days: data.vacationDays,
});
if (result.success) {
await fetchLeaveRequests();
await fetchUsageData();
} else {
alert(`휴가 신청 실패: ${result.error}`);
console.error('[VacationManagement] 휴가 신청 실패:', result.error);
}
} catch (error) {
if (isNextRedirectError(error)) throw error;
console.error('[VacationManagement] 휴가 신청 에러:', error);
alert('휴가 신청 중 오류가 발생했습니다.');
} finally {
setRequestDialogOpen(false);
}
}}
/>
{/* 승인 확인 다이얼로그 */}
<AlertDialog open={approveDialogOpen} onOpenChange={setApproveDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle> </AlertDialogTitle>
<AlertDialogDescription>
{selectedItems.size} ?
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel></AlertDialogCancel>
<AlertDialogAction onClick={handleApproveConfirm}>
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{/* 거절 확인 다이얼로그 */}
<AlertDialog open={rejectDialogOpen} onOpenChange={setRejectDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle> </AlertDialogTitle>
<AlertDialogDescription>
{selectedItems.size} ?
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel></AlertDialogCancel>
<AlertDialogAction
onClick={handleRejectConfirm}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
),
}), [
currentData,
tableColumns,
tabs,
mainTab,
itemsPerPage,
statCards,
filterConfig,
headerActions,
renderTableRow,
renderMobileCard,
grantDialogOpen,
requestDialogOpen,
approveDialogOpen,
rejectDialogOpen,
selectedItems.size,
handleApproveConfirm,
handleRejectConfirm,
fetchGrantData,
fetchUsageData,
fetchLeaveRequests,
]);
return (
<>
{/* IntegratedListTemplateV2 - 카드 아래에 탭 표시됨 */}
<IntegratedListTemplateV2
title="휴가관리"
description="직원들의 휴가 현황을 관리합니다"
icon={Calendar}
headerActions={headerActions}
stats={statCards}
searchValue={searchQuery}
onSearchChange={setSearchQuery}
searchPlaceholder="이름, 부서 검색..."
filterConfig={filterConfig}
filterValues={filterValues}
onFilterChange={handleFilterChange}
onFilterReset={handleFilterReset}
filterTitle="휴가 필터"
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={async (data) => {
try {
// VacationGrantFormData를 CreateLeaveGrantRequest 형식으로 변환
const result = await createLeaveGrant({
userId: parseInt(data.employeeId, 10),
grantType: data.vacationType as LeaveGrantType,
grantDate: data.grantDate,
grantDays: data.grantDays,
reason: data.reason,
});
if (result.success) {
await fetchGrantData();
await fetchUsageData(); // 잔여휴가도 갱신
} else {
alert(`휴가 부여 실패: ${result.error}`);
console.error('[VacationManagement] 휴가 부여 실패:', result.error);
}
} catch (error) {
if (isNextRedirectError(error)) throw error;
console.error('[VacationManagement] 휴가 부여 에러:', error);
alert('휴가 부여 중 오류가 발생했습니다.');
} finally {
setGrantDialogOpen(false);
}
}}
/>
<VacationRequestDialog
open={requestDialogOpen}
onOpenChange={setRequestDialogOpen}
onSave={async (data) => {
try {
// VacationRequestFormData를 CreateLeaveRequest 형식으로 변환
const result = await createLeave({
userId: parseInt(data.employeeId, 10),
leaveType: data.leaveType,
startDate: data.startDate,
endDate: data.endDate,
days: data.vacationDays,
});
if (result.success) {
await fetchLeaveRequests();
await fetchUsageData(); // 잔여휴가도 갱신
} else {
alert(`휴가 신청 실패: ${result.error}`);
console.error('[VacationManagement] 휴가 신청 실패:', result.error);
}
} catch (error) {
if (isNextRedirectError(error)) throw error;
console.error('[VacationManagement] 휴가 신청 에러:', error);
alert('휴가 신청 중 오류가 발생했습니다.');
} finally {
setRequestDialogOpen(false);
}
}}
/>
{/* 승인 확인 다이얼로그 */}
<AlertDialog open={approveDialogOpen} onOpenChange={setApproveDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle> </AlertDialogTitle>
<AlertDialogDescription>
{selectedItems.size} ?
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel></AlertDialogCancel>
<AlertDialogAction onClick={handleApproveConfirm}>
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{/* 거절 확인 다이얼로그 */}
<AlertDialog open={rejectDialogOpen} onOpenChange={setRejectDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle> </AlertDialogTitle>
<AlertDialogDescription>
{selectedItems.size} ?
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel></AlertDialogCancel>
<AlertDialogAction
onClick={handleRejectConfirm}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
<UniversalListPage<any>
config={vacationConfig}
initialData={currentData}
initialTotalCount={currentData.length}
onTabChange={handleMainTabChange}
onSearchChange={setSearchQuery}
onFilterChange={handleFilterChange}
/>
);
}