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:
@@ -1,27 +1,23 @@
|
||||
'use client';
|
||||
|
||||
/**
|
||||
* 악성채권 추심관리 - UniversalListPage 마이그레이션
|
||||
*
|
||||
* 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
|
||||
* - 클라이언트 사이드 필터링 (검색, 거래처, 상태, 정렬)
|
||||
* - Stats 카드 (API 통계 또는 로컬 계산)
|
||||
* - tableHeaderActions: 3개 Select 필터
|
||||
* - Switch 토글 (설정)
|
||||
* - 삭제 다이얼로그 (deleteConfirmMessage)
|
||||
*/
|
||||
|
||||
import { useState, useMemo, useCallback, useTransition } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import {
|
||||
AlertTriangle,
|
||||
Pencil,
|
||||
Trash2,
|
||||
Eye,
|
||||
} from 'lucide-react';
|
||||
import { AlertTriangle, Pencil, Trash2, Eye } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import { TableRow, TableCell } from '@/components/ui/table';
|
||||
import {
|
||||
Select,
|
||||
@@ -30,16 +26,15 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { MobileCard } from '@/components/molecules/MobileCard';
|
||||
import {
|
||||
IntegratedListTemplateV2,
|
||||
type TableColumn,
|
||||
UniversalListPage,
|
||||
type UniversalListConfig,
|
||||
type SelectionHandlers,
|
||||
type RowClickHandlers,
|
||||
type StatCard,
|
||||
} from '@/components/templates/IntegratedListTemplateV2';
|
||||
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
|
||||
import type {
|
||||
BadDebtRecord,
|
||||
SortOption,
|
||||
} from './types';
|
||||
} from '@/components/templates/UniversalListPage';
|
||||
import type { BadDebtRecord, SortOption } from './types';
|
||||
import {
|
||||
COLLECTION_STATUS_LABELS,
|
||||
STATUS_FILTER_OPTIONS,
|
||||
@@ -48,6 +43,19 @@ import {
|
||||
} from './types';
|
||||
import { deleteBadDebt, toggleBadDebt } from './actions';
|
||||
|
||||
// ===== 테이블 컬럼 정의 =====
|
||||
const tableColumns = [
|
||||
{ key: 'no', label: 'No.', className: 'text-center w-[60px]' },
|
||||
{ key: 'vendorName', label: '거래처' },
|
||||
{ key: 'debtAmount', label: '채권금액', className: 'text-right w-[140px]' },
|
||||
{ key: 'occurrenceDate', label: '발생일', className: 'text-center w-[110px]' },
|
||||
{ key: 'overdueDays', label: '연체일수', className: 'text-center w-[100px]' },
|
||||
{ key: 'managerName', label: '담당자', className: 'w-[100px]' },
|
||||
{ key: 'status', label: '상태', className: 'text-center w-[100px]' },
|
||||
{ key: 'setting', label: '설정', className: 'text-center w-[80px]' },
|
||||
{ key: 'actions', label: '작업', className: 'text-center w-[120px]' },
|
||||
];
|
||||
|
||||
// ===== Props 타입 정의 =====
|
||||
interface BadDebtCollectionProps {
|
||||
initialData: BadDebtRecord[];
|
||||
@@ -63,407 +71,421 @@ interface BadDebtCollectionProps {
|
||||
// 거래처 목록 추출 (필터용)
|
||||
const getVendorOptions = (data: BadDebtRecord[]) => {
|
||||
const vendorMap = new Map<string, string>();
|
||||
data.forEach(item => {
|
||||
data.forEach((item) => {
|
||||
vendorMap.set(item.vendorId, item.vendorName);
|
||||
});
|
||||
return [
|
||||
{ value: 'all', label: '전체' },
|
||||
...Array.from(vendorMap.entries()).map(([id, name]) => ({
|
||||
value: id,
|
||||
label: name,
|
||||
})),
|
||||
];
|
||||
return Array.from(vendorMap.entries()).map(([id, name]) => ({
|
||||
value: id,
|
||||
label: name,
|
||||
}));
|
||||
};
|
||||
|
||||
export function BadDebtCollection({ initialData, initialSummary }: BadDebtCollectionProps) {
|
||||
const router = useRouter();
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
// ===== 상태 관리 =====
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [sortOption, setSortOption] = useState<SortOption>('latest');
|
||||
// ===== 외부 상태 (UniversalListPage 외부에서 관리) =====
|
||||
const [data, setData] = useState<BadDebtRecord[]>(initialData);
|
||||
const [vendorFilter, setVendorFilter] = useState<string>('all');
|
||||
const [statusFilter, setStatusFilter] = useState<string>('all');
|
||||
const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const itemsPerPage = 20;
|
||||
|
||||
// 삭제 다이얼로그
|
||||
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
|
||||
const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
|
||||
|
||||
// 데이터 (서버에서 받은 초기 데이터 사용)
|
||||
const [data, setData] = useState<BadDebtRecord[]>(initialData);
|
||||
const [sortOption, setSortOption] = useState<SortOption>('latest');
|
||||
|
||||
// 거래처 옵션
|
||||
const vendorOptions = useMemo(() => getVendorOptions(data), [data]);
|
||||
|
||||
// ===== 체크박스 핸들러 =====
|
||||
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 handleRowClick = useCallback(
|
||||
(item: BadDebtRecord) => {
|
||||
router.push(`/ko/accounting/bad-debt-collection/${item.id}`);
|
||||
},
|
||||
[router]
|
||||
);
|
||||
|
||||
// ===== 필터링된 데이터 =====
|
||||
const filteredData = useMemo(() => {
|
||||
let result = data.filter(item =>
|
||||
item.vendorName.includes(searchQuery) ||
|
||||
item.vendorCode.includes(searchQuery) ||
|
||||
item.businessNumber.includes(searchQuery)
|
||||
);
|
||||
|
||||
// 거래처 필터
|
||||
if (vendorFilter !== 'all') {
|
||||
result = result.filter(item => item.vendorId === vendorFilter);
|
||||
}
|
||||
|
||||
// 상태 필터
|
||||
if (statusFilter !== 'all') {
|
||||
result = result.filter(item => item.status === statusFilter);
|
||||
}
|
||||
|
||||
// 정렬
|
||||
switch (sortOption) {
|
||||
case 'latest':
|
||||
result.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
|
||||
break;
|
||||
case 'oldest':
|
||||
result.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
|
||||
break;
|
||||
}
|
||||
|
||||
return result;
|
||||
}, [data, searchQuery, vendorFilter, statusFilter, sortOption]);
|
||||
|
||||
const paginatedData = useMemo(() => {
|
||||
const startIndex = (currentPage - 1) * itemsPerPage;
|
||||
return filteredData.slice(startIndex, startIndex + itemsPerPage);
|
||||
}, [filteredData, currentPage, itemsPerPage]);
|
||||
|
||||
const totalPages = Math.ceil(filteredData.length / itemsPerPage);
|
||||
|
||||
// ===== 전체 선택 핸들러 =====
|
||||
const toggleSelectAll = useCallback(() => {
|
||||
if (selectedItems.size === filteredData.length && filteredData.length > 0) {
|
||||
setSelectedItems(new Set());
|
||||
} else {
|
||||
setSelectedItems(new Set(filteredData.map(item => item.id)));
|
||||
}
|
||||
}, [selectedItems.size, filteredData]);
|
||||
|
||||
// ===== 액션 핸들러 =====
|
||||
const handleRowClick = useCallback((item: BadDebtRecord) => {
|
||||
router.push(`/ko/accounting/bad-debt-collection/${item.id}`);
|
||||
}, [router]);
|
||||
|
||||
const handleEdit = useCallback((item: BadDebtRecord) => {
|
||||
router.push(`/ko/accounting/bad-debt-collection/${item.id}/edit`);
|
||||
}, [router]);
|
||||
|
||||
const handleDeleteClick = useCallback((id: string) => {
|
||||
setDeleteTargetId(id);
|
||||
setShowDeleteDialog(true);
|
||||
}, []);
|
||||
|
||||
const handleConfirmDelete = useCallback(() => {
|
||||
if (deleteTargetId) {
|
||||
startTransition(async () => {
|
||||
const result = await deleteBadDebt(deleteTargetId);
|
||||
if (result.success) {
|
||||
setData(prev => prev.filter(item => item.id !== deleteTargetId));
|
||||
setSelectedItems(prev => {
|
||||
const newSet = new Set(prev);
|
||||
newSet.delete(deleteTargetId);
|
||||
return newSet;
|
||||
});
|
||||
} else {
|
||||
console.error('[BadDebtCollection] Delete failed:', result.error);
|
||||
}
|
||||
});
|
||||
}
|
||||
setShowDeleteDialog(false);
|
||||
setDeleteTargetId(null);
|
||||
}, [deleteTargetId]);
|
||||
const handleEdit = useCallback(
|
||||
(item: BadDebtRecord) => {
|
||||
router.push(`/ko/accounting/bad-debt-collection/${item.id}/edit`);
|
||||
},
|
||||
[router]
|
||||
);
|
||||
|
||||
// 설정 토글 핸들러 (API 호출)
|
||||
const handleSettingToggle = useCallback((id: string, checked: boolean) => {
|
||||
// Optimistic update
|
||||
setData(prev => prev.map(item =>
|
||||
item.id === id ? { ...item, settingToggle: checked } : item
|
||||
));
|
||||
const handleSettingToggle = useCallback(
|
||||
(id: string, checked: boolean) => {
|
||||
// Optimistic update
|
||||
setData((prev) =>
|
||||
prev.map((item) => (item.id === id ? { ...item, settingToggle: checked } : item))
|
||||
);
|
||||
|
||||
startTransition(async () => {
|
||||
const result = await toggleBadDebt(id);
|
||||
if (!result.success) {
|
||||
// Rollback on error
|
||||
setData(prev => prev.map(item =>
|
||||
item.id === id ? { ...item, settingToggle: !checked } : item
|
||||
));
|
||||
console.error('[BadDebtCollection] Toggle failed:', result.error);
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
startTransition(async () => {
|
||||
const result = await toggleBadDebt(id);
|
||||
if (!result.success) {
|
||||
// Rollback on error
|
||||
setData((prev) =>
|
||||
prev.map((item) => (item.id === id ? { ...item, settingToggle: !checked } : item))
|
||||
);
|
||||
console.error('[BadDebtCollection] Toggle failed:', result.error);
|
||||
}
|
||||
});
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
// ===== 통계 카드 (API 통계 또는 로컬 계산) =====
|
||||
const statCards: StatCard[] = useMemo(() => {
|
||||
// ===== 통계 계산 =====
|
||||
const statsData = useMemo(() => {
|
||||
if (initialSummary) {
|
||||
// API 통계 데이터 사용
|
||||
return [
|
||||
{ label: '총 악성채권', value: `${initialSummary.total_amount.toLocaleString()}원`, icon: AlertTriangle, iconColor: 'text-red-500' },
|
||||
{ label: '추심중', value: `${initialSummary.collecting_amount.toLocaleString()}원`, icon: AlertTriangle, iconColor: 'text-orange-500' },
|
||||
{ label: '법적조치', value: `${initialSummary.legal_action_amount.toLocaleString()}원`, icon: AlertTriangle, iconColor: 'text-red-600' },
|
||||
{ label: '회수완료', value: `${initialSummary.recovered_amount.toLocaleString()}원`, icon: AlertTriangle, iconColor: 'text-green-500' },
|
||||
];
|
||||
return {
|
||||
totalAmount: initialSummary.total_amount,
|
||||
collectingAmount: initialSummary.collecting_amount,
|
||||
legalActionAmount: initialSummary.legal_action_amount,
|
||||
recoveredAmount: initialSummary.recovered_amount,
|
||||
};
|
||||
}
|
||||
|
||||
// 로컬 데이터로 계산 (fallback)
|
||||
const totalAmount = data.reduce((sum, d) => sum + d.debtAmount, 0);
|
||||
const collectingAmount = data.filter(d => d.status === 'collecting').reduce((sum, d) => sum + d.debtAmount, 0);
|
||||
const legalActionAmount = data.filter(d => d.status === 'legalAction').reduce((sum, d) => sum + d.debtAmount, 0);
|
||||
const recoveredAmount = data.filter(d => d.status === 'recovered').reduce((sum, d) => sum + d.debtAmount, 0);
|
||||
const collectingAmount = data
|
||||
.filter((d) => d.status === 'collecting')
|
||||
.reduce((sum, d) => sum + d.debtAmount, 0);
|
||||
const legalActionAmount = data
|
||||
.filter((d) => d.status === 'legalAction')
|
||||
.reduce((sum, d) => sum + d.debtAmount, 0);
|
||||
const recoveredAmount = data
|
||||
.filter((d) => d.status === 'recovered')
|
||||
.reduce((sum, d) => sum + d.debtAmount, 0);
|
||||
|
||||
return [
|
||||
{ label: '총 악성채권', value: `${totalAmount.toLocaleString()}원`, icon: AlertTriangle, iconColor: 'text-red-500' },
|
||||
{ label: '추심중', value: `${collectingAmount.toLocaleString()}원`, icon: AlertTriangle, iconColor: 'text-orange-500' },
|
||||
{ label: '법적조치', value: `${legalActionAmount.toLocaleString()}원`, icon: AlertTriangle, iconColor: 'text-red-600' },
|
||||
{ label: '회수완료', value: `${recoveredAmount.toLocaleString()}원`, icon: AlertTriangle, iconColor: 'text-green-500' },
|
||||
];
|
||||
return { totalAmount, collectingAmount, legalActionAmount, recoveredAmount };
|
||||
}, [data, initialSummary]);
|
||||
|
||||
// ===== 테이블 컬럼 =====
|
||||
const tableColumns: TableColumn[] = useMemo(() => [
|
||||
{ key: 'no', label: 'No.', className: 'text-center w-[60px]' },
|
||||
{ key: 'vendorName', label: '거래처' },
|
||||
{ key: 'debtAmount', label: '채권금액', className: 'text-right w-[140px]' },
|
||||
{ key: 'occurrenceDate', label: '발생일', className: 'text-center w-[110px]' },
|
||||
{ key: 'overdueDays', label: '연체일수', className: 'text-center w-[100px]' },
|
||||
{ key: 'managerName', label: '담당자', className: 'w-[100px]' },
|
||||
{ key: 'status', label: '상태', className: 'text-center w-[100px]' },
|
||||
{ key: 'setting', label: '설정', className: 'text-center w-[80px]' },
|
||||
{ key: 'actions', label: '작업', className: 'text-center w-[120px]' },
|
||||
], []);
|
||||
// ===== UniversalListPage Config =====
|
||||
const config: UniversalListConfig<BadDebtRecord> = useMemo(
|
||||
() => ({
|
||||
// 페이지 기본 정보
|
||||
title: '악성채권 추심관리',
|
||||
description: '연체 및 악성채권 현황을 추적하고 관리합니다',
|
||||
icon: AlertTriangle,
|
||||
basePath: '/accounting/bad-debt-collection',
|
||||
|
||||
// ===== 테이블 행 렌더링 =====
|
||||
const renderTableRow = useCallback((item: BadDebtRecord, index: number, globalIndex: number) => {
|
||||
const isSelected = selectedItems.has(item.id);
|
||||
// ID 추출
|
||||
idField: '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>
|
||||
{/* No. */}
|
||||
<TableCell className="text-center text-sm text-gray-500">{globalIndex}</TableCell>
|
||||
{/* 거래처 */}
|
||||
<TableCell className="font-medium">{item.vendorName}</TableCell>
|
||||
{/* 채권금액 */}
|
||||
<TableCell className="text-right font-medium text-red-600">
|
||||
{item.debtAmount.toLocaleString()}원
|
||||
</TableCell>
|
||||
{/* 발생일 */}
|
||||
<TableCell className="text-center">{item.occurrenceDate}</TableCell>
|
||||
{/* 연체일수 */}
|
||||
<TableCell className="text-center">{item.overdueDays}일</TableCell>
|
||||
{/* 담당자 */}
|
||||
<TableCell>{item.assignedManager?.name || '-'}</TableCell>
|
||||
{/* 상태 */}
|
||||
<TableCell className="text-center">
|
||||
<Badge variant="outline" className={STATUS_BADGE_STYLES[item.status]}>
|
||||
{COLLECTION_STATUS_LABELS[item.status]}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
{/* 설정 */}
|
||||
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
|
||||
<Switch
|
||||
checked={item.settingToggle}
|
||||
onCheckedChange={(checked) => handleSettingToggle(item.id, checked)}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</TableCell>
|
||||
{/* 작업 */}
|
||||
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
|
||||
{isSelected && (
|
||||
<div className="flex items-center justify-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={() => handleEdit(item)}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-red-500 hover:text-red-600 hover:bg-red-50"
|
||||
onClick={() => handleDeleteClick(item.id)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
}, [selectedItems, toggleSelection, handleRowClick, handleEdit, handleDeleteClick, handleSettingToggle, isPending]);
|
||||
// API 액션
|
||||
actions: {
|
||||
getList: async () => {
|
||||
return {
|
||||
success: true,
|
||||
data: data,
|
||||
totalCount: data.length,
|
||||
};
|
||||
},
|
||||
deleteItem: async (id: string) => {
|
||||
const result = await deleteBadDebt(id);
|
||||
if (result.success) {
|
||||
setData((prev) => prev.filter((item) => item.id !== id));
|
||||
}
|
||||
return { success: result.success, error: result.error };
|
||||
},
|
||||
},
|
||||
|
||||
// ===== 모바일 카드 렌더링 =====
|
||||
const renderMobileCard = useCallback((
|
||||
item: BadDebtRecord,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
isSelected: boolean,
|
||||
onToggle: () => void
|
||||
) => {
|
||||
return (
|
||||
<ListMobileCard
|
||||
id={item.id}
|
||||
title={item.vendorName}
|
||||
headerBadges={
|
||||
<Badge variant="outline" className={STATUS_BADGE_STYLES[item.status]}>
|
||||
{COLLECTION_STATUS_LABELS[item.status]}
|
||||
</Badge>
|
||||
// 테이블 컬럼
|
||||
columns: tableColumns,
|
||||
|
||||
// 클라이언트 사이드 필터링
|
||||
clientSideFiltering: true,
|
||||
itemsPerPage: 20,
|
||||
|
||||
// 검색 필터
|
||||
searchPlaceholder: '거래처명, 거래처코드, 사업자번호 검색...',
|
||||
searchFilter: (item, searchValue) => {
|
||||
const search = searchValue.toLowerCase();
|
||||
return (
|
||||
item.vendorName.toLowerCase().includes(search) ||
|
||||
item.vendorCode.toLowerCase().includes(search) ||
|
||||
item.businessNumber.toLowerCase().includes(search)
|
||||
);
|
||||
},
|
||||
|
||||
// 필터 설정 (모바일용)
|
||||
filterConfig: [
|
||||
{
|
||||
key: 'vendor',
|
||||
label: '거래처',
|
||||
type: 'single',
|
||||
options: vendorOptions,
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
label: '상태',
|
||||
type: 'single',
|
||||
options: STATUS_FILTER_OPTIONS.filter((o) => o.value !== 'all').map((o) => ({
|
||||
value: o.value,
|
||||
label: o.label,
|
||||
})),
|
||||
},
|
||||
{
|
||||
key: 'sortBy',
|
||||
label: '정렬',
|
||||
type: 'single',
|
||||
options: SORT_OPTIONS.map((o) => ({
|
||||
value: o.value,
|
||||
label: o.label,
|
||||
})),
|
||||
},
|
||||
],
|
||||
initialFilters: {
|
||||
vendor: 'all',
|
||||
status: 'all',
|
||||
sortBy: 'latest',
|
||||
},
|
||||
filterTitle: '악성채권 필터',
|
||||
|
||||
// 커스텀 필터 함수
|
||||
customFilterFn: (items) => {
|
||||
let result = [...items];
|
||||
|
||||
// 거래처 필터
|
||||
if (vendorFilter !== 'all') {
|
||||
result = result.filter((item) => item.vendorId === vendorFilter);
|
||||
}
|
||||
isSelected={isSelected}
|
||||
onToggleSelection={onToggle}
|
||||
infoGrid={
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<InfoField label="채권금액" value={`${item.debtAmount.toLocaleString()}원`} className="text-red-600" />
|
||||
<InfoField label="연체일수" value={`${item.overdueDays}일`} />
|
||||
<InfoField label="발생일" value={item.occurrenceDate} />
|
||||
<InfoField label="담당자" value={item.assignedManager?.name || '-'} />
|
||||
</div>
|
||||
|
||||
// 상태 필터
|
||||
if (statusFilter !== 'all') {
|
||||
result = result.filter((item) => item.status === statusFilter);
|
||||
}
|
||||
actions={
|
||||
isSelected ? (
|
||||
<div className="flex gap-2 w-full">
|
||||
<Button variant="outline" className="flex-1" onClick={() => handleRowClick(item)}>
|
||||
<Eye className="w-4 h-4 mr-2" /> 상세
|
||||
</Button>
|
||||
<Button variant="outline" className="flex-1" onClick={() => handleEdit(item)}>
|
||||
<Pencil className="w-4 h-4 mr-2" /> 수정
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="flex-1 text-red-500 border-red-200 hover:bg-red-50 hover:text-red-600"
|
||||
onClick={() => handleDeleteClick(item.id)}
|
||||
>
|
||||
<Trash2 className="w-4 h-4 mr-2" /> 삭제
|
||||
</Button>
|
||||
</div>
|
||||
) : undefined
|
||||
|
||||
return result;
|
||||
},
|
||||
|
||||
// 커스텀 정렬 함수
|
||||
customSortFn: (items) => {
|
||||
const sorted = [...items];
|
||||
|
||||
switch (sortOption) {
|
||||
case 'oldest':
|
||||
sorted.sort(
|
||||
(a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()
|
||||
);
|
||||
break;
|
||||
default: // latest
|
||||
sorted.sort(
|
||||
(a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
|
||||
);
|
||||
break;
|
||||
}
|
||||
onClick={() => handleRowClick(item)}
|
||||
/>
|
||||
);
|
||||
}, [handleRowClick, handleEdit, handleDeleteClick]);
|
||||
|
||||
// ===== 테이블 헤더 액션 (3개 필터) =====
|
||||
const tableHeaderActions = (
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
{/* 거래처 필터 */}
|
||||
<Select value={vendorFilter} onValueChange={setVendorFilter}>
|
||||
<SelectTrigger className="w-[150px]">
|
||||
<SelectValue placeholder="전체" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{vendorOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
return sorted;
|
||||
},
|
||||
|
||||
{/* 상태 필터 */}
|
||||
<Select value={statusFilter} onValueChange={setStatusFilter}>
|
||||
<SelectTrigger className="w-[120px]">
|
||||
<SelectValue placeholder="상태" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{STATUS_FILTER_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
// 테이블 헤더 액션 (3개 필터)
|
||||
tableHeaderActions: () => (
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
{/* 거래처 필터 */}
|
||||
<Select value={vendorFilter} onValueChange={setVendorFilter}>
|
||||
<SelectTrigger className="w-[150px]">
|
||||
<SelectValue placeholder="전체" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">전체</SelectItem>
|
||||
{vendorOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* 정렬 */}
|
||||
<Select value={sortOption} onValueChange={(value) => setSortOption(value as SortOption)}>
|
||||
<SelectTrigger className="w-[120px]">
|
||||
<SelectValue placeholder="정렬" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{SORT_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
);
|
||||
{/* 상태 필터 */}
|
||||
<Select value={statusFilter} onValueChange={setStatusFilter}>
|
||||
<SelectTrigger className="w-[120px]">
|
||||
<SelectValue placeholder="상태" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{STATUS_FILTER_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
return (
|
||||
<>
|
||||
<IntegratedListTemplateV2
|
||||
title="악성채권 추심관리"
|
||||
description="연체 및 악성채권 현황을 추적하고 관리합니다"
|
||||
icon={AlertTriangle}
|
||||
stats={statCards}
|
||||
searchValue={searchQuery}
|
||||
onSearchChange={setSearchQuery}
|
||||
searchPlaceholder="거래처명, 거래처코드, 사업자번호 검색..."
|
||||
tableHeaderActions={tableHeaderActions}
|
||||
tableColumns={tableColumns}
|
||||
data={paginatedData}
|
||||
totalCount={filteredData.length}
|
||||
allData={filteredData}
|
||||
selectedItems={selectedItems}
|
||||
onToggleSelection={toggleSelection}
|
||||
onToggleSelectAll={toggleSelectAll}
|
||||
getItemId={(item: BadDebtRecord) => item.id}
|
||||
renderTableRow={renderTableRow}
|
||||
renderMobileCard={renderMobileCard}
|
||||
pagination={{
|
||||
currentPage,
|
||||
totalPages,
|
||||
totalItems: filteredData.length,
|
||||
itemsPerPage,
|
||||
onPageChange: setCurrentPage,
|
||||
}}
|
||||
/>
|
||||
{/* 정렬 */}
|
||||
<Select
|
||||
value={sortOption}
|
||||
onValueChange={(value) => setSortOption(value as SortOption)}
|
||||
>
|
||||
<SelectTrigger className="w-[120px]">
|
||||
<SelectValue placeholder="정렬" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{SORT_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
),
|
||||
|
||||
{/* 삭제 확인 다이얼로그 */}
|
||||
<AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>악성채권 삭제</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
이 악성채권 기록을 삭제하시겠습니까? 이 작업은 취소할 수 없습니다.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>취소</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleConfirmDelete}
|
||||
className="bg-red-600 hover:bg-red-700"
|
||||
// Stats 카드
|
||||
computeStats: (): StatCard[] => [
|
||||
{
|
||||
label: '총 악성채권',
|
||||
value: `${statsData.totalAmount.toLocaleString()}원`,
|
||||
icon: AlertTriangle,
|
||||
iconColor: 'text-red-500',
|
||||
},
|
||||
{
|
||||
label: '추심중',
|
||||
value: `${statsData.collectingAmount.toLocaleString()}원`,
|
||||
icon: AlertTriangle,
|
||||
iconColor: 'text-orange-500',
|
||||
},
|
||||
{
|
||||
label: '법적조치',
|
||||
value: `${statsData.legalActionAmount.toLocaleString()}원`,
|
||||
icon: AlertTriangle,
|
||||
iconColor: 'text-red-600',
|
||||
},
|
||||
{
|
||||
label: '회수완료',
|
||||
value: `${statsData.recoveredAmount.toLocaleString()}원`,
|
||||
icon: AlertTriangle,
|
||||
iconColor: 'text-green-500',
|
||||
},
|
||||
],
|
||||
|
||||
// 삭제 확인 메시지
|
||||
deleteConfirmMessage: {
|
||||
title: '악성채권 삭제',
|
||||
description: '이 악성채권 기록을 삭제하시겠습니까? 이 작업은 취소할 수 없습니다.',
|
||||
},
|
||||
|
||||
// 테이블 행 렌더링
|
||||
renderTableRow: (
|
||||
item: BadDebtRecord,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
handlers: SelectionHandlers & RowClickHandlers<BadDebtRecord>
|
||||
) => (
|
||||
<TableRow
|
||||
key={item.id}
|
||||
className="hover:bg-muted/50 cursor-pointer"
|
||||
onClick={() => handleRowClick(item)}
|
||||
>
|
||||
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
|
||||
<Checkbox checked={handlers.isSelected} onCheckedChange={handlers.onToggle} />
|
||||
</TableCell>
|
||||
{/* No. */}
|
||||
<TableCell className="text-center text-sm text-gray-500">{globalIndex}</TableCell>
|
||||
{/* 거래처 */}
|
||||
<TableCell className="font-medium">{item.vendorName}</TableCell>
|
||||
{/* 채권금액 */}
|
||||
<TableCell className="text-right font-medium text-red-600">
|
||||
{item.debtAmount.toLocaleString()}원
|
||||
</TableCell>
|
||||
{/* 발생일 */}
|
||||
<TableCell className="text-center">{item.occurrenceDate}</TableCell>
|
||||
{/* 연체일수 */}
|
||||
<TableCell className="text-center">{item.overdueDays}일</TableCell>
|
||||
{/* 담당자 */}
|
||||
<TableCell>{item.assignedManager?.name || '-'}</TableCell>
|
||||
{/* 상태 */}
|
||||
<TableCell className="text-center">
|
||||
<Badge variant="outline" className={STATUS_BADGE_STYLES[item.status]}>
|
||||
{COLLECTION_STATUS_LABELS[item.status]}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
{/* 설정 */}
|
||||
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
|
||||
<Switch
|
||||
checked={item.settingToggle}
|
||||
onCheckedChange={(checked) => handleSettingToggle(item.id, checked)}
|
||||
disabled={isPending}
|
||||
>
|
||||
{isPending ? '삭제 중...' : '삭제'}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
/>
|
||||
</TableCell>
|
||||
{/* 작업 */}
|
||||
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
|
||||
{handlers.isSelected && (
|
||||
<div className="flex items-center justify-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={() => handleEdit(item)}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-red-500 hover:text-red-600 hover:bg-red-50"
|
||||
onClick={() => handlers.onDelete?.(item)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
),
|
||||
|
||||
// 모바일 카드 렌더링
|
||||
renderMobileCard: (
|
||||
item: BadDebtRecord,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
handlers: SelectionHandlers & RowClickHandlers<BadDebtRecord>
|
||||
) => (
|
||||
<MobileCard
|
||||
key={item.id}
|
||||
title={item.vendorName}
|
||||
subtitle={`채권금액: ${item.debtAmount.toLocaleString()}원`}
|
||||
badge={COLLECTION_STATUS_LABELS[item.status]}
|
||||
badgeVariant="outline"
|
||||
badgeClassName={STATUS_BADGE_STYLES[item.status]}
|
||||
isSelected={handlers.isSelected}
|
||||
onToggle={handlers.onToggle}
|
||||
onClick={() => handleRowClick(item)}
|
||||
details={[
|
||||
{ label: '연체일수', value: `${item.overdueDays}일` },
|
||||
{ label: '발생일', value: item.occurrenceDate },
|
||||
{ label: '담당자', value: item.assignedManager?.name || '-' },
|
||||
]}
|
||||
actions={
|
||||
handlers.isSelected ? (
|
||||
<div className="flex gap-2 w-full">
|
||||
<Button variant="outline" className="flex-1" onClick={() => handleRowClick(item)}>
|
||||
<Eye className="w-4 h-4 mr-2" /> 상세
|
||||
</Button>
|
||||
<Button variant="outline" className="flex-1" onClick={() => handleEdit(item)}>
|
||||
<Pencil className="w-4 h-4 mr-2" /> 수정
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="flex-1 text-red-500 border-red-200 hover:bg-red-50 hover:text-red-600"
|
||||
onClick={() => handlers.onDelete?.(item)}
|
||||
>
|
||||
<Trash2 className="w-4 h-4 mr-2" /> 삭제
|
||||
</Button>
|
||||
</div>
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
),
|
||||
}),
|
||||
[
|
||||
data,
|
||||
vendorOptions,
|
||||
vendorFilter,
|
||||
statusFilter,
|
||||
sortOption,
|
||||
statsData,
|
||||
handleRowClick,
|
||||
handleEdit,
|
||||
handleSettingToggle,
|
||||
isPending,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
return <UniversalListPage config={config} initialData={data} />;
|
||||
}
|
||||
@@ -1,14 +1,21 @@
|
||||
'use client';
|
||||
|
||||
/**
|
||||
* 입출금 계좌조회 - UniversalListPage 마이그레이션
|
||||
*
|
||||
* 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
|
||||
* - 서버 사이드 필터링/페이지네이션
|
||||
* - dateRangeSelector (헤더 액션)
|
||||
* - beforeTableContent: 새로고침 버튼
|
||||
* - tableHeaderActions: 3개 Select 필터 (결제계좌, 입출금유형, 정렬)
|
||||
* - tableFooter: 합계 행
|
||||
* - 수정 버튼 (입금/출금 상세 페이지 이동)
|
||||
*/
|
||||
|
||||
import { useState, useMemo, useCallback, useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { format, startOfMonth, endOfMonth } from 'date-fns';
|
||||
import {
|
||||
Building2,
|
||||
Pencil,
|
||||
RefreshCw,
|
||||
Loader2,
|
||||
} from 'lucide-react';
|
||||
import { Building2, Pencil, RefreshCw, Loader2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
@@ -20,17 +27,15 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { MobileCard } from '@/components/molecules/MobileCard';
|
||||
import {
|
||||
IntegratedListTemplateV2,
|
||||
type TableColumn,
|
||||
UniversalListPage,
|
||||
type UniversalListConfig,
|
||||
type SelectionHandlers,
|
||||
type RowClickHandlers,
|
||||
type StatCard,
|
||||
} from '@/components/templates/IntegratedListTemplateV2';
|
||||
import { DateRangeSelector } from '@/components/molecules/DateRangeSelector';
|
||||
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
|
||||
import type {
|
||||
BankTransaction,
|
||||
SortOption,
|
||||
} from './types';
|
||||
} from '@/components/templates/UniversalListPage';
|
||||
import type { BankTransaction, SortOption } from './types';
|
||||
import {
|
||||
TRANSACTION_KIND_LABELS,
|
||||
DEPOSIT_TYPE_LABELS,
|
||||
@@ -38,9 +43,29 @@ import {
|
||||
SORT_OPTIONS,
|
||||
TRANSACTION_TYPE_FILTER_OPTIONS,
|
||||
} from './types';
|
||||
import { getBankTransactionList, getBankTransactionSummary, getBankAccountOptions } from './actions';
|
||||
import {
|
||||
getBankTransactionList,
|
||||
getBankTransactionSummary,
|
||||
getBankAccountOptions,
|
||||
} from './actions';
|
||||
import { isNextRedirectError } from '@/lib/utils/redirect-error';
|
||||
|
||||
// ===== 테이블 컬럼 정의 =====
|
||||
const tableColumns = [
|
||||
{ key: 'bankName', label: '은행명' },
|
||||
{ key: 'accountName', label: '계좌명' },
|
||||
{ key: 'transactionDate', label: '거래일시' },
|
||||
{ key: 'type', label: '구분', className: 'text-center' },
|
||||
{ key: 'note', label: '적요' },
|
||||
{ key: 'vendorName', label: '거래처' },
|
||||
{ key: 'depositorName', label: '입금자/수취인' },
|
||||
{ key: 'depositAmount', label: '입금', className: 'text-right' },
|
||||
{ key: 'withdrawalAmount', label: '출금', className: 'text-right' },
|
||||
{ key: 'balance', label: '잔액', className: 'text-right' },
|
||||
{ key: 'transactionType', label: '입출금 유형', className: 'text-center' },
|
||||
{ key: 'actions', label: '작업', className: 'text-center w-[80px]' },
|
||||
];
|
||||
|
||||
// ===== Props =====
|
||||
interface BankTransactionInquiryProps {
|
||||
initialData?: BankTransaction[];
|
||||
@@ -65,21 +90,7 @@ export function BankTransactionInquiry({
|
||||
}: BankTransactionInquiryProps) {
|
||||
const router = useRouter();
|
||||
|
||||
// ===== 상태 관리 =====
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [sortOption, setSortOption] = useState<SortOption>('latest');
|
||||
const [accountFilter, setAccountFilter] = useState<string>('all'); // 결제계좌 필터
|
||||
const [transactionTypeFilter, setTransactionTypeFilter] = useState<string>('all'); // 입출금유형 필터
|
||||
const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
|
||||
const [currentPage, setCurrentPage] = useState(initialPagination?.currentPage || 1);
|
||||
const itemsPerPage = 20;
|
||||
const [isLoading, setIsLoading] = useState(!initialData.length);
|
||||
|
||||
// 날짜 범위 상태
|
||||
const [startDate, setStartDate] = useState(() => format(startOfMonth(new Date()), 'yyyy-MM-dd'));
|
||||
const [endDate, setEndDate] = useState(() => format(endOfMonth(new Date()), 'yyyy-MM-dd'));
|
||||
|
||||
// 데이터 상태
|
||||
// ===== 외부 상태 (UniversalListPage 외부에서 관리) =====
|
||||
const [data, setData] = useState<BankTransaction[]>(initialData);
|
||||
const [summary, setSummary] = useState(
|
||||
initialSummary || { totalDeposit: 0, totalWithdrawal: 0, depositUnsetCount: 0, withdrawalUnsetCount: 0 }
|
||||
@@ -88,14 +99,25 @@ export function BankTransactionInquiry({
|
||||
initialPagination || { currentPage: 1, lastPage: 1, perPage: 20, total: 0 }
|
||||
);
|
||||
const [accountOptions, setAccountOptions] = useState<{ value: string; label: string }[]>([
|
||||
{ value: 'all', label: '전체' }
|
||||
{ value: 'all', label: '전체' },
|
||||
]);
|
||||
|
||||
// 필터 상태
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [sortOption, setSortOption] = useState<SortOption>('latest');
|
||||
const [accountFilter, setAccountFilter] = useState<string>('all');
|
||||
const [transactionTypeFilter, setTransactionTypeFilter] = useState<string>('all');
|
||||
const [currentPage, setCurrentPage] = useState(initialPagination?.currentPage || 1);
|
||||
const [isLoading, setIsLoading] = useState(!initialData.length);
|
||||
|
||||
// 날짜 범위 상태
|
||||
const [startDate, setStartDate] = useState(() => format(startOfMonth(new Date()), 'yyyy-MM-dd'));
|
||||
const [endDate, setEndDate] = useState(() => format(endOfMonth(new Date()), 'yyyy-MM-dd'));
|
||||
|
||||
// ===== 데이터 로드 =====
|
||||
const loadData = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
// 정렬 옵션 매핑
|
||||
const sortMapping: Record<SortOption, { sortBy: string; sortDir: 'asc' | 'desc' }> = {
|
||||
latest: { sortBy: 'transaction_date', sortDir: 'desc' },
|
||||
oldest: { sortBy: 'transaction_date', sortDir: 'asc' },
|
||||
@@ -107,7 +129,7 @@ export function BankTransactionInquiry({
|
||||
const [listResult, summaryResult, accountsResult] = await Promise.all([
|
||||
getBankTransactionList({
|
||||
page: currentPage,
|
||||
perPage: itemsPerPage,
|
||||
perPage: 20,
|
||||
startDate,
|
||||
endDate,
|
||||
bankAccountId: accountFilter !== 'all' ? parseInt(accountFilter, 10) : undefined,
|
||||
@@ -132,7 +154,7 @@ export function BankTransactionInquiry({
|
||||
if (accountsResult.success) {
|
||||
setAccountOptions([
|
||||
{ value: 'all', label: '전체' },
|
||||
...accountsResult.data.map(acc => ({ value: String(acc.id), label: acc.label }))
|
||||
...accountsResult.data.map((acc) => ({ value: String(acc.id), label: acc.label })),
|
||||
]);
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -148,70 +170,22 @@ export function BankTransactionInquiry({
|
||||
loadData();
|
||||
}, [loadData]);
|
||||
|
||||
// ===== 체크박스 핸들러 =====
|
||||
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 handleEditClick = useCallback(
|
||||
(item: BankTransaction) => {
|
||||
if (item.type === 'deposit') {
|
||||
router.push(`/ko/accounting/deposits/${item.sourceId}?mode=edit`);
|
||||
} else {
|
||||
router.push(`/ko/accounting/withdrawals/${item.sourceId}?mode=edit`);
|
||||
}
|
||||
},
|
||||
[router]
|
||||
);
|
||||
|
||||
|
||||
// ===== 데이터 (서버 사이드 필터링/정렬/페이지네이션) =====
|
||||
// 필터링, 정렬, 페이지네이션은 서버에서 처리됨
|
||||
const totalPages = pagination.lastPage;
|
||||
|
||||
// ===== 전체 선택 핸들러 =====
|
||||
const toggleSelectAll = useCallback(() => {
|
||||
if (selectedItems.size === data.length && data.length > 0) {
|
||||
setSelectedItems(new Set());
|
||||
} else {
|
||||
setSelectedItems(new Set(data.map(item => item.id)));
|
||||
}
|
||||
}, [selectedItems.size, data]);
|
||||
|
||||
// ===== 수정 버튼 클릭 (상세 이동) =====
|
||||
const handleEditClick = useCallback((item: BankTransaction) => {
|
||||
if (item.type === 'deposit') {
|
||||
router.push(`/ko/accounting/deposits/${item.sourceId}?mode=edit`);
|
||||
} else {
|
||||
router.push(`/ko/accounting/withdrawals/${item.sourceId}?mode=edit`);
|
||||
}
|
||||
}, [router]);
|
||||
|
||||
// 새로고침 핸들러
|
||||
const handleRefresh = useCallback(() => {
|
||||
loadData();
|
||||
}, [loadData]);
|
||||
|
||||
// ===== 통계 카드 =====
|
||||
const statCards: StatCard[] = useMemo(() => {
|
||||
return [
|
||||
{ label: '입금', value: `${summary.totalDeposit.toLocaleString()}원`, icon: Building2, iconColor: 'text-blue-500' },
|
||||
{ label: '출금', value: `${summary.totalWithdrawal.toLocaleString()}원`, icon: Building2, iconColor: 'text-red-500' },
|
||||
{ label: '입금 유형 미설정', value: `${summary.depositUnsetCount}건`, icon: Building2, iconColor: 'text-green-500' },
|
||||
{ label: '출금 유형 미설정', value: `${summary.withdrawalUnsetCount}건`, icon: Building2, iconColor: 'text-orange-500' },
|
||||
];
|
||||
}, [summary]);
|
||||
|
||||
// ===== 테이블 컬럼 (14개) =====
|
||||
const tableColumns: TableColumn[] = useMemo(() => [
|
||||
{ key: 'bankName', label: '은행명' },
|
||||
{ key: 'accountName', label: '계좌명' },
|
||||
{ key: 'transactionDate', label: '거래일시' },
|
||||
{ key: 'type', label: '구분', className: 'text-center' },
|
||||
{ key: 'note', label: '적요' },
|
||||
{ key: 'vendorName', label: '거래처' },
|
||||
{ key: 'depositorName', label: '입금자/수취인' },
|
||||
{ key: 'depositAmount', label: '입금', className: 'text-right' },
|
||||
{ key: 'withdrawalAmount', label: '출금', className: 'text-right' },
|
||||
{ key: 'balance', label: '잔액', className: 'text-right' },
|
||||
{ key: 'transactionType', label: '입출금 유형', className: 'text-center' },
|
||||
{ key: 'actions', label: '작업', className: 'text-center w-[80px]' },
|
||||
], []);
|
||||
|
||||
// ===== 유형 라벨 가져오기 =====
|
||||
const getTransactionTypeLabel = useCallback((item: BankTransaction) => {
|
||||
if (!item.transactionType) return '미설정';
|
||||
@@ -221,216 +195,6 @@ export function BankTransactionInquiry({
|
||||
return WITHDRAWAL_TYPE_LABELS[item.transactionType as keyof typeof WITHDRAWAL_TYPE_LABELS] || item.transactionType;
|
||||
}, []);
|
||||
|
||||
// ===== 테이블 행 렌더링 =====
|
||||
const renderTableRow = useCallback((item: BankTransaction, index: number, globalIndex: number) => {
|
||||
const isSelected = selectedItems.has(item.id);
|
||||
const isTypeUnset = item.transactionType === 'unset';
|
||||
|
||||
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.bankName}</TableCell>
|
||||
{/* 계좌명 */}
|
||||
<TableCell>{item.accountName}</TableCell>
|
||||
{/* 거래일시 */}
|
||||
<TableCell>{item.transactionDate}</TableCell>
|
||||
{/* 구분 */}
|
||||
<TableCell className="text-center">
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={item.type === 'deposit'
|
||||
? 'border-blue-300 text-blue-600 bg-blue-50'
|
||||
: 'border-red-300 text-red-600 bg-red-50'
|
||||
}
|
||||
>
|
||||
{TRANSACTION_KIND_LABELS[item.type]}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
{/* 적요 */}
|
||||
<TableCell className="text-gray-500">{item.note || '-'}</TableCell>
|
||||
{/* 거래처 */}
|
||||
<TableCell>{item.vendorName || '-'}</TableCell>
|
||||
{/* 입금자/수취인 */}
|
||||
<TableCell>{item.depositorName || '-'}</TableCell>
|
||||
{/* 입금 */}
|
||||
<TableCell className="text-right font-medium text-blue-600">
|
||||
{item.depositAmount > 0 ? item.depositAmount.toLocaleString() : '-'}
|
||||
</TableCell>
|
||||
{/* 출금 */}
|
||||
<TableCell className="text-right font-medium text-red-600">
|
||||
{item.withdrawalAmount > 0 ? item.withdrawalAmount.toLocaleString() : '-'}
|
||||
</TableCell>
|
||||
{/* 잔액 */}
|
||||
<TableCell className="text-right font-medium">
|
||||
{item.balance.toLocaleString()}
|
||||
</TableCell>
|
||||
{/* 입출금 유형 */}
|
||||
<TableCell className="text-center">
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={isTypeUnset ? 'border-red-300 text-red-500 bg-red-50' : ''}
|
||||
>
|
||||
{getTransactionTypeLabel(item)}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
{/* 작업 */}
|
||||
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
|
||||
{isSelected && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-gray-600 hover:text-gray-700 hover:bg-gray-50"
|
||||
onClick={() => handleEditClick(item)}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
}, [selectedItems, toggleSelection, handleEditClick, getTransactionTypeLabel]);
|
||||
|
||||
// ===== 모바일 카드 렌더링 =====
|
||||
const renderMobileCard = useCallback((
|
||||
item: BankTransaction,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
isSelected: boolean,
|
||||
onToggle: () => void
|
||||
) => {
|
||||
return (
|
||||
<ListMobileCard
|
||||
id={item.id}
|
||||
title={`${item.bankName} - ${item.accountName}`}
|
||||
headerBadges={
|
||||
<>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={item.type === 'deposit'
|
||||
? 'border-blue-300 text-blue-600 bg-blue-50'
|
||||
: 'border-red-300 text-red-600 bg-red-50'
|
||||
}
|
||||
>
|
||||
{TRANSACTION_KIND_LABELS[item.type]}
|
||||
</Badge>
|
||||
<Badge variant="outline">
|
||||
{getTransactionTypeLabel(item)}
|
||||
</Badge>
|
||||
</>
|
||||
}
|
||||
isSelected={isSelected}
|
||||
onToggleSelection={onToggle}
|
||||
infoGrid={
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<InfoField label="거래일시" value={item.transactionDate} />
|
||||
<InfoField label="거래처" value={item.vendorName || '-'} />
|
||||
<InfoField
|
||||
label="입금"
|
||||
value={item.depositAmount > 0 ? `${item.depositAmount.toLocaleString()}원` : '-'}
|
||||
/>
|
||||
<InfoField
|
||||
label="출금"
|
||||
value={item.withdrawalAmount > 0 ? `${item.withdrawalAmount.toLocaleString()}원` : '-'}
|
||||
/>
|
||||
<InfoField label="잔액" value={`${item.balance.toLocaleString()}원`} />
|
||||
<InfoField label="입금자/수취인" value={item.depositorName || '-'} />
|
||||
</div>
|
||||
}
|
||||
actions={
|
||||
isSelected ? (
|
||||
<Button variant="outline" className="w-full" onClick={() => handleEditClick(item)}>
|
||||
<Pencil className="w-4 h-4 mr-2" /> 수정
|
||||
</Button>
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
);
|
||||
}, [handleEditClick, getTransactionTypeLabel]);
|
||||
|
||||
// ===== 헤더 액션 (날짜 선택만) =====
|
||||
const headerActions = (
|
||||
<DateRangeSelector
|
||||
startDate={startDate}
|
||||
endDate={endDate}
|
||||
onStartDateChange={setStartDate}
|
||||
onEndDateChange={setEndDate}
|
||||
/>
|
||||
);
|
||||
|
||||
// ===== 테이블 상단 새로고침 버튼 (출금관리 스타일) =====
|
||||
const beforeTableContent = (
|
||||
<div className="flex items-center justify-end w-full">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleRefresh}
|
||||
disabled={isLoading}
|
||||
>
|
||||
{isLoading ? (
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
새로고침
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
|
||||
// ===== 테이블 헤더 액션 (3개 필터) =====
|
||||
const tableHeaderActions = (
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
{/* 결제계좌 필터 */}
|
||||
<Select value={accountFilter} onValueChange={setAccountFilter}>
|
||||
<SelectTrigger className="w-[180px]">
|
||||
<SelectValue placeholder="결제계좌" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{accountOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* 입출금유형 필터 */}
|
||||
<Select value={transactionTypeFilter} onValueChange={setTransactionTypeFilter}>
|
||||
<SelectTrigger className="w-[130px]">
|
||||
<SelectValue placeholder="입출금유형" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{TRANSACTION_TYPE_FILTER_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* 정렬 */}
|
||||
<Select value={sortOption} onValueChange={(value) => setSortOption(value as SortOption)}>
|
||||
<SelectTrigger className="w-[120px]">
|
||||
<SelectValue placeholder="정렬" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{SORT_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
);
|
||||
|
||||
// ===== 테이블 합계 계산 =====
|
||||
const tableTotals = useMemo(() => {
|
||||
const totalDeposit = data.reduce((sum, item) => sum + item.depositAmount, 0);
|
||||
@@ -438,58 +202,344 @@ export function BankTransactionInquiry({
|
||||
return { totalDeposit, totalWithdrawal };
|
||||
}, [data]);
|
||||
|
||||
// ===== 테이블 하단 합계 행 =====
|
||||
const tableFooter = (
|
||||
<TableRow className="bg-muted/50 font-medium">
|
||||
<TableCell className="text-center"></TableCell>
|
||||
<TableCell className="font-bold">합계</TableCell>
|
||||
<TableCell></TableCell>
|
||||
<TableCell></TableCell>
|
||||
<TableCell></TableCell>
|
||||
<TableCell></TableCell>
|
||||
<TableCell></TableCell>
|
||||
<TableCell></TableCell>
|
||||
<TableCell></TableCell>
|
||||
<TableCell className="text-right font-bold text-blue-600">
|
||||
{tableTotals.totalDeposit.toLocaleString()}
|
||||
</TableCell>
|
||||
<TableCell className="text-right font-bold text-red-600">
|
||||
{tableTotals.totalWithdrawal.toLocaleString()}
|
||||
</TableCell>
|
||||
<TableCell></TableCell>
|
||||
<TableCell></TableCell>
|
||||
<TableCell></TableCell>
|
||||
</TableRow>
|
||||
// ===== UniversalListPage Config =====
|
||||
const config: UniversalListConfig<BankTransaction> = useMemo(
|
||||
() => ({
|
||||
// 페이지 기본 정보
|
||||
title: '입출금 계좌조회',
|
||||
description: '은행 계좌 정보와 입출금 내역을 조회할 수 있습니다',
|
||||
icon: Building2,
|
||||
basePath: '/accounting/bank-transactions',
|
||||
|
||||
// ID 추출
|
||||
idField: 'id',
|
||||
|
||||
// API 액션
|
||||
actions: {
|
||||
getList: async () => {
|
||||
return {
|
||||
success: true,
|
||||
data: data,
|
||||
totalCount: pagination.total,
|
||||
};
|
||||
},
|
||||
},
|
||||
|
||||
// 테이블 컬럼
|
||||
columns: tableColumns,
|
||||
|
||||
// 서버 사이드 필터링 (클라이언트 사이드 아님)
|
||||
clientSideFiltering: false,
|
||||
itemsPerPage: 20,
|
||||
|
||||
// 검색
|
||||
searchPlaceholder: '은행명, 계좌명, 거래처, 입금자/수취인 검색...',
|
||||
onSearchChange: setSearchQuery,
|
||||
|
||||
// 필터 설정 (모바일용)
|
||||
filterConfig: [
|
||||
{
|
||||
key: 'account',
|
||||
label: '결제계좌',
|
||||
type: 'single',
|
||||
options: accountOptions.filter((o) => o.value !== 'all'),
|
||||
},
|
||||
{
|
||||
key: 'transactionType',
|
||||
label: '입출금유형',
|
||||
type: 'single',
|
||||
options: TRANSACTION_TYPE_FILTER_OPTIONS.filter((o) => o.value !== 'all').map((o) => ({
|
||||
value: o.value,
|
||||
label: o.label,
|
||||
})),
|
||||
},
|
||||
{
|
||||
key: 'sortBy',
|
||||
label: '정렬',
|
||||
type: 'single',
|
||||
options: SORT_OPTIONS.map((o) => ({
|
||||
value: o.value,
|
||||
label: o.label,
|
||||
})),
|
||||
},
|
||||
],
|
||||
initialFilters: {
|
||||
account: 'all',
|
||||
transactionType: 'all',
|
||||
sortBy: 'latest',
|
||||
},
|
||||
filterTitle: '계좌 필터',
|
||||
|
||||
// 날짜 선택기 (헤더 액션)
|
||||
dateRangeSelector: {
|
||||
enabled: true,
|
||||
startDate,
|
||||
endDate,
|
||||
onStartDateChange: setStartDate,
|
||||
onEndDateChange: setEndDate,
|
||||
},
|
||||
|
||||
// 테이블 상단 콘텐츠 (새로고침 버튼)
|
||||
beforeTableContent: (
|
||||
<div className="flex items-center justify-end w-full">
|
||||
<Button variant="outline" onClick={handleRefresh} disabled={isLoading}>
|
||||
{isLoading ? (
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
새로고침
|
||||
</Button>
|
||||
</div>
|
||||
),
|
||||
|
||||
// 테이블 헤더 액션 (3개 필터)
|
||||
tableHeaderActions: () => (
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
{/* 결제계좌 필터 */}
|
||||
<Select value={accountFilter} onValueChange={setAccountFilter}>
|
||||
<SelectTrigger className="w-[180px]">
|
||||
<SelectValue placeholder="결제계좌" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{accountOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* 입출금유형 필터 */}
|
||||
<Select value={transactionTypeFilter} onValueChange={setTransactionTypeFilter}>
|
||||
<SelectTrigger className="w-[130px]">
|
||||
<SelectValue placeholder="입출금유형" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{TRANSACTION_TYPE_FILTER_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* 정렬 */}
|
||||
<Select value={sortOption} onValueChange={(value) => setSortOption(value as SortOption)}>
|
||||
<SelectTrigger className="w-[120px]">
|
||||
<SelectValue placeholder="정렬" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{SORT_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
),
|
||||
|
||||
// 테이블 푸터 (합계 행)
|
||||
tableFooter: (
|
||||
<TableRow className="bg-muted/50 font-medium">
|
||||
<TableCell className="text-center" />
|
||||
<TableCell className="font-bold">합계</TableCell>
|
||||
<TableCell />
|
||||
<TableCell />
|
||||
<TableCell />
|
||||
<TableCell />
|
||||
<TableCell />
|
||||
<TableCell />
|
||||
<TableCell />
|
||||
<TableCell className="text-right font-bold text-blue-600">
|
||||
{tableTotals.totalDeposit.toLocaleString()}
|
||||
</TableCell>
|
||||
<TableCell className="text-right font-bold text-red-600">
|
||||
{tableTotals.totalWithdrawal.toLocaleString()}
|
||||
</TableCell>
|
||||
<TableCell />
|
||||
<TableCell />
|
||||
<TableCell />
|
||||
</TableRow>
|
||||
),
|
||||
|
||||
// Stats 카드
|
||||
computeStats: (): StatCard[] => [
|
||||
{
|
||||
label: '입금',
|
||||
value: `${summary.totalDeposit.toLocaleString()}원`,
|
||||
icon: Building2,
|
||||
iconColor: 'text-blue-500',
|
||||
},
|
||||
{
|
||||
label: '출금',
|
||||
value: `${summary.totalWithdrawal.toLocaleString()}원`,
|
||||
icon: Building2,
|
||||
iconColor: 'text-red-500',
|
||||
},
|
||||
{
|
||||
label: '입금 유형 미설정',
|
||||
value: `${summary.depositUnsetCount}건`,
|
||||
icon: Building2,
|
||||
iconColor: 'text-green-500',
|
||||
},
|
||||
{
|
||||
label: '출금 유형 미설정',
|
||||
value: `${summary.withdrawalUnsetCount}건`,
|
||||
icon: Building2,
|
||||
iconColor: 'text-orange-500',
|
||||
},
|
||||
],
|
||||
|
||||
// 테이블 행 렌더링
|
||||
renderTableRow: (
|
||||
item: BankTransaction,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
handlers: SelectionHandlers & RowClickHandlers<BankTransaction>
|
||||
) => {
|
||||
const isTypeUnset = item.transactionType === 'unset';
|
||||
|
||||
return (
|
||||
<TableRow key={item.id} className="hover:bg-muted/50">
|
||||
{/* 체크박스 */}
|
||||
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
|
||||
<Checkbox checked={handlers.isSelected} onCheckedChange={handlers.onToggle} />
|
||||
</TableCell>
|
||||
{/* 번호 */}
|
||||
<TableCell className="text-center">{globalIndex}</TableCell>
|
||||
{/* 은행명 */}
|
||||
<TableCell>{item.bankName}</TableCell>
|
||||
{/* 계좌명 */}
|
||||
<TableCell>{item.accountName}</TableCell>
|
||||
{/* 거래일시 */}
|
||||
<TableCell>{item.transactionDate}</TableCell>
|
||||
{/* 구분 */}
|
||||
<TableCell className="text-center">
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={
|
||||
item.type === 'deposit'
|
||||
? 'border-blue-300 text-blue-600 bg-blue-50'
|
||||
: 'border-red-300 text-red-600 bg-red-50'
|
||||
}
|
||||
>
|
||||
{TRANSACTION_KIND_LABELS[item.type]}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
{/* 적요 */}
|
||||
<TableCell className="text-gray-500">{item.note || '-'}</TableCell>
|
||||
{/* 거래처 */}
|
||||
<TableCell>{item.vendorName || '-'}</TableCell>
|
||||
{/* 입금자/수취인 */}
|
||||
<TableCell>{item.depositorName || '-'}</TableCell>
|
||||
{/* 입금 */}
|
||||
<TableCell className="text-right font-medium text-blue-600">
|
||||
{item.depositAmount > 0 ? item.depositAmount.toLocaleString() : '-'}
|
||||
</TableCell>
|
||||
{/* 출금 */}
|
||||
<TableCell className="text-right font-medium text-red-600">
|
||||
{item.withdrawalAmount > 0 ? item.withdrawalAmount.toLocaleString() : '-'}
|
||||
</TableCell>
|
||||
{/* 잔액 */}
|
||||
<TableCell className="text-right font-medium">{item.balance.toLocaleString()}</TableCell>
|
||||
{/* 입출금 유형 */}
|
||||
<TableCell className="text-center">
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={isTypeUnset ? 'border-red-300 text-red-500 bg-red-50' : ''}
|
||||
>
|
||||
{getTransactionTypeLabel(item)}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
{/* 작업 */}
|
||||
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
|
||||
{handlers.isSelected && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-gray-600 hover:text-gray-700 hover:bg-gray-50"
|
||||
onClick={() => handleEditClick(item)}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
},
|
||||
|
||||
// 모바일 카드 렌더링
|
||||
renderMobileCard: (
|
||||
item: BankTransaction,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
handlers: SelectionHandlers & RowClickHandlers<BankTransaction>
|
||||
) => (
|
||||
<MobileCard
|
||||
key={item.id}
|
||||
title={`${item.bankName} - ${item.accountName}`}
|
||||
subtitle={item.transactionDate}
|
||||
badge={TRANSACTION_KIND_LABELS[item.type]}
|
||||
badgeVariant="outline"
|
||||
badgeClassName={
|
||||
item.type === 'deposit'
|
||||
? 'border-blue-300 text-blue-600 bg-blue-50'
|
||||
: 'border-red-300 text-red-600 bg-red-50'
|
||||
}
|
||||
isSelected={handlers.isSelected}
|
||||
onToggle={handlers.onToggle}
|
||||
details={[
|
||||
{
|
||||
label: '입금',
|
||||
value: item.depositAmount > 0 ? `${item.depositAmount.toLocaleString()}원` : '-',
|
||||
},
|
||||
{
|
||||
label: '출금',
|
||||
value: item.withdrawalAmount > 0 ? `${item.withdrawalAmount.toLocaleString()}원` : '-',
|
||||
},
|
||||
{ label: '잔액', value: `${item.balance.toLocaleString()}원` },
|
||||
{ label: '거래처', value: item.vendorName || '-' },
|
||||
{ label: '입출금 유형', value: getTransactionTypeLabel(item) },
|
||||
]}
|
||||
actions={
|
||||
handlers.isSelected ? (
|
||||
<Button variant="outline" className="w-full" onClick={() => handleEditClick(item)}>
|
||||
<Pencil className="w-4 h-4 mr-2" /> 수정
|
||||
</Button>
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
),
|
||||
}),
|
||||
[
|
||||
data,
|
||||
pagination,
|
||||
summary,
|
||||
accountOptions,
|
||||
accountFilter,
|
||||
transactionTypeFilter,
|
||||
sortOption,
|
||||
startDate,
|
||||
endDate,
|
||||
tableTotals,
|
||||
isLoading,
|
||||
handleRefresh,
|
||||
handleEditClick,
|
||||
getTransactionTypeLabel,
|
||||
]
|
||||
);
|
||||
|
||||
return (
|
||||
<IntegratedListTemplateV2
|
||||
title="입출금 계좌조회"
|
||||
description="은행 계좌 정보와 입출금 내역을 조회할 수 있습니다"
|
||||
icon={Building2}
|
||||
headerActions={headerActions}
|
||||
stats={statCards}
|
||||
searchValue={searchQuery}
|
||||
onSearchChange={setSearchQuery}
|
||||
searchPlaceholder="은행명, 계좌명, 거래처, 입금자/수취인 검색..."
|
||||
beforeTableContent={beforeTableContent}
|
||||
tableHeaderActions={tableHeaderActions}
|
||||
tableColumns={tableColumns}
|
||||
tableFooter={tableFooter}
|
||||
data={data}
|
||||
totalCount={pagination.total}
|
||||
allData={data}
|
||||
selectedItems={selectedItems}
|
||||
onToggleSelection={toggleSelection}
|
||||
onToggleSelectAll={toggleSelectAll}
|
||||
getItemId={(item: BankTransaction) => item.id}
|
||||
renderTableRow={renderTableRow}
|
||||
renderMobileCard={renderMobileCard}
|
||||
pagination={{
|
||||
<UniversalListPage
|
||||
config={config}
|
||||
initialData={data}
|
||||
externalPagination={{
|
||||
currentPage,
|
||||
totalPages,
|
||||
totalPages: pagination.lastPage,
|
||||
totalItems: pagination.total,
|
||||
itemsPerPage,
|
||||
itemsPerPage: 20,
|
||||
onPageChange: setCurrentPage,
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
'use client';
|
||||
|
||||
/**
|
||||
* 어음관리 - UniversalListPage 마이그레이션
|
||||
*
|
||||
* IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
|
||||
* - 서버 사이드 필터링/페이지네이션
|
||||
* - dateRangeSelector + 등록 버튼 (headerActions)
|
||||
* - beforeTableContent: 상태 선택 + 저장 버튼 + 수취/발행 라디오
|
||||
* - tableHeaderActions: 거래처, 구분, 상태 필터
|
||||
*/
|
||||
|
||||
import { useState, useMemo, useCallback } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import {
|
||||
@@ -33,10 +43,12 @@ import {
|
||||
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import {
|
||||
IntegratedListTemplateV2,
|
||||
UniversalListPage,
|
||||
type UniversalListConfig,
|
||||
type TableColumn,
|
||||
} from '@/components/templates/IntegratedListTemplateV2';
|
||||
import { DateRangeSelector } from '@/components/molecules/DateRangeSelector';
|
||||
type SelectionHandlers,
|
||||
type RowClickHandlers,
|
||||
} from '@/components/templates/UniversalListPage';
|
||||
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
|
||||
import { toast } from 'sonner';
|
||||
import type {
|
||||
@@ -197,9 +209,12 @@ export function BillManagementClient({
|
||||
], []);
|
||||
|
||||
// ===== 테이블 행 렌더링 =====
|
||||
const renderTableRow = useCallback((item: BillRecord, index: number, globalIndex: number) => {
|
||||
const isSelected = selectedItems.has(item.id);
|
||||
|
||||
const renderTableRow = useCallback((
|
||||
item: BillRecord,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
handlers: SelectionHandlers & RowClickHandlers<BillRecord>
|
||||
) => {
|
||||
return (
|
||||
<TableRow
|
||||
key={item.id}
|
||||
@@ -207,7 +222,7 @@ export function BillManagementClient({
|
||||
onClick={() => handleRowClick(item)}
|
||||
>
|
||||
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
|
||||
<Checkbox checked={isSelected} onCheckedChange={() => toggleSelection(item.id)} />
|
||||
<Checkbox checked={handlers.isSelected} onCheckedChange={handlers.onToggle} />
|
||||
</TableCell>
|
||||
<TableCell className="text-center">{globalIndex}</TableCell>
|
||||
<TableCell>{item.billNumber}</TableCell>
|
||||
@@ -227,7 +242,7 @@ export function BillManagementClient({
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
|
||||
{isSelected && (
|
||||
{handlers.isSelected && (
|
||||
<div className="flex items-center justify-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
@@ -250,15 +265,14 @@ export function BillManagementClient({
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
}, [selectedItems, toggleSelection, handleRowClick, handleDeleteClick, router]);
|
||||
}, [handleRowClick, handleDeleteClick, router]);
|
||||
|
||||
// ===== 모바일 카드 렌더링 =====
|
||||
const renderMobileCard = useCallback((
|
||||
item: BillRecord,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
isSelected: boolean,
|
||||
onToggle: () => void
|
||||
handlers: SelectionHandlers & RowClickHandlers<BillRecord>
|
||||
) => {
|
||||
return (
|
||||
<ListMobileCard
|
||||
@@ -274,8 +288,8 @@ export function BillManagementClient({
|
||||
</Badge>
|
||||
</>
|
||||
}
|
||||
isSelected={isSelected}
|
||||
onToggleSelection={onToggle}
|
||||
isSelected={handlers.isSelected}
|
||||
onToggleSelection={handlers.onToggle}
|
||||
infoGrid={
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<InfoField label="거래처" value={item.vendorName} />
|
||||
@@ -285,7 +299,7 @@ export function BillManagementClient({
|
||||
</div>
|
||||
}
|
||||
actions={
|
||||
isSelected ? (
|
||||
handlers.isSelected ? (
|
||||
<div className="flex gap-2 w-full">
|
||||
<Button variant="outline" className="flex-1" onClick={() => router.push(`/ko/accounting/bills/${item.id}?mode=edit`)}>
|
||||
<Pencil className="w-4 h-4 mr-2" /> 수정
|
||||
@@ -305,22 +319,6 @@ export function BillManagementClient({
|
||||
);
|
||||
}, [handleRowClick, handleDeleteClick, router]);
|
||||
|
||||
// ===== 헤더 액션 =====
|
||||
const headerActions = (
|
||||
<>
|
||||
<DateRangeSelector
|
||||
startDate={startDate}
|
||||
endDate={endDate}
|
||||
onStartDateChange={setStartDate}
|
||||
onEndDateChange={setEndDate}
|
||||
/>
|
||||
<Button className="ml-auto" onClick={() => router.push('/ko/accounting/bills/new')}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
어음 등록
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
|
||||
// ===== 거래처 목록 (필터용) =====
|
||||
const vendorOptions = useMemo(() => {
|
||||
const uniqueVendors = [...new Set(data.map(d => d.vendorName).filter(v => v))];
|
||||
@@ -330,50 +328,6 @@ export function BillManagementClient({
|
||||
];
|
||||
}, [data]);
|
||||
|
||||
// ===== 테이블 헤더 액션 =====
|
||||
const tableHeaderActions = (
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<Select value={vendorFilter} onValueChange={setVendorFilter}>
|
||||
<SelectTrigger className="w-[120px]">
|
||||
<SelectValue placeholder="거래처명" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{vendorOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Select value={billTypeFilter} onValueChange={(value) => { setBillTypeFilter(value); loadData(1); }}>
|
||||
<SelectTrigger className="w-[100px]">
|
||||
<SelectValue placeholder="구분" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{BILL_TYPE_FILTER_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Select value={statusFilter} onValueChange={(value) => { setStatusFilter(value); loadData(1); }}>
|
||||
<SelectTrigger className="w-[110px]">
|
||||
<SelectValue placeholder="보관중" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{BILL_STATUS_FILTER_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
);
|
||||
|
||||
// ===== 저장 핸들러 =====
|
||||
const handleSave = useCallback(async () => {
|
||||
if (selectedItems.size === 0) {
|
||||
@@ -406,73 +360,207 @@ export function BillManagementClient({
|
||||
setIsLoading(false);
|
||||
}, [selectedItems, statusFilter, loadData, currentPage]);
|
||||
|
||||
// ===== beforeTableContent =====
|
||||
const billStatusSelector = (
|
||||
<div className="flex items-center gap-4">
|
||||
<Select value={statusFilter} onValueChange={setStatusFilter}>
|
||||
<SelectTrigger className="w-[110px]">
|
||||
<SelectValue placeholder="보관중" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{BILL_STATUS_FILTER_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
// ===== UniversalListPage Config =====
|
||||
const config: UniversalListConfig<BillRecord> = useMemo(
|
||||
() => ({
|
||||
// 페이지 기본 정보
|
||||
title: '어음관리',
|
||||
description: '어음 및 수취이음 상세 현황을 관리합니다',
|
||||
icon: FileText,
|
||||
basePath: '/accounting/bills',
|
||||
|
||||
<Button onClick={handleSave} className="bg-blue-500 hover:bg-blue-600" disabled={isLoading}>
|
||||
<Save className="h-4 w-4 mr-2" />
|
||||
저장
|
||||
</Button>
|
||||
// ID 추출
|
||||
idField: 'id',
|
||||
|
||||
<RadioGroup
|
||||
value={billTypeFilter}
|
||||
onValueChange={(value) => { setBillTypeFilter(value); loadData(1); }}
|
||||
className="flex items-center gap-4"
|
||||
>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem value="received" id="received" />
|
||||
<Label htmlFor="received" className="cursor-pointer">수취</Label>
|
||||
// API 액션
|
||||
actions: {
|
||||
getList: async () => {
|
||||
return {
|
||||
success: true,
|
||||
data: data,
|
||||
totalCount: pagination.total,
|
||||
};
|
||||
},
|
||||
},
|
||||
|
||||
// 테이블 컬럼
|
||||
columns: tableColumns,
|
||||
|
||||
// 서버 사이드 필터링
|
||||
clientSideFiltering: false,
|
||||
itemsPerPage: pagination.perPage,
|
||||
|
||||
// 검색
|
||||
searchPlaceholder: '어음번호, 거래처, 메모 검색...',
|
||||
onSearchChange: setSearchQuery,
|
||||
|
||||
// 모바일 필터 설정
|
||||
filterConfig: [
|
||||
{
|
||||
key: 'vendorFilter',
|
||||
label: '거래처',
|
||||
type: 'single',
|
||||
options: vendorOptions.filter(o => o.value !== 'all'),
|
||||
},
|
||||
{
|
||||
key: 'billType',
|
||||
label: '구분',
|
||||
type: 'single',
|
||||
options: BILL_TYPE_FILTER_OPTIONS.filter(o => o.value !== 'all'),
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
label: '상태',
|
||||
type: 'single',
|
||||
options: BILL_STATUS_FILTER_OPTIONS.filter(o => o.value !== 'all'),
|
||||
},
|
||||
],
|
||||
initialFilters: {
|
||||
vendorFilter: vendorFilter,
|
||||
billType: billTypeFilter,
|
||||
status: statusFilter,
|
||||
},
|
||||
filterTitle: '어음 필터',
|
||||
|
||||
// 날짜 선택기
|
||||
dateRangeSelector: {
|
||||
enabled: true,
|
||||
startDate,
|
||||
endDate,
|
||||
onStartDateChange: setStartDate,
|
||||
onEndDateChange: setEndDate,
|
||||
},
|
||||
|
||||
// 등록 버튼
|
||||
createButton: {
|
||||
label: '어음 등록',
|
||||
onClick: () => router.push('/ko/accounting/bills/new'),
|
||||
icon: Plus,
|
||||
},
|
||||
|
||||
// 테이블 헤더 액션 (필터)
|
||||
tableHeaderActions: (
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<Select value={vendorFilter} onValueChange={setVendorFilter}>
|
||||
<SelectTrigger className="w-[120px]">
|
||||
<SelectValue placeholder="거래처명" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{vendorOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Select value={billTypeFilter} onValueChange={(value) => { setBillTypeFilter(value); loadData(1); }}>
|
||||
<SelectTrigger className="w-[100px]">
|
||||
<SelectValue placeholder="구분" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{BILL_TYPE_FILTER_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Select value={statusFilter} onValueChange={(value) => { setStatusFilter(value); loadData(1); }}>
|
||||
<SelectTrigger className="w-[110px]">
|
||||
<SelectValue placeholder="보관중" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{BILL_STATUS_FILTER_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem value="issued" id="issued" />
|
||||
<Label htmlFor="issued" className="cursor-pointer">발행</Label>
|
||||
),
|
||||
|
||||
// beforeTableContent: 상태 선택 + 저장 + 수취/발행 라디오
|
||||
beforeTableContent: (
|
||||
<div className="flex items-center gap-4">
|
||||
<Select value={statusFilter} onValueChange={setStatusFilter}>
|
||||
<SelectTrigger className="w-[110px]">
|
||||
<SelectValue placeholder="보관중" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{BILL_STATUS_FILTER_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Button onClick={handleSave} className="bg-blue-500 hover:bg-blue-600" disabled={isLoading}>
|
||||
<Save className="h-4 w-4 mr-2" />
|
||||
저장
|
||||
</Button>
|
||||
|
||||
<RadioGroup
|
||||
value={billTypeFilter}
|
||||
onValueChange={(value) => { setBillTypeFilter(value); loadData(1); }}
|
||||
className="flex items-center gap-4"
|
||||
>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem value="received" id="received" />
|
||||
<Label htmlFor="received" className="cursor-pointer">수취</Label>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem value="issued" id="issued" />
|
||||
<Label htmlFor="issued" className="cursor-pointer">발행</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
),
|
||||
|
||||
// 렌더링 함수
|
||||
renderTableRow,
|
||||
renderMobileCard,
|
||||
}),
|
||||
[
|
||||
data,
|
||||
pagination,
|
||||
tableColumns,
|
||||
startDate,
|
||||
endDate,
|
||||
vendorFilter,
|
||||
vendorOptions,
|
||||
billTypeFilter,
|
||||
statusFilter,
|
||||
isLoading,
|
||||
router,
|
||||
loadData,
|
||||
handleSave,
|
||||
renderTableRow,
|
||||
renderMobileCard,
|
||||
]
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<IntegratedListTemplateV2
|
||||
title="어음관리"
|
||||
description="어음 및 수취이음 상세 현황을 관리합니다"
|
||||
icon={FileText}
|
||||
headerActions={headerActions}
|
||||
searchValue={searchQuery}
|
||||
onSearchChange={setSearchQuery}
|
||||
searchPlaceholder="어음번호, 거래처, 메모 검색..."
|
||||
beforeTableContent={billStatusSelector}
|
||||
tableHeaderActions={tableHeaderActions}
|
||||
tableColumns={tableColumns}
|
||||
data={data}
|
||||
totalCount={pagination.total}
|
||||
allData={data}
|
||||
selectedItems={selectedItems}
|
||||
onToggleSelection={toggleSelection}
|
||||
onToggleSelectAll={toggleSelectAll}
|
||||
getItemId={(item: BillRecord) => item.id}
|
||||
renderTableRow={renderTableRow}
|
||||
renderMobileCard={renderMobileCard}
|
||||
pagination={{
|
||||
<UniversalListPage
|
||||
config={config}
|
||||
initialData={data}
|
||||
externalPagination={{
|
||||
currentPage: pagination.currentPage,
|
||||
totalPages: pagination.lastPage,
|
||||
totalItems: pagination.total,
|
||||
itemsPerPage: pagination.perPage,
|
||||
onPageChange: handlePageChange,
|
||||
}}
|
||||
externalSelection={{
|
||||
selectedItems,
|
||||
onToggleSelection: toggleSelection,
|
||||
onToggleSelectAll: toggleSelectAll,
|
||||
getItemId: (item: BillRecord) => item.id,
|
||||
}}
|
||||
/>
|
||||
|
||||
<AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
|
||||
|
||||
@@ -1,5 +1,16 @@
|
||||
'use client';
|
||||
|
||||
/**
|
||||
* 어음관리 - UniversalListPage 마이그레이션
|
||||
*
|
||||
* 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
|
||||
* - 서버 사이드 페이지네이션 (API에서 페이지별 데이터 로드)
|
||||
* - DateRangeSelector + 등록 버튼 (dateRangeSelector + createButton)
|
||||
* - beforeTableContent (상태 필터 + 저장 + 수취/발행 라디오)
|
||||
* - tableHeaderActions (거래처, 구분, 상태 필터)
|
||||
* - 삭제 기능 (deleteConfirmMessage)
|
||||
*/
|
||||
|
||||
import { useState, useMemo, useCallback, useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { toast } from 'sonner';
|
||||
@@ -14,16 +25,6 @@ import {
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import { TableRow, TableCell } from '@/components/ui/table';
|
||||
import {
|
||||
Select,
|
||||
@@ -35,14 +36,14 @@ import {
|
||||
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import {
|
||||
IntegratedListTemplateV2,
|
||||
type TableColumn,
|
||||
} from '@/components/templates/IntegratedListTemplateV2';
|
||||
import { DateRangeSelector } from '@/components/molecules/DateRangeSelector';
|
||||
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
|
||||
UniversalListPage,
|
||||
type UniversalListConfig,
|
||||
type SelectionHandlers,
|
||||
type RowClickHandlers,
|
||||
} from '@/components/templates/UniversalListPage';
|
||||
import { MobileCard } from '@/components/molecules/MobileCard';
|
||||
import type {
|
||||
BillRecord,
|
||||
BillType,
|
||||
BillStatus,
|
||||
SortOption,
|
||||
} from './types';
|
||||
@@ -54,6 +55,20 @@ import {
|
||||
getBillStatusLabel,
|
||||
} from './types';
|
||||
|
||||
// ===== 테이블 컬럼 정의 =====
|
||||
const tableColumns = [
|
||||
{ key: 'no', label: '번호', className: 'text-center w-[60px]' },
|
||||
{ key: 'billNumber', label: '어음번호' },
|
||||
{ key: 'billType', label: '구분', className: 'text-center' },
|
||||
{ key: 'vendorName', label: '거래처' },
|
||||
{ key: 'amount', label: '금액', className: 'text-right' },
|
||||
{ key: 'issueDate', label: '발행일' },
|
||||
{ key: 'maturityDate', label: '만기일' },
|
||||
{ key: 'installmentCount', label: '차수', className: 'text-center' },
|
||||
{ key: 'status', label: '상태', className: 'text-center' },
|
||||
{ key: 'actions', label: '작업', className: 'text-center w-[80px]' },
|
||||
];
|
||||
|
||||
interface BillManagementProps {
|
||||
initialVendorId?: string;
|
||||
initialBillType?: string;
|
||||
@@ -62,28 +77,23 @@ interface BillManagementProps {
|
||||
export function BillManagement({ initialVendorId, initialBillType }: BillManagementProps = {}) {
|
||||
const router = useRouter();
|
||||
|
||||
// ===== 상태 관리 =====
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [sortOption, setSortOption] = useState<SortOption>('latest');
|
||||
const [billTypeFilter, setBillTypeFilter] = useState<string>(initialBillType || 'received');
|
||||
const [vendorFilter, setVendorFilter] = useState<string>(initialVendorId || 'all');
|
||||
const [statusFilter, setStatusFilter] = useState<string>('all');
|
||||
const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const itemsPerPage = 20;
|
||||
// ===== 외부 상태 (UniversalListPage 외부에서 관리) =====
|
||||
const [billData, setBillData] = useState<BillRecord[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
|
||||
// 삭제 다이얼로그
|
||||
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
|
||||
const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
|
||||
|
||||
// 날짜 범위 상태
|
||||
// 날짜 범위
|
||||
const [startDate, setStartDate] = useState('2025-09-01');
|
||||
const [endDate, setEndDate] = useState('2025-09-03');
|
||||
|
||||
// 데이터 상태
|
||||
const [data, setData] = useState<BillRecord[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
// 인라인 필터 상태
|
||||
const [billTypeFilter, setBillTypeFilter] = useState<string>(initialBillType || 'received');
|
||||
const [vendorFilter, setVendorFilter] = useState<string>(initialVendorId || 'all');
|
||||
const [statusFilter, setStatusFilter] = useState<string>('all');
|
||||
const [sortOption, setSortOption] = useState<SortOption>('latest');
|
||||
|
||||
// 페이지네이션
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [pagination, setPagination] = useState({
|
||||
currentPage: 1,
|
||||
lastPage: 1,
|
||||
@@ -96,18 +106,18 @@ export function BillManagement({ initialVendorId, initialBillType }: BillManagem
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const result = await getBills({
|
||||
search: searchQuery || undefined,
|
||||
search: undefined,
|
||||
billType: billTypeFilter !== 'all' ? billTypeFilter : undefined,
|
||||
status: statusFilter !== 'all' ? statusFilter : undefined,
|
||||
clientId: vendorFilter !== 'all' ? vendorFilter : undefined,
|
||||
issueStartDate: startDate,
|
||||
issueEndDate: endDate,
|
||||
page: currentPage,
|
||||
perPage: itemsPerPage,
|
||||
perPage: 20,
|
||||
});
|
||||
|
||||
if (result.success) {
|
||||
setData(result.data);
|
||||
setBillData(result.data);
|
||||
setPagination(result.pagination);
|
||||
} else {
|
||||
toast.error(result.error || '어음 목록을 불러오는데 실패했습니다.');
|
||||
@@ -117,26 +127,15 @@ export function BillManagement({ initialVendorId, initialBillType }: BillManagem
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [searchQuery, billTypeFilter, statusFilter, vendorFilter, startDate, endDate, currentPage, itemsPerPage]);
|
||||
}, [billTypeFilter, statusFilter, vendorFilter, startDate, endDate, currentPage]);
|
||||
|
||||
useEffect(() => {
|
||||
loadBills();
|
||||
}, [loadBills]);
|
||||
|
||||
// ===== 체크박스 핸들러 =====
|
||||
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;
|
||||
});
|
||||
}, []);
|
||||
|
||||
// ===== API에서 이미 필터링/페이지네이션된 데이터 사용 =====
|
||||
// 로컬 정렬만 적용 (필요시)
|
||||
// 정렬된 데이터 (로컬 정렬)
|
||||
const sortedData = useMemo(() => {
|
||||
const result = [...data];
|
||||
const result = [...billData];
|
||||
|
||||
switch (sortOption) {
|
||||
case 'latest':
|
||||
@@ -157,265 +156,33 @@ export function BillManagement({ initialVendorId, initialBillType }: BillManagem
|
||||
}
|
||||
|
||||
return result;
|
||||
}, [data, sortOption]);
|
||||
}, [billData, sortOption]);
|
||||
|
||||
const totalPages = pagination.lastPage;
|
||||
|
||||
// ===== 전체 선택 핸들러 =====
|
||||
const toggleSelectAll = useCallback(() => {
|
||||
if (selectedItems.size === sortedData.length && sortedData.length > 0) {
|
||||
setSelectedItems(new Set());
|
||||
} else {
|
||||
setSelectedItems(new Set(sortedData.map(item => item.id)));
|
||||
}
|
||||
}, [selectedItems.size, sortedData]);
|
||||
|
||||
// ===== 액션 핸들러 =====
|
||||
const handleRowClick = useCallback((item: BillRecord) => {
|
||||
router.push(`/ko/accounting/bills/${item.id}`);
|
||||
}, [router]);
|
||||
|
||||
const handleDeleteClick = useCallback((id: string) => {
|
||||
setDeleteTargetId(id);
|
||||
setShowDeleteDialog(true);
|
||||
}, []);
|
||||
|
||||
const handleConfirmDelete = useCallback(async () => {
|
||||
if (!deleteTargetId) return;
|
||||
|
||||
setIsSaving(true);
|
||||
try {
|
||||
const result = await deleteBill(deleteTargetId);
|
||||
|
||||
if (result.success) {
|
||||
toast.success('어음이 삭제되었습니다.');
|
||||
setData(prev => prev.filter(item => item.id !== deleteTargetId));
|
||||
setSelectedItems(prev => {
|
||||
const newSet = new Set(prev);
|
||||
newSet.delete(deleteTargetId);
|
||||
return newSet;
|
||||
});
|
||||
} else {
|
||||
toast.error(result.error || '삭제에 실패했습니다.');
|
||||
}
|
||||
} catch {
|
||||
toast.error('서버 오류가 발생했습니다.');
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
setShowDeleteDialog(false);
|
||||
setDeleteTargetId(null);
|
||||
}
|
||||
}, [deleteTargetId]);
|
||||
|
||||
|
||||
// ===== 테이블 컬럼 (사용자 요청: 번호, 어음번호, 구분, 거래처, 금액, 발행일, 만기일, 차수, 상태, 작업) =====
|
||||
const tableColumns: TableColumn[] = useMemo(() => [
|
||||
{ key: 'no', label: '번호', className: 'text-center w-[60px]' },
|
||||
{ key: 'billNumber', label: '어음번호' },
|
||||
{ key: 'billType', label: '구분', className: 'text-center' },
|
||||
{ key: 'vendorName', label: '거래처' },
|
||||
{ key: 'amount', label: '금액', className: 'text-right' },
|
||||
{ key: 'issueDate', label: '발행일' },
|
||||
{ key: 'maturityDate', label: '만기일' },
|
||||
{ key: 'installmentCount', label: '차수', className: 'text-center' },
|
||||
{ key: 'status', label: '상태', className: 'text-center' },
|
||||
{ key: 'actions', label: '작업', className: 'text-center w-[80px]' },
|
||||
], []);
|
||||
|
||||
// ===== 테이블 행 렌더링 (사용자 요청 순서: 번호, 어음번호, 구분, 거래처, 금액, 발행일, 만기일, 차수, 상태, 작업) =====
|
||||
const renderTableRow = useCallback((item: BillRecord, 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-center">{globalIndex}</TableCell>
|
||||
{/* 어음번호 */}
|
||||
<TableCell>{item.billNumber}</TableCell>
|
||||
{/* 구분 */}
|
||||
<TableCell className="text-center">
|
||||
<Badge variant="outline" className={item.billType === 'received' ? 'border-blue-300 text-blue-600' : 'border-green-300 text-green-600'}>
|
||||
{BILL_TYPE_LABELS[item.billType]}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
{/* 거래처 */}
|
||||
<TableCell>{item.vendorName}</TableCell>
|
||||
{/* 금액 */}
|
||||
<TableCell className="text-right font-medium">{item.amount.toLocaleString()}</TableCell>
|
||||
{/* 발행일 */}
|
||||
<TableCell>{item.issueDate}</TableCell>
|
||||
{/* 만기일 */}
|
||||
<TableCell>{item.maturityDate}</TableCell>
|
||||
{/* 차수 */}
|
||||
<TableCell className="text-center">{item.installmentCount || '-'}</TableCell>
|
||||
{/* 상태 */}
|
||||
<TableCell className="text-center">
|
||||
<Badge className={BILL_STATUS_COLORS[item.status]}>
|
||||
{getBillStatusLabel(item.billType, item.status)}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
{/* 작업 */}
|
||||
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
|
||||
{isSelected && (
|
||||
<div className="flex items-center justify-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-gray-600 hover:text-gray-700 hover:bg-gray-50"
|
||||
onClick={() => router.push(`/ko/accounting/bills/${item.id}?mode=edit`)}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-red-500 hover:text-red-600 hover:bg-red-50"
|
||||
onClick={() => handleDeleteClick(item.id)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
}, [selectedItems, toggleSelection, handleRowClick, handleDeleteClick, router]);
|
||||
|
||||
// ===== 모바일 카드 렌더링 =====
|
||||
const renderMobileCard = useCallback((
|
||||
item: BillRecord,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
isSelected: boolean,
|
||||
onToggle: () => void
|
||||
) => {
|
||||
return (
|
||||
<ListMobileCard
|
||||
id={item.id}
|
||||
title={item.billNumber}
|
||||
headerBadges={
|
||||
<>
|
||||
<Badge variant="outline" className={item.billType === 'received' ? 'border-blue-300 text-blue-600' : 'border-green-300 text-green-600'}>
|
||||
{BILL_TYPE_LABELS[item.billType]}
|
||||
</Badge>
|
||||
<Badge className={BILL_STATUS_COLORS[item.status]}>
|
||||
{getBillStatusLabel(item.billType, item.status)}
|
||||
</Badge>
|
||||
</>
|
||||
}
|
||||
isSelected={isSelected}
|
||||
onToggleSelection={onToggle}
|
||||
infoGrid={
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<InfoField label="거래처" value={item.vendorName} />
|
||||
<InfoField label="금액" value={`${item.amount.toLocaleString()}원`} />
|
||||
<InfoField label="발행일" value={item.issueDate} />
|
||||
<InfoField label="만기일" value={item.maturityDate} />
|
||||
</div>
|
||||
}
|
||||
actions={
|
||||
isSelected ? (
|
||||
<div className="flex gap-2 w-full">
|
||||
<Button variant="outline" className="flex-1" onClick={() => router.push(`/ko/accounting/bills/${item.id}?mode=edit`)}>
|
||||
<Pencil className="w-4 h-4 mr-2" /> 수정
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="flex-1 text-red-500 border-red-200 hover:bg-red-50 hover:text-red-600"
|
||||
onClick={() => handleDeleteClick(item.id)}
|
||||
>
|
||||
<Trash2 className="w-4 h-4 mr-2" /> 삭제
|
||||
</Button>
|
||||
</div>
|
||||
) : undefined
|
||||
}
|
||||
onCardClick={() => handleRowClick(item)}
|
||||
/>
|
||||
);
|
||||
}, [handleRowClick, handleDeleteClick, router]);
|
||||
|
||||
// ===== 헤더 액션 (매출관리와 동일한 패턴: DateRangeSelector + extraActions) =====
|
||||
const headerActions = (
|
||||
<DateRangeSelector
|
||||
startDate={startDate}
|
||||
endDate={endDate}
|
||||
onStartDateChange={setStartDate}
|
||||
onEndDateChange={setEndDate}
|
||||
extraActions={
|
||||
<Button onClick={() => router.push('/ko/accounting/bills/new')}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
어음 등록
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
);
|
||||
|
||||
// ===== 거래처 목록 (필터용) =====
|
||||
// 거래처 목록 (필터용)
|
||||
const vendorOptions = useMemo(() => {
|
||||
const uniqueVendors = [...new Set(data.map(d => d.vendorName).filter(v => v))];
|
||||
const uniqueVendors = [...new Set(billData.map(d => d.vendorName).filter(v => v))];
|
||||
return [
|
||||
{ value: 'all', label: '전체' },
|
||||
...uniqueVendors.map(v => ({ value: v, label: v }))
|
||||
];
|
||||
}, [data]);
|
||||
}, [billData]);
|
||||
|
||||
// ===== 테이블 헤더 액션 (거래처명 + 구분 + 보관중 필터) =====
|
||||
const tableHeaderActions = (
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
{/* 거래처명 필터 */}
|
||||
<Select value={vendorFilter} onValueChange={setVendorFilter}>
|
||||
<SelectTrigger className="w-[120px]">
|
||||
<SelectValue placeholder="거래처명" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{vendorOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
// ===== 핸들러 =====
|
||||
const handleRowClick = useCallback((item: BillRecord) => {
|
||||
router.push(`/ko/accounting/bills/${item.id}`);
|
||||
}, [router]);
|
||||
|
||||
{/* 구분 필터 (수취/발행) */}
|
||||
<Select value={billTypeFilter} onValueChange={setBillTypeFilter}>
|
||||
<SelectTrigger className="w-[100px]">
|
||||
<SelectValue placeholder="구분" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{BILL_TYPE_FILTER_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
const handleEdit = useCallback((item: BillRecord) => {
|
||||
router.push(`/ko/accounting/bills/${item.id}?mode=edit`);
|
||||
}, [router]);
|
||||
|
||||
{/* 보관중 상태 필터 */}
|
||||
<Select value={statusFilter} onValueChange={setStatusFilter}>
|
||||
<SelectTrigger className="w-[110px]">
|
||||
<SelectValue placeholder="보관중" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{BILL_STATUS_FILTER_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
);
|
||||
const handleCreate = useCallback(() => {
|
||||
router.push('/ko/accounting/bills/new');
|
||||
}, [router]);
|
||||
|
||||
// ===== 저장 핸들러 (선택된 항목의 상태 일괄 변경) =====
|
||||
const handleSave = useCallback(async () => {
|
||||
if (selectedItems.size === 0) {
|
||||
// 저장 핸들러 (선택된 항목의 상태 일괄 변경)
|
||||
const handleSave = useCallback(async (selectedItems: BillRecord[]) => {
|
||||
if (selectedItems.length === 0) {
|
||||
toast.warning('선택된 항목이 없습니다.');
|
||||
return;
|
||||
}
|
||||
@@ -426,12 +193,11 @@ export function BillManagement({ initialVendorId, initialBillType }: BillManagem
|
||||
|
||||
setIsSaving(true);
|
||||
try {
|
||||
const ids = Array.from(selectedItems);
|
||||
let successCount = 0;
|
||||
let failCount = 0;
|
||||
|
||||
for (const id of ids) {
|
||||
const result = await updateBillStatus(id, statusFilter as BillStatus);
|
||||
for (const item of selectedItems) {
|
||||
const result = await updateBillStatus(item.id, statusFilter as BillStatus);
|
||||
if (result.success) {
|
||||
successCount++;
|
||||
} else {
|
||||
@@ -442,7 +208,6 @@ export function BillManagement({ initialVendorId, initialBillType }: BillManagem
|
||||
if (successCount > 0) {
|
||||
toast.success(`${successCount}건의 상태가 변경되었습니다.`);
|
||||
await loadBills();
|
||||
setSelectedItems(new Set());
|
||||
}
|
||||
if (failCount > 0) {
|
||||
toast.error(`${failCount}건의 상태 변경에 실패했습니다.`);
|
||||
@@ -452,101 +217,301 @@ export function BillManagement({ initialVendorId, initialBillType }: BillManagem
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
}, [selectedItems, statusFilter, loadBills]);
|
||||
}, [statusFilter, loadBills]);
|
||||
|
||||
// ===== beforeTableContent (보관중 + 저장 + 수취/발행 라디오) =====
|
||||
const billStatusSelector = (
|
||||
<div className="flex items-center gap-4">
|
||||
{/* 상태 필터 */}
|
||||
<Select value={statusFilter} onValueChange={setStatusFilter}>
|
||||
<SelectTrigger className="w-[110px]">
|
||||
<SelectValue placeholder="보관중" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{BILL_STATUS_FILTER_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
// ===== UniversalListPage Config =====
|
||||
const config: UniversalListConfig<BillRecord> = useMemo(
|
||||
() => ({
|
||||
// 페이지 기본 정보
|
||||
title: '어음관리',
|
||||
description: '어음 및 수취이음 상세 현황을 관리합니다',
|
||||
icon: FileText,
|
||||
basePath: '/accounting/bills',
|
||||
|
||||
{/* 저장 버튼 */}
|
||||
<Button onClick={handleSave} className="bg-blue-500 hover:bg-blue-600" disabled={isSaving}>
|
||||
<Save className="h-4 w-4 mr-2" />
|
||||
{isSaving ? '저장중...' : '저장'}
|
||||
</Button>
|
||||
// ID 추출
|
||||
idField: 'id',
|
||||
|
||||
{/* 수취/발행 라디오 버튼 */}
|
||||
<RadioGroup
|
||||
value={billTypeFilter}
|
||||
onValueChange={setBillTypeFilter}
|
||||
className="flex items-center gap-4"
|
||||
>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem value="received" id="received" />
|
||||
<Label htmlFor="received" className="cursor-pointer">수취</Label>
|
||||
// API 액션
|
||||
actions: {
|
||||
getList: async () => {
|
||||
// 이미 useEffect에서 로드됨
|
||||
return {
|
||||
success: true,
|
||||
data: sortedData,
|
||||
totalCount: pagination.total,
|
||||
};
|
||||
},
|
||||
deleteItem: async (id: string) => {
|
||||
const result = await deleteBill(id);
|
||||
if (result.success) {
|
||||
toast.success('어음이 삭제되었습니다.');
|
||||
setBillData(prev => prev.filter(item => item.id !== id));
|
||||
}
|
||||
return { success: result.success, error: result.error };
|
||||
},
|
||||
},
|
||||
|
||||
// 테이블 컬럼
|
||||
columns: tableColumns,
|
||||
|
||||
// 서버 사이드 페이지네이션 (clientSideFiltering: false가 기본값)
|
||||
clientSideFiltering: false,
|
||||
itemsPerPage: 20,
|
||||
|
||||
// 검색 필터
|
||||
searchPlaceholder: '어음번호, 거래처, 메모 검색...',
|
||||
|
||||
// 필터 설정 (모바일 필터 시트용)
|
||||
filterConfig: [
|
||||
{
|
||||
key: 'billType',
|
||||
label: '구분',
|
||||
type: 'single',
|
||||
options: BILL_TYPE_FILTER_OPTIONS.filter(o => o.value !== 'all').map(o => ({
|
||||
value: o.value,
|
||||
label: o.label,
|
||||
})),
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
label: '상태',
|
||||
type: 'single',
|
||||
options: BILL_STATUS_FILTER_OPTIONS.filter(o => o.value !== 'all').map(o => ({
|
||||
value: o.value,
|
||||
label: o.label,
|
||||
})),
|
||||
},
|
||||
],
|
||||
initialFilters: {
|
||||
billType: initialBillType || 'received',
|
||||
status: 'all',
|
||||
},
|
||||
filterTitle: '어음 필터',
|
||||
|
||||
// 날짜 범위 선택기
|
||||
dateRangeSelector: {
|
||||
enabled: true,
|
||||
startDate,
|
||||
endDate,
|
||||
onStartDateChange: setStartDate,
|
||||
onEndDateChange: setEndDate,
|
||||
},
|
||||
|
||||
// 등록 버튼
|
||||
createButton: {
|
||||
label: '어음 등록',
|
||||
onClick: handleCreate,
|
||||
icon: Plus,
|
||||
},
|
||||
|
||||
// beforeTableContent: 상태 필터 + 저장 + 수취/발행 라디오
|
||||
beforeTableContent: (
|
||||
<div className="flex items-center gap-4">
|
||||
{/* 상태 필터 */}
|
||||
<Select value={statusFilter} onValueChange={setStatusFilter}>
|
||||
<SelectTrigger className="w-[110px]">
|
||||
<SelectValue placeholder="보관중" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{BILL_STATUS_FILTER_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* 수취/발행 라디오 버튼 */}
|
||||
<RadioGroup
|
||||
value={billTypeFilter}
|
||||
onValueChange={setBillTypeFilter}
|
||||
className="flex items-center gap-4"
|
||||
>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem value="received" id="received" />
|
||||
<Label htmlFor="received" className="cursor-pointer">수취</Label>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem value="issued" id="issued" />
|
||||
<Label htmlFor="issued" className="cursor-pointer">발행</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem value="issued" id="issued" />
|
||||
<Label htmlFor="issued" className="cursor-pointer">발행</Label>
|
||||
),
|
||||
|
||||
// tableHeaderActions: 저장 버튼 + 거래처 필터
|
||||
tableHeaderActions: ({ selectedItems }) => (
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
{/* 저장 버튼 */}
|
||||
<Button
|
||||
onClick={() => handleSave(selectedItems)}
|
||||
className="bg-blue-500 hover:bg-blue-600"
|
||||
disabled={isSaving}
|
||||
>
|
||||
<Save className="h-4 w-4 mr-2" />
|
||||
{isSaving ? '저장중...' : '저장'}
|
||||
</Button>
|
||||
|
||||
{/* 거래처명 필터 */}
|
||||
<Select value={vendorFilter} onValueChange={setVendorFilter}>
|
||||
<SelectTrigger className="w-[120px]">
|
||||
<SelectValue placeholder="거래처명" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{vendorOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
),
|
||||
|
||||
// 삭제 확인 메시지
|
||||
deleteConfirmMessage: {
|
||||
title: '어음 삭제',
|
||||
description: '이 어음을 삭제하시겠습니까? 삭제된 데이터는 복구할 수 없습니다.',
|
||||
},
|
||||
|
||||
// 테이블 행 렌더링
|
||||
renderTableRow: (
|
||||
item: BillRecord,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
handlers: SelectionHandlers & RowClickHandlers<BillRecord>
|
||||
) => (
|
||||
<TableRow
|
||||
key={item.id}
|
||||
className="hover:bg-muted/50 cursor-pointer"
|
||||
onClick={() => handleRowClick(item)}
|
||||
>
|
||||
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
|
||||
<Checkbox checked={handlers.isSelected} onCheckedChange={handlers.onToggle} />
|
||||
</TableCell>
|
||||
{/* 번호 */}
|
||||
<TableCell className="text-center">{globalIndex}</TableCell>
|
||||
{/* 어음번호 */}
|
||||
<TableCell>{item.billNumber}</TableCell>
|
||||
{/* 구분 */}
|
||||
<TableCell className="text-center">
|
||||
<Badge variant="outline" className={item.billType === 'received' ? 'border-blue-300 text-blue-600' : 'border-green-300 text-green-600'}>
|
||||
{BILL_TYPE_LABELS[item.billType]}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
{/* 거래처 */}
|
||||
<TableCell>{item.vendorName}</TableCell>
|
||||
{/* 금액 */}
|
||||
<TableCell className="text-right font-medium">{item.amount.toLocaleString()}</TableCell>
|
||||
{/* 발행일 */}
|
||||
<TableCell>{item.issueDate}</TableCell>
|
||||
{/* 만기일 */}
|
||||
<TableCell>{item.maturityDate}</TableCell>
|
||||
{/* 차수 */}
|
||||
<TableCell className="text-center">{item.installmentCount || '-'}</TableCell>
|
||||
{/* 상태 */}
|
||||
<TableCell className="text-center">
|
||||
<Badge className={BILL_STATUS_COLORS[item.status]}>
|
||||
{getBillStatusLabel(item.billType, item.status)}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
{/* 작업 */}
|
||||
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
|
||||
{handlers.isSelected && (
|
||||
<div className="flex items-center justify-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-gray-600 hover:text-gray-700 hover:bg-gray-50"
|
||||
onClick={() => handleEdit(item)}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-red-500 hover:text-red-600 hover:bg-red-50"
|
||||
onClick={() => handlers.onDelete?.(item)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
),
|
||||
|
||||
// 모바일 카드 렌더링
|
||||
renderMobileCard: (
|
||||
item: BillRecord,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
handlers: SelectionHandlers & RowClickHandlers<BillRecord>
|
||||
) => (
|
||||
<MobileCard
|
||||
key={item.id}
|
||||
title={item.billNumber}
|
||||
subtitle={item.vendorName}
|
||||
badge={BILL_TYPE_LABELS[item.billType]}
|
||||
badgeVariant="outline"
|
||||
isSelected={handlers.isSelected}
|
||||
onToggle={handlers.onToggle}
|
||||
onClick={() => handleRowClick(item)}
|
||||
details={[
|
||||
{ label: '금액', value: `${item.amount.toLocaleString()}원` },
|
||||
{ label: '발행일', value: item.issueDate },
|
||||
{ label: '만기일', value: item.maturityDate },
|
||||
{ label: '상태', value: getBillStatusLabel(item.billType, item.status) },
|
||||
]}
|
||||
actions={
|
||||
handlers.isSelected ? (
|
||||
<div className="flex gap-2 w-full">
|
||||
<Button variant="outline" className="flex-1" onClick={() => handleEdit(item)}>
|
||||
<Pencil className="w-4 h-4 mr-2" /> 수정
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="flex-1 text-red-500 border-red-200 hover:bg-red-50 hover:text-red-600"
|
||||
onClick={() => handlers.onDelete?.(item)}
|
||||
>
|
||||
<Trash2 className="w-4 h-4 mr-2" /> 삭제
|
||||
</Button>
|
||||
</div>
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
),
|
||||
}),
|
||||
[
|
||||
sortedData,
|
||||
pagination,
|
||||
startDate,
|
||||
endDate,
|
||||
billTypeFilter,
|
||||
vendorFilter,
|
||||
statusFilter,
|
||||
isSaving,
|
||||
vendorOptions,
|
||||
handleRowClick,
|
||||
handleEdit,
|
||||
handleCreate,
|
||||
handleSave,
|
||||
loadBills,
|
||||
initialBillType,
|
||||
]
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<IntegratedListTemplateV2
|
||||
title="어음관리"
|
||||
description="어음 및 수취이음 상세 현황을 관리합니다"
|
||||
icon={FileText}
|
||||
headerActions={headerActions}
|
||||
searchValue={searchQuery}
|
||||
onSearchChange={setSearchQuery}
|
||||
searchPlaceholder="어음번호, 거래처, 메모 검색..."
|
||||
beforeTableContent={billStatusSelector}
|
||||
tableHeaderActions={tableHeaderActions}
|
||||
tableColumns={tableColumns}
|
||||
data={sortedData}
|
||||
totalCount={pagination.total}
|
||||
allData={sortedData}
|
||||
selectedItems={selectedItems}
|
||||
onToggleSelection={toggleSelection}
|
||||
onToggleSelectAll={toggleSelectAll}
|
||||
getItemId={(item: BillRecord) => item.id}
|
||||
renderTableRow={renderTableRow}
|
||||
renderMobileCard={renderMobileCard}
|
||||
pagination={{
|
||||
currentPage: pagination.currentPage,
|
||||
totalPages,
|
||||
totalItems: pagination.total,
|
||||
itemsPerPage: pagination.perPage,
|
||||
onPageChange: setCurrentPage,
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* 삭제 확인 다이얼로그 */}
|
||||
<AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>어음 삭제</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
이 어음을 삭제하시겠습니까? 삭제된 데이터는 복구할 수 없습니다.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={isSaving}>취소</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleConfirmDelete}
|
||||
className="bg-red-600 hover:bg-red-700"
|
||||
disabled={isSaving}
|
||||
>
|
||||
{isSaving ? '삭제중...' : '삭제'}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
<UniversalListPage
|
||||
config={config}
|
||||
initialData={sortedData}
|
||||
externalPagination={{
|
||||
currentPage: pagination.currentPage,
|
||||
totalPages: pagination.lastPage,
|
||||
totalItems: pagination.total,
|
||||
itemsPerPage: pagination.perPage,
|
||||
onPageChange: setCurrentPage,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,22 @@
|
||||
'use client';
|
||||
|
||||
/**
|
||||
* 카드 내역 조회 - UniversalListPage 마이그레이션
|
||||
*
|
||||
* 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
|
||||
* - 클라이언트 사이드 필터링/페이지네이션
|
||||
* - dateRangeSelector (헤더 액션)
|
||||
* - beforeTableContent: 계정과목명 선택 + 저장 버튼 + 새로고침
|
||||
* - tableHeaderActions: 2개 Select 필터 (카드명, 정렬)
|
||||
* - tableFooter: 합계 행
|
||||
* - showRowNumber={false}
|
||||
* - 상세 모달 (수정 기능)
|
||||
* - 계정과목명 일괄 저장 다이얼로그
|
||||
*/
|
||||
|
||||
import { useState, useMemo, useCallback, useEffect } from 'react';
|
||||
import { format, startOfMonth, endOfMonth } from 'date-fns';
|
||||
import {
|
||||
CreditCard,
|
||||
RefreshCw,
|
||||
Save,
|
||||
Loader2,
|
||||
} from 'lucide-react';
|
||||
import { CreditCard, RefreshCw, Save, Loader2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Input } from '@/components/ui/input';
|
||||
@@ -37,25 +46,34 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { MobileCard } from '@/components/molecules/MobileCard';
|
||||
import {
|
||||
IntegratedListTemplateV2,
|
||||
type TableColumn,
|
||||
UniversalListPage,
|
||||
type UniversalListConfig,
|
||||
type SelectionHandlers,
|
||||
type RowClickHandlers,
|
||||
type StatCard,
|
||||
} from '@/components/templates/IntegratedListTemplateV2';
|
||||
import { DateRangeSelector } from '@/components/molecules/DateRangeSelector';
|
||||
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
|
||||
import type {
|
||||
CardTransaction,
|
||||
SortOption,
|
||||
} from './types';
|
||||
} from '@/components/templates/UniversalListPage';
|
||||
import type { CardTransaction, SortOption } from './types';
|
||||
import { SORT_OPTIONS, ACCOUNT_SUBJECT_OPTIONS, USAGE_TYPE_OPTIONS } from './types';
|
||||
import {
|
||||
SORT_OPTIONS,
|
||||
ACCOUNT_SUBJECT_OPTIONS,
|
||||
USAGE_TYPE_OPTIONS,
|
||||
} from './types';
|
||||
import { getCardTransactionList, getCardTransactionSummary, bulkUpdateAccountCode } from './actions';
|
||||
getCardTransactionList,
|
||||
getCardTransactionSummary,
|
||||
bulkUpdateAccountCode,
|
||||
} from './actions';
|
||||
import { isNextRedirectError } from '@/lib/utils/redirect-error';
|
||||
|
||||
// ===== 테이블 컬럼 정의 =====
|
||||
const tableColumns = [
|
||||
{ key: 'card', label: '카드' },
|
||||
{ key: 'cardName', label: '카드명' },
|
||||
{ key: 'user', label: '사용자' },
|
||||
{ key: 'usedAt', label: '사용일시' },
|
||||
{ key: 'merchantName', label: '가맹점명' },
|
||||
{ key: 'amount', label: '사용금액', className: 'text-right' },
|
||||
{ key: 'usageType', label: '사용유형' },
|
||||
];
|
||||
|
||||
// ===== Props =====
|
||||
interface CardTransactionInquiryProps {
|
||||
initialData?: CardTransaction[];
|
||||
@@ -76,20 +94,29 @@ export function CardTransactionInquiry({
|
||||
initialSummary,
|
||||
initialPagination,
|
||||
}: CardTransactionInquiryProps) {
|
||||
// ===== 상태 관리 =====
|
||||
// ===== 외부 상태 (UniversalListPage 외부에서 관리) =====
|
||||
const [data, setData] = useState<CardTransaction[]>(initialData);
|
||||
const [summary, setSummary] = useState(
|
||||
initialSummary || { previousMonthTotal: 0, currentMonthTotal: 0 }
|
||||
);
|
||||
const [pagination, setPagination] = useState(
|
||||
initialPagination || { currentPage: 1, lastPage: 1, perPage: 20, total: 0 }
|
||||
);
|
||||
|
||||
// 필터 상태
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [sortOption, setSortOption] = useState<SortOption>('latest');
|
||||
const [cardFilter, setCardFilter] = useState<string>('all'); // 카드명 필터
|
||||
const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
|
||||
const [cardFilter, setCardFilter] = useState<string>('all');
|
||||
const [currentPage, setCurrentPage] = useState(initialPagination?.currentPage || 1);
|
||||
const itemsPerPage = 20;
|
||||
const [isLoading, setIsLoading] = useState(!initialData.length);
|
||||
const itemsPerPage = 20;
|
||||
|
||||
// 상단 계정과목명 선택 (저장용)
|
||||
const [selectedAccountSubject, setSelectedAccountSubject] = useState<string>('unset');
|
||||
|
||||
// 계정과목명 저장 다이얼로그
|
||||
const [showSaveDialog, setShowSaveDialog] = useState(false);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
|
||||
// 선택 필요 알림 다이얼로그
|
||||
const [showSelectWarningDialog, setShowSelectWarningDialog] = useState(false);
|
||||
@@ -103,24 +130,17 @@ export function CardTransactionInquiry({
|
||||
});
|
||||
const [isDetailSaving, setIsDetailSaving] = useState(false);
|
||||
|
||||
// 선택된 항목 (외부 관리)
|
||||
const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
|
||||
|
||||
// 날짜 범위 상태
|
||||
const [startDate, setStartDate] = useState(() => format(startOfMonth(new Date()), 'yyyy-MM-dd'));
|
||||
const [endDate, setEndDate] = useState(() => format(endOfMonth(new Date()), 'yyyy-MM-dd'));
|
||||
|
||||
// 데이터 상태
|
||||
const [data, setData] = useState<CardTransaction[]>(initialData);
|
||||
const [summary, setSummary] = useState(
|
||||
initialSummary || { previousMonthTotal: 0, currentMonthTotal: 0 }
|
||||
);
|
||||
const [pagination, setPagination] = useState(
|
||||
initialPagination || { currentPage: 1, lastPage: 1, perPage: 20, total: 0 }
|
||||
);
|
||||
|
||||
// ===== 데이터 로드 =====
|
||||
const loadData = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
// 정렬 옵션 매핑
|
||||
const sortMapping: Record<SortOption, { sortBy: string; sortDir: 'asc' | 'desc' }> = {
|
||||
latest: { sortBy: 'used_at', sortDir: 'desc' },
|
||||
oldest: { sortBy: 'used_at', sortDir: 'asc' },
|
||||
@@ -166,7 +186,50 @@ export function CardTransactionInquiry({
|
||||
loadData();
|
||||
}, [loadData]);
|
||||
|
||||
// ===== 상세 모달 핸들러 =====
|
||||
// ===== 카드명 옵션 =====
|
||||
const cardOptions = useMemo(() => {
|
||||
const uniqueCards = [...new Set(data.map((d) => d.cardName))];
|
||||
return [
|
||||
{ value: 'all', label: '전체' },
|
||||
...uniqueCards.map((card) => ({ value: card, label: card })),
|
||||
];
|
||||
}, [data]);
|
||||
|
||||
// ===== 필터링된 데이터 =====
|
||||
const filteredData = useMemo(() => {
|
||||
let result = data.filter(
|
||||
(item) =>
|
||||
item.card.includes(searchQuery) ||
|
||||
item.cardName.includes(searchQuery) ||
|
||||
item.user.includes(searchQuery) ||
|
||||
item.merchantName.includes(searchQuery)
|
||||
);
|
||||
|
||||
// 카드명 필터
|
||||
if (cardFilter !== 'all') {
|
||||
result = result.filter((item) => item.cardName === cardFilter);
|
||||
}
|
||||
|
||||
// 정렬
|
||||
switch (sortOption) {
|
||||
case 'oldest':
|
||||
result.sort((a, b) => new Date(a.usedAt).getTime() - new Date(b.usedAt).getTime());
|
||||
break;
|
||||
case 'amountHigh':
|
||||
result.sort((a, b) => b.amount - a.amount);
|
||||
break;
|
||||
case 'amountLow':
|
||||
result.sort((a, b) => a.amount - b.amount);
|
||||
break;
|
||||
default: // latest
|
||||
result.sort((a, b) => new Date(b.usedAt).getTime() - new Date(a.usedAt).getTime());
|
||||
break;
|
||||
}
|
||||
|
||||
return result;
|
||||
}, [data, searchQuery, cardFilter, sortOption]);
|
||||
|
||||
// ===== 핸들러 =====
|
||||
const handleRowClick = useCallback((item: CardTransaction) => {
|
||||
setSelectedItem(item);
|
||||
setDetailFormData({
|
||||
@@ -181,15 +244,14 @@ export function CardTransactionInquiry({
|
||||
|
||||
setIsDetailSaving(true);
|
||||
try {
|
||||
// TODO: API 호출로 상세 정보 저장
|
||||
// const result = await updateCardTransaction(selectedItem.id, detailFormData);
|
||||
|
||||
// 임시: 로컬 데이터 업데이트
|
||||
setData(prev => prev.map(item =>
|
||||
item.id === selectedItem.id
|
||||
? { ...item, memo: detailFormData.memo, usageType: detailFormData.usageType }
|
||||
: item
|
||||
));
|
||||
setData((prev) =>
|
||||
prev.map((item) =>
|
||||
item.id === selectedItem.id
|
||||
? { ...item, memo: detailFormData.memo, usageType: detailFormData.usageType }
|
||||
: item
|
||||
)
|
||||
);
|
||||
|
||||
setShowDetailModal(false);
|
||||
setSelectedItem(null);
|
||||
@@ -200,79 +262,10 @@ export function CardTransactionInquiry({
|
||||
}
|
||||
}, [selectedItem, detailFormData]);
|
||||
|
||||
// ===== 체크박스 핸들러 =====
|
||||
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 cardOptions = useMemo(() => {
|
||||
const uniqueCards = [...new Set(data.map(d => d.cardName))];
|
||||
return [
|
||||
{ value: 'all', label: '전체' },
|
||||
...uniqueCards.map(card => ({ value: card, label: card }))
|
||||
];
|
||||
}, [data]);
|
||||
|
||||
// ===== 필터링된 데이터 =====
|
||||
const filteredData = useMemo(() => {
|
||||
let result = data.filter(item =>
|
||||
item.card.includes(searchQuery) ||
|
||||
item.cardName.includes(searchQuery) ||
|
||||
item.user.includes(searchQuery) ||
|
||||
item.merchantName.includes(searchQuery)
|
||||
);
|
||||
|
||||
// 카드명 필터
|
||||
if (cardFilter !== 'all') {
|
||||
result = result.filter(item => item.cardName === cardFilter);
|
||||
}
|
||||
|
||||
// 정렬
|
||||
switch (sortOption) {
|
||||
case 'latest':
|
||||
result.sort((a, b) => new Date(b.usedAt).getTime() - new Date(a.usedAt).getTime());
|
||||
break;
|
||||
case 'oldest':
|
||||
result.sort((a, b) => new Date(a.usedAt).getTime() - new Date(b.usedAt).getTime());
|
||||
break;
|
||||
case 'amountHigh':
|
||||
result.sort((a, b) => b.amount - a.amount);
|
||||
break;
|
||||
case 'amountLow':
|
||||
result.sort((a, b) => a.amount - b.amount);
|
||||
break;
|
||||
}
|
||||
|
||||
return result;
|
||||
}, [data, searchQuery, cardFilter, sortOption]);
|
||||
|
||||
const paginatedData = useMemo(() => {
|
||||
const startIndex = (currentPage - 1) * itemsPerPage;
|
||||
return filteredData.slice(startIndex, startIndex + itemsPerPage);
|
||||
}, [filteredData, currentPage, itemsPerPage]);
|
||||
|
||||
const totalPages = Math.ceil(filteredData.length / itemsPerPage);
|
||||
|
||||
// 새로고침 핸들러
|
||||
const handleRefresh = useCallback(() => {
|
||||
loadData();
|
||||
}, [loadData]);
|
||||
|
||||
// ===== 전체 선택 핸들러 =====
|
||||
const toggleSelectAll = useCallback(() => {
|
||||
if (selectedItems.size === filteredData.length && filteredData.length > 0) {
|
||||
setSelectedItems(new Set());
|
||||
} else {
|
||||
setSelectedItems(new Set(filteredData.map(item => item.id)));
|
||||
}
|
||||
}, [selectedItems.size, filteredData]);
|
||||
|
||||
// ===== 계정과목명 저장 핸들러 =====
|
||||
const handleSaveAccountSubject = useCallback(() => {
|
||||
if (selectedItems.size === 0) {
|
||||
@@ -282,19 +275,15 @@ export function CardTransactionInquiry({
|
||||
setShowSaveDialog(true);
|
||||
}, [selectedItems.size]);
|
||||
|
||||
// 계정과목명 저장 확정
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
|
||||
const handleConfirmSaveAccountSubject = useCallback(async () => {
|
||||
if (selectedAccountSubject === 'unset') return;
|
||||
|
||||
setIsSaving(true);
|
||||
try {
|
||||
const ids = Array.from(selectedItems).map(id => parseInt(id, 10));
|
||||
const ids = Array.from(selectedItems).map((id) => parseInt(id, 10));
|
||||
const result = await bulkUpdateAccountCode(ids, selectedAccountSubject);
|
||||
|
||||
if (result.success) {
|
||||
// 성공 시 데이터 새로고침
|
||||
await loadData();
|
||||
setSelectedItems(new Set());
|
||||
setSelectedAccountSubject('unset');
|
||||
@@ -309,222 +298,298 @@ export function CardTransactionInquiry({
|
||||
}
|
||||
}, [selectedAccountSubject, selectedItems, loadData]);
|
||||
|
||||
// ===== 통계 카드 (전월/당월 사용액) =====
|
||||
const statCards: StatCard[] = useMemo(() => {
|
||||
return [
|
||||
{ label: '전월 사용액', value: `${summary.previousMonthTotal.toLocaleString()}원`, icon: CreditCard, iconColor: 'text-gray-500' },
|
||||
{ label: '당월 사용액', value: `${summary.currentMonthTotal.toLocaleString()}원`, icon: CreditCard, iconColor: 'text-blue-500' },
|
||||
];
|
||||
}, [summary]);
|
||||
|
||||
// ===== 사용유형 라벨 변환 함수 =====
|
||||
const getUsageTypeLabel = useCallback((value: string) => {
|
||||
return USAGE_TYPE_OPTIONS.find(opt => opt.value === value)?.label || '미설정';
|
||||
return USAGE_TYPE_OPTIONS.find((opt) => opt.value === value)?.label || '미설정';
|
||||
}, []);
|
||||
|
||||
// ===== 테이블 컬럼 (체크박스/번호 없음) =====
|
||||
const tableColumns: TableColumn[] = useMemo(() => [
|
||||
{ key: 'card', label: '카드' },
|
||||
{ key: 'cardName', label: '카드명' },
|
||||
{ key: 'user', label: '사용자' },
|
||||
{ key: 'usedAt', label: '사용일시' },
|
||||
{ key: 'merchantName', label: '가맹점명' },
|
||||
{ key: 'amount', label: '사용금액', className: 'text-right' },
|
||||
{ key: 'usageType', label: '사용유형' },
|
||||
], []);
|
||||
|
||||
// ===== 테이블 행 렌더링 =====
|
||||
const renderTableRow = useCallback((item: CardTransaction) => {
|
||||
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>{item.card}</TableCell>
|
||||
{/* 카드명 */}
|
||||
<TableCell>{item.cardName}</TableCell>
|
||||
{/* 사용자 */}
|
||||
<TableCell>{item.user}</TableCell>
|
||||
{/* 사용일시 */}
|
||||
<TableCell>{item.usedAt}</TableCell>
|
||||
{/* 가맹점명 */}
|
||||
<TableCell>{item.merchantName}</TableCell>
|
||||
{/* 사용금액 */}
|
||||
<TableCell className="text-right font-medium">
|
||||
{item.amount.toLocaleString()}
|
||||
</TableCell>
|
||||
{/* 사용유형 */}
|
||||
<TableCell>{getUsageTypeLabel(item.usageType)}</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
}, [selectedItems, toggleSelection, getUsageTypeLabel, handleRowClick]);
|
||||
|
||||
// ===== 모바일 카드 렌더링 =====
|
||||
const renderMobileCard = useCallback((
|
||||
item: CardTransaction,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
isSelected: boolean,
|
||||
onToggle: () => void
|
||||
) => {
|
||||
return (
|
||||
<ListMobileCard
|
||||
id={item.id}
|
||||
title={`${item.card} - ${item.cardName}`}
|
||||
isSelected={isSelected}
|
||||
onToggleSelection={onToggle}
|
||||
showCheckbox={true}
|
||||
infoGrid={
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<InfoField label="사용자" value={item.user} />
|
||||
<InfoField label="사용일시" value={item.usedAt} />
|
||||
<InfoField label="가맹점명" value={item.merchantName} />
|
||||
<InfoField label="사용금액" value={`${item.amount.toLocaleString()}원`} />
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}, []);
|
||||
|
||||
// ===== 헤더 액션 (날짜 선택만) =====
|
||||
const headerActions = (
|
||||
<DateRangeSelector
|
||||
startDate={startDate}
|
||||
endDate={endDate}
|
||||
onStartDateChange={setStartDate}
|
||||
onEndDateChange={setEndDate}
|
||||
/>
|
||||
);
|
||||
|
||||
// ===== 상단 계정과목명 + 저장 버튼 + 새로고침 =====
|
||||
const beforeTableContent = (
|
||||
<div className="flex items-center justify-between w-full">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium text-gray-700">계정과목명</span>
|
||||
<Select value={selectedAccountSubject} onValueChange={setSelectedAccountSubject}>
|
||||
<SelectTrigger className="w-[150px]">
|
||||
<SelectValue placeholder="계정과목명 선택" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{ACCOUNT_SUBJECT_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button onClick={handleSaveAccountSubject} className="bg-blue-500 hover:bg-blue-600">
|
||||
<Save className="h-4 w-4 mr-2" />
|
||||
저장
|
||||
</Button>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleRefresh}
|
||||
disabled={isLoading}
|
||||
>
|
||||
{isLoading ? (
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
새로고침
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
|
||||
// ===== 테이블 헤더 액션 (2개 필터) =====
|
||||
const tableHeaderActions = (
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
{/* 카드명 필터 */}
|
||||
<Select value={cardFilter} onValueChange={setCardFilter}>
|
||||
<SelectTrigger className="w-[150px]">
|
||||
<SelectValue placeholder="카드" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{cardOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* 정렬 */}
|
||||
<Select value={sortOption} onValueChange={(value) => setSortOption(value as SortOption)}>
|
||||
<SelectTrigger className="w-[120px]">
|
||||
<SelectValue placeholder="정렬" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{SORT_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
);
|
||||
|
||||
// ===== 테이블 합계 계산 =====
|
||||
const totalAmount = useMemo(() => {
|
||||
return filteredData.reduce((sum, item) => sum + item.amount, 0);
|
||||
}, [filteredData]);
|
||||
|
||||
// ===== 테이블 하단 합계 행 =====
|
||||
const tableFooter = (
|
||||
<TableRow className="bg-muted/50 font-medium">
|
||||
<TableCell className="text-center"></TableCell>
|
||||
<TableCell colSpan={5} className="text-right font-bold">합계</TableCell>
|
||||
<TableCell className="text-right font-bold">
|
||||
{totalAmount.toLocaleString()}
|
||||
</TableCell>
|
||||
<TableCell></TableCell>
|
||||
</TableRow>
|
||||
// ===== UniversalListPage Config =====
|
||||
const config: UniversalListConfig<CardTransaction> = useMemo(
|
||||
() => ({
|
||||
// 페이지 기본 정보
|
||||
title: '카드 내역 조회',
|
||||
description: '법인카드 사용 내역을 조회합니다',
|
||||
icon: CreditCard,
|
||||
basePath: '/accounting/card-transactions',
|
||||
|
||||
// ID 추출
|
||||
idField: 'id',
|
||||
|
||||
// API 액션
|
||||
actions: {
|
||||
getList: async () => {
|
||||
return {
|
||||
success: true,
|
||||
data: filteredData,
|
||||
totalCount: filteredData.length,
|
||||
};
|
||||
},
|
||||
},
|
||||
|
||||
// 테이블 컬럼
|
||||
columns: tableColumns,
|
||||
|
||||
// 클라이언트 사이드 필터링
|
||||
clientSideFiltering: true,
|
||||
itemsPerPage,
|
||||
|
||||
// 행 번호 숨기기
|
||||
showRowNumber: false,
|
||||
|
||||
// 검색
|
||||
searchPlaceholder: '카드, 카드명, 사용자, 가맹점명 검색...',
|
||||
searchFilter: (item, searchValue) => {
|
||||
const search = searchValue.toLowerCase();
|
||||
return (
|
||||
item.card.toLowerCase().includes(search) ||
|
||||
item.cardName.toLowerCase().includes(search) ||
|
||||
item.user.toLowerCase().includes(search) ||
|
||||
item.merchantName.toLowerCase().includes(search)
|
||||
);
|
||||
},
|
||||
|
||||
// 필터 설정 (모바일용)
|
||||
filterConfig: [
|
||||
{
|
||||
key: 'card',
|
||||
label: '카드',
|
||||
type: 'single',
|
||||
options: cardOptions.filter((o) => o.value !== 'all'),
|
||||
},
|
||||
{
|
||||
key: 'sortBy',
|
||||
label: '정렬',
|
||||
type: 'single',
|
||||
options: SORT_OPTIONS.map((o) => ({
|
||||
value: o.value,
|
||||
label: o.label,
|
||||
})),
|
||||
},
|
||||
],
|
||||
initialFilters: {
|
||||
card: 'all',
|
||||
sortBy: 'latest',
|
||||
},
|
||||
filterTitle: '카드 필터',
|
||||
|
||||
// 커스텀 필터 함수
|
||||
customFilterFn: (items) => {
|
||||
if (cardFilter === 'all') return items;
|
||||
return items.filter((item) => item.cardName === cardFilter);
|
||||
},
|
||||
|
||||
// 커스텀 정렬 함수
|
||||
customSortFn: (items) => {
|
||||
const sorted = [...items];
|
||||
|
||||
switch (sortOption) {
|
||||
case 'oldest':
|
||||
sorted.sort((a, b) => new Date(a.usedAt).getTime() - new Date(b.usedAt).getTime());
|
||||
break;
|
||||
case 'amountHigh':
|
||||
sorted.sort((a, b) => b.amount - a.amount);
|
||||
break;
|
||||
case 'amountLow':
|
||||
sorted.sort((a, b) => a.amount - b.amount);
|
||||
break;
|
||||
default: // latest
|
||||
sorted.sort((a, b) => new Date(b.usedAt).getTime() - new Date(a.usedAt).getTime());
|
||||
break;
|
||||
}
|
||||
|
||||
return sorted;
|
||||
},
|
||||
|
||||
// 날짜 선택기 (헤더 액션)
|
||||
dateRangeSelector: {
|
||||
enabled: true,
|
||||
startDate,
|
||||
endDate,
|
||||
onStartDateChange: setStartDate,
|
||||
onEndDateChange: setEndDate,
|
||||
},
|
||||
|
||||
// 선택 항목 변경 콜백
|
||||
onSelectionChange: setSelectedItems,
|
||||
|
||||
// 테이블 상단 콘텐츠 (계정과목명 + 저장 + 새로고침)
|
||||
beforeTableContent: (
|
||||
<div className="flex items-center justify-between w-full">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium text-gray-700">계정과목명</span>
|
||||
<Select value={selectedAccountSubject} onValueChange={setSelectedAccountSubject}>
|
||||
<SelectTrigger className="w-[150px]">
|
||||
<SelectValue placeholder="계정과목명 선택" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{ACCOUNT_SUBJECT_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button
|
||||
onClick={handleSaveAccountSubject}
|
||||
className="bg-blue-500 hover:bg-blue-600"
|
||||
>
|
||||
<Save className="h-4 w-4 mr-2" />
|
||||
저장
|
||||
</Button>
|
||||
</div>
|
||||
<Button variant="outline" onClick={handleRefresh} disabled={isLoading}>
|
||||
{isLoading ? (
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
새로고침
|
||||
</Button>
|
||||
</div>
|
||||
),
|
||||
|
||||
// 테이블 헤더 액션 (2개 필터)
|
||||
tableHeaderActions: () => (
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
{/* 카드명 필터 */}
|
||||
<Select value={cardFilter} onValueChange={setCardFilter}>
|
||||
<SelectTrigger className="w-[150px]">
|
||||
<SelectValue placeholder="카드" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{cardOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* 정렬 */}
|
||||
<Select value={sortOption} onValueChange={(value) => setSortOption(value as SortOption)}>
|
||||
<SelectTrigger className="w-[120px]">
|
||||
<SelectValue placeholder="정렬" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{SORT_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
),
|
||||
|
||||
// 테이블 푸터 (합계 행)
|
||||
tableFooter: (
|
||||
<TableRow className="bg-muted/50 font-medium">
|
||||
<TableCell className="text-center" />
|
||||
<TableCell colSpan={5} className="text-right font-bold">
|
||||
합계
|
||||
</TableCell>
|
||||
<TableCell className="text-right font-bold">{totalAmount.toLocaleString()}</TableCell>
|
||||
<TableCell />
|
||||
</TableRow>
|
||||
),
|
||||
|
||||
// Stats 카드
|
||||
computeStats: (): StatCard[] => [
|
||||
{
|
||||
label: '전월 사용액',
|
||||
value: `${summary.previousMonthTotal.toLocaleString()}원`,
|
||||
icon: CreditCard,
|
||||
iconColor: 'text-gray-500',
|
||||
},
|
||||
{
|
||||
label: '당월 사용액',
|
||||
value: `${summary.currentMonthTotal.toLocaleString()}원`,
|
||||
icon: CreditCard,
|
||||
iconColor: 'text-blue-500',
|
||||
},
|
||||
],
|
||||
|
||||
// 테이블 행 렌더링
|
||||
renderTableRow: (
|
||||
item: CardTransaction,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
handlers: SelectionHandlers & RowClickHandlers<CardTransaction>
|
||||
) => (
|
||||
<TableRow
|
||||
key={item.id}
|
||||
className="hover:bg-muted/50 cursor-pointer"
|
||||
onClick={() => handleRowClick(item)}
|
||||
>
|
||||
{/* 체크박스 */}
|
||||
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
|
||||
<Checkbox checked={handlers.isSelected} onCheckedChange={handlers.onToggle} />
|
||||
</TableCell>
|
||||
{/* 카드 */}
|
||||
<TableCell>{item.card}</TableCell>
|
||||
{/* 카드명 */}
|
||||
<TableCell>{item.cardName}</TableCell>
|
||||
{/* 사용자 */}
|
||||
<TableCell>{item.user}</TableCell>
|
||||
{/* 사용일시 */}
|
||||
<TableCell>{item.usedAt}</TableCell>
|
||||
{/* 가맹점명 */}
|
||||
<TableCell>{item.merchantName}</TableCell>
|
||||
{/* 사용금액 */}
|
||||
<TableCell className="text-right font-medium">{item.amount.toLocaleString()}</TableCell>
|
||||
{/* 사용유형 */}
|
||||
<TableCell>{getUsageTypeLabel(item.usageType)}</TableCell>
|
||||
</TableRow>
|
||||
),
|
||||
|
||||
// 모바일 카드 렌더링
|
||||
renderMobileCard: (
|
||||
item: CardTransaction,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
handlers: SelectionHandlers & RowClickHandlers<CardTransaction>
|
||||
) => (
|
||||
<MobileCard
|
||||
key={item.id}
|
||||
title={`${item.card} - ${item.cardName}`}
|
||||
subtitle={`${item.user} | ${item.usedAt}`}
|
||||
isSelected={handlers.isSelected}
|
||||
onToggle={handlers.onToggle}
|
||||
onClick={() => handleRowClick(item)}
|
||||
details={[
|
||||
{ label: '가맹점명', value: item.merchantName },
|
||||
{ label: '사용금액', value: `${item.amount.toLocaleString()}원` },
|
||||
{ label: '사용유형', value: getUsageTypeLabel(item.usageType) },
|
||||
]}
|
||||
/>
|
||||
),
|
||||
}),
|
||||
[
|
||||
filteredData,
|
||||
cardOptions,
|
||||
cardFilter,
|
||||
sortOption,
|
||||
startDate,
|
||||
endDate,
|
||||
summary,
|
||||
totalAmount,
|
||||
selectedAccountSubject,
|
||||
isLoading,
|
||||
handleRowClick,
|
||||
handleRefresh,
|
||||
handleSaveAccountSubject,
|
||||
getUsageTypeLabel,
|
||||
]
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<IntegratedListTemplateV2
|
||||
title="카드 내역 조회"
|
||||
description="법인카드 사용 내역을 조회합니다"
|
||||
icon={CreditCard}
|
||||
headerActions={headerActions}
|
||||
stats={statCards}
|
||||
searchValue={searchQuery}
|
||||
onSearchChange={setSearchQuery}
|
||||
searchPlaceholder="카드, 카드명, 사용자, 가맹점명 검색..."
|
||||
beforeTableContent={beforeTableContent}
|
||||
tableHeaderActions={tableHeaderActions}
|
||||
tableColumns={tableColumns}
|
||||
tableFooter={tableFooter}
|
||||
data={paginatedData}
|
||||
totalCount={filteredData.length}
|
||||
allData={filteredData}
|
||||
selectedItems={selectedItems}
|
||||
onToggleSelection={toggleSelection}
|
||||
onToggleSelectAll={toggleSelectAll}
|
||||
getItemId={(item: CardTransaction) => item.id}
|
||||
renderTableRow={renderTableRow}
|
||||
renderMobileCard={renderMobileCard}
|
||||
showCheckbox={true}
|
||||
showRowNumber={false}
|
||||
pagination={{
|
||||
currentPage,
|
||||
totalPages,
|
||||
totalItems: filteredData.length,
|
||||
itemsPerPage,
|
||||
onPageChange: setCurrentPage,
|
||||
}}
|
||||
/>
|
||||
<UniversalListPage config={config} initialData={filteredData} />
|
||||
|
||||
{/* 계정과목명 저장 확인 다이얼로그 */}
|
||||
<Dialog open={showSaveDialog} onOpenChange={setShowSaveDialog}>
|
||||
@@ -534,7 +599,7 @@ export function CardTransactionInquiry({
|
||||
<DialogDescription>
|
||||
{selectedItems.size}개의 카드 사용 내역을{' '}
|
||||
<span className="font-semibold text-orange-500">
|
||||
{ACCOUNT_SUBJECT_OPTIONS.find(o => o.value === selectedAccountSubject)?.label}
|
||||
{ACCOUNT_SUBJECT_OPTIONS.find((o) => o.value === selectedAccountSubject)?.label}
|
||||
</span>
|
||||
(으)로 모두 변경하시겠습니까?
|
||||
</DialogDescription>
|
||||
@@ -583,9 +648,7 @@ export function CardTransactionInquiry({
|
||||
<DialogContent className="sm:max-w-[500px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>카드 내역 상세</DialogTitle>
|
||||
<DialogDescription>
|
||||
카드 사용 상세 내역을 등록합니다
|
||||
</DialogDescription>
|
||||
<DialogDescription>카드 사용 상세 내역을 등록합니다</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{selectedItem && (
|
||||
@@ -599,7 +662,9 @@ export function CardTransactionInquiry({
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-sm text-gray-500">카드</Label>
|
||||
<p className="mt-1 text-sm font-medium">{selectedItem.card} ({selectedItem.cardName})</p>
|
||||
<p className="mt-1 text-sm font-medium">
|
||||
{selectedItem.card} ({selectedItem.cardName})
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-sm text-gray-500">사용자</Label>
|
||||
@@ -607,14 +672,20 @@ export function CardTransactionInquiry({
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-sm text-gray-500">사용금액</Label>
|
||||
<p className="mt-1 text-sm font-medium">{selectedItem.amount.toLocaleString()}원</p>
|
||||
<p className="mt-1 text-sm font-medium">
|
||||
{selectedItem.amount.toLocaleString()}원
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="detail-memo" className="text-sm text-gray-500">적요</Label>
|
||||
<Label htmlFor="detail-memo" className="text-sm text-gray-500">
|
||||
적요
|
||||
</Label>
|
||||
<Input
|
||||
id="detail-memo"
|
||||
value={detailFormData.memo}
|
||||
onChange={(e) => setDetailFormData(prev => ({ ...prev, memo: e.target.value }))}
|
||||
onChange={(e) =>
|
||||
setDetailFormData((prev) => ({ ...prev, memo: e.target.value }))
|
||||
}
|
||||
placeholder="적요"
|
||||
className="mt-1"
|
||||
/>
|
||||
@@ -624,11 +695,15 @@ export function CardTransactionInquiry({
|
||||
<p className="mt-1 text-sm font-medium">{selectedItem.merchantName}</p>
|
||||
</div>
|
||||
<div className="col-span-2">
|
||||
<Label htmlFor="detail-usage-type" className="text-sm text-gray-500">사용 유형</Label>
|
||||
<Label htmlFor="detail-usage-type" className="text-sm text-gray-500">
|
||||
사용 유형
|
||||
</Label>
|
||||
<Select
|
||||
key={`usage-type-${detailFormData.usageType}`}
|
||||
value={detailFormData.usageType}
|
||||
onValueChange={(value) => setDetailFormData(prev => ({ ...prev, usageType: value }))}
|
||||
onValueChange={(value) =>
|
||||
setDetailFormData((prev) => ({ ...prev, usageType: value }))
|
||||
}
|
||||
>
|
||||
<SelectTrigger id="detail-usage-type" className="mt-1">
|
||||
<SelectValue placeholder="선택" />
|
||||
|
||||
@@ -1,8 +1,20 @@
|
||||
'use client';
|
||||
|
||||
/**
|
||||
* 입금관리 - UniversalListPage 마이그레이션
|
||||
*
|
||||
* 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
|
||||
* - 클라이언트 사이드 필터링 (검색, 필터, 정렬)
|
||||
* - Stats 카드 (단순 표시, 클릭 없음)
|
||||
* - beforeTableContent (계정과목명 Select + 저장 버튼 + 새로고침)
|
||||
* - tableHeaderActions (3개 인라인 필터: 거래처, 입금유형, 정렬)
|
||||
* - tableFooter (합계 행)
|
||||
* - 커스텀 Dialog (계정과목명 저장, 선택 필요 경고) - UniversalListPage 외부 유지
|
||||
* - deleteConfirmMessage로 삭제 다이얼로그 처리
|
||||
*/
|
||||
|
||||
import { useState, useMemo, useCallback } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { format } from 'date-fns';
|
||||
import {
|
||||
Banknote,
|
||||
Pencil,
|
||||
@@ -24,7 +36,6 @@ import {
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
@@ -40,20 +51,19 @@ import {
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import {
|
||||
IntegratedListTemplateV2,
|
||||
type TableColumn,
|
||||
UniversalListPage,
|
||||
type UniversalListConfig,
|
||||
type SelectionHandlers,
|
||||
type RowClickHandlers,
|
||||
type StatCard,
|
||||
} from '@/components/templates/IntegratedListTemplateV2';
|
||||
import { DateRangeSelector } from '@/components/molecules/DateRangeSelector';
|
||||
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
|
||||
} from '@/components/templates/UniversalListPage';
|
||||
import { MobileCard } from '@/components/molecules/MobileCard';
|
||||
import type {
|
||||
DepositRecord,
|
||||
SortOption,
|
||||
} from './types';
|
||||
import {
|
||||
SORT_OPTIONS,
|
||||
DEPOSIT_STATUS_LABELS,
|
||||
DEPOSIT_STATUS_COLORS,
|
||||
DEPOSIT_TYPE_LABELS,
|
||||
DEPOSIT_TYPE_FILTER_OPTIONS,
|
||||
ACCOUNT_SUBJECT_OPTIONS,
|
||||
@@ -61,6 +71,18 @@ import {
|
||||
import { deleteDeposit, updateDepositTypes, getDeposits } from './actions';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
// ===== 테이블 컬럼 정의 =====
|
||||
const tableColumns = [
|
||||
{ key: 'depositDate', label: '입금일' },
|
||||
{ key: 'accountName', label: '입금계좌' },
|
||||
{ key: 'depositorName', label: '입금자명' },
|
||||
{ key: 'depositAmount', label: '입금금액', className: 'text-right' },
|
||||
{ key: 'vendorName', label: '거래처' },
|
||||
{ key: 'note', label: '적요' },
|
||||
{ key: 'depositType', label: '입금유형', className: 'text-center' },
|
||||
{ key: 'actions', label: '작업', className: 'text-center w-[80px]' },
|
||||
];
|
||||
|
||||
// ===== 컴포넌트 Props =====
|
||||
interface DepositManagementProps {
|
||||
initialData: DepositRecord[];
|
||||
@@ -75,132 +97,58 @@ interface DepositManagementProps {
|
||||
export function DepositManagement({ initialData, initialPagination }: DepositManagementProps) {
|
||||
const router = useRouter();
|
||||
|
||||
// ===== 상태 관리 =====
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [sortOption, setSortOption] = useState<SortOption>('latest');
|
||||
const [depositTypeFilter, setDepositTypeFilter] = useState<string>('all');
|
||||
const [vendorFilter, setVendorFilter] = useState<string>('all');
|
||||
const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const itemsPerPage = 20;
|
||||
|
||||
// 상단 계정과목명 선택 (저장용)
|
||||
const [selectedAccountSubject, setSelectedAccountSubject] = useState<string>('unset');
|
||||
|
||||
// 계정과목명 저장 다이얼로그
|
||||
const [showSaveDialog, setShowSaveDialog] = useState(false);
|
||||
|
||||
// 삭제 다이얼로그
|
||||
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
|
||||
const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
|
||||
|
||||
// 선택 필요 알림 다이얼로그
|
||||
const [showSelectWarningDialog, setShowSelectWarningDialog] = useState(false);
|
||||
|
||||
// 날짜 범위 상태
|
||||
// ===== 외부 상태 (UniversalListPage 외부에서 관리) =====
|
||||
const [startDate, setStartDate] = useState('2025-09-01');
|
||||
const [endDate, setEndDate] = useState('2025-09-03');
|
||||
|
||||
// 입금 데이터 (서버에서 전달받은 initialData 사용)
|
||||
const [data, setData] = useState<DepositRecord[]>(initialData);
|
||||
|
||||
// 로딩 상태
|
||||
const [depositData, setDepositData] = useState<DepositRecord[]>(initialData);
|
||||
const [isRefreshing, setIsRefreshing] = useState(false);
|
||||
|
||||
// ===== 체크박스 핸들러 =====
|
||||
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;
|
||||
});
|
||||
}, []);
|
||||
// 인라인 필터 상태 (tableHeaderActions에서 사용)
|
||||
const [vendorFilter, setVendorFilter] = useState<string>('all');
|
||||
const [depositTypeFilter, setDepositTypeFilter] = useState<string>('all');
|
||||
const [sortOption, setSortOption] = useState<SortOption>('latest');
|
||||
|
||||
// ===== 필터링된 데이터 =====
|
||||
const filteredData = useMemo(() => {
|
||||
let result = data.filter(item =>
|
||||
item.depositorName.includes(searchQuery) ||
|
||||
item.accountName.includes(searchQuery) ||
|
||||
item.note.includes(searchQuery) ||
|
||||
item.vendorName.includes(searchQuery)
|
||||
);
|
||||
// 계정과목명 저장 다이얼로그
|
||||
const [selectedAccountSubject, setSelectedAccountSubject] = useState<string>('unset');
|
||||
const [showSaveDialog, setShowSaveDialog] = useState(false);
|
||||
const [selectedItemsForSave, setSelectedItemsForSave] = useState<Set<string>>(new Set());
|
||||
|
||||
// 거래처 필터
|
||||
if (vendorFilter !== 'all') {
|
||||
result = result.filter(item => item.vendorName === vendorFilter);
|
||||
}
|
||||
// 선택 필요 경고 다이얼로그
|
||||
const [showSelectWarningDialog, setShowSelectWarningDialog] = useState(false);
|
||||
|
||||
// 입금 유형 필터
|
||||
if (depositTypeFilter !== 'all') {
|
||||
result = result.filter(item => item.depositType === depositTypeFilter);
|
||||
}
|
||||
// ===== 통계 계산 =====
|
||||
const stats = useMemo(() => {
|
||||
const totalDeposit = depositData.reduce((sum, d) => sum + (d.depositAmount ?? 0), 0);
|
||||
const currentMonth = new Date().getMonth();
|
||||
const currentYear = new Date().getFullYear();
|
||||
const monthlyDeposit = depositData
|
||||
.filter(d => {
|
||||
const date = new Date(d.depositDate);
|
||||
return date.getMonth() === currentMonth && date.getFullYear() === currentYear;
|
||||
})
|
||||
.reduce((sum, d) => sum + (d.depositAmount ?? 0), 0);
|
||||
const vendorUnsetCount = depositData.filter(d => !d.vendorName).length;
|
||||
const depositTypeUnsetCount = depositData.filter(d => d.depositType === 'unset').length;
|
||||
return { totalDeposit, monthlyDeposit, vendorUnsetCount, depositTypeUnsetCount };
|
||||
}, [depositData]);
|
||||
|
||||
// 정렬
|
||||
switch (sortOption) {
|
||||
case 'latest':
|
||||
result.sort((a, b) => new Date(b.depositDate).getTime() - new Date(a.depositDate).getTime());
|
||||
break;
|
||||
case 'oldest':
|
||||
result.sort((a, b) => new Date(a.depositDate).getTime() - new Date(b.depositDate).getTime());
|
||||
break;
|
||||
case 'amountHigh':
|
||||
result.sort((a, b) => (b.depositAmount ?? 0) - (a.depositAmount ?? 0));
|
||||
break;
|
||||
case 'amountLow':
|
||||
result.sort((a, b) => (a.depositAmount ?? 0) - (b.depositAmount ?? 0));
|
||||
break;
|
||||
}
|
||||
// ===== 거래처 목록 (필터용) =====
|
||||
const vendorOptions = useMemo(() => {
|
||||
const uniqueVendors = [...new Set(depositData.map(d => d.vendorName).filter(v => v))];
|
||||
return [
|
||||
{ value: 'all', label: '전체' },
|
||||
...uniqueVendors.map(v => ({ value: v, label: v }))
|
||||
];
|
||||
}, [depositData]);
|
||||
|
||||
return result;
|
||||
}, [data, searchQuery, vendorFilter, depositTypeFilter, sortOption]);
|
||||
|
||||
const paginatedData = useMemo(() => {
|
||||
const startIndex = (currentPage - 1) * itemsPerPage;
|
||||
return filteredData.slice(startIndex, startIndex + itemsPerPage);
|
||||
}, [filteredData, currentPage, itemsPerPage]);
|
||||
|
||||
const totalPages = Math.ceil(filteredData.length / itemsPerPage);
|
||||
|
||||
// ===== 전체 선택 핸들러 =====
|
||||
const toggleSelectAll = useCallback(() => {
|
||||
if (selectedItems.size === filteredData.length && filteredData.length > 0) {
|
||||
setSelectedItems(new Set());
|
||||
} else {
|
||||
setSelectedItems(new Set(filteredData.map(item => item.id)));
|
||||
}
|
||||
}, [selectedItems.size, filteredData]);
|
||||
|
||||
// ===== 액션 핸들러 =====
|
||||
// ===== 핸들러 =====
|
||||
const handleRowClick = useCallback((item: DepositRecord) => {
|
||||
router.push(`/ko/accounting/deposits/${item.id}`);
|
||||
}, [router]);
|
||||
|
||||
// 개별 항목 삭제 핸들러
|
||||
const handleDeleteClick = useCallback((id: string) => {
|
||||
setDeleteTargetId(id);
|
||||
setShowDeleteDialog(true);
|
||||
}, []);
|
||||
|
||||
// 삭제 확정 핸들러
|
||||
const handleConfirmDelete = useCallback(async () => {
|
||||
if (deleteTargetId) {
|
||||
const result = await deleteDeposit(deleteTargetId);
|
||||
if (result.success) {
|
||||
toast.success('입금 내역이 삭제되었습니다.');
|
||||
setData(prev => prev.filter(item => item.id !== deleteTargetId));
|
||||
setSelectedItems(prev => {
|
||||
const newSet = new Set(prev);
|
||||
newSet.delete(deleteTargetId);
|
||||
return newSet;
|
||||
});
|
||||
} else {
|
||||
toast.error(result.error || '삭제에 실패했습니다.');
|
||||
}
|
||||
}
|
||||
setShowDeleteDialog(false);
|
||||
setDeleteTargetId(null);
|
||||
}, [deleteTargetId]);
|
||||
const handleEdit = useCallback((item: DepositRecord) => {
|
||||
router.push(`/ko/accounting/deposits/${item.id}?mode=edit`);
|
||||
}, [router]);
|
||||
|
||||
// 새로고침 핸들러
|
||||
const handleRefresh = useCallback(async () => {
|
||||
@@ -211,12 +159,9 @@ export function DepositManagement({ initialData, initialPagination }: DepositMan
|
||||
startDate,
|
||||
endDate,
|
||||
depositType: depositTypeFilter !== 'all' ? depositTypeFilter : undefined,
|
||||
search: searchQuery || undefined,
|
||||
});
|
||||
if (result.success) {
|
||||
setData(result.data);
|
||||
setSelectedItems(new Set());
|
||||
setCurrentPage(1);
|
||||
setDepositData(result.data);
|
||||
toast.success('데이터를 새로고침했습니다.');
|
||||
} else {
|
||||
toast.error(result.error || '새로고침에 실패했습니다.');
|
||||
@@ -226,344 +171,392 @@ export function DepositManagement({ initialData, initialPagination }: DepositMan
|
||||
} finally {
|
||||
setIsRefreshing(false);
|
||||
}
|
||||
}, [startDate, endDate, depositTypeFilter, searchQuery]);
|
||||
}, [startDate, endDate, depositTypeFilter]);
|
||||
|
||||
// ===== 통계 카드 (총 입금, 당월 입금, 거래처 미설정, 입금유형 미설정) =====
|
||||
const statCards: StatCard[] = useMemo(() => {
|
||||
const totalDeposit = data.reduce((sum, d) => sum + (d.depositAmount ?? 0), 0);
|
||||
|
||||
// 당월 입금
|
||||
const currentMonth = new Date().getMonth();
|
||||
const currentYear = new Date().getFullYear();
|
||||
const monthlyDeposit = data
|
||||
.filter(d => {
|
||||
const date = new Date(d.depositDate);
|
||||
return date.getMonth() === currentMonth && date.getFullYear() === currentYear;
|
||||
})
|
||||
.reduce((sum, d) => sum + (d.depositAmount ?? 0), 0);
|
||||
|
||||
// 거래처 미설정 건수
|
||||
const vendorUnsetCount = data.filter(d => !d.vendorName).length;
|
||||
|
||||
// 입금유형 미설정 건수
|
||||
const depositTypeUnsetCount = data.filter(d => d.depositType === 'unset').length;
|
||||
|
||||
return [
|
||||
{ label: '총 입금', value: `${totalDeposit.toLocaleString()}원`, icon: Banknote, iconColor: 'text-blue-500' },
|
||||
{ label: '당월 입금', value: `${monthlyDeposit.toLocaleString()}원`, icon: Banknote, iconColor: 'text-green-500' },
|
||||
{ label: '거래처 미설정', value: `${vendorUnsetCount}건`, icon: Banknote, iconColor: 'text-orange-500' },
|
||||
{ label: '입금유형 미설정', value: `${depositTypeUnsetCount}건`, icon: Banknote, iconColor: 'text-red-500' },
|
||||
];
|
||||
}, [data]);
|
||||
|
||||
// ===== 테이블 컬럼 =====
|
||||
const tableColumns: TableColumn[] = useMemo(() => [
|
||||
{ key: 'depositDate', label: '입금일' },
|
||||
{ key: 'accountName', label: '입금계좌' },
|
||||
{ key: 'depositorName', label: '입금자명' },
|
||||
{ key: 'depositAmount', label: '입금금액', className: 'text-right' },
|
||||
{ key: 'vendorName', label: '거래처' },
|
||||
{ key: 'note', label: '적요' },
|
||||
{ key: 'depositType', label: '입금유형', className: 'text-center' },
|
||||
{ key: 'actions', label: '작업', className: 'text-center w-[80px]' },
|
||||
], []);
|
||||
|
||||
// ===== 테이블 행 렌더링 =====
|
||||
const renderTableRow = useCallback((item: DepositRecord, index: number, globalIndex: number) => {
|
||||
const isSelected = selectedItems.has(item.id);
|
||||
const isVendorUnset = !item.vendorName;
|
||||
const isDepositTypeUnset = item.depositType === 'unset';
|
||||
|
||||
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>{item.depositDate}</TableCell>
|
||||
{/* 입금계좌 */}
|
||||
<TableCell>{item.accountName}</TableCell>
|
||||
{/* 입금자명 */}
|
||||
<TableCell>{item.depositorName}</TableCell>
|
||||
{/* 입금금액 */}
|
||||
<TableCell className="text-right font-medium">{(item.depositAmount ?? 0).toLocaleString()}</TableCell>
|
||||
{/* 거래처 */}
|
||||
<TableCell className={isVendorUnset ? 'text-red-500 font-medium' : ''}>
|
||||
{item.vendorName || '미설정'}
|
||||
</TableCell>
|
||||
{/* 적요 */}
|
||||
<TableCell className="text-gray-500">{item.note || '-'}</TableCell>
|
||||
{/* 입금유형 */}
|
||||
<TableCell className="text-center">
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={isDepositTypeUnset ? 'border-red-300 text-red-500 bg-red-50' : ''}
|
||||
>
|
||||
{DEPOSIT_TYPE_LABELS[item.depositType]}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
{/* 작업 */}
|
||||
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
|
||||
{isSelected && (
|
||||
<div className="flex items-center justify-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-gray-600 hover:text-gray-700 hover:bg-gray-50"
|
||||
onClick={() => router.push(`/ko/accounting/deposits/${item.id}?mode=edit`)}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-red-500 hover:text-red-600 hover:bg-red-50"
|
||||
onClick={() => handleDeleteClick(item.id)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
}, [selectedItems, toggleSelection, handleRowClick, handleDeleteClick]);
|
||||
|
||||
// ===== 모바일 카드 렌더링 =====
|
||||
const renderMobileCard = useCallback((
|
||||
item: DepositRecord,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
isSelected: boolean,
|
||||
onToggle: () => void
|
||||
) => {
|
||||
return (
|
||||
<ListMobileCard
|
||||
id={item.id}
|
||||
title={item.depositorName}
|
||||
headerBadges={
|
||||
<>
|
||||
<Badge variant="outline">{DEPOSIT_TYPE_LABELS[item.depositType]}</Badge>
|
||||
<Badge className={DEPOSIT_STATUS_COLORS[item.status]}>
|
||||
{DEPOSIT_STATUS_LABELS[item.status]}
|
||||
</Badge>
|
||||
</>
|
||||
}
|
||||
isSelected={isSelected}
|
||||
onToggleSelection={onToggle}
|
||||
infoGrid={
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<InfoField label="입금일" value={item.depositDate} />
|
||||
<InfoField label="입금액" value={`${(item.depositAmount ?? 0).toLocaleString()}원`} />
|
||||
<InfoField label="입금계좌" value={item.accountName} />
|
||||
<InfoField label="거래처" value={item.vendorName || '-'} />
|
||||
</div>
|
||||
}
|
||||
actions={
|
||||
isSelected ? (
|
||||
<div className="flex gap-2 w-full">
|
||||
<Button variant="outline" className="flex-1" onClick={() => handleRowClick(item)}>
|
||||
<Pencil className="w-4 h-4 mr-2" /> 수정
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="flex-1 text-red-500 border-red-200 hover:bg-red-50 hover:text-red-600"
|
||||
onClick={() => handleDeleteClick(item.id)}
|
||||
>
|
||||
<Trash2 className="w-4 h-4 mr-2" /> 삭제
|
||||
</Button>
|
||||
</div>
|
||||
) : undefined
|
||||
}
|
||||
onCardClick={() => handleRowClick(item)}
|
||||
/>
|
||||
);
|
||||
}, [handleRowClick, handleDeleteClick]);
|
||||
|
||||
// ===== 헤더 액션 =====
|
||||
const headerActions = (
|
||||
<DateRangeSelector
|
||||
startDate={startDate}
|
||||
endDate={endDate}
|
||||
onStartDateChange={setStartDate}
|
||||
onEndDateChange={setEndDate}
|
||||
/>
|
||||
);
|
||||
|
||||
// ===== 계정과목명 저장 핸들러 =====
|
||||
const handleSaveAccountSubject = useCallback(() => {
|
||||
// 계정과목명 저장 핸들러
|
||||
const handleSaveAccountSubject = useCallback((selectedItems: Set<string>) => {
|
||||
if (selectedItems.size === 0) {
|
||||
setShowSelectWarningDialog(true);
|
||||
return;
|
||||
}
|
||||
setSelectedItemsForSave(selectedItems);
|
||||
setShowSaveDialog(true);
|
||||
}, [selectedItems.size]);
|
||||
}, []);
|
||||
|
||||
// 계정과목명 저장 확정
|
||||
const handleConfirmSaveAccountSubject = useCallback(async () => {
|
||||
const ids = Array.from(selectedItems);
|
||||
const ids = Array.from(selectedItemsForSave);
|
||||
const result = await updateDepositTypes(ids, selectedAccountSubject);
|
||||
if (result.success) {
|
||||
toast.success('계정과목명이 저장되었습니다.');
|
||||
// 로컬 상태 업데이트
|
||||
setData(prev => prev.map(item =>
|
||||
selectedItems.has(item.id)
|
||||
setDepositData(prev => prev.map(item =>
|
||||
selectedItemsForSave.has(item.id)
|
||||
? { ...item, depositType: selectedAccountSubject as DepositRecord['depositType'] }
|
||||
: item
|
||||
));
|
||||
setSelectedItems(new Set());
|
||||
setSelectedItemsForSave(new Set());
|
||||
} else {
|
||||
toast.error(result.error || '계정과목명 저장에 실패했습니다.');
|
||||
}
|
||||
setShowSaveDialog(false);
|
||||
}, [selectedAccountSubject, selectedItems]);
|
||||
|
||||
// ===== 거래처 목록 (필터용) =====
|
||||
const vendorOptions = useMemo(() => {
|
||||
const uniqueVendors = [...new Set(data.map(d => d.vendorName).filter(v => v))];
|
||||
return [
|
||||
{ value: 'all', label: '전체' },
|
||||
...uniqueVendors.map(v => ({ value: v, label: v }))
|
||||
];
|
||||
}, [data]);
|
||||
|
||||
// ===== 테이블 헤더 액션 (필터들) =====
|
||||
const tableHeaderActions = (
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
{/* 거래처 필터 */}
|
||||
<Select value={vendorFilter} onValueChange={setVendorFilter}>
|
||||
<SelectTrigger className="w-[140px]">
|
||||
<SelectValue placeholder="거래처" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{vendorOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* 입금유형 필터 */}
|
||||
<Select value={depositTypeFilter} onValueChange={setDepositTypeFilter}>
|
||||
<SelectTrigger className="w-[130px]">
|
||||
<SelectValue placeholder="입금유형" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{DEPOSIT_TYPE_FILTER_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* 정렬 */}
|
||||
<Select value={sortOption} onValueChange={(value) => setSortOption(value as SortOption)}>
|
||||
<SelectTrigger className="w-[120px]">
|
||||
<SelectValue placeholder="정렬" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{SORT_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
);
|
||||
|
||||
// ===== 상단 계정과목명 + 저장 버튼 + 새로고침 =====
|
||||
const accountSubjectSelector = (
|
||||
<div className="flex items-center justify-between w-full">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium text-gray-700">계정과목명</span>
|
||||
<Select value={selectedAccountSubject} onValueChange={setSelectedAccountSubject}>
|
||||
<SelectTrigger className="w-[150px]">
|
||||
<SelectValue placeholder="계정과목명 선택" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{ACCOUNT_SUBJECT_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button onClick={handleSaveAccountSubject} className="bg-blue-500 hover:bg-blue-600">
|
||||
<Save className="h-4 w-4 mr-2" />
|
||||
저장
|
||||
</Button>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleRefresh}
|
||||
disabled={isRefreshing}
|
||||
>
|
||||
<RefreshCw className={`h-4 w-4 mr-2 ${isRefreshing ? 'animate-spin' : ''}`} />
|
||||
{isRefreshing ? '조회중...' : '새로고침'}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}, [selectedAccountSubject, selectedItemsForSave]);
|
||||
|
||||
// ===== 테이블 합계 계산 =====
|
||||
const tableTotals = useMemo(() => {
|
||||
const totalAmount = filteredData.reduce((sum, item) => sum + (item.depositAmount ?? 0), 0);
|
||||
const totalAmount = depositData.reduce((sum, item) => sum + (item.depositAmount ?? 0), 0);
|
||||
return { totalAmount };
|
||||
}, [filteredData]);
|
||||
}, [depositData]);
|
||||
|
||||
// ===== 테이블 하단 합계 행 =====
|
||||
const tableFooter = (
|
||||
<TableRow className="bg-muted/50 font-medium">
|
||||
<TableCell className="text-center"></TableCell>
|
||||
<TableCell className="font-bold">합계</TableCell>
|
||||
<TableCell></TableCell>
|
||||
<TableCell></TableCell>
|
||||
<TableCell className="text-right font-bold">{tableTotals.totalAmount.toLocaleString()}</TableCell>
|
||||
<TableCell></TableCell>
|
||||
<TableCell></TableCell>
|
||||
<TableCell></TableCell>
|
||||
<TableCell></TableCell>
|
||||
</TableRow>
|
||||
// ===== UniversalListPage Config =====
|
||||
const config: UniversalListConfig<DepositRecord> = useMemo(
|
||||
() => ({
|
||||
// 페이지 기본 정보
|
||||
title: '입금관리',
|
||||
description: '입금 내역을 등록합니다',
|
||||
icon: Banknote,
|
||||
basePath: '/accounting/deposits',
|
||||
|
||||
// ID 추출
|
||||
idField: 'id',
|
||||
|
||||
// API 액션
|
||||
actions: {
|
||||
getList: async () => {
|
||||
return {
|
||||
success: true,
|
||||
data: initialData,
|
||||
totalCount: initialData.length,
|
||||
};
|
||||
},
|
||||
deleteItem: async (id: string) => {
|
||||
const result = await deleteDeposit(id);
|
||||
if (result.success) {
|
||||
setDepositData(prev => prev.filter(item => item.id !== id));
|
||||
toast.success('입금 내역이 삭제되었습니다.');
|
||||
}
|
||||
return { success: result.success, error: result.error };
|
||||
},
|
||||
},
|
||||
|
||||
// 테이블 컬럼
|
||||
columns: tableColumns,
|
||||
|
||||
// 클라이언트 사이드 필터링
|
||||
clientSideFiltering: true,
|
||||
itemsPerPage: 20,
|
||||
|
||||
// 데이터 변경 콜백
|
||||
onDataChange: (data) => setDepositData(data),
|
||||
|
||||
// 검색 필터
|
||||
searchPlaceholder: '입금자명, 계좌명, 적요, 거래처 검색...',
|
||||
searchFilter: (item, searchValue) => {
|
||||
const search = searchValue.toLowerCase();
|
||||
return (
|
||||
item.depositorName.toLowerCase().includes(search) ||
|
||||
item.accountName.toLowerCase().includes(search) ||
|
||||
(item.note?.toLowerCase().includes(search) || false) ||
|
||||
(item.vendorName?.toLowerCase().includes(search) || false)
|
||||
);
|
||||
},
|
||||
|
||||
// 커스텀 필터 함수 (인라인 필터 사용)
|
||||
customFilterFn: (items, filterValues) => {
|
||||
return items.filter((item) => {
|
||||
// 거래처 필터
|
||||
if (vendorFilter !== 'all' && item.vendorName !== vendorFilter) {
|
||||
return false;
|
||||
}
|
||||
// 입금유형 필터
|
||||
if (depositTypeFilter !== 'all' && item.depositType !== depositTypeFilter) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
},
|
||||
|
||||
// 커스텀 정렬 함수
|
||||
customSortFn: (items, filterValues) => {
|
||||
const sorted = [...items];
|
||||
switch (sortOption) {
|
||||
case 'oldest':
|
||||
sorted.sort((a, b) => new Date(a.depositDate).getTime() - new Date(b.depositDate).getTime());
|
||||
break;
|
||||
case 'amountHigh':
|
||||
sorted.sort((a, b) => (b.depositAmount ?? 0) - (a.depositAmount ?? 0));
|
||||
break;
|
||||
case 'amountLow':
|
||||
sorted.sort((a, b) => (a.depositAmount ?? 0) - (b.depositAmount ?? 0));
|
||||
break;
|
||||
default: // latest
|
||||
sorted.sort((a, b) => new Date(b.depositDate).getTime() - new Date(a.depositDate).getTime());
|
||||
break;
|
||||
}
|
||||
return sorted;
|
||||
},
|
||||
|
||||
// 공통 헤더 옵션
|
||||
dateRangeSelector: {
|
||||
enabled: true,
|
||||
startDate,
|
||||
endDate,
|
||||
onStartDateChange: setStartDate,
|
||||
onEndDateChange: setEndDate,
|
||||
},
|
||||
|
||||
// 모바일 필터 설정
|
||||
filterConfig: [
|
||||
{
|
||||
key: 'depositType',
|
||||
label: '입금유형',
|
||||
type: 'single',
|
||||
options: DEPOSIT_TYPE_FILTER_OPTIONS.filter(o => o.value !== 'all'),
|
||||
},
|
||||
{
|
||||
key: 'sortBy',
|
||||
label: '정렬',
|
||||
type: 'single',
|
||||
options: SORT_OPTIONS,
|
||||
},
|
||||
],
|
||||
initialFilters: {
|
||||
depositType: depositTypeFilter,
|
||||
sortBy: sortOption,
|
||||
},
|
||||
filterTitle: '입금 필터',
|
||||
|
||||
// Stats 카드
|
||||
computeStats: (): StatCard[] => [
|
||||
{ label: '총 입금', value: `${stats.totalDeposit.toLocaleString()}원`, icon: Banknote, iconColor: 'text-blue-500' },
|
||||
{ label: '당월 입금', value: `${stats.monthlyDeposit.toLocaleString()}원`, icon: Banknote, iconColor: 'text-green-500' },
|
||||
{ label: '거래처 미설정', value: `${stats.vendorUnsetCount}건`, icon: Banknote, iconColor: 'text-orange-500' },
|
||||
{ label: '입금유형 미설정', value: `${stats.depositTypeUnsetCount}건`, icon: Banknote, iconColor: 'text-red-500' },
|
||||
],
|
||||
|
||||
// beforeTableContent: 계정과목명 Select + 저장 버튼 + 새로고침
|
||||
beforeTableContent: (
|
||||
<div className="flex items-center justify-between w-full">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium text-gray-700">계정과목명</span>
|
||||
<Select value={selectedAccountSubject} onValueChange={setSelectedAccountSubject}>
|
||||
<SelectTrigger className="w-[150px]">
|
||||
<SelectValue placeholder="계정과목명 선택" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{ACCOUNT_SUBJECT_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleRefresh}
|
||||
disabled={isRefreshing}
|
||||
>
|
||||
<RefreshCw className={`h-4 w-4 mr-2 ${isRefreshing ? 'animate-spin' : ''}`} />
|
||||
{isRefreshing ? '조회중...' : '새로고침'}
|
||||
</Button>
|
||||
</div>
|
||||
),
|
||||
|
||||
// tableHeaderActions: 3개 인라인 필터
|
||||
tableHeaderActions: ({ selectedItems }) => (
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
{/* 저장 버튼 */}
|
||||
<Button onClick={() => handleSaveAccountSubject(selectedItems)} className="bg-blue-500 hover:bg-blue-600">
|
||||
<Save className="h-4 w-4 mr-2" />
|
||||
저장
|
||||
</Button>
|
||||
|
||||
{/* 거래처 필터 */}
|
||||
<Select value={vendorFilter} onValueChange={setVendorFilter}>
|
||||
<SelectTrigger className="w-[140px]">
|
||||
<SelectValue placeholder="거래처" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{vendorOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* 입금유형 필터 */}
|
||||
<Select value={depositTypeFilter} onValueChange={setDepositTypeFilter}>
|
||||
<SelectTrigger className="w-[130px]">
|
||||
<SelectValue placeholder="입금유형" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{DEPOSIT_TYPE_FILTER_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* 정렬 */}
|
||||
<Select value={sortOption} onValueChange={(value) => setSortOption(value as SortOption)}>
|
||||
<SelectTrigger className="w-[120px]">
|
||||
<SelectValue placeholder="정렬" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{SORT_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
),
|
||||
|
||||
// 테이블 하단 합계 행
|
||||
tableFooter: (
|
||||
<TableRow className="bg-muted/50 font-medium">
|
||||
<TableCell className="text-center"></TableCell>
|
||||
<TableCell className="font-bold">합계</TableCell>
|
||||
<TableCell></TableCell>
|
||||
<TableCell></TableCell>
|
||||
<TableCell className="text-right font-bold">{tableTotals.totalAmount.toLocaleString()}</TableCell>
|
||||
<TableCell></TableCell>
|
||||
<TableCell></TableCell>
|
||||
<TableCell></TableCell>
|
||||
<TableCell></TableCell>
|
||||
</TableRow>
|
||||
),
|
||||
|
||||
// 삭제 확인 메시지
|
||||
deleteConfirmMessage: {
|
||||
title: '입금 삭제',
|
||||
description: '이 입금 내역을 삭제하시겠습니까? 이 작업은 취소할 수 없습니다.',
|
||||
},
|
||||
|
||||
// 테이블 행 렌더링
|
||||
renderTableRow: (
|
||||
item: DepositRecord,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
handlers: SelectionHandlers & RowClickHandlers<DepositRecord>
|
||||
) => {
|
||||
const isVendorUnset = !item.vendorName;
|
||||
const isDepositTypeUnset = item.depositType === 'unset';
|
||||
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={handlers.isSelected} onCheckedChange={handlers.onToggle} />
|
||||
</TableCell>
|
||||
<TableCell>{item.depositDate}</TableCell>
|
||||
<TableCell>{item.accountName}</TableCell>
|
||||
<TableCell>{item.depositorName}</TableCell>
|
||||
<TableCell className="text-right font-medium">{(item.depositAmount ?? 0).toLocaleString()}</TableCell>
|
||||
<TableCell className={isVendorUnset ? 'text-red-500 font-medium' : ''}>
|
||||
{item.vendorName || '미설정'}
|
||||
</TableCell>
|
||||
<TableCell className="text-gray-500">{item.note || '-'}</TableCell>
|
||||
<TableCell className="text-center">
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={isDepositTypeUnset ? 'border-red-300 text-red-500 bg-red-50' : ''}
|
||||
>
|
||||
{DEPOSIT_TYPE_LABELS[item.depositType]}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
|
||||
{handlers.isSelected && (
|
||||
<div className="flex items-center justify-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-gray-600 hover:text-gray-700 hover:bg-gray-50"
|
||||
onClick={() => handleEdit(item)}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-red-500 hover:text-red-600 hover:bg-red-50"
|
||||
onClick={() => handlers.onDelete?.(item)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
},
|
||||
|
||||
// 모바일 카드 렌더링
|
||||
renderMobileCard: (
|
||||
item: DepositRecord,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
handlers: SelectionHandlers & RowClickHandlers<DepositRecord>
|
||||
) => (
|
||||
<MobileCard
|
||||
key={item.id}
|
||||
title={item.depositorName}
|
||||
subtitle={item.accountName}
|
||||
badge={DEPOSIT_TYPE_LABELS[item.depositType]}
|
||||
badgeVariant="outline"
|
||||
isSelected={handlers.isSelected}
|
||||
onToggle={handlers.onToggle}
|
||||
onClick={() => handleRowClick(item)}
|
||||
details={[
|
||||
{ label: '입금일', value: item.depositDate },
|
||||
{ label: '입금액', value: `${(item.depositAmount ?? 0).toLocaleString()}원` },
|
||||
{ label: '거래처', value: item.vendorName || '-' },
|
||||
]}
|
||||
actions={
|
||||
handlers.isSelected ? (
|
||||
<div className="flex gap-2 w-full">
|
||||
<Button variant="outline" className="flex-1" onClick={() => handleEdit(item)}>
|
||||
<Pencil className="w-4 h-4 mr-2" /> 수정
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="flex-1 text-red-500 border-red-200 hover:bg-red-50 hover:text-red-600"
|
||||
onClick={() => handlers.onDelete?.(item)}
|
||||
>
|
||||
<Trash2 className="w-4 h-4 mr-2" /> 삭제
|
||||
</Button>
|
||||
</div>
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
),
|
||||
}),
|
||||
[
|
||||
initialData,
|
||||
startDate,
|
||||
endDate,
|
||||
stats,
|
||||
vendorFilter,
|
||||
depositTypeFilter,
|
||||
sortOption,
|
||||
selectedAccountSubject,
|
||||
vendorOptions,
|
||||
tableTotals,
|
||||
isRefreshing,
|
||||
handleRowClick,
|
||||
handleEdit,
|
||||
handleRefresh,
|
||||
handleSaveAccountSubject,
|
||||
]
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<IntegratedListTemplateV2
|
||||
title="입금관리"
|
||||
description="입금 내역을 등록합니다"
|
||||
icon={Banknote}
|
||||
headerActions={headerActions}
|
||||
stats={statCards}
|
||||
searchValue={searchQuery}
|
||||
onSearchChange={setSearchQuery}
|
||||
searchPlaceholder="입금자명, 계좌명, 적요, 거래처 검색..."
|
||||
beforeTableContent={accountSubjectSelector}
|
||||
tableHeaderActions={tableHeaderActions}
|
||||
tableColumns={tableColumns}
|
||||
tableFooter={tableFooter}
|
||||
data={paginatedData}
|
||||
totalCount={filteredData.length}
|
||||
allData={filteredData}
|
||||
selectedItems={selectedItems}
|
||||
onToggleSelection={toggleSelection}
|
||||
onToggleSelectAll={toggleSelectAll}
|
||||
getItemId={(item: DepositRecord) => item.id}
|
||||
renderTableRow={renderTableRow}
|
||||
renderMobileCard={renderMobileCard}
|
||||
pagination={{
|
||||
currentPage,
|
||||
totalPages,
|
||||
totalItems: filteredData.length,
|
||||
itemsPerPage,
|
||||
onPageChange: setCurrentPage,
|
||||
}}
|
||||
/>
|
||||
<UniversalListPage config={config} initialData={initialData} />
|
||||
|
||||
{/* 계정과목명 저장 확인 다이얼로그 */}
|
||||
<Dialog open={showSaveDialog} onOpenChange={setShowSaveDialog}>
|
||||
@@ -571,7 +564,7 @@ export function DepositManagement({ initialData, initialPagination }: DepositMan
|
||||
<DialogHeader>
|
||||
<DialogTitle>계정과목명 변경</DialogTitle>
|
||||
<DialogDescription>
|
||||
{selectedItems.size}개의 입금 유형을{' '}
|
||||
{selectedItemsForSave.size}개의 입금 유형을{' '}
|
||||
<span className="font-semibold text-orange-500">
|
||||
{ACCOUNT_SUBJECT_OPTIONS.find(o => o.value === selectedAccountSubject)?.label}
|
||||
</span>
|
||||
@@ -592,27 +585,6 @@ export function DepositManagement({ initialData, initialPagination }: DepositMan
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* 삭제 확인 다이얼로그 */}
|
||||
<AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>입금 삭제</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
이 입금 내역을 삭제하시겠습니까? 이 작업은 취소할 수 없습니다.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>취소</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleConfirmDelete}
|
||||
className="bg-red-600 hover:bg-red-700"
|
||||
>
|
||||
삭제
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
{/* 선택 필요 알림 다이얼로그 */}
|
||||
<AlertDialog open={showSelectWarningDialog} onOpenChange={setShowSelectWarningDialog}>
|
||||
<AlertDialogContent>
|
||||
|
||||
@@ -1,5 +1,16 @@
|
||||
'use client';
|
||||
|
||||
/**
|
||||
* 지출 예상 내역서 - UniversalListPage 마이그레이션
|
||||
*
|
||||
* 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
|
||||
* - 월별 그룹핑 테이블 (헤더, 소계, 합계 행 포함)
|
||||
* - 등록/수정 폼 다이얼로그
|
||||
* - 예상 지급일 변경 다이얼로그
|
||||
* - 일괄 삭제 다이얼로그
|
||||
* - 외부 선택 상태 관리 (데이터 행만 선택 가능)
|
||||
*/
|
||||
|
||||
import { useState, useMemo, useCallback, useTransition, useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { format } from 'date-fns';
|
||||
@@ -42,11 +53,12 @@ import {
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import {
|
||||
IntegratedListTemplateV2,
|
||||
type TableColumn,
|
||||
UniversalListPage,
|
||||
type UniversalListConfig,
|
||||
type SelectionHandlers,
|
||||
type RowClickHandlers,
|
||||
type StatCard,
|
||||
} from '@/components/templates/IntegratedListTemplateV2';
|
||||
import { DateRangeSelector } from '@/components/molecules/DateRangeSelector';
|
||||
} from '@/components/templates/UniversalListPage';
|
||||
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
|
||||
import type {
|
||||
ExpectedExpenseRecord,
|
||||
@@ -550,20 +562,8 @@ export function ExpectedExpenseManagement({
|
||||
return { label, totalAmount };
|
||||
}, [data, selectedItems]);
|
||||
|
||||
// ===== 통계 카드 =====
|
||||
const statCards: StatCard[] = useMemo(() => {
|
||||
const totalExpense = filteredRawData.reduce((sum, d) => sum + d.amount, 0);
|
||||
const expectedBalance = 10000000;
|
||||
|
||||
return [
|
||||
{ label: '지출 합계', value: `${totalExpense.toLocaleString()}원`, icon: Receipt, iconColor: 'text-red-500' },
|
||||
{ label: '예상 잔액', value: `${expectedBalance.toLocaleString()}원`, icon: Receipt, iconColor: 'text-blue-500' },
|
||||
];
|
||||
}, [filteredRawData]);
|
||||
|
||||
// ===== 테이블 컬럼 =====
|
||||
// 순서: 예상 지급일, 항목, 지출금액, 거래처, 계좌, 전자결재, 작업
|
||||
const tableColumns: TableColumn[] = useMemo(() => [
|
||||
const tableColumns = useMemo(() => [
|
||||
{ key: 'no', label: '번호', className: 'w-[60px] text-center' },
|
||||
{ key: 'expectedPaymentDate', label: '예상 지급일' },
|
||||
{ key: 'accountSubject', label: '항목' },
|
||||
@@ -591,7 +591,12 @@ export function ExpectedExpenseManagement({
|
||||
|
||||
// ===== 테이블 행 렌더링 =====
|
||||
// 컬럼 순서: 체크박스 + 번호 + 예상 지급일 + 항목 + 지출금액 + 거래처 + 계좌 + 전자결재 + 작업
|
||||
const renderTableRow = useCallback((item: TableRowData, index: number, globalIndex: number) => {
|
||||
const renderTableRow = useCallback((
|
||||
item: TableRowData,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
handlers: SelectionHandlers & RowClickHandlers<TableRowData>
|
||||
) => {
|
||||
// 월 헤더 행 (9개 컬럼)
|
||||
if (item.rowType === 'monthHeader') {
|
||||
return (
|
||||
@@ -728,9 +733,10 @@ export function ExpectedExpenseManagement({
|
||||
item: TableRowData,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
isSelected: boolean,
|
||||
onToggle: () => void
|
||||
handlers: SelectionHandlers & RowClickHandlers<TableRowData>
|
||||
) => {
|
||||
const isSelected = selectedItems.has(item.id);
|
||||
const onToggle = () => toggleSelection(item.id);
|
||||
// 헤더/소계/합계 행은 모바일에서 다르게 표시
|
||||
if (item.rowType !== 'data') {
|
||||
if (item.rowType === 'monthHeader') {
|
||||
@@ -807,49 +813,6 @@ export function ExpectedExpenseManagement({
|
||||
);
|
||||
}, []);
|
||||
|
||||
// ===== 헤더 액션 (날짜 선택) =====
|
||||
const headerActions = (
|
||||
<DateRangeSelector
|
||||
startDate={startDate}
|
||||
endDate={endDate}
|
||||
onStartDateChange={setStartDate}
|
||||
onEndDateChange={setEndDate}
|
||||
/>
|
||||
);
|
||||
|
||||
// ===== 테이블 헤더 액션 (거래처 필터/정렬 필터 - 탭 옆) =====
|
||||
const tableHeaderActions = (
|
||||
<div className="flex items-center gap-2">
|
||||
{/* 거래처 필터 */}
|
||||
<Select value={vendorFilter} onValueChange={setVendorFilter}>
|
||||
<SelectTrigger className="w-[140px] h-8 text-sm">
|
||||
<SelectValue placeholder="전체" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{vendorFilterOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* 정렬 필터 (최신순/등록순) */}
|
||||
<Select value={sortOption} onValueChange={(value) => setSortOption(value as SortOption)}>
|
||||
<SelectTrigger className="w-[100px] h-8 text-sm">
|
||||
<SelectValue placeholder="최신순" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{SORT_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
);
|
||||
|
||||
// ===== 선택된 항목 데이터 가져오기 =====
|
||||
const getSelectedItemsData = useCallback(() => {
|
||||
return data.filter(item => selectedItems.has(item.id));
|
||||
@@ -863,84 +826,216 @@ export function ExpectedExpenseManagement({
|
||||
router.push(`/ko/approval/draft/new?type=expected-expense&items=${encodeURIComponent(selectedIds)}`);
|
||||
}, [getSelectedItemsData, router]);
|
||||
|
||||
// ===== 테이블 앞 컨텐츠 (액션 버튼) =====
|
||||
const beforeTableContent = (
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
{/* 등록 버튼 */}
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleOpenCreateDialog}
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
등록
|
||||
</Button>
|
||||
// ===== UniversalListPage Config =====
|
||||
const config: UniversalListConfig<TableRowData> = useMemo(
|
||||
() => ({
|
||||
// 페이지 기본 정보
|
||||
title: '지출 예상 내역서',
|
||||
description: '지출 예상 내역을 등록하고 조회합니다',
|
||||
icon: Receipt,
|
||||
basePath: '/accounting/expected-expense',
|
||||
|
||||
{/* 예상 지급일 변경 버튼 - 1개 이상 선택 시 활성화 */}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleOpenDateChangeDialog}
|
||||
disabled={selectedItems.size === 0}
|
||||
>
|
||||
<CalendarIcon className="h-4 w-4 mr-1" />
|
||||
예상 지급일 변경 {selectedItems.size > 0 && `(${selectedItems.size})`}
|
||||
</Button>
|
||||
// ID 추출
|
||||
idField: 'id',
|
||||
|
||||
{/* 전자결재 버튼 - 1개 이상 선택 시 활성화 */}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleElectronicApproval}
|
||||
disabled={selectedItems.size === 0}
|
||||
>
|
||||
<FileText className="h-4 w-4 mr-1" />
|
||||
전자결재 {selectedItems.size > 0 && `(${selectedItems.size})`}
|
||||
</Button>
|
||||
// API 액션
|
||||
actions: {
|
||||
getList: async () => {
|
||||
return {
|
||||
success: true,
|
||||
data: tableData,
|
||||
totalCount: initialPagination.total || filteredRawData.length,
|
||||
};
|
||||
},
|
||||
},
|
||||
|
||||
{/* 일괄삭제 버튼 - 1개 이상 선택 시 활성화 */}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setShowBulkDeleteDialog(true)}
|
||||
disabled={selectedItems.size === 0}
|
||||
className="text-red-600 hover:text-red-700 hover:bg-red-50"
|
||||
>
|
||||
<Trash2 className="h-4 w-4 mr-1" />
|
||||
일괄삭제 {selectedItems.size > 0 && `(${selectedItems.size})`}
|
||||
</Button>
|
||||
</div>
|
||||
// 테이블 컬럼
|
||||
columns: tableColumns,
|
||||
|
||||
// 클라이언트 사이드 필터링 (이미 tableData에서 필터링 완료)
|
||||
clientSideFiltering: false,
|
||||
itemsPerPage,
|
||||
|
||||
// 검색
|
||||
searchPlaceholder: '거래처, 계정과목, 적요 검색...',
|
||||
onSearchChange: setSearchQuery,
|
||||
|
||||
// 행 번호 숨기기 (커스텀 번호 사용)
|
||||
showRowNumber: false,
|
||||
|
||||
// 날짜 범위 선택기
|
||||
dateRangeSelector: {
|
||||
enabled: true,
|
||||
startDate,
|
||||
endDate,
|
||||
onStartDateChange: setStartDate,
|
||||
onEndDateChange: setEndDate,
|
||||
},
|
||||
|
||||
// 모바일 필터 설정
|
||||
filterConfig: [
|
||||
{
|
||||
key: 'transactionType',
|
||||
label: '거래유형',
|
||||
type: 'single',
|
||||
options: TRANSACTION_TYPE_FILTER_OPTIONS.filter(o => o.value !== 'all'),
|
||||
},
|
||||
{
|
||||
key: 'paymentStatus',
|
||||
label: '지급상태',
|
||||
type: 'single',
|
||||
options: PAYMENT_STATUS_FILTER_OPTIONS.filter(o => o.value !== 'all'),
|
||||
},
|
||||
{
|
||||
key: 'sortBy',
|
||||
label: '정렬',
|
||||
type: 'single',
|
||||
options: SORT_OPTIONS,
|
||||
},
|
||||
],
|
||||
initialFilters: {
|
||||
transactionType: 'all',
|
||||
paymentStatus: 'all',
|
||||
sortBy: sortOption,
|
||||
},
|
||||
filterTitle: '예상비용 필터',
|
||||
|
||||
// 테이블 헤더 액션 (거래처/정렬 필터)
|
||||
tableHeaderActions: () => (
|
||||
<div className="flex items-center gap-2">
|
||||
{/* 거래처 필터 */}
|
||||
<Select value={vendorFilter} onValueChange={setVendorFilter}>
|
||||
<SelectTrigger className="w-[140px] h-8 text-sm">
|
||||
<SelectValue placeholder="전체" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{vendorFilterOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* 정렬 필터 (최신순/등록순) */}
|
||||
<Select value={sortOption} onValueChange={(value) => setSortOption(value as SortOption)}>
|
||||
<SelectTrigger className="w-[100px] h-8 text-sm">
|
||||
<SelectValue placeholder="최신순" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{SORT_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
),
|
||||
|
||||
// 테이블 앞 컨텐츠 (액션 버튼)
|
||||
beforeTableContent: (
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
{/* 등록 버튼 */}
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleOpenCreateDialog}
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
등록
|
||||
</Button>
|
||||
|
||||
{/* 예상 지급일 변경 버튼 - 1개 이상 선택 시 활성화 */}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleOpenDateChangeDialog}
|
||||
disabled={selectedItems.size === 0}
|
||||
>
|
||||
<CalendarIcon className="h-4 w-4 mr-1" />
|
||||
예상 지급일 변경 {selectedItems.size > 0 && `(${selectedItems.size})`}
|
||||
</Button>
|
||||
|
||||
{/* 전자결재 버튼 - 1개 이상 선택 시 활성화 */}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleElectronicApproval}
|
||||
disabled={selectedItems.size === 0}
|
||||
>
|
||||
<FileText className="h-4 w-4 mr-1" />
|
||||
전자결재 {selectedItems.size > 0 && `(${selectedItems.size})`}
|
||||
</Button>
|
||||
|
||||
{/* 일괄삭제 버튼 - 1개 이상 선택 시 활성화 */}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setShowBulkDeleteDialog(true)}
|
||||
disabled={selectedItems.size === 0}
|
||||
className="text-red-600 hover:text-red-700 hover:bg-red-50"
|
||||
>
|
||||
<Trash2 className="h-4 w-4 mr-1" />
|
||||
일괄삭제 {selectedItems.size > 0 && `(${selectedItems.size})`}
|
||||
</Button>
|
||||
</div>
|
||||
),
|
||||
|
||||
// Stats 카드
|
||||
computeStats: (): StatCard[] => {
|
||||
const totalExpense = filteredRawData.reduce((sum, d) => sum + d.amount, 0);
|
||||
const expectedBalance = 10000000;
|
||||
|
||||
return [
|
||||
{ label: '지출 합계', value: `${totalExpense.toLocaleString()}원`, icon: Receipt, iconColor: 'text-red-500' },
|
||||
{ label: '예상 잔액', value: `${expectedBalance.toLocaleString()}원`, icon: Receipt, iconColor: 'text-blue-500' },
|
||||
];
|
||||
},
|
||||
|
||||
// 테이블 행 렌더링
|
||||
renderTableRow,
|
||||
|
||||
// 모바일 카드 렌더링
|
||||
renderMobileCard,
|
||||
}),
|
||||
[
|
||||
tableData,
|
||||
tableColumns,
|
||||
filteredRawData,
|
||||
initialPagination,
|
||||
itemsPerPage,
|
||||
startDate,
|
||||
endDate,
|
||||
vendorFilter,
|
||||
vendorFilterOptions,
|
||||
sortOption,
|
||||
selectedItems,
|
||||
handleOpenCreateDialog,
|
||||
handleOpenDateChangeDialog,
|
||||
handleElectronicApproval,
|
||||
renderTableRow,
|
||||
renderMobileCard,
|
||||
]
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<IntegratedListTemplateV2
|
||||
title="지출 예상 내역서"
|
||||
description="지출 예상 내역을 등록하고 조회합니다"
|
||||
icon={Receipt}
|
||||
headerActions={headerActions}
|
||||
stats={statCards}
|
||||
searchValue={searchQuery}
|
||||
onSearchChange={setSearchQuery}
|
||||
searchPlaceholder="거래처, 계정과목, 적요 검색..."
|
||||
tableHeaderActions={tableHeaderActions}
|
||||
beforeTableContent={beforeTableContent}
|
||||
tableColumns={tableColumns}
|
||||
data={tableData}
|
||||
totalCount={initialPagination.total || filteredRawData.length}
|
||||
allData={tableData}
|
||||
selectedItems={selectedItems}
|
||||
onToggleSelection={toggleSelection}
|
||||
onToggleSelectAll={toggleSelectAll}
|
||||
getItemId={(item: TableRowData) => item.id}
|
||||
renderTableRow={renderTableRow}
|
||||
renderMobileCard={renderMobileCard}
|
||||
pagination={{
|
||||
<UniversalListPage
|
||||
config={config}
|
||||
initialData={tableData}
|
||||
externalPagination={{
|
||||
currentPage,
|
||||
totalPages: totalPages || 1,
|
||||
totalItems: initialPagination.total || filteredRawData.length,
|
||||
itemsPerPage,
|
||||
onPageChange: setCurrentPage,
|
||||
}}
|
||||
externalSelection={{
|
||||
selectedItems,
|
||||
onToggleSelection: toggleSelection,
|
||||
onToggleSelectAll: toggleSelectAll,
|
||||
getItemId: (item: TableRowData) => item.id,
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* 삭제 확인 다이얼로그 */}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,15 @@
|
||||
'use client';
|
||||
|
||||
/**
|
||||
* 거래처원장 - UniversalListPage 마이그레이션
|
||||
*
|
||||
* 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
|
||||
* - 서버 사이드 필터링/페이지네이션
|
||||
* - dateRangeSelector + 엑셀 다운로드 버튼 (headerActions)
|
||||
* - tableFooter: 합계 행
|
||||
* - Stats 카드 (API 통계)
|
||||
*/
|
||||
|
||||
import { useState, useMemo, useCallback, useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { format, startOfMonth, endOfMonth } from 'date-fns';
|
||||
@@ -7,18 +17,30 @@ import { Download, FileText } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { TableRow, TableCell } from '@/components/ui/table';
|
||||
import { MobileCard } from '@/components/molecules/MobileCard';
|
||||
import {
|
||||
IntegratedListTemplateV2,
|
||||
type TableColumn,
|
||||
UniversalListPage,
|
||||
type UniversalListConfig,
|
||||
type SelectionHandlers,
|
||||
type RowClickHandlers,
|
||||
type StatCard,
|
||||
} from '@/components/templates/IntegratedListTemplateV2';
|
||||
import { DateRangeSelector } from '@/components/molecules/DateRangeSelector';
|
||||
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
|
||||
} from '@/components/templates/UniversalListPage';
|
||||
import type { VendorLedgerItem, VendorLedgerSummary } from './types';
|
||||
import { getVendorLedgerList, getVendorLedgerSummary, exportVendorLedgerExcel } from './actions';
|
||||
import { toast } from 'sonner';
|
||||
import { isNextRedirectError } from '@/lib/utils/redirect-error';
|
||||
|
||||
// ===== 테이블 컬럼 정의 =====
|
||||
const tableColumns = [
|
||||
{ key: 'no', label: 'No.', className: 'text-center w-[60px]' },
|
||||
{ key: 'vendorName', label: '거래처명' },
|
||||
{ key: 'carryoverBalance', label: '이월잔액', className: 'text-right w-[120px]' },
|
||||
{ key: 'sales', label: '매출', className: 'text-right w-[120px]' },
|
||||
{ key: 'collection', label: '수금', className: 'text-right w-[120px]' },
|
||||
{ key: 'balance', label: '잔액', className: 'text-right w-[120px]' },
|
||||
{ key: 'paymentDate', label: '결제일', className: 'text-center w-[100px]' },
|
||||
];
|
||||
|
||||
// ===== Props =====
|
||||
interface VendorLedgerProps {
|
||||
initialData?: VendorLedgerItem[];
|
||||
@@ -38,15 +60,7 @@ export function VendorLedger({
|
||||
}: VendorLedgerProps) {
|
||||
const router = useRouter();
|
||||
|
||||
// ===== 상태 관리 =====
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [startDate, setStartDate] = useState(() => format(startOfMonth(new Date()), 'yyyy-MM-dd'));
|
||||
const [endDate, setEndDate] = useState(() => format(endOfMonth(new Date()), 'yyyy-MM-dd'));
|
||||
const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
|
||||
const [currentPage, setCurrentPage] = useState(initialPagination?.currentPage || 1);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
// 데이터 상태
|
||||
// ===== 외부 상태 (UniversalListPage 외부에서 관리) =====
|
||||
const [data, setData] = useState<VendorLedgerItem[]>(initialData);
|
||||
const [summary, setSummary] = useState<VendorLedgerSummary>(
|
||||
initialSummary || { carryoverBalance: 0, totalSales: 0, totalCollection: 0, balance: 0 }
|
||||
@@ -55,6 +69,13 @@ export function VendorLedger({
|
||||
initialPagination || { currentPage: 1, lastPage: 1, perPage: 20, total: 0 }
|
||||
);
|
||||
|
||||
// 필터 상태
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [startDate, setStartDate] = useState(() => format(startOfMonth(new Date()), 'yyyy-MM-dd'));
|
||||
const [endDate, setEndDate] = useState(() => format(endOfMonth(new Date()), 'yyyy-MM-dd'));
|
||||
const [currentPage, setCurrentPage] = useState(initialPagination?.currentPage || 1);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
// ===== 데이터 로드 =====
|
||||
const loadData = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
@@ -94,25 +115,6 @@ export function VendorLedger({
|
||||
loadData();
|
||||
}, [loadData]);
|
||||
|
||||
// ===== 체크박스 핸들러 =====
|
||||
const toggleSelection = useCallback((id: string) => {
|
||||
setSelectedItems(prev => {
|
||||
const newSet = new Set(prev);
|
||||
if (newSet.has(id)) newSet.delete(id);
|
||||
else newSet.add(id);
|
||||
return newSet;
|
||||
});
|
||||
}, []);
|
||||
|
||||
// ===== 전체 선택 핸들러 =====
|
||||
const toggleSelectAll = useCallback(() => {
|
||||
if (selectedItems.size === data.length && data.length > 0) {
|
||||
setSelectedItems(new Set());
|
||||
} else {
|
||||
setSelectedItems(new Set(data.map(item => item.id)));
|
||||
}
|
||||
}, [selectedItems.size, data]);
|
||||
|
||||
// ===== 합계 계산 =====
|
||||
const totals = useMemo(() => {
|
||||
return data.reduce(
|
||||
@@ -126,15 +128,17 @@ export function VendorLedger({
|
||||
);
|
||||
}, [data]);
|
||||
|
||||
// ===== 액션 핸들러 =====
|
||||
const handleRowClick = useCallback((item: VendorLedgerItem) => {
|
||||
// 상세 페이지로 이동 시 날짜 범위 파라미터도 전달
|
||||
const params = new URLSearchParams();
|
||||
if (startDate) params.set('start_date', startDate);
|
||||
if (endDate) params.set('end_date', endDate);
|
||||
const queryString = params.toString();
|
||||
router.push(`/ko/accounting/vendor-ledger/${item.id}${queryString ? `?${queryString}` : ''}`);
|
||||
}, [router, startDate, endDate]);
|
||||
// ===== 핸들러 =====
|
||||
const handleRowClick = useCallback(
|
||||
(item: VendorLedgerItem) => {
|
||||
const params = new URLSearchParams();
|
||||
if (startDate) params.set('start_date', startDate);
|
||||
if (endDate) params.set('end_date', endDate);
|
||||
const queryString = params.toString();
|
||||
router.push(`/ko/accounting/vendor-ledger/${item.id}${queryString ? `?${queryString}` : ''}`);
|
||||
},
|
||||
[router, startDate, endDate]
|
||||
);
|
||||
|
||||
const handleExcelDownload = useCallback(async () => {
|
||||
const result = await exportVendorLedgerExcel({
|
||||
@@ -164,160 +168,189 @@ export function VendorLedger({
|
||||
return amount.toLocaleString();
|
||||
};
|
||||
|
||||
// ===== 통계 카드 =====
|
||||
const statCards: StatCard[] = useMemo(() => [
|
||||
{ label: '전기 이월', value: `${summary.carryoverBalance.toLocaleString()}원`, icon: FileText, iconColor: 'text-blue-500' },
|
||||
{ label: '매출', value: `${summary.totalSales.toLocaleString()}원`, icon: FileText, iconColor: 'text-green-500' },
|
||||
{ label: '수금', value: `${summary.totalCollection.toLocaleString()}원`, icon: FileText, iconColor: 'text-orange-500' },
|
||||
{ label: '잔액', value: `${summary.balance.toLocaleString()}원`, icon: FileText, iconColor: 'text-red-500' },
|
||||
], [summary]);
|
||||
// ===== UniversalListPage Config =====
|
||||
const config: UniversalListConfig<VendorLedgerItem> = useMemo(
|
||||
() => ({
|
||||
// 페이지 기본 정보
|
||||
title: '거래처원장',
|
||||
description: '거래처별 기간 내역을 조회합니다.',
|
||||
icon: FileText,
|
||||
basePath: '/accounting/vendor-ledger',
|
||||
|
||||
// ===== 테이블 컬럼 =====
|
||||
const tableColumns: TableColumn[] = useMemo(() => [
|
||||
{ key: 'no', label: 'No.', className: 'text-center w-[60px]' },
|
||||
{ key: 'vendorName', label: '거래처명' },
|
||||
{ key: 'carryoverBalance', label: '이월잔액', className: 'text-right w-[120px]' },
|
||||
{ key: 'sales', label: '매출', className: 'text-right w-[120px]' },
|
||||
{ key: 'collection', label: '수금', className: 'text-right w-[120px]' },
|
||||
{ key: 'balance', label: '잔액', className: 'text-right w-[120px]' },
|
||||
{ key: 'paymentDate', label: '결제일', className: 'text-center w-[100px]' },
|
||||
], []);
|
||||
// ID 추출
|
||||
idField: 'id',
|
||||
|
||||
// ===== 테이블 행 렌더링 =====
|
||||
const renderTableRow = useCallback((item: VendorLedgerItem, index: number, globalIndex: number) => {
|
||||
const isSelected = selectedItems.has(item.id);
|
||||
// API 액션
|
||||
actions: {
|
||||
getList: async () => {
|
||||
return {
|
||||
success: true,
|
||||
data: data,
|
||||
totalCount: pagination.total,
|
||||
};
|
||||
},
|
||||
},
|
||||
|
||||
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>
|
||||
{/* No. */}
|
||||
<TableCell className="text-center text-sm text-gray-500">
|
||||
{globalIndex}
|
||||
</TableCell>
|
||||
{/* 거래처명 */}
|
||||
<TableCell className="font-medium">{item.vendorName}</TableCell>
|
||||
{/* 이월잔액 */}
|
||||
<TableCell className="text-right">
|
||||
{item.carryoverBalance !== 0 && (
|
||||
<span className={item.carryoverBalance < 0 ? 'text-red-600' : ''}>
|
||||
{formatAmount(item.carryoverBalance)}
|
||||
// 테이블 컬럼
|
||||
columns: tableColumns,
|
||||
|
||||
// 서버 사이드 필터링
|
||||
clientSideFiltering: false,
|
||||
itemsPerPage: 20,
|
||||
isLoading,
|
||||
|
||||
// 검색
|
||||
searchPlaceholder: '거래처명 검색...',
|
||||
onSearchChange: setSearchQuery,
|
||||
|
||||
// 날짜 선택기
|
||||
dateRangeSelector: {
|
||||
enabled: true,
|
||||
startDate,
|
||||
endDate,
|
||||
onStartDateChange: setStartDate,
|
||||
onEndDateChange: setEndDate,
|
||||
},
|
||||
|
||||
// 헤더 액션 (엑셀 다운로드) - 함수로 변환
|
||||
headerActions: () => (
|
||||
<Button variant="outline" size="sm" onClick={handleExcelDownload}>
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
엑셀 다운로드
|
||||
</Button>
|
||||
),
|
||||
|
||||
// 테이블 푸터 (합계 행)
|
||||
tableFooter: (
|
||||
<TableRow className="bg-gray-100 font-medium">
|
||||
<TableCell className="text-center" />
|
||||
<TableCell className="text-center font-bold">합계</TableCell>
|
||||
<TableCell />
|
||||
<TableCell className="text-right">{formatAmount(totals.carryoverBalance)}</TableCell>
|
||||
<TableCell className="text-right">{formatAmount(totals.sales)}</TableCell>
|
||||
<TableCell className="text-right">{formatAmount(totals.collection)}</TableCell>
|
||||
<TableCell className="text-right">{formatAmount(totals.balance)}</TableCell>
|
||||
<TableCell />
|
||||
</TableRow>
|
||||
),
|
||||
|
||||
// Stats 카드
|
||||
computeStats: (): StatCard[] => [
|
||||
{
|
||||
label: '전기 이월',
|
||||
value: `${summary.carryoverBalance.toLocaleString()}원`,
|
||||
icon: FileText,
|
||||
iconColor: 'text-blue-500',
|
||||
},
|
||||
{
|
||||
label: '매출',
|
||||
value: `${summary.totalSales.toLocaleString()}원`,
|
||||
icon: FileText,
|
||||
iconColor: 'text-green-500',
|
||||
},
|
||||
{
|
||||
label: '수금',
|
||||
value: `${summary.totalCollection.toLocaleString()}원`,
|
||||
icon: FileText,
|
||||
iconColor: 'text-orange-500',
|
||||
},
|
||||
{
|
||||
label: '잔액',
|
||||
value: `${summary.balance.toLocaleString()}원`,
|
||||
icon: FileText,
|
||||
iconColor: 'text-red-500',
|
||||
},
|
||||
],
|
||||
|
||||
// 테이블 행 렌더링
|
||||
renderTableRow: (
|
||||
item: VendorLedgerItem,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
handlers: SelectionHandlers & RowClickHandlers<VendorLedgerItem>
|
||||
) => (
|
||||
<TableRow
|
||||
key={item.id}
|
||||
className="hover:bg-muted/50 cursor-pointer"
|
||||
onClick={() => handleRowClick(item)}
|
||||
>
|
||||
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
|
||||
<Checkbox checked={handlers.isSelected} onCheckedChange={handlers.onToggle} />
|
||||
</TableCell>
|
||||
{/* No. */}
|
||||
<TableCell className="text-center text-sm text-gray-500">{globalIndex}</TableCell>
|
||||
{/* 거래처명 */}
|
||||
<TableCell className="font-medium">{item.vendorName}</TableCell>
|
||||
{/* 이월잔액 */}
|
||||
<TableCell className="text-right">
|
||||
{item.carryoverBalance !== 0 && (
|
||||
<span className={item.carryoverBalance < 0 ? 'text-red-600' : ''}>
|
||||
{formatAmount(item.carryoverBalance)}
|
||||
</span>
|
||||
)}
|
||||
</TableCell>
|
||||
{/* 매출 */}
|
||||
<TableCell className="text-right">{formatAmount(item.sales)}</TableCell>
|
||||
{/* 수금 */}
|
||||
<TableCell className="text-right">{formatAmount(item.collection)}</TableCell>
|
||||
{/* 잔액 */}
|
||||
<TableCell className="text-right">
|
||||
<span className={item.balance < 0 ? 'text-red-600' : ''}>
|
||||
{formatAmount(item.balance)}
|
||||
</span>
|
||||
)}
|
||||
</TableCell>
|
||||
{/* 매출 */}
|
||||
<TableCell className="text-right">{formatAmount(item.sales)}</TableCell>
|
||||
{/* 수금 */}
|
||||
<TableCell className="text-right">{formatAmount(item.collection)}</TableCell>
|
||||
{/* 잔액 */}
|
||||
<TableCell className="text-right">
|
||||
<span className={item.balance < 0 ? 'text-red-600' : ''}>
|
||||
{formatAmount(item.balance)}
|
||||
</span>
|
||||
</TableCell>
|
||||
{/* 결제일 */}
|
||||
<TableCell className="text-center">{item.paymentDate}</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
}, [selectedItems, toggleSelection, handleRowClick]);
|
||||
</TableCell>
|
||||
{/* 결제일 */}
|
||||
<TableCell className="text-center">{item.paymentDate}</TableCell>
|
||||
</TableRow>
|
||||
),
|
||||
|
||||
// ===== 모바일 카드 렌더링 =====
|
||||
const renderMobileCard = useCallback((
|
||||
item: VendorLedgerItem,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
isSelected: boolean,
|
||||
onToggle: () => void
|
||||
) => {
|
||||
return (
|
||||
<ListMobileCard
|
||||
id={item.id}
|
||||
title={item.vendorName}
|
||||
isSelected={isSelected}
|
||||
onToggleSelection={onToggle}
|
||||
infoGrid={
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<InfoField label="이월잔액" value={formatAmount(item.carryoverBalance) || '-'} />
|
||||
<InfoField label="매출" value={formatAmount(item.sales) || '-'} />
|
||||
<InfoField label="수금" value={formatAmount(item.collection) || '-'} />
|
||||
<InfoField label="잔액" value={formatAmount(item.balance) || '-'} />
|
||||
<InfoField label="결제일" value={item.paymentDate || '-'} />
|
||||
</div>
|
||||
}
|
||||
onCardClick={() => handleRowClick(item)}
|
||||
/>
|
||||
);
|
||||
}, [handleRowClick]);
|
||||
|
||||
// ===== 헤더 액션 =====
|
||||
const headerActions = (
|
||||
<>
|
||||
<DateRangeSelector
|
||||
startDate={startDate}
|
||||
endDate={endDate}
|
||||
onStartDateChange={setStartDate}
|
||||
onEndDateChange={setEndDate}
|
||||
/>
|
||||
<Button
|
||||
className="ml-auto"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleExcelDownload}
|
||||
>
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
엑셀 다운로드
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
|
||||
// ===== 테이블 하단 합계 행 =====
|
||||
const tableFooter = (
|
||||
<TableRow className="bg-gray-100 font-medium">
|
||||
<TableCell className="text-center"></TableCell>
|
||||
<TableCell className="text-center font-bold">합계</TableCell>
|
||||
<TableCell></TableCell>
|
||||
<TableCell className="text-right">{formatAmount(totals.carryoverBalance)}</TableCell>
|
||||
<TableCell className="text-right">{formatAmount(totals.sales)}</TableCell>
|
||||
<TableCell className="text-right">{formatAmount(totals.collection)}</TableCell>
|
||||
<TableCell className="text-right">{formatAmount(totals.balance)}</TableCell>
|
||||
<TableCell></TableCell>
|
||||
</TableRow>
|
||||
// 모바일 카드 렌더링
|
||||
renderMobileCard: (
|
||||
item: VendorLedgerItem,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
handlers: SelectionHandlers & RowClickHandlers<VendorLedgerItem>
|
||||
) => (
|
||||
<MobileCard
|
||||
key={item.id}
|
||||
title={item.vendorName}
|
||||
subtitle={`결제일: ${item.paymentDate || '-'}`}
|
||||
isSelected={handlers.isSelected}
|
||||
onToggle={handlers.onToggle}
|
||||
onClick={() => handleRowClick(item)}
|
||||
details={[
|
||||
{ label: '이월잔액', value: formatAmount(item.carryoverBalance) || '-' },
|
||||
{ label: '매출', value: formatAmount(item.sales) || '-' },
|
||||
{ label: '수금', value: formatAmount(item.collection) || '-' },
|
||||
{ label: '잔액', value: formatAmount(item.balance) || '-' },
|
||||
]}
|
||||
/>
|
||||
),
|
||||
}),
|
||||
[
|
||||
data,
|
||||
pagination,
|
||||
summary,
|
||||
totals,
|
||||
startDate,
|
||||
endDate,
|
||||
isLoading,
|
||||
handleRowClick,
|
||||
handleExcelDownload,
|
||||
]
|
||||
);
|
||||
|
||||
return (
|
||||
<IntegratedListTemplateV2
|
||||
title="거래처원장"
|
||||
description="거래처별 기간 내역을 조회합니다."
|
||||
icon={FileText}
|
||||
headerActions={headerActions}
|
||||
stats={statCards}
|
||||
searchValue={searchQuery}
|
||||
onSearchChange={setSearchQuery}
|
||||
searchPlaceholder="거래처명 검색..."
|
||||
tableColumns={tableColumns}
|
||||
tableFooter={tableFooter}
|
||||
data={data}
|
||||
totalCount={pagination.total}
|
||||
allData={data}
|
||||
selectedItems={selectedItems}
|
||||
onToggleSelection={toggleSelection}
|
||||
onToggleSelectAll={toggleSelectAll}
|
||||
getItemId={(item: VendorLedgerItem) => item.id}
|
||||
renderTableRow={renderTableRow}
|
||||
renderMobileCard={renderMobileCard}
|
||||
pagination={{
|
||||
currentPage: pagination.currentPage,
|
||||
<UniversalListPage
|
||||
config={config}
|
||||
initialData={data}
|
||||
externalPagination={{
|
||||
currentPage,
|
||||
totalPages: pagination.lastPage,
|
||||
totalItems: pagination.total,
|
||||
itemsPerPage: pagination.perPage,
|
||||
itemsPerPage: 20,
|
||||
onPageChange: setCurrentPage,
|
||||
}}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,14 @@
|
||||
'use client';
|
||||
|
||||
/**
|
||||
* 거래처관리 - UniversalListPage 마이그레이션
|
||||
*
|
||||
* IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
|
||||
* - 클라이언트 사이드 필터링/페이지네이션
|
||||
* - computeStats: 통계 카드 (전체/매출/매입 거래처)
|
||||
* - tableHeaderActions: 5개 필터 (구분, 신용등급, 거래등급, 악성채권, 정렬)
|
||||
*/
|
||||
|
||||
import { useState, useMemo, useCallback } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import {
|
||||
@@ -30,10 +39,13 @@ import {
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import {
|
||||
IntegratedListTemplateV2,
|
||||
UniversalListPage,
|
||||
type UniversalListConfig,
|
||||
type TableColumn,
|
||||
type StatCard,
|
||||
} from '@/components/templates/IntegratedListTemplateV2';
|
||||
type SelectionHandlers,
|
||||
type RowClickHandlers,
|
||||
} from '@/components/templates/UniversalListPage';
|
||||
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
|
||||
import { toast } from 'sonner';
|
||||
import { deleteClient } from './actions';
|
||||
@@ -231,9 +243,12 @@ export function VendorManagementClient({ initialData, initialTotal }: VendorMana
|
||||
], []);
|
||||
|
||||
// ===== 테이블 행 렌더링 =====
|
||||
const renderTableRow = useCallback((item: Vendor, index: number, globalIndex: number) => {
|
||||
const isSelected = selectedItems.has(item.id);
|
||||
|
||||
const renderTableRow = useCallback((
|
||||
item: Vendor,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
handlers: SelectionHandlers & RowClickHandlers<Vendor>
|
||||
) => {
|
||||
return (
|
||||
<TableRow
|
||||
key={item.id}
|
||||
@@ -241,7 +256,7 @@ export function VendorManagementClient({ initialData, initialTotal }: VendorMana
|
||||
onClick={() => handleRowClick(item)}
|
||||
>
|
||||
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
|
||||
<Checkbox checked={isSelected} onCheckedChange={() => toggleSelection(item.id)} />
|
||||
<Checkbox checked={handlers.isSelected} onCheckedChange={handlers.onToggle} />
|
||||
</TableCell>
|
||||
{/* 번호 */}
|
||||
<TableCell className="text-center text-sm text-gray-500">{globalIndex}</TableCell>
|
||||
@@ -289,7 +304,7 @@ export function VendorManagementClient({ initialData, initialTotal }: VendorMana
|
||||
</TableCell>
|
||||
{/* 작업 */}
|
||||
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
|
||||
{isSelected && (
|
||||
{handlers.isSelected && (
|
||||
<div className="flex items-center justify-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
@@ -312,15 +327,14 @@ export function VendorManagementClient({ initialData, initialTotal }: VendorMana
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
}, [selectedItems, toggleSelection, handleRowClick, handleEdit, handleDeleteClick]);
|
||||
}, [handleRowClick, handleEdit, handleDeleteClick]);
|
||||
|
||||
// ===== 모바일 카드 렌더링 =====
|
||||
const renderMobileCard = useCallback((
|
||||
item: Vendor,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
isSelected: boolean,
|
||||
onToggle: () => void
|
||||
handlers: SelectionHandlers & RowClickHandlers<Vendor>
|
||||
) => {
|
||||
return (
|
||||
<ListMobileCard
|
||||
@@ -336,8 +350,8 @@ export function VendorManagementClient({ initialData, initialTotal }: VendorMana
|
||||
</Badge>
|
||||
</>
|
||||
}
|
||||
isSelected={isSelected}
|
||||
onToggleSelection={onToggle}
|
||||
isSelected={handlers.isSelected}
|
||||
onToggleSelection={handlers.onToggle}
|
||||
infoGrid={
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<InfoField label="거래처코드" value={item.vendorCode} />
|
||||
@@ -351,7 +365,7 @@ export function VendorManagementClient({ initialData, initialTotal }: VendorMana
|
||||
</div>
|
||||
}
|
||||
actions={
|
||||
isSelected ? (
|
||||
handlers.isSelected ? (
|
||||
<div className="flex gap-2 w-full">
|
||||
<Button variant="outline" className="flex-1" onClick={() => handleRowClick(item)}>
|
||||
<Eye className="w-4 h-4 mr-2" /> 상세
|
||||
@@ -374,109 +388,198 @@ export function VendorManagementClient({ initialData, initialTotal }: VendorMana
|
||||
);
|
||||
}, [handleRowClick, handleEdit, handleDeleteClick]);
|
||||
|
||||
// ===== 테이블 헤더 액션 (5개 필터) =====
|
||||
const tableHeaderActions = (
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
{/* 구분 필터 */}
|
||||
<Select value={categoryFilter} onValueChange={setCategoryFilter}>
|
||||
<SelectTrigger className="w-[120px]">
|
||||
<SelectValue placeholder="구분" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{VENDOR_CATEGORY_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
// ===== UniversalListPage Config =====
|
||||
const config: UniversalListConfig<Vendor> = useMemo(
|
||||
() => ({
|
||||
// 페이지 기본 정보
|
||||
title: '거래처관리',
|
||||
description: '거래처 정보를 등록하고 관리합니다',
|
||||
icon: Building2,
|
||||
basePath: '/accounting/vendors',
|
||||
|
||||
{/* 신용등급 필터 */}
|
||||
<Select value={creditRatingFilter} onValueChange={setCreditRatingFilter}>
|
||||
<SelectTrigger className="w-[110px]">
|
||||
<SelectValue placeholder="신용등급" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{CREDIT_RATING_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
// ID 추출
|
||||
idField: 'id',
|
||||
|
||||
{/* 거래등급 필터 */}
|
||||
<Select value={transactionGradeFilter} onValueChange={setTransactionGradeFilter}>
|
||||
<SelectTrigger className="w-[120px]">
|
||||
<SelectValue placeholder="거래등급" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{TRANSACTION_GRADE_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
// API 액션
|
||||
actions: {
|
||||
getList: async () => {
|
||||
return {
|
||||
success: true,
|
||||
data: paginatedData,
|
||||
totalCount: filteredData.length,
|
||||
};
|
||||
},
|
||||
},
|
||||
|
||||
{/* 악성채권 필터 */}
|
||||
<Select value={badDebtFilter} onValueChange={setBadDebtFilter}>
|
||||
<SelectTrigger className="w-[110px]">
|
||||
<SelectValue placeholder="악성채권" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{BAD_DEBT_STATUS_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
// 테이블 컬럼
|
||||
columns: tableColumns,
|
||||
|
||||
{/* 정렬 */}
|
||||
<Select value={sortOption} onValueChange={(value) => setSortOption(value as SortOption)}>
|
||||
<SelectTrigger className="w-[150px]">
|
||||
<SelectValue placeholder="정렬" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{SORT_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
// 클라이언트 사이드 필터링 (이미 외부에서 처리)
|
||||
clientSideFiltering: false,
|
||||
itemsPerPage,
|
||||
|
||||
// 검색
|
||||
searchPlaceholder: '거래처명, 거래처코드, 사업자번호 검색...',
|
||||
onSearchChange: setSearchQuery,
|
||||
|
||||
// 모바일 필터 설정
|
||||
filterConfig: [
|
||||
{
|
||||
key: 'category',
|
||||
label: '구분',
|
||||
type: 'single',
|
||||
options: VENDOR_CATEGORY_OPTIONS.filter(o => o.value !== 'all'),
|
||||
},
|
||||
{
|
||||
key: 'creditRating',
|
||||
label: '신용등급',
|
||||
type: 'single',
|
||||
options: CREDIT_RATING_OPTIONS.filter(o => o.value !== 'all'),
|
||||
},
|
||||
{
|
||||
key: 'transactionGrade',
|
||||
label: '거래등급',
|
||||
type: 'single',
|
||||
options: TRANSACTION_GRADE_OPTIONS.filter(o => o.value !== 'all'),
|
||||
},
|
||||
{
|
||||
key: 'badDebt',
|
||||
label: '악성채권',
|
||||
type: 'single',
|
||||
options: BAD_DEBT_STATUS_OPTIONS.filter(o => o.value !== 'all'),
|
||||
},
|
||||
{
|
||||
key: 'sortBy',
|
||||
label: '정렬',
|
||||
type: 'single',
|
||||
options: SORT_OPTIONS.filter(o => o.value !== 'all'),
|
||||
},
|
||||
],
|
||||
initialFilters: {
|
||||
category: categoryFilter,
|
||||
creditRating: creditRatingFilter,
|
||||
transactionGrade: transactionGradeFilter,
|
||||
badDebt: badDebtFilter,
|
||||
sortBy: sortOption,
|
||||
},
|
||||
filterTitle: '거래처 필터',
|
||||
|
||||
// 통계 카드
|
||||
computeStats: (): StatCard[] => statCards,
|
||||
|
||||
// 테이블 헤더 액션 (5개 필터)
|
||||
tableHeaderActions: (
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
{/* 구분 필터 */}
|
||||
<Select value={categoryFilter} onValueChange={setCategoryFilter}>
|
||||
<SelectTrigger className="w-[120px]">
|
||||
<SelectValue placeholder="구분" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{VENDOR_CATEGORY_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* 신용등급 필터 */}
|
||||
<Select value={creditRatingFilter} onValueChange={setCreditRatingFilter}>
|
||||
<SelectTrigger className="w-[110px]">
|
||||
<SelectValue placeholder="신용등급" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{CREDIT_RATING_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* 거래등급 필터 */}
|
||||
<Select value={transactionGradeFilter} onValueChange={setTransactionGradeFilter}>
|
||||
<SelectTrigger className="w-[120px]">
|
||||
<SelectValue placeholder="거래등급" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{TRANSACTION_GRADE_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* 악성채권 필터 */}
|
||||
<Select value={badDebtFilter} onValueChange={setBadDebtFilter}>
|
||||
<SelectTrigger className="w-[110px]">
|
||||
<SelectValue placeholder="악성채권" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{BAD_DEBT_STATUS_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* 정렬 */}
|
||||
<Select value={sortOption} onValueChange={(value) => setSortOption(value as SortOption)}>
|
||||
<SelectTrigger className="w-[150px]">
|
||||
<SelectValue placeholder="정렬" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{SORT_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
),
|
||||
|
||||
// 렌더링 함수
|
||||
renderTableRow,
|
||||
renderMobileCard,
|
||||
}),
|
||||
[
|
||||
paginatedData,
|
||||
filteredData.length,
|
||||
tableColumns,
|
||||
statCards,
|
||||
categoryFilter,
|
||||
creditRatingFilter,
|
||||
transactionGradeFilter,
|
||||
badDebtFilter,
|
||||
sortOption,
|
||||
itemsPerPage,
|
||||
renderTableRow,
|
||||
renderMobileCard,
|
||||
]
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<IntegratedListTemplateV2
|
||||
title="거래처관리"
|
||||
description="거래처 정보를 등록하고 관리합니다"
|
||||
icon={Building2}
|
||||
stats={statCards}
|
||||
searchValue={searchQuery}
|
||||
onSearchChange={setSearchQuery}
|
||||
searchPlaceholder="거래처명, 거래처코드, 사업자번호 검색..."
|
||||
tableHeaderActions={tableHeaderActions}
|
||||
tableColumns={tableColumns}
|
||||
data={paginatedData}
|
||||
totalCount={filteredData.length}
|
||||
allData={filteredData}
|
||||
selectedItems={selectedItems}
|
||||
onToggleSelection={toggleSelection}
|
||||
onToggleSelectAll={toggleSelectAll}
|
||||
getItemId={(item: Vendor) => item.id}
|
||||
renderTableRow={renderTableRow}
|
||||
renderMobileCard={renderMobileCard}
|
||||
pagination={{
|
||||
<UniversalListPage
|
||||
config={config}
|
||||
initialData={paginatedData}
|
||||
externalPagination={{
|
||||
currentPage,
|
||||
totalPages,
|
||||
totalItems: filteredData.length,
|
||||
itemsPerPage,
|
||||
onPageChange: setCurrentPage,
|
||||
}}
|
||||
externalSelection={{
|
||||
selectedItems,
|
||||
onToggleSelection: toggleSelection,
|
||||
onToggleSelectAll: toggleSelectAll,
|
||||
getItemId: (item: Vendor) => item.id,
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* 삭제 확인 다이얼로그 */}
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
'use client';
|
||||
|
||||
/**
|
||||
* 거래처관리 - UniversalListPage 마이그레이션
|
||||
*
|
||||
* 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
|
||||
* - 클라이언트 사이드 필터링 (검색, 필터, 정렬)
|
||||
* - Stats 카드 (단순 표시, 클릭 없음)
|
||||
* - filterConfig (single 5개: 구분, 신용등급, 거래등급, 악성채권, 정렬)
|
||||
* - 삭제 기능 (deleteConfirmMessage)
|
||||
*/
|
||||
|
||||
import { useState, useMemo, useCallback } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import {
|
||||
@@ -9,40 +19,19 @@ import {
|
||||
Eye,
|
||||
} from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { TableRow, TableCell } from '@/components/ui/table';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { MobileCard } from '@/components/molecules/MobileCard';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import { TableRow, TableCell } from '@/components/ui/table';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import {
|
||||
IntegratedListTemplateV2,
|
||||
type TableColumn,
|
||||
UniversalListPage,
|
||||
type UniversalListConfig,
|
||||
type SelectionHandlers,
|
||||
type RowClickHandlers,
|
||||
type StatCard,
|
||||
type FilterFieldConfig,
|
||||
type FilterValues,
|
||||
} from '@/components/templates/IntegratedListTemplateV2';
|
||||
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
|
||||
} from '@/components/templates/UniversalListPage';
|
||||
import type {
|
||||
Vendor,
|
||||
VendorCategory,
|
||||
CreditRating,
|
||||
TransactionGrade,
|
||||
BadDebtStatus,
|
||||
SortOption,
|
||||
} from './types';
|
||||
import {
|
||||
@@ -62,6 +51,20 @@ import {
|
||||
import { deleteClient } from './actions';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
// ===== 테이블 컬럼 정의 =====
|
||||
const tableColumns = [
|
||||
{ key: 'no', label: '번호', className: 'text-center w-[60px]' },
|
||||
{ key: 'category', label: '구분', className: 'text-center w-[100px]' },
|
||||
{ key: 'vendorName', label: '거래처명' },
|
||||
{ key: 'purchasePaymentDay', label: '매입 결제일', className: 'text-center w-[100px]' },
|
||||
{ key: 'salesPaymentDay', label: '매출 결제일', className: 'text-center w-[100px]' },
|
||||
{ key: 'creditRating', label: '신용등급', className: 'text-center w-[90px]' },
|
||||
{ key: 'transactionGrade', label: '거래등급', className: 'text-center w-[100px]' },
|
||||
{ key: 'outstandingAmount', label: '미수금', className: 'text-right w-[120px]' },
|
||||
{ key: 'badDebtStatus', label: '악성채권', className: 'text-center w-[90px]' },
|
||||
{ key: 'actions', label: '작업', className: 'text-center w-[150px]' },
|
||||
];
|
||||
|
||||
// ===== 컴포넌트 Props =====
|
||||
interface VendorManagementProps {
|
||||
initialData: Vendor[];
|
||||
@@ -71,528 +74,361 @@ interface VendorManagementProps {
|
||||
export function VendorManagement({ initialData, initialTotal }: VendorManagementProps) {
|
||||
const router = useRouter();
|
||||
|
||||
// ===== 상태 관리 =====
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [sortOption, setSortOption] = useState<SortOption>('latest');
|
||||
const [categoryFilter, setCategoryFilter] = useState<string>('all');
|
||||
const [creditRatingFilter, setCreditRatingFilter] = useState<string>('all');
|
||||
const [transactionGradeFilter, setTransactionGradeFilter] = useState<string>('all');
|
||||
const [badDebtFilter, setBadDebtFilter] = useState<string>('all');
|
||||
const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const itemsPerPage = 20;
|
||||
// ===== 외부 상태 (Stats 계산용) =====
|
||||
const [vendorData, setVendorData] = useState<Vendor[]>(initialData);
|
||||
|
||||
// 삭제 다이얼로그
|
||||
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
|
||||
const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
|
||||
// ===== Stats 계산 =====
|
||||
const stats = useMemo(() => {
|
||||
const totalCount = vendorData.length;
|
||||
const salesCount = vendorData.filter(d => d.category === 'sales' || d.category === 'both').length;
|
||||
const purchaseCount = vendorData.filter(d => d.category === 'purchase' || d.category === 'both').length;
|
||||
return { totalCount, salesCount, purchaseCount };
|
||||
}, [vendorData]);
|
||||
|
||||
// 거래처 데이터 (서버에서 전달받은 initialData 사용)
|
||||
const [data, setData] = useState<Vendor[]>(initialData);
|
||||
// ===== 핸들러 =====
|
||||
const handleRowClick = useCallback(
|
||||
(vendor: Vendor) => {
|
||||
router.push(`/ko/accounting/vendors/${vendor.id}`);
|
||||
},
|
||||
[router]
|
||||
);
|
||||
|
||||
// ===== 체크박스 핸들러 =====
|
||||
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 handleEdit = useCallback(
|
||||
(vendor: Vendor) => {
|
||||
router.push(`/ko/accounting/vendors/${vendor.id}?mode=edit`);
|
||||
},
|
||||
[router]
|
||||
);
|
||||
|
||||
// ===== 필터링된 데이터 =====
|
||||
const filteredData = useMemo(() => {
|
||||
let result = data.filter(item =>
|
||||
item.vendorName.includes(searchQuery) ||
|
||||
item.vendorCode.includes(searchQuery) ||
|
||||
item.businessNumber.includes(searchQuery)
|
||||
);
|
||||
// ===== UniversalListPage Config =====
|
||||
const config: UniversalListConfig<Vendor> = useMemo(
|
||||
() => ({
|
||||
// 페이지 기본 정보
|
||||
title: '거래처관리',
|
||||
description: '거래처 정보를 등록하고 관리합니다',
|
||||
icon: Building2,
|
||||
basePath: '/accounting/vendors',
|
||||
|
||||
// 구분 필터
|
||||
if (categoryFilter !== 'all') {
|
||||
result = result.filter(item => item.category === categoryFilter);
|
||||
}
|
||||
// ID 추출
|
||||
idField: 'id',
|
||||
|
||||
// 신용등급 필터
|
||||
if (creditRatingFilter !== 'all') {
|
||||
result = result.filter(item => item.creditRating === creditRatingFilter);
|
||||
}
|
||||
// API 액션
|
||||
actions: {
|
||||
getList: async () => {
|
||||
// 이미 initialData로 로드됨, 클라이언트 사이드 필터링
|
||||
return {
|
||||
success: true,
|
||||
data: initialData,
|
||||
totalCount: initialData.length,
|
||||
};
|
||||
},
|
||||
deleteItem: async (id: string) => {
|
||||
const result = await deleteClient(id);
|
||||
if (result.success) {
|
||||
toast.success('거래처가 삭제되었습니다.');
|
||||
}
|
||||
return { success: result.success, error: result.error };
|
||||
},
|
||||
},
|
||||
|
||||
// 거래등급 필터
|
||||
if (transactionGradeFilter !== 'all') {
|
||||
result = result.filter(item => item.transactionGrade === transactionGradeFilter);
|
||||
}
|
||||
// 테이블 컬럼
|
||||
columns: tableColumns,
|
||||
|
||||
// 악성채권 필터
|
||||
if (badDebtFilter !== 'all') {
|
||||
result = result.filter(item => item.badDebtStatus === badDebtFilter);
|
||||
}
|
||||
// 클라이언트 사이드 필터링
|
||||
clientSideFiltering: true,
|
||||
itemsPerPage: 20,
|
||||
|
||||
// 정렬
|
||||
switch (sortOption) {
|
||||
case 'latest':
|
||||
result.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
|
||||
break;
|
||||
case 'oldest':
|
||||
result.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
|
||||
break;
|
||||
case 'nameAsc':
|
||||
result.sort((a, b) => a.vendorName.localeCompare(b.vendorName));
|
||||
break;
|
||||
case 'nameDesc':
|
||||
result.sort((a, b) => b.vendorName.localeCompare(a.vendorName));
|
||||
break;
|
||||
case 'outstandingHigh':
|
||||
result.sort((a, b) => b.outstandingAmount - a.outstandingAmount);
|
||||
break;
|
||||
case 'outstandingLow':
|
||||
result.sort((a, b) => a.outstandingAmount - b.outstandingAmount);
|
||||
break;
|
||||
}
|
||||
// 데이터 변경 콜백 (Stats 계산용)
|
||||
onDataChange: (data) => setVendorData(data),
|
||||
|
||||
return result;
|
||||
}, [data, searchQuery, categoryFilter, creditRatingFilter, transactionGradeFilter, badDebtFilter, sortOption]);
|
||||
// 검색 필터
|
||||
searchPlaceholder: '거래처명, 거래처코드, 사업자번호 검색...',
|
||||
searchFilter: (item, searchValue) => {
|
||||
const search = searchValue.toLowerCase();
|
||||
return (
|
||||
item.vendorName.toLowerCase().includes(search) ||
|
||||
item.vendorCode.toLowerCase().includes(search) ||
|
||||
item.businessNumber.toLowerCase().includes(search)
|
||||
);
|
||||
},
|
||||
|
||||
const paginatedData = useMemo(() => {
|
||||
const startIndex = (currentPage - 1) * itemsPerPage;
|
||||
return filteredData.slice(startIndex, startIndex + itemsPerPage);
|
||||
}, [filteredData, currentPage, itemsPerPage]);
|
||||
// 필터 설정 (5개 single 필터)
|
||||
filterConfig: [
|
||||
{
|
||||
key: 'category',
|
||||
label: '구분',
|
||||
type: 'single',
|
||||
options: VENDOR_CATEGORY_OPTIONS.filter(o => o.value !== 'all').map(o => ({
|
||||
value: o.value,
|
||||
label: o.label,
|
||||
})),
|
||||
},
|
||||
{
|
||||
key: 'creditRating',
|
||||
label: '신용등급',
|
||||
type: 'single',
|
||||
options: CREDIT_RATING_OPTIONS.filter(o => o.value !== 'all').map(o => ({
|
||||
value: o.value,
|
||||
label: o.label,
|
||||
})),
|
||||
},
|
||||
{
|
||||
key: 'transactionGrade',
|
||||
label: '거래등급',
|
||||
type: 'single',
|
||||
options: TRANSACTION_GRADE_OPTIONS.filter(o => o.value !== 'all').map(o => ({
|
||||
value: o.value,
|
||||
label: o.label,
|
||||
})),
|
||||
},
|
||||
{
|
||||
key: 'badDebt',
|
||||
label: '악성채권',
|
||||
type: 'single',
|
||||
options: BAD_DEBT_STATUS_OPTIONS.filter(o => o.value !== 'all').map(o => ({
|
||||
value: o.value,
|
||||
label: o.label,
|
||||
})),
|
||||
},
|
||||
{
|
||||
key: 'sortBy',
|
||||
label: '정렬',
|
||||
type: 'single',
|
||||
options: SORT_OPTIONS.map(o => ({
|
||||
value: o.value,
|
||||
label: o.label,
|
||||
})),
|
||||
},
|
||||
],
|
||||
initialFilters: {
|
||||
category: 'all',
|
||||
creditRating: 'all',
|
||||
transactionGrade: 'all',
|
||||
badDebt: 'all',
|
||||
sortBy: 'latest',
|
||||
},
|
||||
filterTitle: '거래처 필터',
|
||||
|
||||
const totalPages = Math.ceil(filteredData.length / itemsPerPage);
|
||||
// 커스텀 필터 함수
|
||||
customFilterFn: (items, filterValues) => {
|
||||
return items.filter((item) => {
|
||||
// 구분 필터
|
||||
const categoryFilter = filterValues.category as string;
|
||||
if (categoryFilter && categoryFilter !== 'all' && item.category !== categoryFilter) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// ===== 전체 선택 핸들러 =====
|
||||
const toggleSelectAll = useCallback(() => {
|
||||
if (selectedItems.size === filteredData.length && filteredData.length > 0) {
|
||||
setSelectedItems(new Set());
|
||||
} else {
|
||||
setSelectedItems(new Set(filteredData.map(item => item.id)));
|
||||
}
|
||||
}, [selectedItems.size, filteredData]);
|
||||
// 신용등급 필터
|
||||
const creditRatingFilter = filterValues.creditRating as string;
|
||||
if (creditRatingFilter && creditRatingFilter !== 'all' && item.creditRating !== creditRatingFilter) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// ===== 액션 핸들러 =====
|
||||
const handleRowClick = useCallback((item: Vendor) => {
|
||||
router.push(`/ko/accounting/vendors/${item.id}`);
|
||||
}, [router]);
|
||||
// 거래등급 필터
|
||||
const transactionGradeFilter = filterValues.transactionGrade as string;
|
||||
if (transactionGradeFilter && transactionGradeFilter !== 'all' && item.transactionGrade !== transactionGradeFilter) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const handleEdit = useCallback((item: Vendor) => {
|
||||
router.push(`/ko/accounting/vendors/${item.id}?mode=edit`);
|
||||
}, [router]);
|
||||
// 악성채권 필터
|
||||
const badDebtFilter = filterValues.badDebt as string;
|
||||
if (badDebtFilter && badDebtFilter !== 'all' && item.badDebtStatus !== badDebtFilter) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const handleDeleteClick = useCallback((id: string) => {
|
||||
setDeleteTargetId(id);
|
||||
setShowDeleteDialog(true);
|
||||
}, []);
|
||||
|
||||
const handleConfirmDelete = useCallback(async () => {
|
||||
if (deleteTargetId) {
|
||||
const result = await deleteClient(deleteTargetId);
|
||||
if (result.success) {
|
||||
toast.success('거래처가 삭제되었습니다.');
|
||||
setData(prev => prev.filter(item => item.id !== deleteTargetId));
|
||||
setSelectedItems(prev => {
|
||||
const newSet = new Set(prev);
|
||||
newSet.delete(deleteTargetId);
|
||||
return newSet;
|
||||
return true;
|
||||
});
|
||||
} else {
|
||||
toast.error(result.error || '삭제에 실패했습니다.');
|
||||
}
|
||||
}
|
||||
setShowDeleteDialog(false);
|
||||
setDeleteTargetId(null);
|
||||
}, [deleteTargetId]);
|
||||
},
|
||||
|
||||
// ===== 통계 카드 =====
|
||||
const statCards: StatCard[] = useMemo(() => {
|
||||
const totalCount = data.length;
|
||||
const salesCount = data.filter(d => d.category === 'sales' || d.category === 'both').length;
|
||||
const purchaseCount = data.filter(d => d.category === 'purchase' || d.category === 'both').length;
|
||||
// 커스텀 정렬 함수
|
||||
customSortFn: (items, filterValues) => {
|
||||
const sorted = [...items];
|
||||
const sortBy = (filterValues.sortBy as SortOption) || 'latest';
|
||||
|
||||
return [
|
||||
{ label: '전체 거래처', value: `${totalCount}개`, icon: Building2, iconColor: 'text-blue-500' },
|
||||
{ label: '매출 거래처', value: `${salesCount}개`, icon: Building2, iconColor: 'text-green-500' },
|
||||
{ label: '매입 거래처', value: `${purchaseCount}개`, icon: Building2, iconColor: 'text-orange-500' },
|
||||
];
|
||||
}, [data]);
|
||||
|
||||
// ===== 테이블 컬럼 =====
|
||||
const tableColumns: TableColumn[] = useMemo(() => [
|
||||
{ key: 'no', label: '번호', className: 'text-center w-[60px]' },
|
||||
{ key: 'category', label: '구분', className: 'text-center w-[100px]' },
|
||||
{ key: 'vendorName', label: '거래처명' },
|
||||
{ key: 'purchasePaymentDay', label: '매입 결제일', className: 'text-center w-[100px]' },
|
||||
{ key: 'salesPaymentDay', label: '매출 결제일', className: 'text-center w-[100px]' },
|
||||
{ key: 'creditRating', label: '신용등급', className: 'text-center w-[90px]' },
|
||||
{ key: 'transactionGrade', label: '거래등급', className: 'text-center w-[100px]' },
|
||||
{ key: 'outstandingAmount', label: '미수금', className: 'text-right w-[120px]' },
|
||||
{ key: 'badDebtStatus', label: '악성채권', className: 'text-center w-[90px]' },
|
||||
{ key: 'actions', label: '작업', className: 'text-center w-[150px]' },
|
||||
], []);
|
||||
|
||||
// ===== 테이블 행 렌더링 =====
|
||||
const renderTableRow = useCallback((item: Vendor, 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-center text-sm text-gray-500">{globalIndex}</TableCell>
|
||||
{/* 구분 */}
|
||||
<TableCell className="text-center">
|
||||
<Badge className={VENDOR_CATEGORY_COLORS[item.category]}>
|
||||
{VENDOR_CATEGORY_LABELS[item.category]}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
{/* 거래처명 */}
|
||||
<TableCell className="font-medium">{item.vendorName}</TableCell>
|
||||
{/* 매입 결제일 */}
|
||||
<TableCell className="text-center">{item.purchasePaymentDay}일</TableCell>
|
||||
{/* 매출 결제일 */}
|
||||
<TableCell className="text-center">{item.salesPaymentDay}일</TableCell>
|
||||
{/* 신용등급 */}
|
||||
<TableCell className="text-center">
|
||||
<Badge className={CREDIT_RATING_COLORS[item.creditRating]}>
|
||||
{item.creditRating}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
{/* 거래등급 */}
|
||||
<TableCell className="text-center">
|
||||
<Badge className={TRANSACTION_GRADE_COLORS[item.transactionGrade]}>
|
||||
{TRANSACTION_GRADE_LABELS[item.transactionGrade]}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
{/* 미수금 */}
|
||||
<TableCell className="text-right">
|
||||
{item.outstandingAmount > 0 ? (
|
||||
<span className="text-red-600 font-medium">{item.outstandingAmount.toLocaleString()}원</span>
|
||||
) : (
|
||||
<span className="text-gray-500">-</span>
|
||||
)}
|
||||
</TableCell>
|
||||
{/* 악성채권 */}
|
||||
<TableCell className="text-center">
|
||||
{item.badDebtStatus === 'none' ? (
|
||||
<span className="text-gray-400">-</span>
|
||||
) : (
|
||||
<Badge className={BAD_DEBT_STATUS_COLORS[item.badDebtStatus]}>
|
||||
{BAD_DEBT_STATUS_LABELS[item.badDebtStatus]}
|
||||
</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
{/* 작업 */}
|
||||
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
|
||||
{isSelected && (
|
||||
<div className="flex items-center justify-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={() => handleEdit(item)}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-red-500 hover:text-red-600 hover:bg-red-50"
|
||||
onClick={() => handleDeleteClick(item.id)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
}, [selectedItems, toggleSelection, handleRowClick, handleEdit, handleDeleteClick]);
|
||||
|
||||
// ===== 모바일 카드 렌더링 =====
|
||||
const renderMobileCard = useCallback((
|
||||
item: Vendor,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
isSelected: boolean,
|
||||
onToggle: () => void
|
||||
) => {
|
||||
return (
|
||||
<ListMobileCard
|
||||
id={item.id}
|
||||
title={item.vendorName}
|
||||
headerBadges={
|
||||
<>
|
||||
<Badge className={VENDOR_CATEGORY_COLORS[item.category]}>
|
||||
{VENDOR_CATEGORY_LABELS[item.category]}
|
||||
</Badge>
|
||||
<Badge className={CREDIT_RATING_COLORS[item.creditRating]}>
|
||||
{item.creditRating}
|
||||
</Badge>
|
||||
</>
|
||||
switch (sortBy) {
|
||||
case 'oldest':
|
||||
sorted.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
|
||||
break;
|
||||
case 'nameAsc':
|
||||
sorted.sort((a, b) => a.vendorName.localeCompare(b.vendorName));
|
||||
break;
|
||||
case 'nameDesc':
|
||||
sorted.sort((a, b) => b.vendorName.localeCompare(a.vendorName));
|
||||
break;
|
||||
case 'outstandingHigh':
|
||||
sorted.sort((a, b) => b.outstandingAmount - a.outstandingAmount);
|
||||
break;
|
||||
case 'outstandingLow':
|
||||
sorted.sort((a, b) => a.outstandingAmount - b.outstandingAmount);
|
||||
break;
|
||||
default: // latest
|
||||
sorted.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
|
||||
break;
|
||||
}
|
||||
isSelected={isSelected}
|
||||
onToggleSelection={onToggle}
|
||||
infoGrid={
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<InfoField label="거래처코드" value={item.vendorCode} />
|
||||
<InfoField label="거래등급" value={TRANSACTION_GRADE_LABELS[item.transactionGrade]} />
|
||||
<InfoField
|
||||
label="미수금"
|
||||
value={item.outstandingAmount > 0 ? `${item.outstandingAmount.toLocaleString()}원` : '-'}
|
||||
className={item.outstandingAmount > 0 ? 'text-red-600' : ''}
|
||||
/>
|
||||
<InfoField label="결제일" value={`매입 ${item.purchasePaymentDay}일 / 매출 ${item.salesPaymentDay}일`} />
|
||||
</div>
|
||||
}
|
||||
actions={
|
||||
isSelected ? (
|
||||
<div className="flex gap-2 w-full">
|
||||
<Button variant="outline" className="flex-1" onClick={() => handleRowClick(item)}>
|
||||
<Eye className="w-4 h-4 mr-2" /> 상세
|
||||
</Button>
|
||||
<Button variant="outline" className="flex-1" onClick={() => handleEdit(item)}>
|
||||
<Pencil className="w-4 h-4 mr-2" /> 수정
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="flex-1 text-red-500 border-red-200 hover:bg-red-50 hover:text-red-600"
|
||||
onClick={() => handleDeleteClick(item.id)}
|
||||
>
|
||||
<Trash2 className="w-4 h-4 mr-2" /> 삭제
|
||||
</Button>
|
||||
</div>
|
||||
) : undefined
|
||||
}
|
||||
onClick={() => handleRowClick(item)}
|
||||
/>
|
||||
);
|
||||
}, [handleRowClick, handleEdit, handleDeleteClick]);
|
||||
return sorted;
|
||||
},
|
||||
|
||||
// ===== filterConfig 방식 모바일 필터 =====
|
||||
const filterConfig: FilterFieldConfig[] = useMemo(() => [
|
||||
{
|
||||
key: 'category',
|
||||
label: '구분',
|
||||
type: 'single',
|
||||
options: VENDOR_CATEGORY_OPTIONS.filter(o => o.value !== 'all').map(o => ({
|
||||
value: o.value,
|
||||
label: o.label,
|
||||
})),
|
||||
allOptionLabel: '전체',
|
||||
},
|
||||
{
|
||||
key: 'creditRating',
|
||||
label: '신용등급',
|
||||
type: 'single',
|
||||
options: CREDIT_RATING_OPTIONS.filter(o => o.value !== 'all').map(o => ({
|
||||
value: o.value,
|
||||
label: o.label,
|
||||
})),
|
||||
allOptionLabel: '전체',
|
||||
},
|
||||
{
|
||||
key: 'transactionGrade',
|
||||
label: '거래등급',
|
||||
type: 'single',
|
||||
options: TRANSACTION_GRADE_OPTIONS.filter(o => o.value !== 'all').map(o => ({
|
||||
value: o.value,
|
||||
label: o.label,
|
||||
})),
|
||||
allOptionLabel: '전체',
|
||||
},
|
||||
{
|
||||
key: 'badDebt',
|
||||
label: '악성채권',
|
||||
type: 'single',
|
||||
options: BAD_DEBT_STATUS_OPTIONS.filter(o => o.value !== 'all').map(o => ({
|
||||
value: o.value,
|
||||
label: o.label,
|
||||
})),
|
||||
allOptionLabel: '전체',
|
||||
},
|
||||
{
|
||||
key: 'sort',
|
||||
label: '정렬',
|
||||
type: 'single',
|
||||
options: SORT_OPTIONS.map(o => ({
|
||||
value: o.value,
|
||||
label: o.label,
|
||||
})),
|
||||
},
|
||||
], []);
|
||||
// Stats 카드
|
||||
computeStats: (): StatCard[] => [
|
||||
{
|
||||
label: '전체 거래처',
|
||||
value: `${stats.totalCount}개`,
|
||||
icon: Building2,
|
||||
iconColor: 'text-blue-500',
|
||||
},
|
||||
{
|
||||
label: '매출 거래처',
|
||||
value: `${stats.salesCount}개`,
|
||||
icon: Building2,
|
||||
iconColor: 'text-green-500',
|
||||
},
|
||||
{
|
||||
label: '매입 거래처',
|
||||
value: `${stats.purchaseCount}개`,
|
||||
icon: Building2,
|
||||
iconColor: 'text-orange-500',
|
||||
},
|
||||
],
|
||||
|
||||
const filterValues: FilterValues = useMemo(() => ({
|
||||
category: categoryFilter,
|
||||
creditRating: creditRatingFilter,
|
||||
transactionGrade: transactionGradeFilter,
|
||||
badDebt: badDebtFilter,
|
||||
sort: sortOption,
|
||||
}), [categoryFilter, creditRatingFilter, transactionGradeFilter, badDebtFilter, sortOption]);
|
||||
// 삭제 확인 메시지
|
||||
deleteConfirmMessage: {
|
||||
title: '거래처 삭제',
|
||||
description: '이 거래처를 삭제하시겠습니까? 이 작업은 취소할 수 없습니다.',
|
||||
},
|
||||
|
||||
const handleFilterChange = useCallback((key: string, value: string | string[]) => {
|
||||
switch (key) {
|
||||
case 'category':
|
||||
setCategoryFilter(value as string);
|
||||
break;
|
||||
case 'creditRating':
|
||||
setCreditRatingFilter(value as string);
|
||||
break;
|
||||
case 'transactionGrade':
|
||||
setTransactionGradeFilter(value as string);
|
||||
break;
|
||||
case 'badDebt':
|
||||
setBadDebtFilter(value as string);
|
||||
break;
|
||||
case 'sort':
|
||||
setSortOption(value as SortOption);
|
||||
break;
|
||||
}
|
||||
setCurrentPage(1);
|
||||
}, []);
|
||||
// 테이블 행 렌더링
|
||||
renderTableRow: (
|
||||
vendor: Vendor,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
handlers: SelectionHandlers & RowClickHandlers<Vendor>
|
||||
) => (
|
||||
<TableRow
|
||||
key={vendor.id}
|
||||
className="hover:bg-muted/50 cursor-pointer"
|
||||
onClick={() => handleRowClick(vendor)}
|
||||
>
|
||||
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
|
||||
<Checkbox checked={handlers.isSelected} onCheckedChange={handlers.onToggle} />
|
||||
</TableCell>
|
||||
{/* 번호 */}
|
||||
<TableCell className="text-center text-sm text-gray-500">{globalIndex}</TableCell>
|
||||
{/* 구분 */}
|
||||
<TableCell className="text-center">
|
||||
<Badge className={VENDOR_CATEGORY_COLORS[vendor.category]}>
|
||||
{VENDOR_CATEGORY_LABELS[vendor.category]}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
{/* 거래처명 */}
|
||||
<TableCell className="font-medium">{vendor.vendorName}</TableCell>
|
||||
{/* 매입 결제일 */}
|
||||
<TableCell className="text-center">{vendor.purchasePaymentDay}일</TableCell>
|
||||
{/* 매출 결제일 */}
|
||||
<TableCell className="text-center">{vendor.salesPaymentDay}일</TableCell>
|
||||
{/* 신용등급 */}
|
||||
<TableCell className="text-center">
|
||||
<Badge className={CREDIT_RATING_COLORS[vendor.creditRating]}>
|
||||
{vendor.creditRating}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
{/* 거래등급 */}
|
||||
<TableCell className="text-center">
|
||||
<Badge className={TRANSACTION_GRADE_COLORS[vendor.transactionGrade]}>
|
||||
{TRANSACTION_GRADE_LABELS[vendor.transactionGrade]}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
{/* 미수금 */}
|
||||
<TableCell className="text-right">
|
||||
{vendor.outstandingAmount > 0 ? (
|
||||
<span className="text-red-600 font-medium">{vendor.outstandingAmount.toLocaleString()}원</span>
|
||||
) : (
|
||||
<span className="text-gray-500">-</span>
|
||||
)}
|
||||
</TableCell>
|
||||
{/* 악성채권 */}
|
||||
<TableCell className="text-center">
|
||||
{vendor.badDebtStatus === 'none' ? (
|
||||
<span className="text-gray-400">-</span>
|
||||
) : (
|
||||
<Badge className={BAD_DEBT_STATUS_COLORS[vendor.badDebtStatus]}>
|
||||
{BAD_DEBT_STATUS_LABELS[vendor.badDebtStatus]}
|
||||
</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
{/* 작업 */}
|
||||
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
|
||||
{handlers.isSelected && (
|
||||
<div className="flex items-center justify-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={() => handleEdit(vendor)}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-red-500 hover:text-red-600 hover:bg-red-50"
|
||||
onClick={() => handlers.onDelete?.(vendor)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
),
|
||||
|
||||
const handleFilterReset = useCallback(() => {
|
||||
setCategoryFilter('all');
|
||||
setCreditRatingFilter('all');
|
||||
setTransactionGradeFilter('all');
|
||||
setBadDebtFilter('all');
|
||||
setSortOption('latest');
|
||||
setCurrentPage(1);
|
||||
}, []);
|
||||
|
||||
// ===== 테이블 헤더 필터 액션 =====
|
||||
const tableHeaderActions = (
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
{/* 구분 필터 */}
|
||||
<Select value={categoryFilter} onValueChange={(value) => handleFilterChange('category', value)}>
|
||||
<SelectTrigger className="w-[100px] h-8">
|
||||
<SelectValue placeholder="구분" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{VENDOR_CATEGORY_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* 신용등급 필터 */}
|
||||
<Select value={creditRatingFilter} onValueChange={(value) => handleFilterChange('creditRating', value)}>
|
||||
<SelectTrigger className="w-[100px] h-8">
|
||||
<SelectValue placeholder="신용등급" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{CREDIT_RATING_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* 거래등급 필터 */}
|
||||
<Select value={transactionGradeFilter} onValueChange={(value) => handleFilterChange('transactionGrade', value)}>
|
||||
<SelectTrigger className="w-[100px] h-8">
|
||||
<SelectValue placeholder="거래등급" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{TRANSACTION_GRADE_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* 악성채권 필터 */}
|
||||
<Select value={badDebtFilter} onValueChange={(value) => handleFilterChange('badDebt', value)}>
|
||||
<SelectTrigger className="w-[100px] h-8">
|
||||
<SelectValue placeholder="악성채권" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{BAD_DEBT_STATUS_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* 정렬 필터 */}
|
||||
<Select value={sortOption} onValueChange={(value) => handleFilterChange('sort', value)}>
|
||||
<SelectTrigger className="w-[140px] h-8">
|
||||
<SelectValue placeholder="정렬" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{SORT_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* 필터 초기화 버튼 */}
|
||||
<Button variant="outline" size="sm" onClick={handleFilterReset} className="h-8">
|
||||
초기화
|
||||
</Button>
|
||||
</div>
|
||||
// 모바일 카드 렌더링
|
||||
renderMobileCard: (
|
||||
vendor: Vendor,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
handlers: SelectionHandlers & RowClickHandlers<Vendor>
|
||||
) => (
|
||||
<MobileCard
|
||||
key={vendor.id}
|
||||
title={vendor.vendorName}
|
||||
subtitle={vendor.vendorCode}
|
||||
badge={VENDOR_CATEGORY_LABELS[vendor.category]}
|
||||
badgeVariant="secondary"
|
||||
isSelected={handlers.isSelected}
|
||||
onToggle={handlers.onToggle}
|
||||
onClick={() => handleRowClick(vendor)}
|
||||
details={[
|
||||
{ label: '거래등급', value: TRANSACTION_GRADE_LABELS[vendor.transactionGrade] },
|
||||
{
|
||||
label: '미수금',
|
||||
value: vendor.outstandingAmount > 0 ? `${vendor.outstandingAmount.toLocaleString()}원` : '-',
|
||||
},
|
||||
{ label: '결제일', value: `매입 ${vendor.purchasePaymentDay}일 / 매출 ${vendor.salesPaymentDay}일` },
|
||||
]}
|
||||
actions={
|
||||
handlers.isSelected ? (
|
||||
<div className="flex gap-2 w-full">
|
||||
<Button variant="outline" className="flex-1" onClick={() => handleRowClick(vendor)}>
|
||||
<Eye className="w-4 h-4 mr-2" /> 상세
|
||||
</Button>
|
||||
<Button variant="outline" className="flex-1" onClick={() => handleEdit(vendor)}>
|
||||
<Pencil className="w-4 h-4 mr-2" /> 수정
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="flex-1 text-red-500 border-red-200 hover:bg-red-50 hover:text-red-600"
|
||||
onClick={() => handlers.onDelete?.(vendor)}
|
||||
>
|
||||
<Trash2 className="w-4 h-4 mr-2" /> 삭제
|
||||
</Button>
|
||||
</div>
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
),
|
||||
}),
|
||||
[initialData, stats, handleRowClick, handleEdit]
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<IntegratedListTemplateV2
|
||||
title="거래처관리"
|
||||
description="거래처 정보를 등록하고 관리합니다"
|
||||
icon={Building2}
|
||||
stats={statCards}
|
||||
searchValue={searchQuery}
|
||||
onSearchChange={setSearchQuery}
|
||||
searchPlaceholder="거래처명, 거래처코드, 사업자번호 검색..."
|
||||
tableHeaderActions={tableHeaderActions}
|
||||
tableColumns={tableColumns}
|
||||
data={paginatedData}
|
||||
totalCount={filteredData.length}
|
||||
allData={filteredData}
|
||||
selectedItems={selectedItems}
|
||||
onToggleSelection={toggleSelection}
|
||||
onToggleSelectAll={toggleSelectAll}
|
||||
getItemId={(item: Vendor) => item.id}
|
||||
renderTableRow={renderTableRow}
|
||||
renderMobileCard={renderMobileCard}
|
||||
pagination={{
|
||||
currentPage,
|
||||
totalPages,
|
||||
totalItems: filteredData.length,
|
||||
itemsPerPage,
|
||||
onPageChange: setCurrentPage,
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* 삭제 확인 다이얼로그 */}
|
||||
<AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>거래처 삭제</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
이 거래처를 삭제하시겠습니까? 이 작업은 취소할 수 없습니다.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>취소</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleConfirmDelete}
|
||||
className="bg-red-600 hover:bg-red-700"
|
||||
>
|
||||
삭제
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
return <UniversalListPage config={config} initialData={initialData} />;
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user