[FO] 일계부 월별현황 목록 Model 변경

This commit is contained in:
김현주
2025-06-16 12:18:33 +09:00
parent 132077a3c4
commit 152d5e5e42
11 changed files with 791 additions and 205 deletions

View File

@@ -13,32 +13,19 @@ import java.util.List;
@Mapper
public interface RecordCalendarMapper {
List<DailyRecordCalendarDto> getCalendarByDailyRecord(RecordCalendarUIReqVO reqVO);
/**
* 특정월의 일 그룹 목록 조회
*
* @param reqVO 검색 조건
* @return 특정월의 그룹 목록
*/
List<DailyRecordCalendarDto> getCalendarByDailyRecord(RecordCalendarUIReqVO reqVO);
DailyRecordStatusDto getDailyRecordStatus(RecordCalendarUIReqVO reqVO);
int getStartDayByDailyGroupNo(@Param("groupNo") Integer groupNo);
/**
* 일계부 등록 여부
* @param householdSeq
* @param recordMonth
* @param dayGroupNo
* @return
*/
Long getDailyRecordExistCount(@Param("householdSeq") Long householdSeq, @Param("recordMonth") String recordMonth, @Param("dayGroupNo") Integer dayGroupNo);
/**
* 일계부 등록(생성)
* @param command
* @return
*/
Long createDailyRecord(CreateDailyRecordReqVO command);
/**
* 일계부 상태 수정
* @param command
* @return
*/
int updateDailyRecordStatus(UpdateDailyRecordStatusCmd command);
/**
* 특정일의 일계부 등록 상태 조회
*
* @param reqVO 검색 조건
* @return 일계부 등록 현황 목록
*/
List<DailyRecordStatusDto> getDailyRecordStatus(RecordCalendarUIReqVO reqVO);
}

View File

@@ -6,9 +6,9 @@ import lombok.Setter;
@Getter
@Setter
public class DailyRecordCalendarDto {
private String groupNo;
private Integer groupNo;
private Integer startDay;
private Integer endDay;
private String startDate;
private String dailyId;
private Long dailyId;
}

View File

@@ -1,5 +1,8 @@
package app.module.front.usecase.daily.calendar.persistence.model;
import app.module.front.usecase.daily.record.web.model.DailyStatus;
import app.module.front.usecase.daily.record.web.model.DailyTargetStatus;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.ToString;
@@ -8,22 +11,72 @@ import java.time.LocalDate;
@Data
@ToString
public class DailyRecordStatusDto {
/**
* 일계부 일련번호
*/
private Long dailyId;
private LocalDate startDate;
private LocalDate endDate;
/**
* 특정일 입력 상태 TODO enum
*/
private String allStatus;
/**
* 수입 입력 상태 TODO enum
*/
private String incomeStatus;
/**
* 수입 입력 개수
*/
private Integer incomeCount;
/**
* 일계부 일련번호
*/
private Long dailyId;
/**
* 특정일의 그룹 번호
*/
private Integer dayGroupNo;
/**
* 시작일
*/
private LocalDate startDate;
/**
* 종료일
*/
private LocalDate endDate;
/**
* 특정일 입력 상태
*/
private DailyStatus allStatus;
/**
* 수입 입력 상태
*/
private DailyTargetStatus incomeStatus;
/**
* 임업노동 입력 상태
*/
private DailyTargetStatus workStatus;
/**
* 지출 입력 상태
*/
private DailyTargetStatus expenseStatus;
/**
* 동력 사용시간 입력 상태
*/
private DailyTargetStatus powerStatus;
/**
* 자가임업 입력 상태
*/
private DailyTargetStatus forestryStatus;
/**
* 자가농업 입력 상태
*/
private DailyTargetStatus farmingStatus;
/**
* 수입 입력 개수
*/
private Integer incomeCount;
/**
* 임업노동 입력 개수
*/
private Integer workCount;
/**
* 지출 입력 개수
*/
private Integer expenseCount;
/**
* 동력 사용시간 입력 개수
*/
private Integer powerCount;
/**
* 자가임업 입력 개수
*/
private Integer forestryCount;
/**
* 자가농업 입력 개수
*/
private Integer farmingCount;
}

View File

@@ -1,16 +1,16 @@
package app.module.front.usecase.daily.calendar.service;
import app.module.front.usecase.daily.calendar.persistence.model.DailyRecordCalendarDto;
import app.module.front.usecase.daily.calendar.persistence.model.DailyRecordStatusDto;
import app.module.front.usecase.daily.calendar.web.model.RecordCalendarUIReqVO;
import app.module.front.usecase.daily.calendar.web.model.RecordCalendarUIResVO;
import java.util.List;
public interface RecordCalendarService {
List<DailyRecordCalendarDto> getCalendarByDailyRecord(RecordCalendarUIReqVO reqVO);
DailyRecordStatusDto getDailyRecordStatus(RecordCalendarUIReqVO reqVO);
int getStartDayByDailyGroupNo(RecordCalendarUIReqVO reqVO);
/**
* 특정월의 일계부 현황 조회
*
* @param reqVO 검색 조건
* @return 월별 일계부 목록
*/
List<RecordCalendarUIResVO> getCalendarByDailyRecord(RecordCalendarUIReqVO reqVO);
}

