- 모바일 검색 결과에 품목 사진 썸네일 표시 (photo_path 있으면 이미지, 없으면 아이콘) - 데스크탑 검색 드롭다운에도 사진 썸네일 추가 - 신규 품목 등록 시 사진 촬영 → consumable_items.photo_path에 저장 (bulk API) - 기존 품목에 사진 없을 때 장바구니에서 "품목 사진 등록" → PUT /consumable-items/:id/photo - imageUploadService에 consumables 디렉토리 추가 - HEIC 변환 + 폴백 지원 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
780 lines
36 KiB
JavaScript
780 lines
36 KiB
JavaScript
/* ===== 소모품 신청 페이지 ===== */
|
|
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 CAT_BG = { consumable: '#dbeafe', safety: '#dcfce7', repair: '#fef3c7', equipment: '#f3e8ff' };
|
|
const CAT_FG = { consumable: '#1e40af', safety: '#166534', repair: '#92400e', equipment: '#7e22ce' };
|
|
const STATUS_LABELS = { pending: '대기', grouped: '구매진행중', purchased: '구매완료', received: '입고완료', cancelled: '취소', returned: '반품', hold: '보류' };
|
|
const STATUS_COLORS = { pending: 'badge-amber', grouped: 'badge-blue', purchased: 'badge-green', received: 'badge-teal', cancelled: 'badge-red', returned: 'badge-red', hold: 'badge-gray' };
|
|
|
|
function _fmtSpec(spec) { return spec ? ' [' + spec + ']' : ''; }
|
|
|
|
let consumableItems = [];
|
|
let vendorsList = [];
|
|
let requestsList = [];
|
|
let currentRequestForPurchase = null;
|
|
let currentRequestForHold = null;
|
|
let isAdmin = false;
|
|
let photoBase64 = null;
|
|
let searchDebounceTimer = null;
|
|
let dropdownActiveIndex = -1;
|
|
let selectedRequestIds = new Set();
|
|
let batchesVisible = 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 || [];
|
|
populateVendorSelect();
|
|
} catch (e) {
|
|
console.error('초기 데이터 로드 실패:', e);
|
|
}
|
|
}
|
|
|
|
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 initItemSearch() {
|
|
const input = document.getElementById('prItemSearch');
|
|
const dropdown = document.getElementById('prItemDropdown');
|
|
|
|
input.addEventListener('input', () => {
|
|
clearTimeout(searchDebounceTimer);
|
|
// 검색어 변경 시 이전 선택 자동 해제
|
|
if (document.getElementById('prItemId').value) {
|
|
document.getElementById('prItemId').value = '';
|
|
document.getElementById('prCustomItemName').value = '';
|
|
document.getElementById('prItemPreview').classList.add('hidden');
|
|
document.getElementById('prCustomCategoryWrap').classList.add('hidden');
|
|
}
|
|
searchDebounceTimer = setTimeout(() => {
|
|
const query = input.value.trim();
|
|
if (query.length === 0) {
|
|
// 빈 입력: 전체 목록 보여주기
|
|
showDropdown(consumableItems.slice(0, 30), '');
|
|
} else {
|
|
const lower = query.toLowerCase();
|
|
const filtered = consumableItems.filter(item =>
|
|
item.item_name.toLowerCase().includes(lower) ||
|
|
(item.maker && item.maker.toLowerCase().includes(lower)) ||
|
|
(item.spec && item.spec.toLowerCase().includes(lower))
|
|
);
|
|
showDropdown(filtered, query);
|
|
}
|
|
}, 200);
|
|
});
|
|
|
|
input.addEventListener('focus', () => {
|
|
const query = input.value.trim();
|
|
if (query.length === 0) {
|
|
showDropdown(consumableItems.slice(0, 30), '');
|
|
} else {
|
|
const lower = query.toLowerCase();
|
|
const filtered = consumableItems.filter(item =>
|
|
item.item_name.toLowerCase().includes(lower) ||
|
|
(item.maker && item.maker.toLowerCase().includes(lower)) ||
|
|
(item.spec && item.spec.toLowerCase().includes(lower))
|
|
);
|
|
showDropdown(filtered, query);
|
|
}
|
|
});
|
|
|
|
input.addEventListener('keydown', (e) => {
|
|
const items = dropdown.querySelectorAll('.item-dropdown-item, .item-dropdown-custom');
|
|
if (e.key === 'ArrowDown') {
|
|
e.preventDefault();
|
|
dropdownActiveIndex = Math.min(dropdownActiveIndex + 1, items.length - 1);
|
|
updateDropdownActive(items);
|
|
} else if (e.key === 'ArrowUp') {
|
|
e.preventDefault();
|
|
dropdownActiveIndex = Math.max(dropdownActiveIndex - 1, 0);
|
|
updateDropdownActive(items);
|
|
} else if (e.key === 'Enter') {
|
|
e.preventDefault();
|
|
if (dropdownActiveIndex >= 0 && dropdownActiveIndex < items.length) {
|
|
items[dropdownActiveIndex].click();
|
|
}
|
|
} else if (e.key === 'Escape') {
|
|
closeDropdown();
|
|
}
|
|
});
|
|
|
|
// 외부 클릭 시 드롭다운 닫기
|
|
document.addEventListener('click', (e) => {
|
|
if (!e.target.closest('#prItemSearch') && !e.target.closest('#prItemDropdown')) {
|
|
closeDropdown();
|
|
}
|
|
});
|
|
}
|
|
|
|
function showDropdown(items, query) {
|
|
const dropdown = document.getElementById('prItemDropdown');
|
|
dropdownActiveIndex = -1;
|
|
|
|
let html = '';
|
|
if (items.length > 0) {
|
|
items.forEach((item, idx) => {
|
|
const catLabel = CAT_LABELS[item.category] || item.category;
|
|
const bg = CAT_BG[item.category] || '#f3f4f6';
|
|
const fg = CAT_FG[item.category] || '#374151';
|
|
const spec = _fmtSpec(item.spec ? escapeHtml(item.spec) : '');
|
|
const maker = item.maker ? ` (${escapeHtml(item.maker)})` : '';
|
|
const photoSrc = item.photo_path ? (item.photo_path.startsWith('http') ? item.photo_path : TKUSER_BASE_URL + item.photo_path) : '';
|
|
html += `<div class="item-dropdown-item" data-item-id="${item.item_id}" onclick="selectItem(${item.item_id})">
|
|
${photoSrc ? `<img src="${photoSrc}" style="width:28px;height:28px;border-radius:4px;object-fit:cover" onerror="this.style.display='none'">` : ''}
|
|
<span class="cat-tag" style="background:${bg};color:${fg}">${catLabel}</span>
|
|
<span>${escapeHtml(item.item_name)}${spec}${maker}</span>
|
|
</div>`;
|
|
});
|
|
}
|
|
|
|
// 직접 입력 옵션 (검색어가 있을 때만)
|
|
if (query.length > 0) {
|
|
html += `<div class="item-dropdown-custom" onclick="selectCustomItem()">
|
|
<i class="fas fa-plus-circle"></i>
|
|
<span>"${escapeHtml(query)}"(으)로 직접 신청</span>
|
|
</div>`;
|
|
}
|
|
|
|
if (html) {
|
|
dropdown.innerHTML = html;
|
|
dropdown.classList.add('open');
|
|
} else {
|
|
closeDropdown();
|
|
}
|
|
}
|
|
|
|
function updateDropdownActive(items) {
|
|
items.forEach((el, idx) => {
|
|
el.classList.toggle('active', idx === dropdownActiveIndex);
|
|
if (idx === dropdownActiveIndex) el.scrollIntoView({ block: 'nearest' });
|
|
});
|
|
}
|
|
|
|
function closeDropdown() {
|
|
document.getElementById('prItemDropdown').classList.remove('open');
|
|
dropdownActiveIndex = -1;
|
|
}
|
|
|
|
function selectItem(itemId) {
|
|
const item = consumableItems.find(i => i.item_id === itemId);
|
|
if (!item) return;
|
|
|
|
const input = document.getElementById('prItemSearch');
|
|
input.value = item.item_name + _fmtSpec(item.spec) + (item.maker ? ' (' + item.maker + ')' : '');
|
|
document.getElementById('prItemId').value = item.item_id;
|
|
document.getElementById('prCustomItemName').value = '';
|
|
closeDropdown();
|
|
|
|
// 미리보기
|
|
const preview = document.getElementById('prItemPreview');
|
|
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}${_fmtSpec(item.spec)} ${item.maker ? '(' + item.maker + ')' : ''}`;
|
|
const price = item.base_price ? Number(item.base_price).toLocaleString() + '원/' + (item.unit || 'EA') : '기준가 미설정';
|
|
document.getElementById('prItemPrice').textContent = price;
|
|
|
|
// 분류 선택 숨김
|
|
document.getElementById('prCustomCategoryWrap').classList.add('hidden');
|
|
}
|
|
|
|
function selectCustomItem() {
|
|
const input = document.getElementById('prItemSearch');
|
|
const customName = input.value.trim();
|
|
if (!customName) return;
|
|
|
|
document.getElementById('prItemId').value = '';
|
|
document.getElementById('prCustomItemName').value = customName;
|
|
closeDropdown();
|
|
|
|
// 미리보기 숨기고 분류 선택 표시
|
|
document.getElementById('prItemPreview').classList.add('hidden');
|
|
document.getElementById('prCustomCategoryWrap').classList.remove('hidden');
|
|
}
|
|
|
|
/* ===== 사진 첨부 ===== */
|
|
async function onPhotoSelected(inputEl) {
|
|
const file = inputEl.files[0];
|
|
if (!file) return;
|
|
|
|
const statusEl = document.getElementById('prPhotoStatus');
|
|
let processFile = file;
|
|
|
|
// HEIC/HEIF 변환
|
|
const isHeic = file.type === 'image/heic' || file.type === 'image/heif' ||
|
|
file.name.toLowerCase().endsWith('.heic') || file.name.toLowerCase().endsWith('.heif');
|
|
if (isHeic) {
|
|
if (typeof heic2any === 'undefined') {
|
|
showToast('HEIC 변환 라이브러리를 불러오지 못했습니다.', 'error');
|
|
return;
|
|
}
|
|
statusEl.textContent = 'HEIC 변환 중...';
|
|
try {
|
|
const blob = await heic2any({ blob: file, toType: 'image/jpeg', quality: 0.85 });
|
|
processFile = new File([blob], file.name.replace(/\.heic$/i, '.jpg').replace(/\.heif$/i, '.jpg'), { type: 'image/jpeg' });
|
|
} catch (e) {
|
|
console.error('HEIC 변환 실패:', e);
|
|
showToast('HEIC 이미지 변환에 실패했습니다.', 'error');
|
|
statusEl.textContent = '';
|
|
return;
|
|
}
|
|
}
|
|
|
|
// 파일 크기 확인 (10MB)
|
|
if (processFile.size > 10 * 1024 * 1024) {
|
|
showToast('파일 크기는 10MB 이하만 가능합니다.', 'error');
|
|
return;
|
|
}
|
|
|
|
statusEl.textContent = '처리 중...';
|
|
|
|
const reader = new FileReader();
|
|
reader.onload = (e) => {
|
|
photoBase64 = e.target.result;
|
|
document.getElementById('prPhotoPreviewImg').src = photoBase64;
|
|
document.getElementById('prPhotoPreview').classList.remove('hidden');
|
|
statusEl.textContent = '';
|
|
};
|
|
reader.readAsDataURL(processFile);
|
|
}
|
|
|
|
function removePhoto() {
|
|
photoBase64 = null;
|
|
document.getElementById('prPhotoPreview').classList.add('hidden');
|
|
document.getElementById('prPhotoInput').value = '';
|
|
document.getElementById('prPhotoStatus').textContent = '';
|
|
}
|
|
|
|
/* ===== 소모품 신청 제출 ===== */
|
|
async function submitPurchaseRequest() {
|
|
const itemId = document.getElementById('prItemId').value;
|
|
const customItemName = document.getElementById('prCustomItemName').value;
|
|
const quantity = parseInt(document.getElementById('prQuantity').value) || 0;
|
|
const notes = document.getElementById('prNotes').value.trim();
|
|
|
|
if (!itemId && !customItemName) { showToast('소모품을 선택하거나 품목명을 입력해주세요.', 'error'); return; }
|
|
if (quantity < 1) { showToast('수량은 1 이상이어야 합니다.', 'error'); return; }
|
|
|
|
const body = { quantity, notes };
|
|
if (itemId) {
|
|
body.item_id = parseInt(itemId);
|
|
} else {
|
|
body.custom_item_name = customItemName;
|
|
body.custom_category = document.getElementById('prCustomCategory').value;
|
|
}
|
|
if (photoBase64) {
|
|
body.photo = photoBase64;
|
|
}
|
|
|
|
try {
|
|
await api('/purchase-requests', {
|
|
method: 'POST',
|
|
body: JSON.stringify(body)
|
|
});
|
|
showToast('소모품 신청이 등록되었습니다.');
|
|
// 폼 초기화
|
|
document.getElementById('prItemSearch').value = '';
|
|
document.getElementById('prItemId').value = '';
|
|
document.getElementById('prCustomItemName').value = '';
|
|
document.getElementById('prQuantity').value = '1';
|
|
document.getElementById('prNotes').value = '';
|
|
document.getElementById('prItemPreview').classList.add('hidden');
|
|
document.getElementById('prCustomCategoryWrap').classList.add('hidden');
|
|
removePhoto();
|
|
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');
|
|
selectedRequestIds.clear();
|
|
updateSelectedCount();
|
|
|
|
// admin이면 체크박스 열 보이기, 그룹 버튼 보이기
|
|
if (isAdmin) {
|
|
document.getElementById('thCheckbox').style.display = '';
|
|
document.getElementById('batchActions').classList.remove('hidden');
|
|
document.getElementById('batchViewBtn').classList.remove('hidden');
|
|
}
|
|
|
|
if (!requestsList.length) {
|
|
tbody.innerHTML = `<tr><td colspan="${isAdmin ? 8 : 7}" class="px-4 py-8 text-center text-gray-400">소모품 신청 내역이 없습니다.</td></tr>`;
|
|
return;
|
|
}
|
|
tbody.innerHTML = requestsList.map(r => {
|
|
// 등록 품목이면 ci 데이터, 미등록이면 custom 데이터 사용
|
|
const itemName = r.item_name || r.custom_item_name || '-';
|
|
const category = r.category || r.custom_category;
|
|
const catLabel = CAT_LABELS[category] || category || '-';
|
|
const catColor = CAT_COLORS[category] || 'badge-gray';
|
|
const statusLabel = STATUS_LABELS[r.status] || r.status;
|
|
const statusColor = STATUS_COLORS[r.status] || 'badge-gray';
|
|
const isCustom = !r.item_id && r.custom_item_name;
|
|
|
|
// 사진: 구매신청 첨부 사진 우선, 없으면 소모품 마스터 사진
|
|
let photoSrc = '';
|
|
if (r.pr_photo_path) {
|
|
photoSrc = r.pr_photo_path;
|
|
} else if (r.ci_photo_path) {
|
|
photoSrc = TKUSER_BASE_URL + r.ci_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 === 'grouped') {
|
|
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 === 'purchased') {
|
|
actions = `<button onclick="openReceiveModal(${r.request_id})" class="px-2 py-1 bg-teal-500 text-white rounded text-xs hover:bg-teal-600 mr-1" title="입고 처리"><i class="fas fa-box-open"></i></button>
|
|
<button onclick="cancelPurchase(${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-times"></i></button>`;
|
|
} else if (isAdmin && r.status === 'received') {
|
|
actions = `<button onclick="returnItem(${r.request_id})" class="px-2 py-1 bg-red-500 text-white rounded text-xs hover:bg-red-600" title="반품"><i class="fas fa-undo-alt"></i></button>`;
|
|
} else if (isAdmin && r.status === 'cancelled') {
|
|
actions = `<button onclick="revertCancel(${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>`;
|
|
} 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>`;
|
|
}
|
|
|
|
const cbCell = isAdmin && r.status === 'pending'
|
|
? `<td class="px-2 py-3 text-center" style="${isAdmin ? '' : 'display:none'}"><input type="checkbox" class="request-cb h-4 w-4" data-id="${r.request_id}" onchange="onRequestChecked()"></td>`
|
|
: `<td class="px-2 py-3" style="${isAdmin ? '' : 'display:none'}"></td>`;
|
|
|
|
return `<tr class="hover:bg-gray-50">
|
|
${cbCell}
|
|
<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(itemName)}${r.spec ? ' <span class="text-gray-400">[' + escapeHtml(r.spec) + ']</span>' : ''}${isCustom ? ' <span class="text-xs text-orange-500">(직접입력)</span>' : ''}</div>
|
|
<div class="text-xs text-gray-500">${escapeHtml(r.maker || '')}${r.batch_name ? ' <span class="text-blue-500"><i class="fas fa-layer-group"></i> ' + escapeHtml(r.batch_name) + '</span>' : ''}</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 itemName = r.item_name || r.custom_item_name || '-';
|
|
const category = r.category || r.custom_category;
|
|
const isCustom = !r.item_id && r.custom_item_name;
|
|
const basePrice = r.base_price ? Number(r.base_price).toLocaleString() + '원' : '-';
|
|
|
|
document.getElementById('purchaseModalInfo').innerHTML = `
|
|
<div class="font-medium">${escapeHtml(itemName)}${_fmtSpec(r.spec ? escapeHtml(r.spec) : '')} ${r.maker ? '(' + escapeHtml(r.maker) + ')' : ''}${isCustom ? ' <span class="text-orange-500 text-xs">(직접입력)</span>' : ''}</div>
|
|
<div class="text-xs text-gray-500 mt-1">분류: ${CAT_LABELS[category] || category || '-'} | 기준가: ${basePrice} | 신청수량: ${r.quantity}</div>
|
|
${r.pr_photo_path ? `<img src="${r.pr_photo_path}" class="mt-2 w-20 h-20 rounded object-cover" onerror="this.style.display='none'">` : ''}
|
|
`;
|
|
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 = '';
|
|
|
|
// 마스터 등록 체크박스: 미등록 품목일 때만 표시
|
|
const masterWrap = document.getElementById('pmMasterRegisterWrap');
|
|
if (isCustom) {
|
|
masterWrap.classList.remove('hidden');
|
|
document.getElementById('pmRegisterToMaster').checked = true;
|
|
} else {
|
|
masterWrap.classList.add('hidden');
|
|
}
|
|
|
|
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 ? '▲' : '▼';
|
|
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()}원 → 실구매가 ${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 registerCheckbox = document.getElementById('pmRegisterToMaster');
|
|
const isCustom = !currentRequestForPurchase.item_id && currentRequestForPurchase.custom_item_name;
|
|
|
|
const body = {
|
|
request_id: currentRequestForPurchase.request_id,
|
|
item_id: currentRequestForPurchase.item_id || null,
|
|
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,
|
|
register_to_master: isCustom ? (registerCheckbox ? registerCheckbox.checked : true) : undefined,
|
|
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'); }
|
|
}
|
|
|
|
/* ===== 그룹화 기능 ===== */
|
|
function onRequestChecked() {
|
|
selectedRequestIds.clear();
|
|
document.querySelectorAll('.request-cb:checked').forEach(cb => {
|
|
selectedRequestIds.add(parseInt(cb.dataset.id));
|
|
});
|
|
updateSelectedCount();
|
|
}
|
|
|
|
function updateSelectedCount() {
|
|
const el = document.getElementById('selectedCount');
|
|
if (el) el.textContent = selectedRequestIds.size + '건 선택';
|
|
}
|
|
|
|
function toggleSelectAll(masterCb) {
|
|
document.querySelectorAll('.request-cb').forEach(cb => {
|
|
cb.checked = masterCb.checked;
|
|
});
|
|
onRequestChecked();
|
|
}
|
|
|
|
function openBatchCreateModal() {
|
|
if (selectedRequestIds.size === 0) { showToast('그룹에 포함할 신청 건을 선택해주세요.', 'error'); return; }
|
|
document.getElementById('batchSelectedInfo').textContent = `${selectedRequestIds.size}건의 신청을 그룹으로 묶습니다.`;
|
|
document.getElementById('bcName').value = '';
|
|
document.getElementById('bcCategory').value = '';
|
|
document.getElementById('bcNotes').value = '';
|
|
// 업체 셀렉트 채우기
|
|
const sel = document.getElementById('bcVendor');
|
|
sel.innerHTML = '<option value="">업체 선택</option>' +
|
|
vendorsList.map(v => `<option value="${v.vendor_id}">${escapeHtml(v.vendor_name)}</option>`).join('');
|
|
document.getElementById('batchCreateModal').classList.remove('hidden');
|
|
}
|
|
|
|
function closeBatchCreateModal() {
|
|
document.getElementById('batchCreateModal').classList.add('hidden');
|
|
}
|
|
|
|
async function submitBatchCreate() {
|
|
const body = {
|
|
batch_name: document.getElementById('bcName').value.trim() || null,
|
|
category: document.getElementById('bcCategory').value || null,
|
|
vendor_id: parseInt(document.getElementById('bcVendor').value) || null,
|
|
notes: document.getElementById('bcNotes').value.trim() || null,
|
|
request_ids: Array.from(selectedRequestIds)
|
|
};
|
|
try {
|
|
await api('/purchase-batches', { method: 'POST', body: JSON.stringify(body) });
|
|
showToast('구매 그룹이 생성되었습니다.');
|
|
closeBatchCreateModal();
|
|
selectedRequestIds.clear();
|
|
await loadRequests();
|
|
if (batchesVisible) await loadBatches();
|
|
} catch (e) { showToast(e.message, 'error'); }
|
|
}
|
|
|
|
function toggleBatchView() {
|
|
batchesVisible = !batchesVisible;
|
|
document.getElementById('batchView').classList.toggle('hidden', !batchesVisible);
|
|
if (batchesVisible) loadBatches();
|
|
}
|
|
|
|
async function loadBatches() {
|
|
try {
|
|
const res = await api('/purchase-batches');
|
|
const batches = res.data || [];
|
|
const container = document.getElementById('batchList');
|
|
if (!batches.length) {
|
|
container.innerHTML = '<div class="text-gray-400 text-center py-4">생성된 그룹이 없습니다.</div>';
|
|
return;
|
|
}
|
|
const BATCH_STATUS = { pending: { label: '진행중', color: 'badge-blue' }, purchased: { label: '구매완료', color: 'badge-green' }, received: { label: '입고완료', color: 'badge-teal' } };
|
|
container.innerHTML = batches.map(b => {
|
|
const s = BATCH_STATUS[b.status] || { label: b.status, color: 'badge-gray' };
|
|
return `<div class="flex items-center justify-between p-3 border rounded-lg hover:bg-gray-50">
|
|
<div>
|
|
<span class="font-medium">${escapeHtml(b.batch_name || '그룹 #' + b.batch_id)}</span>
|
|
<span class="badge ${s.color} ml-2">${s.label}</span>
|
|
<span class="text-xs text-gray-400 ml-2">${b.request_count || 0}건</span>
|
|
${b.vendor_name ? `<span class="text-xs text-gray-400 ml-1">· ${escapeHtml(b.vendor_name)}</span>` : ''}
|
|
</div>
|
|
<div class="flex gap-1">
|
|
${b.status === 'pending' ? `<button onclick="batchPurchase(${b.batch_id})" class="px-2 py-1 bg-orange-500 text-white rounded text-xs hover:bg-orange-600" title="일괄 구매"><i class="fas fa-shopping-cart"></i></button>
|
|
<button onclick="batchDelete(${b.batch_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>` : ''}
|
|
${b.status === 'purchased' ? `<button onclick="batchReceive(${b.batch_id})" class="px-2 py-1 bg-teal-500 text-white rounded text-xs hover:bg-teal-600" title="일괄 입고"><i class="fas fa-box-open"></i></button>` : ''}
|
|
</div>
|
|
</div>`;
|
|
}).join('');
|
|
} catch (e) { console.error('그룹 목록 로드 실패:', e); }
|
|
}
|
|
|
|
async function batchPurchase(batchId) {
|
|
if (!confirm('이 그룹의 모든 신청을 구매완료 처리하시겠습니까?')) return;
|
|
try {
|
|
await api(`/purchase-batches/${batchId}/purchase`, { method: 'POST' });
|
|
showToast('일괄 구매 처리 완료.');
|
|
await Promise.all([loadRequests(), loadBatches()]);
|
|
} catch (e) { showToast(e.message, 'error'); }
|
|
}
|
|
|
|
async function batchDelete(batchId) {
|
|
if (!confirm('이 그룹을 삭제하시겠습니까? 포함된 신청은 대기 상태로 복원됩니다.')) return;
|
|
try {
|
|
await api(`/purchase-batches/${batchId}`, { method: 'DELETE' });
|
|
showToast('그룹이 삭제되었습니다.');
|
|
await Promise.all([loadRequests(), loadBatches()]);
|
|
} catch (e) { showToast(e.message, 'error'); }
|
|
}
|
|
|
|
async function batchReceive(batchId) {
|
|
// 간단한 입고 — 위치만 입력
|
|
const location = prompt('보관 위치를 입력하세요 (선택):');
|
|
if (location === null) return; // 취소
|
|
try {
|
|
await api(`/purchase-batches/${batchId}/receive`, {
|
|
method: 'PUT',
|
|
body: JSON.stringify({ received_location: location || null })
|
|
});
|
|
showToast('일괄 입고 처리 완료.');
|
|
await Promise.all([loadRequests(), loadBatches()]);
|
|
} catch (e) { showToast(e.message, 'error'); }
|
|
}
|
|
|
|
/* ===== 구매 취소 / 반품 / 되돌리기 ===== */
|
|
async function cancelPurchase(requestId) {
|
|
const reason = prompt('취소 사유를 입력하세요 (선택):');
|
|
if (reason === null) return;
|
|
try {
|
|
await api(`/purchase-requests/${requestId}/cancel`, {
|
|
method: 'PUT', body: JSON.stringify({ cancel_reason: reason || null })
|
|
});
|
|
showToast('구매가 취소되었습니다.');
|
|
await loadRequests();
|
|
} catch (e) { showToast(e.message, 'error'); }
|
|
}
|
|
|
|
async function returnItem(requestId) {
|
|
const reason = prompt('반품 사유를 입력하세요:');
|
|
if (reason === null) return;
|
|
try {
|
|
await api(`/purchase-requests/${requestId}/return`, {
|
|
method: 'PUT', body: JSON.stringify({ cancel_reason: reason || null })
|
|
});
|
|
showToast('반품 처리되었습니다.');
|
|
await loadRequests();
|
|
} catch (e) { showToast(e.message, 'error'); }
|
|
}
|
|
|
|
async function revertCancel(requestId) {
|
|
if (!confirm('이 신청을 대기 상태로 되돌리시겠습니까?')) return;
|
|
try {
|
|
await api(`/purchase-requests/${requestId}/revert-cancel`, { method: 'PUT' });
|
|
showToast('대기 상태로 되돌렸습니다.');
|
|
await loadRequests();
|
|
} catch (e) { showToast(e.message, 'error'); }
|
|
}
|
|
|
|
/* ===== 입고 처리 모달 ===== */
|
|
let currentRequestForReceive = null;
|
|
let receivePhotoBase64 = null;
|
|
|
|
function openReceiveModal(requestId) {
|
|
const r = requestsList.find(x => x.request_id === requestId);
|
|
if (!r) return;
|
|
currentRequestForReceive = r;
|
|
const itemName = r.item_name || r.custom_item_name || '-';
|
|
document.getElementById('receiveModalInfo').innerHTML = `
|
|
<div class="font-medium">${escapeHtml(itemName)}</div>
|
|
<div class="text-xs text-gray-500 mt-1">수량: ${r.quantity} | 신청자: ${escapeHtml(r.requester_name || '')}</div>
|
|
`;
|
|
document.getElementById('rcLocation').value = '';
|
|
receivePhotoBase64 = null;
|
|
document.getElementById('rcPhotoPreview').classList.add('hidden');
|
|
document.getElementById('rcPhotoInput').value = '';
|
|
document.getElementById('receiveModal').classList.remove('hidden');
|
|
}
|
|
|
|
function closeReceiveModal() {
|
|
document.getElementById('receiveModal').classList.add('hidden');
|
|
currentRequestForReceive = null;
|
|
receivePhotoBase64 = null;
|
|
}
|
|
|
|
async function onReceivePhotoSelected(inputEl) {
|
|
const file = inputEl.files[0];
|
|
if (!file) return;
|
|
let processFile = file;
|
|
const isHeic = file.type === 'image/heic' || file.type === 'image/heif' ||
|
|
file.name.toLowerCase().endsWith('.heic') || file.name.toLowerCase().endsWith('.heif');
|
|
if (isHeic && typeof heic2any !== 'undefined') {
|
|
try {
|
|
const blob = await heic2any({ blob: file, toType: 'image/jpeg', quality: 0.85 });
|
|
processFile = new File([blob], file.name.replace(/\.hei[cf]$/i, '.jpg'), { type: 'image/jpeg' });
|
|
} catch (e) {
|
|
// 변환 실패 시 원본 시도
|
|
console.warn('HEIC 변환 실패, 원본 사용:', e);
|
|
}
|
|
}
|
|
if (processFile.size > 10 * 1024 * 1024) { showToast('파일 크기는 10MB 이하만 가능합니다.', 'error'); return; }
|
|
const reader = new FileReader();
|
|
reader.onload = (e) => {
|
|
receivePhotoBase64 = e.target.result;
|
|
document.getElementById('rcPhotoPreviewImg').src = receivePhotoBase64;
|
|
document.getElementById('rcPhotoPreview').classList.remove('hidden');
|
|
};
|
|
reader.readAsDataURL(processFile);
|
|
}
|
|
|
|
async function submitReceive() {
|
|
if (!currentRequestForReceive) return;
|
|
const received_location = document.getElementById('rcLocation').value.trim();
|
|
const body = { received_location };
|
|
if (receivePhotoBase64) body.photo = receivePhotoBase64;
|
|
|
|
try {
|
|
await api(`/purchase-requests/${currentRequestForReceive.request_id}/receive`, {
|
|
method: 'PUT',
|
|
body: JSON.stringify(body)
|
|
});
|
|
showToast('입고 처리가 완료되었습니다.');
|
|
closeReceiveModal();
|
|
await loadRequests();
|
|
} catch (e) { showToast(e.message, 'error'); }
|
|
}
|
|
|
|
/* ===== Init ===== */
|
|
(async function() {
|
|
if (!await initAuth()) return;
|
|
isAdmin = currentUser && ['admin', 'system', 'system admin'].includes(currentUser.role);
|
|
initItemSearch();
|
|
await loadInitialData();
|
|
await loadRequests();
|
|
})();
|