Create
cancel
Showing results for 
Search instead for 
Did you mean: 
Sign up Log in
Deleted user
0 / 0 points
Next:
badges earned

Your Points Tracker
Challenges
Leaderboard
  • Global
  • Feed

Badge for your thoughts?

You're enrolled in our new beta rewards program. Join our group to get the inside scoop and share your feedback.

Join group
Recognition
Give the gift of kudos
You have 0 kudos available to give
Who do you want to recognize?
Why do you want to recognize them?
Kudos
Great job appreciating your peers!
Check back soon to give more kudos.

Past Kudos Given
No kudos given
You haven't given any kudos yet. Share the love above and you'll see it here.

It's not the same without you

Join the community to find out what other Atlassian users are discussing, debating and creating.

Atlassian Community Hero Image Collage

Null when sending mail notifications

Good day! I have a script on a "Resolve" transition. When the transition is in progress, the related requests are closed and should send email notifications to the authors of the close. The letter comes, but it is marked with null. Tell me where the problem might be? The problem appeared after updating jira.
Sample script:


import com.atlassian.jira.component.ComponentAccessorimport com.atlassian.jira.issue.Issueimport com.atlassian.jira.issue.MutableIssueimport com.atlassian.jira.event.type.EventDispatchOptionimport com.atlassian.jira.bc.project.component.ProjectComponentimport com.atlassian.jira.issue.customfields.option.Optionimport com.atlassian.jira.issue.util.DefaultIssueChangeHolderimport com.atlassian.jira.issue.ModifiedValueimport com.atlassian.jira.util.ImportUtilsimport com.atlassian.jira.issue.index.IssueIndexingServiceimport com.atlassian.jira.workflow.TransitionOptions;import com.atlassian.jira.workflow.TransitionOptions.Builder;import com.atlassian.jira.bc.issue.IssueService;import com.atlassian.jira.issue.IssueInputParameters;import com.atlassian.jira.issue.comments.MutableComment;import com.atlassian.jira.issue.CustomFieldManager;import com.atlassian.jira.issue.link.IssueLink;import com.atlassian.jira.issue.link.IssueLinkManager;import com.atlassian.jira.issue.Issue;import com.atlassian.jira.issue.IssueInputParameters;import com.atlassian.jira.issue.IssueManager;import com.atlassian.jira.user.util.UserManager;import com.atlassian.jira.user.ApplicationUser;



final linkTypeName = "Массовость"final transitionId = 251 // переход Закрытие инцидента (251) из WF Инцидентаint actionId = 591; // ОТПРАВКА ПИСЬМА(из массового) // тестово отключен в пользу "transitionId = 251"

