본문 바로가기
프로젝트/운동일지

오류발생 - 총볼륨 구하는 로직

by 티코딩 2024. 6. 10.

가장 최근에 구현한 총볼륨을 구해서 표시해주는 로직에 문제가 생겼다.

여기서 세트추가하면 home에서 총볼륨을 구해 표시해준다.

 

세트가 한개일땐 잘 구해진다.

세트가 두개가되면

총 볼륨이 2배가 된다.

로직이 잘못된거같다.

 

현재 로직부터 살펴보자.

 

1. HomeController

@GetMapping("/home")
    public String home(@RequestParam(value = "year", required = false) Integer year,
                       @RequestParam(value = "month", required = false) Integer month,
                       Model model) {
        LocalDate now = LocalDate.now();
        int currentYear = (year == null) ? now.getYear() : year;
        int currentMonth = (month == null) ? now.getMonthValue() : month;

        YearMonth yearMonth = YearMonth.of(currentYear, currentMonth);
        User currentUser = userService.getCurrentUser();
        Long userId = currentUser.getId();
        WsessionDto.WsessionStatsDto stats = wsessionService.getMonthlyStats(userId, yearMonth);
        model.addAttribute("totalVolume", stats.getTotalVolume());
        int daysInMonth = yearMonth.lengthOfMonth();
        LocalDate firstOfMonth = yearMonth.atDay(1);
        int dayOfWeekValue = firstOfMonth.getDayOfWeek().getValue() % 7; // Sunday=0, Monday=1, ..., Saturday=6

        List<Integer> emptyDays = new ArrayList<>();
        for (int i = 0; i < dayOfWeekValue; i++) {
            emptyDays.add(i);
        }

        List<String> days = new ArrayList<>();
        for (int i = 1; i <= daysInMonth; i++) {
            days.add(String.format("%02d", i));
        }

        String paddedMonth = String.format("%02d", currentMonth);

        List<LocalDate> sessionDates = wsessionService.getSessionDates(currentYear, currentMonth);
        List<String> sessionDays = (sessionDates != null) ? sessionDates.stream()
                .map(date -> String.format("%02d", date.getDayOfMonth()))
                .collect(Collectors.toList()) : new ArrayList<>();

        model.addAttribute("currentYear", currentYear);
        model.addAttribute("currentMonth", currentMonth); // 패딩 처리하지 않은 숫자
        model.addAttribute("paddedMonth", paddedMonth); // 패딩된 월 문자열
        model.addAttribute("emptyDays", emptyDays);
        model.addAttribute("days", days);
        model.addAttribute("sessionDays", sessionDays);

        return "home";
    }

 

2. WsessionService

@Transactional(readOnly = true)
    public WsessionDto.WsessionStatsDto getMonthlyStats(Long userId, YearMonth yearMonth) {
        LocalDate startDate = yearMonth.atDay(1);
        LocalDate endDate = yearMonth.atEndOfMonth();

        List<Wsession> sessions = wsessionRepository.findAllByUserIdAndWsessionIdBetween(userId, startDate, endDate);

        int totalWeight = 0;
        int totalReps = 0;

        for (Wsession session : sessions) {
            for (Exercise exercise : session.getExercises()) {
                for (ExerciseSet set : exercise.getSets()) {
                    totalWeight += set.getWeight();
                    totalReps += set.getReps();
                }
            }
        }
        int totalVolume = totalWeight * totalReps;
        return new WsessionDto.WsessionStatsDto(totalVolume);
    }

 

내가 왜이렇게 한지 모르겠다. 계산식이 잘못되었다. 총볼륨은 총무게 * 총반복횟수가 아니라, 각세트의 무게 x 횟수한거를 다 더한게 총볼륨이다.

그래서 간단히 고쳤다.

@Transactional(readOnly = true)
    public WsessionDto.WsessionStatsDto getMonthlyStats(Long userId, YearMonth yearMonth) {
        LocalDate startDate = yearMonth.atDay(1);
        LocalDate endDate = yearMonth.atEndOfMonth();

        List<Wsession> sessions = wsessionRepository.findAllByUserIdAndWsessionIdBetween(userId, startDate, endDate);

        int totalVolume = 0;	//수정한부분


        for (Wsession session : sessions) {
            for (Exercise exercise : session.getExercises()) {
                for (ExerciseSet set : exercise.getSets()) {
                    int setVolume = set.getWeight() * set.getReps();	//수정한부분
                    totalVolume += setVolume;	//수정한부분
                }
            }
        }
        return new WsessionDto.WsessionStatsDto(totalVolume);
    }
}

휴~ 잘됐다.

'프로젝트 > 운동일지' 카테고리의 다른 글

코드리뷰 - View 부분(HTML,CSS,JavaScript)  (1) 2024.06.11
코드리뷰 - 운동관련부분  (0) 2024.06.10
프로젝트 개요  (1) 2024.06.04