Badges on user dashboard, refactoring
authorCharles Connell <charles@connells.org>
Thu, 23 Jan 2014 15:44:21 +0000 (10:44 -0500)
committerCharles Connell <charles@connells.org>
Thu, 23 Jan 2014 15:44:36 +0000 (10:44 -0500)
karmaworld/apps/courses/views.py
karmaworld/apps/notes/views.py
karmaworld/apps/users/models.py
karmaworld/apps/users/views.py
karmaworld/assets/css/global.css
karmaworld/templates/courses/course_detail.html
karmaworld/templates/user_profile.html
karmaworld/utils/__init__.py [new file with mode: 0644]
karmaworld/utils/ajax_increment.py [new file with mode: 0644]

index 36df93f5976656ef77bdde04c0bdf25dc0fc2be3..bb12926f020db67297dd48f6aa88c8cc85db44b9 100644 (file)
@@ -20,6 +20,9 @@ from karmaworld.apps.courses.models import Course
 from karmaworld.apps.courses.models import School
 from karmaworld.apps.notes.models import Note
 from karmaworld.apps.users.models import CourseKarmaEvent
+from karmaworld.utils import ajax_increment, format_session_increment_field
+
+FLAG_FIELD = 'flags'
 
 
 class CourseListView(ListView, ModelFormMixin, ProcessFormView):
@@ -73,6 +76,9 @@ class CourseDetailView(DetailView):
         # Include "Add Note" button in header
         kwargs['display_add_note'] = True
 
+        if self.request.session.get(format_session_increment_field(Course, self.object.id, FLAG_FIELD), False):
+            kwargs['already_flagged'] = True
+
         return kwargs
 
 
@@ -167,7 +173,7 @@ def school_course_instructor_list(request):
         school = School.objects.get(id__exact=_school_id)
     except (MultipleObjectsReturned, ObjectDoesNotExist):
         return HttpResponseBadRequest(json.dumps({'status': 'fail',
-                                                'message': 'school id did not match exactly one school'}),
+                                                  'message': 'school id did not match exactly one school'}),
                                     mimetype="application/json")
 
     # Look up matching courses
@@ -181,34 +187,6 @@ def school_course_instructor_list(request):
                         mimetype="application/json")
 
 
-def format_session_increment_field(id, field):
-    return field + '-' + str(id)
-
-
-def ajaxIncrementBase(request, pk, field, event_processor=None):
-    """Increment a course's field by one."""
-    if not (request.method == 'POST' and request.is_ajax()):
-        # return that the api call failed
-        return HttpResponseBadRequest(json.dumps({'status': 'fail', 'message': 'must be a POST ajax request'}),
-                                      mimetype="application/json")
-
-    try:
-        course = Course.objects.get(pk=pk)
-        count = getattr(course, field)
-        setattr(course, field,  count+1)
-        course.save()
-
-        event_processor(request.user, course)
-
-        # Record that user has performed this, to prevent
-        # them from doing it again
-        request.session[format_session_increment_field(pk, field)] = True
-    except ObjectDoesNotExist:
-        return HttpResponseNotFound(json.dumps({'status': 'fail', 'message': 'course id does not match a course'}),
-                                    mimetype="application/json")
-
-    return HttpResponse(status=204)
-
 def process_course_flag_events(request_user, course):
     # Take a point away from person flagging this course
     if request_user.is_authenticated():
@@ -217,5 +195,5 @@ def process_course_flag_events(request_user, course):
 
 def flag_course(request, pk):
     """Record that somebody has flagged a note."""
-    return ajaxIncrementBase(request, pk, 'flags', process_course_flag_events)
+    return ajax_increment(Course, request, pk, FLAG_FIELD, process_course_flag_events)
 
index bc66cb1762266835a2585f211d9ff7c7be6b7bb8..09b7827babae4dc8675986d490592ab4ed859ef7 100644 (file)
@@ -9,6 +9,7 @@ from django.core.exceptions import ObjectDoesNotExist
 from karmaworld.apps.courses.models import Course
 from karmaworld.apps.notes.search import SearchIndex
 from karmaworld.apps.users.models import NoteKarmaEvent
+from karmaworld.utils.ajax_increment import *
 
 import os
 
