示例#1
0
文件: teller.py 项目: iecruz/qa-bank
def withdraw():
    if request.method == 'POST':
        account = Account.get(Account.id == session['atm_auth'])

        total_amount = (Transaction.select(fn.Sum(Transaction.amount).alias('amounts'))
            .where(
                (Transaction.account_number == account.account_number) & 
                (Transaction.created_at >= datetime.combine(datetime.today(), time.min)) & 
                (Transaction.type == 'ATM WITHDRAW')
            )
            .get()
        ).amounts or 0

        if float(total_amount) + float(request.form.get('amount')) > 25000:
            flash('You have reached the daily maximum withdraw limit')

        elif int(request.form.get('amount')) < 500:
            flash('Amount must be greater than Php 500.00')

        else:
            Account.update(balance = Account.balance - request.form.get('amount')).where(Account.id == session['atm_auth']).execute()

            Transaction.insert(
                account_number = account.account_number,
                reference_number = account.account_number,
                amount = request.form.get('amount'),
                type = 'ATM WITHDRAW'
            ).execute()
            
            return redirect(url_for('teller.inquiry'))
    return render_template('teller/withdraw.html')
示例#2
0
def home_meal(request, consumer_cpf):
    error = ""
    if request.method == 'POST':
        try:
            consumer = Consumer.objects.get(user__username=consumer_cpf)
            if consumer.has_studentship:
                value = 0
            else:
                value = consumer.get_meal_value(
                    request.POST['meal_kind']) * int(request.POST['quantity'])
            if consumer.credit >= value:
                transaction = Transaction(
                    type=Transaction.Type.Output.value,
                    value=value,
                    consumer_cpf=consumer.user.username,
                    operator=request.user.get_full_name())

                consumer.credit -= value
                transaction.save()
                consumer.save()
                return redirect('home')
            else:
                error = "Pessoa não Possui Saldo!"
        except Consumer.DoesNotExist:
            error = "Pessoa Não Cadastrada!"
    return render(request, 'application/home_meal.html', {'error': error})
示例#3
0
文件: main.py 项目: iecruz/qa-bank
def transfer():
    accounts = Account.select().where(
        (Account.user_id == session['user']['id'])
        & (Account.type != 3)).execute()

    form = UserTransferForm(request.form)
    form.sender_account_number.choices = [
        (account.account_number,
         "{} ({})".format(account.account_number,
                          'Savings' if account.type == 1 else 'ATM'))
        for account in accounts
    ]
    if form.validate_on_submit():
        sender_account = Account.get(
            Account.account_number == form.sender_account_number.data)
        receiver_account = Account.get(
            Account.account_number == form.receiver_account_number.data)

        Account.update(balance=Account.balance - form.amount.data,
                       updated_at=datetime.now()).where(
                           Account.account_number ==
                           form.sender_account_number.data).execute()

        Account.update(balance=Account.balance + form.amount.data,
                       updated_at=datetime.now()).where(
                           Account.account_number ==
                           form.receiver_account_number.data).execute()

        Transaction.insert(account_number=form.sender_account_number.data,
                           reference_number=form.receiver_account_number.data,
                           amount=form.amount.data,
                           type='FUND TRANSFER').execute()
        flash('Fund Transfer successful')
        return redirect(url_for('main.transfer'))
    return render_template('main/transfer.html', form=form)
示例#4
0
文件: admin.py 项目: iecruz/qa-bank
def transfer():
    form = TransferForm(request.form)
    if form.validate_on_submit():
        sender_account = Account.get(Account.account_number == form.sender_account_number.data)
        receiver_account = Account.get(Account.account_number == form.receiver_account_number.data)

        Account.update(
            balance = Account.balance - form.amount.data,
            updated_at = datetime.now()
        ).where(Account.account_number == form.sender_account_number.data).execute()

        Account.update(
            balance = Account.balance + form.amount.data,
            updated_at = datetime.now()
        ).where(Account.account_number == form.receiver_account_number.data).execute()

        Transaction.insert(
            account_number = form.sender_account_number.data,
            reference_number = form.receiver_account_number.data,
            amount = form.amount.data,
            type = 'FUND TRANSFER'
        ).execute()
        flash('Fund Transfer successful')
        return redirect(url_for('admin.transfer'))
    return render_template('admin/transfer.html', form=form)
