Example #1
0
def post(request):
  if request.is_ajax() and request.method == "POST":
    form = WallForm(request.POST)
    if form.is_valid():
      post = Post(
          user=request.user, 
          floor=request.user.get_profile().floor, 
          text=form.cleaned_data["post"]
      )
      post.save()
      
      # Render the post and send it as a response.
      template = render_to_string("news/user_post.html", {"post": post}, 
          context_instance=RequestContext(request))
      return HttpResponseRedirect(reverse("mobile_news_index"))
      return HttpResponse(json.dumps({
        "contents": template,
      }), mimetype="application/json")
    return HttpResponseRedirect(reverse("mobile_news_index"))

    # At this point there is a form validation error.
    return HttpResponse(json.dumps({
        "message": "This should not be blank."
    }), mimetype="application/json")
  
  raise Http404
Example #2
0
def post(request):
    if request.is_ajax() and request.method == "POST":
        form = WallForm(request.POST)
        if form.is_valid():
            post = Post(user=request.user,
                        floor=request.user.get_profile().floor,
                        text=form.cleaned_data["post"])
            post.save()

            # Render the post and send it as a response.
            template = render_to_string(
                "news/user_post.html", {"post": post},
                context_instance=RequestContext(request))
            return HttpResponseRedirect(reverse("mobile_news_index"))
            return HttpResponse(json.dumps({
                "contents": template,
            }),
                                mimetype="application/json")
        return HttpResponseRedirect(reverse("mobile_news_index"))

        # At this point there is a form validation error.
        return HttpResponse(json.dumps(
            {"message": "This should not be blank."}),
                            mimetype="application/json")

    raise Http404
Example #3
0
 def delete(self):
   """Custom delete method to remove the points for completed commitments."""
   profile = self.user.get_profile()
   
   if self.award_date:
     profile.remove_points(self.commitment.point_value, self.award_date)
     profile.save()
   elif profile.floor:
     message = "is no longer participating in \"%s\"." % (
       self.commitment.title,
     )
     post = Post(user=self.user, floor=self.user.get_profile().floor, text=message, style_class="system_post")
     post.save()
     
   super(CommitmentMember, self).delete()
Example #4
0
 def testAjaxPosts(self):
   """Test that we can load new posts via AJAX."""
   # Generate test posts.
   for i in range(0, DEFAULT_POST_COUNT + 1):
     text = "Testing AJAX response %d." % i
     post = Post(user=self.user, floor=self.floor, text=text)
     post.save()
   
   second_post = Post.objects.all().order_by("-pk")[0]
   response = self.client.get(reverse("news_more_posts"), HTTP_X_REQUESTED_WITH='XMLHttpRequest')
   self.failUnlessEqual(response.status_code, 200)
   self.assertNotContains(response, "Testing AJAX response 0.")
   self.assertContains(response, "See more")
   for i in range(1, DEFAULT_POST_COUNT + 1):
     self.assertContains(response, "Testing AJAX response %d" % i)
   
   response = self.client.get(reverse("news_more_posts") + ("?last_post=%d" % second_post.id), HTTP_X_REQUESTED_WITH='XMLHttpRequest')
   self.assertContains(response, "Testing AJAX response 0.")
   
Example #5
0
    def testAjaxPosts(self):
        """Test that we can load new posts via AJAX."""
        # Generate test posts.
        for i in range(0, DEFAULT_POST_COUNT + 1):
            text = "Testing AJAX response %d." % i
            post = Post(user=self.user, floor=self.floor, text=text)
            post.save()

        second_post = Post.objects.all().order_by("-pk")[0]
        response = self.client.get(reverse("news_more_posts"), HTTP_X_REQUESTED_WITH="XMLHttpRequest")
        self.failUnlessEqual(response.status_code, 200)
        self.assertNotContains(response, "Testing AJAX response 0.")
        self.assertContains(response, "See more")
        for i in range(1, DEFAULT_POST_COUNT + 1):
            self.assertContains(response, "Testing AJAX response %d" % i)

        response = self.client.get(
            reverse("news_more_posts") + ("?last_post=%d" % second_post.id), HTTP_X_REQUESTED_WITH="XMLHttpRequest"
        )
        self.assertContains(response, "Testing AJAX response 0.")
Example #6
0
 def delete(self):
   """Custom delete method to remove the points for completed commitments."""
   profile = self.user.get_profile()
   
   if self.award_date:
     title = "Commitment: %s (Removed)" % self.commitment.title
     profile.remove_points(self.commitment.point_value, self.award_date, title, self)
     profile.save()
   elif profile.floor:
     message = "is no longer participating in \"%s\"." % (
       self.commitment.title,
     )
     post = Post(user=self.user, floor=self.user.get_profile().floor, text=message, style_class="system_post")
     post.save()
     
   # Invalidate the categories cache.
   cache.delete('smartgrid-categories-%s' % self.user.username)
   cache.delete('user_events-%s' % self.user.username)
   invalidate_floor_avatar_cache(self.commitment, self.user)
   invalidate_commitments_cache(self.user)
   super(CommitmentMember, self).delete()
Example #7
0
  def save(self):
    """Custom save method to set fields depending on whether or not the item is just added or if the item is completed."""
    profile = self.user.get_profile()
    
    if not self.completion_date:
      self.completion_date = datetime.date.today() + datetime.timedelta(days=self.commitment.duration)
      
    if not self.pk and profile.floor:
      # User is adding the commitment.
      message = "is participating in the commitment \"%s\"." % (
        self.commitment.title,
      )
      post = Post(user=self.user, floor=profile.floor, text=message, style_class="system_post")
      post.save()
      
    if self.award_date:
      # User has finished the commitment.
      # Award the points
      profile = self.user.get_profile()
      profile.add_points(self.commitment.point_value, self.award_date)
      profile.save()
      
      if profile.floor:
        # Construct the points
        message = "has completed the commitment \"%s\"." % (
          self.commitment.title,
        )

        post = Post(user=self.user, floor=self.user.get_profile().floor, text=message, style_class="system_post")
        post.save()
        
    super(CommitmentMember, self).save()
    
    # Note, possibly_award is here because the member needs to be saved.
    badges.possibly_award_badge("fully_committed", user=self.user)
Example #8
0
  def _handle_approved(self):
    profile = self.user.get_profile()
    # Determine how many points to award.
    if self.activity.has_variable_points:
      points = self.points_awarded
    else:
      points = self.activity.point_value

    # Record dates.
    self.award_date = datetime.datetime.today()

    ## reverse event/excursion noshow penalty
    if (self.activity.type == "event" or self.activity.type=="excursion") and self._has_noshow_penalty():
        message = "%s: %s (Reverse No Show Penalty)" % (self.activity.type.capitalize(), self.activity.title)
        profile.add_points(4, self.award_date, message, self)

    if not self.submission_date:
      # This may happen if it is an item with a confirmation code.
      self.submission_date = self.award_date

    if self.activity.type == "event" or self.activity.type=="excursion":
      point_transaction_date = self.award_date
    else:
      point_transaction_date = self.submission_date
    
    title = "%s%s: %s" % (
        'Canopy ' if self.activity.is_canopy else '',
        self.activity.type.capitalize(), 
        self.activity.title
    )
    profile.add_points(points, point_transaction_date, title, self)

    ## award social bonus to myself if the ref user had successfully completed the activity
    social_title = "%s: %s (Social Bonus)" % (self.activity.type.capitalize(), self.activity.title)
    if self.social_email:
      ref_user = User.objects.get(email=self.social_email)
      ref_members = ActivityMember.objects.filter(user=ref_user, activity=self.activity)
      for m in ref_members:
        if m.approval_status == 'approved':
          profile.add_points(self.activity.social_bonus, point_transaction_date, social_title, self)
      
    profile.save()
    
    ## award social bonus to others referenced my email and successfully completed the activity
    ref_members = ActivityMember.objects.filter(activity=self.activity, social_email=self.user.email)
    for m in ref_members:
      if m.approval_status == 'approved':
        ref_profile = m.user.get_profile()
        ref_profile.add_points(self.activity.social_bonus, point_transaction_date, social_title, self)
        ref_profile.save()

    ## canopy group activity need to create multiple approved members
    if self.activity.is_group:
      # Assumption: given activity only belongs to one mission, so we only have to check that a group user
      # is participating in that mission.
      mission = self.activity.mission_set.all()[0]
      if self.social_email:
        group_user = User.objects.get(email=self.social_email)
        if mission in group_user.mission_set.filter(missionmember__completed=False):
          member, created = ActivityMember.objects.get_or_create(user=group_user, activity=self.activity,)

          if member.approval_status != 'approved':
            member.question = self.question
            member.response = self.response
            member.image = self.image
            member.submission_date = self.submission_date
            member.points_awarded = self.points_awarded
            member.approval_status = 'approved'
            member.save()
          
      if self.social_email2:
        group_user = User.objects.get(email=self.social_email2)
        if mission in group_user.mission_set.filter(missionmember__completed=False):
          member, created = ActivityMember.objects.get_or_create(user=group_user, activity=self.activity,)
          if created:
            member.question = self.question
            member.response = self.response
            member.image = self.image
            member.points_awarded = self.points_awarded
            member.submission_date = self.submission_date

          if member.approval_status != 'approved':
            member.approval_status = 'approved'
            member.save()
            
    if profile.floor and not self.activity.is_canopy:
      # Post on the user's floor wall.
      message = " has been awarded %d points for completing \"%s\"." % (
        points,
        self.activity.title,
      )
      post = Post(user=self.user, floor=profile.floor, text=message, style_class="system_post")
      post.save()
      
    elif self.activity.is_canopy:
      from components.canopy.models import Post as CanopyPost
      
      message = " has been awarded %d karma points for completing \"%s\"." % (
        points,
        self.activity.title,
      )
      post = CanopyPost(user=self.user, text=message)
      post.save()
