From 6ee10a414be68f5d741ea2ed725b2f2ac251c8a5 Mon Sep 17 00:00:00 2001 From: ismail710 Date: Wed, 18 Nov 2026 19:08:48 +0000 Subject: [PATCH] Fix tenant-safe monthly revenue dashboard --- backend/app/api/v1/dashboard.py | 70 +++++++-- backend/app/core/database_pool.py | 65 ++++---- backend/app/services/cache.py | 51 +++--- backend/app/services/reservations.py | 171 +++++++++------------ backend/requirements.txt | 2 +- frontend/src/components/Dashboard.tsx | 79 +++++----- frontend/src/components/RevenueSummary.tsx | 119 ++++---------- frontend/src/lib/secureApi.ts | 14 +- 8 files changed, 265 insertions(+), 306 deletions(-) diff --git a/backend/app/api/v1/dashboard.py b/backend/app/api/v1/dashboard.py index 1ec352d7e3..7abda23890 100644 --- a/backend/app/api/v1/dashboard.py +++ b/backend/app/api/v1/dashboard.py @@ -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"], } diff --git a/backend/app/core/database_pool.py b/backend/app/core/database_pool.py index d638dfcfe3..ec35469b05 100644 --- a/backend/app/core/database_pool.py +++ b/backend/app/core/database_pool.py @@ -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 diff --git a/backend/app/services/cache.py b/backend/app/services/cache.py index b81474957f..e04eadb0c1 100644 --- a/backend/app/services/cache.py +++ b/backend/app/services/cache.py @@ -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 diff --git a/backend/app/services/reservations.py b/backend/app/services/reservations.py index 384bd00abe..8deb9c4b10 100644 --- a/backend/app/services/reservations.py +++ b/backend/app/services/reservations.py @@ -1,109 +1,80 @@ -from datetime import datetime -from decimal import Decimal -from typing import Dict, Any, List +from datetime import datetime, timezone +from decimal import Decimal, ROUND_HALF_UP +from typing import Any, Dict, Optional +from zoneinfo import ZoneInfo, ZoneInfoNotFoundError -async def calculate_monthly_revenue(property_id: str, month: int, year: int, db_session=None) -> Decimal: - """ - Calculates revenue for a specific month. - """ +from sqlalchemy import text - start_date = datetime(year, month, 1) - if month < 12: - end_date = datetime(year, month + 1, 1) +from app.core.database_pool import db_pool + + +CENT = Decimal("0.01") + + +def month_bounds(month: str, timezone_name: str): + year, month_number = (int(part) for part in month.split("-")) + zone = ZoneInfo(timezone_name) + start_local = datetime(year, month_number, 1, tzinfo=zone) + if month_number == 12: + next_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}") + next_local = datetime(year, month_number + 1, 1, tzinfo=zone) + return start_local.astimezone(timezone.utc), next_local.astimezone(timezone.utc) - # SQL Simulation (This would be executed against the actual DB) - query = """ - SELECT SUM(total_amount) as total - 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 -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 - db_pool = DatabasePool() +async def calculate_total_revenue( + property_id: str, tenant_id: str, month: Optional[str] = None +) -> Dict[str, Any]: + """Return property-local monthly revenue rounded to currency precision.""" + if not tenant_id: + raise ValueError("Authenticated user has no tenant") + if not db_pool.session_factory: 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: - raise Exception("Database pool not available") - - except Exception as e: - 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}) - + + async with db_pool.get_session() as session: + property_row = (await session.execute(text(""" + SELECT timezone FROM properties + WHERE id = :property_id AND tenant_id = :tenant_id + """), {"property_id": property_id, "tenant_id": tenant_id})).first() + if not property_row: + return {"not_found": True} + timezone_name = property_row.timezone or "UTC" + zone = ZoneInfo(timezone_name) + + if month is None: + latest = (await session.execute(text(""" + SELECT MAX(check_in_date) AS latest + FROM reservations + WHERE property_id = :property_id AND tenant_id = :tenant_id + """), {"property_id": property_id, "tenant_id": tenant_id})).first() + latest_date = latest.latest if latest else None + month = latest_date.astimezone(zone).strftime("%Y-%m") if latest_date else datetime.now(zone).strftime("%Y-%m") + + try: + start_utc, end_utc = month_bounds(month, timezone_name) + except (ValueError, TypeError, ZoneInfoNotFoundError) as exc: + raise ValueError("month must be YYYY-MM and timezone must be valid") from exc + + row = (await session.execute(text(""" + SELECT COALESCE(SUM(total_amount), 0) AS total, + COUNT(*) AS reservation_count, + COALESCE(MIN(currency), 'USD') AS currency + FROM reservations + WHERE property_id = :property_id AND tenant_id = :tenant_id + AND check_in_date >= :start_utc AND check_in_date < :end_utc + """), { + "property_id": property_id, + "tenant_id": tenant_id, + "start_utc": start_utc, + "end_utc": end_utc, + })).first() + total = Decimal(str(row.total)).quantize(CENT, rounding=ROUND_HALF_UP) return { "property_id": property_id, - "tenant_id": tenant_id, - "total": mock_property_data['total'], - "currency": "USD", - "count": mock_property_data['count'] + "tenant_id": tenant_id, + "month": month, + "timezone": timezone_name, + "total": format(total, ".2f"), + "currency": row.currency, + "count": row.reservation_count, } diff --git a/backend/requirements.txt b/backend/requirements.txt index 6b777d2aaa..06cb8bd4a6 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -18,7 +18,7 @@ pytz redis>=5.0.0 requests sendgrid -sqlalchemy>=2.0.0 +sqlalchemy[asyncio]>=2.0.0 supabase tenacity>=8.0.0 uvicorn[standard] diff --git a/frontend/src/components/Dashboard.tsx b/frontend/src/components/Dashboard.tsx index a21bba404e..6c89d6919d 100644 --- a/frontend/src/components/Dashboard.tsx +++ b/frontend/src/components/Dashboard.tsx @@ -1,53 +1,58 @@ -import React, { useState } from "react"; +import React, { useEffect, useState } from "react"; import { RevenueSummary } from "./RevenueSummary"; +import { SecureAPI } from "../lib/secureApi"; -const PROPERTIES = [ - { id: 'prop-001', name: 'Beach House Alpha' }, - { id: 'prop-002', name: 'City Apartment Downtown' }, - { id: 'prop-003', name: 'Country Villa Estate' }, - { id: 'prop-004', name: 'Lakeside Cottage' }, - { id: 'prop-005', name: 'Urban Loft Modern' } -]; +type PropertyOption = { id: string; name: string }; const Dashboard: React.FC = () => { - const [selectedProperty, setSelectedProperty] = useState('prop-001'); + const [properties, setProperties] = useState([]); + const [selectedProperty, setSelectedProperty] = useState(""); + const [month, setMonth] = useState(""); + const [error, setError] = useState(""); + + useEffect(() => { + let active = true; + SecureAPI.getDashboardProperties() + .then((result) => { + if (!active) return; + setProperties(result); + setSelectedProperty(result[0]?.id ?? ""); + }) + .catch((err) => { + console.error("Failed to load tenant properties", err); + if (active) setError("Failed to load your properties"); + }); + return () => { active = false; }; + }, []); return (

Property Management Dashboard

-
-
-
-
-

Revenue Overview

-

- Monthly performance insights for your properties -

-
- - {/* Property Selector */} -
- - setSelectedProperty(e.target.value)} disabled={!properties.length} + className="min-w-[200px] px-3 py-2 border border-gray-300 rounded-md text-sm"> + {properties.map((property) => )} -
+ +
- -
- -
+ {error &&

{error}

} + {properties.length === 0 && !error &&

Loading your properties…

} + {selectedProperty && }
diff --git a/frontend/src/components/RevenueSummary.tsx b/frontend/src/components/RevenueSummary.tsx index dbb6d0629d..95f921f974 100644 --- a/frontend/src/components/RevenueSummary.tsx +++ b/frontend/src/components/RevenueSummary.tsx @@ -3,115 +3,54 @@ import { SecureAPI } from '../lib/secureApi'; interface RevenueData { property_id: string; - total_revenue: number; + total_revenue: string; currency: string; reservations_count: number; + month: string; + timezone: string; } interface RevenueSummaryProps { propertyId?: string; - debugTenant?: string; + month?: string; showRaw?: boolean; } -export const RevenueSummary: React.FC = ({ propertyId = 'prop-001', debugTenant, showRaw }) => { +export const RevenueSummary: React.FC = ({ propertyId = 'prop-001', month, showRaw }) => { const [data, setData] = useState(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); - } catch (err) { - setError('Failed to load revenue data'); + let active = true; + setLoading(true); + SecureAPI.getDashboardSummary(propertyId, { month, timestamp: Date.now() }) + .then((response) => { if (active) { setData(response); setError(''); } }) + .catch((err) => { console.error(err); - } finally { - setLoading(false); - } - }; - - fetchRevenue(); - }, [propertyId, activeTenant]); - - if (loading) { - return ( -
-
-
-
-
-
-
-
-
-
- ); - } - - if (error) return
{error}
; + if (active) setError('Failed to load revenue data. Please try again.'); + }) + .finally(() => { if (active) setLoading(false); }); + return () => { active = false; }; + }, [propertyId, month]); + + if (loading) return
Loading revenue…
; + if (error) return
{error}
; if (!data) return null; - const displayTotal = Math.round(data.total_revenue * 100) / 100; - + const total = Number(data.total_revenue); return ( -
- {showRaw && ( -
- Raw API Response -
{JSON.stringify(data, null, 2)}
-
- )} - +
+ {showRaw &&
{JSON.stringify(data, null, 2)}
}
-
-
-

Total Revenue

-
- - {data.currency} {displayTotal.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })} - - {/* Fake trend indicator for premium feel */} - - - 12% - -
-
-
- -
-
-

