'Creates an extra move if necessary depending on extra quantities than foreseen or extra moves'

@api.multi
def _create_extra_move(self):

    self.ensure_one()
    quantity_to_split = 0
    uom_qty_to_split = 0
    extra_move = self.env['stock.move']
    rounding = self.product_uom.rounding
    link_procurement = False
    if (self.procurement_id and self.production_id and (float_compare(self.production_id.qty_produced, self.procurement_id.product_qty, precision_rounding=rounding) > 0)):
        done_moves_total = sum(self.production_id.move_finished_ids.filtered((lambda x: ((x.product_id == self.product_id) and (x.state == 'done')))).mapped('product_uom_qty'))
        if (float_compare(done_moves_total, self.procurement_id.product_qty, precision_rounding=rounding) >= 0):
            quantity_to_split = 0
            if (float_compare(self.product_uom_qty, self.quantity_done, precision_rounding=rounding) < 0):
                self.product_uom_qty = self.quantity_done
        else:
            quantity_to_split = ((done_moves_total + self.quantity_done) - self.procurement_id.product_qty)
            uom_qty_to_split = (self.product_uom_qty - (self.quantity_done - quantity_to_split))
            if (float_compare(uom_qty_to_split, quantity_to_split, precision_rounding=rounding) < 0):
                uom_qty_to_split = quantity_to_split
            self.product_uom_qty = (self.quantity_done - quantity_to_split)
    elif (float_compare(self.quantity_done, self.product_uom_qty, precision_rounding=rounding) > 0):
        quantity_to_split = (self.quantity_done - self.product_uom_qty)
        uom_qty_to_split = quantity_to_split
        link_procurement = True
    if quantity_to_split:
        extra_move = self.copy(default={'quantity_done': quantity_to_split, 'product_uom_qty': uom_qty_to_split, 'production_id': self.production_id.id, 'raw_material_production_id': self.raw_material_production_id.id, 'procurement_id': ((link_procurement and self.procurement_id.id) or False)})
        extra_move.action_confirm()
        if (self.has_tracking != 'none'):
            qty_todo = (self.quantity_done - quantity_to_split)
            for movelot in self.move_lot_ids.filtered((lambda x: x.done_wo)):
                if (movelot.quantity_done and movelot.done_wo):
                    if (float_compare(qty_todo, movelot.quantity_done, precision_rounding=rounding) >= 0):
                        qty_todo -= movelot.quantity_done
                    elif (float_compare(qty_todo, 0, precision_rounding=rounding) > 0):
                        remaining = (movelot.quantity_done - qty_todo)
                        movelot.quantity_done = qty_todo
                        movelot.copy(default={'move_id': extra_move.id, 'quantity_done': remaining})
                        qty_todo = 0
                    else:
                        movelot.move_id = extra_move.id
        else:
            self.quantity_done -= quantity_to_split
    return extra_move