Example #9
0
  def save(self):
    """Custom save method to set fields depending on whether or not the item is just added or if the item is completed."""
    profile = self.user.get_profile()
    
    if not self.completion_date:
      self.completion_date = datetime.date.today() + datetime.timedelta(days=self.commitment.duration)
      
    if not self.pk and profile.floor:
      # User is adding the commitment.
      message = "is participating in the commitment \"%s\"." % (
        self.commitment.title,
      )
      post = Post(user=self.user, floor=profile.floor, text=message, style_class="system_post")
      post.save()
      
    if self.award_date:
      # User has finished the commitment.
      # Award the points
      profile = self.user.get_profile()
      message = "%sCommitment: %s"  % (
          'Canopy ' if self.commitment.is_canopy else '',
          self.commitment.title
      )
      profile.add_points(self.commitment.point_value, self.award_date, message, self)
      profile.save()

      ## award social bonus to myself if the ref user had successfully completed the activity
      social_message = message + "(Social Bonus)"
      if self.social_email:
        ref_user = User.objects.get(email=self.social_email)
        ref_members = CommitmentMember.objects.filter(user=ref_user, commitment=self.commitment)
        for m in ref_members:
          if m.award_date:
            profile.add_points(self.commitment.social_bonus, self.award_date, social_message, self)
            profile.save()
      
      ## award social bonus to others who referenced my email and successfully completed the activity
      ref_members = CommitmentMember.objects.filter(commitment=self.commitment, social_email=self.user.email)
      for m in ref_members:
        if m.award_date:
          ref_profile = m.user.get_profile()
          ref_profile.add_points(self.commitment.social_bonus, self.award_date, social_message, self)
          ref_profile.save()
      
      if profile.floor:
        # Construct the points
        message = "has completed the commitment \"%s\"." % (
          self.commitment.title,
        )

        post = Post(user=self.user, floor=self.user.get_profile().floor, text=message, style_class="system_post")
        post.save()
        
    # Invalidate the categories cache.
    cache.delete('smartgrid-categories-%s' % self.user.username)
    cache.delete('user_events-%s' % self.user.username)
    invalidate_floor_avatar_cache(self.commitment, self.user)
    invalidate_commitments_cache(self.user)
    super(CommitmentMember, self).save()
    
    # Note, possibly_award is here because the member needs to be saved.
    badges.possibly_award_badge(user_badges.FullyCommittedBadge.slug, user=self.user)
Example #10
0
 def save(self, *args, **kwargs):
   """Custom save method to award/remove points if the activitymember is approved or rejected."""
   if self.approval_status == u"pending":
     # Mark pending items as submitted.
     self.submission_date = datetime.datetime.today()
     
   elif self.approval_status == u"approved" and not self.award_date:
     # Award users points and update wall.
     self.award_date = datetime.datetime.today()
     
     # Determine how many points to award.
     if self.activity.has_variable_points:
       points = self.points_awarded
     else:
       points = self.activity.point_value
       
     if not self.submission_date:
       # This may happen if it is an item with a confirmation code.
       self.submission_date = self.award_date
     profile = self.user.get_profile()
     profile.add_points(points, self.submission_date)
     profile.save()
     
     if profile.floor:
       # Post on the user's floor wall.
       message = " has been awarded %d points for completing \"%s\"." % (
         points,
         self.activity.title,
       )
       post = Post(user=self.user, floor=profile.floor, text=message, style_class="system_post")
       post.save()
     
   elif self.approval_status != u"approved" and self.award_date:
     # Removing user points and resetting award date.
     # Determine how many points to remove.
     if self.activity.has_variable_points:
       points = self.points_awarded
     else:
       points = self.activity.point_value
       
     profile = self.user.get_profile()
     profile.remove_points(points, self.submission_date)
     profile.save()
     self.award_date = None
     self.submission_date = None # User will have to resubmit.
     
   super(ActivityMember, self).save()
   
   # We check here for a rejected item because it should have an id now.
   if self.approval_status == u"rejected":
     # Construct the message to be sent.
     message = "Your response to <a href='%s'>%s</a> was not approved." % (
         reverse("activity_task", args=(self.activity.id,)),
         self.activity.title
     )
     
     message += " You can still get points by clicking on the link and trying again."
     # message += " Please check your <a href='%s'>profile</a> for more information." % (
     #           reverse("profile_rejected", args=(self.id,)),
     #       )
     
     UserNotification.create_error_notification(self.user, message)