File size: 2,160 Bytes
38dccca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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`
    }