25 Commits

Author SHA1 Message Date
VivianDee 9831395e2a [add]: balance when calculating loan total 2025-06-25 08:23:11 +01:00
ameye aa408cc720 Merge branch 'test' of DigiFi/digifi-EventManager into master 2025-06-23 10:42:04 +00:00
Chinenye Nmoh 35e4580313 changed balance to 2 decimal place 2025-06-23 11:09:28 +01:00
CHIEFSOFT\ameye 3d62cbc157 Loan status 2025-06-22 21:50:18 -04:00
CHIEFSOFT\ameye 3785196fb7 salary process apart 2025-06-21 11:55:54 -04:00
CHIEFSOFT\ameye 8249a1b6d8 kafka collect error 2025-06-21 11:11:45 -04:00
CHIEFSOFT\ameye caa77191c7 balace onm payment 2025-06-21 10:43:31 -04:00
CHIEFSOFT\ameye 3f1d87b88a Loan status fix 2025-06-20 22:31:15 -04:00
CHIEFSOFT\ameye 42a3b0fd73 except Exception as e: 2025-06-20 21:55:07 -04:00
CHIEFSOFT\ameye 43055ad010 LoanStatus 2025-06-20 21:51:43 -04:00
CHIEFSOFT\ameye 114a089bdb ["LoanStatus"] 2025-06-20 21:37:20 -04:00
CHIEFSOFT\ameye 48fb58c6ab repayment_data 2025-06-20 21:35:05 -04:00
CHIEFSOFT\ameye 306221f502 repayment_data.LoanStatus 2025-06-20 21:27:53 -04:00
CHIEFSOFT\ameye a310709c5e repayment bug 2025-06-20 21:24:14 -04:00
CHIEFSOFT\ameye a1b1caf5d7 variable bug 2025-06-20 21:22:06 -04:00
CHIEFSOFT\ameye b88a09376b loid 2025-06-20 21:19:33 -04:00
CHIEFSOFT\ameye ee077fb380 loan id 2025-06-20 20:52:08 -04:00
CHIEFSOFT\ameye 4e23ea4e91 customerId 2025-06-20 20:48:44 -04:00
CHIEFSOFT\ameye cb4383c10b loan_dict 2025-06-20 20:46:49 -04:00
CHIEFSOFT\ameye e9c29a8743 "customerId": loan_dict["customer_id"], 2025-06-20 20:45:08 -04:00
CHIEFSOFT\ameye 08a0c8a933 Repayment data 2025-06-20 20:39:37 -04:00
CHIEFSOFT\ameye 6200fc4dba fix ID 2025-06-20 20:23:05 -04:00
CHIEFSOFT\ameye 0d2ce16ff5 enums 2025-06-20 15:48:29 -04:00
CHIEFSOFT\ameye 7b21140b39 Repayment updates 2025-06-20 15:18:04 -04:00
ameye 190cd6611a Merge branch 'add_total_amount' of DigiFi/digifi-EventManager into master 2025-06-20 16:28:39 +00:00
12 changed files with 145 additions and 30 deletions
+2
View File
@@ -0,0 +1,2 @@
from .transaction_type import TransactionType
from .loan_status import LoanStatus
+8
View File
@@ -0,0 +1,8 @@
from enum import Enum
class LoanStatus(str, Enum):
PENDING = "pending"
ACTIVE = "active"
ACTIVE_PARTIAL = "active_partial"
START_REPAY = "start_repay"
REPAID = "repaid"
+10
View File
@@ -0,0 +1,10 @@
from enum import Enum
class TransactionType(str, Enum):
ELIGIBILITY_CHECK = "eligibility_check"
CUSTOMER_CONSENT = "customer_consent"
LOAN_STATUS = "loan_status"
NOTIFICATION_CALLBACK = "notification_callback"
PROVIDE_LOAN = "provide_loan"
REPAYMENT = "repayment"
SELECT_OFFER = "select_offer"
+2 -1
View File
@@ -146,10 +146,11 @@ class KafkaIntegration:
logger.info(f"Calling collect_loan service with message: {message}")
try:
#Calling CollectLoan endpoint with data: {'transactionId': 'TRCVIC85641527829', 'customerId': 'ZX48440946', 'productId': 'AMPC', 'loanRef': 'TRCVIC85641527829USSDAMPC', 'debtId': '014231'}
response = SimbrellaClient.collect_loan_user_initiated(message)
logger.info(
f"Successfully sent message to collect_loan service: {response}"
)
except Exception as e:
logger.info(f"Failed to call collect_loan service: {e}")
logger.error(f"Failed to call collect_loan service: {e}")
# raise
+11 -2
View File
@@ -181,8 +181,17 @@ class SimbrellaClient:
@staticmethod
def collect_loan_user_initiated(data):
# InitiatedBy = USER_INITIATED
logger.info(f"Calling CollectLoan collect_loan_user_initiated ******* endpoint with data: {data}")
return SimbrellaClient._collect_loan(data,"1")
try:
logger.info(f"Calling CollectLoan collect_loan_user_initiated ******* endpoint with data: {data}")
return SimbrellaClient._collect_loan(data, "1")
except Exception as e:
logger.error(f"Error in collect_loan_user_initiated: {e}")
# return ResponseHelper.error(
# message="Failed to collect loan for user initiated ",
# status_code=500,
# error=str(e)
# )
@staticmethod
def collect_loan_user_salary_detect(data):
try:
+22 -3
View File
@@ -30,6 +30,7 @@ class Loan(db.Model):
continuous_fee = db.Column(db.Float, default=0)
upfront_fee = db.Column(db.Float, nullable=True, default=0.0)
repayment_amount = db.Column(db.Float, nullable=True, default=0.0)
balance = db.Column(db.Float, nullable=True, default=0.0)
installment_amount = db.Column(db.Float, nullable=True, default=0.0)
status = db.Column(db.String(20), default='pending')
tenor = db.Column(db.Integer, nullable=True)
@@ -230,11 +231,29 @@ class Loan(db.Model):
raise ValueError(f"Customer with Id {customer_id} does not have any loan.")
total_amount = (
db.session.query(func.coalesce(func.sum(cls.current_loan_amount), 0.0))
cls.query.with_entities(func.coalesce(func.sum(cls.balance), 0.0))
.filter_by(customer_id=customer_id)
.scalar()
)
)
logger.info(f"Found {len(customer_loans)} loans for customer ID: {customer_id} with total amount: {total_amount}")
return customer_loans, total_amount
return customer_loans, total_amount
@classmethod
def update_status(cls, loan_id, status):
"""
Update the status of the loan with the given loan_id.
"""
# Retrieve loan
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
# Update loan status and the updated_at timestamp
loan.status = status
+27
View File
@@ -1,6 +1,7 @@
from app.extensions import db
from datetime import datetime, timezone
from app.utils.logger import logger
from app.enums.loan_status import LoanStatus
class Repayment(db.Model):
__tablename__ = "repayments"
@@ -47,6 +48,32 @@ class Repayment(db.Model):
'VerifyDate': self.verify_date.isoformat() if self.verify_date else None,
}
@classmethod
def create_repayment(cls, repayment_data):
if repayment_data["LoanStatus"] not in [LoanStatus.ACTIVE, LoanStatus.START_REPAY]:
raise ValueError(f"Repayment cannot be processed. Loan status: ({repayment_data['LoanStatus']})")
repayment = cls(
customer_id=repayment_data["customerId"],
loan_id=repayment_data["loanId"],
product_id=repayment_data["productId"],
transaction_id=repayment_data["transactionId"],
created_at=datetime.now(timezone.utc),
updated_at=datetime.now(timezone.utc),
initiated_by= repayment_data["initiatedBy"],
salary_amount=repayment_data["salaryAmount"]
)
try:
db.session.add(repayment)
db.session.commit()
logger.info("Repayment record committed.")
return repayment
except InqtegrityError as err:
logger.error(f"Database integrity error: {err}")
return [q]
@classmethod
def add_repayment(cls, data: dict):
+7 -2
View File
@@ -42,6 +42,10 @@ 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
new_data = cls(
transaction_id=data.get('transactionId'),
response_code=data.get('responseCode'),
@@ -49,8 +53,9 @@ class RepaymentsData(db.Model):
fbn_transaction_id=data.get('fbnTransactionId'),
account_id=data.get('accountId'),
customer_id=data.get('customerId'),
amount_collected=data.get('amountCollected'),
repayment_amount=data.get('repaymentAmount'),
amount_collected=amountCollected,
repayment_amount=repaymentAmount,
balance=round(float(accountBalance), 2)
)
db.session.add(new_data)
db.session.commit()
+1 -1
View File
@@ -41,7 +41,7 @@ class Salary(db.Model):
"""
Add a new salary data entry.
"""
logger.info(f"receieved data:{data}")
logger.info(f"Received data:{data}")
try:
new_data = cls(
customer_id=data.get('customerId'),
+38 -20
View File
@@ -8,6 +8,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.enums.loan_status import LoanStatus
autocall_bp = Blueprint("autocall", __name__)
@@ -123,16 +124,29 @@ def salary_detect():
if payload is None:
logger.warning("No payload received in request")
return ResponseHelper.error("Missing request payload", status_code=400)
#- Sometimes no paylod 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)
if new_salary:
logger.info(f"Salary added: {new_salary.id}")
except Exception as e:
logger.error(f"Failed to save salary: {e}")
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}")
process_salary_list() # TODO - This should be threaded out or removed from here finally
logger.info(f"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 2: Get all pending salaries
pending_salaries = SalaryService.get_pending_salaries()
if not pending_salaries:
@@ -164,31 +178,35 @@ def salary_detect():
# Step 3.3: Create repayments
for loan in loans:
logger.info(f"Loan LOOP LoanID = :{loan.id}")
try:
loan_dict = loan.to_dict()
# loan_dict = loan.to_dict()
logger.info(f"loan_dict ==== Repayment Data:{loan}")
repayment_data = {
"customerId": pending_salary.customer_id,
"loanId": loan_dict["debtId"],
"productId": loan_dict["productId"],
"transactionId": loan_dict["transactionId"],
"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 for loan ID {loan_dict['debtId']}")
repayment = RepaymentService.add_repayment(repayment_data)
logger.info(f"Saving/Creating Repayment Data:{repayment_data}")
repayment = RepaymentService.create_repayment(repayment_data)
LoanService.update_status(loan_id=repayment_data["loanId"],
status=LoanStatus.START_REPAY) # repay started
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 4: Simbrella integration call after all processing
try:
SimbrellaClient.collect_loan_user_salary_detect(repayment.to_dict())
except Exception as e:
logger.error(f"Failed to call Simbrella client: {e}")
logger.info(f"Finished processing salary ID: {pending_salary.id}")
return ResponseHelper.success([], "AutoCall Successful")
return []
+8
View File
@@ -78,3 +78,11 @@ class LoanService:
"""
return Loan.get_customer_loans(customer_id=customer_id)
@classmethod
def update_status(cls, loan_id, status):
"""
Update the status of the loan with the given loan_id.
"""
# Retrieve loan
return Loan.update_status(loan_id, status)
+9 -1
View File
@@ -62,9 +62,17 @@ class RepaymentService:
Get the latest repayment with a repay date and no verification date.
"""
return Repayment.get_latest_loan_with_repay_date()
@classmethod
def add_repayment(cls, data):
"""
Add a new repayment entry.
"""
return Repayment.add_repayment(data)
return Repayment.add_repayment(data)
@classmethod
def create_repayment(cls, repayment_data):
"""
Add a new repayment entry.
"""
return Repayment.create_repayment(repayment_data)