Badges on user dashboard, refactoring
[oweals/karmaworld.git] / karmaworld / apps / users / views.py
1 #!/usr/bin/env python
2 # -*- coding:utf8 -*-
3 # Copyright (C) 2013  FinalsClub Foundation
4 from itertools import chain
5
6 from django.contrib.auth.models import User
7 from django.views.generic import TemplateView
8 from django.views.generic.list import MultipleObjectMixin
9 from karmaworld.apps.notes.models import Note
10 from karmaworld.apps.users.models import ALL_KARMA_EVENT_CLASSES
11
12
13 class ProfileView(TemplateView, MultipleObjectMixin):
14     model = User
15     context_object_name = 'user' # name passed to template
16     template_name = 'user_profile.html'
17
18     @staticmethod
19     def compareProfileItems(a, b):
20         if a.__class__ == Note:
21             timestampA = a.uploaded_at
22         else:
23             timestampA = a.timestamp
24
25         if b.__class__ == Note:
26             timestampB = b.uploaded_at
27         else:
28             timestampB = b.timestamp
29
30         if timestampA < timestampB:
31             return -1
32         elif timestampA > timestampB:
33             return 1
34         else:
35             return 0
36
37     def get_context_data(self, **kwargs):
38         notes = [('note', o) for o in Note.objects.filter(user=self.request.user)]
39         all_events = []
40         for cls in ALL_KARMA_EVENT_CLASSES:
41             all_events.append(
42                 [(cls.__name__, o) for o in cls.objects.filter(user=self.request.user)]
43             )
44         all_events = chain.from_iterable(all_events)
45
46         result_list = sorted(chain(notes, all_events),
47                              cmp=ProfileView.compareProfileItems,
48                              key=lambda o: o[1],
49                              reverse=True)
50
51         kwargs['object_list'] = result_list
52
53         kwargs['badge'] = self.request.user.get_profile().get_badge()
54
55         return super(ProfileView, self).get_context_data(**kwargs)
56