Ejemplo n.º 1
0
def payment():
    # Create a Payment Form object
    form = PaymentForm()
    # Do if all form fields are valid
    if form.validate_on_submit():
        ## flash('The transaction was submitted for approval.')

        # If the form is POSTed, load it as object and convert to JSON
        if request.method == 'POST':
            # Request key-value pairs from the HTML form
            form_obj = request.form
            # Convert the form data into JSON
            cc_json_data = make_json(form_obj)
            # 'Request' authorization from the credit card service provider
            # using the 'authorize' function.
            auth_response = authorize(cc_json_data)
            
            # Pull approval and amount out of JSON to send to page
            response_dict = json.loads(auth_response)
            approval = response_dict.get('approval')
            amount = response_dict.get('amount')

            # Save the authorization response to the database
            write_auth_to_db(auth_response)
            # Display the authorization response in the page template.
            return render_template('make-payment.html', \
                auth_response=auth_response, approval = approval,\
                amount = amount)
        # Reload page if form does not validate
    return render_template('payment.html', title='Make a Payment', form=form)
Ejemplo n.º 2
0
def send_payment():
    form = PaymentForm()
    formDict = {}
    if (form.validate_on_submit()):
        To = form.To.data
        Success = True
        req_hash = userdata[session['username']]['requested_hash']
        rec_hash = userdata[session['username']]['received_hash']
        print(req_hash, end='*')
        print(rec_hash, end='*')
        if len(req_hash) == 0:
            return 'Transaction Failiure no request sent'
        if req_hash[0] not in rec_hash:
            Success = False
        userdata[session['username']]['payment_request'].pop(0)
        userdata[session['username']]['received_hash'].pop(0)
        userdata[session['username']]['requested_hash'].pop(0)
        if Success:
            formDict['To'] = form.To.data
            formDict['From'] = session['username']
            formDict['Payment'] = form.payment.data
            formDict['Type'] = 'payment_sent'
            supplier_manu = concat(form.To.data, session['username'])
            url = 'http://' + userdata[form.To.data]['host'] + ':' + str(
                userdata[form.To.data]['port']) + '/update'
            r = post(url=url, data=formDict)
            hashr = post(url=validater_data + '/Manu/Sent',
                         data={
                             'supplier_manu': supplier_manu,
                             'sent_payment': form.payment.data
                         })

            return 'Payment Sent'
        return 'Transaction Failiure: requested_hash and received_hash not matching.'
    return render_template('/payment.html', title='Send Payment', form=form)
def index():
    form = PaymentForm()
    if form.validate_on_submit() and request.method == 'POST':
        strategy = choose_strategy(currency=form.currency.data)
        app.logger.info(f"Payment: {request.form.to_dict()}")
        res = strategy.execute(params=request.form.to_dict())
        return res
    return render_template('base.html', form=form)
Ejemplo n.º 4
0
def create_payment_forms(payments, project_owner):
    payment_forms = {}
    for payment in payments:
        # If a payment already contains a category, retrieve it to set
        # this category as the selected category in the drop-down menu
        selected_category = ''
        if payment.category:
            selected_category = payment.category.id
        payment_form = PaymentForm(prefix='payment_form',
                                   **{
                                       'short_user_description':
                                       payment.short_user_description,
                                       'long_user_description':
                                       payment.long_user_description,
                                       'created': payment.created,
                                       'id': payment.id,
                                       'hidden': payment.hidden,
                                       'category_id': selected_category,
                                       'route': payment.route
                                   })

        # The created field may only be edited on manually added transactions
        if payment.type != 'MANUAL':
            del payment_form['created']

        # A project with subprojects can contain multiple editable
        # payments on the project page, so we need to retrieve the
        # categories for each payment (could be made more efficient,
        # but this is readable)
        if payment.subproject:
            payment_form.category_id.choices = payment.subproject.make_category_select_options(
            )
        else:
            payment_form.category_id.choices = payment.project.make_category_select_options(
            )

        payment_form.route.choices = [('subsidie', 'subsidie'),
                                      ('inbesteding', 'inbesteding'),
                                      ('aanbesteding', 'aanbesteding')]

        # Only allow manually added payments to be removed
        if payment.type != 'MANUAL':
            del payment_form.remove

        # Only allow project owners to hide a transaction
        if project_owner:
            payment_form.hidden = payment.hidden

        payment_forms[payment.id] = payment_form

    return payment_forms
Ejemplo n.º 5
0
def index():
    debtor_form = DebtorForm()
    payment_form = PaymentForm()

    return render_template('admin/debtor/index.html',
                           debtor_form=debtor_form,
                           payment_form=payment_form)
