Skip to content

Commit

Permalink
Merge pull request #83 from TurTaskProject/feature/dashboard
Browse files Browse the repository at this point in the history
Completed all dashboard features and corrected percent issues. + Rewrite test of task/ dashboard + move some signal to users
  • Loading branch information
Sosokker authored Nov 26, 2023
2 parents 0158fe5 + d1fca5c commit 9273181
Show file tree
Hide file tree
Showing 24 changed files with 608 additions and 306 deletions.
5 changes: 1 addition & 4 deletions backend/boards/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,4 @@

class BoardsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'boards'

def ready(self):
import boards.signals
name = 'boards'
17 changes: 0 additions & 17 deletions backend/boards/signals.py

This file was deleted.

1 change: 1 addition & 0 deletions backend/core/local_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@
'DESCRIPTION': 'API documentation for TurTask',
'VERSION': '1.0.0',
'SERVE_INCLUDE_SCHEMA': False,
'SERVE_PERMISSIONS': ['rest_framework.permissions.IsAuthenticated'],
}

REST_USE_JWT = True
Expand Down
1 change: 1 addition & 0 deletions backend/core/production_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@
'DESCRIPTION': 'API documentation for TurTask',
'VERSION': '1.0.0',
'SERVE_INCLUDE_SCHEMA': False,
'SERVE_PERMISSIONS': ['rest_framework.permissions.IsAuthenticated'],
}

REST_USE_JWT = True
Expand Down
12 changes: 6 additions & 6 deletions backend/dashboard/serializers.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from rest_framework import serializers
from .models import UserStats
# from rest_framework import serializers
# from .models import UserStats

class UserStatsSerializer(serializers.ModelSerializer):
class Meta:
model = UserStats
fields = ['health', 'gold', 'experience', 'strength', 'intelligence', 'endurance', 'perception', 'luck', 'level']
# class UserStatsSerializer(serializers.ModelSerializer):
# class Meta:
# model = UserStats
# fields = ['health', 'gold', 'experience', 'strength', 'intelligence', 'endurance', 'perception', 'luck', 'level']
89 changes: 16 additions & 73 deletions backend/dashboard/tests.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,35 @@
from django.test import TestCase
from rest_framework.test import APITestCase
from django.urls import reverse
from tasks.models import Todo
from django.utils import timezone
from datetime import timedelta

from tasks.tests.utils import create_test_user, login_user
from boards.models import Board
from tasks.tests.utils import create_test_user

class DashboardStatsAndWeeklyViewSetTests(TestCase):
class DashboardStatsAndWeeklyViewSetTests(APITestCase):
def setUp(self):
self.user = create_test_user()
self.client = login_user(self.user)
self.client.force_authenticate(user=self.user)
self.list_board = Board.objects.get(user=self.user).listboard_set.first()

def create_task(self, title, completed=False, completion_date=None, end_event=None):
def _create_task(self, title, completed=False, completion_date=None, end_event=None):
return Todo.objects.create(
user=self.user,
title=title,
completed=completed,
completion_date=completion_date,
end_event=end_event
end_event=end_event,
list_board=self.list_board
)

def test_dashboard_stats_view(self):
# Create tasks for testing
self.create_task('Task 1', completed=True)
self.create_task('Task 2', end_event=timezone.now() - timedelta(days=8))
self.create_task('Task 3', end_event=timezone.now())
self._create_task('Task 1', completed=True)
self._create_task('Task 2', end_event=timezone.now() - timedelta(days=8))
self._create_task('Task 3', end_event=timezone.now())

response = self.client.get(reverse('stats-list'))
response = self.client.get(reverse('statstodo-list'))
self.assertEqual(response.status_code, 200)

self.assertEqual(response.data['completed_this_week'], 1)
Expand All @@ -35,69 +38,9 @@ def test_dashboard_stats_view(self):

def test_dashboard_weekly_view(self):
# Create tasks for testing
self.create_task('Task 1', completion_date=timezone.now() - timedelta(days=1))
self.create_task('Task 2', end_event=timezone.now() - timedelta(days=8))
self.create_task('Task 3', end_event=timezone.now())
self._create_task('Task 1', completion_date=timezone.now() - timedelta(days=1))
self._create_task('Task 2', end_event=timezone.now() - timedelta(days=8))
self._create_task('Task 3', end_event=timezone.now())

response = self.client.get(reverse('weekly-list'))
self.assertEqual(response.status_code, 200)


# class DashboardStatsAPITestCase(TestCase):
# def setUp(self):
# # Create a test user
# self.user = create_test_user()

# # Create test tasks
# self.todo = Todo.objects.create(user=self.user, title='Test Todo')
# self.recurrence_task = RecurrenceTask.objects.create(user=self.user, title='Test Recurrence Task')

# # Create an API client
# self.client = APIClient()

