def create(image_id): data = request.form image = Image.get_by_id(image_id) result = create_transaction(data.get("amount"), data.get("payment_method_nonce")) if type(result) == SuccessfulResult: new_transaction = Transaction(amount=data.get("amount"), image=image, user_id=current_user.id) if new_transaction.save(): requests.post( "https://api.mailgun.net/v3/sandboxf2ff5a19c3874580ac009024f05edf38.mailgun.org/messages", auth=("api", "17b5f5ca8aa9f463dab52b23c72c4c9d-53c13666-50ef3ea2"), data={ "from": "Mailgun Sandbox <*****@*****.**>", "to": "[email protected] <*****@*****.**>", "subject": "Hello [email protected]", "text": "Succesfully receive a donation" }) return redirect(url_for("users.show", username=image.user.username)) else: return "Could not save transaction" else: return "Could not create braintree transaction" return redirect(url_for("users.show", username=image.user.username))
def create_checkout(subscription_id): subscription = Subscription.get_or_none(Subscription.id == subscription_id) user = User.get_by_id(current_user.id) nonce_from_the_client = request.form["payment_method_nonce"] result = gateway.customer.create({ "first_name": current_user.name, "email": current_user.email, "payment_method_nonce": nonce_from_the_client }) if result.is_success : result_subscription = gateway.subscription.create({ "id" : current_user.id, "payment_method_token": result.customer.payment_methods[0].token, "plan_id": subscription.id }) if type(result_subscription) == SuccessfulResult: new_transaction = Transaction(amount = subscription.price, subscription = subscription.id , user = current_user.id) if new_transaction.save(): user.is_valid = True user.save() flash ("Transaction Successful", "success") send_message_first_payment.delay(email = current_user.email, name = current_user.name) return redirect(url_for('home')) else : flash ("Transaction Failed, check your card details and try again", "danger") return redirect(url_for('home'))
def create(image_id): data = request.form image = Image.get_by_id(image_id) result = create_transaction(data.get("amount"), data.get("payment_method_nonce")) print(type(result)) if type(result) == SuccessfulResult: new_transaction = Transaction(amount=data.get("amount"), image=image, user_id=current_user.id) if new_transaction.save(): # If want to use mailgun api # from app import app # requests.post( # "https://api.mailgun.net/v3/<YOUR_DOMAIN_NAME>/messages", # auth=("api", app.config.get("MAILGUN_API") ), # data={"from": "Mailgun Sandbox <YOUR_DOMAIN_NAME>", # "to": "Your Name <DOMAIN_EMAIL>", # "subject": "Hello", # "text": "Successfully donated"}) flash("Transactions successfull", "success") return redirect(url_for("users.show", username=image.user.username )) else: flash("Could not save transaction", "danger") return redirect(url_for("users.show", username=image.user.username )) else: flash("Could not create braintree transaction", "danger") return redirect(url_for("users.show", username=image.user.username ))
def setUp(self): self.company_1 = Company("RailScot") self.tag_1 = Tag("travel") self.company_2 = Company("Pilot Beer") self.tag_2 = Tag("food") self.transaction_1 = Transaction(10.00, self.company_1, self.tag_1) self.transaction_2 = Transaction(6.50, self.company_2, self.tag_2)
def show_checkout(transaction_id, image_id): image = Image.get_by_id(image_id) transaction = find_transaction(transaction_id) user = User.get_by_id(current_user.id) photographer = image.user result = {} if transaction.status in TRANSACTION_SUCCESS_STATUSES: result = { 'header': 'Sweet Success!', 'icon': url_for('static', filename="images/ok_icon.png"), 'message': 'Your test transaction has been successfully processed. You will receive a payment receipt via email shortly.' } t = Transaction(amount=transaction.amount, braintree_id=transaction.id, user=user, image=image) if t.save(): flash(f"Transaction successfully created.") rq_job = app.task_queue.enqueue( 'tasks.' + 'send_transaction_email', user, transaction.amount, transaction.credit_card_details.card_type, transaction.credit_card_details.last_4, photographer, transaction.id) task = Task(redis_job_id=rq_job.get_id(), name='send_transaction_email', description='Send user a donation receipt.', transaction=t) task.save() else: return render_template('transactions/show.html', transaction=transaction, result=result, errors=t.errors) else: result = { 'header': 'Transaction Failed', 'icon': url_for('static', filename="images/fail_icon.png"), 'message': 'Your test transaction has a status of ' + transaction.status + '. See the Braintree API response and try again.' } return render_template('transactions/show.html', transaction=transaction, result=result)
def add_transaction(account, transaction_type, amount): """ Add a transaction to the transaction log Args: account: the account the transaction is for transaction_type: the type of transaction amount: the amount of the transaction Returns: """ new_transaction = Transaction(transaction_type, '$%.2f' % amount, datetime.datetime.now()) account.transaction_log += new_transaction.get_transaction_str()
def pay(self, recipient_address, value): """ Generates the transaction. :param recipient_address: the address of the recipient. :param value: the amount of money to pay. :return: signed Transaction as a dictionary. """ transaction = Transaction(recipient_address, value, self.public_key) transaction.sign(self.__private_key) if value <= self.balance(): return transaction else: raise ValueError('There is not enough money on your account.')
def mine_block(self): proof_of_work = self.get_proof_of_work() mining_reward_transaction = Transaction(MINING_SENDER, self.__node_pub_key, MINING_REWARD, None) self.__outstanding_transactions.append(mining_reward_transaction) new_block = Block( hash_block(self.get_last_block()), int(self.get_last_block().index) + 1, self.__outstanding_transactions, proof_of_work, ) self.__chain.append(new_block) # Check to see if any outstanding transactions have been tampered with after being saved for txn in self.__outstanding_transactions: if not Verification.verify_transaction(txn, self.get_balance): return False if Verification.verify_blockchain(self.__chain): global participants self.__outstanding_transactions = [] participants[self.__node_pub_key] = True self.save_data() return True self.__chain.pop() self.__outstanding_transactions.pop() return False
def post(): try: data = request.get_json() new_transaction = Transaction(**data).save() except Exception as e: return jsonify({'error_msg':str(e)}), 405 return jsonify({'result': new_transaction}), 201
def main(): engine = create_engine(connection_url) Session = sessionmaker() Session.configure(bind=engine) session = Session() try: client = YnabClient(token) budget_id = get_budget_id(client) transactions = client.getTransactions(budget_id) for t in transactions: # TODO: Handle subtransactions # TODO: Add more date-related columns. Separate year, month, week of month, day of week etc. to allow for cool window functions amount = t['amount'] / 100 transaction = Transaction(id=t['id'], date=t['date'], amount=amount, category=t['category_name'], payee=t['payee_name'], description=t['memo']) session.add(transaction) session.commit() except: session.rollback() raise finally: session.close()
def get_transaction(trans_id): # fetch transaction via id try: t = Transaction.get(trans_id) return jsonify(t.serialize()) except: abort(404)
def generate_json_file_structure(cls, customer) -> Dict: """ :param customer: Take customer object :return: dictionary of Transaction Export model """ transaction = Transaction(customer) return TransactionExport(transaction).to_export()
def add_block(self, block): # block is dict here # transactions is a list of transaction object transactions = [ Transaction(tx['sender'], tx['recipient'], tx['signature'], tx['amount']) for tx in block['transactions'] ] proof_is_valid = Verification.valid_proof(transactions[:-1], block['previous_hash'], block['proof']) hashes_match = hash_block(self.chain[-1]) == block['previous_hash'] if not proof_is_valid or not hashes_match: return False converted_block = Block(block['index'], block['previous_hash'], transactions, block['proof'], block['timestamp']) self.__chain.append(converted_block) """ update open transaction on peer node, when broadcast block to peer node the some open transactions on peer node should be removed because it will be store in new block """ stored_transactions = self.__open_transactions[:] for itx in block['transactions']: # itx is incoming tx for opentx in stored_transactions: # opentx is open transaction of node # for every incoming transaction, check if it is part of my open transaction if opentx.sender == itx['sender'] and opentx.recipient == itx[ 'recipient'] and opentx.amount == itx[ 'amount'] and opentx.signature == itx['signature']: # if same, try removing it from peer node to prevent encountering second time try: self.__open_transactions.remove(opentx) except ValueError: print('Item was already removed') self.save_data() return True
def new_transaction(user_id): ''' Add new transaction. ''' # First check that the user is valid dc = DynamoClient() user = dc.get_user_by_id(user_id) if user is None: return Response(json.dumps( {'403 BAD': 'Unauthorized access to webhook'}), status=403, mimetype='application/json') # If user is valid, make sure that actor or target is the user. req_data = request.get_json() if req_data['data']['target'][req_data['data']['target']['type']][ 'username'] == user.username or req_data['data']['actor'][ 'username'] == user.username: # Then, check the transaction try: t = Transaction(req_data) except: return Response(json.dumps( {'400 BAD': 'Invalid params for transaction payload'}), status=400, mimetype='application/json') # If all is good, index the transaction. es = EsClient() es.add_transaction(t) return Response(json.dumps({'200 OK': 'The request has succeeded'}), status=200, mimetype='application/json') return Response(json.dumps({'403 BAD': 'Unauthorized access to webhook'}), status=403, mimetype='application/json')
def create_transaction(): tag = tag_repository.select(request.form["tag_id"]) merchant = merchant_repository.select(request.form["merchant_id"]) amount = request.form["amount"] new_transaction = Transaction(tag, merchant, amount) transaction_repository.save(new_transaction) return redirect("/transactions")
def resolve(self): winner_chain = self.chain replace = False # whether our current chain is getting replaced, initially is False for node in self.__peer_nodes: url = 'http://{}/chain'.format(node) try: response = requests.get(url) node_chain = response.json() # list of block dict # create list of block object with a list of dict transaction node_chain = [ Block(block['index'], block['previous_hash'], [ Transaction(tx['sender'], tx['recipient'], tx['signature'], tx['amount']) for tx in block['transactions'] ], block['proof'], block['timestamp']) for block in node_chain ] node_chain_length = len(node_chain) local_chain_length = len(winner_chain) if node_chain_length > local_chain_length and Verification.verify_chain( node_chain): winner_chain = node_chain replace = True # if replace is True, we can assume our transactions are incorrect except requests.exceptions.ConnectionError: continue self.resolve_conflicts = False self.chain = winner_chain if replace: self.__open_transactions = [ ] # if chain is replaced, set local open tx to [] self.save_data() return replace
def test_transaction_doubled_transaction(capsys): account_args = { 'account': { 'activeCard': True, 'availableLimit': 1000 }, 'violations': [''] } transaction_args = { "transaction": { "merchant": "Burger King", "amount": 20, "time": "2019-02-13T10:00:30.000Z" } } transaction1_args = { "transaction": { "merchant": "Burger King", "amount": 20, "time": "2019-02-13T10:00:00.000Z" } } account = Account(**account_args) transaction1 = Transaction(**transaction1_args) transactions = {0: transaction1} TransactionAuthorizer(account, transactions, transaction_args) assert capsys.readouterr().out == \ "{'account': {'activeCard': True, 'availableLimit': 1000}, 'violations': ['doubled-transaction']}\n"
def load_data(self): try: target_path = "../target/blockchain" + self.__node_port + ".txt" with open(target_path, mode="r") as file: print("------Loading existing blockchain------") file_content = file.readlines() blockchain = json.loads(file_content[0][:-1]) outstanding_transactions = json.loads(file_content[1][:-1]) updated_blockchain = [] updated_outstanding_transactions = [] for block in blockchain: updated_block = Block( block["prev_hash"], block["index"], [ Transaction( tx["sender"], tx["recepient"], tx["amount"], tx["signature"], tx["timestamp"], ) for tx in block["transactions"] ], block["proof_of_work"], block["timestamp"], ) updated_blockchain.append(updated_block) self.__chain = updated_blockchain for txn in outstanding_transactions: updated_txn = Transaction( txn["sender"], txn["recepient"], txn["amount"], txn["signature"], txn["timestamp"], ) updated_outstanding_transactions.append(updated_txn) self.__outstanding_transactions = updated_outstanding_transactions global participants participants = json.loads(file_content[2][:-1]) peer_nodes = json.loads(file_content[3][:-1]) self.__peer_nodes = set(peer_nodes) self.__node_port = json.loads(file_content[4]) except (IOError, IndexError): print("------Initializing new blockchain with genesis block------")
def select(id): sql = "SELECT * FROM transactions WHERE id=%s" values = [id] result = run_sql(sql, values)[0] company = company_repository.select(result["company_id"]) tag = tag_repository.select(result["tag_id"]) transaction = Transaction(result["amount"], company, tag, result["id"]) return transaction
def select(id): sql = "SELECT * FROM transactions WHERE id = %s" values = [id] result = run_sql(sql, values)[0] merchant = merchant_repository.select(result["merchant_id"]) tag = tag_repository.select(result["tag_id"]) transaction = Transaction(merchant, result["date"], result["amount"], tag, result["id"]) return transaction
def select(id): sql = "SELECT * FROM transactions WHERE id = %s" values = [id] result = run_sql(sql, values)[0] tag = tag_repository.select(result['tag_id']) merchant = merchant_repository.select(result['merchant_id']) user = user_repository.select(result['user_id']) transaction = Transaction(tag, merchant, user, result['amount'], result['date'], result['id']) return transaction
def navigation(): transactions = transaction_repository.select_all_transactions() total_spent = Transaction.add_transaction_total(transactions) account = transactions[0].account new_balance = account.update_balance(total_spent) return render_template("account/full_statment.html", transactions=transactions, total_spent=total_spent, account=account)
def create_transaction(): merchant_id = request.form['merchant_id'] tag_id = request.form['tag_id'] amount = request.form['amount'] merchant = merchant_repository.select(merchant_id) tag = tag_repository.select(tag_id) transaction = Transaction(merchant, tag, amount) transaction_repository.save(transaction) return redirect('/transactions')
def delete(self) -> Response: """Endpoint (private) responsible for allowing a User to delete a Transaction. Returns: Response -- The Flask response object. """ args = DELETE_PARSER.parse_args() transaction = Transaction.get_by_id(args['transaction_id']) if transaction is None: return abort(400, "Invalid {transaction_id} specified.") if transaction.get_user().get_email() != get_jwt_identity(): return abort(401, "You are not authorised to delete this transaction.") if Transaction.remove(transaction): return make_response( jsonify({"msg": "The transaction was successfully deleted."}), 200) return abort(400, "An error occurred in deleting the transaction.")
def update_transaction(id): amount = request.form['amount'] category = category_repository.select(request.form['category_id']) date = request.form['date'] merchant = merchant_repository.select(request.form['merchant_id']) user = user_repository.select(request.form['user_id']) transaction = Transaction(amount, category, date, merchant, user, id) transaction_repository.update(transaction) return redirect("/transactions")
def create_transaction(): amount = request.form["amount"] merchant_id = request.form["merchant_id"] tag_id = request.form["tag_id"] merchant = merchant_repository.select(merchant_id) tag = tag_repository.select(tag_id) new_transaction = Transaction(amount, merchant, tag) transaction_repository.save(new_transaction) return redirect("/transactions")
def add(): """Input transaction.""" t = Transaction( datetime.strptime(request.values['day'], '%Y-%m-%d').date(), request.values['supplier'], float(request.values['amount']), request.values['category']) Session.add(t) Session.commit() return get_latest()
def create_transaction(): amount = request.form["amount"] company_id = request.form["company_id"] tag_id = request.form["tag_id"] company = company_repository.select(company_id) tag = tag_repository.select(tag_id) new_transaction = Transaction(amount, company, tag) transaction_repository.save(new_transaction) return redirect("/")
def test_transaction_minimum_interval(capsys): account_args = { 'account': { 'activeCard': True, 'availableLimit': 1000 }, 'violations': [''] } transaction_args = { "transaction": { "merchant": "Burger King", "amount": 20, "time": "2019-02-13T10:01:30.000Z" } } transaction1_args = { "transaction": { "merchant": "Burger King", "amount": 30, "time": "2019-02-13T10:00:00.000Z" } } transaction2_args = { "transaction": { "merchant": "7 Eleven", "amount": 20, "time": "2019-02-13T10:00:30.000Z" } } transaction3_args = { "transaction": { "merchant": "Pizza Hut", "amount": 10, "time": "2019-02-13T10:01:00.000Z" } } account = Account(**account_args) transaction1 = Transaction(**transaction1_args) transaction2 = Transaction(**transaction2_args) transaction3 = Transaction(**transaction3_args) transactions = {0: transaction1, 1: transaction2, 2: transaction3} TransactionAuthorizer(account, transactions, transaction_args) assert capsys.readouterr().out == \ "{'account': {'activeCard': True, 'availableLimit': 1000}, 'violations': ['high-frequency-small-intervall']}\n"
def select_all(): transactions = [] sql = "SELECT * FROM transactions" results = run_sql(sql) for result in results: company = company_repository.select(result["company_id"]) tag = tag_repository.select(result["tag_id"]) transaction = Transaction(result["amount"], company, tag, result["id"]) transactions.append(transaction) return transactions
def __init__(self): log.info("Entity::__init__") self.dbconn = DboMySQL() self.table = "entities" self._fields = self._getFields() self.storage_path = os.path.abspath(config.get("path", "storage")) self.Transaction = Transaction()
def load_data(self): try: # mode should be 'rb' if using pickle, and txt should be p with open('blockchain-{}.txt'.format(self.node_id), mode='r') as f: # file_content = pickle.loads(f.read()) # blockchain = file_content['chain'] # open_transactions = file_content['ot'] file_content = f.readlines() # from string to python object blockchain = json.loads(file_content[0][:-1]) # without '\n' # at this time, blockchain is a list of dict # [{..}, {..}...] updated_blockchain = [] for block in blockchain: converted_tx = [ Transaction(tx['sender'], tx['recipient'], tx['signature'], tx['amount']) for tx in block['transactions'] ] # a list of transaction object # block = {...} for now updated_block = Block(block['index'], block['previous_hash'], converted_tx, block['proof'], block['timestamp']) updated_blockchain.append(updated_block) self.chain = updated_blockchain # a list of block object will be loaded by setter open_transactions = json.loads(file_content[1][:-1]) updated_transactions = [] for tx in open_transactions: updated_transaction = Transaction(tx['sender'], tx['recipient'], tx['signature'], tx['amount']) updated_transactions.append(updated_transaction) self.__open_transactions = updated_transactions peer_nodes = json.loads(file_content[2]) self.__peer_nodes = set(peer_nodes) # IOError is file not found error except (IOError, IndexError): pass finally: print('Cleanup!')
def add_transaction(): t = Transaction(request.form['amount'], request.form['reoccurs'], description=request.form['description']) Transaction.add(t) # adds a transaction pass
class Entity(AppModel): def __init__(self): log.info("Entity::__init__") self.dbconn = DboMySQL() self.table = "entities" self._fields = self._getFields() self.storage_path = os.path.abspath(config.get("path", "storage")) self.Transaction = Transaction() def __actionToInt(self, action): log.info("Entity::__actionToInt") log.debug(action) result = None if action == "upload": result = UPLOAD elif action == "download": result = DOWNLOAD elif action == "delete": result = DELETE return result def __getSkipedEntities(self, params): rows = self.Transaction.getSkiped(params) skiped_entities = self.Transaction.prepareToClient(rows) for entity in skiped_entities: if entity["action"] == "upload": entity["action"] = "download" return skiped_entities def syncEntities(self, user_id, client_id, params): log.info("Entity::syncEntities") log.debug(params) # get unfinished transactions data = { "user_id": user_id, "client_id": client_id, "finished": self.Transaction.getLastSyncedDate(user_id, client_id), } log.debug(data) entities = self.__getSkipedEntities(data) # !!!!!! ADD REMOVE EXPIRED TRANSACTION self.Transaction.removeUncompleted(user_id, client_id) # ???? # rows = self.Transaction.getUnCompleted(user_id, client_id) # entities = self.Transaction.prepareToClient(rows) # entities = entities + skiped_entities log.debug("Previous skiped transactions:") log.debug(entities) if params.has_key("entities"): data = {"user_id": user_id, "client_id": client_id} tickets = self.__sync(data, params.get("entities")) if len(tickets) > 0: log.debug("Tickets: %s" % tickets) rows = self.Transaction.findByUserTickets(user_id, client_id, tickets) rows = self.Transaction.prepareToClient(rows) entities = entities + rows log.debug("Entities: %s" % entities) entities = {"command": "syncEntities", "entities": entities} return entities def __sync(self, params, entities): log.info("Entity::__sync") log.debug(entities) tickets = [] try: for entity in entities: type, path = entity.get("path").split(":") if type == "files": switch = self.__files(params.get("user_id"), params.get("client_id"), entity) else: switch = self.__undefined(type, entity) # switch = { # 'files': self.__files(params.get('user_id'), params.get('client_id'), entity) # }.get(type, self.__undefined(type, entity)) if not switch is None: tickets.append(switch) except Exception, e: log.error("Entities synchronization error %s" % repr(e)) return tickets
def get_transactions(): try: return jsonify(transactions=[i.serialize() for i in Transaction.get()]) except: abort(404) pass
def delete_transaction(trans_id): #deletes a transaction try: Transaction.delete(trans_id) except: abort(404)