示例#1
0
def check_new_submissions():
    """Check the action submission queue and send out notifications to admin when there is new
    submissions in the queue.
    algorithm for queue processing:
      1. on zero to one transition: send email unless email already sent within N minutes.
    """
    submission_count = ActionMember.objects.filter(
        action__type="activity", approval_status="pending").count()

    if submission_count:
        try:
            admin = User.objects.get(username=settings.ADMIN_USER)
            action = Action.objects.get(slug=SETUP_WIZARD_ACTIVITY)
            reminder = EmailReminder.objects.filter(user=admin, action=action)
            if not reminder:
                EmailReminder.objects.create(user=admin,
                                             action=action,
                                             send_at=datetime.datetime.today(),
                                             sent=True)

                challenge = challenge_mgr.get_challenge()
                subject = "[%s] %d New Pending Action Submissions" % (
                    challenge.name, submission_count)
                message = "There are %d new pending action submissions as of %s." % (
                    submission_count, datetime.datetime.today())

                if challenge.email_enabled and challenge.contact_email:
                    print "Sending new submission notification to %s" % challenge.contact_email
                    mail = EmailMultiAlternatives(subject, message,
                                                  challenge.contact_email, [
                                                      challenge.contact_email,
                                                  ])
                    mail.send()
        except ObjectDoesNotExist:
            pass
示例#2
0
def send_feedback(request):
    """send feedback."""
    if request.method == "POST":
        form = FeedbackForm(request.POST)
        if form.is_valid():
            html_message = render_to_string(
                "email/ask_admin.html",
                {"user": request.user, "url": form.cleaned_data["url"], "question": form.cleaned_data["question"]},
            )
            message = render_to_string(
                "email/ask_admin.txt",
                {"user": request.user, "url": form.cleaned_data["url"], "question": form.cleaned_data["question"]},
            )

            challenge = challenge_mgr.get_challenge()
            # Using adapted version from Django source code
            subject = u"[%s] %s asked a question" % (challenge.competition_name, request.user.get_profile().name)

            if challenge.email_enabled:
                mail = EmailMultiAlternatives(
                    subject, message, FROM_EMAIL, [challenge.contact_email], headers={"Reply-To": request.user.email}
                )

                mail.attach_alternative(html_message, "text/html")
                mail.send()

            # print "email sent %s" % html_message
            if request.is_ajax():
                return HttpResponse(json.dumps({"success": True}), mimetype="application/json")

    raise Http404
示例#3
0
    def _get_energy_usage(self, session, source):
        """Return the energy usage from wattdepot."""
        rest_url = "%s/sources/%s/energy/" % (
            challenge_mgr.get_challenge().wattdepot_server_url, source)

        # comment out for debug
        #import sys
        #session.config['verbose'] = sys.stderr

        session.timeout = 5

        try:
            response = session.get(url=rest_url)

            #print response.text
            usage = 0
            property_elements = ElementTree.XML(
                response.text).findall(".//Property")
            for p in property_elements:
                key_value = p.getchildren()
                if key_value and key_value[0].text == "energyConsumed":
                    usage = key_value[1].text

            return int(round(float(usage)))

        except Timeout:
            print 'Wattdepot data retrieval for team %s error: connection timeout.' % source
        except ParseError as exception:
            print 'Wattdepot data retrieval for team %s ParseError : %s' % (
                source, exception)

        return 0
示例#4
0
def change_theme(user):
    """returns True if the user change their theme."""
    theme = user.get_profile().theme
    if not theme:
        return False
    else:
        return theme != challenge_mgr.get_challenge().theme
示例#5
0
def check_new_submissions():
    """Check the action submission queue and send out notifications to admin when there is new
    submissions in the queue.
    algorithm for queue processing:
      1. on zero to one transition: send email unless email already sent within N minutes.
    """
    submission_count = ActionMember.objects.filter(
        action__type="activity",
        approval_status="pending").count()

    if submission_count:
        try:
            admin = User.objects.get(username=settings.ADMIN_USER)
            action = Action.objects.get(slug=SETUP_WIZARD_ACTIVITY)
            reminder = EmailReminder.objects.filter(user=admin, action=action)
            if not reminder:
                EmailReminder.objects.create(user=admin,
                                             action=action,
                                             send_at=datetime.datetime.today(),
                                             sent=True)

                challenge = challenge_mgr.get_challenge()
                subject = "[%s] %d New Pending Action Submissions" % (challenge.name,
                                                                      submission_count)
                message = "There are %d new pending action submissions as of %s." % (
                    submission_count, datetime.datetime.today())

                if challenge.email_enabled and challenge.contact_email:
                    print "Sending new submission notification to %s" % challenge.contact_email
                    mail = EmailMultiAlternatives(subject, message, challenge.contact_email,
                        [challenge.contact_email, ])
                    mail.send()
        except ObjectDoesNotExist:
            pass
