
from django.db.models import Sum,Min,Max
from ..serializers import *
from ..models import *
from ..helper import *
from ledgers.models import *
from ledgers.ledgers_helper import *
from rest_framework.pagination import PageNumberPagination

def loan_repayment_loans_totals(payment_filter):
    payment_data   = []
    payment_totals = {
        "princ_paid":0,
        "int_paid":0,
        "penalty_paid":0,
        "total_paid":0
    }
    payments = LoanPayments.objects.filter(payment_status='normal', **payment_filter)
  
    if payments:
        for payment in payments:
            total_paid = payment.princ_paid + payment.int_paid + payment.penalty_paid
            payment_data.append({
                "member_number":payment.loan_application.customer.member_number,
                "name":payment.loan_application.customer.name,
                "telephone":payment.loan_application.customer.telephone,
                "id":payment.id,
                "princ_paid":payment.princ_paid,
                "int_paid":payment.int_paid,
                "penalty_paid":payment.penalty_paid,
                "total_paid": payment.princ_paid + payment.int_paid + payment.penalty_paid,
                "reference_no":payment.loan_main_transaction.system_transaction.reference_no,
                "voucher_no":payment.loan_main_transaction.system_transaction.voucher_no,
                "payment_method":payment.loan_main_transaction.system_transaction.payment_method,
                "record_date":payment.loan_main_transaction.system_transaction.record_date,
                "date_added":payment.loan_main_transaction.system_transaction.date_added
            })
            payment_totals["princ_paid"]    += payment.princ_paid
            payment_totals["int_paid"]      += payment.int_paid
            payment_totals["penalty_paid"]  += payment.penalty_paid
            payment_totals["total_paid"]    += total_paid
    return {"payment_data":payment_data,"payment_totals":payment_totals}

