Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 55 additions & 15 deletions backend/app/api/v1/dashboard.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,65 @@
from fastapi import APIRouter, Depends, HTTPException
from typing import Dict, Any
from app.services.cache import get_revenue_summary
import logging
import re
from typing import Any, Dict

from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import text

from app.core.auth import authenticate_request as get_current_user
from app.core.database_pool import db_pool
from app.services.cache import get_revenue_summary

router = APIRouter()
logger = logging.getLogger(__name__)


def tenant_for(user) -> str:
tenant_id = getattr(user, "tenant_id", None)
if not tenant_id:
raise HTTPException(status_code=403, detail="No tenant is assigned to this account")
return tenant_id


@router.get("/dashboard/properties")
async def get_dashboard_properties(current_user=Depends(get_current_user)):
tenant_id = tenant_for(current_user)
try:
if not db_pool.session_factory:
await db_pool.initialize()
async with db_pool.get_session() as session:
rows = (await session.execute(text("""
SELECT id, name FROM properties
WHERE tenant_id = :tenant_id ORDER BY name
"""), {"tenant_id": tenant_id})).mappings().all()
return [{"id": row["id"], "name": row["name"]} for row in rows]
except Exception as exc:
logger.exception("Dashboard property lookup failed")
raise HTTPException(status_code=503, detail="Property data is temporarily unavailable") from exc


@router.get("/dashboard/summary")
async def get_dashboard_summary(
property_id: str,
current_user: dict = Depends(get_current_user)
month: str | None = Query(default=None, pattern=r"^\d{4}-(0[1-9]|1[0-2])$"),
current_user=Depends(get_current_user),
) -> Dict[str, Any]:

tenant_id = getattr(current_user, "tenant_id", "default_tenant") or "default_tenant"

revenue_data = await get_revenue_summary(property_id, tenant_id)

total_revenue_float = float(revenue_data['total'])

tenant_id = tenant_for(current_user)
if month and not re.fullmatch(r"\d{4}-(0[1-9]|1[0-2])", month):
raise HTTPException(status_code=422, detail="month must use YYYY-MM format")
try:
revenue_data = await get_revenue_summary(property_id, tenant_id, month)
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
except Exception as exc:
logger.exception("Dashboard revenue lookup failed")
raise HTTPException(status_code=503, detail="Revenue data is temporarily unavailable") from exc
if revenue_data.get("not_found"):
raise HTTPException(status_code=404, detail="Property not found")
return {
"property_id": revenue_data['property_id'],
"total_revenue": total_revenue_float,
"currency": revenue_data['currency'],
"reservations_count": revenue_data['count']
"property_id": revenue_data["property_id"],
"total_revenue": revenue_data["total"],
"currency": revenue_data["currency"],
"reservations_count": revenue_data["count"],
"month": revenue_data["month"],
"timezone": revenue_data["timezone"],
}
65 changes: 33 additions & 32 deletions backend/app/core/database_pool.py
Original file line number Diff line number Diff line change
@@ -1,60 +1,61 @@
import asyncio
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy.pool import QueuePool
import logging

from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.engine import make_url

from ..config import settings

logger = logging.getLogger(__name__)


class DatabasePool:
def __init__(self):
self.engine = None
self.session_factory = None

async def initialize(self):
"""Initialize database connection pool"""
"""Initialize the async pool from the configured DATABASE_URL."""
if self.session_factory:
return
try:
# Create async engine with connection pooling
database_url = f"postgresql+asyncpg://{settings.supabase_db_user}:{settings.supabase_db_password}@{settings.supabase_db_host}:{settings.supabase_db_port}/{settings.supabase_db_name}"

database_url = make_url(settings.database_url)
if database_url.drivername in {"postgres", "postgresql"}:
database_url = database_url.set(drivername="postgresql+asyncpg")
self.engine = create_async_engine(
database_url,
poolclass=QueuePool,
pool_size=20, # Number of connections to maintain
max_overflow=30, # Additional connections when needed
pool_pre_ping=True, # Validate connections
pool_recycle=3600, # Recycle connections every hour
echo=False # Set to True for SQL debugging
pool_size=settings.database_pool_size,
max_overflow=settings.database_max_overflow,
pool_pre_ping=True,
pool_recycle=settings.database_pool_recycle,
echo=False,
)

self.session_factory = async_sessionmaker(
bind=self.engine,
class_=AsyncSession,
expire_on_commit=False
bind=self.engine, class_=AsyncSession, expire_on_commit=False
)

logger.info("✅ Database connection pool initialized")

except Exception as e:
logger.error(f"❌ Database pool initialization failed: {e}")
logger.info("Database connection pool initialized")
except Exception:
logger.exception("Database pool initialization failed")
self.engine = None
self.session_factory = None

raise

async def close(self):
"""Close database connections"""
if self.engine:
await self.engine.dispose()

async def get_session(self) -> AsyncSession:
"""Get database session from pool"""
self.engine = None
self.session_factory = None

def get_session(self) -> AsyncSession:
if not self.session_factory:
raise Exception("Database pool not initialized")
raise RuntimeError("Database pool not initialized")
return self.session_factory()

# Global database pool instance

db_pool = DatabasePool()

async def get_db_session() -> AsyncSession:
"""Dependency to get database session"""

async def get_db_session():
if not db_pool.session_factory:
await db_pool.initialize()
async with db_pool.get_session() as session:
yield session
51 changes: 28 additions & 23 deletions backend/app/services/cache.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,34 @@
import json
import logging
from typing import Any, Dict, Optional

import redis.asyncio as redis
from typing import Dict, Any
import os

# Initialize Redis client (typically configured centrally).
redis_client = redis.Redis.from_url(os.getenv("REDIS_URL", "redis://localhost:6379/0"))
from app.config import settings

logger = logging.getLogger(__name__)
redis_client = redis.Redis.from_url(settings.redis_url, decode_responses=True, socket_timeout=0.5)


async def get_revenue_summary(
property_id: str, tenant_id: str, month: Optional[str] = None
) -> Dict[str, Any]:
# Scope every cached result to the authenticated tenant as well as property/month.
cache_key = f"revenue:v2:{tenant_id}:{property_id}:{month or 'latest'}"
try:
cached = await redis_client.get(cache_key)
if cached:
return json.loads(cached)
except Exception as exc:
logger.warning("Revenue cache read failed; using database: %s", type(exc).__name__)

async def get_revenue_summary(property_id: str, tenant_id: str) -> Dict[str, Any]:
"""
Fetches revenue summary, utilizing caching to improve performance.
"""
cache_key = f"revenue:{property_id}"

# Try to get from cache
cached = await redis_client.get(cache_key)
if cached:
return json.loads(cached)

# Revenue calculation is delegated to the reservation service.
from app.services.reservations import calculate_total_revenue

# Calculate revenue
result = await calculate_total_revenue(property_id, tenant_id)

# Cache the result for 5 minutes
await redis_client.setex(cache_key, 300, json.dumps(result))


result = await calculate_total_revenue(property_id, tenant_id, month)
if result.get("not_found"):
return result
try:
await redis_client.setex(cache_key, 300, json.dumps(result))
except Exception as exc:
logger.warning("Revenue cache write failed: %s", type(exc).__name__)
return result
Loading