feat(purchase): 생산소모품 구매 관리 시스템 구현

tkuser: 업체(공급업체) CRUD + 소모품 마스터 CRUD (사진 업로드 포함)
tkfb: 구매신청 → 구매 처리 → 월간 분석/정산 전체 워크플로
설비(equipment) 분류 구매 시 자동 등록 + 실패 시 admin 알림

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Hyungi Ahn
2026-03-13 21:21:59 +09:00
parent 1abdb92a71
commit 3623551a6b
29 changed files with 2581 additions and 1 deletions

View File

@@ -0,0 +1,113 @@
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>구매 분석 - TK 공장관리</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="/static/css/tkfb.css">
</head>
<body class="bg-gray-50">
<header class="bg-orange-700 text-white sticky top-0 z-50">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex justify-between items-center h-14">
<div class="flex items-center gap-3">
<button id="mobileMenuBtn" class="lg:hidden text-orange-200 hover:text-white"><i class="fas fa-bars text-xl"></i></button>
<i class="fas fa-industry text-xl text-orange-200"></i>
<h1 class="text-lg font-semibold">TK 공장관리</h1>
</div>
<div class="flex items-center gap-4">
<span id="headerUserName" class="text-sm hidden sm:block">-</span>
<div id="headerUserAvatar" class="w-8 h-8 bg-orange-600 rounded-full flex items-center justify-center text-sm font-bold">-</div>
<button onclick="doLogout()" class="text-orange-200 hover:text-white" title="로그아웃"><i class="fas fa-sign-out-alt"></i></button>
</div>
</div>
</div>
</header>
<div id="mobileOverlay" class="hidden fixed inset-0 bg-black/50 z-30 lg:hidden"></div>
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 fade-in">
<div class="flex gap-6">
<nav id="sideNav" class="hidden lg:flex flex-col gap-1 w-52 flex-shrink-0 pt-2 fixed lg:static z-40 bg-white lg:bg-transparent p-4 lg:p-0 rounded-lg lg:rounded-none shadow-lg lg:shadow-none top-14 left-0 bottom-0 overflow-y-auto"></nav>
<div class="flex-1 min-w-0">
<div class="page-header">
<div class="page-title-section">
<h1 class="page-title">구매 분석</h1>
<p class="page-description">월간 구매 현황 분석 및 업체별 정산 관리</p>
</div>
</div>
<!-- 월 선택 -->
<div class="flex items-center gap-3 mb-6">
<input type="month" id="paMonth" class="px-3 py-2 border rounded-lg text-sm">
<button onclick="loadAnalysis()" class="px-4 py-2 bg-orange-600 text-white rounded-lg text-sm hover:bg-orange-700">
<i class="fas fa-search mr-1"></i>조회
</button>
</div>
<!-- 분류별 요약 카드 -->
<div id="paCategorySummary" class="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
<div class="bg-white rounded-xl shadow-sm p-4 text-center text-gray-400 col-span-4">월을 선택하고 조회해주세요</div>
</div>
<!-- 업체별 요약 -->
<div class="bg-white rounded-xl shadow-sm p-5 mb-6">
<h2 class="text-base font-semibold text-gray-800 mb-4"><i class="fas fa-building text-orange-500 mr-2"></i>업체별 요약</h2>
<div class="overflow-x-auto">
<table class="w-full text-sm">
<thead class="bg-gray-50 text-gray-600 text-xs uppercase">
<tr>
<th class="px-4 py-3 text-left">업체</th>
<th class="px-4 py-3 text-right">건수</th>
<th class="px-4 py-3 text-right">총액</th>
<th class="px-4 py-3 text-center">정산</th>
<th class="px-4 py-3 text-center">액션</th>
</tr>
</thead>
<tbody id="paVendorSummary" class="divide-y">
<tr><td colspan="5" class="px-4 py-8 text-center text-gray-400">-</td></tr>
</tbody>
</table>
</div>
</div>
<!-- 상세 구매 목록 -->
<div class="bg-white rounded-xl shadow-sm p-5 mb-6">
<h2 class="text-base font-semibold text-gray-800 mb-4"><i class="fas fa-list text-orange-500 mr-2"></i>상세 구매 목록</h2>
<div class="overflow-x-auto">
<table class="w-full text-sm">
<thead class="bg-gray-50 text-gray-600 text-xs uppercase">
<tr>
<th class="px-4 py-3 text-left">품목</th>
<th class="px-4 py-3 text-left">분류</th>
<th class="px-4 py-3 text-right">수량</th>
<th class="px-4 py-3 text-right">단가</th>
<th class="px-4 py-3 text-right">소계</th>
<th class="px-4 py-3 text-left">업체</th>
<th class="px-4 py-3 text-left">구매일</th>
<th class="px-4 py-3 text-left">비고</th>
</tr>
</thead>
<tbody id="paPurchaseList" class="divide-y">
<tr><td colspan="8" class="px-4 py-8 text-center text-gray-400">-</td></tr>
</tbody>
</table>
</div>
</div>
<!-- 가격 변동 -->
<div class="bg-white rounded-xl shadow-sm p-5">
<h2 class="text-base font-semibold text-gray-800 mb-4"><i class="fas fa-exchange-alt text-orange-500 mr-2"></i>가격 변동 항목</h2>
<div id="paPriceChanges" class="overflow-x-auto">
<p class="text-gray-400 text-center py-4 text-sm">-</p>
</div>
</div>
</div>
</div>
</div>
<script src="/static/js/tkfb-core.js?v=20260313"></script>
<script src="/static/js/purchase-analysis.js?v=20260313"></script>
</body>
</html>

