391 lines
18 KiB
Python
391 lines
18 KiB
Python
import requests
|
|
from app.config import settings
|
|
from app.helpers.response_helper import ResponseHelper
|
|
from app.services.loan import LoanService
|
|
from app.utils.auth import get_headers
|
|
from app.utils.extras import preprocess_loan_charges_data
|
|
import random
|
|
import random
|
|
import string
|
|
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 decimal import Decimal, ROUND_HALF_UP
|
|
from requests.exceptions import SSLError, RequestException,Timeout
|
|
import sys
|
|
|
|
|
|
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
|
|
|
|
@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['disburseDate'] is not None:
|
|
logger.info(
|
|
f"Please call verify loan : {data['transactionId']} loan send 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']
|
|
|
|
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,
|
|
"collectAmountMgtFee": mgt_fee,
|
|
"collectAmountInsurance": insurance_fee,
|
|
"collectAmountVAT": vat_fee,
|
|
"countryId": "01",
|
|
"comment": "Loan Disbursement",
|
|
}
|
|
|
|
try:
|
|
logger.info(f"Here is your Disbursement Request data ****** : {disbursement_data}")
|
|
response = requests.post(api_url, json=disbursement_data, timeout=10, headers=get_headers())
|
|
if response.status_code == 404:
|
|
logger.error("Received 404 from external service")
|
|
return ResponseHelper.error("Disbursement Service url not found (404)", status_code=404)
|
|
logger.info(f"Disbursement response: {response.json()}")
|
|
result = response.json()
|
|
LoanService.set_disbursement_result(loan_data['debtId'],result.get('responseCode', ''), result.get('responseMessage', ''))
|
|
return ResponseHelper.success(response.json(), "Successful")
|
|
except Exception as e:
|
|
logger.info(f"Failed to call Disbursement endpoint: {e}")
|
|
return 0
|
|
|
|
return 1
|
|
|
|
@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')
|
|
}
|
|
|
|
try:
|
|
logger.info(f"Here is your TransactionVerify Request data ****** : {verify_data}")
|
|
response = requests.post(api_url, json=verify_data, timeout=10, 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()
|
|
logger.info(f"this is verify result, {result}")
|
|
LoanService.set_disburse_verify_result(loan_data['debtId'],result.get('responseCode', ''), result.get('responseMessage', ''))
|
|
sms_data = {
|
|
"dest": transaction_data.get('phone_number') or settings.TEST_NO,
|
|
"text": f"Transaction {loan_data.get('transactionId')} verified successfully",
|
|
"unicode": True
|
|
}
|
|
try:
|
|
sms_response = requests.post(sms_url, json=sms_data, timeout=10, 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
|
|
return SimbrellaClient._collect_loan(data,"3")
|
|
|
|
|
|
@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 = RepaymentService.get_repayment_by_id(id=data['Id'])
|
|
if not repayment:
|
|
logger.info(f"Repayment with id: {data['Id']} not found")
|
|
return ResponseHelper.error("Repayment not found")
|
|
|
|
repayment_data = repayment.to_dict()
|
|
loan = LoanService.get_loan_by_loan_id(loan_id=int(repayment_data['loanId']))
|
|
if not loan:
|
|
logger.info(f"Loan with debtId: {repayment_data['loanId']} not found")
|
|
return ResponseHelper.error("Loan not found")
|
|
|
|
loan_data = loan.to_dict()
|
|
logger.info(f"Loan data: {loan_data}")
|
|
|
|
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()
|
|
|
|
debtId = str(loan_data.get('debtId', "")).strip().zfill(6)
|
|
t_id = ''.join(random.choices(string.ascii_uppercase, k=22))
|
|
collect_loan_data = {
|
|
"transactionId": t_id,
|
|
"fbnTransactionId": loan_data['transactionId'],
|
|
"debtId": debtId,
|
|
"customerId": repayment_data['customerId'],
|
|
"accountId": loan_data['accountId'],
|
|
"productId": repayment_data['productId'],
|
|
"collectAmount": loan_data['balance'] or 0,
|
|
"penalCharge": 0,
|
|
"channel": "USSD",
|
|
"collectionMethod": collectionMethod,
|
|
"lienAmount": 0,
|
|
"countryId": "NG",
|
|
"comment": "COLLECT LOAN"
|
|
}
|
|
|
|
try:
|
|
logger.info(f"Sending CollectLoan request............ {collect_loan_data}")
|
|
response = requests.post(api_url, json=collect_loan_data, timeout=30, headers=get_headers())
|
|
|
|
logger.info(f"HTTP response object: {response}")
|
|
|
|
if response.status_code == 404:
|
|
RepaymentService.set_repay_result(
|
|
repayment_data['Id'],
|
|
'404',
|
|
'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")
|
|
|
|
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}")
|
|
|
|
if loan.balance is None or loan.balance <= 0:
|
|
logger.warning(f"Loan ID {loan.id} has no balance. Skipping loan update.")
|
|
return ResponseHelper.error("Loan has no balance. Skipping.")
|
|
|
|
try:
|
|
logger.info(f"Updating loan balance for loan ID {loan_data['debtId']} with amount collected: {amount_collected}")
|
|
updated_loan = LoanService.update_loan_balance(int(loan_data['debtId']), amount_collected)
|
|
logger.info(f"Updated loan: {updated_loan}")
|
|
except Exception as ex:
|
|
logger.error(f"Error updating loan balance for loan ID {loan.id}: {ex}")
|
|
return ResponseHelper.error("Error updating loan balance")
|
|
|
|
try:
|
|
updated_balance = Decimal(str(updated_loan['balance'])).quantize(Decimal('0.01'))
|
|
logger.info(f"Updated balance: {updated_balance}")
|
|
|
|
if updated_balance <= Decimal('0.00'):
|
|
logger.info('Loan fully repaid')
|
|
repaid = LoanService.update_status(updated_loan['debtId'], LoanStatus.REPAID)
|
|
logger.info(f'Updated loan with repaid status: {repaid}')
|
|
else:
|
|
logger.info('Loan partially repaid')
|
|
partial = LoanService.update_status(updated_loan['debtId'], LoanStatus.ACTIVE_PARTIAL)
|
|
logger.info(f'Updated loan with partial status: {partial}')
|
|
except Exception as e:
|
|
logger.error(f"Error while updating loan status for debtId {updated_loan['debtId']}: {e}")
|
|
|
|
return ResponseHelper.success(result, "Successful")
|
|
|
|
except SSLError as ssl_err:
|
|
logger.exception(f"SSL error while calling Simbrella endpoint: {ssl_err}")
|
|
return ResponseHelper.error("SSL handshake failed with Simbrella", status_code=502, error=str(ssl_err))
|
|
|
|
except Timeout as timeout_err:
|
|
logger.exception(f"Timeout while calling Simbrella: {timeout_err}")
|
|
return ResponseHelper.error("Connection to Simbrella timed out", status_code=504, error=str(timeout_err))
|
|
|
|
except RequestException as req_err:
|
|
logger.exception(f"RequestException while calling Simbrella: {req_err}")
|
|
return ResponseHelper.error("Connection to Simbrella failed", status_code=503, error=str(req_err))
|
|
|
|
except SystemExit as sys_exit:
|
|
logger.error(f"SystemExit was triggered: {sys_exit}")
|
|
return ResponseHelper.error("Unexpected shutdown detected", status_code=500, error=str(sys_exit))
|
|
|
|
except Exception as e:
|
|
logger.exception(f"Unexpected error occurred while calling CollectLoan: {e}")
|
|
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=10, 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 |