/* tkpurchase-daylabor.js - Day labor management */
let dayLaborPage = 1;
const dayLaborLimit = 20;
async function loadDayLabor() {
const dateFrom = document.getElementById('filterDateFrom').value;
const dateTo = document.getElementById('filterDateTo').value;
const status = document.getElementById('filterStatus').value;
const department = document.getElementById('filterDepartment').value;
let query = `?page=${dayLaborPage}&limit=${dayLaborLimit}`;
if (dateFrom) query += '&date_from=' + dateFrom;
if (dateTo) query += '&date_to=' + dateTo;
if (status) query += '&status=' + status;
if (department) query += '&department=' + encodeURIComponent(department);
try {
const r = await api('/day-labor' + query);
renderDayLaborTable(r.data || [], r.total || 0);
} catch(e) {
console.warn('Day labor load error:', e);
document.getElementById('dayLaborTableBody').innerHTML = '
| 로딩 실패 |
';
}
}
function renderDayLaborTable(list, total) {
const tbody = document.getElementById('dayLaborTableBody');
if (!list.length) {
tbody.innerHTML = '| 신청 내역이 없습니다 |
';
document.getElementById('dayLaborPagination').innerHTML = '';
return;
}
const statusMap = {
pending: ['badge-amber', '대기'],
approved: ['badge-green', '승인'],
rejected: ['badge-red', '거절'],
completed: ['badge-gray', '완료']
};
tbody.innerHTML = list.map(d => {
const [cls, label] = statusMap[d.status] || ['badge-gray', d.status];
let actions = '';
if (d.status === 'pending') {
actions = `
`;
} else if (d.status === 'approved') {
actions = ``;
}
return `
| ${formatDate(d.created_at)} |
${formatDate(d.work_date)} |
${escapeHtml(d.requester_name || '')} |
${escapeHtml(d.department || '')} |
${d.worker_count || 0}명 |
${escapeHtml(d.workplace_name || '')} |
${label} |
${actions} |
`;
}).join('');
// Pagination
const totalPages = Math.ceil(total / dayLaborLimit);
renderDayLaborPagination(totalPages);
}
function renderDayLaborPagination(totalPages) {
const container = document.getElementById('dayLaborPagination');
if (totalPages <= 1) { container.innerHTML = ''; return; }
let html = '';
if (dayLaborPage > 1) {
html += ``;
}
for (let i = 1; i <= totalPages; i++) {
if (i === dayLaborPage) {
html += ``;
} else if (Math.abs(i - dayLaborPage) <= 2 || i === 1 || i === totalPages) {
html += ``;
} else if (Math.abs(i - dayLaborPage) === 3) {
html += '...';
}
}
if (dayLaborPage < totalPages) {
html += ``;
}
container.innerHTML = html;
}
function goToDayLaborPage(p) {
dayLaborPage = p;
loadDayLabor();
}
function openAddDayLabor() {
document.getElementById('addDayLaborForm').reset();
// Default to tomorrow
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
document.getElementById('addWorkDate').value = toLocalDate(tomorrow);
document.getElementById('addDayLaborModal').classList.remove('hidden');
}
function closeAddDayLabor() {
document.getElementById('addDayLaborModal').classList.add('hidden');
}
async function submitAddDayLabor(e) {
e.preventDefault();
const body = {
work_date: document.getElementById('addWorkDate').value,
worker_count: parseInt(document.getElementById('addWorkerCount').value) || 1,
work_description: document.getElementById('addWorkDescription').value.trim(),
workplace_name: document.getElementById('addWorkplaceName').value.trim(),
notes: document.getElementById('addNotes').value.trim()
};
if (!body.work_date) { showToast('작업일을 선택하세요', 'error'); return; }
try {
await api('/day-labor', { method: 'POST', body: JSON.stringify(body) });
showToast('일용공 신청이 등록되었습니다');
closeAddDayLabor();
loadDayLabor();
} catch(e) {
showToast(e.message || '등록 실패', 'error');
}
}
async function approveDayLabor(id) {
if (!confirm('이 신청을 승인하시겠습니까?')) return;
try {
await api('/day-labor/' + id + '/approve', { method: 'PUT' });
showToast('승인되었습니다');
loadDayLabor();
} catch(e) {
showToast(e.message || '승인 실패', 'error');
}
}
async function rejectDayLabor(id) {
const reason = prompt('거절 사유를 입력하세요:');
if (reason === null) return;
try {
await api('/day-labor/' + id + '/reject', { method: 'PUT', body: JSON.stringify({ reason }) });
showToast('거절되었습니다');
loadDayLabor();
} catch(e) {
showToast(e.message || '거절 실패', 'error');
}
}
async function completeDayLabor(id) {
if (!confirm('이 신청을 완료 처리하시겠습니까?')) return;
try {
await api('/day-labor/' + id + '/complete', { method: 'PUT' });
showToast('완료 처리되었습니다');
loadDayLabor();
} catch(e) {
showToast(e.message || '완료 처리 실패', 'error');
}
}
function initDayLaborPage() {
if (!initAuth()) return;
// Set default date range to this month
const now = new Date();
const firstDay = new Date(now.getFullYear(), now.getMonth(), 1);
document.getElementById('filterDateFrom').value = toLocalDate(firstDay);
document.getElementById('filterDateTo').value = toLocalDate(now);
loadDayLabor();
}