示例#6
0
def supply(request, page_name):
    """Supply view_objects for My_Info and process the POST command."""
    _ = page_name

    session = request.session
    form = None
    if "form" in session:
        form = session.pop('form')

    if not form:
        user = request.user
        profile = user.get_profile()
        user_theme = profile.theme
        if not user_theme:
            user_theme = challenge_mgr.get_challenge().theme
        form = ProfileForm(initial={
            "display_name": profile.name,
            "contact_email": user.email,
            "contact_text": profile.contact_text,
            "contact_carrier": profile.contact_carrier,
            "theme": user_theme,
            })

        if "changed_avatar" in request.GET:
            form.message = "Your avatar has been updated."

    return {
        "form": form,
    }
示例#7
0
    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()
示例#8
0
def prize_form(request, prize_id, user_id):
    """Supply the prize form."""
    _ = request
    prize = get_object_or_404(Prize, pk=prize_id)
    prize.winner = get_object_or_404(User, pk=user_id)
    challenge = challenge_mgr.get_challenge()

    try:
        template = NoticeTemplate.objects.get(
            notice_type='prize-winner-receipt')
    except NoticeTemplate.DoesNotExist:
        return render_to_response('view_prizes/form.txt', {
            'raffle': False,
            'prize': prize,
            'round': prize.round.name,
            'competition_name': challenge.name,
        },
                                  context_instance=RequestContext(request),
                                  mimetype='text/plain')

    message = template.render({
        'raffle': False,
        'prize': prize,
        'round': prize.round.name,
        'competition_name': challenge.name,
    })
    return HttpResponse(message, content_type="text", mimetype='text/html')
示例#9
0
    def _get_energy_usage(self, session, source):
        """Return the energy usage from wattdepot."""
        rest_url = "%s/sources/%s/energy/" % (
            challenge_mgr.get_challenge().wattdepot_server_url, source)

        # comment out for debug
        #import sys
        #session.config['verbose'] = sys.stderr

        session.timeout = 5

        try:
            response = session.get(url=rest_url)

            #print response.text
            usage = 0
            property_elements = ElementTree.XML(response.text).findall(".//Property")
            for p in property_elements:
                key_value = p.getchildren()
                if key_value and key_value[0].text == "energyConsumed":
                    usage = key_value[1].text

            return int(round(float(usage)))

        except Timeout:
            print 'Wattdepot data retrieval for team %s error: connection timeout.' % source
        except ParseError as exception:
            print 'Wattdepot data retrieval for team %s ParseError : %s' % (source, exception)

        return 0
示例#10
0
    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()
示例#11
0
    def get_latest_resource_data_wattdepot2(self, session, source_name, date):
        """Returns the latest usage of the specified resource for the current date."""
        start_time = date.strftime("%Y-%m-%dT00:00:00")
        end_time = "latest"

        session.params = {"startTime": start_time, "endTime": end_time}
        url = "%s/sources/%s/energy/" % (challenge_mgr.get_challenge().wattdepot_server_url, source_name)
        return self._get_energy_usage(session, url, source_name)
示例#12
0
    def get_latest_resource_data_wattdepot3(self, session, source_name, date):
        """Returns the latest usage of the specified resource for the current date."""
        _ = date
        source_name = source_name.lower()

        session.params = {'sensor': source_name,
                          'latest': "true"}
        url = "%s/depository/energy/value/" % (challenge_mgr.get_challenge().wattdepot_server_url)
        return self._get_energy_usage(session, url, source_name) / 1000