View File

@@ -0,0 +1,181 @@
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>구매신청 - TK 공장관리</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="/static/css/tkfb.css">
</head>
<body class="bg-gray-50">
<header class="bg-orange-700 text-white sticky top-0 z-50">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex justify-between items-center h-14">
<div class="flex items-center gap-3">
<button id="mobileMenuBtn" class="lg:hidden text-orange-200 hover:text-white"><i class="fas fa-bars text-xl"></i></button>
<i class="fas fa-industry text-xl text-orange-200"></i>
<h1 class="text-lg font-semibold">TK 공장관리</h1>
</div>
<div class="flex items-center gap-4">
<span id="headerUserName" class="text-sm hidden sm:block">-</span>
<div id="headerUserAvatar" class="w-8 h-8 bg-orange-600 rounded-full flex items-center justify-center text-sm font-bold">-</div>
<button onclick="doLogout()" class="text-orange-200 hover:text-white" title="로그아웃"><i class="fas fa-sign-out-alt"></i></button>
</div>
</div>
</div>
</header>
<div id="mobileOverlay" class="hidden fixed inset-0 bg-black/50 z-30 lg:hidden"></div>
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 fade-in">
<div class="flex gap-6">
<nav id="sideNav" class="hidden lg:flex flex-col gap-1 w-52 flex-shrink-0 pt-2 fixed lg:static z-40 bg-white lg:bg-transparent p-4 lg:p-0 rounded-lg lg:rounded-none shadow-lg lg:shadow-none top-14 left-0 bottom-0 overflow-y-auto"></nav>
<div class="flex-1 min-w-0">
<div class="page-header">
<div class="page-title-section">
<h1 class="page-title">구매신청</h1>
<p class="page-description">생산소모품 구매를 신청하고 처리 현황을 확인합니다</p>
</div>
</div>
<!-- 구매신청 폼 -->
<div class="bg-white rounded-xl shadow-sm p-5 mb-6">
<h2 class="text-base font-semibold text-gray-800 mb-4"><i class="fas fa-plus-circle text-orange-500 mr-2"></i>신규 구매신청</h2>
<div class="grid grid-cols-1 sm:grid-cols-4 gap-4 items-end">
<div class="sm:col-span-2">
<label class="block text-xs font-medium text-gray-600 mb-1">소모품 <span class="text-red-400">*</span></label>
<select id="prItemSelect" class="w-full px-3 py-2 border rounded-lg text-sm focus:ring-2 focus:ring-orange-300" onchange="onItemSelect()">
<option value="">소모품 선택</option>
</select>
<div id="prItemPreview" class="mt-2 hidden flex items-center gap-3 p-2 bg-gray-50 rounded-lg">
<img id="prItemPhoto" class="w-12 h-12 rounded object-cover hidden">
<div>
<div id="prItemInfo" class="text-sm text-gray-700"></div>
<div id="prItemPrice" class="text-xs text-gray-500"></div>
</div>
</div>
</div>
<div>
<label class="block text-xs font-medium text-gray-600 mb-1">수량 <span class="text-red-400">*</span></label>
<input type="number" id="prQuantity" class="w-full px-3 py-2 border rounded-lg text-sm" min="1" value="1">
</div>
<div>
<label class="block text-xs font-medium text-gray-600 mb-1">메모</label>
<input type="text" id="prNotes" class="w-full px-3 py-2 border rounded-lg text-sm" placeholder="선택 사항">
</div>
</div>
<div class="mt-4 flex justify-end">
<button onclick="submitPurchaseRequest()" class="px-5 py-2 bg-orange-600 text-white rounded-lg text-sm hover:bg-orange-700">
<i class="fas fa-paper-plane mr-1"></i>구매신청
</button>
</div>
</div>
<!-- 필터 -->
<div class="flex gap-3 mb-4 flex-wrap items-center">
<select id="prFilterStatus" class="px-3 py-2 border rounded-lg text-sm" onchange="loadRequests()">
<option value="">전체 상태</option>
<option value="pending">대기</option>
<option value="purchased">구매완료</option>
<option value="hold">보류</option>
</select>
<select id="prFilterCategory" class="px-3 py-2 border rounded-lg text-sm" onchange="loadRequests()">
<option value="">전체 분류</option>
<option value="consumable">소모품</option>
<option value="safety">안전용품</option>
<option value="repair">수선비</option>
<option value="equipment">설비</option>
</select>
<button onclick="loadRequests()" class="px-3 py-2 border rounded-lg text-sm text-gray-600 hover:bg-gray-100">
<i class="fas fa-sync-alt"></i>
</button>
</div>
<!-- 신청 목록 -->
<div class="bg-white rounded-xl shadow-sm overflow-hidden">
<div class="overflow-x-auto">
<table class="w-full text-sm">
<thead class="bg-gray-50 text-gray-600 text-xs uppercase">
<tr>
<th class="px-4 py-3 text-left">품목</th>
<th class="px-4 py-3 text-left">분류</th>
<th class="px-4 py-3 text-right">수량</th>
<th class="px-4 py-3 text-left">신청자</th>
<th class="px-4 py-3 text-left">신청일</th>
<th class="px-4 py-3 text-center">상태</th>
<th class="px-4 py-3 text-center">액션</th>
</tr>
</thead>
<tbody id="prRequestList" class="divide-y">
<tr><td colspan="7" class="px-4 py-8 text-center text-gray-400">데이터를 불러오는 중...</td></tr>
</tbody>
</table>
</div>
</div>
<!-- 구매 처리 모달 -->
<div id="purchaseModal" class="hidden fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-4" onclick="if(event.target===this)closePurchaseModal()">
<div class="bg-white rounded-xl shadow-xl max-w-lg w-full p-6">
<div class="flex justify-between items-center mb-4">
<h3 class="text-lg font-semibold">구매 처리</h3>
<button onclick="closePurchaseModal()" class="text-gray-400 hover:text-gray-600"><i class="fas fa-times"></i></button>
</div>
<div id="purchaseModalInfo" class="bg-gray-50 rounded-lg p-3 mb-4 text-sm"></div>
<div class="grid grid-cols-2 gap-3">
<div>
<label class="block text-xs font-medium text-gray-600 mb-1">업체</label>
<select id="pmVendor" class="w-full px-3 py-2 border rounded-lg text-sm">
<option value="">업체 선택</option>
</select>
</div>
<div>
<label class="block text-xs font-medium text-gray-600 mb-1">구매일 <span class="text-red-400">*</span></label>
<input type="date" id="pmDate" class="w-full px-3 py-2 border rounded-lg text-sm">
</div>
<div>
<label class="block text-xs font-medium text-gray-600 mb-1">실구매 단가 <span class="text-red-400">*</span></label>
<input type="number" id="pmUnitPrice" class="w-full px-3 py-2 border rounded-lg text-sm" min="0" oninput="showPriceDiff()">
</div>
<div>
<label class="block text-xs font-medium text-gray-600 mb-1">수량</label>
<input type="number" id="pmQuantity" class="w-full px-3 py-2 border rounded-lg text-sm" min="1" value="1">
</div>
<div class="col-span-2" id="pmPriceDiffArea" class="hidden">
</div>
<div class="col-span-2">
<label class="block text-xs font-medium text-gray-600 mb-1">메모</label>
<input type="text" id="pmNotes" class="w-full px-3 py-2 border rounded-lg text-sm">
</div>
</div>
<div class="flex justify-end mt-4 gap-2">
<button type="button" onclick="closePurchaseModal()" class="px-4 py-2 border rounded-lg text-sm hover:bg-gray-50">취소</button>
<button type="button" onclick="submitPurchase()" class="px-4 py-2 bg-orange-600 text-white rounded-lg text-sm hover:bg-orange-700">구매 완료</button>
</div>
</div>
</div>
<!-- 보류 모달 -->
<div id="holdModal" class="hidden fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-4" onclick="if(event.target===this)closeHoldModal()">
<div class="bg-white rounded-xl shadow-xl max-w-md w-full p-6">
<div class="flex justify-between items-center mb-4">
<h3 class="text-lg font-semibold">보류 처리</h3>
<button onclick="closeHoldModal()" class="text-gray-400 hover:text-gray-600"><i class="fas fa-times"></i></button>
</div>
<div>
<label class="block text-xs font-medium text-gray-600 mb-1">보류 사유</label>
<textarea id="holdReason" rows="3" class="w-full px-3 py-2 border rounded-lg text-sm" placeholder="보류 사유를 입력하세요"></textarea>
</div>
<div class="flex justify-end mt-4 gap-2">
<button type="button" onclick="closeHoldModal()" class="px-4 py-2 border rounded-lg text-sm hover:bg-gray-50">취소</button>
<button type="button" onclick="submitHold()" class="px-4 py-2 bg-gray-600 text-white rounded-lg text-sm hover:bg-gray-700">보류</button>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="/static/js/tkfb-core.js?v=20260313"></script>
<script src="/static/js/purchase-request.js?v=20260313"></script>
</body>
</html>

