Sla conditions state value

BHARATHS
Tera Contributor

Need to set an state value dynamically from sys_choice list based selecting table, please helpt to write an scripted rest api

2 ACCEPTED SOLUTIONS

Prathmeshdagade
Mega Guru

Hello @BHARATHS 
scripted rest api

(function process(request,  response) {

try {
var body = request.body.data;

var tableName = body.table;
var recordSysId = body.sys_id;
var fieldName = body.field; // e.g. "state"
var choiceLabel = body.choice_label;

if (!tableName || !recordSysId || !fieldName || !choiceLabel) {
response.setStatus(400);
response.setBody({
status: "error",
message: "Missing required parameters"
});
return;
}
var choiceGR = new GlideRecord("sys_choice");
choiceGR.addQuery("name", tableName);
choiceGR.addQuery("element", fieldName);
choiceGR.addQuery("label", choiceLabel);
choiceGR.addQuery("inactive", false);
choiceGR.query();

if (!choiceGR.next()) {
response.setStatus(404);
response.setBody({
status: "error",
message: "Choice not found for given table and field"
});
return;
}

var choiceValue = choiceGR.getValue("value");
var targetGR = new GlideRecord(tableName);
if (!targetGR.get(recordSysId)) {
response.setStatus(404);
response.setBody({
status: "error",
message: "Record not found"
});
return;
}

targetGR.setValue(fieldName, choiceValue);
targetGR.update();
response.setStatus(200);
response.setBody({
status: "success",
table: tableName,
field: fieldName,
label: choiceLabel,
value: choiceValue
});

} catch (ex) {
response.setStatus(500);
response.setBody({
status: "error",
message: ex.message
});
}

})(request, response);

sys_choice table   : Stores choice list values for fields like state, priority, etc.

If this response proves useful, please mark it as Accept as Solution and Helpful. Doing so benefits both the community and me. 👍🙂

View solution in original post

@BHARATHS 

I won't recommend creating SLA via script.

I have never seen this in any of my implementations.

SLAs are to be configured by admin as 1 time activity and it can be updated later by admins in PROD

💡 If my response helped, please mark it as correct and close the thread 🔒— this helps future readers find the solution faster! 🙏

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

View solution in original post

5 REPLIES 5

Prathmeshdagade
Mega Guru

Hello @BHARATHS 
scripted rest api

(function process(request,  response) {

try {
var body = request.body.data;

var tableName = body.table;
var recordSysId = body.sys_id;
var fieldName = body.field; // e.g. "state"
var choiceLabel = body.choice_label;

if (!tableName || !recordSysId || !fieldName || !choiceLabel) {
response.setStatus(400);
response.setBody({
status: "error",
message: "Missing required parameters"
});
return;
}
var choiceGR = new GlideRecord("sys_choice");
choiceGR.addQuery("name", tableName);
choiceGR.addQuery("element", fieldName);
choiceGR.addQuery("label", choiceLabel);
choiceGR.addQuery("inactive", false);
choiceGR.query();

if (!choiceGR.next()) {
response.setStatus(404);
response.setBody({
status: "error",
message: "Choice not found for given table and field"
});
return;
}

var choiceValue = choiceGR.getValue("value");
var targetGR = new GlideRecord(tableName);
if (!targetGR.get(recordSysId)) {
response.setStatus(404);
response.setBody({
status: "error",
message: "Record not found"
});
return;
}

targetGR.setValue(fieldName, choiceValue);
targetGR.update();
response.setStatus(200);
response.setBody({
status: "success",
table: tableName,
field: fieldName,
label: choiceLabel,
value: choiceValue
});

} catch (ex) {
response.setStatus(500);
response.setBody({
status: "error",
message: ex.message
});
}

})(request, response);

sys_choice table   : Stores choice list values for fields like state, priority, etc.

If this response proves useful, please mark it as Accept as Solution and Helpful. Doing so benefits both the community and me. 👍🙂

Ankur Bawiskar
Tera Patron

