from flask import jsonify from app.utils.logger import logger from app.api.services.base_service import BaseService from app.models.transaction import Transaction from app.models.loan import Loan from sqlalchemy import func, desc from datetime import datetime, timedelta from app.extensions import db class DashboardService(BaseService): @staticmethod def get_dashboard_data(): """ Get dashboard summary data. Returns: dict: A standardized response with dashboard data. """ try: # Get current date and start of the week now = datetime.now() start_of_week = now - timedelta(days=now.weekday()) start_of_week = start_of_week.replace(hour=0, minute=0, second=0, microsecond=0) # Get loans data for the current week loans_this_week = db.session.query( func.sum(Loan.initial_loan_amount) ).filter( Loan.created_at >= start_of_week ).scalar() or 0 # Get payments data for the current week # Assuming payments are transactions with type 'PAYMENT' payments_this_week = db.session.query( func.count(Transaction.id) ).filter( Transaction.created_at >= start_of_week, Transaction.type == 'PAYMENT' ).scalar() or 0 # Get request summary counts # These are placeholders - needed to adjust based on your actual data model eligibility_check_count = db.session.query( func.count(Transaction.id) ).filter( Transaction.type == 'ELIGIBILITY_CHECK' ).scalar() or 0 select_offer_count = db.session.query( func.count(Transaction.id) ).filter( Transaction.type == 'SELECT_OFFER' ).scalar() or 0 provide_loan_count = db.session.query( func.count(Transaction.id) ).filter( Transaction.type == 'PROVIDE_LOAN' ).scalar() or 0 repayment_count = db.session.query( func.count(Transaction.id) ).filter( Transaction.type == 'REPAYMENT' ).scalar() or 0 # Get recent transactions recent_transactions = Transaction.query.order_by( Transaction.id.desc() ).limit(15).all() # Format recent transactions recent_transactions_data = [] for transaction in recent_transactions: recent_transactions_data.append({ 'id': transaction.id, 'transaction_id': transaction.transaction_id, 'account_id': transaction.account_id, 'type': transaction.type, 'channel': transaction.channel, 'created_at': transaction.created_at.isoformat() if transaction.created_at else None, 'updated_at': transaction.updated_at.isoformat() if transaction.updated_at else None }) # Prepare response data dashboard_data = { "loans": { "value": float(loans_this_week), "currency": "Naira", "currency_text": "₦", "text": "this week" }, "payments": { "value": payments_this_week, "currency": "Naira", "currency_text": "₦", "text": "this week" }, "request_summary": { "eligibility_check": {"Eligibility": eligibility_check_count}, "select_offer": {"Offers": select_offer_count}, "provide_loan": {"Loans": provide_loan_count}, "repayment": {"Repayments": repayment_count} }, "recent_transactions": recent_transactions_data } return dashboard_data except Exception as e: logger.error(f"An error occurred while getting dashboard data: {str(e)}", exc_info=True) return jsonify({ "message": "Internal Server Error" }), 500