Exemplo n.º 1
0
def prizes(req):
    if not req.user.is_authenticated:
        raise Http404()
    if req.POST.get('action') == 'purchase':
        try:
            prize = Prize.objects.get(id=req.POST.get('prize'))
            if prize.stock <= 0:
                raise ValueError("Not enough stock")
            if prize.cost > req.user.bonuses:
                raise ValueError("Too expensive")
            purchase = Purchase()
            purchase.user = req.user
            purchase.prize = prize
            purchase.code = ''.join(
                random.choice("ABCDEFGHKMNPQRSTUVWXYZ23456789")
                for _ in range(8))
            purchase.status = Purchase.PAYED
            purchase.save()
            transaction = Transaction()
            transaction.sender = req.user
            transaction.amount = prize.cost
            transaction.save()
            req.user.bonuses -= prize.cost
            req.user.save()
            prize.stock -= 1
            prize.save()
            return redirect('/')
        except:
            raise Http404()
    return render(req,
                  'prizes.html',
                  context=dict(prizes=Prize.objects.filter(
                      stock__gt=0).order_by('cost').all()))
Exemplo n.º 2
0
def autoreward_lesson(lesson):
    if not lesson.contest_id:
        return
    upsolving = is_upsolving(lesson.contest_id)
    rules = [Rule(upsolving, rule) for rule in lesson.autorewards.split("\n")]
    runs = run_contests_cmd(lesson.contest_id, "dump-filtered-runs",
                            "status==OK", "0", "-1").split('\n')
    for s in runs:
        if not s:
            continue
        info = s.split(';')
        user_id, prob = int(info[10]), info[18]
        if not Autoreward.objects.filter(
                user__id=user_id, prob=prob, lesson=lesson).exists():
            score = 0
            for rule in rules:
                if rule.appliable(prob):
                    score += rule.score
                    if not rule.add:
                        break
            r = Autoreward()
            r.user = EjudgeAuthBackend().get_user(user_id)
            r.prob = prob
            r.lesson = lesson
            r.save()
            if score > 0:
                r.user.bonuses += score
                r.user.save()
                lesson.bank.bonuses -= score
                tr = Transaction()
                tr.sender = lesson.bank
                tr.receiver = r.user
                tr.amount = score
                tr.save()
    lesson.bank.save()
Exemplo n.º 3
0
def add_bonuses(modeladmin, request, queryset):
    bonuses = int(request.POST['bonuses'])
    for user in queryset:
        user.bonuses += bonuses
        user.save()
        tr = Transaction()
        tr.receiver = user
        tr.amount = bonuses
        tr.save()
Exemplo n.º 4
0
    def delete(self, request, *args, **kwargs):
        model = ujson.loads(request.POST.get("model", '{}'))
        goal = get_object_or_404(Goal,
                                 pk=model["id"],
                                 account__primary_owner=self.client)
        goal.archived = True
        # remove from financial plan
        # remove automatic deposit and wdw
        #AutomaticWithdrawal.objects.filter(account=goal).delete()
        #AutomaticDeposit.objects.filter(account=goal).delete()

        # move shares
        if goal.total_balance > 0:
            if "transferAllTo" in model and model["transferAllTo"] != "bank":
                to_account = int(model["transferAllTo"])
                transfer_transaction = Transaction()
                transfer_transaction.type = "ACCOUNT_TRANSFER_FROM"
                transfer_transaction.from_account = goal
                transfer_transaction.to_account = get_object_or_404(Goal, pk=to_account,
                                                                    account__primary_owner=self.client)
                transfer_transaction.amount = goal.total_balance
                # transfer shares to the other account
                for p in Position.objects.filter(goal=transfer_transaction.from_account).all():
                    new_position, is_new = Position.objects.get_or_create(goal=transfer_transaction.to_account,
                                                                          ticker=p.ticker)
                    new_position.share += p.share
                    new_position.save()
                    p.delete()

                transfer_transaction.status = Transaction.STATUS_EXECUTED
                transfer_transaction.executed = now()
                transfer_transaction.save()

            else:
                # wdw all the money
                wdw_transaction = Transaction()
                wdw_transaction.account = goal
                wdw_transaction.type = Transaction.REASON_WITHDRAWAL
                wdw_transaction.amount = goal.total_balance
                wdw_transaction.save()
        goal.save()
        return HttpResponse('null', content_type="application/json")
Exemplo n.º 5
0
def make_declined(modeladmin, request, queryset):
    for purchase in queryset.all():
        purchase.user.bonuses += purchase.prize.cost
        purchase.user.save()
        purchase.prize.stock += 1
        purchase.prize.save()
        purchase.status = Purchase.DECLINED
        purchase.save()
        tr = Transaction()
        tr.receiver = purchase.user
        tr.amount = purchase.prize.cost
        tr.save()
