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
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
node_modules/

# Python bytecode and local test caches
__pycache__/
*.py[cod]
.pytest_cache/
8 changes: 5 additions & 3 deletions backend/app/api/v1/dashboard.py
Original file line number Diff line number Diff line change
@@ -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()
Expand All @@ -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']
}
14 changes: 8 additions & 6 deletions backend/app/core/database_pool.py
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -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
Expand All @@ -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")
Expand Down
4 changes: 3 additions & 1 deletion backend/app/services/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
158 changes: 103 additions & 55 deletions backend/app/services/reservations.py
Original file line number Diff line number Diff line change
@@ -1,76 +1,142 @@
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:
# Use SQLAlchemy text for raw SQL
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:
Expand All @@ -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
37 changes: 26 additions & 11 deletions frontend/src/components/Dashboard.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<div className="p-4 lg:p-6 min-h-full">
Expand All @@ -35,7 +50,7 @@ const Dashboard: React.FC = () => {
onChange={(e) => setSelectedProperty(e.target.value)}
className="block w-full sm:w-auto min-w-[200px] px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 text-sm"
>
{PROPERTIES.map((property) => (
{properties.map((property) => (
<option key={property.id} value={property.id}>
{property.name}
</option>
Expand All @@ -46,7 +61,7 @@ const Dashboard: React.FC = () => {
</div>

<div className="space-y-6">
<RevenueSummary propertyId={selectedProperty} />
{selectedProperty && <RevenueSummary propertyId={selectedProperty} />}
</div>
</div>
</div>
Expand Down
6 changes: 3 additions & 3 deletions frontend/src/components/RevenueSummary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { SecureAPI } from '../lib/secureApi';

interface RevenueData {
property_id: string;
total_revenue: number;
total_revenue: string;
currency: string;
reservations_count: number;
}
Expand Down Expand Up @@ -61,7 +61,7 @@ export const RevenueSummary: React.FC<RevenueSummaryProps> = ({ propertyId = 'pr
if (error) return <div className="p-4 text-red-500 bg-red-50 rounded-lg">{error}</div>;
if (!data) return null;

const displayTotal = Math.round(data.total_revenue * 100) / 100;
const displayTotal = Number(data.total_revenue);

return (
<div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden hover:shadow-md transition-shadow duration-300">
Expand Down Expand Up @@ -104,7 +104,7 @@ export const RevenueSummary: React.FC<RevenueSummaryProps> = ({ propertyId = 'pr

{/* Precision Warning Area */}
<div className="mt-4 h-6">
{Math.abs(data.total_revenue - displayTotal) > 0.000001 && showRaw && (
{data.total_revenue !== displayTotal.toFixed(2) && showRaw && (
<div className="flex items-center text-xs text-amber-600 bg-amber-50 px-2 py-1 rounded">
<svg className="h-4 w-4 mr-1.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
Expand Down
9 changes: 8 additions & 1 deletion frontend/src/contexts/AuthContext.new.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,13 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
source = 'user_metadata';
}

// Local challenge authentication returns tenant_id directly on the user.
// Preserve it when the token does not expose the tenant in metadata.
if (!tenant_id && enhancedUser.tenant_id) {
tenant_id = enhancedUser.tenant_id;
source = 'user';
}

// Add tenant_id as a direct property for backward compatibility
enhancedUser.tenant_id = tenant_id;

Expand Down Expand Up @@ -343,4 +350,4 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
{children}
</AuthContext.Provider>
);
};
};
Loading