User Criteria based on user manager's company

Angel32
Tera Contributor

Hi,

 

I'm desperately trying to set a user criteria depending of the company of the user and the user's manager.

So far among other things, I've tried adding the following script using the advanced mode of the user criteria with no luck.

Any idea of what I'm doing wrong ?

 

// Condition: utilisateur.company == targetCompanySysId OU manager.company == targetCompanySysId

answer = (function() {
var targetCompanySysId = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; // xxxxxxx

// Current user
var userId = gs.getUserID().toString();
if (!userId) return false;

var u = new GlideRecord('sys_user');
if (!u.get(userId)) return false;

// --- user company ---
var userCompanyId = u.getValue('company');
if (userCompanyId && userCompanyId === targetCompanySysId) {
return true;
}

var managerId = u.getValue('manager'); 
if (!managerId) return false;

var m = new GlideRecord('sys_user');
if (!m.get(managerId)) return false;

var managerCompanyId = m.getValue('company');
if (!managerCompanyId) return false;

return managerCompanyId === targetCompanySysId;
})();

6 REPLIES 6

TomKwon
Kilo Contributor

In Advanced User Criteria, you should not use gs.getUserID() or other session APIs. The script is evaluated against a user record and ServiceNow provides a predefined variable called user_id for that purpose. Using gs.getUserID() can return the logged in user, which fails in cases where the platform evaluates criteria for someone else. 

 

Use this instead.

 

answer = (function () {
var targetCompanySysId = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

// user_id is provided by User Criteria evaluation context
if (!user_id) return false;

var u = new GlideRecord('sys_user');
if (!u.get(user_id)) return false;

// user company match
if (u.company == targetCompanySysId) return true;

// manager company match
if (!u.manager) return false;

var m = new GlideRecord('sys_user');
if (!m.get(u.manager)) return false;

return m.company == targetCompanySysId;
})();

Angel32
Tera Contributor

I've been trying with :

answer = (function () {
var targetCompanySysId = 'cb221d84db7fdc90228e641d0b96199b';

// user_id is provided by User Criteria evaluation context
if (!user_id) return false;

var u = new GlideRecord('sys_user');
if (!u.get(user_id)) return false;

// user company match
if (u.company == targetCompanySysId) return true;

// manager company match
if (!u.manager) return false;

var m = new GlideRecord('sys_user');
if (!m.get(u.manager)) return false;

return m.company == targetCompanySysId;
})();
 
And it is still not ok when I check with "user criteria diagnostics" with a user which complies with both companies criterias (company and manager's company).
😕