|
1 | | -(function executeRule(current, previous /*null when async*/ ) { |
| 1 | +(function executeRule(current, previous /*null when async*/) { |
| 2 | + |
| 3 | + |
| 4 | + //When the Incident state values are set to: 6 (Resolved), 7 (Closed), 8 (Cancelled). |
| 5 | + // The `previous.state` check prevents the script from running when a closed ticket is re-closed. |
| 6 | + if ((current.state == '6' || current.state == '7' || current.state == '8') && current.state != previous.state) { |
2 | 7 |
|
3 | | - // Query for any child incidents related to the current parent incident. |
4 | | - var childIncidents = new GlideRecord('incident'); |
5 | | - childIncidents.addQuery('parent_incident', current.sys_id); |
6 | | - childIncidents.addEncodedQuery('state!=6^ORstate!=7^ORstate!=8'); // state is not closed,Resoved,cancelled |
7 | | - childIncidents.addActiveQuery(); |
8 | | - childIncidents.query(); |
9 | | - // Check if any open child incidents were found. |
10 | | - if (childIncidents.getRowCount() > 0) { |
11 | | - var childNumbers = []; |
12 | | - while (childIncidents.next()) { |
13 | | - childNumbers.push(childIncidents.number.toString()); |
| 8 | + // Use GlideAggregate to efficiently count child incidents that are not yet closed. |
| 9 | + var ga = new GlideAggregate('incident'); |
| 10 | + ga.addQuery('parent_incident', current.sys_id); |
| 11 | + ga.addActiveQuery(); |
| 12 | + ga.addAggregate('COUNT'); |
| 13 | + ga.query(); |
| 14 | + var childCount = 0; |
| 15 | + if (ga.next()) { |
| 16 | + // Retrieve the aggregated count. |
| 17 | + childCount = ga.getAggregate('COUNT'); |
| 18 | + } |
| 19 | + // If open child incidents are found, abort the parent's closure and display an error. |
| 20 | + if (childCount > 0) { |
| 21 | + gs.addErrorMessage('Cannot close this incident. ' + childCount + ' child incidents are still open.'); |
| 22 | + current.setAbortAction(true); |
14 | 23 | } |
15 | | - // Display an error message with the open child incident numbers. |
16 | | - gs.addErrorMessage('Cannot close this incident. Please close the following child incidents first: ' + childNumbers.join(', ')); |
17 | | - //prevent saving the record |
18 | | - current.setAbortAction(true); |
19 | 24 | } |
20 | 25 |
|
21 | 26 | })(current, previous); |
0 commit comments