Clone content based on template selected with the help groovy script.

Vaijayanti Chaundhari
I'm New Here
I'm New Here
Those new to the Atlassian Community have posted less than three times. Give them a warm welcome!
December 29, 2024

In workflow post function i have added script runner where i written code as below,

 Condition

 //Declare and initialize the list of issue keys

def issueKeys = ["MYQCMR-42", "MYQCMR-59", "MYQCMR-60", "MYQCMR-78", "MYQCMR-128"]

// Safely access the necessary properties using safe navigation

def issueKey

def issueTypeName d

ef customField23961

// Check if the issue key is in the list, the issue type is 'CMR v2', and custom field 'customfield_23961' is not present

def isConditionMet = issueKeys.contains(issueKey) && issueTypeName == 'CMR v2' && !customField23961 logger.info("Condition met: ${isConditionMet}")

return isConditionMet

Additional Code : 

 

 

@grab(group='com.konghq', module='unirest-java', version='3.11.09')

import org.apache.http.entity.ContentType;
import kong.unirest.Unirest;
import kong.unirest.HttpResponse
import kong.unirest.JsonNode
import kong.unirest.HttpRequest
import org.apache.http.entity.ContentType

def issueKey = issue.key

logger.info("It ran!")
//ISSUE DETAILS
def taskTemplate = getIssueDetails(issueKey,"customField","customfield_18811")

if (taskTemplate) {
   
    switch(taskTemplate) {        
         case {it.contains("MYQCMR-42")}:
            def templateKey = "MYQCMR-42"
            def proFormaCF = "customfield_22200"
            updateIssueFromTemplate(issueKey, templateKey, proFormaCF)
            break
         case {it.contains("MYQCMR-59")}: a
            def templateKey = "MYQCMR-59"
            def proFormaCF = "customfield_22201"
            updateIssueFromTemplate(issueKey, templateKey, proFormaCF)
            break
         case {it.contains("MYQCMR-60")}:
            def templateKey = "MYQCMR-60"
            def proFormaCF = "customfield_22202"
            updateIssueFromTemplate(issueKey, templateKey, proFormaCF)
            break
         case {it.contains("MYQCMR-78")}:
            def templateKey = "MYQCMR-78"
            def proFormaCF = "customfield_22703"
            updateIssueFromTemplate(issueKey, templateKey, proFormaCF)
            break
        case {it.contains("MYQCMR-128")}:
            def templateKey = "MYQCMR-128"
            def proFormaCF = "customfield_22801"
            updateIssueFromTemplate(issueKey, templateKey, proFormaCF)
            break
         default:
            logger.info("Issue: ${issueKey} - No template!")
            break
      }
}

def updateIssueFromTemplate(issueKey, templateKey, proFormaCF) {
        def newSummary = getIssueDetails(issueKey,"proFormaField",proFormaCF)
        def newDescription = getIssueDetails(templateKey,"systemField","description")
        updateIssue(issueKey, newSummary, newDescription)
        def attachments = getIssueDetails(templateKey,"attachment","attachment")
        if (attachments) { copyIssueAttachments(issueKey, attachments) }
}

def getIssueDetails(issueKey, type, fieldName) {
    def result = get("/rest/api/2/issue/${issueKey}?fields=${fieldName}")
            .header('Content-Type', 'application/json')
            .asObject(Map)
    if (result.status == 200) {
        if (type == "systemField") {
            return result.body.fields[fieldName]
        } else if (type == "customField") {
            return result.body.fields[fieldName].value
        } else if (type == "proFormaField") {
            return result.body.fields[fieldName]
        } else if (type == "attachment") {
            return [result.body.fields[fieldName].filename, result.body.fields[fieldName].content, result.body.fields[fieldName].mimeType]          
        }
    } else {
        logger.info("Error retrieving issue ${result}")
    }
}

def updateIssue(issueKey,summary, description){
    def resp = put("/rest/api/2/issue/${issueKey}")
        .header('Content-Type', 'application/json')
        .body([
            fields: [
                    summary             : summary,
                    description         : description,
                    customfield_23961   : [[value: 'Yes']]
                    ]
            ])
        .asString()
    assert resp.status == 204
}

def copyIssueAttachments(issueKey, attachments){
    if (attachments) {
        for(int i = 0; i < attachments[0].size(); i++ ){
                def fileName = attachments[0][i]
                def downloadUrl = attachments[1][i]
                def mimeType = attachments[2][i]
                logger.info("fileName: ${fileName} - downloadUrl: ${downloadUrl} - mimeType: ${mimeType}")
                def readFileResp = Unirest.get(downloadUrl).asBinary()
                def resp = Unirest.post("/rest/api/2/issue/${issueKey}/attachments")
                //.header('Content-Type', 'application/json')
                .header('X-Atlassian-Token', 'no-check')
                .field("file", readFileResp.body, ContentType.create(mimeType as String), fileName as String)
            .asObject(Map)
                assert resp.status >= 200 && resp.status < 300
        }
    } else logger.info("Template has no attachment.")
}


When i check check logs ,
1)

 

CorrelationId: Self=1-676fe459-5dade21b24c89d6e3b5c5e7d;Root=1-676fe459-44d38642051c894f52c5b974
Script identifier: 8d674583-8b21-4270-bdc2-bdfd3080d833 com.adaptavist.sr.cloud.workflow.RunScript ('Create' transition made for issue MYQCMR-2722)  Took: -1ms Logs:
2024-12-28 11:43:24.560 ERROR - org/apache/ivy/util/MessageLogger
2024-12-28 11:43:24.579 ERROR - Class: com.adaptavist.sr.cloud.workflow.RunScript, Config: [className:com.adaptavist.sr.cloud.workflow.RunScript, uuid:8d674583-8b21-4270-bdc2-bdfd3080d833, enabled:true, executionUser:ADD_ON, condition:, description:Clone content based on template selected, additionalCode:import org.apache.http.entity.ContentType;
@Grapes([ @Grab(group='com.konghq', module='unirest-java', version='3.11.09') ])
import kong.unirest.Unirest;

def issueKeys = ["MYQCMR-42", "MYQCMR-59", "MYQCMR-60", "MYQCMR-78", "MYQCMR-128"]
def issueKey = issue.key
def issueTypeName = issue.issueType.name
def customField_23961 = null

def isConditionMet = issueKeys.contains(issueKey) && issueTypeName == 'CMR v2' && !customField_23961

logger.info("Condition met: ${isConditionMet}")
return isConditionMet

1 answer

0 votes
Ram Kumar Aravindakshan _Adaptavist_
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
December 31, 2024

Hi @Vaijayanti Chaundhari

I can confirm the approach you are trying will not work as expected for Jira cloud.

You can't use annotations like @grab(group='com.konghq', module='unirest-java', version='3.11.09') in the Jira cloud, as this will fail.

If your objective is to clone an issue, you can refer to this code snippet to clone an Epic, Child Issues and Sub-tasks.

Please note that the sample working code in the Snippet is not 100% exact to your environment and requirements. Hence, you must modify the code accordingly.

I hope this help to answer your question. :-)

Thank you and Kind regards,
Ram

Suggest an answer

Log in or Sign up to answer
DEPLOYMENT TYPE
CLOUD
PRODUCT PLAN
PREMIUM
PERMISSIONS LEVEL
Product Admin
TAGS
AUG Leaders

Atlassian Community Events