How to get different userID and email for the same fname, lname wen submitted the record producer

Ram33843094
Tera Contributor

Need script to update userid as userid, userid0 , userid1 and email as test.abc@gmail.com , test.abc0@gmail.com etc.

each time when we submit the form using same first name and last name, as organisation may have multiple users having same name. So that there wont be any duplicates.

 

When im trying to code, values are getting updated in the same profile, but not generating new profiles and new userids and email like userid0,userid1 ,  test.abc0@gmail.com etc

 

Attached OOTB script include(hr_sysUser), where the logic of userid from firstname and lastname mentioned.

 

Userid code :

 

(function executeRule(current, previous /*null when async*/) {

 

var fname = current.first_name;
var lname = current.last_name;
var firstLetter = fname.slice(0,1);

 

var count = (gs.getProperty("sn_hr_core.profile.max.tries", 50));
for (var suffix = 0; suffix < count; ++suffix) {
var userName = firstLetter + lname +suffix;
current.user_name=userName;

current.update();
}

}

 

Email Field code:

 

(function executeRule(current, previous /*null when async*/) {

var first = current.first_name;

var last = current.last_name;

 

var count = (gs.getProperty("sn_hr_core.profile.max.tries", 50));
for (var suffix = 0; suffix < count; ++suffix) {

var userName = first + "." + last + suffix + '@gmail.com';

current.email=userName;
current.update();
}

})(current, previous);

 

@Ankur Bawiskar 

10 REPLIES 10

Sandeep Rajput
Tera Patron
Tera Patron

@Ram33843094 

 

May I know the reason why you are handling the user name logic separately when it is already handled within sn_hr_core.hr_SysUser script include using the following method.

 

generateUserName: function(first_name, last_name) {
        var userName = first_name + "." + last_name;
        var record = new GlideRecord(hr.TABLE_USER);
        if (!record.get("user_name", userName))
            return userName.toLowerCase();

        var count = (gs.getProperty("sn_hr_core.profile.max.tries", 50));
        for (var suffix = 0; suffix < count; ++suffix) {
            record = new GlideRecord("sys_user");
            userName = first_name + "." + last_name + suffix;
            if (!record.get("user_name", userName))
                return userName.toLowerCase(); 
        }
        gs.debug("[hr_SysUser] Cannot generate user name for " + first_name + ", " + last_name);
        return null;
    },

What this code does is, it takes value of first name and last name and merges them using a (.) e.g. john.doe and checks if this username already exists within sys_user table if does then it appends a suffix starting from 0 and goes up to 49 e.g. john.doe0 to john.doe49 to check if this user already exists if it doesn't find the record it creates one otherwise after checking for 50 times it finally gives up by throwing an error cannot generate user name. 

 

Since the username generation is already taken care of, you simply need to focus on the email part.

 

Create an onBefore insert business rule on sys_user table and set the value of email field = current.username+<your company domain>.com

 

Since the username is taken care of my the sn_hr_core.hr_SysUser script include you will always get the username in <first_name.last_name01> format and you can use this username to form the email address for your new hire. In this case the work email would be simply set to 

 

current.work_email = current.username+'<your company domain>.com';

 Hope this helps.

Hi Sandeep,

 

Thanks for the reply.  The Username logic which Im looking for is : firstletter of firstname + lastname + suffix(if duplicate found)

Thats the reason i wud like to change the OOTB script include. 

 

Email required : firstname.lastname@domain.com

Yes if i use OOTB username logic, I can directly set the email value from username as you suggested.

But here my username requirement is different.

Please let me know if you can provide any script for the same.

 

@Sandeep Rajput @Ankur Bawiskar 

In this case you would need to change the logic of user name generation in sn_hr_core.hr_SysUser script include. Make following changes in this method.

generateUserName: function(first_name, last_name) {
        var userName = first_name.slice(0,1) + "." + last_name;
        var record = new GlideRecord(hr.TABLE_USER);
        if (!record.get("user_name", userName))
            return userName.toLowerCase();

        var count = (gs.getProperty("sn_hr_core.profile.max.tries", 50));
        for (var suffix = 0; suffix < count; ++suffix) {
            record = new GlideRecord("sys_user");
            userName = first_name.slice(0,1)  + "." + last_name + suffix;
            if (!record.get("user_name", userName))
                return userName.toLowerCase(); 
        }
        gs.debug("[hr_SysUser] Cannot generate user name for " + first_name + ", " + last_name);
        return null;
    },

Caution: Please be informed that this is an OOTB script include and any changes here will prevent this script include from future upgrades. You will have to merge the latest changes during upgrades if anything changes from ServiceNow's end in this script include.

 

For email. Please create a before insert business rule on sys_user table and put the following code.

Here are the screenshot of how your business rule should look like 

Screenshot 2023-04-03 at 9.10.31 AM.pngScreenshot 2023-04-03 at 9.12.25 AM.png

Here is how the business rule script.

(function executeRule(current, previous /*null when async*/ ) {

    //Generate email for the user
    // Add your code here
    var email = generateEmail(current.first_name + '', current.last_name + '', '@example.com');
    if (email) {
        current.email = email + '';
    }
    // Add your code here
    function generateEmail(first_name, last_name, domain) {
        var email = first_name + "." + last_name + domain;
        email = email.toLowerCase();
        var record = new GlideRecord('sys_user');
        if (!record.get("email", email))
            return email;

        var count = (gs.getProperty("sn_hr_core.profile.max.tries", 50));
        for (var suffix = 0; suffix < count; ++suffix) {
            record = new GlideRecord("sys_user");
            email = first_name + "." + last_name + suffix + domain;
            email = email.toLowerCase();
            if (!record.get("email", email))
                return email;
        }
        gs.debug("Cannot generate user email for " + first_name + ", " + last_name);
        return null;
    }

})(current, previous);

Hope this helps.

Hi Sandeep,

 

Got to know that it is not recommended to change OOTB script include logic. Keeping that aside, the username logic defined in hr_sysuser SI has been interlinked to some other fields on OOTB RP form like  personal_email etc. 

Im my customised record producer form, we dont have/need email field to enter manually.

 

Altogether Im looking for a separate username and email logic on user profile irrespective of what has been defined on hr_profile and hr_sys user script includes.

 

Trying to execute below after BR, but no luck :

 

(function executeRule(current, previous /*null when async*/) {

var first = current.first_name;

var last = current.last_name;


var firstLetter = first.slice(0,1);
var firstlast;


var user_ref;


var MAX_ATTEMPT = 1000;

 


var possibleMatches = findPossibleMatches(first, last);


var validName = false;


for (var i = 1; i <= firstlast.length; i++) {


//set base username/email

firstlast = firstLetter + last;

var email = first + "." + last + '@gmail.com';


if (!usernameExists(firstlast, email, possibleMatches)) {


//username and email are unique

validName = true;

user_ref = createUser(first, last, email, firstlast);
current.user_name=firstlast;
current.email=email;
break;

 

 

 

 

}


}


if (!validName){


for (var j = 1; j < MAX_ATTEMPT; j++){


var usernameNr = firstlast + j;


var emails = first + "." + last + j + '@gmail.com';


if (!usernameExists(usernameNr, emails, possibleMatches)){


user_ref = createUser(first, last, emails, usernameNr);

current.user_name=usernameNr;
current.email=emails;

break;

 


}


}


}

 

 

 

function usernameExists(username, email, possibleMatches){


return possibleMatches.indexOf(username) > -1 || possibleMatches.indexOf(email) > -1;


}

 

function createUser(first, last, email, firstlast) {


gs.log(firstlast);


var newUser = new GlideRecord('sys_user');


newUser.first_name = first;

newUser.last_name = last;


newUser.email = email;


newUser.user_name = firstlast;


var userSysID = newUser.insert();


return userSysID;


}

 

function findPossibleMatches(first, last){


var grGet = new GlideRecord('sys_user');

 

 

grGet.addEncodedQuery('user_nameSTARTSWITH' + firstLetter + '^user_nameLIKE' + last + '^NQemailSTARTSWITH'+ first +'^emailLIKE'+"."+'^emailLIKE' + last);


grGet.query();


var possibleMatches = [];


while (grGet.next()){


possibleMatches.push(grGet.user_name + "");


possibleMatches.push(grGet.email + "");


}


return possibleMatches;


}

 

 

 

 

})(current, previous);

 

@Sandeep Rajput