示例#13
0
def supply(request, page_name):
    """Supply view_objects for My_Info and process the POST command."""
    _ = page_name
    user = request.user
    form = None
    if request.method == "POST":
        user = request.user
        form = ProfileForm(request.POST, user=request.user)
        if form.is_valid():
            profile = user.get_profile()
            name = form.cleaned_data["display_name"].strip()

            if name != profile.name:
                profile.name = name

            theme = form.cleaned_data["theme"].strip()

            if theme and theme != profile.theme:
                profile.theme = theme

            user.email = form.cleaned_data["contact_email"]
            user.save()
            profile.contact_text = form.cleaned_data["contact_text"]
            profile.contact_carrier = form.cleaned_data["contact_carrier"]

            profile.save()

            # Invalidate info bar cache.
            cache_mgr.invalidate_template_cache("RIB", user.username)

            form.message = "Your changes have been saved"

        else:
            form.message = "Please correct the errors below."

    # If this is a new request, initialize the form.
    if not form:
        profile = user.get_profile()
        user_theme = profile.theme
        if not user_theme:
            user_theme = challenge_mgr.get_challenge().theme
        form = ProfileForm(initial={
            "display_name": profile.name,
            "contact_email": user.email,
            "contact_text": profile.contact_text,
            "contact_carrier": profile.contact_carrier,
            "theme": user_theme,
            })

        if "changed_avatar" in request.GET:
            form.message = "Your avatar has been updated."

    return {
        "form": form,
    }
示例#14
0
    def get_history_resource_data_wattdepot3(self, session, source_name, date, hour):
        """Return the history energy usage of the team for the date and hour."""
        if hour and hour < 24:
            timestamp = date.strftime("%Y-%m-%dT") + "%.2d:00:00.000" % hour
        else:
            timestamp = (date + datetime.timedelta(days=1)).strftime("%Y-%m-%dT00:00:00.000")

        session.params = {"sensor": source_name, "timestamp": timestamp}
        url = "%s/depository/energy/value/" % (challenge_mgr.get_challenge().wattdepot_server_url)

        return self._get_energy_usage(session, url, source_name)
示例#15
0
    def get_history_resource_data_wattdepot2(self, session, source_name, date, hour):
        """Return the history energy usage of the team for the date and hour."""
        start_time = date.strftime("%Y-%m-%dT00:00:00")
        if hour and hour < 24:
            end_time = date.strftime("%Y-%m-%dT") + "%.2d:00:00" % hour
        else:
            end_time = (date + datetime.timedelta(days=1)).strftime("%Y-%m-%dT00:00:00")

        session.params = {"startTime": start_time, "endTime": end_time}
        url = "%s/sources/%s/energy/" % (challenge_mgr.get_challenge().wattdepot_server_url, source_name)
        return self._get_energy_usage(session, url, source_name)
示例#16
0
    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)
示例#17
0
    def create_email_notification(recipient_email, subject, message, html_message=None):
        """Create an email notification."""

        if settings.EMAIL_BACKEND == 'django.core.mail.backends.locmem.EmailBackend' or\
           challenge_mgr.get_challenge().email_enabled:
            msg = EmailMultiAlternatives(subject,
                                         message,
                                         settings.SERVER_EMAIL,
                                         [recipient_email, ])
            if html_message:
                msg.attach_alternative(html_message, "text/html")

            msg.send()
示例#18
0
    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)
示例#19
0
    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.")
示例#20
0
    def create_email_notification(recipient_email,
                                  subject,
                                  message,
                                  html_message=None):
        """Create an email notification."""

        if settings.EMAIL_BACKEND == 'django.core.mail.backends.locmem.EmailBackend' or\
           challenge_mgr.get_challenge().email_enabled:
            msg = EmailMultiAlternatives(subject, message,
                                         settings.SERVER_EMAIL, [
                                             recipient_email,
                                         ])
            if html_message:
                msg.attach_alternative(html_message, "text/html")

            msg.send()
示例#21
0
    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.")
示例#22
0
    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.")