Ejemplo n.º 6
0
def purchase():
    form = PaymentForm()
    user = User.query.filter(User.id == current_user.id).first()
    cart = Cart.query.filter(Cart.custID == current_user.id).first()

    if request.method == 'POST' and form.validate_on_submit():
        order = Order(user.username)
        db.session.add(order)
        db.session.commit()
        books = db.session.query(Book).join(
            Cart, Book.bookID == Cart.bookID).filter(
                Cart.custID == current_user.id).all()

        subject = "Order"
        message = "Thank You"
        msg = Message(subject,
                      sender='*****@*****.**',
                      recipients=[user.email])
        msg.body = message
        msg.html = ordr()
        mail.send(msg)

        for book in books:
            #Removing  book from stock
            bk = Book.query.filter(Book.bookID == book.bookID).first()
            bk.stock = Book.stock - 1

            # Recording Sale
            orderIt = OrderItem(order.ordID, book.bookID, book.title,
                                book.author, book.price)
            db.session.add(orderIt)

            #Clearing Cart and Promo
            #for item in cart:

        AppliedPromotion.query.filter(
            AppliedPromotion.cID == cart.cID).delete()
        Cart.query.filter(Cart.custID == current_user.id).delete()
        db.session.commit()
        flash('Order Successfully Completed', 'success')
        checkStock()

        return redirect(url_for('get_books'))

    db.session.commit()

    return render_template("payment.html", form=form)
Ejemplo n.º 7
0
def receive_payment():
    form = PaymentForm()
    formDict = {}
    if (form.validate_on_submit()):
        supplier_manu = concat(form.To.data, session['username'])
        url = 'http://' + userdata[form.To.data]['host'] + ':' + str(
            userdata[form.To.data]['port']) + '/update'
        hashr = post(url=validater_data + '/Supplier/Received',
                     data={
                         'supplier_manu': supplier_manu,
                         'received_payment': form.payment.data
                     })
        if (len(userdata[session['username']]['payment_sent']) == 0):
            return 'No Payments sent for recieving'
        userdata[session['username']]['payment_sent'].pop(0)
        userdata[session['username']]['sent_hash'].pop(0)
        return 'Payment Recieved Acknowledged'
    return render_template('/payment.html', title='Recieve Payment', form=form)
Ejemplo n.º 8
0
def index():
    form = PaymentForm()
    logging.info('Login to the payment page')

    if form.validate_on_submit():

        transaction = Transaction(amount=form.amount.data,
                                  currency=form.currency.data,
                                  description=form.description.data)
        db.session.add(transaction)
        db.session.commit()

        if form.currency.data == 'EUR':

            data_for_send = {
                'amount': str(transaction.amount),
                'currency': CURRENCY_CODE.get(transaction.currency),
                'description': transaction.description,
                'shop_id': SHOP_ID,
                'shop_order_id': str(transaction.id),
            }

            keys = ['amount', 'currency', 'shop_id', 'shop_order_id']
            sign = create_sign(keys, data_for_send)
            data_for_send.update({'sign': sign})

            transaction_send = TransactionSend(transaction_id=transaction.id,
                                               request=str(data_for_send),
                                               response=None)
            db.session.add(transaction_send)
            db.session.commit()

            logging.info(f'Запрос: {data_for_send}')

            return render_template('direct.html',
                                   data=data_for_send,
                                   url_=URL_PIASTRIX_EN)

        elif form.currency.data == 'USD':

            headers = {'Content-Type': 'application/json'}
            data_for_send = {
                "payer_currency": CURRENCY_CODE.get(transaction.currency),
                "shop_amount": str(transaction.amount),
                "shop_currency": CURRENCY_CODE.get(transaction.currency),
                "shop_id": SHOP_ID,
                "shop_order_id": str(transaction.id),
            }

            keys = [
                'shop_amount', 'shop_currency', 'shop_id', 'shop_order_id',
                'payer_currency'
            ]
            sign = create_sign(keys, data_for_send)
            data_for_send.update({'sign': sign})

            logging.info(f'Запрос: {data_for_send}')

            try:
                response_json = requests.post(URL_PIASTRIX_BILL_CRATE,
                                              json=data_for_send,
                                              headers=headers)
            except Exception as e:
                logging.error(f'Ошибка сети. Ошибка: {e}')
                return

            if not response_json:
                logging.error(
                    'Провайдер вернул пустой ответ, или возникла ошибка обработке ответа провайдера'
                )
                return

            response = json.loads(response_json.content)

            logging.info(f'Ответ: {response}')

            transaction_send = TransactionSend(transaction_id=transaction.id,
                                               request=str(data_for_send),
                                               response=str(response))
            db.session.add(transaction_send)
            db.session.commit()

            if not response.get('result'):
                logging.error('В ответе провайдера нет поля "result"')
                return

            url = response.get('data', {}).get('url')

            return redirect(url, code=302)

        elif form.currency.data == 'RUB':

            headers = {'Content-Type': 'application/json'}
            data_for_send = {
                "amount": str(transaction.amount),
                "currency": CURRENCY_CODE.get(transaction.currency),
                "payway": PAYWAY,
                "shop_id": SHOP_ID,
                "shop_order_id": str(transaction.id),
            }

            keys = ['amount', 'currency', 'payway', 'shop_id', 'shop_order_id']
            sign = create_sign(keys, data_for_send)
            data_for_send.update({'sign': sign})

            logging.info(f'Запрос: {data_for_send}')

            try:
                response_json = requests.post(URL_PIASTRIX_INVOICE_CRATE,
                                              json=data_for_send,
                                              headers=headers)
            except Exception as e:
                logging.error(f'Ошибка сети. Ошибка: {e}')
                return

            if not response_json:
                logging.error(
                    'Провайдер вернул пустой ответ, или возникла ошибка обработке ответа провайдера'
                )
                return

            response = json.loads(response_json.content)

            logging.info(f'Ответ: {response}')

            transaction_send = TransactionSend(transaction_id=transaction.id,
                                               request=str(data_for_send),
                                               response=str(response))
            db.session.add(transaction_send)
            db.session.commit()

            if not response.get('result'):
                logging.error('В ответе провайдера нет поля "result"')
                return

            return render_template(
                'invoice.html',
                method_=response.get('data', {}).get('method'),
                url=response.get('data', {}).get('url'),
                data=response.get('data', {}).get('data'),
            )

    return render_template('index.html', title='Home', form=form)
