You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

views.py 6.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. from datetime import timedelta
  2. from decimal import Decimal as D, ROUND_UP
  3. from django.utils.timezone import now
  4. from django.views.generic import TemplateView
  5. from django.db.models.loading import get_model
  6. from django.db.models import Avg, Sum, Count
  7. from django.contrib.auth.models import User
  8. from oscar.apps.promotions.models import AbstractPromotion
  9. ConditionalOffer = get_model('offer', 'ConditionalOffer')
  10. Voucher = get_model('voucher', 'Voucher')
  11. Basket = get_model('basket', 'Basket')
  12. StockAlert = get_model('partner', 'StockAlert')
  13. Product = get_model('catalogue', 'Product')
  14. Order = get_model('order', 'Order')
  15. Line = get_model('order', 'Line')
  16. class IndexView(TemplateView):
  17. template_name = 'dashboard/index.html'
  18. def get_context_data(self, **kwargs):
  19. ctx = super(IndexView, self).get_context_data(**kwargs)
  20. ctx.update(self.get_stats())
  21. return ctx
  22. def get_active_site_offers(self):
  23. """
  24. Return active conditional offers of type "site offer". The returned
  25. ``Queryset`` of site offers is filtered by end date greater then
  26. the current date.
  27. """
  28. return ConditionalOffer.objects.filter(end_date__gt=now(),
  29. offer_type=ConditionalOffer.SITE)
  30. def get_active_vouchers(self):
  31. """
  32. Get all active vouchers. The returned ``Queryset`` of vouchers
  33. is filtered by end date greater then the current date.
  34. """
  35. return Voucher.objects.filter(end_date__gt=now())
  36. def get_number_of_promotions(self, abstract_base=AbstractPromotion):
  37. """
  38. Get the number of promotions for all promotions derived from
  39. *abstract_base*. All subclasses of *abstract_base* are queried
  40. and if another abstract base class is found this method is executed
  41. recursively.
  42. """
  43. total = 0
  44. for cls in abstract_base.__subclasses__():
  45. if cls._meta.abstract:
  46. total += self.get_number_of_promotions(cls)
  47. else:
  48. total += cls.objects.count()
  49. return total
  50. def get_open_baskets(self, filters=None):
  51. """
  52. Get all open baskets. If *filters* dictionary is provided they will
  53. be applied on all open baskets and return only filtered results.
  54. """
  55. if filters is None:
  56. filters = {}
  57. filters['status'] = Basket.OPEN
  58. return Basket.objects.filter(**filters)
  59. def get_hourly_report(self, hours=24, segments=10):
  60. """
  61. Get report of order revenue split up in hourly chunks. A report is
  62. generated for the last *hours* (default=24) from the current time.
  63. The report provides ``max_revenue`` of the hourly order revenue sum,
  64. ``y-range`` as the labeling for the y-axis in a template and
  65. ``order_total_hourly``, a list of properties for hourly chunks.
  66. *segments* defines the number of labeling segments used for the y-axis
  67. when generating the y-axis labels (default=10).
  68. """
  69. # Get datetime for 24 hours agao
  70. time_now = now().replace(minute=0, second=0)
  71. start_time = time_now - timedelta(hours=hours-1)
  72. orders_last_day = Order.objects.filter(date_placed__gt=start_time)
  73. order_total_hourly = []
  74. for hour in range(0, hours):
  75. end_time = start_time + timedelta(hours=1)
  76. hourly_orders = orders_last_day.filter(date_placed__gt=start_time,
  77. date_placed__lt=end_time)
  78. total = hourly_orders.aggregate(
  79. Sum('total_incl_tax')
  80. )['total_incl_tax__sum'] or D('0.0')
  81. order_total_hourly.append({
  82. 'end_time': end_time,
  83. 'total_incl_tax': total
  84. })
  85. start_time = end_time
  86. max_value = max([x['total_incl_tax'] for x in order_total_hourly])
  87. divisor = 1
  88. while divisor < max_value / 50:
  89. divisor *= 10
  90. max_value = (max_value / divisor).quantize(D('1'), rounding=ROUND_UP)
  91. max_value *= divisor
  92. if max_value:
  93. segment_size = (max_value) / D('100.0')
  94. for item in order_total_hourly:
  95. item['percentage'] = int(item['total_incl_tax'] / segment_size)
  96. y_range = []
  97. y_axis_steps = max_value / D(str(segments))
  98. for idx in reversed(range(segments+1)):
  99. y_range.append(idx * y_axis_steps)
  100. else:
  101. y_range = []
  102. for item in order_total_hourly:
  103. item['percentage'] = 0
  104. ctx = {
  105. 'order_total_hourly': order_total_hourly,
  106. 'max_revenue': max_value,
  107. 'y_range': y_range,
  108. }
  109. return ctx
  110. def get_stats(self):
  111. datetime_24hrs_ago = now() - timedelta(hours=24)
  112. orders = Order.objects.filter()
  113. orders_last_day = orders.filter(date_placed__gt=datetime_24hrs_ago)
  114. open_alerts = StockAlert.objects.filter(status=StockAlert.OPEN)
  115. closed_alerts = StockAlert.objects.filter(status=StockAlert.CLOSED)
  116. stats = {
  117. 'total_orders_last_day': orders_last_day.count(),
  118. 'total_lines_last_day': Line.objects.filter(order__in=orders_last_day).count(),
  119. 'average_order_costs': orders_last_day.aggregate(
  120. Avg('total_incl_tax')
  121. )['total_incl_tax__avg'] or D('0.00'),
  122. 'total_revenue_last_day': orders_last_day.aggregate(
  123. Sum('total_incl_tax')
  124. )['total_incl_tax__sum'] or D('0.00'),
  125. 'hourly_report_dict': self.get_hourly_report(hours=24),
  126. 'total_customers_last_day': User.objects.filter(
  127. date_joined__gt=datetime_24hrs_ago,
  128. ).count(),
  129. 'total_open_baskets_last_day': self.get_open_baskets({
  130. 'date_created__gt': datetime_24hrs_ago
  131. }).count(),
  132. 'total_products': Product.objects.count(),
  133. 'total_open_stock_alerts': open_alerts.count(),
  134. 'total_closed_stock_alerts': closed_alerts.count(),
  135. 'total_site_offers': self.get_active_site_offers().count(),
  136. 'total_vouchers': self.get_active_vouchers().count(),
  137. 'total_promotions': self.get_number_of_promotions(),
  138. 'total_customers': User.objects.count(),
  139. 'total_open_baskets': self.get_open_baskets().count(),
  140. 'total_orders': orders.count(),
  141. 'total_lines': Line.objects.filter(order__in=orders).count(),
  142. 'total_revenue': orders.aggregate(
  143. Sum('total_incl_tax')
  144. )['total_incl_tax__sum'] or D('0.00'),
  145. 'order_status_breakdown': orders.order_by(
  146. 'status'
  147. ).values('status').annotate(freq=Count('id'))
  148. }
  149. return stats