# def test_dashboard_stats_api(self):
# # Authenticate the user
# self.client.force_authenticate(user=self.user)

# # Make a GET request to the DashboardStatsAPIView
# response = self.client.get(reverse("dashboard-stats"))

# # Assert the response status code is 200
# self.assertEqual(response.status_code, 200)

# def test_task_completion_status_update(self):
# # Authenticate the user
# self.client.force_authenticate(user=self.user)

# # Make a POST request to update the completion status of a task
# data = {'task_id': self.todo.id, 'is_completed': True}
# response = self.client.post(reverse("dashboard-stats"), data, format='json')

# # Assert the response status code is 200
# self.assertEqual(response.status_code, 200)

# # Assert the message in the response
# self.assertEqual(response.data['message'], 'Task completion status updated successfully')

# # Refresh the todo instance from the database and assert the completion status
# self.todo.refresh_from_db()
# self.assertTrue(self.todo.completed)


# class WeeklyStatsAPITestCase(TestCase):
# def setUp(self):
# # Create a test user
# self.user = create_test_user()

# # Create an API client
# self.client = APIClient()

# def test_weekly_stats_api(self):
# # Authenticate the user
# self.client.force_authenticate(user=self.user)

# # Make a GET request to the WeeklyStatsAPIView
# response = self.client.get(reverse('dashboard-weekly-stats'))

# # Assert the response status code is 200
# self.assertEqual(response.status_code, 200)
5 changes: 3 additions & 2 deletions backend/dashboard/urls.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
from django.urls import path, include
from rest_framework.routers import DefaultRouter

from .views import DashboardStatsViewSet, DashboardWeeklyViewSet
from .views import DashboardStatsTodoViewSet, DashboardWeeklyViewSet

router = DefaultRouter()
router.register(r'dashboard/stats', DashboardStatsViewSet, basename='stats')
router.register(r'dashboard/todostats', DashboardStatsTodoViewSet, basename='statstodo')
router.register(r'dashboard/weekly', DashboardWeeklyViewSet, basename='weekly')
router.register(r'dashboard/recstats', DashboardStatsTodoViewSet, basename='statsrec')
urlpatterns = [
path('', include(router.urls)),
]
167 changes: 165 additions & 2 deletions backend/dashboard/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,13 @@
from rest_framework.permissions import IsAuthenticated
from rest_framework import viewsets, mixins

from tasks.models import Todo
from tasks.models import Todo, RecurrenceTask


class DashboardStatsViewSet(viewsets.GenericViewSet, mixins.ListModelMixin):
class DashboardStatsTodoViewSet(viewsets.GenericViewSet, mixins.ListModelMixin):
"""
A viewset for retrieving statistics related to user tasks for the last 7 days.
"""
permission_classes = (IsAuthenticated,)

def get_queryset(self):
Expand Down Expand Up @@ -66,6 +69,27 @@ def list(self, request, *args, **kwargs):
# Overall completion rate
total_tasks = Todo.objects.filter(user=user).count()
overall_completion_rate = (completed_last_7_days / total_tasks) * 100 if total_tasks > 0 else 0

total_completed_tasks = Todo.objects.filter(user=user, completed=True).count()

total_tasks = Todo.objects.filter(user=user).count()

today_start = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
today_end = timezone.now().replace(hour=23, minute=59, second=59, microsecond=999999)

tasks_completed_today = Todo.objects.filter(
user=user,
completed=True,
completion_date__gte=today_start,
completion_date__lte=today_end
).count()

total_tasks_today = Todo.objects.filter(
user=user,
completion_date__gte=today_start,
completion_date__lte=today_end
).count()


data = {
"completed_last_7_days": completed_last_7_days,
Expand All @@ -75,6 +99,10 @@ def list(self, request, *args, **kwargs):
"completed_this_week": completed_this_week,
"overdue_tasks": overdue_tasks,
"overall_completion_rate": overall_completion_rate,
"total_completed_tasks": total_completed_tasks,
"total_tasks" : total_tasks,
"total_tasks_today": total_tasks_today,
"tasks_completed_today": tasks_completed_today,
}

return Response(data, status=status.HTTP_200_OK)
Expand Down Expand Up @@ -145,7 +173,142 @@ def list(self, request, *args, **kwargs):

return Response(weekly_stats, status=status.HTTP_200_OK)

class DashboardStatsReccurenceViewSet(viewsets.GenericViewSet, mixins.ListModelMixin):
"""
A viewset for retrieving statistics related to user tasks for the last 7 days.
"""
permission_classes = (IsAuthenticated,)

def get_queryset(self):
return RecurrenceTask.objects.all()

def list(self, request, *args, **kwargs):
user = self.request.user

# Calculate the start and end date for the last 7 days
end_date = timezone.now()
start_date = end_date - timedelta(days=7)

