import requests from app.config import settings from app.helpers.response_helper import ResponseHelper # from app.routes.autocall import verify_transaction from app.models.customer import Customer from app.services.loan import LoanService from app.services.loan_repayment_schedule import LoanRepaymentScheduleService from app.utils.auth import get_headers from app.utils.extras import preprocess_loan_charges_data import random import string from app.extensions import db from app.utils.logger import logger from flask import jsonify, current_app from app.services.transactions import TransactionService from app.services.repayment import RepaymentService from app.extensions import db from app.services.repayments_data import RepaymentsData from app.services.salary import SalaryService from app.enums.loan_status import LoanStatus from app.models.loan_repayment_schedule import LoanRepaymentSchedule from decimal import Decimal, ROUND_HALF_UP from requests.exceptions import SSLError, RequestException, Timeout, ReadTimeout, ConnectTimeout import sys import socket from app.helpers.collect_loan_helper import CollectLoanHelper class SimbrellaClient: BANK_CALL_BASE_URL = settings.BANK_CALL_BASE_URL BANK_CALL_SMS_BASE_URL = settings.BANK_CALL_SMS_BASE_URL BANK_CALL_DISBURSE_LOAN_ENDPOINT = settings.BANK_CALL_DISBURSE_LOAN_ENDPOINT BANK_CALL_COLLECT_LOAN_ENDPOINT = settings.BANK_CALL_COLLECT_LOAN_ENDPOINT BANK_CALL_TRANSACTION_VERIFY = settings.BANK_CALL_TRANSACTION_VERIFY BANK_HEALTH_CHECK_ENDPOINT = settings.BANK_HEALTH_CHECK_ENDPOINT BANK_CALL_API_TIME_OUT = settings.BANK_CALL_API_TIME_OUT @staticmethod def disburse_loan(data): 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 endpoint with data: {data}") # Check if the transaction exists logger.info(f"Checking if transaction exists") transaction = TransactionService.get_transaction_by_transaction_id(transaction_id=data['transactionId']) logger.info(f"Loan Response From Database ** : {transaction}") # If transaction is not found if not transaction: logger.info(f"Transaction id: {data['transactionId']}, was not found") 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['status'] != LoanStatus.ACTIVE: logger.info(f"Loan with transaction id: {data['transactionId']} is not active") return 0 if loan_data['disburseDate'] is not None: logger.info("*************************SEEM LIKE A RETRY CALL -WE WILL VERIFY Result to Continue ") logger.info( f"Please call verify loan : {data['transactionId']} loan sent for processing at {loan_data['disburseDate']}") # return 0 -- we need the disburseResult = '00' to be sure all is good if loan_data['disburseDate'] is not None and loan_data['disburseResult'] == '00': logger.info("*************************Duplicate call to completed loan ") logger.info( f"Duplicate call detected for loan : {data['transactionId']} loan sent for processing at {loan_data['disburseDate']}") return 0 # let us set disbursement date LoanService.set_disbursement_date(loan_data['debtId'], loan_data['customerId']) # toda this must return something logger.info(f"Here is your loan data after setting disbursement date: {loan_data}") loan_charges = preprocess_loan_charges_data([loan_charge.to_dict() for loan_charge in loan.loan_charges]) logger.info(f"Here are your loan_charges: {loan_charges}") mgt_fee = loan_charges.get("MGTFEE")['amount'] vat_fee = loan_charges.get("VAT")['amount'] interest_fee = loan_charges.get("INTEREST")['amount'] insurance_fee = loan_charges.get("INSURANCE")['amount'] product_id = str(loan_data.get('productId', "")) debtId = str(loan_data.get('debtId', "")).strip().zfill(6) disbursement_data = { "transactionId": loan_data.get('transactionId'), "fbnTransactionId": loan_data.get('transactionId'), "debtId": debtId, "customerId": loan_data.get('customerId'), "accountId": loan_data.get('accountId'), "productId": str(loan_data.get('productId', "")), "provideAmount": loan_data.get('currentLoanAmount'), "collectAmountInterest": interest_fee if product_id != '3MPC' else 0, "collectAmountMgtFee": mgt_fee, "collectAmountInsurance": insurance_fee, "collectAmountVAT": vat_fee, "countryId": "01", "comment": "Loan Disbursement", } # ''' # { Veryfing with the bank # "transactionId": "string", # "fbnTransactionId": "string", # "debtId": "string", # "customerId": "string", # "accountId": "string", # "productId": "string", # "provideAmount": 0, # "collectAmountInterest": 0, # "collectAmountMgtFee": 0, # "collectAmountInsurance": 0, # "collectAmountVAT": 0, # "countryId": "string", # "comment": "string" # } # ''' try: logger.info(f"Calling Bank Disbursement with Request data ****** : {disbursement_data}") response = requests.post(api_url, json=disbursement_data, timeout=SimbrellaClient.BANK_CALL_API_TIME_OUT, headers=get_headers()) logger.info( f"Call to bank end point returned with Here is your Disbursement Request data ****** : {disbursement_data}") if response.status_code == 404: logger.error("") LoanService.set_disbursement_loan_description(loan_data['debtId'], "Disbursement Service url not found (404)") logger.info(f"Loan status updated to {LoanStatus.FAILED} for loan ID {loan_data['debtId']} due to disbursement failure") LoanService.update_status(loan_data['debtId'], LoanStatus.FAILED) return ResponseHelper.error("Disbursement Service url not found (404)", status_code=404) logger.info(f"Disbursement response: {response.json()}") if response.status_code == 200: result = response.json() LoanService.set_disbursement_result(loan_data['debtId'], result.get('responseCode', ''), result.get('responseMessage', '')) reload_loan = LoanService.get_loan_by_transaction_id(transaction_id=data['transactionId']) reload_loan_data = reload_loan.to_dict() #mark repayment schedule as active repayment_schedule = LoanRepaymentScheduleService.get_repayment_schedule_by_loan_id( reload_loan_data['debtId'], include_paid=False) logger.info(f'Loan repayment schedule: {repayment_schedule}') if repayment_schedule: for schedule in repayment_schedule: logger.info(f"Updating repayment schedule ID {schedule.id} status to ACTIVE") LoanRepaymentScheduleService.update_repayment_schedule_status_to_active(schedule.id) SimbrellaClient.verify_disbursement_transaction(reload_loan_data) return ResponseHelper.success(response.json(), "Successful") else: logger.error("") errorMessage = "Unable to complete Disbursement Service with HTTP status code: " + str( response.status_code) LoanService.set_disbursement_loan_description(loan_data['debtId'], errorMessage) updatedLoan = LoanService.update_status(loan_data['debtId'], LoanStatus.FAILED) logger.info(f"Loan status updated to {updatedLoan.get('status')} for loan ID {loan_data['debtId']} due to disbursement failure") return ResponseHelper.error(errorMessage, status_code=response.status_code) except requests.exceptions.HTTPError as errh: print(f"Disbursement HTTP Error: {errh}") except requests.exceptions.ConnectionError as errc: print(f"Disbursement Error Connecting: {errc}") except requests.exceptions.Timeout as errt: print(f"Disbursement Timeout Error: {errt}") except requests.exceptions.RequestException as err: print(f"Disbursement - Unexpected Error Occurred: {err}") except Exception as e: logger.info(f"Failed to call Disbursement endpoint: {e}") return 0 # try: # logger.info(f"Calling Bank Disbursement with Request data ****** : {disbursement_data}") # response = requests.post(api_url, json=disbursement_data, timeout=SimbrellaClient.BANK_CALL_API_TIME_OUT, # headers=get_headers()) # logger.info( # f"Call to bank end point returned with Here is your Disbursement Request data ****** : {disbursement_data}") # if response.status_code == 404: # logger.error("") # LoanService.set_disbursement_loan_description(loan_data['debtId'], # "Disbursement Service url not found (404)") # return ResponseHelper.error("Disbursement Service url not found (404)", status_code=404) # # logger.info(f"Disbursement response: {response.json()}") # # if response.status_code == 200: # result = response.json() # LoanService.set_disbursement_result(loan_data['debtId'], result.get('responseCode', ''), # result.get('responseMessage', '')) # reload_loan = LoanService.get_loan_by_transaction_id(transaction_id=data['transactionId']) # reload_loan_data = reload_loan.to_dict() # SimbrellaClient.verify_disbursement_transaction(reload_loan_data) # return ResponseHelper.success(response.json(), "Successful") # # else: # logger.error("") # errorMessage = "Unable to complete Disbursement Service with HTTP status code: " + str( # response.status_code) # LoanService.set_disbursement_loan_description(loan_data['debtId'], errorMessage) # return ResponseHelper.error(errorMessage, status_code=response.status_code) # except Exception as e: # logger.info(f"Failed to call Disbursement endpoint: {e}") # return 0 return 1 @staticmethod def verify_disbursement_transaction(loan_data): if loan_data['disburseResult'] and loan_data['disburseResult'] == '00': SimbrellaClient.verify_transaction(loan_data) @staticmethod def verify_transaction(data): api_url = f"{SimbrellaClient.BANK_CALL_BASE_URL}{SimbrellaClient.BANK_CALL_TRANSACTION_VERIFY}" sms_url = f"{SimbrellaClient.BANK_CALL_SMS_BASE_URL}/singleSMS" logger.info(f"Calling TransactionVerify api_url==> : {api_url}") # Check if the transaction exists logger.info(f"Checking if transaction exists") transaction = TransactionService.get_transaction_by_transaction_id(transaction_id=data['transactionId']) transaction_data = transaction.to_dict() logger.info(f"Loan Response From Database ** : {transaction}") # If transaction is not found if not transaction: logger.info(f"Transaction id: {data['transactionId']}, was not found") 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 and loan_data['disburseVerify'] is None: LoanService.set_disburse_verify_date(loan_data['debtId'], loan_data['customerId']) loan_data = loan.to_dict() logger.info(f"Here is your loan data after setting verify date: {loan_data}") logger.info(f"Good to Verify transaction id: {data['transactionId']}") else: logger.info( f"Please call disburse loan : {data['transactionId']} loan send for processing first") return 0 verify_data = { "customerId": loan_data.get('customerId'), "accountId": loan_data.get('accountId'), "transactionId": loan_data.get('transactionId'), "transactionType": "provide", "fbnTransactionId": loan_data.get('transactionId'), "countryId": "NG", "requestId": loan_data.get('transactionId') } # ''' # { Verify with bank # "accountId": "string", # "customerId": "string", # "transactionId": "string", # "fbnTransactionId": "string", # "transactionType": "string", # "countryId": "string", # "requestId": "string" # } # ''' try: logger.info(f"Here is your TransactionVerify Request data ****** : {verify_data}") response = requests.post(api_url, json=verify_data, timeout=SimbrellaClient.BANK_CALL_API_TIME_OUT, headers=get_headers()) if response.status_code == 404: logger.error("Received 404 from external service") return ResponseHelper.error("Verify Service url not found (404)", status_code=404) result = response.json() #check for res 00 and status 200 logger.info(f"this is verify result, {result}") LoanService.set_disburse_verify_result(loan_data['debtId'], result.get('responseCode', ''), result.get('responseMessage', '')) customer = Customer.get_customer(loan_data.get('customerId')) if customer: misisdn = customer.msisdn else: logger.info(f"Customer does not exist for customer id: {loan_data.get('customerId')}") misisdn = settings.TEST_NO sms_data = { "dest": misisdn, "text": f"Transaction {loan_data.get('transactionId')} verified successfully", "unicode": True } try: TransactionService.create_transaction(loan_data['transactionId'], loan_data['accountId'], loan_data['customerId'], "send_sms", "USSD") except Exception as e: logger.info(f"Failed to LOG SMS Transaction Record: {e}") try: sms_response = requests.post(sms_url, json=sms_data, timeout=SimbrellaClient.BANK_CALL_API_TIME_OUT, headers=get_headers()) sms_response.raise_for_status() # Raise an exception for 4xx or 5xx status codes result = sms_response.json() logger.info(f"SMS Response JSON: {result}") if result.get('isSuccess'): logger.info(f"sms sent successfully") return ResponseHelper.success(response.json(), "Successful") logger.info(f"sms failed!") return 1 except requests.RequestException as e: # Handle the exception logger.error(f"Failed to send SMS: {e}") return 0 except Exception as e: logger.info(f"Failed to call TransactionVerify endpoint: {e}") return 0 @staticmethod def collect_loan_user_initiated(data): # InitiatedBy = USER_INITIATED try: logger.info(f"Calling CollectLoan collect_loan_user_initiated ******* endpoint with data: {data}") return SimbrellaClient._collect_loan(data, "1") except Exception as e: logger.error(f"Error in collect_loan_user_initiated: {e}") # return ResponseHelper.error( # message="Failed to collect loan for user initiated ", # status_code=500, # error=str(e) # ) @staticmethod def collect_loan_user_salary_detect(data): try: return SimbrellaClient._collect_loan(data, "2") except Exception as e: logger.error(f"Error in collect_loan_user_salary_detect: {e}") return ResponseHelper.error( message="Failed to collect loan for salary detection", status_code=500, error=str(e) ) @staticmethod def collect_loan_user_due_payment(data): # InitiatedBy = REPAYMENT_DUE try: return SimbrellaClient._collect_loan(data, "3") except Exception as e: logger.error(f"Error in collect_loan_user_due_payment: {e}") return ResponseHelper.error( message="Failed to collect loan for due payment", status_code=500, error=str(e) ) @staticmethod def _collect_loan(data, collectionMethod: str): api_url = f"{SimbrellaClient.BANK_CALL_BASE_URL}{SimbrellaClient.BANK_CALL_COLLECT_LOAN_ENDPOINT}" logger.info(f"Calling CollectLoan api_url==> : {api_url}") logger.info(f"Calling CollectLoan endpoint with data: {data}") repayment_data, loan, error = CollectLoanHelper._validate_repayment_and_loan(data) if error: return error loan_data = loan.to_dict() if repayment_data['repayDate'] is not None: logger.info(f"Repayment already processed at {repayment_data['repayDate']}") return ResponseHelper.error("Repayment already processed") RepaymentService.set_repay_date(repayment_data['Id'], repayment_data['customerId']) repayment = RepaymentService.get_repayment_by_transaction_id(transaction_id=data['transactionId']) repayment_data = repayment.to_dict() collect_loan_data = CollectLoanHelper._build_collect_loan_payload(loan_data, repayment_data, data, collectionMethod) try: logger.info(f"Sending CollectLoan request............ {collect_loan_data}") response = requests.post(api_url, json=collect_loan_data, timeout=SimbrellaClient.BANK_CALL_API_TIME_OUT, headers=get_headers()) logger.info(f"HTTP response object: {response}") if response.status_code == 404: db.session.rollback() RepaymentService.set_repay_result( repayment_data['Id'], '404', 'Collection Service url not found' ) if (data.get('overdueLoanScheduleId') is not None): LoanRepaymentScheduleService.update_repayment_schedule_description(data['overdueLoanScheduleId'], 'Collection Service url not found') logger.error("Received 404 from external service") return ResponseHelper.error("Collection Service URL not found", status_code=404) result = response.json() logger.info(f"CollectLoan response: {result}") RepaymentService.set_repay_result( repayment_data['Id'], result.get('responseCode', ''), result.get('responseMessage', '') ) data_to_add = { "transactionId": result.get('transactionId') or collect_loan_data.get('transactionId'), "fbnTransactionId": loan_data['transactionId'], "accountId": result.get('accountId') or collect_loan_data.get('accountId'), "customerId": result.get('customerId') or collect_loan_data.get('customerId'), "amountCollected": float(result.get('amountCollected', 0)), "repaymentAmount": collect_loan_data.get('collectAmount'), "responseCode": result.get('responseCode'), "responseDescr": result.get('responseMessage'), "balance": round(float(result.get('lienAmount', 0)), 2) } new_repayment_data = RepaymentsData.add_repayment_data(data_to_add) if new_repayment_data: logger.info(f"Repayment data added: {new_repayment_data.to_dict()}") else: logger.warning("Failed to add repayment data") updated_loan = None response_message = result.get('responseMessage') if result.get('responseCode') == '00': amount_collected = Decimal(str(result.get('amountCollected', 0))).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP) logger.info(f"Amount collected: {amount_collected}") updated_loan = LoanService._update_loan_after_collection( loan, loan_data, updated_loan, amount_collected, data, response_message=response_message ) return ResponseHelper.success(result, "Successful") except SSLError as ssl_err: db.session.rollback() logger.exception(f"SSL error while calling Simbrella endpoint: {ssl_err}") RepaymentService.set_repay_result( repayment_data['Id'], '502', 'SSL error occurred while calling Simbrella' ) if (data.get('overdueLoanScheduleId') is not None): LoanRepaymentScheduleService.update_repayment_schedule_description(data['overdueLoanScheduleId'], 'SSL error occurred') return ResponseHelper.error("SSL handshake failed with Simbrella", status_code=502, error=str(ssl_err)) except (Timeout, ReadTimeout, ConnectTimeout, socket.timeout, TimeoutError) as timeout_err: db.session.rollback() logger.exception(f"Timeout while calling Simbrella: {timeout_err}") RepaymentService.set_repay_result( repayment_data['Id'], '500', 'There was a timeout while calling Simbrella' ) if (data.get('overdueLoanScheduleId') is not None): LoanRepaymentScheduleService.update_repayment_schedule_description(data['overdueLoanScheduleId'], 'Timeout occurred') return ResponseHelper.error("Connection to Simbrella timed out", status_code=504, error=str(timeout_err)) except RequestException as req_err: db.session.rollback() logger.exception(f"RequestException while calling Simbrella: {req_err}") RepaymentService.set_repay_result( repayment_data['Id'], '500', 'There was a request error while calling Simbrella' ) if (data.get('overdueLoanScheduleId') is not None): LoanRepaymentScheduleService.update_repayment_schedule_description(data['overdueLoanScheduleId'], 'Request error occurred') except SystemExit as sys_exit: db.session.rollback() logger.error(f"SystemExit was triggered: {sys_exit}") RepaymentService.set_repay_result( repayment_data['Id'], '500', 'There was a system error while calling Simbrella' ) if (data.get('overdueLoanScheduleId') is not None): LoanRepaymentScheduleService.update_repayment_schedule_description(data['overdueLoanScheduleId'], 'Unexpected shutdown occurred') return ResponseHelper.error("Unexpected shutdown detected", status_code=500, error=str(sys_exit)) except Exception as e: db.session.rollback() logger.exception(f"Unexpected error occurred while calling CollectLoan: {e}") RepaymentService.set_repay_result( repayment_data['Id'], '500', 'Unexpected error while processing loan collection' ) if (data.get('overdueLoanScheduleId') is not None): LoanRepaymentScheduleService.update_repayment_schedule_description(data['overdueLoanScheduleId'], 'Unexpected error occurred') return ResponseHelper.error("Unexpected error while processing loan collection", status_code=500, error=str(e)) @staticmethod def penal_charge(data): api_url = f"{SimbrellaClient.BANK_CALL_BASE_URL}/PenalCharge" logger.info(f"Calling Penal Charge endpoint with data: {data}") try: logger.info(f"Here is your Penal Charge Request data ***** : {data}") try: logger.info(f"Here is your Penal Charge Request data ****** : {data}") response = requests.post(api_url, json=data, timeout=SimbrellaClient.BANK_CALL_API_TIME_OUT, headers=get_headers()) logger.info(f"Penal Charge response: {response.json()}") return ResponseHelper.success(response.json(), "Successful") except Exception as e: logger.info(f"Failed to call Penal Charge endpoint: {e}") return ResponseHelper.error("An error occurred", 500) except Exception as e: logger.info(f"Failed to call Penal Charge endpoint: {e}") raise