View File

@@ -0,0 +1,183 @@
/* ===== 구매 분석 페이지 ===== */
const CAT_LABELS = { consumable: '소모품', safety: '안전용품', repair: '수선비', equipment: '설비' };
const CAT_ICONS = { consumable: 'fa-box', safety: 'fa-hard-hat', repair: 'fa-wrench', equipment: 'fa-cogs' };
const CAT_BG = { consumable: 'bg-blue-50 text-blue-700', safety: 'bg-green-50 text-green-700', repair: 'bg-amber-50 text-amber-700', equipment: 'bg-purple-50 text-purple-700' };
let currentYearMonth = '';
async function loadAnalysis() {
currentYearMonth = document.getElementById('paMonth').value;
if (!currentYearMonth) { showToast('월을 선택해주세요.', 'error'); return; }
try {
const [summaryRes, purchasesRes, priceChangesRes] = await Promise.all([
api(`/settlements/summary?year_month=${currentYearMonth}`),
api(`/settlements/purchases?year_month=${currentYearMonth}`),
api(`/settlements/price-changes?year_month=${currentYearMonth}`)
]);
renderCategorySummary(summaryRes.data?.categorySummary || []);
renderVendorSummary(summaryRes.data?.vendorSummary || []);
renderPurchaseList(purchasesRes.data || []);
renderPriceChanges(priceChangesRes.data || []);
} catch (e) {
showToast('데이터 로드 실패: ' + e.message, 'error');
}
}
function renderCategorySummary(data) {
const el = document.getElementById('paCategorySummary');
const allCategories = ['consumable', 'safety', 'repair', 'equipment'];
const dataMap = {};
data.forEach(d => { dataMap[d.category] = d; });
const totalAmount = data.reduce((sum, d) => sum + Number(d.total_amount || 0), 0);
el.innerHTML = allCategories.map(cat => {
const d = dataMap[cat] || { count: 0, total_amount: 0 };
const label = CAT_LABELS[cat];
const icon = CAT_ICONS[cat];
const bg = CAT_BG[cat];
return `<div class="bg-white rounded-xl shadow-sm p-4">
<div class="flex items-center gap-2 mb-2">
<div class="w-8 h-8 rounded-lg ${bg} flex items-center justify-center"><i class="fas ${icon} text-sm"></i></div>
<span class="text-sm font-medium text-gray-700">${label}</span>
</div>
<div class="text-xl font-bold text-gray-800">${Number(d.total_amount || 0).toLocaleString()}<span class="text-xs font-normal text-gray-400 ml-1">원</span></div>
<div class="text-xs text-gray-500 mt-1">${d.count || 0}건</div>
</div>`;
}).join('') + `
<div class="col-span-2 lg:col-span-4 bg-orange-50 rounded-xl p-3 text-center">
<span class="text-sm text-orange-700 font-semibold">월 합계: ${totalAmount.toLocaleString()}원</span>
</div>`;
}
function renderVendorSummary(data) {
const tbody = document.getElementById('paVendorSummary');
if (!data.length) {
tbody.innerHTML = '<tr><td colspan="5" class="px-4 py-8 text-center text-gray-400">해당 월 구매 내역이 없습니다.</td></tr>';
return;
}
tbody.innerHTML = data.map(v => {
const isCompleted = v.settlement_status === 'completed';
const statusBadge = isCompleted
? '<span class="badge badge-green">정산완료</span>'
: '<span class="badge badge-gray">미정산</span>';
const vendorName = v.vendor_name || '(업체 미지정)';
const vendorId = v.vendor_id || 0;
let actionBtn = '';
if (vendorId > 0) {
if (isCompleted) {
actionBtn = `<button onclick="cancelSettlement(${vendorId})" class="px-3 py-1 border border-gray-300 rounded text-xs text-gray-600 hover:bg-gray-50">정산 취소</button>`;
} else {
actionBtn = `<button onclick="completeSettlement(${vendorId})" class="px-3 py-1 bg-green-500 text-white rounded text-xs hover:bg-green-600">정산완료</button>`;
}
}
return `<tr class="hover:bg-gray-50">
<td class="px-4 py-3 font-medium text-gray-800">${escapeHtml(vendorName)}</td>
<td class="px-4 py-3 text-right">${v.count}건</td>
<td class="px-4 py-3 text-right font-medium">${Number(v.total_amount || 0).toLocaleString()}원</td>
<td class="px-4 py-3 text-center">${statusBadge}</td>
<td class="px-4 py-3 text-center">${actionBtn}</td>
</tr>`;
}).join('');
}
function renderPurchaseList(data) {
const tbody = document.getElementById('paPurchaseList');
if (!data.length) {
tbody.innerHTML = '<tr><td colspan="8" class="px-4 py-8 text-center text-gray-400">해당 월 구매 내역이 없습니다.</td></tr>';
return;
}
tbody.innerHTML = data.map(p => {
const catLabel = CAT_LABELS[p.category] || p.category;
const catColor = CAT_BG[p.category] || '';
const subtotal = (p.quantity || 0) * (p.unit_price || 0);
const basePrice = Number(p.base_price || 0);
const unitPrice = Number(p.unit_price || 0);
const hasPriceDiff = basePrice > 0 && unitPrice > 0 && basePrice !== unitPrice;
const priceDiffClass = hasPriceDiff ? (unitPrice > basePrice ? 'text-red-600 font-semibold' : 'text-blue-600 font-semibold') : '';
return `<tr class="hover:bg-gray-50 ${hasPriceDiff ? 'bg-yellow-50' : ''}">
<td class="px-4 py-3">
<div class="font-medium text-gray-800">${escapeHtml(p.item_name)}</div>
<div class="text-xs text-gray-500">${escapeHtml(p.maker || '')}</div>
</td>
<td class="px-4 py-3"><span class="px-1.5 py-0.5 rounded text-xs ${catColor}">${catLabel}</span></td>
<td class="px-4 py-3 text-right">${p.quantity}</td>
<td class="px-4 py-3 text-right ${priceDiffClass}">${unitPrice.toLocaleString()}${hasPriceDiff ? `<div class="text-xs text-gray-400">(기준: ${basePrice.toLocaleString()})</div>` : ''}</td>
<td class="px-4 py-3 text-right font-medium">${subtotal.toLocaleString()}원</td>
<td class="px-4 py-3 text-gray-600">${escapeHtml(p.vendor_name || '-')}</td>
<td class="px-4 py-3 text-gray-600">${formatDate(p.purchase_date)}</td>
<td class="px-4 py-3 text-gray-500 text-xs">${escapeHtml(p.notes || '')}</td>
</tr>`;
}).join('');
}
function renderPriceChanges(data) {
const el = document.getElementById('paPriceChanges');
if (!data.length) {
el.innerHTML = '<p class="text-gray-400 text-center py-4 text-sm">가격 변동 항목이 없습니다.</p>';
return;
}
el.innerHTML = `<table class="w-full text-sm">
<thead class="bg-gray-50 text-gray-600 text-xs uppercase">
<tr>
<th class="px-4 py-3 text-left">품목</th>
<th class="px-4 py-3 text-right">기준가</th>
<th class="px-4 py-3 text-right">실구매가</th>
<th class="px-4 py-3 text-right">차이</th>
<th class="px-4 py-3 text-left">업체</th>
<th class="px-4 py-3 text-left">구매일</th>
</tr>
</thead>
<tbody class="divide-y">${data.map(p => {
const diff = Number(p.unit_price) - Number(p.base_price);
const arrow = diff > 0 ? '&#9650;' : '&#9660;';
const color = diff > 0 ? 'text-red-600' : 'text-blue-600';
return `<tr class="hover:bg-gray-50">
<td class="px-4 py-3">${escapeHtml(p.item_name)} ${p.maker ? '(' + escapeHtml(p.maker) + ')' : ''}</td>
<td class="px-4 py-3 text-right">${Number(p.base_price).toLocaleString()}원</td>
<td class="px-4 py-3 text-right font-medium ${color}">${Number(p.unit_price).toLocaleString()}원</td>
<td class="px-4 py-3 text-right ${color}">${arrow} ${Math.abs(diff).toLocaleString()}원</td>
<td class="px-4 py-3 text-gray-600">${escapeHtml(p.vendor_name || '-')}</td>
<td class="px-4 py-3 text-gray-600">${formatDate(p.purchase_date)}</td>
</tr>`;
}).join('')}</tbody>
</table>`;
}
/* ===== 정산 처리 ===== */
async function completeSettlement(vendorId) {
if (!confirm('이 업체의 정산을 완료 처리하시겠습니까?')) return;
try {
await api('/settlements/complete', {
method: 'POST',
body: JSON.stringify({ year_month: currentYearMonth, vendor_id: vendorId })
});
showToast('정산 완료 처리되었습니다.');
await loadAnalysis();
} catch (e) { showToast(e.message, 'error'); }
}
async function cancelSettlement(vendorId) {
if (!confirm('정산 완료를 취소하시겠습니까?')) return;
try {
await api('/settlements/cancel', {
method: 'POST',
body: JSON.stringify({ year_month: currentYearMonth, vendor_id: vendorId })
});
showToast('정산이 취소되었습니다.');
await loadAnalysis();
} catch (e) { showToast(e.message, 'error'); }
}
/* ===== Init ===== */
(async function() {
if (!await initAuth()) return;
// 기본값: 현재 월
const now = new Date();
document.getElementById('paMonth').value = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
})();

