340 lines
13 KiB
Python
340 lines
13 KiB
Python
from flask import Blueprint, request, jsonify, current_app
|
|
import requests
|
|
from app.extensions import db
|
|
from app.config import settings
|
|
from app.helpers.response_helper import ResponseHelper
|
|
from app.utils.auth import get_headers
|
|
from app.utils.logger import logger
|
|
from app.integrations.simbrella import SimbrellaClient
|
|
from app.services.loan import LoanService
|
|
from app.services.repayment import RepaymentService
|
|
from app.services.salary import SalaryService
|
|
from app.enums.loan_status import LoanStatus
|
|
from app.utils.mail import send_report_email, get_report_data
|
|
from app.config import settings
|
|
|
|
autocall_bp = Blueprint("autocall", __name__)
|
|
|
|
@autocall_bp.route("/refresh-verify-disbursement", methods=["GET"])
|
|
def verify_transaction():
|
|
logger.info(f"Calling VerifyTransaction Components")
|
|
|
|
loan = LoanService.get_latest_loan_with_disburse_date()
|
|
if not loan:
|
|
logger.info(f"No loan found without disbursement date")
|
|
return 0
|
|
logger.info(f"Calling VerifyTransaction endpoint with data: {loan}")
|
|
loan_data = loan.to_dict()
|
|
|
|
data = {
|
|
"transactionId": loan_data.get('transactionId'),
|
|
"FbnTransactionId": loan_data.get('transactionId'),
|
|
"debtId": str(loan_data.get('debtId')),
|
|
"customerId": loan_data.get('customerId'),
|
|
"accountId": loan_data.get('accountId'),
|
|
"productId": str(loan_data.get('productId', "")),
|
|
"provideAmount": loan_data.get('currentLoanAmount'),
|
|
}
|
|
response = SimbrellaClient.verify_transaction(data)
|
|
return response
|
|
|
|
@autocall_bp.route("/refresh-disbursement", methods=["GET"])
|
|
def disbursement():
|
|
# data = request.json()
|
|
logger.info(f"Calling Disbursement Components")
|
|
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()
|
|
|
|
data = {
|
|
"transactionId": loan_data.get('transactionId'),
|
|
"FbnTransactionId": loan_data.get('transactionId'),
|
|
"debtId": str(loan_data.get('debtId')),
|
|
"customerId": loan_data.get('customerId'),
|
|
"accountId": loan_data.get('accountId'),
|
|
"productId": str(loan_data.get('productId', "")),
|
|
"provideAmount": loan_data.get('currentLoanAmount'),
|
|
}
|
|
response = SimbrellaClient.disburse_loan(data)
|
|
return response
|
|
|
|
|
|
@autocall_bp.route("/refresh-verify-collection", methods=["GET"])
|
|
def refresh_verify_collection():
|
|
data = request.get_json()
|
|
logger.info(f"Calling Verify Collection")
|
|
|
|
response = SimbrellaClient.collect_loan(data)
|
|
|
|
return response
|
|
|
|
@autocall_bp.route("/refresh-collection", methods=["GET"])
|
|
def refresh_collection():
|
|
#data = request.get_json()
|
|
logger.info(f"Calling Collection ")
|
|
#grab the last repayments with repay date is none
|
|
repayment = RepaymentService.get_latest_repayment_without_repay_date()
|
|
#repayment = RepaymentService.get_latest_repayment_with_loanId(13735)
|
|
if not repayment:
|
|
logger.info(f"No repayment found without repay date")
|
|
return 0
|
|
logger.info(f"Calling repay loan endpoint with data: {repayment}")
|
|
repayment_data = repayment.to_dict()
|
|
logger.info(f"here is the dict form of repayment {repayment_data}")
|
|
|
|
data = {
|
|
"transactionId": repayment_data['transactionId'],
|
|
"debtId": repayment_data['loanId'],
|
|
"customerId": repayment_data['customerId'],
|
|
"productId": repayment_data['productId'],
|
|
"Id":repayment_data['Id']
|
|
}
|
|
logger.info(f"Data being sent to Simbrella: {data}")
|
|
logger.info(f"calling simbrella")
|
|
response = SimbrellaClient.collect_loan_user_initiated(data)
|
|
|
|
return response
|
|
|
|
@autocall_bp.route("/payment-callback", methods=["POST"])
|
|
def payment_callback():
|
|
data = request.get_json()
|
|
logger.info(f"Calling Callback Components")
|
|
|
|
response = SimbrellaClient.payment_callback(data)
|
|
|
|
return response
|
|
|
|
@autocall_bp.route("/penal-charge", methods=["POST"])
|
|
def penal_charge():
|
|
data = request.get_json()
|
|
logger.info(f"Calling Penal Charge Endpoint")
|
|
|
|
try:
|
|
response = SimbrellaClient.penal_charge(data[0])
|
|
return response
|
|
except Exception as e:
|
|
logger.error(f"Error in Penal Charge: {e}")
|
|
return ResponseHelper.error("Penal charge failed")
|
|
|
|
|
|
@autocall_bp.route("/analytic-salary-detect", methods=["POST"])
|
|
def salary_detect():
|
|
payload = request.get_json()
|
|
logger.info("Calling Salary Detect endpoint")
|
|
|
|
if payload is None:
|
|
logger.warning("No payload received in request")
|
|
return ResponseHelper.error("Missing request payload", status_code=400)
|
|
|
|
# Step 1: Try to add new salary data
|
|
try:
|
|
new_salary = SalaryService.add_salary_data(payload) # TODO - This will come as array of salaries - not just one
|
|
if new_salary:
|
|
logger.info(f"Salary added: {new_salary.id}")
|
|
except Exception as e:
|
|
logger.error(f"Failed to save salary: {e}")
|
|
|
|
# Step 2: Try processing salary list
|
|
try:
|
|
process_salary_list()
|
|
except Exception as e:
|
|
logger.exception("Unhandled error occurred while processing salary list {e}")
|
|
return ResponseHelper.error("Failed to process salary list", status_code=500, error=str(e))
|
|
|
|
logger.info("Finished processing List")
|
|
return ResponseHelper.success([], "AutoCall Add Salary Successful")
|
|
|
|
|
|
@autocall_bp.route("/analytic-salary-process", methods=["POST"])
|
|
def salary_process():
|
|
response = process_salary_list()
|
|
return ResponseHelper.success([], "AutoCall Successful")
|
|
|
|
|
|
def process_salary_list():
|
|
# Step 1: Get all pending salaries
|
|
pending_salaries = SalaryService.get_pending_salaries()
|
|
if not pending_salaries:
|
|
logger.info("No pending salaries found")
|
|
return ResponseHelper.success([], "No pending salaries")
|
|
|
|
logger.info(f"Found {len(pending_salaries)} pending salaries to process")
|
|
|
|
for pending_salary in pending_salaries:
|
|
logger.info(f"Processing salary ID: {pending_salary.id}")
|
|
|
|
# Step 2: Update salary status to PROCESSING
|
|
try:
|
|
SalaryService.update_status(pending_salary.id, "PROCESSING")
|
|
except Exception as e:
|
|
db.session.rollback()
|
|
logger.warning(f"Could not update status for salary ID {pending_salary.id}: {e}")
|
|
continue
|
|
|
|
# Step 3: Get customer's active loans
|
|
try:
|
|
loans, total_amount = LoanService.get_customer_active_loans(pending_salary.customer_id)
|
|
if not loans:
|
|
logger.warning(f"No loans found for customer ID: {pending_salary.customer_id}")
|
|
continue
|
|
except Exception as e:
|
|
db.session.rollback()
|
|
logger.error(f"Error fetching loans for customer ID {pending_salary.customer_id}: {e}")
|
|
continue
|
|
|
|
# Step 4: Create repayments for each loan
|
|
for loan in loans:
|
|
logger.info(f"Processing Loan ID: {loan.id}")
|
|
try:
|
|
repayment_data = {
|
|
"customerId": loan.customer_id,
|
|
"loanId": loan.id,
|
|
"productId": loan.product_id,
|
|
"transactionId": loan.transaction_id,
|
|
"initiatedBy": "SALARY_DETECT",
|
|
"salaryAmount": pending_salary.amount,
|
|
"LoanStatus": loan.status,
|
|
}
|
|
|
|
logger.info(f"Creating repayment with data: {repayment_data}")
|
|
repayment = RepaymentService.create_repayment(repayment_data)
|
|
|
|
if not repayment or isinstance(repayment, dict) and "error" in repayment:
|
|
db.session.rollback() # important in case create_repayment failed mid-way
|
|
logger.error(f"Repayment creation failed for loan ID {loan.id}: {repayment}")
|
|
continue
|
|
|
|
try:
|
|
LoanService.update_status(loan_id=loan.id, status=LoanStatus.START_REPAY)
|
|
except Exception as e:
|
|
db.session.rollback()
|
|
logger.error(f"Failed to update loan status for loan ID {loan.id}: {e}")
|
|
|
|
logger.info(f"Created repayment ID: {repayment.id}")
|
|
|
|
# Step 5: Call Simbrella
|
|
try:
|
|
simbrella_response = SimbrellaClient.collect_loan_user_salary_detect(repayment.to_dict())
|
|
|
|
if isinstance(simbrella_response, tuple):
|
|
simbrella_response, status_code = simbrella_response
|
|
logger.warning(f"Simbrella returned tuple: status={status_code}, response={simbrella_response}")
|
|
|
|
if isinstance(simbrella_response, dict):
|
|
if simbrella_response.get("status") != "success":
|
|
logger.warning(f"Simbrella failed for repayment ID {repayment.id}: {simbrella_response}")
|
|
else:
|
|
logger.warning(f"Unexpected Simbrella response: {type(simbrella_response)}")
|
|
|
|
except Exception as e:
|
|
logger.error(f"Failed to call Simbrella for repayment ID {repayment.id}: {e}")
|
|
|
|
except Exception as e:
|
|
db.session.rollback()
|
|
logger.error(f"Error creating repayment for loan ID {loan.id}: {e}")
|
|
continue
|
|
|
|
logger.info(f"Finished processing salary ID: {pending_salary.id}")
|
|
|
|
return ResponseHelper.success([], "Processed all pending salaries")
|
|
|
|
|
|
|
|
@autocall_bp.route("/report", methods=["GET"])
|
|
def report():
|
|
try:
|
|
report_data = get_report_data()
|
|
logger.info(f"Generated report data: {report_data}")
|
|
send_report_email(
|
|
report_data,
|
|
recipients = [email.strip() for email in settings.MAIL_RECEIVER.split(",")])
|
|
logger.info(f"Report sent successfully")
|
|
return ResponseHelper.success(message="Report sent successfully",status_code=200)
|
|
except Exception as e:
|
|
logger.error(f"Error generating or sending report: {e}")
|
|
return ResponseHelper.error("Failed to send report", status_code=500, error=str(e))
|
|
|
|
|
|
@autocall_bp.route("/overdue-loans", methods=["GET"])
|
|
def overdue_loans():
|
|
try:
|
|
# Step 1: Get all overdue loans
|
|
loans = LoanService.get_overdue_loans()
|
|
logger.info(f"Found {len(loans)} overdue loans.")
|
|
|
|
if not loans:
|
|
return ResponseHelper.success(message="No overdue loans found", status_code=200)
|
|
|
|
# Step 2: Process each loan
|
|
for loan in loans:
|
|
process_overdue_loan(loan)
|
|
|
|
return ResponseHelper.success(message="Processed overdue loans successfully", status_code=200)
|
|
|
|
except Exception as e:
|
|
logger.error(f"Error fetching overdue loans: {e}")
|
|
return ResponseHelper.error("Failed to fetch overdue loans", status_code=500, error=str(e))
|
|
|
|
|
|
def process_overdue_loan(loan):
|
|
"""
|
|
Handles repayment creation, loan status update, and Simbrella call
|
|
for a single overdue loan.
|
|
"""
|
|
logger.info(f"Processing Loan ID: {loan.id}")
|
|
|
|
try:
|
|
repayment_data = {
|
|
"customerId": loan.customer_id,
|
|
"loanId": loan.id,
|
|
"productId": loan.product_id,
|
|
"transactionId": loan.transaction_id,
|
|
"initiatedBy": "SYSTEM", # To be reviewed
|
|
"salaryAmount": 0,
|
|
"LoanStatus": loan.status,
|
|
}
|
|
|
|
logger.info(f"Creating repayment with data: {repayment_data}")
|
|
repayment = RepaymentService.create_repayment(repayment_data)
|
|
|
|
if not repayment or (isinstance(repayment, dict) and "error" in repayment):
|
|
db.session.rollback() # important in case create_repayment failed mid-way
|
|
logger.error(f"Repayment creation failed for loan ID {loan.id}: {repayment}")
|
|
return
|
|
|
|
# Update loan status
|
|
try:
|
|
LoanService.update_status(loan_id=loan.id, status=LoanStatus.START_REPAY)
|
|
except Exception as e:
|
|
db.session.rollback()
|
|
logger.error(f"Failed to update loan status for loan ID {loan.id}: {e}")
|
|
|
|
logger.info(f"Created repayment ID: {repayment.id}")
|
|
|
|
# Step 3: Call Simbrella
|
|
try:
|
|
simbrella_response = SimbrellaClient.collect_loan_user_due_payment(repayment.to_dict())
|
|
|
|
if isinstance(simbrella_response, tuple):
|
|
simbrella_response, status_code = simbrella_response
|
|
logger.warning(f"Simbrella returned tuple: status={status_code}, response={simbrella_response}")
|
|
|
|
if isinstance(simbrella_response, dict):
|
|
if simbrella_response.get("status") != "success":
|
|
logger.warning(f"Simbrella failed for repayment ID {repayment.id}: {simbrella_response}")
|
|
else:
|
|
logger.warning(f"Unexpected Simbrella response: {type(simbrella_response)}")
|
|
|
|
except Exception as e:
|
|
logger.error(f"Failed to call Simbrella for repayment ID {repayment.id}: {e}")
|
|
|
|
except Exception as e:
|
|
db.session.rollback()
|
|
logger.error(f"Error creating repayment for loan ID {loan.id}: {e}")
|
|
|
|
finally:
|
|
logger.info(f"Finished processing loan ID: {loan.id}")
|