示例#5
0
    def test_can_set_as_paid_if_has_withdraw_address_internal(self):
        # Creates an withdraw address fro this user
        address = Address(user=self.user,
                          type='W',
                          address='17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j')
        address.save()

        payment_method = PaymentMethod(name='Internal Test', is_internal=True)
        payment_method.save()

        pref = PaymentPreference(payment_method=payment_method,
                                 user=self.order.user,
                                 identifier='InternalTestIdentifier')
        pref.save()

        payment = Payment(payment_preference=pref,
                          amount_cash=self.order.amount_cash,
                          order=self.order,
                          currency=self.RUB,
                          user=self.order.user)
        payment.save()
        # Creates an Transaction for the Order, using the user Address
        transaction = Transaction(order=self.order,
                                  address_to=address,
                                  address_from=address)
        transaction.save()

        # Set Order as Paid
        response = self.client.post(self.url, {'paid': 'true'})
        expected = {"frozen": True, "paid": True, "status": "OK"}
        self.assertJSONEqual(
            json.dumps(expected),
            str(response.content, encoding='utf8'),
        )
示例#6
0
文件: main.py 项目: iecruz/bank-admin
def time_deposit():
    form = TimeDepositForm(request.form)
    form.duration.choices = ([(3, '3 months (7.0% interest)'),
                              (6, '6 months (8.0% interest)'),
                              (12, '12 months (9.0% interest)')])

    if form.validate_on_submit():
        interest_ref = {3: 7.0, 6: 8.0, 12: 9.0}

        Account.update(
            time_deposit=Account.time_deposit + form.amount.data,
            updated_at=datetime.now()).where(
                Account.account_number == form.account_number.data).execute()

        TimeDeposit.insert(account_number=form.account_number.data,
                           amount=form.amount.data,
                           interest=interest_ref[form.duration.data],
                           terminal_date=datetime.now() +
                           timedelta(days=form.duration.data * 30)).execute()

        Transaction.insert(account_number=form.account_number.data,
                           reference_number=form.account_number.data,
                           amount=form.amount.data,
                           type='TIME DEPOSIT').execute()
        flash('Time Deposit successful')
        return redirect(url_for('main.time_deposit'))
    return render_template('main/time_deposit.html', form=form)
示例#7
0
 def post(self, request, **kwargs):
     tag_id = request.POST.get("tag_id")
     amount = request.POST.get("amount")
     item_id = request.POST.get("item_id")
     hash = request.POST.get("hash")
     if None in [tag_id, amount, item_id, hash]:
         return HttpResponseBadRequest("The request was malformed.")
     for secret in Secret.objects.all():
         calc_string = str(tag_id) + str(amount) + str(item_id) + str(
             secret.value)
         calc_hash = hashlib.sha256(calc_string.encode("ascii")).hexdigest()
         print(calc_string)
         print(calc_hash.upper())
         print(hash)
         if calc_hash.upper() == hash.upper():
             tag = get_object_or_404(Tag, pk=tag_id)
             item = get_object_or_404(Item, pk=item_id)
             transaction = Transaction(owner=tag.attendee,
                                       item=item,
                                       amount=amount)
             transaction.save()
             return HttpResponse("Success")
     log(user=request.user,
         action="attempted_break_in",
         extra={
             "REMOTE_ADDR": request.META.get('REMOTE_ADDR'),
             "body": str(request.body),
         })
     return HttpResponseForbidden(
         "Unauthorized attempt, this has been logged")
