feat(purchase): 소모품 신청 시스템 v2 — 모바일 최적화, 스마트 검색, 그룹화, 입고 알림
- 4단계 상태 플로우: pending → grouped → purchased → received - 한국어 스마트 검색: 초성 매칭(ㅁㅈㄱ→면장갑), 별칭 테이블, 인메모리 캐시 - 모바일 전용 신청 페이지: 바텀시트 UI, FAB, 카드 리스트, 스크롤 페이지네이션 - 인라인 품목 등록: 미등록 품목 검색→등록→신청 단일 트랜잭션 - 관리자 그룹화: 체크박스 다중 선택, 구매 그룹(batch) 생성/일괄 구매/입고 - 입고 처리: 사진+보관위치 등록, 부분 입고 허용, batch 자동 상태 전환 - 알림: notifyHelper에 target_user_ids 추가, 구매진행중/입고완료 시 신청자 ntfy+push Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -42,6 +42,7 @@ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; b
|
||||
.badge-gray { background: #f3f4f6; color: #6b7280; }
|
||||
.badge-orange { background: #fff7ed; color: #c2410c; }
|
||||
.badge-purple { background: #faf5ff; color: #7c3aed; }
|
||||
.badge-teal { background: #f0fdfa; color: #0d9488; }
|
||||
|
||||
/* Collapsible */
|
||||
.collapsible-content { max-height: 0; overflow: hidden; transition: max-height 0.3s ease; }
|
||||
|
||||
393
system1-factory/web/static/js/purchase-request-mobile.js
Normal file
393
system1-factory/web/static/js/purchase-request-mobile.js
Normal file
@@ -0,0 +1,393 @@
|
||||
/* ===== 소모품 신청 모바일 ===== */
|
||||
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 STATUS_LABELS = { pending: '대기', grouped: '구매진행중', purchased: '구매완료', received: '입고완료', hold: '보류' };
|
||||
const STATUS_COLORS = { pending: 'badge-amber', grouped: 'badge-blue', purchased: 'badge-green', received: 'badge-teal', hold: 'badge-gray' };
|
||||
const MATCH_LABELS = { exact: '정확', name: '이름', alias: '별칭', spec: '규격', chosung: '초성', chosung_alias: '초성' };
|
||||
|
||||
let currentPage = 1;
|
||||
let currentStatus = '';
|
||||
let totalPages = 1;
|
||||
let isLoadingMore = false;
|
||||
let requestsList = [];
|
||||
let photoBase64 = null;
|
||||
let searchTimer = null;
|
||||
let isRegisterMode = false;
|
||||
|
||||
/* ===== 상태 탭 필터 ===== */
|
||||
function filterByStatus(btn) {
|
||||
document.querySelectorAll('.pm-tab').forEach(t => t.classList.remove('active'));
|
||||
btn.classList.add('active');
|
||||
currentStatus = btn.dataset.status;
|
||||
currentPage = 1;
|
||||
requestsList = [];
|
||||
loadRequests();
|
||||
}
|
||||
|
||||
/* ===== 신청 목록 로드 ===== */
|
||||
async function loadRequests(append = false) {
|
||||
try {
|
||||
if (!append) {
|
||||
document.getElementById('requestCards').innerHTML = '<div class="pm-loading">불러오는 중...</div>';
|
||||
}
|
||||
const params = new URLSearchParams({ page: currentPage, limit: 20 });
|
||||
if (currentStatus) params.set('status', currentStatus);
|
||||
|
||||
const res = await api('/purchase-requests/my-requests?' + params.toString());
|
||||
const items = res.data || [];
|
||||
totalPages = res.pagination?.totalPages || 1;
|
||||
|
||||
if (append) {
|
||||
requestsList = requestsList.concat(items);
|
||||
} else {
|
||||
requestsList = items;
|
||||
}
|
||||
renderCards();
|
||||
} catch (e) {
|
||||
document.getElementById('requestCards').innerHTML = `<div class="pm-empty"><i class="fas fa-exclamation-circle"></i>${escapeHtml(e.message)}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
function renderCards() {
|
||||
const container = document.getElementById('requestCards');
|
||||
if (!requestsList.length) {
|
||||
container.innerHTML = '<div class="pm-empty"><i class="fas fa-box-open"></i>신청 내역이 없습니다.</div>';
|
||||
return;
|
||||
}
|
||||
container.innerHTML = requestsList.map(r => {
|
||||
const itemName = r.item_name || r.custom_item_name || '-';
|
||||
const category = r.category || r.custom_category;
|
||||
const catLabel = CAT_LABELS[category] || category || '';
|
||||
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;
|
||||
|
||||
return `<div class="pm-card" onclick="openDetail(${r.request_id})">
|
||||
<div class="pm-card-header">
|
||||
<div>
|
||||
<div class="pm-card-name">${escapeHtml(itemName)}${isCustom ? '<span class="pm-card-custom">(직접입력)</span>' : ''}</div>
|
||||
${catLabel ? `<span class="badge ${STATUS_COLORS[category] || 'badge-gray'} mt-1" style="font-size:11px">${catLabel}</span>` : ''}
|
||||
</div>
|
||||
<span class="badge ${statusColor}">${statusLabel}</span>
|
||||
</div>
|
||||
<div class="pm-card-meta">
|
||||
<span>수량: <span class="pm-card-qty">${r.quantity}</span></span>
|
||||
<span>${formatDate(r.request_date)}</span>
|
||||
${r.batch_name ? `<span><i class="fas fa-layer-group"></i> ${escapeHtml(r.batch_name)}</span>` : ''}
|
||||
</div>
|
||||
</div>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
/* ===== 무한 스크롤 ===== */
|
||||
window.addEventListener('scroll', () => {
|
||||
if (isLoadingMore || currentPage >= totalPages) return;
|
||||
if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 200) {
|
||||
isLoadingMore = true;
|
||||
currentPage++;
|
||||
document.getElementById('loadingMore').classList.remove('hidden');
|
||||
loadRequests(true).finally(() => {
|
||||
isLoadingMore = false;
|
||||
document.getElementById('loadingMore').classList.add('hidden');
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/* ===== 상세 바텀시트 ===== */
|
||||
function openDetail(requestId) {
|
||||
const r = requestsList.find(x => x.request_id === requestId);
|
||||
if (!r) return;
|
||||
|
||||
const itemName = r.item_name || r.custom_item_name || '-';
|
||||
const category = r.category || r.custom_category;
|
||||
const catLabel = CAT_LABELS[category] || category || '-';
|
||||
const statusLabel = STATUS_LABELS[r.status] || r.status;
|
||||
const statusColor = STATUS_COLORS[r.status] || 'badge-gray';
|
||||
|
||||
let html = `
|
||||
<div class="text-center mb-4">
|
||||
<div class="text-lg font-bold">${escapeHtml(itemName)}</div>
|
||||
<span class="badge ${statusColor} mt-2">${statusLabel}</span>
|
||||
</div>
|
||||
<div class="pm-detail-row"><span class="pm-detail-label">분류</span><span class="pm-detail-value">${catLabel}</span></div>
|
||||
<div class="pm-detail-row"><span class="pm-detail-label">수량</span><span class="pm-detail-value">${r.quantity}</span></div>
|
||||
<div class="pm-detail-row"><span class="pm-detail-label">신청일</span><span class="pm-detail-value">${formatDate(r.request_date)}</span></div>
|
||||
`;
|
||||
if (r.notes) {
|
||||
html += `<div class="pm-detail-row"><span class="pm-detail-label">메모</span><span class="pm-detail-value">${escapeHtml(r.notes)}</span></div>`;
|
||||
}
|
||||
if (r.batch_name) {
|
||||
html += `<div class="pm-detail-row"><span class="pm-detail-label">구매 그룹</span><span class="pm-detail-value">${escapeHtml(r.batch_name)}</span></div>`;
|
||||
}
|
||||
if (r.hold_reason) {
|
||||
html += `<div class="pm-detail-row"><span class="pm-detail-label">보류 사유</span><span class="pm-detail-value text-red-600">${escapeHtml(r.hold_reason)}</span></div>`;
|
||||
}
|
||||
|
||||
// 입고 정보
|
||||
if (r.status === 'received') {
|
||||
html += `<div class="mt-4 p-3 bg-teal-50 rounded-lg">
|
||||
<div class="text-sm font-semibold text-teal-700 mb-2"><i class="fas fa-box-open mr-1"></i>입고 완료</div>`;
|
||||
if (r.received_location) {
|
||||
html += `<div class="text-sm text-gray-700"><i class="fas fa-map-marker-alt mr-1 text-teal-500"></i>보관위치: ${escapeHtml(r.received_location)}</div>`;
|
||||
}
|
||||
if (r.received_at) {
|
||||
html += `<div class="text-xs text-gray-500 mt-1">${formatDateTime(r.received_at)}${r.received_by_name ? ' · ' + escapeHtml(r.received_by_name) : ''}</div>`;
|
||||
}
|
||||
if (r.received_photo_path) {
|
||||
html += `<img src="${r.received_photo_path}" class="pm-received-photo" onerror="this.style.display='none'">`;
|
||||
}
|
||||
html += `</div>`;
|
||||
}
|
||||
|
||||
// 신청 사진
|
||||
if (r.pr_photo_path) {
|
||||
html += `<div class="mt-3"><div class="text-xs text-gray-500 mb-1">첨부 사진</div><img src="${r.pr_photo_path}" class="pm-received-photo" onerror="this.style.display='none'"></div>`;
|
||||
}
|
||||
|
||||
document.getElementById('detailContent').innerHTML = html;
|
||||
document.getElementById('detailOverlay').classList.add('open');
|
||||
document.getElementById('detailSheet').classList.add('open');
|
||||
}
|
||||
|
||||
function closeDetailSheet() {
|
||||
document.getElementById('detailOverlay').classList.remove('open');
|
||||
document.getElementById('detailSheet').classList.remove('open');
|
||||
}
|
||||
|
||||
/* ===== 신청 바텀시트 ===== */
|
||||
function openRequestSheet() {
|
||||
document.getElementById('requestOverlay').classList.add('open');
|
||||
document.getElementById('requestSheet').classList.add('open');
|
||||
document.getElementById('searchInput').focus();
|
||||
}
|
||||
|
||||
function closeRequestSheet() {
|
||||
document.getElementById('requestOverlay').classList.remove('open');
|
||||
document.getElementById('requestSheet').classList.remove('open');
|
||||
resetRequestForm();
|
||||
}
|
||||
|
||||
function resetRequestForm() {
|
||||
document.getElementById('searchInput').value = '';
|
||||
document.getElementById('searchResults').classList.remove('open');
|
||||
document.getElementById('selectedItemWrap').classList.add('hidden');
|
||||
document.getElementById('selectedItemId').value = '';
|
||||
document.getElementById('selectedCustomName').value = '';
|
||||
document.getElementById('newItemForm').classList.add('hidden');
|
||||
document.getElementById('reqQuantity').value = '1';
|
||||
document.getElementById('reqNotes').value = '';
|
||||
document.getElementById('reqPhotoInput').value = '';
|
||||
document.getElementById('reqPhotoPreview').classList.add('hidden');
|
||||
document.getElementById('photoLabel').textContent = '사진 촬영/선택';
|
||||
photoBase64 = null;
|
||||
isRegisterMode = false;
|
||||
}
|
||||
|
||||
/* ===== 서버 스마트 검색 ===== */
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const input = document.getElementById('searchInput');
|
||||
input.addEventListener('input', () => {
|
||||
clearTimeout(searchTimer);
|
||||
const q = input.value.trim();
|
||||
if (q.length === 0) {
|
||||
document.getElementById('searchResults').classList.remove('open');
|
||||
document.getElementById('searchSpinner').classList.remove('show');
|
||||
return;
|
||||
}
|
||||
document.getElementById('searchSpinner').classList.add('show');
|
||||
searchTimer = setTimeout(async () => {
|
||||
try {
|
||||
const res = await api('/purchase-requests/search?q=' + encodeURIComponent(q));
|
||||
renderSearchResults(res.data || [], q);
|
||||
} catch (e) {
|
||||
console.error('검색 오류:', e);
|
||||
} finally {
|
||||
document.getElementById('searchSpinner').classList.remove('show');
|
||||
}
|
||||
}, 300);
|
||||
});
|
||||
});
|
||||
|
||||
function renderSearchResults(items, query) {
|
||||
const container = document.getElementById('searchResults');
|
||||
let html = '';
|
||||
|
||||
items.forEach(item => {
|
||||
const catLabel = CAT_LABELS[item.category] || '';
|
||||
const matchLabel = MATCH_LABELS[item._matchType] || '';
|
||||
const spec = item.spec ? ' [' + escapeHtml(item.spec) + ']' : '';
|
||||
const maker = item.maker ? ' (' + escapeHtml(item.maker) + ')' : '';
|
||||
html += `<div class="pm-search-item" onclick="selectSearchItem(${item.item_id})">
|
||||
<div class="flex-1">
|
||||
<div class="text-sm font-medium">${escapeHtml(item.item_name)}${spec}${maker}</div>
|
||||
${catLabel ? `<div class="text-xs text-gray-400 mt-0.5">${catLabel}</div>` : ''}
|
||||
</div>
|
||||
${matchLabel ? `<span class="match-type">${matchLabel}</span>` : ''}
|
||||
</div>`;
|
||||
});
|
||||
|
||||
// 새 품목 등록 옵션
|
||||
html += `<div class="pm-search-register" onclick="selectNewItem()">
|
||||
<i class="fas fa-plus-circle"></i>
|
||||
<span>"${escapeHtml(query)}" 새 품목으로 등록 후 신청</span>
|
||||
</div>`;
|
||||
|
||||
container.innerHTML = html;
|
||||
container.classList.add('open');
|
||||
}
|
||||
|
||||
/* ===== 품목 선택 ===== */
|
||||
let searchItemsCache = [];
|
||||
|
||||
function selectSearchItem(itemId) {
|
||||
// API 검색 결과에서 선택 — searchResults에서 데이터 가져오기
|
||||
api('/purchase-requests/search?q=' + encodeURIComponent(document.getElementById('searchInput').value.trim()))
|
||||
.then(res => {
|
||||
const item = (res.data || []).find(i => i.item_id === itemId);
|
||||
if (!item) return;
|
||||
document.getElementById('selectedItemId').value = item.item_id;
|
||||
document.getElementById('selectedCustomName').value = '';
|
||||
document.getElementById('selectedItemName').textContent = item.item_name + (item.spec ? ' [' + item.spec + ']' : '') + (item.maker ? ' (' + item.maker + ')' : '');
|
||||
document.getElementById('selectedItemMeta').textContent = (CAT_LABELS[item.category] || '') + (item.base_price ? ' · ' + Number(item.base_price).toLocaleString() + '원' : '');
|
||||
document.getElementById('selectedItemWrap').classList.remove('hidden');
|
||||
document.getElementById('searchResults').classList.remove('open');
|
||||
document.getElementById('newItemForm').classList.add('hidden');
|
||||
isRegisterMode = false;
|
||||
});
|
||||
}
|
||||
|
||||
function selectNewItem() {
|
||||
const query = document.getElementById('searchInput').value.trim();
|
||||
if (!query) return;
|
||||
document.getElementById('selectedItemId').value = '';
|
||||
document.getElementById('selectedCustomName').value = query;
|
||||
document.getElementById('selectedItemName').textContent = query;
|
||||
document.getElementById('selectedItemMeta').textContent = '직접 입력';
|
||||
document.getElementById('selectedItemWrap').classList.remove('hidden');
|
||||
document.getElementById('searchResults').classList.remove('open');
|
||||
|
||||
// 신규 등록 폼 표시
|
||||
document.getElementById('newItemForm').classList.remove('hidden');
|
||||
document.getElementById('newItemName').value = query;
|
||||
isRegisterMode = true;
|
||||
}
|
||||
|
||||
function clearSelectedItem() {
|
||||
document.getElementById('selectedItemWrap').classList.add('hidden');
|
||||
document.getElementById('selectedItemId').value = '';
|
||||
document.getElementById('selectedCustomName').value = '';
|
||||
document.getElementById('newItemForm').classList.add('hidden');
|
||||
document.getElementById('searchInput').value = '';
|
||||
isRegisterMode = false;
|
||||
}
|
||||
|
||||
/* ===== 사진 ===== */
|
||||
async function onMobilePhotoSelected(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') {
|
||||
document.getElementById('photoLabel').textContent = '변환 중...';
|
||||
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');
|
||||
document.getElementById('photoLabel').textContent = '사진 촬영/선택';
|
||||
return;
|
||||
}
|
||||
|
||||
const reader = new FileReader();
|
||||
reader.onload = (e) => {
|
||||
photoBase64 = e.target.result;
|
||||
document.getElementById('reqPhotoPreview').src = photoBase64;
|
||||
document.getElementById('reqPhotoPreview').classList.remove('hidden');
|
||||
document.getElementById('photoLabel').textContent = '사진 변경';
|
||||
};
|
||||
reader.readAsDataURL(processFile);
|
||||
}
|
||||
|
||||
/* ===== 신청 제출 ===== */
|
||||
async function submitRequest() {
|
||||
const itemId = document.getElementById('selectedItemId').value;
|
||||
const customName = document.getElementById('selectedCustomName').value;
|
||||
const quantity = parseInt(document.getElementById('reqQuantity').value) || 0;
|
||||
|
||||
if (!itemId && !customName) { showToast('품목을 선택하거나 검색해주세요.', 'error'); return; }
|
||||
if (quantity < 1) { showToast('수량은 1 이상이어야 합니다.', 'error'); return; }
|
||||
|
||||
const btn = document.getElementById('submitBtn');
|
||||
btn.disabled = true;
|
||||
btn.textContent = '처리 중...';
|
||||
|
||||
try {
|
||||
if (isRegisterMode && customName) {
|
||||
// Phase 4: 인라인 등록 + 신청
|
||||
const body = {
|
||||
item_name: customName,
|
||||
spec: document.getElementById('newItemSpec').value.trim() || null,
|
||||
maker: document.getElementById('newItemMaker').value.trim() || null,
|
||||
category: document.getElementById('newItemCategory').value || null,
|
||||
quantity,
|
||||
notes: document.getElementById('reqNotes').value.trim() || null
|
||||
};
|
||||
if (photoBase64) body.photo = photoBase64;
|
||||
await api('/purchase-requests/register-and-request', {
|
||||
method: 'POST', body: JSON.stringify(body)
|
||||
});
|
||||
} else {
|
||||
// 기존 방식
|
||||
const body = { quantity, notes: document.getElementById('reqNotes').value.trim() };
|
||||
if (itemId) {
|
||||
body.item_id = parseInt(itemId);
|
||||
} else {
|
||||
body.custom_item_name = customName;
|
||||
body.custom_category = document.getElementById('newItemCategory')?.value || null;
|
||||
}
|
||||
if (photoBase64) body.photo = photoBase64;
|
||||
await api('/purchase-requests', {
|
||||
method: 'POST', body: JSON.stringify(body)
|
||||
});
|
||||
}
|
||||
|
||||
showToast('소모품 신청이 등록되었습니다.');
|
||||
closeRequestSheet();
|
||||
currentPage = 1;
|
||||
requestsList = [];
|
||||
await loadRequests();
|
||||
} catch (e) {
|
||||
showToast(e.message, 'error');
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.textContent = '신청하기';
|
||||
}
|
||||
}
|
||||
|
||||
/* ===== URL 파라미터로 상세 열기 ===== */
|
||||
function checkViewParam() {
|
||||
const urlParams = new URLSearchParams(location.search);
|
||||
const viewId = urlParams.get('view');
|
||||
if (viewId) {
|
||||
// 데이터 로드 후 상세 열기
|
||||
setTimeout(() => openDetail(parseInt(viewId)), 500);
|
||||
}
|
||||
}
|
||||
|
||||
/* ===== Init ===== */
|
||||
(async function() {
|
||||
if (!await initAuth()) return;
|
||||
await loadRequests();
|
||||
checkViewParam();
|
||||
})();
|
||||
@@ -7,8 +7,8 @@ const CAT_LABELS = { consumable: '소모품', safety: '안전용품', repair: '
|
||||
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: '대기', purchased: '구매완료', hold: '보류' };
|
||||
const STATUS_COLORS = { pending: 'badge-amber', purchased: 'badge-green', hold: 'badge-gray' };
|
||||
const STATUS_LABELS = { pending: '대기', grouped: '구매진행중', purchased: '구매완료', received: '입고완료', hold: '보류' };
|
||||
const STATUS_COLORS = { pending: 'badge-amber', grouped: 'badge-blue', purchased: 'badge-green', received: 'badge-teal', hold: 'badge-gray' };
|
||||
|
||||
function _fmtSpec(spec) { return spec ? ' [' + spec + ']' : ''; }
|
||||
|
||||
@@ -21,6 +21,8 @@ let isAdmin = false;
|
||||
let photoBase64 = null;
|
||||
let searchDebounceTimer = null;
|
||||
let dropdownActiveIndex = -1;
|
||||
let selectedRequestIds = new Set();
|
||||
let batchesVisible = false;
|
||||
|
||||
async function loadInitialData() {
|
||||
try {
|
||||
@@ -310,8 +312,18 @@ async function loadRequests() {
|
||||
|
||||
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="7" class="px-4 py-8 text-center text-gray-400">소모품 신청 내역이 없습니다.</td></tr>';
|
||||
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 => {
|
||||
@@ -336,6 +348,11 @@ function renderRequests() {
|
||||
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" title="입고 처리"><i class="fas fa-box-open"></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>`;
|
||||
}
|
||||
@@ -343,13 +360,18 @@ function renderRequests() {
|
||||
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 || '')}</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>
|
||||
@@ -508,6 +530,197 @@ async function deleteRequest(requestId) {
|
||||
} 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'); }
|
||||
}
|
||||
|
||||
/* ===== 입고 처리 모달 ===== */
|
||||
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;
|
||||
|
||||
@@ -20,6 +20,11 @@
|
||||
label: '작업보고',
|
||||
icon: '<svg ' + SVG_ATTR + '><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>'
|
||||
},
|
||||
{
|
||||
href: '/pages/purchase/request-mobile.html',
|
||||
label: '소모품',
|
||||
icon: '<svg ' + SVG_ATTR + '><path d="M6 2L3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z"/><line x1="3" y1="6" x2="21" y2="6"/><path d="M16 10a4 4 0 0 1-8 0"/></svg>'
|
||||
},
|
||||
{
|
||||
href: '/pages/attendance/my-vacation-info.html',
|
||||
label: '연차관리',
|
||||
|
||||
@@ -133,7 +133,8 @@ const NAV_MENU = [
|
||||
{ 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/purchase/request-mobile.html', icon: 'fa-shopping-cart', label: '소모품 신청', key: 'purchase.request_mobile' },
|
||||
{ href: '/pages/purchase/request.html', icon: 'fa-clipboard-list', label: '소모품 관리', key: 'purchase.request' },
|
||||
{ href: '/pages/admin/purchase-analysis.html', icon: 'fa-chart-line', label: '소모품 분석', key: 'purchase.analysis', admin: true },
|
||||
]},
|
||||
{ cat: '근태 관리', items: [
|
||||
|
||||
Reference in New Issue
Block a user