Exemplo n.º 6
0
 def put(self, request):
     body = json.loads(request.body)
     transaction = Transaction()
     if 'currency' in body:
         transaction.choice_currency = body.get('currency')
     transaction.transaction_from = FinancialNode.objects.filter(
         id=int(body['transaction_from'])).first()
     transaction.transaction_to = FinancialNode.objects.filter(
         id=int(body['transaction_to'])).first()
     transaction.amount = int(body['amount'])
     transaction.data_from = datetime.strptime(body['date'],
                                               '%d.%m.%Y').date()
     transaction.user = request.user
     transaction.save()
     body['id'] = transaction.id
     body['transaction_from'] = transaction.transaction_from.name
     body['transaction_to'] = transaction.transaction_to.name
     return JsonResponse({'ok': True, 'body': body})
Exemplo n.º 7
0
def close_casino(finalize=True):
    for group in Group.objects.all():
        if group.casino_contest:
            if finalize:
                finalize_casino(group)
            with open(os.path.join(MEDIA_ROOT, 'casino_%d.html' % group.id),
                      "w") as f:
                f.write(render_casino(group))
    for session in CasinoSession.objects.all():
        if session.won:
            tr = Transaction()
            tr.receiver = session.user
            tr.amount = session.won
            tr.save()
            session.user.bonuses += session.won
            session.user.save()
    for group in Group.objects.all():
        if group.casino_contest:
            reset_contest(casino_contest)
    CasinoSession.objects.all().delete()
Exemplo n.º 8
0
def casino(req, group_id):
    session = False
    try:
        group = Group.objects.get(id=group_id)
        if CasinoSession.objects.filter(user=req.user, group=group).exists():
            session = True
        if not group.casino_contest:
            raise ValueError
        if not req.user.is_authenticated:
            raise ValueError
        if not User.objects.filter(id=req.user.id,
                                   groups__id=group.id).exists():
            raise ValueError
    except:
        raise Http404()
    if req.POST.get('action') == 'start' and not session:
        try:
            bet = int(req.POST.get('bet'))
            if bet < 0:
                raise ValueError
            if bet > req.user.bonuses:
                raise ValueError
            sess = CasinoSession()
            sess.group = group
            sess.user = req.user
            sess.bet = bet
            sess.save()
            sess.start_contest()
            transaction = Transaction()
            transaction.sender = req.user
            transaction.amount = bet
            transaction.save()
            req.user.bonuses -= bet
            req.user.save()
            return redirect('/casino/%d/play' % group.id)
        except:
            raise Http404()

    return render(req,
                  'casino.html',
                  context=dict(group=group, session=session))
Exemplo n.º 9
0
    def post(self, request, *args, **kwargs):
        payload = ujson.loads(request.body.decode('utf8'))
        goal = get_object_or_404(Goal,
                                 pk=kwargs["pk"],
                                 account__primary_owner=self.client)
        new_transaction = Transaction()
        new_transaction.account = goal
        new_transaction.from_account = None
        new_transaction.to_account = None
        new_transaction.type = Transaction.REASON_WITHDRAWAL
        new_transaction.amount = payload["amount"]
        new_transaction.save()

        nt_return = {
            "transactionId": new_transaction.pk,
            "account": new_transaction.account.pk,
            "type": new_transaction.type,
            "amount": new_transaction.amount
        }

        return HttpResponse(ujson.dumps(nt_return),
                            content_type="application/json")
Exemplo n.º 10
0
    def post(self, request, *args, **kwargs):
        model = ujson.loads(request.POST.get("model", '{}'))
        new_transaction = Transaction()
        if model['account']:
            new_transaction.account = get_object_or_404(
                Goal,
                pk=model['account'],
                account__primary_owner=self.client)

        new_transaction.from_account = None
        new_transaction.to_account = None
        new_transaction.type = model["type"]
        new_transaction.amount = model["amount"]

        if model["fromAccount"]:
            new_transaction.from_account = get_object_or_404(
                Goal,
                pk=model['fromAccount'],
                account__primary_owner=self.client)

        if model["toAccount"]:
            new_transaction.to_account = get_object_or_404(
                Goal,
                pk=model['toAccount'],
                account__primary_owner=self.client)

        new_transaction.save()

        if new_transaction.type == "ACCOUNT_TRANSFER_FROM":
            # transfer shares to the other account
            total_balance = new_transaction.from_account.total_balance
            transaction_amount = float(new_transaction.amount)
            for p in Position.objects.filter(goal=new_transaction.from_account).all():
                transfer_share_size = (p.value/total_balance) * transaction_amount / p.ticker.unit_price
                p.share -= transfer_share_size
                p.save()
                new_position, is_new = Position.objects.get_or_create(goal=new_transaction.to_account, ticker=p.ticker)
                new_position.share += transfer_share_size
                new_position.save()
            new_transaction.status = Transaction.STATUS_EXECUTED
            new_transaction.executed = now()
            new_transaction.save()

        if not new_transaction.account:
            return HttpResponse("null", content_type='application/json')

        nt_return = {
            "id": new_transaction.pk,
            "type": new_transaction.type,
            "amount": new_transaction.amount
        }
        if new_transaction.account:
            nt_return["account"] = new_transaction.account.pk

        if new_transaction.from_account:
            nt_return["fromAccount"] = new_transaction.from_account.pk

        if new_transaction.to_account:
            nt_return["toAccount"] = new_transaction.to_account.pk

        return HttpResponse(ujson.dumps(nt_return),
                            content_type='application/json')
