feat(sprint-002): 대리입력 + 일별 현황 대시보드 (Section A+B)

Section A (Backend):
- POST /api/proxy-input: TBM 세션+팀배정+작업보고서 일괄 생성 (트랜잭션)
- GET /api/proxy-input/daily-status: 일별 TBM/보고서 입력 현황
- GET /api/proxy-input/daily-status/detail: 작업자별 상세
- tbm_sessions에 is_proxy_input, proxy_input_by 컬럼 추가
- system1/system2/tkuser requireMinLevel → shared requirePage 전환
- permissionModel에 factory_proxy_input, factory_daily_status 키 등록

Section B (Frontend):
- daily-status.html: 날짜 네비 + 요약 카드 + 필터 탭 + 작업자 리스트 + 바텀시트
- proxy-input.html: 미입력자 카드 + 확장 폼 + 일괄 설정 + 저장
- tkfb-core.js NAV_MENU에 입력 현황/대리입력 추가

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Hyungi Ahn
2026-03-30 07:40:56 +09:00
parent 66676ac923
commit 6411eab210
28 changed files with 2097 additions and 96 deletions

View File

@@ -0,0 +1,300 @@
/**
* daily-status.js — 일별 TBM/작업보고서 입력 현황 대시보드
* Sprint 002 Section B
*/
// ===== Mock 설정 =====
const MOCK_ENABLED = false;
const MOCK_DATA = {
success: true,
data: {
date: '2026-03-30',
summary: {
total_active_workers: 45, tbm_completed: 38, tbm_missing: 7,
report_completed: 35, report_missing: 10, both_completed: 33, both_missing: 5
},
workers: [
{ user_id: 15, worker_name: '김철수', job_type: '용접', department_name: '생산1팀', has_tbm: false, has_report: false, tbm_session_id: null, total_report_hours: 0, status: 'both_missing', proxy_history: null },
{ user_id: 22, worker_name: '이영희', job_type: '배관', department_name: '생산2팀', has_tbm: true, has_report: false, tbm_session_id: 140, total_report_hours: 0, status: 'tbm_only', proxy_history: null },
{ user_id: 30, worker_name: '박민수', job_type: '전기', department_name: '생산1팀', has_tbm: true, has_report: true, tbm_session_id: 141, total_report_hours: 8, status: 'complete', proxy_history: { proxy_by: '관리자', proxy_at: '2026-03-30T14:30:00' } },
{ user_id: 35, worker_name: '정대호', job_type: '도장', department_name: '생산2팀', has_tbm: false, has_report: true, tbm_session_id: null, total_report_hours: 8, status: 'report_only', proxy_history: null },
{ user_id: 40, worker_name: '최윤서', job_type: '용접', department_name: '생산1팀', has_tbm: true, has_report: true, tbm_session_id: 142, total_report_hours: 9, status: 'complete', proxy_history: null },
{ user_id: 41, worker_name: '한지민', job_type: '사상', department_name: '생산2팀', has_tbm: false, has_report: false, tbm_session_id: null, total_report_hours: 0, status: 'both_missing', proxy_history: null },
{ user_id: 42, worker_name: '송민호', job_type: '절단', department_name: '생산1팀', has_tbm: true, has_report: true, tbm_session_id: 143, total_report_hours: 8, status: 'complete', proxy_history: null },
]
}
};
const MOCK_DETAIL = {
success: true,
data: {
worker: { user_id: 15, worker_name: '김철수', job_type: '용접', department_name: '생산1팀' },
tbm_sessions: [],
work_reports: [],
proxy_history: []
}
};
// ===== State =====
let currentDate = new Date();
let workers = [];
let currentFilter = 'all';
let selectedWorkerId = null;
const DAYS_KR = ['일요일', '월요일', '화요일', '수요일', '목요일', '금요일', '토요일'];
const ALLOWED_ROLES = ['support_team', 'admin', 'system'];
// ===== Init =====
document.addEventListener('DOMContentLoaded', async () => {
// URL 파라미터에서 날짜 가져오기
const urlDate = new URLSearchParams(location.search).get('date');
if (urlDate) currentDate = new Date(urlDate + 'T00:00:00');
// 권한 체크 (initAuth 완료 후)
setTimeout(() => {
const user = window.currentUser;
if (user && !ALLOWED_ROLES.includes(user.role)) {
document.getElementById('workerList').classList.add('hidden');
document.getElementById('bottomAction').classList.add('hidden');
document.getElementById('noPermission').classList.remove('hidden');
return;
}
loadStatus();
}, 500);
});
// ===== Date Navigation =====
function formatDateStr(d) {
return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
}
function updateDateDisplay() {
const str = formatDateStr(currentDate);
document.getElementById('dateText').textContent = str;
document.getElementById('dayText').textContent = DAYS_KR[currentDate.getDay()];
// 미래 날짜 비활성
const today = new Date();
today.setHours(0, 0, 0, 0);
const nextBtn = document.getElementById('nextDate');
nextBtn.disabled = currentDate >= today;
}
function changeDate(delta) {
currentDate.setDate(currentDate.getDate() + delta);
updateDateDisplay();
loadStatus();
}
function openDatePicker() {
const picker = document.getElementById('datePicker');
picker.value = formatDateStr(currentDate);
picker.max = formatDateStr(new Date());
picker.showPicker ? picker.showPicker() : picker.click();
}
function onDatePicked(val) {
if (!val) return;
currentDate = new Date(val + 'T00:00:00');
updateDateDisplay();
loadStatus();
}
// ===== Data Loading =====
async function loadStatus() {
const listEl = document.getElementById('workerList');
listEl.innerHTML = '<div class="ds-skeleton"></div><div class="ds-skeleton"></div><div class="ds-skeleton"></div>';
document.getElementById('emptyState').classList.add('hidden');
updateDateDisplay();
try {
let res;
if (MOCK_ENABLED) {
res = MOCK_DATA;
} else {
res = await window.apiCall('/proxy-input/daily-status?date=' + formatDateStr(currentDate));
}
if (!res || !res.success) {
listEl.innerHTML = '<div class="ds-empty"><p>데이터를 불러올 수 없습니다</p></div>';
return;
}
workers = res.data.workers || [];
updateSummary(res.data.summary || {});
updateFilterCounts();
renderWorkerList();
} catch (e) {
listEl.innerHTML = '<div class="ds-empty"><i class="fas fa-exclamation-triangle text-2xl text-red-300"></i><p>네트워크 오류. 다시 시도해주세요.</p></div>';
}
}
function updateSummary(s) {
document.getElementById('totalCount').textContent = s.total_active_workers || 0;
document.getElementById('doneCount').textContent = s.both_completed || 0;
document.getElementById('missingCount').textContent = s.both_missing || 0;
const total = s.total_active_workers || 1;
document.getElementById('donePct').textContent = Math.round((s.both_completed || 0) / total * 100) + '%';
document.getElementById('missingPct').textContent = Math.round((s.both_missing || 0) / total * 100) + '%';
// 하단 버튼 카운트
const missingWorkers = workers.filter(w => w.status !== 'complete').length;
document.getElementById('proxyCount').textContent = missingWorkers;
document.getElementById('proxyBtn').disabled = missingWorkers === 0;
}
function updateFilterCounts() {
document.getElementById('filterAll').textContent = workers.length;
document.getElementById('filterComplete').textContent = workers.filter(w => w.status === 'complete').length;
document.getElementById('filterMissing').textContent = workers.filter(w => w.status === 'both_missing').length;
document.getElementById('filterPartial').textContent = workers.filter(w => w.status === 'tbm_only' || w.status === 'report_only').length;
}
// ===== Filter =====
function setFilter(f) {
currentFilter = f;
document.querySelectorAll('.ds-tab').forEach(tab => {
tab.classList.toggle('active', tab.dataset.filter === f);
});
renderWorkerList();
}
// ===== Render =====
function renderWorkerList() {
const listEl = document.getElementById('workerList');
const emptyEl = document.getElementById('emptyState');
let filtered = workers;
if (currentFilter === 'complete') filtered = workers.filter(w => w.status === 'complete');
else if (currentFilter === 'both_missing') filtered = workers.filter(w => w.status === 'both_missing');
else if (currentFilter === 'partial') filtered = workers.filter(w => w.status === 'tbm_only' || w.status === 'report_only');
if (filtered.length === 0) {
listEl.innerHTML = '';
emptyEl.classList.remove('hidden');
return;
}
emptyEl.classList.add('hidden');
listEl.innerHTML = filtered.map(w => {
const tbmBadge = w.has_tbm
? '<span class="ds-badge-ok">TBM ✓</span>'
: '<span class="ds-badge-no">TBM ✗</span>';
const reportBadge = w.has_report
? `<span class="ds-badge-ok">보고서 ✓${w.total_report_hours ? ' ' + w.total_report_hours + 'h' : ''}</span>`
: '<span class="ds-badge-no">보고서 ✗</span>';
const isProxy = w.tbm_sessions?.some(t => t.is_proxy_input) || false;
const proxyBadge = isProxy
? '<span class="ds-badge-proxy">대리입력</span>'
: '';
return `
<div class="ds-worker-row" onclick="openSheet(${w.user_id})">
<div class="ds-status-dot ${w.status}"></div>
<div class="ds-worker-info">
<div class="ds-worker-name">${escHtml(w.worker_name)}</div>
<div class="ds-worker-dept">${escHtml(w.job_type)} · ${escHtml(w.department_name)}</div>
</div>
<div class="ds-worker-status">${tbmBadge}${reportBadge}${proxyBadge}</div>
</div>`;
}).join('');
}
function escHtml(s) { return (s || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;'); }
// ===== Bottom Sheet =====
function openSheet(userId) {
selectedWorkerId = userId;
const w = workers.find(x => x.user_id === userId);
if (!w) return;
document.getElementById('sheetWorkerName').textContent = w.worker_name;
document.getElementById('sheetWorkerInfo').textContent = `${w.job_type} · ${w.department_name}`;
document.getElementById('sheetBody').innerHTML = '<div class="ds-sheet-loading"><i class="fas fa-spinner fa-spin"></i> 로딩 중...</div>';
document.getElementById('sheetOverlay').classList.remove('hidden');
document.getElementById('detailSheet').classList.remove('hidden');
setTimeout(() => document.getElementById('detailSheet').classList.add('open'), 10);
// 상세 데이터 로드
loadDetail(userId, w);
}
async function loadDetail(userId, workerBasic) {
const bodyEl = document.getElementById('sheetBody');
try {
let res;
if (MOCK_ENABLED) {
res = JSON.parse(JSON.stringify(MOCK_DETAIL));
res.data.worker = workerBasic;
// mock: complete 상태면 TBM/보고서 데이터 채우기
if (workerBasic.has_tbm) {
res.data.tbm_sessions = [{ session_id: workerBasic.tbm_session_id, session_date: formatDateStr(currentDate), status: 'completed', leader_name: '반장' }];
}
if (workerBasic.has_report) {
res.data.work_reports = [{ report_date: formatDateStr(currentDate), project_name: '프로젝트A', work_type_name: workerBasic.job_type, work_hours: workerBasic.total_report_hours }];
}
if (workerBasic.proxy_history) {
res.data.proxy_history = [workerBasic.proxy_history];
}
} else {
res = await window.apiCall('/proxy-input/daily-status/detail?date=' + formatDateStr(currentDate) + '&user_id=' + userId);
}
if (!res || !res.success) { bodyEl.innerHTML = '<div class="ds-sheet-card empty">상세 정보를 불러올 수 없습니다</div>'; return; }
const d = res.data;
let html = '';
// TBM 섹션
html += '<div class="ds-sheet-section"><div class="ds-sheet-section-title"><i class="fas fa-clipboard-check"></i> TBM</div>';
if (d.tbm_sessions && d.tbm_sessions.length > 0) {
html += d.tbm_sessions.map(s => {
const proxyTag = s.is_proxy_input ? ` · <span class="ds-badge-proxy">대리입력(${escHtml(s.proxy_input_by_name || '-')})</span>` : '';
return `<div class="ds-sheet-card">세션 #${s.session_id} · ${s.status === 'completed' ? '완료' : '진행중'} · 리더: ${escHtml(s.leader_name || '-')}${proxyTag}</div>`;
}).join('');
} else {
html += '<div class="ds-sheet-card empty">세션 없음</div>';
}
html += '</div>';
// 작업보고서 섹션
html += '<div class="ds-sheet-section"><div class="ds-sheet-section-title"><i class="fas fa-file-alt"></i> 작업보고서</div>';
if (d.work_reports && d.work_reports.length > 0) {
html += d.work_reports.map(r => `<div class="ds-sheet-card">${escHtml(r.project_name || '-')} · ${escHtml(r.work_type_name || '-')} · ${r.work_hours || 0}시간</div>`).join('');
} else {
html += '<div class="ds-sheet-card empty">보고서 없음</div>';
}
html += '</div>';
bodyEl.innerHTML = html;
// 완료 상태면 대리입력 버튼 숨김
const btn = document.getElementById('sheetProxyBtn');
btn.style.display = workerBasic.status === 'complete' ? 'none' : 'block';
} catch (e) {
bodyEl.innerHTML = '<div class="ds-sheet-card empty">네트워크 오류</div>';
}
}
function closeSheet() {
document.getElementById('detailSheet').classList.remove('open');
setTimeout(() => {
document.getElementById('sheetOverlay').classList.add('hidden');
document.getElementById('detailSheet').classList.add('hidden');
}, 300);
}
// ===== Navigation =====
function goProxyInput() {
location.href = '/pages/work/proxy-input.html?date=' + formatDateStr(currentDate);
}
function goProxyInputSingle() {
if (selectedWorkerId) {
location.href = '/pages/work/proxy-input.html?date=' + formatDateStr(currentDate) + '&user_id=' + selectedWorkerId;
}
}

View File

@@ -0,0 +1,404 @@
/**
* proxy-input.js — 대리입력 (TBM + 작업보고서 동시 생성)
* Sprint 002 Section B
*/
// ===== Mock =====
const MOCK_ENABLED = false;
const MOCK_STATUS = {
success: true,
data: {
date: '2026-03-30',
summary: { total_active_workers: 45, tbm_completed: 38, tbm_missing: 7, report_completed: 35, report_missing: 10, both_completed: 33, both_missing: 5 },
workers: [
{ user_id: 15, worker_name: '김철수', job_type: '용접', department_name: '생산1팀', has_tbm: false, has_report: false, tbm_session_id: null, total_report_hours: 0, status: 'both_missing', proxy_history: null },
{ user_id: 22, worker_name: '이영희', job_type: '배관', department_name: '생산2팀', has_tbm: true, has_report: false, tbm_session_id: 140, total_report_hours: 0, status: 'tbm_only', proxy_history: null },
{ user_id: 35, worker_name: '정대호', job_type: '도장', department_name: '생산2팀', has_tbm: false, has_report: true, tbm_session_id: null, total_report_hours: 8, status: 'report_only', proxy_history: null },
{ user_id: 41, worker_name: '한지민', job_type: '사상', department_name: '생산2팀', has_tbm: false, has_report: false, tbm_session_id: null, total_report_hours: 0, status: 'both_missing', proxy_history: null },
]
}
};
const MOCK_PROJECTS = [
{ project_id: 1, project_name: 'JOB-2026-001 용기제작', job_no: 'JOB-2026-001' },
{ project_id: 2, project_name: 'JOB-2026-002 Skid 제작', job_no: 'JOB-2026-002' },
{ project_id: 3, project_name: 'JOB-2026-003 PKG 조립', job_no: 'JOB-2026-003' },
];
const MOCK_WORK_TYPES = [
{ id: 1, name: '절단' }, { id: 2, name: '용접' }, { id: 3, name: '배관' },
{ id: 4, name: '도장' }, { id: 5, name: '사상' }, { id: 6, name: '전기' },
];
const MOCK_TASKS = [
{ task_id: 1, work_type_id: 2, task_name: '취부&용접' },
{ task_id: 2, work_type_id: 2, task_name: '가우징' },
{ task_id: 3, work_type_id: 1, task_name: '절단작업' },
{ task_id: 4, work_type_id: 3, task_name: '배관설치' },
];
const MOCK_WORK_STATUSES = [
{ id: 1, name: '정상' }, { id: 2, name: '잔업' }, { id: 3, name: '특근' },
];
// ===== State =====
let currentDate = '';
let missingWorkers = [];
let selectedIds = new Set();
let projects = [], workTypes = [], tasks = [], workStatuses = [];
let workerFormData = {}; // { userId: { project_id, work_type_id, ... } }
let saving = false;
const ALLOWED_ROLES = ['support_team', 'admin', 'system'];
// ===== Init =====
document.addEventListener('DOMContentLoaded', async () => {
const urlDate = new URLSearchParams(location.search).get('date');
const urlUserId = new URLSearchParams(location.search).get('user_id');
currentDate = urlDate || formatDateStr(new Date());
document.getElementById('dateInput').value = currentDate;
document.getElementById('headerDate').textContent = currentDate;
setTimeout(async () => {
const user = window.currentUser;
if (user && !ALLOWED_ROLES.includes(user.role)) {
document.getElementById('workerCards').classList.add('hidden');
document.getElementById('bottomSave').classList.add('hidden');
document.getElementById('noPermission').classList.remove('hidden');
return;
}
await loadMasterData();
await loadWorkers();
// URL에서 user_id가 있으면 자동 선택
if (urlUserId) toggleWorker(parseInt(urlUserId));
}, 500);
});
function formatDateStr(d) {
return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
}
function onDateChange(val) {
if (!val) return;
currentDate = val;
document.getElementById('headerDate').textContent = val;
loadWorkers();
}
// ===== Master Data =====
async function loadMasterData() {
if (MOCK_ENABLED) {
projects = MOCK_PROJECTS;
workTypes = MOCK_WORK_TYPES;
tasks = MOCK_TASKS;
workStatuses = MOCK_WORK_STATUSES;
return;
}
try {
const [pRes, wtRes, tRes, wsRes] = await Promise.all([
window.apiCall('/projects'),
window.apiCall('/daily-work-reports/work-types'),
window.apiCall('/tasks'),
window.apiCall('/daily-work-reports/work-status-types'),
]);
projects = (pRes && pRes.data) || [];
workTypes = (wtRes && wtRes.data) || [];
tasks = (tRes && tRes.data) || [];
workStatuses = (wsRes && wsRes.data) || [];
} catch (e) {
console.error('마스터 데이터 로드 실패:', e);
}
}
// ===== Load Workers =====
async function loadWorkers() {
const cardsEl = document.getElementById('workerCards');
cardsEl.innerHTML = '<div class="ds-skeleton"></div><div class="ds-skeleton"></div>';
document.getElementById('emptyState').classList.add('hidden');
selectedIds.clear();
workerFormData = {};
updateSaveBtn();
updateBulkBar();
try {
let res;
if (MOCK_ENABLED) {
res = MOCK_STATUS;
} else {
res = await window.apiCall('/proxy-input/daily-status?date=' + currentDate);
}
if (!res || !res.success) { cardsEl.innerHTML = '<div class="pi-empty"><p>데이터를 불러올 수 없습니다</p></div>'; return; }
missingWorkers = (res.data.workers || []).filter(w => w.status !== 'complete');
document.getElementById('missingNum').textContent = missingWorkers.length;
if (missingWorkers.length === 0) {
cardsEl.innerHTML = '';
document.getElementById('emptyState').classList.remove('hidden');
return;
}
renderCards();
} catch (e) {
cardsEl.innerHTML = '<div class="pi-empty"><i class="fas fa-exclamation-triangle text-2xl text-red-300"></i><p>네트워크 오류</p></div>';
}
}
// ===== Render Cards =====
function renderCards() {
const cardsEl = document.getElementById('workerCards');
cardsEl.innerHTML = missingWorkers.map(w => {
const statusLabel = { both_missing: 'TBM+보고서 미입력', tbm_only: '보고서만 미입력', report_only: 'TBM만 미입력' }[w.status] || '';
const fd = workerFormData[w.user_id] || getDefaultFormData(w);
workerFormData[w.user_id] = fd;
const sel = selectedIds.has(w.user_id);
return `
<div class="pi-card ${sel ? 'selected' : ''}" id="card-${w.user_id}">
<div class="pi-card-header" onclick="toggleWorker(${w.user_id})">
<div class="pi-card-check">${sel ? '<i class="fas fa-check text-xs"></i>' : ''}</div>
<div>
<div class="pi-card-name">${escHtml(w.worker_name)}</div>
<div class="pi-card-meta">${escHtml(w.job_type)} · ${escHtml(w.department_name)}</div>
</div>
<div class="pi-card-status ${w.status}">${statusLabel}</div>
</div>
<div class="pi-card-form">
<div class="pi-field">
<label>프로젝트 <span class="text-red-400">*</span></label>
<select id="proj-${w.user_id}" onchange="updateField(${w.user_id},'project_id',this.value)">
<option value="">선택</option>
${projects.map(p => `<option value="${p.project_id}" ${fd.project_id == p.project_id ? 'selected' : ''}>${escHtml(p.job_no)} ${escHtml(p.project_name)}</option>`).join('')}
</select>
</div>
<div class="pi-field-row">
<div class="pi-field">
<label>공종 <span class="text-red-400">*</span></label>
<select id="wt-${w.user_id}" onchange="updateField(${w.user_id},'work_type_id',this.value); updateTaskOptions(${w.user_id})">
<option value="">선택</option>
${workTypes.map(t => `<option value="${t.id}" ${fd.work_type_id == t.id ? 'selected' : ''}>${escHtml(t.name)}</option>`).join('')}
</select>
</div>
<div class="pi-field">
<label>작업</label>
<select id="task-${w.user_id}" onchange="updateField(${w.user_id},'task_id',this.value)">
<option value="">선택</option>
${tasks.filter(t => t.work_type_id == fd.work_type_id).map(t => `<option value="${t.task_id}" ${fd.task_id == t.task_id ? 'selected' : ''}>${escHtml(t.task_name)}</option>`).join('')}
</select>
</div>
</div>
<div class="pi-field-row3">
<div class="pi-field">
<label>시간 <span class="text-red-400">*</span></label>
<input type="number" min="0" max="24" step="0.5" value="${fd.work_hours}" onchange="updateField(${w.user_id},'work_hours',this.value)">
</div>
<div class="pi-field">
<label>시작</label>
<input type="time" value="${fd.start_time}" onchange="updateField(${w.user_id},'start_time',this.value)">
</div>
<div class="pi-field">
<label>종료</label>
<input type="time" value="${fd.end_time}" onchange="updateField(${w.user_id},'end_time',this.value)">
</div>
</div>
<div class="pi-field-row">
<div class="pi-field">
<label>작업 상태</label>
<select onchange="updateField(${w.user_id},'work_status_id',this.value)">
${workStatuses.map(s => `<option value="${s.id}" ${fd.work_status_id == s.id ? 'selected' : ''}>${escHtml(s.name)}</option>`).join('')}
</select>
</div>
<div class="pi-field">
<label>비고</label>
<input type="text" placeholder="메모" value="${escHtml(fd.note || '')}" onchange="updateField(${w.user_id},'note',this.value)">
</div>
</div>
</div>
</div>`;
}).join('');
}
function getDefaultFormData(worker) {
return {
project_id: '', work_type_id: '', task_id: '',
work_hours: 8, start_time: '08:00', end_time: '17:00',
work_status_id: 1, note: ''
};
}
function escHtml(s) { return (s || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;'); }
// ===== Worker Toggle =====
function toggleWorker(userId) {
if (selectedIds.has(userId)) {
selectedIds.delete(userId);
} else {
selectedIds.add(userId);
}
renderCards();
updateSaveBtn();
updateBulkBar();
}
function updateField(userId, field, value) {
if (!workerFormData[userId]) workerFormData[userId] = getDefaultFormData({});
workerFormData[userId][field] = value;
}
function updateTaskOptions(userId) {
const wtId = workerFormData[userId]?.work_type_id;
const sel = document.getElementById('task-' + userId);
if (!sel) return;
const filtered = tasks.filter(t => t.work_type_id == wtId);
sel.innerHTML = '<option value="">선택</option>' + filtered.map(t => `<option value="${t.task_id}">${escHtml(t.task_name)}</option>`).join('');
workerFormData[userId].task_id = '';
}
// ===== Bulk Actions =====
function updateBulkBar() {
const bar = document.getElementById('bulkBar');
if (selectedIds.size > 0) {
bar.classList.remove('hidden');
document.getElementById('selectedCount').textContent = selectedIds.size;
} else {
bar.classList.add('hidden');
}
}
function bulkSet(type) {
const modal = document.getElementById('bulkModal');
const body = document.getElementById('bulkModalBody');
const title = document.getElementById('bulkModalTitle');
const confirm = document.getElementById('bulkConfirmBtn');
if (type === 'project') {
title.textContent = '프로젝트 일괄 설정';
body.innerHTML = `<select id="bulkValue">${projects.map(p => `<option value="${p.project_id}">${escHtml(p.job_no)} ${escHtml(p.project_name)}</option>`).join('')}</select>`;
confirm.onclick = () => applyBulk('project_id', document.getElementById('bulkValue').value);
} else if (type === 'workType') {
title.textContent = '공종 일괄 설정';
body.innerHTML = `<select id="bulkValue">${workTypes.map(t => `<option value="${t.id}">${escHtml(t.name)}</option>`).join('')}</select>`;
confirm.onclick = () => applyBulk('work_type_id', document.getElementById('bulkValue').value);
} else if (type === 'hours') {
title.textContent = '작업시간 일괄 설정';
body.innerHTML = '<input type="number" id="bulkValue" min="0" max="24" step="0.5" value="8">';
confirm.onclick = () => applyBulk('work_hours', document.getElementById('bulkValue').value);
}
modal.classList.remove('hidden');
}
function applyBulk(field, value) {
let hasExisting = false;
for (const uid of selectedIds) {
const fd = workerFormData[uid];
if (fd && fd[field] && fd[field] !== '' && String(fd[field]) !== String(value)) {
hasExisting = true;
break;
}
}
if (hasExisting) {
if (!confirm('이미 입력된 값이 있습니다. 덮어쓰시겠습니까?')) {
// 빈 필드만 채움
for (const uid of selectedIds) {
if (!workerFormData[uid][field] || workerFormData[uid][field] === '') {
workerFormData[uid][field] = value;
}
}
closeBulkModal();
renderCards();
return;
}
}
for (const uid of selectedIds) {
workerFormData[uid][field] = value;
if (field === 'work_type_id') workerFormData[uid].task_id = '';
}
closeBulkModal();
renderCards();
}
function closeBulkModal() {
document.getElementById('bulkModal').classList.add('hidden');
}
// ===== Save =====
function updateSaveBtn() {
const btn = document.getElementById('saveBtn');
const text = document.getElementById('saveBtnText');
if (selectedIds.size === 0) {
btn.disabled = true;
text.textContent = '저장할 작업자를 선택하세요';
} else {
btn.disabled = false;
text.textContent = `${selectedIds.size}명 대리입력 저장`;
}
}
async function saveProxyInput() {
if (saving || selectedIds.size === 0) return;
// 유효성 검사
for (const uid of selectedIds) {
const fd = workerFormData[uid];
const w = missingWorkers.find(x => x.user_id === uid);
if (!fd.project_id) { showToast(`${w?.worker_name || uid}: 프로젝트를 선택하세요`, 'error'); return; }
if (!fd.work_type_id) { showToast(`${w?.worker_name || uid}: 공종을 선택하세요`, 'error'); return; }
}
saving = true;
const btn = document.getElementById('saveBtn');
btn.disabled = true;
btn.classList.add('loading');
document.getElementById('saveBtnText').textContent = '저장 중...';
const entries = [...selectedIds].map(uid => ({
user_id: uid,
project_id: parseInt(workerFormData[uid].project_id),
work_type_id: parseInt(workerFormData[uid].work_type_id),
task_id: workerFormData[uid].task_id ? parseInt(workerFormData[uid].task_id) : null,
work_hours: parseFloat(workerFormData[uid].work_hours) || 8,
start_time: workerFormData[uid].start_time || '08:00',
end_time: workerFormData[uid].end_time || '17:00',
work_status_id: parseInt(workerFormData[uid].work_status_id) || 1,
note: workerFormData[uid].note || ''
}));
try {
let res;
if (MOCK_ENABLED) {
await new Promise(r => setTimeout(r, 1000)); // simulate delay
res = {
success: true,
data: { session_id: 999, created_reports: entries.length, workers: entries.map(e => ({ user_id: e.user_id, worker_name: missingWorkers.find(w => w.user_id === e.user_id)?.worker_name || '', report_id: Math.floor(Math.random() * 1000) })) },
message: `${entries.length}명의 대리입력이 완료되었습니다.`
};
} else {
res = await window.apiCall('/proxy-input', 'POST', { session_date: currentDate, entries });
}
if (res && res.success) {
showToast(res.message || `${entries.length}명 대리입력 완료`, 'success');
selectedIds.clear();
await loadWorkers();
} else {
showToast(res?.message || '저장 실패', 'error');
}
} catch (e) {
showToast('네트워크 오류. 다시 시도해주세요.', 'error');
} finally {
saving = false;
btn.classList.remove('loading');
updateSaveBtn();
}
}
// ===== Toast =====
function showToast(msg, type) {
if (window.showToast) { window.showToast(msg, type); return; }
const c = document.getElementById('toastContainer');
const t = document.createElement('div');
t.className = `toast toast-${type || 'info'}`;
t.textContent = msg;
c.appendChild(t);
setTimeout(() => t.remove(), 3000);
}