Ejemplo n.º 1
0
def resource_goal_ranks(resource, round_name=None):
    """Generate the scoreboard for resource goals."""
    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)

        round_info = challenge_mgr.get_round_info(round_name)
        if not round_info:
            return None

        ranks = goal.objects.filter(
            goal_status="Below the goal",
            date__lte=round_info["end"].date).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():
                if not t.name in goal_ranks:
                    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
Ejemplo n.º 2
0
    def testIndex(self):
        """Check that we can load the index page."""
        raffle_prize = RafflePrize(
            title="Test raffle prize",
            description="A raffle prize for testing",
            round_name="Round 2",
            value=5,
        )
        raffle_prize.save()

        response = self.client.get(reverse("win_index"))
        self.failUnlessEqual(response.status_code, 200)
        self.assertContains(response, "Round 2 Raffle",
            msg_prefix="We should be in round 2 of the raffle.")
        self.assertContains(response,
            "Your total raffle tickets: 0 Allocated right now: 0 Available: 0",
            msg_prefix="User should not have any raffle tickets.")
        deadline = challenge_mgr.get_round_info()["end"]
        date_string = deadline.strftime("%b. %d, %Y, %I:%M ")
        date_string = re.sub(r" \b0", " ", date_string)
        #self.assertContains(response, "Deadline for Round 2 submissions: " + date_string,
        #    msg_prefix="Raffle should have the correct deadline.")

        # Give the user some points and see if their tickets update.
        profile = self.user.get_profile()
        profile.add_points(25, datetime.datetime.today(), "test")
        profile.save()
        response = self.client.get(reverse("win_index"))
        self.assertContains(response,
            "Your total raffle tickets: 1 Allocated right now: 0 Available: 1",
            msg_prefix="User should have 1 raffle ticket.")
Ejemplo n.º 3
0
def resource_ranks(name, round_name=None):
    """Return the ranking of resource use for all teams."""

    cache_key = "%s_ranks-%s" % (name, slugify(round_name))
    ranks = cache_mgr.get_cache(cache_key)
    if ranks is None:
        resource_usage = _get_resource_usage(name)

        resource_setting = get_resource_setting(name)
        if resource_setting.winning_order == "Ascending":
            ordering = "total"
        else:
            ordering = "-total"

        round_info = challenge_mgr.get_round_info(round_name)
        if not round_info:
            return None

        usage_ranks = resource_usage.objects.filter(
            date__lte=round_info["end"].date).values("team__name").annotate(
                total=Sum("usage")).order_by(ordering)

        ranks = []
        for rank in usage_ranks:
            ranks.append(rank)
        cache_mgr.set_cache(cache_key, ranks, 3600)
    return ranks
Ejemplo n.º 4
0
def resource_ranks(name, round_name=None):
    """Return the ranking of resource use for all teams."""

    cache_key = "%s_ranks-%s" % (name, slugify(round_name))
    ranks = cache_mgr.get_cache(cache_key)
    if ranks is None:
        resource_usage = _get_resource_usage(name)

        resource_setting = get_resource_setting(name)
        rate = resource_setting.conversion_rate
        if resource_setting.winning_order == "Ascending":
            ordering = "total"
        else:
            ordering = "-total"

        round_info = challenge_mgr.get_round_info(round_name)
        if not round_info:
            return None

        all_rounds_info = challenge_mgr.get_all_round_info()

        usage_ranks = resource_usage.objects.filter(
            date__lte=round_info["end"].date,
            date__gte=all_rounds_info["competition_start"]).values("team__name").annotate(
                total=Sum("usage")).order_by(ordering)

        ranks = []
        for rank in usage_ranks:
            ranks.append({"team__name": rank["team__name"],
                          "total": utils.format_usage(rank["total"], rate)})

        cache_mgr.set_cache(cache_key, ranks, 600)
    return ranks
Ejemplo n.º 5
0
    def testIndex(self):
        """Check that we can load the index page."""
        raffle_prize = RafflePrize(
            title="Test raffle prize",
            description="A raffle prize for testing",
            round=RoundSetting.objects.get(name="Round 3"),
            value=5,
        )
        raffle_prize.save()

        response = self.client.get(reverse("win_index"))
        self.failUnlessEqual(response.status_code, 200)
        self.assertContains(
            response,
            "Round 2 Raffle",
            msg_prefix="We should be in round 2 of the raffle.")
        print response
        self.assertContains(
            response,
            "Your Total Raffle Tickets: <em class=\"raffle-ticket-num\">0</em>,",
            msg_prefix="User should not have any raffle tickets.")
        self.assertContains(
            response,
            "Allocated:  <em class=\"raffle-ticket-num\">0</em>,",
            msg_prefix="User should not have any raffle tickets.")
        self.assertContains(
            response,
            "Available: <em class=\"raffle-ticket-num\">0</em>",
            msg_prefix="User should not have any raffle tickets.")
        deadline = challenge_mgr.get_round_info()["end"]
        date_string = deadline.strftime("%b. %d, %Y, %I:%M ")
        date_string = re.sub(r" \b0", " ", date_string)
        #self.assertContains(response, "Deadline for Round 2 submissions: " + date_string,
        #    msg_prefix="Raffle should have the correct deadline.")

        # Give the user some points and see if their tickets update.
        profile = self.user.get_profile()
        profile.add_points(25, datetime.datetime.today(), "test")
        profile.save()
        response = self.client.get(reverse("win_index"))
        self.assertContains(
            response,
            "Your Total Raffle Tickets: <em class=\"raffle-ticket-num\">1</em>",
            msg_prefix="User should have 1 raffle ticket.")
        self.assertContains(
            response,
            "Allocated:  <em class=\"raffle-ticket-num\">0</em>,",
            msg_prefix="User should have 1 raffle ticket.")
        self.assertContains(
            response,
            "Available: <em class=\"raffle-ticket-num\">1</em>",
            msg_prefix="User should have 1 raffle ticket.")
