1
0

Merge branch 'update_loan_status_response' of DigiFi/digifi-BankToProductCore into master

This commit is contained in:
2025-10-23 10:42:23 +00:00
committed by Gogs
9 changed files with 134 additions and 25 deletions
+18
View File
@@ -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):
@@ -43,3 +44,20 @@ class SimbrellaIntegration:
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
+18
View File
@@ -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
}
+48 -15
View File
@@ -27,30 +27,56 @@ 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')
transactionId = validated_data.get("transactionId")
account_id = validated_data.get("accountId")
if(LoanStatusService.validate_account_ownership(account_id = account_id, customer_id = customer_id)):
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 = {
@@ -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,7 +99,9 @@ class LoanStatusService(BaseService):
logger.error(f"Validation Error: {getattr(err, 'messages', str(err))}")
db.session.rollback()
return ResponseHelper.unprocessable_entity(result_description="Validation exception")
return ResponseHelper.unprocessable_entity(
result_description="Validation exception"
)
except ValueError as err:
logger.error(f"{getattr(err, 'messages', str(err))}")
+1
View File
@@ -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",
+6
View File
@@ -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
View File
@@ -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,
+6
View File
@@ -57,6 +57,12 @@ class Repayment(db.Model):
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 {
"id": self.id,
+6 -2
View File
@@ -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": {