worked on balance

This commit was merged in pull request #31.
This commit is contained in:
Chinenye Nmoh
2025-06-24 22:21:58 +01:00
parent 35e4580313
commit 340132d8ad
3 changed files with 91 additions and 43 deletions
+56 -9
View File
@@ -240,19 +240,66 @@ class Loan(db.Model):
return customer_loans, total_amount
@classmethod
def update_status(cls, loan_id, status):
"""
Update the status of the loan with the given loan_id.
Update the status of the loan record with the given loan_id.
"""
# Retrieve loan
loan = cls.query.get(loan_id)
try:
# Retrieve loan record
loan = cls.query.get(loan_id)
if not loan:
raise ValueError(f"Loan with ID {loan_id} does not exist.")
if loan.status == status:
return loan.to_dict() # Still return the current state if no change
# Update status and timestamp
loan.status = status
loan.updated_at = datetime.now(timezone.utc)
db.session.commit()
if not loan:
raise ValueError(f"Loan with ID {loan_id} does not exist.")
logger.info("Loan status updated and committed.")
return loan.to_dict()
if loan.status == status:
return
except Exception as e:
db.session.rollback()
logger.error(f"Error updating loan status: {e}")
raise Exception(f"Error updating loan status: {str(e)}")
@classmethod
def update_loan_balance(cls, loan_id, amount_collected):
"""
Update the balance of a loan after successful repayment.
"""
try:
# Fetch the loan record
loan = cls.query.get(loan_id)
# Update loan status and the updated_at timestamp
loan.status = status
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")
if amount_collected > loan.balance:
raise ValueError("Repayment amount exceeds current loan balance.")
# Deduct the amount from the current balance
loan.balance -= amount_collected
loan.updated_at = datetime.now(timezone.utc)
db.session.commit()
logger.info(f"Loan balance updated for loan ID {loan_id}. New balance: {loan.balance}")
return loan.to_dict()
except Exception as e:
db.session.rollback()
logger.error(f"Error updating loan balance: {e}")
raise Exception(f"Error updating loan balance: {str(e)}")