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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Python bytecode and interpreter caches
__pycache__/
*.py[cod]
74 changes: 59 additions & 15 deletions backend/app/api/v1/dashboard.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,69 @@
from fastapi import APIRouter, Depends, HTTPException
from typing import Dict, Any
import logging
from typing import Any, Dict

from fastapi import APIRouter, Depends, HTTPException, Query

from app.core.auth import authenticate_request
from app.models.auth import AuthenticatedUser
from app.services.cache import get_revenue_summary
from app.core.auth import authenticate_request as get_current_user
from app.services.reservations import get_pool

router = APIRouter()
logger = logging.getLogger(__name__)


@router.get("/dashboard/properties")
async def get_dashboard_properties(
current_user: AuthenticatedUser = Depends(authenticate_request),
):
if not current_user.tenant_id:
raise HTTPException(status_code=403, detail="Tenant is required")

try:
pool = await get_pool()
async with pool.acquire() as connection:
rows = await connection.fetch(
"""
SELECT p.id, p.name,
TO_CHAR(MAX(r.check_in_date AT TIME ZONE p.timezone), 'YYYY-MM') AS latest_month
FROM properties p
LEFT JOIN reservations r
ON r.property_id = p.id AND r.tenant_id = p.tenant_id
WHERE p.tenant_id = $1
GROUP BY p.id, p.name, p.tenant_id
ORDER BY p.name
""",
current_user.tenant_id,
)
return [dict(row) for row in rows]
except Exception:
logger.exception("Failed to load dashboard properties")
raise HTTPException(status_code=503, detail="Dashboard data unavailable")


@router.get("/dashboard/summary")
async def get_dashboard_summary(
property_id: str,
current_user: dict = Depends(get_current_user)
month: int = Query(ge=1, le=12),
year: int = Query(ge=1, le=9999),
current_user: AuthenticatedUser = Depends(authenticate_request),
) -> 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'])

if not current_user.tenant_id:
raise HTTPException(status_code=403, detail="Tenant is required")

try:
revenue_data = await get_revenue_summary(property_id, current_user.tenant_id, month, year)
except LookupError:
raise HTTPException(status_code=404, detail="Property not found")
except ValueError as error:
raise HTTPException(status_code=422, detail=str(error))
except Exception:
logger.exception("Failed to load dashboard summary")
raise HTTPException(status_code=503, detail="Dashboard data unavailable")

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"],
}
20 changes: 16 additions & 4 deletions backend/app/core/tenant_resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def resolve_tenant_from_user(user_data: dict) -> Optional[str]:
return None

@staticmethod
async def resolve_tenant_id(user_id: str, user_email: str, token: Optional[str] = None) -> str:
async def resolve_tenant_id(user_id: str, user_email: str, token: Optional[str] = None) -> Optional[str]:
"""
Resolve tenant ID for a user.

Expand All @@ -80,16 +80,28 @@ async def resolve_tenant_id(user_id: str, user_email: str, token: Optional[str]
Returns:
Tenant ID
"""
# Fallback mapping by known user email.
if token:
try:
from jose import jwt
from app.config import settings

payload = jwt.decode(token, settings.secret_key, algorithms=["HS256"], audience="authenticated")
tenant_id = TenantResolver.resolve_tenant_from_token(payload)
if tenant_id:
return tenant_id
except Exception:
# Other auth providers may use a different signing key.
pass

# Local assignment accounts.
if user_email == "sunset@propertyflow.com":
return "tenant-a"
if user_email == "ocean@propertyflow.com":
return "tenant-b"
if user_email == "candidate@propertyflow.com":
return "tenant-a"

# Default fallback
return "tenant-a"
return None

@staticmethod
async def update_user_tenant_metadata(user_id: str, tenant_id: str) -> None:
Expand Down
6 changes: 3 additions & 3 deletions backend/app/services/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@
# 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, year: int) -> Dict[str, Any]:
"""
Fetches revenue summary, utilizing caching to improve performance.
"""
cache_key = f"revenue:{property_id}"
cache_key = f"revenue:v2:{tenant_id}:{property_id}:{year}:{month}"

# Try to get from cache
cached = await redis_client.get(cache_key)
Expand All @@ -21,7 +21,7 @@ async def get_revenue_summary(property_id: str, tenant_id: str) -> Dict[str, Any
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, year)

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

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

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}")
from app.config import settings

# 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
_pool = None
_pool_lock = asyncio.Lock()

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()
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})

return {
"property_id": property_id,
"tenant_id": tenant_id,
"total": mock_property_data['total'],
"currency": "USD",
"count": mock_property_data['count']
}

async def get_pool():
global _pool
if _pool is None:
async with _pool_lock:
if _pool is None:
_pool = await asyncpg.create_pool(dsn=settings.database_url)
return _pool


async def calculate_monthly_revenue(
property_id: str, month: int, year: int, tenant_id: str
) -> Decimal:
"""Return the month's revenue using the property's local check-in date."""
summary = await calculate_total_revenue(property_id, tenant_id, month, year)
return Decimal(summary["total"])


async def calculate_total_revenue(
property_id: str,
tenant_id: str,
month: Optional[int] = None,
year: Optional[int] = None,
) -> Dict[str, Any]:
"""Summarize reservations for a property owned by the authenticated tenant."""
pool = await get_pool()
async with pool.acquire() as connection:
property_result = await connection.fetchrow(
"SELECT id FROM properties WHERE id = $1 AND tenant_id = $2",
property_id, tenant_id,
)
if property_result is None:
raise LookupError("Property not found")

date_filter = ""
params = [property_id, tenant_id]
if month is not None and year is not None:
start_date = datetime(year, month, 1)
end_date = datetime(year + 1, 1, 1) if month == 12 else datetime(year, month + 1, 1)
date_filter = """
AND (r.check_in_date AT TIME ZONE p.timezone) >= $3
AND (r.check_in_date AT TIME ZONE p.timezone) < $4
"""
params.extend([start_date, end_date])

rows = await connection.fetch(
f"""
SELECT r.currency, COALESCE(SUM(r.total_amount), 0) AS total,
COUNT(*) AS reservation_count
FROM reservations r
JOIN properties p ON p.id = r.property_id AND p.tenant_id = r.tenant_id
WHERE r.property_id = $1 AND r.tenant_id = $2
{date_filter}
GROUP BY r.currency
""",
*params,
)

if len(rows) > 1:
raise ValueError("Property reservations contain multiple currencies")

total = rows[0]["total"] if rows else Decimal("0")
return {
"property_id": property_id,
"tenant_id": tenant_id,
"total": str(total.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)),
"currency": rows[0]["currency"] if rows else "USD",
"count": rows[0]["reservation_count"] if rows else 0,
}
Loading