Files
sam-react-prod/src/components/accounting/SalesManagement/index.tsx
김보곤 e4b25e2648 fix(WEB): 매출관리 페이지 렌더링 크래시 수정 (BUG-SALES-20260213-001)
- SalesManagement: vendorOptions에 빈 문자열 필터링 추가 (.filter(Boolean))
  - 원인: API 데이터에 vendorName: "" 레코드 존재 → Radix UI Select.Item value="" 에러
- IntegratedListTemplateV2: SelectItem value="" 방어 코드 추가
  - 모든 페이지에서 빈 value SelectItem 크래시 방지

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 21:24:49 +09:00

551 lines
20 KiB
TypeScript

'use client';
/**
* 매출관리 - UniversalListPage 마이그레이션
*
* 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
* - 클라이언트 사이드 필터링 (검색, 필터, 정렬)
* - Stats 카드 (단순 표시, 클릭 없음)
* - beforeTableContent (계정과목명 Select + 저장 버튼)
* - filterConfig (4개 필터: 거래처, 매출유형, 발행여부, 정렬) - PC 인라인, 모바일 바텀시트
* - tableFooter (합계 행)
* - Switch 토글 (세금계산서/거래명세서 발행)
* - 커스텀 Dialog (계정과목명 저장) - UniversalListPage 외부 유지
* - deleteConfirmMessage로 삭제 다이얼로그 처리
*/
import { useState, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { toast } from 'sonner';
import {
Receipt,
Save,
Search,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge';
import { Switch } from '@/components/ui/switch';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { TableRow, TableCell } from '@/components/ui/table';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import {
UniversalListPage,
type UniversalListConfig,
type SelectionHandlers,
type RowClickHandlers,
type StatCard,
type FilterFieldConfig,
} from '@/components/templates/UniversalListPage';
import { MobileCard } from '@/components/organisms/MobileCard';
import type { SalesRecord } from './types';
import {
SORT_OPTIONS,
SALES_STATUS_LABELS,
SALES_STATUS_COLORS,
SALES_TYPE_LABELS,
SALES_TYPE_FILTER_OPTIONS,
ISSUANCE_FILTER_OPTIONS,
ACCOUNT_SUBJECT_SELECTOR_OPTIONS,
} from './types';
import { deleteSale, toggleSaleIssuance } from './actions';
// ===== 테이블 컬럼 정의 =====
const tableColumns = [
{ key: 'no', label: '번호', className: 'text-center w-[60px]' },
{ key: 'salesNo', label: '매출번호' },
{ key: 'salesDate', label: '매출일' },
{ key: 'vendorName', label: '거래처' },
{ key: 'supplyAmount', label: '공급가액', className: 'text-right' },
{ key: 'vat', label: '부가세', className: 'text-right' },
{ key: 'totalAmount', label: '합계금액', className: 'text-right' },
{ key: 'salesType', label: '매출유형', className: 'text-center' },
{ key: 'taxInvoice', label: '세금계산서 발행완료', className: 'text-center' },
{ key: 'transactionStatement', label: '거래명세서 발행완료', className: 'text-center' },
];
// ===== Props 타입 =====
interface SalesManagementProps {
initialData: SalesRecord[];
initialPagination: {
currentPage: number;
lastPage: number;
perPage: number;
total: number;
};
}
export function SalesManagement({ initialData, initialPagination }: SalesManagementProps) {
const router = useRouter();
// ===== 외부 상태 (UniversalListPage 외부에서 관리) =====
const [startDate, setStartDate] = useState('2025-01-01');
const [endDate, setEndDate] = useState('2025-12-31');
const [salesData, setSalesData] = useState<SalesRecord[]>(initialData);
const [searchQuery, setSearchQuery] = useState('');
// 통합 필터 상태 (filterConfig 사용)
const [filterValues, setFilterValues] = useState<Record<string, string | string[]>>({
vendor: 'all',
salesType: 'all',
issuance: 'all',
sort: 'latest',
});
// 계정과목명 저장 다이얼로그
const [selectedAccountSubject, setSelectedAccountSubject] = useState<string>('unset');
const [showSaveDialog, setShowSaveDialog] = useState(false);
const [selectedItemsForSave, setSelectedItemsForSave] = useState<Set<string>>(new Set());
// ===== 통계 계산 =====
const stats = useMemo(() => {
const totalSalesAmount = salesData.reduce((sum, d) => sum + d.totalAmount, 0);
const currentMonth = new Date().getMonth();
const currentYear = new Date().getFullYear();
const monthlyAmount = salesData
.filter(d => {
const date = new Date(d.salesDate);
return date.getMonth() === currentMonth && date.getFullYear() === currentYear;
})
.reduce((sum, d) => sum + d.totalAmount, 0);
const taxInvoicePendingCount = salesData.filter(d => !d.taxInvoiceIssued).length;
const transactionStatementPendingCount = salesData.filter(d => !d.transactionStatementIssued).length;
return { totalSalesAmount, monthlyAmount, taxInvoicePendingCount, transactionStatementPendingCount };
}, [salesData]);
// ===== 거래처 목록 (필터용) =====
const vendorOptions = useMemo(() => {
const uniqueVendors = [...new Set(salesData.map(d => d.vendorName))].filter(Boolean);
return uniqueVendors.map(v => ({ value: v, label: v }));
}, [salesData]);
// ===== filterConfig 정의 =====
const filterConfig: FilterFieldConfig[] = useMemo(() => [
{
key: 'vendor',
label: '거래처',
type: 'single',
options: vendorOptions,
allOptionLabel: '거래처 전체',
},
{
key: 'salesType',
label: '매출유형',
type: 'single',
options: SALES_TYPE_FILTER_OPTIONS.filter(o => o.value !== 'all'),
allOptionLabel: '전체',
},
{
key: 'issuance',
label: '발행여부',
type: 'single',
options: ISSUANCE_FILTER_OPTIONS.filter(o => o.value !== 'all'),
allOptionLabel: '전체',
},
{
key: 'sort',
label: '정렬',
type: 'single',
options: SORT_OPTIONS,
},
], [vendorOptions]);
// ===== 필터 핸들러 =====
const handleFilterChange = useCallback((key: string, value: string | string[]) => {
setFilterValues(prev => ({ ...prev, [key]: value }));
}, []);
const handleFilterReset = useCallback(() => {
setFilterValues({
vendor: 'all',
salesType: 'all',
issuance: 'all',
sort: 'latest',
});
}, []);
// ===== 핸들러 =====
const handleRowClick = useCallback((item: SalesRecord) => {
router.push(`/ko/accounting/sales/${item.id}?mode=view`);
}, [router]);
const handleCreate = useCallback(() => {
router.push('/ko/accounting/sales?mode=new');
}, [router]);
// 토글 핸들러 (Optimistic UI: 먼저 UI 업데이트 → API 호출 → 실패 시 롤백)
const handleTaxInvoiceToggle = useCallback(async (itemId: string, checked: boolean) => {
setSalesData(prev => prev.map(item =>
item.id === itemId ? { ...item, taxInvoiceIssued: checked } : item
));
const result = await toggleSaleIssuance(itemId, 'taxInvoiceIssued', checked);
if (!result.success) {
setSalesData(prev => prev.map(item =>
item.id === itemId ? { ...item, taxInvoiceIssued: !checked } : item
));
toast.error(result.error || '세금계산서 발행 상태 변경에 실패했습니다.');
}
}, []);
const handleTransactionStatementToggle = useCallback(async (itemId: string, checked: boolean) => {
setSalesData(prev => prev.map(item =>
item.id === itemId ? { ...item, transactionStatementIssued: checked } : item
));
const result = await toggleSaleIssuance(itemId, 'transactionStatementIssued', checked);
if (!result.success) {
setSalesData(prev => prev.map(item =>
item.id === itemId ? { ...item, transactionStatementIssued: !checked } : item
));
toast.error(result.error || '거래명세서 발행 상태 변경에 실패했습니다.');
}
}, []);
// 계정과목명 저장 핸들러
const handleSaveAccountSubject = useCallback((selectedItems: Set<string>) => {
if (selectedItems.size === 0) {
toast.warning('변경할 매출 항목을 선택해주세요.');
return;
}
setSelectedItemsForSave(selectedItems);
setShowSaveDialog(true);
}, []);
const handleConfirmSaveAccountSubject = useCallback(() => {
// TODO: API 호출로 저장
setShowSaveDialog(false);
setSelectedItemsForSave(new Set());
toast.success('계정과목명이 변경되었습니다.');
}, [selectedAccountSubject]);
// ===== 테이블 합계 계산 =====
const tableTotals = useMemo(() => {
const totalSupplyAmount = salesData.reduce((sum, item) => sum + item.totalSupplyAmount, 0);
const totalVat = salesData.reduce((sum, item) => sum + item.totalVat, 0);
const totalAmount = salesData.reduce((sum, item) => sum + item.totalAmount, 0);
return { totalSupplyAmount, totalVat, totalAmount };
}, [salesData]);
// ===== UniversalListPage Config =====
const config: UniversalListConfig<SalesRecord> = useMemo(
() => ({
// 페이지 기본 정보
title: '매출관리',
description: '매출 내역을 등록하고 관리합니다',
icon: Receipt,
basePath: '/accounting/sales',
// ID 추출
idField: 'id',
// API 액션
actions: {
getList: async () => {
return {
success: true,
data: salesData,
totalCount: salesData.length,
};
},
deleteItem: async (id: string) => {
const result = await deleteSale(id);
if (result.success) {
setSalesData(prev => prev.filter(item => item.id !== id));
toast.success('매출이 삭제되었습니다.');
}
return { success: result.success, error: result.error };
},
},
// 테이블 컬럼
columns: tableColumns,
// 클라이언트 사이드 필터링
clientSideFiltering: true,
itemsPerPage: 20,
// 데이터 변경 콜백
onDataChange: (data) => setSalesData(data),
// 검색 필터
searchPlaceholder: '매출번호, 거래처명, 비고 검색...',
searchFilter: (item, searchValue) => {
const search = searchValue.toLowerCase();
return (
item.salesNo.toLowerCase().includes(search) ||
item.vendorName.toLowerCase().includes(search) ||
item.note.toLowerCase().includes(search)
);
},
// 커스텀 필터 함수 (filterConfig 사용)
customFilterFn: (items, fv) => {
if (!items || items.length === 0) return items;
return items.filter((item) => {
// 검색어 필터
if (searchQuery) {
const search = searchQuery.toLowerCase();
const matchesSearch =
item.salesNo.toLowerCase().includes(search) ||
item.vendorName.toLowerCase().includes(search) ||
item.note.toLowerCase().includes(search);
if (!matchesSearch) return false;
}
const vendorVal = fv.vendor as string;
const salesTypeVal = fv.salesType as string;
const issuanceVal = fv.issuance as string;
// 거래처 필터
if (vendorVal !== 'all' && item.vendorName !== vendorVal) {
return false;
}
// 매출유형 필터
if (salesTypeVal !== 'all' && item.salesType !== salesTypeVal) {
return false;
}
// 발행여부 필터
if (issuanceVal === 'taxInvoicePending' && item.taxInvoiceIssued) {
return false;
}
if (issuanceVal === 'transactionStatementPending' && item.transactionStatementIssued) {
return false;
}
return true;
});
},
// 커스텀 정렬 함수
customSortFn: (items, fv) => {
const sorted = [...items];
const sortVal = fv.sort as string;
switch (sortVal) {
case 'oldest':
sorted.sort((a, b) => new Date(a.salesDate).getTime() - new Date(b.salesDate).getTime());
break;
case 'amountHigh':
sorted.sort((a, b) => b.totalAmount - a.totalAmount);
break;
case 'amountLow':
sorted.sort((a, b) => a.totalAmount - b.totalAmount);
break;
default: // latest
sorted.sort((a, b) => new Date(b.salesDate).getTime() - new Date(a.salesDate).getTime());
break;
}
return sorted;
},
// 검색창 (공통 컴포넌트에서 자동 생성)
hideSearch: true,
searchValue: searchQuery,
onSearchChange: setSearchQuery,
// 공통 헤더 옵션
dateRangeSelector: {
enabled: true,
showPresets: true,
startDate,
endDate,
onStartDateChange: setStartDate,
onEndDateChange: setEndDate,
},
// 헤더 액션 (계정과목명 Select + 저장 버튼)
headerActions: ({ selectedItems }) => (
<div className="flex items-center gap-2">
<span className="text-sm font-medium text-gray-700 whitespace-nowrap"></span>
<Select value={selectedAccountSubject} onValueChange={setSelectedAccountSubject}>
<SelectTrigger className="w-[120px]">
<SelectValue placeholder="선택" />
</SelectTrigger>
<SelectContent>
{ACCOUNT_SUBJECT_SELECTOR_OPTIONS.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
<Button onClick={() => handleSaveAccountSubject(selectedItems)} size="sm">
<Save className="h-4 w-4 mr-1" />
</Button>
</div>
),
createButton: {
label: '매출 등록',
onClick: handleCreate,
},
// Stats 카드
computeStats: (): StatCard[] => [
{ label: '총 매출', value: `${stats.totalSalesAmount.toLocaleString()}`, icon: Receipt, iconColor: 'text-blue-500' },
{ label: '당월 매출', value: `${stats.monthlyAmount.toLocaleString()}`, icon: Receipt, iconColor: 'text-green-500' },
{ label: '세금계산서 발행대기', value: `${stats.taxInvoicePendingCount}`, icon: Receipt, iconColor: 'text-orange-500' },
{ label: '거래명세서 발행대기', value: `${stats.transactionStatementPendingCount}`, icon: Receipt, iconColor: 'text-orange-500' },
],
// 필터 설정 (filterConfig 사용 - PC 인라인, 모바일 바텀시트)
filterConfig,
initialFilters: filterValues,
filterTitle: '매출 필터',
// 테이블 하단 합계 행
tableFooter: (
<TableRow className="bg-muted/50 font-medium">
<TableCell className="text-center"></TableCell>
<TableCell className="text-center"></TableCell>
<TableCell className="font-bold"></TableCell>
<TableCell></TableCell>
<TableCell></TableCell>
<TableCell className="text-right font-bold">{tableTotals.totalSupplyAmount.toLocaleString()}</TableCell>
<TableCell className="text-right font-bold">{tableTotals.totalVat.toLocaleString()}</TableCell>
<TableCell className="text-right font-bold">{tableTotals.totalAmount.toLocaleString()}</TableCell>
<TableCell></TableCell>
<TableCell></TableCell>
<TableCell></TableCell>
</TableRow>
),
// 삭제 확인 메시지
deleteConfirmMessage: {
title: '매출 삭제',
description: '이 매출 내역을 삭제하시겠습니까? 이 작업은 취소할 수 없습니다.',
},
// 테이블 행 렌더링
renderTableRow: (
item: SalesRecord,
index: number,
globalIndex: number,
handlers: SelectionHandlers & RowClickHandlers<SalesRecord>
) => (
<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 text-sm text-gray-500">{globalIndex}</TableCell>
<TableCell className="text-sm font-medium">{item.salesNo}</TableCell>
<TableCell>{item.salesDate}</TableCell>
<TableCell>{item.vendorName}</TableCell>
<TableCell className="text-right">{item.totalSupplyAmount.toLocaleString()}</TableCell>
<TableCell className="text-right">{item.totalVat.toLocaleString()}</TableCell>
<TableCell className="text-right font-medium">{item.totalAmount.toLocaleString()}</TableCell>
<TableCell className="text-center">
<Badge variant="outline">{SALES_TYPE_LABELS[item.salesType]}</Badge>
</TableCell>
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
<div className="flex items-center justify-center gap-1">
<Switch
checked={item.taxInvoiceIssued}
onCheckedChange={(checked) => handleTaxInvoiceToggle(item.id, checked)}
className="data-[state=checked]:bg-orange-500"
/>
{item.taxInvoiceIssued && <span className="text-xs text-orange-500 font-medium"></span>}
</div>
</TableCell>
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
<div className="flex items-center justify-center gap-1">
<Switch
checked={item.transactionStatementIssued}
onCheckedChange={(checked) => handleTransactionStatementToggle(item.id, checked)}
className="data-[state=checked]:bg-orange-500"
/>
{item.transactionStatementIssued && <span className="text-xs text-orange-500 font-medium"></span>}
</div>
</TableCell>
</TableRow>
),
// 모바일 카드 렌더링
renderMobileCard: (
item: SalesRecord,
index: number,
globalIndex: number,
handlers: SelectionHandlers & RowClickHandlers<SalesRecord>
) => (
<MobileCard
key={item.id}
title={item.vendorName}
subtitle={item.salesNo}
badge={SALES_TYPE_LABELS[item.salesType]}
badgeVariant="outline"
isSelected={handlers.isSelected}
onToggle={handlers.onToggle}
onClick={() => handleRowClick(item)}
details={[
{ label: '매출일', value: item.salesDate },
{ label: '매출금액', value: `${item.totalAmount.toLocaleString()}` },
{ label: '미수금액', value: item.outstandingAmount > 0 ? `${item.outstandingAmount.toLocaleString()}` : '-' },
]}
/>
),
}),
[
salesData,
startDate,
endDate,
stats,
filterConfig,
filterValues,
selectedAccountSubject,
tableTotals,
searchQuery,
handleRowClick,
handleCreate,
handleTaxInvoiceToggle,
handleTransactionStatementToggle,
handleSaveAccountSubject,
]
);
return (
<>
<UniversalListPage config={config} initialData={salesData} />
{/* 계정과목명 저장 확인 다이얼로그 */}
<Dialog open={showSaveDialog} onOpenChange={setShowSaveDialog}>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle> </DialogTitle>
<DialogDescription>
{selectedItemsForSave.size} {' '}
<span className="font-semibold text-orange-500">
{ACCOUNT_SUBJECT_SELECTOR_OPTIONS.find(o => o.value === selectedAccountSubject)?.label}
</span>
() ?
</DialogDescription>
</DialogHeader>
<DialogFooter className="gap-2 sm:gap-0">
<Button variant="outline" onClick={() => setShowSaveDialog(false)}>
</Button>
<Button
onClick={handleConfirmSaveAccountSubject}
className="bg-blue-500 hover:bg-blue-600"
>
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
);
}