From 3ae7d8085de8ddc7d61b4000da50cc071ab37144 Mon Sep 17 00:00:00 2001 From: Amani Date: Tue, 10 Nov 2026 16:09:23 +0100 Subject: [PATCH 1/3] Fix monthly revenue accuracy: real DB connection, timezone-aware months, decimal rounding --- backend/app/api/v1/dashboard.py | 10 ++++-- backend/app/core/database_pool.py | 6 ++-- backend/app/services/reservations.py | 40 +++++++++++++--------- backend/pyproject.toml | 2 +- backend/requirements.txt | 2 +- frontend/src/components/RevenueSummary.tsx | 4 ++- 6 files changed, 38 insertions(+), 26 deletions(-) diff --git a/backend/app/api/v1/dashboard.py b/backend/app/api/v1/dashboard.py index 1ec352d7e3..e3db64b75b 100644 --- a/backend/app/api/v1/dashboard.py +++ b/backend/app/api/v1/dashboard.py @@ -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 @@ -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'] } diff --git a/backend/app/core/database_pool.py b/backend/app/core/database_pool.py index d638dfcfe3..eea590f435 100644 --- a/backend/app/core/database_pool.py +++ b/backend/app/core/database_pool.py @@ -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 @@ -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 @@ -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") diff --git a/backend/app/services/reservations.py b/backend/app/services/reservations.py index 384bd00abe..484267f260 100644 --- a/backend/app/services/reservations.py +++ b/backend/app/services/reservations.py @@ -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. """ @@ -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]: """ diff --git a/backend/pyproject.toml b/backend/pyproject.toml index ebaa4bc92d..6968736a46 100644 --- a/backend/pyproject.toml +++ b/backend/pyproject.toml @@ -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", 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/RevenueSummary.tsx b/frontend/src/components/RevenueSummary.tsx index dbb6d0629d..80f6ea8ef8 100644 --- a/frontend/src/components/RevenueSummary.tsx +++ b/frontend/src/components/RevenueSummary.tsx @@ -61,7 +61,9 @@ export const RevenueSummary: React.FC = ({ propertyId = 'pr if (error) return
{error}
; 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 (
From 38f086ec8d208721428973ea9ec48fc4818da7f3 Mon Sep 17 00:00:00 2001 From: Amani Date: Tue, 10 Nov 2026 16:10:42 +0100 Subject: [PATCH 2/3] Add tenant_id in cache key --- backend/app/services/cache.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/app/services/cache.py b/backend/app/services/cache.py index b81474957f..672e3f9d69 100644 --- a/backend/app/services/cache.py +++ b/backend/app/services/cache.py @@ -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) From 94f4d25306d40cdff6ced93c29ad304c8cd5010d Mon Sep 17 00:00:00 2001 From: Amani Date: Tue, 10 Nov 2026 16:19:52 +0100 Subject: [PATCH 3/3] Document the bugs in Readme --- README.md | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000000..7fb09d22de --- /dev/null +++ b/README.md @@ -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. + +---