from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from app.db.database import get_db from app.db.models import ClosedPeriod, JournalEntry, User from app.api.auth import get_current_user from pydantic import BaseModel router = APIRouter() class CloseMonthRequest(BaseModel): period: str # e.g. "2026-06" @router.post("/month") # Bug 1 fixed: was missing the @ decorator def close_month( req: CloseMonthRequest, db: Session = Depends(get_db), current_user: User = Depends(get_current_user) ): user_id = current_user.user_id period = req.period # 1. Block if already closed already_closed = db.query(ClosedPeriod).filter( ClosedPeriod.user_id == user_id, ClosedPeriod.period == period ).first() if already_closed: raise HTTPException(status_code=400, detail=f"{period} is already closed.") # 2. Block if any transactions in this month are still flagged/pending open_transactions = db.query(JournalEntry).filter( JournalEntry.user_id == user_id, JournalEntry.date.startswith(period), JournalEntry.status.in_(["flagged", "pending"]) ).count() if open_transactions > 0: raise HTTPException( status_code=400, detail=f"Cannot close {period}. {open_transactions} transaction(s) still need review." ) # 3. Lock the month closed = ClosedPeriod(user_id=user_id, period=period) db.add(closed) db.commit() return {"status": "success", "message": f"{period} has been locked successfully."} @router.get("/months") # Bug 2 fixed: was missing @ and wrong path "/month" → "/months" def get_closed_months( db: Session = Depends(get_db), current_user: User = Depends(get_current_user) ): user_id = current_user.user_id closed_periods = db.query(ClosedPeriod).filter( ClosedPeriod.user_id == user_id ).all() return { "status": "success", "data": [{"period": c.period, "closed_at": str(c.closed_at)} for c in closed_periods] # Bug 3 fixed: was `closed`, should be `closed_periods` }