servicesstats.py 1.8 KB

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