feat: 작업일정 기간 기반 + 프로젝트 연결

- partner_schedules: work_date → start_date/end_date 기간 기반으로 변경
- project_id 컬럼 추가 (projects 테이블 연결, 선택사항)
- 프로젝트 조회 API 추가 (GET /projects/active)
- 일정 조회 시 기간 겹침 조건으로 필터링
- 체크인 시 기간 내 검증 추가
- 프론트엔드: 시작일/종료일 입력 + 프로젝트 선택 드롭다운
- 마이그레이션 SQL 포함 (scripts/migration-schedule-daterange.sql)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Hyungi Ahn
2026-03-13 08:18:53 +09:00
parent fa4c899d95
commit b5b0fa1728
12 changed files with 228 additions and 36 deletions

View File

@@ -0,0 +1,23 @@
-- Migration: partner_schedules 기간 기반 + 프로젝트 연결
-- 실행 순서: 1단계 → 2단계 → 3단계 순서대로 실행할 것
-- ===== 1단계: 컬럼 변경 + end_date/project_id 추가 =====
ALTER TABLE partner_schedules
CHANGE COLUMN work_date start_date DATE NOT NULL,
ADD COLUMN end_date DATE DEFAULT NULL AFTER start_date,
ADD COLUMN project_id INT DEFAULT NULL AFTER company_id;
-- ===== 2단계: 기존 데이터 채우기 (단일 날짜 → 시작일=종료일) =====
UPDATE partner_schedules SET end_date = start_date WHERE end_date IS NULL;
-- ===== 3단계: NOT NULL로 변경 + 인덱스 재구성 =====
-- ※ 실행 전 SHOW INDEX FROM partner_schedules; 로 실제 인덱스명 확인 후 맞출 것
ALTER TABLE partner_schedules
MODIFY end_date DATE NOT NULL,
ADD INDEX idx_partner_sched_dates (start_date, end_date),
ADD INDEX idx_partner_sched_company (company_id, start_date),
ADD INDEX idx_partner_sched_project (project_id);
-- 기존 인덱스가 있다면 별도로 삭제:
-- ALTER TABLE partner_schedules DROP INDEX idx_work_date;
-- ALTER TABLE partner_schedules DROP INDEX idx_company_date;

View File

