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

@@ -1,12 +1,15 @@
'use client';
/**
* 작업실적 조회 목록 페이지
* IntegratedListTemplateV2 패턴 적용
* API 연동 완료 (2025-12-26)
* 작업실적 조회 - UniversalListPage 마이그레이션
*
* 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
* - 서버 사이드 페이지네이션 (getWorkResults API)
* - 통계 카드 (getWorkResultStats API)
* - 기본 리스트 (탭 없음)
*/
import { useState, useCallback, useEffect } from 'react';
import { useState, useEffect, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import {
BarChart3,
@@ -17,19 +20,22 @@ import {
Download,
CheckCircle,
} from 'lucide-react';
import { ContentLoadingSpinner } from '@/components/ui/loading-spinner';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { TableCell, TableRow } from '@/components/ui/table';
import { Checkbox } from '@/components/ui/checkbox';
import {
IntegratedListTemplateV2,
TableColumn,
StatCard,
} from '@/components/templates/IntegratedListTemplateV2';
UniversalListPage,
type UniversalListConfig,
type SelectionHandlers,
type RowClickHandlers,
type StatCard,
type ListParams,
} from '@/components/templates/UniversalListPage';
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
import { toast } from 'sonner';
import { getWorkResults, getWorkResultStats } from './actions';
import { PROCESS_TYPE_LABELS } from '../WorkOrders/types';
import type { WorkResult, WorkResultStats } from './types';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
@@ -37,301 +43,270 @@ import { isNextRedirectError } from '@/lib/utils/redirect-error';
const ITEMS_PER_PAGE = 20;
export function WorkResultList() {
const router = useRouter();
// ===== 상태 관리 =====
const [searchTerm, setSearchTerm] = useState('');
const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
const [currentPage, setCurrentPage] = useState(1);
const [workResults, setWorkResults] = useState<WorkResult[]>([]);
const [totalItems, setTotalItems] = useState(0);
const [totalPages, setTotalPages] = useState(1);
// ===== 통계 데이터 (외부 관리 - 별도 API) =====
const [statsData, setStatsData] = useState<WorkResultStats>({
totalProduction: 0,
totalGood: 0,
totalDefect: 0,
defectRate: 0,
});
const [isLoading, setIsLoading] = useState(true);
// ===== 데이터 로드 =====
const loadData = useCallback(async () => {
setIsLoading(true);
try {
// 병렬로 목록 + 통계 조회
const [listResult, statsResult] = await Promise.all([
getWorkResults({
page: currentPage,
size: ITEMS_PER_PAGE,
q: searchTerm || undefined,
}),
getWorkResultStats(),
]);
if (listResult.success) {
setWorkResults(listResult.data);
setTotalItems(listResult.pagination.total);
setTotalPages(listResult.pagination.lastPage);
} else {
toast.error(listResult.error || '작업실적 목록 조회에 실패했습니다.');
}
if (statsResult.success && statsResult.data) {
setStatsData(statsResult.data);
}
} catch (error) {
if (isNextRedirectError(error)) throw error;
console.error('[WorkResultList] loadData error:', error);
toast.error('데이터 로드 중 오류가 발생했습니다.');
} finally {
setIsLoading(false);
}
}, [currentPage, searchTerm]);
// 통계 데이터 로드 (초기 1회)
useEffect(() => {
loadData();
}, [loadData]);
// 통계 카드
const stats: StatCard[] = [
{
label: '총 생산수량',
value: `${statsData.totalProduction.toLocaleString()}`,
icon: Package,
iconColor: 'text-gray-600',
},
{
label: '양품수량',
value: `${statsData.totalGood.toLocaleString()}`,
icon: CheckCircle2,
iconColor: 'text-green-600',
},
{
label: '불량수량',
value: `${statsData.totalDefect.toLocaleString()}`,
icon: XCircle,
iconColor: 'text-red-600',
},
{
label: '불량률',
value: `${statsData.defectRate.toFixed(1)}%`,
icon: Percent,
iconColor: 'text-orange-600',
},
];
// 테이블 컬럼
const tableColumns: TableColumn[] = [
{ key: 'no', label: '번호', className: 'w-[60px] text-center' },
{ key: 'lotNo', label: '로트번호', className: 'min-w-[150px]' },
{ key: 'workDate', label: '작업일', className: 'w-[100px]' },
{ key: 'workOrderNo', label: '작업지시번호', className: 'min-w-[140px]' },
{ key: 'processType', label: '공정', className: 'w-[80px]' },
{ key: 'productName', label: '품목명', className: 'min-w-[180px]' },
{ key: 'specification', label: '규격', className: 'w-[100px]' },
{ key: 'productionQty', label: '생산수량', className: 'w-[80px] text-center' },
{ key: 'goodQty', label: '양품수량', className: 'w-[80px] text-center' },
{ key: 'defectQty', label: '불량수량', className: 'w-[80px] text-center' },
{ key: 'defectRate', label: '불량률', className: 'w-[80px] text-center' },
{ key: 'inspection', label: '검사', className: 'w-[60px] text-center' },
{ key: 'packaging', label: '포장', className: 'w-[60px] text-center' },
{ key: 'worker', label: '작업자', className: 'w-[80px]' },
];
// 페이지네이션 설정 (API 기반)
const pagination = {
currentPage,
totalPages,
totalItems,
itemsPerPage: ITEMS_PER_PAGE,
onPageChange: setCurrentPage,
};
// 선택 핸들러
const handleToggleSelection = useCallback((id: string) => {
setSelectedItems((prev) => {
const newSet = new Set(prev);
if (newSet.has(id)) {
newSet.delete(id);
} else {
newSet.add(id);
const loadStats = async () => {
try {
const result = await getWorkResultStats();
if (result.success && result.data) {
setStatsData(result.data);
}
} catch (error) {
if (isNextRedirectError(error)) throw error;
console.error('[WorkResultList] loadStats error:', error);
}
return newSet;
});
};
loadStats();
}, []);
const handleToggleSelectAll = useCallback(() => {
if (selectedItems.size === workResults.length) {
setSelectedItems(new Set());
} else {
setSelectedItems(new Set(workResults.map((r) => r.id)));
}
}, [workResults, selectedItems.size]);
// ===== 상세 보기 핸들러 =====
const handleView = useCallback((item: WorkResult) => {
console.log('상세 보기:', item.id);
// TODO: 상세 보기 기능 구현
}, []);
// 검색 변경 시 페이지 리셋
const handleSearchChange = (value: string) => {
setSearchTerm(value);
setCurrentPage(1);
};
// 엑셀 다운로드
// ===== 엑셀 다운로드 =====
const handleExcelDownload = useCallback(() => {
console.log('엑셀 다운로드:', workResults);
console.log('엑셀 다운로드');
// TODO: 엑셀 다운로드 기능 구현
}, [workResults]);
}, []);
// 상세 보기 (작업지시 상세 페이지로 이동)
const handleView = useCallback((workOrderId: number) => {
router.push(`/production/work-orders/${workOrderId}`);
}, [router]);
// ===== 통계 카드 =====
const stats: StatCard[] = useMemo(
() => [
{
label: '총 생산수량',
value: `${statsData.totalProduction.toLocaleString()}`,
icon: Package,
iconColor: 'text-gray-600',
},
{
label: '양품수량',
value: `${statsData.totalGood.toLocaleString()}`,
icon: CheckCircle2,
iconColor: 'text-green-600',
},
{
label: '불량수량',
value: `${statsData.totalDefect.toLocaleString()}`,
icon: XCircle,
iconColor: 'text-red-600',
},
{
label: '불량률',
value: `${statsData.defectRate.toFixed(1)}%`,
icon: Percent,
iconColor: 'text-orange-600',
},
],
[statsData]
);
// 작업일 포맷팅 (날짜만 표시)
const formatWorkDate = (dateStr: string) => {
if (!dateStr) return '-';
return dateStr.split(' ')[0]; // "2025-01-14 10:30:00" → "2025-01-14"
};
// ===== UniversalListPage Config =====
const config: UniversalListConfig<WorkResult> = useMemo(
() => ({
// 페이지 기본 정보
title: '작업실적 조회',
description: '생산 작업실적 조회',
icon: BarChart3,
basePath: '/production/work-results',
// 테이블 행 렌더링
const renderTableRow = (result: WorkResult, index: number, globalIndex: number) => {
const isSelected = selectedItems.has(result.id);
// ID 추출
idField: 'id',
return (
<TableRow
key={result.id}
className={`cursor-pointer hover:bg-muted/50 ${isSelected ? 'bg-blue-50' : ''}`}
onClick={() => handleView(result.workOrderId)}
>
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
<Checkbox
checked={isSelected}
onCheckedChange={() => handleToggleSelection(result.id)}
// API 액션 (서버 사이드 페이지네이션)
actions: {
getList: async (params?: ListParams) => {
try {
const result = await getWorkResults({
page: params?.page || 1,
size: params?.pageSize || ITEMS_PER_PAGE,
q: params?.search || undefined,
});
if (result.success) {
// 통계도 다시 로드
const statsResult = await getWorkResultStats();
if (statsResult.success && statsResult.data) {
setStatsData(statsResult.data);
}
return {
success: true,
data: result.data,
totalCount: result.pagination.total,
totalPages: result.pagination.lastPage,
};
}
return { success: false, error: result.error };
} catch (error) {
if (isNextRedirectError(error)) throw error;
return { success: false, error: '데이터 로드 중 오류가 발생했습니다.' };
}
},
},
// 테이블 컬럼
columns: [
{ key: 'no', label: '번호', className: 'w-[60px] text-center' },
{ key: 'lotNo', label: '로트번호', className: 'min-w-[150px]' },
{ key: 'workDate', label: '작업일', className: 'w-[100px]' },
{ key: 'workOrderNo', label: '작업지시번호', className: 'min-w-[140px]' },
{ key: 'processType', label: '공정', className: 'w-[80px]' },
{ key: 'productName', label: '품목명', className: 'min-w-[180px]' },
{ key: 'specification', label: '규격', className: 'w-[100px]' },
{ key: 'productionQty', label: '생산수량', className: 'w-[80px] text-center' },
{ key: 'goodQty', label: '양품수량', className: 'w-[80px] text-center' },
{ key: 'defectQty', label: '불량수량', className: 'w-[80px] text-center' },
{ key: 'defectRate', label: '불량률', className: 'w-[80px] text-center' },
{ key: 'inspection', label: '검사', className: 'w-[60px] text-center' },
{ key: 'packaging', label: '포장', className: 'w-[60px] text-center' },
{ key: 'worker', label: '작업자', className: 'w-[80px]' },
],
// 서버 사이드 페이지네이션
clientSideFiltering: false,
itemsPerPage: ITEMS_PER_PAGE,
// 검색
searchPlaceholder: '로트번호, 작업지시번호, 품목명 검색...',
// 통계 카드
stats,
// 헤더 액션 (엑셀 다운로드)
headerActions: () => (
<Button variant="outline" onClick={handleExcelDownload}>
<Download className="w-4 h-4 mr-1.5" />
</Button>
),
// 테이블 행 렌더링
renderTableRow: (
item: WorkResult,
index: number,
globalIndex: number,
handlers: SelectionHandlers & RowClickHandlers<WorkResult>
) => {
return (
<TableRow
key={item.id}
className={`cursor-pointer hover:bg-muted/50 ${handlers.isSelected ? 'bg-blue-50' : ''}`}
onClick={() => handleView(item)}
>
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
<Checkbox
checked={handlers.isSelected}
onCheckedChange={handlers.onToggle}
/>
</TableCell>
<TableCell className="text-center text-muted-foreground">{globalIndex}</TableCell>
<TableCell className="font-medium">{item.lotNo}</TableCell>
<TableCell>{item.workDate}</TableCell>
<TableCell>{item.workOrderNo}</TableCell>
<TableCell>
<Badge variant="outline" className="text-xs">
{PROCESS_TYPE_LABELS[item.processType]}
</Badge>
</TableCell>
<TableCell className="max-w-[200px] truncate">{item.productName}</TableCell>
<TableCell>{item.specification}</TableCell>
<TableCell className="text-center">{item.productionQty}</TableCell>
<TableCell className="text-center">{item.goodQty}</TableCell>
<TableCell className="text-center">
<span className={item.defectQty > 0 ? 'text-red-600 font-medium' : ''}>
{item.defectQty}
</span>
</TableCell>
<TableCell className="text-center">
<span className={item.defectRate > 0 ? 'text-red-600 font-medium' : ''}>
{item.defectRate}%
</span>
</TableCell>
<TableCell className="text-center">
{item.inspection ? (
<CheckCircle className="w-4 h-4 text-green-600 mx-auto" />
) : (
<span className="text-muted-foreground">-</span>
)}
</TableCell>
<TableCell className="text-center">
{item.packaging ? (
<CheckCircle className="w-4 h-4 text-green-600 mx-auto" />
) : (
<span className="text-muted-foreground">-</span>
)}
</TableCell>
<TableCell>{item.worker}</TableCell>
</TableRow>
);
},
// 모바일 카드 렌더링
renderMobileCard: (
item: WorkResult,
index: number,
globalIndex: number,
handlers: SelectionHandlers & RowClickHandlers<WorkResult>
) => {
return (
<ListMobileCard
key={item.id}
id={item.id}
isSelected={handlers.isSelected}
onToggleSelection={handlers.onToggle}
onClick={() => handleView(item)}
headerBadges={
<>
<Badge variant="outline" className="text-xs">
#{globalIndex}
</Badge>
<Badge variant="outline" className="text-xs">
{item.lotNo}
</Badge>
</>
}
title={item.productName}
statusBadge={
<Badge variant="outline" className="text-xs">
{PROCESS_TYPE_LABELS[item.processType]}
</Badge>
}
infoGrid={
<div className="grid grid-cols-2 gap-x-4 gap-y-3">
<InfoField label="작업일" value={item.workDate} />
<InfoField label="작업지시번호" value={item.workOrderNo} />
<InfoField label="규격" value={item.specification} />
<InfoField label="작업자" value={item.worker} />
<InfoField label="생산수량" value={`${item.productionQty}`} />
<InfoField label="양품수량" value={`${item.goodQty}`} />
<InfoField
label="불량수량"
value={`${item.defectQty}`}
className={item.defectQty > 0 ? 'text-red-600' : ''}
/>
<InfoField
label="불량률"
value={`${item.defectRate}%`}
className={item.defectRate > 0 ? 'text-red-600' : ''}
/>
</div>
}
/>
</TableCell>
<TableCell className="text-center text-muted-foreground">{globalIndex}</TableCell>
<TableCell className="font-medium">{result.lotNo}</TableCell>
<TableCell>{formatWorkDate(result.workDate)}</TableCell>
<TableCell>{result.workOrderNo}</TableCell>
<TableCell>
<Badge variant="outline" className="text-xs">
{result.processName || '-'}
</Badge>
</TableCell>
<TableCell className="max-w-[200px] truncate">{result.productName}</TableCell>
<TableCell>{result.specification}</TableCell>
<TableCell className="text-center">{Math.floor(result.productionQty)}</TableCell>
<TableCell className="text-center">{Math.floor(result.goodQty)}</TableCell>
<TableCell className="text-center">
<span className={result.defectQty > 0 ? 'text-red-600 font-medium' : ''}>
{Math.floor(result.defectQty)}
</span>
</TableCell>
<TableCell className="text-center">
<span className={result.defectRate > 0 ? 'text-red-600 font-medium' : ''}>
{result.defectRate.toFixed(1)}%
</span>
</TableCell>
<TableCell className="text-center">
{result.inspection ? (
<CheckCircle className="w-4 h-4 text-green-600 mx-auto" />
) : (
<span className="text-muted-foreground">-</span>
)}
</TableCell>
<TableCell className="text-center">
{result.packaging ? (
<CheckCircle className="w-4 h-4 text-green-600 mx-auto" />
) : (
<span className="text-muted-foreground">-</span>
)}
</TableCell>
<TableCell>{result.workerName || '-'}</TableCell>
</TableRow>
);
};
// 모바일 카드 렌더링
const renderMobileCard = (
result: WorkResult,
index: number,
globalIndex: number,
isSelected: boolean,
onToggle: () => void
) => {
return (
<ListMobileCard
id={result.id}
isSelected={isSelected}
onToggleSelection={onToggle}
onClick={() => handleView(result.workOrderId)}
headerBadges={
<>
<Badge variant="outline" className="text-xs">#{globalIndex}</Badge>
<Badge variant="outline" className="text-xs">{result.lotNo}</Badge>
</>
}
title={result.productName}
statusBadge={
<Badge variant="outline" className="text-xs">
{result.processName || '-'}
</Badge>
}
infoGrid={
<div className="grid grid-cols-2 gap-x-4 gap-y-3">
<InfoField label="작업일" value={formatWorkDate(result.workDate)} />
<InfoField label="작업지시번호" value={result.workOrderNo} />
<InfoField label="규격" value={result.specification} />
<InfoField label="작업자" value={result.workerName || '-'} />
<InfoField label="생산수량" value={`${Math.floor(result.productionQty)}`} />
<InfoField label="양품수량" value={`${Math.floor(result.goodQty)}`} />
<InfoField
label="불량수량"
value={`${Math.floor(result.defectQty)}`}
className={result.defectQty > 0 ? 'text-red-600' : ''}
/>
<InfoField
label="불량률"
value={`${result.defectRate.toFixed(1)}%`}
className={result.defectRate > 0 ? 'text-red-600' : ''}
/>
</div>
}
/>
);
};
// 헤더 액션
const headerActions = (
<Button variant="outline" onClick={handleExcelDownload}>
<Download className="w-4 h-4 mr-1.5" />
</Button>
);
},
}),
[stats, handleView, handleExcelDownload]
);
// 로딩 상태
if (isLoading && workResults.length === 0) {
return <ContentLoadingSpinner text="작업실적 목록을 불러오는 중..." />;
}
return (
<IntegratedListTemplateV2<WorkResult>
title="작업실적 조회"
icon={BarChart3}
headerActions={headerActions}
stats={stats}
searchValue={searchTerm}
onSearchChange={handleSearchChange}
searchPlaceholder="로트번호, 작업지시번호, 품목명 검색..."
tableColumns={tableColumns}
data={workResults}
totalCount={totalItems}
allData={workResults}
selectedItems={selectedItems}
onToggleSelection={handleToggleSelection}
onToggleSelectAll={handleToggleSelectAll}
getItemId={(result) => result.id}
renderTableRow={renderTableRow}
renderMobileCard={renderMobileCard}
pagination={pagination}
/>
);
return <UniversalListPage config={config} />;
}