Repository navigation
Fix tenant revenue dashboard calculations #234
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
tonycletus
wants to merge
1
commit into
Base360-AI:main
Choose a base branch
from
tonycletus:codex/fix-tenant-revenue-dashboard
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,109 +1,119 @@ | ||
| 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 | ||
| import pytz | ||
|
|
||
| async def calculate_monthly_revenue(property_id: str, month: int, year: int, db_session=None) -> Decimal: | ||
| """ | ||
| Calculates revenue for a specific month. | ||
| """ | ||
| from sqlalchemy import text | ||
|
|
||
| start_date = datetime(year, month, 1) | ||
| if month < 12: | ||
| end_date = datetime(year, month + 1, 1) | ||
|
|
||
| CENT = Decimal("0.01") | ||
|
|
||
|
|
||
| def _money(value: Any) -> Decimal: | ||
| return Decimal(str(value or 0)).quantize(CENT, rounding=ROUND_HALF_UP) | ||
|
|
||
|
|
||
| async def calculate_monthly_revenue( | ||
| property_id: str, | ||
| month: int, | ||
| year: int, | ||
| tenant_id: str, | ||
| db_session=None, | ||
| ) -> Decimal: | ||
| """Sum reservations whose check-in falls in the property's local month.""" | ||
| summary = await calculate_monthly_summary( | ||
| property_id, month, year, tenant_id, db_session=db_session | ||
| ) | ||
| return Decimal(summary["total"]) | ||
|
|
||
|
|
||
| async def calculate_monthly_summary( | ||
| property_id: str, | ||
| month: int, | ||
| year: int, | ||
| tenant_id: str, | ||
| db_session=None, | ||
| ) -> Dict[str, Any]: | ||
| """Return a tenant-scoped monthly revenue and reservation count.""" | ||
| if not 1 <= month <= 12: | ||
| raise ValueError("month must be between 1 and 12") | ||
|
|
||
| from app.core.database_pool import db_pool | ||
|
|
||
| if db_session is None: | ||
| if db_pool.session_factory is None: | ||
| await db_pool.initialize() | ||
| session_context = await db_pool.get_session() | ||
| 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 | ||
| session_context = None | ||
|
|
||
| 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 | ||
| } | ||
| async def query(session): | ||
| property_row = await session.execute( | ||
| text("SELECT timezone FROM properties WHERE id = :property_id AND tenant_id = :tenant_id"), | ||
| {"property_id": property_id, "tenant_id": tenant_id}, | ||
| ) | ||
| property_data = property_row.fetchone() | ||
| if not property_data: | ||
| return {"total": "0.00", "count": 0} | ||
|
|
||
| timezone = pytz.timezone(property_data.timezone or "UTC") | ||
| start_local = timezone.localize(datetime(year, month, 1), is_dst=None) | ||
| if month == 12: | ||
| end_local = timezone.localize(datetime(year + 1, 1, 1), is_dst=None) | ||
| 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} | ||
| end_local = timezone.localize(datetime(year, month + 1, 1), is_dst=None) | ||
|
|
||
| result = await session.execute( | ||
| text(""" | ||
| SELECT COALESCE(SUM(total_amount), 0) AS total, COUNT(*) AS reservation_count | ||
| 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_local, | ||
| "end_date": end_local, | ||
| }, | ||
| ) | ||
| row = result.fetchone() | ||
| return { | ||
| "total": format(_money(row.total), ".2f"), | ||
| "count": row.reservation_count, | ||
| } | ||
|
|
||
| mock_property_data = mock_data.get(property_id, {'total': '0.00', 'count': 0}) | ||
|
|
||
|
|
||
| if db_session is not None: | ||
| return await query(db_session) | ||
| async with session_context as session: | ||
| return await query(session) | ||
|
|
||
|
|
||
| async def calculate_total_revenue(property_id: str, tenant_id: str) -> Dict[str, Any]: | ||
| """Aggregate exact reservation amounts for one tenant's property.""" | ||
| 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 is unavailable") | ||
|
|
||
| session_context = await db_pool.get_session() | ||
| async with session_context as session: | ||
| result = await session.execute( | ||
| text(""" | ||
| SELECT COALESCE(SUM(total_amount), 0) AS total_revenue, COUNT(*) AS reservation_count | ||
| FROM reservations | ||
| WHERE property_id = :property_id AND tenant_id = :tenant_id | ||
| """), | ||
| {"property_id": property_id, "tenant_id": tenant_id}, | ||
| ) | ||
| row = result.fetchone() | ||
| total = _money(row.total_revenue if row else 0) | ||
| return { | ||
| "property_id": property_id, | ||
| "tenant_id": tenant_id, | ||
| "total": mock_property_data['total'], | ||
| "tenant_id": tenant_id, | ||
| "total": format(total, ".2f"), | ||
| "currency": "USD", | ||
| "count": mock_property_data['count'] | ||
| "count": row.reservation_count if row else 0, | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When a property's monthly reservations include non-USD amounts, this raw sum combines nominal values without conversion, and the dashboard labels the result as USD. Clients therefore see an inaccurate total; convert amounts using an explicit rate or return separate totals by currency.
Useful? React with 👍 / 👎.