示例#23
0
def send_feedback(request):
    """send feedback."""
    if request.method == "POST":
        form = FeedbackForm(request.POST)
        if form.is_valid():
            html_message = render_to_string(
                "email/ask_admin.html", {
                    "user": request.user,
                    "url": form.cleaned_data["url"],
                    "question": form.cleaned_data["question"],
                })
            message = render_to_string(
                "email/ask_admin.txt", {
                    "user": request.user,
                    "url": form.cleaned_data["url"],
                    "question": form.cleaned_data["question"],
                })

            challenge = challenge_mgr.get_challenge()
            # Using adapted version from Django source code
            subject = u'[%s] %s asked a question' % (challenge.name,
                                                     request.user.profile.name)

            if challenge.email_enabled or True:
                mail = EmailMultiAlternatives(
                    subject,
                    message,
                    challenge.contact_email, [
                        challenge.contact_email,
                    ],
                    headers={"Reply-To": request.user.email})

                mail.attach_alternative(html_message, 'text/html')
                print html_message
                mail.send()

            #print "email sent %s" % html_message
            if request.is_ajax():
                return HttpResponse(json.dumps({"success": True}),
                                    mimetype="application/json")

    raise Http404
示例#24
0
def check_daily_submissions():
    """Check the action submission queue and send out notifications to admin when there are still
    submission in the queue.
    algorithm for queue processing:
      2. every 24 hours: send email with queue size unless queue size is zero.
    """
    submission_count = ActionMember.objects.filter(action__type="activity", approval_status="pending").count()

    if submission_count:
        challenge = challenge_mgr.get_challenge()
        subject = "[%s] %d Remaining Pending Action Submissions" % (challenge.competition_name, submission_count)
        message = "There are %d remaining pending action submissions as of %s." % (
            submission_count,
            datetime.datetime.today(),
        )

        if challenge.email_enabled and challenge.contact_email:
            print "Sending new submission notification to %s" % challenge.contact_email
            mail = EmailMultiAlternatives(subject, message, challenge.contact_email, [challenge.contact_email])
            mail.send()
示例#25
0
def check_daily_submissions():
    """Check the action submission queue and send out notifications to admin when there are still
    submission in the queue.
    algorithm for queue processing:
      2. every 24 hours: send email with queue size unless queue size is zero.
    """
    submission_count = ActionMember.objects.filter(
        action__type="activity", approval_status="pending").count()

    if submission_count:
        challenge = challenge_mgr.get_challenge()
        subject = "[%s] %d Remaining Pending Action Submissions" % (
            challenge.name, submission_count)
        message = "There are %d remaining pending action submissions as of %s." % (
            submission_count, datetime.datetime.today())

        if challenge.email_enabled and challenge.contact_email:
            print "Sending new submission notification to %s" % challenge.contact_email
            mail = EmailMultiAlternatives(subject, message,
                                          challenge.contact_email, [
                                              challenge.contact_email,
                                          ])
            mail.send()
示例#26
0
文件: views.py 项目: csdl/makahiki
def prize_form(request, prize_id, user_id):
    """Supply the prize form."""
    _ = request
    prize = get_object_or_404(Prize, pk=prize_id)
    prize.winner = get_object_or_404(User, pk=user_id)
    challenge = challenge_mgr.get_challenge()

    try:
        template = NoticeTemplate.objects.get(notice_type='prize-winner-receipt')
    except NoticeTemplate.DoesNotExist:
        return render_to_response('view_prizes/form.txt', {
            'raffle': False,
            'prize': prize,
            'round': prize.round.name,
            'competition_name': challenge.name,
        }, context_instance=RequestContext(request), mimetype='text/plain')

    message = template.render({
        'raffle': False,
        'prize': prize,
        'round': prize.round.name,
        'competition_name': challenge.name,
    })
    return HttpResponse(message, content_type="text", mimetype='text/html')
示例#27
0
    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