Ejemplo n.º 6
0
def supply(request, page_name):
    """Supply the view_objects contents, which provides all raffle data."""
    _ = page_name
    user = request.user
    today = datetime.datetime.today()
    current_round_info = challenge_mgr.get_round_info()
    if not current_round_info:
        # no in any round
        return {"today": today}

    deadline = current_round_info["end"]

    # Get the user's tickets.
    total_tickets = RaffleTicket.total_tickets(user)

    user_tickets = RaffleTicket.objects.filter(
        user=user).select_related("raffle_prize")
    allocated_tickets = user_tickets.count()
    available_tickets = total_tickets - allocated_tickets

    prizes = None
    if today < deadline:
        # Get the prizes for the raffle.
        prizes = RafflePrize.objects.filter(
            round__name=current_round_info["name"]).annotate(
                total_tickets=Count("raffleticket")).order_by("-value")

        for prize in prizes:
            prize.user_tickets = 0
            for ticket in user_tickets:
                if ticket.raffle_prize == prize:
                    prize.user_tickets += 1

    return {
        "round_name": current_round_info["name"],
        "deadline": deadline,
        "today": today,
        "points_per_ticket": POINTS_PER_TICKET,
        "tickets": {
            "available": available_tickets,
            "total": total_tickets,
            "allocated": allocated_tickets,
        },
        "prizes": prizes,
    }
Ejemplo n.º 7
0
def supply(request, page_name):
    """Supply the view_objects contents, which provides all raffle data."""
    _ = page_name
    user = request.user
    today = datetime.datetime.today()
    current_round_info = challenge_mgr.get_round_info()
    if not current_round_info:
        # no in any round
        return {"today": today}

    deadline = current_round_info["end"]

    # Get the user's tickets.
    total_tickets = RaffleTicket.total_tickets(user)

    user_tickets = RaffleTicket.objects.filter(user=user).select_related("raffle_prize")
    allocated_tickets = user_tickets.count()
    available_tickets = total_tickets - allocated_tickets

    prizes = None
    if today < deadline:
        # Get the prizes for the raffle.
        prizes = RafflePrize.objects.filter(
            round__name=current_round_info["name"]).annotate(
            total_tickets=Count("raffleticket")).order_by("-value")

        for prize in prizes:
            prize.user_tickets = 0
            for ticket in user_tickets:
                if ticket.raffle_prize == prize:
                    prize.user_tickets += 1

    return {
        "round_name": current_round_info["name"],
        "deadline": deadline,
        "today": today,
        "points_per_ticket": POINTS_PER_TICKET,
        "tickets": {
            "available": available_tickets,
            "total": total_tickets,
            "allocated": allocated_tickets,
            },
        "prizes": prizes,
        }
Ejemplo n.º 8
0
def get_daily_goal_data(team, resource):
    """:return: the daily energy goal data."""

    round_info = challenge_mgr.get_round_info()
    if not round_info:
        return None

    start = round_info["start"].date()
    end = round_info["end"].date()
    delta = (end - start).days + 1
    data_table = []
    for day in range(0, delta):
        date = start + datetime.timedelta(days=day)

        goal_info = {"date": date}

        if day == 0:
            # cal and store the filler_days in the first day goal_info
            goal_info["filler_days"] = range(0, date.weekday())

        if day == (delta - 1):
            # cal and store the filler_days in the last day goal_info
            goal_info["filler_days"] = range(0, 6 - date.weekday())

        goal = resource_goal.team_goal(date, team, resource)
        goal_settings = resource_goal.team_goal_settings(team, resource)
        unit = resource_mgr.get_resource_setting(resource).unit
        goal_usage = resource_goal.team_daily_goal_usage(date, team, resource, goal_settings)
        goal_info["goal_info"] = "%d %s" % (goal_usage, unit)
        if goal:
            goal_info["goal_status"] = goal.goal_status
            goal_info["verbose_info"] = "%d %s used within the last 24 hours (ends at %s). " \
                                        "The goal is %d %s." % (
                resource_mgr.team_resource_usage(date, team, resource),
                unit,
                goal_settings.manual_entry_time,
                goal_usage,
                unit
            )

        data_table.append(goal_info)

    return data_table
