def transaction(): #Assigns to the previously defined form class form = TransactionForm(request.form) # Takes the hashed value of the provided private key if request.method == "POST" and form.validate(): private_key_hash = hasher.sha1( form.private_key.data.encode('utf-8')).hexdigest() # checks whether the owner of the car and the vendor matches if all_owners()[form.car.data] != form.vendor.data: flash( "You are not owning a car with this ID. A transaction is therefore not possible", "danger") # Checks whether the hasehd private key in the db and the provided private key match if all_loggins()[form.vendor.data] != private_key_hash: flash( "The secret key you typed in does not match with your profil", "danger") else: next_id = check_id() + 1 hash_block = block(next_id, [ form.vendor.data, form.buyer.data, form.car.data, form.private_key.data ], previous_hash()).hash data = db(next_id, form.vendor.data, form.buyer.data, form.car.data, private_key_hash, 0, 0, hash_block, 0, 0, 0) data.trans_db() return render_template('transaction.html', form=form)
def transact(request, product_slug, template_name="pdcts/transact.html"): page_title = "Bid Product" pdct = get_object_or_404(Product, slug=product_slug) offers = Transaction.objects.filter(product__slug=product_slug).order_by('-bid_price')[:1] if request.method =='POST': form = TransactionForm (request.POST) p = get_object_or_404(Product, slug=product_slug) email_subject = 'Approve a buyer Offer' email_body = "Hello %s, \n\nThis is a My Campuser seller alert send to the Site's Sellers. \n\nPlease, check your My Campuser transactions page to either Accept or Reject a new buyer offer for the product %s by using the following link: \n\nhttp://mycampuser.com/accounts/my_transactions/ \n\nRegards,\nMy Campuser Team" % (p.user, p.product_name) if form.is_valid(): r = form.cleaned_data["quantity"] if r > p.quantity: # raise forms.ValidationError('%s is only available. Request for it or less' % (p.quantity)) qtty = "Available: %d . Enter it or Less." % (p.quantity) form = BuyNowForm() else: buy = form.save(commit=False) buy.user = request.user buy.product = p buy.status = "Not Yet Approved" buy.save() send_mail(email_subject, email_body, '*****@*****.**', [p.user.email]) return HttpResponseRedirect('/accounts/my_transactions/') else: p = get_object_or_404(Product, slug=product_slug) form = TransactionForm() return render_to_response(template_name, locals(), context_instance = RequestContext(request))
def add_transaction(): transaction_dict = request.json form = TransactionForm(**transaction_dict) if form.validate(): wallet = Wallet(key) transaction = Transaction(outputs=[(PrivateKey( transaction_dict['receiver']).public_key().to_bytes(), transaction_dict['amount'])]) signed_transaction = wallet.sign(transaction) transactionPool.receive_transaction(blockchain, signed_transaction) return '' return '', 403
def add_transaction(): form = TransactionForm(request.form) team_id = form.team_id.data drop_player = form.drop_player.data add_player = form.add_player.data if form.validate(): transaction = Transaction(drop_player=drop_player, add_player=add_player, team_id=team_id, status=Transaction.Status.PENDING) db.session.add(transaction) db.session.commit() return jsonify({}), 200, {} return jsonify({}), 404, {}
def createFinancialTranx(request): isLoged(request) acc = getCurrentAccount(request) currentAccFina = getSavedInSession(request, 'currentAccFina') team = getSavedInSession(request, 'team') accFina = team.financialacc_set.all() page = request.GET.get('page','1') msj = '' if request.method == 'POST': trx = TransactionForm(request.POST) if trx.is_valid(): typeTrx = request.POST.get('transTypeParam' , '') trxt = trx.save(commit = False) trxt.creator = acc trxt.accounttrans = currentAccFina if typeTrx == 'isSpending': trxt.amount = trxt.amount * -1 trxt.save() budgetlist = currentAccFina.budget_set.all() data = [] if budgetlist: data=budgetlist[0].transactionbudget_set.filter(concept= trxt.concept) if data: newAmount = abs(data[0].amount) - abs(trxt.amount) if trxt.amount >=0 and data[0].amount<0: msj = "El presupuesto asumira este ingreso como un gasto por usar su mismo concepto." if (newAmount<=0): data[0].isDone = True data[0].save() else: if(data[0].amount < 0): data[0].amount = newAmount * -1 else: data[0].amount = newAmount data[0].save() trxs = Paginator(currentAccFina.transaction_set.all(),5).page(int(page)) balance = 0 for t in trxs: balance += t.amount return render(request,'financialAcctnx.html',{'msjInfo':msj ,'user':getLogin(request),'accFina':accFina,'currentAccFina':currentAccFina.name,'trans':trxs,'balance':balance})
def transaction(): form = TransactionForm() if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash( form.password.data).decode('utf-8') cart = Transaction(product=form.product.data, amount=form.amount.data, id=form.id.data, payment=form.payment.data) db.session.add(cart) db.session.commit() flash('You have successfully completed a transaction.', 'success') return redirect(url_for('transaction')) return render_template('transaction.html', title='Transaction', link1=url_for('Employee'), form=form)
def transaction(): form = TransactionForm() if form.validate_on_submit(): if form.file.data: ipfs_master = IpfsMaster("example.conf") client = ipfs_master.getClient() path = os.path.join(UPLOAD_FOLDER, form.file.data.filename) form.file.data.save(path) info = client.add(path) result = client.object.patch.add_link(info['Hash'], info['Name'], info['Hash']) hash_str = result['Hash'] client.close() flash(hash_str) #return redirect("https://rinkeby.etherscan.io/tx/0x852ce8ca4875c0084635b7133a3b6d8e804bb61e22f9e0567b401f941c78a739?fbclid=IwAR0LsnLbqCNadLGqkeRvgdba5TeYXBmSE1h_UBeQzjar23Gfkt6nfN0Psj0") else: flash('Unsuccessful', 'danger') return render_template('trans.html', title='Transaction', form=form)
def new_transaction(request): if request.session.has_key('logged_in'): # get the time, time as string, and location via json thingy now = datetime.datetime.now() strnow = now.strftime('%d/%m/%Y') # handle form submission if request.method == 'POST': # Get everything from form form = TransactionForm(request.POST, request.FILES) if form.is_valid(): # clean up and set vars cd = form.cleaned_data item = cd['item'] price = cd['price'] shop = cd['shop'] notes = cd['notes'] bing_image = cd['bing_image'] address = request.POST.get('address') lat = request.POST.get('manual-lat') lon = request.POST.get('manual-lon') t = Transaction(date=now, strdate=strnow, item=item, price=price, shop=shop, notes=notes, address=address, bing_image=bing_image, lat=lat, lon=lon) t.save() success = True return render(request, 'new_transaction.html', {'success': success}) else: # not POST, render form form = TransactionForm() return render(request, 'new_transaction.html', {'form': form}) else: # not logged in, render login return render( request, 'login.html', { 'user_login': '******', 'destiantion': 'new_transaction' })
def pay(request): render = {} if request.method == "POST": render["form"] = form = TransactionForm(data=request.POST, user=request.user.clerk) if form.is_valid(): obj = form.save(commit=False) obj.comment = u"Пополнение SMS-баланса" obj.save() sign = hashlib.md5("SkyZmey:%s:%d:Pxh3dzVg5bayPQvXwz2v" % (str(obj.amount), obj.id)).hexdigest() return HttpResponseRedirect( "http://merchant.roboxchange.com/Index.aspx?MrchLogin=SkyZmey&OutSum=%s&InvId=%d&Desc=%s&SignatureValue=%s&IncCurrLabel=QiwiR&Culture=ru" % (str(obj.amount), obj.id, obj.comment, sign)) else: render["form"] = TransactionForm(user=request.user.clerk) return render_to_response("~billing/pay.html", render, context_instance=RequestContext(request))
def add_trans(): print (str(session['email']),'is on add_trans') email = session['email'] form = TransactionForm() form.account.choices = [(a.name,a.name) for a in Accounts.query.filter_by(email=email).order_by(Accounts.name)] form.category.choices = [(c.name,c.name) for c in Categories.query.filter_by(email=email).order_by(Categories.name)] form.goal.choices = [(g.description,g.description) for g in Goals.query.filter_by(email=email).order_by(Goals.description)] if request.method == 'POST': if form.validate() == False: print ("validate failed: ",session['email'], form.account.data, form.category.data, form.notes.data, form.amount.data) return render_template('addtrans.html', form=form) else: newtrans = Transactions(str(session['email']), str(form.account.data), str(form.category.data), str(form.goal.data), today, str(form.notes.data), float(form.amount.data)) print ("validated Transaction data: ", session['email'], form.account.data, form.category.data, str(today), form.notes.data, form.amount.data) db_session.add(newtrans) db_session.commit() flash('You created a new transaction.') print (str(session['email']),'has successfully added a new transaction') return redirect('/home/',) print ("submit failed: ",session['email'], form.account.data, form.category.data, today, form.notes.data, form.amount.data) return render_template('addtrans.html', form=form)
def transfer(request): if request.method == "POST": f = TransactionForm(request.POST) if f.is_valid(): recaccno = f.cleaned_data['receiver_accno'] transpass = f.cleaned_data['transaction_password'] amt = f.cleaned_data['amount'] curruser = User.objects.get(username=request.user.username) balance = curruser.profile.balance transactionpass = curruser.profile.transaction_password receiver = Profile.objects.get(account_no=recaccno) if balance >= amt: if receiver is not None: if transpass == transactionpass: receiver.balance = receiver.balance + amt receiver.save() curruser.profile.balance = curruser.profile.balance - amt curruser.save() f.save() iid = (Transaction.objects.all().aggregate( Max('id')))['id__max'] currtrans = Transaction.objects.get(id=iid) currtrans.sender_accno = curruser.profile.account_no currtrans.save() return render_to_response('transfer_success.html') return render_to_response('transfer_fail.html') args = {} #args.update(csrf(request)) args['f'] = TransactionForm() print args #return render_to_response('register.html', args) return render(request, 'transfer.html', args)
def addtransaction(request): categories = Category.objects.all() if request.method == "POST": form = TransactionForm(request.POST) if form.is_valid(): transaction = form.save(commit=False) transaction.user = request.user transaction.save() return redirect("/expensemanager/") else: print form.errors else: form = TransactionForm() return render(request, "expensemanager/addtransaction.html", { 'categories': categories, 'form': form })
def transact(request, product_slug, template_name="pdcts/transact.html"): page_title = "Bid Product" pdct = get_object_or_404(Product, slug=product_slug) offers = Transaction.objects.filter( product__slug=product_slug).order_by('-bid_price')[:1] if request.method == 'POST': form = TransactionForm(request.POST) p = get_object_or_404(Product, slug=product_slug) email_subject = 'Approve a buyer Offer' email_body = "Hello %s, \n\nThis is a My Campuser seller alert send to the Site's Sellers. \n\nPlease, check your My Campuser transactions page to either Accept or Reject a new buyer offer for the product %s by using the following link: \n\nhttp://mycampuser.com/accounts/my_transactions/ \n\nRegards,\nMy Campuser Team" % ( p.user, p.product_name) if form.is_valid(): r = form.cleaned_data["quantity"] if r > p.quantity: # raise forms.ValidationError('%s is only available. Request for it or less' % (p.quantity)) qtty = "Available: %d . Enter it or Less." % (p.quantity) form = BuyNowForm() else: buy = form.save(commit=False) buy.user = request.user buy.product = p buy.status = "Not Yet Approved" buy.save() send_mail(email_subject, email_body, '*****@*****.**', [p.user.email]) return HttpResponseRedirect('/accounts/my_transactions/') else: p = get_object_or_404(Product, slug=product_slug) form = TransactionForm() return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def list_transactions(): form = TransactionForm(request.form) return render_template("transactions.html", form=form)
def transaction(): form = TransactionForm() if request.method == 'POST': if form.validate()==False: flash('Preencha todos os campos') return render_template('transaction.html', form=form) else: #Para capturar o conteúdo dos campos str(form.name.data) #Captura dos dados digitados e envio para o endpoint da pagar.me params = { "amount": int(int(form.amount.data)*100), #Valor da transação em centavos "card_number": str(form.card_number.data), #Número do cartão de crédito "card_cvv": str(form.card_cvv.data), #Código de segurança do cartão de crédito "card_expiration_date": str(form.card_expiration_date.data), #Data de expiração do cartão (somente números) "card_holder_name": str(form.card_holder_name.data), #Nome do titular do cartão "customer": { #Informações do cliente "external_id": "#0001", "name": str(form.name.data), "type": "individual", "country": str(form.country.data), "email": str(form.email.data), "documents": [ #Documento do cliente (necessário para o antifraude) { "type": "cpf", "number": str(form.cpf.data) } ], "phone_numbers": ["+5511999998888"], "birthday": "1984-12-03" }, "billing": { #Informações da cobrança (Obrigatório com antifraude) "name": "Capsule Corp", #Entidade de cobrança "address": { #Endereço de cobrança "country": "jp", "state": "Chiyoda", "city": "Tokyo", "neighborhood": "Shogakukan", "street": "Jinbo Cho", "street_number": "3-13", "zipcode": "1000001" } }, "shipping": { #Informações de envio para bens físicos "name": "Capsule Corp", #Entidade de cobrança "fee": "1000", #Custo do envio "delivery_date": "2019-01-14", #Data de entrega no formato YYYY-MM-DD "expedited": True, #Entrega expressa (true or false) "address": { #Endereço de envio "country": str(form.scountry.data), "state": str(form.state.data), "city": str(form.city.data), "neighborhood": str(form.neighborhood.data), "street": str(form.street.data), "street_number": str(form.street_number.data), "zipcode": str(form.zipcode.data) } }, "items": [ #Informações do itens comprados { "id": "c123", #SKU (Unidade de manutenção de estoque) ou número de identificação da loja "title": "Nuvem voadora", #Nome do item vendido "unit_price": int(int(form.amount.data)*100), #Preço unitário "quantity": "1", #Quantidade "tangible": True #Bem tangivel (true or false) } ], #https://docs.pagar.me/v3/docs/split-rules "split_rules": [ #Informações de dois recebedores (split_rule) { "recipient_id": "re_cjqmnxj8o002ywv6e3guj9zbj", #Id do recebedor "percentage": 50, #Porcentagem da transação que irá pro recebedor (Sempre valores redondos 40, 50, 60, etc) pode ser substituído por amount "liable": True, #Se assume os riscos de chargeback (ao menos um deve estar como true) "charge_processing_fee": True #Se será cobrado pelas taxas de transação (ao menos um deve estar como true) },{ "recipient_id": "re_cjq867x4m01fl2p6dq9i32ttf", "percentage": 50, "liable": True, #Está errado na documentação, o true está minúsculo "charge_processing_fee": True #Está errado na documentação, o true está minúsculo } ] } try: transaction = pagarme.transaction.create(params) except: return render_template('transaction-fail.html', form=form) #Fim da interação com a API da Pagar.me return render_template('transaction-complete.html', form=form) elif request.method == 'GET': return render_template('transaction.html', form=form)
def transaction(request): if request.user.is_authenticated(): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = TransactionForm(request.POST) EntryFormSet = formset_factory(EntryForm, extra=10) formset = EntryFormSet(request.POST) # check whether it's valid: if form.is_valid() and formset.is_valid(): # process the data in form.cleaned_data as required in_type = form.cleaned_data['type'] in_party = form.cleaned_data['party'] in_description = form.cleaned_data['description'] # create the transaction # todo be careful because there is a DB hit with create, consider using save transaction = Transaction.objects.create(transaction_type=in_type, transaction_actor=request.user.username, transaction_party=in_party, transaction_description=in_description) # now save the data for each entry in the formset new_entries = [] for entry_form in formset: in_transaction_gkey = transaction in_product = entry_form.cleaned_data.get('product') in_color = entry_form.cleaned_data.get('color') in_quantity = entry_form.cleaned_data.get('quantity') if in_transaction_gkey and in_product and in_color and in_quantity: # Adjust the stock try: product = Product.objects.get(product_name=in_product, product_color=in_color) except Product.DoesNotExist: product = Product(product_name=in_product, product_color=in_color) product.save() try: stk = Stock.objects.get(product_gkey=product) except Stock.DoesNotExist: stk = Stock(product_gkey=product) stk.save() if transaction.transaction_type == 'In': stk.quantity = stk.quantity + in_quantity else: stk.quantity = stk.quantity - in_quantity stk.save() new_entries.append(Entry(transaction_gkey=in_transaction_gkey, product_gkey=product, quantity=in_quantity)) #todo: add try catch #todo: add verification no 2 same product Entry.objects.bulk_create(new_entries) # redirect to a new URL: return render(request,'mafia/index.html') # if a GET (or any other method) we'll create a blank form else: form = TransactionForm() EntryFormSet = formset_factory(EntryForm,extra=10) formset = EntryFormSet() return render(request, 'mafia/transaction.html', {'form': form, 'formset': formset}) else: return render(request, 'mafia/request_login.html')