Skip to content
Closed
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
47 changes: 47 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Property Revenue Dashboard – Bug Fixes

Summary of the issues reported by clients, their root causes, and how each was fixed.

---

## Bug 1 – Monthly revenue doesn't match client records (Client A – Sunset Properties)

**Symptom**
Sunset's March total for Beach House Alpha showed 1,000.00 from 3 bookings, while their records show 2,250.00 from 4 bookings.

**Root cause**
1. **Month boundaries were calculated in UTC instead of the property's local time.** One reservation checks in at 23:30 UTC on 29 February, which is 00:30 on 1 March in Paris, where the property is. The client correctly counts it as March, but the system put it in February.

**Fix**
- The monthly revenue calculation now converts each check-in date to the property's own timezone before deciding which month it belongs to.

---

## Bug 2 – Clients seeing another company's revenue (Client B – Ocean Rentals)

**Symptom**
When refreshing the dashboard, Ocean Rentals sometimes saw revenue that belonged to Sunset Properties.

**Root cause**
Revenue summaries are cached for 5 minutes, and the cache key contained only the property ID, not the tenant. Both clients have a property with the same ID (prop-001). Whichever client loaded it first filled the cache, and the other client was then shown that cached data.

**Fix**
The cache key now includes the tenant as well as the property ID, so each client's cached data is stored and read separately. After the fix, Ocean's prop-001 correctly shows 0.00 while Sunset's shows 2,250.00.

---

## Bug 3 – Totals "slightly off" by a few cents (Finance team)

**Symptom**
Some revenue totals were off by one cent, with no obvious pattern.

**Root cause**
Amounts are stored with three decimal places to track sub-cent values. The exact total was converted to a floating-point number in the backend and then rounded again with floating-point math in the frontend. Floats can't represent most decimal values exactly; for example, 128.015 is really stored as slightly less than that, so it rounds down to 128.01 instead of up to 128.02. This only affects some amounts, which is why the error looked random.

**Fix**
The total stays an exact decimal value throughout the calculation and is rounded once, to the cent, using standard half-up rounding before the API returns it. The frontend no longer rounds it again.

**Note**
Our totals add up exact amounts and round once at the end. If the finance team rounds each reservation to the cent before adding them up, their totals can still differ by a cent; for example, three bookings of 333.333, 333.333 and 333.334 give 1,000.00 our way and 999.99 their way. This is a business choice rather than a bug, and one convention should be agreed on and used everywhere.

---
10 changes: 7 additions & 3 deletions backend/app/api/v1/dashboard.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from fastapi import APIRouter, Depends, HTTPException
from typing import Dict, Any
from decimal import Decimal, ROUND_HALF_UP
from app.services.cache import get_revenue_summary
from app.core.auth import authenticate_request as get_current_user

Expand All @@ -15,11 +16,14 @@ async def get_dashboard_summary(

revenue_data = await get_revenue_summary(property_id, tenant_id)

total_revenue_float = float(revenue_data['total'])

# Round once, in Decimal, to whole cents (half-up as in accounting) before
# leaving the API. Converting the raw sub-cent NUMERIC straight to float
# lets binary rounding error (e.g. 2.675 -> 2.67) leak into displayed totals.
total_revenue = Decimal(revenue_data['total']).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)

return {
"property_id": revenue_data['property_id'],
"total_revenue": total_revenue_float,
"total_revenue": float(total_revenue),
"currency": revenue_data['currency'],
"reservations_count": revenue_data['count']
}
6 changes: 2 additions & 4 deletions backend/app/core/database_pool.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
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 @@ -15,11 +14,10 @@ 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}"
database_url = settings.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 +43,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
2 changes: 1 addition & 1 deletion backend/app/services/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ 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}"
cache_key = f"revenue:{tenant_id}:{property_id}"

# Try to get from cache
cached = await redis_client.get(cache_key)
Expand Down
40 changes: 24 additions & 16 deletions backend/app/services/reservations.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
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:
async def calculate_monthly_revenue(property_id: str, tenant_id: str, month: int, year: int, db_session=None) -> Decimal:
"""
Calculates revenue for a specific month.
"""
Expand All @@ -15,21 +15,29 @@ async def calculate_monthly_revenue(property_id: str, month: int, year: int, db_

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
# Month boundaries must be evaluated in the property's local timezone:
# e.g. 2024-02-29 23:30 UTC is 2024-03-01 00:30 in Europe/Paris -> March.
from sqlalchemy import text
from app.core.database_pool import DatabasePool

query = text("""
SELECT COALESCE(SUM(r.total_amount), 0) as total
FROM reservations r
JOIN properties p ON p.id = r.property_id AND p.tenant_id = r.tenant_id
WHERE r.property_id = :property_id
AND r.tenant_id = :tenant_id
AND (r.check_in_date AT TIME ZONE p.timezone) >= :start_date
AND (r.check_in_date AT TIME ZONE p.timezone) < :end_date
""")

db_pool = DatabasePool()
await db_pool.initialize()
async with db_pool.get_session() as session:
result = await session.execute(query, {
"property_id": property_id, "tenant_id": tenant_id,
"start_date": start_date, "end_date": end_date,
})
return Decimal(result.scalar_one())

async def calculate_total_revenue(property_id: str, tenant_id: str) -> Dict[str, Any]:
"""
Expand Down
2 changes: 1 addition & 1 deletion backend/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ dependencies = [
"reportlab>=4.4.3",
"requests>=2.32.4",
"sendgrid>=6.12.4",
"sqlalchemy>=2.0.0",
"sqlalchemy[asyncio]>=2.0.0",
"stripe>=7.0.0",
"supabase>=2.18.0",
"tenacity>=9.1.2",
Expand Down
2 changes: 1 addition & 1 deletion backend/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
4 changes: 3 additions & 1 deletion frontend/src/components/RevenueSummary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,9 @@ 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;
// The API already rounds to whole cents using Decimal; re-rounding here with
// float math (Math.round(x * 100) / 100) can be off by a cent.
const displayTotal = 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