예제 #1
0
def _create_withdrawal(bot, update):
    text = update.message.text

    try:
        amount = _validate_transaction(bot.user, text)
    except ValueError:
        bot.send_message(chat_id=bot.chat_id, text=lang.invalid_input())
        return bot_states.CREATE_WITHDRAWAL
    except LessThanMinimalWithdraw:
        bot.send_message(chat_id=bot.chat_id,
                         text=lang.minimal_withdraw_amount())
        return bot_states.CREATE_WITHDRAWAL
    except NotEnoughBalance:
        bot.send_message(chat_id=bot.chat_id, text=lang.not_enough_eth())
        return bot_states.CREATE_WITHDRAWAL

    try:
        not_approved_withdrawal = Withdrawal.get(approved=False)
        bot.send_message(chat_id=bot.chat_id,
                         text=lang.not_approved_previous(
                             not_approved_withdrawal.amount),
                         reply_markup=keyboards.main_keyboard())
        return bot_states.MAIN
    except DoesNotExist:
        pass

    Withdrawal.create(user=bot.user, amount=amount)

    bot.send_message(chat_id=bot.chat_id,
                     text=lang.withdrawal_created(bot.user.wallet),
                     reply_markup=keyboards.main_keyboard())

    return bot_states.MAIN
예제 #2
0
def withdraw_investment():
    invest_id = request.form.get("invest_id")
    invest_type = request.form.get("type")

    context = {}
    all_tasks = Admin_tasks.query.all()
    for task in all_tasks:
        context[f"{task.key}"] = task.value

    invest = Investments.query.get(invest_id)
    if invest_type == "profit":
        funds = invest.expected_return - invest.capital
        withdraw = Withdrawal(investment_id=invest.id,
                              amount=funds,
                              withdraw_type=invest_type,
                              user_id=current_user.id)
        invest.profit_withdraw = True
        # print(invest.profit_withdraw)
        db.session.add(withdraw)
        db.session.commit()

        flash(
            f'You have successfully request to withdraw your profit which is #{funds}, You will be credited anytime soon'
        )
        return redirect(url_for('my_investment', id=invest.id))

    elif invest_type == "capital":
        funds = invest.capital
        withdraw = Withdrawal(investment_id=invest.id,
                              amount=funds,
                              withdraw_type=invest_type,
                              user_id=current_user.id)
        invest.capital_withdraw = True
        db.session.add(withdraw)
        db.session.commit()
        flash(
            f'You have successfully request to withdraw your profit which is #{funds}, You will be credited anytime soon'
        )
        return redirect(url_for('my_investment', id=invest.id))

    elif invest_type == "bonus":
        funds = current_user.bonus_wallet
        if int(funds) >= int(context["min_ref_withdraw"]):
            funds = current_user.bonus_wallet
            withdraw = Withdrawal(amount=funds,
                                  withdraw_type="bonus",
                                  user_id=current_user.id)
            current_user.bonus_wallet = "0"
            db.session.add(withdraw)
            db.session.commit()
            flash(
                f'You have successfully request to withdraw your bonus which is #{funds}, You will be credited anytime soon'
            )
            return redirect(url_for('dashboard'))
        else:
            flash(
                f"You don't have up to #{context['min_ref_withdraw']} Refer enough people to have above #{context['min_ref_withdraw']} in your bonus wallet"
            )
            return redirect(url_for('dashboard'))
예제 #3
0
def withdrawals():
    withdrawals = Withdrawal.select(Withdrawal, User) \
        .where(Withdrawal.approved == False).order_by(Withdrawal.created_at).join(User)

    total_sum = Withdrawal.select(fn.COALESCE(fn.SUM(Withdrawal.amount), 0).alias('total_sum')) \
        .where(Withdrawal.approved == False).execute()

    return render_template(
        'withdrawals.html',
        total_sum=total_sum[0].total_sum,
        withdrawals=withdrawals,
    )
예제 #4
0
def approve_withdrawal():
    id = request.get_json(silent=True)['id']
    withdrawal = Withdrawal.get(id=id)
    if withdrawal.approved:
        return Response(response='The conclusion has already been confirmed',
                        status=400,
                        mimetype='application/json')
    withdrawal.approved = True
    withdrawal.save()
    return Response(response='Successfully',
                    status=200,
                    mimetype='application/json')
