Files
sam-react-prod/src/components/accounting/BillManagement/index.tsx
byeongcheolryu a938da9e22 feat(WEB): 회계/HR/주문관리 모듈 개선 및 알림설정 리팩토링
- 회계: 거래처, 매입/매출, 입출금 상세 페이지 개선
- HR: 직원 관리 및 출퇴근 설정 기능 수정
- 주문관리: 상세폼 구조 분리 (cards, dialogs, hooks, tables)
- 알림설정: 컴포넌트 구조 단순화 및 리팩토링
- 캘린더: 헤더 및 일정 타입 개선
- 출고관리: 액션 및 타입 정의 추가

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 09:58:10 +09:00

553 lines
19 KiB
TypeScript

'use client';
import { useState, useMemo, useCallback, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { toast } from 'sonner';
import { getBills, deleteBill, updateBillStatus } from './actions';
import {
FileText,
Plus,
Pencil,
Trash2,
Save,
} from 'lucide-react';
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,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
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';
import type {
BillRecord,
BillType,
BillStatus,
SortOption,
} from './types';
import {
BILL_TYPE_LABELS,
BILL_TYPE_FILTER_OPTIONS,
BILL_STATUS_COLORS,
BILL_STATUS_FILTER_OPTIONS,
getBillStatusLabel,
} from './types';
interface BillManagementProps {
initialVendorId?: string;
initialBillType?: string;
}
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;
// 삭제 다이얼로그
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 [pagination, setPagination] = useState({
currentPage: 1,
lastPage: 1,
perPage: 20,
total: 0,
});
// ===== API에서 데이터 로드 =====
const loadBills = useCallback(async () => {
setIsLoading(true);
try {
const result = await getBills({
search: searchQuery || undefined,
billType: billTypeFilter !== 'all' ? billTypeFilter : undefined,
status: statusFilter !== 'all' ? statusFilter : undefined,
clientId: vendorFilter !== 'all' ? vendorFilter : undefined,
issueStartDate: startDate,
issueEndDate: endDate,
page: currentPage,
perPage: itemsPerPage,
});
if (result.success) {
setData(result.data);
setPagination(result.pagination);
} else {
toast.error(result.error || '어음 목록을 불러오는데 실패했습니다.');
}
} catch {
toast.error('서버 오류가 발생했습니다.');
} finally {
setIsLoading(false);
}
}, [searchQuery, billTypeFilter, statusFilter, vendorFilter, startDate, endDate, currentPage, itemsPerPage]);
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];
switch (sortOption) {
case 'latest':
result.sort((a, b) => new Date(b.issueDate).getTime() - new Date(a.issueDate).getTime());
break;
case 'oldest':
result.sort((a, b) => new Date(a.issueDate).getTime() - new Date(b.issueDate).getTime());
break;
case 'amountHigh':
result.sort((a, b) => b.amount - a.amount);
break;
case 'amountLow':
result.sort((a, b) => a.amount - b.amount);
break;
case 'maturityDate':
result.sort((a, b) => new Date(a.maturityDate).getTime() - new Date(b.maturityDate).getTime());
break;
}
return result;
}, [data, 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))];
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-[120px]">
<SelectValue placeholder="거래처명" />
</SelectTrigger>
<SelectContent>
{vendorOptions.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
{/* 구분 필터 (수취/발행) */}
<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>
{/* 보관중 상태 필터 */}
<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 handleSave = useCallback(async () => {
if (selectedItems.size === 0) {
toast.warning('선택된 항목이 없습니다.');
return;
}
if (statusFilter === 'all') {
toast.warning('변경할 상태를 선택해주세요.');
return;
}
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);
if (result.success) {
successCount++;
} else {
failCount++;
}
}
if (successCount > 0) {
toast.success(`${successCount}건의 상태가 변경되었습니다.`);
await loadBills();
setSelectedItems(new Set());
}
if (failCount > 0) {
toast.error(`${failCount}건의 상태 변경에 실패했습니다.`);
}
} catch {
toast.error('서버 오류가 발생했습니다.');
} finally {
setIsSaving(false);
}
}, [selectedItems, 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>
{/* 저장 버튼 */}
<Button onClick={handleSave} className="bg-blue-500 hover:bg-blue-600" disabled={isSaving}>
<Save className="h-4 w-4 mr-2" />
{isSaving ? '저장중...' : '저장'}
</Button>
{/* 수취/발행 라디오 버튼 */}
<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>
);
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>
</>
);
}