# How many tasks were completed in the last 7 days
completed_last_7_days = RecurrenceTask.objects.filter(
user=user,
completed=True,
completion_date__gte=start_date,
completion_date__lte=end_date
).count()

# Task assign last week compared with this week
tasks_assigned_last_week = RecurrenceTask.objects.filter(
user=user,
completion_date__gte=start_date - timedelta(days=7),
completion_date__lte=start_date
).count()

tasks_assigned_this_week = RecurrenceTask.objects.filter(
user=user,
completion_date__gte=start_date,
completion_date__lte=end_date
).count()

# Completed tasks from last week compared with this week
completed_last_week = RecurrenceTask.objects.filter(
user=user,
completed=True,
completion_date__gte=start_date - timedelta(days=7),
completion_date__lte=start_date
).count()

completed_this_week = RecurrenceTask.objects.filter(
user=user,
completed=True,
completion_date__gte=start_date,
completion_date__lte=end_date
).count()

overdue_tasks = RecurrenceTask.objects.filter(
user=user,
completed=False,
end_event__lt=timezone.now()
).count()

# Overall completion rate
total_tasks = RecurrenceTask.objects.filter(user=user).count()
overall_completion_rate = (completed_last_7_days / total_tasks) * 100 if total_tasks > 0 else 0

total_completed_tasks = RecurrenceTask.objects.filter(
user=user,
completed=True
).count()

total_tasks = RecurrenceTask.objects.filter(user=user).count()

tasks_completed_today = RecurrenceTask.objects.filter(
user=user,
completed=True,
completion_date__gte=timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
).count()

data = {
"completed_last_7_days": completed_last_7_days,
"tasks_assigned_last_week": tasks_assigned_last_week,
"tasks_assigned_this_week": tasks_assigned_this_week,
"completed_last_week": completed_last_week,
"completed_this_week": completed_this_week,
"overdue_tasks": overdue_tasks,
"overall_completion_rate": overall_completion_rate,
"total_completed_tasks": total_completed_tasks,
"total_tasks" : total_tasks,
"tasks_completed_today": tasks_completed_today,
}

return Response(data, status=status.HTTP_200_OK)

# class DashboardStatsAllViewSet(viewsets.GenericViewSet, mixins.ListModelMixin):
# permission_classes = [IsAuthenticated]

# def get_queryset(self):
# return Todo.objects.filter(user=self.request.user)

# def list(self, request, *args, **kwargs):
# user = request.user

# # Calculate task usage statistics
# todo_count = self.get_queryset().count()
# recurrence_task_count = RecurrenceTask.objects.filter(user=user).count()

# # Calculate how many tasks were completed in the last 7 days
# completed_todo_count_last_week = Todo.objects.filter(user=user, completed=True, last_update__gte=timezone.now() - timezone.timedelta(days=7)).count()
# completed_recurrence_task_count_last_week = RecurrenceTask.objects.filter(user=user, completed=True, last_update__gte=timezone.now() - timezone.timedelta(days=7)).count()

# # Calculate subtask completion rate
# total_subtasks = Todo.objects.filter(user=user).aggregate(total=Count('subtask__id'))['total']
# completed_subtasks = Todo.objects.filter(user=user, subtask__completed=True).aggregate(total=Count('subtask__id'))['total']

# # Calculate overall completion rate
# total_tasks = todo_count + recurrence_task_count
# completed_tasks = completed_todo_count_last_week + completed_recurrence_task_count_last_week
# overall_completion_rate = (completed_tasks / total_tasks) * 100 if total_tasks > 0 else 0

# # pie chart show
# complete_todo_percent_last_week = (completed_todo_count_last_week / todo_count) * 100 if todo_count > 0 else 0
# complete_recurrence_percent_last_week = (completed_recurrence_task_count_last_week / recurrence_task_count) * 100 if recurrence_task_count > 0 else 0
# incomplete_task_percent_last_week = 100 - complete_recurrence_percent_last_week - complete_todo_percent_last_week

# data = {
# 'todo_count': todo_count,
# 'recurrence_task_count': recurrence_task_count,
# 'completed_todo_count_last_week': completed_todo_count_last_week,
# 'completed_recurrence_task_count_last_week': completed_recurrence_task_count_last_week,
# 'total_subtasks': total_subtasks,
# 'completed_subtasks': completed_subtasks,
# 'overall_completion_rate': overall_completion_rate,
# 'complete_todo_percent_last_week': complete_todo_percent_last_week,
# 'complete_recurrence_percent_last_week' : complete_recurrence_percent_last_week,
# 'incomplete_task_percent_last_week': incomplete_task_percent_last_week,
# }

# return Response(data, status=status.HTTP_200_OK)

# class DashboardStatsAPIView(APIView):
# permission_classes = [IsAuthenticated]

Expand Down
Loading

0 comments on commit 9273181

Please sign in to comment.