53 lines
1.6 KiB
Python
53 lines
1.6 KiB
Python
from datetime import datetime, timezone
|
|
from app.api.enums.loan_status import LoanStatus
|
|
from app.extensions import db
|
|
from app.models.customer import Customer
|
|
from app.models.loan import Loan
|
|
from sqlalchemy.exc import IntegrityError
|
|
|
|
|
|
class Repayment(db.Model):
|
|
__tablename__ = 'repayments'
|
|
|
|
id = db.Column(
|
|
db.Integer,
|
|
primary_key=True,
|
|
autoincrement=True,
|
|
)
|
|
loan_id = db.Column(db.String(50), nullable=False)
|
|
customer_id = db.Column(db.String(50), nullable=False)
|
|
product_id = db.Column(db.String(20), nullable=True)
|
|
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_repayment(cls, customer_id, loan_id, product_id):
|
|
|
|
# Check customer exists
|
|
if not Customer.is_valid_customer(customer_id):
|
|
raise ValueError("Invalid customer")
|
|
|
|
# Check loan exists
|
|
loan = Loan.get_customer_loan(loan_id = loan_id, customer_id = customer_id)
|
|
|
|
# Check that the loan is active
|
|
if loan.status != LoanStatus.ACTIVE:
|
|
raise ValueError(f"Repayment cannot be processed. Loan status: ({loan.status})")
|
|
|
|
|
|
repayment = cls(
|
|
customer_id=customer_id,
|
|
loan_id=loan_id,
|
|
product_id=product_id,
|
|
)
|
|
|
|
try:
|
|
db.session.add(repayment)
|
|
except IntegrityError as err:
|
|
raise ValueError(f"Database integrity error: {err}")
|
|
|
|
return repayment
|
|
|
|
def __repr__(self):
|
|
return f'<Repayment {self.id}>'
|