@@ -1,5 +1,6 @@
const checkinModel = require('../models/checkinModel');
const workReportModel = require('../models/workReportModel');
const scheduleModel = require('../models/scheduleModel');
// 일정별 체크인 목록
async function list(req, res) {
@@ -38,6 +39,20 @@ async function checkIn(req, res) {
if (!resolvedCompanyId) {
return res.status(400).json({ success: false, error: '업체 정보가 필요합니다' });
}
// 일정 기간 내 체크인 검증
const schedule = await scheduleModel.findById(schedule_id);
if (!schedule) {
return res.status(404).json({ success: false, error: '일정을 찾을 수 없습니다' });
}
const today = new Date();
today.setHours(0, 0, 0, 0);
const startDate = new Date(schedule.start_date);
startDate.setHours(0, 0, 0, 0);
const endDate = new Date(schedule.end_date);
endDate.setHours(0, 0, 0, 0);
if (today < startDate || today > endDate) {
return res.status(400).json({ success: false, error: '오늘은 해당 일정의 작업 기간이 아닙니다' });
}
const data = {
schedule_id,
company_id: resolvedCompanyId,

View File

@@ -0,0 +1,13 @@
const projectModel = require('../models/projectModel');
async function getActive(req, res) {
try {
const rows = await projectModel.findActive();
res.json({ success: true, data: rows });
} catch (err) {
console.error('Project getActive error:', err);
res.status(500).json({ success: false, error: err.message });
}
}
module.exports = { getActive };

View File

@@ -3,12 +3,13 @@ const scheduleModel = require('../models/scheduleModel');
// 일정 목록
async function list(req, res) {
try {
const { company_id, date_from, date_to, status, page, limit } = req.query;
const { company_id, date_from, date_to, status, project_id, page, limit } = req.query;
const rows = await scheduleModel.findAll({
company_id: company_id ? parseInt(company_id) : undefined,
date_from,
date_to,
status,
project_id: project_id ? parseInt(project_id) : undefined,
page: page ? parseInt(page) : 1,
limit: limit ? parseInt(limit) : 50
});
@@ -49,12 +50,18 @@ async function mySchedules(req, res) {
// 일정 등록
async function create(req, res) {
try {
const { company_id, work_date } = req.body;
const { company_id, start_date, end_date } = req.body;
if (!company_id) {
return res.status(400).json({ success: false, error: '업체를 선택해주세요' });
}
if (!work_date) {
return res.status(400).json({ success: false, error: '작일은 필수입니다' });
if (!start_date) {
return res.status(400).json({ success: false, error: '작일은 필수입니다' });
}
if (!end_date) {
return res.status(400).json({ success: false, error: '종료일은 필수입니다' });
}
if (end_date < start_date) {
return res.status(400).json({ success: false, error: '종료일은 시작일 이후여야 합니다' });
}
const data = {
...req.body,
@@ -71,6 +78,10 @@ async function create(req, res) {
// 일정 수정
async function update(req, res) {
try {
const { start_date, end_date } = req.body;
if (start_date && end_date && end_date < start_date) {
return res.status(400).json({ success: false, error: '종료일은 시작일 이후여야 합니다' });
}
const row = await scheduleModel.update(req.params.id, req.body);
if (!row) return res.status(404).json({ success: false, error: '일정을 찾을 수 없습니다' });
res.json({ success: true, data: row });

View File

@@ -7,6 +7,7 @@ const scheduleRoutes = require('./routes/scheduleRoutes');
const checkinRoutes = require('./routes/checkinRoutes');
const workReportRoutes = require('./routes/workReportRoutes');
const partnerAccountRoutes = require('./routes/partnerAccountRoutes');
const projectRoutes = require('./routes/projectRoutes');
const app = express();
const PORT = process.env.PORT || 3000;
@@ -43,6 +44,7 @@ app.use('/api/schedules', scheduleRoutes);
app.use('/api/checkins', checkinRoutes);
app.use('/api/work-reports', workReportRoutes);
app.use('/api/partner-accounts', partnerAccountRoutes);
app.use('/api/projects', projectRoutes);
// 404
app.use((req, res) => {

View File

@@ -0,0 +1,13 @@
const { getPool } = require('./partnerModel');
async function findActive() {
const db = getPool();
const [rows] = await db.query(
`SELECT project_id, job_no, project_name, site
FROM projects
WHERE is_active = 1 AND project_status = 'active'
ORDER BY project_name`);
return rows;
}
module.exports = { findActive };

View File

@@ -1,18 +1,21 @@
const { getPool } = require('./partnerModel');
async function findAll({ company_id, date_from, date_to, status, page = 1, limit = 50 } = {}) {
async function findAll({ company_id, date_from, date_to, status, project_id, page = 1, limit = 50 } = {}) {
const db = getPool();
let sql = `SELECT ps.*, pc.company_name, su.name AS registered_by_name
let sql = `SELECT ps.*, pc.company_name, su.name AS registered_by_name,
p.project_name, p.job_no
FROM partner_schedules ps
LEFT JOIN partner_companies pc ON ps.company_id = pc.id
LEFT JOIN sso_users su ON ps.registered_by = su.user_id
LEFT JOIN projects p ON ps.project_id = p.project_id
WHERE 1=1`;
const params = [];
if (company_id) { sql += ' AND ps.company_id = ?'; params.push(company_id); }
if (date_from) { sql += ' AND ps.work_date >= ?'; params.push(date_from); }
if (date_to) { sql += ' AND ps.work_date <= ?'; params.push(date_to); }
if (date_from) { sql += ' AND ps.end_date >= ?'; params.push(date_from); }
if (date_to) { sql += ' AND ps.start_date <= ?'; params.push(date_to); }
if (status) { sql += ' AND ps.status = ?'; params.push(status); }
sql += ' ORDER BY ps.work_date DESC, ps.created_at DESC';
if (project_id) { sql += ' AND ps.project_id = ?'; params.push(project_id); }
sql += ' ORDER BY ps.start_date DESC, ps.created_at DESC';
const offset = (page - 1) * limit;
sql += ' LIMIT ? OFFSET ?';
params.push(limit, offset);
@@ -23,31 +26,47 @@ async function findAll({ company_id, date_from, date_to, status, page = 1, limit
async function findById(id) {
const db = getPool();
const [rows] = await db.query(
`SELECT ps.*, pc.company_name, su.name AS registered_by_name
`SELECT ps.*, pc.company_name, su.name AS registered_by_name,
p.project_name, p.job_no
FROM partner_schedules ps
LEFT JOIN partner_companies pc ON ps.company_id = pc.id
LEFT JOIN sso_users su ON ps.registered_by = su.user_id
LEFT JOIN projects p ON ps.project_id = p.project_id
WHERE ps.id = ?`, [id]);
return rows[0] || null;
}
async function findByCompanyToday(companyId) {
const db = getPool();
const [rows] = await db.query(
`SELECT ps.*, pc.company_name, p.project_name, p.job_no
FROM partner_schedules ps
LEFT JOIN partner_companies pc ON ps.company_id = pc.id
LEFT JOIN projects p ON ps.project_id = p.project_id
WHERE ps.company_id = ? AND ps.start_date <= CURDATE() AND ps.end_date >= CURDATE()
ORDER BY ps.created_at DESC`, [companyId]);
return rows;
}
async function findByProject(projectId) {
const db = getPool();
const [rows] = await db.query(
`SELECT ps.*, pc.company_name
FROM partner_schedules ps
LEFT JOIN partner_companies pc ON ps.company_id = pc.id
WHERE ps.company_id = ? AND ps.work_date = CURDATE()
ORDER BY ps.created_at DESC`, [companyId]);
WHERE ps.project_id = ?
ORDER BY ps.start_date, pc.company_name`, [projectId]);
return rows;
}
async function create(data) {
const db = getPool();
const [result] = await db.query(
`INSERT INTO partner_schedules (company_id, work_date, work_description, workplace_name, expected_workers, registered_by, notes)
VALUES (?, ?, ?, ?, ?, ?, ?)`,
[data.company_id, data.work_date, data.work_description || null,
`INSERT INTO partner_schedules (company_id, project_id, start_date, end_date, work_description, workplace_name, expected_workers, registered_by, notes)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[data.company_id, data.project_id || null,
data.start_date, data.end_date || data.start_date,
data.work_description || null,
data.workplace_name || null, data.expected_workers || null,
data.registered_by, data.notes || null]);
return findById(result.insertId);
@@ -58,7 +77,9 @@ async function update(id, data) {
const fields = [];
const values = [];
if (data.company_id !== undefined) { fields.push('company_id = ?'); values.push(data.company_id); }
if (data.work_date !== undefined) { fields.push('work_date = ?'); values.push(data.work_date); }
if (data.project_id !== undefined) { fields.push('project_id = ?'); values.push(data.project_id || null); }
if (data.start_date !== undefined) { fields.push('start_date = ?'); values.push(data.start_date); }
if (data.end_date !== undefined) { fields.push('end_date = ?'); values.push(data.end_date); }
if (data.work_description !== undefined) { fields.push('work_description = ?'); values.push(data.work_description || null); }
if (data.workplace_name !== undefined) { fields.push('workplace_name = ?'); values.push(data.workplace_name || null); }
if (data.expected_workers !== undefined) { fields.push('expected_workers = ?'); values.push(data.expected_workers || null); }
@@ -81,4 +102,4 @@ async function deleteSchedule(id) {
await db.query('DELETE FROM partner_schedules WHERE id = ?', [id]);
}
module.exports = { findAll, findById, findByCompanyToday, create, update, updateStatus, deleteSchedule };
module.exports = { findAll, findById, findByCompanyToday, findByProject, create, update, updateStatus, deleteSchedule };

View File

@@ -0,0 +1,10 @@
const express = require('express');
const router = express.Router();
const { requireAuth } = require('../middleware/auth');
const ctrl = require('../controllers/projectController');
router.use(requireAuth);
router.get('/active', ctrl.getActive);
module.exports = router;

View File

@@ -78,7 +78,8 @@
<thead>
<tr>
<th>업체</th>
<th>작업일</th>
<th>기간</th>
<th>프로젝트</th>
<th>작업내용</th>
<th class="hide-mobile">작업장</th>
<th class="text-center">예상인원</th>
@@ -87,7 +88,7 @@
</tr>
</thead>
<tbody id="scheduleTableBody">
<tr><td colspan="7" class="text-center text-gray-400 py-8">로딩 중...</td></tr>
<tr><td colspan="8" class="text-center text-gray-400 py-8">로딩 중...</td></tr>
</tbody>
</table>
</div>
@@ -112,9 +113,21 @@
<input type="hidden" id="addCompanyId">
<div id="addCompanyDropdown" class="hidden absolute z-10 w-full mt-1 bg-white border rounded-lg shadow-lg max-h-48 overflow-y-auto"></div>
</div>
<div class="grid grid-cols-2 gap-3">
<div>
<label class="block text-xs font-medium text-gray-600 mb-1">시작일 <span class="text-red-400">*</span></label>
<input type="date" id="addStartDate" class="input-field w-full px-3 py-2 rounded-lg text-sm" required>
</div>
<div>
<label class="block text-xs font-medium text-gray-600 mb-1">종료일 <span class="text-red-400">*</span></label>
<input type="date" id="addEndDate" class="input-field w-full px-3 py-2 rounded-lg text-sm" required>
</div>
</div>
<div>
<label class="block text-xs font-medium text-gray-600 mb-1">작업일 <span class="text-red-400">*</span></label>
<input type="date" id="addWorkDate" class="input-field w-full px-3 py-2 rounded-lg text-sm" required>
<label class="block text-xs font-medium text-gray-600 mb-1">프로젝트</label>
<select id="addProject" class="input-field w-full px-3 py-2 rounded-lg text-sm">
<option value="">선택 안함</option>
</select>
</div>
<div>
<label class="block text-xs font-medium text-gray-600 mb-1">작업내용</label>
@@ -157,9 +170,21 @@
<input type="hidden" id="editCompanyId">
<div id="editCompanyDropdown" class="hidden absolute z-10 w-full mt-1 bg-white border rounded-lg shadow-lg max-h-48 overflow-y-auto"></div>
</div>
<div class="grid grid-cols-2 gap-3">
<div>
<label class="block text-xs font-medium text-gray-600 mb-1">시작일 <span class="text-red-400">*</span></label>
<input type="date" id="editStartDate" class="input-field w-full px-3 py-2 rounded-lg text-sm" required>
</div>
<div>
<label class="block text-xs font-medium text-gray-600 mb-1">종료일 <span class="text-red-400">*</span></label>
<input type="date" id="editEndDate" class="input-field w-full px-3 py-2 rounded-lg text-sm" required>
</div>
</div>
<div>
<label class="block text-xs font-medium text-gray-600 mb-1">작업일 <span class="text-red-400">*</span></label>
<input type="date" id="editWorkDate" class="input-field w-full px-3 py-2 rounded-lg text-sm" required>
<label class="block text-xs font-medium text-gray-600 mb-1">프로젝트</label>
<select id="editProject" class="input-field w-full px-3 py-2 rounded-lg text-sm">
<option value="">선택 안함</option>
</select>
</div>
<div>
<label class="block text-xs font-medium text-gray-600 mb-1">작업내용</label>

View File

@@ -52,12 +52,13 @@ async function loadTodaySchedules() {
const statusMap = { scheduled: ['badge-amber', '예정'], in_progress: ['badge-green', '진행중'], completed: ['badge-blue', '완료'], cancelled: ['badge-gray', '취소'] };
c.innerHTML = list.map(s => {
const [cls, label] = statusMap[s.status] || ['badge-gray', s.status];
const dateDisplay = formatDate(s.start_date) === formatDate(s.end_date) ? formatDate(s.start_date) : formatDate(s.start_date) + ' ~ ' + formatDate(s.end_date);
return `<div class="p-3 bg-gray-50 rounded-lg">
<div class="flex items-center justify-between">
<span class="text-sm font-medium">${escapeHtml(s.company_name || '')}</span>
<span class="badge ${cls}">${label}</span>
</div>
<div class="text-xs text-gray-500 mt-1">${escapeHtml(s.workplace_name || '')} · ${s.expected_workers || 0}명</div>
<div class="text-xs text-gray-500 mt-1">${dateDisplay} · ${escapeHtml(s.workplace_name || '')} · ${s.expected_workers || 0}명</div>
${s.work_description ? `<div class="text-xs text-gray-400 mt-0.5 truncate">${escapeHtml(s.work_description)}</div>` : ''}
</div>`;
}).join('');

View File

@@ -58,7 +58,7 @@ async function renderScheduleCards() {
<div class="p-5 border-b">
<div class="flex items-center justify-between mb-2">
<h3 class="text-base font-semibold text-gray-800">${escapeHtml(s.workplace_name || '작업장 미지정')}</h3>
<span class="text-xs text-gray-500">${formatDate(s.work_date)}</span>
<span class="text-xs text-gray-500">${formatDate(s.start_date) === formatDate(s.end_date) ? formatDate(s.start_date) : formatDate(s.start_date) + ' ~ ' + formatDate(s.end_date)}</span>
</div>
${s.work_description ? `<p class="text-sm text-gray-600 mb-2">${escapeHtml(s.work_description)}</p>` : ''}
<div class="flex gap-4 text-xs text-gray-500">

View File

@@ -3,6 +3,39 @@
let schedulePage = 1;
const scheduleLimit = 20;
let companySearchTimer = null;
let projectList = [];
async function loadProjects() {
try {
const r = await api('/projects/active');
projectList = r.data || [];
} catch(e) {
console.warn('Load projects error:', e);
projectList = [];
}
}
function populateProjectDropdown(selectId, selectedId) {
const select = document.getElementById(selectId);
select.innerHTML = '<option value="">선택 안함</option>';
projectList.forEach(p => {
const label = p.job_no ? `[${p.job_no}] ${p.project_name}` : p.project_name;
select.innerHTML += `<option value="${p.project_id}" ${p.project_id == selectedId ? 'selected' : ''}>${escapeHtml(label)}</option>`;
});
}
function formatDateRange(startDate, endDate) {
const s = formatDate(startDate);
const e = formatDate(endDate);
if (s === e) return s;
// 같은 연도이면 월/일만 표시
const sd = new Date(startDate);
const ed = new Date(endDate);
if (sd.getFullYear() === ed.getFullYear()) {
return `${sd.getMonth()+1}/${sd.getDate()} ~ ${ed.getMonth()+1}/${ed.getDate()}`;
}
return `${s} ~ ${e}`;
}
async function loadSchedules() {
const company = document.getElementById('filterCompany').value.trim();
@@ -21,14 +54,14 @@ async function loadSchedules() {
renderScheduleTable(r.data || [], r.total || 0);
} catch(e) {
console.warn('Schedule load error:', e);
document.getElementById('scheduleTableBody').innerHTML = '<tr><td colspan="7" class="text-center text-red-400 py-8">로딩 실패</td></tr>';
document.getElementById('scheduleTableBody').innerHTML = '<tr><td colspan="8" class="text-center text-red-400 py-8">로딩 실패</td></tr>';
}
}
function renderScheduleTable(list, total) {
const tbody = document.getElementById('scheduleTableBody');
if (!list.length) {
tbody.innerHTML = '<tr><td colspan="7" class="text-center text-gray-400 py-8">일정이 없습니다</td></tr>';
tbody.innerHTML = '<tr><td colspan="8" class="text-center text-gray-400 py-8">일정이 없습니다</td></tr>';
document.getElementById('schedulePagination').innerHTML = '';
return;
}
@@ -43,9 +76,11 @@ function renderScheduleTable(list, total) {
tbody.innerHTML = list.map(s => {
const [cls, label] = statusMap[s.status] || ['badge-gray', s.status];
const canEdit = s.status === 'scheduled';
const projectLabel = s.project_name ? (s.job_no ? `[${s.job_no}] ${s.project_name}` : s.project_name) : '';
return `<tr>
<td class="font-medium">${escapeHtml(s.company_name || '')}</td>
<td>${formatDate(s.work_date)}</td>
<td class="whitespace-nowrap">${formatDateRange(s.start_date, s.end_date)}</td>
<td class="text-xs text-gray-500">${escapeHtml(projectLabel)}</td>
<td class="max-w-xs truncate">${escapeHtml(s.work_description || '')}</td>
<td class="hide-mobile">${escapeHtml(s.workplace_name || '')}</td>
<td class="text-center">${s.expected_workers || 0}명</td>
@@ -131,12 +166,16 @@ function selectCompany(inputId, hiddenId, dropdownId, id, name) {
}
/* ===== Add Schedule ===== */
function openAddSchedule() {
async function openAddSchedule() {
document.getElementById('addScheduleForm').reset();
document.getElementById('addCompanyId').value = '';
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
document.getElementById('addWorkDate').value = tomorrow.toISOString().substring(0, 10);
const tomorrowStr = tomorrow.toISOString().substring(0, 10);
document.getElementById('addStartDate').value = tomorrowStr;
document.getElementById('addEndDate').value = tomorrowStr;
await loadProjects();
populateProjectDropdown('addProject', '');
document.getElementById('addScheduleModal').classList.remove('hidden');
}
@@ -149,9 +188,17 @@ async function submitAddSchedule(e) {
const companyId = document.getElementById('addCompanyId').value;
if (!companyId) { showToast('업체를 선택하세요', 'error'); return; }
const startDate = document.getElementById('addStartDate').value;
const endDate = document.getElementById('addEndDate').value;
if (endDate < startDate) { showToast('종료일은 시작일 이후여야 합니다', 'error'); return; }
const projectId = document.getElementById('addProject').value;
const body = {
partner_company_id: parseInt(companyId),
work_date: document.getElementById('addWorkDate').value,
company_id: parseInt(companyId),
start_date: startDate,
end_date: endDate,
project_id: projectId ? parseInt(projectId) : null,
work_description: document.getElementById('addWorkDescription').value.trim(),
workplace_name: document.getElementById('addWorkplaceName').value.trim(),
expected_workers: parseInt(document.getElementById('addExpectedWorkers').value) || 0,
@@ -179,12 +226,15 @@ async function openEditSchedule(id) {
document.getElementById('editScheduleId').value = id;
document.getElementById('editCompanySearch').value = s.company_name || '';
document.getElementById('editCompanyId').value = s.partner_company_id || '';
document.getElementById('editWorkDate').value = formatDate(s.work_date);
document.getElementById('editCompanyId').value = s.company_id || '';
document.getElementById('editStartDate').value = formatDate(s.start_date);
document.getElementById('editEndDate').value = formatDate(s.end_date);
document.getElementById('editWorkDescription').value = s.work_description || '';
document.getElementById('editWorkplaceName').value = s.workplace_name || '';
document.getElementById('editExpectedWorkers').value = s.expected_workers || 0;
document.getElementById('editNotes').value = s.notes || '';
await loadProjects();
populateProjectDropdown('editProject', s.project_id || '');
document.getElementById('editScheduleModal').classList.remove('hidden');
} catch(e) {
showToast('일정 정보를 불러올 수 없습니다', 'error');
@@ -201,9 +251,17 @@ async function submitEditSchedule(e) {
const companyId = document.getElementById('editCompanyId').value;
if (!companyId) { showToast('업체를 선택하세요', 'error'); return; }
const startDate = document.getElementById('editStartDate').value;
const endDate = document.getElementById('editEndDate').value;
if (endDate < startDate) { showToast('종료일은 시작일 이후여야 합니다', 'error'); return; }
const projectId = document.getElementById('editProject').value;
const body = {
partner_company_id: parseInt(companyId),
work_date: document.getElementById('editWorkDate').value,
company_id: parseInt(companyId),
start_date: startDate,
end_date: endDate,
project_id: projectId ? parseInt(projectId) : null,
work_description: document.getElementById('editWorkDescription').value.trim(),
workplace_name: document.getElementById('editWorkplaceName').value.trim(),
expected_workers: parseInt(document.getElementById('editExpectedWorkers').value) || 0,