示例#28
0
def competition(request):
    """Provides access to standard competition constants within a template.

    :param request: The request object.
    :return: a dictionary of game settings."""
    # Get user-specific information.

    if _pass_through(request):
        return {}

    user = request.user
    team_member_count = None
    team_count = None
    overall_member_count = None
    available_events = None
    default_view_objects = None
    all_page_info = None
    designer_models = [None, None]
    admin_models = [None, None]
    developer_models = [None, None]

    challenge = challenge_mgr.get_challenge()
    css_theme = challenge.theme
    page_name = request.path[1:][:-1]
    if user.is_authenticated():
        profile = user.get_profile()

        default_view_objects = _get_default_view_objects(request)
        all_page_info = challenge_mgr.all_page_info(user)

        if profile.team:
            team_member_count = profile.team.profile_set.count()
            team_count = Team.objects.count()
            overall_member_count = Profile.objects.count()
            available_events = smartgrid.get_next_available_event(user)

        # override the site theme if there is any
        if profile.theme:
            css_theme = profile.theme

        if page_name == "sys_admin/challenge_mgr/challengesetting/1":
            page_name = "admin"
        if page_name in ("challenge_setting_admin", "challenge_admin",
                         "developer_admin"):
            page_name = "admin"
            designer_models[0] = \
                challenge_mgr.get_designer_challenge_info_models()
            designer_models[1] = \
                challenge_mgr.get_designer_game_info_models()
            admin_models[0] = \
                challenge_mgr.get_admin_challenge_info_models()
            admin_models[1] = challenge_mgr.get_admin_game_info_models()
            developer_models[
                0] = challenge_mgr.get_developer_challenge_info_models()
            developer_models[1] = challenge_mgr.get_developer_game_info_models(
            )

    return {
        "CHALLENGE":
        challenge,
        "SCORE_SETTINGS":
        score_mgr.score_setting(),
        "CSS_THEME":
        css_theme,
        "TEAM_LABEL":
        challenge.team_label,
        "MAKAHIKI_FACEBOOK_APP_ID":
        settings.MAKAHIKI_FACEBOOK_APP_ID
        if settings.MAKAHIKI_USE_FACEBOOK else '',
        "MAKAHIKI_USE_LESS":
        settings.MAKAHIKI_USE_LESS,
        "CURRENT_ROUND_INFO":
        settings.CURRENT_ROUND_INFO,
        "TEAM_COUNT":
        team_count,
        "TEAM_MEMBER_COUNT":
        team_member_count,
        "OVERALL_MEMBER_COUNT":
        overall_member_count,
        "DEFAULT_VIEW_OBJECTS":
        default_view_objects,
        "AVAILABLE_EVENTS":
        available_events,
        "ALL_PAGE_INFO":
        all_page_info,
        "MAKAHIKI_DESIGNER_CHALLENGE_MODELS":
        designer_models[0],
        "MAKAHIKI_DESIGNER_GAME_MODELS":
        designer_models[1],
        "MAKAHIKI_ADMIN_CHALLENGE_MODELS":
        admin_models[0],
        "MAKAHIKI_ADMIN_GAME_MODELS":
        admin_models[1],
        "MAKAHIKI_DEVELOPER_CHALLENGE_MODELS":
        developer_models[0],
        "MAKAHIKI_DEVELOPER_GAME_MODELS":
        developer_models[1],
        "ACTIVE_PAGE":
        page_name
    }
示例#29
0
    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 competition(request):
    """Provides access to standard competition constants within a template.

    :param request: The request object.
    :return: a dictionary of game settings."""
    # Get user-specific information.

    if _pass_through(request):
        return {}

    user = request.user
    team_member_count = None
    team_count = None
    overall_member_count = None
    available_events = None
    default_view_objects = None
    all_page_info = None
    site_admin_models = None
    sys_admin_models = None
    game_admin_models = None

    challenge = challenge_mgr.get_challenge()
    css_theme = challenge.theme
    page_name = request.path[1:][:-1]
    if user.is_authenticated():
        profile = user.get_profile()

        default_view_objects = _get_default_view_objects(request)
        all_page_info = challenge_mgr.all_page_info(user)

        if profile.team:
            team_member_count = profile.team.profile_set.count()
            team_count = Team.objects.count()
            overall_member_count = Profile.objects.count()
            available_events = smartgrid.get_next_available_event(user)

        # override the site theme if there is any
        if profile.theme:
            css_theme = profile.theme

        if page_name == "admin":
            site_admin_models = challenge_mgr.get_site_admin_models()
            sys_admin_models = challenge_mgr.get_sys_admin_models()
            game_admin_models = challenge_mgr.get_game_admin_models()

    return {
        "CHALLENGE": challenge,
        "CSS_THEME": css_theme,
        "TEAM_LABEL": challenge.competition_team_label,
        "MAKAHIKI_FACEBOOK_APP_ID":
            settings.MAKAHIKI_FACEBOOK_APP_ID if settings.MAKAHIKI_USE_FACEBOOK else '',
        "MAKAHIKI_USE_LESS": settings.MAKAHIKI_USE_LESS,
        "CURRENT_ROUND_INFO": settings.CURRENT_ROUND_INFO,
        "TEAM_COUNT": team_count,
        "TEAM_MEMBER_COUNT": team_member_count,
        "OVERALL_MEMBER_COUNT": overall_member_count,
        "DEFAULT_VIEW_OBJECTS": default_view_objects,
        "AVAILABLE_EVENTS": available_events,
        "ALL_PAGE_INFO": all_page_info,
        "MAKAHIKI_SITE_ADMIN_MODELS": site_admin_models,
        "MAKAHIKI_SYS_ADMIN_MODELS": sys_admin_models,
        "MAKAHIKI_GAME_ADMIN_MODELS": game_admin_models,
        "ACTIVE_PAGE": page_name
    }
