Hi,
I want to create a scripted field in scriptrunner that calculates time in status (like Jira suite utilities) in certain conditions.
Is the best way to create some custom fields that populate a date and time or can I script this?
Hi Robin,
Take a look at this link: https://scriptrunner.adaptavist.com/latest/jira/scripted-fields.html#_total_time_this_issue_has_been_in_progress
You can edit this code to show the total time for any status.
Is that what you are looking for?
Thanks,
Johnson Howard
Can you show me your code please?
It looks like it, but the values are not correct
It was in the status for less than a minute.
Kind regards,
Robin
double post
import com.atlassian.jira.component.ComponentAccessor import com.atlassian.jira.issue.history.ChangeItemBean def changeHistoryManager = ComponentAccessor.getChangeHistoryManager() def inProgressName = "Assess 2nd Line" List<Long> rt = [0L] def changeItems = changeHistoryManager.getChangeItemsForField(issue, "status") changeItems.reverse().each {ChangeItemBean item -> item.toString == inProgressName def timeDiff = System.currentTimeMillis() - item.created.getTime() if (item.fromString == inProgressName) { rt << -timeDiff } if (item.toString == inProgressName){ rt << timeDiff } } def total = rt.sum() as Long return total ?: 0L
Try adding this return instead of the one you have:
def total = rt as int [] return DateUtils.getDurationString(Math.round(total.sum() / 1000))
You will have to import:
import com.atlassian.core.util.DateUtils
Can you please set this answer to accepted?
Done
Is it possible to set that duration time in relation to already configured service calendars/times? The method above includes also non-working times.
Thanks for inspiration
The display of the data works, but querying is inconsistent.
You are in effect using datetime.now() as a basis of your scripts calculation, which in itself is a non-deterministic function. (On ANY platform you shouldnt really ever index a piece of data that is based on a non-deterministic function...but I wanted to reprove this to myself in JIRA too!)
My own objective was to be able to alert when a ticket has been in any given state which exceeds the time-estimate for it (to highlight flow hotspots)
I created a field: "Time in current status" that effectively has a value of now() - date time of last transition (simplified version of script above: just gets the first entry and does the calculation, or if no transition entry then use now() - created date)
Putting my field on the Kanban cards always displayed the right value, but JQL filters were inconsistent. The data in the field was only ever saved if the issue was updated + saved in some way.
My test script was thus:
Create an issue, kanban shows 0 minutes in "Time in current status" field
After 10 minutes refresh the kanban board: issue shows 10 minutes in "Time in current status"
Run JQL: "Time in current status" > 9m : issue doesn't show (bad)
Immediately edit a field (eg Description or Summary) to trigger issue data to be saved
Run JQL: "Time in current status" > 9m : issue shows (good)
I waited 2 minutes:
Run JQL: "Time in current status" > 11m : issue doesn't show (bad)
Then re-index my project (triggers script to run on each issue: NB this is potential danger of using scripted fields)
Run JQL: "Time in current status" > 11m : issue shows (good)
The message is: think carefully what you are doing with any data in your script and whether it can actually support queries on that data - does it rely on a piece of data that can change, without triggering an update to the scripted field on your issue.
Always ask yourself: when using data external to the issues fields for any calculations: if that piece of data changes does your field need to be recalculated or is your field usage explicitly for a snapshot?
@[deleted]@JohnsonHoward
We followed same steps but we are getting below exception , Can you please look into it and help us to get resolved .
An error occurred whilst rendering this message. Please contact the administrators, and inform them of this bug. Details: ------- org.apache.velocity.exception.MethodInvocationException: Invocation of method 'formatDurationPretty' in class com.atlassian.core.util.DateUtils threw exception java.lang.NumberFormatException: For input string: "0m" at templates/customfield/view-duration.vm[line 3, column 16] at org.apache.velocity.runtime.parser.node.ASTMethod.handleInvocationException(ASTMethod.java:337) at org.apache.velocity.runtime.parser.node.ASTMethod.execute(ASTMethod.java:284)
// You can try this [I am new to script runner please check twice][Added by Sanjay]
import com.atlassian.jira.component.ComponentAccessorimport com.atlassian.jira.issue.history.ChangeItemBeanimport com.atlassian.core.util.DateUtilsimport com.atlassian.jira.component.ComponentAccessorimport com.atlassian.jira.issue.IssueManagerimport com.atlassian.jira.issue.MutableIssueimport com.atlassian.jira.user.ApplicationUserimport com.atlassian.jira.issue.util.DefaultIssueChangeHolderimport com.atlassian.jira.bc.issue.IssueService.UpdateValidationResult;import com.atlassian.jira.user.ApplicationUserimport com.atlassian.jira.bc.issue.IssueService;import com.atlassian.jira.bc.issue.IssueService.IssueResult;import com.atlassian.jira.issue.IssueInputParameters;import com.atlassian.jira.bc.issue.IssueService.IssueResult;
IssueManager im = ComponentAccessor.getIssueManager()def customFieldManager =ComponentAccessor.getCustomFieldManager();def Time_in_Current_Status = customFieldManager.getCustomFieldObject("customfield_10803")MutableIssue issue = im.getIssueObject("DP-2") //STATIC VALUE [need to change]def changeHistoryManager = ComponentAccessor.getChangeHistoryManager()def name = issue.getStatus().name;log.warn(name); //Troubleshoot
List<Long> rt = [0L]def changeItems = changeHistoryManager.getChangeItemsForField(issue, "status")changeItems.reverse().each {ChangeItemBean item ->item.toString == namedef timeDiff = System.currentTimeMillis() - item.created.getTime()if (item.fromString == name) {rt << -timeDiff}if (item.toString == name){rt << timeDiff}}
def newRT = rt as long []def total = newRT.sum()/ 1000 as longdef mytotal =DateUtils.getDurationString(total)IssueService issueService = ComponentAccessor.getIssueService();IssueInputParameters issueInputParameters = ComponentAccessor.issueService.newIssueInputParameters();log.warn(issueInputParameters.addCustomFieldValue(10803,mytotal)) //10803 is a custom field iddef autoUser = ComponentAccessor.getUserManager().getUserByName("admin") as ApplicationUserUpdateValidationResult updateValidationResult = issueService.validateUpdate(autoUser, issue.id, issueInputParameters);if (updateValidationResult.isValid()){IssueResult updateResult = issueService.update(autoUser, updateValidationResult);if (updateResult.isValid()){log.warn("Approvals Added successfully")}else{updateResult.getErrorCollection().getErrors().each{ error->log.warn("Approvals not added bcz:"+error)}}}else{updateValidationResult.getErrorCollection().getErrors().each{ error->log.warn("Approvals not added bcz:"+error)}}return "Time duration of issue in status "+name+" is "+mytotal
So I am using a longer method for getting time in all statuses, see the example below. I am having 2 issues, one I have resolved by using my own calculations:
def newRT = rt as long []rt.clear()def total = newRT.sum()/ 1000 as long
def seconds = total.intValue()def iD = (seconds / 85400).round(0)def days = seconds % 86400def iH = (days / 3600).round(0)def hours = days % 3600def iM = (hours /60).round(0)def strTimeStr = sName + ": " + iD.toString() + "d " + iH.toString() + "h " + iM.toString() + "m" + " | "strResult += strTimeStr
Here is the script below (I am going to add logic to the output to only print d m h if there are values for them):
//Import the relevant librariesimport com.atlassian.jira.component.ComponentAccessorimport com.atlassian.jira.issue.history.ChangeItemBean//Define the variables to be useddef strResult = ""List<Long> rt = [0L]List<String> statusName = []def changeHistoryManager = ComponentAccessor.getChangeHistoryManager()def changeItems = changeHistoryManager.getChangeItemsForField(issue, "status")//Validate that there is only one of each change item namefor(item in changeItems){ if(statusName.contains(item.getToString())){ //Do Nothing } else { statusName << item.getToString() }}//Get time difference for each status and concatinate onto strResultfor(sName in statusName){ changeItems.reverse().each { ChangeItemBean item -> if (changeItems.indexOf(sName) == 0){ rt << issue.create.getTime() - item.create.getTime() } else { item.fromString == sName def timeDiff = System.currentTimeMillis() - item.created.getTime() if (item.fromString == sName) { rt << -timeDiff } if (item.toString == sName) { rt << timeDiff } } } //Create the output string def newRT = rt as long [] rt.clear() def total = newRT.sum()/ 1000 as long def seconds = total.intValue() def iD = (seconds / 85400).round(0) def days = seconds % 86400 def iH = (days / 3600).round(0) def hours = days % 3600 def iM = (hours /60).round(0) def strTimeStr = sName + ": " + iD.toString() + "d " + iH.toString() + "h " + iM.toString() + "m" + " | " strResult += strTimeStr}return strResult
If anyone could provide advice for including something to calculate for the first status of the workflow? I know the majority of our projects use Backlog but there may be a few that use another status in the beginning of the workflow
Thanks in advance
This function work for me:
Hi @Slava Gefen and everyone who is looking for solution 😌
As an alternative, for advanced analysis you can try - Time in Status for Jira (Cloud, Data Center), (developed by SaaSJet) that generates 7 types of status reports including Status Entrance Date report. It shows the date a particular issue has entered each of a status (Resolved or Closed, etc.).
On the chart, it shows the number of tasks that have entered a status on a certain date - for example, 1 task out of 5 tasks has entered the Progress status for the first time on the 23-rd of May.
Add-on has a 30-day free trial version and free up to 10 users .
Hope it helps 😌
It looks like you're new here. Sign in or register to get started.