Пример #1
0
def order_pay():
    """
        Page to pay an order
    """
    coID = request.vars['coID']

    order = Order(coID)
    invoice_id = ''
    mollie_payment_id = ''

    # check if the order belongs to the currently logged in customer
    if not order.order.auth_customer_id == auth.user.id:
        session.flash = T("Unable to show order")
        redirect(URL('cart'))

    mollie = Client()
    mollie_api_key = get_sys_property('mollie_website_profile')
    mollie.set_api_key(mollie_api_key)

    amounts = order.get_amounts()

    # Go to Mollie for payment
    amount = format(amounts.TotalPriceVAT, '.2f')
    description = T('Order') + ' #' + unicode(coID)

    try:
        payment = mollie.payments.create({
            'amount': {
                'currency': CURRENCY,
                'value': amount
            },
            'description':
            description,
            'redirectUrl':
            'https://' + request.env.http_host + '/shop/complete?coID=' +
            unicode(coID),
            'webhookUrl':
            'https://' + request.env.http_host + '/mollie/webhook',
            'metadata': {
                'customers_orders_id': coID
            }
        })

        db.customers_orders_mollie_payment_ids.insert(
            customers_orders_id=coID, mollie_payment_id=payment['id'])

        # Send the customer off to complete the payment.
        redirect(payment.checkout_url)

    except MollieError as e:
        return 'API call failed: ' + e.message
Пример #2
0
def deliver():
    """
        Deliver selected order
    """
    coID = request.vars['coID']

    order = Order(coID)
    order.deliver()

    session.flash = SPAN(
        T('Delivered order '),
        A('#', coID, _href=URL('orders', 'edit', vars={'coID': coID})))

    redirect(URL('orders', 'index'))
Пример #3
0
def webhook_order_paid(coID,
                       payment_amount=None,
                       payment_date=None,
                       mollie_payment_id=None,
                       invoice=True,
                       payment=None):
    """
        :param coID: db.customers_orders.id
        :return: None
    """
    # print('webhook order paid')
    # print(payment)
    order = Order(coID)
    result = order.deliver()

    if result and invoice:
        # Add payment to invoice
        invoice = result['invoice']

        if not invoice is None:
            ipID = invoice.payment_add(
                payment_amount,
                payment_date,
                payment_methods_id=100,  # Static id for Mollie payments
                mollie_payment_id=mollie_payment_id)

    if payment:
        # print("payment found")
        # Check for setting to do initial payment using mollie and
        # The following payments using direct debit
        if get_sys_property(
                "shop_subscriptions_payment_method") == "mollie_directdebit":
            # Check for subscription id in order
            # print("correct sys property")
            subscription_found_in_order = False
            items = order.get_order_items_rows()
            for item in items:
                if item.customers_orders_items.school_subscriptions_id:
                    subscription_found_in_order = True
                    break

            # print(payment)
            # print(subscription_found_in_order)

            if subscription_found_in_order and payment.method == "ideal":

                webhook_order_paid_get_bank_info_from_mollie(
                    order.order.auth_customer_id, payment)
Пример #4
0
def order_cancel():
    """
        Cancel order
    """
    coID = request.vars['coID']
    order = Order(coID)

    permission  = ((auth.has_membership(group_id='Admins') or
                    auth.has_permission('read', 'invoices')) or
                   order.order.auth_customer_id == auth.user.id)

    if not permission:
        return T("Not authorized")

    order.set_status_cancelled()

    redirect(URL('profile', 'orders'))
Пример #5
0
def webhook_order_paid(coID, payment_amount=None, payment_date=None, mollie_payment_id=None, invoice=True):
    """
        :param coID: db.customers_orders.id
        :return: None
    """
    order = Order(coID)
    result = order.deliver()

    if invoice:
        # Add payment to invoice
        invoice = result['invoice']

        if not invoice is None:
            ipID = invoice.payment_add(
                payment_amount,
                payment_date,
                payment_methods_id=100,  # Static id for Mollie payments
                mollie_payment_id=mollie_payment_id
            )
Пример #6
0
    def get_orders_with_items_and_amounts(self):
        """
            Returns orders info for a customer with additional info
        """
        from openstudio.os_order import Order

        db = current.db

        orders = []
        rows = self.get_orders_rows()
        for i, row in enumerate(rows):
            repr_row = list(rows[i:i + 1].render())[0]

            order_obj = Order(row.customers_orders.id)
            order = {}
            order['row'] = row
            order['repr_row'] = repr_row
            order['items'] = order_obj.get_order_items_rows()

            orders.append(order)

        return orders
