Lab as a Service 2.0
[pharos-tools.git] / dashboard / src / booking / stats.py
1 ##############################################################################
2 # Copyright (c) 2018 Parker Berberian, Sawyer Bergeron, and others.
3 #
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9 from booking.models import Booking
10 import datetime
11 import pytz
12
13
14 class StatisticsManager(object):
15
16     @staticmethod
17     def getContinuousBookingTimeSeries(span=28):
18         """
19         Will return a dictionary of names and 2-D array of x and y data points.
20         e.g. {"plot1": [["x1", "x2", "x3"],["y1", "y2", "y3]]}
21         x values will be dates in string
22         every change (booking start / end) will be reflected, instead of one data point per day
23         y values are the integer number of bookings/users active at some point in the given date
24         span is the number of days to plot. The last x value will always be the current time
25         """
26         x_set = set()
27         x = []
28         y = []
29         users = []
30         now = datetime.datetime.now(pytz.utc)
31         delta = datetime.timedelta(days=span)
32         end = now-delta
33         bookings = Booking.objects.filter(start__lte=now, end__gte=end)
34         for booking in bookings:
35             x_set.add(booking.start)
36             if booking.end < now:
37                 x_set.add(booking.end)
38
39         x_set.add(now)
40         x_set.add(end)
41
42         x_list = list(x_set)
43         x_list.sort(reverse=True)
44         for time in x_list:
45             x.append(str(time))
46             active = Booking.objects.filter(start__lte=time, end__gt=time)
47             booking_count = len(active)
48             users_set = set()
49             for booking in active:
50                 users_set.add(booking.owner)
51                 for user in booking.collaborators.all():
52                     users_set.add(user)
53             y.append(booking_count)
54             users.append(len(users_set))
55
56         return {"booking": [x, y], "user": [x, users]}