Name

global.ScrumStoryStateWatcher

Description

Update percent_complete in Story when its state changes

Script

var ScrumStoryStateWatcher = Class.create();

ScrumStoryStateWatcher.prototype = {
  initialize: function(story) {
      this.story = story;
  },

  storyStateChanged: function() {
      var storyState = this.story.getValue('state');
      var statesUtil = new ScrumStatesUtil(this.story.getRecordClassName());

      if (statesUtil.isCompletedState(storyState))
          this.storyCompleted();
      else if (!statesUtil.isCancelledState(storyState))
          this.storyReopened();
  },

  storyStateSet: function() {
      var storyState = this.story.getValue('state');
      var statesUtil = new ScrumStatesUtil(this.story.getRecordClassName());

      if (statesUtil.isCompletedState(storyState))
          this.storyCompleted();
      else if (statesUtil.isCancelledState(storyState)) {
          this.storyCancelled();
      } else {
          this.storyOpened();
      }
  },

  storyOpened: function() {
      this.story.percent_complete = 0;
  },

  storyReopened: function() {
      var stateUtil = new ScrumStatesUtil("rm_scrum_task");
  	var completedStates = stateUtil.getCompletedStates();
      var totalTasks = 0,
          completedTasks = 0;
      var story = this.story.getValue("sys_id");
      var gr = new GlideAggregate("rm_scrum_task");
      gr.addQuery('story', story);
      gr.addAggregate('COUNT', "state");
      gr.groupBy('state');
      gr.query();
      while (gr.next()) {
          var temp = parseInt(gr.getAggregate('COUNT', 'state'));
          totalTasks += temp;
  		var state = gr.state.getValue();
          if (completedStates.indexOf(state) > -1)
              completedTasks += temp;
      }
      if (totalTasks === 0) {
          this.story.percent_complete = 0;
      } else {
          this.story.percent_complete = ((completedTasks / totalTasks) * 100);
      }
  },

  storyCancelled: function() {
      this.story.percent_complete = 0;
      this.syncDurationWithPoints();
  },

  storyCancelRevoked: function() {
      this.syncDurationWithPoints();
  },

  storyCompleted: function() {
      this.story.percent_complete = 100;
  },

  syncDurationWithPoints: function() {
      var durationSync = new ScrumStoryPointDurationSync(this.story);
      durationSync.syncDurationWithPoints();
  },

  type: 'ScrumStoryStateWatcher'
}

Sys ID

a1f01a398f0221001a83cfd827bdeecf

Offical Documentation

Official Docs: