feat: Add hourly stats endpoint for today chart

This commit is contained in:
haneulai 2026-01-26 10:49:49 +09:00
parent a7a83e8792
commit 1aa4448f9f

View File

@ -140,3 +140,68 @@ async def get_plant_stats(
status_code=500, status_code=500,
detail=f"통계 조회 실패: {str(e)}" detail=f"통계 조회 실패: {str(e)}"
) )
@router.get("/{plant_id}/stats/today")
async def get_plant_hourly_stats(
plant_id: str,
db: Client = Depends(get_db)
) -> dict:
"""
오늘 시간별 발전 데이터 조회 (solar_logs 기반)
Args:
plant_id: 발전소 ID
Returns:
시간별 데이터 [{"hour": 0, "current_kw": ..., "today_kwh": ...}, ...]
"""
try:
today = datetime.now().date()
today_str = today.isoformat()
# 오늘의 모든 solar_logs 조회
logs_result = db.table("solar_logs") \
.select("current_kw, today_kwh, created_at") \
.eq("plant_id", plant_id) \
.gte("created_at", f"{today_str}T00:00:00") \
.order("created_at", desc=False) \
.execute()
# 시간별로 그룹화 (각 시간의 마지막 데이터 사용)
hourly_data = {}
for log in logs_result.data:
created_at = log.get("created_at", "")
if created_at:
# ISO 형식에서 시간 추출
hour = int(created_at[11:13]) if len(created_at) > 13 else 0
hourly_data[hour] = {
"current_kw": log.get("current_kw", 0) or 0,
"today_kwh": log.get("today_kwh", 0) or 0,
}
# 0시~23시 전체 배열 생성
result = []
for hour in range(24):
data = hourly_data.get(hour, {"current_kw": 0, "today_kwh": 0})
result.append({
"hour": hour,
"label": f"{hour}",
"current_kw": round(data["current_kw"], 2),
"today_kwh": round(data["today_kwh"], 2),
"has_data": hour in hourly_data
})
return {
"status": "success",
"plant_id": plant_id,
"date": today_str,
"data": result,
"count": len([d for d in result if d["has_data"]])
}
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"시간별 통계 조회 실패: {str(e)}"
)