From 1180b6f7771dbc362434c468f0e3c096b308e967 Mon Sep 17 00:00:00 2001
From: Arnold Moyaux <arm@odoo.com>
Date: Mon, 23 Aug 2021 15:58:47 +0000
Subject: [PATCH] [IMP] mrp: Do not write quantity done on draft line

In the backorder process the operation are done in this order:
1. If the MO has workorders then set the remaining quantity as quantity
producing
2. Confirm the moves

However the system do not expect qty done on draft moves for a lot
of operations.

This commit inverse the order to allow some buisness logique to work
(e.g the analytic accounting)

opw-2469742

closes odoo/odoo#68708

Related: odoo/enterprise#18594
Related: odoo/upgrade#2739
Signed-off-by: Arnold Moyaux <amoyaux@users.noreply.github.com>
---
 addons/mrp/models/mrp_production.py | 15 ++++++++-------
 1 file changed, 8 insertions(+), 7 deletions(-)

diff --git a/addons/mrp/models/mrp_production.py b/addons/mrp/models/mrp_production.py
index 8fd18aa854e6..cdb1858c5799 100644
--- a/addons/mrp/models/mrp_production.py
+++ b/addons/mrp/models/mrp_production.py
@@ -1476,14 +1476,8 @@ class MrpProduction(models.Model):
                         else:
                             move_vals[0]['production_id'] = backorder_mo.id
                         new_moves_vals.append(move_vals[0])
-                new_moves = self.env['stock.move'].create(new_moves_vals)
+                self.env['stock.move'].create(new_moves_vals)
             backorders |= backorder_mo
-            for old_wo, wo in zip(production.workorder_ids, backorder_mo.workorder_ids):
-                wo.qty_produced = max(old_wo.qty_produced - old_wo.qty_producing, 0)
-                if wo.product_tracking == 'serial':
-                    wo.qty_producing = 1
-                else:
-                    wo.qty_producing = wo.qty_remaining
 
             # We need to adapt `duration_expected` on both the original workorders and their
             # backordered workorders. To do that, we use the original `duration_expected` and the
@@ -1506,6 +1500,13 @@ class MrpProduction(models.Model):
         backorders.move_raw_ids.move_line_ids.filtered(lambda ml: ml.product_id.tracking == 'serial' and ml.product_qty == 0).unlink()
         backorders.move_raw_ids._recompute_state()
 
+        for old_wo, wo in zip(self.workorder_ids, backorders.workorder_ids):
+            wo.qty_produced = max(old_wo.qty_produced - old_wo.qty_producing, 0)
+            if wo.product_tracking == 'serial':
+                wo.qty_producing = 1
+            else:
+                wo.qty_producing = wo.qty_remaining
+
         return backorders
 
     def button_mark_done(self):
-- 
GitLab