def filter_repayment_reports(report_filters):
        all_payments   = []
        payments_count = 0
        result    = {}
        filter_1  = report_filters['filter_1']
        filter_2  = report_filters['filter_2']

        page_size      = report_filters['page_size']
        report_filter  = report_filters['report_filter']
        request        = report_filters['request']
        search         = report_filters['search']
        payment_filter = {
            "loan_main_transaction__system_transaction__record_date__gte":report_filters["start"],
            "loan_main_transaction__system_transaction__record_date__lte":report_filters["end"],
            "loan_application__organisation_branch__branch_organisation__id":report_filters["organisation_id"]}
        paginator = PageNumberPagination()
        paginator.page_size = page_size

        if report_filter == 'officer_client_type':
            payment_filter["loan_application__loan_officer__id__in"] = filter_1
            payment_filter["loan_application__customer__branch_customer_type__id__in"] = filter_2
            if search and len(search) > 0:
                all_payments = LoanPayments.objects.filter(Q(loan_application__customer__member_number__icontains=search) | Q(loan_application__customer__name__icontains=search),**payment_filter)
            else:
                all_payments = LoanPayments.objects.filter(**payment_filter)
            payments_count = len(all_payments)
            repayments  = paginator.paginate_queryset(all_payments, request)
            result      = filter_repayment_officer_client_type(filter_1,filter_2,repayments)
            
        elif report_filter == 'officer_gender':
            payment_filter["loan_application__loan_officer__id__in"] = filter_1
            payment_filter["loan_application__customer__gender__in"] = filter_2
            if search and len(search) > 0:
                all_payments = LoanPayments.objects.filter(Q(loan_application__customer__member_number__icontains=search) | Q(loan_application__customer__name__icontains=search),**payment_filter)
            else:
                all_payments = LoanPayments.objects.filter(**payment_filter)
            payments_count = len(all_payments)
            repayments  = paginator.paginate_queryset(all_payments, request)
            result      = filter_repayment_officer_gender(filter_1,filter_2,repayments)

        elif report_filter == 'officer_branch':
            payment_filter["loan_application__loan_officer__id__in"] = filter_1
            payment_filter["loan_application__organisation_branch__id__in"] = filter_2
            if search and len(search) > 0:
                all_payments = LoanPayments.objects.filter(Q(loan_application__customer__member_number__icontains=search) | Q(loan_application__customer__name__icontains=search),**payment_filter)
            else:
                all_payments = LoanPayments.objects.filter(**payment_filter)
            payments_count = len(all_payments)
            repayments = paginator.paginate_queryset(all_payments, request)
            result     = filter_repayment_officer_branch(filter_1,filter_2,repayments)

        elif report_filter == 'product_client_type':
            payment_filter["loan_application__loan_application_product__id__in"]  = filter_1
            payment_filter["loan_application__customer__branch_customer_type__id__in"] = filter_2
            if search and len(search) > 0:
                all_payments = LoanPayments.objects.filter(Q(loan_application__customer__member_number__icontains=search) | Q(loan_application__customer__name__icontains=search),**payment_filter)
            else:
                all_payments = LoanPayments.objects.filter(**payment_filter)
            payments_count = len(all_payments)
            repayments = paginator.paginate_queryset(all_payments, request)
            result     = filter_repayment_product_client_type(filter_1,filter_2,repayments)
        
        elif report_filter == 'product_gender':
            payment_filter["loan_application__loan_application_product__id__in"] = filter_1
            payment_filter["loan_application__customer__gender__in"] =  filter_2
            if search and len(search) > 0:
                all_payments = LoanPayments.objects.filter(Q(loan_application__customer__member_number__icontains=search) | Q(loan_application__customer__name__icontains=search),**payment_filter)
            else:
                all_payments = LoanPayments.objects.filter(**payment_filter)
            payments_count = len(all_payments)
            repayments  = paginator.paginate_queryset(all_payments, request)
            result      = filter_repayment_product_gender(filter_1,filter_2,repayments)
        
        elif report_filter == 'product_branch':
            payment_filter["loan_application__loan_application_product__id__in"] = filter_1
            payment_filter["loan_application__organisation_branch__id__in"] = filter_2
            if search and len(search) > 0:
                    all_payments = LoanPayments.objects.filter(Q(loan_application__customer__member_number__icontains=search) | Q(loan_application__customer__name__icontains=search),**payment_filter)
            else:
                all_payments = LoanPayments.objects.filter(**payment_filter)
            payments_count = len(all_payments)
            repayments  = paginator.paginate_queryset(all_payments, request)
            result      = filter_repayment_product_branch(filter_1,filter_2,repayments)
        
        elif report_filter == 'product_officer':
            payment_filter["loan_application__loan_application_product__id__in"] = filter_1
            payment_filter["loan_application__loan_officer__id__in"] = filter_2
            if search and len(search) > 0:
                all_payments = LoanPayments.objects.filter(Q(loan_application__customer__member_number__icontains=search) | Q(loan_application__customer__name__icontains=search),**payment_filter)
            else:
                all_payments = LoanPayments.objects.filter(**payment_filter)
            payments_count = len(all_payments)
            repayments  = paginator.paginate_queryset(all_payments, request)
            result      = filter_repayment_product_officer(filter_1,filter_2,repayments)
        
        elif report_filter == 'product_sector':
            payment_filter["loan_application__loan_application_product__id__in"] = filter_1
            payment_filter["loan_application__loan_sector__id__in"] = filter_2
            if search and len(search) > 0:
                all_payments = LoanPayments.objects.filter(Q(loan_application__customer__member_number__icontains=search) | Q(loan_application__customer__name__icontains=search),**payment_filter)
            else:
                all_payments = LoanPayments.objects.filter(**payment_filter)
            payments_count = len(all_payments)
            repayments  = paginator.paginate_queryset(all_payments, request)
            result      = filter_repayment_product_sector(filter_1,filter_2,repayments,report_filters['start'],report_filters['end'])

        elif report_filter == 'gender_branch':
            payment_filter["loan_application__organisation_branch__id__in"] = filter_1
            payment_filter["loan_application__customer__gender__in"] = filter_2
            if search and len(search) > 0:
                all_payments = LoanPayments.objects.filter(Q(loan_application__customer__member_number__icontains=search) | Q(loan_application__customer__name__icontains=search),**payment_filter)
            else:
                all_payments = LoanPayments.objects.filter(**payment_filter)
            payments_count = len(all_payments)
            repayments  = paginator.paginate_queryset(all_payments, request)
            result      = filter_repayment_gender_branch(filter_1,filter_2,repayments)
        
        elif report_filter == 'group_branch':
            customer_ids = GroupMembership.objects.filter(group__id__in=filter_2).values_list('member__id', flat=True)
            payment_filter["loan_application__organisation_branch__id__in"] = filter_1
            payment_filter["loan_application__customer__id__in"] = customer_ids
            if search and len(search) > 0:
                all_payments = LoanPayments.objects.filter(Q(loan_application__customer__member_number__icontains=search) | Q(loan_application__customer__name__icontains=search),**payment_filter)
            else:
                all_payments = LoanPayments.objects.filter(**payment_filter)
            payments_count = len(all_payments)
            repayments  = paginator.paginate_queryset(all_payments, request)
            result      = filter_repayment_group_branch(filter_1,filter_2,repayments)
        return Response({"results":result,"count":payments_count})
        
def filter_repayment_officer_client_type(officer_ids,client_type_ids,repayments):
    section             = []
    loan_repayment_ids  = []
    payment_filter      = {}
    grand_totals   = {
        "princ_paid":0,
        "int_paid":0,
        "penalty_paid":0,
        "total_paid":0
    }

    if repayments:
        for loan_repayment in repayments:
            loan_repayment_ids.append(loan_repayment.id)

    loan_officers = Staff.objects.filter(id__in=officer_ids)
    if loan_officers:
        for loan_officer in loan_officers:
            sub_section     = []
            officers_totals = {
                "princ_paid":0,
                "int_paid":0,
                "penalty_paid":0,
                "total_paid":0
            }

            for client_type_id in client_type_ids:
                client_type      = CustomerType.objects.get(id=client_type_id)
                payment_filter["loan_application__loan_officer__id"] = loan_officer.id
                payment_filter["loan_application__customer__branch_customer_type__id"] = client_type_id
                payment_filter["id__in"] = loan_repayment_ids

                results = loan_repayment_loans_totals(payment_filter)

                client_type_data = results['payment_data']
                client_totals    = results['payment_totals']
                if client_type:
                    if len(client_type_data) > 0:
                        client_totals['member_number'] =  client_type.customer_type+" "+str(len(client_type_data))
                        sub_section.append({
                            "id":client_type.id,
                            "name":client_type.customer_type,
                            "sub_section_data":client_type_data,
                            "sub_section_total":client_totals,
                            "sub_section_total_count":len(client_type_data)
                        })

                        officers_totals["princ_paid"]    += client_totals["princ_paid"]
                        officers_totals["int_paid"]      += client_totals["int_paid"]
                        officers_totals["penalty_paid"]  += client_totals["penalty_paid"]
                        officers_totals['total_paid']    += client_totals["total_paid"]

                        grand_totals["princ_paid"]    += client_totals["princ_paid"]
                        grand_totals["int_paid"]      += client_totals["int_paid"]
                        grand_totals["penalty_paid"]  += client_totals["penalty_paid"]
                        grand_totals['total_paid']    += client_totals["total_paid"]
            if len(sub_section) > 0:
                section.append({
                    "id":loan_officer.id,
                    "name":loan_officer.name,
                    "section_data":sub_section,
                    "section_total":officers_totals
                })
    return  {"total":len(section),"data":section,"grand_total":grand_totals}

def filter_repayment_officer_gender(officer_ids,gender_list,repayments):
    section             = []
    loan_repayment_ids  = []
    payment_filter      = {}
    grand_totals   = {
       "princ_paid":0,
        "int_paid":0,
        "penalty_paid":0,
        "total_paid":0
    }

    if repayments:
        for loan_repayment in repayments:
            loan_repayment_ids.append(loan_repayment.id)

    loan_officers = Staff.objects.filter(id__in=officer_ids)
    if loan_officers:
        for loan_officer in loan_officers:
            sub_section     = []
            officers_totals = {
                "princ_paid":0,
                "int_paid":0,
                "penalty_paid":0,
                "total_paid":0
            }

            for gender in gender_list:
                gender_name = 'Male'
                if gender == 'F':
                    gender_name = 'Female'
                elif gender == 'O':
                    gender_name = 'Other'
                payment_filter["loan_application__loan_officer__id"] = loan_officer.id
                payment_filter["loan_application__customer__gender"] = gender
                payment_filter["id__in"] = loan_repayment_ids
                results     = loan_repayment_loans_totals(payment_filter)
                gender_data = results['payment_data']
                gender_totals = results['payment_totals']

                if len(gender_data) > 0:
                    gender_totals['member_number'] =  gender_name+" "+str(len(gender_data))
                    sub_section.append({
                        "id":gender,
                        "name":gender_name,
                        "sub_section_data":gender_data,
                        "sub_section_total":gender_totals,
                        "sub_section_total_count":len(gender_data)
                    })

                    officers_totals["princ_paid"]  += gender_totals["princ_paid"]
                    officers_totals["int_paid"]      += gender_totals["int_paid"]
                    officers_totals["penalty_paid"]  += gender_totals["penalty_paid"]
                    officers_totals['total_paid']    += gender_totals["total_paid"]

                    grand_totals["princ_paid"]    += gender_totals["princ_paid"]
                    grand_totals["int_paid"]      += gender_totals["int_paid"]
                    grand_totals["penalty_paid"]  += gender_totals["penalty_paid"]
                    grand_totals['total_paid']    += gender_totals["total_paid"]

            if len(sub_section) > 0:
                section.append({
                    "id":loan_officer.id,
                    "name":loan_officer.name,
                    "section_data":sub_section,
                    "section_total":officers_totals
                })
    return  {"total":len(section),"data":section,"grand_total":grand_totals}

def filter_repayment_officer_branch(officer_ids,branch_ids,repayments):
    section             = []
    loan_repayment_ids  = []
    payment_filter      = {}
    grand_totals   = {
        "princ_paid":0,
        "int_paid":0,
        "penalty_paid":0,
        "total_paid":0
    }

    if repayments:
        for loan_repayment in repayments:
            loan_repayment_ids.append(loan_repayment.id)

    loan_branches   = OrganisationBranch.objects.filter(id__in=branch_ids)
    if loan_branches:
        for loan_branch in loan_branches:
            sub_section     = []
            branch_totals = {
                "princ_paid":0,
                "int_paid":0,
                "penalty_paid":0,
                "total_paid":0
            }

            for officer_id in officer_ids:
                loan_officer    = Staff.objects.get(pk=officer_id)
                payment_filter["loan_application__loan_officer__id"] = loan_officer.id
                payment_filter["loan_application__organisation_branch__id"] = loan_branch.id
                payment_filter["id__in"] = loan_repayment_ids
                results     = loan_repayment_loans_totals(payment_filter)

                officers_data   = results['payment_data']
                officers_totals = results['payment_totals']
                if loan_officer:
                    if len(officers_data) > 0:
                        officers_totals['member_number'] =  loan_officer.name+" "+str(len(officers_data))
                        sub_section.append({
                            "id":loan_officer.id,
                            "name":loan_officer.name,
                            "sub_section_data":officers_data,
                            "sub_section_total":officers_totals,
                            "sub_section_total_count":len(officers_data)
                        })
                        branch_totals["princ_paid"]  += officers_totals["princ_paid"]
                        branch_totals["int_paid"]      += officers_totals["int_paid"]
                        branch_totals["penalty_paid"]  += officers_totals["penalty_paid"]
                        branch_totals['total_paid']    += officers_totals["total_paid"]

                        grand_totals["princ_paid"]    += officers_totals["princ_paid"]
                        grand_totals["int_paid"]      += officers_totals["int_paid"]
                        grand_totals["penalty_paid"]  += officers_totals["penalty_paid"]
                        grand_totals['total_paid']    += officers_totals["total_paid"]

            if len(sub_section) > 0:
                section.append({
                    "id":loan_branch.id,
                    "name":loan_branch.name,
                    "section_data":sub_section,
                    "section_total":branch_totals
                })
    return  {"total":len(section),"data":section,"grand_total":grand_totals}

def filter_repayment_product_client_type(product_ids,client_type_ids,repayments):
    section             = []
    loan_repayment_ids  = []
    payment_filter      = {}
    grand_totals   = {
        "princ_paid":0,
        "int_paid":0,
        "penalty_paid":0,
        "total_paid":0
    }

    if repayments:
        for loan_repayment in repayments:
            loan_repayment_ids.append(loan_repayment.id)

    loan_products = LoanProduct.objects.filter(id__in=product_ids)
    if loan_products:
        for loan_product in loan_products:
            sub_section = []
            loan_products_totals = {
                "princ_paid":0,
                "int_paid":0,
                "penalty_paid":0,
                "total_paid":0
            }

            for client_type_id in client_type_ids:
                client_type      = CustomerType.objects.get(id=client_type_id)
                payment_filter["loan_application__loan_application_product__id"] = loan_product.id
                payment_filter["loan_application__customer__branch_customer_type__id"] = client_type_id
                payment_filter["id__in"] = loan_repayment_ids
                results = loan_repayment_loans_totals(payment_filter)

                client_type_data = results['payment_data']
                client_totals    = results['payment_totals']
                if client_type:
                    if len(client_type_data) > 0:
                        client_totals['member_number'] =  client_type.customer_type+" "+str(len(client_type_data))
                        sub_section.append({
                            "id":client_type.id,
                            "name":client_type.customer_type,
                            "sub_section_data":client_type_data,
                            "sub_section_total":client_totals,
                            "sub_section_total_count":len(client_type_data)
                        })
                        loan_products_totals["princ_paid"]  += client_totals["princ_paid"]
                        loan_products_totals["int_paid"]      += client_totals["int_paid"]
                        loan_products_totals["penalty_paid"]  += client_totals["penalty_paid"]
                        loan_products_totals['total_paid']    += client_totals["total_paid"]

                        grand_totals["princ_paid"]   += client_totals["princ_paid"]
                        grand_totals["int_paid"]      += client_totals["int_paid"]
                        grand_totals["penalty_paid"]  += client_totals["penalty_paid"]
                        grand_totals['total_paid']    += client_totals["total_paid"]

            if len(sub_section) > 0:
                section.append({
                    "id":loan_product.id,
                    "name":loan_product.product_name,
                    "section_data":sub_section,
                    "section_total":loan_products_totals
                })
    return  {"total":len(section),"data":section,"grand_total":grand_totals}

def filter_repayment_product_gender(product_ids,gender_list,repayments):
    section        = []
    payment_filter      = {}
    loan_repayment_ids  = []
    grand_totals   = {
         "princ_paid":0,
        "int_paid":0,
        "penalty_paid":0,
        "total_paid":0
    }

    if repayments:
        for loan_repayment in repayments:
            loan_repayment_ids.append(loan_repayment.id)

    loan_products = LoanProduct.objects.filter(id__in=product_ids)
    if loan_products:
        for loan_product in loan_products:
            sub_section     = []
            product_totals = {
                "princ_paid":0,
                "int_paid":0,
                "penalty_paid":0,
                "total_paid":0
            }

            for gender in gender_list:
                gender_name = 'Male'
                if gender == 'F':
                    gender_name = 'Female'
                elif gender == 'O':
                    gender_name = 'Other'

                payment_filter["loan_application__loan_application_product__id"] = loan_product.id
                payment_filter["loan_application__customer__gender"] = gender
                payment_filter["id__in"] = loan_repayment_ids
                results     = loan_repayment_loans_totals(payment_filter)
                gender_data = results['payment_data']
                gender_totals = results['payment_totals']

                if len(gender_data) > 0:
                    gender_totals['member_number'] =  gender_name+" "+str(len(gender_data))
                    sub_section.append({
                        "id":gender,
                        "name":gender_name,
                        "sub_section_data":gender_data,
                        "sub_section_total":gender_totals,
                        "sub_section_total_count":len(gender_data)
                    })
                    product_totals["princ_paid"]  += gender_totals["princ_paid"]
                    product_totals["int_paid"]      += gender_totals["int_paid"]
                    product_totals["penalty_paid"]  += gender_totals["penalty_paid"]
                    product_totals['total_paid']    += gender_totals["total_paid"]

                    grand_totals["princ_paid"]  += gender_totals["princ_paid"]
                    grand_totals["int_paid"]      += gender_totals["int_paid"]
                    grand_totals["penalty_paid"]  += gender_totals["penalty_paid"]
                    grand_totals['total_paid']    += gender_totals["total_paid"]

            if len(sub_section) > 0:
                section.append({
                    "id":loan_product.id,
                    "name":loan_product.product_name,
                    "section_data":sub_section,
                    "section_total":product_totals
                })
    return  {"total":len(section),"data":section,"grand_total":grand_totals}

