added repayment_schedule
This commit is contained in:
@@ -274,7 +274,11 @@ class SimbrellaClient:
|
||||
"customerId": repayment_data['customerId'],
|
||||
"accountId": loan_data['accountId'],
|
||||
"productId": repayment_data['productId'],
|
||||
"collectAmount": loan_data['balance'] or 0,
|
||||
"collectAmount": (
|
||||
data['overdueLoanScheduleAmount']
|
||||
if data.get('overdueLoanScheduleAmount') is not None
|
||||
else loan_data.get('balance', 0)
|
||||
),
|
||||
"penalCharge": 0,
|
||||
"channel": "USSD",
|
||||
"collectionMethod": collectionMethod,
|
||||
@@ -353,12 +357,45 @@ class SimbrellaClient:
|
||||
repaid = LoanService.update_status(updated_loan['debtId'], LoanStatus.REPAID)
|
||||
logger.info(f'Updated loan with repaid status: {repaid}')
|
||||
updated_loan = 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}')
|
||||
updated_loan = partial
|
||||
|
||||
try:
|
||||
schedule_to_update = LoanRepaymentScheduleService.get_repayment_schedule_by_id_and_transaction_id(
|
||||
data["overdueLoanScheduleId"], data["transactionId"]
|
||||
)
|
||||
logger.info(f"Schedule to update: {schedule_to_update}")
|
||||
|
||||
if schedule_to_update is None:
|
||||
logger.warning(
|
||||
f"Repayment schedule not found for ID {data['overdueLoanScheduleId']} "
|
||||
f"and transaction ID {loan_data['transactionId']}"
|
||||
)
|
||||
else:
|
||||
# Use DB installment amount as the reference
|
||||
installment_amount = Decimal(str(schedule_to_update.installment_amount)).quantize(Decimal("0.01"))
|
||||
|
||||
if amount_collected >= installment_amount:
|
||||
LoanRepaymentScheduleService.update_repayment_schedule_status(
|
||||
schedule_to_update.id, paid=True)
|
||||
logger.info(
|
||||
f"Installment {data['overdueLoanScheduleId']} fully covered "
|
||||
f"with {amount_collected}, marked as paid"
|
||||
)
|
||||
else:
|
||||
logger.info(
|
||||
f"Installment {data['overdueLoanScheduleId']} not fully covered. "
|
||||
f"Collected={amount_collected}, "
|
||||
f"Installment={installment_amount}"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to update repayment schedule installment: {e}")
|
||||
|
||||
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
logger.error(f"Error while updating loan status for debtId {updated_loan['debtId']}: {e}")
|
||||
|
||||
@@ -55,8 +55,28 @@ class LoanRepaymentSchedule(db.Model):
|
||||
except Exception as e:
|
||||
logger.error(f"Error fetching repayment schedule for loan_id={loan_id}: {e}")
|
||||
return []
|
||||
@classmethod
|
||||
def get_repayment_schedule_by_id_and_transaction_id(cls, id, transaction_id):
|
||||
"""
|
||||
Get repayment schedule by ID and transaction ID
|
||||
"""
|
||||
try:
|
||||
return cls.query.filter_by(id=id, transaction_id=transaction_id).first()
|
||||
except Exception as e:
|
||||
logger.error(f"Error fetching repayment schedule for id={id}, transaction_id={transaction_id}: {e}")
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def get_overdue_repayment_schedule(cls):
|
||||
"""
|
||||
Get all overdue repayment schedules.
|
||||
"""
|
||||
try:
|
||||
return cls.query.filter(cls.due_date < datetime.now(timezone.utc), cls.paid == False).all()
|
||||
except Exception as e:
|
||||
logger.error(f"Error fetching overdue repayment schedules: {e}")
|
||||
return []
|
||||
|
||||
|
||||
@classmethod
|
||||
def get_repayment_schedule_by_transaction_id(cls, transaction_id):
|
||||
"""
|
||||
|
||||
+65
-52
@@ -9,6 +9,7 @@ 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.services.loan_repayment_schedule import LoanRepaymentScheduleService
|
||||
from app.enums.loan_status import LoanStatus
|
||||
from app.utils.mail import send_report_email, get_report_data
|
||||
from app.config import settings
|
||||
@@ -262,14 +263,14 @@ def report():
|
||||
def overdue_loans():
|
||||
try:
|
||||
# Step 1: Get all overdue loans
|
||||
loans = LoanService.get_overdue_loans()
|
||||
logger.info(f"Found {len(loans)} overdue loans.")
|
||||
overdue_loans = LoanRepaymentScheduleService.get_overdue_repayment_schedule()
|
||||
logger.info(f"Found {len(overdue_loans)} overdue loans.")
|
||||
|
||||
if not loans:
|
||||
if not overdue_loans:
|
||||
return ResponseHelper.success(message="No overdue loans found", status_code=200)
|
||||
|
||||
# Step 2: Process each loan
|
||||
for loan in loans:
|
||||
for loan in overdue_loans:
|
||||
process_overdue_loan(loan)
|
||||
|
||||
return ResponseHelper.success(message="Processed overdue loans successfully", status_code=200)
|
||||
@@ -284,56 +285,68 @@ 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}")
|
||||
logger.info(f"Processing Loan ID: {loan.loan_id}")
|
||||
full_loan_data = LoanService.get_loan_by_loan_id(loan.loan_id)
|
||||
logger.info(f"full loan details: {full_loan_data.to_dict()}")
|
||||
if not full_loan_data:
|
||||
logger.warning(f"Full Loan ID {loan.loan_id} not found in database")
|
||||
else:
|
||||
|
||||
customer_id = full_loan_data.to_dict().get("customerId")
|
||||
loan_status = full_loan_data.to_dict().get("status")
|
||||
|
||||
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)
|
||||
repayment_data = {
|
||||
"customerId": customer_id,
|
||||
"loanId": loan.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.loan_id}: {repayment}")
|
||||
return
|
||||
|
||||
# Update loan status
|
||||
try:
|
||||
LoanService.update_status(loan_id=loan.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.loan_id}: {e}")
|
||||
|
||||
logger.info(f"Created repayment ID: {repayment.id}")
|
||||
|
||||
# Step 3: Call Simbrella
|
||||
try:
|
||||
#lets add the overdue loan schedule id and amount we are currently processing to the repayment data
|
||||
repayment_data["overdueLoanScheduleId"] = loan.id
|
||||
repayment_data["overdueLoanScheduleAmount"] = loan.installment_amount
|
||||
repayment_data["Id"] = repayment.id
|
||||
simbrella_response = SimbrellaClient.collect_loan_user_due_payment(repayment_data)
|
||||
|
||||
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"Failed to update loan status for loan ID {loan.id}: {e}")
|
||||
logger.error(f"Error creating repayment 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}")
|
||||
finally:
|
||||
logger.info(f"Finished processing loan ID: {loan.id}")
|
||||
|
||||
@@ -6,6 +6,12 @@ class LoanRepaymentScheduleService:
|
||||
@classmethod
|
||||
def get_repayment_schedule_by_loan_id(cls, loan_id):
|
||||
return LoanRepaymentSchedule.get_repayment_schedule_by_loan_id(loan_id)
|
||||
@classmethod
|
||||
def get_overdue_repayment_schedule(cls):
|
||||
return LoanRepaymentSchedule.get_overdue_repayment_schedule()
|
||||
@classmethod
|
||||
def get_repayment_schedule_by_id_and_transaction_id(cls, id, transaction_id):
|
||||
return LoanRepaymentSchedule.get_repayment_schedule_by_id_and_transaction_id(id, transaction_id)
|
||||
|
||||
@classmethod
|
||||
def get_repayment_schedule_by_transaction_id(cls, transaction_id):
|
||||
|
||||
Reference in New Issue
Block a user