views.py 15.6 KB
Newer Older
1
from django.contrib.auth import get_user_model
2
from django.contrib.auth.models import User
3
from django.db.models import Count
Matheus Miranda's avatar
Matheus Miranda committed
4 5
from django.utils import timezone
from datetime import timedelta
6

Matheus Miranda's avatar
Matheus Miranda committed
7
from rest_framework import viewsets, filters, views, permissions, status
8 9
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
10 11 12
from rest_framework.pagination import PageNumberPagination

from django_filters.rest_framework import DjangoFilterBackend
13 14 15 16 17 18

from rest_pandas import PandasViewSet
from rest_pandas.renderers import PandasCSVRenderer, PandasJSONRenderer
import pandas as pd

from discussion.models import Comment, CommentLike, Topic, TopicLike
Matheus Miranda's avatar
Matheus Miranda committed
19
from baquara.users.models import UserLogin
20

21
from courses.models import Course, CourseStudent, StudentProgress
22 23 24 25 26 27 28
from courses.classes.models import Class

from courses_learning_objects.models import LearningObject, Answer

from courses.reports.serializers import (
    UserInDetailSerializer,
    UsersByClassSerializer,
29
    UserStatsSerializer
30 31
)

32 33 34
from django.core.exceptions import ObjectDoesNotExist


35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
User = get_user_model()


class SummaryViewSet(viewsets.ViewSet):

    permission_classes = [IsAuthenticated]

    def list_new(self, request):

        courses = Course.objects.all().prefetch_related('class_set', 'course_students')
        stats = {}
        activities = {}
        unit_set = {}
        all_answers = {}
        all_progress = {}

        for course in courses:
            stats[course.slug] = {
                'name': course.name,
54
                'user_count': course.course_students.filter(user__is_active=True).count(),
55 56 57 58 59 60 61 62 63 64 65 66 67
                'user_finished_course_count': 0,
                'classes' : []
            }
            unit_set[course.slug] = course.unit_set.count()
            le_activities = LearningObject.objects \
                .filter(unit__lesson__in=course.lessons
                        .filter(status='published'),
                        type="discussion")
            all_answers[course.slug] = {}
            all_progress[course.slug] = {}
            activities[course.slug] = le_activities.count()

            aux = Answer.objects \
68
                .filter(activity__in=le_activities, user__is_active=True)\
69 70 71 72 73 74 75 76
                .values('user')\
                .order_by('user')\
                .annotate(Count('user'))
            for ans in aux:
                all_answers[course.slug][ans['user']] = ans['user__count']

            aux = StudentProgress.objects\
                .exclude(complete=None) \
77
                .filter(unit__lesson__course=course, user__is_active=True)\
78 79 80 81 82 83 84 85 86 87 88
                .values('user')\
                .order_by('user').\
                annotate(Count('user'))

            for progress in aux:
                all_progress[course.slug][progress['user']] = progress['user__count']



        def __plpc_course_finished(activities, answers, units_len,
                                  units_done_len, min_percent_to_complete):
Bruno Martin's avatar
Bruno Martin committed
89
            return __percent_progress(units_len, units_done_len) >= min_percent_to_complete and \
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
                   activities == answers

        def __percent_progress(units_len, units_done_len):
            if units_len <= 0:
                return 0
            return int(100.0 * units_done_len / units_len)

        def __can_emmit_receipt(cclass, certificate, answers, user):
            course_finished = __plpc_course_finished(activities[cclass.course.slug],
                                                    answers,
                                                    unit_set[cclass.course.slug],
                                                    all_progress[cclass.course.slug].get(user, 0),
                                                    cclass.course.min_percent_to_complete)
            if not cclass.user_can_certificate and not course_finished:
                return False
            if cclass.user_can_certificate_even_without_progress and certificate:
                return True
            return course_finished

        classes = Class.objects.filter(course__in=courses).prefetch_related('students').select_related('course')
        for cclass in classes:
111 112
            certified = cclass.get_students.filter(certificate__type='certificate', user__is_active=True).select_related('course', 'user')
            not_certified = cclass.get_students.exclude(certificate__type='certificate', user__is_active=False).select_related('course', 'user')
113 114
            cclass_stats = {
                'name': cclass.name,
115
                'user_count': cclass.get_students.filter(user__is_active=True).count(),
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
                'certificate_count': certified.count(),
                'user_finished': 0
            }

            for cs in certified:
                answers = all_answers[cclass.course.slug].get(cs.user.id, 0)
                if __can_emmit_receipt(cclass, True, answers, cs.user.id):
                    stats[cclass.course.slug]['user_finished_course_count'] += 1
                    cclass_stats['user_finished'] += 1

            for cs in not_certified:
                answers = all_answers[cclass.course.slug].get(cs.user.id, 0)
                if __can_emmit_receipt(cclass, False, answers, cs.user.id):
                    stats[cclass.course.slug]['user_finished_course_count'] += 1
                    cclass_stats['user_finished'] += 1

            stats[cclass.course.slug]['classes'].append(cclass_stats)

        stats = list(stats.values())

136 137 138 139 140 141 142 143 144 145 146
        users_active = User.objects.filter(is_active=True)
        users_director_total = users_active.filter(groups__name='Diretor Escolar').count()
        users_director_login = users_active.filter(groups__name='Diretor Escolar').exclude(last_login=None).count()
        users_coordinator_total = users_active.filter(groups__name='Coordenação Pedagógica').count()
        users_coordinator_login = users_active.filter(groups__name='Coordenação Pedagógica').exclude(last_login=None).count()
        users_technical_total = users_active.filter(groups__name='Equipe Técnica').count()
        users_technical_login = users_active.filter(groups__name='Equipe Técnica').exclude(last_login=None).count()
        users_formadores_total = users_active.filter(groups__name='Formadores').count()
        users_formadores_login = users_active.filter(groups__name='Formadores').exclude(last_login=None).count()
        users_apoio_total = users_active.filter(groups__name='Apoio Pedagógico').count()
        users_apoio_login = users_active.filter(groups__name='Apoio Pedagógico').exclude(last_login=None).count()
147 148 149 150 151 152 153 154 155 156 157 158

        response = Response({
            'users_director_total': users_director_total,
            'users_director_login': users_director_login,
            'users_coordinator_total': users_coordinator_total,
            'users_coordinator_login': users_coordinator_login,
            'users_technical_total': users_technical_total,
            'users_technical_login': users_technical_login,
            'users_formadores_total': users_formadores_total,
            'users_formadores_login': users_formadores_login,
            'users_apoio_total': users_apoio_total,
            'users_apoio_login': users_apoio_login,
159 160 161 162 163
            'user_count': User.objects.filter(is_active=True).count(),
            'user_inactive_count': User.objects.filter(is_active=False).count(),
            'total_number_of_topics': Topic.objects.filter(author__is_active=True).count(),
            'total_number_of_comments': Comment.objects.filter(author__is_active=True).count(),
            'total_number_of_likes': TopicLike.objects.filter(user__is_active=True).count() + CommentLike.objects.filter(user__is_active=True).count(),
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
            'statistics_per_course': stats})

        return response

    def list(self, request):
        return self.list_new(request)

    def list_old(self, request):
        courses = Course.objects.all()
        stats = []
        for course in courses:
            course_stats = {
                'name': course.name,
                'user_count': course.course_students.count(),
                'user_finished_course_count': 0
            }
            classes = Class.objects.filter(course=course)
            classes_stats = []
            for cclass in classes:
                cclass_stats = {
                    'name': cclass.name,
                    'user_count': cclass.get_students.count(),
                    'certificate_count': 0,
                    'user_finished': 0
                }

                course_students = cclass.get_students.all()
                certified = course_students.filter(certificate__type='certificate')
                cclass_stats['certificate_count'] += certified.count()

                for cs in course_students:
                    # if cs.course_finished:
                    #    cclass_stats['user_finished'] += 1
                    if cs.can_emmit_receipt():
                        course_stats['user_finished_course_count'] += 1
                        cclass_stats['user_finished'] += 1

                classes_stats.append(cclass_stats)

            course_stats['classes'] = classes_stats
            stats.append(course_stats)

        response = Response({
            'user_count': User.objects.count(),
            'total_number_of_topics': Topic.objects.count(),
            'total_number_of_comments': Comment.objects.count(),
            'total_number_of_likes': TopicLike.objects.count() + CommentLike.objects.count(),
            'statistics_per_course': stats})
        return response


