61 lines
1.9 KiB
Python
61 lines
1.9 KiB
Python
from datetime import datetime, timezone
|
|
from app.extensions import db
|
|
from app.models.customer import Customer
|
|
from app.models.account import Account
|
|
|
|
|
|
class Loan(db.Model):
|
|
__tablename__ = 'loans'
|
|
|
|
id = db.Column(db.String(50), primary_key=True)
|
|
customer_id = db.Column(db.String(50), nullable=False)
|
|
account_id = db.Column(db.String(50), nullable=False)
|
|
product_id = db.Column(db.String(20), nullable=False)
|
|
principal_amount = db.Column(db.Float, nullable=False)
|
|
status = db.Column(db.String(20), default='pending')
|
|
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))
|
|
|
|
|
|
@classmethod
|
|
def create_loan(cls, id, customer_id, account_id, product_id, principal_amount, status='pending'):
|
|
|
|
# Check if customer exists
|
|
is_valid = Customer.is_valid_customer(customer_id)
|
|
if not is_valid:
|
|
raise ValueError("Customer does not exist")
|
|
|
|
# # Check for active loans
|
|
# has_active_loans = cls.has_active_loans(customer_id)
|
|
# if has_active_loans:
|
|
# raise ValueError("Customer has active loans")
|
|
|
|
# Create and save the loan
|
|
loan = cls(
|
|
id=id,
|
|
customer_id=customer_id,
|
|
account_id=account_id,
|
|
product_id=product_id,
|
|
principal_amount=principal_amount,
|
|
status=status
|
|
)
|
|
|
|
db.session.add(loan)
|
|
db.session.commit()
|
|
return loan
|
|
|
|
|
|
@classmethod
|
|
def has_active_loans(cls, customer_id):
|
|
active_loans = cls.query.filter_by(
|
|
customer_id=customer_id,
|
|
status='active'
|
|
).count()
|
|
|
|
if active_loans > 0:
|
|
return False
|
|
return True
|
|
|
|
|
|
def __repr__(self):
|
|
return f'<Loan {self.id}>' |