debugging #34

Merged
ameye merged 1 commits from test into master 2025-06-26 20:11:58 +00:00
5 changed files with 144 additions and 90 deletions
+48 -41
View File
@@ -218,38 +218,29 @@ class SimbrellaClient:
logger.info(f"Calling CollectLoan api_url==> : {api_url}")
logger.info(f"Calling CollectLoan endpoint with data: {data}")
# Check if the repayment exists
logger.info(f"Checking if repayment exists")
repayment = RepaymentService.get_repayment_by_id(id=data['Id'])
logger.info(f"Repayment Response From Database ** : {repayment}")
if not repayment:
logger.info(f"Repayment with id: {data['Id']}, was not found")
logger.info(f"Repayment with id: {data['Id']} not found")
return ResponseHelper.error("Repayment not found")
logger.info(f"Repayment Response From Database ** : {repayment.to_dict()}")
repayment_data = repayment.to_dict()
loan = LoanService.get_loan_by_loan_id(loan_id=int(repayment_data['loanId']))
# If loan is not found
if loan is None:
logger.info(f"Loan with debtId: {repayment_data['loanId']}, was not found")
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 dict : {loan_data}")
logger.info(f"Loan data: {loan_data}")
if repayment_data['repayDate'] is not None:
logger.info(
f"Please call verify collection : {data['transactionId']} repayment send for processing at {repayment_data['repayDate']}")
logger.info(f"Repayment already processed at {repayment_data['repayDate']}")
return ResponseHelper.error("Repayment already processed")
# let us set repay date
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()
logger.info(f"Here is your repayment data after setting repay date: {repayment_data}")
debtId = str(loan_data.get('debtId', "")).strip().zfill(6)
debtId = str(loan_data.get('debtId', "")).strip().zfill(6)
collect_loan_data = {
"transactionId": loan_data['transactionId'],
"fbnTransactionId": loan_data['transactionId'],
@@ -258,7 +249,7 @@ class SimbrellaClient:
"accountId": loan_data['accountId'],
"productId": repayment_data['productId'],
"collectAmount": loan_data['repaymentAmount'] or 0,
"penalCharge": 5,
"penalCharge": 0,
"channel": "USSD",
"collectionMethod": collectionMethod,
"lienAmount": 0,
@@ -267,13 +258,21 @@ class SimbrellaClient:
}
try:
logger.info(f"Here is your CollectLoan Request data ***** : {collect_loan_data}")
response = requests.post(api_url, json=collect_loan_data,timeout=30, headers=get_headers())
logger.info(f"CollectLoan response: {response.json()}")
RepaymentService.set_repay_result(repayment_data['Id'], response.json().get('responseCode', ''), response.json().get('responseMessage', ''))
logger.info(f"Sending CollectLoan request: {collect_loan_data}")
response = requests.post(api_url, json=collect_loan_data, timeout=30, headers=get_headers())
result = response.json()
logger.info(f"this is the result {result}")
logger.info(f"CollectLoan response: {result}")
RepaymentService.set_repay_result(
repayment_data['Id'],
result.get('responseCode', ''),
result.get('responseMessage', '')
)
if not result.get('transactionId'):
logger.error("Missing transactionId in response")
return ResponseHelper.error("Missing transactionId from Simbrella response", status_code=500)
data_to_add = {
"transactionId": result.get('transactionId') or collect_loan_data.get('transactionId'),
"fbnTransactionId": result.get('fbnTransactionId') or collect_loan_data.get('fbnTransactionId'),
@@ -288,33 +287,40 @@ class SimbrellaClient:
new_repayment_data = RepaymentsData.add_repayment_data(data_to_add)
if new_repayment_data:
logger.info(f"Repayment data added successfully: {new_repayment_data.to_dict()}")
logger.info(f"Repayment data added: {new_repayment_data.to_dict()}")
else:
logger.warning("Failed to add repayment data")
# Process loan update only if successful
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}')
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} with amount collected: {amount_collected}")
updated_loan = LoanService.update_loan_balance(int(loan_data['debtId']), amount_collected)
except ValueError as ve:
logger.error(f"Validation error updating loan balance: {ve}")
return ResponseHelper.error(str(ve), status_code=400)
logger.info(f"Updated loan: {updated_loan}")
except Exception as ex:
logger.error(f"Unexpected error updating loan balance: {ex}")
return ResponseHelper.error("Unexpected error updating loan balance", status_code=500)
logger.error(f"Error updating loan balance for loan ID {loan.id}: {ex}")
return ResponseHelper.error("Error updating loan balance")
logger.info(f'updated loan {updated_loan}')
updated_balance = Decimal(str(updated_loan['balance'])).quantize(Decimal('0.01'))
logger.info(f'updated balance {updated_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'):
repaid = LoanService.update_status(updated_loan['debtId'], LoanStatus.REPAID)
logger.info(f'updated loan with repaid {repaid}')
else:
LoanService.update_status(updated_loan['debtId'], LoanStatus.ACTIVE_PARTIAL)
logger.info(f'updated loan with partial ')
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")
@@ -322,6 +328,7 @@ class SimbrellaClient:
logger.exception("Failed to call CollectLoan endpoint")
return ResponseHelper.error("Failed to call CollectLoan endpoint")
@staticmethod
def penal_charge(data):
+28 -14
View File
@@ -7,7 +7,9 @@ import logging
from sqlalchemy import and_, or_, not_
from sqlalchemy.sql import func
from app.utils.logger import logger
from app.extensions import db
from app.extensions import db
from decimal import Decimal, ROUND_HALF_UP
from datetime import datetime, timezone
class Loan(db.Model):
__tablename__ = "loans"
@@ -243,21 +245,29 @@ class Loan(db.Model):
return customer_loans, total_amount
@classmethod
def get_customer_active_loans(cls, customer_id):
def get_customer_active_loans(cls, customer_id):
"""
Get customer's active loans and sum by customer_id.
"""
customer_loans = cls.query.filter_by( customer_id = customer_id, status='active').all()
customer_loans = cls.query.filter(
cls.customer_id == customer_id,
cls.status != 'repaid'
).all()
if not customer_loans:
raise ValueError(f"Customer with Id {customer_id} does not have any active loan.")
total_amount = (
cls.query.with_entities(func.coalesce(func.sum(cls.balance), 0.0))
.filter_by(customer_id=customer_id)
.scalar()
cls.query
.with_entities(func.coalesce(func.sum(cls.balance), 0.0))
.filter(
cls.customer_id == customer_id,
cls.status != 'repaid'
)
.scalar()
)
logger.info(f"Found {len(customer_loans)} loans for customer ID: {customer_id} with total amount: {total_amount}")
logger.info(f"Found {len(customer_loans)} active loans for customer ID: {customer_id} with total amount: {total_amount}")
return customer_loans, total_amount
@@ -303,17 +313,21 @@ class Loan(db.Model):
if not loan:
raise ValueError(f"Loan with ID {loan_id} does not exist.")
# Ensure valid repayment amount
if amount_collected <= 0:
raise ValueError("Repayment amount must be greater than zero.")
if loan.balance is None:
raise ValueError("There is no balance for this loan")
# Convert to Decimal and round to 2 decimal places
amount_collected = Decimal(str(amount_collected)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
balance = Decimal(str(loan.balance or 0)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
if amount_collected > loan.balance:
# Ensure valid repayment amount
if amount_collected <= Decimal("0.00"):
raise ValueError("Repayment amount must be greater than zero.")
if balance <= Decimal("0.00"):
raise ValueError("There is no balance for this loan.")
if amount_collected > balance:
raise ValueError("Repayment amount exceeds current loan balance.")
# Deduct the amount from the current balance
loan.balance -= float(amount_collected)
new_balance = balance - amount_collected
loan.balance = float(new_balance)
loan.updated_at = datetime.now(timezone.utc)
db.session.commit()
+17 -8
View File
@@ -42,9 +42,13 @@ class RepaymentsData(db.Model):
Add a new repayment data entry.
"""
try:
repaymentAmount = data.get('repaymentAmount', 0.0)
amountCollected = data.get('amountCollected',0.0)
accountBalance = repaymentAmount - amountCollected
repayment_amount = float(data.get('repaymentAmount', 0.0))
amount_collected = float(data.get('amountCollected', 0.0))
if amount_collected < 0 or repayment_amount < 0:
raise ValueError("Amounts cannot be negative.")
account_balance = round(repayment_amount - amount_collected, 2)
new_data = cls(
transaction_id=data.get('transactionId'),
@@ -53,14 +57,19 @@ class RepaymentsData(db.Model):
fbn_transaction_id=data.get('fbnTransactionId'),
account_id=data.get('accountId'),
customer_id=data.get('customerId'),
amount_collected=amountCollected,
repayment_amount=repaymentAmount,
balance=round(float(accountBalance), 2)
amount_collected=amount_collected,
repayment_amount=repayment_amount,
balance=account_balance,
)
db.session.add(new_data)
db.session.commit()
logger.info(f"data has been commited ")
logger.info("Repayment data committed successfully")
return new_data
except Exception as e:
db.session.rollback()
raise Exception(f"Error adding repayment data: {str(e)}")
logger.error(f"Error adding repayment data: {e}")
raise Exception(f"Error adding repayment data: {str(e)}")
+50 -26
View File
@@ -124,22 +124,27 @@ def salary_detect():
if payload is None:
logger.warning("No payload received in request")
#- Sometimes no paylod return ResponseHelper.error("Missing request payload", status_code=400)
return ResponseHelper.error("Missing request payload", status_code=400)
if payload:
# 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 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}")
process_salary_list() # TODO - This should be threaded out or removed from here finally
# Step 2: Try processing salary list
try:
process_salary_list()
except Exception as e:
logger.exception("Unhandled error occurred while processing salary list")
return ResponseHelper.error("Failed to process salary list", status_code=500, error=str(e))
logger.info(f"Finished processing List")
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()
@@ -147,7 +152,7 @@ def salary_process():
def process_salary_list():
# Step 2: Get all pending salaries
# Step 1: Get all pending salaries
pending_salaries = SalaryService.get_pending_salaries()
if not pending_salaries:
logger.info("No pending salaries found")
@@ -155,18 +160,17 @@ def process_salary_list():
logger.info(f"Found {len(pending_salaries)} pending salaries to process")
# Step 3: Process each salary
for pending_salary in pending_salaries:
logger.info(f"Processing salary ID: {pending_salary.id}")
# Step 3.1: Update status to PROCESSING
# Step 2: Update salary status to PROCESSING
try:
SalaryService.update_status(pending_salary.id, "PROCESSING")
except Exception as e:
logger.warning(f"Could not update status for salary ID {pending_salary.id}: {e}")
continue
# Step 3.2: Get loans
# Step 3: Get customer's active loans
try:
loans, total_amount = LoanService.get_customer_active_loans(pending_salary.customer_id)
if not loans:
@@ -176,12 +180,10 @@ def process_salary_list():
logger.error(f"Error fetching loans for customer ID {pending_salary.customer_id}: {e}")
continue
# Step 3.3: Create repayments
# Step 4: Create repayments for each loan
for loan in loans:
logger.info(f"Loan LOOP LoanID = :{loan.id}")
logger.info(f"Processing Loan ID: {loan.id}")
try:
# loan_dict = loan.to_dict()
logger.info(f"loan_dict ==== Repayment Data:{loan}")
repayment_data = {
"customerId": loan.customer_id,
"loanId": loan.id,
@@ -192,21 +194,43 @@ def process_salary_list():
"LoanStatus": loan.status,
}
logger.info(f"Saving/Creating Repayment Data:{repayment_data}")
logger.info(f"Creating repayment with data: {repayment_data}")
repayment = RepaymentService.create_repayment(repayment_data)
LoanService.update_status(loan_id=repayment_data["loanId"],
status=LoanStatus.START_REPAY) # repay started
if not repayment:
logger.error(f"Repayment creation failed for loan ID {loan.id}")
continue
# Update loan status to START_REPAY
try:
LoanService.update_status(loan_id=loan.id, status=LoanStatus.START_REPAY)
except Exception as e:
logger.error(f"Failed to update loan status for loan ID {loan.id}: {e}")
logger.info(f"Created repayment ID: {repayment.id}")
except Exception as e:
logger.error(f"Error creating repayment for loan ID {loan.id}: {e}")
continue
# Step 4: Simbrella integration call after all processing
# Step 5: Call Simbrella to collect loan
try:
SimbrellaClient.collect_loan_user_salary_detect(repayment.to_dict())
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):
status = simbrella_response.get("status")
if status != "success":
logger.warning(f"Simbrella call failed for repayment ID {repayment.id}: {simbrella_response}")
else:
logger.warning(f"Unexpected Simbrella response type: {type(simbrella_response)}")
except Exception as e:
logger.error(f"Failed to call Simbrella client: {e}")
logger.error(f"Failed to call Simbrella for repayment ID {repayment.id}: {e}")
logger.info(f"Finished processing salary ID: {pending_salary.id}")
return []
return ResponseHelper.success([], "Processed all pending salaries")
+1 -1
View File
@@ -84,7 +84,7 @@ class LoanService:
Get customer's active loans by customer_id.
"""
return Loan.get_customer_loans(customer_id=customer_id)
return Loan.get_customer_active_loans(customer_id=customer_id)
@classmethod
def update_status(cls, loan_id, status):