Exemplo n.º 11
0
    def post(self, request):
        try:
            date_t = request.POST["date_t"] if "date_t" in request.POST else None
            date_bank = request.POST["date_bank"] if "date_bank" in request.POST else None
            if date_bank == "":
                date_bank = None
            amount = float(request.POST["amount"].replace(",", "."))
            subject = request.POST["subject"]
            try:
                category = Category.objects.get(pk=request.POST["category"])
            except Category.DoesNotExist:
                return JsonResponse({"success": False,
                                     "message": "Category %s does not exists" % request.POST["category"]})
            try:
                month = Month.objects.get(pk=request.POST["month"]) \
                    if ("month" in request.POST and request.POST["month"] != "") else None
            except Month.DoesNotExist:
                return JsonResponse({"success": False, "message": "Month %s does not exists" % request.POST["month"]})
            tr_id = request.POST["tr_id"] if "tr_id" in request.POST else None
            group_id = request.POST["group_id"] if "group_id" in request.POST else None
            if tr_id == "":
                tr_id = None
        except (KeyError, ValueError):
            traceback.print_exc()
            return JsonResponse({"success": False, "message":
                                 "Bad query. Please contact the support to report the bug"})

        if (group_id is None or group_id == "") and (date_t is None or month is None):
            return JsonResponse({"success": False,
                                 "message": "Bad request (2). please contact the support to report the bug"})

        if group_id is None or group_id == "":
            try:
                date_regex = r"^\d\d/\d\d/\d\d\d\d$"
                if date_t is not None:
                    if not re.match(date_regex, date_t):
                        raise ValueError("Invalid date: %s" % date_t)
                    date_t = functions.format_date(date_t)
                else:
                    raise ValueError("Date is required")
                if date_bank is not None and date_bank != "":
                    if not re.match(date_regex, date_bank):
                        raise ValueError("Invalid date: %s" % date_bank)
                    date_bank = functions.format_date(date_bank)
            except ValueError as e:
                return JsonResponse({"success": False, "message": str(e)})

        try:
            if tr_id is None:
                # Add a new transaction
                try:
                    with db_transaction.atomic():
                        if group_id is None or group_id == "":
                            transaction_group = TransactionGroup(date_t=date_t, date_bank=date_bank, month=month)
                            transaction_group.save()
                        else:
                            try:
                                transaction_group = TransactionGroup.objects.get(pk=int(group_id))
                            except TransactionGroup.DoesNotExist:
                                return JsonResponse({"success": False, "message": "Transaction group does not exists"})
                        transaction = Transaction(amount=amount, subject=subject, category=category,
                                                  group=transaction_group)
                        transaction.save()
                        tr_id = transaction.pk
                except:
                    db_transaction.rollback()
                    traceback.print_exc()
                    return JsonResponse({"success": False,
                                         "message": "An unexpected error occurred. Please contact the support"})
            else:
                # Edit existing transaction
                try:
                    with db_transaction.atomic():
                        try:
                            transaction = Transaction.objects.get(pk=tr_id)
                            transaction_group = transaction.group
                            transaction_group.date_t = date_t
                            transaction_group.date_bank = date_bank
                            transaction_group.month = month
                            transaction_group.save()
                            transaction.amount = amount
                            transaction.subject = subject
                            transaction.category = category
                            transaction.save()
                        except:
                            db_transaction.rollback()
                            raise Exception()
                except Transaction.DoesNotExist:
                    db_transaction.rollback()
                    return JsonResponse({"success": False, "message": "Transaction %s does not exists" % tr_id})
                except:
                    db_transaction.rollback()
                    traceback.print_exc()
                    return JsonResponse({"success": False,
                                         "message": "An unexpected error occurred. Please contact the support"})
        except:
            traceback.print_exc()
            return JsonResponse({"success": False,
                                 "message": "An unexpected error occurred. Please contact the support"})

        return JsonResponse({"success": True,
                             "html": render_to_string("main_content.html",
                                                      {"data": content_data(request.user)}),
                             "tr_id": tr_id})