Skip to main content
Book your demo
Example scripts
To homepage
Jira
Cloud icon
Cloud

Automate Epic Custom Field Sum

Features
Listeners
Created 2 year(s) ago, Updated 1 day(s) ago
App in script
ScriptRunner For Jira
ScriptRunner For Jira
by Adaptavist
Compatibility
compatibility bullet
Jira
Language |
groovy
def eventWorkItem = Issues.getByKey(issue.key as String)

//the name of the custom field. This code will work just as well with the custom field ID instead i.e. 10124L
def sumCustomFieldName = 'custom field name i.e. Sum of values'

//for regular work items the parent is an Epic
def epicKey = eventWorkItem.getParentObject()?.key ?: null

if(!epicKey) {
    // Checks the 'Epic Link' custom field
    epicKey = eventWorkItem.getEpic()?.key ?: null
}

if (!epicKey && eventWorkItem.issueType.subtask) {
    epicKey = eventWorkItem.parentObject?.epic?.key ?: null
}

if (!epicKey) {
    logger.info("We did not find an Epic in the hierarchy of this work item. Exiting.")
    return
}

// Find the epic work item
def epicWorkItem = Issues.search("key = ${epicKey}").first()
if (!epicWorkItem) {
    throw new IllegalStateException("Epic work item not found for key ${epicKey}")
}

// Sum all work items linked to the epic, taking care to exclude the epic
def sum = Issues.search("linkedissue = ${epicKey}").sum { workItem ->
    if (workItem.key == epicKey) return 0
    workItem.getCustomFieldValue(sumCustomFieldName) ?: 0
}

epicWorkItem.update {
    setCustomFieldValue(sumCustomFieldName, sum)
}
Having an issue with this script?
Report it here