45 lines
1.8 KiB
Python
45 lines
1.8 KiB
Python
from fastapi import APIRouter
|
|
import logging
|
|
from ..clients.firefly_client import firefly_client
|
|
|
|
logger = logging.getLogger("reports_router")
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.get("/spending-by-category")
|
|
async def spending_by_category():
|
|
try:
|
|
transactions = await firefly_client.get_transactions()
|
|
logger.info("Fetched %d transactions from Firefly for reports", len(transactions))
|
|
category_totals = {}
|
|
|
|
for transaction in transactions:
|
|
attrs = transaction.get("attributes", {})
|
|
legs = attrs.get("transactions", []) or []
|
|
|
|
for leg in legs:
|
|
try:
|
|
leg_amount = float(leg.get("amount", 0))
|
|
except Exception:
|
|
leg_amount = 0.0
|
|
|
|
leg_type = (leg.get("type") or "").lower()
|
|
# we consider 'withdrawal' legs as spending
|
|
if leg_type == "withdrawal" or (leg.get("destination_type") or "").lower().startswith("expense"):
|
|
category_name = leg.get("category_name") or leg.get("category") or attrs.get("category_name") or attrs.get("category_id") or "Uncategorized"
|
|
category_totals[category_name] = category_totals.get(category_name, 0) + abs(leg_amount)
|
|
|
|
data = [
|
|
{"name": name, "amount": amount}
|
|
for name, amount in sorted(category_totals.items(), key=lambda item: item[1], reverse=True)
|
|
]
|
|
|
|
return {"data": data}
|
|
except Exception as e:
|
|
logger.exception("Error computing spending-by-category: %s", e)
|
|
# Return 500 with message for frontend debugging
|
|
from fastapi import HTTPException
|
|
|
|
raise HTTPException(status_code=500, detail="Error fetching report data")
|