views.py 4.97 KB
Newer Older
1
from django.shortcuts import get_object_or_404
2 3 4
from django.http import HttpResponse
from django.contrib.contenttypes.models import ContentType

5
from rest_framework import viewsets
6 7
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
Bruno Martin's avatar
Bruno Martin committed
8
from rest_framework.decorators import action
9

Bruno Martin's avatar
Bruno Martin committed
10
from docx import Document
11

12 13 14 15 16 17 18 19
from courses.models import Course, Unit
from courses.notes.models import Note
from courses.notes.serializers import (
    NoteSerializer,
    UnitNoteSerializer,
    LessonNoteSerializer,
    CourseNoteSerializer,
)
20

21 22

class NotesViewSet(viewsets.ModelViewSet):
23 24 25
    model = Note
    serializer_class = NoteSerializer
    filter_fields = ('content_type', 'object_id')
26
    permission_classes = (IsAuthenticated,)
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45

    def perform_create(self, serializer):
        # Only create a new note if there isn't one already for this user in this unit
        if not Note.objects.filter(object_id=serializer.validated_data['object_id'],
                                   user=self.request.user).exists():
            serializer.save(user=self.request.user)

    def perform_update(self, serializer):
        serializer.save(user=self.request.user)

    def pre_save(self, obj):
        obj.user = self.request.user
        return super(NotesViewSet, self).pre_save(obj)

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


46 47 48 49 50 51
class UserNotesViewSet(viewsets.ReadOnlyModelViewSet):

    model = Course
    queryset = Course.objects.all()
    lookup_field = 'course'
    permission_classes = (IsAuthenticated,)
52

Bruno Martin's avatar
Bruno Martin committed
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
    @staticmethod
    def get_user_notes_by_course(user):
        """
        Return the user notes organized by course
        """
        units = Unit.objects.filter(notes__user=user).exclude(notes__isnull=True)
        courses = {}
        for unit in units:
            course = unit.lesson.course
            lesson = unit.lesson
            if course.slug not in courses:
                courses[course.slug] = course
                courses[course.slug].lessons_dict = {}
            if lesson.slug not\
                    in courses[course.slug].lessons_dict:
                courses[course.slug].lessons_dict[lesson.slug] = lesson
                courses[course.slug].lessons_dict[lesson.slug].units_notes = []
            unit_type = ContentType.objects.get_for_model(unit)
            note = get_object_or_404(Note, user=user, content_type__pk=unit_type.id, object_id=unit.id)
            unit.user_note = note
            courses[course.slug].lessons_dict[lesson.slug].units_notes.append(unit)

        return courses

77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
    def retrieve(self, request, *args, **kwargs):
        user = self.request.user
        if 'course' in self.kwargs:
            course = get_object_or_404(Course, slug=self.kwargs['course'])
            units = Unit.objects.filter(lesson__course=course, notes__user=user).exclude(notes__isnull=True)

            lessons_dict = {}
            for unit in units:
                lesson = unit.lesson
                if lesson.slug not in lessons_dict:
                    lessons_dict[lesson.slug] = lesson
                    lessons_dict[lesson.slug].units_notes = []
                unit_type = ContentType.objects.get_for_model(unit)
                note = get_object_or_404(Note, user=user, content_type__pk=unit_type.id, object_id=unit.id)
                unit.user_note = note
                lessons_dict[lesson.slug].units_notes.append(unit)
93

94 95 96 97 98 99 100
            results = []
            for lesson in lessons_dict.values():
                results.append(LessonNoteSerializer(lesson).data)
            return Response(results)

    def list(self, request, *args, **kwargs):
        user = self.request.user
Bruno Martin's avatar
Bruno Martin committed
101
        courses = self.get_user_notes_by_course(user)
102

103 104 105 106 107 108 109
        results = []
        for course in courses.values():
            course.lessons_notes = course.lessons_dict.values()
            course.course_notes_number = Unit.objects.filter(lesson__course=course, notes__user=user).exclude(notes__isnull=True).count()
            del course.lessons_dict
            results.append(CourseNoteSerializer(course).data)
        return Response(results)
Bruno Martin's avatar
Bruno Martin committed
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134


    @action(detail=False, methods=['get'])
    def download(self, request):

        courses = self.get_user_notes_by_course(self.request.user)

        document = Document()

        # TODO Translate this
        document.add_heading('AEA Notes', 0)

        for course in courses.values():
            document.add_heading(course.name, level=1)
            for lesson in course.lessons_dict.values():
                document.add_heading(lesson.name, level=2)
                for unit in lesson.units_notes:
                    document.add_heading(unit.title, level=3)
                    document.add_paragraph(unit.user_note.text)

        response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
        response['Content-Disposition'] = 'attachment; filename=my-notes.docx'
        document.save(response)

        return response