class UsersByGroupViewSet(PandasViewSet):

    permission_classes = [IsAuthenticated]
    renderer_classes = [PandasCSVRenderer, PandasJSONRenderer]
    queryset = User.objects.all()

    def get_queryset(self):
        self.queryset = super(UsersByGroupViewSet, self).get_queryset()

        groups = self.request.query_params.get('group', None)
        if groups is not None:
            self.queryset = self.queryset.filter(groups__name__in=groups.split(','))

228
        self.queryset = self.queryset.prefetch_related('groups', 'coursestudent_set')
229 230 231 232 233 234 235 236 237

        return self.queryset

    def list(self, request, format=None):

        queryset = self.get_queryset()

        serializer = UserInDetailSerializer(queryset, many=True)
        # in order to get the data in the wanted column form, I'll need to make some transformations
238
        return self.update_pandas_headers(Response(self.transform_data(serializer.data)))
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253

    def transform_data(self, data):
        response = []
        for user in data:
            for course in user.get('courses'):
                user.update({
                    u'{} - progresso'.format(course['course_name']): course['percent_progress'],
                    u'{} - nome da turma'.format(course['course_name']): course['class_name'],
                    u'{} - concluiu'.format(course['course_name']): course['course_finished'],
                    u'{} - possui certificado'.format(course['course_name']): course['has_certificate']
                })
            user.pop('courses', None)
            response.append(user)
        return pd.DataFrame.from_dict(response)

254
    def get_pandas_filename(self, request, format):
255

256 257
        return 'Relatório de atividades dos usuários'

258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289

class UsersByClassViewSet(PandasViewSet):

    permission_classes = [IsAuthenticated]
    queryset = CourseStudent.objects.all()

    def get_queryset(self):

        self.queryset = super(UsersByClassViewSet, self).get_queryset()

        ids = self.request.query_params.get('id', [])
        if ids:
            ids = [int(i) for i in ids.split(',')]

            classes = Class.objects.all().filter(pk__in=ids).prefetch_related('students')
            students = [cls.students.all() for cls in classes]
            students = [s for cls in students for s in cls]
            courses = [cls['course_id'] for cls in classes.values()]

            self.queryset = self.queryset \
                .filter(user__in=students, course__id__in=courses)

        self.queryset = self.queryset.select_related('user', 'course', 'certificate')
        self.queryset = self.queryset.prefetch_related('course__lessons__units')

        return self.queryset

    def list(self, request, format=None):

        queryset = self.get_queryset()
        serializer = UsersByClassSerializer(queryset, many=True)

290 291
        return self.update_pandas_headers(Response(pd.DataFrame
                        .from_dict(self.transform_data(serializer.data))))
292
                        # .set_index('cpf'))
293 294 295 296 297 298 299 300 301 302 303 304 305

    def transform_data(self, data):
        for coursestudent in data:
            for lesson in coursestudent.get(u'percent_progress_by_lesson', None):
                coursestudent.update({
                    u'Lição {} - Progresso'.format(lesson['name']): lesson['progress']
                })
                for activity in lesson.get(u'activities', None):
                    coursestudent.update({
                        u'Lição {} - Atividade {} realizada'.format(lesson['name'], activity['name']): activity['done']
                    })
            coursestudent.pop('percent_progress_by_lesson', None)
        return data
306 307

    def get_pandas_filename(self, request, format):
308

309
        return 'Relatório de progresso dos usuários'
