def run_sim(d, scrip, a, amount, ledger): net_buys = 0 for i in a: f = d.get_first(i) s = d.stocks.get(f) qty = int(float(amount) / float(s.high)) net_buys += qty t0 = Transaction(scrip, BUY, s.date, s.high, qty) ledger.append(t0) a0 = d.get_last(a[-1]) s0 = d.stocks.get(a0) t1 = Transaction(scrip, SELL, s0.date, s0.high, net_buys) ledger.append(t1) # for i in ledger: # print( i.to_str(), i.tx_value()) investment = sum( [float(x.price) * x.qty for x in ledger if x.action == BUY]) sale = 0 profit = 0 roi = 0 if not investment == 0: sale = sum( [float(x.price) * x.qty for x in ledger if x.action == SELL]) profit = (sale - investment) roi = round((profit * 100) / investment, 2) #print( "Roi for {} months starting {} is {}".format( len(a) , a[0], round( roi,2))) scenario = Scenario(a[0], len(a), amount, profit, investment, ledger, roi) return scenario
def create_transactions(db, source_wallet, target_wallet, amount, host): source_transaction = Transaction(wallet_id=source_wallet.id, amount=(-amount), ip=host) db.add(source_transaction) target_transaction = Transaction(wallet_id=target_wallet.id, amount=amount, ip=host) db.add(target_transaction)
def setUp(self): """Define test variables and initialize app.""" self.app = create_app() self.client = self.app.test_client self.database_name = "lending_test" self.database_path = 'postgres://davidhunter@localhost:5432/lending_test' #"postgres://{}/{}".format('localhost:5432', self.database_name) setup_db(self.app) self.new_user1 = { 'name': 'Jedediah' } self.new_user2 = { 'name': 'Barbara' } self.new_group = { 'name': 'house', 'users': [1,2] } self.new_transaction = { 'item':'milk', 'price': 3, 'buyer_id': 1, 'group_id': 1 } user_1 = User(name="Jedidiah", total_owed=0, outstanding=json.dumps({})) user_2 = User(name="Barbara", total_owed=0, outstanding=json.dumps({})) user_1.insert() user_2.insert() group_1 = Group(name="house") group_1.insert() group_1.people.append(user_1) group_1.people.append(user_2) group_1.update() transaction_1 = Transaction(item="milk", price=3, buyer_id=1, group_id=1) transaction_2 = Transaction(item="milk", price=3, buyer_id=1, group_id=1) transaction_3 = Transaction(item="milk", price=3, buyer_id=1, group_id=1) transaction_1.insert() transaction_2.insert() transaction_3.insert() with self.app.app_context(): self.db = SQLAlchemy() self.db.init_app(self.app) self.db.create_all()
def main(): engine = create_engine("sqlite:///{}.sqlite".format(DB_NAME)) session_factory = sessionmaker(bind=engine) # create teh tables from the defined model(s) Base.metadata.create_all(engine) session = session_factory() # insert some FALSE test data session.add_all([ Transaction( description= "Purchase: 12345678 100 Main St TARGET T-0111 Atlanta GA Card: ****1111 11/22/2015", ), Transaction( description= "Purchase: LK111222 FRESH MKT-011 ATL ATLANTA GA Card: ****2222 11/22/2015", ), Transaction( description= "Purchase: 12345678 100 Main St TARGET T-0111 Atlanta GA Card: ****1111 11/25/2015", ), Transaction( description= "Purchase: 111 2222 SUR LA TABLE DIRECT 800-123-4567 WA Card: ****2222 11/25/2015", ), Transaction(description="Deposit SOMEWHERE CO-DIR DEP *****2222"), Transaction(description="Deposit SOMEWHERE ELSE CO-DIR DEP *****1111"), Transaction(description="Withdrawal VENMO-PAYMENT *****1111 (S)"), Transaction(description="Withdrawal Check # 1111 Trace: 123456789") ]) session.commit()
def login(): from random import randint from sbb import db from models import User from models import Transaction from models import TransactionType if request.method == 'GET': session['a'] = randint(1, 10) session['b'] = randint(1, 10) return render_template('home/login.html', a=session['a'], b=session['b']) form = LoginForm(request.form) if form.validate_on_submit(): captcha = form.captcha.data.strip() if captcha != '' and int(captcha) == session['a'] + session['b']: email = form.email.data password = form.password.data remember_me = False if 'remember_me' in request.form: remember_me = True user = User.query.filter_by(email=email).first() tr = TransactionType.query.filter_by(id=1).first() if user is None or not user.check_password(password): flash('Username or Password is invalid', 'error') if user: login_act = Transaction(date=datetime.now(), amount=None, status=0) login_act.account = user.account login_act.transactionType = tr db.session.add(login_act) db.session.commit() return redirect(url_for('home.login')) login_user(user, remember=remember_me) flash('Logged in successfully') login_act = Transaction(date=datetime.now(), amount=None, status=1) login_act.account = current_user.account login_act.transactionType = tr db.session.add(login_act) db.session.commit() return redirect( request.args.get('next') or url_for( 'userprofile.dashboard', _external=True, _scheme='https')) else: flash("Wrong captcha") flash_errors(form) session['a'] = randint(1, 10) session['b'] = randint(1, 10) return render_template('home/login.html', a=session['a'], b=session['b'])
def post(self): parsed_args = parser.parse_args() transaction = Transaction( transaction_type=parsed_args['transaction_type']) session.add(transaction) session.commit() return transaction, 201
def do_get_history(): print("正在为您抓取流水记录!") transaction_list = [] time.sleep(10) last = self.xpath( '//android.webkit.WebView/android.view.View[4]/android.view.View').all( ) trans_time = "" trans_type = "" amount = "" balance = "" postscript = "" summary = "" account = "" for el in last: if el.attrib['index'] == "1": print("amount:", el.attrib['content-desc']) amount = el.attrib['content-desc'].split("交易金额")[1] if el.attrib['index'] == "3": print("time:", el.attrib['content-desc']) trans_time = el.attrib['content-desc'] if el.attrib['index'] == "10": print("summary:", el.attrib['content-desc']) if el.attrib['content-desc'].strip() == "转账": trans_type = 0 else: trans_type = 1 if el.attrib['index'] == "12": print("account:", el.attrib['content-desc']) account = el.attrib['content-desc'] if el.attrib['index'] == "6": print("summary:", el.attrib['content-desc']) summary = el.attrib['content-desc'] if el.attrib['index'] == "27": print("postscript:", el.attrib['content-desc']) postscript = el.attrib['content-desc'] if el.attrib['index'] == "24": print("balance:", el.attrib['content-desc']) balance = el.attrib['content-desc'] transaction_list.append( Transaction(trans_time=trans_time, trans_type=trans_type, amount=amount, balance=balance, postscript=postscript, account=account, summary=summary)) print("------------------------------") trans_api(settings.bot.account.alias, "0", transaction_list) print("------------------------------") back_activity() back_activity() return transaction_list
def convert(session, event, account_from, account_to, amount): if account_from.currency == account_to.currency: return if account_from.user != account_to.user: raise PermissionDeniedException('Cannot convert currency externally.') rate = session.query(CurrencyRate).filter( CurrencyRate.currency_from_id == account_from.currency.id, CurrencyRate.currency_to_id == account_to.currency.id).first() if not rate: raise DBRecordNotFound( 'There\'s no currency convert rate needed for the operation.') converted_amount = amount * rate.value transaction = Transaction() transaction.value = converted_amount transaction.type = Transaction.TYPE_CONVERT transaction.event = event transaction.account_from = account_from transaction.account_to = account_to account_from.balance -= amount account_to.balance += converted_amount session.add(transaction) return converted_amount
def add_transaction(request, Session): # TODO: verify user has write access to book if request.form.get('amount') is None or len(request.form.get('amount')) < 1: return "Amount is required" if request.form.get('date') is None or len(request.form.get('date')) < 1: return "Date is required" if request.form.get('book_id') is None or len(request.form.get('book_id')) < 1: return "Book id is required" kws = {"amount": float(request.form['amount']), "date": request.form['date'], "book_id": request.form['book_id'], "comment": request.form.get('comment'), "category_id": request.form.get('category_id')} if request.form.get('image') is not None: path = str(image_name) + ".gif" image_name += 1 tmp_file = open(path, "w") img_data = base64.b64decode(request.form.get('image')) tmp_file.write(img_data) tmp_file.close() # Todo: put try/catch around this kws = {"image": image_name} try: # trans = Transaction(amount=float(request.form['amount']), # date=request.form['date'], # book_id=request.form['book_id'], # comment=request.form.get('comment'), # category_id=request.form.get('category_id')) trans = Transaction(kws) Session.add(trans) Session.commit() except Exception as ex: return "Error adding transaction: " + str(ex) return "1"
def upload(self, name, file, source): try: acc = Account.get(name=name) balance_to_add = 0 with open(file) as f: csv_f = xl.reader(f) next(csv_f) # Skip filename line next(csv_f) # Skip column headers for row in csv_f: cleaned = lambda s: float(s[1:len(s)-4]) date = datetime.datetime.strptime(row[0], '%d/%m/%Y').strftime('%Y/%m/%d') trans = Transaction(date=date, amount_in=cleaned(row[1]), fees=cleaned(row[2]), amount_out=cleaned(row[4]), source=source, account=acc) trans.save() balance_to_add += cleaned(row[4]) acc.balance += balance_to_add acc.last_updated = datetime.datetime.now() acc.save() print('Successfully uploaded', file, 'to account', name) print('Added', '$' + str(balance_to_add), 'to account', name) print('New balance for account', name, 'is', '$' + str(acc.balance)) except IOError as e: print('Error uploading', e)
def test_model_transaction(self): "Test transaction model" contact_type = ContactType(name='test') contact_type.save() contact = Contact(name='test', contact_type=contact_type) contact.save() currency = Currency(code="GBP", name="Pounds", symbol="L", is_default=True) currency.save() account = Account(name='test', owner=contact, balance_currency=currency) account.save() obj = Transaction(name='test', account=account, source=contact, target=contact, value=10, value_currency=currency) obj.save() self.assertEquals('test', obj.name) self.assertNotEquals(obj.id, None) obj.delete()
def post(self, id=None): ''' Endpoint for creating a new transaction Creates a new Transaction record and updates the associated User record's balance ''' parser = reqparse.RequestParser() parser.add_argument('netid', location='json', required=True, type=validate_netid) parser.add_argument('amount', location='json', required=True, type=int) parser.add_argument('description', location='json', default='') args = parser.parse_args() transaction = Transaction(netid=args.netid, amount=args.amount, description=args.description) user = get_user(args.netid) user.balance += args.amount db.session.add(user) db.session.add(transaction) db.session.commit() return jsonify(transaction.serialize())
def create_transaction(): ''' Creates a transaction for the user's shopping cart. Apparently, adding relations to transient transactions somehow automatically adds them to the current session. As we usually don't want to commit semi-complete transactions, DB modifications are prepent with session.rollback(). ''' ta = Transaction() lending = session_or_empty('lend') buying = session_or_empty('buy') ta.group = session_or_empty('group') if ta.group == []: ta.group = 'int' for id in lending: item = Item.query.get(id) ta.lend[id] = Lend(item, lending[id]) for id in buying: item = Item.query.get(id) ta.buy[id] = Buy(item, buying[id]) ta.date_start = session_or_empty('date_start') ta.date_end = session_or_empty('date_end') ta.name = session_or_empty('name') ta.email = session_or_empty('email') ta.tel = session_or_empty('tel') g.ta = ta
def save_reset_pass(): from lib.email2 import send_email from models import User from models import Transaction from models import TransactionType from sbb import application, db form = ResetPassordForm(request.form) if form.validate_on_submit(): user = User.query.filter_by(email=request.form['email']).first() if user: user.password = User.hash_password(form.password.data) db.session.add(user) tr = Transaction(datetime.now(), None, 1) tr.transactionTypeId = TransactionType.query.filter_by( id=6).first().id db.session.add(tr) db.session.commit() html = 'Thank you! You have successfully reset your password.' subject = "Reset password" send_email(request.form['email'], subject, html, application.config) flash('Thank you! You have successfully reset your password.') else: flash('No user found with specified email.', 'warning') return redirect(request.referrer) else: flash_errors(form) return redirect(request.referrer) return redirect('login')
def create(attributes_transaction: dict): try: new_transaction = Transaction(**attributes_transaction) new_transaction.save() return View.get_response(new_transaction) except BaseException: return None
def makeTransaction(node_send, node_rec, val): get_val = val transactions = copy.deepcopy(node_send.unSpentTransactions) inputs = [] for hash in transactions: tr = transactions[hash] for index in range(len(tr.outputs)): output = tr.outputs[index] if output is not None: if output.pub_key == node_send.pub_key.to_string(): signature = node_send.priv_key.sign(hash.encode('utf-8')) input = Input(hash, index, signature) inputs.append(input) get_val -= output.value if get_val < 0.0: break if get_val > 0.0: print("Not enough Coin to make Transaction...") return False outputs = [] main_output = Output(node_rec.pub_key.to_string(), val) outputs.append(main_output) if get_val < 0.0: outputs.append(Output(node_send.pub_key.to_string(), 0.0 - get_val)) new_transaction = Transaction(inputs, outputs) node_send.sendTransaction(new_transaction) return True
def simulate_startup(): conn = mysql.connect() cursor = conn.cursor() t = Transaction(cursor, conn) ec = EmployeeCard(cursor, conn) for dept, e_list in client.department_employees.items(): dept_bal = client.retrieve_balance( dept).gpa.available_balance * (random.randint(1, 19) / 100) employees = random.sample(e_list, 5) for e in employees: transfer = client.transfer( dept_bal, dept, e, dest_token_is_user=True) t.insert(dept, e, Transaction.current_time( transfer.created_time), dept_bal) card = client.client_sdk.cards.list_for_user(e)[0].token mid_identifer = random.choice(MIDS) employee_transaction = simulate( card, amount=dept_bal * (random.randint(1, 19) / 100), mid=mid_identifer) t.insert(card, mid_identifer, Transaction.current_time( employee_transaction.created_time), employee_transaction.amount, is_card=True) ec.insert(e, card) conn.close()
def buy(stocks_symbol=''): """Buy shares of stock""" # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # Assign the data (symbol, number of shares) from the form symbol = request.form.get("symbol").upper() # Ensure symbol was entered if not symbol: return apology("missing symbol") # Ensure number of shares was submitted elif not request.form.get("shares"): return apology("missing shares") shares = int(request.form.get("shares")) # Ensure number of shares are valid if shares < 1: return apology("value must be greater than or equal to 1", 400) # To be checked how to implement in javascript # Get the info. of the symbol and check if symbol is valid quote_ = lookup(symbol) if quote_ is None: return apology("invalid symbol", 400) # Query users table for the available cash using id rows = User.query.filter_by(id=session["user_id"]).first() # Check the available cash and the price of stocks cash = float(rows.cash) transaction_price = shares * quote_["price"] if cash - transaction_price < 0: return apology("can't afford", 400) # If cash is enough, deduct the price to the cash and update users table cash -= transaction_price rows.cash = cash db.session.commit() # Add the buy transaction to the database transaction = Transaction(stocks_symbol=symbol, shares=shares, price=quote_["price"], user_id=session["user_id"]) db.session.add(transaction) db.session.commit() flash(f"Bought {shares} shares of {symbol}!") # Redirect user to home page return redirect("/") # User reached route via GET (as by clicking a link or via redirect) else: return render_template("buy.html", stocks_symbol=stocks_symbol)
def send_block(height_or_hash): """ 获得指定高度的区块数据并发送到 kafka :param height_or_hash: :return: """ # 获取指定的区块,并加入缓存列表 block1 = w3.eth.getBlock(height_or_hash, True) if block1.number in block_cache: logger_err.error(f'获得重复区块高度 {block1.number}') block_cache[block1.number] = block1 return block_cache[block1.number] = block1 # 从缓存列表里获得待处理的区块,如果为 None,则代表缓存的数据量不够,不进行任何处理 block2 = block_cache.pop() if block2 is None: logger.info( f'获取到高度为 {block1.number} 的区块,加入缓存,当前缓存区块数 {len(block_cache)}') return else: logger.info( f'获取到高度为 {block1.number} 的区块,加入缓存,开始处理高度为 {block2.number} 的区块') Block(data=block2).save() for tx in block2.transactions: Transaction(data=tx).save()
def add_transaction(): transaction_name = request.form.get('transaction_name') if transaction_name == 'Transaction Name': return redirect('/new_transaction') fields = [ Field('field_0', 'name', 'string', False), Field('field_1', 'date', 'date', False), Field('field_2', 'cost', 'number', False) ] for k, v in request.form.items(): try: if int(k.split('_')[-1]) > 2 and k.split('_')[0] != 'type': if v == '': v = 'enter name' new_field = Field(k, v, request.form['type_{}'.format(k)], True) fields.append(new_field) except ValueError: pass payload = Transaction(transaction_name) for field in fields: payload.add_property(field.name, field.type) db.put('transaction_types', payload.to_json()) return redirect('/types')
def deposite(acc_id): form = DepositeForm() if request.method == 'POST': if form.validate_on_submit(): amt = form.amt.data account = Account.query.filter_by(ws_acc_id=acc_id).first() x = int(account.ws_acct_balance) account.ws_acct_balance = x + int(amt) db.session.commit() flash("Amount deposited successfully", "success") transaction = Transaction(ws_acc_id=account.ws_acc_id, ws_cust_id=account.ws_cust_id, ws_amt=amt, ws_acct_type=account.ws_acct_type, ws_src_typ=None, ws_tgt_typ=None, cr_or_db='Credit') transaction.ws_trxn_date = datetime.now() transaction.description = '' + str(amt) + ' credited in ' + str( account.ws_acc_id) + ' account' db.session.add(transaction) db.session.commit() return render_template("deposite.html", account=account, old_balance=x, get_accounts=True) return render_template("deposite.html", title='Deposite Amount', form=form, get_accounts=True)
def withdraw(acc_id): form = WithdrawForm() if request.method == 'POST': if form.validate_on_submit: amt = form.amt.data account = Account.query.filter_by(ws_acc_id=acc_id).first() x = int(account.ws_acct_balance) if (x < int(amt)): flash("Your Balance is not sufficient to withdraw !", "danger") else: account.ws_acct_balance = x - int(amt) db.session.commit() flash("Amount withdrawed successfully .", "success") transaction = Transaction(ws_acc_id=account.ws_acc_id, ws_cust_id=account.ws_cust_id, ws_amt=amt, ws_acct_type=account.ws_acct_type, ws_src_typ=None, ws_tgt_typ=None, cr_or_db='Debit') transaction.ws_trxn_date = datetime.now() transaction.description = '' + str( amt) + ' debited from ' + str( account.ws_acc_id) + ' account' db.session.add(transaction) db.session.commit() return render_template("withdraw.html", account=account, old_balance=x, get_accounts=True) return render_template("withdraw.html", title='Withdraw Amount', form=form)
def adhoc_charge(): if not current_user.isSuperUser: abort(401) amount = request.json['amount'] subject = request.json['subject'] message = request.json['message'] users = User.query.order_by(User.firstname.asc()).all() cost_per_player = float("{0:.2f}".format(float(amount) / float(len(users)))) """Add expense entry""" expense_entry = Expense(amount, cost_per_player, "Deduction_AdHoc", len(users)) db.session.add(expense_entry) db.session.commit() email_ids = [] for user in users: email_ids.append(user.email) user.balance = float("{0:.2f}".format(user.balance - cost_per_player)) transaction = Transaction(user.email, cost_per_player, user.balance, "Deduct_AdHoc") db.session.add(transaction) db.session.commit() SendGrid.send_email(email_ids, "*****@*****.**", subject, message) """Insert a log""" description = 'An AdHoc amount of $' + str(amount) + ' is charged for reason: ' + subject log = Log(current_user.email, description) db.session.add(log) db.session.commit() return "Success"
def first(): if request.method == 'POST': data = Transaction( currency=request.form['currency'], amount=request.form['amount'], description=request.form['description'], ) db.session.add(data) db.session.commit() if request.form["currency"] == "840": tip_data = tip(data) data = tip_data[0] data['sign'] = tip_data[1] return render_template( 'between.html', data=data, ) if request.form["currency"] == "978": text = post_invoice_API(data) return render_template("euro.html", data=data, text=text) else: return render_template("index.html")
def add(message, creditor, debtor, amount, currency=None): chat, _ = Chat.get_or_create(id=message.chat.id) creditor, _ = User.get_or_create(username=creditor.upper()) debtor, _ = User.get_or_create(username=debtor.upper()) amount = Decimal(amount) original_amount = amount currency = check_currency(currency, chat.currency) if currency != chat.currency: amount = cr.convert(currency, chat.currency, amount) transaction = Transaction( chat=chat, transaction_id=uuid4(), transaction_type=TransactionType.DEBT.value, date=datetime.now(), debtor=debtor, creditor=creditor, amount=amount, currency=chat.currency, original_amount=original_amount, original_currency=currency ) transaction.save() debt_graph = DebtGraph.load_graph(chat) debt_graph.add_debt(transaction) DebtGraph.save_graph(chat, debt_graph) return str(transaction)
def create(cls, **kwargs): obj = cls(**kwargs) with Transaction() as session: session.add(obj) session.commit() session.expunge(obj) return obj
def pay(user_id, discounts_response): discounts_response_json = discounts_response.json() if discounts_response.status_code != 200: discounts_response_json["Source of response"] = "Discounts microservice" return discounts_response_json, discounts_response.status_code headers = request.headers if 'Authorization' in headers: token = headers['Authorization'].split(' ')[1] decoded_token = decode_token(token) # user_id = decoded_token['user_details']['id'] amount = discounts_response.json() user = UserPayments.query.filter_by(id=user_id).first() if user is None: user = UserPayments(id=user_id, funds=0) db.session.add(user) # db.session.commit() # print ("Amount:", amount) transaction = Transaction(date=datetime.now(), amount=amount, user=user, completed=True) db.session.add(transaction) db.session.commit() return transaction_to_json(transaction), 200 else: return {'message': 'Pay was not successful'}, 400
def dept_to_emp(plan_id): conn = mysql.connect() cursor = conn.cursor() query = 'SELECT * FROM plan WHERE id = %s' cursor.execute(query, plan_id) records = cursor.fetchall() funding_amount = records[0][2] source_fund_FK = records[0][7] query = 'SELECT token FROM department_lookup WHERE id = %s' cursor.execute(query, source_fund_FK) source_token = cursor.fetchall()[0][0] query = 'SELECT * FROM employee_plan WHERE ep_plan_FK = %s' cursor.execute(query, plan_id) records = cursor.fetchall() t = Transaction(cursor, conn) for row in records: query = 'SELECT token FROM employee WHERE id = %s' cursor.execute(query, row[0]) dest_token = cursor.fetchall()[0][0] transfer = client.transfer(funding_amount, source_token, dest_token, dest_token_is_user=True) t.insert(source_token, dest_token, Transaction.current_time(transfer.created_time), funding_amount) conn.commit() conn.close() complete_employee_plan(plan_id) simulate_employee_plan(plan_id)
def pay(line): """Logic new payment""" msg = 0 if len(line) > 4: actor = User.get_by_name(line[1]) target = User.get_by_name(line[2]) amount = line[3] note = ' '.join(line[4:]) actor_card = CreditCard.get_by_user(actor) if actor_card: # actor has a card if actor and target: #both existed if actor != target: #not paying self amount = clean_amount(amount) if amount: #valid amount t = Transaction(actor, target, amount, note) t.save() else: msg = ERROR_MSG['INVLIAD_AMOUNT'] else: msg = ERROR_MSG['PAY_SELF'] else: msg = ERROR_MSG['U_NOT_EXISTED'] else: msg = ERROR_MSG['U_HAS_NO_CARD'] else: msg = ERROR_MSG['INVALID_ARS'] return msg
def transaction_create(payload): body = request.get_json() new_drink_id = body.get('drink_id') new_quantity = body.get('quantity') new_created_at = body.get('created_at') # check input if new_drink_id is None or new_quantity is None or new_created_at is None: abort(400) drink = Drink.query.get(new_drink_id) if drink is None or drink.quantity < new_quantity: abort(400) t = datetime.datetime.strptime(new_created_at, "%Y-%m-%d") trans = Transaction(new_drink_id, new_quantity, t) trans.insert() drink.quantity -= new_quantity drink.update() return jsonify({ 'success': True, 'transaction': trans.format(), 'drink': drink.name })