Reflecting CHG Actual End Dates with the latest closed CTask end date

GB9414
Tera Contributor

Not sure if this is even possible but does anyone have a script or suggestion that will allow for the latest closed CTask work end date to also reflect as the actual end date for the CHG request. 

 

The following script is currently active and it works if I only have one closed CTask within the CHG request, however if a user had a few more tasks (specifically more that 2), then it would only reflect up to the second closed task.

 

Script as follows:

(function executeRule(current, previous /*null when async*/)
      
      //Query change tasks related to the current change request
      var task = new GlideRecord('change_task');
      task.addQuery('parent', current.sys_id);
      task.query();
 
      var latest_end_date;
      
      //Loop through all related tasks
      while (task.next()) {
            //If the task is closed
            if (task.state == '3') {
                  // If this is the first task or this task ended later than the previous latest
 
                  if (!latest_end_date || task.work_end > latest_end_date) {
                        latest_end_date = task.work_end;
 
 
                  }
 
            }
      }
 
      //If there was at least one closed task, update the change request's actual end date
      if (latest_end_date) {
            current.work_end = latest_end_date;
            current.update();
      }
 
})(current, previous);
 
I have try other variations as well as ensuring accurate field configurations but nothing seems to work. Even AI suggestions are proving futile. 
 
Any promising leads would be extremely appreciated!
 
Thank you!
9 REPLIES 9

Brad Bowman
Kilo Patron
Kilo Patron

A simpler approach would be to add the state to the query criteria, and order by work_end descending so that the first record returned is the change task that was closed last:

 

function executeRule(current, previous /*null when async*/)
    //Query change tasks related to the current change request
    var tsk = new GlideRecord('change_task');
    tsk.addQuery('change_request', current.sys_id);
    tsk.addQuery('state', 3);
    tsk.orderByDesc('work_end');
    tsk.query();
    if (tsk.next()) {
        current.work_end = tsk.work_end;
        current.update();
  }
 })(current, previous);

 

I've changed the task var to tsk in case 'task' is a reserved word and could cause issues.  The change_request field should be more reliably populated than parent, but maybe not in your environment?  Since this script includes current.update(), make sure you're running it after Update.

Brad,

Thank you for the quick reply!
Will this work as is or is there any additions needed or tweaking of the code required?

It shouldn't need altered.  You're running this as a Business Rule on the change_request table after update when State changes to closed or Active changes to false?

Yes, that is correct.