solorpower_server/app/routers/plants.py

141 lines
3.8 KiB
Python

"""
발전소 관련 API 엔드포인트
- 발전소 목록 조회
- 발전 현황 조회
"""
from fastapi import APIRouter, HTTPException, Depends
from supabase import Client
from typing import List
from app.core.database import get_db
from app.schemas.plant import PlantsListResponse, PlantWithLatestLog, SolarLogBase
router = APIRouter(
prefix="/plants",
tags=["Plants"]
)
@router.get("/{company_id}", response_model=PlantsListResponse)
async def get_plants_by_company(
company_id: int,
db: Client = Depends(get_db)
) -> PlantsListResponse:
"""
특정 업체의 모든 발전소 목록과 최신 발전 현황을 조회합니다.
Args:
company_id: 업체 ID
Returns:
발전소 목록 및 각 발전소의 최신 발전 로그
"""
try:
# 1. 해당 업체의 모든 발전소 조회
plants_response = db.table("plants") \
.select("*") \
.eq("company_id", company_id) \
.execute()
plants = plants_response.data
if not plants:
return PlantsListResponse(
status="success",
data=[],
total_count=0
)
# 2. 각 발전소의 최신 발전 로그 조회
result: List[PlantWithLatestLog] = []
for plant in plants:
# 해당 발전소의 최신 로그 1건 조회
log_response = db.table("solar_logs") \
.select("*") \
.eq("plant_id", plant["id"]) \
.order("created_at", desc=True) \
.limit(1) \
.execute()
latest_log = None
if log_response.data:
latest_log = SolarLogBase(**log_response.data[0])
plant_with_log = PlantWithLatestLog(
**plant,
latest_log=latest_log
)
result.append(plant_with_log)
return PlantsListResponse(
status="success",
data=result,
total_count=len(result)
)
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"데이터베이스 조회 중 오류가 발생했습니다: {str(e)}"
)
@router.get("/{company_id}/{plant_id}", response_model=dict)
async def get_plant_detail(
company_id: int,
plant_id: int,
db: Client = Depends(get_db)
) -> dict:
"""
특정 발전소의 상세 정보를 조회합니다.
Args:
company_id: 업체 ID
plant_id: 발전소 ID
Returns:
발전소 상세 정보 및 최근 발전 로그
"""
try:
# 발전소 조회
plant_response = db.table("plants") \
.select("*") \
.eq("id", plant_id) \
.eq("company_id", company_id) \
.single() \
.execute()
if not plant_response.data:
raise HTTPException(
status_code=404,
detail="발전소를 찾을 수 없습니다."
)
plant = plant_response.data
# 최근 발전 로그 10건 조회
logs_response = db.table("solar_logs") \
.select("*") \
.eq("plant_id", plant_id) \
.order("created_at", desc=True) \
.limit(10) \
.execute()
return {
"status": "success",
"data": {
"plant": plant,
"recent_logs": logs_response.data or []
}
}
except HTTPException:
raise
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"데이터베이스 조회 중 오류가 발생했습니다: {str(e)}"
)