예제 #5
0
def statistics():
    def get_chart_data_for_transactions(transactions, columns):
        statistics_data = {}
        for transaction in transactions:
            date = transaction.created_at.strftime("%d %B")
            if date not in statistics_data:
                statistics_data[date] = 0
            statistics_data[date] += float(transaction.amount)

        chart_data = [columns]
        for day in statistics_data.keys():
            chart_data.append([day, statistics_data[day]])

        return chart_data

    now = datetime.datetime.now()
    month_ago = now - datetime.timedelta(days=30)
    withdrawals = Withdrawal.select() \
        .where(Withdrawal.created_at < now) \
        .where(Withdrawal.created_at > month_ago).order_by(Withdrawal.created_at)

    top_ups = TopUp.select() \
        .where(TopUp.created_at < now) \
        .where(TopUp.created_at > month_ago).order_by(TopUp.created_at)

    withdrawal_data = get_chart_data_for_transactions(withdrawals,
                                                      ['Day', 'Withdrawals'])

    top_up_data = get_chart_data_for_transactions(top_ups, ['Day', 'TopUps'])

    registrations = User.select().where(User.created_at < now) \
        .where(User.created_at > month_ago).order_by(User.created_at)

    registration_temp = {}
    for registration in registrations:
        date = registration.created_at.strftime("%d %B")
        if date not in registration_temp:
            registration_temp[date] = 0
        registration_temp[date] += 1

    registration_data = [['Day', 'Registrations']]

    for day in registration_temp.keys():
        registration_data.append([day, registration_temp[day]])

    return render_template('statistics.html',
                           withdrawal_data=withdrawal_data,
                           top_up_data=top_up_data,
                           registration_data=registration_data)
예제 #6
0
def approve_withdrawal():
    id = request.get_json(silent=True)['id']
    withdrawal = Withdrawal.get(id=id)
    if withdrawal.approved:
        return Response(
            response='Вывод уже был подтвержден',
            status=400,
            mimetype='application/json'
        )
    withdrawal.approved = True
    withdrawal.save()
    return Response(
        response='Успешно',
        status=200,
        mimetype='application/json'
    )
예제 #7
0
파일: admin4.py 프로젝트: DeadMonstr/gennis
def withdrawal():
    user = get_current_user()
    try:
        if not user.gazalkent_admin and not user.director and not user.xojakent_admin:
            return redirect(url_for('home'))
    except AttributeError:
        return redirect(url_for('home'))
    if request.method == "POST":
        who = request.form.get('who')
        why = request.form.get('why')
        sum = int(request.form.get('amount'))
        add = Withdrawal(who=who, why=why, amount=sum, date=now)
        db.session.add(add)
        witdh = All_withdrawal.query.filter_by(id=1).first()
        all = witdh.total_sum + sum
        All_withdrawal.query.filter_by(id=1).update({'total_sum': all})
        db.session.commit()
        return redirect(url_for('withdrawal'))
    withdrawals = Withdrawal.query.order_by('id').all()
    all_withdrawal = All_withdrawal.query.order_by('id').all()
    return render_template('payment/withdrawal.html',
                           user=user,
                           withdrawals=withdrawals,
                           all_withdrawal=all_withdrawal)
예제 #8
0
def settings():
    change_username_form = ChangeUsernameForm()
    change_email_form = ChangeMailForm()
    change_password_form = ChangePasswordForm()
    add_funds_form = TopUpBalanceForm()
    withdrawal_form = WithdrawalForm()

    channels = db.session.query(Channel).filter(Channel.admin_id == current_user.id)

    # actions with changing username
    if change_username_form.validate_on_submit():
        if re.search('[a-zA-Z]', change_username_form.name.data):
            current_user.name = change_username_form.name.data
            db.session.commit()
            flash('Successfully updated your username!')
            return redirect(url_for('settings'))
        else:
            flash('Invalid username! It must contain at least 1 english letter.')
            return redirect(url_for('settings'))

    # actions with changing email
    if change_email_form.validate_on_submit():
        if db.session.query(User).filter_by(email=(change_email_form.new_email.data).lower()).first():
            flash("Error! User with the given email already exists! ")
            return redirect(url_for('settings'))

        if check_password_hash(current_user.password, change_email_form.current_password.data):
            curr = db.session.query(User).filter_by(email=(current_user.email).lower()).first()
            curr.email = change_email_form.new_email.data
            # Message sending
            token = s.dumps(change_email_form.new_email.data, salt='email-confirm')
            msg = Message('Confirm Email', sender='*****@*****.**',
                          recipients=[change_email_form.new_email.data])

            link = url_for('confirm_email', token=token, _external=True)
            msg.body = 'Your link is {}'.format(link)

            mail.send(msg)
            current_user.email_confirmed = 0
            db.session.commit()
            flash("Success! Now you can confirm your new email!")
            return redirect(url_for('settings'))
        else:
            flash("Error! Password does not match! ")
            return redirect(url_for('settings'))

    # actions with withdrawal
    w = Withdrawal.query.filter_by(user_id=current_user.id)
    if withdrawal_form.validate_on_submit():
        if current_user.current_balance < withdrawal_form.amount.data:
            flash('You do not have enough funds!')
            return redirect('/settings')

        reserved_sum = 0
        for channel in current_user.channels:
            for r in channel.requests:
                if r.posted and datetime.datetime.utcnow() < r.post_time:
                    reserved_sum += r.channel.price
        if current_user.current_balance - reserved_sum < withdrawal_form.amount.data:
            diff = float(current_user.current_balance) - float(
                reserved_sum) if current_user.current_balance - reserved_sum > 0 else 0
            flash('You\'ve got only ${} available, the rest is reserved till the end of posting duration!'.
                  format(diff))
            return redirect('/settings')
        else:
            user = db.session.query(User).filter_by(email=current_user.email).first()
            user.current_balance -= withdrawal_form.amount.data
            db.session.commit()

            new_withdrawal = Withdrawal(status="Request sent", amount=withdrawal_form.amount.data,
                                        card=withdrawal_form.card.data,
                                        user_id=current_user.id)
            db.session.add(new_withdrawal)
            db.session.commit()

            msg = Message('Withdrawal request', sender='*****@*****.**', recipients=["*****@*****.**"])
            msg.body = 'User ' + current_user.email + ' wants ' + str(
                withdrawal_form.amount.data) + ' dollars on ' + str(
                withdrawal_form.card.data)
            mail.send(msg)

            flash('Your request was successfully sent!')
            return redirect('/settings')

    # actions with adding funds
    if add_funds_form.validate_on_submit() and request.method == 'POST':
        curr = db.session.query(User).filter_by(email=current_user.email).first()
        if isinstance(add_funds_form.amount.data, int) and add_funds_form.amount.data > 1:
            customer = stripe.Customer.create(email=request.form['stripeEmail'],
                                              source=request.form['stripeToken'])
            charge = stripe.Charge.create(
                customer=customer,
                amount=add_funds_form.amount.data * 100,
                currency='usd',
                description='Posting'
            )

            curr.current_balance = curr.current_balance + add_funds_form.amount.data
            db.session.commit()

            flash('Successfully replenished your balance!')
            return redirect('/settings')
        else:
            flash('Ooops...Something went wrong')
            return redirect('/settings')

    # actions with changing password
    if change_password_form.validate_on_submit():
        if check_password_hash(current_user.password, change_password_form.current_password.data):
            new_hashed_password = generate_password_hash(change_password_form.new_password.data, method='sha256')

            curr = db.session.query(User).filter_by(email=current_user.email).first()
            curr.password = new_hashed_password

            db.session.commit()
            flash('Successfully updated your password!')
            return redirect(url_for('settings'))
        else:
            flash('Current password is wrong!')
            return redirect(url_for('settings'))

    return render_template('profile/settings.html', change_username_form=change_username_form,
                           change_email_form=change_email_form, add_funds_form=add_funds_form,
                           withdrawal_form=withdrawal_form, w=w, change_password_form=change_password_form,
                           channels=channels)