示例#8
0
    def setUp(self):
        super(PaymentReleaseTestCase, self).setUp()
        self.method_data = {"is_internal": 1, 'name': 'Robokassa'}

        amount_cash = Decimal(30000.00)

        self.payment_method = PaymentMethod(name='ROBO')
        self.payment_method.save()

        self.addr_data = {
            'type': 'W',
            'name': '17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j',
            'address': '17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j',
        }

        self.addr = Address(**self.addr_data)
        self.addr.user = self.user
        self.addr.save()

        pref_data = {
            'user': self.user,
            'comment': 'Just testing',
            'payment_method': self.payment_method
        }

        pref = PaymentPreference(**pref_data)
        pref.save('internal')

        self.data = {
            'amount_cash': amount_cash,
            'amount_btc': Decimal(1.00),
            'currency': self.RUB,
            'user': self.user,
            'admin_comment': 'test Order',
            'unique_reference': '12345',
            'payment_preference': pref,
            'is_paid': True
        }

        self.order = Order(**self.data)
        self.order.save()

        self.pay_data = {
            'amount_cash': self.order.amount_cash,
            'currency': self.RUB,
            'user': self.user,
            'payment_preference': pref,
        }

        self.payment = Payment(**self.pay_data)
        self.payment.save()

        tx_id_ = '76aa6bdc27e0bb718806c93db66525436' \
                 'fa621766b52bad831942dee8b618678'

        self.transaction = Transaction(tx_id=tx_id_,
                                       order=self.order,
                                       address_to=self.addr)
        self.transaction.save()
示例#9
0
 def form_valid(self, form):
     form.instance.created_by = self.request.user
     form.instance.category = ExpenseCategory.get_transfer()
     form.instance.direction = Transaction.DIRECTION_OUT
     response = super(TransferAddView, self).form_valid(form)
     Transaction.create_acceptor(self.object,
                                 form.cleaned_data['account_dst'])
     return response
示例#10
0
 def _create_internal_tx_obj(self, currency, address_to, amount):
     tx = Transaction(
         currency=currency,
         amount=amount,
         address_to=address_to,
         type=Transaction.INTERNAL
     )
     tx.save()
     return tx
示例#11
0
def credit(request, account, amount):
    transaction = Transaction(
        account=account,
        transaction_type='C',
        transaction_amount=amount,
        transaction_fee=0.0,
    )
    account.credit(amount)
    transaction.save()
    # TODO: Send mail to admin and customer
    return messages.success(request, 'Credit successful')
示例#12
0
 def create_withdraw_txn(self, txn_type=Transaction.WITHDRAW):
     deposit_tx_id = self.generate_txn_id()
     txn_with1 = Transaction(amount=self.order.amount_quote,
                             tx_id_api=deposit_tx_id,
                             order=self.order,
                             address_to=self.order.deposit_address,
                             is_completed=True,
                             is_verified=True)
     if txn_type is not None:
         txn_with1.type = Transaction.WITHDRAW
     txn_with1.save()
     self.order.save()
示例#13
0
    def save(self):
        transaction_type = int(self.cleaned_data['type'])
        date = self.cleaned_data['date']
        description = self.cleaned_data['description']

        transaction = Transaction(date=date,
                                  description=description,
                                  type=transaction_type,
                                  wealth=self.wealth)
        transaction.save()

        account_from = Account.objects.get(
            wealth=self.wealth, id=self.cleaned_data['account_from'])

        amount = self.cleaned_data['amount']
        date = self.cleaned_data['date']
        tags = self.cleaned_data['tags']
        transaction_type = int(self.cleaned_data['type'])

        category = Category.objects.get(wealth=self.wealth,
                                        id=self.cleaned_data['category_id'])

        amount_account, amount_category = get_category_amounts(
            account_from, self.wealth, amount, transaction_type)

        split_account = AccountSplit(account=account_from,
                                     date=date,
                                     wealth=self.wealth,
                                     transaction=transaction,
                                     type=transaction_type,
                                     amount=amount_account)
        split_category = CategorySplit(wealth=self.wealth,
                                       date=date,
                                       category=category,
                                       type=transaction_type,
                                       transaction=transaction,
                                       amount=amount_category)

        split_account.save()
        split_category.save()

        if tags:
            for tag_id in tags:
                tag = Tag.objects.get(wealth=self.wealth, id=tag_id)
                tag_split = TagSplit(tag=tag,
                                     date=date,
                                     wealth=self.wealth,
                                     amount=amount_account,
                                     transaction=transaction,
                                     type=transaction_type)
                tag_split.save()
        return transaction