Пример #7
0
def order():
    """
        Page to show order content
    """
    coID = request.vars['coID']

    features = db.customers_profile_features(1)
    if not features.Orders:
        redirect(URL('profile', 'index'))

    order = Order(coID)
    if not order.order.auth_customer_id == auth.user.id:
        return 'Not authorized'

    rows = order.get_order_items_rows()
    amounts = order.get_amounts()

    response.title = T('Order')
    response.subtitle = T('# ') + coID

    back = os_gui.get_button('back', URL('profile', 'orders'), _class='btn-link')

    return dict(rows=rows, amounts=amounts, order=order.order, back=back)
Пример #8
0
def edit():
    """
        :return: shows order
    """
    response.title = T('Order #') + request.vars['coID']
    response.subtitle = T('Edit')
    response.view = 'general/only_content.html'

    coID = request.vars['coID']

    order = Order(coID)
    cuID = order.order.auth_customer_id
    customer = Customer(cuID)
    # Info table
    info = TABLE(THEAD(
        TR(
            TH(T('Customer')),
            TH(T('Ordered on')),
            TH(T('Status')),
        )),
                 _class='table')

    # Display status
    for field in db.customers_orders:
        field.readable = False
        field.writable = False

    db.customers_orders.Status.readable = True
    db.customers_orders.Status.writable = True

    crud.messages.record_updated = T('Saved')
    form = crud.update(db.customers_orders, coID)

    result = set_form_id_and_get_submit_button(form, 'MainForm')
    form = result['form']
    submit = result['submit']

    form = DIV(
        XML('<form id="MainForm" action="#" enctype="multipart/form-data" method="post">'
            ), form.custom.widget.Status, form.custom.end)

    #status = form

    # status = represent_customers_orders_status(order.order.Status, order.order)
    # Display ordered on
    ordered_on = represent_datetime(order.order.DateCreated, order.order)
    customer_link = A(customer.get_name(),
                      _href=URL('customers', 'edit', args=customer.row.id))
    info.append(TR(TD(customer_link), TD(ordered_on), TD(form)))

    # Info content
    content = DIV(DIV(info, _class='col-md-8 no-padding-left'))

    # Display items
    rows = order.get_order_items_rows()

    header = THEAD(
        TR(
            TH(T('Product')),
            TH(T('Description')),
            TH(SPAN(T('Amount incl. VAT'), _class='right')),
            TH(T("G/L Account")),
            TH(T("Cost center")),
            TH(),
        ))
    table = TABLE(header, _class='table table-striped table-hover order-items')

    for i, row in enumerate(rows):
        repr_row = list(rows[i:i + 1].render())[0]

        table.append(
            TR(
                TD(repr_row.customers_orders_items.ProductName),
                TD(repr_row.customers_orders_items.Description),
                TD(
                    SPAN(repr_row.customers_orders_items.TotalPriceVAT,
                         _class='right')),
                TD(repr_row.customers_orders_items.accounting_glaccounts_id),
                TD(repr_row.customers_orders_items.accounting_costcenters_id),
                TD(),
            ))

    # Display totals
    amounts = order.get_amounts()

    footer = TFOOT(
        TR(
            TD(), TD(B(T('Subtotal'))),
            TD(
                SPAN(CURRSYM,
                     ' ',
                     format(amounts.TotalPrice, '.2f'),
                     _class='bold right')), TD()),
        TR(
            TD(), TD(B(T('VAT'))),
            TD(
                SPAN(CURRSYM,
                     ' ',
                     format(amounts.VAT, '.2f'),
                     _class='bold right')), TD()),
        TR(
            TD(), TD(B(T('Total'))),
            TD(
                SPAN(CURRSYM,
                     ' ',
                     format(amounts.TotalPriceVAT, '.2f'),
                     _class='bold right')), TD()))
    table.append(footer)

    content.append(table)

    # Customer message
    customer_message = ''
    if order.order.CustomerNote:
        customer_message = DIV(
            B(T('Customer message')),
            BR(),
            BR(),
            XML(order.order.CustomerNote.replace("\n", "<br>")),
        )
    content.append(customer_message)

    back = os_gui.get_button('back', edit_get_return_url(cuID))

    return dict(content=content, back=back, save=submit)