示例#31
0
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)
示例#32
0
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)
示例#33
0
def competition(request):
    """Provides access to standard competition constants within a template.

    :param request: The request object.
    :return: a dictionary of game settings."""
    # Get user-specific information.

    if _pass_through(request):
        return {}

    user = request.user
    team_member_count = None
    team_count = None
    overall_member_count = None
    available_events = None
    default_view_objects = None
    all_page_info = None
    designer_models = [None, None]
    admin_models = [None, None]
    developer_models = [None, None]

    challenge = challenge_mgr.get_challenge()
    css_theme = challenge.theme
    page_name = request.path[1:][:-1]

    if user.is_authenticated():
        try:
            profile = user.profile
        except User.DoesNotExist:
            profile = None

        if profile:
            default_view_objects = _get_default_view_objects(request)
            all_page_info = challenge_mgr.all_page_info(user)

            if profile.team:
                team_member_count = profile.team.profile_set.count()
                team_count = Team.objects.count()
                overall_member_count = Profile.objects.count()
                available_events = smartgrid.get_next_available_event(user)

            # override the site theme if there is any
            if profile.theme:
                css_theme = profile.theme

            if page_name == "sys_admin/challenge_mgr/challengesetting/1":
                page_name = "admin"
            if page_name in ("challenge_setting_admin", "challenge_admin", "developer_admin"):
                page_name = "admin"
                designer_models[0] = \
                    challenge_mgr.get_designer_challenge_info_models()
                designer_models[1] = \
                    challenge_mgr.get_designer_game_info_models()
                admin_models[0] = \
                    challenge_mgr.get_admin_challenge_info_models()
                admin_models[1] = challenge_mgr.get_admin_game_info_models()
                developer_models[0] = challenge_mgr.get_developer_challenge_info_models()
                developer_models[1] = challenge_mgr.get_developer_game_info_models()

    return {
        "CHALLENGE": challenge,
        "SCORE_SETTINGS": score_mgr.score_setting(),
        "CSS_THEME": css_theme,
        "TEAM_LABEL": challenge.team_label,
        "MAKAHIKI_FACEBOOK_APP_ID":
            settings.MAKAHIKI_FACEBOOK_APP_ID if settings.MAKAHIKI_USE_FACEBOOK else '',
        "MAKAHIKI_USE_LESS": settings.MAKAHIKI_USE_LESS,
        "CURRENT_ROUND_INFO": settings.CURRENT_ROUND_INFO,
        "TEAM_COUNT": team_count,
        "TEAM_MEMBER_COUNT": team_member_count,
        "OVERALL_MEMBER_COUNT": overall_member_count,
        "DEFAULT_VIEW_OBJECTS": default_view_objects,
        "AVAILABLE_EVENTS": available_events,
        "ALL_PAGE_INFO": all_page_info,
        "MAKAHIKI_DESIGNER_CHALLENGE_MODELS": designer_models[0],
        "MAKAHIKI_DESIGNER_GAME_MODELS": designer_models[1],
        "MAKAHIKI_ADMIN_CHALLENGE_MODELS": admin_models[0],
        "MAKAHIKI_ADMIN_GAME_MODELS": admin_models[1],
        "MAKAHIKI_DEVELOPER_CHALLENGE_MODELS": developer_models[0],
        "MAKAHIKI_DEVELOPER_GAME_MODELS": developer_models[1],
        "ACTIVE_PAGE": page_name
    }