servicesstats.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. from django.core.management.base import BaseCommand
  2. from django.db.models import DecimalField, F, Sum, Func, Q
  3. from decimal import Decimal
  4. from services.models import Service, 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.filter(Service.get_ongoing_filter())
  13. ntotal = services.count()
  14. services = services.exclude(adherent=None)
  15. nadh = services.count()
  16. ninf = ntotal - nadh
  17. services = services.exclude(
  18. Q(contribution__isnull=True)
  19. | Q(contribution__amount=0)
  20. | Q(contribution__period=0)
  21. )
  22. npay = services.count()
  23. ngra = nadh - npay
  24. amount = Func(F('contribution__amount'), function='CAST', template=as_float_template)
  25. period = F('contribution__period')
  26. output_field = DecimalField(max_digits=9, decimal_places=2)
  27. income = services.aggregate(income=Sum(amount / period,
  28. output_field=output_field))['income'] or Decimal(0.0)
  29. total_income += income
  30. lines += [(str(service_type), npay, ninf, ngra, income,)]
  31. self.stdout.write("%-16s%12s%12s%12s%12s%12s" % ('Service', 'npay', 'ninf', 'ngra', 'eur', 'pourcent'))
  32. for service_type, npay, ninf, ngra, income in lines:
  33. if total_income:
  34. percent = income / total_income * 100
  35. else:
  36. percent = 0
  37. self.stdout.write("%-16s%12d%12d%12d%12.2f%12.1f" % (service_type, npay, ninf, ngra, income, percent))