Added logs #60

Merged
ameye merged 5 commits from test into master 2025-11-21 02:55:32 +00:00
2 changed files with 150 additions and 84 deletions
+2 -1
View File
@@ -54,7 +54,8 @@ class Config:
MAIL_USE_SSL = os.getenv('MAIL_USE_SSL', 'False').lower() in ('true', '1', 'yes')
MAIL_DEFAULT_SENDER = ('FirstAdvance', 'firstadvance@dynamikservices.tech')
MAIL_RECEIVER= os.getenv('MAIL_RECEIVER', 'chinenyeumeaku@gmail.com,umeakuchinenye@gmail.com')
BANK_CALL_API_TIME_OUT = os.getenv("BANK_CALL_API_TIME_OUT", 100)
BANK_CALL_BASE_URL = os.getenv("BANK_CALL_BASE_URL", "https://bank-emulator.dev.simbrellang.net/api")
BANK_CALL_SMS_BASE_URL= os.getenv("BANK_CALL_SMS_BASE_URL","https://first-advance-middleware-develop.fbn-devops-dev-asenv.appserviceenvironment.net/SMS")
BANK_CALL_DISBURSE_LOAN_ENDPOINT = os.getenv("BANK_CALL_DISBURSE_LOAN_ENDPOINT","/DisburseLoan")
+148 -83
View File
@@ -1,38 +1,39 @@
import requests
from app.config import settings
from app.helpers.response_helper import ResponseHelper
#from app.routes.autocall import verify_transaction
# 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.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.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
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_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):
@@ -62,7 +63,7 @@ class SimbrellaClient:
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
@@ -80,7 +81,8 @@ class SimbrellaClient:
return 0
# 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 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])
@@ -91,7 +93,7 @@ class SimbrellaClient:
interest_fee = loan_charges.get("INTEREST")['amount']
insurance_fee = loan_charges.get("INSURANCE")['amount']
debtId = str(loan_data.get('debtId', "")).strip().zfill(6)
debtId = str(loan_data.get('debtId', "")).strip().zfill(6)
disbursement_data = {
"transactionId": loan_data.get('transactionId'),
@@ -108,37 +110,42 @@ class SimbrellaClient:
"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"
# }
# '''
# '''
# { 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"Here is your Disbursement Request data ****** : {disbursement_data}")
response = requests.post(api_url, json=disbursement_data, timeout=10, headers=get_headers())
logger.info(f"Call to bank end point returned with Here is your Disbursement Request data ****** : {disbursement_data}")
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)" )
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', ''))
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)
@@ -146,22 +153,64 @@ class SimbrellaClient:
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 )
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 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':
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}"
@@ -192,17 +241,16 @@ class SimbrellaClient:
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'])
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"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'),
@@ -212,44 +260,55 @@ class SimbrellaClient:
"countryId": "NG",
"requestId": loan_data.get('transactionId')
}
# '''
# { Verify with bank
# "accountId": "string",
# "customerId": "string",
# "transactionId": "string",
# "fbnTransactionId": "string",
# "transactionType": "string",
# "countryId": "string",
# "requestId": "string"
# }
# '''
# '''
# { 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=10, headers=get_headers())
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', ''))
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": transaction_data.get('phone_number') or settings.TEST_NO,
"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")
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=10, headers=get_headers())
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'):
@@ -290,13 +349,12 @@ class SimbrellaClient:
status_code=500,
error=str(e)
)
@staticmethod
def collect_loan_user_due_payment(data):
# InitiatedBy = REPAYMENT_DUE
try:
return SimbrellaClient._collect_loan(data,"3")
return SimbrellaClient._collect_loan(data, "3")
except Exception as e:
logger.error(f"Error in collect_loan_user_due_payment: {e}")
return ResponseHelper.error(
@@ -324,10 +382,12 @@ class SimbrellaClient:
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)
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=90, headers=get_headers())
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:
@@ -337,8 +397,9 @@ class SimbrellaClient:
'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')
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)
@@ -372,7 +433,8 @@ class SimbrellaClient:
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)
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(
@@ -388,8 +450,9 @@ class SimbrellaClient:
'502',
'SSL error occurred while calling Simbrella'
)
if(data.get('overdueLoanScheduleId') is not None):
LoanRepaymentScheduleService.update_repayment_schedule_description(data['overdueLoanScheduleId'], 'SSL error occurred')
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))
@@ -401,8 +464,9 @@ class SimbrellaClient:
'500',
'There was a timeout while calling Simbrella'
)
if(data.get('overdueLoanScheduleId') is not None):
LoanRepaymentScheduleService.update_repayment_schedule_description(data['overdueLoanScheduleId'], 'Timeout occurred')
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:
@@ -413,8 +477,9 @@ class SimbrellaClient:
'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')
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()
@@ -423,12 +488,12 @@ class SimbrellaClient:
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')
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:
@@ -439,11 +504,12 @@ class SimbrellaClient:
'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))
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):
@@ -456,7 +522,8 @@ class SimbrellaClient:
try:
logger.info(f"Here is your Penal Charge Request data ****** : {data}")
response = requests.post(api_url, json=data, timeout=10, headers=get_headers())
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")
@@ -467,5 +534,3 @@ class SimbrellaClient:
except Exception as e:
logger.info(f"Failed to call Penal Charge endpoint: {e}")
raise