View File

@@ -3,52 +3,138 @@ package app.module.front.usecase.daily.calendar.service;
import app.module.front.usecase.daily.calendar.persistence.RecordCalendarMapper;
import app.module.front.usecase.daily.calendar.persistence.model.DailyRecordCalendarDto;
import app.module.front.usecase.daily.calendar.persistence.model.DailyRecordStatusDto;
import app.module.front.usecase.daily.calendar.web.model.RecordCalendarChildrenVO;
import app.module.front.usecase.daily.calendar.web.model.RecordCalendarUIReqVO;
import app.module.front.usecase.daily.calendar.web.model.RecordCalendarUIResVO;
import app.module.front.usecase.daily.record.persistence.DailyRecordMapper;
import app.module.front.usecase.daily.record.web.model.DailyTargetStatus;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.*;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class RecordCalendarServiceImpl implements RecordCalendarService {
private final RecordCalendarMapper recordCalendarMapper;
private final RecordCalendarMapper recordCalendarMapper;
@Override
public List<DailyRecordCalendarDto> getCalendarByDailyRecord(RecordCalendarUIReqVO reqVO) {
int lastDay = reqVO.getSearchDate().withDayOfMonth(reqVO.getSearchDate().lengthOfMonth()).getDayOfMonth();
@Override
public List<RecordCalendarUIResVO> getCalendarByDailyRecord(RecordCalendarUIReqVO reqVO) {
List<DailyRecordCalendarDto> calendarList = this.getCalendarList(reqVO);
List<DailyRecordStatusDto> statusList = this.getDailyRecordStatus(reqVO);
List<DailyRecordCalendarDto> list = recordCalendarMapper.getCalendarByDailyRecord(reqVO);
String pathFormat = "/record/%s/%s/%s";
List<DailyRecordCalendarDto> refineList = new ArrayList<DailyRecordCalendarDto>();
for (DailyRecordCalendarDto record : list) {
record.setStartDate(reqVO.getSearchMonth() + String.format("%02d", record.getStartDay()));
List<RecordCalendarUIResVO> refineList = new ArrayList<>();
for (DailyRecordCalendarDto calendar : calendarList) {
RecordCalendarUIResVO refine = new RecordCalendarUIResVO();
refine.setNo(calendar.getGroupNo());
refine.setStart(calendar.getStartDay());
refine.setEnd(calendar.getEndDay());
if ((lastDay == 28 || lastDay == 30) && record.getStartDay() == lastDay) {
record.setEndDay(lastDay);
refineList.add(record);
} else if (record.getStartDay() <= lastDay && record.getEndDay() <= lastDay) {
refineList.add(record);
}
DailyRecordStatusDto findStatus = statusList.stream()
.filter(f -> Objects.equals(calendar.getDailyId(), f.getDailyId()))
.findFirst().orElse(null);
if (findStatus == null) {
refine.setChildren(new ArrayList<>());
} else {
List<RecordCalendarChildrenVO> childList = new ArrayList<>();
if (DailyTargetStatus.TARGET.equals(findStatus.getIncomeStatus())) {
childList.add(new RecordCalendarChildrenVO(
"INCOME",
"수입",
findStatus.getIncomeCount(),
String.format(pathFormat, "income", reqVO.getSearchMonth(), findStatus.getDayGroupNo())));
}
if (DailyTargetStatus.TARGET.equals(findStatus.getWorkStatus())) {
childList.add(new RecordCalendarChildrenVO(
"WORK",
"임업노동 투입 내역",
findStatus.getWorkCount(),
String.format(pathFormat, "work", reqVO.getSearchMonth(), findStatus.getDayGroupNo())));
}
if (DailyTargetStatus.TARGET.equals(findStatus.getExpenseStatus())) {
childList.add(new RecordCalendarChildrenVO(
"EXPENSE",
"지출",
findStatus.getExpenseCount(),
String.format(pathFormat, "expense", reqVO.getSearchMonth(), findStatus.getDayGroupNo())));
}
if (DailyTargetStatus.TARGET.equals(findStatus.getPowerStatus())) {
childList.add(new RecordCalendarChildrenVO(
"POWER",
"동력 사용시간",
findStatus.getPowerCount(),
String.format(pathFormat, "power", reqVO.getSearchMonth(), findStatus.getDayGroupNo())));
}
if (DailyTargetStatus.TARGET.equals(findStatus.getForestryStatus())) {
childList.add(new RecordCalendarChildrenVO(
"FORESTRY",
"자가임업 생산물 중 자가소비량",
findStatus.getForestryCount(),
String.format(pathFormat, "forestry", reqVO.getSearchMonth(), findStatus.getDayGroupNo())));
}
if (DailyTargetStatus.TARGET.equals(findStatus.getFarmingStatus())) {
childList.add(new RecordCalendarChildrenVO(
"FARMING",
"자가농업 생산물 중 자가소비량",
findStatus.getFarmingCount(),
String.format(pathFormat, "farming", reqVO.getSearchMonth(), findStatus.getDayGroupNo())));
}
refine.setChildren(childList);
}
refineList.add(refine);
}
return refineList;
}
return refineList;
}
/**
* 특정월의 일 그룹 조회
*
* @param reqVO
* @return
*/
private List<DailyRecordCalendarDto> getCalendarList(RecordCalendarUIReqVO reqVO) {
int lastDay = reqVO.getSearchDate().withDayOfMonth(reqVO.getSearchDate().lengthOfMonth()).getDayOfMonth();
@Override
public DailyRecordStatusDto getDailyRecordStatus(RecordCalendarUIReqVO reqVO) {
return recordCalendarMapper.getDailyRecordStatus(reqVO);
}
List<DailyRecordCalendarDto> calendarList = recordCalendarMapper.getCalendarByDailyRecord(reqVO);
@Override
public int getStartDayByDailyGroupNo(RecordCalendarUIReqVO reqVO) {
return recordCalendarMapper.getStartDayByDailyGroupNo(reqVO.getGroupNo());
}
List<DailyRecordCalendarDto> refineList = new ArrayList<>();
for (DailyRecordCalendarDto record : calendarList) {
record.setStartDate(reqVO.getSearchMonth() + String.format("%02d", record.getStartDay()));
if ((lastDay == 28 || lastDay == 30) && record.getStartDay() == lastDay) {
record.setEndDay(lastDay);
refineList.add(record);
} else if (record.getStartDay() <= lastDay && record.getEndDay() <= lastDay) {
refineList.add(record);
}
}
return refineList;
}
/**
* 특정월의 일계부 등록 상태 조회
*
* @param reqVO
* @return
*/
private List<DailyRecordStatusDto> getDailyRecordStatus(RecordCalendarUIReqVO reqVO) {
List<DailyRecordStatusDto> statusList = recordCalendarMapper.getDailyRecordStatus(reqVO);
if (statusList == null || statusList.isEmpty()) {
return Collections.emptyList();
}
return statusList;
}
}

View File

@@ -3,7 +3,9 @@ package app.module.front.usecase.daily.calendar.web;
import app.module.front.usecase.daily.calendar.persistence.model.DailyRecordCalendarDto;
import app.module.front.usecase.daily.calendar.persistence.model.DailyRecordStatusDto;
import app.module.front.usecase.daily.calendar.service.RecordCalendarService;
import app.module.front.usecase.daily.calendar.web.model.RecordCalendarChildrenVO;
import app.module.front.usecase.daily.calendar.web.model.RecordCalendarUIReqVO;
import app.module.front.usecase.daily.calendar.web.model.RecordCalendarUIResVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
@@ -14,6 +16,7 @@ import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@@ -21,46 +24,16 @@ import java.util.List;
@RequiredArgsConstructor
@RequestMapping(path = "/record/calendar")
public class RecordCalendarController {
private final RecordCalendarService recordCalendarService;
private final RecordCalendarService recordCalendarService;
@GetMapping(path = "")
public String index(Model model, @RequestParam(value = "searchDay", required = false) String searchDay) {
RecordCalendarUIReqVO reqVO = new RecordCalendarUIReqVO(searchDay, getAccessId());
log.debug("reqVO: {}", reqVO);
@GetMapping(path = "")
public String index(Model model, @RequestParam(value = "searchDay", required = false) String searchDay) {
RecordCalendarUIReqVO reqVO = new RecordCalendarUIReqVO(searchDay);
log.debug("reqVO: {}", reqVO);
model.addAttribute("reqVO", reqVO);
model.addAttribute("calendarList", recordCalendarService.getCalendarByDailyRecord(reqVO));
model.addAttribute("reqVO", reqVO);
model.addAttribute("calendarList", recordCalendarService.getCalendarByDailyRecord(reqVO));
return "record/calendar";
}
@PostMapping(path = "/{searchMonth}/{groupNo}")
public String detail(Model model
, @PathVariable(required = true) String searchMonth
, @PathVariable(required = true) String groupNo) {
RecordCalendarUIReqVO reqVO = new RecordCalendarUIReqVO();
reqVO.setSearchMonth(searchMonth);
reqVO.setGroupNo(Integer.parseInt(groupNo));
reqVO.setHouseholdSeq(getAccessId());
log.debug("reqVO: {}", reqVO);
DailyRecordStatusDto detail = recordCalendarService.getDailyRecordStatus(reqVO);
if (detail == null) {
int startDay = recordCalendarService.getStartDayByDailyGroupNo(reqVO);
reqVO.setSearchDay(reqVO.getSearchMonth() + String.format("%02d", startDay));
return "record/calendar";
}
//uiCodeListPortIn.connect("code.pageable.rows");
model.addAttribute("reqVO", reqVO);
model.addAttribute("detail", detail);
return "record/calendar-wrap";
}
// TODO : 로그인 SEQ
private Long getAccessId() {
return 2L;
}
}

View File

@@ -0,0 +1,19 @@
package app.module.front.usecase.daily.calendar.web.model;
import app.module.front.usecase.daily.calendar.persistence.model.DailyRecordStatusDto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.ToString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
@Data
@AllArgsConstructor
public class RecordCalendarChildrenVO {
private String code;
private String codeLabel;
private Integer total;
private String path;
}

View File

@@ -1,8 +1,7 @@
package app.module.front.usecase.daily.calendar.web.model;
import app.module.front.usecase.daily.record.web.model.DailyUIReqVO;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.apache.tika.utils.StringUtils;
import org.slf4j.Logger;
@@ -10,64 +9,48 @@ import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Date;
import java.util.Locale;
@Data
@ToString
public class RecordCalendarUIReqVO {
private static final Logger LOGGER = LoggerFactory.getLogger(RecordCalendarUIReqVO.class);
public class RecordCalendarUIReqVO extends DailyUIReqVO {
private static final Logger LOGGER = LoggerFactory.getLogger(RecordCalendarUIReqVO.class);
public RecordCalendarUIReqVO() {
}
public RecordCalendarUIReqVO(String searchDay, Long accessId) {
if (StringUtils.isBlank(searchDay) || searchDay.length() != 8) {
searchDay = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
public RecordCalendarUIReqVO() {
}
try {
SimpleDateFormat beforeSdf = new SimpleDateFormat("yyyyMMdd", Locale.KOREAN);
SimpleDateFormat afterSdf = new SimpleDateFormat("yyyy-MM-dd", Locale.KOREAN);
SimpleDateFormat monthSdf = new SimpleDateFormat("yyyyMM", Locale.KOREAN);
public RecordCalendarUIReqVO(String searchDay) {
if (StringUtils.isBlank(searchDay) || searchDay.length() != 8) {
searchDay = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
}
Date formatDate = beforeSdf.parse(searchDay);
try {
SimpleDateFormat beforeSdf = new SimpleDateFormat("yyyyMMdd", Locale.KOREAN);
SimpleDateFormat afterSdf = new SimpleDateFormat("yyyy-MM-dd", Locale.KOREAN);
SimpleDateFormat monthSdf = new SimpleDateFormat("yyyyMM", Locale.KOREAN);
setSearchDate(LocalDate.parse(afterSdf.format(formatDate)));
setSearchMonth(monthSdf.format(formatDate));
setSearchDay(beforeSdf.format(formatDate));
Date formatDate = beforeSdf.parse(searchDay);
} catch (Exception e) {
LOGGER.warn("[DateParse] target={}", searchDay, e);
setSearchDate(LocalDate.parse(afterSdf.format(formatDate)));
setSearchMonth(monthSdf.format(formatDate));
setSearchDay(beforeSdf.format(formatDate));
} catch (Exception e) {
LOGGER.warn("[DateParse] target={}", searchDay, e);
}
}
setHouseholdSeq(accessId);
}
/**
* 검색 일(yyyyMMdd)
*/
private String searchDay;
/**
* 검색 일(yyyyMMdd)
*/
private String searchDay;
/**
* 검색 월(yyyyMM)
*/
private String searchMonth;
private Integer groupNo;
/**
* 검색 일(yyyy-MM-dd)
*/
private LocalDate searchDate;
/**
* 임가회원 일련번호
*/
private Long householdSeq;
/**
* 검색 일(yyyy-MM-dd)
*/
private LocalDate searchDate;
}

View File

@@ -0,0 +1,19 @@
package app.module.front.usecase.daily.calendar.web.model;
import app.module.front.usecase.daily.calendar.persistence.model.DailyRecordStatusDto;
import lombok.Data;
import lombok.ToString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
@Data
@ToString
public class RecordCalendarUIResVO {
private static final Logger LOGGER = LoggerFactory.getLogger(RecordCalendarUIResVO.class);
private Integer no;
private Integer start;
private Integer end;
private List<RecordCalendarChildrenVO> children;
}

View File

@@ -19,43 +19,27 @@
<select id="getDailyRecordStatus"
resultType="app.module.front.usecase.daily.calendar.persistence.model.DailyRecordStatusDto">
select dr.id as daily_id
, dr.start_date, dr.end_date
, dr.day_group_no, dr.start_date, dr.end_date
, dr.all_status
, dr.income_status
, (select count(*) from daily_income di where di.daily_record_seq = dr.id and di.is_deleted = false) as income_count
, dr.work_status
, dr.expense_status
, dr.power_status
, dr.forestry_status
, dr.farming_status
, (select count(*) from daily_income di where di.daily_record_seq = dr.id and di.is_deleted = false) as income_count
, (select count(*) from daily_work dw where dw.daily_record_seq = dr.id and dw.is_deleted = false) as work_count
, (select count(*) from daily_expense de where de.daily_record_seq = dr.id and de.is_deleted = false) as expense_count
, (select count(*) from daily_power dp where dp.daily_record_seq = dr.id and dp.is_deleted = false) as power_count
, (select count(*) from daily_forestry df1 where df1.daily_record_seq = dr.id and df1.is_deleted = false) as forestry_count
, (select count(*) from daily_farming df2 where df2.daily_record_seq = dr.id and df2.is_deleted = false) as farming_count
from daily_record dr
where dr.is_deleted = false
and dr.household_seq = #{householdSeq}
and dr.record_month = #{searchMonth}
and dr.day_group_no = #{groupNo}
<if test="groupNo != null and groupNo != 'groupNo'">
and dr.day_group_no = #{groupNo}
</if>
</select>
<select id="getStartDayByDailyGroupNo"
resultType="int">
select ddg.start_day
from daily_day_group ddg
where ddg.is_deleted = false
and ddg.group_no = #{groupNo}
</select>
<select id="getDailyRecordExistCount"
resultType="int">
/* 일계부 데이터 존재 여부 getDailyRecordExistCount */
select count(*) as exist
from daily_record dr
where dr.household_seq = 2
and dr.is_deleted = false
and dr.record_month = '2025-06'
and dr.day_group_no = 3
</select>
<sql id="InnerJoinByDailyRecord">
/* TODO */
inner join daily_record dr on
dr.id = ds.daily_record_seq
and dr.is_deleted = false
and dr.recordMonth = #{recordMonth} and dr.day_group_no = #{dayGroupNo}
and dr.household_seq = #{householdSeq}
</sql>
</mapper>

View File

@@ -3,21 +3,25 @@
xmlns:th="http://www.thymeleaf.org" lang="ko">
<div layout:fragment="content" th:classappend="acco-wrap">
<main id="content" role="main">
<h2>calendar</h2>
<th:block th:if="${@systemProperties['spring.profiles.active'] eq 'local'}">
<div>
reqVO: [[${reqVO}]]
</div>
<div>
<th:block th:each="calendar, calendarStatus : ${calendarList}">
<th:block th:if="${not #strings.isEmpty(calendar.dailyId)}">
<span th:onclick="formControl.getDetail([[${reqVO.searchMonth}]], [[${calendar.groupNo}]])">
No=[[${calendar.groupNo}]], Start=[[${calendar.startDay}]], End=[[${calendar.endDay}]], StartDate=[[${calendar.startDate}]], Id=[[${calendar.dailyId}]]<br/>
<th:block th:if="${not #strings.isEmpty(calendar.children)}">
<span th:onclick="formControl.getDetail([[${reqVO.searchMonth}]], [[${calendar.no}]])">
No=[[${calendar.no}]], Start=[[${calendar.start}]], End=[[${calendar.end}]], children=[[${calendar.children}]]<br/>
<th:block th:each="children, childrenStatus : ${calendar.children}">
<a th:href="${children.path}">
>> Text=[[${children.codeLabel}]], Path=[[${children.path}]], Count=[[${children.total}]]<br/>
</a>
</th:block>
</span>
</th:block>
<th:block th:if="${#strings.isEmpty(calendar.dailyId)}">
<span th:onclick="formControl.getDetail([[${reqVO.searchMonth}]], [[${calendar.groupNo}]])">
No=[[${calendar.groupNo}]], Start=[[${calendar.startDay}]], End=[[${calendar.endDay}]], StartDate=[[${calendar.startDate}]]<br/>
<th:block th:if="${#strings.isEmpty(calendar.children)}">
<span th:onclick="formControl.getDetail([[${reqVO.searchMonth}]], [[${calendar.no}]])">
No=[[${calendar.no}]], Start=[[${calendar.start}]], End=[[${calendar.end}]]<br/>
</span>
</th:block>
</th:block>
@@ -28,6 +32,484 @@
<div id="selectedDay">
</div>
</th:block>
<main id="content" role="main">
<!-- alert-box 클래스 리스트트
fail : 실패(빨강)
warning : 경고(노랑)
success : 성공(초록)
info : 인포(파랑)
-->
<!-- TODO -->
<!--<article class="alert-box warning">
<p class="tit"><strong>홍길동</strong>님,</p>
<span class="txt">
일계부를 등록하지 않은 날짜가 있습니다. <br>
정확한 조사를 위해 꾸준히 입력해 주세요.
</span>
</article>-->
<!-- 캘린더 -->
<section class="main-calendar">
<div class="datepicker-loading"><i class="ico-spinner" aria-hidden="true"></i></div>
<button type="button" class="btn-week-month month"><span>월</span> <span>주</span></button>
<div class="component-datepicker kri" data-props-type="inline" data-init="false"></div>
<script>
class DatepickerComponent {
$datepicker
$datepickerLoading
$btnWeekMonth
$btnPrevMonth
$btnNextMonth
$btnPrevWeek
$btnNextWeek
datepickerInstance
datepickerCompInstance
weekStart = 0 // 주 시작일 (0: 일요일, 1: 월요일 등)
weekPaging = 0
maxWeekPaging = 0
serverData = new Map()
isLoading = false
currentMonth
currentList = []
mode = 'month'
_changeDateCallback = () => {}
_changeMonthCallback = () => {}
constructor (changeDateCallback, changeMonthCallback) {
this._changeDateCallback = changeDateCallback || this._changeDateCallback
this._changeMonthCallback = changeMonthCallback || this._changeMonthCallback
this.$datepicker = document.querySelector('.component-datepicker.kri')
this.$datepickerLoading = document.querySelector('.datepicker-loading')
this.$btnWeekMonth = document.querySelector('.btn-week-month')
this.datepickerCompInstance = etUI.components.DatepickerComp()
this.datepickerCompInstance.core.init(this.$datepicker, {
maxView: 0,
beforeShowDay: this.beforeShowDay.bind(this)
})
this.datepickerInstance = this.datepickerCompInstance.getDatepickerInstance()
this.cloneButtons();
this.$btnPrevMonth = document.querySelector('.datepicker-controls .prev-btn:not(.week-prev-btn)')
this.$btnNextMonth = document.querySelector('.datepicker-controls .next-btn:not(.week-next-btn)')
this.$btnPrevWeek = document.querySelector('.datepicker-controls .week-prev-btn')
this.$btnNextWeek = document.querySelector('.datepicker-controls .week-next-btn')
this.$btnPrevWeek.style.display = 'none'
this.$btnNextWeek.style.display = 'none'
this.addEvents()
// 초기 데이터 로딩
const today = new Date()
this.loadMonthData(today);
}
addEvents () {
this._changeDateCallbackDebounced = etUI.utils.debounce(function(currentList, datePair, date, viewDate) {
this._changeDateCallback.apply(this, [currentList, datePair, date, viewDate]);
}, 200);
this.$datepicker.addEventListener('changeDate', ({ detail }) => {
const data = this.serverData.get(this.currentMonth)
this.currentList = etUI.utils.getServerDataChildren(data, detail.viewDate.getDate())
this._changeDateCallbackDebounced(this.currentList, etUI.utils.getDatePair(detail.date), detail.date, detail.viewDate)
})
this.$datepicker.addEventListener('changeMonth', async ({ detail }) => {
const date = new Date(detail.viewDate)
const monthKey = this.getMonthKey(date)
this.setupMonth(date);
if (!this.isLoading) {
await this.loadMonthData(date)
this.setupMonth(date);
}
this._changeMonthCallback.apply(this, [monthKey, date])
})
this.$btnPrevWeek.addEventListener('click', () => {
console.log('prev week')
this.weekPagingPrev()
this.weekPagination('prev')
})
this.$btnNextWeek.addEventListener('click', () => {
console.log('next week')
this.weekPagingNext()
this.weekPagination('next')
})
this.$btnWeekMonth.addEventListener('click', () => {
if(this.mode === 'month'){
this.mode = 'week'
this.$datepicker.classList.remove('month')
this.$datepicker.classList.add('week')
this.$btnWeekMonth.classList.remove('month')
this.$btnWeekMonth.classList.add('week')
this.$btnPrevMonth.style.display = 'none'
this.$btnNextMonth.style.display = 'none'
this.$btnPrevWeek.style.display = 'block'
this.$btnNextWeek.style.display = 'block'
this.setFirstDateDay(this.datepickerInstance.getDate())
this.datepickerInstance.setOptions({
...this.datepickerCompInstance.core.props,
weekStart: this.weekStart,
})
this.loadMonthData(this.datepickerInstance.getDate())
this.weekPaging = 0;
this.weekPagination()
}else{
this.mode = 'month'
this.$datepicker.classList.remove('week')
this.$datepicker.classList.add('month')
this.$btnWeekMonth.classList.remove('week')
this.$btnWeekMonth.classList.add('month')
this.$btnPrevMonth.style.display = 'block'
this.$btnNextMonth.style.display = 'block'
this.$btnPrevWeek.style.display = 'none'
this.$btnNextWeek.style.display = 'none'
this.setFirstDateDay(this.datepickerInstance.getDate())
this.datepickerInstance.setOptions({
...this.datepickerCompInstance.core.props,
weekStart: this.weekStart,
})
this.loadMonthData(this.datepickerInstance.getDate())
const allCells = Array.from(this.$datepicker.querySelectorAll('.datepicker-cell'));
allCells.forEach((cell, idx) => {
cell.classList.remove('hide')
});
}
})
}
weekPagingPrev() {
// 현재 주가 1주차(weekPaging = 0)라면 이전 달로 이동
if (this.weekPaging <= 0) {
this.moveToPreviousMonth();
return;
}
// 이전 주로 이동
this.weekPaging -= 1;
setTimeout(() => {
document.querySelector('.datepicker-cell:not(.hide)').click();
}, 80)
// 주 페이지네이션 적용
this.weekPagination('prev');
}
/**
* 다음 주로 이동
* 1일부터 시작하는 주 단위 기준 (1~7일=1주, 8~14일=2주...)
*/
weekPagingNext() {
const currentDate = this.datepickerInstance.getDate();
const lastDayOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0).getDate();
// 현재 달의 최대 주차 계산 (1일 기준)
this.maxWeekPaging = Math.ceil(lastDayOfMonth / 7);
// 마지막 주차를 넘어가면 다음 달로 이동
if (this.weekPaging >= this.maxWeekPaging - 1) {
this.moveToNextMonth();
return;
}
// 다음 주로 이동
this.weekPaging += 1;
setTimeout(() => {
document.querySelector('.datepicker-cell:not(.hide)').click();
}, 80)
// 주 페이지네이션 적용
this.weekPagination('next');
}
moveToPreviousMonth() {
console.log('===========moveToPreviousMonth')
const currentDate = this.datepickerInstance.getDate();
// 이전 달의 마지막 날 구하기
const lastDayOfPrevMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 0).getDate();
// 이전 달의 마지막 주차 계산 (1일 기준)
const lastWeekOfPrevMonth = Math.ceil(lastDayOfPrevMonth / 7) - 1;
// 이전 달 마지막 주의 첫 번째 날 계산 (1일 기준 주차)
const firstDayOfLastWeek = (lastWeekOfPrevMonth * 7) + 1;
// 이전 달의 해당 주 첫 날로 이동
const targetDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, firstDayOfLastWeek);
console.log('targetDate===================', targetDate)
// this.$btnPrevMonth.click()
this.datepickerInstance.setDate(targetDate);
this.weekPaging = lastWeekOfPrevMonth;
console.log('this.weekPaging', this.weekPaging)
this.weekPagination('prev');
setTimeout(() => {
document.querySelector('.datepicker-cell:not(.hide)').click();
}, 80)
}
moveToNextMonth() {
console.log('===========moveToNextMonth')
const currentDate = this.datepickerInstance.getDate();
// 다음 달 1일로 이동 (첫 주의 첫 번째 날)
const nextMonthFirstDay = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 1);
// 다음 달로 이동
// this.$btnNextMonth.click()
this.datepickerInstance.setDate(nextMonthFirstDay);
this.weekPaging = 0;
this.weekPagination('next');
}
setFirstDateDay(date) {
const firstDate = new Date(date.getFullYear(), date.getMonth(), 1);
this.weekStart = firstDate.getDay();
}
weekPagination(direction) {
if (this.mode !== 'week') return;
const allCells = Array.from(this.$datepicker.querySelectorAll('.datepicker-cell'));
const thisMonthCells = allCells.filter(cell => !cell.classList.contains('prev') && !cell.classList.contains('next'));
// 현재 페이지의 첫 번째 셀 인덱스
const startIndex = this.weekPaging * 7;
// 현재 페이지의 마지막 셀 인덱스
const endIndex = startIndex + 7;
// 모든 셀 숨기기
allCells.forEach(cell => cell.classList.add('hide'));
// 현재 페이지의 셀만 보이기
thisMonthCells.slice(startIndex, endIndex).forEach(cell => cell.classList.remove('hide'));
}
cloneButtons(){
const prevBtn = document.querySelector('.prev-btn');
if (prevBtn) {
// 요소 복제 (깊은 복사로 모든 속성과 이벤트 리스너 포함)
const clonedPrevBtn = prevBtn.cloneNode(true);
// 복제된 요소에 고유한 식별자 추가 (선택사항)
clonedPrevBtn.classList.add('week-prev-btn');
// 원본 요소 다음에 복제된 요소 삽입
prevBtn.insertAdjacentElement('afterend', clonedPrevBtn);
}
const nextBtn = document.querySelector('.next-btn');
if (nextBtn) {
// 요소 복제 (깊은 복사로 모든 속성과 이벤트 리스너 포함)
const clonedNextBtn = nextBtn.cloneNode(true);
// 복제된 요소에 고유한 식별자 추가 (선택사항)
clonedNextBtn.classList.add('week-next-btn');
// 원본 요소 다음에 복제된 요소 삽입
nextBtn.insertAdjacentElement('afterend', clonedNextBtn);
}
}
setupMonth(date){
this.currentMonth = this.getMonthKey(date)
const allCells = Array.from(this.$datepicker.querySelectorAll('.datepicker-cell'));
const thisMonthCells = Array.from(this.$datepicker.querySelectorAll('.datepicker-cell:not(.prev):not(.next)'));
// 먼저 모든 클래스 초기화
allCells.forEach(cell => {
cell.classList.remove('selected', 'registered', 'group-start', 'group-end', 'single');
});
const data = this.serverData.get(this.currentMonth)
thisMonthCells.forEach((cell, i) => {
if (cell.classList.contains('disabled') || !cell.dataset.date) return;
const cellDate = new Date(Number(cell.dataset.date));
cellDate.setHours(0, 0, 0, 0);
if(data){
const registered = etUI.utils.checkServerDataChildren(data, cellDate.getDate()) ? 'registered' : '';
cell.classList.add(...etUI.utils.findNumberPosition(cellDate, registered).split(' '))
}else{
cell.classList.add(etUI.utils.findNumberPosition(cellDate))
}
})
}
beforeShowDay (date) {
const today = new Date()
const availToday = etUI.utils.getShowAvailDate(today)
if(availToday < date) {
return {
classes: 'disabled',
}
}
}
async loadMonthData (date) {
if (this.isLoading) return
this.loadingStart()
try {
const monthKey = this.getMonthKey(date)
if(!this.serverData.get(monthKey)){
const data = await this.getData(monthKey)
this.serverData.set(monthKey, data)
}
} catch (error) {
console.error('Failed to load calendar data:', error)
} finally {
const today = new Date()
if (
date.getMonth() === today.getMonth() &&
date.getFullYear() === today.getFullYear()) {
this.datepickerInstance.setDate(today)
setTimeout(() => {
document.querySelector('.focused').click()
})
} else {
date.setDate(1)
this.datepickerInstance.setDate(date)
setTimeout(() => {
document.querySelector('.focused').click()
})
}
this.datepickerInstance.refresh()
this.loadingEnd()
this.$datepicker.classList.remove('loading')
this.setupMonth(today);
}
}
getMonthKey (date) {
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`
}
loadingStart () {
this.isLoading = true
this.$datepicker.classList.add('loading')
this.$datepickerLoading.style.display = 'block'
}
loadingEnd () {
this.isLoading = false
this.$datepicker.classList.remove('loading')
this.$datepickerLoading.style.display = 'none'
}
async getData (month) {
await new Promise(resolve => setTimeout(resolve, 50))
const data = await fetch(`http://localhost:8888/assets/json/${month}.json`)
return await data.json()
}
}
new DatepickerComponent(function(list, currentDate, viewDate){
console.log('changeDateCallback', list, currentDate, viewDate);
}, function(monthKey, currentDate){
console.log('changeMonthCallback', monthKey, currentDate);
});
</script>
</section>
<section class="daily-report-area bg-gray bg-lround">
<div class="inner">
<p class="date">2025. 5. 19 ~ 2025. 5. 20</p>
<ul class="btn-column-list">
<li>
<a href="">
<p class="label">수입</p>
<p class="value"><em>총 <b>4</b>건</em></p>
</a>
</li>
<li>
<a href="">
<p class="label">노동투입</p>
<p class="value">없음</p>
</a>
</li>
<li>
<a href="">
<p class="label">지출</p>
<p class="value">없음</p>
</a>
</li>
<li>
<a href="">
<p class="label">동력사용시간</p>
<p class="value"><em>총 <b>4</b>건</em></p>
</a>
</li>
<li>
<a href="">
<p class="label">임업생산물 중 자가소비량</p>
<p class="value">없음</p>
</a>
</li>
<li>
<a href="">
<p class="label">농업생산물 중 자가소비량</p>
<p class="value">없음</p>
</a>
</li>
</ul>
<div class="component-btns btn-add">
<button type="button">
<p class="txt">일계부 등록하기</p>
</button>
</div>
<div class="regist-btn-area">
<a href="" class="btn complete">
<p>임산물 현황 등록</p>
<span>등록완료</span>
</a>
<a href="" class="btn">
<p>은행 자동이체 내역 등록</p>
<span>미등록</span>
</a>
</div>
</div>
</section>
</main>
</div>