Forums

Articles
Create
cancel
Showing results for 
Search instead for 
Did you mean: 

Clone issue to new projects and link

Andrew Downs
Contributor
October 2, 2018

Hi guys,

 

I need some assistance please, I am trying to clone and issue into a workflow function based on an Insight Multi Select list.

Basically I have a form which a user can select one or multiple Business Applications, each application is linked to one or more projects on Insights.

 

What I need to be able do is as follows:

 

1) Iterate through each object selected in the multi select

2) Obtain the associated project(s) from the select business application

3) Clone existing issue from service desk into the project(s) obtained above

4) Link the clones to the Service Desk project

 

I have looked at various questions posted on the forums but do not seem to be coming right.

 

So far I have the following which returns a project ID:

 

import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.ContentType.*
import groovyx.net.http.ContentType
import static groovyx.net.http.Method.*
import groovy.json.JsonSlurper
import net.sf.json.groovy.JsonSlurper
import com.atlassian.jira.ComponentManager
import com.atlassian.jira.issue.CustomFieldManager
import com.atlassian.jira.issue.fields.CustomField
import com.atlassian.jira.issue.IssueManager
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.MutableIssue
import com.atlassian.jira.issue.Issue
import com.atlassian.jira.issue.UpdateIssueRequest
import com.atlassian.jira.issue.comments.CommentManager
import com.atlassian.jira.user.ApplicationUser
import com.atlassian.jira.util.json.JSONObject
import com.atlassian.jira.issue.Issue
import org.apache.log4j.Category
import com.atlassian.jira.bc.issue.comment.property.CommentPropertyService
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.issue.MutableIssue
import com.atlassian.jira.issue.fields.CustomField;

// Enable Logging
def Category log = Category.getInstance("com.onresolve.jira.groovy")
log.setLevel(org.apache.log4j.Level.DEBUG)
log.info "Info Statements"

// Define Required Component Access

def customFieldManager = ComponentAccessor.getCustomFieldManager()
def issueManager = ComponentAccessor.getIssueManager()


// Get Issue ID that contains the Data
//def issueKey = issue.getKey()
//MutableIssue issue = issueManager.getIssueObject(issueKey)
Issue issue = issueManager.getIssueObject( "TRC-506")

//def getInsightFieldValue(object_id, attribute_id) {

 /* Get Insight Object Facade from plugin accessor */
 Class objectFacadeClass = ComponentAccessor.getPluginAccessor().getClassLoader().findClass("com.riadalabs.jira.plugins.insight.channel.external.api.facade.ObjectFacade");
 def objectFacade = ComponentAccessor.getOSGiComponentInstanceOfType(objectFacadeClass);
 
 ArrayList requiredApplications = (ArrayList)issue.getCustomFieldValue(customFieldManager.getCustomFieldObjectByName("Required Application Access")).unique();

for(i=0;i < requiredApplications.size();i++)
{
     def objectBean = requiredApplications[i]
     log.info(objectBean)
     projectIDs =  objectFacade.loadObjectAttributeBean(objectBean.getId(), 3320).getObjectAttributeValueBeans()[0].getValue() //attribute id
    log.info(projectIDs)
    
    
}

 

But further to that I am lost. I am using Jira 7.10.1 and Script Runner 5.4.28.

 

Assistance is greatly appreciated.

1 answer

0 votes
Andrew Downs
Contributor
October 31, 2018

For future reference I came right by doing the following:

 

import com.atlassian.jira.bc.issue.search.SearchService
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.Issue
import com.atlassian.jira.web.bean.PagerFilter
import com.atlassian.jira.issue.CustomFieldManager
import org.apache.log4j.Category
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.MutableIssue

// Configure Logging
Category log = Category.getInstance("com.onresolve.jira.groovy")
log.setLevel(org.apache.log4j.Level.DEBUG)
log.debug "Clone Issue to Relevant Projects"

// Define required Components
customFieldManager = ComponentAccessor.getCustomFieldManager()
issueManager = ComponentAccessor.getIssueManager()
searchService = ComponentAccessor.getComponent(SearchService)
user = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser()
issueFactory = ComponentAccessor.getIssueFactory()

// Insight Object Facade
Class objectFacadeClass = ComponentAccessor.getPluginAccessor().getClassLoader().findClass("com.riadalabs.jira.plugins.insight.channel.external.api.facade.ObjectFacade");
objectFacade = ComponentAccessor.getOSGiComponentInstanceOfType(objectFacadeClass);

