
from django.db.models import Sum

from iltshot.models import ShotOperation

def get_customer_balance(photocustomer):
    #print("customer", photocustomer)
    credit = ShotOperation.objects.filter(state='E').filter(customer=photocustomer).filter(shotoperation_type='C').aggregate(total_credit=Sum('shotoperation_credit'))
    debit = ShotOperation.objects.filter(state='E').filter(customer=photocustomer).filter(shotoperation_type='D').aggregate(total_debit=Sum('shotoperation_debit')) 
    #print(debit, credit)
    if credit['total_credit'] is not None:
        if debit['total_debit'] is not None:
            return credit['total_credit'] - debit['total_debit']
        else:
            return credit['total_credit']
    else:
        return 0
