Project

ERP 프로젝트 - FullCalendar

아잠만_ 2024. 10. 11. 15:34

위 사진은 본사의 상담을 하는 사람들의 일정을 가독성이 좋게 하기 위해 fullCalendar API를 활용하기로 결정하였다.

먼저 API를 사용하기 위해선 해당 script를 import해야한다

JavaScript

<script src="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.15/index.global.min.js"></script>

이벤트를 전체를 가져오기 보단 달력에 보이는 영역마다 해당하는 상담 일정을 보이는 형식으로 이벤트를 삭제하고 추가하는 형식으로 설정했다.

///////////// 상담 달력 이벤트 추가
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
    initialView: "dayGridMonth",
    firstDay: 1,
    buttonText: {
        today: '오늘'  // today 버튼 텍스트를 "오늘"로 변경
    },
    datesSet: function(info) { // 사용자가 달력을 이동할 때 발생하는 이벤트
        // 현재 조회 중인 달의 시작일과 종료일 가져오기
        var startDate = info.startStr.split('T')[0];  // '2024-09-30' 형식으로 변환
        var endDate = info.endStr.split('T')[0];      // '2024-11-11' 형식으로 변환

        console.log(startDate, endDate);
     // AJAX로 서버에 조회 중인 기간 데이터를 요청
        $.ajax({
          url: '/hdofc/getEvent',
          type: 'POST',
           // csrf설정 secuity설정된 경우 필수!!
            beforeSend:function(xhr){ 
                xhr.setRequestHeader(csrfHeader, csrfToken); // CSRF 헤더와 토큰을 설정
            },
          contentType: 'application/json',
          data: JSON.stringify({
            startDate: startDate,
            endDate: endDate
          }),
          success: function(res) {
            // 서버로부터 받은 데이터를 처리하여 FullCalendar에 반영
            calendar.removeAllEvents(); // 기존 이벤트 제거

            // 서버에서 받은 데이터가 객체라고 가정하고, 객체의 값을 배열처럼 처리
            Object.values(res).forEach(function(event) {
              // 각 이벤트 추가
              var eventData = {
                title: event.mbrNm,          // VO에서 mbrNm을 이벤트 제목으로 설정
                start: event.dscsnPlanYmd,   // VO에서 dscsnPlanYmd를 이벤트 날짜로 설정 (YYYY-MM-DD 형식)
                allDay: true                 // 하루 종일 이벤트로 설정
              };

              // 이벤트 소스에 추가
              calendar.addEvent(eventData);
            });
          },
          error: function(xhr, status, error) {
            console.error('Error:', error); // 에러 처리
          }
        });
     },
// 	    showNonCurrentDates: false,  // 현재 달 외의 날짜를 숨김
    titleFormat: function (date) {
      year = date.date.year;
      month = date.date.month + 1;

      return year + "년 " + month + "월";
    },
});
calendar.render();

처음에 calendar를 가져올 때 기존에 썼던 css와 합쳐져서 그런지 css설정도 이상해 메인에 넣기 적당한 style로 변경하였으며 이때 토요일과 일요일에 글씨 색 효과를 추가하였다.

CSS

/* 캘린더 */
.fc .fc-toolbar.fc-header-toolbar {
    margin-bottom: 0;
    padding: var(--pd--s);
}

.fc-toolbar-title{
	font-size : 1rem !important;	
}
/* today */
.fc .fc-button-primary{
	width: 50px !important;
    font-size: 0.7rem !important;
}
.fc .fc-daygrid-day-number, .fc .fc-col-header-cell-cushion {
	color: var(--blue--8);
}
.fc-button-primary{
	width: 30px !important;
    height: 30px !important;
    padding: 0 !important;   /* 기본 패딩 제거 */
    display: flex !important; /* 가운데 정렬을 위한 flex 설정 */
    align-items: center !important; /* 수직 가운데 정렬 */
    justify-content: center !important; /* 수평 가운데 정렬 */	
}
.fc-toolbar-chunk{
	display: flex !important;
}
.fc-icon{
	color: white !important;
    font-size: 16px !important;
    width: 100% !important;    
    height: auto !important;    
}
.fc-event {
    background-color: var(--green--3) !important;  /* 이벤트 배경 색상 */
    border-color: var(--green--3) !important;      /* 이벤트 테두리 색상 */
    color: var(--blue--8) !important;             /* 이벤트 글자 색상 */
}

/* 일요일 날짜 빨간색 */
.fc-day-sun a {
  color: var(--red--5) !important;
  text-decoration: none;
}

/* 토요일 날짜 파란색 */
.fc-day-sat a {
  color: var(--blue--5) !important;
  text-decoration: none;
}
#calendar {
    max-width: 100%;
    width: 600px; /* 기본 크기 600px */
    margin: 0 auto;
}

@media (max-width: 768px) {
    #calendar {
        width: 100%; /* 작은 화면에서는 전체 너비로 설정 */
    }
}