eliminated some hardcoded values

This commit is contained in:
2025-04-17 17:16:01 +01:00
parent 0268bbd557
commit d2e272e44b
8 changed files with 145 additions and 9 deletions
+28 -6
View File
@@ -1,6 +1,8 @@
import requests
from app.config import settings
from app.services.loan import LoanService
from app.utils.auth import get_headers
from app.utils.extras import preprocess_loan_charges_data
from app.utils.logger import logger
from flask import jsonify, current_app
from app.services.transactions import TransactionService
@@ -26,21 +28,42 @@ class SimbrellaClient:
logger.info(f"Transaction id: {data['transactionId']}, was not found")
return 0
# Fetch the loan based on the transaction_id
logger.info(f"Fetching the loan with transaction ID: {data['transactionId']}")
loan = LoanService.get_loan_by_transaction_id(transaction_id=data['transactionId'])
logger.info(f"Response from database: {loan}")
# If loan is not found
if not loan:
logger.info(f"Could not find loan with transaction id: {data['transactionId']}")
return 0
loan_data = loan.to_dict()
logger.info(f"Here is your loan data: {loan_data}")
loan_charges = preprocess_loan_charges_data([loan_charge.to_dict() for loan_charge in loan.loan_charges])
logger.info(f"Here are your loan_charges: {loan_charges}")
mgt_fee = loan_charges.get("MGTFEE")['amount']
vat_fee = loan_charges.get("VAT")['amount']
disbursement_data ={
"requestId": data['requestId'],
"transactionId": data['transactionId'],
"debtId": "273194670",
"debtId": loan_data['debtId'],
"customerId": data['customerId'],
"accountId": data['accountId'],
"productId": "101",
"provideAmount": 100000,
"productId": loan_data['productId'],
"provideAmount": loan_data['currentLoanAmount'],
"collectAmountInterest": 5000,
"collectAmountMgtFee": 1000,
"collectAmountMgtFee": mgt_fee,
"collectAmountInsurance": 1000,
"collectAmountVAT": 75,
"collectAmountVAT": vat_fee,
"countryId": "01",
"comment": "Loan Disbursement",
}
try:
logger.info(f"Here is your Disbursement Request data ****** : {disbursement_data}")
response = requests.post(api_url, json=disbursement_data, timeout=10, headers=get_headers())
@@ -51,7 +74,6 @@ class SimbrellaClient:
#raise
return 0
# return jsonify(response.json()), response.status_code
return 1
@staticmethod
+5 -1
View File
@@ -1,4 +1,8 @@
from .transactions import Transaction
from .repayment import Repayment
from .loan import Loan
from .loan_charge import LoanCharge
from .customer import Customer
from .account import Account
__all__ = ['Transaction', 'Repayment']
__all__ = ['Transaction', 'Repayment', 'Loan', 'LoanCharge', 'Customer', 'Account']
+25
View File
@@ -0,0 +1,25 @@
from datetime import datetime, timezone
from sqlalchemy.orm import relationship
from app.extensions import db
class Account(db.Model):
__tablename__ = 'accounts'
id = db.Column(db.String(50), primary_key=True)
customer_id = db.Column(db.String(50), nullable=False)
account_type = db.Column(db.String(50))
status = db.Column(db.String(20), default='active')
lien_amount = db.Column(db.Float, 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))
customer = relationship(
"Customer",
primaryjoin="Customer.id == Account.customer_id",
foreign_keys=[customer_id],
back_populates="accounts",
)
def __repr__(self):
return f'<Account {self.id}>'
+41
View File
@@ -0,0 +1,41 @@
from datetime import datetime, timezone
from sqlalchemy.orm import relationship
from app.extensions import db
class Customer(db.Model):
__tablename__ = 'customers'
id = db.Column(db.String(50), primary_key=True)
msisdn = db.Column(db.String(20), unique=True, nullable=False)
country_code = db.Column(db.String(3), nullable=False)
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))
accounts = relationship(
"Account",
primaryjoin="Customer.id == Account.customer_id",
foreign_keys="Account.customer_id",
back_populates="customer",
)
loans = relationship(
"Loan",
primaryjoin="Customer.id == Loan.customer_id",
foreign_keys="Loan.customer_id",
back_populates="customer",
)
@classmethod
def get_customer(cls, customer_id):
"""
Get customer by ID.
"""
customer = cls.query.filter_by(id=customer_id).first()
if not customer:
raise ValueError(f"Customer does not exist")
return customer
def __repr__(self):
return f'<Customer {self.id}>'
+6 -1
View File
@@ -54,6 +54,11 @@ class Loan(db.Model):
'continuousFee': self.continuous_fee,
'collectionType': self.collection_type,
'status': self.status,
'productId': self.product_id,
'dueDate': self.due_date.isoformat() if self.due_date else None,
'loanDate': self.created_at.isoformat if self.created_at else None
}
}
@classmethod
def get_loan_by_transaction_id(cls, transaction_id):
return cls.query.filter_by(transaction_id=transaction_id).first()
+7 -1
View File
@@ -1,4 +1,6 @@
from datetime import datetime, timezone, timedelta
from os.path import devnull
from app.extensions import db
from sqlalchemy.orm import relationship
@@ -40,4 +42,8 @@ class LoanCharge(db.Model):
'percent': self.percent,
'description': self.description,
'due': self.due
}
}
@classmethod
def get_loan_charge_by_debt_id(cls, debt_id):
return cls.query.filter_by(loan_id=debt_id)
+17
View File
@@ -0,0 +1,17 @@
from app.models import Loan, LoanCharge
class LoanService:
@classmethod
def get_loan_by_transaction_id(cls, transaction_id):
"""
Get the loan by transaction ID
"""
return Loan.get_loan_by_transaction_id(transaction_id)
@classmethod
def get_loan_charge_by_debt_id(cls, debt_id):
"""
Get the loan charge by debt ID
"""
return LoanCharge.get_loan_charge_by_debt_id(debt_id)
+16
View File
@@ -0,0 +1,16 @@
def preprocess_loan_charges_data(data):
"""
Preprocesses the data into a dictionary for efficient lookups by 'code'.
Args:
data: A list of dictionaries.
Returns:
A dictionary where keys are 'code' values and values are the corresponding dictionaries from the input data.
If multiple items have the same code, the last one encountered will be stored.
"""
preprocessed = {}
for item in data:
if 'code' in item:
preprocessed[item['code']] = item
return preprocessed