From d8a3efab065be0112603d857d5d52b1dcce15fd3 Mon Sep 17 00:00:00 2001 From: haneulai Date: Thu, 12 Feb 2026 10:50:40 +0900 Subject: [PATCH] fix: fallback to daily_stats summation for current month stats --- app/routers/stats.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/app/routers/stats.py b/app/routers/stats.py index 7baeda8..39dc3e5 100644 --- a/app/routers/stats.py +++ b/app/routers/stats.py @@ -99,6 +99,7 @@ async def get_all_plants_comparison( # 월간: monthly_stats 조회 (해당 월) month_str = f"{target_year}-{target_month:02d}" + # 1. monthly_stats 조회 monthly_res = db.table("monthly_stats") \ .select("plant_id, total_generation") \ .eq("month", month_str) \ @@ -108,6 +109,33 @@ async def get_all_plants_comparison( val = row.get('total_generation', 0) if val is None: val = 0 stats_map[row['plant_id']] = val + + # 2. 이번 달이거나 데이터가 부족하면 daily_stats 합산 시도 + is_current_month = (target_year == today.year and target_month == today.month) + has_missing_data = not stats_map or all(v == 0 for v in stats_map.values()) + + if is_current_month or has_missing_data: + last_day = calendar.monthrange(target_year, target_month)[1] + start_date = f"{target_year}-{target_month:02d}-01" + end_date = f"{target_year}-{target_month:02d}-{last_day}" + + daily_res = db.table("daily_stats") \ + .select("plant_id, total_generation") \ + .gte("date", start_date) \ + .lte("date", end_date) \ + .execute() + + temp_map = {} + for row in daily_res.data: + pid = row['plant_id'] + val = row.get('total_generation', 0) + if val is None: val = 0 + temp_map[pid] = temp_map.get(pid, 0) + val + + # 합산된 값이 있으면 업데이트 + for pid, val in temp_map.items(): + if val > stats_map.get(pid, 0): + stats_map[pid] = val elif period == "year": # 연간: monthly_stats 조회 (해당 연도 전체 합산)