Hello,
I am experiencing an issue with an automated script in Odoo that is supposed to add a reference product to a sales order line. The script is meant to add only one reference product line when a sales order line is created or modified. However, when I exit and return to the order, I find that multiple lines of the same reference product have been added.
Problem Description:
When I save a sales order, everything appears to function correctly, and only one reference product line is added as expected. However, if I leave the order and come back to it, I see that eight lines of the reference product have been added to the order, which is not the intended behavior. The script should ensure that only one line of the reference product is added per product in the order, regardless of how many times the order is saved or revisited.
I am seeking assistance to understand why this behavior is occurring and how I might modify the script or configurations in Odoo to resolve this issue. Any suggestions or guidance would be greatly appreciated.
Thank you in advance for your help and suggestions.
Code Used:
Here is the script I am currently using:
if record:
# Obtain the reference product from the custom field
product_reference = record.product_id.product_tmpl_id.x_studio_key_ring
if product_reference:
# Check if the reference product has already been added to the order
already_added = any(line.product_id == product_reference for line in record.order_id.order_line if line.id != record.id)
if not already_added:
# Determine if the reference product is a variant or a template
if product_reference.product_variant_count == 1:
product_to_add = product_reference.product_variant_id # Use the single variant
elif product_reference.product_variant_count > 1:
product_to_add = product_reference.product_variant_ids[0] # Take the first available variant
else:
product_to_add = product_reference # Use the template if no variants are specified
# Create the new order line for the reference product
new_line = env['sale.order.line'].create({
'order_id': record.order_id.id,
'product_id': product_to_add.id,
'product_uom_qty': 1, # Add only one unit of the reference product
'price_unit': product_to_add.lst_price,
})