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
9 changes: 9 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
__pycache__/
*.py[cod]
*$py.class
.pytest_cache/
*.env
node_modules/
dist/
.DS_Store
Thumbs.db
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
The Video Link for the Above with resolved issues is provided BELOW:

**https://drive.google.com/file/d/1aTU41IZWuGG7c9luTE66z2ggJKmR-k6c/view?usp=sharing**
41 changes: 29 additions & 12 deletions backend/app/api/v1/dashboard.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,42 @@
from fastapi import APIRouter, Depends, HTTPException
from typing import Dict, Any
from fastapi import APIRouter, Depends, HTTPException, Query, Request
from typing import Dict, Any, Optional
from decimal import Decimal, ROUND_HALF_UP
from app.services.cache import get_revenue_summary
from app.core.auth import authenticate_request as get_current_user

router = APIRouter()


@router.get("/dashboard/summary")
async def get_dashboard_summary(
property_id: str,
current_user: dict = Depends(get_current_user)
month: Optional[int] = Query(None, ge=1, le=12),
year: Optional[int] = Query(None, ge=2000, le=2100),
request: Request = None,
current_user: Any = 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'])

"""
Returns revenue summary for a property, properly scoped to the authenticated tenant.
Supports optional month and year filtering with timezone awareness.
"""
tenant_id = getattr(current_user, "tenant_id", None)
if not tenant_id and request:
tenant_id = request.headers.get("x-simulated-tenant")
tenant_id = tenant_id or "default_tenant"

revenue_data = await get_revenue_summary(property_id, tenant_id, month=month, year=year)

# Standard financial precision: parse to Decimal and round half up to 2 decimal places
raw_total = Decimal(str(revenue_data.get('total', '0.00'))).quantize(
Decimal('0.01'), rounding=ROUND_HALF_UP
)
total_revenue_float = float(raw_total)

return {
"property_id": revenue_data['property_id'],
"tenant_id": tenant_id,
"total_revenue": total_revenue_float,
"currency": revenue_data['currency'],
"reservations_count": revenue_data['count']
"formatted_total": f"{raw_total:.2f}",
"currency": revenue_data.get('currency', 'USD'),
"reservations_count": revenue_data.get('count', 0)
}
6 changes: 4 additions & 2 deletions backend/app/api/v1/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,9 @@ async def login(request: LoginRequest):
user_data = {
"id": "user-sunset",
"email": "sunset@propertyflow.com",
"tenant_id": "tenant-a",
"app_metadata": {"role": "user", "tenant_id": "tenant-a"},
"user_metadata": {"name": "Sunset Properties Manager"},
"user_metadata": {"name": "Sunset Properties Manager", "tenant_id": "tenant-a"},
"aud": "authenticated",
"created_at": datetime.utcnow().isoformat(),
"exp": datetime.utcnow() + timedelta(hours=24)
Expand Down Expand Up @@ -77,8 +78,9 @@ async def login(request: LoginRequest):
user_data = {
"id": "user-ocean",
"email": "ocean@propertyflow.com",
"tenant_id": "tenant-b",
"app_metadata": {"role": "user", "tenant_id": "tenant-b"},
"user_metadata": {"name": "Ocean Rentals Manager"},
"user_metadata": {"name": "Ocean Rentals Manager", "tenant_id": "tenant-b"},
"aud": "authenticated",
"created_at": datetime.utcnow().isoformat(),
"exp": datetime.utcnow() + timedelta(hours=24)
Expand Down
27 changes: 19 additions & 8 deletions backend/app/core/database_pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,27 @@ def __init__(self):

async def initialize(self):
"""Initialize database connection pool"""
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}"
# Create async engine with connection pooling from settings.database_url
db_url = settings.database_url
if db_url.startswith("postgresql://"):
database_url = db_url.replace("postgresql://", "postgresql+asyncpg://", 1)
elif db_url.startswith("postgres://"):
database_url = db_url.replace("postgres://", "postgresql+asyncpg://", 1)
else:
database_url = db_url

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=getattr(settings, 'database_pool_size', 20),
max_overflow=getattr(settings, 'database_max_overflow', 30),
pool_pre_ping=True,
pool_recycle=getattr(settings, 'database_pool_recycle', 3600),
echo=False
)

self.session_factory = async_sessionmaker(
Expand All @@ -48,7 +57,9 @@ async def close(self):
async def get_session(self) -> AsyncSession:
"""Get database session from pool"""
if not self.session_factory:
raise Exception("Database pool not initialized")
await self.initialize()
if not self.session_factory:
raise Exception("Database pool not available")
return self.session_factory()

# Global database pool instance
Expand Down
49 changes: 34 additions & 15 deletions backend/app/services/cache.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,48 @@
import json
import redis.asyncio as redis
from typing import Dict, Any
from typing import Dict, Any, Optional
import os
import logging

# Initialize Redis client (typically configured centrally).
redis_client = redis.Redis.from_url(os.getenv("REDIS_URL", "redis://localhost:6379/0"))
logger = logging.getLogger(__name__)

async def get_revenue_summary(property_id: str, tenant_id: str) -> Dict[str, Any]:
# Initialize Redis client with fallback to environment
redis_url = os.getenv("REDIS_URL", "redis://localhost:6379/0")
redis_client = redis.Redis.from_url(redis_url)


async def get_revenue_summary(
property_id: str,
tenant_id: str,
month: Optional[int] = None,
year: Optional[int] = None
) -> Dict[str, Any]:
"""
Fetches revenue summary, utilizing caching to improve performance.
Cache key is strictly namespaced by tenant_id to prevent cross-tenant data leakage.
"""
cache_key = f"revenue:{property_id}"

cache_key = f"revenue:{tenant_id}:{property_id}"
if month and year:
cache_key += f":{year}:{month}"

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

try:
cached = await redis_client.get(cache_key)
if cached:
return json.loads(cached)
except Exception as e:
logger.debug(f"Redis cache lookup error for {cache_key}: {e}")

# 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)
result = await calculate_total_revenue(property_id, tenant_id, month=month, year=year)

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

try:
await redis_client.setex(cache_key, 300, json.dumps(result))
except Exception as e:
logger.debug(f"Redis cache store error for {cache_key}: {e}")

return result
Loading