Matheus Miranda's avatar
Matheus Miranda committed
310 311 312 313 314 315 316 317


class ReportPagination(PageNumberPagination):
    page_size = 50
    page_size_query_param = 'page_size'
    max_page_size = 100


318
class UserStatsViewSet(viewsets.ReadOnlyModelViewSet):
Matheus Miranda's avatar
Matheus Miranda committed
319 320
    model = User
    queryset = User.objects.all().order_by('name')
Matheus Miranda's avatar
Matheus Miranda committed
321
    group_id = ''
322 323
    serializer_class = UserStatsSerializer
    filterset_fields = ['groups']
324
    permission_classes = [IsAuthenticated]
Matheus Miranda's avatar
Matheus Miranda committed
325 326 327 328 329 330 331 332 333 334 335 336 337 338
    pagination_class = ReportPagination
    filter_backends = [
        filters.SearchFilter,
        DjangoFilterBackend,
    ]
    search_fields = [
        'username',
        'name',
        'first_name',
        'last_name',
        'email'
    ]

    def get_queryset(self):
339 340 341
        queryset = super().get_queryset()
        group_id = self.request.query_params.get('group')

Glaucia S. Santos's avatar
Glaucia S. Santos committed
342
        queryset = queryset.filter(groups__id=group_id, is_active=True)
Matheus Miranda's avatar
Matheus Miranda committed
343

344
        return queryset
Matheus Miranda's avatar
Matheus Miranda committed
345 346 347 348 349


class UserAccessView(views.APIView):
    permission_classes = [permissions.IsAuthenticated]

350
    def format_date(self, timestamp):
351 352 353 354
        from django.utils import timezone
        tz_str = timezone.localtime(timestamp)
        date, hour = tz_str.strftime('%d-%m-%Y %H:%M:%S').split()
        return '{} às {}'.format(date, hour)
355

Matheus Miranda's avatar
Matheus Miranda committed
356 357 358 359
    def get(self, request, format=None):
        user_id = request.GET['user']
        user = User.objects.get(id=user_id)

360
        actions = user.actor_actions.all().order_by('timestamp')
Matheus Miranda's avatar
Matheus Miranda committed
361 362

        last_access = ''
Matheus Miranda's avatar
Matheus Miranda committed
363
        last_login = ''
Matheus Miranda's avatar
Matheus Miranda committed
364
        last_completed_activity = ''
Matheus Miranda's avatar
Matheus Miranda committed
365 366 367 368
        accesses_7_days = 0
        accesses_30_days = 0

        if actions:
Matheus Miranda's avatar
Matheus Miranda committed
369
            last_access_obj = actions.filter(verb='access').last()
Matheus Miranda's avatar
Matheus Miranda committed
370 371
            last_activity_obj = actions.filter(verb='answered').last()

Matheus Miranda's avatar
Matheus Miranda committed
372 373
            if last_access_obj:
                last_access = self.format_date(last_access_obj.timestamp)
Matheus Miranda's avatar
Matheus Miranda committed
374
            if last_activity_obj:
375
                last_completed_activity = self.format_date(last_activity_obj.timestamp)
Matheus Miranda's avatar
Matheus Miranda committed
376 377 378 379 380 381 382

            time_delta = timezone.now() - timedelta(days=7)
            accesses_7_days = actions.filter(verb='access', timestamp__gte=time_delta).count()

            time_delta = timezone.now() - timedelta(days=30)
            accesses_30_days = actions.filter(verb='access', timestamp__gte=time_delta).count()

383 384 385
        if user.last_login:
            last_login = self.format_date(user.last_login)

Matheus Miranda's avatar
Matheus Miranda committed
386
        access_data = {
Matheus Miranda's avatar
Matheus Miranda committed
387
            'last_login': last_login,
388
            'last_completed_activity': last_completed_activity,
Matheus Miranda's avatar
Matheus Miranda committed
389 390 391 392 393 394
            'last_access': last_access,
            'accesses_7_days': accesses_7_days,
            'accesses_30_days': accesses_30_days
        }

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