// Get Current Issue
//issueKey = issue.getKey()
//MutableIssue issue = issueManager.getIssueObject(issueKey)
Issue issue = issueManager.getIssueObject( "SSD-43282")

// Get custom fields
fullName = customFieldManager.getCustomFieldObjectByName("Full Name");
fullNameValue = issue.getCustomFieldValue(fullName);
firstName = customFieldManager.getCustomFieldObjectByName("Firstname");
firstNameValue = issue.getCustomFieldValue(firstName);
lastName = customFieldManager.getCustomFieldObjectByName("Surname");
lastNameValue = issue.getCustomFieldValue(lastName);
officeNumber = customFieldManager.getCustomFieldObjectByName("User Office Number");
officeNumberValue = issue.getCustomFieldValue(officeNumber);
lineManager = customFieldManager.getCustomFieldObjectByName("Line Manager");
lineManagerValue = issue.getCustomFieldValue(lineManager).toString();
mobileNumber = customFieldManager.getCustomFieldObjectByName("Cell Phone Number");
mobileNumberValue = issue.getCustomFieldValue(mobileNumber);
faxNumber = customFieldManager.getCustomFieldObjectByName("Office Number");
faxNumberValue = issue.getCustomFieldValue(faxNumber);
title = customFieldManager.getCustomFieldObjectByName("Job Title");
titleValue = issue.getCustomFieldValue(title);
department = customFieldManager.getCustomFieldObjectByName("Department");
departmentValue = issue.getCustomFieldValue(department);
siteName = customFieldManager.getCustomFieldObjectByName("Site Code");
siteNameValue = issue.getCustomFieldValue(siteName);
streetAddress = customFieldManager.getCustomFieldObjectByName("Street Address");
streetAddressValue = issue.getCustomFieldValue(streetAddress);
city = customFieldManager.getCustomFieldObjectByName("City");
cityValue = issue.getCustomFieldValue(city);
province = customFieldManager.getCustomFieldObjectByName("Province");
provinceValue = issue.getCustomFieldValue(province);
country = customFieldManager.getCustomFieldObjectByName("Country");
countryValue = issue.getCustomFieldValue(country);
BU1 = customFieldManager.getCustomFieldObjectByName("Business Unit 1");
BU1Value = issue.getCustomFieldValue(BU1)
BU2 = customFieldManager.getCustomFieldObjectByName("Business Unit 2");
BU2Value = issue.getCustomFieldValue(BU2)
BU3 = customFieldManager.getCustomFieldObjectByName("Business Unit 3");
BU3Value = issue.getCustomFieldValue(BU3)
emailRequired = customFieldManager.getCustomFieldObjectByName("Email Requirements");
emailRequiredValue = issue.getCustomFieldValue(emailRequired)
emailDomain = customFieldManager.getCustomFieldObjectByName("Email Domain Requirements");
emailDomainValue = issue.getCustomFieldValue(emailDomain)
logonNameOverride = customFieldManager.getCustomFieldObjectByName("Logon Name Override");
logonNameOverrideValue = issue.getCustomFieldValue(logonNameOverride);
requiredApplicationAccess = customFieldManager.getCustomFieldObjectByName("Required Application Access")
requiredApplicationAccessValue = issue.getCustomFieldValue(requiredApplicationAccess)
requiredApplicationPermissions = customFieldManager.getCustomFieldObjectByName("Required Application Permissions")
requiredApplicationPermissionValue = issue.getCustomFieldValue(requiredApplicationPermissions)
originalReference = customFieldManager.getCustomFieldObjectByName("Original Reference")

// Update Original Reference custom field
issue.setCustomFieldValue(originalReference,issue)

// Get originalReference Value

originalReferenceValue = issue.getCustomFieldValue(originalReference).toString()


if (logonNameOverrideValue == null){
   firstNameValue = firstNameValue.replaceAll('\\ ','').replaceAll('\\ ','').trim()
   fullNameValue = fullNameValue
}
else{
   firstNameValue = logonNameOverrideValue.replaceAll('\\ ','').replaceAll('\\ ','').trim()
   fullNameValue = logonNameOverrideValue + " " + lastNameValue
}

// Build Array of Required Applications

ArrayList requiredApplications = (ArrayList)issue.getCustomFieldValue(customFieldManager.getCustomFieldObjectByName("Required Application Access")).unique();

// Start loop on requiredApplications

for(i=0; i < requiredApplications.size();i++){
    
    // Get Object Bean
    // Uses value of i to get the index within the array
    
    log.debug ("Getting object for index ${i}")
    
    objectBean = requiredApplications[i]
    
    log.debug ("Object Bean is ${objectBean}")
        
    applicationAccessName = objectBean.name
    
      // Get Project ID, this is linked to Applications within Insight
        
    try{
        log.debug ("Attempting to get Project ID for ${objectBean}")
        projectIDs =  objectFacade.loadObjectAttributeBean(objectBean.getId(), 3320).getObjectAttributeValueBeans()[0].getValue()
        
    }
    catch(Exception ex){
        log.debug ("Application is not linked to a project, defaulting to Service Desk Project (10402)")
        projectIDs = 10402
    }

    log.debug ("Project ID is ${projectIDs}")
    
    // Get the project Key for associated Project ID returned in projectIDs
    
    projectKey = ComponentAccessor.getProjectManager().getAllProjectKeys(projectIDs).toString().replaceAll('\\[','').replaceAll('\\]','')
 
       PROJECT_KEY_TO = projectKey

    log.debug("Destination Project: $PROJECT_KEY_TO")

    
    // edit the JQL to return the issues you want to clone
    jqlSearch = """
    project = "SSD" AND Key = "$issue"
    """

     projectTo = ComponentAccessor.getProjectManager().getProjectByCurrentKey(PROJECT_KEY_TO)
    
     List<Issue> issuesFrom = []

    // Get all the issues returned from the JQL
   
    SearchService.ParseResult parseResult =  searchService.parseQuery(user, jqlSearch)
    if (parseResult.isValid()) {
        searchResult = searchService.search(user, parseResult.getQuery(), PagerFilter.getUnlimitedFilter())
        issuesFrom = searchResult.issues.collect { issueManager.getIssueObject(it.id) } as List <Issue>
        log.debug ("Issues From: $issuesFrom")
    }

    // Clone all the issues returned from the JQL to each project returned
   
    issuesFrom?.each { it ->
        newIssue = issueFactory.cloneIssue(it)

        log.debug ("New issue: $newIssue")

        // set the project and any field you want to have a different value
        newIssue.setProjectObject(projectTo)
        newIssue.setSummary("Please give user access to ${applicationAccessName}")
        newIssue.setAssignee(null)
        newIssue.setCustomFieldValue(fullName, fullNameValue)
        newIssue.setCustomFieldValue(firstName, firstNameValue)
        newIssue.setCustomFieldValue(lastName, lastNameValue)
        newIssue.setCustomFieldValue(title, titleValue)
        newIssue.setCustomFieldValue(department, departmentValue)
        newIssue.setCustomFieldValue(BU1, BU1Value)
        newIssue.setCustomFieldValue(BU2, BU2Value)
        newIssue.setCustomFieldValue(BU3, BU3Value)
        newIssue.setCustomFieldValue(siteName, siteNameValue)
        newIssue.setCustomFieldValue(streetAddress,streetAddressValue)
        newIssue.setCustomFieldValue(city,cityValue)
        newIssue.setCustomFieldValue(province,provinceValue)
        newIssue.setCustomFieldValue(country,countryValue)
        newIssue.setCustomFieldValue(mobileNumber, mobileNumberValue)
        newIssue.setCustomFieldValue(officeNumber, officeNumberValue)
        newIssue.setCustomFieldValue(requiredApplicationAccess, requiredApplicationAccessValue)
        newIssue.setCustomFieldValue(requiredApplicationPermissions, requiredApplicationPermissionValue)
        newIssue.setCustomFieldValue(originalReference, issue.toString())
        
           Map<String,Object> newIssueParams = ["issue":newIssue] as Map<String,Object>
        log.debug("Issue Params: ${newIssueParams}")
        log.debug ("Original Reference: ${originalReferenceValue}")
        issueManager.createIssueObject(user, newIssueParams)
        
        log.debug ("Issue Details ${newIssue?.issueType}")
        log.debug ("Issue ${newIssue?.key} cloned to project ${projectTo.key}")
        log.debug ("Successfully created linked issue in project ${PROJECT_KEY_TO}")
    }
}

Suggest an answer

Log in or Sign up to answer