Files
sam-react-prod/src/components/material/StockStatus/StockStatusList.tsx
권혁성 a0343eec93 feat(WEB): 부실채권, 재고, 입고, 수주 UI 개선
- BadDebtCollection 액션/타입 리팩토링
- ReceivingProcessDialog 입고처리 개선
- StockStatusList 재고현황 UI 개선
- OrderSalesDetailView 수주 상세 수정
- UniversalListPage 범용 리스트 개선
- production-order 페이지 수정
2026-01-23 21:32:24 +09:00

370 lines
13 KiB
TypeScript

'use client';
/**
* 재고현황 목록 - UniversalListPage 마이그레이션
*
* 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
* - 서버 사이드 페이지네이션 (getStocks API)
* - 통계 카드 (getStockStats API)
* - 품목유형별 탭 필터 (getStockStatsByType API)
* - 테이블 푸터 (요약 정보)
*/
import { useState, useEffect, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import {
Package,
CheckCircle2,
Clock,
AlertCircle,
Download,
Eye,
} from 'lucide-react';
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 {
UniversalListPage,
type UniversalListConfig,
type SelectionHandlers,
type RowClickHandlers,
type TabOption,
type StatCard,
type ListParams,
} from '@/components/templates/UniversalListPage';
import { ListMobileCard, InfoField } from '@/components/organisms/MobileCard';
import { getStocks, getStockStats, getStockStatsByType } from './actions';
import { ITEM_TYPE_LABELS, ITEM_TYPE_STYLES, STOCK_STATUS_LABELS } from './types';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
import type { StockItem, StockStats, ItemType } from './types';
// 페이지당 항목 수
const ITEMS_PER_PAGE = 20;
export function StockStatusList() {
const router = useRouter();
// ===== 통계 및 품목유형별 통계 (외부 관리) =====
const [stockStats, setStockStats] = useState<StockStats | null>(null);
const [typeStats, setTypeStats] = useState<Record<string, { label: string; count: number; total_qty: number | string }>>({});
const [totalItems, setTotalItems] = useState(0);
// 초기 통계 로드
useEffect(() => {
const loadStats = async () => {
try {
const [statsResult, typeStatsResult] = await Promise.all([
getStockStats(),
getStockStatsByType(),
]);
if (statsResult.success && statsResult.data) {
setStockStats(statsResult.data);
}
if (typeStatsResult.success && typeStatsResult.data) {
setTypeStats(typeStatsResult.data);
}
} catch (error) {
if (isNextRedirectError(error)) throw error;
console.error('[StockStatusList] loadStats error:', error);
}
};
loadStats();
}, []);
// ===== 행 클릭 핸들러 =====
const handleRowClick = useCallback(
(item: StockItem) => {
router.push(`/ko/material/stock-status/${item.id}`);
},
[router]
);
// ===== 엑셀 다운로드 =====
const handleExcelDownload = useCallback(() => {
console.log('엑셀 다운로드');
// TODO: 엑셀 다운로드 기능 구현
}, []);
// ===== 통계 카드 =====
const stats: StatCard[] = useMemo(
() => [
{
label: '전체 품목',
value: `${stockStats?.totalItems || 0}`,
icon: Package,
iconColor: 'text-gray-600',
},
{
label: '정상 재고',
value: `${stockStats?.normalCount || 0}`,
icon: CheckCircle2,
iconColor: 'text-green-600',
},
{
label: '재고 부족',
value: `${stockStats?.lowCount || 0}`,
icon: Clock,
iconColor: 'text-orange-600',
},
{
label: '재고 없음',
value: `${stockStats?.outCount || 0}`,
icon: AlertCircle,
iconColor: 'text-red-600',
},
],
[stockStats]
);
// ===== 탭 옵션 (기본 탭 + 품목유형별 통계) =====
const tabs: TabOption[] = useMemo(() => {
// 기본 탭 정의 (Item 모델의 MATERIAL_TYPES: RM, SM, CS)
const defaultTabs: { value: string; label: string }[] = [
{ value: 'all', label: '전체' },
{ value: 'RM', label: '원자재' },
{ value: 'SM', label: '부자재' },
{ value: 'CS', label: '소모품' },
];
return defaultTabs.map((tab) => {
if (tab.value === 'all') {
return { ...tab, count: stockStats?.totalItems || 0 };
}
const stat = typeStats[tab.value];
const count = typeof stat?.count === 'number' ? stat.count : 0;
return { ...tab, count };
});
}, [typeStats, stockStats?.totalItems]);
// ===== 테이블 푸터 =====
const tableFooter = useMemo(() => {
const lowStockCount = stockStats?.lowCount || 0;
return (
<TableRow className="bg-gray-50 hover:bg-gray-50">
<TableCell colSpan={12} className="py-3">
<span className="text-sm text-muted-foreground">
{totalItems} / {lowStockCount}
</span>
</TableCell>
</TableRow>
);
}, [totalItems, stockStats?.lowCount]);
// ===== UniversalListPage Config =====
const config: UniversalListConfig<StockItem> = useMemo(
() => ({
// 페이지 기본 정보
title: '재고 목록',
description: '재고현황 관리',
icon: Package,
basePath: '/material/stock-status',
// ID 추출
idField: 'id',
// API 액션 (서버 사이드 페이지네이션)
actions: {
getList: async (params?: ListParams) => {
try {
const result = await getStocks({
page: params?.page || 1,
perPage: params?.pageSize || ITEMS_PER_PAGE,
itemType: params?.tab !== 'all' ? (params?.tab as ItemType) : undefined,
search: params?.search || undefined,
});
if (result.success) {
// 통계 및 품목유형별 통계 다시 로드
const [statsResult, typeStatsResult] = await Promise.all([
getStockStats(),
getStockStatsByType(),
]);
if (statsResult.success && statsResult.data) {
setStockStats(statsResult.data);
}
if (typeStatsResult.success && typeStatsResult.data) {
setTypeStats(typeStatsResult.data);
}
// totalItems 업데이트 (푸터용)
setTotalItems(result.pagination.total);
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: 'itemCode', label: '품목코드', className: 'min-w-[120px]' },
{ key: 'itemName', label: '품목명', className: 'min-w-[200px]' },
{ key: 'itemType', label: '품목유형', className: 'w-[100px]' },
{ key: 'unit', label: '단위', className: 'w-[60px] text-center' },
{ key: 'stockQty', label: '재고량', className: 'w-[80px] text-center' },
{ key: 'safetyStock', label: '안전재고', className: 'w-[80px] text-center' },
{ key: 'lot', label: 'LOT', className: 'w-[100px] text-center' },
{ key: 'status', label: '상태', className: 'w-[60px] text-center' },
{ key: 'location', label: '위치', className: 'w-[60px] text-center' },
],
// 서버 사이드 페이지네이션
clientSideFiltering: false,
itemsPerPage: ITEMS_PER_PAGE,
// 검색
searchPlaceholder: '품목코드, 품목명 검색...',
// 탭 설정
tabs,
defaultTab: 'all',
// 통계 카드
stats,
// 테이블 푸터
tableFooter,
// 헤더 액션 (엑셀 다운로드)
headerActions: () => (
<Button variant="outline" onClick={handleExcelDownload}>
<Download className="w-4 h-4 mr-1.5" />
</Button>
),
// 테이블 행 렌더링
renderTableRow: (
item: StockItem,
index: number,
globalIndex: number,
handlers: SelectionHandlers & RowClickHandlers<StockItem>
) => {
return (
<TableRow
key={item.id}
className={`cursor-pointer hover:bg-muted/50 ${handlers.isSelected ? 'bg-blue-50' : ''}`}
onClick={() => handleRowClick(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.itemCode}</TableCell>
<TableCell className="max-w-[200px] truncate">{item.itemName}</TableCell>
<TableCell>
<Badge className={`text-xs ${ITEM_TYPE_STYLES[item.itemType]}`}>
{ITEM_TYPE_LABELS[item.itemType]}
</Badge>
</TableCell>
<TableCell className="text-center">{item.unit}</TableCell>
<TableCell className="text-center">{item.stockQty}</TableCell>
<TableCell className="text-center">{item.safetyStock}</TableCell>
<TableCell className="text-center">
<div className="flex flex-col items-center">
<span>{item.lotCount}</span>
{item.lotDaysElapsed > 0 && (
<span className="text-xs text-muted-foreground">
{item.lotDaysElapsed}
</span>
)}
</div>
</TableCell>
<TableCell className="text-center">
{item.status ? (
<span className={item.status === 'low' ? 'text-orange-600 font-medium' : ''}>
{STOCK_STATUS_LABELS[item.status]}
</span>
) : (
<span className="text-gray-400">-</span>
)}
</TableCell>
<TableCell className="text-center">{item.location}</TableCell>
</TableRow>
);
},
// 모바일 카드 렌더링
renderMobileCard: (
item: StockItem,
index: number,
globalIndex: number,
handlers: SelectionHandlers & RowClickHandlers<StockItem>
) => {
return (
<ListMobileCard
key={item.id}
id={item.id}
isSelected={handlers.isSelected}
onToggleSelection={handlers.onToggle}
onClick={() => handleRowClick(item)}
headerBadges={
<>
<Badge variant="outline" className="text-xs">#{globalIndex}</Badge>
<Badge variant="outline" className="text-xs">{item.itemCode}</Badge>
</>
}
title={item.itemName}
statusBadge={
<Badge className={`text-xs ${ITEM_TYPE_STYLES[item.itemType]}`}>
{ITEM_TYPE_LABELS[item.itemType]}
</Badge>
}
infoGrid={
<div className="grid grid-cols-2 gap-x-4 gap-y-3">
<InfoField label="단위" value={item.unit} />
<InfoField label="위치" value={item.location} />
<InfoField label="재고량" value={`${item.stockQty}`} />
<InfoField label="안전재고" value={`${item.safetyStock}`} />
<InfoField
label="LOT"
value={`${item.lotCount}${item.lotDaysElapsed > 0 ? ` (${item.lotDaysElapsed}일 경과)` : ''}`}
/>
<InfoField
label="상태"
value={item.status ? STOCK_STATUS_LABELS[item.status] : '-'}
className={item.status === 'low' ? 'text-orange-600' : ''}
/>
</div>
}
actions={
handlers.isSelected && (
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
className="flex-1"
onClick={(e) => {
e.stopPropagation();
handleRowClick(item);
}}
>
<Eye className="w-4 h-4 mr-1" />
</Button>
</div>
)
}
/>
);
},
}),
[tabs, stats, tableFooter, handleRowClick, handleExcelDownload]
);
return <UniversalListPage config={config} />;
}