Business rule

Mohd Kamran1
Tera Contributor

I have written a AFTER BR business rule to automate the some kind of incident, script is working fine but one thing i'm stuck additional comment is updated by Who is open the incident means Opened by but i want to set as system ,, additional comment should be updated by system only ,, tried  to applied runAs  , journal entry but still stuck. cIf anyone have idea please share to me how can i achieve this --

 

var instanceName = gs.getProperty('instance_name');
if (instanceName !== 'testinstance') {
    gs.info('This is not the specified instance.');
    current.comments = 'This is not the specified instance';
    current.setWorkflow(true);
    return;
}

var description = current.getValue('description');
var role = '';
var action = '';
var email = '';
var comments = ''; // Variable to accumulate comments
var actionTaken = false; // Track if any action was taken

// Regular expression patterns
var emailPattern = /Email:\s*([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/i;
var rolePattern = /Role:\s*(.*)/i;
var addActionPattern = /Add\s*new\s*role/i;
var removeActionPattern = /Remove\s*role/i;
var renewActionPattern = /Renew\s*role/i;

// Extract email
var emailMatch = description.match(emailPattern);
if (emailMatch) {
    email = emailMatch[1];
} else {
    gs.info('Email not found in description.');
    comments += 'Correct email not found in description. Incident not resolved\n';
    current.comments = comments;
    current.setWorkflow(true);
    return; // Abort further execution
}

// Extract role
var roleMatch = description.match(rolePattern);
if (roleMatch && roleMatch.length > 1) {
    role = roleMatch[1].trim();
} else {
    gs.info('Role not found in description.');
    comments += 'Role not found in description. Incident not resolved\n';
    current.comments = comments;
    current.setWorkflow(true);
    return; // Abort further execution
}

// Extract action
if (description.match(addActionPattern)) {
    action = 'add';
} else if (description.match(removeActionPattern)) {
    action = 'remove';
} else if (description.match(renewActionPattern)) {
    action = 'renew';
} else {
    gs.info('Action not recognized.');
    comments += 'Action not recognized. Incident not resolved\n';
    current.comments = comments;
    current.setWorkflow(true);
    return; // Abort further execution
}

// Get the sys_id of the user
var emailGR = new GlideRecord('sys_user');
emailGR.addQuery('email', email);
emailGR.addNotNullQuery('email');
emailGR.query();
if (!emailGR.next()) {
    gs.info('User not found for email: ' + email);
    comments += 'Email not found, hence Incident not resolved\n';
    current.comments = comments;
    current.setWorkflow(true);
    return; // Abort further execution
}

var userId = emailGR.sys_id;
var userName = emailGR.user_name;
// Check if user is internal (user id starts with n[0-9][0-9]* or m[0-9][0-9]*)
var isInternal = /^n[0-9]+|^m[0-9]+/.test(userName);

// Get the sys_id of the group
var groupGR = new GlideRecord('sys_user_group');
groupGR.addQuery('name', role);
groupGR.query();
if (!groupGR.next()) {
    gs.info('Group not found for role: ' + role);
    comments += 'Mentioned group not found. Incident not resolved\n';
    current.comments = comments;
    current.setWorkflow(true);
    return; // Abort further execution
}

var groupId = groupGR.sys_id;

// Check if the user is already a member of the group
var groupMemberGR = new GlideRecord('sys_user_grmember');
groupMemberGR.addQuery('user', userId);
groupMemberGR.addQuery('group', groupId);
groupMemberGR.query();
var isMember = groupMemberGR.hasNext();

if (action === 'add' || action === 'renew') {
    if (!isMember) {
        // Attempt to add the user to the group
        var newGroupMemberGR = new GlideRecord('sys_user_grmember');
        newGroupMemberGR.initialize();
        newGroupMemberGR.user = userId;
        newGroupMemberGR.group = groupId;
        newGroupMemberGR.insert();
       
        // Verify if the user has been added successfully
        groupMemberGR.initialize();
        groupMemberGR.addQuery('user', userId);
        groupMemberGR.addQuery('group', groupId);
        groupMemberGR.query();
        if (groupMemberGR.hasNext()) {
            comments += 'User successfully added to the group. Incident resolved\n';
            actionTaken = true; // Mark that an action was successfully taken
        } else {
            comments += 'Attempt to add user failed. Incident remains open\n';
        }

        // Handle the case for internal users and ITIL role
        if (isInternal && role === ' ITIL') {
            var paUserGroupGR = new GlideRecord('sys_user_group');
            paUserGroupGR.addQuery('name', 'PA User Internal');
            paUserGroupGR.query();
            if (paUserGroupGR.next()) {
                var paGroupId = paUserGroupGR.sys_id;
                var paGroupMemberGR = new GlideRecord('sys_user_grmember');
                paGroupMemberGR.initialize();
                paGroupMemberGR.user = userId;
                paGroupMemberGR.group = paGroupId;
                paGroupMemberGR.insert();

                // Verify if user was added to the PA group
                paGroupMemberGR.initialize();
                paGroupMemberGR.addQuery('user', userId);
                paGroupMemberGR.addQuery('group', paGroupId);
                paGroupMemberGR.query();
                if (paGroupMemberGR.hasNext()) {
                    comments += 'User added to both ITIL and  PA User Internal groups.\n';
                } else {
                    comments += 'Failed to add user to PA User group.\n';
                }
            }
        }
    } else {
        gs.info('User is already a member of the group.');
        comments += 'User is already a member of the group. No changes made\n';
    }
} else if (action === 'remove') {
    if (isMember) {
        // Attempt to remove the user from the group
        while (groupMemberGR.next()) {
            groupMemberGR.deleteRecord();
        }
       
        // Verify if the user was successfully removed
        groupMemberGR.initialize();
        groupMemberGR.addQuery('user', userId);
        groupMemberGR.addQuery('group', groupId);
        groupMemberGR.query();
        if (!groupMemberGR.hasNext()) {
            comments += 'User successfully removed from the group. Incident resolved\n';
            actionTaken = true; // Mark that an action was successfully taken
        } else {
            comments += 'Attempt to remove user failed. Incident remains open\n';
        }
    } else {
        gs.info('User is not a member of the group.');
        comments += 'User is not a member of the group. No changes made\n';
    }
}

comments += '\nUser ID: ' + userName;

// Only resolve the incident if an action was actually taken (add or remove)
if (actionTaken) {
    current.state = 6; // 6 is the state value for "Resolved"
    current.incident_state = 6;
    current.close_code = 'Closed/Resolved by automation'; // Example resolution code
    current.close_notes = 'Completed Successfully';
    current.assigned_to = 'testuser';
} else {
    comments += 'No changes made. User was neither added nor removed. Incident remains open.\n';
}

// Set the accumulated comments and update once at the end
current.comments = comments;
current.update();
current.setWorkflow(true);
6 REPLIES 6

If you change it to before Update you don't need current.update(), otherwise you do if you want to add a comment.

Ankur Bawiskar
Tera Patron
Tera Patron

@Mohd Kamran1 

I would suggest this

1) have a custom flow action which has the entire script logic.

2) then have a flow triggered which runs on same BR conditions. Ensure Run As = System User in Flow properties

3) this flow will call the custom flow action

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader