from odoo import models, _ from odoo.exceptions import UserError class MrpProduction(models.Model): _inherit = 'mrp.production' def _prepare_stock_lot_values(self): self.ensure_one() name = False product = self.product_id tmpl = product.product_tmpl_id seq = getattr(tmpl, 'lot_sequence_id', False) if seq: tried = set() # Try generating a unique candidate from the per-product sequence for _i in range(10): candidate = seq.next_by_id() if not candidate: break if candidate in tried: continue tried.add(candidate) exist_lot = self.env['stock.lot'].search([ ('product_id', '=', product.id), '|', ('company_id', '=', False), ('company_id', '=', self.company_id.id), ('name', '=', candidate), ], limit=1) if not exist_lot: name = candidate break # Fallback to default behavior if no per-product candidate was found if not name: name = self.env['ir.sequence'].next_by_code('stock.lot.serial') exist_lot = (not name) or self.env['stock.lot'].search([ ('product_id', '=', product.id), '|', ('company_id', '=', False), ('company_id', '=', self.company_id.id), ('name', '=', name), ], limit=1) if exist_lot: name = self.env['stock.lot']._get_next_serial(self.company_id, product) if not name: raise UserError(_("Please set the first Serial Number or a default sequence")) return { 'product_id': product.id, 'name': name, }