76 lines
2.1 KiB
Python
76 lines
2.1 KiB
Python
from django.db.models import Sum, Case, F, DecimalField, When
|
|
|
|
from core.apps.finance.models import Expence
|
|
from core.apps.finance.models import Income
|
|
|
|
|
|
def update_counterparty_balance(counterparty):
|
|
if not counterparty:
|
|
return
|
|
|
|
expences = Expence.objects.filter(
|
|
counterparty=counterparty,
|
|
is_deleted=False,
|
|
)
|
|
|
|
debit_usd = expences.filter(currency='usd').aggregate(
|
|
total=Sum('price')
|
|
)['total'] or 0
|
|
|
|
debit_uzs_direct = expences.filter(currency='uzs').aggregate(
|
|
total=Sum('price')
|
|
)['total'] or 0
|
|
|
|
debit_uzs_from_usd = expences.filter(currency='usd').aggregate(
|
|
total=Sum(
|
|
Case(
|
|
When(exchange_rate__gt=0, then=F('price') * F('exchange_rate') / 100),
|
|
default=0,
|
|
output_field=DecimalField()
|
|
)
|
|
)
|
|
)['total'] or 0
|
|
|
|
debit_uzs = debit_uzs_direct + debit_uzs_from_usd
|
|
|
|
|
|
incomes = Income.objects.filter(
|
|
counterparty=counterparty,
|
|
is_deleted=False
|
|
)
|
|
|
|
kredit_usd = incomes.filter(currency='usd').aggregate(
|
|
total=Sum('price')
|
|
)['total'] or 0
|
|
|
|
kredit_uzs_direct = incomes.filter(currency='uzs').aggregate(
|
|
total=Sum('price')
|
|
)['total'] or 0
|
|
|
|
kredit_uzs_from_usd = incomes.filter(currency='usd').aggregate(
|
|
total=Sum(
|
|
Case(
|
|
When(exchange_rate__gt=0, then=F('price') * F('exchange_rate') / 100),
|
|
default=0,
|
|
output_field=DecimalField()
|
|
)
|
|
)
|
|
)['total'] or 0
|
|
|
|
kredit_uzs = kredit_uzs_direct + kredit_uzs_from_usd
|
|
|
|
|
|
total_debit = debit_usd + debit_uzs
|
|
total_kredit = kredit_usd + kredit_uzs
|
|
|
|
counterparty.debit_usd = debit_usd
|
|
counterparty.debit_uzs = int(debit_uzs)
|
|
counterparty.total_debit = int(total_debit)
|
|
counterparty.kredit_usd = kredit_usd
|
|
counterparty.kredit_uzs = int(kredit_uzs)
|
|
counterparty.total_kredit = int(total_kredit)
|
|
counterparty.save(update_fields=[
|
|
'debit_usd', 'debit_uzs', 'total_debit',
|
|
'kredit_usd', 'kredit_uzs', 'total_kredit'
|
|
])
|