Ejemplo n.º 9
0
def process_payment_form(request, project_or_subproject, project_owner,
                         user_subproject_ids, is_subproject):
    payment_form = PaymentForm(prefix="payment_form")
    # Somehow we need to repopulate the category_id.choices with the same
    # values as used when the form was generated. Probably to validate
    # if the selected value is valid. We don't know the subproject in the
    # case of an edited payment on a project page which contains subprojects,
    # so we need to retrieve this before running validate_on_submit
    temppayment = Payment.query.filter_by(id=payment_form.id.data).first()
    if temppayment:
        if temppayment.subproject:
            payment_form.category_id.choices = temppayment.subproject.make_category_select_options(
            )
        else:
            payment_form.category_id.choices = temppayment.project.make_category_select_options(
            )

        # Make sure the user is allowed to edit this payment
        # (especially needed when a normal users edits a subproject
        # payment on a project page)
        if not project_owner and not temppayment.subproject.id in user_subproject_ids:
            return
    else:
        return

    payment_form.route.choices = [('subsidie', 'subsidie'),
                                  ('inbesteding', 'inbesteding'),
                                  ('aanbesteding', 'aanbesteding')]

    # When the user removes a manually added payment, the route selection
    # field will have no value and validate_on_submit will fail, so add a
    # default value
    if payment_form.route.data == 'None':
        payment_form.route.data = 'subsidie'

    if payment_form.validate_on_submit():
        # Remove payment
        if payment_form.remove.data:
            Payment.query.filter_by(id=payment_form.id.data).delete()
            db.session.commit()
            flash(
                '<span class="text-default-green">Transactie is verwijderd</span>'
            )
        # Get data from the form
        else:
            new_payment_data = {}
            for f in payment_form:
                if f.type != 'SubmitField' and f.type != 'CSRFTokenField':
                    # If the category is edited to be empty again, make
                    # sure to set it to None instead of ''
                    if f.short_name == 'category_id':
                        if f.data == '':
                            new_payment_data[f.short_name] = None
                        else:
                            new_payment_data[f.short_name] = f.data
                    else:
                        new_payment_data[f.short_name] = f.data

            try:
                # Update if the payment already exists
                payments = Payment.query.filter_by(id=payment_form.id.data)

                # In case of a manual payment we update the updated field with
                # the current timestamp
                if payments.first().type == 'MANUAL':
                    new_payment_data['updated'] = datetime.now()

                # In case of non-manual payments we don't allow the modification
                # of the 'created' field, so we need to fill in the form with
                # created timestamp that already exists
                if payments.first().type != 'MANUAL':
                    new_payment_data['created'] = payments.first().created

                if len(payments.all()):
                    payments.update(new_payment_data)
                    db.session.commit()
                    flash(
                        '<span class="text-default-green">Transactie is bijgewerkt</span>'
                    )
            except IntegrityError as e:
                db.session().rollback()
                app.logger.error(repr(e))
                flash(
                    '<span class="text-default-red">Transactie bijwerken mislukt<span>'
                )

        if is_subproject:
            # Redirect back to clear form data
            return redirect(
                url_for('subproject',
                        project_id=project_or_subproject.project_id,
                        subproject_id=project_or_subproject.id))

        # Redirect back to clear form data
        return redirect(
            url_for(
                'project',
                project_id=project_or_subproject.id,
            ))
    else:
        flash_form_errors(payment_form, request)
Ejemplo n.º 10
0
def processing():
    form = PaymentForm()
    return render_template('processing.html', title ='Payment', form=form)