Preventing SCTASK Closure if Linked CHGs Are Still Open

LeighAnnB
Tera Contributor

I’m trying to prevent catalog tasks (SCTASKs) from being closed if there are still open change requests (CHGs) linked to them.

I know that it’s possible to block RITMs from closing when they have open SCTASKs. For reference, here’s an Business Rule I found that is used for RITMs (LINK)

 

 
Table: Requested Item
When to Run: Before Update
Condition: State is One of Closed States
Script:
(function executeRule(current, previous) {
var scTask = new GlideRecord('sc_task');
scTask.addActiveQuery();
scTask.addQuery('request_item', current.sys_id);
scTask.query();
if (scTask.hasNext()) {
gs.addErrorMessage('RITM cannot be closed until all tasks are closed');
current.state = previous.state;
}
})(current, previous);
 
If a CHG is created as part of an SCTASK, ServiceNow treats the SCTASK as the parent of the CHG, similar to how RITMs are children of SCTASKs. Just because it seems like the parent/chile relationship is the same or similar, doesn't mean it actually is.  My question is: can the same approach be applied so that SCTASKs cannot be closed if they have open child CHGs? If so, what would be the recommended field to query and best practices for implementing it?

 

Thanks in advance for any guidance!

3 REPLIES 3

Bert_c1
Kilo Patron

The change_request table has a reference field named 'parent' that can refer to a sc_task record. If this is what you have, then you can define a similar BR defined on the 'sc_task' table where you query the 'change_request' table:

 

(function executeRule(current, previous) {
var chg = new GlideRecord('change_request');
chg.addActiveQuery();
chg.addQuery('parent', current.sys_id);
chg.addEncodedQuery('stateNOT IN3,4');  // may not be needed, seems active is false for this condition 
chg.query();
if (chg.hasNext()) {
gs.addErrorMessage('SCTASK cannot be closed until all child Change Requests are closed');
current.state = previous.state;
}
})(current, previous);

 

I will be testing this out shortly and will mark as the solution as soon as it is working for me.

also thank you for the code - I am still learning that part of the system so that is very helpful!

Bert_c1
Kilo Patron

@LeighAnnB 

 

I would modify the script logic to include a list of child records still active. To let the user know which need to be closed/cancelled.

 

...
chg.query();
var chgs = [];
while (chg.next()) {
	chgs.push(chg.number.toString());
}
if (chgs.length > 0) {
	gs.addErrorMessage('SCTASK cannot be closed until all child Change Requests are closed');
	gs.addInfoMessage('Active child Change Requests: ' + chgs);
	current.state = previous.state;
}

Do the same for your existing BR.