Пример #9
0
def order_pay():
    """
        Page to pay an order
    """
    from openstudio.os_customer import Customer
    coID = request.vars['coID']

    order = Order(coID)
    os_customer = Customer(auth.user.id)
    mollie_customer_id = None
    invoice_id = ''
    mollie_payment_id = ''

    # check if the order belongs to the currently logged in customer
    if not order.order.auth_customer_id == auth.user.id:
        session.flash = T("Unable to show order")
        redirect(URL('profile', 'index'))

    # Check if the order contains a class that's been fully booked in the main time
    if order.contains_class():
        cls = order.get_class_object_order_item()
        if cls.get_full() or cls.get_full_bookings_shop():
            redirect(
                URL("shop",
                    "class_full",
                    vars={
                        "clsID": cls.clsID,
                        "date": cls.date.strftime(DATE_FORMAT)
                    }))

    mollie = Client()
    mollie_api_key = get_sys_property('mollie_website_profile')
    mollie.set_api_key(mollie_api_key)

    amounts = order.get_amounts()

    # Go to Mollie for payment
    amount = format(amounts.TotalPriceVAT, '.2f')
    description = T('Order') + ' #' + str(coID)

    if os_customer.row.mollie_customer_id:
        # yep
        mollie_customer_id = os_customer.row.mollie_customer_id
        try:
            mollie_customer = mollie.customers.get(mollie_customer_id)
            # print "we've got one!"
            # print mollie_customer
            # print mollie.customers.all()
        except Exception as e:
            # print e.__class__.__name__
            # print str(e)
            # print 'customer id invalid, create new customer'
            if 'The customer id is invalid' in str(e):
                create_mollie_customer(auth.user.id, mollie)
                os_customer = Customer(auth.user.id)  # refresh
                mollie_customer_id = os_customer.row.mollie_customer_id
    else:
        create_mollie_customer(auth.user.id, mollie)
        os_customer = Customer(auth.user.id)  # refresh
        mollie_customer_id = os_customer.row.mollie_customer_id

    contains_subscription = order.contains_subscription()
    recurring_type = None
    if contains_subscription:
        mandates = os_customer.get_mollie_mandates()
        # set default recurring type, change to recurring if a valid mandate is found.
        recurring_type = 'first'
        if mandates['count'] > 0:
            # background payment
            valid_mandate = False
            for mandate in mandates['_embedded']['mandates']:
                if mandate['status'] == 'valid':
                    valid_mandate = True
                    break

            if valid_mandate:
                # Do a normal payment, probably an automatic payment failed somewhere in the process
                # and customer should pay manually now
                recurring_type = None

    try:
        redirect_url = 'https://' + request.env.http_host + '/shop/complete?coID=' + str(
            coID)

        payment = mollie.payments.create({
            'amount': {
                'currency': CURRENCY,
                'value': amount
            },
            'description':
            description,
            'sequenceType':
            recurring_type,
            'customerId':
            mollie_customer_id,
            'redirectUrl':
            redirect_url,
            'webhookUrl':
            'https://' + request.env.http_host + '/mollie/webhook',
            'metadata': {
                'customers_orders_id': coID
            }
        })

        db.customers_orders_mollie_payment_ids.insert(
            customers_orders_id=coID,
            mollie_payment_id=payment['id'],
            RecurringType=recurring_type)

        # Send the customer off to complete the payment.
        redirect(payment.checkout_url)

    except MollieError as e:
        return 'API call failed: ' + e.message
Пример #10
0
def validate_cart_create_order(cuID, pmID, items):
    """
    :param cuID: db.auth_user.id
    :param items:
    :return:
    """
    from openstudio.os_order import Order

    coID = db.customers_orders.insert(
        auth_customer_id=cuID,
        Status='order_received',
        Origin='pos',
    )
    order = Order(coID)

    # Add items
    for item in items:
        if item['item_type'] == 'product':
            order.order_item_add_product_variant(item['data']['id'],
                                                 item['quantity'])
        elif item['item_type'] == 'classcard':
            order.order_item_add_classcard(item['data']['id'])
        elif item['item_type'] == 'subscription':
            order.order_item_add_subscription(item['data']['id'], TODAY_LOCAL)
        elif item['item_type'] == 'membership':
            order.order_item_add_membership(item['data']['id'], TODAY_LOCAL)
        elif item['item_type'] == 'class_dropin':
            order.order_item_add_class(
                item['data']['clsID'],
                TODAY_LOCAL,
                2  # Attendance Type 2 = drop-in
            )
        elif item['item_type'] == 'class_trial':
            order.order_item_add_class(
                item['data']['clsID'],
                TODAY_LOCAL,
                1  # Attendance Type 1 = trial
            )

    # update order status
    order.set_status_awaiting_payment()

    # mail order to customer
    #    order_received_mail_customer(coID)

    # check if this order needs to be paid or it's free and can be added to the customers' account straight away
    amounts = order.get_amounts()

    # Deliver order, add stuff to customer's account
    result = order.deliver()
    invoice = result['invoice']

    # Add payment
    ipID = invoice.payment_add(
        amounts.TotalPriceVAT,
        TODAY_LOCAL,
        payment_methods_id=pmID,
    )

    return invoice