from datetime import datetime, timezone from app.extensions import db 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(50), 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)) transaction_id = db.Column(db.String(50)) @classmethod def get_all_repayments(cls, loan_id=None, customer_id=None, product_id=None, start_date=None, end_date=None, page=1, limit=20): """ Get all repayments with optional filtering Args: loan_id (str, optional): Filter by loan ID customer_id (str, optional): Filter by customer ID product_id (str, optional): Filter by product ID start_date (datetime, optional): Filter by start date (created_at) end_date (datetime, optional): Filter by end date (created_at) page (int, optional): Page number for pagination limit (int, optional): Number of items per page Returns: tuple: (list of Repayment objects, total count) """ query = cls.query # Apply filters if provided if loan_id: query = query.filter(cls.loan_id == loan_id) if customer_id: query = query.filter(cls.customer_id == customer_id) if product_id: query = query.filter(cls.product_id == product_id) if start_date: query = query.filter(cls.created_at >= start_date) if end_date: query = query.filter(cls.created_at <= end_date) # Order by created_at descending (newest first) query = query.order_by(cls.created_at.desc()) # Get total count before pagination total_count = query.count() # Apply pagination offset = (page - 1) * limit query = query.limit(limit).offset(offset) return query.all(), total_count def to_dict(self): """ Convert the Repayment object to a dictionary format for JSON serialization. """ return { 'loan_id': self.loan_id, 'customer_id': self.customer_id, 'product_id': self.product_id, 'transaction_id': self.transaction_id, 'created_at': self.created_at.isoformat() if self.created_at else None, 'updated_at': self.updated_at.isoformat() if self.updated_at else None } def __repr__(self): return f''