def globalgamemodes(timespan="monthly", month=None, year=None):
    """Respond with view for global statistics for gamemodes, with optional timespan grouping. Currently only all time or by month."""
    query_timespan = request.args.get("timespan") if request.args.get(
        "timespan") else "monthly"
    request_month = int(
        request.args.get("month") if request.args.get("month") else datetime.
        datetime.now().month)
    request_year = int(
        request.args.get("year") if request.args.get("year") else datetime.
        datetime.now().year)
    request_starttime = datetime.datetime(year=request_year,
                                          month=request_month,
                                          day=1)

    request_timespan = (query_timespan, request_starttime)
    next_page = add_months(request_starttime, 1)
    prev_page = add_months(request_starttime, -1)
    (stats, counts) = global_stats.get_formatted_global_stats(request_timespan)
    return render_template('globalstats.html',
                           matchData=stats,
                           timespan=query_timespan,
                           query_start=request_starttime,
                           matchCounts=counts,
                           nextpage=next_page,
                           prevpage=prev_page)
Exemplo n.º 2
0
Arquivo: views.py Projeto: rozig/lend
    def post(self, request, loan_id=None):
        user = request.user
        loan = Loan.objects.filter(
            pk=loan_id).prefetch_related('loanpayment_set')
        if not loan.exists():
            return Response(
                {'detail': MESSAGES.get('NOT_FOUND').format('Loan')},
                status=status.HTTP_404_NOT_FOUND)

        loan = loan.first()
        if not loan.user == user:
            return Response({'detail': MESSAGES.get('NOT_LOAN_OWNER')},
                            status=status.HTTP_400_BAD_REQUEST)

        if loan.status == 'paid':
            return Response({'detail': MESSAGES.get('LOAN_ALREADY_PAID')},
                            status=status.HTTP_400_BAD_REQUEST)

        payment = loan.loanpayment_set.filter(status='pending')

        if not payment.exists():
            return Response({'detail': MESSAGES.get('LOAN_ALREADY_PAID')},
                            status=status.HTTP_400_BAD_REQUEST)

        payment = payment.first()
        payment.payment_date = datetime.datetime.now()
        payment.status = 'paid'
        payment.save()

        loan_profile = LoanProfile.objects.filter(user=user)
        loan_profile = loan_profile.first() \
            if loan_profile.exists() \
            else LoanProfile(user=user, score=0)
        today = datetime.date.today()
        if payment.deadline < today:
            loan_profile.score -= 3
        else:
            loan_profile.score += 1
        loan_profile.save()

        total_payment = 0
        for pm in loan.loanpayment_set.all():
            total_payment += pm.amount

        serializer = self.serializer_class(payment)
        response_data = serializer.data
        if total_payment >= (loan.amount +
                             loan.amount * loan.interest_rate / 100):
            loan.status = 'paid'
            loan.save()
        else:
            LoanPayment.objects.create(loan=loan,
                                       amount=payment.amount,
                                       status='pending',
                                       payment_date=None,
                                       deadline=add_months(
                                           payment.deadline, 1))

        response_data['loan_status'] = loan.status
        return Response(response_data)
def match_stats(timespan):
    """
    Return all match victories/losses that match timespan.

    Return all matches that match timespan. Then checks the match's victory conditions in checkModeVictory.

    Parameters:
        timespan(tuple): Three-part tuple. First part is "monthly" or "all".
        Second part is a datetime with month and year as the starting month.

    Returns:
        array: Array of MatchTypeVictory.

    """
    db = LocalProxy(lambda: current_app.db.session)
    q = models.Match.query
    timespan_criteria = None
    count_query = db.query(models.Match.modes_string,
                           func.count(models.Match.id))
    if timespan[0] != "all":
        query_start = timespan[1]
        query_end = add_months(query_start, 1)
        print(query_start, query_end)
        timespan_criteria = and_(
            models.Match.start_datetime is not None,
            models.Match.start_datetime.between(query_start, query_end))
        q = q.filter(timespan_criteria)
        count_query = count_query.filter(timespan_criteria)

    # completion-agnostic playrate first

    counts = count_query.group_by(models.Match.modes_string).all()
    formattedCounts = [list(a) for a in (zip(*counts))]

    q = q.filter(~models.Match.modes_string.contains('|'),
                 ~models.Match.mastermode.contains('mixed'))
    q = q.all()

    matches = []

    for match in q:
        if match.is_mixed():
            continue
        victory = checkModeVictory(match)
        if victory is None:
            continue
        s = True if match.mastermode == "secret" else False
        t = match.modes_string
        m = MatchTypeVictory(victory, s, t)
        matches.append(m)
    return matches, formattedCounts
