From 8fffa06efa7905b6d1c875ab0f851c718423f941 Mon Sep 17 00:00:00 2001
From: Adrien Widart <awt@odoo.com>
Date: Wed, 1 Sep 2021 15:08:00 +0000
Subject: [PATCH] [FIX] website_sale: include purchase_price in product changes
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

When changing the pricelist on the shop, if the new one has a different
currency and if the cart already contains some products, the purchase
price of each product should be updated

To reproduce the error:
1. Select Public Pricelist
2. Add the Customizable Desk (Steel, White)
3. Back to shop, select EUR pricelist

Error: Consulting the SO on back-end, the purchase price is not
converted (and therefore the margin is incorrect)

Changing the pricelist on a SO that already contains some lines is not a
valid flow. Therefore, the fix must only concern the web-shop.

When setting a new pricelist, the request gets the current carte and
forces the new pricelist. Therefore, the cart is updated and several
values are computed again:
https://github.com/odoo/odoo/blob/379f1490c93dc599a74add2d678c18fbba1efa62/addons/website_sale/models/sale_order.py#L142-L149
In the above dictionary, the price unit is based on the new pricelist
(new discount, new currency...). When the module `sale_margin` is
installed, this dictionary should include the new value of
`purchase_price`. By doing this, the `margin` will also have a correct
value:
https://github.com/odoo/odoo/blob/194ce17436929b74fc3d4c2744853d32bd9d2567/addons/sale_margin/models/sale_order.py#L64-L67

OPW-2585376

closes odoo/odoo#75885

Signed-off-by: Jérémy Kersten (jke) <jke@openerp.com>
---
 addons/website_sale/models/sale_order.py | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/addons/website_sale/models/sale_order.py b/addons/website_sale/models/sale_order.py
index 526eeabb8415..4c0fd35e4b5c 100644
--- a/addons/website_sale/models/sale_order.py
+++ b/addons/website_sale/models/sale_order.py
@@ -139,7 +139,7 @@ class SaleOrder(models.Model):
                 if order_line:
                     pu = self.env['account.tax']._fix_tax_included_price_company(pu, product.taxes_id, order_line[0].tax_id, self.company_id)
 
-        return {
+        res = {
             'product_id': product_id,
             'product_uom_qty': qty,
             'order_id': order_id,
@@ -147,6 +147,10 @@ class SaleOrder(models.Model):
             'price_unit': pu,
             'discount': discount,
         }
+        if hasattr(self.env['sale.order.line'], '_compute_margin'):
+            # In case sale_margin is installed:
+            res['purchase_price'] = self.env['sale.order.line']._compute_margin(order, product, product.uom_id)
+        return res
 
     @api.multi
     def _get_line_description(self, order_id, product_id, no_variant_attribute_values=None, custom_values=None):
-- 
GitLab