Property ID

-

{data.property_id}

-
-
-

Reservations

-

{data.reservations_count} bookings

-
-
- - {/* Precision Warning Area */} -
- {Math.abs(data.total_revenue - displayTotal) > 0.000001 && showRaw && ( -
- - - - Precision Mismatch Detected -
- )} +

Total Revenue

+

+ {data.currency} {total.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })} +

+

{data.month} · {data.timezone}

+
+

Property ID

{data.property_id}

+

Reservations

{data.reservations_count} bookings

diff --git a/frontend/src/lib/secureApi.ts b/frontend/src/lib/secureApi.ts index f85f04c90a..11abd74e50 100644 --- a/frontend/src/lib/secureApi.ts +++ b/frontend/src/lib/secureApi.ts @@ -1452,20 +1452,18 @@ export class SecureAPIClient { /** * Get dashboard summary with optional simulation header */ - async getDashboardSummary(propertyId: string, options?: { simulatedTenant?: string, timestamp?: number }) { + async getDashboardSummary(propertyId: string, options?: { month?: string, timestamp?: number }) { const queryParams = new URLSearchParams({ property_id: propertyId }); + if (options?.month) queryParams.append('month', options.month); if (options?.timestamp) { queryParams.append('_t', options.timestamp.toString()); } - const requestOptions: RequestInit = {}; - if (options?.simulatedTenant) { - requestOptions.headers = { - 'X-Simulated-Tenant': options.simulatedTenant - }; - } + return this.request(`/api/v1/dashboard/summary?${queryParams}`); + } - return this.request(`/api/v1/dashboard/summary?${queryParams}`, requestOptions); + async getDashboardProperties() { + return this.request>('/api/v1/dashboard/properties'); } async uploadCompanyLogo(logo_url: string) {