From 300f7431b219e5d65037afecf97d17d81ed300f0 Mon Sep 17 00:00:00 2001 From: Unai Beristain Date: Mon, 16 Dec 2024 16:22:25 +0100 Subject: [PATCH] [IMP] stock_lot_last_move_locations: Change python with sql for better performance --- stock_lot_last_move_locations/__init__.py | 47 ++++++++++++++++++----- 1 file changed, 37 insertions(+), 10 deletions(-) diff --git a/stock_lot_last_move_locations/__init__.py b/stock_lot_last_move_locations/__init__.py index 7d9b457e68..b79d4d9425 100644 --- a/stock_lot_last_move_locations/__init__.py +++ b/stock_lot_last_move_locations/__init__.py @@ -4,15 +4,42 @@ def _post_install_put_last_move_locations_in_lots(cr, registry): """ - This method will set the production cost on already done manufacturing orders. + Set the last move locations for all lots based on the latest stock move line. """ env = api.Environment(cr, SUPERUSER_ID, {}) - lots = env["stock.lot"].search([]) - for lot in lots: - cond = [("qty_done", ">", 0), ("state", "=", "done"), ("lot_id", "=", lot.id)] - lines = env["stock.move.line"].search(cond) - if lines: - latest_line = lines.sorted(key=lambda line: line.write_date, reverse=True)[ - 0 - ] - latest_line._put_last_move_locations_in_lots() + + query = """ +WITH latest_lines AS ( + SELECT + lot_id, + MAX(write_date) AS max_write_date + FROM + stock_move_line + WHERE + qty_done > 0 AND state = 'done' AND lot_id IS NOT NULL + GROUP BY + lot_id +) +SELECT + sml.lot_id, + l.name AS location_name, + ld.name AS location_dest_name +FROM + stock_move_line sml +INNER JOIN + latest_lines ll ON sml.lot_id = ll.lot_id AND sml.write_date = ll.max_write_date +INNER JOIN + stock_location l ON sml.location_id = l.id +INNER JOIN + stock_location ld ON sml.location_dest_id = ld.id +ORDER BY + sml.write_date DESC; + """ + cr.execute(query) + results = cr.fetchall() + + for _, lot_id, location_name, location_dest_name in results: + last_move_locations = f"{location_name} - {location_dest_name}" + env["stock.lot"].browse(lot_id).write( + {"last_move_locations": last_move_locations} + )