Name

global.UniqueCodeGenerator

Description

This class handles the logic to generate a unique code value for the given filed and table. By default, it generates the unique code for the table cmn_skill_category and the field code .

Script

var UniqueCodeGenerator = Class.create();
UniqueCodeGenerator.prototype = {
  initialize: function() {
  	this.CHARS = "!#$&()*+,-.0123456789:;<?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]`}|{~";
  	this.DEFAULT_TABLE = 'cmn_skill_category';
  	this.DEFAULT_FIELD = 'code';
  },

  generateUniqueCode : function(table, field) {
  	table = table || this.DEFAULT_TABLE;
  	field = field || this.DEFAULT_FIELD;
  	var property = table + '.' + field + '.' + 'last_generated';
  	var mutexName = table + '.' + field + '.lock';
  	var mutex = new GlideMutex(mutexName, mutexName);
  	mutex.setSpinWait(100);
  	mutex.setMaxSpins(1000);
  	var newCode;
  	if (mutex.get()) {
  		try{
  			var lastUsedCode = this.getLastUsedCode(table, field, property);
  			var indices = this.getLastUsedIndex(lastUsedCode);
  			indices = this.getNextIndex(indices);
  			newCode = this.getCode(indices);
  			this.setLastUsedCode(property, newCode);
  		}
  		finally {
  			mutex.release();
  		}
  	}
  	return newCode;
  },

  getLastUsedCode: function(table, field, propertyName) {
  	var gr = new GlideRecord('sys_properties');
  	gr.addQuery('name', propertyName);
  	gr.query();
  	if(gr.next()) {
  		return gr.getValue('value');
  	}
  	else {
  		gr = new GlideRecord(table);
  		gr.orderByDesc('sys_created_on');
  		gr.query();
  		gr.setLimit(1);
  		if(gr.next()) {
  			return gr.getValue(field);
  		}
  	}
  	return '';
  },

  getLastUsedIndex : function(lastUsedCode) {
  	var indices = [0,0,0,-1];
  	if(!gs.nil(lastUsedCode)) {
  		for(var i = 0; i < lastUsedCode.length; i++) {
  			var index = this.CHARS.indexOf(lastUsedCode[i]);
  			indices[i] = index > -1 ? index : 0;
  		}
  	}
  	return indices;
  },

  getNextIndex: function(indices) {
  	for(var i = indices.length - 1; i >= 0; i--) {
  		if(indices[i] < this.CHARS.length - 1) {
  			indices[i] = indices[i] + 1;
  			break;
  		}
  		else {
  			indices[i] = 0;
  		}
  	}
  	return indices;
  },

  getCode: function(indices) {
  	var newCode = '';
  	for(var i = 0; i < indices.length; i++) {
  		newCode = newCode + this.CHARS[indices[i]];
  	}
  	return newCode;
  },

  setLastUsedCode: function(propertyName, code) {
  	var gr = new GlideRecord('sys_properties');
  	gr.addQuery('name', propertyName);
  	gr.query();
  	if(gr.hasNext())
  		gr.next();
  	gr.name = propertyName;
  	gr.type = 'string';
  	gr.value = code;
  	gr.setWorkflow(false);
  	gr.update();
  },

  type: 'UniqueCodeGenerator'
};

Sys ID

77fd7e35b3232300290ea943c6a8dcf8

Offical Documentation

Official Docs: