From e5ab8cf9623bc436f43706926bc6ee596c549244 Mon Sep 17 00:00:00 2001
From: "Tiffany Chang (tic)" <tic@odoo.com>
Date: Thu, 17 Dec 2020 10:56:50 +0000
Subject: [PATCH] [FIX] stock: make package level package consistent

Currently a package level is created and has the newly created package
assigned to it when "Put In Pack" is used. Unfortunately if a move line
has its result_package_id changed after having a package assigned via
the Put In Pack, then the package level's package_id isn't correctly
updated. This leads to incorrect data in the db. This incorrect data
doesn't affect much since result_package_id from an entire package move
cannot be changed in any views, but it does mean that the created
package associated with the package level can never be deleted even if
it's never used.

Steps to reproduce:
1. active (delivery) packages in settings
2. create a picking and create some done values
3. use "Put In Pack" to put done move lines into a package
4. change the newly created Destination Package to another package
5. Go to Packages and try to delete the package created by Put In Pack

Expected result: able to delete the package
Actual result: Server error that package is still required by Stock
Package Level.

This is a short term fix. In the long run it would be better to fix the
package_level logic so it isn't unnecessarily assigned to moves/move
lines and/or updates in a cleaner way.

Task ID: 2418907

closes odoo/odoo#63544

Signed-off-by: Arnold Moyaux <amoyaux@users.noreply.github.com>
---
 addons/stock/models/stock_move_line.py | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/addons/stock/models/stock_move_line.py b/addons/stock/models/stock_move_line.py
index 05320555a0ad..9f4461d22369 100644
--- a/addons/stock/models/stock_move_line.py
+++ b/addons/stock/models/stock_move_line.py
@@ -235,6 +235,16 @@ class StockMoveLine(models.Model):
             if key in vals:
                 updates[key] = self.env[model].browse(vals[key])
 
+        if 'result_package_id' in updates:
+            for ml in self.filtered(lambda ml: ml.package_level_id):
+                if updates.get('result_package_id'):
+                    ml.package_level_id.package_id = updates.get('result_package_id')
+                else:
+                    # TODO: make package levels less of a pain and fix this
+                    package_level = ml.package_level_id
+                    ml.package_level_id = False
+                    package_level.unlink()
+
         # When we try to write on a reserved move line any fields from `triggers` or directly
         # `product_uom_qty` (the actual reserved quantity), we need to make sure the associated
         # quants are correctly updated in order to not make them out of sync (i.e. the sum of the
-- 
GitLab