def filter_repayment_product_branch(product_ids,branch_ids,repayments):
    section        = []
    payment_filter = {}
    loan_repayment_ids  = []
    grand_totals   = {
        "princ_paid":0,
        "int_paid":0,
        "penalty_paid":0,
        "total_paid":0
    }

    if repayments:
        for loan_repayment in repayments:
            loan_repayment_ids.append(loan_repayment.id)

    loan_branches   = OrganisationBranch.objects.filter(id__in=branch_ids)
    if loan_branches:
        for loan_branch in loan_branches:
            sub_section     = []
            branch_totals = {
                "princ_paid":0,
                "int_paid":0,
                "penalty_paid":0,
                "total_paid":0
            }

            for product_id in product_ids:
                loan_product    = LoanProduct.objects.get(pk=product_id)
                payment_filter["loan_application__loan_application_product__id"] = loan_product.id
                payment_filter["loan_application__organisation_branch__id"] = loan_branch.id
                payment_filter["id__in"] = loan_repayment_ids
                results = loan_repayment_loans_totals(payment_filter)

                product_data   = results['payment_data']
                products_totals = results['payment_totals']
                if loan_product:
                    if len(product_data) > 0:
                        products_totals['member_number'] =  loan_product.product_name+" "+str(len(product_data))
                        sub_section.append({
                            "id":loan_product.id,
                            "name":loan_product.product_name,
                            "sub_section_data":product_data,
                            "sub_section_total":products_totals,
                            "sub_section_total_count":len(product_data)
                        })

                        branch_totals["princ_paid"]  += products_totals["princ_paid"]
                        branch_totals["int_paid"]      += products_totals["int_paid"]
                        branch_totals["penalty_paid"]  += products_totals["penalty_paid"]
                        branch_totals['total_paid']    += products_totals["total_paid"]

                        grand_totals["princ_paid"]  += products_totals["princ_paid"]
                        grand_totals["int_paid"]      += products_totals["int_paid"]
                        grand_totals["penalty_paid"]  += products_totals["penalty_paid"]
                        grand_totals['total_paid']    += products_totals["total_paid"]

            if len(sub_section) > 0:
                section.append({
                    "id":loan_branch.id,
                    "name":loan_branch.name,
                    "section_data":sub_section,
                    "section_total":branch_totals
                })
    return  {"total":len(section),"data":section,"grand_total":grand_totals}

def filter_repayment_product_officer(product_ids,officer_ids,repayments):
    section        = []
    loan_repayment_ids  = []
    payment_filter      = {}
    grand_totals   = {
       "princ_paid":0,
        "int_paid":0,
        "penalty_paid":0,
        "total_paid":0
    }

    if repayments:
        for loan_repayment in repayments:
            loan_repayment_ids.append(loan_repayment.id)

    loan_officers = Staff.objects.filter(id__in=officer_ids)
    if loan_officers:
        for loan_officer in loan_officers:
            sub_section     = []
            officer_totals = {
                "princ_paid":0,
                "int_paid":0,
                "penalty_paid":0,
                "total_paid":0
            }

            for product_id in product_ids:
                loan_product    = LoanProduct.objects.get(pk=product_id)
                payment_filter["loan_application__loan_application_product__id"] = product_id
                payment_filter["loan_application__loan_officer__id"] = loan_officer.id
                payment_filter["id__in"] = loan_repayment_ids
                results = loan_repayment_loans_totals(payment_filter)

                product_data   = results['payment_data']
                products_totals = results['payment_totals']
                if loan_product:
                    if len(product_data) > 0:
                        products_totals['member_number'] =  loan_product.product_name+" "+str(len(product_data))
                        sub_section.append({
                            "id":loan_product.id,
                            "name":loan_product.product_name,
                            "sub_section_data":product_data,
                            "sub_section_total":products_totals,
                            "sub_section_total_count":len(product_data)
                        })

                        officer_totals["princ_paid"]  += products_totals["princ_paid"]
                        officer_totals["int_paid"]      += products_totals["int_paid"]
                        officer_totals["penalty_paid"]  += products_totals["penalty_paid"]
                        officer_totals['total_paid']    += products_totals["total_paid"]

                        grand_totals["princ_paid"]  += products_totals["princ_paid"]
                        grand_totals["int_paid"]      += products_totals["int_paid"]
                        grand_totals["penalty_paid"]  += products_totals["penalty_paid"]
                        grand_totals['total_paid']    += products_totals["total_paid"]
            if len(sub_section) > 0:
                section.append({
                    "id":loan_officer.id,
                    "name":loan_officer.name,
                    "section_data":sub_section,
                    "section_total":officer_totals
                })
    return  {"total":len(section),"data":section,"grand_total":grand_totals}

