
This commit introduces significant updates to the cost management functionality, including: - New endpoints for retrieving cost summaries and generating expenses from lists, improving user interaction with financial data. - Implementation of a service layer for cost-related logic, encapsulating the core business rules for calculating cost summaries and managing expenses. - Introduction of a financial activity endpoint to consolidate user expenses and settlements, enhancing the user experience by providing a comprehensive view of financial activities. - Refactoring of existing code to improve maintainability and clarity, including the addition of new exception handling for financial conflicts. These changes aim to streamline cost management processes and enhance the overall functionality of the application.
31 lines
1.2 KiB
Python
31 lines
1.2 KiB
Python
import logging
|
|
from typing import List, Union
|
|
from datetime import datetime
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from app.models import Expense as ExpenseModel, Settlement as SettlementModel
|
|
from app.crud import expense as crud_expense, settlement as crud_settlement
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
async def get_user_financial_activity(
|
|
db: AsyncSession, user_id: int
|
|
) -> List[Union[ExpenseModel, SettlementModel]]:
|
|
"""
|
|
Retrieves and merges all financial activities (expenses and settlements) for a user.
|
|
The combined list is sorted by date.
|
|
"""
|
|
# Fetch all accessible expenses
|
|
expenses = await crud_expense.get_user_accessible_expenses(db, user_id=user_id, limit=200) # Using a generous limit
|
|
|
|
# Fetch all settlements involving the user
|
|
settlements = await crud_settlement.get_settlements_involving_user(db, user_id=user_id, limit=200) # Using a generous limit
|
|
|
|
# Combine and sort the activities
|
|
# We use a lambda to get the primary date for sorting from either type of object
|
|
combined_activity = sorted(
|
|
expenses + settlements,
|
|
key=lambda x: x.expense_date if isinstance(x, ExpenseModel) else x.settlement_date,
|
|
reverse=True
|
|
)
|
|
|
|
return combined_activity |