diff --git a/resources/views/finance/receivables.blade.php b/resources/views/finance/receivables.blade.php index 75466f91..ca189893 100644 --- a/resources/views/finance/receivables.blade.php +++ b/resources/views/finance/receivables.blade.php @@ -35,56 +35,16 @@ }; const Receipt = createIcon('receipt'); -const Plus = createIcon('plus'); const Search = createIcon('search'); const Download = createIcon('download'); -const X = createIcon('x'); -const Edit = createIcon('edit'); -const Trash2 = createIcon('trash-2'); -const Banknote = createIcon('banknote'); -const AlertTriangle = createIcon('alert-triangle'); -const CheckCircle = createIcon('check-circle'); const Clock = createIcon('clock'); -const RefreshCw = createIcon('refresh-cw'); const BookOpen = createIcon('book-open'); const Building = createIcon('building-2'); -const FileText = createIcon('file-text'); -const Filter = createIcon('filter'); -const ArrowUpDown = createIcon('arrow-up-down'); const TrendingUp = createIcon('trending-up'); const TrendingDown = createIcon('trending-down'); // ==================== 포맷 유틸 ==================== const formatCurrency = (num) => num ? Number(num).toLocaleString() : '0'; -const formatInputCurrency = (value) => { - if (!value && value !== 0) return ''; - const num = String(value).replace(/[^\d]/g, ''); - return num ? Number(num).toLocaleString() : ''; -}; -const parseInputCurrency = (value) => String(value).replace(/[^\d]/g, ''); - -const calculateOverdueDays = (dueDate) => { - if (!dueDate) return 0; - const today = new Date(); - const due = new Date(dueDate); - const diff = Math.floor((today - due) / (1000 * 60 * 60 * 24)); - return diff > 0 ? diff : 0; -}; - -const getStatusLabel = (status) => { - const labels = { 'outstanding': '미수', 'partial': '부분수금', 'collected': '수금완료', 'overdue': '연체' }; - return labels[status] || status; -}; - -const getStatusStyle = (status) => { - const styles = { - 'outstanding': 'bg-amber-100 text-amber-700', - 'partial': 'bg-blue-100 text-blue-700', - 'collected': 'bg-emerald-100 text-emerald-700', - 'overdue': 'bg-red-100 text-red-700' - }; - return styles[status] || 'bg-gray-100 text-gray-700'; -}; // ==================== 로딩 스피너 ==================== function LoadingSpinner() { @@ -411,315 +371,6 @@ className="hover:bg-blue-50 cursor-pointer"> ); } -// ==================== 탭 3: 수동관리 (기존 기능) ==================== -function ManualTab() { - const [receivables, setReceivables] = useState([]); - const [stats, setStats] = useState({ totalAmount: 0, totalCollected: 0, totalOutstanding: 0, overdueAmount: 0, count: 0 }); - const [loading, setLoading] = useState(true); - - const [searchTerm, setSearchTerm] = useState(''); - const [filterStatus, setFilterStatus] = useState('all'); - const [filterCategory, setFilterCategory] = useState('all'); - - const [showModal, setShowModal] = useState(false); - const [modalMode, setModalMode] = useState('add'); - const [editingItem, setEditingItem] = useState(null); - const [saving, setSaving] = useState(false); - - const [showCollectModal, setShowCollectModal] = useState(false); - const [collectingItem, setCollectingItem] = useState(null); - const [collectAmount, setCollectAmount] = useState(''); - const [collectDate, setCollectDate] = useState(''); - - const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content'); - - const categories = ['서비스', '상품', '컨설팅', '기타']; - - const initialFormState = { - customerName: '', - invoiceNo: '', - issueDate: new Date().toISOString().split('T')[0], - dueDate: '', - amount: '', - collectedAmount: 0, - status: 'outstanding', - category: '서비스', - description: '' - }; - const [formData, setFormData] = useState(initialFormState); - - const fetchReceivables = async () => { - setLoading(true); - try { - const res = await fetch('/finance/receivables/list'); - const data = await res.json(); - if (data.success) { - setReceivables(data.data); - setStats(data.stats); - } - } catch (err) { - console.error('미수금 조회 실패:', err); - } finally { - setLoading(false); - } - }; - - useEffect(() => { fetchReceivables(); }, []); - - const filteredReceivables = receivables.filter(item => { - const matchesSearch = (item.customerName || '').toLowerCase().includes(searchTerm.toLowerCase()) || - (item.invoiceNo || '').toLowerCase().includes(searchTerm.toLowerCase()); - const matchesStatus = filterStatus === 'all' || item.status === filterStatus; - const matchesCategory = filterCategory === 'all' || item.category === filterCategory; - return matchesSearch && matchesStatus && matchesCategory; - }); - - const handleAdd = () => { setModalMode('add'); setFormData(initialFormState); setShowModal(true); }; - const handleEdit = (item) => { - setModalMode('edit'); - setEditingItem(item); - const safeItem = {}; - Object.keys(initialFormState).forEach(key => { safeItem[key] = item[key] ?? ''; }); - setFormData(safeItem); - setShowModal(true); - }; - const handleSave = async () => { - if (!formData.customerName || !formData.invoiceNo || !formData.amount) { alert('필수 항목을 입력해주세요.'); return; } - setSaving(true); - try { - const url = modalMode === 'add' ? '/finance/receivables/store' : `/finance/receivables/${editingItem.id}`; - const body = { ...formData, amount: parseInt(formData.amount) || 0 }; - const res = await fetch(url, { - method: modalMode === 'add' ? 'POST' : 'PUT', - headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken }, - body: JSON.stringify(body), - }); - const data = await res.json(); - if (!res.ok) { - const errors = data.errors ? Object.values(data.errors).flat().join('\n') : data.message; - alert(errors || '저장에 실패했습니다.'); - return; - } - setShowModal(false); - setEditingItem(null); - fetchReceivables(); - } catch (err) { - console.error('저장 실패:', err); - alert('저장에 실패했습니다.'); - } finally { - setSaving(false); - } - }; - const handleDelete = async (id) => { - if (!confirm('정말 삭제하시겠습니까?')) return; - try { - const res = await fetch(`/finance/receivables/${id}`, { - method: 'DELETE', - headers: { 'X-CSRF-TOKEN': csrfToken }, - }); - if (res.ok) { - setShowModal(false); - fetchReceivables(); - } - } catch (err) { - console.error('삭제 실패:', err); - alert('삭제에 실패했습니다.'); - } - }; - - const handleCollect = (item) => { - setCollectingItem(item); - setCollectAmount(''); - setCollectDate(new Date().toISOString().split('T')[0]); - setShowCollectModal(true); - }; - - const processCollection = async () => { - const amount = parseInt(parseInputCurrency(collectAmount)) || 0; - if (amount <= 0) { alert('수금액을 입력해주세요.'); return; } - const remaining = collectingItem.amount - collectingItem.collectedAmount; - if (amount > remaining) { alert('수금액이 잔액을 초과합니다.'); return; } - - try { - const res = await fetch(`/finance/receivables/${collectingItem.id}/collect`, { - method: 'POST', - headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken }, - body: JSON.stringify({ collectAmount: amount }), - }); - const data = await res.json(); - if (!res.ok) { - alert(data.message || '수금 처리에 실패했습니다.'); - return; - } - setShowCollectModal(false); - setCollectingItem(null); - fetchReceivables(); - } catch (err) { - console.error('수금 처리 실패:', err); - alert('수금 처리에 실패했습니다.'); - } - }; - - const handleDownload = () => { - const rows = [['미수금 관리'], [], ['고객사', '청구서번호', '발행일', '만기일', '분류', '청구금액', '수금액', '잔액', '상태'], - ...filteredReceivables.map(item => [item.customerName, item.invoiceNo, item.issueDate, item.dueDate, item.category, item.amount, item.collectedAmount, item.amount - item.collectedAmount, getStatusLabel(item.status)])]; - const csvContent = rows.map(row => row.join(',')).join('\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const link = document.createElement('a'); link.href = URL.createObjectURL(blob); link.download = `미수금관리_${new Date().toISOString().split('T')[0]}.csv`; link.click(); - }; - - return ( -
{formatCurrency(stats.totalAmount)}원
-{stats.count}건
-{formatCurrency(stats.totalOutstanding)}원
-{formatCurrency(stats.overdueAmount)}원
-{formatCurrency(stats.totalCollected)}원
-| 고객사 | -청구서번호 | -만기일 | -분류 | -청구금액 | -잔액 | -상태 | -연체일 | -
|---|---|---|---|---|---|---|---|
| 데이터가 없습니다. | |||||||
{item.customerName} {item.description} |
- {item.invoiceNo} | -{item.dueDate} | -{item.category} | -{formatCurrency(item.amount)}원 | -{formatCurrency(item.amount - item.collectedAmount)}원 | -{getStatusLabel(item.status)} | -{item.status === 'overdue' ? {calculateOverdueDays(item.dueDate)}일 : '-'} | -
{collectingItem.customerName}
-{collectingItem.invoiceNo}
-