Files
sam-manage/resources/views/finance/vehicle-maintenance.blade.php
2026-02-03 19:56:44 +09:00

654 lines
46 KiB
PHP

@extends('layouts.app')
@section('title', '법인차량 관리')
@push('styles')
<style>
@media print { .no-print { display: none !important; } }
</style>
@endpush
@section('content')
<div id="vehicle-maintenance-root"></div>
@endsection
@push('scripts')
<script src="https://unpkg.com/react@18/umd/react.development.js?v={{ time() }}"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js?v={{ time() }}"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js?v={{ time() }}"></script>
<script src="https://unpkg.com/lucide@latest?v={{ time() }}"></script>
@verbatim
<script type="text/babel">
const { useState, useRef, useEffect } = React;
const createIcon = (name) => ({ className = "w-5 h-5", ...props }) => {
const ref = useRef(null);
useEffect(() => {
if (ref.current && lucide.icons[name]) {
ref.current.innerHTML = '';
const svg = lucide.createElement(lucide.icons[name]);
svg.setAttribute('class', className);
ref.current.appendChild(svg);
}
}, [className]);
return <span ref={ref} className="inline-flex items-center" {...props} />;
};
const Wrench = createIcon('wrench');
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 DollarSign = createIcon('dollar-sign');
const Fuel = createIcon('fuel');
const Car = createIcon('car');
function VehicleMaintenanceManagement() {
// 탭 상태
const [activeTab, setActiveTab] = useState('maintenance');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
// 차량 목록 (API에서 로드)
const [vehicles, setVehicles] = useState([]);
// 정비 이력 (API에서 로드)
const [maintenances, setMaintenances] = useState([]);
// 데이터 로드
const loadVehicles = async () => {
try {
const response = await fetch('/finance/vehicle-maintenance/vehicles');
const result = await response.json();
if (result.success) {
setVehicles(result.data.map(v => ({
id: v.id,
plateNumber: v.plate_number,
model: v.model,
ownershipType: v.ownership_type,
currentMileage: v.mileage || 0
})));
}
} catch (error) {
console.error('차량 로드 실패:', error);
}
};
const loadMaintenances = async () => {
try {
const params = new URLSearchParams({
start_date: dateRange.start,
end_date: dateRange.end,
category: filterCategory,
vehicle_id: filterVehicle,
search: searchTerm
});
const response = await fetch(`/finance/vehicle-maintenance/list?${params}`);
const result = await response.json();
if (result.success) {
setMaintenances(result.data);
}
} catch (error) {
console.error('정비 이력 로드 실패:', error);
} finally {
setLoading(false);
}
};
useEffect(() => {
loadVehicles();
}, []);
useEffect(() => {
if (vehicles.length > 0 || !loading) {
loadMaintenances();
}
}, [dateRange, filterCategory, filterVehicle]);
const [searchTerm, setSearchTerm] = useState('');
const [filterCategory, setFilterCategory] = useState('all');
const [filterVehicle, setFilterVehicle] = useState('all');
const [dateRange, setDateRange] = useState({
start: new Date(new Date().setMonth(new Date().getMonth() - 3)).toISOString().split('T')[0],
end: new Date().toISOString().split('T')[0]
});
const [showModal, setShowModal] = useState(false);
const [modalMode, setModalMode] = useState('add');
const [editingItem, setEditingItem] = useState(null);
// 차량 등록 모달
const [showVehicleModal, setShowVehicleModal] = useState(false);
const [vehicleModalMode, setVehicleModalMode] = useState('add');
const [editingVehicle, setEditingVehicle] = useState(null);
const categories = ['주유', '정비', '보험', '세차', '주차', '통행료', '검사', '기타'];
const ownershipTypes = [
{ value: 'corporate', label: '법인차량' },
{ value: 'rent', label: '렌트차량' },
{ value: 'lease', label: '리스차량' }
];
// 차량 표시용 헬퍼
const getVehicleDisplay = (vehicleId) => {
const v = vehicles.find(v => v.id === vehicleId);
return v ? `${v.plateNumber} (${v.model})` : '-';
};
// API 응답에서 차량 정보 표시 (plateNumber가 직접 포함된 경우)
const getVehicleDisplayFromItem = (item) => {
if (item.plateNumber && item.model) {
return `${item.plateNumber} (${item.model})`;
}
return getVehicleDisplay(item.vehicleId);
};
const getOwnershipLabel = (type) => {
const found = ownershipTypes.find(t => t.value === type);
return found ? found.label : type;
};
const getOwnershipColor = (type) => {
switch(type) {
case 'corporate': return 'bg-blue-100 text-blue-700';
case 'rent': return 'bg-purple-100 text-purple-700';
case 'lease': return 'bg-orange-100 text-orange-700';
default: return 'bg-gray-100 text-gray-700';
}
};
const initialFormState = {
date: new Date().toISOString().split('T')[0],
vehicleId: vehicles[0]?.id || '',
category: '주유',
description: '',
amount: '',
mileage: '',
vendor: '',
memo: ''
};
const [formData, setFormData] = useState(initialFormState);
// 차량 등록 초기 상태
const initialVehicleFormState = {
plateNumber: '',
model: '',
ownershipType: 'corporate',
purchaseDate: '',
purchasePrice: '',
currentMileage: '',
// 렌트/리스 전용 필드
contractDate: '',
rentCompany: '',
rentCompanyTel: '',
rentPeriod: '',
agreedMileage: '',
vehiclePrice: '',
residualValue: '',
deposit: '',
monthlyRent: '',
monthlyRentTax: '',
insuranceCompany: '',
insuranceCompanyTel: ''
};
const [vehicleFormData, setVehicleFormData] = useState(initialVehicleFormState);
const formatCurrency = (num) => num ? 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, '');
// API에서 이미 필터링된 데이터를 받으므로 클라이언트 측에서는 검색어만 필터링
const filteredMaintenances = maintenances.filter(item => {
if (!searchTerm) return true;
const search = searchTerm.toLowerCase();
return (item.description || '').toLowerCase().includes(search) ||
(item.vendor || '').toLowerCase().includes(search) ||
(item.plateNumber || '').toLowerCase().includes(search);
});
const totalAmount = filteredMaintenances.reduce((sum, item) => sum + item.amount, 0);
const fuelAmount = filteredMaintenances.filter(m => m.category === '주유').reduce((sum, item) => sum + item.amount, 0);
const maintenanceAmount = filteredMaintenances.filter(m => m.category === '정비').reduce((sum, item) => sum + item.amount, 0);
const otherAmount = totalAmount - fuelAmount - maintenanceAmount;
// 유지비 등록/수정
const handleAdd = () => { setModalMode('add'); setFormData({...initialFormState, vehicleId: vehicles[0]?.id || ''}); setShowModal(true); };
const handleEdit = (item) => { setModalMode('edit'); setEditingItem(item); setFormData({ ...item }); setShowModal(true); };
const handleSave = async () => {
if (!formData.description || !formData.amount) { alert('필수 항목을 입력해주세요.'); return; }
setSaving(true);
try {
const payload = {
vehicle_id: parseInt(formData.vehicleId),
date: formData.date,
category: formData.category,
description: formData.description,
amount: parseInt(String(formData.amount).replace(/[^\d]/g, '')) || 0,
mileage: parseInt(String(formData.mileage).replace(/[^\d]/g, '')) || null,
vendor: formData.vendor,
memo: formData.memo
};
const url = modalMode === 'add' ? '/finance/vehicle-maintenance' : `/finance/vehicle-maintenance/${editingItem.id}`;
const method = modalMode === 'add' ? 'POST' : 'PUT';
const response = await fetch(url, {
method,
headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content },
body: JSON.stringify(payload)
});
const result = await response.json();
if (result.success) {
await loadMaintenances();
setShowModal(false);
setEditingItem(null);
} else {
alert(result.message || '저장에 실패했습니다.');
}
} catch (error) {
console.error('저장 오류:', error);
alert('저장 중 오류가 발생했습니다.');
} finally {
setSaving(false);
}
};
const handleDelete = async (id) => {
if (!confirm('정말 삭제하시겠습니까?')) return;
try {
const response = await fetch(`/finance/vehicle-maintenance/${id}`, {
method: 'DELETE',
headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content }
});
const result = await response.json();
if (result.success) {
await loadMaintenances();
setShowModal(false);
} else {
alert(result.message || '삭제에 실패했습니다.');
}
} catch (error) {
console.error('삭제 오류:', error);
alert('삭제 중 오류가 발생했습니다.');
}
};
// 차량 등록/수정 - corporate-vehicles API 사용
const handleAddVehicle = () => { setVehicleModalMode('add'); setVehicleFormData(initialVehicleFormState); setShowVehicleModal(true); };
const handleEditVehicle = (vehicle) => { setVehicleModalMode('edit'); setEditingVehicle(vehicle); setVehicleFormData({ ...vehicle }); setShowVehicleModal(true); };
const handleSaveVehicle = async () => {
if (!vehicleFormData.plateNumber || !vehicleFormData.model) { alert('차량번호와 모델명은 필수입니다.'); return; }
setSaving(true);
try {
const payload = {
plate_number: vehicleFormData.plateNumber,
model: vehicleFormData.model,
vehicle_type: '승용차',
ownership_type: vehicleFormData.ownershipType,
year: new Date().getFullYear(),
mileage: parseInt(String(vehicleFormData.currentMileage).replace(/[^\d]/g, '')) || 0,
purchase_date: vehicleFormData.purchaseDate,
purchase_price: parseInt(String(vehicleFormData.purchasePrice).replace(/[^\d]/g, '')) || 0,
contract_date: vehicleFormData.contractDate,
rent_company: vehicleFormData.rentCompany,
rent_company_tel: vehicleFormData.rentCompanyTel,
rent_period: vehicleFormData.rentPeriod,
agreed_mileage: vehicleFormData.agreedMileage,
vehicle_price: parseInt(String(vehicleFormData.vehiclePrice).replace(/[^\d]/g, '')) || 0,
residual_value: parseInt(String(vehicleFormData.residualValue).replace(/[^\d]/g, '')) || 0,
deposit: parseInt(String(vehicleFormData.deposit).replace(/[^\d]/g, '')) || 0,
monthly_rent: parseInt(String(vehicleFormData.monthlyRent).replace(/[^\d]/g, '')) || 0,
monthly_rent_tax: parseInt(String(vehicleFormData.monthlyRentTax).replace(/[^\d]/g, '')) || 0,
insurance_company: vehicleFormData.insuranceCompany,
insurance_company_tel: vehicleFormData.insuranceCompanyTel
};
const url = vehicleModalMode === 'add' ? '/finance/corporate-vehicles' : `/finance/corporate-vehicles/${editingVehicle.id}`;
const method = vehicleModalMode === 'add' ? 'POST' : 'PUT';
const response = await fetch(url, {
method,
headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content },
body: JSON.stringify(payload)
});
const result = await response.json();
if (result.success) {
await loadVehicles();
setShowVehicleModal(false);
setEditingVehicle(null);
} else {
alert(result.message || '저장에 실패했습니다.');
}
} catch (error) {
console.error('저장 오류:', error);
alert('저장 중 오류가 발생했습니다.');
} finally {
setSaving(false);
}
};
const handleDeleteVehicle = async (id) => {
if (!confirm('차량을 삭제하시겠습니까? 관련 유지비 기록도 함께 삭제됩니다.')) return;
try {
const response = await fetch(`/finance/corporate-vehicles/${id}`, {
method: 'DELETE',
headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content }
});
const result = await response.json();
if (result.success) {
await loadVehicles();
await loadMaintenances();
setShowVehicleModal(false);
} else {
alert(result.message || '삭제에 실패했습니다.');
}
} catch (error) {
console.error('삭제 오류:', error);
alert('삭제 중 오류가 발생했습니다.');
}
};
const handleDownload = () => {
const rows = [['차량 유지비', `${dateRange.start} ~ ${dateRange.end}`], [], ['날짜', '차량', '구분', '내용', '금액', '주행거리', '업체'],
...filteredMaintenances.map(item => [item.date, getVehicleDisplay(item.vehicleId), item.category, item.description, item.amount, item.mileage, item.vendor])];
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 = `차량유지비_${dateRange.start}_${dateRange.end}.csv`; link.click();
};
const getCategoryColor = (cat) => {
const colors = { '주유': 'bg-amber-100 text-amber-700', '정비': 'bg-blue-100 text-blue-700', '보험': 'bg-purple-100 text-purple-700', '세차': 'bg-cyan-100 text-cyan-700', '주차': 'bg-gray-100 text-gray-700', '통행료': 'bg-emerald-100 text-emerald-700', '검사': 'bg-indigo-100 text-indigo-700', '기타': 'bg-slate-100 text-slate-700' };
return colors[cat] || 'bg-gray-100 text-gray-700';
};
return (
<div className="bg-gray-50 min-h-screen">
<header className="bg-white border-b border-gray-200 rounded-t-xl mb-6">
<div className="px-6 py-4 flex items-center justify-between">
<div className="flex items-center gap-4">
<div className="p-2 bg-amber-100 rounded-xl"><Car className="w-6 h-6 text-amber-600" /></div>
<div><h1 className="text-xl font-bold text-gray-900">법인차량 관리</h1><p className="text-sm text-gray-500">Corporate Vehicle Management</p></div>
</div>
<div className="flex items-center gap-3">
{activeTab === 'maintenance' ? (
<>
<button onClick={handleDownload} className="flex items-center gap-2 px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg"><Download className="w-4 h-4" /><span className="text-sm">Excel</span></button>
<button onClick={handleAdd} className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg"><Plus className="w-4 h-4" /><span className="text-sm font-medium">비용 등록</span></button>
</>
) : (
<button onClick={handleAddVehicle} className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg"><Plus className="w-4 h-4" /><span className="text-sm font-medium">차량 등록</span></button>
)}
</div>
</div>
{/* 탭 */}
<div className="px-6 flex gap-1">
<button onClick={() => setActiveTab('maintenance')} className={`px-4 py-2 text-sm font-medium rounded-t-lg transition-colors ${activeTab === 'maintenance' ? 'bg-gray-50 text-amber-600 border-b-2 border-amber-500' : 'text-gray-500 hover:text-gray-700'}`}>
유지비 관리
</button>
<button onClick={() => setActiveTab('vehicles')} className={`px-4 py-2 text-sm font-medium rounded-t-lg transition-colors ${activeTab === 'vehicles' ? 'bg-gray-50 text-amber-600 border-b-2 border-amber-500' : 'text-gray-500 hover:text-gray-700'}`}>
차량 등록
</button>
</div>
</header>
{/* 유지비 관리 탭 */}
{activeTab === 'maintenance' && (
<>
<div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
<div className="bg-white rounded-xl border border-gray-200 p-6">
<div className="flex items-center justify-between mb-2"><span className="text-sm text-gray-500"> 유지비</span><DollarSign className="w-5 h-5 text-gray-400" /></div>
<p className="text-2xl font-bold text-gray-900">{formatCurrency(totalAmount)}</p>
<p className="text-xs text-gray-400 mt-1">{filteredMaintenances.length}</p>
</div>
<div className="bg-white rounded-xl border border-amber-200 p-6 bg-amber-50/30">
<div className="flex items-center justify-between mb-2"><span className="text-sm text-amber-700">주유비</span><Fuel className="w-5 h-5 text-amber-500" /></div>
<p className="text-2xl font-bold text-amber-600">{formatCurrency(fuelAmount)}</p>
</div>
<div className="bg-white rounded-xl border border-blue-200 p-6">
<div className="flex items-center justify-between mb-2"><span className="text-sm text-blue-700">정비비</span><Wrench className="w-5 h-5 text-blue-500" /></div>
<p className="text-2xl font-bold text-blue-600">{formatCurrency(maintenanceAmount)}</p>
</div>
<div className="bg-white rounded-xl border border-gray-200 p-6">
<div className="flex items-center justify-between mb-2"><span className="text-sm text-gray-500">기타</span></div>
<p className="text-2xl font-bold text-gray-900">{formatCurrency(otherAmount)}</p>
</div>
</div>
<div className="bg-white rounded-xl border border-gray-200 p-4 mb-6">
<div className="grid grid-cols-1 md:grid-cols-5 gap-4">
<div className="relative">
<Search className="w-5 h-5 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2" />
<input type="text" placeholder="내용, 업체 검색..." value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-amber-500" />
</div>
<select value={filterVehicle} onChange={(e) => setFilterVehicle(e.target.value)} className="px-3 py-2 border border-gray-300 rounded-lg">
<option value="all">전체 차량</option>
{vehicles.map(v => <option key={v.id} value={v.id}>{v.plateNumber} ({v.model})</option>)}
</select>
<select value={filterCategory} onChange={(e) => setFilterCategory(e.target.value)} className="px-3 py-2 border border-gray-300 rounded-lg"><option value="all">전체 구분</option>{categories.map(c => <option key={c} value={c}>{c}</option>)}</select>
<div className="flex items-center gap-2 md:col-span-2">
<input type="date" value={dateRange.start} onChange={(e) => setDateRange(prev => ({ ...prev, start: e.target.value }))} className="flex-1 px-2 py-2 border border-gray-300 rounded-lg text-sm" />
<span>~</span>
<input type="date" value={dateRange.end} onChange={(e) => setDateRange(prev => ({ ...prev, end: e.target.value }))} className="flex-1 px-2 py-2 border border-gray-300 rounded-lg text-sm" />
</div>
</div>
</div>
<div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
<table className="w-full">
<thead className="bg-gray-50 border-b border-gray-200">
<tr>
<th className="px-6 py-3 text-left text-xs font-semibold text-gray-600">날짜</th>
<th className="px-6 py-3 text-left text-xs font-semibold text-gray-600">차량</th>
<th className="px-6 py-3 text-left text-xs font-semibold text-gray-600">구분</th>
<th className="px-6 py-3 text-left text-xs font-semibold text-gray-600">내용</th>
<th className="px-6 py-3 text-right text-xs font-semibold text-gray-600">금액</th>
<th className="px-6 py-3 text-right text-xs font-semibold text-gray-600">주행거리</th>
<th className="px-6 py-3 text-center text-xs font-semibold text-gray-600">관리</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{filteredMaintenances.length === 0 ? (
<tr><td colSpan="7" className="px-6 py-12 text-center text-gray-400">데이터가 없습니다.</td></tr>
) : filteredMaintenances.map(item => {
const vehicle = vehicles.find(v => v.id === item.vehicleId);
return (
<tr key={item.id} className="hover:bg-gray-50 cursor-pointer" onClick={() => handleEdit(item)}>
<td className="px-6 py-4 text-sm text-gray-600">{item.date}</td>
<td className="px-6 py-4">
<p className="text-sm font-medium text-gray-900">{vehicle?.plateNumber || '-'}</p>
<p className="text-xs text-gray-400">{vehicle?.model || ''}</p>
</td>
<td className="px-6 py-4"><span className={`px-2 py-1 rounded text-xs font-medium ${getCategoryColor(item.category)}`}>{item.category}</span></td>
<td className="px-6 py-4"><p className="text-sm text-gray-900">{item.description}</p>{item.vendor && <p className="text-xs text-gray-400">{item.vendor}</p>}</td>
<td className="px-6 py-4 text-sm font-bold text-right text-amber-600">{formatCurrency(item.amount)}</td>
<td className="px-6 py-4 text-sm text-right text-gray-600">{formatCurrency(item.mileage)}km</td>
<td className="px-6 py-4 text-center" onClick={(e) => e.stopPropagation()}>
<button onClick={() => handleEdit(item)} className="p-1 text-gray-400 hover:text-blue-500"><Edit className="w-4 h-4" /></button>
<button onClick={() => handleDelete(item.id)} className="p-1 text-gray-400 hover:text-rose-500"><Trash2 className="w-4 h-4" /></button>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</>
)}
{/* 차량 등록 탭 */}
{activeTab === 'vehicles' && (
<>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
<div className="bg-white rounded-xl border border-blue-200 p-6 bg-blue-50/30">
<div className="flex items-center justify-between mb-2"><span className="text-sm text-blue-700">법인차량</span><Car className="w-5 h-5 text-blue-500" /></div>
<p className="text-2xl font-bold text-blue-600">{vehicles.filter(v => v.ownershipType === 'corporate').length}</p>
</div>
<div className="bg-white rounded-xl border border-purple-200 p-6 bg-purple-50/30">
<div className="flex items-center justify-between mb-2"><span className="text-sm text-purple-700">렌트차량</span><Car className="w-5 h-5 text-purple-500" /></div>
<p className="text-2xl font-bold text-purple-600">{vehicles.filter(v => v.ownershipType === 'rent').length}</p>
</div>
<div className="bg-white rounded-xl border border-orange-200 p-6 bg-orange-50/30">
<div className="flex items-center justify-between mb-2"><span className="text-sm text-orange-700">리스차량</span><Car className="w-5 h-5 text-orange-500" /></div>
<p className="text-2xl font-bold text-orange-600">{vehicles.filter(v => v.ownershipType === 'lease').length}</p>
</div>
</div>
<div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
<table className="w-full">
<thead className="bg-gray-50 border-b border-gray-200">
<tr>
<th className="px-6 py-3 text-left text-xs font-semibold text-gray-600">차량번호</th>
<th className="px-6 py-3 text-left text-xs font-semibold text-gray-600">모델명</th>
<th className="px-6 py-3 text-left text-xs font-semibold text-gray-600">구분</th>
<th className="px-6 py-3 text-left text-xs font-semibold text-gray-600">계약/구입일</th>
<th className="px-6 py-3 text-left text-xs font-semibold text-gray-600">렌트/리스사</th>
<th className="px-6 py-3 text-right text-xs font-semibold text-gray-600"> 렌트료</th>
<th className="px-6 py-3 text-right text-xs font-semibold text-gray-600">현재 주행거리</th>
<th className="px-6 py-3 text-center text-xs font-semibold text-gray-600">관리</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{vehicles.length === 0 ? (
<tr><td colSpan="8" className="px-6 py-12 text-center text-gray-400">등록된 차량이 없습니다.</td></tr>
) : vehicles.map(vehicle => (
<tr key={vehicle.id} className="hover:bg-gray-50 cursor-pointer" onClick={() => handleEditVehicle(vehicle)}>
<td className="px-6 py-4 text-sm font-medium text-gray-900">{vehicle.plateNumber}</td>
<td className="px-6 py-4 text-sm text-gray-600">{vehicle.model}</td>
<td className="px-6 py-4"><span className={`px-2 py-1 rounded text-xs font-medium ${getOwnershipColor(vehicle.ownershipType)}`}>{getOwnershipLabel(vehicle.ownershipType)}</span></td>
<td className="px-6 py-4 text-sm text-gray-600">{vehicle.contractDate || vehicle.purchaseDate || '-'}</td>
<td className="px-6 py-4 text-sm text-gray-600">{vehicle.rentCompany || '-'}</td>
<td className="px-6 py-4 text-sm font-bold text-right text-purple-600">{vehicle.monthlyRent ? `${formatCurrency(parseInt(vehicle.monthlyRent))}원` : '-'}</td>
<td className="px-6 py-4 text-sm text-right text-gray-600">{formatCurrency(vehicle.currentMileage)}km</td>
<td className="px-6 py-4 text-center" onClick={(e) => e.stopPropagation()}>
<button onClick={() => handleEditVehicle(vehicle)} className="p-1 text-gray-400 hover:text-blue-500"><Edit className="w-4 h-4" /></button>
<button onClick={() => handleDeleteVehicle(vehicle.id)} className="p-1 text-gray-400 hover:text-rose-500"><Trash2 className="w-4 h-4" /></button>
</td>
</tr>
))}
</tbody>
</table>
</div>
</>
)}
{/* 유지비 등록/수정 모달 */}
{showModal && (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
<div className="bg-white rounded-xl p-6 w-full max-w-lg mx-4 max-h-[90vh] overflow-y-auto">
<div className="flex items-center justify-between mb-6">
<h3 className="text-lg font-bold text-gray-900">{modalMode === 'add' ? '비용 등록' : '비용 수정'}</h3>
<button onClick={() => setShowModal(false)} className="p-1 hover:bg-gray-100 rounded-lg"><X className="w-5 h-5 text-gray-500" /></button>
</div>
<div className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div><label className="block text-sm font-medium text-gray-700 mb-1">날짜 *</label><input type="date" value={formData.date} onChange={(e) => setFormData(prev => ({ ...prev, date: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></div>
<div><label className="block text-sm font-medium text-gray-700 mb-1">구분</label><select value={formData.category} onChange={(e) => setFormData(prev => ({ ...prev, category: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg">{categories.map(c => <option key={c} value={c}>{c}</option>)}</select></div>
</div>
<div><label className="block text-sm font-medium text-gray-700 mb-1">차량</label>
<select value={formData.vehicleId} onChange={(e) => setFormData(prev => ({ ...prev, vehicleId: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg">
{vehicles.map(v => <option key={v.id} value={v.id}>{v.plateNumber} ({v.model})</option>)}
</select>
</div>
<div><label className="block text-sm font-medium text-gray-700 mb-1">내용 *</label><input type="text" value={formData.description} onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))} placeholder="내용" className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></div>
<div className="grid grid-cols-2 gap-4">
<div><label className="block text-sm font-medium text-gray-700 mb-1">금액 *</label><input type="text" value={formatInputCurrency(formData.amount)} onChange={(e) => setFormData(prev => ({ ...prev, amount: parseInputCurrency(e.target.value) }))} placeholder="0" className="w-full px-3 py-2 border border-gray-300 rounded-lg text-right" /></div>
<div><label className="block text-sm font-medium text-gray-700 mb-1">주행거리(km)</label><input type="text" value={formatInputCurrency(formData.mileage)} onChange={(e) => setFormData(prev => ({ ...prev, mileage: parseInputCurrency(e.target.value) }))} placeholder="0" className="w-full px-3 py-2 border border-gray-300 rounded-lg text-right" /></div>
</div>
<div className="grid grid-cols-2 gap-4">
<div><label className="block text-sm font-medium text-gray-700 mb-1">업체</label><input type="text" value={formData.vendor} onChange={(e) => setFormData(prev => ({ ...prev, vendor: e.target.value }))} placeholder="업체명" className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></div>
<div><label className="block text-sm font-medium text-gray-700 mb-1">메모</label><input type="text" value={formData.memo} onChange={(e) => setFormData(prev => ({ ...prev, memo: e.target.value }))} placeholder="메모" className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></div>
</div>
</div>
<div className="flex gap-3 mt-6">
{modalMode === 'edit' && <button onClick={() => handleDelete(editingItem.id)} className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg">삭제</button>}
<button onClick={() => setShowModal(false)} className="flex-1 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50">취소</button>
<button onClick={handleSave} className="flex-1 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg">{modalMode === 'add' ? '등록' : '저장'}</button>
</div>
</div>
</div>
)}
{/* 차량 등록/수정 모달 */}
{showVehicleModal && (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
<div className="bg-white rounded-xl p-6 w-full max-w-2xl mx-4 max-h-[90vh] overflow-y-auto">
<div className="flex items-center justify-between mb-6">
<h3 className="text-lg font-bold text-gray-900">{vehicleModalMode === 'add' ? '차량 등록' : '차량 수정'}</h3>
<button onClick={() => setShowVehicleModal(false)} className="p-1 hover:bg-gray-100 rounded-lg"><X className="w-5 h-5 text-gray-500" /></button>
</div>
<div className="space-y-4">
{/* 기본 정보 */}
<div className="grid grid-cols-3 gap-4">
<div><label className="block text-sm font-medium text-gray-700 mb-1">차량번호 *</label><input type="text" value={vehicleFormData.plateNumber} onChange={(e) => setVehicleFormData(prev => ({ ...prev, plateNumber: e.target.value }))} placeholder="12가 3456" className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></div>
<div><label className="block text-sm font-medium text-gray-700 mb-1">모델명 *</label><input type="text" value={vehicleFormData.model} onChange={(e) => setVehicleFormData(prev => ({ ...prev, model: e.target.value }))} placeholder="제네시스 G80" className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></div>
<div><label className="block text-sm font-medium text-gray-700 mb-1">구분 *</label>
<select value={vehicleFormData.ownershipType} onChange={(e) => setVehicleFormData(prev => ({ ...prev, ownershipType: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg">
{ownershipTypes.map(t => <option key={t.value} value={t.value}>{t.label}</option>)}
</select>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div><label className="block text-sm font-medium text-gray-700 mb-1">현재 주행거리 (km)</label><input type="text" value={formatInputCurrency(vehicleFormData.currentMileage)} onChange={(e) => setVehicleFormData(prev => ({ ...prev, currentMileage: parseInputCurrency(e.target.value) }))} placeholder="0" className="w-full px-3 py-2 border border-gray-300 rounded-lg text-right" /></div>
{vehicleFormData.ownershipType === 'corporate' && (
<>
<div><label className="block text-sm font-medium text-gray-700 mb-1">구입일</label><input type="date" value={vehicleFormData.purchaseDate} onChange={(e) => setVehicleFormData(prev => ({ ...prev, purchaseDate: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></div>
</>
)}
</div>
{/* 렌트/리스 전용 필드 */}
{(vehicleFormData.ownershipType === 'rent' || vehicleFormData.ownershipType === 'lease') && (
<>
<div className="border-t pt-4 mt-4">
<h4 className="text-sm font-semibold text-gray-900 mb-3">{vehicleFormData.ownershipType === 'rent' ? '렌트' : '리스'} 계약 정보</h4>
<div className="grid grid-cols-2 gap-4">
<div><label className="block text-sm font-medium text-gray-700 mb-1">계약일자</label><input type="date" value={vehicleFormData.contractDate} onChange={(e) => setVehicleFormData(prev => ({ ...prev, contractDate: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></div>
<div><label className="block text-sm font-medium text-gray-700 mb-1">{vehicleFormData.ownershipType === 'rent' ? '렌트' : '리스'}회사명</label><input type="text" value={vehicleFormData.rentCompany} onChange={(e) => setVehicleFormData(prev => ({ ...prev, rentCompany: e.target.value }))} placeholder="렌터카/리스사명" className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></div>
</div>
<div className="grid grid-cols-2 gap-4 mt-3">
<div><label className="block text-sm font-medium text-gray-700 mb-1">{vehicleFormData.ownershipType === 'rent' ? '렌트' : '리스'}회사 연락처</label><input type="text" value={vehicleFormData.rentCompanyTel} onChange={(e) => setVehicleFormData(prev => ({ ...prev, rentCompanyTel: e.target.value }))} placeholder="02-1234-5678" className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></div>
<div><label className="block text-sm font-medium text-gray-700 mb-1">{vehicleFormData.ownershipType === 'rent' ? '렌트' : '리스'}기간</label><input type="text" value={vehicleFormData.rentPeriod} onChange={(e) => setVehicleFormData(prev => ({ ...prev, rentPeriod: e.target.value }))} placeholder="36개월" className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></div>
</div>
<div className="grid grid-cols-2 gap-4 mt-3">
<div><label className="block text-sm font-medium text-gray-700 mb-1">약정운행거리 (km)</label><input type="text" value={formatInputCurrency(vehicleFormData.agreedMileage)} onChange={(e) => setVehicleFormData(prev => ({ ...prev, agreedMileage: parseInputCurrency(e.target.value) }))} placeholder="0" className="w-full px-3 py-2 border border-gray-300 rounded-lg text-right" /></div>
<div><label className="block text-sm font-medium text-gray-700 mb-1">차량가격 ()</label><input type="text" value={formatInputCurrency(vehicleFormData.vehiclePrice)} onChange={(e) => setVehicleFormData(prev => ({ ...prev, vehiclePrice: parseInputCurrency(e.target.value) }))} placeholder="0" className="w-full px-3 py-2 border border-gray-300 rounded-lg text-right" /></div>
</div>
<div className="grid grid-cols-2 gap-4 mt-3">
<div><label className="block text-sm font-medium text-gray-700 mb-1">추정잔존가액 ()</label><input type="text" value={formatInputCurrency(vehicleFormData.residualValue)} onChange={(e) => setVehicleFormData(prev => ({ ...prev, residualValue: parseInputCurrency(e.target.value) }))} placeholder="0" className="w-full px-3 py-2 border border-gray-300 rounded-lg text-right" /></div>
<div><label className="block text-sm font-medium text-gray-700 mb-1">보증금 ()</label><input type="text" value={formatInputCurrency(vehicleFormData.deposit)} onChange={(e) => setVehicleFormData(prev => ({ ...prev, deposit: parseInputCurrency(e.target.value) }))} placeholder="0" className="w-full px-3 py-2 border border-gray-300 rounded-lg text-right" /></div>
</div>
<div className="grid grid-cols-2 gap-4 mt-3">
<div><label className="block text-sm font-medium text-gray-700 mb-1"> {vehicleFormData.ownershipType === 'rent' ? '렌트' : '리스'} - 공급가액 ()</label><input type="text" value={formatInputCurrency(vehicleFormData.monthlyRent)} onChange={(e) => setVehicleFormData(prev => ({ ...prev, monthlyRent: parseInputCurrency(e.target.value) }))} placeholder="0" className="w-full px-3 py-2 border border-gray-300 rounded-lg text-right" /></div>
<div><label className="block text-sm font-medium text-gray-700 mb-1"> {vehicleFormData.ownershipType === 'rent' ? '렌트' : '리스'} - 세액 ()</label><input type="text" value={formatInputCurrency(vehicleFormData.monthlyRentTax)} onChange={(e) => setVehicleFormData(prev => ({ ...prev, monthlyRentTax: parseInputCurrency(e.target.value) }))} placeholder="0" className="w-full px-3 py-2 border border-gray-300 rounded-lg text-right" /></div>
</div>
</div>
<div className="border-t pt-4 mt-4">
<h4 className="text-sm font-semibold text-gray-900 mb-3">보험 정보</h4>
<div className="grid grid-cols-2 gap-4">
<div><label className="block text-sm font-medium text-gray-700 mb-1">보험사명</label><input type="text" value={vehicleFormData.insuranceCompany} onChange={(e) => setVehicleFormData(prev => ({ ...prev, insuranceCompany: e.target.value }))} placeholder="삼성화재" className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></div>
<div><label className="block text-sm font-medium text-gray-700 mb-1">보험사 연락처</label><input type="text" value={vehicleFormData.insuranceCompanyTel} onChange={(e) => setVehicleFormData(prev => ({ ...prev, insuranceCompanyTel: e.target.value }))} placeholder="1588-0000" className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></div>
</div>
</div>
</>
)}
</div>
<div className="flex gap-3 mt-6">
{vehicleModalMode === 'edit' && <button onClick={() => handleDeleteVehicle(editingVehicle.id)} className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg">삭제</button>}
<button onClick={() => setShowVehicleModal(false)} className="flex-1 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50">취소</button>
<button onClick={handleSaveVehicle} className="flex-1 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg">{vehicleModalMode === 'add' ? '등록' : '저장'}</button>
</div>
</div>
</div>
)}
</div>
);
}
const rootElement = document.getElementById('vehicle-maintenance-root');
if (rootElement) { ReactDOM.createRoot(rootElement).render(<VehicleMaintenanceManagement />); }
</script>
@endverbatim
@endpush