91 lines
2.9 KiB
Python
91 lines
2.9 KiB
Python
from flask import jsonify
|
|
from app.utils.logger import logger
|
|
from app.api.services.base_service import BaseService
|
|
from app.models.loan import Loan
|
|
from datetime import datetime
|
|
|
|
|
|
class LoanService(BaseService):
|
|
@staticmethod
|
|
def process_request(filters=None):
|
|
"""
|
|
Process the get loans request.
|
|
|
|
Args:
|
|
filters (dict, optional): Filters for the loans query.
|
|
|
|
Returns:
|
|
dict: A standardized response with loans data.
|
|
"""
|
|
try:
|
|
if filters is None:
|
|
filters = {}
|
|
|
|
# Extract filters
|
|
customer_id = filters.get('customer_id')
|
|
account_id = filters.get('account_id')
|
|
offer_id = filters.get('offer_id')
|
|
status = filters.get('status')
|
|
start_date = filters.get('start_date')
|
|
end_date = filters.get('end_date')
|
|
|
|
# Convert string dates to datetime objects if provided
|
|
if start_date and isinstance(start_date, str):
|
|
start_date = datetime.fromisoformat(start_date.replace('Z', '+00:00'))
|
|
if end_date and isinstance(end_date, str):
|
|
end_date = datetime.fromisoformat(end_date.replace('Z', '+00:00'))
|
|
|
|
# Get loans with filters
|
|
query = Loan.query
|
|
|
|
if customer_id:
|
|
query = query.filter(Loan.customer_id == customer_id)
|
|
|
|
if account_id:
|
|
query = query.filter(Loan.account_id == account_id)
|
|
|
|
if offer_id:
|
|
query = query.filter(Loan.offer_id == offer_id)
|
|
|
|
if status:
|
|
query = query.filter(Loan.status == status)
|
|
|
|
if start_date:
|
|
query = query.filter(Loan.created_at >= start_date)
|
|
|
|
if end_date:
|
|
query = query.filter(Loan.created_at <= end_date)
|
|
|
|
# Order by created_at descending (newest first)
|
|
query = query.order_by(Loan.created_at.desc())
|
|
|
|
loans = query.all()
|
|
|
|
# Convert loans to dictionary format
|
|
loans_data = []
|
|
for loan in loans:
|
|
loans_data.append({
|
|
'id': loan.id,
|
|
'customer_id': loan.customer_id,
|
|
'account_id': loan.account_id,
|
|
'offer_id': loan.offer_id,
|
|
'principal_amount': loan.principal_amount,
|
|
'status': loan.status,
|
|
'created_at': loan.created_at.isoformat(),
|
|
'updated_at': loan.updated_at.isoformat()
|
|
})
|
|
|
|
response_data = {
|
|
'loans': loans_data,
|
|
'count': len(loans_data)
|
|
}
|
|
|
|
return response_data
|
|
|
|
except Exception as e:
|
|
logger.error(f"Error retrieving loans: {str(e)}", exc_info=True)
|
|
return jsonify({
|
|
'status': 'error',
|
|
'message': f'Failed to retrieve loans: {str(e)}'
|
|
}), 500
|