Skip to content

Instantly share code, notes, and snippets.

@wave-inguane
Last active September 22, 2021 04:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wave-inguane/300dd6d95d6eb001851064a36c304060 to your computer and use it in GitHub Desktop.
Save wave-inguane/300dd6d95d6eb001851064a36c304060 to your computer and use it in GitHub Desktop.
RITM Utils
/**************************************************************************************************************************************
* List Collector Reference qualifier or Single Field
***************************************************************************************************************************************/
NOTE: For single field
Use Reference qualifier: Advanced
https://community.servicenow.com/community?id=community_question&sys_id=e1ee3ae5db58dbc01dcaf3231f96198f
Ex: active=true^first_nameISNOTEMPTY^ORlast_nameISNOTEMPTY^emailISNOTEMPTY^user_nameISNOTEMPTY
Add in system properties and call it in Dynamic way if needed
SOLUTION: Use query builder to build the query
Scripted for single Referece Field
var ReferenceQualifierUtil = Class.create();
ReferenceQualifierUtil.prototype = {
initialize: function() {
},
// USAGE
// javascript: new global.SMARTFilterLists().filterShowMyGroups(current.variables.select_team_member_to_modify);
getActiveUsers: function() {
var userList = "";
var grUser = new GlideRecord('sys_user');
grUser.addEncodedQuery("active=true^first_nameISNOTEMPTY^ORlast_nameISNOTEMPTY^emailISNOTEMPTY^user_nameISNOTEMPTY");
grUser.query();
while(grUser.next()) {
userList += ","+grUser.sys_id;
}
return 'sys_idIN'+userList;
},
getMyGroups: function(userId) {
var grMember = new GlideRecord('sys_user_grmember');
grMember.addQuery("user",userId);
grMember.query();
var groupList;
while(grMember.next()) {
groupList += ","+grMember.group;
}
return 'sys_idIN'+groupList;
},
type: 'ReferenceQualifierUtil'
};
var SMARTFilterListsV2 = Class.create();
SMARTFilterListsV2.prototype = {
initialize: function() {
},
filterShowInternalGroups: function() {
var groups = new GlideRecord('sys_user_group');
groups.addActiveQuery();
//groups.addEncodedQuery("type!=NULL^type=c822543f1b966c986a2e4196bc4bcbf5");
groups.query();
var groupList;
while(groups.next()) {
groupList += ","+groups.sys_id;
}
return 'sys_idIN'+groupList;
},
filterShowInternalUers: function() {
var grUser = new GlideRecord('sys_user');
grUser.addActiveQuery();
//grUser.addQuery("u_type","Internal");
grUser.query();
var userList;
while(grUser.next()) {
userList += ","+grUser.sys_id;
}
return 'sys_idIN'+userList;
},
//****************************************************************************************************************
// USAGE
// javascript: new global.SMARTFilterLists().filterShowMyGroups(current.variables.select_team_member_to_modify);
//****************************************************************************************************************
filterShowMyGroups: function(userId) {
var grMember = new GlideRecord('sys_user_grmember');
grMember.addQuery("user",userId);
grMember.query();
var groupList;
while(grMember.next()) {
groupList += ","+grMember.group;
}
return 'sys_idIN'+groupList;
},
filterShowOtherInternalGroups: function(userId) {
//gs.info("IDD = "+userId);
var grMember = new GlideRecord('sys_user_grmember');
grMember.addQuery("user",userId);
grMember.query();
var currentGroups;
while(grMember.next()) {
currentGroups += ","+grMember.group;
}
var groups = new GlideRecord('sys_user_group');
groups.addActiveQuery();
//groups.addEncodedQuery("type!=NULL^type=c822543f1b966c986a2e4196bc4bcbf5");
//groups.addQuery("sys_id","NOT IN",currentGroups);
groups.query();
var groupList;
while(groups.next()) {
groupList += ","+groups.sys_id;
}
return 'sys_idIN'+groupList;
},
MyGroupMembers : function(){
var groupList = "";
var grGP = new GlideRecord("sys_user_group");
grGP.addNotNullQuery("manager");
grGP.addQuery("manager", gs.getUserID());
grGP.query();
while (grGP.next()) {
var grGM = new GlideRecord("sys_user_grmember");
grGM.addNotNullQuery("user");
grGM.addQuery("group.name", grGP.name);
grGM.query();
while(grGM.next()){
var id = grGM.user.toString();
if(groupList.indexOf(id) == -1){
//gs.info(""+ grGM.user.name);
//gs.info(""+ grGP.name);
groupList += ","+grGM.user;
}
}
}
if(groupList)
return 'sys_idIN'+groupList;
else
return "active=true";
},
type: 'SMARTFilterListsV2'
};
/**************************************************************************************************************************************
* sync requested_for
***************************************************************************************************************************************/
BR: Sync Requested For
When : Before
Table: sc_request
(function executeRule(current, previous /*null when async*/) {
var grRITM = new GlideRecord("sc_req_item");
var found = grRITM.get("request", current.sys_id);
if(found){
if(grRITM.variables.requested_for != "" && grRITM.cat_item == "8de31c4d1b4abc109f33ed3be54bcbe0"){
current.requested_for = grRITM.variables.requested_for;
}
}
})(current, previous);
/**************************************************************************************************************************************
* Images
***************************************************************************************************************************************/
STEP 1
goto: db_image.list
Create new record
Name : removable_smaller.png
Next attach the image
Copy the code to be used in service portal
<img src="removable_smaller.png" width="200" height="100"/>
/**************************************************************************************************************************************
* Cat Item With Just Link
***************************************************************************************************************************************/
goto: sc_cat_item_content.list
/**************************************************************************************************************************************
* Populate RITM or REQ Fields from CAT Variables
***************************************************************************************************************************************/
/////////////////////// USE WORKFLOW//////////////////////////////
Use Run Script Activity after Begin
var userID = current.variables.requested_for;
if (userID){
var request = new GlideRecord('sc_request');
request.get(current.request);
request.requested_for = userID;
request.setWorkflow(false);
request.autoSysFields(false);
request.update();
}
var ritm = new GlideRecord("sc_req_item");
if(ritm.get(current.sys_id)){
ritm.description = current.variables.reason_for_report;
request.setWorkflow(false);
request.autoSysFields(false);
ritm.update();
}
/////////////////////// USE BUSINESS RULE//////////////////////////////
Name: xyz
Table: sc_req_item
When to run: before insert
Filter Condition:
Item -is- ?
Script :
(function executeRule(current, previous /*null when async*/) {
current.short_description = current.variables.first_question;
current.description = current.variables.reason_for_report;
})(current, previous);
/**************************************************************************************************************************************
* Hide Reference LookUp In Portal
***************************************************************************************************************************************/
ServiceNow Hi Solution:
Page Specific CSS
.ref-picker-container.field-has-reference .btn-default {
display: none;
}
OTHERE
.add-on > button.lookup {
display:none;
}
.field-has-reference .reference {
display: block;
}
//Client onLoad
var variableName = 'name of reference variable';
var id = g_form.getControl(variableName ).id;
$(id + 'LINK').hide();
OR
On Page or Portal css
#sp_formfield_reference_hiring_manger > .add-on button.lookup {
display:none;
}
For All Use
Page Specific CSS
.add-on{
display: none;
}
OR
.add-on > button.lookup {
display:none !important;
}
/**************************************************************************************************************************************
* Sync RITM field with variables
***************************************************************************************************************************************/
Before BR on RITM
(function executeRule(current, previous /*null when async*/) {
current.short_description = current.variables.XYZ;
})(current, previous);
/**************************************************************************************************************************************
* REQ/RITM/SCTASK Requested Fo Variable
***************************************************************************************************************************************/
var userID = current.variables.requested_for;
if (userID){
var request = new GlideRecord('sc_request');
request.get(current.request);
request.requested_for = userID;
request.update();
}
/**************************************************************************************************************************************
* Create Cat Item
***************************************************************************************************************************************/
Variables ...
/**************************************************************************************************************************************
* Workflow
***************************************************************************************************************************************/
1. Begin
2. Approval - if Yes
|
if No
3.Rejection Notification
To: ${requested_for}
Subject: Your requested item ${number} for ${cat_item} has been rejected
Message: Click here to view request: ${URI}
<p>
Number: ${number}
Opened: ${opened_at}
Item: ${cat_item}
Quantity: ${quantity}
</p>
<p>
Additional comments:
${comments}
</p>
4. End
if Yes
3. Catalog Task
4. X-Set Values
Name: Set State to Closed Complete
Stage: Completed
Set these values
state=3 --- Close Complete
stage=complete
/**************************************************************************************************************************************
* Email reminder for approver
***************************************************************************************************************************************/
Run: Daily or Periodically
//Take 1
returnApproval();
function returnApproval() {
try {
var grAPP = new GlideRecord('sysapproval_approver');
var grQuery = "state=requested^sysapproval.ref_sc_req_item.cat_item=505444c51b0a28909f33ed3be54bcb63^sysapproval.ref_sc_req_item.stage!=XYZifNEEDED";
grAPP.addEncodedQuery(grQuery);
grAPP.query();
while (grAPP.next()) {
var dt1 = new GlideDateTime(grAPP.getValue('sys_created_on'));
var dt2 = new GlideDateTime();
var diff = GlideDateTime.subtract(dt1, dt2);
var daysAgo = diff.getDayPart();
if (daysAgo % 3 == 0 && daysAgo != 0) {
gs.eventQueue('xyz.request.approval.reminder', grAPP);
}
}
} catch (ex) {
gs.info("ERROR - XYZ Request approval reminder :: " + ex.message);
}
}
//Take 2
Daily @4 00 00
returnApproval();
function returnApproval() {
var gr = new GlideRecord('sysapproval_approver');
var grQuery = "state=requested^sysapproval.ref_sc_req_item.stage=waiting_for_supervisor_approval^sysapproval.ref_sc_req_item.cat_item=505444c51b0a28909f33ed3be54bcb63";
gr.addEncodedQuery(grQuery);
gr.query();
while (gr.next()) {
gs.eventQueue('xyz.request.approval.reminder.daily', gr);
}
}
//Notification
Name: Open RITM Approval Reminder
Table: sysapproval_approver
Category: Approval
Event name: open.ritm.approval.reminders
Who will receive: Users in field : Approver
Send to event creator: yes
Subject: Reminder for Requested Item ${sysapproval} Approval Request
Email body: ${mail_script:find_pending_approvals}
//Email Script
Name: find_pending_approvals
(function runMailScript(/* GlideRecord */ current, /* TemplatePrinter */ template,
/* Optional EmailOutbound */ email, /* Optional GlideRecord */ email_action,
/* Optional GlideRecord */ event) {
try{
var app = current; //new GlideRecord('sysapproval_approver'); //create a query to retrieve open approvals
if(!app.nil()){//app.next()
//now that we have an approval for that user, we are going to look up the change tickets they need to approve and print out the data
var grRITM = new GlideRecord('sc_req_item'); //find the first related Change approval and print info
if(grRITM.get(app.sysapproval)){
template.print('<div><span style="font-size: 12pt; font-family: helvetica;">'+app.approver.first_name+',</span></div>');
template.print("<br/>");
template.print('<div><span style="font-size: 12pt; font-family: helvetica;">'+"Please review the information and respond by clicking on the appropriate link below."+'</span></div>');
template.print('<div><span style="font-size: 12pt; font-family: helvetica;">'+"Item Name: "+app.sysapproval.cat_item.getDisplayValue()+'</span></div>');
template.print('<div><span style="font-size: 12pt; font-family: helvetica;">'+"Short Description: "+app.sysapproval.short_description+'</span></div>');
template.print('<div><span style="font-size: 12pt; font-family: helvetica;">'+"Requested For: "+app.sysapproval.request.requested_for.getDisplayValue()+'</span></div>');
template.print('<div><span style="font-size: 12pt; font-family: helvetica;">'+"Requested By: "+app.sysapproval.opened_by.getDisplayValue()+'</span></div>');
template.print('<div><hr /></div>');
//template.print('<div><span style="font-size: 12pt; font-family: helvetica;">'+"${mail_script:ritm.itil.approve.role_script_1}"+'</span></div>');
template.print("<b>Summary of Approval request:</b><br />");
var scReqItem = new GlideRecord("sc_req_item");
scReqItem.addQuery("sys_id", app.sysapproval.toString());
scReqItem.query();
while (scReqItem.next()) {
gs.print(scReqItem.number + ": " + scReqItem.quantity + " X " + scReqItem.cat_item.getDisplayValue() + "\n" + "<br />");
gs.print(" Options:\n" + "<br />");
var varown = new GlideRecord('sc_item_option_mtom');
varown.addQuery("request_item", app.sysapproval.toString());
varown.orderBy("sc_item_option.order");
varown.query();
while (varown.next()) {
var visible = varown.sc_item_option.item_option_new.visible_summary;
//var question = Packages.com.glideapp.questionset.Question.getQuestion(varown.sc_item_option.item_option_new);//Packages call replaced with line below on Calgary+
var question = GlideappAbstractChoiceListQuestion.getQuestion(varown.sc_item_option.item_option_new);
question.setValue(varown.sc_item_option.value);
if (question.getLabel() != "" && question.getDisplayValue() != "" && visible == true) {
if (question.getType() == 20 || question.getType() == 19)
continue;
template.space(4);
template.print(' ' + question.getLabel() + " = " + question.getDisplayValue() + "\n" + "<br />");
}
}
}
template.print("<br/>");
template.print('<div><span style="font-size: 12pt; font-family: helvetica;">'+"Comments:"+'</span></div>');
template.print('<div><span style="font-size: 12pt; font-family: helvetica;">'+app.sysapproval.description+'</span></div>');
template.print('<div><hr /></div>');
template.print('<div><span style="font-size: 12pt; font-family: helvetica;">${mailto:mailto.approval}</span></div>');
template.print('<div><hr /></div>');
template.print('<div><span style="font-size: 12pt; font-family: helvetica;">${mailto:mailto.rejection}</span></div>');
template.print('<div><hr /></div>');
template.print('<div><span style="font-size: 12pt; font-family: helvetica;">Click here to view Approval Request: ${URI_REF}</span></div>');
template.print('<div><span style="font-size: 12pt; font-family: helvetica;">Click here to view ${sysapproval.sys_class_name}: ${sysapproval.URI_REF}</span></div>');
template.print("<br/>");
template.print("<br/>");
}
}
}catch(ex){
gs.error("ERROR in mail_script:find_pending_approvals"+ ex.name);
gs.error("ERROR in mail_script:find_pending_approvals"+ ex.massege);
}
})(current, template, email, email_action, event);
/**************************************************************************************************************************************
* Catalog Client Script
***************************************************************************************************************************************/
Name: AttachmentRequred
Type: onSubmit
Isolate script: false
function onSubmit() {
//for non-Service Portal
try {
var attachments = document.getElementById('header_attachment_list_label');
if (attachments.style.visibility == 'hidden' || attachments.style.display == 'none') {
alert(getMessage("Please use the paperclip icon below to attach a CSV file for reference."));
return false;
}
//for Service Portal
} catch (e) {
if ((this.document.getElementsByClassName('get-attachment').length == 0)) {
alert(getMessage("Please use the paperclip icon below to attach a CSV file for reference."));
return false;
}
}
}
/**************************************************************************************************************************************
* Aboart onSubmit
***************************************************************************************************************************************/
function onSubmit() {
if(g_form.getValue("report_format") == "Scheduled Report"){
var people = g_form.getValue("distribution_list_people");
var group = g_form.getValue("distribution_list_groups");
try{
if(people == "" && group == ""){
alert("Please provide the distribution list.");
return false;
}
}catch(e){
g_form.addErrorMessage("ERROR : "+e.message);
}
}
}
/**************************************************************************************************************************************
* Requested For iNFO
***************************************************************************************************************************************/
Name: onRequestedForChange
Variable name: requested_for
function onChange(control, oldValue, newValue, isLoading) {
if(isLoading && newValue == "")
g_form.setValue("requested_for", g_user.userID);
if(newValue != ""){
var ga = new GlideAjax('commonUtils');
ga.addParam('sysparm_name', "getUserInfo");
ga.addParam('sysparm_user', newValue);
ga.getXMLAnswer(function(answer) {
var response = JSON.parse(answer);
g_form.setValue('department', response.dept);
});
}
}
//Script incluide
Name: commonUtils
Client callable: true
var commonUtils = Class.create();
commonUtils.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getUserInfo: function() {
var user = this.getParameter('sysparm_user');
var response = {};
var gr = new GlideRecord("sys_user");
if(gr.get(user)){
var deptname = gr.department.getDisplayValue();
var dept = gr.getValue('department');
var manager = gr.getValue('manager');
var managername = gr.manager.getDisplayValue();
var location = gr.getValue('location');
var locationname = gr.location.getDisplayValue();
var email = gr.email.getDisplayValue();
var phone_number = gr.phone.getDisplayValue();
var title = gr.title.getDisplayValue();
var topLevel = new GlideRecord('cmn_department');
topLevel.addQuery('name', company.toString());
topLevel.setLimit(1);
topLevel.query();
while(topLevel.next()){
var sysID = topLevel.getValue('sys_id');
var topDept = sysID.toString();
}
response.deptname = deptname;
response.dept = dept;
response.manager = manager;
response.managername = managername;
response.location = location;
response.locationname = locationname;
response.email = email;
response.phone_number = phone_number;
response.title = title;
response.topDept = topDept;
}
return JSON.stringify(response);
},
type: 'commonUtils'
});
//*********************************************************************************************************************************
// Variables
//**********************************************************************************************************************************
Requested For - Default: javascript:gs.getUserID()
Variable Type: List Collector
Tables:
sys_user, sys_user_group
Reference qualifier : javascript: new global.SMARTFilterListsV2().filterShowInternalGroups();
Script Include:
var SMARTFilterListsV2 = Class.create();
SMARTFilterListsV2.prototype = {
initialize: function() {
},
filterShowInternalGroups: function() {
var groups = new GlideRecord('sys_user_group');
groups.addActiveQuery();
//groups.addEncodedQuery("type!=NULL^type=c822543f1b966c986a2e4196bc4bcbf5");
groups.query();
var groupList;
while(groups.next()) {
groupList += ","+groups.sys_id;
}
return 'sys_idIN'+groupList;
},
filterShowInternalUers: function() {
var grUser = new GlideRecord('sys_user');
grUser.addActiveQuery();
//grUser.addQuery("u_type","Internal");
grUser.query();
var userList;
while(grUser.next()) {
userList += ","+grUser.sys_id;
}
return 'sys_idIN'+userList;
},
//****************************************************************************************************************
// USAGE
// javascript: new x_smart.SMARTFilterLists().filterShowMyGroups(current.variables.select_team_member_to_modify);
//****************************************************************************************************************
filterShowMyGroups: function(userId) {
var grMember = new GlideRecord('sys_user_grmember');
grMember.addQuery("user",userId);
grMember.query();
var groupList;
while(grMember.next()) {
groupList += ","+grMember.group;
}
return 'sys_idIN'+groupList;
},
filterShowOtherInternalGroups: function(userId) {
//gs.info("IDD = "+userId);
var grMember = new GlideRecord('sys_user_grmember');
grMember.addQuery("user",userId);
grMember.query();
var currentGroups;
while(grMember.next()) {
currentGroups += ","+grMember.group;
}
var groups = new GlideRecord('sys_user_group');
groups.addActiveQuery();
//groups.addEncodedQuery("type!=NULL^type=c822543f1b966c986a2e4196bc4bcbf5");
//groups.addQuery("sys_id","NOT IN",currentGroups);
groups.query();
var groupList;
while(groups.next()) {
groupList += ","+groups.sys_id;
}
return 'sys_idIN'+groupList;
},
type: 'SMARTFilterListsV2'
};
//************************************************************************************************************************************
// HideEmptyVariables
//************************************************************************************************************************************
function onLoad() {
var variables = [
"variable_1",
"variable_2"
];
for (var i = 0; i < variables.length; i++) {
var name = variables[i];
var value = g_form.getValue(name);
if(value == "" || value == "--NONE--"){
g_form.setMandatory(name, false);
g_form.setDisplay(name, false);
}
}
}
//************************************************************************************************************************************
// Variable Attribute
//************************************************************************************************************************************
ref_ac_columns
Specifies the columns whose display values appear in an auto completion list in addition to the name. Separate column names with a semi-colon. For example, ref_ac_columns=user_name;email;sys_created_on allows auto-complete to match text from the user_name, email, and sys_created_on columns.
Applicable variables: Reference, Requested For
ref_ac_order_by
Specifies the column that is used to sort the auto completion list. For example, ref_ac_order_by=name sorts the auto-completion choices alphabetically by name.
Applicable variables: Reference
ref_auto_completer
Specifies the name of a JavaScript class (client-side) that creates the list for auto completion choices. Valid class values include:
AJAXReferenceCompleter: Displays matching auto-complete choices as a drop-down choice-list. The list only displays the display value column of the reference table. If there is no other auto-completion class specified, reference fields automatically use this class.
AJAXTableCompleter: Displays matching auto-complete choices as rows in a table. The table displays the display value column of the reference table and any columns listed in the ref_ac_columns attribute.
AJAXReferenceChoice: Displays matching auto-complete choices as a drop-down choice-list. The list only displays the display value column of the reference table. Furthermore, the list only displays up to 25 matching choices. If there are more than 25 auto-complete choices, the reference field instead displays the choices with the AJAXTableCompleter class.
Applicable variables: Reference
https://docs.servicenow.com/bundle/paris-servicenow-platform/page/product/service-catalog-management/reference/variable-attributes.html
ref_auto_completer=AJAXTableCompleter,ref_ac_columns_search=true,ref_ac_columns=name;title;email;
ref_auto_completer=AJAXTableCompleter,ref_ac_columns=email;user_name,ref_ac_columns_search=true,ref_ac_order_by=name
ref_auto_completer=AJAXTableCompleter,ref_ac_columns=u_state;u_zip
ref_auto_completer=AJAXTableCompleter,ref_ac_columns_search=true,ref_ac_columns=u_facility_address;u_facility_name_and_drive_distance
no_filter,ref_auto_completer=AJAXTableCompleter,ref_ac_columns=first_name;last_name;email;u_hash_id,ref_ac_columns_search=true
Table
incident
Field
u_affected_user
Type
reference
Reference
sys_user
Max Length
32
Attributes
edge_encryption_enabled=true,encode_utf8=false,ref_ac_columns=email;u_hash_id,ref_auto_completer=AJAXTableCompleter,ref_contributions=user_show_incidents
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment