Files
2025-03-22 17:11:46 +01:00

147 lines
4.8 KiB
Python

"""
Controller for loan-related endpoints.
"""
from flask import Blueprint, request, jsonify
from app.middleware import basic_auth_required
from app.models import (
ProvideLoanRequest, ProvideLoanResponse,
LoanInformationRequest, LoanInformationResponse, Loan
)
from datetime import datetime, timedelta
import logging
# Configure logger
logger = logging.getLogger(__name__)
# Create blueprint
loan_bp = Blueprint('loan', __name__)
@loan_bp.route('/ProvideLoan', methods=['POST'])
@basic_auth_required
def provide_loan():
"""
Endpoint to process loan provision requests.
This method handles the request to provide a loan to a customer.
Returns:
JSON response with loan provision status
"""
try:
# Parse and validate request
data = request.get_json()
if not data:
return jsonify({
'resultCode': '400',
'resultDescription': 'Invalid JSON payload'
}), 400
# Validate required fields
required_fields = ['$type', 'requestId', 'transactionId', 'customerId',
'accountId', 'productId', 'lienAmount', 'requestedAmount',
'collectionType', 'loanType', 'channel']
for field in required_fields:
if field not in data:
return jsonify({
'resultCode': '422',
'resultDescription': f'Missing required field: {field}'
}), 422
# Create request model
req = ProvideLoanRequest.from_dict(data)
# Process loan provision (this would connect to the business logic)
# For demonstration, we'll return a mock response
# Create response
response = ProvideLoanResponse(
requestId=req.requestId,
transactionId=req.transactionId,
customerId=req.customerId,
accountId=req.accountId,
resultCode="00",
resultDescription="Loan provided successfully",
msisdn=req.msisdn if hasattr(req, 'msisdn') else None
)
logger.info(f"Processed loan provision for customer {req.customerId}")
return jsonify(response.to_dict())
except Exception as e:
logger.error(f"Error processing loan provision: {str(e)}")
return jsonify({
'resultCode': '500',
'resultDescription': 'Internal server error'
}), 500
@loan_bp.route('/LoanInformation', methods=['POST'])
@basic_auth_required
def loan_information():
"""
Endpoint to retrieve loan information.
This method provides information about a customer's existing loans.
Returns:
JSON response with loan information
"""
try:
# Parse and validate request
data = request.get_json()
if not data:
return jsonify({
'resultCode': '400',
'resultDescription': 'Invalid JSON payload'
}), 400
# Validate required fields
required_fields = ['$type', 'transactionId', 'customerId', 'channel']
for field in required_fields:
if field not in data:
return jsonify({
'resultCode': '422',
'resultDescription': f'Missing required field: {field}'
}), 422
# Create request model
req = LoanInformationRequest.from_dict(data)
# Process loan information request (this would connect to the business logic)
# For demonstration, we'll return a mock response
# Create sample loans
now = datetime.now()
loan_date = now - timedelta(days=15)
due_date = now + timedelta(days=15)
loans = [
Loan(
debtId="123456789",
loanDate=loan_date.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3],
dueDate=due_date.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3],
currentLoanAmount=8500.0,
initialLoanAmount=10000.0,
defaultFee=0.0,
continiousFee=0.0,
productId="101"
)
]
# Create response
response = LoanInformationResponse(
customerId=req.customerId,
loans=[loan.to_dict() for loan in loans],
resultCode="00",
resultDescription="Successful",
totalDebtAmount=8500.0
)
logger.info(f"Processed loan information request for customer {req.customerId}")
return jsonify(response.to_dict())
except Exception as e:
logger.error(f"Error processing loan information request: {str(e)}")
return jsonify({
'resultCode': '500',
'resultDescription': 'Internal server error'
}), 500