簡體   English   中英

以編程方式將產品添加到購物車 – Odoo 13

[英]Programmatically add products to a cart – Odoo 13

我有一個創建表單的自定義模塊。 根據此表格中的答案,我正在生成訂單行。 用戶發送此表單后,我將使用生成的訂單行中的所有產品創建銷售訂單。

所以從 JavaScript 我發送一個 JSON 與產品購買:

order_data = [{product_id: 1, amount: 10, …},{product_id: 2, …}, …];
note = '';
this._rpc({
        route: '/api/create_order',
        params: { order_products: order_data, note: note }
    }).then((data) => {
        window.location = '/contactus-thank-you';
    }).catch((error) => {
        console.error(error);
    });

然后在 Python 中,我根據 JSON 創建銷售訂單:

@http.route('/api/create_order', type='json', auth='user', website=True)
def create_order(self, **kw):
    uid = http.request.env.context.get('uid')
    partner_id = http.request.env['res.users'].search([('id','=',uid)]).partner_id.id
    
    order_products = kw.get('order_products', [])
    note = kw.get('note', '')
    order_line = []

    for product in order_products:

        amount = 0
        if 'custom_amount' in product:
            amount = product['custom_amount']
        else:
            amount = product['amount']

        if amount > 0:
            order_line.append(
                (0, 0, {
                    'product_id': product['product_id'],
                    'product_uom_qty': amount,
                }))

    order_data = {
        'name': http.request.env['ir.sequence'].with_user(SUPERUSER_ID).next_by_code('sale.order') or _('New'),
        'partner_id': partner_id,
        'order_line': order_line,
        'note': note,
    }

    result_insert_record = http.request.env['sale.order'].with_user(SUPERUSER_ID).create(order_data)
    return result_insert_record.id

但是,我需要使用 Odoo 電子商務插件中的工作流程,而不是直接生成銷售訂單。 這樣用戶可以編輯送貨地址,選擇付款等。所以我想我只需要以編程方式將所有產品放入購物車,然后 rest 將由 Odoo 內置功能處理。 但是怎么做? 我試圖在 Odoo 源代碼中找到一些東西,但很難掌握任何東西。

Odoo 使用典型的銷售訂單來處理購物車內的產品。 但是這個過程並不像僅僅用一些產品創建銷售訂單那么簡單。 Odoo 需要知道哪個訂單與哪個購物車相關聯等。

幸運的是,Odoo 有一種處理它的方法。 有一個sale_get_order()方法,可以讓您獲取當前與購物車鏈接的訂單,或者如果沒有,則創建新訂單。

我不確定它是否記錄在源代碼之外的任何地方,所以這里是代碼的一部分( /addons/website_sale/models/website.py ):

def sale_get_order(self, force_create=False, code=None, update_pricelist=False, force_pricelist=False):
    """ Return the current sales order after mofications specified by params.
    :param bool force_create: Create sales order if not already existing
    :param str code: Code to force a pricelist (promo code)
                        If empty, it's a special case to reset the pricelist with the first available else the default.
    :param bool update_pricelist: Force to recompute all the lines from sales order to adapt the price with the current pricelist.
    :param int force_pricelist: pricelist_id - if set,  we change the pricelist with this one
    :returns: browse record for the current sales order
    """
# ...

我將它與另一種方法_cart_update()一起使用,這讓我可以輕松地更新此訂單中的產品。 還有sale_reset() ,我使用它只是為了確保當前的 session 每次都會更新特定的銷售訂單。

sale_order = request.website.sale_get_order(force_create=True)
request.website.sale_reset()
sale_order.write({'order_line':[(5, 0, 0)]})

for product in order_products:
    sale_order._cart_update(product_id=product['product_id'], line_id=None, add_qty=None, set_qty=product['amount'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM