33 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
VivianDee c550c8c356 [add]: loan total amount 2025-06-20 15:58:53 +01:00
ameye 3cf6c94786 Merge branch 'test' of DigiFi/digifi-EventManager into master 2025-06-20 13:30:08 +00:00
Chinenye Nmoh 79b22e6d4f changed amount to salaryAmount 2025-06-20 13:49:10 +01:00
ameye 1d0409d072 Merge branch 'test' of DigiFi/digifi-EventManager into master 2025-06-20 10:52:31 +00:00
Chinenye Nmoh bcd9513a10 added loop 2025-06-20 11:47:21 +01:00
Chinenye Nmoh 684833bd66 added loop 2025-06-19 23:23:06 +01:00
Chinenye Nmoh 7fbb659fc6 added salary table 2025-06-19 21:30:21 +01:00
vivian.d.simbrellang.com 3be765bf41 Merge branch 'pending_salaries' of DigiFi/digifi-EventManager into master 2025-06-19 12:25:26 +00:00
14 changed files with 333 additions and 75 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
+25 -22
View File
@@ -181,45 +181,48 @@ 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):
#InitiatedBy = SALARY_DETECT
# logger.info(f"salary data: {data}")
# try:
# salary = SalaryService.add_salary_data(data)
# if salary:
# return ResponseHelper.success(salary.to_dict(), "Successful")
#
# except Exception as e:
# logger.info(f"Failed to save salary: {e}")
# return ResponseHelper.error(message="Failed to call salary endpoint",
# status_code=400,
# error=str(e) )
return SimbrellaClient._collect_loan(data,2)
try:
return SimbrellaClient._collect_loan(data, "2")
except Exception as e:
logger.error(f"Error in collect_loan_user_salary_detect: {e}")
return ResponseHelper.error(
message="Failed to collect loan for salary detection",
status_code=500,
error=str(e)
)
@staticmethod
def collect_loan_user_due_payment(data):
# InitiatedBy = REPAYMENT_DUE
return SimbrellaClient._collect_loan(data,3)
return SimbrellaClient._collect_loan(data,"3")
@staticmethod
def _collect_loan(data, collectionMethod: int):
def _collect_loan(data, collectionMethod: str):
api_url = f"{SimbrellaClient.BANK_CALL_BASE_URL}{SimbrellaClient.BANK_CALL_COLLECT_LOAN_ENDPOINT}"
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_transaction_id(transaction_id=data['transactionId'])
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 transactionId: {data['transactionId']}, was not found")
logger.info(f"Repayment with id: {data['Id']}, was not found")
return ResponseHelper.error("Repayment not found")
logger.info(f"Repayment Response From Database ** : {repayment.to_dict()}")
repayment_data = repayment.to_dict()
@@ -252,7 +255,7 @@ class SimbrellaClient:
"customerId": repayment_data['customerId'],
"accountId": loan_data['accountId'],
"productId": repayment_data['productId'],
"collectAmount": loan_data['repaymentAmount'],
"collectAmount": loan_data['repaymentAmount'] or 0,
"penalCharge": 5,
"channel": "USSD",
"collectionMethod": collectionMethod,
@@ -263,7 +266,7 @@ class SimbrellaClient:
try:
logger.info(f"Here is your CollectLoan Request data ***** : {collect_loan_data}")
response = requests.post(api_url, json=collect_loan_data, headers=get_headers())
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', ''))
+39 -1
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)
@@ -218,4 +219,41 @@ class Loan(db.Model):
return cls.query.filter(
cls.disburse_date.isnot(None),
cls.disburse_verify.is_(None)
).order_by(cls.created_at.desc()).first()
).order_by(cls.created_at.desc()).first()
@classmethod
def get_customer_loans(cls, customer_id):
"""
Get customer's active loans and sum by customer_id.
"""
customer_loans = cls.query.filter_by( customer_id = customer_id).all()
if not customer_loans:
raise ValueError(f"Customer with Id {customer_id} does not have any loan.")
total_amount = (
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
@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
+75
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"
@@ -14,6 +15,8 @@ class Repayment(db.Model):
customer_id = db.Column(db.String(50), nullable=False)
product_id = db.Column(db.String(20), nullable=True)
transaction_id = db.Column(db.String(50), nullable=False)
initiated_by = db.Column(db.String(50), nullable=True)
salary_amount = db.Column(db.Float, nullable=True, default=0.0)
created_at = db.Column(db.DateTime, default=datetime.now(timezone.utc))
updated_at = db.Column(db.DateTime, default=datetime.now(timezone.utc), onupdate=datetime.now(timezone.utc))
repay_date = db.Column(db.DateTime, nullable=True)
@@ -39,15 +42,87 @@ class Repayment(db.Model):
'verifyResult': self.verify_result,
'verifyDescription': self.verify_description,
'transactionId': self.transaction_id,
'initiatedBy':self.initiated_by,
'salaryAmount':self.salary_amount,
'repayDate': self.repay_date.isoformat() if self.repay_date else None,
'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):
"""
Create and persist a new repayment record.
"""
logger.info(f"Received repayment data: {data}")
try:
new_repayment = cls(
loan_id=data["loanId"],
customer_id=data["customerId"],
product_id=data.get("productId"),
transaction_id=data["transactionId"],
initiated_by=data.get("initiatedBy"),
salary_amount=float(data.get("salaryAmount", 0.0)),
repay_date=(
datetime.strptime(data["repayDate"], "%Y-%m-%d")
.replace(tzinfo=timezone.utc)
if data.get("repayDate")
else None
),
repay_result=data.get("repayResult"),
repay_description=data.get("repayDescription"),
verify_result=data.get("verifyResult"),
verify_description=data.get("verifyDescription"),
verify_date=(
datetime.strptime(data["verifyDate"], "%Y-%m-%d")
.replace(tzinfo=timezone.utc)
if data.get("verifyDate")
else None
),
)
db.session.add(new_repayment)
db.session.commit()
logger.info("Repayment record committed.")
return new_repayment
except Exception as e:
db.session.rollback()
logger.error(f"Error adding repayment data: {e}")
raise
@classmethod
def get_repayment_by_transaction_id(cls, transaction_id):
return cls.query.filter_by(transaction_id=transaction_id).first()
@classmethod
def get_repayment_by_id(cls, id):
return cls.query.filter_by(id=id).first()
@classmethod
def set_repay_date(cls, repayment_id, customer_id):
+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()
+29 -2
View File
@@ -29,7 +29,7 @@ class Salary(db.Model):
'id': self.id,
'customerId': self.customer_id,
'accountId' : self.account_id,
'amount': self.amount,
'salaryAmount': self.amount,
'status': self.status,
'createdAt': self.created_at.isoformat() if self.created_at else None,
'updatedAt': self.updated_at.isoformat() if self.updated_at else None,
@@ -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'),
@@ -69,3 +69,30 @@ class Salary(db.Model):
except Exception as e:
logger.error(f"Error fetching pending salaries: {str(e)}")
return []
@classmethod
def update_status(cls, salary_id, status):
"""
Update the status of the salary record with the given salary_id.
"""
try:
# Retrieve salary record
salary = cls.query.get(salary_id)
if not salary:
raise ValueError(f"Salary with ID {salary_id} does not exist.")
if salary.status == status:
return salary.to_dict() # Still return the current state if no change
# Update status and timestamp
salary.status = status
salary.updated_at = datetime.now(timezone.utc) # Manually update timestamp if not auto-updating
db.session.commit()
logger.info("Salary status updated and committed.")
return salary.to_dict()
except Exception as e:
db.session.rollback()
logger.error(f"Error updating salary status: {e}")
raise Exception(f"Error updating salary status: {str(e)}")
+91 -44
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__)
@@ -75,7 +76,7 @@ def refresh_collection():
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 disbursement date")
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()
@@ -86,6 +87,7 @@ def refresh_collection():
"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")
@@ -105,61 +107,106 @@ def payment_callback():
@autocall_bp.route("/penal-charge", methods=["POST"])
def penal_charge():
data = request.get_json()
logger.info(f"Calling Penal Charge Endpoints")
logger.info(f"Calling Penal Charge Endpoint")
response = SimbrellaClient.penal_charge(data[0])
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")
return response
@autocall_bp.route("/analytic-salary-detect", methods=["POST"])
def salary_detect():
#***************************************************
# PART 1 Accept any new import of salary detection
#**************************************************
data = request.get_json()
logger.info(f"Calling Salary Detect Endpoints")
payload = request.get_json()
logger.info("Calling Salary Detect endpoint")
try:
salary = SalaryService.add_salary_data(data)
if salary:
logger.info(f"Successful Salary Added")
# return ResponseHelper.success(salary.to_dict(), "Successful")
except Exception as e:
logger.info(f"Failed to save salary: {e}")
if payload is None:
logger.warning("No payload received in request")
#- Sometimes no paylod return ResponseHelper.error("Missing request payload", status_code=400)
# ***************************************************
# PART 2 SELECT * FROM salaries WHERE status IS 'START' ORDER BY id ASC
# **************************************************
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:
logger.info(f"No pending salaries found")
# return ResponseHelper.success([], "No pending salaries found")
logger.info("No pending salaries found")
return ResponseHelper.success([], "No pending salaries")
logger.info(f"Found {len(pending_salaries)} pending salaries")
logger.info(f"Found {len(pending_salaries)} pending salaries to process")
#in the loop
# USE the customerID to find thu user Loan
# if loan is/are found for the user
# INSERT INTO repayments TABLE
# repayment = cls(
# customer_id=customer_id,
# loan_id=loan.id,
# product_id=loan.product_id,
# transaction_id = transaction_id,
# created_at=datetime.now(timezone.utc),
# updated_at=datetime.now(timezone.utc),
# initiated_by='SALARY_DETECT'
# )
# Step 3: Process each salary
for pending_salary in pending_salaries:
logger.info(f"Processing salary ID: {pending_salary.id}")
# by the time you call this you must be on repayment table
try:
SimbrellaClient.collect_loan_user_salary_detect(data)
except Exception as e:
logger.info(f"Failed to call collect_loan_user_salary_detect: {e}")
# Step 3.1: Update 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
return_data=[]
# Step 3.2: Get loans
try:
loans, total_amount = LoanService.get_customer_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:
logger.error(f"Error fetching loans for customer ID {pending_salary.customer_id}: {e}")
continue
# Step 3.3: Create repayments
for loan in loans:
logger.info(f"Loan LOOP LoanID = :{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,
"productId": loan.product_id,
"transactionId": loan.transaction_id,
"initiatedBy": "SALARY_DETECT",
"salaryAmount": pending_salary.amount,
"LoanStatus": loan.status,
}
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
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 []
return ResponseHelper.success(return_data, "AutoCall Successful")
+16
View File
@@ -70,3 +70,19 @@ class LoanService:
Get the latest loan without a disbursement date.
"""
return Loan.get_latest_loan_with_disburse_date()
@classmethod
def get_customer_loans(cls, customer_id):
"""
Get customer's active loans by customer_id.
"""
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)
+21 -1
View File
@@ -8,6 +8,12 @@ class RepaymentService:
Get the repayment by transaction ID
"""
return Repayment.get_repayment_by_transaction_id(transaction_id)
@staticmethod
def get_repayment_by_id(id):
"""
Get the repayment by ID
"""
return Repayment.get_repayment_by_id(id)
@classmethod
def set_repay_date(cls, repayment_id, customer_id):
@@ -55,4 +61,18 @@ class RepaymentService:
"""
Get the latest repayment with a repay date and no verification date.
"""
return Repayment.get_latest_loan_with_repay_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)
@classmethod
def create_repayment(cls, repayment_data):
"""
Add a new repayment entry.
"""
return Repayment.create_repayment(repayment_data)
+7 -1
View File
@@ -15,4 +15,10 @@ class SalaryService:
"""
Get the pending salary for a given customer.
"""
return Salary.get_pending_salaries()
return Salary.get_pending_salaries()
@classmethod
def update_status(cls, salary_id, status):
"""
Update the status of the salary with the given salary_id.
"""
return Salary.update_status(salary_id, status)
+1 -1
View File
@@ -192,7 +192,7 @@ paths:
example: "OP621868"
status:
type: string
amount:
salaryAmount:
type: number
example: 200000
salaryDate: