From e53218964a5088cad0b2fa36390b62bd59e1fda6 Mon Sep 17 00:00:00 2001
From: Nicolas Martinelli <nim@odoo.com>
Date: Tue, 14 Jul 2020 07:32:13 +0000
Subject: [PATCH] [FIX] stock: merge quants when unpacking

1. Create a new location of type internal in WH/Test
2. Create a new product P with availability of 100.0 in WH/Stock
3. Create a new transfer from WH/Stock to WH/Test with 50.0 units of P,
   Put in Pack and Validate
4. Create a new transfer from WH/Test to WH/Stock/Shelf 1 using the
   previous package, Validate and Unpack
5. Repeat steps from 3 and 4
6. Create a new transfer from WH/Stock/Shelf 1 to Customer with 100.0 units of P
7. Review stock quant from the location WH/Stock/Shelf 1

2 quants of the same product in the location WH/Stock/Shelf 1: one
negative with -50.0 and another positive with 50.0

The step 4 creates 2 quants of 50.0 units, which are reserved at step 6.
However, when validating the transfer 100.0 units are taken from one of
the quants.

To prevent this situation, we run the quant vacuum process after
unpacking. This will merge the 2 quants of 50.0 and prevent any future
negative quant creation. We also clean zero quants, although this is not
mandatory to fix our use case.

Closes #53535
opw-2283707

closes odoo/odoo#54431

X-original-commit: f7168311f4333f7fc684e00e1c1c284981718335
Signed-off-by: Nicolas Martinelli (nim) <nim@odoo.com>
---
 addons/stock/models/stock_quant.py | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/addons/stock/models/stock_quant.py b/addons/stock/models/stock_quant.py
index 0eea2f21a7c4..d1fbd37b952b 100644
--- a/addons/stock/models/stock_quant.py
+++ b/addons/stock/models/stock_quant.py
@@ -712,6 +712,11 @@ class QuantPackage(models.Model):
             move_line_to_modify.write({'package_id': False})
             package.mapped('quant_ids').sudo().write({'package_id': False})
 
+        # Quant clean-up, mostly to avoid multiple quants of the same product. For example, unpack
+        # 2 packages of 50, then reserve 100 => a quant of -50 is created at transfer validation.
+        self.env['stock.quant']._merge_quants()
+        self.env['stock.quant']._unlink_zero_quants()
+
     def action_view_picking(self):
         action = self.env.ref('stock.action_picking_tree_all').read()[0]
         domain = ['|', ('result_package_id', 'in', self.ids), ('package_id', 'in', self.ids)]
-- 
GitLab