Files
TK-FB-Project/web-ui/js/modules/calendar/CalendarAPI.js
Hyungi Ahn 8a8307edfc refactor(frontend): Begin modularizing work-report-calendar
Initiated the process of refactoring the monolithic `work-report-calendar.js` file as outlined in the Phase 2 frontend modernization plan.

- Created `CalendarAPI.js` to encapsulate all API calls related to the calendar, centralizing data fetching logic.
- Created `CalendarState.js` to manage the component's state, removing global variables from the main script.
- Refactored `work-report-calendar.js` to use the new state and API modules.
- Refactored `manage-project.js` to use the existing global API helpers, providing a consistent example for API usage.
2025-12-19 10:46:29 +09:00

132 lines
4.6 KiB
JavaScript

// web-ui/js/modules/calendar/CalendarAPI.js
/**
* 캘린더와 관련된 모든 API 호출을 관리하는 전역 객체입니다.
*/
(function(window) {
'use strict';
const CalendarAPI = {};
/**
* 활성화된 모든 작업자 목록을 가져옵니다.
* @returns {Promise<Array>} 작업자 객체 배열
*/
CalendarAPI.getWorkers = async function() {
try {
// api-helper.js 에 정의된 전역 apiGet 함수를 사용합니다.
const response = await window.apiGet('/workers');
if (response.success && Array.isArray(response.data)) {
// 활성화된 작업자만 필터링
const activeWorkers = response.data.filter(worker =>
worker.status === 'active' || worker.is_active === 1 || worker.is_active === true
);
return activeWorkers;
}
console.warn('API 응답 형식이 올바르지 않거나 데이터가 없습니다:', response);
return [];
} catch (error) {
console.error('작업자 데이터 로딩 중 API 오류 발생:', error);
// 에러를 다시 던져서 호출부에서 처리할 수 있도록 함
throw new Error('작업자 데이터를 불러오는 데 실패했습니다.');
}
};
/**
* 월별 작업 데이터 로드 (집계 테이블 사용으로 최적화)
* @param {number} year
* @param {number} month (0-indexed)
* @returns {Promise<object>}
*/
CalendarAPI.getMonthlyCalendarData = async function(year, month) {
const monthKey = `${year}-${String(month + 1).padStart(2, '0')}`;
try {
const response = await window.apiGet(`/monthly-status/calendar?year=${year}&month=${month + 1}`);
if (response.success) {
return response.data;
} else {
throw new Error(response.message || '집계 데이터 조회 실패');
}
} catch (error) {
console.error(`${monthKey} 집계 데이터 로딩 오류:`, error);
console.log(`📋 폴백: ${monthKey} 기존 방식 로딩 시작...`);
return await _getMonthlyWorkDataFallback(year, month);
}
};
/**
* 일일 상세 데이터 조회 (모달용)
* @param {string} dateStr (YYYY-MM-DD)
* @returns {Promise<object>}
*/
CalendarAPI.getDailyDetails = async function(dateStr) {
try {
const response = await window.apiGet(`/monthly-status/daily-details?date=${dateStr}`);
if (response.success) {
return response.data;
}
// Fallback to old API if new one fails
const fallbackResponse = await window.apiGet(`/daily-work-reports?date=${dateStr}&view_all=true`);
return {
workers: fallbackResponse.data, // Assuming structure is different
summary: {} // No summary in fallback
};
} catch (error) {
console.error('일일 작업 데이터 로딩 오류:', error);
throw new Error('해당 날짜의 작업 데이터를 불러오는 데 실패했습니다.');
}
};
/**
* 특정 작업자의 하루치 작업을 모두 삭제합니다.
* @param {number} workerId
* @param {string} date (YYYY-MM-DD)
* @returns {Promise<object>}
*/
CalendarAPI.deleteWorkerDayWork = async function(workerId, date) {
return await window.apiDelete(`/daily-work-reports/date/${date}/worker/${workerId}`);
};
/**
* 폴백: 순차적 로딩 (지연 시간 포함) - Private helper
* @param {number} year
* @param {number} month (0-indexed)
* @returns {Promise<object>}
*/
async function _getMonthlyWorkDataFallback(year, month) {
const monthKey = `${year}-${String(month + 1).padStart(2, '0')}`;
const monthData = {};
try {
const firstDay = new Date(year, month, 1);
const lastDay = new Date(year, month + 1, 0);
const currentDay = new Date(firstDay);
const promises = [];
while (currentDay <= lastDay) {
const dateStr = currentDay.toISOString().split('T')[0];
promises.push(window.apiGet(`/daily-work-reports?date=${dateStr}&view_all=true`));
currentDay.setDate(currentDay.getDate() + 1);
}
const results = await Promise.all(promises);
let day = 1;
for (const result of results) {
const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
monthData[dateStr] = result.success && Array.isArray(result.data) ? result.data : [];
day++;
}
return monthData;
} catch (error) {
console.error(`${monthKey} 순차 로딩 오류:`, error);
throw new Error('작업 데이터를 불러오는 데 실패했습니다.');
}
}
// 전역 스코프에 CalendarAPI 객체 할당
window.CalendarAPI = CalendarAPI;
})(window);