diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..bef9b2d4a --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +node_modules/ + +# Python bytecode and local test caches +__pycache__/ +*.py[cod] +.pytest_cache/ \ No newline at end of file diff --git a/backend/app/api/v1/dashboard.py b/backend/app/api/v1/dashboard.py index 1ec352d7e..31b6c20c6 100644 --- a/backend/app/api/v1/dashboard.py +++ b/backend/app/api/v1/dashboard.py @@ -1,6 +1,7 @@ from fastapi import APIRouter, Depends, HTTPException from typing import Dict, Any from app.services.cache import get_revenue_summary +from app.services.reservations import property_belongs_to_tenant from app.core.auth import authenticate_request as get_current_user router = APIRouter() @@ -12,14 +13,15 @@ async def get_dashboard_summary( ) -> Dict[str, Any]: tenant_id = getattr(current_user, "tenant_id", "default_tenant") or "default_tenant" + + if not await property_belongs_to_tenant(property_id, tenant_id): + raise HTTPException(status_code=404, detail="Property not found") revenue_data = await get_revenue_summary(property_id, tenant_id) - total_revenue_float = float(revenue_data['total']) - return { "property_id": revenue_data['property_id'], - "total_revenue": total_revenue_float, + "total_revenue": revenue_data['total'], "currency": revenue_data['currency'], "reservations_count": revenue_data['count'] } diff --git a/backend/app/core/database_pool.py b/backend/app/core/database_pool.py index d638dfcfe..5ba0ac0cf 100644 --- a/backend/app/core/database_pool.py +++ b/backend/app/core/database_pool.py @@ -1,6 +1,4 @@ -import asyncio from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker -from sqlalchemy.pool import QueuePool import logging from ..config import settings @@ -14,12 +12,16 @@ def __init__(self): 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}" + # Compose provides DATABASE_URL using the synchronous PostgreSQL + # scheme. SQLAlchemy's async engine needs the asyncpg scheme. + database_url = settings.database_url + if database_url.startswith("postgresql://"): + database_url = database_url.replace( + "postgresql://", "postgresql+asyncpg://", 1 + ) 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 @@ -45,7 +47,7 @@ async def close(self): if self.engine: await self.engine.dispose() - async def get_session(self) -> AsyncSession: + def get_session(self) -> AsyncSession: """Get database session from pool""" if not self.session_factory: raise Exception("Database pool not initialized") diff --git a/backend/app/services/cache.py b/backend/app/services/cache.py index b81474957..ac228602e 100644 --- a/backend/app/services/cache.py +++ b/backend/app/services/cache.py @@ -10,7 +10,9 @@ 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}" + # Property IDs are only unique within a tenant. Include both dimensions + # so one tenant can never read another tenant's cached revenue. + cache_key = f"revenue:{tenant_id}:{property_id}" # Try to get from cache cached = await redis_client.get(cache_key) diff --git a/backend/app/services/reservations.py b/backend/app/services/reservations.py index 384bd00ab..4dfa80f26 100644 --- a/backend/app/services/reservations.py +++ b/backend/app/services/reservations.py @@ -1,47 +1,108 @@ -from datetime import datetime +from datetime import datetime, timezone from decimal import Decimal from typing import Dict, Any, List +from zoneinfo import ZoneInfo -async def calculate_monthly_revenue(property_id: str, month: int, year: int, db_session=None) -> Decimal: + +async def property_belongs_to_tenant(property_id: str, tenant_id: str) -> bool: + """Return whether a property is owned by the requesting tenant.""" + from sqlalchemy import text + from app.core.database_pool import db_pool + + if db_pool.session_factory is None: + await db_pool.initialize() + + if db_pool.session_factory is None: + raise RuntimeError("Database pool not available") + + async with db_pool.get_session() as session: + result = 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}, + ) + return result.scalar_one_or_none() is not None + +async def calculate_monthly_revenue( + property_id: str, + month: int, + year: int, + tenant_id: str = None, + 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) - else: - end_date = datetime(year + 1, 1, 1) - - print(f"DEBUG: Querying revenue for {property_id} from {start_date} to {end_date}") - - # 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 + if not tenant_id: + raise ValueError("tenant_id is required for monthly revenue calculation") + + from sqlalchemy import text + from app.core.database_pool import db_pool + + if db_session is None: + if db_pool.session_factory is None: + await db_pool.initialize() + if db_pool.session_factory is None: + raise RuntimeError("Database pool not available") + + property_query = text(""" + SELECT timezone + FROM properties + WHERE id = :property_id AND tenant_id = :tenant_id + """) + + async def calculate(session) -> Decimal: + property_result = await session.execute(property_query, { + "property_id": property_id, + "tenant_id": tenant_id, + }) + property_row = property_result.fetchone() + if not property_row: + raise ValueError("Property not found") + + property_timezone = ZoneInfo(property_row.timezone) + start_date = datetime(year, month, 1, tzinfo=property_timezone) + if month < 12: + end_date = datetime(year, month + 1, 1, tzinfo=property_timezone) + else: + end_date = datetime(year + 1, 1, 1, tzinfo=property_timezone) + + result = await session.execute(text(""" + SELECT COALESCE(SUM(total_amount), 0) AS total + FROM reservations + WHERE property_id = :property_id + AND tenant_id = :tenant_id + AND check_in_date >= :start_date + AND check_in_date < :end_date + """), { + "property_id": property_id, + "tenant_id": tenant_id, + "start_date": start_date.astimezone(timezone.utc), + "end_date": end_date.astimezone(timezone.utc), + }) + return Decimal(str(result.scalar_one())) + + if db_session is not None: + return await calculate(db_session) + + async with db_pool.get_session() as session: + return await calculate(session) 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 + from app.core.database_pool import db_pool # Initialize pool if needed - db_pool = DatabasePool() - await db_pool.initialize() + if db_pool.session_factory is None: + await db_pool.initialize() if db_pool.session_factory: async with db_pool.get_session() as session: @@ -49,28 +110,33 @@ async def calculate_total_revenue(property_id: str, tenant_id: str) -> Dict[str, from sqlalchemy import text query = text(""" - SELECT + SELECT property_id, + currency, 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 + GROUP BY property_id, currency """) result = await session.execute(query, { "property_id": property_id, "tenant_id": tenant_id }) - row = result.fetchone() + rows = result.fetchall() - if row: + if len(rows) > 1: + raise ValueError("Cannot aggregate revenue across multiple currencies") + + if rows: + row = rows[0] total_revenue = Decimal(str(row.total_revenue)) return { "property_id": property_id, "tenant_id": tenant_id, "total": str(total_revenue), - "currency": "USD", + "currency": row.currency, "count": row.reservation_count } else: @@ -86,24 +152,6 @@ async def calculate_total_revenue(property_id: str, tenant_id: str) -> Dict[str, 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}) - - return { - "property_id": property_id, - "tenant_id": tenant_id, - "total": mock_property_data['total'], - "currency": "USD", - "count": mock_property_data['count'] - } + raise RuntimeError( + f"Unable to calculate revenue for property {property_id}" + ) from e diff --git a/frontend/src/components/Dashboard.tsx b/frontend/src/components/Dashboard.tsx index a21bba404..96ec7a64e 100644 --- a/frontend/src/components/Dashboard.tsx +++ b/frontend/src/components/Dashboard.tsx @@ -1,16 +1,31 @@ -import React, { useState } from "react"; +import React, { useEffect, useState } from "react"; import { RevenueSummary } from "./RevenueSummary"; +import { useAuth } from "../contexts/AuthContext.new"; -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' } -]; +const PROPERTIES_BY_TENANT = { + 'tenant-a': [ + { id: 'prop-001', name: 'Beach House Alpha' }, + { id: 'prop-002', name: 'City Apartment Downtown' }, + { id: 'prop-003', name: 'Country Villa Estate' } + ], + 'tenant-b': [ + { id: 'prop-001', name: 'Mountain Lodge Beta' }, + { id: 'prop-004', name: 'Lakeside Cottage' }, + { id: 'prop-005', name: 'Urban Loft Modern' } + ] +} as const; const Dashboard: React.FC = () => { - const [selectedProperty, setSelectedProperty] = useState('prop-001'); + const { user } = useAuth(); + const tenantId = user?.tenant_id; + const properties = tenantId ? PROPERTIES_BY_TENANT[tenantId as keyof typeof PROPERTIES_BY_TENANT] || [] : []; + const [selectedProperty, setSelectedProperty] = useState(''); + + useEffect(() => { + if (properties.length > 0 && !properties.some((property) => property.id === selectedProperty)) { + setSelectedProperty(properties[0].id); + } + }, [properties, selectedProperty]); return (