示例#14
0
def payment_release():
    # TODO: iterate over payments instead, will be much faster
    for o in Order.objects.filter(is_paid=True, is_released=False):
        user = o.user
        profile = user.profile
        if settings.DEBUG:
            print("Look order {} ".format(o.unique_reference))
        p = Payment.objects.filter(user=user,
                                   amount_cash=o.amount_cash,
                                   payment_preference__payment_method=o.
                                   payment_preference.payment_method,
                                   is_redeemed=False,
                                   currency=o.currency).first()
        p.is_complete = True
        p.save()

        if p:
            print(o.withdraw_address)
            tx_id = release_payment(o.withdraw_address, o.amount_btc)

            if tx_id is None:
                continue

            print('tx id: {}'.format(tx_id))
            o.is_released = True
            o.save()

            p.is_redeemed = True
            p.save()

            # send sms depending on notification settings in profile
            msg = _("Your order {}:  is released").format(o.unique_reference)
            print(msg)
            if profile.notify_by_phone:
                phone_to = str(o.user.username)
                sms_result = send_sms(msg, phone_to)
                if settings.DEBUG:
                    print(str(sms_result))

            # send email
            if profile.notify_by_email:
                email = send_email(user.email, 'title', msg)
                email.send()

            print(tx_id)
            adr = Address.objects.get(user=o.user, address=o.withdraw_address)

            t = Transaction(tx_id=tx_id, order=o, address_to=adr)
            t.save()

        elif settings.DEBUG:
            print('payment not found')
示例#15
0
  def save(self):
    transaction_type = int(self.cleaned_data['type'])
    date = self.cleaned_data['date']
    description = self.cleaned_data['description']
    amount = self.cleaned_data['amount']

    transaction = Transaction(
        transaction_type=transaction_type,
        date=date,
        description=description,
        amount=amount)
    transaction.save()
    return transaction
示例#16
0
文件: teller.py 项目: iecruz/qa-bank
def deposit():
    if request.method == 'POST':
        account = Account.get(Account.id == session['atm_auth'])

        Account.update(balance = Account.balance + request.form.get('amount')).where(Account.id == session['atm_auth']).execute()

        Transaction.insert(
            account_number = account.account_number,
            reference_number = account.account_number,
            amount = request.form.get('amount'),
            type = 'ATM DEPOSIT'
        ).execute()

        return redirect(url_for('teller.inquiry'))
    return render_template('teller/deposit.html')
示例#17
0
文件: main.py 项目: iecruz/bank-admin
def deposit():
    form = TransactionForm(request.form)
    if form.validate_on_submit():
        Account.update(
            balance=Account.balance + form.amount.data,
            updated_at=datetime.now()).where(
                Account.account_number == form.account_number.data).execute()

        Transaction.insert(account_number=form.account_number.data,
                           reference_number=form.account_number.data,
                           amount=form.amount.data,
                           type='DEPOSIT').execute()
        flash('Deposit successful')
        return redirect(url_for('main.deposit'))
    return render_template('main/deposit.html', form=form)
