async def post_transactions_handler(self, request): db_session = request.app.session data = await request.json() try: limit = db_session.query(Limits).filter( Limits.client_id == data['client_id'], Limits.cur == data['cur'], Limits.country == data['country']).one() except Exception: return web.json_response( {"error_msg": "Not found limit for this params"}, status=404) data['date'] = datetime.fromtimestamp( data.get('date', int(time.time()))) transactions = db_session.query(Transactions).filter( Transactions.client_id == data['client_id'], Transactions.cur == data['cur'], Transactions.country == data['country'], extract('year', Transactions.date) == data['date'].year, extract('month', Transactions.date) == data['date'].month).all() amount = 0 if transactions != None: amount = sum([transaction.amount for transaction in transactions]) if amount + data['amount'] > limit.limit: return web.json_response({"error_msg": "Limit exeeded"}, status=400) transaction = Transactions(**data) db_session.add(transaction) db_session.commit() return web.json_response(status=200, data=transaction.get_json())
def call_user(sender_id, recipient_id): sender_details = Transactions.query.filter_by(sender_id=sender_id).first() sender_data = '' recipient_data = '' # Check if a session created by sender exists if (sender_details.session): session = sender_details.session else: sender_data = {"user": recipient_id, "session": Haikunator.haikunate()} Transactions(sender_data).save() try: recipient_data = {"user": recipient_id, "session": session} # Push data to a database Transactions(recipient_data).save() except Exception: pass recipient_token = tokenize(recipient_data) send_message( recipient_id, 'You have been invited to join the following call:' ' {}/call/{}'.format(main_url, recipient_token)) sender_token = tokenize(sender_data) return redirect('/call/{}'.format(sender_token))
def save_data(key): jsoned = trans(request.get_data()) value = jsoned["payload"] res = blockchain.save_data(key, value) if res["success"] == True: # save to data_on_chain an_item = Data_on_chain() an_item.key = key an_item.value = value an_item.tx_id = res['payload']['txId'] an_item.last_update_time = datetime.datetime.now() db.session.add(an_item) db.session.commit() # save to transactions a_tx = Transactions() a_tx.key = key a_tx.value = value a_tx.tx_id = res['payload']['txId'] a_tx.operation = "create" a_tx.timestamp = datetime.datetime.now() db.session.add(a_tx) db.session.commit() db.session.refresh(a_tx) return json.dumps(a_tx.to_dict()) else: return "error"
def update_data(key): jsoned = trans(request.get_data()) value = jsoned["payload"] res = blockchain.update_data(key, value) if res["success"] == True: # update data an_item = Data_on_chain.query.filter_by(key=key).first() # get last one: # obj = session.query(ObjectRes).order_by(ObjectRes.id.desc()).first() an_item.value = value an_item.tx_id = res['payload']['txId'] an_item.last_update_time = datetime.datetime.now() db.session.add(an_item) db.session.commit() # save to transactions a_tx = Transactions() a_tx.key = key a_tx.value = value a_tx.tx_id = res['payload']['txId'] a_tx.operation = "update" a_tx.timestamp = datetime.datetime.now() db.session.add(a_tx) db.session.commit() db.session.refresh(a_tx) return json.dumps(a_tx.to_dict()) else: return "error"
def add_transaction(id): form = TransactionForm() book = Books.query.get_or_404(id) if form.is_submitted(): check_member = Members.query.filter_by(id=form.member_id.data).first() if (book.total_qty - book.issued_qty) > 1 and check_member is not None: issued_qty = book.issued_qty + 1 print(form.member_id.data) data = Transactions(member_id=form.member_id.data, book_id=form.book_id.data, issue_date=form.issue_date.data, return_date=form.return_date.data, book_status=True) Books.query.filter_by(id=id).update({Books.issued_qty: issued_qty}) db.session.add(data) db.session.commit() flash("Book issued successfully !") form.book_id.default = book.id data = Members.query.all() choice_list = [(member.id, str(member.id) + "---------" + member.name) for member in data] form.member_id.choices = choice_list form.member_id.default = form.member_id.data form.process() return render_template("add_transaction.html", form=form) else: flash("Sorry! book cannot be issued due to low stock or member not found!") return render_template("add_transaction.html", form=form) form.book_id.default = book.id data = Members.query.all() choice_list = [(member.id, str(member.id) + "---------" + member.name) for member in data] form.member_id.choices = choice_list form.process() return render_template("add_transaction.html", form=form)
def addonPay(user, pid, qty): # Online purchase method # Create a transaction # Create a Addon transaction message = "Success" if pid == 2: print("Yeah 2") # Outstation: Proshow + Choreonite + Fashionshow total = qty * Prices.P2 if qty >= 3: total -= int(qty / 3) * 100 message = "Offer applied. Rs. " + str(int(qty / 3) * 100) + " off." elif pid == 3: # General: Headbangers + Choreonite + Fashionshow total = qty * Prices.P3 elif pid == 100: # Testing case total = qty * Prices.P100 else: responseObject = {'status': 'failed', 'message': 'No such product'} return jsonify(responseObject) transaction = Transactions(vid=user.vid, cat=3, eid=pid, amount=total) print("TOTAL ", total) print("Transactions ", transaction.__dict__) db.session.add(transaction) db.session.commit() traddon = AddonTransactions(trid=transaction.trid, qty=qty) db.session.add(traddon) db.session.commit() return jsonify(pay_data(transaction.amount, transaction.trid))
def prodaza(): form = ProdazaForm() if form.validate_on_submit(): # currency = form.currency_name.data currency = form.Вид_валюты.data pok = Kind_operations.query.filter_by( operation_short='Продажа').first() #Обновим баланс пользователя kurs_val = (currency.c_course_pokupka / currency.quantity) sum_val = round(form.sum_curr.data, 2) # sum_ru=form.sum_rubl.data sum_ru = round(sum_val * kurs_val, 2) bal_curr = ('-' + str(sum_val) + currency.currency_short + ';' + current_user.balance_curr) bal_rubl = ('+' + str(sum_ru) + 'РУБ;' + current_user.balance_rubl) current_user.balance_curr = bal_curr[0:150] current_user.balance_rubl = bal_rubl[0:150] db.session.commit() # print(current_user.id, current_user.balance_curr, current_user.balance_rubl) trans = Transactions(sum_curr=form.sum_curr.data, sum_rubl=sum_ru, \ user_id=current_user.id, operation_id=pok.id, currency_id=currency.id) db.session.add(trans) db.session.commit() flash('Вы обменяли: '+str(sum_val)+currency.currency_short+' на: '+str(sum_ru)+'РУБ'\ +' по курсу: '+str(kurs_val)+'. Транзакция прошла успешно.') return redirect(url_for('prodaza')) return render_template('prodaza.html', title='Sale', form=form)
def deposit(): if request.method == 'POST': acc_id = request.form.get('acc_id') amount = request.form.get('amount') account = Account.query.filter_by(acc_id=acc_id).first() try: account.amount = int(account.amount) + int(amount) transaction = Transactions(debit=" ", credit=amount, balance=account.amount, description="Cash Deposit", account=account) db.session.add(transaction) db.session.commit() flash("Amount deposited successfully", 'success') except Exception as e: print(e) flash("Something Went Wrong", 'error') accounts = None ssn_id = request.args.get('ssn_id') cust_id = request.args.get('cust_id') acc_id = request.args.get('acc_id') if ssn_id is not None: customer = Customer.query.filter_by(ssn_id=ssn_id).first() if customer: cust_id = customer.cust_id if cust_id is not None: accounts = Account.query.filter_by(cust_id=cust_id).all() if acc_id is not None: accounts = Account.query.filter_by(acc_id=acc_id).all() if (ssn_id or cust_id or acc_id) and not accounts: flash("User does not exist", 'error') return render_template("deposit.html", accounts=accounts)
def add_transaction_to_list(): """ The curl command to test this endpoint is as follows: curl -H "Content-Type: application/json" -X POST -d '{"date": "2017-06-15", "balance": 13.86, "category": "Other", "description": "pie", "value": 3.33}' http://localhost:5000/add_transaction """ data = request.get_json(force=True) date, category, description, balance, value, error_list = get_json_values( data) if True not in error_list: transaction = Transactions(date=date, category=category, description=description, balance=balance, value=value) transaction.save() response = jsonify({ "id": transaction.id, "date": transaction.date, "category": transaction.category, "description": transaction.description, "balance": float(transaction.balance), # Decimals not serializable "value": float(transaction.value), }) response.status_code = 201 return response response = jsonify({ "error": "Invalid data entry! date: {}, category: {}, description: {}, balance: {}, value: {}" .format(error_list[0], error_list[1], error_list[2], error_list[3], error_list[4]), "date": date, "category": category, "description": description, "balance": float(balance), "value": float(value), }) response.status_code = 400 return response
def transfer(): if request.method == 'POST': amount = request.form.get('amount') source_acc_id = request.form.get('source_acc_id') target_acc_id = request.form.get('target_acc_id') source_account = Account.query.filter_by(acc_id=source_acc_id).first() target_account = Account.query.filter_by(acc_id=target_acc_id).first() try: if int(source_account.amount) < int(amount): flash('Transfer not allowed, please choose smaller amount', 'error') return redirect(url_for('main.transfer')) source_account.amount = int(source_account.amount) - int(amount) target_account.amount = int(target_account.amount) + int(amount) transaction1 = Transactions(debit=amount, credit=" ", balance=source_account.amount, description="Transfer to " + target_acc_id, account=source_account) transaction2 = Transactions(debit=" ", credit=amount, balance=target_account.amount, description="Transfer from " + source_acc_id, account=target_account) db.session.add(transaction1) db.session.add(transaction2) db.session.add(source_account) db.session.add(target_account) db.session.commit() flash('Amount transfer completed successfully', 'success') except Exception as e: print(e) flash("Something Went Wrong", 'error') return render_template("transfer.html")
def get_list_of_transaction(): """ The curl command to test this endpoint is as follows: curl http://localhost:5000/query_transactions """ transactions = Transactions.get_all() results = [] for transaction in transactions: obj = { "id": transaction.id, "date": transaction.date, "description": transaction.description, "category": transaction.category, "balance": float(transaction.balance), "value": float(transaction.value), } results.append(obj) response = jsonify(results) response.status_code = 200 return response
def addexpense(): if 'user' not in session: return redirect(url_for("login")) else: if request.method == "POST": result = request.form for num in range(1, 101): if db.session.query( Transactions.id).filter_by(id=num).scalar() is None: tno = num break t = Transactions(id=tno, date=datetime.strptime(result['date'], '%Y-%m-%d'), category=result['type'], amount=result['amount'], note=result['note'], user_id=int(session['id'])) db.session.add(t) db.session.commit() return redirect(url_for("trans"))
def delete_data(key): res = blockchain.delete_data(key) if res["success"] == True: # delete item in data_on_chain item = Data_on_chain.query.filter_by(key=key).first() db.session.delete(item) db.session.commit() # save to transactions a_tx = Transactions() a_tx.key = key a_tx.tx_id = res['payload']['txId'] a_tx.operation = "delete" a_tx.timestamp = datetime.datetime.now() db.session.add(a_tx) db.session.commit() db.session.refresh(a_tx) return json.dumps(a_tx.to_dict()) else: return "error"
def withdraw(): if request.method == 'POST': acc_id = request.form.get('acc_id') amount = request.form.get('amount') account = Account.query.filter_by(acc_id=acc_id).first() if int(account.amount) < int(amount): flash("Withdraw not allowed, please choose smaller amount", 'error') return redirect(url_for('main.withdraw')) try: account.amount = int(account.amount) - int(amount) transaction = Transactions(debit=amount, credit=" ", balance=account.amount, description="Cash Withdraw", account=account) db.session.add(transaction) db.session.commit() flash("Amount withdrawn successfully", 'success') except Exception as e: print(e) flash("Something Went Wrong", 'error') accounts = None ssn_id = request.args.get('ssn_id') cust_id = request.args.get('cust_id') acc_id = request.args.get('acc_id') if ssn_id is not None: customer = Customer.query.filter_by(ssn_id=ssn_id).first() if customer: cust_id = customer.cust_id if cust_id is not None: accounts = Account.query.filter_by(cust_id=cust_id).all() if acc_id is not None: accounts = Account.query.filter_by(acc_id=acc_id).all() if (ssn_id or cust_id or acc_id) and not accounts: flash("User does not exist", 'error') return render_template("withdraw.html", accounts=accounts)
def user_dashboard(): transactform = TransactForm() TransactQuery = Transactions.query.join( User, (Transactions.payer_id == User.id)).filter( or_(Transactions.payer_id == current_user.id, Transactions.payee_id == current_user.id)).order_by( Transactions.timestamp.desc()) Requests = Transactions.query.join( User, (Transactions.payer_id == User.id)).filter( and_(Transactions.done == 0, Transactions.payer_id == current_user.id)).order_by( Transactions.timestamp.desc()) # Add Money feature if request.method == "POST" and transactform.addbutton.data: current_user.money += int(transactform.add.data) db.session.commit() return redirect(url_for('user_dashboard')) # Pay/Receive feature if request.method == "POST": if transactform.paybutton.data: payee = User.query.filter_by(phone=transactform.payee.data).first() transact = Transactions(payer_id=current_user.id, payee_id=payee.id, amount=int(transactform.pay.data)) current_user.money -= int(transactform.pay.data) payee.money += int(transactform.pay.data) transact.done = 1 db.session.add(transact) if transactform.receivebutton.data: payer = User.query.filter_by(phone=transactform.payer.data).first() transact = Transactions(payer_id=payer.id, payee_id=current_user.id, amount=int(transactform.receive.data)) db.session.add(transact) if 'accept' in request.form.values(): transact = Transactions.query.filter_by( id=request.form.get('request_id')).first() payee = User.query.filter_by(id=transact.payee_id).first() current_user.money -= int(transact.amount) payee.money += int(transact.amount) transact.done = 1 if 'decline' in request.form.values(): Transactions.query.filter_by( id=request.form.get('request_id')).delete() db.session.commit() return redirect(url_for('user_dashboard')) # Request someone if request.method == 'POST' and request.form['filter'] == 'string': print('string request') TransactQuery = Transactions.query.join( User, (Transactions.payer_id == User.id)).filter( or_(Transactions.payer_id == current_user.id, Transactions.payee_id == current_user.id)).filter( Transactions.timestamp.between( request.form.get('from'), request.form.get('to'))).order_by( Transactions.timestamp.desc()) if request.method == 'POST' and request.form['filter'] == 'date': print('date request') TransactQuery = Transactions.query.join( User, (Transactions.payer_id == User.id)).filter( or_(Transactions.payer_id == current_user.id, Transactions.payee_id == current_user.id)).filter( User.name.contains( request.form.get('search'))).order_by( Transactions.timestamp.desc()) return render_template("user.html", name=current_user.name, money=current_user.money, transactform=transactform, TransactionsHistory=TransactQuery, current_user_id=current_user.id, type=current_user.type, requests_pending=Requests)
for i in transactions.get("payload").get("context"): try: time = i.get("txTime") transactions_dict = json.loads(i.get('dataInfo')) transactions_dict["timestamp"] = i.get("txTime") transactions_dict["txid"] = i.get("txId") except: transactions_dict = {"txid": i.get("txId"), "BaseKey": None, "BaseInfo": None, "timestamp": i.get("txTime")} transactions_list.append(transactions_dict) for i in transactions_list: trans = Transactions(txid=i.get("txid"), key=i.get("BaseKey"), operation=None, value=i.get("BaseInfo"), timestamp=i.get("timestamp")) db.session.add(trans) db.session.commit() if data_on_chain.get("payload").get("context"): data_on_chain_dict = {"txid": data_on_chain.get("payload").get("txId"), "BaseKey": i.get("BaseKey"), "Value": data_on_chain.get("payload").get("context"), "Last UpdateTime": i.get("timestamp")} data_on_chain_list.append(data_on_chain_dict) print(data_on_chain_dict) data = Data_on_chain(txid=data_on_chain_dict.get("txid"), key=data_on_chain_dict.get("BaseKey"), value=data_on_chain_dict.get("Value"), last_updatetime=data_on_chain_dict.get("Last UpdateTime"))
def transfer(): """ Функция для осуществления переводов между пользователями. """ private_key_sender = CryptoInfo.query.filter( CryptoInfo.user_id == current_user.id).first() private_key_sender = base_decode(private_key_sender) info = [(i.billfold_number, 'Счёт №' + i.billfold_number + ' | ' + str(i.wallet)) for i in Billfold.query.filter(Billfold.user_id == current_user.id) ] form = TransferMoney() form.bills.choices = info if form.bills.data and form.validate_on_submit(): newTransaction = Transactions() newTransaction.senderId = int(current_user.id) newTransaction.senderBill = str(form.bills.data) newTransaction.receiverBill = str(form.transBill.data) newTransaction.receiverId = Billfold.query.filter( Billfold.billfold_number == newTransaction.receiverBill).first() if newTransaction.receiverId is None: flash('Данного счета не существует.') return redirect(url_for('transfer')) newTransaction.receiverId = newTransaction.receiverId.user_id try: newTransaction.transferAmount = float(form.transSum.data) except ValueError: flash('Введите корректную сумму') return redirect(url_for('transfer')) else: sender = Billfold.query.filter( Billfold.billfold_number == newTransaction.senderBill).first() receiver = Billfold.query.filter( Billfold.user_id == newTransaction.receiverId, Billfold.billfold_number == newTransaction.receiverBill).first() if newTransaction.transferAmount > sender.balance: flash('На вашем счету недостаточно средств.') return redirect(url_for('transfer')) elif newTransaction.transferAmount <= 0: flash( 'Сумма перевода не может быть отрицательной или меньшей нуля.' ) return redirect(url_for('transfer')) elif sender.wallet != receiver.wallet: flash('Валюты на счету отправителя и получателя не совпадают.') return redirect(url_for('transfer')) elif newTransaction.transferAmount <= sender.balance: # Информация для отладки #print("Сумма перевода: {}\n".format(newTransaction.transferAmount)) #print("Валюты на счетах отправителя и получателя: {} и {}".format( # sender.wallet, receiver.wallet)) private_key = CryptoInfo.query.filter( CryptoInfo.user_id == newTransaction.receiverId).first() private_key = base_decode(private_key) public_key = generate_public(private_key) # TEST darkening_factor = random.randint(2, 30) m = public_key['modulus'] e = public_key['publ_exp'] d = private_key['priv_exp'] r_pow_e = gmpy2.mpz(darkening_factor)**e fx = oneside_func(int(newTransaction.transferAmount), int(e), int(m)) bank_sign = gmpy2.powmod(int(fx), int(d), int(m)) if (fx == gmpy2.powmod(int(fx), 1, int(m))): user_balance = Billfold.query.filter(Billfold.user_id == current_user.id,\ Billfold.billfold_number == newTransaction.senderBill).first() user_balance.balance = user_balance.balance - newTransaction.transferAmount receiver_balace = Billfold.query.filter(Billfold.user_id\ == newTransaction.receiverId, Billfold.billfold_number ==\ newTransaction.receiverBill).first() receiver_balace.balance = receiver_balace.balance + newTransaction.transferAmount db.session.commit() decrypted_message = str(form.message.data) private_key = CryptoInfo.query.filter( CryptoInfo.user_id == newTransaction.receiverId).first() newKey = CryptoInfo() if private_key: private_key = base_decode(private_key) public_key = generate_public(private_key) else: private_key, public_key = generate_keys() newKey.key = str(private_key['priv_exp']) + '|' + str( private_key['modulus']) + '|' + str( private_key['p']) + '|' + str(private_key['q']) newKey.user_id = int(newTransaction.receiverId) db.session.add(newKey) newTransaction.transferAmount = encrypt_message( str(newTransaction.transferAmount), public_key) encrypted_message = encrypt_message( decrypted_message, public_key) newTransaction.message = encrypted_message newTransaction.date = str(datetime.datetime.utcnow())[:19] newTransaction.date = encrypt_message( newTransaction.date, public_key) db.session.add(newTransaction) db.session.commit() return redirect(url_for('main')) return render_template('transfer.html', form=form)
def query_list_of_transaction(): """ The curl command to test this endpoint is as follows: curl http://localhost:5000/query_transactions?description=pie """ # This needs a null consideration and update by guide which has been faved on laptop id = request.args.get("id") date = request.args.get("date") description = request.args.get("description") category = request.args.get("category") balance = request.args.get("balance") value = request.args.get("value") validation = { verify_id: [{ "id": id }], verify_date: [{ "date": date }], verify_category: [{ "category": category }], verify_description: [{ "description": description }], verify_monetary_values: [{ "balance": balance }, { "value": value }], } filter_by_dict = {} c = "" for key, val in validation.items(): for domain in val: for column, col_val in domain.items(): returned_val, error = key(col_val) if returned_val is not None and error: # The query column failed response = jsonify({ "Validation issue. The following query is not valid": returned_val }) response.status_code = 400 return response elif not error: filter_by_dict[column] = returned_val c = column queried_transactions = Transactions.query_by(filter_by_dict) if len(queried_transactions) == 0: val = filter_by_dict[c] if isinstance(val, Decimal): response = jsonify({ "Data issue. No transactions matching query for {} ".format(c): float(val) }) else: response = jsonify({ "Data issue. No transactions matching query for {} ".format(c): val }) response.status_code = 200 return response results = [] for transaction in queried_transactions: obj = { "id": transaction.id, "date": transaction.date, "description": transaction.description, "category": transaction.category, "balance": float(transaction.balance), "value": float(transaction.value), } results.append(obj) response = jsonify(results) response.status_code = 200 return response