import logging from datetime import datetime from app.models.repayment_data import RepaymentsData from dateutil.parser import parse as parse_date logger = logging.getLogger(__name__) class RepaymentDataService: """ Service class for handling repayment-data operations. """ @staticmethod def get_all_repayments_data(filters=None): try: if filters is None: filters = {} customer_id = filters.get('customer_id') account_id = filters.get('account_id') added_date = filters.get('added_date') transaction_id = filters.get('transaction_id') fbn_transaction_id = filters.get('fbn_transaction_id') page = int(filters.get('page', 1)) limit = int(filters.get('limit', 20)) if page < 1: page = 1 if limit < 1 or limit > 100: limit = 20 if added_date and isinstance(added_date, str): try: added_date = parse_date(added_date) except Exception as parse_err: logger.error(f"Invalid date format for 'added_date': {added_date}") return {"message": "Invalid date format for 'added_date'"}, 400 repayments_data, total_count = RepaymentsData.get_all_repayment_data( customer_id=customer_id, account_id=account_id, added_date=added_date, transaction_id=transaction_id, fbn_transaction_id=fbn_transaction_id, page=page, limit=limit ) repayments_list = [] for repayment in repayments_data: repayments_list.append({ 'customer_id': repayment.customer_id, 'account_id': repayment.account_id, 'transaction_id': repayment.transaction_id, 'fbn_transaction_id': repayment.fbn_transaction_id, 'added_date': repayment.added_date.isoformat() if repayment.added_date else None, 'response_code': repayment.response_code, 'response_descr': repayment.response_descr, 'repayment_amount': repayment.repayment_amount, 'amount_collected': repayment.amount_collected, 'balance': repayment.balance }) total_pages = (total_count + limit - 1) // limit return { 'repayment_data': repayments_list, 'count': len(repayments_list), 'pagination': { 'total_count': total_count, 'total_pages': total_pages, 'current_page': page, 'limit': limit, 'has_next': page < total_pages, 'has_prev': page > 1 } } except Exception as e: logger.error(f"An error occurred: {str(e)}", exc_info=True) return {"message": "Internal Server Error"}, 500