Skip to content

Commit

Permalink
[IMP] stock_lot_last_move_locations: Change python with sql for bette…
Browse files Browse the repository at this point in the history
…r performance
  • Loading branch information
unaiberis committed Dec 16, 2024
1 parent 9105e41 commit 51bf6d8
Showing 1 changed file with 36 additions and 10 deletions.
46 changes: 36 additions & 10 deletions stock_lot_last_move_locations/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,41 @@

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.id AS move_line_id,
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
"""
cr.execute(query)
results = cr.fetchall()

for move_line_id, 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}
)

0 comments on commit 51bf6d8

Please sign in to comment.