from datetime import datetime, timezone, timedelta from app.extensions import db from sqlalchemy.orm import relationship class LoanCharge(db.Model): __tablename__ = 'loan_charges' id = db.Column(db.Integer, primary_key=True, autoincrement=True) loan_id = db.Column(db.Integer, nullable=False) transaction_id = db.Column(db.String(50), nullable=True) code = db.Column(db.String(50), nullable=False) amount = db.Column(db.Float, default=0.0) percent = db.Column(db.Float, default=0.0) description = db.Column(db.Text, nullable=True) due = db.Column(db.Integer, nullable=False) due_date = db.Column(db.DateTime, 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)) loan = relationship( "Loan", primaryjoin="LoanCharge.loan_id == Loan.id", foreign_keys=[loan_id], back_populates="loan_charges", ) @classmethod def create_charges_for_loan(cls, loan_id, transaction_id, charges, referenced_amount = 0.0): """ Create loan charges for a given loan. Args: loan_id (int): ID of the loan to associate charges with. charges (list): A list of dictionaries with keys: code (str), amount (float), percent (float), description (str), due (int) """ if not charges or not isinstance(charges, list): raise ValueError("Charges must be a non-empty list of dictionaries") if loan_id is None: raise ValueError("loan_id cannot be None") loan_charges = [] now = datetime.now(timezone.utc) for charge in charges: due_days = getattr(charge, "due", 0) amount = getattr(charge, "amount", 0.0) percent = getattr(charge, "percent", 0.0) if amount == 0.0: amount = (percent / 100.0) * referenced_amount charge_obj = cls( loan_id = loan_id, transaction_id = transaction_id, code = getattr(charge, "code"), amount = round(amount, 2), percent = percent, description = getattr(charge, "description", ""), due = due_days, due_date = now + timedelta(days=due_days) ) db.session.add(charge_obj) loan_charges.append(charge_obj) return loan_charges def to_dict(self): return { 'id': self.id, 'loanId': self.loan_id, 'transactionId': self.transaction_id, 'code': self.code, 'amount': self.amount, 'percent': self.percent, 'description': self.description, 'due': self.due, } def __repr__(self): return f""