def filter_repayment_product_sector(product_ids,sector_ids,repayments,start,end):
    section        = []
    payment_filter = {}
    loan_repayment_ids  = []
    grand_totals   = {
        "princ_paid":0,
        "int_paid":0,
        "penalty_paid":0,
        "total_paid":0
    }

    if repayments:
        for loan_repayment in repayments:
            loan_repayment_ids.append(loan_repayment.id)
    loan_sectors = LoanSectors.objects.filter(id__in=sector_ids)
    if loan_sectors:
        for loan_sector in loan_sectors:
            sub_section     = []
            sector_totals = {
                "princ_paid":0,
                "int_paid":0,
                "penalty_paid":0,
                "total_paid":0
            }

            for product_id in product_ids:
                loan_product    = LoanProduct.objects.get(pk=product_id)
                payment_filter["loan_application__loan_application_product__id"] = loan_product.id
                payment_filter["loan_application__loan_sector__id"] = loan_sector.id
                payment_filter["id__in"] = loan_repayment_ids
                results = loan_repayment_loans_totals(payment_filter)

                product_data   = results['payment_data']
                products_totals = results['payment_totals']
                if loan_product:
                    if len(product_data) > 0:
                        products_totals['member_number'] =  loan_product.product_name+" "+str(len(product_data))
                        sub_section.append({
                            "id":loan_product.id,
                            "name":loan_product.product_name,
                            "sub_section_data":product_data,
                            "sub_section_total":products_totals,
                            "sub_section_total_count":len(product_data)
                        })

                        sector_totals["princ_paid"]  += products_totals["princ_paid"]
                        sector_totals["int_paid"]      += products_totals["int_paid"]
                        sector_totals["penalty_paid"]  += products_totals["penalty_paid"]
                        sector_totals['total_paid']    += products_totals["total_paid"]

                        grand_totals["princ_paid"]  += products_totals["princ_paid"]
                        grand_totals["int_paid"]      += products_totals["int_paid"]
                        grand_totals["penalty_paid"]  += products_totals["penalty_paid"]
                        grand_totals['total_paid']    += products_totals["total_paid"]

            if len(sub_section) > 0:
                section.append({
                    "id":loan_sector.id,
                    "name":loan_sector.name,
                    "section_data":sub_section,
                    "section_total":sector_totals
                })
    return  {"total":len(section),"data":section,"grand_total":grand_totals}
    
