Chapter 3: Enhancing Rules with Smart Values

The visual rule editor, which we explored in Chapter 1, Key Concepts of Automation, makes the creation of complex automation rules really easy and requires no knowledge of the Jira API or any specialist scripting knowledge in order to get started.

While this approach will work for a large number of use cases, there will always be cases where you will need direct access to issue data and the ability to perform more complex functions against this data. This is where smart values come to the rescue.

This chapter will introduce you to smart values. You will learn how to find smart values, how smart functions work, and how you can introduce your own smart values into automation rules. You will also get an overview of how to manipulate dates, lists of data, text values, and how to perform numeric calculations using math expressions.

In this chapter, we'll cover the following topics:

  • Understanding smart values
  • Using smart value date functions
  • Using smart value text functions
  • Using smart value list functions
  • Using smart value math expressions and functions

By the end of this chapter, you will have learned how you can use smart values and functions to manipulate dates, text strings, and lists, as well as how to use math expressions and functions to perform calculations involving numerical values.

Technical requirements

The requirements for this chapter are as follows:

  • Jira Cloud environment: If you don't already have access to Jira, you can create a free Jira Cloud account at https://www.atlassian.com/software/jira/free and ensure that you have both Jira Software and Jira Service Management selected.
  • Jira Server environment: If you are using Jira Server (available from https://www.atlassian.com/software/jira/download), ensure you have licenses for both Jira Software and Jira Service Management. In addition, you will also need to ensure that you install the Automation for Jira app, available from the Atlassian Marketplace.

In both instances, you will need to have at least project administrator access to a Service Management project and a Scrum Software project to be able to follow the examples in this chapter. For the examples in this chapter, we have used the IT Service Management project template to create the Service Management project, and the Scrum Software project template to create the Software project.

You can download the latest code samples for this chapter from this book's official GitHub repository at https://github.com/PacktPublishing/Automate-Everyday-Tasks-in-Jira. The Code in Action videos for this chapter are available at https://bit.ly/39Hk44d.

Understanding smart values

Smart values allow you to access and manipulate almost all issue data in the context of an automation rule. In addition to allowing you to access the issue data, smart values also provide advanced functionality in the form of functions that allow you to perform complex operations on the issue data.

In this section, we'll explore what smart values are available to you and how to recognize and use them in rules. We will also introduce you to smart value functions and explain how you can create your own smart values for use in your rules.

Let's begin by taking a look at where we can find smart values and how to use them.

Finding and using smart values

Smart values are generally set in the rule context by the trigger that initiated execution of the rule. In addition, certain actions, such as the Send web request action, can also introduce smart values into the rule context.

Each of the smart values made available by these triggers are data structures that contain fields. These can either be simple field types, such as text or numbers, or more complex data structures that, in turn, contain other fields.

For example, a trigger such as Issue updated will set the smart value {{issue}} to the current Jira issue in the rule context. This smart value is a data structure that represents an issue in Jira and contains both simple and complex fields.

Examples of simple fields would be {{issue.summary}} and {{issue.key}}, which allow you to access the summary and key of the issue, respectively. An example of a complex field, a field that itself is a data object, would be {{issue.assignee}}, as it itself contains further fields, which allow you to access the assignee's display name, email address, and accountId fields in the case of Jira Cloud or key in Jira Server or Jira Data Center. These would be represented as follows: {{issue.assignee.displayName}}, {{issue.assignee.emailAddress}}, {{issue.assignee.accountId}}, and {{issue.assignee.key}}, respectively.

Tip

To access a custom field in a smart value, you can either use the custom field's name or its ID. For example, if you had a custom field named My Custom Field with an ID value of 10000, you could access it in a smart value as either {{issue.My Custom Field}}, {{issue.my custom field}}, or {{issue.customfield_10000}}. You can find the custom field ID by editing the custom field from the Custom Fields admin section and copying the ID from the resulting URL. However, you should only use this approach if, for some reason, you have multiple custom fields with the same name.

In the following table, we can see the smart values made available by each automation trigger that you can use in subsequent rule components:

Figure 3.1 - Smart values available by trigger

Figure 3.1 - Smart values available by trigger

The preceding table shows the main smart value for each trigger and, for the majority of cases, you can find the fields available for each of these smart values listed at https://support.atlassian.com/jira-software-cloud/docs/smart-values-general for Jira Cloud, or https://confluence.atlassian.com/display/AUTOMATION/Smart+values for Jira Server and Jira Data Center.

Smart values are based on the Mustache templating system (https://mustache.github.io). To use smart values (or tags, as they are referred to in Mustache), you surround keys using double curly braces (or mustaches). Using this format signifies to the rule engine that it needs to treat the given value as a smart value, and not just static text.

To access fields within smart value objects, you use dot notation. For example, to access the display name of the assignee of an issue, you would use dot notation as follows: {{issue.assignee.displayName}}.

Tip

When you reference a field or value that does not exist in a particular issue, the smart value will be empty. You can instead specify that a smart value has a default value by using the pipe (|) symbol. For example, the smart value {{issue.description|No description was supplied}} will return the text No description was supplied if the Description field is empty.

Smart values can be used in Advanced compare condition, JQL condition, and User condition, as well as in most rule actions.

Let's take a look at an example rule that uses smart values.

Creating a rule to add a comment when issues first become assigned

In this example rule, we are going to add a comment to the issue when the issue is first assigned, which will notify the reporter that we're working on their request:

  1. In your Service Management project, navigate to Project settings, click the Automation tab, and then click on Create rule.
  2. Select Issue assigned and then click Save.
  3. Then select New condition followed by Advanced compare condition.

    We need to examine the changelog to ensure that the previous assignee was empty before continuing. The changelog contains all the fields that were changed in the issue during the update that caused the trigger to fire. For each changed field, the changelog will contain the from and to values, as well as the text representations of those values in the fromString and toString fields.

    Set the condition fields as follows and click Save:

    First value: {{changelog.assignee.fromString}}

    Condition: equals

    Second value: Leave blank

  4. Now, select New action and then Comment on issue.

    Add the following text to the Comment field and click Save:

    Hi {{issue.reporter.displayName}}

    We're now looking into your issue {{issue.summary}}.

    We'll get back to you soon with an update.

    {{issue.assignee.displayName}}.

    The rule should look as follows:

    Figure 3.2 - Using smart values in a rule

    Figure 3.2 - Using smart values in a rule

  5. Finally, name the rule Comment to reporter on issue assigned and click Turn it on to save and enable the rule.

In this section, we learned how we can use smart values in our rules to make them more flexible and, in the next section, we will introduce you to smart value functions.

Smart value functions

In addition to the ability to access data fields with smart values, you can also manipulate these data values with the addition of functions.

Functions are generally appended to the end of smart values using dot notation. For example, to truncate the issue summary to the first 50 characters and add an ellipsis to the end of the truncated summary, we would use the following smart function: {{issue.summary.abbreviate(50)}}.

Important note

Smart value functions can only be applied to fields of the corresponding type. For example, date and time functions can only be applied to the created, updated, duedate, resolutiondate, and any custom fields with Date Picker or Date Time Picker types.

Smart functions can also be chained together, allowing us to perform multiple transformations in a single step. For example, the following smart function chain will convert the summary to lowercase, extract the fifth to tenth characters, and then append an exclamation to the end: {{issue.summary.toLowerCase().substring(5,10).concat("!")}}.

Let's look at an example of using smart value functions in a rule.

Creating a rule to add a comment asking for screenshots

In this example, we are going to create a manually triggered rule that a user can invoke to create a customized comment on the issue requesting the reporter to upload attachments to help further diagnose an issue:

  1. In your Service Management project, navigate to Project settings, click the Automation tab, and then click on Create rule.
  2. Select Manual trigger and click Save.
  3. Next, select New action followed by Comment on issue.

    Add the following text to the Comment field and click on Save:

    Hi {{issue.reporter.displayName.split(" ").first}}

    We require a little more info in order to diagnose your issue further.

    Please take a screenshot and attach it to this issue by no later than {{now.plusBusinessDays(2).fullDate}}.

    Thank you :)

    {{issue.assignee.displayName}}

    The rule should look similar to the following screenshot:

    Figure 3.3 - Using smart value functions

    Figure 3.3 - Using smart value functions

  4. Finally, name the rule Ask reporter to attach screenshot and click Turn it on to save and enable the rule.

    Important note

    In Jira Cloud, it is possible to use the Create variable action to create a custom smart value based on other smart value functions and expressions that you can then make use of in later conditions and actions.

In this section, we learned what smart values are and how we can use them to access data in automation rules. We also learned how to find the correct smart value for triggers and how to find the associated smart value fields. We also looked at smart value functions and saw how we can chain them together to apply multiple transformations in a single step.

In the next section, we will look at how we can use smart values to manipulate and format dates in automation rules.

Using smart value date functions

As a project management and tracking tool, having the ability to manipulate dates in Jira is critical to the correct operation of the application, and smart values in automation rules give us a lot of flexibility in how we can use and manipulate dates and times in rules.

In this section, we will look at how we can use smart values to format dates and times for inclusion in other date and time fields, as well as how to format them for use in other fields such as text fields, the advanced field editor, or for use in notifications.

We will also explore all the available formats and functions applicable to dates and see how we can use these in automation rules.

Tip

You can access the current date and time using the smart value {{now}}. All formatting and date manipulation functions that can be used with date fields can also be used with the {{now}} smart value.

Let's take a look at how we can format dates using smart value functions.

Formatting dates

The ability to format dates and times gives us flexibility in how we can display these to users, in either comments, text fields, or notifications. It also allows us to be able to specify the exact format to use when communicating with external systems that require date and time inputs in specific formats and in reformatting dates and times received from external systems.

Finally, being able to control the format of dates and times allows us to manipulate them using smart value functions and ensure that we can set a date or time field with the resulting calculation correctly.

In the following table, we can see how the date, Tuesday, December 31, 2019 10:25:30 PM CET will be formatted using each of the available date and time formats available to automation rules:

Figure 3.4 - Available date formats

Figure 3.4 - Available date formats

As you can see from the preceding list, dates and times can be formatted for display in a variety of ways, and it is also possible to use a custom pattern if none of the standard ones are suitable.

Tip

The pattern syntax used for the custom formatters format("pattern") and as("pattern") are defined by the underlying Java platform and the full syntax descriptions can be found at the following link, https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/format/DateTimeFormatter.html, under the heading Patterns for Formatting and Parsing.

Formatting dates with locales and time zones

In addition to the formats that we have just looked at, with smart values, it is also possible to format dates and times for specific locales and time zones, or even the locale or time zone of a specific user, such as the assignee or reporter of an issue.

The following formatting functions are provided to enable locale- and time zone-based formatting of dates and times:

  • locale(string locale)/withLocale(string locale): Formats the date field using the given locale. For example, you can use {{issue.created.withLocale("fr_CA")}} to format the issue created date using Canadian French, or {{issue.created.withLocale(issue.reporter.locale)}} to format the issue created date using the reporter's locale.
  • convertToTimeZone(string timezone): Converts the time in the DateTime field to the given time zone. For example, you can use {{issue.created.convertToTimeZone("America/New_York")}} to format the issue created date to display in the current time zone in New York, or {{issue.created.convertToTimeZone(issue.reporter.timeZone)}} to format the issue created date to the reporter's time zone.
  • setTimeZone(string timezone): Sets the time zone component of the DateTime field to the given time zone. This function will change the time zone without converting the time.

The full list of supported locales can be found at https://www.oracle.com/java/technologies/javase/jdk11-suported-locales.html#modules. The list of time zones is defined by the tz database and the full list can be found at https://en.wikipedia.org/wiki/List_of_tz_database_time_zones.

Let's see how we can use date formats in an example rule.

Creating a rule to create onboarding sub-tasks

In this rule, when a new employee onboarding request is created, we need to ensure that certain tasks, such as provisioning a laptop and desk phone, are completed before the new employee starts.

We want the sub-task summaries to include the start date so that it is immediately apparent to the user assigned to the request when the task is due:

  1. In your Service Management project, navigate to Project settings, click on the Automation tab, and then click on Create rule.
  2. Select the Issue created trigger and click Save.
  3. Then select New condition followed by Issue fields condition.

    Complete the fields as follows, and then click Save:

    Field: Request Type

    Condition: equals

    Value: Onboard new employees

  4. Next, select New action, followed by the Create sub-tasks action.

    Add two sub-tasks with the following summaries:

    Provision new laptop by {{issue.duedate.longDate}}

    Setup new desk phone by {{issue.duedate.longDate}}

    The rule should look similar to the following screenshot:

    Figure 3.5 - Using the smart value date format

    Figure 3.5 - Using the smart value date format

  5. Finally, click Save, name the rule Create onboarding sub-tasks, and click Turn it on to save and enable the rule.

Now that we've seen how to format dates and time, let's take a look at how we can manipulate them using smart value functions.

Manipulating dates

In addition to providing the ability to format dates, a number of smart value functions are provided that enable us to perform operations on dates. These operations allow us to perform comparisons on dates and times, perform basic arithmetic on dates and times, and manipulate the various components of dates and times.

Let's take a look at the functions you can use to manipulate dates in your rules. The first set of functions relate to date comparisons and allow you to compare one date with another:

  • isBefore(date): Checks whether the date field used to call the function is before the date supplied as the function parameter. This function will return true if the date is earlier than the date parameter, and false otherwise.
  • isAfter(date): Checks whether the date field used to call the function is after the date supplied as the function parameter. This function will return true if the date is later than the date parameter, and false otherwise.
  • isEquals(date): Checks whether the date field used to call the function is equal to the date supplied as the function parameter. This function will return true if the date is exactly equal to the date parameter, and false otherwise.
  • compareTo(date): Checks whether the date field used to call the function is earlier than, equal to, or later than, the date supplied as the parameter. This function returns a negative integer (such as -1) when the date field used to call the function is earlier than the date in the parameter, 0 if they are equal, or a positive integer (such as 1) if the date field is later than the date field in the parameter.

The next set of functions allows us to manipulate dates and times in various ways:

  • diff(date): This function calculates the difference between the date field used to call the function and the date supplied as the parameter. The result can be refined to display the difference, using any of the components of a date, including millis, seconds, minutes, hours, days, weeks, months, years, or businessDays by appending this to the end of the function. For example, diffDate(date).seconds will display the difference between the dates in seconds. The default output is prettyPrint, which displays the difference in words, for example, 2 days 3 hours.
  • plusDays(int days)/minusDays(int days): Adds or subtracts the given number of days to or from the respective date component and returns a new date with the relevant calculation applied.
  • plusHours(int hours)/minusHours(int hours): Adds or subtracts the given number of hours to or from the respective date component and returns a new date with the relevant calculation applied.
  • plusWeeks(int weeks)/minusWeeks(int weeks): Adds or subtracts the given number of weeks to or from the respective date component and returns a new date with the relevant calculation applied.
  • plusMillis(int millis)/minusMillis(int millis): Adds or subtracts the given number of milliseconds to or from the respective date component and returns a new date with the relevant calculation applied.
  • plusMinutes(int minutes)/minusMinutes(int minutes): Adds or subtracts the given number of minutes to or from the respective date component and returns a new date with the relevant calculation applied.
  • plusMonths(int months)/minusMonths(int months): Adds or subtracts the given number of months to or from the respective date component and returns a new date with the relevant calculation applied.
  • plusSeconds(int seconds)/minusSeconds(int seconds): Adds or subtracts the given number of seconds to or from the respective date component and returns a new date with the relevant calculation applied.
  • plusYears(int years)/minusYears(int years): Adds or subtracts the given number of years to or from the respective date component and returns a new date with the relevant calculation applied.
  • plusBusinessDays(int days)/minusBusinessDays(int days): Adds or subtracts the given number of business days to or from the respective date component and returns a new date with the relevant calculation applied. A business day is defined as the hours of 9 a.m. to 6 p.m., Monday to Friday.
  • toBusinessDay/toBusinessDayBackwards: Returns the first business day after or before the date used to call the function, respectively.
  • toStartOfDay/toDateTimeAtStartOfDay: Sets the time components to zero (that is, midnight) for the given date using the server's default time zone. The first function is used for DateTime fields, while the second function will convert a Date field to a DateTime field and set the time component accordingly.
  • toCurrentTime/toDateTimeAtCurrentTime: Sets the time components to the current time for the given date. The first function is used for DateTime fields, while the second function will convert a Date field to a DateTime field and set the time component accordingly.
  • withNextDayOfWeek(string dayOfWeek): Sets the date to the next matching day of the week. It accepts MON, TUE, WED, THU, FRI, SAT, or SUN as values for the dayOfWeek parameter.
  • withDayOfMonth(int dayOfMonth): Sets the day of month component of the Date or DateTime field to the supplied dayOfMonth. The allowable range for the dayOfMonth parameter is 1 to 31.
  • withHour(int hour): Sets the hour component of the DateTime field to the supplied hour. The allowable range for the hour parameter is 0 to 23.
  • withMillis(int millis): Sets the milliseconds component of the DateTime field to the supplied millisecond. The allowable range for the millis parameter is 0 to 999.
  • withMinute(int minute): Sets the minute component of the Date or DateTime field to the supplied minute. The allowable range for the minute parameter is 0 to 59.
  • withMonth(int month): Sets the month component of the Date or DateTime field to the supplied month. The allowable range for the month parameter is 1 to 12.
  • withSecond(int second): Sets the second component of the DateTime field to the supplied second. The allowable range for the second parameter is 0 to 59.
  • withYear(int year): Sets the year component of the Date or DateTime field to the supplied year. The allowable range for the year parameter is any valid year in the Gregorian calendar.
  • withDayOfYear(int dayOfYear): Sets the day of year component of the Date or DateTime field to the supplied dayOfYear. The allowable range for the dayOfYear parameter is 1 to 365.
  • startOfMonth/endOfMonth: Sets the date component of the Date or DateTime field to the first or last calendar day of the month in the field's month component.
  • firstBusinessDayOfMonth/lastBusinessDayOfMonth: Sets the day of month component of the Date or DateTime field to the first or last business day of the month in the field's month component.
  • firstOfTheMonth(int dayOfWeek)/lastOfTheMonth(int dayOfWeek): Sets the date component of the Date or DateTime field to the first or last weekday of the month based on the day of the week supplied in the parameter. The day of the week parameter is in the range 1 to 7, 1 being Monday and 7 being Sunday. For example, calling {{datefield.firstOfTheMonth(3)}} will set the date to the first Wednesday of the month.
  • ofTheMonth(int weekOfMonth, int dayOfWeek): Sets the date component of the Date or DateTime field to the supplied day of the week in the supplied week of the month. The range for the weekOfMonth parameter is from 1 to 5 and the range for the dayOfWeek parameter is 1 to 7, 1 being Monday and 7 being Sunday. For example, to set the date to the third Monday of the month, you would use {{datefield.ofTheMonth(3, 1)}}.

Now that we've taken a look at the various functions available to manipulate dates and times, let's take a look at a couple of examples of how to use them in rules.

Creating a rule to update the due date based on sub-tasks

For this example, we have a number of sub-tasks for each user story in the software project, and we would like to update the due date of the user story to 5 business days from the current date when the last sub-task transitions to In Progress:

  1. In your Software project, navigate to Project settings, click the Automation tab (or Project automation tab if you're using Jira Server), and then click on Create rule.
  2. Select the Issue transitioned trigger and set the To status field to In Progress and then click Save.
  3. Then select New condition followed by Issue fields condition.

    Set the condition fields as follows and click Save:

    Field: Issue Type

    Condition: equals

    Value: Sub-task

  4. Next, select Branch rule / related issues, set Type of related issues to Parent, and then click Save.
  5. Now select New condition, followed by Related issues condition.

    Set the condition fields as follows and then click Save:

    Related issues: Sub-tasks

    Condition: All match specified JQL

    Matching JQL: status = "In Progress"

  6. Select New action and then select Edit issue action. In the Choose fields to set dropdown, select Due date and enter {{now.plusBusinessDays(5)}} in the Due date field and click Save.

    Your rule should now look similar to the following screenshot:

    Figure 3.6 - Adding business days to the current date

    Figure 3.6 - Adding business days to the current date

  7. Finally, name your rule Set user story due date and click Turn it on to save and enable the rule.

Let's now take a look at another example of using smart value functions to manipulate dates.

Creating a rule to set the due date

For this example, we want to set the due date of an issue to the 15th of the current month if the issue is created before the 15th of the month, and to the 15th of the following month if the issue is created after the 15th of the month:

  1. In your Software project, navigate to Project settings, click the Automation tab (or the Project automation tab if you're using Jira Server), and then click on Create rule.
  2. Select Issue created and then click Save.
  3. Next, select New condition, followed by If / else block, and add an Advanced compare condition to the If block.
  4. Set the fields for the Condition as follows and then click Save:

    First value: {{issue.created}}

    Condition: greater than

    Second value: {{now.startOfMonth.plusDays(15)}}

  5. Now select New action and then Edit issue. Select Due date from the Choose fields to set dropdown and then set the Due date field to {{now.endOfMonth.plusDays(15)}} and click Save.

    Your rule should now look as per the following screenshot:

    Figure 3.7 - Setting the date to the middle of next month

    Figure 3.7 - Setting the date to the middle of next month

  6. Now that we've dealt with due dates for next month, let's complete the rule for due dates this month. Click on Add else in the rule-chain view and then click Save.
  7. Next, add a New action field, followed by Edit issue. Again, select Due date from the Choose fields to set dropdown and then set the Due date field to {{now.withDayOfMonth(15)}} and click Save.

    Your rule should look similar to the following screenshot:

    Figure 3.8 - Setting the date to the middle of the current month

    Figure 3.8 - Setting the date to the middle of the current month

  8. Finally, name the rule Set due date to middle of the month and click Turn it on to save and enable the rule.

In this section, we have taken a look at the various smart value date and time functions available and learned how to use these to manipulate dates in automation rules. Next, we'll take a look at how we can use smart values to work with text.

Using smart value text functions

In a similar fashion to working with dates and times, smart value functions that deal with text strings allow us to manipulate any text field type, including the sub-attributes of fields where they are also text-type fields.

In this section, we will look at how smart value functions for text allow us to manipulate text, encode it for use in HTML, JSON, XML, or URLs, and how we can use functions to test for specific characteristics within blocks of text.

Let's take a look at the functions available to manipulate text in automation rules. The first set of functions we'll look at deal with text comparisons and return either true or false depending on whether the check passes or fails:

  • startsWith(string)/endsWith(string): Checks whether the text field starts or ends with the given string, respectively
  • equals(string)/equalsIgnoreCase(string): Checks whether the text field equals the given string exactly or ignoring capitalization, respectively
  • isAlpha: Checks whether the text field contains only letters
  • isNumeric: Checks whether the text field contains only numbers
  • isAlphaNumeric: Checks whether the text field contains only letters and numbers
  • isEmpty: Checks for the absence of data in the text field
  • isNotEmpty: Checks for the presence of data in the text field

The next set of functions allows us to convert text into other types, such as numbers, dates, or lists:

  • asNumber: Converts the text field to a number allowing you to perform numeric operations and calculations on the converted value.

    Tip

    Use the isNumeric test on the text field prior to conversion to ensure you don't get errors by trying to convert text that cannot be represented as numbers.

  • toDate/toDate(string pattern): Converts a text field to a date. Use the second form of the function to specify what the format of the date in its textual representation should be. Refer to the Formatting dates section for examples of how to define the pattern.
  • split(string separator): Splits a text field into a list of items around the separator. The resulting list of items can then be manipulated using the smart value list functions.
  • match(string regularExpression): Performs a regular expression search on the text field. Multiple matches of regularExpression are returned as a list of items that can be manipulated further using the smart value list functions.

    Tip

    A regular expression is a special text string for describing a search pattern. These patterns are usually used to perform find or find-and-replace operations on text strings or to validate input. In Jira automation, regular expressions are based on the underlying Java implementation, which can be found at https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html.

The following set of functions allows us to change the way text is displayed, extract portions of text, or even replace blocks of text:

  • abbreviate(int maxLength): Abbreviates the text field to the maximum length specified and adds an ellipsis ("…") to the end of the text.
  • toLowerCase: Converts the text field to all lowercase.
  • toUpperCase: Converts the text field to all uppercase.
  • capitalize: Converts the first character of the text field to uppercase.
  • reverse: Reverses all the characters of the text field.
  • trim: Removes all leading and trailing white spaces from the text field.
  • concat(string): Appends the given string to the end of the text field.
  • charAt(int index): Returns the character at the specified position in the text. The first character is at index 0.
  • indexOf(string) / lastIndexOf(string): Finds the first or last position of the given string within the text field.
  • length: Returns the total number of characters of the text field.
  • quote: Formats the text field into a literal expression that can then be used in a regular expression in the match function. For example, if the text field contains regular expression special characters, such as * or , these will be treated as normal (or literal) characters rather than as regular expressions.
  • remove(string): Removes all occurrences of the given string from the text field.
  • replace(string target, string replacement): Replaces the target string in the text field with the replacement string value.
  • replaceAll(string regex, string replacement): Replaces all occurrences in the text field of the regular expression regex with the replacement string.
  • left(int length)/right(int length): Returns the specified number of characters from either the left or right of the text field, respectively.
  • leftPad(int length, string)/rightPad(int length, string): Adds the given string to either the left or right of the text field until the text reaches the total length specified.
  • substring(int start): Returns a portion of the text field beginning at the start index.
  • substring(int start, int end): Returns a portion of the text field beginning at the start index and ending at the end index.
  • substringAfter(string)/substringAfterLast(string): Returns a portion of the text field after the first or last occurrence of the supplied string, respectively.
  • substringBefore(string)/substringBeforeLast(string): Returns a portion of the text field before the first or last occurrence of the supplied string, respectively.
  • substringBetween(string open, string close): Returns a portion of the text field between the given start and end strings.

The final set of functions allows us to encode text to comply with specific standards. This is especially useful when integrating with external systems or when sending email notifications from rules:

  • htmlEncode: Use this function to ensure the text field value is correctly encoded when including the field in HTML output.
  • jsonEncode): Use this function to ensure the text field value is correctly encoded when including the field in JSON output.
  • urlEncode: Use this function to ensure the text field value is correctly encoded when using the field to create a URL link.
  • xmlEncode: Use this function to ensure the text field value is correctly encoded when including the field in XML output.

Now that we've looked at the various functions available that we can use to manipulate text, let's take a look at how we can leverage these in automation rules.

Creating a rule to auto-close an issue

A common scenario faced by many teams is that after a ticket has been resolved, the reporter replies to say thank you. This will generally cause the ticket to re-open and someone will have to manually go and resolve the ticket again.

In this example, we'll use text smart value functions to examine the latest comment and auto-resolve the issue if we find the words "thank you":

  1. In your Service Management project, navigate to Project settings, click the Automation tab, and then click on Create rule.
  2. Select the Issue transitioned trigger, set the From status field to Resolved, the To status field to In Progress, and then click Save.
  3. Now select New condition followed by Advanced compare condition.

    Complete the condition fields as follows and click Save:

    First value: {{issue.comments.last.body.trim.toLowercase}}

    Condition: contains regular expression

    Second value: thanks+you

    The rule should now look as follows:

    Figure 3.9 - Using text smart value functions in conditions

    Figure 3.9 - Using text smart value functions in conditions

  4. Next, select New action and then Transition issue. Set Transition the issue by to Selecting the destination status, and, in the Destination status field, select Resolved and then click Save.
  5. Name the rule Auto-resolve thank you comments and click Turn it on to save and enable the rule.

In this section, we have seen how we can use smart value functions to compare and manipulate text values. In the next section, we'll take a look at how we can use smart values and functions to work with lists of items.

Using smart value list functions

There are a number of scenarios you'll come across when authoring automation rules, where you'll be presented with a list of items. This could be a list of versions or components attached to an issue, or a list of issues, such as all the sub-tasks of a particular issue.

Smart value functions for lists give us the ability to work with these lists of items by iterating over each item and being able to perform additional functions against attributes of the items. We also have access to functions that allow us to perform simple calculations against all the items in a list.

In this section, we'll take a look at the smart value functions available for accessing and formatting lists of items.

We'll cover examples of iterating over lists using smart values when we look at sending notifications via email and Slack in Chapter 4, Sending Automated Notifications.

Let's now take a look at the smart value functions available for working with lists:

  • isEmpty: Checks whether a list contains any items. This function will return true if the list is empty and false if it contains items.
  • size: Returns the number of items in the list.
  • join(string separator): Joins all the items in the list into a single text value, separated by the supplied separator.
  • get(int index)/getFromEnd(int index): Gets the item in the specified location from the front or end of the list, respectively. The position of items in the list are counted starting from 0 (zero) on either end of the list.
  • first: Retrieves the first item of the list.
  • last: Retrieves the last item of the list.
  • average: Computes the average of all the items in a numerical list.
  • max: Finds the item with the largest number in a numerical list or finds the latest date in a list of dates.
  • min: Finds the item with the smallest number in a numerical list or finds the earliest date in a list of dates.
  • sum: Computes the sum of all the items in a numerical list.

Let's take a look at how we can incorporate what we have learned about lists into a practical example that uses a smart value list function to calculate the sum of story points in sub-tasks.

Creating a rule to sum up sub-task story points in a parent story

In this example, we are tracking story points against sub-tasks and would like to ensure that the parent story always reflects the correct total of story points whenever the story points in one of its sub-tasks' changes. You will need to enable the configuration context for the Story Points custom field to include sub-tasks in addition to Epics and Stories:

  1. In your Software Project, navigate to Project settings, click the Automation tab (or the Project automation tab if you're using Jira Server), and then click on Create rule.
  2. Select Field value changed, set Fields to monitor for changes to Story Points, and then click Save.
  3. Now select New condition followed by Issue fields condition.

    Set the condition fields as follows and click Save:

    Field: Issue Type

    Condition: equals

    Value: Sub-task

  4. Then select Branch rule / related issues and set Type of related issues to Parent and click Save.
  5. Next, select New action and then select Edit issue.
  6. In the Choose fields to set dropdown, find and select Story Points in the Story Points field.

    Add the following smart value expression and click Save:

    {{issue.subtasks.Story Points.sum}}

    Your rule should now look as per the following screenshot:

    Figure 3.10 - Using a smart value list function to sum list item values

    Figure 3.10 - Using a smart value list function to sum list item values

  7. Finally, name the rule Keep parent in sync with sub-task story points and click Turn it on to save and enable the rule.

In this section, we have learned how we can use smart value list functions to iterate over items in a list and how to perform operations against values in a list.

Next we'll take a look at the mathematical operations available for use in automation rules.

Using smart value math expressions and functions

So far, we have seen how to use smart values for working with dates, text, and lists and how they are able to help you create powerful and flexible automation rules.

In this section, we are going to look at math expressions and functions. Math expressions and functions will allow you to perform calculations directly in numeric fields as well as allow you to reference numeric fields in calculations for display in text fields. In Jira, all numeric fields are based on floating-point numbers.

To use any of the math expressions, they need to be surrounded by the following smart value block in order to be recognized as shown in the following example:

{{#=}} <math expression> {{/}}

The {{#=}} operator signifies to the automation engine that you are about to perform a calculation and is a custom addition to the underlying Mustache library.

Important note

Jira Cloud offers additional capabilities for working with numbers, including the ability to format numbers using locales or with custom patterns.

Let's take a look at the math expressions in common between Jira Cloud and Jira Server first.

Math expressions support the usual operations you'd expect to see, as can be seen in the following table:

Figure 3.11 - Basic math expression operators

Figure 3.11 - Basic math expression operators

In addition to the basic operations, math expressions support Boolean operators as well, and the supported operators can be seen in the following table:

Figure 3.12 - Boolean math expression operators

Figure 3.12 - Boolean math expression operators

Math expressions also support a number of functions that can be used, and we can see a full list of supported functions in the following table:

Figure 3.13 - Supported math functions

Figure 3.13 - Supported math functions

There are also a few constant values that are supported for use in math expressions, and these are listed here:

Figure 3.14 - Support constant values

Figure 3.14 - Support constant values

In addition to the preceding common functions and operations, Jira Cloud introduces some additional numerical operations. These operations do not need to be surrounded by the smart value block we learned about earlier, but rather can be applied directly to numerical smart values or fields.

Let's take a look at these additional numerical operations:

  • abs: Returns the absolute value of a number
  • round: Returns a number rounded to the nearest whole number
  • floor/ceil: Returns the lower or upper value of a number, respectively
  • plus(value)/minus(value): Adds or subtracts the number or smart value in the parameter to or from the numerical value or field used to call the operation
  • multiply(value)/divide(value): Multiplies or divides the number or smart value in the parameter with or by the numerical value or field used to call the operation
  • gt(value)/gte(value): Checks whether the numerical smart value is greater than, or greater than or equal to, the value given in the parameter
  • eq(value): Checks whether the numerical smart value is equal to the value given in the parameter
  • lt(value)/lte(value): Checks whether the numerical smart value is less than, or less than or equal to, the value given in the parameter

Jira Cloud also adds the ability to format numerical values using smart value functions, and these functions are listed here:

  • format: Formats the numerical field using the numerical format of the US locale.
  • formatWithLocale(locale): Formats the numerical field using the numerical format of the supplied locale, for example, fr_CA.
  • format(string pattern): Formats the numerical field using a custom pattern. The patterns you can use rely on the underlying Java implementation and can be found at the following link: https://docs.oracle.com/javase/tutorial/java/data/numberformat.html.
  • asPercentage/asPercentage(string locale): Formats the numerical field as a percentage in the US locale or as a percentage in the locale specified.
  • asCurrency/asCurrency(string locale): Formats the numerical field as a currency in the US locale or as a currency in the locale specified.

As we've seen, there is a comprehensive number of smart value functions that we can make use of to perform advanced mathematical operations in automation rules. Let's now take a look at using math expressions in an example.

Creating a rule to keep an original estimate for an epic in sync with its child issues

In this example, we're going to update the original estimate of an epic any time tracking fields in the epic's underlying issues change:

  1. In your Software project, navigate to Project settings, click the Automation tab (or the Project automation tab if you're using Jira Server), and then click on Create rule.
  2. Select the Field value changed trigger and, in the Fields to monitor for changes list, select Time tracking and then click Save.
  3. Next, select New condition and then Related issues condition.

    Set the fields of the condition as follows and click Save:

    Related issues: Epic

    Condition: Exists

  4. Now select Branch rule / related issues and, in the Type of related issues field, select Epic (parent) and click Save.
  5. Then, select Edit issue. In the Choose fields to set dropdown, find and select Original Estimate (System).

    Add the following math expression to the Original Estimate (System) field and click Save:

    {{#=}}{{fieldChange.to}}/60 – {{fieldChange.from}}/60 + {{issue.original estimate}}/60{{/}}

    The rule should now look similar to the following screenshot:

    Figure 3.15 - Using math expressions in a rule

    Figure 3.15 - Using math expressions in a rule

  6. Finally, name the rule Keep Epic estimates in sync and click Turn it on to save and enable the rule.

In this section, we have seen the comprehensive list of smart value mathematical functions available for use in your automation rules and how we can use these to manipulate numerical values.

Summary

In this chapter, you have learned how to enhance the functionality of automation rules by using smart values and smart value functions.

We learned which smart values are set by the various triggers and how you can access their attributes or fields. In addition, you learned about smart value functions and how they can be used in isolation against a particular field or chained together to perform multiple operations on data in a single step.

Finally, we learned about the various smart value functions available for dates, text, lists, and numerical values and how these can be used to format and manipulate data to create extremely powerful and flexible rules.

Smart values and their associated functions can be used in nearly every field in automation rule conditions and actions, and we'll learn throughout the rest of this book how they will help us to create much more powerful and richer rules as a result of their use.

In the next chapter, we will be looking at how to send notifications to various channels from your automation rules.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.22.169