示例#18
0
def buy():
    form = BuyForm()
    if form.validate_on_submit():
        company = lookup(form.symbol.data)
        companyPrice = company["price"]
        companySymbol = company["symbol"]
        amount = float(form.shares.data)
        row = User.query.filter_by(username=current_user.username).first()
        balance = float(row.cash)
        if (float(companyPrice) * amount) > balance:
            abort(
                404,
                'You do not have sufficient funds for this purchase, please check your balance and try again.'
            )
        row.cash = (balance - (companyPrice * amount))
        transaction = Transaction(user_id=current_user.id,
                                  symbol=companySymbol,
                                  price=companyPrice,
                                  quantity=int(amount))
        db.session.add(transaction)
        db.session.commit()
        flash('Bought!', 'info')
        return redirect(url_for('finance.index'))
    return render_template('finance/buy.html',
                           title="Buy",
                           legend='Buy Stock',
                           form=form,
                           finance=finance)
示例#19
0
文件: main.py 项目: iecruz/qa-bank
def index():
    time_deposits = TimeDeposit.select().where(
        (TimeDeposit.terminal_date <= datetime.now())
        & (TimeDeposit.deleted == False)).execute()

    for time_deposit in time_deposits:
        Account.update(account=Account.balance +
                       (time_deposit.amount * time_deposit.interest) +
                       time_deposit.amount).where(
                           Account.account_number ==
                           time_deposit.account_number).execute()

        TimeDeposit.update(deleted=True).where(
            TimeDeposit.id == time_deposit.id).execute()

    accounts = Account.select().where(
        Account.user_id == session['user']['id']).execute()
    transactions = len(
        Transaction.select(Transaction).join(
            Account,
            on=(Transaction.account_number == Account.account_number)).join(
                User, on=(Account.user_id == User.id)).where(
                    User.id == session['user']['id']).dicts())

    return render_template('main/index.html',
                           accounts=accounts,
                           transactions=transactions)
示例#20
0
文件: main.py 项目: iecruz/qa-bank
def history():
    transactions = (Transaction.select(Transaction).join(
        Account,
        on=(Transaction.account_number == Account.account_number)).join(
            User, on=(Account.user_id == User.id)).where(
                User.id == session['user']['id']).execute())
    return render_template('main/history.html', transactions=transactions)
示例#21
0
文件: views.py 项目: bilalba/AasanAds
	def form_valid(self, form):
		# this ssaves the ad fields.
		self.object = form.save()
		# This saves the Location field. Copied from Ad Create view form_valid
		ad_locations = form.cleaned_data['location']
		old_locs = self.object.locations_set.all()

		# deleting old locations
		for old_loc in old_locs:
			old_loc.delete()
		# adding new locations
		for loc in ad_locations:
			loc_object = Locations(ad=self.object, location=loc) # create location counters.
			# these are for tracking hits 
			loc_object.save()
		#Saving a TopUp
		topup = coremodels.Topup(closed_by = self.request.user.get_SalesAgent(), ad = self.object,
						clicks = form.cleaned_data['clicks_promised'],
						cnic = form.cleaned_data['cnic'],
						money_paid = form.cleaned_data['money_negotiated'],
						phone_number = form.cleaned_data['phone_number']
						)
		topup.save()
		Transaction(status=0, topup=topup, phone_number=form.cleaned_data['phone_number'],
			cnic=form.cleaned_data['cnic']).save()
		# topuplocationcounters = []
		# for loc in ad_locations:
			# topuplocationcounters.append(TopupLocationCounter(topup=topup, location= loc))
		# TopupLocationCounter.objects.bulk_create(topuplocationcounters)
		self.object.status = 4
		self.object.save()
		return redirect('sales_agent')
示例#22
0
def withdraw(request, account, amount):
    transaction_rate = 0.01
    transaction_fee = transaction_rate * amount
    transaction = Transaction(
        account=account,
        transaction_type='D',
        transaction_amount=amount,
        transaction_fee=transaction_fee,
    )
    total_amount = amount + transaction_fee
    if account.account_balance >= total_amount:
        account.debit(total_amount)
        transaction.save()
        # TODO: Send mail to admin and customer
        return messages.success(request, 'Withdrawal successful')
    else:
        return messages.error(request, 'Insufficient balance')
