As a SAM Agent I want a sorting job that sets "Next version" based on version field.

may13
Tera Contributor

Hello Team, please help me with the following requirement on how to write a script to include

 

Given I am a SAM PO 

When Version field is NOT NULL
Then I want

  1. A job running every night at 1
  2. Calling the script include
    1. Expected functionality:
      1. Take all SW Models with the same name 
      2. For each take "version" - Use regex to compare the xx.yyy.z Version syntax
      3. Sort them by version And in the sequence, put "Next version" Reference

 

6 REPLIES 6

Robert H
Mega Sage

Hello @may13 ,

 

It's a bit hard to understand that requirement, but I guess you are looking for something like this:

If you have three Software Models, e.g.

  • Adobe Acrobat, Version 1.0
  • Adobe Acrobat, Version 2.0
  • Adobe Acrobat, Version 2.5

You want the "Next version" of "Adobe Acrobat, Version 1.0" to be set to "Version 2.0", and for "Adobe Acrobat, Version 2.0" to be set to "Version 2.5". Is that correct?

 

Regards,

Robert

 

Regards,

Robert

may13
Tera Contributor

@Robert H  Yes Correct .

Hello @may13 ,

 

Ok, there you go:

// query all models with non-empty name and version
var gr = new GlideRecord('cmdb_software_product_model');
gr.addNotNullQuery('name');
gr.addNotNullQuery('version');
gr.query();

// store the sys_ids and versions of models that have the same name
var modelNames = {};
while (gr.next()) {
	var name = gr.getValue('name'),
		details = { id: gr.getUniqueValue(), version: gr.getValue('version') };
	if (!modelNames[name]) {
		modelNames[name] = [];
	}
	modelNames[name].push(details);
}

// sort function for version numbers
function sortByVersion(a, b) {
	var aElements = a.version.split('.'),
		bElements = b.version.split('.'),
		commonLength = Math.min(aElements.length, bElements.length),
		i = 0;
	
	while (i < commonLength && aElements[i] === bElements[i]) i++;
	
	if (i === commonLength) return aElements.length - bElements.length;
	if (!isNaN(aElements[i]) && !isNaN(bElements[i])) return aElements[i] - bElements[i];
	return aElements[i].localeCompare(bElements[i]);
}

// function for updating the next version of a model record
function setNextVersionOnModel(id, nextVersion) {
	var gr = new GlideRecord('cmdb_software_product_model');
	if (gr.get(id)) {
		gr.setValue('next_version', nextVersion);
		gr.update();
	}
}

// putting it all together
for (var m in modelNames) {
	var details = modelNames[m];
	if (details.length === 1) continue; // only continue if we have more than one model with the same name
	var sorted = details.sort(sortByVersion);
	for (var i = details.length - 1; i > 0; i--) {
		setNextVersionOnModel(sorted[i-1].id, sorted[i].id);
	}
}

 

Result:

RobertH_0-1743495448184.png

 

Regards,

Robert

may13
Tera Contributor

HI @Robert H  where I need to write this script ?