[add]: Bank to simbrella calls

This commit is contained in:
VivianDee
2025-03-25 06:39:27 +01:00
parent 0bb36be246
commit f4c2e25025
79 changed files with 1428 additions and 938 deletions
+251
View File
@@ -0,0 +1,251 @@
from flask import jsonify
from typing import List, Dict, Union, Optional, Any
class ResponseHelper:
"""
A helper class for building standardized JSON responses in Flask.
"""
@staticmethod
def build_response(
status: bool,
message: str,
data: Optional[Union[Dict, List, str]] = None,
status_code: int = 200,
error: Optional[Union[Dict, str]] = None,
) -> Dict[str, Any]:
"""
Build a standardized JSON response.
Args:
status (bool): Indicates whether the request was successful.
message (str): A message describing the result of the request.
data (Optional[Union[Dict, List, str]]): The data to return in the response.
status_code (int): The HTTP status code for the response.
error (Optional[Union[Dict, str]]): Any error details to include in the response.
Returns:
Dict[str, Any]: A dictionary representing the JSON response.
"""
response = {
"status": status,
"statusCode": status_code,
"message": message,
"data": data if data is not None else {},
"error": error if error is not None else {},
}
return jsonify(response), status_code
@staticmethod
def success(
data: Optional[Union[Dict, List, str]] = None,
message: str = "Successful",
status_code: int = 200,
error: Optional[Union[Dict, str]] = None,
) -> Dict[str, Any]:
"""
Return a success response.
Args:
data (Optional[Union[Dict, List, str]]): The data to return in the response.
message (str): A message describing the result of the request.
status_code (int): The HTTP status code for the response.
error (Optional[Union[Dict, str]]): Any error details to include in the response.
Returns:
Dict[str, Any]: A dictionary representing the JSON response.
"""
return ResponseHelper.build_response(True, message, data, status_code, error)
@staticmethod
def error(
message: str = "An error occurred",
status_code: int = 400,
data: Optional[Union[Dict, List, str]] = None,
error: Optional[Union[Dict, str]] = None,
) -> Dict[str, Any]:
"""
Return an error response.
Args:
message (str): A message describing the error.
status_code (int): The HTTP status code for the response.
data (Optional[Union[Dict, List, str]]): The data to return in the response.
error (Optional[Union[Dict, str]]): Any error details to include in the response.
Returns:
Dict[str, Any]: A dictionary representing the JSON response.
"""
return ResponseHelper.build_response(False, message, data, status_code, error)
@staticmethod
def created(
data: Optional[Union[Dict, List, str]] = None,
message: str = "Resource created successfully",
error: Optional[Union[Dict, str]] = None,
) -> Dict[str, Any]:
"""
Return a response for a created resource.
Args:
data (Optional[Union[Dict, List, str]]): The data to return in the response.
message (str): A message describing the result of the request.
error (Optional[Union[Dict, str]]): Any error details to include in the response.
Returns:
Dict[str, Any]: A dictionary representing the JSON response.
"""
return ResponseHelper.build_response(True, message, data, 201, error)
@staticmethod
def updated(
data: Optional[Union[Dict, List, str]] = None,
message: str = "Resource updated successfully",
error: Optional[Union[Dict, str]] = None,
) -> Dict[str, Any]:
"""
Return a response for an updated resource.
Args:
data (Optional[Union[Dict, List, str]]): The data to return in the response.
message (str): A message describing the result of the request.
error (Optional[Union[Dict, str]]): Any error details to include in the response.
Returns:
Dict[str, Any]: A dictionary representing the JSON response.
"""
return ResponseHelper.build_response(True, message, data, 200, error)
@staticmethod
def internal_server_error(
message: str = "Internal Server Error",
data: Optional[Union[Dict, List, str]] = None,
error: Optional[Union[Dict, str]] = None,
) -> Dict[str, Any]:
"""
Return a response for an internal server error.
Args:
message (str): A message describing the error.
data (Optional[Union[Dict, List, str]]): The data to return in the response.
error (Optional[Union[Dict, str]]): Any error details to include in the response.
Returns:
Dict[str, Any]: A dictionary representing the JSON response.
"""
return ResponseHelper.build_response(False, message, data, 500, error)
@staticmethod
def unauthorized(
message: str = "Unauthorized",
data: Optional[Union[Dict, List, str]] = None,
error: Optional[Union[Dict, str]] = None,
) -> Dict[str, Any]:
"""
Return a response for an unauthorized request.
Args:
message (str): A message describing the error.
data (Optional[Union[Dict, List, str]]): The data to return in the response.
error (Optional[Union[Dict, str]]): Any error details to include in the response.
Returns:
Dict[str, Any]: A dictionary representing the JSON response.
"""
return ResponseHelper.build_response(False, message, data, 401, error)
@staticmethod
def forbidden(
message: str = "Forbidden",
data: Optional[Union[Dict, List, str]] = None,
error: Optional[Union[Dict, str]] = None,
) -> Dict[str, Any]:
"""
Return a response for a forbidden request.
Args:
message (str): A message describing the error.
data (Optional[Union[Dict, List, str]]): The data to return in the response.
error (Optional[Union[Dict, str]]): Any error details to include in the response.
Returns:
Dict[str, Any]: A dictionary representing the JSON response.
"""
return ResponseHelper.build_response(False, message, data, 403, error)
@staticmethod
def not_found(
message: str = "Resource not found",
data: Optional[Union[Dict, List, str]] = None,
error: Optional[Union[Dict, str]] = None,
) -> Dict[str, Any]:
"""
Return a response for a not found resource.
Args:
message (str): A message describing the error.
data (Optional[Union[Dict, List, str]]): The data to return in the response.
error (Optional[Union[Dict, str]]): Any error details to include in the response.
Returns:
Dict[str, Any]: A dictionary representing the JSON response.
"""
return ResponseHelper.build_response(False, message, data, 404, error)
@staticmethod
def unprocessable_entity(
message: str = "Unprocessable entity",
data: Optional[Union[Dict, List, str]] = None,
error: Optional[Union[Dict, str]] = None,
) -> Dict[str, Any]:
"""
Return a response for an unprocessable entity.
Args:
message (str): A message describing the error.
data (Optional[Union[Dict, List, str]]): The data to return in the response.
error (Optional[Union[Dict, str]]): Any error details to include in the response.
Returns:
Dict[str, Any]: A dictionary representing the JSON response.
"""
return ResponseHelper.build_response(False, message, data, 422, error)
@staticmethod
def method_not_allowed(
message: str = "Method Not Allowed",
data: Optional[Union[Dict, List, str]] = None,
error: Optional[Union[Dict, str]] = None,
) -> Dict[str, Any]:
"""
Return a response for a method not allowed error.
Args:
message (str): A message describing the error.
data (Optional[Union[Dict, List, str]]): The data to return in the response.
error (Optional[Union[Dict, str]]): Any error details to include in the response.
Returns:
Dict[str, Any]: A dictionary representing the JSON response.
"""
return ResponseHelper.build_response(False, message, data, 405, error)
@staticmethod
def bad_request(
message: str = "Bad Request",
data: Optional[Union[Dict, List, str]] = None,
error: Optional[Union[Dict, str]] = None,
) -> Dict[str, Any]:
"""
Return a response for a bad request error.
Args:
message (str): A message describing the error.
data (Optional[Union[Dict, List, str]]): The data to return in the response.
error (Optional[Union[Dict, str]]): Any error details to include in the response.
Returns:
Dict[str, Any]: A dictionary representing the JSON response.
"""
return ResponseHelper.build_response(False, message, data, 400, error)
+4
View File
@@ -0,0 +1,4 @@
from .verify_api_key import require_api_key
from .app_id_checker import require_app_id
from .cors import enforce_json
from .basic_auth import require_auth
+27
View File
@@ -0,0 +1,27 @@
from functools import wraps
from flask import request, jsonify
from app.utils.logger import logger
from app.config import Config
VALID_APP_ID = Config.VALID_APP_ID
def require_app_id(f):
"""Decorator to enforce App-ID validation."""
@wraps(f)
def decorated_function(*args, **kwargs):
app_id = request.headers.get("App-ID")
if not app_id:
logger.error("Unauthorized access: Missing App-ID.")
return jsonify({"message": "Invalid request parameters"}), 400
if app_id != VALID_APP_ID:
logger.error(f"Unauthorized access: Invalid App-ID {app_id}.")
return jsonify({"message": "Invalid request parameters"}), 400
return f(*args, **kwargs)
return decorated_function
+30
View File
@@ -0,0 +1,30 @@
from functools import wraps
from flask import request, jsonify
import base64
from app.config import Config
USERNAME = Config.BASIC_AUTH_USERNAME
PASSWORD = Config.BASIC_AUTH_PASSWORD
def require_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.headers.get('Authorization')
if not auth or not check_auth(auth):
return jsonify({"message": "Invalid request parameters"}), 401
return f(*args, **kwargs)
return decorated
def check_auth(auth_header):
if not auth_header:
return False
try:
auth_type, credentials = auth_header.split()
if auth_type.lower() != "basic":
return False
decoded_credentials = base64.b64decode(credentials).decode("utf-8")
user, pwd = decoded_credentials.split(":", 1)
return user == USERNAME and pwd == PASSWORD
except Exception:
return False
+7
View File
@@ -0,0 +1,7 @@
from flask import request, jsonify
def enforce_json():
"""Middleware to enforce JSON Content-Type for incoming requests"""
if request.method in ["POST", "PUT", "PATCH"] and request.content_type != "application/json":
return jsonify({"message": "Invalid request parameters"}), 400
+25
View File
@@ -0,0 +1,25 @@
from functools import wraps
from flask import request, jsonify
from app.utils.logger import logger
from app.config import Config
# Load valid API key from environment variables (fallback for testing)
VALID_API_KEY = Config.VALID_API_KEY
def require_api_key(f):
"""Decorator to enforce API key authentication."""
@wraps(f)
def decorated_function(*args, **kwargs):
api_key = request.headers.get("X-API-KEY")
if not api_key:
logger.error("Unauthorized access: Missing API key.")
return jsonify({"message": "Invalid request parameters"}), 400
if api_key != VALID_API_KEY:
logger.error("Unauthorized access: Invalid API key.")
return jsonify({"message": "Invalid request parameters"}), 400
return f(*args, **kwargs)
return decorated_function
+1
View File
@@ -0,0 +1 @@
from .routes import api
+111
View File
@@ -0,0 +1,111 @@
from flask import Blueprint, request, jsonify, send_from_directory
from app.api.services import (
EligibilityCheckService,
SelectOfferService,
ProvideLoanService,
LoanInformationService,
RepaymentService,
CustomerConsentService,
NotificationCallbackService
)
from app.utils.logger import logger
from app.api.middlewares import enforce_json, require_auth
import os
api = Blueprint("api", __name__)
@api.before_request
def cors_middleware():
"""Middleware applied globally to all API routes in this blueprint"""
return enforce_json()
# Swagger JSON file
@api.route("/swagger.json", methods=['GET'])
def swagger_json():
swagger_dir = os.path.join("swagger")
return send_from_directory(swagger_dir, "digifi_swagger.json")
@api.route('/swagger/<path:filename>')
def serve_paths(filename):
swagger_dir = os.path.join("swagger")
return send_from_directory(swagger_dir, filename)
# EligibilityCheck Endpoint
@api.route('/EligibilityCheck', methods=['POST'])
@require_auth
def eligibility_check():
data = request.get_json()
# logger.info(f"EligibilityCheck request received: {data}")
response = EligibilityCheckService.process_request(data)
return response
# SelectOffer Endpoint
@api.route('/SelectOffer', methods=['POST'])
@require_auth
def select_offer():
data = request.get_json()
# logger.info(f"SelectOffer request received: {data}")
response = SelectOfferService.process_request(data)
return response
# ProvideLoan Endpoint
@api.route('/ProvideLoan', methods=['POST'])
@require_auth
def provide_loan():
data = request.get_json()
# logger.info(f"ProvideLoan request received: {data}")
response = ProvideLoanService.process_request(data)
return response
# LoanInformation Endpoint
@api.route('/LoanInformation', methods=['GET'])
@require_auth
def loan_information():
data = request.args.to_dict()
# logger.info(f"LoanInformation request received: {data}")
response = LoanInformationService.process_request(data)
return response
# Repayment Endpoint
@api.route('/Repayment', methods=['POST'])
@require_auth
def repayment():
data = request.get_json()
# logger.info(f"Repayment request received: {data}")
response = RepaymentService.process_request(data)
return response
# CustomerConsent Endpoint
@api.route('/CustomerConsent', methods=['POST'])
@require_auth
def customer_consent():
data = request.get_json()
# logger.info(f"CustomerConsent request received: {data}")
response = CustomerConsentService.process_request(data)
return response
# NotificationCallback Endpoint
@api.route('/NotificationCallback', methods=['POST'])
@require_auth
def notification_callback():
data = request.get_json()
# logger.info(f"NotificationCallback request received: {data}")
response = NotificationCallbackService.process_request(data)
return response
# Health Check Endpoint
@api.route('/health', methods=['GET'])
def health_check():
return {"status": "ok"} , 200
View File
+11
View File
@@ -0,0 +1,11 @@
from marshmallow import Schema, fields
# Customer Consent Schema
class CustomerConsentSchema(Schema):
type = fields.Str(required=True)
transactionId = fields.Str(required=True)
customerId = fields.Str(required=True)
accountId = fields.Str(required=True)
requestTime = fields.DateTime(required=True, format="%Y-%m-%d %H:%M:%S.%f")
consentType = fields.Str(required=True)
channel = fields.Str(required=True)
+10
View File
@@ -0,0 +1,10 @@
from marshmallow import Schema, fields
class EligibilityCheckSchema(Schema):
transactionId = fields.Str(required=True)
countryCode = fields.Str(required=True)
customerId = fields.Str(required=True)
accountId = fields.Str(required=True)
msisdn = fields.Str(required=True)
lienAmount = fields.Float(required=True)
channel = fields.Str(required=True)
+5
View File
@@ -0,0 +1,5 @@
from marshmallow import Schema, fields
# Loan Information Schema
class LoanInformationSchema(Schema):
loan_id = fields.Str(required=True)
+14
View File
@@ -0,0 +1,14 @@
from marshmallow import Schema, fields
# Notification Callback Schema
class NotificationCallbackSchema(Schema):
fbnTransactionId = fields.Str(required=True)
transactionId = fields.Str(required=True)
customerId = fields.Str(required=True)
accountId = fields.Str(required=True)
debtId = fields.Str(required=True)
transactionType = fields.Str(required=True)
amountProvided = fields.Float(required=True)
amountCollected = fields.Float(required=True)
responseCode = fields.Str(required=True)
responseDescription = fields.Str(required=True)
+16
View File
@@ -0,0 +1,16 @@
from marshmallow import Schema, fields
# Provide Loan Schema
class ProvideLoanSchema(Schema):
type = fields.Str(required=True)
requestId = fields.Str(required=True)
transactionId = fields.Str(required=True)
customerId = fields.Str(required=True)
accountId = fields.Str(required=True)
msisdn = fields.Str(required=False)
productId = fields.Str(required=True)
lienAmount = fields.Float(required=True)
requestedAmount = fields.Float(required=True)
collectionType = fields.Int(required=True)
loanType = fields.Int(required=True)
channel = fields.Str(required=True)
+11
View File
@@ -0,0 +1,11 @@
from marshmallow import Schema, fields
# Repayment Schema
class RepaymentSchema(Schema):
type = fields.Str(required=True)
msisdn = fields.Str(required=False) #optional
debtId = fields.Str(required=True)
productId = fields.Str(required=True)
transactionId = fields.Str(required=True)
customerId = fields.Str(required=True)
channel = fields.Str(required=True)
+13
View File
@@ -0,0 +1,13 @@
from marshmallow import Schema, fields
# Select Offer Schema
class SelectOfferSchema(Schema):
requestId = fields.Str(required=True)
transactionId = fields.Str(required=True)
customerId = fields.Str(required=True)
accountId = fields.Str(required=True)
msisdn = fields.Str(required=True)
requestedAmount = fields.Float(required=True)
productId = fields.Str(required=True)
channel = fields.Str(required=True)
+7
View File
@@ -0,0 +1,7 @@
from app.api.services.eligibility_check import EligibilityCheckService
from app.api.services.select_offer import SelectOfferService
from app.api.services.provide_loan import ProvideLoanService
from app.api.services.loan_information import LoanInformationService
from app.api.services.repayment import RepaymentService
from app.api.services.customer_consent import CustomerConsentService
from app.api.services.notification_callback import NotificationCallbackService
+50
View File
@@ -0,0 +1,50 @@
from flask import request, jsonify
from marshmallow import ValidationError
from app.utils.logger import logger
from app.api.schemas.customer_consent import CustomerConsentSchema
class CustomerConsentService:
@staticmethod
def process_request(data):
"""
Process the CustomerConsent request.
Args:
data (dict): The request data.
Returns:
dict: A standardized response.
"""
try:
logger.info("Processing CustomerConsent request")
# Validate input data using the CustomerConsent schema
schema = CustomerConsentSchema()
validated_data = schema.load(data) # Raises ValidationError if invalid
# Simulated processing logic
response_data = {
"resultCode": "00",
"resultDescription": "Request is received"
}
# return ResponseHelper.success(
# data=response_data,
# message="Customer consent processed successfully"
# )
return response_data
except ValidationError as err:
logger.error(f"Validation Error: {err.messages}")
return jsonify({
"message": "Validation exception"
}) , 422
except Exception as e:
logger.error(f"An error occurred: {str(e)}", exc_info=True)
return jsonify({
"message": "Internal Server Error"
}) , 500
+68
View File
@@ -0,0 +1,68 @@
from flask import session, jsonify
from app.utils.logger import logger
from app.api.schemas.eligibility_check import EligibilityCheckSchema
from marshmallow import ValidationError
class EligibilityCheckService:
@staticmethod
def process_request(data):
"""
Process the EligibilityCheck request.
Args:
data (dict): The request data.
Returns:
dict: A standardized response.
"""
try:
logger.info("Processing EligibilityCheck request")
# Validate input data using Schema
schema = EligibilityCheckSchema()
validated_data = schema.load(data) # Raises an error if invalid
# Simulate processing
response_data = {
"customerId": "CN621868",
"transactionId": "Tr201712RK9232P115",
"msisdn": "3451342",
"eligibleOffers": [
{
"minamount": 5000,
"maxamount": 20000,
"productId": 101,
"offerid": 101,
"Tenor": 30
},
{
"minamount": 20000,
"maxamount": 50000,
"productId": 102,
"offerid": 102,
"Tenor": 60
}
],
"resultCode": "00",
"resultDescription": "Successful"
}
# Return a success response
# return ResponseHelper.success(
# data=response_data,
# message="Eligibility check completed successfully"
# )
return response_data
except ValidationError as err:
logger.error(f"Validation Error: {err.messages}")
return jsonify({
"message": "Validation exception"
}) , 422
except Exception as e:
logger.error(f"An error occurred: {str(e)}", exc_info=True)
return jsonify({
"message": "Internal Server Error"
}) , 500
+62
View File
@@ -0,0 +1,62 @@
from flask import request, jsonify
from marshmallow import ValidationError
from app.utils.logger import logger
from app.api.schemas.loan_information import LoanInformationSchema
class LoanInformationService:
@staticmethod
def process_request(data):
"""
Process the Loan Information request.
Args:
data (dict): The request data.
Returns:
dict: A standardized response.
"""
try:
logger.info("Processing LoanInformation request")
# Validate input data using the imported schema
schema = LoanInformationSchema()
validated_data = schema.load(data) # Raises ValidationError if invalid
# Simulated processing logic
response_data = {
"customerId": "CN621868",
"loans": [
{
"debtId": "123456789",
"loanDate": "2019-10-18 14:26:21.063",
"dueDate": "2019-11-20 14:26:21.063",
"currentLoanAmount": 8500.0,
"initialLoanAmount": 10000.0,
"defaultFee": 0.0,
"continuousFee": 0.0,
"productId": "101"
}
],
"resultCode": "00",
"resultDescription": "Successful"
}
# return ResponseHelper.success(
# data=response_data,
# message="Loan information retrieved successfully"
# )
return response_data
except ValidationError as err:
logger.error(f"Validation Error: {err.messages}")
return jsonify({
"message": "Validation exception"
}) , 422
except Exception as e:
logger.error(f"An error occurred: {str(e)}", exc_info=True)
return jsonify({
"message": "Internal Server Error"
}) , 500
+49
View File
@@ -0,0 +1,49 @@
from flask import request, jsonify
from marshmallow import ValidationError
from app.utils.logger import logger
from app.api.schemas.notification_callback import NotificationCallbackSchema
class NotificationCallbackService:
@staticmethod
def process_request(data):
"""
Process the NotificationCallback request.
Args:
data (dict): The request data.
Returns:
dict: A standardized response.
"""
try:
logger.info("Processing NotificationCallback request")
# Validate input data using the NotificationCallback schema
schema = NotificationCallbackSchema()
validated_data = schema.load(data) # Raises ValidationError if invalid
# Simulated processing logic
response_data = {
"resultCode": "00",
"resultDescription": "Successful"
}
# return ResponseHelper.success(
# data=response_data,
# message="Notification callback processed successfully"
# )
return response_data
except ValidationError as err:
logger.error(f"Validation Error: {err.messages}")
return jsonify({
"message": "Validation exception"
}) , 422
except Exception as e:
logger.error(f"An error occurred: {str(e)}", exc_info=True)
return jsonify({
"message": "Internal Server Error"
}) , 500
+54
View File
@@ -0,0 +1,54 @@
from flask import request, jsonify
from marshmallow import ValidationError
from app.utils.logger import logger
from app.api.schemas.provide_loan import ProvideLoanSchema
class ProvideLoanService:
@staticmethod
def process_request(data):
"""
Process the ProvideLoan request.
Args:
data (dict): The request data.
Returns:
dict: A standardized response.
"""
try:
logger.info("Processing ProvideLoan request")
# Validate input data using the imported schema
schema = ProvideLoanSchema()
validated_data = schema.load(data) # Raises ValidationError if invalid
# Business logic - providing a loan
response_data ={
"requestId": "202111170001371256908",
"transactionId": "Tr201712RK9232P115",
"customerId": "CN621868",
"accountId": "ACN8263457",
"msisdn": "3451342",
"resultCode": "00",
"resultDescription": "Successful"
}
# return ResponseHelper.success(
# data=response_data,
# message="Loan successfully provided"
# )
return response_data
except ValidationError as err:
logger.error(f"Validation Error: {err.messages}")
return jsonify({
"message": "Validation exception"
}) , 422
except Exception as e:
logger.error(f"An error occurred: {str(e)}", exc_info=True)
return jsonify({
"message": "Internal Server Error"
}) , 500
+49
View File
@@ -0,0 +1,49 @@
from flask import request, jsonify
from marshmallow import ValidationError
from app.utils.logger import logger
from app.api.schemas.repayment import RepaymentSchema
class RepaymentService:
@staticmethod
def process_request(data):
"""
Process the Repayment request.
Args:
data (dict): The request data.
Returns:
dict: A standardized response.
"""
try:
logger.info("Processing Repayment request")
# Validate input data using the Repayment schema
schema = RepaymentSchema()
validated_data = schema.load(data) # Raises ValidationError if invalid
# Simulated processing logic
response_data = {
"repayment_id": "67890",
"status": "Paid",
"amount": validated_data.get("amount", 0), # Example: Use validated field
}
# return ResponseHelper.success(
# data=response_data,
# message="Repayment processed successfully"
# )
return response_data
except ValidationError as err:
logger.error(f"Validation Error: {err.messages}")
return jsonify({
"message": "Validation exception"
}) , 422
except Exception as e:
logger.error(f"An error occurred: {str(e)}", exc_info=True)
return jsonify({
"message": "Internal Server Error"
}) , 500
+106
View File
@@ -0,0 +1,106 @@
from flask import request, jsonify
from marshmallow import ValidationError
from app.utils.logger import logger
from app.api.schemas.select_offer import SelectOfferSchema
class SelectOfferService:
@staticmethod
def process_request(data):
"""
Process the SelectOffer request.
Args:
data (dict): The request data.
Returns:
dict: A standardized response.
"""
try:
logger.info("Processing SelectOffer request")
# Validate input data using the imported schema
schema = SelectOfferSchema()
validated_data = schema.load(data) # Raises ValidationError if invalid
offers = [
{
"offerId": "14451",
"productId": "2030",
"amount": 10000.0,
"upfrontPayment": 1000.0,
"interestRate": 3.0,
"managementRate": 1.0,
"managementFee": 1.0,
"insuranceRate": 1.0,
"insuranceFee": 100.0,
"VATRate": 7.5,
"VATAmount": 100.0,
"recommendedRepaymentDates": ["2022-11-30"],
"installmentAmount": 11000.0,
"totalRepaymentAmount": 11000.0
},
{
"offerId": "16645",
"productId": "2060",
"amount": 10000.0,
"upfrontPayment": 0.0,
"interestRate": 3.0,
"managementRate": 1.0,
"managementFee": 1.0,
"insuranceRate": 1.0,
"insuranceFee": 100.0,
"VATRate": 7.5,
"VATAmount": 100.0,
"recommendedRepaymentDates": ["2022-11-30", "2023-12-30"],
"installmentAmount": 5761.9,
"totalRepaymentAmount": 11523.8
},
{
"offerId": "122212",
"productId": "2090",
"amount": 10000.0,
"upfrontPayment": 0.0,
"interestRate": 10.0,
"managementRate": 1.0,
"managementFee": 1.0,
"insuranceRate": 1.0,
"insuranceFee": 100.0,
"VATRate": 7.5,
"VATAmount": 100.0,
"recommendedRepaymentDates": ["2022-11-30", "2022-12-30", "2023-01-29"],
"installmentAmount": 4021.15,
"totalRepaymentAmount": 12063.45
}
]
# Business logic - selecting an offer
response_data = {
"outstandingDebtAmount": 0,
"requestId": "202111170001371256908",
"transactionId": "1231231321232",
"customerId": "1256907",
"accountId": "5948306019",
"loan": offers,
"resultCode": "00",
"resultDescription": "Successful"
}
# return ResponseHelper.success(
# data=response_data,
# message="Offer selection completed successfully"
# )
return response_data
except ValidationError as err:
logger.error(f"Validation Error: {err.messages}")
return jsonify({
"message": "Validation exception"
}) , 422
except Exception as e:
logger.error(f"An error occurred: {str(e)}", exc_info=True)
return jsonify({
"message": "Internal Server Error"
}) , 500