def aborroweditem(request): if request.method == 'POST': # If the form has been submitted... row = Transactions(item = request.POST['borrowedItem'], user_id = 100, date_init = request.POST['borrowedOn'], date_due = request.POST['borrowedDueOn'], lent_borrowed_flag = False, quantity = 100, status = True, person = request.POST['borrowedFrom']) row.save() return HttpResponseRedirect('alternative')
def request(user): user_check, exist_acc = existence_check(user, "sender") amount = float(input("Enter the amount to be requested:")) comment = input("Any comments? (Press enter if there are none") Transactions.create(sender_acc=exist_acc, receiver_acc=user.acc_num, amount=amount, done=0, comment=comment)
def borroweditem(request): if request.method == 'POST': # If the form has been submitted... row = Transactions(item = request.POST['borroweditem'], user_id = 100, date_init = request.POST['borroweddategiven'], date_due = request.POST['borroweddatereturn'], lent_borrowed_flag = False, quantity = request.POST['borrowedquantity'], status = False, person = request.POST['borrowedperson']) #UserLents(item = request.POST['lentitem'], user_id = 100, date_lent = request.POST['lentdategiven']) row.save() history = Transactions.objects.all() return render_to_response('leboo/index.html', {'history' : history}, context_instance=RequestContext(request))#, {'lentFields' : lentFields})
def transactionsNewPost(): # POST request if request.method == 'POST': body = request.get_json() missing_item = verify_json(body, 'purchases_id', 'products_id', 'quantity') if missing_item: raise APIException('You need to specify the ' + missing_item, status_code=400) transactions = Transactions(purchases_id=body['purchases_id'], products_id=body['products_id'], sales_id=body['sales_id'], quantity=body['quantity'], warehouses_id=body['warehouses_id']) products = Products.query.get(body['products_id']) products.quantity = int(products.quantity) + body['quantity'] db.session.add(transactions) db.session.commit() all_transactions = Transactions.query.filter().order_by( Transactions.id) all_transactions = list(map(lambda e: e.serialize(), all_transactions)) return jsonify(all_transactions), 200 # GET request if request.method == 'GET': all_transactions = Transactions.query.all() all_transactions = list(map(lambda e: e.serialize(), all_transactions)) return jsonify(all_transactions), 200 return "Invalid Method", 404
def onExit(): id = request.args.get('id') fee_input = request.args.get('price') # TODO: idから駐車時刻取得 (ファイル読み込み) amount = fee_input # UI側から渡された料金で上書き currency = "JPY" product_name = "駐車料金" (order_id, response) = pay.request_payments(product_name=product_name, amount=amount, currency=currency) print(response["returnCode"]) print(response["returnMessage"]) transaction_id = response["info"]["transactionId"] print(order_id, transaction_id, product_name, amount, currency) obj = Transactions(transaction_id=transaction_id, order_id=order_id, product_name=product_name, amount=amount, currency=currency) db.session.add(obj) db.session.commit() db.session.close() redirect_url = response["info"]["paymentUrl"]["web"] return redirect(redirect_url)
def exitPosition(exitIndex): #print(current_user.id) #user_id #print(current_user.stocks[exitIndex-1].id) #ticker_id """Deletes position from Active Positions""" user = User.query.filter_by(id=current_user.id).first() exitPosition = current_user.stocks[exitIndex-1] print() print() print("EXIT INDEX: ", exitIndex) print() print() current_user.stocks.pop(exitIndex-1) db.session.commit() """Need to add to transactions table""" t = datetime.now() today = str(t.month) + "/" + str(t.day) + "/" + str(t.year) exitPrice = float(get_info(exitPosition.ticker)['price']) if (exitPosition.short): exitReturn = exitPosition.startingPrice - exitPrice else: exitReturn = exitPrice - exitPosition.startingPrice transaction = Transactions(id = db.session.query(Transactions).count() + 100, user_id=current_user.id, ticker=str(exitPosition.ticker), date=today, end_price = exitPrice, returns = exitReturn) db.session.add(transaction) db.session.commit() return redirect(url_for('dashboard'))
def createTransaction(self, address=None): session = self.dbSession() maxId = session.query(func.max(Transactions.id)).one()[0] maxId = 0 if maxId is None else int(maxId)+1 ids = session.query(Addresses.id).all() ids = [int(x[0]) for x in ids] if address is None: receiver = self.getRandomAddress(session, ids) sender = self.getRandomAddress(session, ids) else: if random.randint(0, 1) == 0: receiver = address sender = self.getRandomAddress(session, ids) else: receiver = self.getRandomAddress(session, ids) sender = address transaction = Transactions( id=maxId, time=datetime.datetime.now(), receiver=receiver, sender=sender, money='{0:.2f}'.format(random.uniform(0.01, 10000)) ) session.add(transaction) session.commit() session.close()
def import_json(): """ This code read the json and create transactions on database """ with open('transactions.json') as json_file: data = json.load(json_file) for t in data: Trans, created = Transactions.get_or_create(desc = t['description'],amount = t['amount'], date = t['date'], defaults={'pub': datetime.now()})
def comp_request(user): flag = 0 requests = Transactions.select().where( (Transactions.sender_acc == user.acc_num) & (Transactions.done == 0)) if not requests.exists(): print("No pending requests") dummy = input("Press any key") else: while True: os.system("clear") table = PrettyTable( ['Id', 'Request by Acc No', 'Amount', 'Comments']) for each_request in requests: table.add_row([ each_request.id, each_request.receiver_acc, each_request.amount, str(each_request.comment)[:25] ]) print(table) if flag == 1: print("Inavlid entry!") flag = 0 if flag == 2: print("Transaction amount exceeds available balance!") choice_id = input("Choose by ID: ") choice = Transactions.select().where(Transactions.id == choice_id) if not choice.exists(): flag = 1 else: choice = choice.get() if choice.amount > user.balance: flag = 2 continue withdraw(user, f"Tsfr to {choice.receiver_acc}", trans_type=1, withdraw_am=choice.amount) receiver = Customer.get( Customer.acc_num == choice.receiver_acc) deposit(receiver, f"Tsfr by {user.acc_num}", trans_type=1, deposit_am=choice.amount) choice.done = 1 choice.save() break
def fetch_bill(): ''' Function for fetching bill of particular customer ''' expected = { "mobileNumber": "" } body = request.get_json() verify_request_body(body, expected) # Get data from db cust = None try: cust = Customers.query.filter_by(mobileno=body["mobileNumber"]).first() except Exception as e: print(e) raise SetuError(ErrorCodes.Customer_not_found) if not cust: raise SetuError(ErrorCodes.Customer_not_found) # Generate refID # Not a scalable/secure way to generate refID, only for demo refID = "" if cust.amount > 0: refID = 'r' + secrets.token_hex(16) # Store refID tr = Transactions(refID) tr.custID = cust.custID try: db.session.add(tr) db.session.commit() except Exception as e: print(e) # Keep trying to insert in Transactions table # Jsonify and send with proper code in case of error r = { "status": "SUCCESS", "data": { "customerName": cust.name, "dueAmount": str(cust.amount), "dueDate": cust.duedate, "refID": refID } } return jsonify(r)
def update_stock(): form = StockUpdate() if Stock_list.query.all() is None: item_choices = [] else: item_choices = Stock_list.query.order_by(Stock_list.item).all() each_item=[] for choice in item_choices: each_item.append(choice.item) form.item_name.choices=each_item if request.method =='POST': if form.validate_on_submit(): item_actioned = request.form['item_name'] item_quantity = int(request.form['item_quantity']) print(type(item_quantity)) action = request.form['actions'] item_to_add = Transactions(action=action, number_actioned=item_quantity, item=item_actioned) db.session.add(item_to_add) db.session.commit() entry_to_change = Stock_list.query.filter_by(item=item_actioned).first() if action == 'New stock to kitchen': entry_to_change.kitchen_stock += item_quantity entry_to_change.to_buy = 0 elif action == 'New stock to garage': entry_to_change.garage_stock += item_quantity entry_to_change.to_buy = 0 elif action == 'Move from kitchen to garage': entry_to_change.kitchen_stock -= item_quantity entry_to_change.garage_stock += item_quantity elif action == 'Move from garage to kitchen': entry_to_change.kitchen_stock += item_quantity entry_to_change.garage_stock -= item_quantity elif action =='Use kitchen stock': entry_to_change.kitchen_stock -= item_quantity else: entry_to_change.garage_stock -= item_quantity if entry_to_change.kitchen_stock < 0 or entry_to_change.garage_stock < 0: flash(f"You appear to have used or moved more {item_actioned} than were recorded as being at that location. \n Please check and re-enter") else: db.session.commit() flash (f"Stock level of {item_actioned} successfully updated. \n There are {entry_to_change.kitchen_stock} {item_actioned} left in the kitchen \n and {entry_to_change.garage_stock} left in the garage") else: flash('Invalid Entry') return render_template("update_stock.html", form=form)
def addstock(name, symbol, price): wb = load_workbook(filename='~/Downloads/' + name) ws = wb.active index = 1 while ws['A' + str(index)].value: choice = str(ws['B' + str(index)].value) print("Looking at " + str(ws['A'+str(index)].value) + ".") if choice == 'Yes - long': if Tickers.query.filter_by(short = False, ticker = symbol).count() > 0: stock = Tickers.query.filter_by(short = False, ticker = symbol).first() else: stock = Tickers(id = db.session.query(Tickers).count() + 1, ticker=symbol, startingPrice=price, short=False) # refreshdb(symbol) elif choice == 'No - short': if Tickers.query.filter_by(short = True, ticker = symbol).count() > 0: stock = Tickers.query.filter_by(short = True, ticker = symbol).first() else: stock = Tickers(id = db.session.query(Tickers).count() + 1, ticker=symbol, startingPrice=price, short=True) # refreshdb(symbol) elif choice == 'No - no position': if User.query.filter(func.lower(User.email) == func.lower(str(ws['A'+str(index)].value))).first() != None: student = User.query.filter(func.lower(User.email) == func.lower(str(ws['A'+str(index)].value))).first() if Transactions.query.filter_by(user_id = student.id, ticker = symbol).first() == None: t = datetime.now() today = str(t.month) + "/" + str(t.day) + "/" + str(t.year) transaction = Transactions(id = db.session.query(Transactions).count() + 1, user_id=student.id, ticker=symbol, date=today, end_price = float(get_price(symbol)), returns = 0) db.session.add(transaction) db.session.commit() if choice == 'Yes - long' or choice == 'No - short': if User.query.filter(func.lower(User.email) == func.lower(str(ws['A'+str(index)].value))).first() != None: student = User.query.filter(func.lower(User.email) == func.lower(str(ws['A'+str(index)].value))).first() add_stock(student, stock) else: member = Role(id = db.session.query(Role).count() + 1, name="Member", description="Just a general user to start off with") password = passwords.generate() db.session.add(User(id = db.session.query(User).count() + 1, firstName="", lastName="",email=str(ws['A'+str(index)].value), password=password, roles=[member])) db.session.commit() msg = "Hello,\n\nThank you for being an active participant at USIT's general meetings and voting in the Voting Challenge! Since you do not already have an account, we have created an account for you! We highly recommend that you visit vote.texasusit.org/reset to change your password to something more familiar. Below, we have inserted your new temporary password.\n\nEmail: {}\nPassword: {}\n\nThank you,\nUSIT Team".format(str(ws['A'+str(index)].value), password) server.sendmail('*****@*****.**', str(ws['A'+str(index)].value).lower(), msg) student = User.query.filter(func.lower(User.email) == func.lower(str(ws['A'+str(index)].value))).first() add_stock(student, stock) index += 1 refreshdb()
def post(self): body = request.get_json(silent=True) # "Upsert" asset if name is available asset = db.session.query(Assets)\ .filter(Assets._symbol == body['ticket'])\ .one_or_none() if asset is None: name = body['ticket'] if body['asset_name'] == "" else body['asset_name'] asset = Assets(body['ticket'], name) db.session.add(asset) elif body['asset_name'] != asset.name and body['asset_name'] != "": asset.name = body['asset_name'] db.session.add(asset) transaction = Transactions(when=body['transaction_date'].replace(" ", ""), quotas=body['quantity'], price=body['price'], transaction_type=body['transaction_type'], assets_id=None) transaction.asset = asset db.session.add(transaction) try: db.session.commit() except SQLAlchemyError: db.session.rollback() raise response = { "assetName": transaction.asset.name, "assetSymbol": transaction.asset.symbol, "price": transaction.price, "quotas": transaction.quotas, "transactionType": transaction.transaction_type, "transaction_id": transaction.transaction_id } return response, 201
def addTransaction(sender_id, receiver_id, amount): newTransaction = Transactions(sender_id=sender_id, receiver_id=receiver_id, amount=amount) try: db.session.add(newTransaction) db.session.commit() return 1 except IntegrityError as e: print(e.__dict__) if isinstance(e.orig, UniqueViolation): return "Transaction associated with that amount and time already exists" return "Could not process transaction"
def get_transactions(): try: transaction = UserTransaction.query.filter_by( user_id=session[CURR_USER_KEY]).join( Transactions, UserTransaction.transaction).order_by( Transactions.date.desc()).first() except: transaction = None # If no current transactions, import all if not transaction: start_date = '{:%Y-%m-%d}'.format(datetime.datetime.now() + datetime.timedelta(-180)) end_date = '{:%Y-%m-%d}'.format(datetime.datetime.now() + datetime.timedelta(-15)) # Else, import only new transactions else: most_recent = transaction.transaction.date end_day = int(most_recent[-1]) start_date = f'{most_recent[:-1]}{end_day+1}' end_date = '{:%Y-%m-%d}'.format(datetime.datetime.now()) try: transactions_response = client.Transactions.get( access_token, start_date, end_date) transactions = transactions_response['transactions'] for tran in transactions: t = Transactions(transaction_id=tran['transaction_id'], name=tran['name'], amount=tran['amount'], date=tran['date']) db.session.add(t) db.session.commit() u_t = UserTransaction(user_id=session['user-id'], transaction_id=tran['transaction_id']) db.session.add(u_t) db.session.commit() except plaid.errors.PlaidError as e: return jsonify(format_error(e)) # pretty_print_response(transactions_response) return jsonify(transactions_response)
def add_coins(user_id): req = request.get_json() utils.check_params(req, 'coins') db.session.add( Transactions(user_id=user_id, coins=req['coins'], dollars=req.get('dollars', 0))) db.session.commit() user = Profiles.query.get(user_id) return jsonify({'total_coins': user.get_coins()})
def getTransactionsByOrg(receiver_id): result = Transactions.query.filter_by(receiver_id=receiver_id) if result == None: return "No transactions associated with this charity" transformedTrans = [] for transaction in result: transformedTran = Transactions( sender_id=transaction.sender_id, receiver_id=transaction.receiver_id, amount=transaction.amount, time=transaction.time, ).__repr__() transformedTrans.append(transformedTran) return transformedTrans
def initialize_transactions_database(): # with app.app_context(): # db.create_all() try: db.create_all() transaction1 = Transactions(username='******', date='1/31/2021', purpose='deposit', amount=10.00, savingPercent=0.0) transaction2 = Transactions(username='******', date='2/10/2021', purpose='deposit', amount=10.00, savingPercent=0.0) if not bool(Transactions.query.filter_by(username='******').first()): db.session.add(transaction1) db.session.add(transaction2) #print(Transactions.query.filter_by(username='******').all()) db.session.commit() except exc.IntegrityError as e: errorInfo = e.orig.args print(errorInfo)
def post(self): """Send money request""" data = request.get_json() api_key = data.get('api_key') amount = abs(data.get('amount')) recipient_api_key = data.get('recipient') logger.debug('Send money request. ' 'sender: {}, amount: {}, recipient: {}, ip: {}'.format( api_key, amount, recipient_api_key, request.remote_addr)) sender = self.db_session.query(Wallets).filter_by( api_key=api_key).with_for_update().one() if sender.balance < amount: logger.debug('Sender balance exceed: {} {} {}'.format( api_key, sender.balance, amount)) return {'status': 'error', 'message': 'Not enough money'}, 200 try: recipient = self.db_session.query(Wallets).filter_by( api_key=recipient_api_key).with_for_update().one() except NoResultFound: logger.debug('Recipient not found: {}'.format(recipient_api_key)) return {'status': 'error', 'message': 'Recipient Not Found'}, 200 if recipient.limit < recipient.balance + amount: logger.debug('Recipient lemit exceed: {} {} {}'.format( recipient_api_key, recipient.limit, recipient.balance + amount)) return { 'status': 'error', 'message': 'Recipient Limit Exceed' }, 200 sender.balance = sender.balance - amount recipient.balance = recipient.balance + amount transaction = Transactions(sender=sender.id, recipient=recipient.id, amount=amount) self.db_session.add(transaction) self.db_session.commit() logger.debug('Transaction is created: ' 'trid={}, sender={}, recipient={}, amount={}'.format( transaction.id, sender.id, recipient.id, amount)) return {'status': 'success'}, 200
def test_show_transaction(): url = "http://127.0.0.1:5000/user/1/show_transaction" user = Users(email="*****@*****.**", password=hashlib.md5("123456".encode()).hexdigest(), passport="HUI", adress="Lviv", money_amount=500000, telephone_number="0930430540", super_user=False) user.id = 1 session.add(user) session.commit() bank = Banks(per_cent=20, all_money=5000) bank.id = 1 session.add(bank) session.commit() credit = Credits( start_date=datetime.datetime(2020, 0o1, 0o3), end_date=datetime.datetime(2020, 0o1, 0o3), start_sum=50000, current_sum=100000, user_id=user.id, bank_id=bank.id) credit.id = 1 session.add(credit) session.commit() trans = Transactions( id=1, date=datetime.datetime(2020, 0o1, 0o3), sum=1212, credit_id=1) session.add(trans) session.commit() resp = requests.get(url, auth=HTTPBasicAuth('*****@*****.**', '123456')) assert resp.status_code == 200 assert resp.json()[0]["sum"] == 1212 session.query(Transactions).delete() session.query(Credits).delete() session.query(Banks).delete() session.query(Users).delete() session.commit()
def add_transaction(bankId, creditId): credit = session.query(Credits).filter_by(id=creditId).first() bank = session.query(Banks).filter_by(id=bankId).first() if credit is None: return jsonify({"msg": "Not Found"}), 404 if bank is None: return jsonify({"msg": "Not Found"}), 404 date = request.json.get('date', None) sum = request.json.get('sum', None) credit_id = credit.id new_transaction = Transactions(date=date, sum=sum, credit_id=credit_id) bank.all_money += sum credit.current_sum -= sum session.add(new_transaction) session.commit() schemas = TransactionSchema() return jsonify(schemas.dump(new_transaction)), 200
def pay_reserve(): product_name = "チョコレート" amount = 1 currency = "JPY" (order_id, response) = pay.request_payments(product_name=product_name, amount=amount, currency=currency) print(response["returnCode"]) print(response["returnMessage"]) transaction_id = response["info"]["transactionId"] print(order_id, transaction_id, product_name, amount, currency) obj = Transactions(transaction_id=transaction_id, order_id=order_id, product_name=product_name, amount=amount, currency=currency) db.session.add(obj) db.session.commit() db.session.close() redirect_url = response["info"]["paymentUrl"]["web"] return redirect(redirect_url)
def register_profile(user_id): prof = Profiles.query.get(user_id) if prof is not None: raise APIException( 'A profile already exists with "id": ' + user_id, 400) req = request.get_json() utils.check_params(req, 'first_name', 'last_name', 'device_token') prof_data = { 'first_name': req['first_name'], 'last_name': req['last_name'], 'nickname': req.get('nickname'), 'hendon_url': req.get('hendon_url') } # Create user at Poker Society if there is none, get back pokersociety_id user = Users.query.get(user_id) resp = requests.post( os.environ['POKERSOCIETY_HOST'] + '/swapprofit/user', json={ 'api_token': utils.sha256(os.environ['POKERSOCIETY_API_TOKEN']), 'email': user.email, 'password': user.password, **prof_data }) if not resp.ok: raise APIException('Error creating user in Poker Society', 500) data = resp.json() db.session.add( Profiles(id=user_id, pokersociety_id=data['pokersociety_id'], **prof_data)) db.session.add(Devices(user_id=user_id, token=req['device_token'])) db.session.add(Transactions(user_id=user_id, coins=5)) db.session.commit() return jsonify({'message': 'ok'}), 200
def modifyDeposits(): if request.method == "POST": depositAmount = float(request.form.get('amount')) transactionDate = request.form.get('date') percentToSavings = float(request.form.get('savingPercent')) newTransaction = Transactions(username=current_user.username, date=transactionDate, purpose='deposit', amount=depositAmount, savingPercent=percentToSavings) temp = float(percentToSavings / 100) temp2 = depositAmount - (depositAmount * temp) current_user.checkingBalance = current_user.checkingBalance + temp2 current_user.savingBalance = current_user.savingBalance + depositAmount * temp db.session.add(newTransaction) db.session.commit() return render_template('deposits.html', statusMessage='Deposit Successful') else: return render_template('deposits.html')
def modifyExpenses(): if request.method == "POST": amountToDeduct = float(request.form.get('amount')) date = request.form.get('date') category = request.form.get('categories') newTransaction = Transactions(username=current_user.username, date=date, purpose='withdrawal', amount=amountToDeduct, category=category) currentUser = current_user currentUser.checkingBalance = currentUser.checkingBalance - amountToDeduct db.session.add(newTransaction) db.session.commit() return render_template('expenses.html', statusMessage='Expense Recorded') else: return render_template('expenses.html')
def register_profile(user_id): prof = Profiles.query.get(user_id) if prof is not None: raise APIException( 'A profile already exists with "id": ' + user_id, 400) req = request.get_json() utils.check_params(req, 'first_name', 'last_name', 'device_token') db.session.add( Profiles(id=user_id, first_name=req['first_name'], last_name=req['last_name'], nickname=req.get('nickname'), hendon_url=req.get('hendon_url'))) db.session.add(Devices(user_id=user_id, token=req['device_token'])) db.session.add(Transactions(user_id=user_id, coins=5)) db.session.commit() return jsonify({'message': 'ok'}), 200
def dashboard(): transForm = transactionForm() bar = ghaint_chart() line = baseGraph() line2 = baseGraph2() line3 = savingGraph() line4 = savingGraph2() TotalBal = totalBal() LeftBal = leftBal() if transForm.validate_on_submit(): print("In form") data = Transactions( cashFlow=transForm.flow.data, amount=transForm.amount.data, description=transForm.description.data, cat=transForm.category.data, date=transForm.date.data, userId=current_user.id, ) db.session.add(data) db.session.commit() flash("Transaction added successfully!") print("data send") return redirect(url_for("dashboard")) # elif not transForm.validate_on_submit(): # flash("Some error occured! Make sure you have filled all feilds correctly") return render_template( "dashboard.html", transForm=transForm, plot=bar, plot2=line, plot3=line2, plot4=line3, plot5=line4, totalBal=TotalBal, leftBal=LeftBal, )
def transaction(user): flag = 0 success_msg = '' while True: os.system("clear") if success_msg != '': print(success_msg) success_msg = '' num_str = '' transout = Transactions.select().where( (Transactions.sender_acc == user.acc_num) & (Transactions.done == 0)) request_count = transout.count() if request_count > 0: num_str = f"({request_count})" if flag == 1: print("Invalid input !") flag = 0 print("Transactions Menu") print("1.Transfer") print("2.Request transfer") print(f"3.Requests{num_str}") print("4.Refresh") print("5.Back to main menu") choice = input(">>>") if choice == "1": transfer(user) success_msg = "Transfer successful!" elif choice == "2": request(user) success_msg = "Request sent!" elif choice == "3": comp_request(user) success_msg = "Request completed!" elif choice == "4": continue elif choice == "5": break else: flag = 1
def look_similars(): """ looks all transactions and group by similar descriptions using diff :return: returns groups of similarity in a data list """ query = Transactions.select() groups = [] for Trans in query: #print("grupos", groups) ratio = 0 for g in groups: for tr in g: print(tr.desc) if SequenceMatcher(None, Trans.desc, tr.desc).ratio() >= 0.6: ratio =+ 1 g.append(Trans) break if ratio <= 0: #print("Creating a new group" , Trans.desc) groups.append([Trans]) return groups
def add_income(): if request.method == 'GET': return redirect(url_for('dashboard')) else: # Query database for current user balance balance = db.session.query(Users).filter_by( username=session["username"]).first().balance # get values from income form incAmount = float(request.form.get('inc_amount')) incTitle = request.form.get('inc_title') incDate = request.form.get('inc_date') # calculate balance # total_balance = round(float(balance) + float(incAmount), 2) total_balance = float( "{:.2f}".format(float(balance) + float(incAmount))) # update balance in USERS table db.session.query(Users).filter_by(username=session["username"]).update( {Users.balance: total_balance}, synchronize_session=False) db.session.commit() # insert inc into TRANSACTION table income = Transactions(username=session["username"], title=incTitle, inc_exp='inc', category='income', amount=incAmount, date=incDate) db.session.add(income) db.session.commit() flash("Income added") return redirect(url_for('dashboard.dashboard'))
def budget(budget_id): b = Budgets.query.get(budget_id) if b.user_id != current_user.id: abort(403) transact = Transactions.query.filter_by(budget_id=budget_id)[-1] form = BalanceForm() form.description.query = Descriptions.query.filter_by(budget_id=budget_id) if form.validate_on_submit(): if form.income.data == 0 and form.expense.data == 0: flash('Insert, at least, income or expense') return redirect(url_for('budget', budget_id=budget_id)) if form.description.data == None: flash('Choose description') return redirect(url_for('budget', budget_id=budget_id)) tr = transact.balance - form.expense.data tr = tr + form.income.data transaction = Transactions( budget_id=budget_id, income=form.income.data, expense=form.expense.data, user_id=current_user.id, balance=tr, description=(None if form.description.data == None else form.description.data.name)) db.session.add(transaction) db.session.commit() return redirect(url_for('budget', budget_id=budget_id)) return render_template('budget.html', title='enter data', budget=b, bal=transact, form=form)
def addstock(name, symbol, price): wb = load_workbook(filename=name) ws = wb.active index = 1 while ws['A' + str(index)].value: choice = str(ws['B' + str(index)].value) if choice == 'Long': if Tickers.query.filter_by(short = False, ticker = symbol).count() > 0: stock = Tickers.query.filter_by(short = False, ticker = symbol).first() else: stock = Tickers(ticker=symbol, startingPrice=price, short=False) elif choice == 'Short': if Tickers.query.filter_by(short = True, ticker = symbol).count() > 0: stock = Tickers.query.filter_by(short = True, ticker = symbol).first() else: stock = Tickers(ticker=symbol, startingPrice=price, short=True) elif choice == 'Abstain': if User.query.filter(func.lower(User.email) == func.lower(str(ws['A'+str(index)].value))).first() != None: student = User.query.filter(func.lower(User.email) == func.lower(str(ws['A'+str(index)].value))).first() t = datetime.now() today = str(t.month) + "/" + str(t.day) + "/" + str(t.year) transaction = Transactions(user_id=student.id, ticker=symbol, date=today, end_price = float(get_price(symbol)), returns = 0) db.session.add(transaction) db.session.commit() if choice == 'Long' or choice == 'Short': if User.query.filter(func.lower(User.email) == func.lower(str(ws['A'+str(index)].value))).first() != None: student = User.query.filter(func.lower(User.email) == func.lower(str(ws['A'+str(index)].value))).first() add_stock(student, stock) index += 1