How to Clear Odoo 15 Cart

Viewed 25

Good day, We want to only allow one product order in Odoo Cart, although we are selling all products on our website.

We want a customer to only order one product at a time, so my question is How can I clear the cart in Odoo 15 when it is not empty every time a customer click Add to Cart.

We have thought of changing the add to cart function but we have failed please help.

@http.route(['shop/cart/update'], type='http', auth="public", methods=['POST'], website=True)
def cart_update(self, product_id, add_qty=1, set_qty=0, **kw):
    """This route is called when adding a product to cart (no options)."""
    sale_order = request.website.sale_get_order(force_create=True)
    if sale_order.state != 'draft':
        request.session['sale_order_id'] = None
        sale_order = request.website.sale_get_order(force_create=True)

    product_custom_attribute_values = None
    if kw.get('product_custom_attribute_values'):
        product_custom_attribute_values = json_scriptsafe.loads(kw.get('product_custom_attribute_values'))

    no_variant_attribute_values = None
    if kw.get('no_variant_attribute_values'):
        no_variant_attribute_values = json_scriptsafe.loads(kw.get('no_variant_attribute_values'))

    sale_order._cart_update(
        product_id=int(product_id),
        add_qty=add_qty,
        set_qty=set_qty,
        product_custom_attribute_values=product_custom_attribute_values,
        no_variant_attribute_values=no_variant_attribute_values
    )

    if kw.get('express'):
        return request.redirect("/checkout?express=1")

    return request.redirect("/cart")
1 Answers

You could simple always delete the order_line records from the order in the add_to_cart function.

Would be something like this :

@http.route(['shop/cart/update'], type='http', auth="public", methods=['POST'], website=True)
def cart_update(self, product_id, add_qty=1, set_qty=0, **kw):
    """This route is called when adding a product to cart (no options)."""
    sale_order = request.website.sale_get_order(force_create=True)
    if sale_order.state != 'draft':
        request.session['sale_order_id'] = None
        sale_order = request.website.sale_get_order(force_create=True)
    # Delete the lines if there are some:
    if sale_order.order_line:
        sale_order.order_line.unlink()
    # ...

In case you have an error for unauthorized operation, you'll have to sudo() your sale_order so sale_order.sudo().order_line.unlink()

Related