def award_possible_daily_badges(): """award badges for all users. called in an hourly scheduler.""" if not challenge_mgr.is_game_enabled("Badge Game Mechanics"): return for p in Profile.objects.filter(setup_complete=True): award_possible_badges(p, "daily")
def setup_complete(request): """Display page 7 (complete) of the first login wizard.""" if request.is_ajax(): profile = request.user.get_profile() if request.method == "POST": # User got the question right. # link it to an activity. smartgrid.complete_setup_activity(request.user) profile.setup_complete = True profile.completion_date = datetime.datetime.today() profile.save() quest_enabled = challenge_mgr.is_game_enabled("Quest Game Mechanics") template = render_to_string("first-login/complete.html", {"quest_enabled": quest_enabled, }, context_instance=RequestContext(request)) response = HttpResponse(json.dumps({ "title": "Introduction: Step 7 of 7", "contents": template, }), mimetype='application/json') return response raise Http404
def setup_complete(request): """Display page 7 (complete) of the first login wizard.""" if request.is_ajax(): profile = request.user.profile if request.method == "POST": # User got the question right. # link it to an activity. smartgrid.complete_setup_activity(request.user) profile.setup_complete = True profile.completion_date = datetime.datetime.today() profile.save() quest_enabled = challenge_mgr.is_game_enabled("Quest Game Mechanics") template = render_to_string("first-login/complete.html", {"quest_enabled": quest_enabled, }, context_instance=RequestContext(request)) response = HttpResponse(json.dumps({ "title": "Introduction: Step 7 of 7", "contents": template, }), mimetype='application/json') return response raise Http404
def view_action(request, action_type, slug): """individual action page""" action = smartgrid.get_action(slug=slug) user = request.user team = user.get_profile().team view_objects = {} action = smartgrid.annotate_action_details(user, action) if not action.is_unlock: response = HttpResponseRedirect(reverse("learn_index", args=())) response.set_cookie("task_unlock_condition", action.unlock_condition_text) return response completed_members = smartgrid.get_action_members(action) completed_count = completed_members.count() team_members = completed_members.select_related('user__profile').filter( user__profile__team=team) if action_type == "commitment": form = view_commitments.view(request, action) elif action_type == "activity": form = view_activities.view(request, action) # if there is embedded widget, get the supplied objects if action.embedded_widget: view_module_name = 'apps.widgets.' + action.embedded_widget + '.views' view_objects[action.embedded_widget] = importlib.import_module( view_module_name).supply(request, None) view_objects['embedded_widget_template'] = "widgets/" + \ action.embedded_widget + "/templates/index.html" elif action.type in ("event", "excursion"): # action.event: form = view_events.view(request, action) # calculate available seat action.available_seat = action.event.event_max_seat - completed_count elif action_type == "filler": response = HttpResponseRedirect(reverse("learn_index", args=())) return response user_reminders = view_reminders.load_reminders(action, user) try: feedback = ActionFeedback.objects.get(user=user.pk, action=action.pk) except ObjectDoesNotExist: feedback = None if challenge_mgr.is_game_enabled("Quest Game Mechanics"): view_objects['quests'] = get_quests(user) return render_to_response("task.html", { "action": action, "form": form, "completed_count": completed_count, "team_members": team_members, "display_form": True if "display_form" in request.GET else False, "reminders": user_reminders, "view_objects": view_objects, "feedback_p": feedback, }, context_instance=RequestContext(request))
def handle(self, *args, **options): """Update the energy usage for all teams.""" date = datetime.datetime.today() print '****** Processing energy usage update at %s *******\n' % date if not challenge_mgr.is_game_enabled("Energy Game"): print "Energy Game is not enabled. Do nothing." return resource_goal.update_resource_usage("energy", date)
def get_quests_from_cache(user): """ get the quests for the user and store in cache. """ if not challenge_mgr.is_game_enabled("Quest Game Mechanics"): return {} return_dict = cache_mgr.get_cache("get_quests-%s" % user.username) if return_dict is None: return_dict = get_quests(user) cache_mgr.set_cache("get_quests-%s" % user.username, return_dict, 1800) return return_dict
def resource_goal_ranks(resource, round_name=None): """Generate the scoreboard for resource goals.""" if not challenge_mgr.is_game_enabled("%s Game" % resource.capitalize()): return None cache_key = "%s_goal_ranks-%s" % (resource, slugify(round_name)) goal_ranks = cache_mgr.get_cache(cache_key) if goal_ranks is None: goal_ranks = [] goal = get_resource_goal(resource) start_end = challenge_mgr.get_round_start_end(round_name) if start_end is not None: start, end = start_end else: return None ranks = goal.objects.filter( goal_status="Below the goal", date__gte=start, date__lte=end).values("team__name").annotate( completions=Count("team"), average_reduction=Avg("percent_reduction")).order_by( "-completions", "-average_reduction") for rank in ranks: goal_ranks.append(rank) total_count = Team.objects.count() if len(goal_ranks) != total_count: for t in Team.objects.all(): # find the team in the goal_ranks count = 0 for goal_rank in goal_ranks: if t.name == goal_rank["team__name"]: break else: count += 1 if count == len(goal_ranks): # not found rank = { "team__name": t.name, "completions": 0, "average_reduction": 0 } goal_ranks.append(rank) if len(goal_ranks) == total_count: break cache_mgr.set_cache(cache_key, goal_ranks, 3600 * 24) return goal_ranks
def resource_goal_ranks(resource, round_name=None): """Generate the scoreboard for resource goals.""" if not challenge_mgr.is_game_enabled("%s Game" % resource.capitalize()): return None cache_key = "%s_goal_ranks-%s" % (resource, slugify(round_name)) goal_ranks = cache_mgr.get_cache(cache_key) if goal_ranks is None: goal_ranks = [] goal = get_resource_goal(resource) start_end = challenge_mgr.get_round_start_end(round_name) if start_end is not None: start, end = start_end else: return None ranks = goal.objects.filter( goal_status="Below the goal", date__gte=start, date__lte=end).values("team__name").annotate( completions=Count("team"), average_reduction=Avg("percent_reduction")).order_by( "-completions", "-average_reduction") for rank in ranks: goal_ranks.append(rank) total_count = Team.objects.count() if len(goal_ranks) != total_count: for t in Team.objects.all(): # find the team in the goal_ranks count = 0 for goal_rank in goal_ranks: if t.name == goal_rank["team__name"]: break else: count += 1 if count == len(goal_ranks): # not found rank = {"team__name": t.name, "completions": 0, "average_reduction": 0} goal_ranks.append(rank) if len(goal_ranks) == total_count: break cache_mgr.set_cache(cache_key, goal_ranks, 3600 * 24) return goal_ranks
def award_possible_badges(profile, trigger): """Award any possible badges to a user. """ if not challenge_mgr.is_game_enabled("Badge Game Mechanics"): return user_badges = [] for awarded in profile.badgeaward_set.all().select_related("badge"): user_badges.append(awarded.badge) for badge in Badge.objects.filter(award_trigger=trigger): if not badge in user_badges and utils.eval_predicates(badge.award_condition, profile.user): award_badge(profile=profile, badge=badge) print "Awarded %s badge to %s." % (badge, profile)
def handle(self, *args, **options): """check the water goal for all teams and update the daily baseline""" today = datetime.datetime.today() print '****** Processing check_water_goal for %s *******\n' % today if not challenge_mgr.is_game_enabled("Water Game"): print "Water Game is not enabled. Do nothing." return today = today.date() resource_goal.check_resource_goals("water", today) # update the baseline resource_goal.update_resource_baseline("water", today, 2)
def award_participation(): """award the participation rate for all team.""" if not challenge_mgr.is_game_enabled("Participation Game"): return p_setting, _ = ParticipationSetting.objects.get_or_create(pk=1) current_round = challenge_mgr.get_round_name() for team in team_mgr.team_active_participation(round_name=current_round): team_participation, _ = TeamParticipation.objects.get_or_create( team=team, round_name=current_round) # check if the participation rate change if team_participation.participation != team.active_participation: # save the new participation rate if team.active_participation == 100: if team_participation.awarded_percent != "100": team_participation.awarded_percent = "100" team_mgr.award_member_points(team, p_setting.points_100_percent, "Team 100% participation") elif team.active_participation >= 75: if team_participation.awarded_percent != "75": team_participation.awarded_percent = "75" team_mgr.award_member_points(team, p_setting.points_75_percent, "Team 75% participation") elif team.active_participation >= 50: if not team_participation.awarded_percent: team_participation.awarded_percent = "50" team_mgr.award_member_points(team, p_setting.points_50_percent, "Team 50% participation") team_participation.participation = team.active_participation team_participation.save() # store the overall participation rate for team in team_mgr.team_active_participation(round_name="Overall"): team_participation, _ = TeamParticipation.objects.get_or_create( team=team, round_name="Overall") # check if the participation rate change if team_participation.participation != team.active_participation: # save the new participation rate team_participation.participation = team.active_participation team_participation.save()
def _award_possible_referral_bonus(self): """award possible referral bonus.""" # check if the referral game mechanics is enabled if not challenge_mgr.is_game_enabled("Referral Game Mechanics"): return has_referral = self.referring_user is not None and not self.referrer_awarded if has_referral and self.points() >= score_mgr.active_threshold_points(): referrer = self.referring_user.profile if referrer.setup_profile: self.referrer_awarded = True self.save() score_mgr.award_referral_bonus(self, referrer)
def _award_possible_referral_bonus(self): """award possible referral bonus.""" # check if the referral game mechanics is enabled if not challenge_mgr.is_game_enabled("Referral Game Mechanics"): return has_referral = self.referring_user is not None and not self.referrer_awarded if has_referral and self.points() >= score_mgr.active_threshold_points( ): referrer = self.referring_user.profile if referrer.setup_profile: self.referrer_awarded = True self.save() score_mgr.award_referral_bonus(self, referrer)
def terms(request): """Display page 2 (terms and conditions) of first login wizard.""" if request.is_ajax(): referral_enabled = challenge_mgr.is_game_enabled("Referral Game Mechanics") tcObj = HelpTopic.objects.filter(slug="terms-and-conditions") if tcObj: termsObj = tcObj[0].contents response = render_to_string("first-login/terms.html", { "terms": termsObj, "referral_enabled": referral_enabled, }, context_instance=RequestContext(request)) return HttpResponse(json.dumps({ "title": "Introduction: Step 2 of 7", "contents": response, }), mimetype='application/json') raise Http404
def _get_profile_form(request, form=None, non_xhr=False): """Helper method to render the profile form.""" fb_id = None facebook_photo = None if settings.MAKAHIKI_USE_FACEBOOK: fb_id = facebook.get_user_from_cookie( request.COOKIES, settings.MAKAHIKI_FACEBOOK_APP_ID, settings.MAKAHIKI_FACEBOOK_SECRET_KEY) if fb_id: facebook_photo = "http://graph.facebook.com/%s/picture?type=normal" % fb_id if not form: form = ProfileForm( initial={ "display_name": request.user.get_profile().name, "facebook_photo": facebook_photo, }) referral_enabled = challenge_mgr.is_game_enabled("Referral Game Mechanics") response = render_to_string("first-login/profile.html", { "form": form, "fb_id": fb_id, "referral_enabled": referral_enabled, }, context_instance=RequestContext(request)) if non_xhr: return HttpResponse('<textarea>' + json.dumps({ "title": "Introduction: Step 4 of 7", "contents": cgi.escape(response), }) + '</textarea>', mimetype='text/html') else: return HttpResponse(json.dumps({ "title": "Introduction: Step 4 of 7", "contents": response, }), mimetype='application/json')
def _get_profile_form(request, form=None, non_xhr=False): """Helper method to render the profile form.""" fb_id = None facebook_photo = None if settings.MAKAHIKI_USE_FACEBOOK: fb_id = facebook.get_user_from_cookie( request.COOKIES, settings.MAKAHIKI_FACEBOOK_APP_ID, settings.MAKAHIKI_FACEBOOK_SECRET_KEY) if fb_id: facebook_photo = "http://graph.facebook.com/%s/picture?type=normal" % fb_id if not form: form = ProfileForm(initial={ "display_name": request.user.get_profile().name, "facebook_photo": facebook_photo, }) referral_enabled = challenge_mgr.is_game_enabled("Referral Game Mechanics") response = render_to_string("first-login/profile.html", { "form": form, "fb_id": fb_id, "referral_enabled": referral_enabled, }, context_instance=RequestContext(request)) if non_xhr: return HttpResponse('<textarea>' + json.dumps({ "title": "Introduction: Step 4 of 7", "contents": cgi.escape(response), }) + '</textarea>', mimetype='text/html') else: return HttpResponse(json.dumps({ "title": "Introduction: Step 4 of 7", "contents": response, }), mimetype='application/json')
def view_action(request, action_type, slug): """individual action page""" action = smartgrid.get_action(slug=slug) user = request.user team = user.get_profile().team view_objects = {} action = smartgrid.annotate_action_details(user, action) if not action.is_unlock: response = HttpResponseRedirect(reverse("learn_index", args=())) response.set_cookie("task_unlock_condition", action.unlock_condition_text) return response completed_members = smartgrid.get_action_members(action) completed_count = completed_members.count() team_members = completed_members.select_related('user__profile').filter( user__profile__team=team) if action_type == "commitment": form = view_commitments.view(request, action) elif action_type == "activity": form = view_activities.view(request, action) # if there is embedded widget, get the supplied objects if action.embedded_widget: view_module_name = 'apps.widgets.' + action.embedded_widget + '.views' view_objects[action.embedded_widget] = importlib.import_module( view_module_name).supply(request, None) view_objects['embedded_widget_template'] = "widgets/" + \ action.embedded_widget + "/templates/index.html" elif action.type in ("event", "excursion"): # action.event: form = view_events.view(request, action) # calculate available seat action.available_seat = action.event.event_max_seat - completed_count elif action_type == "filler": response = HttpResponseRedirect(reverse("learn_index", args=())) return response user_reminders = view_reminders.load_reminders(action, user) try: feedback = ActionFeedback.objects.get(user=user.pk, action=action.pk) except ObjectDoesNotExist: feedback = None if challenge_mgr.is_game_enabled("Quest Game Mechanics"): view_objects['quests'] = get_quests(user) return render_to_response( "task.html", { "action": action, "form": form, "completed_count": completed_count, "team_members": team_members, "display_form": True if "display_form" in request.GET else False, "reminders": user_reminders, "view_objects": view_objects, "feedback_p": feedback, }, context_instance=RequestContext(request))