# =======================
# SYSTEM-WIDE ROLLOVER FILTERING UTILITY
# Add this to reports/filters.py
# =======================

from loans.models import Loan

class RolloverAwareQuerySet:
    """
    Utility to filter out rolled-over loans from querysets
    Use this consistently across all reports
    """
    
    @staticmethod
    def get_active_loans_queryset(base_queryset=None):
        """
        Get active loans excluding rolled-over loans
        
        Usage:
            # Instead of: loans_qs = Loan.objects.filter(status='active')
            # Use: loans_qs = RolloverAwareQuerySet.get_active_loans_queryset()
        """
        if base_queryset is None:
            base_queryset = Loan.objects
        
        return base_queryset.filter(status='active').exclude(
            status='rolled_over'
        ).exclude(
            is_rolled_over=True
        )
    
    @staticmethod
    def exclude_rolled_over(queryset):
        """
        Exclude rolled-over loans from an existing queryset
        
        Usage:
            # Instead of: loans_qs = Loan.objects.filter(status='active')
            # Use: loans_qs = RolloverAwareQuerySet.exclude_rolled_over(
            #          Loan.objects.filter(status='active')
            #      )
        """
        return queryset.exclude(
            status='rolled_over'
        ).exclude(
            is_rolled_over=True
        )


# =======================
# HOW TO APPLY - Search and replace these patterns in all report files:
# =======================

"""
PATTERN 1 - Simple active filter:
OLD: loans_qs = Loan.objects.filter(status='active')
NEW: loans_qs = Loan.objects.filter(status='active').exclude(status='rolled_over').exclude(is_rolled_over=True)

PATTERN 2 - With additional filters:
OLD: loans_qs = Loan.objects.filter(status='active', borrower__branch_id=branch_id)
NEW: loans_qs = Loan.objects.filter(status='active', borrower__branch_id=branch_id).exclude(status='rolled_over').exclude(is_rolled_over=True)

PATTERN 3 - Multiple status filter:
OLD: loans_qs = Loan.objects.filter(status__in=['active', 'rolled_over', 'defaulted'])
NEW: loans_qs = Loan.objects.filter(status__in=['active', 'defaulted']).exclude(is_rolled_over=True)

FILES TO UPDATE:
- reports/simple_reports_service.py (lines 26, 90, 155, 291)
- reports/views.py (all report functions)
- loans/views.py (api_loan_data and other listing views)

AUTOMATIC APPLICATION:
Run this PowerShell command in the branch-system directory to see all locations:
Get-ChildItem -Recurse -Filter *.py | Select-String "Loan.objects.filter\(status='active'\)" | Select-Object Path, LineNumber
"""
