def notify_round_started(): """Notify the user of a start of a round.""" if not challenge_mgr.in_competition(): return today = datetime.datetime.today() current_round = None previous_round = None rounds = challenge_mgr.get_all_round_info()["rounds"] for key in rounds.keys(): # We're looking for a round that ends today and another that starts # today (or overall) start = rounds[key]["start"] end = rounds[key]["end"] # Check yesterday's round and check for the current round. if start < (today - datetime.timedelta(days=1)) < end: previous_round = key if start < today < end: current_round = key print "Previous Round: %s" % previous_round print "Current Round: %s" % current_round if current_round and previous_round and current_round != previous_round: print "Sending out round transition notices." template = NoticeTemplate.objects.get(notice_type="round-transition") message = template.render({"PREVIOUS_ROUND": previous_round, "CURRENT_ROUND": current_round}) for user in User.objects.all(): UserNotification.create_info_notification(user, message, display_alert=True)
def _handle_activity_notification(self, status): """Creates a notification for rejected or approved tasks. This also creates an email message if it is configured. """ # don't create notification if the action is the SETUP_WIZARD_ACTIVITY # that is used in the setup wizard. if self.action.slug == SETUP_WIZARD_ACTIVITY: return # Construct the message to be sent. status_nicely = 'not approved' if status != 'approved' else status message = 'Your response to <a href="%s#action-details">"%s"</a> %s was %s.' % ( reverse("activity_task", args=(self.action.type, self.action.slug,)), self.action.title, # The below is to tell the javascript to convert into a pretty date. # See the prettyDate function in media/js/makahiki.js '<span class="rejection-date" title="%s"></span>' % self.submission_date.isoformat(), status_nicely, ) if status != 'approved': message += " You can still get points by clicking on the link and trying again." UserNotification.create_error_notification(self.user, message, display_alert=True, content_object=self) else: points = self.points_awarded if self.points_awarded else self.action.point_value message += " You earned %d points!" % points UserNotification.create_success_notification(self.user, message, display_alert=True, content_object=self)
def action_feedback(request, action_type, slug): """Handle feedback for an action.""" _ = action_type action = smartgrid.get_action(slug=slug) user = request.user profile = request.user.profile form = ActionFeedbackForm(request.POST) if form.is_valid(): #print form.cleaned_data # should do something ?? pass feedback, created = ActionFeedback.objects.get_or_create(action=action, user=user) has_comment = False has_score = False if 'Score' in request.POST: feedback.rating = request.POST['Score'] has_score = True else: feedback.rating = 0 if 'comments' in request.POST: feedback.comment = request.POST['comments'] if len(feedback.comment.strip() ) > 0: # ignore pure whitespace comments has_comment = True else: feedback.comment = "" feedback.changed = datetime.datetime.now() if has_comment or has_score: feedback.save() # only save if they provided any feedback else: if created: feedback.delete() # remove the feedback created = False # reset created for giving points if created: # Give the user points for providing feedback profile.add_points(score_mgr.feedback_points(), datetime.datetime.today(), "{0}: {1} (Provide feedback)"\ .format(action.type.capitalize(), action.title), action) if score_mgr.feedback_points() > 0: message = "Thank you for your feedback on {0}: {1} you've earned {2} points"\ .format(action.type.capitalize(), action.title, score_mgr.feedback_points()) else: message = "Thank you for your feedback on {0}: {1}"\ .format(action.type.capitalize(), action.title) UserNotification.create_info_notification(user, message, display_alert=True, content_object=action) # Take them back to the action page. return HttpResponseRedirect( reverse("activity_task", args=( action.type, action.slug, )))
def send(self): """ Sends a reminder email to the user. """ if not self.sent: challenge = challenge_mgr.get_challenge() subject = "[%s] Reminder for %s" % (challenge.name, self.action.title) message = render_to_string( "email/activity_reminder.txt", { "action": self.action, "user": self.user, "COMPETITION_NAME": challenge.name, "domain": challenge.domain, }) html_message = render_to_string( "email/activity_reminder.html", { "action": self.action, "user": self.user, "COMPETITION_NAME": challenge.name, "domain": challenge.domain, }) UserNotification.create_email_notification(self.email_address, subject, message, html_message) self.sent = True self.save()
def notify_commitment_end(): """Notify the user of the end of a commitment period and award their points.""" members = ActionMember.objects.filter(completion_date=datetime.date.today(), action__type="commitment", award_date__isnull=True) # try and load the notification template. template = None try: template = NoticeTemplate.objects.get(notice_type="commitment-ready") except NoticeTemplate.DoesNotExist: pass for member in members: if template: message = template.render({"COMMITMENT": member.action}) else: message = "Your commitment <a href='%s'>%s</a> has ended." % ( reverse("activity_task", args=(member.action.type, member.action.slug)), member.action.title) message += "You can click on the link to claim your points." UserNotification.create_info_notification(member.user, message, display_alert=True, content_object=member) print "created commitment end notification for %s : %s" % ( member.user, member.action.slug)
def send(self): """ Sends a reminder email to the user. """ if not self.sent: challenge = challenge_mgr.get_challenge() subject = "[%s] Reminder for %s" % (challenge.name, self.action.title) message = render_to_string( "email/activity_reminder.txt", { "action": self.action, "user": self.user, "COMPETITION_NAME": challenge.name, "domain": challenge.domain, }, ) html_message = render_to_string( "email/activity_reminder.html", { "action": self.action, "user": self.user, "COMPETITION_NAME": challenge.name, "domain": challenge.domain, }, ) UserNotification.create_email_notification(self.email_address, subject, message, html_message) self.sent = True self.save()
def notify_commitment_end(): """Notify the user of the end of a commitment period and award their points.""" members = ActionMember.objects.filter( completion_date=datetime.date.today(), action__type="commitment", award_date__isnull=True) # try and load the notification template. template = None try: template = NoticeTemplate.objects.get(notice_type="commitment-ready") except NoticeTemplate.DoesNotExist: pass for member in members: if template: message = template.render({"COMMITMENT": member.action}) else: message = "Your commitment <a href='%s'>%s</a> has ended." % ( reverse("activity_task", args=(member.action.type, member.action.slug)), member.action.title) message += "You can click on the link to claim your points." UserNotification.create_info_notification(member.user, message, display_alert=True, content_object=member) print "created commitment end notification for %s : %s" % ( member.user, member.action.slug)
def testAlertNotifications(self): """Test alert.""" alert = UserNotification(recipient=self.user, contents="Alert notification", display_alert=True) alert.save() response = self.client.get(reverse("home_index")) self.assertContains(response, "notification-dialog", msg_prefix="Alert should be shown") response = self.client.get(reverse("help_index")) self.assertNotContains(response, "notification-dialog", msg_prefix="Dialog should not be displayed")
def testAjaxReadNotifications(self): """Test that notifications can be marked as read via AJAX.""" notification = UserNotification(recipient=self.user, contents="Test notification") notification.save() response = self.client.post(reverse("notifications_read", args=(notification.pk,)), {}, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.failUnlessEqual(response.status_code, 200) response = self.client.get(reverse("home_index")) self.assertNotContains(response, "Test notification", msg_prefix="Notification should be read")
def _send_winner_notification(self, prize, leader): """send notification.""" if leader and not self._notification_exists(prize, leader): # Notify winner using the template. template = NoticeTemplate.objects.get(notice_type='prize-winner') message = template.render({'PRIZE': prize}) UserNotification.create_info_notification(leader.user, message, True, prize) challenge = challenge_mgr.get_challenge() subject = "[%s] Congratulations, you won a prize!" % challenge.name UserNotification.create_email_notification( leader.user.email, subject, message, message)
def action_feedback(request, action_type, slug): """Handle feedback for an action.""" _ = action_type action = smartgrid.get_action(slug=slug) user = request.user profile = request.user.get_profile() form = ActionFeedbackForm(request.POST) if form.is_valid(): #print form.cleaned_data # should do something ?? pass feedback, created = ActionFeedback.objects.get_or_create(action=action, user=user) has_comment = False has_score = False if 'Score' in request.POST: feedback.rating = request.POST['Score'] has_score = True else: feedback.rating = 0 if 'comments' in request.POST: feedback.comment = request.POST['comments'] if len(feedback.comment.strip()) > 0: # ignore pure whitespace comments has_comment = True else: feedback.comment = "" feedback.changed = datetime.datetime.now() if has_comment or has_score: feedback.save() # only save if they provided any feedback else: if created: feedback.delete() # remove the feedback created = False # reset created for giving points if created: # Give the user points for providing feedback profile.add_points(score_mgr.feedback_points(), datetime.datetime.today(), "{0}: {1} (Provide feedback)"\ .format(action.type.capitalize(), action.title), action) if score_mgr.feedback_points() > 0: message = "Thank you for your feedback on {0}: {1} you've earned {2} points"\ .format(action.type.capitalize(), action.title, score_mgr.feedback_points()) else: message = "Thank you for your feedback on {0}: {1}"\ .format(action.type.capitalize(), action.title) UserNotification.create_info_notification(user, message, display_alert=True, content_object=action) # Take them back to the action page. return HttpResponseRedirect(reverse("activity_task", args=(action.type, action.slug,)))
def send(self): """ Sends a reminder text to the user via an email. """ number = self.text_number.replace("-", "") email = number + "@" + self.TEXT_EMAILS[self.text_carrier] if not self.sent: message = render_to_string("email/activity_text_reminder.txt", {"activity": self.action, "user": self.user}) UserNotification.create_email_notification(email, "", message) self.sent = True self.save()
def testReadNotifications(self): """Test that notifications can be marked as read without AJAX.""" notification = UserNotification(recipient=self.user, contents="Test notification") notification.save() response = self.client.post( reverse("notifications_read", args=(notification.pk, )), {}) self.assertRedirects(response, reverse("home_index"), msg_prefix="Marking as read should redirect.") response = self.client.get(reverse("home_index")) self.assertNotContains(response, "Test notification", msg_prefix="Notification should be read") # Test with a referring page. notification = UserNotification(recipient=self.user, contents="Test notification 2") notification.save() response = self.client.post(reverse("notifications_read", args=(notification.pk, )), {}, HTTP_REFERER=reverse("help_index")) self.assertRedirects(response, reverse("help_index"), msg_prefix="Marking as read should redirect.") response = self.client.get(reverse("home_index")) self.assertNotContains(response, "Test notification 2", msg_prefix="Notification should be read")
def testGetUnread(self): """Test that we can get the user's unread notifications.""" user = User.objects.create_user("test", "*****@*****.**") for i in range(0, 3): notification = UserNotification(recipient=user, contents="Test notification %i" % i) notification.save() notifications = get_unread_notifications(user) self.assertEqual(notifications["alerts"].count(), 0, "There should not be any alert notifications.") unread = notifications["unread"] self.assertEqual(unread.count(), 3, "There should be three unread notifications.") alert = UserNotification(recipient=user, contents="Alert notification", display_alert=True) alert.save() notifications = get_unread_notifications(user) self.assertEqual(notifications["alerts"][0], alert, "Alert notification should have been returned.") unread = notifications["unread"] self.assertEqual(unread.count(), 4, "There should be four unread notifications.")
def notify_winner(request): """Sends an email to the user notifying them that they are a winner.""" _ = request round_name = challenge_mgr.get_round_name() prizes = RafflePrize.objects.filter(round__name=round_name) for prize in prizes: if prize.winner: # Notify winner using the template. template = NoticeTemplate.objects.get(notice_type='raffle-winner') message = template.render({'PRIZE': prize}) UserNotification.create_info_notification(prize.winner, message, True, prize) return HttpResponseRedirect("/admin/raffle/raffleprize/")
def _send_winner_notification(self, prize, leader): """send notification.""" if leader and not self._notification_exists(prize, leader): # Notify winner using the template. template = NoticeTemplate.objects.get(notice_type='prize-winner') message = template.render({'PRIZE': prize}) UserNotification.create_info_notification(leader.user, message, True, prize) challenge = challenge_mgr.get_challenge() subject = "[%s] Congratulations, you won a prize!" % challenge.name UserNotification.create_email_notification(leader.user.email, subject, message, message)
def notify_winner(self, request, queryset): """pick winner.""" _ = request for obj in queryset: if obj.winner and not self.notice_sent(obj): # Notify winner using the template. template = NoticeTemplate.objects.get(notice_type="raffle-winner") message = template.render({"PRIZE": obj}) UserNotification.create_info_notification(obj.winner, message, True, obj) challenge = challenge_mgr.get_challenge() subject = "[%s] Congratulations, you won a prize!" % challenge.name UserNotification.create_email_notification(obj.winner.email, subject, message, message) self.message_user(request, "Winners notification sent.")
def send(self): """ Sends a reminder text to the user via an email. """ number = self.text_number.replace("-", "") email = number + "@" + self.TEXT_EMAILS[self.text_carrier] if not self.sent: message = render_to_string("email/activity_text_reminder.txt", { "activity": self.action, "user": self.user, }) UserNotification.create_email_notification(email, "", message) self.sent = True self.save()
def notify_round_started(): """Notify the user of a start of a round.""" if not challenge_mgr.in_competition(): return today = datetime.datetime.today() current_round = None previous_round = None all_round_info = challenge_mgr.get_all_round_info() rounds = all_round_info["rounds"] for key in rounds.keys(): # We're looking for a round that ends today and another that starts # today (or overall) start = rounds[key]["start"] end = rounds[key]["end"] # Check yesterday's round and check for the current round. if start < (today - datetime.timedelta(days=1)) < end: previous_round = key if start < today < end: current_round = key print 'Previous Round: %s' % previous_round print 'Current Round: %s' % current_round if current_round and previous_round and current_round != previous_round: # only carry over the scoreboard entry if the round don't need to be reset if not rounds[current_round]["round_reset"]: print "carry over scoreboard entry to new round." score_mgr.copy_scoreboard_entry(previous_round, current_round) # if there is a gap, previous_round is null, check if it is not out of round if current_round and current_round != previous_round and\ all_round_info["competition_start"] <= today <= all_round_info["competition_end"]: print 'Sending out round transition notices.' template = NoticeTemplate.objects.get(notice_type="round-transition") message = template.render({ "PREVIOUS_ROUND": previous_round, "CURRENT_ROUND": current_round, }) for user in User.objects.all(): UserNotification.create_info_notification( user, message, display_alert=True, )
def testShowNotifications(self): """ Test that we can show notifications to the user. """ for i in range(0, 3): notification = UserNotification(recipient=self.user, contents="Test notification %i" % i) notification.save() response = self.client.get(reverse("home_index")) self.assertNotContains(response, "The following item(s) need your attention", msg_prefix="Alert should not be shown" ) for i in range(0, 3): self.assertContains(response, "Test notification %i" % i, msg_prefix="Notification %i is not shown" % i )
def save(self, *args, **kwargs): """custom save method.""" message = "Congratulations, You have been awarded the {0} badge. ".format(self.badge.name) message += "<div class=\"badge-theme-{0}-small\"><p>{1}</p></div>".format(self.badge.theme, self.badge.label) message += "Check out your badges <a href= %s >here</a>" % "/profile/?ref=dialog" UserNotification.create_info_notification( self.profile.user, message, True, content_object=self ) message = "Badge: %s" % self.badge.name self.profile.add_points(self.badge.points, self.awarded_at, message, self) super(BadgeAward, self).save(args, kwargs)
def save(self, *args, **kwargs): """custom save method.""" message = "Congratulations, You have been awarded the {0} badge. ".format( self.badge.name) message += "<div class=\"badge-theme-{0}-small\"><p>{1}</p></div>".format( self.badge.theme, self.badge.label) message += "Check out your badges <a href= %s >here</a>" % "/profile/?ref=dialog" UserNotification.create_info_notification(self.profile.user, message, True, content_object=self) message = "Badge: %s" % self.badge.name self.profile.add_points(self.badge.points, self.awarded_at, message, self) super(BadgeAward, self).save(args, kwargs)
def possibly_completed_quests(user): """Check if the user may have completed one of their quests. Returns an array of the completed quests.""" user_quests = user.quest_set.filter(questmember__completed=False, questmember__opt_out=False) completed = [] for quest in user_quests: if quest.completed_quest(user): member = QuestMember.objects.get(user=user, quest=quest) member.completed = True member.save() completed.append(quest) # Create quest notification. message = "Congratulations! You completed the '%s' quest." % quest.name UserNotification.create_success_notification(user, message, display_alert=True) return completed
def notify_winner(self, request, queryset): """pick winner.""" _ = request for obj in queryset: leader = obj.leader() if leader and obj.award_to in ('individual_overall', 'individual_team')\ and not self.notice_sent(obj): # Notify winner using the template. template = NoticeTemplate.objects.get(notice_type='prize-winner') message = template.render({'PRIZE': obj}) UserNotification.create_info_notification(leader.user, message, True, obj) challenge = challenge_mgr.get_challenge() subject = "[%s] Congratulations, you won a prize!" % challenge.competition_name UserNotification.create_email_notification( leader.user.email, subject, message, message) self.message_user(request, "Winners notification sent.")
def notify_winner(self, request, queryset): """pick winner.""" _ = request for obj in queryset: if obj.winner and not self.notice_sent(obj): # Notify winner using the template. template = NoticeTemplate.objects.get( notice_type='raffle-winner') message = template.render({'PRIZE': obj}) UserNotification.create_info_notification( obj.winner, message, True, obj) challenge = challenge_mgr.get_challenge() subject = "[%s] Congratulations, you won a prize!" % challenge.name UserNotification.create_email_notification( obj.winner.email, subject, message, message) self.message_user(request, "Winners notification sent.")
def notify_round_started(): """Notify the user of a start of a round.""" if not challenge_mgr.in_competition(): return today = datetime.datetime.today() current_round = None previous_round = None all_round_info = challenge_mgr.get_all_round_info() rounds = all_round_info["rounds"] for key in rounds.keys(): # We're looking for a round that ends today and another that starts # today (or overall) start = rounds[key]["start"] end = rounds[key]["end"] # Check yesterday's round and check for the current round. if start < (today - datetime.timedelta(days=1)) < end: previous_round = key if start < today < end: current_round = key print 'Previous Round: %s' % previous_round print 'Current Round: %s' % current_round if current_round and previous_round and current_round != previous_round: # only carry over the scoreboard entry if the round don't need to be reset if not rounds[current_round]["round_reset"]: print "carry over scoreboard entry to new round." score_mgr.copy_scoreboard_entry(previous_round, current_round) # if there is a gap, previous_round is null, check if it is not out of round if current_round and current_round != previous_round and\ all_round_info["competition_start"] <= today <= all_round_info["competition_end"]: print 'Sending out round transition notices.' template = NoticeTemplate.objects.get(notice_type="round-transition") message = template.render({"PREVIOUS_ROUND": previous_round, "CURRENT_ROUND": current_round, }) for user in User.objects.all(): UserNotification.create_info_notification(user, message, display_alert=True,)
def bonus_code(request): """Claim the Bonus Points via code.""" user = request.user message = None profile = user.get_profile() if request.is_ajax() and request.method == "POST": form = BonusPointForm(request.POST) if form.is_valid(): message, code = _check_bonus_code(user, form) if message: return HttpResponse(json.dumps({ "message": message}), mimetype="application/json") # award points points = code.point_value s = "Bonus Points: claimed {0} points".format(points) profile.add_points(points, datetime.datetime.today(), s) code.is_active = False code.save() response = HttpResponse(json.dumps({ "redirectUrl": reverse("learn_index")}), mimetype="application/json") notification = "You collected " + str(points) + " bonus points!" response.set_cookie("bonus_notify", notification) UserNotification.create_info_notification(user, s) return response # At this point there is a form validation error. return HttpResponse(json.dumps({ "message": "Please input bonus points code." }), mimetype="application/json") raise Http404
def testReadNotifications(self): """Test that notifications can be marked as read without AJAX.""" notification = UserNotification(recipient=self.user, contents="Test notification") notification.save() response = self.client.post(reverse("notifications_read", args=(notification.pk,)), {}) self.assertRedirects(response, reverse("home_index"), msg_prefix="Marking as read should redirect.") response = self.client.get(reverse("home_index")) self.assertNotContains(response, "Test notification", msg_prefix="Notification should be read") # Test with a referring page. notification = UserNotification(recipient=self.user, contents="Test notification 2") notification.save() response = self.client.post(reverse("notifications_read", args=(notification.pk,)), {}, HTTP_REFERER=reverse("help_index")) self.assertRedirects(response, reverse("help_index"), msg_prefix="Marking as read should redirect.") response = self.client.get(reverse("home_index")) self.assertNotContains(response, "Test notification 2", msg_prefix="Notification should be read")
def _handle_activity_notification(self, status): """Creates a notification for rejected or approved tasks. This also creates an email message if it is configured. """ # don't create notification if the action is the SETUP_WIZARD_ACTIVITY # that is used in the setup wizard. if self.action.slug == SETUP_WIZARD_ACTIVITY: return # Construct the message to be sent. status_nicely = 'not approved' if status != 'approved' else status message = 'Your response to <a href="%s#action-details">"%s"</a> %s was %s.' % ( reverse("activity_task", args=( self.action.type, self.action.slug, )), self.action.title, # The below is to tell the javascript to convert into a pretty date. # See the prettyDate function in media/js/makahiki.js '<span class="rejection-date" title="%s"></span>' % self.submission_date.isoformat(), status_nicely, ) if status != 'approved': message += " You can still get points by clicking on the link and trying again." UserNotification.create_error_notification(self.user, message, display_alert=True, content_object=self) else: points = self.points_awarded if self.points_awarded else self.action.point_value message += " You earned %d points!" % points UserNotification.create_success_notification(self.user, message, display_alert=True, content_object=self)
def bonus_code(request): """Claim the Bonus Points via code.""" user = request.user message = None profile = user.profile if request.is_ajax() and request.method == "POST": form = BonusPointForm(request.POST) if form.is_valid(): message, code = _check_bonus_code(user, form) if message: return HttpResponse(json.dumps({"message": message}), mimetype="application/json") # award points points = code.point_value s = "Bonus Points: claimed {0} points".format(points) profile.add_points(points, datetime.datetime.today(), s) code.is_active = False code.save() response = HttpResponse(json.dumps( {"redirectUrl": reverse("learn_index")}), mimetype="application/json") notification = "You collected " + str(points) + " bonus points!" response.set_cookie("bonus_notify", notification) UserNotification.create_info_notification(user, s) return response # At this point there is a form validation error. return HttpResponse(json.dumps( {"message": "Please input bonus points code."}), mimetype="application/json") raise Http404
def process_rsvp(): """Process RSVP notification and penalty""" noshow_penalty_points = score_mgr.noshow_penalty_points() signup_points = score_mgr.signup_points() members = ActionMember.objects.filter(Q(action__type="event") | Q(action__type="excursion"), approval_status="pending") # try and load the notification template. template_noshow = None try: template_noshow = NoticeTemplate.objects.get( notice_type="event-noshow-penalty") except NoticeTemplate.DoesNotExist: pass template_reminder = None try: template_reminder = NoticeTemplate.objects.get( notice_type="event-post-reminder") except NoticeTemplate.DoesNotExist: pass for member in members: action = member.action user = member.user profile = user.profile diff = datetime.date.today() - action.event.event_date.date() if diff.days == NOSHOW_PENALTY_DAYS: # send out notification to remind the penalty if template_reminder: message = template_reminder.render({"ACTIVITY": action}) else: message = "Hi %s, <p/> We just wanted to remind you that the "\ "%s <a href='http://%s%s'>%s</a> had ended. Please "\ "click on the link to claim your points." % ( profile.name, action.type.capitalize(), challenge_mgr.get_challenge().domain, reverse("activity_task", args=(action.type, action.slug,)), action.title) message += "<p/>Because you signed up for the "\ "event, if you do not enter the "\ "confirmation code within %d days after the "\ "event, a total of %d points (%d point "\ "signup bonus plus %d point no-show penalty) will "\ "be deducted from your total points. So please "\ "enter your confirmation code early to avoid the "\ "penalty." % ( NOSHOW_PENALTY_DAYS, noshow_penalty_points + signup_points, noshow_penalty_points, signup_points, ) message += "<p/><p/>Kukui Cup Administrators" subject = "[Kukui Cup] Reminder to enter your event confirmation code" UserNotification.create_email_notification(user.email, subject, message, message) print "sent post event email reminder to %s for %s" % ( profile.name, action.title) elif diff.days == (NOSHOW_PENALTY_DAYS + 1): # the day after the penalty day, process the penalty reduction message = "%s: %s (No Show)" % (action.type.capitalize(), action.title) profile.remove_points( noshow_penalty_points + signup_points, datetime.datetime.today() - datetime.timedelta(minutes=1), message, member) print "removed noshow penalty points from %s for '%s'" % ( profile.name, message) if template_noshow: message = template_noshow.render({"ACTIVITY": action}) else: message = "%d points had been deducted from you, "\ "because you signed up but did not enter the "\ "confirmation code %d days after the %s <a "\ "href='%s'>%s</a>, " % ( noshow_penalty_points + signup_points, NOSHOW_PENALTY_DAYS, action.type.capitalize(), reverse("activity_task", args=(action.type, action.slug,)), action.title) message += " If you did attend, please click on the link to "\ "claim your points and reverse the deduction." UserNotification.create_info_notification(user, message, display_alert=True, content_object=member) print "created no-show penalty notification for %s for %s" % ( profile.name, action.title)
def process_rsvp(): """Process RSVP notification and penalty""" noshow_penalty_points = score_mgr.noshow_penalty_points() signup_points = score_mgr.signup_points() members = ActionMember.objects.filter( Q(action__type="event") | Q(action__type="excursion"), approval_status="pending") # try and load the notification template. template_noshow = None try: template_noshow = NoticeTemplate.objects.get( notice_type="event-noshow-penalty") except NoticeTemplate.DoesNotExist: pass template_reminder = None try: template_reminder = NoticeTemplate.objects.get( notice_type="event-post-reminder") except NoticeTemplate.DoesNotExist: pass for member in members: action = member.action user = member.user profile = user.get_profile() diff = datetime.date.today() - action.event.event_date.date() if diff.days == NOSHOW_PENALTY_DAYS: # send out notification to remind the penalty if template_reminder: message = template_reminder.render({"ACTIVITY": action}) else: message = "Hi %s, <p/> We just wanted to remind you that the "\ "%s <a href='http://%s%s'>%s</a> had ended. Please "\ "click on the link to claim your points." % ( profile.name, action.type.capitalize(), challenge_mgr.get_challenge().domain, reverse("activity_task", args=(action.type, action.slug,)), action.title) message += "<p/>Because you signed up for the "\ "event, if you do not enter the "\ "confirmation code within %d days after the "\ "event, a total of %d points (%d point "\ "signup bonus plus %d point no-show penalty) will "\ "be deducted from your total points. So please "\ "enter your confirmation code early to avoid the "\ "penalty." % ( NOSHOW_PENALTY_DAYS, noshow_penalty_points + signup_points, noshow_penalty_points, signup_points, ) message += "<p/><p/>Kukui Cup Administrators" subject = "[Kukui Cup] Reminder to enter your event confirmation code" UserNotification.create_email_notification(user.email, subject, message, message) print "sent post event email reminder to %s for %s" % ( profile.name, action.title) elif diff.days == (NOSHOW_PENALTY_DAYS + 1): # the day after the penalty day, process the penalty reduction message = "%s: %s (No Show)" % (action.type.capitalize(), action.title) profile.remove_points(noshow_penalty_points + signup_points, datetime.datetime.today() - datetime.timedelta(minutes=1), message, member) print "removed noshow penalty points from %s for '%s'" % (profile.name, message) if template_noshow: message = template_noshow.render({"ACTIVITY": action}) else: message = "%d points had been deducted from you, "\ "because you signed up but did not enter the "\ "confirmation code %d days after the %s <a "\ "href='%s'>%s</a>, " % ( noshow_penalty_points + signup_points, NOSHOW_PENALTY_DAYS, action.type.capitalize(), reverse("activity_task", args=(action.type, action.slug,)), action.title) message += " If you did attend, please click on the link to "\ "claim your points and reverse the deduction." UserNotification.create_info_notification(user, message, display_alert=True, content_object=member) print "created no-show penalty notification for %s for %s" % ( profile.name, action.title)
def attend_code(request): """Claim the attendance code or the Bonus Points code""" user = request.user action_member = None message = None social_email = None if request.is_ajax() and request.method == "POST": form = EventCodeForm(request.POST) if form.is_valid(): message, social_email, code, is_bonus = _check_attend_code(user, form) if message: return HttpResponse(json.dumps({ "message": message, "social_email": social_email }), mimetype="application/json") if not is_bonus: # It was an event code. try: action_member = ActionMember.objects.get(user=user, action=code.action) except ObjectDoesNotExist: action_member = ActionMember(user=user, action=code.action) action_member.approval_status = "approved" value = code.action.point_value if "social_email" in form.cleaned_data and \ form.cleaned_data["social_email"] != "Email": action_member.social_email = form.cleaned_data["social_email"].lower() # Model save method will award the points. action_member.save() else: # It was a bonus point code. profile = user.get_profile() value = code.point_value s = "Bonus Points: claimed {0} points".format(value) profile.add_points(value, datetime.datetime.today(), s) code.claim_date = datetime.datetime.now() code.is_active = False code.user = user code.save() notification = "You just earned " + str(value) + " points." if not is_bonus: response = HttpResponse(json.dumps({ "redirectUrl": reverse("activity_task", args=(code.action.type, code.action.slug)) }), mimetype="application/json") response.set_cookie("task_notify", notification) else: response = HttpResponse(json.dumps({ "redirectUrl": reverse("learn_index")}), mimetype="application/json") response.set_cookie("bonus_notify", notification) UserNotification.create_info_notification(user, s) return response # At this point there is a form validation error. return HttpResponse(json.dumps({ "message": "Please input code." }), mimetype="application/json") raise Http404
def _handle_activity_notification(self, status): """Creates a notification for rejected or approved tasks. This also creates an email message if it is configured. """ # don't create notification if the action is the SETUP_WIZARD_ACTIVITY # that is used in the setup wizard. if self.action.slug == SETUP_WIZARD_ACTIVITY: return # Construct the message to be sent. status_nicely = "not approved" if status != "approved" else status message = 'Your response to <a href="%s#action-details">"%s"</a> %s was %s.' % ( reverse("activity_task", args=(self.action.type, self.action.slug)), self.action.title, # The below is to tell the javascript to convert into a pretty date. # See the prettyDate function in media/js/makahiki.js '<span class="rejection-date" title="%s"></span>' % self.submission_date.isoformat(), status_nicely, ) if status != "approved": challenge = challenge_mgr.get_challenge() message += " You can still get points by clicking on the link and trying again." UserNotification.create_error_notification(self.user, message, display_alert=True, content_object=self) # only send out email notification for rejected action subject = "[%s] Your response to '%s' was %s" % (challenge.name, self.action.title, status_nicely) message = render_to_string( "email/rejected_activity.txt", { "object": self, "COMPETITION_NAME": challenge.name, "domain": challenge.domain, "status_nicely": status_nicely, }, ) html_message = render_to_string( "email/rejected_activity.html", { "object": self, "COMPETITION_NAME": challenge.name, "domain": challenge.domain, "status_nicely": status_nicely, }, ) UserNotification.create_email_notification(self.user.email, subject, message, html_message) else: points = self.points_awarded if self.points_awarded else self.action.point_value message += " You earned %d points!" % points UserNotification.create_success_notification(self.user, message, display_alert=True, content_object=self) # if admin approve an activity (action_type==activity), # check to the submission queue is empty, # if so, remove the admin reminder object. if self.action.type == "activity": submission_count = ActionMember.objects.filter( action__type="activity", approval_status="pending" ).count() if not submission_count: try: admin = User.objects.get(username=settings.ADMIN_USER) action = Action.objects.get(slug=SETUP_WIZARD_ACTIVITY) EmailReminder.objects.filter(user=admin, action=action).delete() except ObjectDoesNotExist: pass
def _handle_activity_notification(self, status): """Creates a notification for rejected or approved tasks. This also creates an email message if it is configured. """ # don't create notification if the action is the SETUP_WIZARD_ACTIVITY # that is used in the setup wizard. if self.action.slug == SETUP_WIZARD_ACTIVITY: return # Construct the message to be sent. status_nicely = 'not approved' if status != 'approved' else status message = 'Your response to <a href="%s#action-details">"%s"</a> %s was %s.' % ( reverse("activity_task", args=( self.action.type, self.action.slug, )), self.action.title, # The below is to tell the javascript to convert into a pretty date. # See the prettyDate function in media/js/makahiki.js '<span class="rejection-date" title="%s"></span>' % self.submission_date.isoformat(), status_nicely, ) if status != 'approved': challenge = challenge_mgr.get_challenge() message += " You can still get points by clicking on the link and trying again." UserNotification.create_error_notification(self.user, message, display_alert=True, content_object=self) # only send out email notification for rejected action subject = "[%s] Your response to '%s' was %s" % ( challenge.name, self.action.title, status_nicely) message = render_to_string( "email/rejected_activity.txt", { "object": self, "COMPETITION_NAME": challenge.name, "domain": challenge.domain, "status_nicely": status_nicely, }) html_message = render_to_string( "email/rejected_activity.html", { "object": self, "COMPETITION_NAME": challenge.name, "domain": challenge.domain, "status_nicely": status_nicely, }) UserNotification.create_email_notification(self.user.email, subject, message, html_message) else: points = self.points_awarded if self.points_awarded else self.action.point_value message += " You earned %d points!" % points UserNotification.create_success_notification(self.user, message, display_alert=True, content_object=self) # if admin approve an activity (action_type==activity), # check to the submission queue is empty, # if so, remove the admin reminder object. if self.action.type == "activity": submission_count = ActionMember.objects.filter( action__type="activity", approval_status="pending").count() if not submission_count: try: admin = User.objects.get(username=settings.ADMIN_USER) action = Action.objects.get(slug=SETUP_WIZARD_ACTIVITY) EmailReminder.objects.filter(user=admin, action=action).delete() except ObjectDoesNotExist: pass