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?
Can you show me your code please?
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
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Try adding this return instead of the one you have:
def total = rt as int [] return DateUtils.getDurationString(Math.round(total.sum() / 1000))
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
You will have to import:
import com.atlassian.core.util.DateUtils
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Now I'm getting an error
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
What are you passing into the getDuration() method?
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
It's actually a double error.
import com.atlassian.jira.component.ComponentAccessor import com.atlassian.jira.issue.history.ChangeItemBean import com.atlassian.core.util.DateUtils 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 as int [] return DateUtils.getDurationString(Math.round(total.sum() / 1000))
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
This removes the errors I believe:
rt = rt as long [] def total = rt.sum()/ 1000 as long return DateUtils.getDurationString(total)
You wil need the template for the scripted field to be Text-Field. Otherwise it will fail.
Thanks
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Still errors:
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Apologies, try this:
def newRT = rt as long []
def total = newRT.sum()/ 1000 as long
return DateUtils.getDurationString(total)
Does that work?
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
It works like a charm! No, I can build on this.
Thanks!!
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
No problem!
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
I tried this scripted field as well, and I always get 0 min as the time in status. No errors shown in code:
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
I have switched to using a new add-on called Issue History Collector:
https://marketplace.atlassian.com/apps/1211499/issue-history-collector?hosting=server&tab=overview
And, it is free.
Just follow the documentation and it is pretty easy to get up an running.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hey Guys, what's about Cloud?
Is it possible to somehow implement it there?
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
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
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
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 😌
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
This function work for me:
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
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 % 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
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 libraries
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.history.ChangeItemBean
//Define the variables to be used
def 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 name
for(item in changeItems){
if(statusName.contains(item.getToString())){
//Do Nothing
} else {
statusName << item.getToString()
}
}
//Get time difference for each status and concatinate onto strResult
for(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
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
// You can try this [I am new to script runner please check twice][Added by Sanjay]
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.history.ChangeItemBean
import com.atlassian.core.util.DateUtils
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.IssueManager
import com.atlassian.jira.issue.MutableIssue
import com.atlassian.jira.user.ApplicationUser
import com.atlassian.jira.issue.util.DefaultIssueChangeHolder
import com.atlassian.jira.bc.issue.IssueService.UpdateValidationResult;
import com.atlassian.jira.user.ApplicationUser
import 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 == name
def 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 long
def mytotal =DateUtils.getDurationString(total)
IssueService issueService = ComponentAccessor.getIssueService();
IssueInputParameters issueInputParameters = ComponentAccessor.issueService.newIssueInputParameters();
log.warn(issueInputParameters.addCustomFieldValue(10803,mytotal)) //10803 is a custom field id
def autoUser = ComponentAccessor.getUserManager().getUserByName("admin") as ApplicationUser
UpdateValidationResult 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
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
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?
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
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 :)
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Can you please set this answer to accepted?
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Done :)
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
@[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 must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.