@BHARATHS 

what's your exact business requirement here?

share screenshots.

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

My requirement is to create an SLA automatically once a record producer is created via integration. The record producer table should automatically be fetched in the new SLA definition. However, I need to set start, pause, and stop conditions based on the state value from that table. I am planning to use a dynamic approach to set these conditions.
 
Below I have scripted rest api, but it's not working
 
(function process(request, response) {

    this.status = '200';
    var responseBody = {};

    gs.info("SLA API Request Body: " + JSON.stringify(request.body.data));

    try {
        var requestBody = request.body.data;

        var sla = new GlideRecord('contract_sla');
        sla.initialize();

        sla.name = requestBody.name;
        sla.target = requestBody.type;
        sla.schedule = requestBody.slaSchedule;
        sla.timezone_source = requestBody.time;
        sla.collection = requestBody.table;
        sla.sys_scope = requestBody.scope;

        // --------------------------
        // Parse SLA Duration
        // --------------------------
        var durationStr = requestBody.slaDuration; // "1970-01-03 08:10:05"
        var dateTime = durationStr.split(' ');
        var day = parseInt(dateTime[0].split('-')[2], 10) - 1;
        var t = dateTime[1].split(':');
        var hours = parseInt(t[0], 10);
        var minutes = parseInt(t[1], 10);
        var seconds = parseInt(t[2], 10);

        var totalMs = (((day * 24 + hours) * 60 + minutes) * 60 + seconds) * 1000;
        sla.duration = new GlideDuration(totalMs);

        // --------------------------
        // Dynamic state detection
        // --------------------------
        function getStateValue(table, field, label) {
            var gr = new GlideRecord('sys_choice');
            gr.addQuery('name', table);
            gr.addQuery('element', field);
            gr.addQuery('label', label);
            gr.addQuery('inactive', false);
            gr.orderByDesc('sys_scope'); // prefer scoped over global
            gr.query();

            if (gr.next()) {
                return gr.value.toString();
            }
            return null;
        }

        function getStateField(table) {
            var fields = ['state', 'status'];
            for (var i = 0; i < fields.length; i++) {
                if (GlideTableDescriptor.get(table).hasElement(fields[i])) {
                    return fields[i];
                }
            }
            return null;
        }

        var stateField = getStateField(requestBody.table);

        if (stateField) {
            var stateNew = getStateValue(requestBody.table, stateField, 'New');
            var stateHold = getStateValue(requestBody.table, stateField, 'On Hold');
            var stateClosed = getStateValue(requestBody.table, stateField, 'Closed');
            var stateCancelled = getStateValue(requestBody.table, stateField, 'Cancelled');

            if (stateNew && stateHold && stateClosed && stateCancelled) {
                startCond = stateField + '=' + stateNew;
                pauseCond = stateField + '=' + stateHold;
                stopCond = stateField + '=' + stateClosed + '^OR' +
                    stateField + '=' + stateCancelled;
                cancelCond = stateField + '=' + stateCancelled;
            }
        }

        if (!stateField || !startCond) {
            startCond = 'active=true';
            pauseCond = '';
            stopCond = 'active=false';
            cancelCond = 'active=false';
        }

        // --------------------------
        // Assign SLA Fields
        // --------------------------
        sla.start_condition = startCond;
        sla.pause_condition = pauseCond;
        sla.stop_condition = stopCond;
        sla.cancel_condition = cancelCond;


        var slaSysId = sla.insert();
        responseBody.status = 'success';
        responseBody.sys_id = slaSysId;

    } catch (e) {
        responseBody.status = 'error';
        responseBody.message = e.message;
    }

    response.setBody(responseBody);

})(request, response);

@BHARATHS 

I won't recommend creating SLA via script.

I have never seen this in any of my implementations.

SLAs are to be configured by admin as 1 time activity and it can be updated later by admins in PROD

💡 If my response helped, please mark it as correct and close the thread 🔒— this helps future readers find the solution faster! 🙏

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