示例#23
0
 def test_check_tx_scrypt(self, get_tx, **kwargs):
     tx = Transaction(tx_id='123')
     self.BTC.min_confirmations = kwargs['min_confs']
     self.BTC.save()
     api = self.factory.get_api_client(self.BTC.wallet)
     get_tx.return_value = {'confirmations': kwargs['tx_count']}
     res = api.check_tx(tx, self.BTC)
     self.assertEqual(res, kwargs['expected_return'], kwargs['case_name'])
示例#24
0
  def save(self):
    transaction_type = int(self.cleaned_data['type'])
    date = self.cleaned_data['date']
    description = self.cleaned_data['description']

    transaction = Transaction(
        date=date,
        description=description,
        type=transaction_type,
        wealth=self.wealth)
    transaction.save()

    account_from = Account.objects.get(
        wealth=self.wealth,
        id=self.cleaned_data['account_from'])

    amount = self.cleaned_data['amount']
    final = self.cleaned_data['final']
    rate = self.cleaned_data['rate']
    date = self.cleaned_data['date']
    transaction_type = int(self.cleaned_data['type'])

    account_to = Account.objects.get(
        wealth=self.wealth,
        id=self.cleaned_data['account_id'])
    amount_to = amount
    if is_conversion_needed(account_from, account_to):
      amount_to = get_converted_amount_transfer(amount, final, rate)
    split_from = AccountSplit(
        date=date,
        wealth=self.wealth,
        amount=amount * -1,
        transaction=transaction,
        type=transaction_type,
        account=account_from)
    split_to = AccountSplit(
        date=date,
        wealth=self.wealth,
        amount=amount_to,
        transaction=transaction,
        type=transaction_type,
        account=account_to)
    split_from.save()
    split_to.save()
    return transaction
示例#25
0
def _create_transaction(transaction_type, date, amount, description):
  transaction = Transaction()
  transaction.transaction_type = transaction_type
  transaction.date = date
  transaction.amount = Decimal(amount)
  transaction.description = description
  transaction.save()
示例#26
0
 def create_withdraw_txn(self, tx_id, amount, address_from='random_from',
                         address_to='random_to', currency=None,
                         tx_type=Transaction.WITHDRAW):
     address_obj_from = self.create_addresss(address_from)
     address_obj_to = self.create_addresss(address_to)
     tx = Transaction(
         amount=amount,
         tx_id=tx_id,
         address_from=address_obj_from,
         address_to=address_obj_to,
         currency=currency,
         is_completed=True,
         is_verified=True,
         type=tx_type
     )
     tx.type = Transaction.WITHDRAW
     tx.save()
     return tx
示例#27
0
    def handle_to_user_not_registered(self, from_user_id, to_user_id, amt):
        """Creates pending transaction and subtracts tip amount from from_user"""

        from_user = User.objects.get(user_id=from_user_id)
        if from_user.balance >= amt:
            trans = Transaction(
                from_user=User.objects.get(user_id=from_user_id),
                to_user_temp_id=to_user_id,
                amount=amt,
                pending=True,
                accepted=False,
            )
            trans.save()
            logger.info('Created pending transaction: %s', trans)
            from_user.balance -= amt
            from_user.save()
        else:
            raise BadBalance()
示例#28
0
    def _release(self, tx_data, api=None, currency=None, amount=None):
        if currency != self.withdraw_currency \
                or amount != self.withdraw_amount:
            raise ValidationError(
                'Wrong amount {} or currency {} for order {} release'.format(
                    amount, currency, self.unique_reference))
        old_withdraw_txs = self.transactions.exclude(
            type__in=[Transaction.DEPOSIT, Transaction.INTERNAL])
        tx_type = tx_data.get('type')
        if tx_type != Transaction.WITHDRAW:
            msg = 'Bad Transaction type'
            raise ValidationError(msg)
        if len(old_withdraw_txs) == 0:
            tx = Transaction(**tx_data)
            tx.save()

            payment_id = self.payment_id \
                if self.payment_id is not None \
                else None
            destination_tag = self.destination_tag if \
                self.destination_tag is not None \
                else None
            api.assert_tx_unique(currency,
                                 self.withdraw_address,
                                 amount,
                                 payment_id=payment_id,
                                 destination_tag=destination_tag)
            tx_id, success = api.release_coins(currency,
                                               self.withdraw_address,
                                               amount,
                                               payment_id=payment_id,
                                               destination_tag=destination_tag)
            setattr(tx, api.TX_ID_FIELD_NAME, tx_id)
            tx.save()
        else:
            msg = 'Order {} already has WITHDRAW or None type ' \
                  'transactions {}'.format(self, old_withdraw_txs)
            self.flag(val=msg)
            raise ValidationError(msg)

        if not tx_id:
            msg = 'Payment release returned None, order {}'.format(self)
            self.flag(val=msg)
            raise ValidationError(msg)

        if success:
            tx.is_verified = True
            tx.save()
        return tx
示例#29
0
 def test_do_not_refund_order_another_tx_exists(self, tx_type,
                                                release_coins):
     order = self._create_paid_order()
     another_tx = Transaction(address_to=order.withdraw_address,
                              order=order, amount=order.amount_base,
                              currency=order.pair.base, type=tx_type)
     another_tx.save()
     refund_address = Address.objects.filter(
         currency=order.pair.quote
     ).exclude(pk=order.deposit_address.pk).first()
     order.refund_address = refund_address
     order.save()
     res = order.refund()
     self.assertEqual(res['status'], 'ERROR', res)
     order.refresh_from_db()
     self.assertEqual(order.status, Order.PAID)
     txns = order.transactions.all()
     self.assertEqual(2, txns.count())
     release_coins.assert_not_called()
示例#30
0
def sell():
    # create a list of tuples containing each option of the symbol drop down menu
    # this is then passed into the sell form under the choices parameter
    tempRows = db.session.query(Transaction.symbol, func.sum(Transaction.quantity))\
                .group_by(Transaction.symbol)\
                .filter_by(user_id=current_user.id).all()
    tempRows = [i for i in tempRows if not (i[1] <= 0)]

    def choices():
        rows = [('', "Select Symbol")]
        for tempRow in tempRows:
            rows.append((tempRow[0], tempRow[0]))
        return rows

    choices = choices()
    form = SellForm()
    form.symbol.choices = choices

    if form.validate_on_submit():
        if not lookup(form.symbol.data):
            abort(
                404,
                'This symbol is not recognized, please try again with a different symbol.'
            )
        else:
            company = lookup(form.symbol.data)
            companyPrice = company["price"]
            companySymbol = company["symbol"]
            inputAmount = form.shares.data
            row = User.query.filter_by(username=current_user.username).first()
            balance = float(row.cash)
            for tempRow in tempRows:
                if (tempRow[0] == form.symbol.data):
                    ownedAmount = tempRow[1]
                    break
            if inputAmount > ownedAmount:
                abort(
                    404,
                    'You do not own this many shares, please try again with a lesser amount.'
                )
            else:
                row.cash = (balance + (companyPrice * inputAmount))
                transaction = Transaction(user_id=current_user.id,
                                          symbol=companySymbol,
                                          price=companyPrice,
                                          quantity=int(-inputAmount))
                db.session.add(transaction)
                db.session.commit()
                flash('Sold!', 'info')
                return redirect(url_for('finance.index'))
    return render_template('finance/sell.html',
                           title="Sell",
                           legend='Sell Stock',
                           form=form,
                           finance=finance)
示例#31
0
 def test_do_not_release_if_order_has_non_deposit_tx(self, txn_type,
                                                     eth_listen):
     eth_listen.return_value = True
     order = self._create_paid_order()
     txn_dep = order.transactions.get()
     another_tx = Transaction(type=txn_type, order=order,
                              address_to=order.withdraw_address)
     another_tx.save()
     txn_before = order.transactions.filter(
         type=Transaction.WITHDRAW
     )
     exchange_order_release_invoke.apply_async([txn_dep.pk])
     order.refresh_from_db()
     # Check things after first release
     self.assertEqual(order.status, Order.PRE_RELEASE)
     txn_after = order.transactions.filter(
         type=Transaction.WITHDRAW
     )
     self.assertEqual(txn_after.count() - txn_before.count(), 0, txn_type)
     self.assertTrue(order.flagged)