@@ -22,6 +23,7 @@ from django.views.generic.detail import SingleObjectMixin
 from karmaworld.apps.notes.models import Note
 from karmaworld.apps.notes.forms import NoteForm
 
+
 logger = logging.getLogger(__name__)
 
 PDF_MIMETYPES = (
@@ -40,9 +42,6 @@ def is_ppt(self):
         return True
     return False
 
-def format_session_increment_field(id, field):
-    return field + '-' + str(id)
-
 THANKS_FIELD = 'thanks'
 FLAG_FIELD = 'flags'
 
@@ -64,10 +63,10 @@ class NoteDetailView(DetailView):
         if self.object.mimetype in PDF_MIMETYPES:
             kwargs['pdf_controls'] = True
 
-        if self.request.session.get(format_session_increment_field(self.object.id, THANKS_FIELD), False):
+        if self.request.session.get(format_session_increment_field(Note, self.object.id, THANKS_FIELD), False):
             kwargs['already_thanked'] = True
 
-        if self.request.session.get(format_session_increment_field(self.object.id, FLAG_FIELD), False):
+        if self.request.session.get(format_session_increment_field(Note, self.object.id, FLAG_FIELD), False):
             kwargs['already_flagged'] = True
 
         return super(NoteDetailView, self).get_context_data(**kwargs)
@@ -230,32 +229,6 @@ class NoteSearchView(ListView):
         return super(NoteSearchView, self).get_context_data(**kwargs)
 
 
-def ajaxIncrementBase(request, pk, field, event_processor=None):
-    """Increment a note's field by one."""
-    if not (request.method == 'POST' and request.is_ajax()):
-        # return that the api call failed
-        return HttpResponseBadRequest(json.dumps({'status': 'fail', 'message': 'must be a POST ajax request'}),
-                                    mimetype="application/json")
-
-    try:
-        # Increment counter
-        note = Note.objects.get(pk=pk)
-        count = getattr(note, field)
-        setattr(note, field,  count+1)
-        note.save()
-
-        event_processor(request.user, note)
-
-        # Record that user has performed this, to prevent
-        # them from doing it again
-        request.session[format_session_increment_field(pk, field)] = True
-    except ObjectDoesNotExist:
-        return HttpResponseNotFound(json.dumps({'status': 'fail', 'message': 'note id does not match a note'}),
-                                    mimetype="application/json")
-
-    return HttpResponse(status=204)
-
-
 def process_note_thank_events(request_user, note):
     # Give points to the person who uploaded this note
     if note.user != request_user:
@@ -264,7 +237,7 @@ def process_note_thank_events(request_user, note):
 
 def thank_note(request, pk):
     """Record that somebody has thanked a note."""
-    return ajaxIncrementBase(request, pk, THANKS_FIELD, process_note_thank_events)
+    return ajax_increment(Note, request, pk, THANKS_FIELD, process_note_thank_events)
 
 
 def process_note_flag_events(request_user, note):
@@ -279,6 +252,6 @@ def process_note_flag_events(request_user, note):
 
 def flag_note(request, pk):
     """Record that somebody has flagged a note."""
-    return ajaxIncrementBase(request, pk, FLAG_FIELD, process_note_flag_events)
+    return ajax_increment(Note, request, pk, FLAG_FIELD, process_note_flag_events)
 
 
index de80967532d2702f71008bcf988531e255782344..b13f4792819ed51b2eb807646a67eaf35a59f2a4 100644 (file)
@@ -65,7 +65,11 @@ class UserProfile(models.Model):
         for badge in self.BADGES:
             if points >= self.BADGE_THRESHOLDS[badge]:
                 highest_badge = badge
-        return highest_badge
+
+        if highest_badge is not self.NO_BADGE:
+            return self.BADGE_NAMES[highest_badge]
+        else:
+            return None
 
     def __unicode__(self):
         return self.user.__unicode__()
index 7bd02f621cfc3ebe65b9e686e565428546f3e4d4..8d5feab82744e808586cd064377374021e6ec76a 100644 (file)
@@ -50,5 +50,7 @@ class ProfileView(TemplateView, MultipleObjectMixin):
 
         kwargs['object_list'] = result_list
 
+        kwargs['badge'] = self.request.user.get_profile().get_badge()
+
         return super(ProfileView, self).get_context_data(**kwargs)
 
index e4d2d9747fbe4c717ee9a087c35a4ae6f575b511..0116f235534e270a704d17b23b10a241a9a46dd3 100644 (file)
@@ -559,6 +559,21 @@ a.activity_target:hover
   font-family: "MuseoSlab-900";
 }
 