def userManager = ComponentAccessor.getUserManager()def issueLinkManager = ComponentAccessor.getIssueLinkManager()def issueManager = ComponentAccessor.getIssueManager()def customFieldManager = ComponentAccessor.getCustomFieldManager()def issueService = ComponentAccessor.getIssueService()def commentManager = ComponentAccessor.getCommentManager()def issueIndexingService = ComponentAccessor.getComponent(IssueIndexingService)
// def issue = (MutableIssue) issueManager.getIssueObject("HELPDESK-492249")
def jirarobot = userManager.getUserByName("jirarobot")
if (issue.getCustomFieldValue(customFieldManager.getCustomFieldObject(13192L)).toString() == "Да") { // "Массовый инцидент"
    // "Заполнить категорию у связанных?" / customfield_20281    // class com.atlassian.jira.issue.customfields.option.LazyLoadedOption    def fillLinkedIssuesFieldValue = issue.getCustomFieldValue(customFieldManager.getCustomFieldObject(20281L)) as Option
    // "Категория инцидента"    def incidentCategoryField = customFieldManager.getCustomFieldObject(13183L)    def incidentCategoryFieldValue = issue.getCustomFieldValue(incidentCategoryField)
    // "Категория обслуживания"    def serviceCategoryField = customFieldManager.getCustomFieldObject(13184L)
    // "Сообщение"    def messageField = customFieldManager.getCustomFieldObject(13191L)    String comment = issue.getCustomFieldValue(messageField)
    def inwardLinks = issueLinkManager.getInwardLinks(issue.id)    ArrayList<Issue> linkedIssues = new ArrayList<Issue>()
    if (inwardLinks[0] != null) {        inwardLinks?.each {            inwardLink ->                if (inwardLink.issueLinkType.name == linkTypeName) {                    linkedIssues.add(inwardLink.getSourceObject())                }        }    }
    linkedIssues?.each {        linkedIssue ->            def issueInputParameters = issueService.newIssueInputParameters()            def transitionValidationResult = issueService.validateTransition(jirarobot, linkedIssue.id, transitionId, issueInputParameters)
            if (transitionValidationResult.isValid()) {                ((MutableIssue)linkedIssue).setCustomFieldValue(messageField, comment)                // 1) Here doesn't work                //if (linkedIssue.getIssueTypeId().equals("10818")) ((MutableIssue) linkedIssue).setIssueTypeId("10602")                commentManager.create(linkedIssue, jirarobot, comment, false)                issueManager.updateIssue(jirarobot, (MutableIssue) linkedIssue, EventDispatchOption.DO_NOT_DISPATCH, false)                issueService.transition(jirarobot, transitionValidationResult)            }
            // 1) Works correct!            // Если "Запрос на обслуживание", то меняем тип на "Инцидент" и обнуляем поле "Категория обслуживания"            if (linkedIssue.getIssueTypeId().equals("10818")) {                ((MutableIssue) linkedIssue).setIssueTypeId("10602")                ((MutableIssue) linkedIssue).setCustomFieldValue(serviceCategoryField, null)            }
            // ----- Заполнение поля "Категория инцидента" -----            // 19354 - "Да"            if (fillLinkedIssuesFieldValue != null && fillLinkedIssuesFieldValue.getOptionId() == 19354L) {                ((MutableIssue) linkedIssue).setCustomFieldValue(incidentCategoryField, incidentCategoryFieldValue)            }            // ----- Заполнение полей 19584 - Предварительная оценка сложности, 19585 - Итоговая оценка сложности" -----            def preDiffRating = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(19584)            if (!preDiffRating.getValue(linkedIssue)){                def preFieldConfig = preDiffRating.getRelevantConfig(linkedIssue)                def preFieldConfigValue = ComponentAccessor.optionsManager.getOptions(preFieldConfig)?.find {it.toString() == "0"}                preDiffRating.updateValue(null, linkedIssue, new ModifiedValue("", (Object) preFieldConfigValue), new DefaultIssueChangeHolder())            }            def postDiffRating = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(19585)            if (!postDiffRating.getValue(linkedIssue)){                def postFieldConfig = postDiffRating.getRelevantConfig(linkedIssue)                def postFieldConfigValue = ComponentAccessor.optionsManager.getOptions(postFieldConfig)?.find {it.toString() == "0"}                postDiffRating.updateValue(null, linkedIssue, new ModifiedValue("", (Object) postFieldConfigValue), new DefaultIssueChangeHolder())            }
            issueManager.updateIssue(jirarobot, (MutableIssue) linkedIssue, EventDispatchOption.DO_NOT_DISPATCH, false)
            // Индексация            boolean wasIndexing = ImportUtils.isIndexIssues()            ImportUtils.setIndexIssues(true)            issueIndexingService.reIndex(issueManager.getIssueObject(linkedIssue.id))            ImportUtils.setIndexIssues(wasIndexing)    }            // IT-69956    TransitionOptions transitionOptions = new TransitionOptions.Builder().skipConditions().skipValidators().skipPermissions().build();    linkedIssues.each {        CustomFieldManager cfm = ComponentAccessor.getCustomFieldManager();        IssueLinkManager ilm = ComponentAccessor.getIssueLinkManager();        IssueManager im = ComponentAccessor.getIssueManager();        IssueService is = ComponentAccessor.getIssueService();        UserManager um = ComponentAccessor.getUserManager();        MutableIssue targetIssue = (MutableIssue) it;        ApplicationUser user = um.getUserByName("jirarobot");//ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser()

        IssueInputParameters iip = is.newIssueInputParameters();        iip.addCustomFieldValue(17781L, null); // Отправить файл(ы)
        // EmailTo        String reporterEmail = targetIssue.getReporter().getEmailAddress();        String emailTo = targetIssue.getCustomFieldValue(cfm.getCustomFieldObject("customfield_13180")); // E-mail        if (emailTo != null && !emailTo.isEmpty() && reporterEmail != null && !reporterEmail.isEmpty()) {            if (!emailTo.contains(reporterEmail)) {                iip.addCustomFieldValue(13180L, reporterEmail + "," + emailTo); // E-mail            }        } else if ((emailTo != null && !emailTo.isEmpty()) || (reporterEmail != null && !reporterEmail.isEmpty())) {            if ((emailTo != null && !emailTo.isEmpty()) && (reporterEmail == null || reporterEmail.isEmpty())) {            iip.addCustomFieldValue(13180L, emailTo); // E-mail     } else {                iip.addCustomFieldValue(13180L, reporterEmail); // E-mail            }    } else {            iip.addCustomFieldValue(13180L, targetIssue.getAssignee().getEmailAddress()); // E-mail        }
        // EmailCc        String emailCc = targetIssue.getCustomFieldValue(cfm.getCustomFieldObject("customfield_13480")); // Копия        if (emailCc != null && !emailCc.isEmpty()) {            iip.addCustomFieldValue(13480L, emailCc); // Копия        }
        // EmailSubject        iip.addCustomFieldValue(13286L, targetIssue.getSummary()); // Тема письма
        // SendFiles        iip.addCustomFieldValue(17781L, null); // Отправить файл(ы)
        IssueService.TransitionValidationResult transitionValidationResult = is.validateTransition(user, targetIssue.getId(), transitionId, iip, transitionOptions);
        if (transitionValidationResult.isValid()) {            is.transition(user, transitionValidationResult);            log.info("GLOBAL INCIDENT linked issue " + targetIssue.getKey() + " transition must be GOOD");        } else {            log.warn("GLOBAL INCIDENT linked issue " + targetIssue.getKey() + " transition is BAD");        }
        im.updateIssue(user, targetIssue, EventDispatchOption.DO_NOT_DISPATCH, false);    }    
    // 2) Adding new components from global incident to sub-tasked incidents    ArrayList<ProjectComponent> globalComponents = new ArrayList<>()    globalComponents.addAll(issue.getComponents())
    if (globalComponents.size() > 0) {        linkedIssues?.each {            linkedIssue ->                ArrayList<ProjectComponent> localComponents = new ArrayList<>()                localComponents.addAll(linkedIssue.getComponents()) // берем компоненты подзапроса                localComponents.removeAll(globalComponents) // из них удаляем те, что есть в массовом                localComponents.addAll(globalComponents) // добавляем все из массового
                ((MutableIssue)linkedIssue).setComponent(localComponents)                issueManager.updateIssue(jirarobot, (MutableIssue) linkedIssue, EventDispatchOption.DO_NOT_DISPATCH, false)        }    }}

1 answer

Hey there,

I've had more than one issues with emails in postfunction scripts and such.Therefore, my advice:

Dont use it.

Create an event, fire that in the transition you want to notify users about, and then setup the notification scheme accordingly. Its cleaner and works better, usually.

regards

Suggest an answer

Log in or Sign up to answer
TAGS
Community showcase
Published in Jira Service Management

JSM June Challenge #2: Share how your business teams became ITSM rockstars

For JSM June Challenge #2, share how your non-technical teams like HR, legal, marketing, finance, and beyond started using Jira Service Management! Tell us: Did they ask to start using it or...

167 views 6 7
Read article

Community Events

Connect with like-minded Atlassian users at free events near you!

Find an event

Connect with like-minded Atlassian users at free events near you!

Unfortunately there are no Community Events near you at the moment.

Host an event

You're one step closer to meeting fellow Atlassian users at your local event. Learn more about Community Events

Events near you