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
44 changes: 36 additions & 8 deletions backend/app/api/v1/dashboard.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,53 @@
from fastapi import APIRouter, Depends, HTTPException
from typing import Dict, Any
from typing import Dict, Any, Optional
from decimal import Decimal
from app.services.cache import get_revenue_summary
from app.core.auth import authenticate_request as get_current_user
from app.models.auth import AuthenticatedUser
from app.core.database_pool import DatabasePool
from sqlalchemy import text

router = APIRouter()

@router.get("/dashboard/summary")
async def get_dashboard_summary(
property_id: str,
current_user: dict = Depends(get_current_user)
month: Optional[int] = None,
year: Optional[int] = None,
current_user: AuthenticatedUser = Depends(get_current_user)
) -> Dict[str, Any]:

tenant_id = current_user.tenant_id
if not tenant_id:
raise HTTPException(status_code=403, detail="Tenant context missing")
# Ensure the requested property belongs to the authenticated tenant
try:
db_pool = DatabasePool()
await db_pool.initialize()
async with (await db_pool.get_session()) as session:
ownership = await session.execute(
text("SELECT 1 FROM properties WHERE id = :property_id AND tenant_id = :tenant_id LIMIT 1"),
{"property_id": property_id, "tenant_id": tenant_id},
)
if not ownership.fetchone():
raise HTTPException(status_code=403, detail="Property not found for tenant")
except HTTPException:
raise
except Exception:
# If DB lookup fails for some reason, deny access rather than risk data leakage
raise HTTPException(status_code=403, detail="Property access denied")

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

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

total_revenue_float = float(revenue_data['total'])
# Use Decimal to preserve precision, then round to 2 decimal places
total = Decimal(revenue_data['total']).quantize(Decimal('0.01'))

return {
"property_id": revenue_data['property_id'],
"total_revenue": total_revenue_float,
"total_revenue": float(total),
"currency": revenue_data['currency'],
"reservations_count": revenue_data['count']
"reservations_count": revenue_data['count'],
"month": revenue_data.get('month'),
"year": revenue_data.get('year'),
"timezone": revenue_data.get('timezone')
}
20 changes: 14 additions & 6 deletions backend/app/core/database_pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,23 @@ async def initialize(self):
"""Initialize database connection pool"""
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}"
# Prefer a single DATABASE_URL if provided (convert to asyncpg driver),
# otherwise fall back to legacy separate supabase_db_* settings.
database_url = None
try:
database_url = getattr(settings, 'database_url', None)
except Exception:
database_url = None

if database_url:
# Convert sync driver to asyncpg driver
if database_url.startswith('postgresql://'):
database_url = database_url.replace('postgresql://', 'postgresql+asyncpg://', 1)
else:
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}"

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
)

Expand Down
11 changes: 9 additions & 2 deletions backend/app/services/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,19 @@
import redis.asyncio as redis
from typing import Dict, Any
import os
from datetime import datetime, timezone

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

async def get_revenue_summary(property_id: str, tenant_id: str) -> Dict[str, Any]:
async def get_revenue_summary(property_id: str, tenant_id: str, month: int | None = None, year: int | None = None) -> Dict[str, Any]:
"""
Fetches revenue summary, utilizing caching to improve performance.
"""
cache_key = f"revenue:{property_id}"
now = datetime.now(timezone.utc)
month = month or now.month
year = year or now.year
cache_key = f"revenue:{tenant_id}:{property_id}:{year}:{month}"

