Repository navigation
Fix per-tenant revenue #229
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
radenpranantya
wants to merge
5
commits into
Base360-AI:main
Choose a base branch
from
radenpranantya:fix/tenant-revenue
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
Show all changes
5 commits
Select commit
Hold shift + click to select a range
260f6cf
feat: add .gitignore for pycache
radenpranantya c53a301
fix: read revenue from pgsql
radenpranantya 4025a03
fix: sum revenue in each timezone
radenpranantya 69a13d2
fix: revenue cache
radenpranantya 5568129
fix: show each tenant revenue
radenpranantya 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| __pycache__/ | ||
| *.py[cod] |
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,25 +1,39 @@ | ||
| from fastapi import APIRouter, Depends, HTTPException | ||
| from typing import Dict, Any | ||
| from typing import Any, Dict, List | ||
| from app.services.cache import get_revenue_summary | ||
| from app.services.reservations import REPORT_MONTH, REPORT_YEAR, list_tenant_properties | ||
| from app.core.auth import authenticate_request as get_current_user | ||
|
|
||
| router = APIRouter() | ||
|
|
||
|
|
||
| def _tenant_id(current_user) -> str: | ||
| tenant_id = getattr(current_user, "tenant_id", None) | ||
| if not tenant_id: | ||
| raise HTTPException(status_code=401, detail="Tenant not resolved") | ||
| return tenant_id | ||
|
|
||
|
|
||
| @router.get("/dashboard/properties") | ||
| async def get_dashboard_properties( | ||
| current_user: dict = Depends(get_current_user), | ||
| ) -> List[Dict[str, Any]]: | ||
| return await list_tenant_properties(_tenant_id(current_user)) | ||
|
|
||
|
|
||
| @router.get("/dashboard/summary") | ||
| async def get_dashboard_summary( | ||
| property_id: str, | ||
| current_user: dict = Depends(get_current_user) | ||
| year: int = REPORT_YEAR, | ||
| month: int = REPORT_MONTH, | ||
| current_user: dict = Depends(get_current_user), | ||
| ) -> 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']) | ||
|
|
||
| tenant_id = _tenant_id(current_user) | ||
| revenue_data = await get_revenue_summary(property_id, tenant_id, year=year, month=month) | ||
|
|
||
| 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"], | ||
| } | ||
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,60 +1,63 @@ | ||
| import asyncio | ||
| from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker | ||
| from sqlalchemy.pool import QueuePool | ||
| from contextlib import asynccontextmanager | ||
| import logging | ||
|
|
||
| import asyncpg | ||
|
|
||
| from ..config import settings | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| def _asyncpg_database_url(url: str) -> str: | ||
| if url.startswith("postgresql+asyncpg://"): | ||
| return "postgresql://" + url[len("postgresql+asyncpg://"):] | ||
| if url.startswith("postgres+asyncpg://"): | ||
| return "postgresql://" + url[len("postgres+asyncpg://"):] | ||
| return url | ||
|
|
||
|
|
||
| class DatabasePool: | ||
| def __init__(self): | ||
| self.engine = None | ||
| self.session_factory = None | ||
| self.pool = None | ||
| self._init_lock = asyncio.Lock() | ||
|
|
||
| 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}" | ||
|
|
||
| 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 | ||
| pool_recycle=3600, # Recycle connections every hour | ||
| echo=False # Set to True for SQL debugging | ||
| ) | ||
|
|
||
| self.session_factory = async_sessionmaker( | ||
| bind=self.engine, | ||
| class_=AsyncSession, | ||
| expire_on_commit=False | ||
| ) | ||
|
|
||
| logger.info("✅ Database connection pool initialized") | ||
|
|
||
| except Exception as e: | ||
| logger.error(f"❌ Database pool initialization failed: {e}") | ||
| self.engine = None | ||
| self.session_factory = None | ||
|
|
||
| if self.pool: | ||
| return | ||
|
|
||
| async with self._init_lock: | ||
| if self.pool: | ||
| return | ||
|
|
||
| try: | ||
| self.pool = await asyncpg.create_pool( | ||
| _asyncpg_database_url(settings.database_url), | ||
| min_size=1, | ||
| max_size=20, | ||
| ) | ||
| logger.info("Database connection pool initialized") | ||
| except Exception as e: | ||
| logger.error(f"Database pool initialization failed: {e}") | ||
| self.pool = None | ||
|
|
||
| async def close(self): | ||
| """Close database connections""" | ||
| if self.engine: | ||
| await self.engine.dispose() | ||
|
|
||
| async def get_session(self) -> AsyncSession: | ||
| """Get database session from pool""" | ||
| if not self.session_factory: | ||
| if self.pool: | ||
| await self.pool.close() | ||
| self.pool = None | ||
|
|
||
| @asynccontextmanager | ||
| async def get_connection(self): | ||
| if not self.pool: | ||
| await self.initialize() | ||
| if not self.pool: | ||
| raise Exception("Database pool not initialized") | ||
| return self.session_factory() | ||
| async with self.pool.acquire() as connection: | ||
| yield connection | ||
|
|
||
| # Global database pool instance | ||
| db_pool = DatabasePool() | ||
|
|
||
| async def get_db_session() -> AsyncSession: | ||
| """Dependency to get database session""" | ||
| async with db_pool.get_session() as session: | ||
| yield session | ||
| async def get_db_session(): | ||
| async with db_pool.get_connection() as connection: | ||
| yield connection |
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
Oops, something went wrong.
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.
Bug: Lack of parameter validation on
yearandmonthcauses invalid inputs to swallowValueErrorand return HTTP 200 with zero revenue.Severity: LOW
Suggested Fix
Add parameter validation constraints (e.g.
Query(ge=1, le=12)formonthand valid range constraints foryear) on the endpoint inbackend/app/api/v1/dashboard.py.Prompt for AI Agent
Also affects:
backend/app/services/reservations.py:31~38Did we get this right? 👍 / 👎 to inform future reviews.