2017-08-21 23:21:08 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
from __future__ import unicode_literals
|
|
|
|
|
2017-08-23 01:37:10 +00:00
|
|
|
from collections import OrderedDict
|
|
|
|
|
2017-08-21 23:21:08 +00:00
|
|
|
from django.contrib.auth.mixins import PermissionRequiredMixin
|
2017-08-23 01:37:10 +00:00
|
|
|
from django.utils import timezone
|
2017-08-21 23:21:08 +00:00
|
|
|
from django.views.generic.detail import DetailView
|
|
|
|
|
2017-08-23 01:37:10 +00:00
|
|
|
from core.models import Child, Sleep
|
2017-08-21 23:21:08 +00:00
|
|
|
|
|
|
|
|
|
|
|
class SleepReport(PermissionRequiredMixin, DetailView):
|
2017-08-23 01:37:10 +00:00
|
|
|
"""All sleep data for a child."""
|
2017-08-21 23:21:08 +00:00
|
|
|
model = Child
|
|
|
|
permission_required = ('core.view_child',)
|
|
|
|
template_name = 'reports/sleep.html'
|
2017-08-23 01:37:10 +00:00
|
|
|
|
|
|
|
def get_context_data(self, **kwargs):
|
|
|
|
context = super(SleepReport, self).get_context_data(**kwargs)
|
|
|
|
child = context['object']
|
|
|
|
|
|
|
|
sleep_entries = Sleep.objects.filter(child=child).order_by('-end')
|
|
|
|
diff = timezone.localtime().date() - timezone.localtime(sleep_entries.last().end).date()
|
|
|
|
stats = OrderedDict()
|
|
|
|
for x in range(0, diff.days + 1):
|
|
|
|
key = (timezone.localtime() - timezone.timedelta(days=x))
|
|
|
|
stats[key.date()] = []
|
|
|
|
|
|
|
|
last = None
|
|
|
|
for entry in sleep_entries:
|
|
|
|
start = timezone.localtime(entry.start)
|
|
|
|
end = timezone.localtime(entry.end)
|
|
|
|
|
|
|
|
if not stats[end.date()]:
|
|
|
|
last = end.replace(hour=23, minute=59, second=59)
|
|
|
|
|
|
|
|
# TODO: Account for sleep sessions crossing midnight.
|
|
|
|
stats[start.date()].append((
|
|
|
|
(last - end).seconds/86400 * 100,
|
|
|
|
(end - start).seconds/86400 * 100
|
|
|
|
))
|
|
|
|
last = start
|
|
|
|
|
|
|
|
context['stats'] = stats
|
|
|
|
|
|
|
|
return context
|