forked from DigiFi/digifi-BankToProductCore
Merge branch 'update_loan_status_response' of DigiFi/digifi-BankToProductCore into master
This commit is contained in:
@@ -8,6 +8,7 @@ import logging
|
||||
class SimbrellaIntegration:
|
||||
BASE_URL = settings.SIMBRELLA_BASE_URL
|
||||
ENDPOINT_RAC_CHECKS = settings.SIMBRELLA_ENDPOINT_RAC_CHECKS
|
||||
HEALTH_ENDPOINT = settings.SIMBRELLA_HEALTH
|
||||
|
||||
@staticmethod
|
||||
def rac_check(customer_id, account_id, transaction_id):
|
||||
@@ -42,4 +43,21 @@ class SimbrellaIntegration:
|
||||
except Exception as e:
|
||||
logger.error(f"RACCheck API call failed: {str(e)}", exc_info=True)
|
||||
raise Exception(f"RACCheck API call failed: {str(e)}")
|
||||
|
||||
@staticmethod
|
||||
def health_check():
|
||||
"""
|
||||
Health check for Simbrella Service
|
||||
"""
|
||||
|
||||
url = f"{SimbrellaIntegration.BASE_URL}/{SimbrellaIntegration.HEALTH_ENDPOINT}"
|
||||
logger.info(f"Simbrella Health Check URL: {url}")
|
||||
|
||||
try:
|
||||
response = httpx.get(url, timeout=10.0)
|
||||
logger.info(f"Simbrella Health Check Response: {response.text}")
|
||||
return response
|
||||
except Exception as e:
|
||||
logger.error(f"Simbrella Health Check API call failed: {str(e)}", exc_info=True)
|
||||
raise
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
from re import S
|
||||
from sqlite3 import DatabaseError
|
||||
from app.api.integrations.events_service import EventServiceIntegration
|
||||
from app.api.integrations.simbrella import SimbrellaIntegration
|
||||
from flask import Blueprint, request, jsonify, send_from_directory
|
||||
from app.api.services import (
|
||||
EligibilityCheckService,
|
||||
@@ -125,6 +127,7 @@ def health_check():
|
||||
response = {}
|
||||
db_status = "Connection Successful"
|
||||
events_service_status = "Connection Successful"
|
||||
emulator_status = "Connection Successful"
|
||||
errors = []
|
||||
status = "ok"
|
||||
|
||||
@@ -162,11 +165,26 @@ def health_check():
|
||||
status = "failed"
|
||||
errors.append(f"Events Service connection failed: {str(e)}")
|
||||
|
||||
# Check Emulator health
|
||||
try:
|
||||
emulator_response = SimbrellaIntegration.health_check()
|
||||
|
||||
if emulator_response.status_code != 200:
|
||||
emulator_status = "Connection Failed"
|
||||
status = "failed"
|
||||
errors.append(f"Emulator response: {emulator_response.text}")
|
||||
|
||||
except Exception as e:
|
||||
emulator_status = "Connection Failed"
|
||||
status = "failed"
|
||||
errors.append(f"Emulator connection failed: {str(e)}")
|
||||
|
||||
|
||||
response = {
|
||||
"status": status,
|
||||
"db_status": db_status,
|
||||
"events_service_status": events_service_status,
|
||||
"emulator_status": emulator_status,
|
||||
"db_uri": db_uri,
|
||||
"errors": errors or None
|
||||
}
|
||||
|
||||
@@ -3,15 +3,15 @@ from marshmallow import ValidationError
|
||||
from app.api.enums.loan_status import LoanStatus
|
||||
from app.models import Customer
|
||||
from app.utils.logger import logger
|
||||
from app.api.schemas.loan_status import LoanStatusSchema
|
||||
from app.api.schemas.loan_status import LoanStatusSchema
|
||||
from app.api.services.base_service import BaseService
|
||||
from app.api.enums import TransactionType
|
||||
from app.api.enums import TransactionType
|
||||
from app.extensions import db
|
||||
from app.api.helpers.response_helper import ResponseHelper
|
||||
|
||||
|
||||
class LoanStatusService(BaseService):
|
||||
TRANSACTION_TYPE = TransactionType.LOAN_STATUS
|
||||
TRANSACTION_TYPE = TransactionType.LOAN_STATUS
|
||||
|
||||
@staticmethod
|
||||
def process_request(data):
|
||||
@@ -27,31 +27,57 @@ class LoanStatusService(BaseService):
|
||||
try:
|
||||
with db.session.begin():
|
||||
# Validate data
|
||||
validated_data = LoanStatusService.validate_data(data, LoanStatusSchema())
|
||||
validated_data = LoanStatusService.validate_data(
|
||||
data, LoanStatusSchema()
|
||||
)
|
||||
|
||||
customer_id = validated_data.get('customerId')
|
||||
customer_id = validated_data.get("customerId")
|
||||
|
||||
logger.info(f"Looking for customer *** {customer_id}")
|
||||
customer = Customer.get_customer_with_loan_list(customer_id)
|
||||
|
||||
transactionId = validated_data.get('transactionId')
|
||||
account_id = validated_data.get('accountId')
|
||||
|
||||
if(LoanStatusService.validate_account_ownership(account_id = account_id, customer_id = customer_id)):
|
||||
transactionId = validated_data.get("transactionId")
|
||||
account_id = validated_data.get("accountId")
|
||||
|
||||
if LoanStatusService.validate_account_ownership(
|
||||
account_id=account_id, customer_id=customer_id
|
||||
):
|
||||
# Get loans
|
||||
loans = [loan.to_dict() for loan in customer.loans if loan.status == LoanStatus.ACTIVE]
|
||||
transaction = LoanStatusService.log_transaction(validated_data = validated_data)
|
||||
customer_loans = customer.loans
|
||||
loans = [
|
||||
loan.to_dict()
|
||||
for loan in customer_loans
|
||||
if loan.status in [LoanStatus.ACTIVE, LoanStatus.START_REPAY, LoanStatus.ACTIVE_PARTIAL]
|
||||
]
|
||||
|
||||
transaction = LoanStatusService.log_transaction(
|
||||
validated_data=validated_data
|
||||
)
|
||||
if not transaction:
|
||||
logger.error(f"Failed to log transaction")
|
||||
return ResponseHelper.error(result_description="Failed to log transaction.")
|
||||
else:
|
||||
return ResponseHelper.error(result_description="Invalid Customer or Account")
|
||||
|
||||
total_debt_amount = sum(
|
||||
loan.get("currentLoanAmount") or 0
|
||||
for loan in loans
|
||||
return ResponseHelper.error(
|
||||
result_description="Failed to log transaction."
|
||||
)
|
||||
else:
|
||||
return ResponseHelper.error(
|
||||
result_description="Invalid Customer or Account"
|
||||
)
|
||||
|
||||
# CONFIRM IF THE TOTAL DEBT IF FOR ONLY ACTIVE LOANS OR ALL LOANS
|
||||
total_debt_amount = sum(
|
||||
loan.get("currentLoanAmount") or 0 for loan in loans
|
||||
)
|
||||
|
||||
total_outstanding_amount = sum(
|
||||
loan.get("currentLoanAmount") or 0 for loan in loans
|
||||
)
|
||||
|
||||
total_active_loan_amount = sum(
|
||||
loan.get("repaymentAmount") or 0 for loan in loans
|
||||
)
|
||||
|
||||
total_settled_amount = total_active_loan_amount - total_outstanding_amount
|
||||
|
||||
# Simulated processing logic
|
||||
response_data = {
|
||||
"customerId": customer_id,
|
||||
@@ -59,6 +85,11 @@ class LoanStatusService(BaseService):
|
||||
"transactionId": transactionId,
|
||||
"loans": loans,
|
||||
"totalDebtAmount": total_debt_amount,
|
||||
"summary": {
|
||||
"totalSettledAmount": total_settled_amount,
|
||||
"totalOutstandingAmount": total_outstanding_amount,
|
||||
"totalActiveLoanAmount": total_active_loan_amount,
|
||||
}
|
||||
}
|
||||
|
||||
db.session.commit()
|
||||
@@ -68,9 +99,11 @@ class LoanStatusService(BaseService):
|
||||
|
||||
logger.error(f"Validation Error: {getattr(err, 'messages', str(err))}")
|
||||
db.session.rollback()
|
||||
return ResponseHelper.unprocessable_entity(result_description="Validation exception")
|
||||
|
||||
except ValueError as err:
|
||||
return ResponseHelper.unprocessable_entity(
|
||||
result_description="Validation exception"
|
||||
)
|
||||
|
||||
except ValueError as err:
|
||||
logger.error(f"{getattr(err, 'messages', str(err))}")
|
||||
db.session.rollback()
|
||||
return ResponseHelper.error(result_description=str(err))
|
||||
@@ -78,4 +111,4 @@ class LoanStatusService(BaseService):
|
||||
except Exception as e:
|
||||
logger.error(f"An error occurred: {str(e)}", exc_info=True)
|
||||
db.session.rollback()
|
||||
return ResponseHelper.internal_server_error()
|
||||
return ResponseHelper.internal_server_error()
|
||||
|
||||
@@ -38,6 +38,7 @@ class SelectOfferService(BaseService):
|
||||
transaction_id = validated_data.get("transactionId")
|
||||
request_id = validated_data.get("requestId")
|
||||
|
||||
|
||||
offer_id = int(transaction_offer_id[5:]) # The last part is int
|
||||
|
||||
#"offerId": "SAL30001129",
|
||||
|
||||
@@ -44,8 +44,14 @@ class Config:
|
||||
# SIMBRELLA_ENDPOINT_RAC_CHECKS = os.getenv("SIMBRELLA_ENDPOINT_RAC_CHECKS", "RACCheck")
|
||||
VALID_APP_ID = os.getenv("SIMBRELLA_APP_ID", "app1")
|
||||
VALID_API_KEY = os.getenv("SIMBRELLA_API_KEY", "test-api-key-12345")
|
||||
|
||||
|
||||
SIMBRELLA_BASE_URL = os.getenv("SIMBRELLA_BASE_URL", "http://127.0.0.1:6337")
|
||||
SIMBRELLA_ENDPOINT_RAC_CHECKS = os.getenv("SIMBRELLA_ENDPOINT_RAC_CHECKS","api/rac-check")
|
||||
SIMBRELLA_HEALTH = os.getenv("SIMBRELLA_ENDPOINT_RAC_CHECKS","api/system-health-check")
|
||||
|
||||
|
||||
|
||||
EVENTS_SERVICE_BASE_URL = os.getenv("EVENTS_SERVICE_BASE_URL","https://event-core.simbrellang.net")
|
||||
ENDPOINT_DIRECT_LOAN = os.getenv("ENDPOINT_DIRECT_LOAN","/autocall/direct/loan")
|
||||
ENDPOINT_DIRECT_REPAYMENT = os.getenv("ENDPOINT_DIRECT_REPAYMENT","/autocall/direct/repayment")
|
||||
|
||||
+1
-1
@@ -246,7 +246,7 @@ class Loan(db.Model):
|
||||
'loanRef': self.reference,
|
||||
'productId': self.product_id,
|
||||
'initialLoanAmount': self.initial_loan_amount,
|
||||
'currentLoanAmount': self.current_loan_amount,
|
||||
'currentLoanAmount': self.balance,
|
||||
'defaultPenaltyFee': self.default_penalty_fee,
|
||||
'continuousFee': self.continuous_fee,
|
||||
'collectionType': self.collection_type,
|
||||
|
||||
@@ -56,6 +56,12 @@ class Repayment(db.Model):
|
||||
raise ValueError(f"Database integrity error: {err}")
|
||||
|
||||
return repayment
|
||||
|
||||
# Get loan repayments
|
||||
@classmethod
|
||||
def get_repayments_by_id(cls, loan_id):
|
||||
return cls.query.filter_by(loan_id=loan_id).all()
|
||||
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
|
||||
@@ -103,7 +103,9 @@
|
||||
"example": {
|
||||
"status": "ok",
|
||||
"db_status": "Connection Successful",
|
||||
"events_service_status": "healthy",
|
||||
"events_service_status":"Connection Successful",
|
||||
"emulator_status":"Connection Successful",
|
||||
"db_uri": "postgresql://user:****@localhost:5432/digifi_db",
|
||||
"error": []
|
||||
}
|
||||
}
|
||||
@@ -116,7 +118,9 @@
|
||||
"example": {
|
||||
"status": "failed",
|
||||
"db_status": "Connection Failed",
|
||||
"events_service_status": "unhealthy",
|
||||
"events_service_status":"Connection Failed",
|
||||
"emulator_status":"Connection Failed",
|
||||
"db_uri": "Unavailable",
|
||||
"error":["could not connect to server: Connection refused"]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,6 +102,29 @@
|
||||
"type": "number",
|
||||
"format": "float",
|
||||
"example": 30000.0
|
||||
},
|
||||
"summary": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"totalOutstandingAmount": {
|
||||
"type": "number",
|
||||
"format": "float",
|
||||
"example": 114450.0,
|
||||
"description": "Total amount still owed across all unpaid loans."
|
||||
},
|
||||
"totalActiveLoanAmount": {
|
||||
"type": "number",
|
||||
"format": "float",
|
||||
"example": 40000.0,
|
||||
"description": "Total principal amount of currently active loans."
|
||||
},
|
||||
"totalSettledAmount": {
|
||||
"type": "number",
|
||||
"format": "float",
|
||||
"example": 80000.0,
|
||||
"description": "Total amount that has been fully repaid."
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"xml": {
|
||||
|
||||
Reference in New Issue
Block a user