servicesstats.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. from django.core.management.base import BaseCommand, CommandError
  2. from django.db.models import DecimalField, F, Sum, Func, Q
  3. from decimal import Decimal
  4. from services.models import ServiceType
  5. class Command(BaseCommand):
  6. help = 'Bénéfices des services'
  7. def handle(self, *args, **options):
  8. as_float_template = '%(function)s(%(expressions)s AS FLOAT)'
  9. total_income = Decimal(0.0)
  10. lines = []
  11. for service_type in ServiceType.objects.all():
  12. services = service_type.services
  13. ntotal = services.count()
  14. services = services.exclude(adherent=None)
  15. nadh = services.count()
  16. ninf = ntotal - nadh
  17. services = services.exclude(Q(contribution__isnull=True) | Q(contribution__amount=0) | Q(contribution__period=0))
  18. npay = services.count()
  19. ngra = nadh - npay
  20. amount = Func(F('contribution__amount'), function='CAST', template=as_float_template)
  21. period = F('contribution__period')
  22. output_field = DecimalField(max_digits=9, decimal_places=2)
  23. income = services.aggregate(income=Sum(amount / period, output_field=output_field))['income'] or Decimal(0.0)
  24. total_income += income
  25. lines += [(str(service_type), npay, ninf, ngra, income,)]
  26. self.stdout.write("%-16s%12s%12s%12s%12s%12s" % ('Service', 'npay', 'ninf', 'ngra', 'eur', 'pourcent'))
  27. for service_type, npay, ninf, ngra, income in lines:
  28. if total_income:
  29. percent = income / total_income * 100
  30. else:
  31. percent = 0
  32. self.stdout.write("%-16s%12d%12d%12d%12.2f%12.1f" % (service_type, npay, ninf, ngra, income, percent))