def match_stats(timespan):
    """
    Return all match victories/losses that match timespan.

    Return all matches that match timespan. Then checks the match's victory conditions in checkModeVictory.

    Parameters:
        timespan(tuple): Three-part tuple. First part is "monthly" or "all". Second part is a datetime with month and year as the starting month.

    Returns:
        array: Array of MatchTypeVictory.

    """
    q = models.Match.query
    if timespan[
            0] != "all":  # TODO add browsing through dates that aren't  the current date
        query_start = timespan[1]
        query_end = add_months(query_start, 1)

        q = q.filter(
            and_(models.Match.date is not None,
                 models.Match.date >= query_start,
                 models.Match.date < query_end))

    q = q.filter(~models.Match.modes_string.contains('|'),
                 ~models.Match.mastermode.contains('mixed'))
    q = q.all()

    matches = []

    for match in q:
        if match.modes_string.lower() in do_not_show:
            continue
        if match.is_mixed():
            continue
        victory = checkModeVictory(match)
        if victory is None:
            continue
        s = True if match.mastermode == "secret" else False
        t = match.modes_string
        m = MatchTypeVictory(victory, s, t)
        matches.append(m)
    return matches
Exemplo n.º 5
0
Arquivo: views.py Projeto: rozig/lend
    def post(self, request):
        user = request.user
        requested_amount = request.data.get('amount')
        requested_length = request.data.get('length')

        errors = {}

        if not requested_amount:
            errors['amount'] = [
                MESSAGES.get('FIELD_REQUIRED').format('This field')
            ]

        if not requested_length:
            errors['length'] = [
                MESSAGES.get('FIELD_REQUIRED').format('This field')
            ]

        loan_profile = LoanProfile.objects.filter(user=user)
        if loan_profile.exists():
            loan_profile = loan_profile.first()
            loans = self.get_queryset().prefetch_related(
                'loanpayment_set').filter(user=user)

            for loan in loans:
                loan_finished = True
                total_amount = loan.amount + (loan.amount *
                                              loan.interest_rate / 100)
                amount = 0

                for payment in loan.loanpayment_set.filter(status='paid'):
                    amount += payment.amount
                if total_amount > amount:
                    loan_finished = False

                if not loan_finished:
                    return Response({'detail': MESSAGES.get('UNPAID_LOAN')},
                                    status=status.HTTP_400_BAD_REQUEST)

            num_of_loans = len(loans)
        else:
            loan_profile = LoanProfile.objects.create(user=user, score=0)
            num_of_loans = 0

        lend_score = loan_profile.score

        eligibility = is_eligible_lender(requested_amount, requested_length,
                                         lend_score, num_of_loans)

        if not eligibility['eligible']:
            return Response({'detail': eligibility['reason']},
                            status=status.HTTP_400_BAD_REQUEST)

        today = datetime.date.today()
        deadline = today.replace(year=today.year +
                                 math.ceil(requested_length / 12))
        loan_request = Loan.objects.create(
            user=user,
            amount=requested_amount,
            interest_rate=eligibility['interest_rate'],
            status='ongoing',
            deadline=deadline)

        account = Account.objects.get(user=user)
        account.balance += requested_amount
        account.updated_at = datetime.datetime.now()
        account.save()

        Transaction.objects.create(id=generate_transaction_id(),
                                   type='loan',
                                   amount=requested_amount,
                                   description='LOAN FOR {} {}'.format(
                                       user.first_name, user.last_name),
                                   account=account)

        payment_deadline = add_months(today, 1)

        payment_amount = requested_amount
        payment_amount += payment_amount * eligibility['interest_rate'] / 100
        payment_amount /= requested_length

        LoanPayment.objects.create(loan=loan_request,
                                   amount=payment_amount,
                                   status='pending',
                                   payment_date=None,
                                   deadline=payment_deadline)

        return Response({
            'id': loan_request.id,
            'monthly_payment_amount': payment_amount,
            'loan_length': requested_length,
            'loan_amount': requested_amount,
            'interest_rate': eligibility['interest_rate'],
            'next_payment_date': payment_deadline,
            'loan_deadline': deadline
        })