Compare commits
25 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9831395e2a | |||
| aa408cc720 | |||
| 35e4580313 | |||
| 3d62cbc157 | |||
| 3785196fb7 | |||
| 8249a1b6d8 | |||
| caa77191c7 | |||
| 3f1d87b88a | |||
| 42a3b0fd73 | |||
| 43055ad010 | |||
| 114a089bdb | |||
| 48fb58c6ab | |||
| 306221f502 | |||
| a310709c5e | |||
| a1b1caf5d7 | |||
| b88a09376b | |||
| ee077fb380 | |||
| 4e23ea4e91 | |||
| cb4383c10b | |||
| e9c29a8743 | |||
| 08a0c8a933 | |||
| 6200fc4dba | |||
| 0d2ce16ff5 | |||
| 7b21140b39 | |||
| 190cd6611a |
@@ -0,0 +1,2 @@
|
||||
from .transaction_type import TransactionType
|
||||
from .loan_status import LoanStatus
|
||||
@@ -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"
|
||||
@@ -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"
|
||||
@@ -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
|
||||
|
||||
@@ -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
@@ -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
|
||||
@@ -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):
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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
@@ -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 []
|
||||
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
Reference in New Issue
Block a user