# Try to get from cache
cached = await redis_client.get(cache_key)
Expand All @@ -22,6 +26,9 @@ async def get_revenue_summary(property_id: str, tenant_id: str) -> Dict[str, Any

# Calculate revenue
result = await calculate_total_revenue(property_id, tenant_id)
if result.get("month") != month or result.get("year") != year:
from app.services.reservations import calculate_monthly_revenue
result = await calculate_monthly_revenue(property_id, tenant_id, month, year)

# Cache the result for 5 minutes
await redis_client.setex(cache_key, 300, json.dumps(result))
Expand Down
200 changes: 106 additions & 94 deletions backend/app/services/reservations.py
Original file line number Diff line number Diff line change
@@ -1,109 +1,121 @@
from datetime import datetime
from decimal import Decimal
from typing import Dict, Any, List

async def calculate_monthly_revenue(property_id: str, month: int, year: int, db_session=None) -> Decimal:
"""
Calculates revenue for a specific month.
"""

start_date = datetime(year, month, 1)
if month < 12:
end_date = datetime(year, month + 1, 1)
from datetime import datetime, timezone
from decimal import Decimal, ROUND_HALF_UP
from typing import Any, Dict
from zoneinfo import ZoneInfo


async def _fetch_monthly_summary(session, property_id: str, tenant_id: str, month: int, year: int) -> Dict[str, Any]:
from sqlalchemy import text

tz_query = text("""
SELECT timezone
FROM properties
WHERE id = :property_id AND tenant_id = :tenant_id
LIMIT 1
""")
tz_result = await session.execute(tz_query, {"property_id": property_id, "tenant_id": tenant_id})
tz_row = tz_result.fetchone()
property_tz = tz_row.timezone if tz_row and tz_row.timezone else "UTC"

zone = ZoneInfo(property_tz)
start_local = datetime(year, month, 1, tzinfo=zone)
if month == 12:
end_local = datetime(year + 1, 1, 1, tzinfo=zone)
else:
end_date = datetime(year + 1, 1, 1)

print(f"DEBUG: Querying revenue for {property_id} from {start_date} to {end_date}")
end_local = datetime(year, month + 1, 1, tzinfo=zone)

# SQL Simulation (This would be executed against the actual DB)
query = """
SELECT SUM(total_amount) as total
query = text("""
SELECT
property_id,
COALESCE(SUM(total_amount), 0) AS total_revenue,
COUNT(*) AS reservation_count,
COALESCE(MAX(currency), 'USD') AS currency
FROM reservations
WHERE property_id = $1
AND tenant_id = $2
AND check_in_date >= $3
AND check_in_date < $4
"""

# In production this query executes against a database session.
# result = await db.fetch_val(query, property_id, tenant_id, start_date, end_date)
# return result or Decimal('0')

return Decimal('0') # Placeholder for now until DB connection is finalized
WHERE property_id = :property_id
AND tenant_id = :tenant_id
AND check_in_date >= :start_date
AND check_in_date < :end_date
GROUP BY property_id
""")

result = await session.execute(
query,
{
"property_id": property_id,
"tenant_id": tenant_id,
"start_date": start_local.astimezone(timezone.utc),
"end_date": end_local.astimezone(timezone.utc),
},
)
row = result.fetchone()

if row:
total_revenue = Decimal(str(row.total_revenue)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
return {
"property_id": property_id,
"tenant_id": tenant_id,
"total": str(total_revenue),
"currency": row.currency or "USD",
"count": row.reservation_count,
"month": month,
"year": year,
"timezone": property_tz,
}

return {
"property_id": property_id,
"tenant_id": tenant_id,
"total": "0.00",
"currency": "USD",
"count": 0,
"month": month,
"year": year,
"timezone": property_tz,
}


async def calculate_monthly_revenue(
property_id: str,
tenant_id: str,
month: int,
year: int,
db_session=None,
) -> Dict[str, Any]:
"""Calculate a property's revenue for one month in the property's timezone."""

async def calculate_total_revenue(property_id: str, tenant_id: str) -> Dict[str, Any]:
"""
Aggregates revenue from database.
"""
try:
# Import database pool
from app.core.database_pool import DatabasePool

# Initialize pool if needed

if db_session is not None:
return await _fetch_monthly_summary(db_session, property_id, tenant_id, month, year)

db_pool = DatabasePool()
await db_pool.initialize()

if db_pool.session_factory:
async with db_pool.get_session() as session:
# Use SQLAlchemy text for raw SQL
from sqlalchemy import text

query = text("""
SELECT
property_id,
SUM(total_amount) as total_revenue,
COUNT(*) as reservation_count
FROM reservations
WHERE property_id = :property_id AND tenant_id = :tenant_id
GROUP BY property_id
""")

result = await session.execute(query, {
"property_id": property_id,
"tenant_id": tenant_id
})
row = result.fetchone()

if row:
total_revenue = Decimal(str(row.total_revenue))
return {
"property_id": property_id,
"tenant_id": tenant_id,
"total": str(total_revenue),
"currency": "USD",
"count": row.reservation_count
}
else:
# No reservations found for this property
return {
"property_id": property_id,
"tenant_id": tenant_id,
"total": "0.00",
"currency": "USD",
"count": 0
}
else:

if not db_pool.session_factory:
raise Exception("Database pool not available")


async with (await db_pool.get_session()) as session:
return await _fetch_monthly_summary(session, property_id, tenant_id, month, year)

except Exception as e:
# Database unavailable or error occurred. Return a safe zeroed response
# to avoid leaking mocked financial data across tenants.
print(f"Database error for {property_id} (tenant: {tenant_id}): {e}")

# Create property-specific mock data for testing when DB is unavailable
# This ensures each property shows different figures
mock_data = {
'prop-001': {'total': '1000.00', 'count': 3},
'prop-002': {'total': '4975.50', 'count': 4},
'prop-003': {'total': '6100.50', 'count': 2},
'prop-004': {'total': '1776.50', 'count': 4},
'prop-005': {'total': '3256.00', 'count': 3}
}

mock_property_data = mock_data.get(property_id, {'total': '0.00', 'count': 0})

return {
"property_id": property_id,
"tenant_id": tenant_id,
"total": mock_property_data['total'],
"tenant_id": tenant_id,
"total": "0.00",
"currency": "USD",
"count": mock_property_data['count']
"count": 0,
"month": month,
"year": year,
"timezone": "UTC",
}


async def calculate_total_revenue(property_id: str, tenant_id: str) -> Dict[str, Any]:
"""Aggregate revenue for the current month."""

now = datetime.now(timezone.utc)
return await calculate_monthly_revenue(property_id, tenant_id, now.month, now.year)
5 changes: 4 additions & 1 deletion frontend/src/apiConfig.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import axios from 'axios';
import { supabase } from "./lib/supabase";

const backendBaseUrl = import.meta.env.VITE_BACKEND_URL
|| (typeof window !== 'undefined' ? `${window.location.protocol}//${window.location.hostname}:8000` : 'http://localhost:8000');

const Api = axios.create({
baseURL: import.meta.env.VITE_BACKEND_URL + '/api/v1',
baseURL: `${backendBaseUrl}/api/v1`,
});


Expand Down
9 changes: 2 additions & 7 deletions frontend/src/components/RevenueSummary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,16 @@ interface RevenueSummaryProps {
showRaw?: boolean;
}

export const RevenueSummary: React.FC<RevenueSummaryProps> = ({ propertyId = 'prop-001', debugTenant, showRaw }) => {
export const RevenueSummary: React.FC<RevenueSummaryProps> = ({ propertyId = 'prop-001', showRaw }) => {
const [data, setData] = useState<RevenueData | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');

const activeTenant = debugTenant || 'candidate';

useEffect(() => {
const fetchRevenue = async () => {
setLoading(true);
try {
// Use SecureAPI to handle authentication automatically
// We pass the simulatedTenant option which SecureAPI will attach as a header
const response = await SecureAPI.getDashboardSummary(propertyId, {
simulatedTenant: activeTenant,
timestamp: Date.now()
});
setData(response);
Expand All @@ -41,7 +36,7 @@ export const RevenueSummary: React.FC<RevenueSummaryProps> = ({ propertyId = 'pr
};

fetchRevenue();
}, [propertyId, activeTenant]);
}, [propertyId]);

if (loading) {
return (
Expand Down
Loading