View File

@@ -0,0 +1,294 @@
/* ===== 구매신청 페이지 ===== */
const TKUSER_BASE_URL = location.hostname.includes('technicalkorea.net')
? 'https://tkuser.technicalkorea.net'
: location.protocol + '//' + location.hostname + ':30180';
const CAT_LABELS = { consumable: '소모품', safety: '안전용품', repair: '수선비', equipment: '설비' };
const CAT_COLORS = { consumable: 'badge-blue', safety: 'badge-green', repair: 'badge-amber', equipment: 'badge-purple' };
const STATUS_LABELS = { pending: '대기', purchased: '구매완료', hold: '보류' };
const STATUS_COLORS = { pending: 'badge-amber', purchased: 'badge-green', hold: 'badge-gray' };
let consumableItems = [];
let vendorsList = [];
let requestsList = [];
let currentRequestForPurchase = null;
let currentRequestForHold = null;
let isAdmin = false;
async function loadInitialData() {
try {
const [itemsRes, vendorsRes] = await Promise.all([
api('/purchase-requests/consumable-items'),
api('/purchase-requests/vendors')
]);
consumableItems = itemsRes.data || [];
vendorsList = vendorsRes.data || [];
populateItemSelect();
populateVendorSelect();
} catch (e) {
console.error('초기 데이터 로드 실패:', e);
}
}
function populateItemSelect() {
const sel = document.getElementById('prItemSelect');
const groups = {};
consumableItems.forEach(item => {
const cat = CAT_LABELS[item.category] || item.category;
if (!groups[cat]) groups[cat] = [];
groups[cat].push(item);
});
let html = '<option value="">소모품 선택</option>';
for (const [cat, items] of Object.entries(groups)) {
html += `<optgroup label="${cat}">`;
items.forEach(item => {
const maker = item.maker ? ` (${escapeHtml(item.maker)})` : '';
html += `<option value="${item.item_id}">${escapeHtml(item.item_name)}${maker}</option>`;
});
html += '</optgroup>';
}
sel.innerHTML = html;
}
function populateVendorSelect() {
const sel = document.getElementById('pmVendor');
sel.innerHTML = '<option value="">업체 선택 (선택사항)</option>' +
vendorsList.map(v => `<option value="${v.vendor_id}">${escapeHtml(v.vendor_name)}</option>`).join('');
}
function onItemSelect() {
const itemId = parseInt(document.getElementById('prItemSelect').value);
const preview = document.getElementById('prItemPreview');
const item = consumableItems.find(i => i.item_id === itemId);
if (!item) { preview.classList.add('hidden'); return; }
preview.classList.remove('hidden');
const photoEl = document.getElementById('prItemPhoto');
if (item.photo_path) {
photoEl.src = TKUSER_BASE_URL + item.photo_path;
photoEl.classList.remove('hidden');
photoEl.onerror = () => photoEl.classList.add('hidden');
} else {
photoEl.classList.add('hidden');
}
document.getElementById('prItemInfo').textContent = `${item.item_name} ${item.maker ? '(' + item.maker + ')' : ''}`;
const price = item.base_price ? Number(item.base_price).toLocaleString() + '원/' + (item.unit || 'EA') : '기준가 미설정';
document.getElementById('prItemPrice').textContent = price;
}
/* ===== 구매신청 제출 ===== */
async function submitPurchaseRequest() {
const item_id = document.getElementById('prItemSelect').value;
const quantity = parseInt(document.getElementById('prQuantity').value) || 0;
const notes = document.getElementById('prNotes').value.trim();
if (!item_id) { showToast('소모품을 선택해주세요.', 'error'); return; }
if (quantity < 1) { showToast('수량은 1 이상이어야 합니다.', 'error'); return; }
try {
await api('/purchase-requests', {
method: 'POST',
body: JSON.stringify({ item_id: parseInt(item_id), quantity, notes })
});
showToast('구매신청이 등록되었습니다.');
document.getElementById('prItemSelect').value = '';
document.getElementById('prQuantity').value = '1';
document.getElementById('prNotes').value = '';
document.getElementById('prItemPreview').classList.add('hidden');
await loadRequests();
} catch (e) { showToast(e.message, 'error'); }
}
/* ===== 신청 목록 ===== */
async function loadRequests() {
try {
const status = document.getElementById('prFilterStatus').value;
const category = document.getElementById('prFilterCategory').value;
const params = new URLSearchParams();
if (status) params.set('status', status);
if (category) params.set('category', category);
const res = await api('/purchase-requests?' + params.toString());
requestsList = res.data || [];
renderRequests();
} catch (e) {
document.getElementById('prRequestList').innerHTML = `<tr><td colspan="7" class="px-4 py-8 text-center text-red-500">${escapeHtml(e.message)}</td></tr>`;
}
}
function renderRequests() {
const tbody = document.getElementById('prRequestList');
if (!requestsList.length) {
tbody.innerHTML = '<tr><td colspan="7" class="px-4 py-8 text-center text-gray-400">구매신청 내역이 없습니다.</td></tr>';
return;
}
tbody.innerHTML = requestsList.map(r => {
const catLabel = CAT_LABELS[r.category] || r.category;
const catColor = CAT_COLORS[r.category] || 'badge-gray';
const statusLabel = STATUS_LABELS[r.status] || r.status;
const statusColor = STATUS_COLORS[r.status] || 'badge-gray';
const photoSrc = r.photo_path ? TKUSER_BASE_URL + r.photo_path : '';
let actions = '';
if (isAdmin && r.status === 'pending') {
actions = `<button onclick="openPurchaseModal(${r.request_id})" class="px-2 py-1 bg-orange-500 text-white rounded text-xs hover:bg-orange-600 mr-1" title="구매 처리"><i class="fas fa-shopping-cart"></i></button>
<button onclick="openHoldModal(${r.request_id})" class="px-2 py-1 bg-gray-400 text-white rounded text-xs hover:bg-gray-500" title="보류"><i class="fas fa-pause"></i></button>`;
} else if (isAdmin && r.status === 'hold') {
actions = `<button onclick="revertRequest(${r.request_id})" class="px-2 py-1 bg-blue-500 text-white rounded text-xs hover:bg-blue-600" title="대기로 되돌리기"><i class="fas fa-undo"></i></button>`;
}
if (r.status === 'pending' && (isAdmin || r.requester_id === currentUser.id)) {
actions += ` <button onclick="deleteRequest(${r.request_id})" class="px-2 py-1 bg-red-400 text-white rounded text-xs hover:bg-red-500" title="삭제"><i class="fas fa-trash"></i></button>`;
}
return `<tr class="hover:bg-gray-50">
<td class="px-4 py-3">
<div class="flex items-center gap-2">
${photoSrc ? `<img src="${photoSrc}" class="w-8 h-8 rounded object-cover" onerror="this.style.display='none'">` : ''}
<div>
<div class="font-medium text-gray-800">${escapeHtml(r.item_name)}</div>
<div class="text-xs text-gray-500">${escapeHtml(r.maker || '')}</div>
</div>
</div>
</td>
<td class="px-4 py-3"><span class="badge ${catColor}">${catLabel}</span></td>
<td class="px-4 py-3 text-right font-medium">${r.quantity}</td>
<td class="px-4 py-3 text-gray-600">${escapeHtml(r.requester_name || '')}</td>
<td class="px-4 py-3 text-gray-600">${formatDate(r.request_date)}</td>
<td class="px-4 py-3 text-center">
<span class="badge ${statusColor}">${statusLabel}</span>
${r.status === 'hold' && r.hold_reason ? `<div class="text-xs text-gray-400 mt-1">${escapeHtml(r.hold_reason)}</div>` : ''}
</td>
<td class="px-4 py-3 text-center">${actions}</td>
</tr>`;
}).join('');
}
/* ===== 구매 처리 모달 ===== */
function openPurchaseModal(requestId) {
const r = requestsList.find(x => x.request_id === requestId);
if (!r) return;
currentRequestForPurchase = r;
const basePrice = r.base_price ? Number(r.base_price).toLocaleString() + '원' : '-';
document.getElementById('purchaseModalInfo').innerHTML = `
<div class="font-medium">${escapeHtml(r.item_name)} ${r.maker ? '(' + escapeHtml(r.maker) + ')' : ''}</div>
<div class="text-xs text-gray-500 mt-1">분류: ${CAT_LABELS[r.category] || r.category} | 기준가: ${basePrice} | 신청수량: ${r.quantity}</div>
`;
document.getElementById('pmUnitPrice').value = r.base_price || '';
document.getElementById('pmQuantity').value = r.quantity;
document.getElementById('pmDate').value = new Date().toISOString().substring(0, 10);
document.getElementById('pmNotes').value = '';
document.getElementById('pmPriceDiffArea').innerHTML = '';
document.getElementById('purchaseModal').classList.remove('hidden');
showPriceDiff();
}
function closePurchaseModal() {
document.getElementById('purchaseModal').classList.add('hidden');
currentRequestForPurchase = null;
}
function showPriceDiff() {
if (!currentRequestForPurchase) return;
const basePrice = Number(currentRequestForPurchase.base_price) || 0;
const unitPrice = Number(document.getElementById('pmUnitPrice').value) || 0;
const area = document.getElementById('pmPriceDiffArea');
if (basePrice > 0 && unitPrice > 0 && basePrice !== unitPrice) {
const diff = unitPrice - basePrice;
const arrow = diff > 0 ? '&#9650;' : '&#9660;';
const color = diff > 0 ? 'text-red-600' : 'text-blue-600';
area.innerHTML = `
<div class="flex items-center gap-2 text-sm ${color}">
<span>기준가 ${basePrice.toLocaleString()}원 &rarr; 실구매가 ${unitPrice.toLocaleString()}${arrow}${Math.abs(diff).toLocaleString()}</span>
</div>
<label class="flex items-center gap-2 mt-1 cursor-pointer">
<input type="checkbox" id="pmUpdateBasePrice" class="h-4 w-4 rounded">
<span class="text-xs text-gray-600">기준가를 ${unitPrice.toLocaleString()}원으로 업데이트</span>
</label>`;
} else {
area.innerHTML = '';
}
}
async function submitPurchase() {
if (!currentRequestForPurchase) return;
const unit_price = Number(document.getElementById('pmUnitPrice').value);
const purchase_date = document.getElementById('pmDate').value;
if (!unit_price) { showToast('구매 단가를 입력해주세요.', 'error'); return; }
if (!purchase_date) { showToast('구매일을 입력해주세요.', 'error'); return; }
const updateCheckbox = document.getElementById('pmUpdateBasePrice');
const body = {
request_id: currentRequestForPurchase.request_id,
item_id: currentRequestForPurchase.item_id,
vendor_id: parseInt(document.getElementById('pmVendor').value) || null,
quantity: parseInt(document.getElementById('pmQuantity').value) || currentRequestForPurchase.quantity,
unit_price,
purchase_date,
update_base_price: updateCheckbox ? updateCheckbox.checked : false,
notes: document.getElementById('pmNotes').value.trim()
};
try {
const res = await api('/purchases', { method: 'POST', body: JSON.stringify(body) });
let msg = '구매 처리가 완료되었습니다.';
if (res.data?.equipment?.success) msg += ` 설비 ${res.data.equipment.equipment_code} 자동 등록됨.`;
else if (res.data?.equipment && !res.data.equipment.success) msg += ' (설비 자동 등록 실패 - 수동 등록 필요)';
showToast(msg);
closePurchaseModal();
await loadRequests();
} catch (e) { showToast(e.message, 'error'); }
}
/* ===== 보류 모달 ===== */
function openHoldModal(requestId) {
currentRequestForHold = requestId;
document.getElementById('holdReason').value = '';
document.getElementById('holdModal').classList.remove('hidden');
}
function closeHoldModal() {
document.getElementById('holdModal').classList.add('hidden');
currentRequestForHold = null;
}
async function submitHold() {
if (!currentRequestForHold) return;
const hold_reason = document.getElementById('holdReason').value.trim();
try {
await api(`/purchase-requests/${currentRequestForHold}/hold`, {
method: 'PUT',
body: JSON.stringify({ hold_reason })
});
showToast('보류 처리되었습니다.');
closeHoldModal();
await loadRequests();
} catch (e) { showToast(e.message, 'error'); }
}
/* ===== 기타 액션 ===== */
async function revertRequest(requestId) {
if (!confirm('이 신청을 대기 상태로 되돌리시겠습니까?')) return;
try {
await api(`/purchase-requests/${requestId}/revert`, { method: 'PUT' });
showToast('대기 상태로 되돌렸습니다.');
await loadRequests();
} catch (e) { showToast(e.message, 'error'); }
}
async function deleteRequest(requestId) {
if (!confirm('이 구매신청을 삭제하시겠습니까?')) return;
try {
await api(`/purchase-requests/${requestId}`, { method: 'DELETE' });
showToast('삭제되었습니다.');
await loadRequests();
} catch (e) { showToast(e.message, 'error'); }
}
/* ===== Init ===== */
(async function() {
if (!await initAuth()) return;
isAdmin = currentUser && ['admin', 'system', 'system admin'].includes(currentUser.role);
await loadInitialData();
await loadRequests();
})();

View File

@@ -119,6 +119,10 @@ const NAV_MENU = [
{ href: '/pages/attendance/checkin.html', icon: 'fa-user-check', label: '출근 체크', key: 'inspection.checkin' },
{ href: '/pages/attendance/work-status.html', icon: 'fa-briefcase', label: '근무 현황', key: 'inspection.work_status' },
]},
{ cat: '구매 관리', items: [
{ href: '/pages/purchase/request.html', icon: 'fa-shopping-cart', label: '구매신청', key: 'purchase.request' },
{ href: '/pages/admin/purchase-analysis.html', icon: 'fa-chart-line', label: '구매 분석', key: 'purchase.analysis', admin: true },
]},
{ cat: '근태 관리', items: [
{ href: '/pages/attendance/my-vacation-info.html', icon: 'fa-info-circle', label: '내 연차 정보', key: 'attendance.my_vacation_info' },
{ href: '/pages/attendance/monthly.html', icon: 'fa-calendar', label: '월간 근태', key: 'attendance.monthly' },