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

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