populated results field #19

Merged
ameye merged 1 commits from test into master 2025-06-04 22:58:23 +00:00
4 changed files with 88 additions and 42 deletions
+23 -28
View File
@@ -8,6 +8,7 @@ from app.utils.logger import logger
from flask import jsonify, current_app from flask import jsonify, current_app
from app.services.transactions import TransactionService from app.services.transactions import TransactionService
from app.services.repayment import RepaymentService from app.services.repayment import RepaymentService
from app.extensions import db
class SimbrellaClient: class SimbrellaClient:
@@ -18,40 +19,33 @@ class SimbrellaClient:
BANK_CALL_TRANSACTION_VERIFY = settings.BANK_CALL_TRANSACTION_VERIFY BANK_CALL_TRANSACTION_VERIFY = settings.BANK_CALL_TRANSACTION_VERIFY
@staticmethod @staticmethod
def disburse_loan(data): def disburse_loan():
api_url = f"{SimbrellaClient.BANK_CALL_BASE_URL}/{SimbrellaClient.BANK_CALL_DISBURSE_LOAN_ENDPOINT}" api_url = f"{SimbrellaClient.BANK_CALL_BASE_URL}/{SimbrellaClient.BANK_CALL_DISBURSE_LOAN_ENDPOINT}"
logger.info(f"Calling DisburseLoan api_url==> : {api_url}") logger.info(f"Calling DisburseLoan api_url==> : {api_url}")
logger.info(f"Calling DisburseLoan endpoint with data: {data}") loan = LoanService.get_latest_loan_without_disburse_date()
if not loan:
logger.info(f"No loan found without disbursement date")
return 0
logger.info(f"Calling DisburseLoan endpoint with data: {loan}")
loan_data = loan.to_dict()
logger.info(f"Here is your loan data: {loan_data}")
# Check if the transaction exists # Check if the transaction exists
logger.info(f"Checking if transaction exists") logger.info(f"Checking if transaction exists")
transaction = TransactionService.get_transaction_by_transaction_id(transaction_id=data['transactionId']) transaction = TransactionService.get_transaction_by_transaction_id(transaction_id=loan_data['transactionId'])
logger.info(f"Loan Response From Database ** : {transaction}") logger.info(f"Loan Response From Database ** : {transaction}")
# If transaction is not found # If transaction is not found
if not transaction: if not transaction:
logger.info(f"Transaction id: {data['transactionId']}, was not found") logger.info(f"Transaction id: {loan_data['transactionId']}, was not found")
return 0 return 0
# Fetch the loan based on the transaction_id
logger.info(f"Fetching the loan with transaction ID: {data['transactionId']}")
loan = LoanService.get_loan_by_transaction_id(transaction_id=data['transactionId'])
logger.info(f"Response from database: {loan}")
# If loan is not found
if not loan:
logger.info(f"Could not find loan with transaction id: {data['transactionId']}")
return 0
loan_data = loan.to_dict()
logger.info(f"Here is your loan data: {loan_data}")
if loan_data['disburseDate'] is not None: if loan_data['disburseDate'] is not None:
logger.info(f"Please call verify loan : {data['transactionId']} loan send for processing at {loan_data['disburseDate']}") logger.info(f"Please call verify loan : {loan_data['transactionId']} loan send for processing at {loan_data['disburseDate']}")
return 0 else:
logger.info(f"Here are your cal 111 : *********************************************************") logger.info(f"Here are your cal 111 : *********************************************************")
# let us set disbursement date # let us set disbursement date
LoanService.set_disbursement_date(loan_data['debtId'], loan_data['customerId']) # toda this must return something LoanService.set_disbursement_date(loan_data['debtId'], loan_data['customerId']) # toda this must return something
logger.info(f"Here are your cal 000 : *********************************************************") logger.info(f"Here are your cal 000 : *********************************************************")
logger.info(f"Here is your loan data after setting disbursement date: {loan_data}") logger.info(f"Here is your loan data after setting disbursement date: {loan_data}")
@@ -64,12 +58,11 @@ class SimbrellaClient:
insurance_fee = loan_charges.get("INSURANCE")['amount'] insurance_fee = loan_charges.get("INSURANCE")['amount']
disbursement_data = { disbursement_data = {
"requestId": data.get('requestId'), "transactionId": loan_data.get('transactionId'),
"transactionId": data.get('transactionId'), "FbnTransactionId": loan_data.get('transactionId'),
"FbnTransactionId": data.get('FbnTransactionId'), "debtId": str(loan_data.get('debtId', "")).strip().zfill(6),
"debtId": str(loan_data.get('debtId', "")), "customerId": loan_data.get('customerId'),
"customerId": data.get('customerId'), "accountId": loan_data.get('accountId'),
"accountId": data.get('accountId'),
"productId": str(loan_data.get('productId', "")), "productId": str(loan_data.get('productId', "")),
"provideAmount": loan_data.get('currentLoanAmount'), "provideAmount": loan_data.get('currentLoanAmount'),
"collectAmountInterest": interest_fee, "collectAmountInterest": interest_fee,
@@ -84,6 +77,8 @@ class SimbrellaClient:
logger.info(f"Here is your Disbursement Request data ****** : {disbursement_data}") logger.info(f"Here is your Disbursement Request data ****** : {disbursement_data}")
response = requests.post(api_url, json=disbursement_data, timeout=10, headers=get_headers()) response = requests.post(api_url, json=disbursement_data, timeout=10, headers=get_headers())
logger.info(f"Disbursement response: {response.json()}") logger.info(f"Disbursement response: {response.json()}")
result = response.json()
LoanService.set_disbursement_result(loan_data['debtId'],result.get('responseCode', ''), result.get('responseMessage', ''))
except Exception as e: except Exception as e:
+38
View File
@@ -39,6 +39,8 @@ class Loan(db.Model):
eligible_amount = db.Column(db.Float, nullable=True, default=0.0) eligible_amount = db.Column(db.Float, nullable=True, default=0.0)
disburse_date = db.Column(db.DateTime, nullable=True) disburse_date = db.Column(db.DateTime, nullable=True)
disburse_verify = db.Column(db.DateTime, nullable=True) disburse_verify = db.Column(db.DateTime, nullable=True)
disburse_result = db.Column(db.String(10), nullable=True)
disburse_description = db.Column(db.String(100), nullable=True)
reference = db.Column(db.String(50), nullable=True) reference = db.Column(db.String(50), nullable=True)
customer = relationship( customer = relationship(
@@ -72,6 +74,10 @@ class Loan(db.Model):
'collectionType': self.collection_type, 'collectionType': self.collection_type,
'status': self.status, 'status': self.status,
'productId': self.product_id, 'productId': self.product_id,
'disburseResult': self.disburse_result,
'disburseDescription': self.disburse_description,
'transactionId': self.transaction_id,
'accountId':self.account_id,
'dueDate': self.due_date.isoformat() if self.due_date else None, 'dueDate': self.due_date.isoformat() if self.due_date else None,
'loanDate': self.created_at.isoformat() if self.created_at else None, 'loanDate': self.created_at.isoformat() if self.created_at else None,
'disburseDate': self.disburse_date.isoformat() if self.disburse_date else None, 'disburseDate': self.disburse_date.isoformat() if self.disburse_date else None,
@@ -112,3 +118,35 @@ class Loan(db.Model):
logger.error(f"Failed to update disburse date: {e}") logger.error(f"Failed to update disburse date: {e}")
raise raise
@classmethod
def set_disbursement_result(cls, loan_id, result, description):
"""
Update the disburse result and description of the loan with the given loan_id.
"""
# Retrieve loan
loan = cls.query.get(loan_id)
if not loan:
raise ValueError(f"Loan with ID {loan_id} does not exist.")
# Update disburse result and description
loan.disburse_result = result
loan.disburse_description = description
# Commit changes to database
try:
logger.info(f"Updating disburse result for loan ID {loan_id} to {result} with description {description}")
db.session.commit()
except Exception as e:
db.session.rollback()
logger.error(f"Failed to update disbursement result: {e}")
raise
@classmethod
def get_latest_loan_without_disburse_date(cls):
"""
Get the latest loan without a disbursement date.
"""
return cls.query.filter(
cls.disburse_date.is_(None)
).order_by(cls.created_at.desc()).first()
+12 -13
View File
@@ -19,23 +19,22 @@ def verify_transaction():
def disbursement(): def disbursement():
# data = request.json() # data = request.json()
logger.info(f"Calling Disbursement Components") logger.info(f"Calling Disbursement Components")
data = { """ data = {
"requestId": "TRX1747399791142408", "transactionId": "TRX1749033507722975",
"transactionId": "TRX1747399791142408", "FbnTransactionId":"TRX1748643654575327",
"FbnTransactionId":"TRX1747399791142408", "debtId": "94696900",
"debtId": "9451", "customerId": "CID00000559140T",
"customerId": "CUC1696296013", "accountId": "ACC20267810160T",
"accountId": "ACC8112865094", "productId": "3MPC",
"productId": "AMPC", "provideAmount": 10000.0,
"provideAmount": 6600.0, "collectAmountInterest": 19.0,
"collectAmountInterest": 198.0,
"collectAmountMgtFee": 66.0, "collectAmountMgtFee": 66.0,
"collectAmountInsurance": 66.0, "collectAmountInsurance": 66.0,
"collectAmountVAT": 4.95, "collectAmountVAT": 75.00,
"countryId": "01", "countryId": "01",
"comment": "Loan Disbursement" "comment": "Loan Disbursement"
} }"""
response = SimbrellaClient.disburse_loan(data) response = SimbrellaClient.disburse_loan()
return response return response
+14
View File
@@ -30,3 +30,17 @@ class LoanService:
Update the disbursement status of the loan with the given loan_id. Update the disbursement status of the loan with the given loan_id.
""" """
return Loan.set_disbursement_date(loan_id, customer_id) return Loan.set_disbursement_date(loan_id, customer_id)
@classmethod
def set_disbursement_result(cls, loan_id, result, description):
"""
Update the disbursement result of the loan with the given loan_id.
"""
return Loan.set_disbursement_result(loan_id, result, description)
@classmethod
def get_latest_loan_without_disburse_date(cls):
"""
Get the latest loan without a disbursement date.
"""
return Loan.get_latest_loan_without_disburse_date()