+.badge
+{
+  background: none repeat scroll 0 0 #FFFFCD;
+  border-top-color: rgb(238, 238, 238);
+  border-right-color: rgb(204, 204, 204);
+  border-bottom-color: rgb(204, 204, 204);
+  border-left-color: rgb(238, 238, 238);
+  border-style: solid;
+  border-width: 1px;
+  font-size: 14px;
+  padding: 4px 6px 4px 6px;
+  font-weight: bold;
+  line-height: 250%;
+}
+
 .course_meta_action
 {
   height: 36px;
index 410d4374f0f5b2beec9d00050efd4d3b6743741b..f539f02e0665bb8fd0e03466bfdd273b1fc2b2f9 100644 (file)
@@ -65,8 +65,8 @@
         <div id="course_actions" class="large-3 medium-6 small-12 columns small-centered">
           <div class="row">
             <div class="small-12 column center">
-              <a href="#" id="flag-button"><img src="{{ STATIC_URL }}img/note_flag.png" alt="note_flag" width="25" height="35"/></a>
-              <a href="#" id="flag-button-disabled" class="hide"><img src="{{ STATIC_URL }}img/note_flag_disabled.png" alt="note_flag" width="25" height="35"/></a>
+              <a href="#" id="flag-button" {% if already_flagged %} class="hide" {% endif %}><img src="{{ STATIC_URL }}img/note_flag.png" alt="note_flag" width="25" height="35"/></a>
+              <a href="#" id="flag-button-disabled" {% if not already_flagged %} class="hide" {% endif %}><img src="{{ STATIC_URL }}img/note_flag_disabled.png" alt="note_flag" width="25" height="35"/></a>
             </div>
           </div>
         </div><!-- /note_actions -->
index 7d4bd528ed1aff63444968f8bb19f27ae3cf3038..c37dc6d60547249afc1a4c224ad11aa445922b23 100644 (file)
       <div class="row">
         <div class="small-10 columns small-centered center header_title">
           {% user_display user %}
-        </div>
+          {% if badge %}
+            <span class="badge">{{ badge }}</span>
+          {% endif %}
       </div>
+        </div>
       <div class="row">
         <div class="small-12 medium-8 large-4 columns small-centered">
           <div class="row">
diff --git a/karmaworld/utils/__init__.py b/karmaworld/utils/__init__.py
new file mode 100644 (file)
index 0000000..e9c769d
--- /dev/null
@@ -0,0 +1 @@
+from ajax_increment import *
\ No newline at end of file
diff --git a/karmaworld/utils/ajax_increment.py b/karmaworld/utils/ajax_increment.py
new file mode 100644 (file)
index 0000000..d399443
--- /dev/null
@@ -0,0 +1,35 @@
+import json
+from django.core.exceptions import ObjectDoesNotExist
+from django.http import HttpResponseBadRequest, HttpResponseNotFound, HttpResponse
+
+
+def format_session_increment_field(cls, id, field):
+    return cls.__name__ + '-' + field + '-' + str(id)
+
+
+def ajax_increment(cls, request, pk, field, event_processor=None):
+    """Increment a note's field by one."""
+    if not (request.method == 'POST' and request.is_ajax()):
+        # return that the api call failed
+        return HttpResponseBadRequest(json.dumps({'status': 'fail', 'message': 'must be a POST ajax request'}),
+                                      mimetype="application/json")
+
+    try:
+        # Increment counter
+        note = cls.objects.get(pk=pk)
+        count = getattr(note, field)
+        setattr(note, field,  count+1)
+        note.save()
+
+        if event_processor:
+            event_processor(request.user, note)
+
+        # Record that user has performed this, to prevent
+        # them from doing it again
+        request.session[format_session_increment_field(cls, pk, field)] = True
+    except ObjectDoesNotExist:
+        return HttpResponseNotFound(json.dumps({'status': 'fail', 'message': 'note id does not match a note'}),
+                                    mimetype="application/json")
+
+    return HttpResponse(status=204)
+