Ejemplo n.º 9
0
def _get_round_start_end(round_name=None):
    """return the start and end date of a round regarding the round_reset."""
    if round_name == "Overall":
        all_round_info = challenge_mgr.get_all_round_info()
        start = all_round_info["competition_start"]
        end = all_round_info["competition_end"]
    else:
        round_info = challenge_mgr.get_round_info(round_name)
        if not round_info:
            return None

        end = round_info["end"].date
        if round_info["round_reset"]:
            start = round_info["start"].date
        else:
            # if no round reset, use the competition_start as start date
            start = challenge_mgr.get_all_round_info()["competition_start"]

    return start, end
Ejemplo n.º 10
0
def add_ticket(request, prize_id):
    """Adds a user's raffle ticket to the prize."""
    if request.method == "POST":
        prize = get_object_or_404(RafflePrize, id=prize_id)
        user = request.user
        current_round_info = challenge_mgr.get_round_info()
        deadline = current_round_info["end"]
        in_deadline = datetime.datetime.today() <= deadline

        if RaffleTicket.available_tickets(user) > 0 and in_deadline:
            prize.add_ticket(user)
            return HttpResponseRedirect(reverse("win_index"))
        elif not in_deadline:
            messages.error(request, "The raffle for this round is over.")
            return HttpResponseRedirect(reverse("win_index"))
        else:
            messages.error(request, "Sorry, but you do not have any more tickets.")
            return HttpResponseRedirect(reverse("win_index"))

    raise Http404
Ejemplo n.º 11
0
def add_ticket(request, prize_id):
    """Adds a user's raffle ticket to the prize."""
    if request.method == "POST":
        prize = get_object_or_404(RafflePrize, id=prize_id)
        user = request.user
        current_round_info = challenge_mgr.get_round_info()
        deadline = current_round_info["end"]
        in_deadline = datetime.datetime.today() <= deadline

        if RaffleTicket.available_tickets(user) > 0 and in_deadline:
            prize.add_ticket(user)
            return HttpResponseRedirect(reverse("win_index"))
        elif not in_deadline:
            messages.error(request, "The raffle for this round is over.")
            return HttpResponseRedirect(reverse("win_index"))
        else:
            messages.error(request,
                           "Sorry, but you do not have any more tickets.")
            return HttpResponseRedirect(reverse("win_index"))

    raise Http404
Ejemplo n.º 12
0
def get_daily_goal_data(team, resource):
    """:return: the daily energy goal data."""

    round_info = challenge_mgr.get_round_info()
    if not round_info:
        return None

    today = datetime.date.today()
    start = round_info["start"].date()
    end = round_info["end"].date()
    delta = (end - start).days + 1
    data_table = []
    for day in range(0, delta):
        date = start + datetime.timedelta(days=day)
        goal_info = {"date": date, "resource": resource}

        if day == 0:
            # cal and store the filler_days in the first day goal_info
            goal_info["filler_days"] = range(0, date.weekday())

        if day == (delta - 1):
            # cal and store the filler_days in the last day goal_info
            goal_info["filler_days"] = range(0, 6 - date.weekday())

        if date <= today:
            if date == datetime.date.today():
                goal_info["is_today"] = True

            if resource_mgr.is_blackout(date):
                # the game is disabled for the blackout dates
                goal_info["goal_status"] = "Not available"
                goal_info["verbose_info"] = "Game disabled for today"
            else:
                _set_goal_info(goal_info, resource, team, date)

        data_table.append(goal_info)

    return data_table
Ejemplo n.º 13
0
def get_daily_goal_data(team, resource):
    """:return: the daily energy goal data."""

    round_info = challenge_mgr.get_round_info()
    if not round_info:
        return None

    today = datetime.date.today()
    start = round_info["start"].date()
    end = round_info["end"].date()
    delta = (end - start).days + 1
    data_table = []
    for day in range(0, delta):
        date = start + datetime.timedelta(days=day)
        goal_info = {"date": date, "resource": resource}

        if day == 0:
            # cal and store the filler_days in the first day goal_info
            goal_info["filler_days"] = range(0, date.weekday())

        if day == (delta - 1):
            # cal and store the filler_days in the last day goal_info
            goal_info["filler_days"] = range(0, 6 - date.weekday())

        if date <= today:
            if date == datetime.date.today():
                goal_info["is_today"] = True

            if resource_mgr.is_blackout(date):
                # the game is disabled for the blackout dates
                goal_info["goal_status"] = "Not available"
                goal_info["verbose_info"] = "Game disabled for today"
            else:
                _set_goal_info(goal_info, resource, team, date)

        data_table.append(goal_info)

    return data_table
Ejemplo n.º 14
0
def reached_round(user, name):
    """Returns True if the current time was past the start of specified round."""
    _ = user
    info = challenge_mgr.get_round_info(name)
    today = datetime.datetime.today()
    return info and today >= info["start"]