def filter_repayment_gender_branch(branch_ids,gender_list,repayments):
        section        = []
        payment_filter = {}
        loan_repayment_ids = []
        grand_totals   = {
            "princ_paid":0,
            "int_paid":0,
            "penalty_paid":0,
            "total_paid":0
        }

        if repayments:
            for loan_repayment in repayments:
                loan_repayment_ids.append(loan_repayment.id)
        loan_branches   = OrganisationBranch.objects.filter(id__in=branch_ids)
        if loan_branches:
            for loan_branch in loan_branches:
                sub_section     = []
                branch_totals = {
                    "princ_paid":0,
                    "int_paid":0,
                    "penalty_paid":0,
                    "total_paid":0
                }

                for gender in gender_list:
                    gender_name = 'Male'
                    if gender == 'F':
                        gender_name = 'Female'
                    elif gender == 'O':
                        gender_name = 'Other'

                    payment_filter["loan_application__organisation_branch__id"] = loan_branch.id
                    payment_filter["loan_application__customer__gender"] = gender
                    payment_filter["id__in"] = loan_repayment_ids
                    results     = loan_repayment_loans_totals(payment_filter)
                    gender_data = results['payment_data']
                    gender_totals = results['payment_totals']

                    if len(gender_data) > 0:
                        #client totols
                        gender_totals['member_number'] =  gender_name+" "+str(len(gender_data))
                        sub_section.append({
                            "id":gender,
                            "name":gender_name,
                            "sub_section_data":gender_data,
                            "sub_section_total":gender_totals,
                            "sub_section_total_count":len(gender_data)
                        })

                        branch_totals["princ_paid"]  += gender_totals["princ_paid"]
                        branch_totals["int_paid"]      += gender_totals["int_paid"]
                        branch_totals["penalty_paid"]  += gender_totals["penalty_paid"]
                        branch_totals['total_paid']    += gender_totals["total_paid"]

                        grand_totals["princ_paid"]  += gender_totals["princ_paid"]
                        grand_totals["int_paid"]      += gender_totals["int_paid"]
                        grand_totals["penalty_paid"]  += gender_totals["penalty_paid"]
                        grand_totals['total_paid']    += gender_totals["total_paid"]

                if len(sub_section) > 0:
                    section.append({
                        "id":loan_branch.id,
                        "name":loan_branch.name,
                        "section_data":sub_section,
                        "section_total":branch_totals
                    })
        return  {"total":len(section),"data":section,"grand_total":grand_totals}

def filter_repayment_group_branch(branch_ids,group_ids,repayments):
    section        = []
    payment_filter = {}
    loan_repayment_ids  = []
    grand_totals   = {
        "princ_paid":0,
        "int_paid":0,
        "penalty_paid":0,
        "total_paid":0
    }

    if repayments:
        for loan_repayment in repayments:
            loan_repayment_ids.append(loan_repayment.id)
    loan_branches   = OrganisationBranch.objects.filter(id__in=branch_ids)
    if loan_branches:
        for loan_branch in loan_branches:
            sub_section     = []
            branch_totals = {
                "princ_paid":0,
                "int_paid":0,
                "penalty_paid":0,
                "total_paid":0
            }

            for group_id in group_ids:
                group    = Customer.objects.get(pk=group_id)
                customer_ids = GroupMembership.objects.filter(group=group).values_list('member__id', flat=True)
                payment_filter["loan_application__organisation_branch__id"] = loan_branch.id
                payment_filter["loan_application__customer__id__in"] = customer_ids
                payment_filter["id__in"] = loan_repayment_ids
                results = loan_repayment_loans_totals(payment_filter)

                group_data   = results['payment_data']
                group_totals = results['payment_totals']
                if group:
                    if len(group_data) > 0:
                        group_totals['member_number'] =  group.name+" "+str(len(group_data))
                        sub_section.append({
                            "id":group.id,
                            "name":group.name,
                            "sub_section_data":group_data,
                            "sub_section_total":group_totals,
                            "sub_section_total_count":len(group_data)
                        })

                        branch_totals["princ_paid"]  += group_totals["princ_paid"]
                        branch_totals["int_paid"]      += group_totals["int_paid"]
                        branch_totals["penalty_paid"]  += group_totals["penalty_paid"]
                        branch_totals['total_paid']    += group_totals["total_paid"]

                        grand_totals["princ_paid"]  += group_totals["princ_paid"]
                        grand_totals["int_paid"]      += group_totals["int_paid"]
                        grand_totals["penalty_paid"]  += group_totals["penalty_paid"]
                        grand_totals['total_paid']    += group_totals["total_paid"]

            if len(sub_section) > 0:
                section.append({
                    "id":loan_branch.id,
                    "name":loan_branch.name,
                    "section_data":sub_section,
                    "section_total":branch_totals
                })
    return  {"total":len(section),"data":section,"grand_total":grand_totals}
