diff --git a/stock_inventory_product_exhausted/models/stock_inventory.py b/stock_inventory_product_exhausted/models/stock_inventory.py index cad759e..910f029 100644 --- a/stock_inventory_product_exhausted/models/stock_inventory.py +++ b/stock_inventory_product_exhausted/models/stock_inventory.py @@ -44,7 +44,9 @@ class StockInventory(models.Model): quants_to_create = [] for location in locations: - for product in products.filtered(lambda p: p.type == "product"): + for product in products.filtered( + lambda p: p.type == "product" and p.active + ): if (product.id, location.id) not in existing_combinations: _logger.debug( "Creating zero quant for product %s in location %s", @@ -103,14 +105,28 @@ class StockQuant(models.Model): @api.model def _unlink_zero_quants(self): - """Prevent automatic unlinking of zero quants. + """Override to only unlink zero quants for archived products. - This method overrides the default behavior to prevent - zero quants from being automatically removed. - This may need review to ensure it doesn't conflict - with standard Odoo behavior. + This method modifies the default behavior to preserve zero quants + for active products while still removing them for archived products. + This is useful when using the 'Include Exhausted Products' feature. """ - if self.product_tmpl_id.active: - _logger.debug("Preventing automatic unlinking of zero quants") - else: - super()._unlink_zero_quants() + precision_digits = max( + 6, self.sudo().env.ref("product.decimal_product_uom").digits * 2 + ) + # Use a select instead of ORM search for UoM robustness. + # Join with product_product and product_template to check if product is active + query = """SELECT sq.id FROM stock_quant sq + INNER JOIN product_product pp ON sq.product_id = pp.id + INNER JOIN product_template pt ON pp.product_tmpl_id = pt.id + WHERE (round(sq.quantity::numeric, %s) = 0 OR sq.quantity IS NULL) + AND round(sq.reserved_quantity::numeric, %s) = 0 + AND (round(sq.inventory_quantity::numeric, %s) = 0 OR sq.inventory_quantity IS NULL) + AND sq.user_id IS NULL + AND (pp.active = false OR pt.active = false);""" + params = (precision_digits, precision_digits, precision_digits) + self.env.cr.execute(query, params) + quant_ids = self.env["stock.quant"].browse( + [quant["id"] for quant in self.env.cr.dictfetchall()] + ) + quant_ids.sudo().unlink()