示例#32
0
    def test_can_set_as_paid_if_has_withdraw_address(self):
        # Creates an withdraw address fro this user
        address = Address(user=self.user,
                          type='W',
                          address='17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j')
        address.save()

        # Creates an Transaction for the Order, using the user Address
        transaction = Transaction(order=self.order,
                                  address_to=address,
                                  address_from=address)
        transaction.save()

        # Set Order as Paid
        response = self.client.post(self.url, {'paid': 'true'})
        expected = {"frozen": None, "paid": True, "status": "OK"}
        self.assertJSONEqual(
            json.dumps(expected),
            str(response.content, encoding='utf8'),
        )
示例#33
0
文件: teller.py 项目: iecruz/qa-bank
def transfer():
    form = TransactionForm(request.form)
    if form.validate_on_submit():
        account = Account.get(Account.id == session['atm_auth'])

        if form.account_number.data == account.account_number:
            flash('You cannot transfer funds to your own account')

        else:
            Account.update(balance = Account.balance - form.amount.data).where(Account.id == session['atm_auth']).execute()
            Account.update(balance = Account.balance + form.amount.data).where(Account.account_number == form.account_number.data).execute()

            Transaction.insert(
                account_number = account.account_number,
                reference_number = form.account_number.data,
                amount = request.form.get('amount'),
                type = 'ATM FUND TRANSFER'
            ).execute()

            return redirect(url_for('teller.inquiry'))
    return render_template('teller/transfer.html', form=form)
示例#34
0
    def transfer_funds(self, from_user, to_user, amt):
        """Transfer funds between users in the network

        :param from_user: User
        :param to_user: User
        :param amt: Decimal
        """
        from_user.balance -= amt
        from_user.save()
        # because some oddballs like to tip themselves
        to_user = User.objects.get(id=to_user.id)
        to_user.balance += amt
        to_user.save()
        trans = Transaction(from_user=from_user,
                            to_user=to_user,
                            amount=amt,
                            pending=False,
                            accepted=True)
        trans.save()
        logger.info('Moved coin: %s', trans)
        return trans
示例#35
0
  def save(self):
    transaction_type = int(self.cleaned_data['type'])
    date = self.cleaned_data['date']
    description = self.cleaned_data['description']

    transaction = Transaction(
        date=date,
        description=description,
        type=transaction_type,
        wealth=self.wealth)
    transaction.save()

    account_from = Account.objects.get(
        wealth=self.wealth,
        id=self.cleaned_data['account_from'])

    amount = self.cleaned_data['amount']
    date = self.cleaned_data['date']
    tags = self.cleaned_data['tags']
    transaction_type = int(self.cleaned_data['type'])

    category = Category.objects.get(
        wealth=self.wealth,
        id=self.cleaned_data['category_id'])

    amount_account, amount_category = get_category_amounts(
        account_from,
        self.wealth,
        amount,
        transaction_type)

    split_account = AccountSplit(
        account=account_from,
        date=date,
        wealth=self.wealth,
        transaction=transaction,
        type=transaction_type,
        amount=amount_account)
    split_category = CategorySplit(
        wealth=self.wealth,
        date=date,
        category=category,
        type=transaction_type,
        transaction=transaction,
        amount=amount_category)

    split_account.save()
    split_category.save()

    if tags:
      for tag_id in tags:
        tag = Tag.objects.get(
            wealth=self.wealth,
            id=tag_id)
        tag_split = TagSplit(
            tag=tag,
            date=date,
            wealth=self.wealth,
            amount=amount_account,
            transaction=transaction,
            type=transaction_type)
        tag_split.save()
    return transaction