feat(WEB): UniversalListPage 전체 마이그레이션 및 코드 정리

- UniversalListPage/IntegratedListTemplateV2 컴포넌트 기능 개선
- 회계, HR, 건설, 고객센터, 결재, 설정 등 전체 리스트 컴포넌트 마이그레이션
- 테스트 페이지 및 미사용 API 라우트 정리 (board-test, order-management-test 등)
- 미들웨어 토큰 갱신 로직 개선
- AuthenticatedLayout 구조 개선
- claudedocs 문서 업데이트

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
byeongcheolryu
2026-01-16 15:19:09 +09:00
parent 8639eee5df
commit ad493bcea6
90 changed files with 19864 additions and 20305 deletions

View File

@@ -1,12 +1,16 @@
'use client';
/**
* 입고 목록 페이지
* IntegratedListTemplateV2 패턴 적용
* API 연동 버전
* 입고 목록 - UniversalListPage 마이그레이션
*
* 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
* - 서버 사이드 페이지네이션 (getReceivings API)
* - 통계 카드 (getReceivingStats API)
* - 고정 탭 필터 (전체/입고대기/입고완료)
* - 테이블 푸터 (요약 정보)
*/
import { useState, useMemo, useCallback, useEffect } from 'react';
import { useState, useEffect, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import {
Package,
@@ -15,17 +19,19 @@ import {
Calendar,
Eye,
} 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,
TabOption,
TableColumn,
StatCard,
} from '@/components/templates/IntegratedListTemplateV2';
UniversalListPage,
type UniversalListConfig,
type SelectionHandlers,
type RowClickHandlers,
type TabOption,
type StatCard,
type ListParams,
} from '@/components/templates/UniversalListPage';
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
import { getReceivings, getReceivingStats } from './actions';
import { RECEIVING_STATUS_LABELS, RECEIVING_STATUS_STYLES } from './types';
@@ -35,326 +41,277 @@ import type { ReceivingItem, ReceivingStats } from './types';
// 페이지당 항목 수
const ITEMS_PER_PAGE = 20;
// 필터 탭 정의
const FILTER_TABS: { key: string; label: string; status?: string }[] = [
{ key: 'all', label: '전체' },
{ key: 'receiving_pending', label: '입고대기', status: 'receiving_pending' },
{ key: 'completed', label: '입고완료', status: 'completed' },
];
export function ReceivingList() {
const router = useRouter();
// 상태 관리
const [searchTerm, setSearchTerm] = useState('');
const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
const [currentPage, setCurrentPage] = useState(1);
const [activeFilter, setActiveFilter] = useState<string>('all');
// API 데이터 상태
const [items, setItems] = useState<ReceivingItem[]>([]);
// ===== 통계 데이터 (외부 관리) =====
const [stats, setStats] = useState<ReceivingStats | null>(null);
const [totalItems, setTotalItems] = useState(0);
const [totalPages, setTotalPages] = useState(1);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
// 데이터 로드
const loadData = useCallback(async () => {
setIsLoading(true);
setError(null);
try {
// 목록 및 통계 병렬 조회
const [listResult, statsResult] = await Promise.all([
getReceivings({
page: currentPage,
perPage: ITEMS_PER_PAGE,
status: activeFilter !== 'all' ? activeFilter : undefined,
search: searchTerm || undefined,
}),
getReceivingStats(),
]);
if (listResult.success) {
setItems(listResult.data);
setTotalItems(listResult.pagination.total);
setTotalPages(listResult.pagination.lastPage);
} else {
setError(listResult.error || '목록 조회에 실패했습니다.');
}
if (statsResult.success && statsResult.data) {
setStats(statsResult.data);
}
} catch (err) {
if (isNextRedirectError(err)) throw err;
console.error('[ReceivingList] loadData error:', err);
setError('데이터를 불러오는 중 오류가 발생했습니다.');
} finally {
setIsLoading(false);
}
}, [currentPage, activeFilter, searchTerm]);
// 데이터 로드 트리거
// 초기 통계 로드
useEffect(() => {
loadData();
}, [loadData]);
// 통계 카드
const statCards: StatCard[] = useMemo(() => [
{
label: '입고대기',
value: `${stats?.receivingPendingCount ?? 0}`,
icon: Package,
iconColor: 'text-yellow-600',
},
{
label: '배송중',
value: `${stats?.shippingCount ?? 0}`,
icon: Truck,
iconColor: 'text-blue-600',
},
{
label: '검사대기',
value: `${stats?.inspectionPendingCount ?? 0}`,
icon: ClipboardCheck,
iconColor: 'text-orange-600',
},
{
label: '금일입고',
value: `${stats?.todayReceivingCount ?? 0}`,
icon: Calendar,
iconColor: 'text-green-600',
},
], [stats]);
// 테이블 컬럼
const tableColumns: TableColumn[] = [
{ key: 'no', label: '번호', className: 'w-[60px] text-center' },
{ key: 'orderNo', label: '발주번호', className: 'min-w-[150px]' },
{ key: 'itemCode', label: '품목코드', className: 'min-w-[130px]' },
{ key: 'itemName', label: '품목명', className: 'min-w-[150px]' },
{ key: 'supplier', label: '공급업체', className: 'min-w-[100px]' },
{ key: 'orderQty', label: '발주수량', className: 'w-[100px] text-center' },
{ key: 'receivingQty', label: '입고수량', className: 'w-[100px] text-center' },
{ key: 'lotNo', label: 'LOT번호', className: 'w-[120px] text-center' },
{ key: 'status', label: '상태', className: 'w-[100px] text-center' },
];
// 페이지네이션 설정
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 getReceivingStats();
if (result.success && result.data) {
setStats(result.data);
}
} catch (error) {
if (isNextRedirectError(error)) throw error;
console.error('[ReceivingList] loadStats error:', error);
}
return newSet;
});
};
loadStats();
}, []);
const handleToggleSelectAll = useCallback(() => {
if (selectedItems.size === items.length) {
setSelectedItems(new Set());
} else {
setSelectedItems(new Set(items.map((item) => item.id)));
}
}, [items, selectedItems.size]);
// 검색 변경 시 페이지 리셋
const handleSearchChange = (value: string) => {
setSearchTerm(value);
setCurrentPage(1);
};
// 탭 변경 시 페이지 리셋
const handleTabChange = (value: string) => {
setActiveFilter(value);
setCurrentPage(1);
setSelectedItems(new Set());
};
// 상세 보기
const handleView = useCallback(
(id: string) => {
router.push(`/ko/material/receiving-management/${id}`);
// ===== 행 클릭 핸들러 =====
const handleRowClick = useCallback(
(item: ReceivingItem) => {
router.push(`/ko/material/receiving-management/${item.id}`);
},
[router]
);
// 테이블 행 렌더링
const renderTableRow = (item: ReceivingItem, index: number, globalIndex: number) => {
const isSelected = selectedItems.has(item.id);
// ===== 통계 카드 =====
const statCards: StatCard[] = useMemo(
() => [
{
label: '입고대기',
value: `${stats?.receivingPendingCount ?? 0}`,
icon: Package,
iconColor: 'text-yellow-600',
},
{
label: '배송중',
value: `${stats?.shippingCount ?? 0}`,
icon: Truck,
iconColor: 'text-blue-600',
},
{
label: '검사대기',
value: `${stats?.inspectionPendingCount ?? 0}`,
icon: ClipboardCheck,
iconColor: 'text-orange-600',
},
{
label: '금일입고',
value: `${stats?.todayReceivingCount ?? 0}`,
icon: Calendar,
iconColor: 'text-green-600',
},
],
[stats]
);
return (
<TableRow
key={item.id}
className={`cursor-pointer hover:bg-muted/50 ${isSelected ? 'bg-blue-50' : ''}`}
onClick={() => handleView(item.id)}
>
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
<Checkbox
checked={isSelected}
onCheckedChange={() => handleToggleSelection(item.id)}
/>
</TableCell>
<TableCell className="text-center text-muted-foreground">{globalIndex}</TableCell>
<TableCell className="font-medium">{item.orderNo}</TableCell>
<TableCell>{item.itemCode}</TableCell>
<TableCell className="max-w-[150px] truncate">{item.itemName}</TableCell>
<TableCell>{item.supplier}</TableCell>
<TableCell className="text-center">
{item.orderQty} {item.orderUnit}
</TableCell>
<TableCell className="text-center">
{item.receivingQty !== undefined ? item.receivingQty : '-'}
</TableCell>
<TableCell className="text-center">{item.lotNo || '-'}</TableCell>
<TableCell className="text-center">
<Badge className={`text-xs ${RECEIVING_STATUS_STYLES[item.status]}`}>
{RECEIVING_STATUS_LABELS[item.status]}
</Badge>
// ===== 탭 옵션 (고정) =====
const tabs: TabOption[] = useMemo(
() => [
{ value: 'all', label: '전체', count: totalItems },
{ value: 'receiving_pending', label: '입고대기', count: stats?.receivingPendingCount ?? 0 },
{ value: 'completed', label: '입고완료', count: stats?.todayReceivingCount ?? 0 },
],
[totalItems, stats]
);
// ===== 테이블 푸터 =====
const tableFooter = useMemo(
() => (
<TableRow className="bg-gray-50 hover:bg-gray-50">
<TableCell colSpan={10} className="py-3">
<span className="text-sm text-muted-foreground">
{totalItems} / {stats?.receivingPendingCount ?? 0} / {' '}
{stats?.inspectionPendingCount ?? 0}
</span>
</TableCell>
</TableRow>
);
};
// 모바일 카드 렌더링
const renderMobileCard = (
item: ReceivingItem,
index: number,
globalIndex: number,
isSelected: boolean,
onToggle: () => void
) => {
return (
<ListMobileCard
id={item.id}
isSelected={isSelected}
onToggleSelection={onToggle}
onClick={() => handleView(item.id)}
headerBadges={
<>
<Badge variant="outline" className="text-xs">
#{globalIndex}
</Badge>
<Badge variant="outline" className="text-xs">
{item.orderNo}
</Badge>
</>
}
title={item.itemName}
statusBadge={
<Badge className={`text-xs ${RECEIVING_STATUS_STYLES[item.status]}`}>
{RECEIVING_STATUS_LABELS[item.status]}
</Badge>
}
infoGrid={
<div className="grid grid-cols-2 gap-x-4 gap-y-3">
<InfoField label="품목코드" value={item.itemCode} />
<InfoField label="공급업체" value={item.supplier} />
<InfoField label="발주수량" value={`${item.orderQty} ${item.orderUnit}`} />
<InfoField
label="입고수량"
value={item.receivingQty !== undefined ? `${item.receivingQty}` : '-'}
/>
<InfoField label="LOT번호" value={item.lotNo || '-'} />
</div>
}
actions={
isSelected && (
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
className="flex-1"
onClick={(e) => {
e.stopPropagation();
handleView(item.id);
}}
>
<Eye className="w-4 h-4 mr-1" />
</Button>
</div>
)
}
/>
);
};
// 탭 옵션
const tabs: TabOption[] = FILTER_TABS.map((tab) => ({
value: tab.key,
label: tab.label,
count: tab.key === 'all'
? totalItems
: tab.key === 'receiving_pending'
? (stats?.receivingPendingCount ?? 0)
: (stats?.todayReceivingCount ?? 0),
}));
// 하단 요약
const tableFooter = (
<TableRow className="bg-gray-50 hover:bg-gray-50">
<TableCell colSpan={tableColumns.length + 1} className="py-3">
<span className="text-sm text-muted-foreground">
{totalItems} / {stats?.receivingPendingCount ?? 0} / {' '}
{stats?.inspectionPendingCount ?? 0}
</span>
</TableCell>
</TableRow>
),
[totalItems, stats]
);
// 로딩 상태
if (isLoading && items.length === 0) {
return <ContentLoadingSpinner text="입고 목록을 불러오는 중..." />;
}
// ===== UniversalListPage Config =====
const config: UniversalListConfig<ReceivingItem> = useMemo(
() => ({
// 페이지 기본 정보
title: '입고 목록',
description: '입고 관리',
icon: Package,
basePath: '/material/receiving-management',
// 에러 상태
if (error && items.length === 0) {
return (
<div className="flex flex-col items-center justify-center min-h-[400px] gap-4">
<p className="text-muted-foreground">{error}</p>
<Button onClick={loadData}> </Button>
</div>
);
}
// ID 추출
idField: 'id',
return (
<IntegratedListTemplateV2<ReceivingItem>
title="입고 목록"
icon={Package}
stats={statCards}
searchValue={searchTerm}
onSearchChange={handleSearchChange}
searchPlaceholder="발주번호, 품목코드, 품목명, 공급업체 검색..."
tabs={tabs}
activeTab={activeFilter}
onTabChange={handleTabChange}
tableColumns={tableColumns}
data={items}
totalCount={totalItems}
allData={items}
selectedItems={selectedItems}
onToggleSelection={handleToggleSelection}
onToggleSelectAll={handleToggleSelectAll}
getItemId={(item) => item.id}
renderTableRow={renderTableRow}
renderMobileCard={renderMobileCard}
pagination={pagination}
tableFooter={tableFooter}
/>
// API 액션 (서버 사이드 페이지네이션)
actions: {
getList: async (params?: ListParams) => {
try {
const result = await getReceivings({
page: params?.page || 1,
perPage: params?.pageSize || ITEMS_PER_PAGE,
status: params?.tab !== 'all' ? params?.tab : undefined,
search: params?.search || undefined,
});
if (result.success) {
// 통계 다시 로드
const statsResult = await getReceivingStats();
if (statsResult.success && statsResult.data) {
setStats(statsResult.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: 'orderNo', label: '발주번호', className: 'min-w-[150px]' },
{ key: 'itemCode', label: '품목코드', className: 'min-w-[130px]' },
{ key: 'itemName', label: '품목명', className: 'min-w-[150px]' },
{ key: 'supplier', label: '공급업체', className: 'min-w-[100px]' },
{ key: 'orderQty', label: '발주수량', className: 'w-[100px] text-center' },
{ key: 'receivingQty', label: '입고수량', className: 'w-[100px] text-center' },
{ key: 'lotNo', label: 'LOT번호', className: 'w-[120px] text-center' },
{ key: 'status', label: '상태', className: 'w-[100px] text-center' },
],
// 서버 사이드 페이지네이션
clientSideFiltering: false,
itemsPerPage: ITEMS_PER_PAGE,
// 검색
searchPlaceholder: '발주번호, 품목코드, 품목명, 공급업체 검색...',
// 탭 설정
tabs,
defaultTab: 'all',
// 통계 카드
stats: statCards,
// 테이블 푸터
tableFooter,
// 테이블 행 렌더링
renderTableRow: (
item: ReceivingItem,
index: number,
globalIndex: number,
handlers: SelectionHandlers & RowClickHandlers<ReceivingItem>
) => {
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.orderNo}</TableCell>
<TableCell>{item.itemCode}</TableCell>
<TableCell className="max-w-[150px] truncate">{item.itemName}</TableCell>
<TableCell>{item.supplier}</TableCell>
<TableCell className="text-center">
{item.orderQty} {item.orderUnit}
</TableCell>
<TableCell className="text-center">
{item.receivingQty !== undefined ? item.receivingQty : '-'}
</TableCell>
<TableCell className="text-center">{item.lotNo || '-'}</TableCell>
<TableCell className="text-center">
<Badge className={`text-xs ${RECEIVING_STATUS_STYLES[item.status]}`}>
{RECEIVING_STATUS_LABELS[item.status]}
</Badge>
</TableCell>
</TableRow>
);
},
// 모바일 카드 렌더링
renderMobileCard: (
item: ReceivingItem,
index: number,
globalIndex: number,
handlers: SelectionHandlers & RowClickHandlers<ReceivingItem>
) => {
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.orderNo}
</Badge>
</>
}
title={item.itemName}
statusBadge={
<Badge className={`text-xs ${RECEIVING_STATUS_STYLES[item.status]}`}>
{RECEIVING_STATUS_LABELS[item.status]}
</Badge>
}
infoGrid={
<div className="grid grid-cols-2 gap-x-4 gap-y-3">
<InfoField label="품목코드" value={item.itemCode} />
<InfoField label="공급업체" value={item.supplier} />
<InfoField label="발주수량" value={`${item.orderQty} ${item.orderUnit}`} />
<InfoField
label="입고수량"
value={item.receivingQty !== undefined ? `${item.receivingQty}` : '-'}
/>
<InfoField label="LOT번호" value={item.lotNo || '-'} />
</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, statCards, tableFooter, handleRowClick]
);
return <UniversalListPage config={config} />;
}

View File

@@ -1,12 +1,16 @@
'use client';
/**
* 재고현황 목록 페이지
* IntegratedListTemplateV2 패턴 적용
* API 연동 완료 (2025-12-26)
* 재고현황 목록 - UniversalListPage 마이그레이션
*
* 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
* - 서버 사이드 페이지네이션 (getStocks API)
* - 통계 카드 (getStockStats API)
* - 품목유형별 탭 필터 (getStockStatsByType API)
* - 테이블 푸터 (요약 정보)
*/
import { useState, useMemo, useCallback, useEffect } from 'react';
import { useState, useEffect, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import {
Package,
@@ -16,17 +20,19 @@ import {
Download,
Eye,
} 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,
TabOption,
TableColumn,
StatCard,
} from '@/components/templates/IntegratedListTemplateV2';
UniversalListPage,
type UniversalListConfig,
type SelectionHandlers,
type RowClickHandlers,
type TabOption,
type StatCard,
type ListParams,
} from '@/components/templates/UniversalListPage';
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
import { getStocks, getStockStats, getStockStatsByType } from './actions';
import { ITEM_TYPE_LABELS, ITEM_TYPE_STYLES, STOCK_STATUS_LABELS } from './types';
@@ -38,359 +44,325 @@ const ITEMS_PER_PAGE = 20;
export function StockStatusList() {
const router = useRouter();
const [searchTerm, setSearchTerm] = useState('');
const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
const [currentPage, setCurrentPage] = useState(1);
const [activeFilter, setActiveFilter] = useState<'all' | ItemType>('all');
// API 데이터 상태
const [items, setItems] = useState<StockItem[]>([]);
// ===== 통계 및 품목유형별 통계 (외부 관리) =====
const [stockStats, setStockStats] = useState<StockStats | null>(null);
const [typeStats, setTypeStats] = useState<Record<string, { label: string; count: number; total_qty: number | string }>>({});
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [totalItems, setTotalItems] = useState(0);
const [lastPage, setLastPage] = useState(1);
// API 데이터 로드
const loadData = useCallback(async () => {
setIsLoading(true);
setError(null);
try {
const [listResult, statsResult, typeStatsResult] = await Promise.all([
getStocks({
page: currentPage,
perPage: ITEMS_PER_PAGE,
itemType: activeFilter !== 'all' ? activeFilter : undefined,
search: searchTerm || undefined,
}),
getStockStats(),
getStockStatsByType(),
]);
if (listResult.success) {
setItems(listResult.data);
setTotalItems(listResult.pagination.total);
setLastPage(listResult.pagination.lastPage);
} else {
setError(listResult.error || '재고 목록 조회에 실패했습니다.');
}
if (statsResult.success && statsResult.data) {
setStockStats(statsResult.data);
}
if (typeStatsResult.success && typeStatsResult.data) {
setTypeStats(typeStatsResult.data);
}
} catch (err) {
if (isNextRedirectError(err)) throw err;
console.error('[StockStatusList] loadData error:', err);
setError('데이터를 불러오는 중 오류가 발생했습니다.');
} finally {
setIsLoading(false);
}
}, [currentPage, activeFilter, searchTerm]);
// 데이터 로드
// 초기 통계 로드
useEffect(() => {
loadData();
}, [loadData]);
// 통계 카드
const stats: StatCard[] = [
{
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',
},
];
// 테이블 컬럼
const tableColumns: TableColumn[] = [
{ 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' },
{ key: 'actions', label: '작업', className: 'w-[60px] text-center' },
];
// 선택 핸들러 (Hooks는 조건부 return 전에 선언되어야 함)
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 [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);
}
return newSet;
});
};
loadStats();
}, []);
const handleToggleSelectAll = useCallback(() => {
if (selectedItems.size === items.length) {
setSelectedItems(new Set());
} else {
setSelectedItems(new Set(items.map((item) => item.id)));
}
}, [items, selectedItems.size]);
// ===== 행 클릭 핸들러 =====
const handleRowClick = useCallback(
(item: StockItem) => {
router.push(`/ko/material/stock-status/${item.id}`);
},
[router]
);
// 검색 변경 시 페이지 리셋
const handleSearchChange = useCallback((value: string) => {
setSearchTerm(value);
setCurrentPage(1);
}, []);
// 탭 변경 시 페이지 리셋
const handleTabChange = useCallback((value: string) => {
setActiveFilter(value as 'all' | ItemType);
setCurrentPage(1);
setSelectedItems(new Set());
}, []);
// 엑셀 다운로드
// ===== 엑셀 다운로드 =====
const handleExcelDownload = useCallback(() => {
console.log('엑셀 다운로드:', items);
console.log('엑셀 다운로드');
// TODO: 엑셀 다운로드 기능 구현
}, [items]);
}, []);
// 상세 보기
const handleView = useCallback((id: string) => {
router.push(`/ko/material/stock-status/${id}`);
}, [router]);
// ===== 통계 카드 =====
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]
);
// 재고부족 수 (API 통계 사용)
const lowStockCount = stockStats?.lowCount || 0;
// ===== 탭 옵션 (기본 탭 + 품목유형별 통계) =====
const tabs: TabOption[] = useMemo(() => {
// 기본 탭 정의 (API 데이터 없어도 항상 표시)
const defaultTabs: { value: string; label: string }[] = [
{ value: 'all', label: '전체' },
{ value: 'raw_material', label: '원자재' },
{ value: 'bent_part', label: '절곡부품' },
{ value: 'purchased_part', label: '구매부품' },
{ value: 'sub_material', label: '부자재' },
{ value: 'consumable', label: '소모품' },
];
// 테이블 행 렌더링
const renderTableRow = (item: StockItem, index: number, globalIndex: number) => {
const isSelected = selectedItems.has(item.id);
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
key={item.id}
className={`cursor-pointer hover:bg-muted/50 ${isSelected ? 'bg-blue-50' : ''}`}
onClick={() => handleView(item.id)}
>
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
<Checkbox
checked={isSelected}
onCheckedChange={() => handleToggleSelection(item.id)}
/>
</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">
<span className={item.status === 'low' ? 'text-orange-600 font-medium' : ''}>
{STOCK_STATUS_LABELS[item.status]}
<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>
<TableCell className="text-center">{item.location}</TableCell>
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
{isSelected && (
<Eye
className="w-5 h-5 text-gray-500 hover:text-gray-700 cursor-pointer mx-auto"
onClick={() => handleView(item.id)}
/>
)}
</TableCell>
</TableRow>
);
};
}, [totalItems, stockStats?.lowCount]);
// 모바일 카드 렌더링
const renderMobileCard = (
item: StockItem,
index: number,
globalIndex: number,
isSelected: boolean,
onToggle: () => void
) => {
return (
<ListMobileCard
id={item.id}
isSelected={isSelected}
onToggleSelection={onToggle}
onClick={() => handleView(item.id)}
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={STOCK_STATUS_LABELS[item.status]}
className={item.status === 'low' ? 'text-orange-600' : ''}
/>
</div>
}
actions={
isSelected && (
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
className="flex-1"
onClick={(e) => { e.stopPropagation(); handleView(item.id); }}
>
<Eye className="w-4 h-4 mr-1" />
</Button>
</div>
)
}
/>
);
};
// ===== UniversalListPage Config =====
const config: UniversalListConfig<StockItem> = useMemo(
() => ({
// 페이지 기본 정보
title: '재고 목록',
description: '재고현황 관리',
icon: Package,
basePath: '/material/stock-status',
// 탭 옵션 (API typeStats 사용)
const tabs: TabOption[] = useMemo(() => {
const allTab: TabOption = {
value: 'all',
label: '전체',
count: stockStats?.totalItems || 0,
};
// ID 추출
idField: 'id',
const typeTabs: TabOption[] = Object.entries(typeStats).map(([key, stat]) => ({
value: key,
label: stat.label,
count: stat.count,
}));
// 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,
});
return [allTab, ...typeTabs];
}, [typeStats, stockStats?.totalItems]);
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);
}
// 페이지네이션 설정 (API 서버 사이드 페이지네이션)
const pagination = {
currentPage,
totalPages: lastPage,
totalItems,
itemsPerPage: ITEMS_PER_PAGE,
onPageChange: setCurrentPage,
};
// totalItems 업데이트 (푸터용)
setTotalItems(result.pagination.total);
// 로딩 상태 표시 (모든 Hooks 선언 후)
if (isLoading && items.length === 0) {
return <ContentLoadingSpinner text="재고 목록을 불러오는 중..." />;
}
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: '데이터 로드 중 오류가 발생했습니다.' };
}
},
},
// 에러 상태 표시
if (error && items.length === 0) {
return (
<div className="flex flex-col items-center justify-center min-h-[400px] gap-4">
<AlertCircle className="w-12 h-12 text-red-500" />
<p className="text-lg text-muted-foreground">{error}</p>
<Button onClick={loadData}> </Button>
</div>
);
}
// 테이블 컬럼
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' },
],
// 헤더 액
const headerActions = (
<Button variant="outline" className="ml-auto" onClick={handleExcelDownload}>
<Download className="w-4 h-4 mr-1.5" />
</Button>
// 서버 사이드 페이지네이
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">
<span className={item.status === 'low' ? 'text-orange-600 font-medium' : ''}>
{STOCK_STATUS_LABELS[item.status]}
</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={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]
);
// 하단 요약 (테이블 푸터)
const tableFooter = (
<TableRow className="bg-gray-50 hover:bg-gray-50">
<TableCell colSpan={tableColumns.length + 1} className="py-3">
<span className="text-sm text-muted-foreground">
{totalItems} / {lowStockCount}
</span>
</TableCell>
</TableRow>
);
return (
<IntegratedListTemplateV2<StockItem>
title="재고 목록"
icon={Package}
headerActions={headerActions}
stats={stats}
searchValue={searchTerm}
onSearchChange={handleSearchChange}
searchPlaceholder="품목코드, 품목명 검색..."
tabs={tabs}
activeTab={activeFilter}
onTabChange={handleTabChange}
tableColumns={tableColumns}
data={items}
totalCount={totalItems}
allData={items}
selectedItems={selectedItems}
onToggleSelection={handleToggleSelection}
onToggleSelectAll={handleToggleSelectAll}
getItemId={(item) => item.id}
renderTableRow={renderTableRow}
renderMobileCard={renderMobileCard}
pagination={pagination}
tableFooter={tableFooter}
/>
);
return <UniversalListPage config={config} />;
}