diff --git a/Server-Side Components/Business Rules/Abort Parent Incident Closure When Child is Open/README.md b/Server-Side Components/Business Rules/Abort Parent Incident Closure When Child is Open/README.md new file mode 100644 index 0000000000..aa5dcb5fa2 --- /dev/null +++ b/Server-Side Components/Business Rules/Abort Parent Incident Closure When Child is Open/README.md @@ -0,0 +1,16 @@ +This business rule is designed for ServiceNow to prevent a parent incident from being closed or resolved while it still has active child incidents. +If a user attempts to set the parent incident's state to "Resolved," "Closed," or "Cancelled," the rule will query for any related child incidents that are still open. +If open children are found, the update will be aborted, and an error message will be displayed to the user. + +Navigate to System Definition > Business Rules in the ServiceNow filter navigator. +Click New. +Fill out the form with the following details: +Name: Prevent Parent Closure with Open Children +Table: Incident [incident] +Advanced: true +When: before +Update: Check this box. +In the When to run tab, set the Condition field: +current.state.changesTo(7) || current.state.changesTo(6) || current.state.changesTo(8) //The state values are: 6 (Resolved), 7 (Closed), 8 (Cancelled). +Note: The state values (6, 7, 8) may vary based on your instance configuration. +In the Advanced tab, paste the provided script into the Script field. diff --git a/Server-Side Components/Business Rules/Abort Parent Incident Closure When Child is Open/scriptBR.js b/Server-Side Components/Business Rules/Abort Parent Incident Closure When Child is Open/scriptBR.js new file mode 100644 index 0000000000..4d2f5d092b --- /dev/null +++ b/Server-Side Components/Business Rules/Abort Parent Incident Closure When Child is Open/scriptBR.js @@ -0,0 +1,26 @@ +(function executeRule(current, previous /*null when async*/) { + + + //When the Incident state values are set to: 6 (Resolved), 7 (Closed), 8 (Cancelled). + // The `previous.state` check prevents the script from running when a closed ticket is re-closed. + if ((current.state == '6' || current.state == '7' || current.state == '8') && current.state != previous.state) { + + // Use GlideAggregate to efficiently count child incidents that are not yet closed. + var ga = new GlideAggregate('incident'); + ga.addQuery('parent_incident', current.sys_id); + ga.addActiveQuery(); + ga.addAggregate('COUNT'); + ga.query(); + var childCount = 0; + if (ga.next()) { + // Retrieve the aggregated count. + childCount = ga.getAggregate('COUNT'); + } + // If open child incidents are found, abort the parent's closure and display an error. + if (childCount > 0) { + gs.addErrorMessage('Cannot close this incident. ' + childCount + ' child incidents are still open.'); + current.setAbortAction(true); + } + } + +})(current, previous);