Forums

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

Automation for Jira is not working for Scriptrunner scripts

Vineela Durbha
Contributor
December 20, 2024

Hi Team,

I am trying to update a date field called "FTR" whenever another date field (FSD) is updated. 
I am trying to do this using Automation for Jira (attached screenshot). 
My script is as below

 

import com.atlassian.jira.component.ComponentAccessor 
import java.util.Calendar 

// Get the custom field manage 
def customFieldManager = ComponentAccessor.getCustomFieldManager() 

// Retrieve the custom fields by name 
def fsdField = customFieldManager.getCustomFieldObjectByName("FSD (First Service Date)") 
def ftrField = customFieldManager.getCustomFieldObjectByName("First Training Release Date") 

// Log if the fields are not found 
if (fsdField == null) { 
		return "FSD (First Service Date) custom field not found." 
} 

if (ftrField == null) { 
		return "First Training Release Date custom field not found." 
} 

// Get the value of the FSD field (date) 
def fsdDate = issue.getCustomFieldValue(fsdField) 

// Ensure fsdDate is not null 
if (fsdDate == null) { 
		return "FSD (First Service Date) field is empty or invalid." 
} 

// Log the original FSD date for debugging 
log.info("Original FSD Date: " + fsdDate) 

// Create a Calendar object to manipulate the date 
def calendar = Calendar.getInstance() 
calendar.setTime(fsdDate) 

// Loop to subtract 28 business days (skip weekends) 
int businessDaysToSubtract = 28 
int subtractedDays = 0

while (subtractedDays < businessDaysToSubtract) { 
			calendar.add(Calendar.DAY_OF_MONTH, -1) 

			// Go back one day // Check if it's a business day (Monday to Friday) 
      if (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && calendar.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) { 
					subtractedDays++ 
			} 
} 

// Get the new date after subtracting 28 business days 
def newDate = calendar.getTime() 

// Log the new date for debugging 
log.info("New Date after subtracting 28 business days: " + newDate) 

// Set the calculated date to the First Training Release Date field 
issue.setCustomFieldValue(ftrField, newDate) 

// Log success 
log.info("Successfully updated First Training Release Date field to: " + newDate) 

// Return success message 
return "First Training Release Date successfully updated to: ${newDate}"

 

 

 

But it is not updating the FTR field. 

Am i missing something here?Screenshot 2024-12-20 151733.png

2 answers

1 accepted

4 votes
Answer accepted
Ram Kumar Aravindakshan _Adaptavist_
Community Champion
December 22, 2024

Hi @Vineela Durbha

Since the FTR field is dependent on another field's value, why not use Behaviour or Listener instead of Automation?

Behaviours and Listeners are much simpler to manage than Automation and can do the exact same thing.

If you want to do this via Behaviour, you will need to create a Server-Side Behaviour. 

Below is a sample working code for your reference:-

import com.onresolve.jira.groovy.user.FieldBehaviours
import groovy.transform.BaseScript

@BaseScript FieldBehaviours behaviours
def sampleDate = getFieldById(fieldChanged)
def baselineDate = getFieldByName('Baseline Date')

if (sampleDate.value) {
def sampleDateValue = sampleDate.value as Date
def updatedDate = (sampleDateValue + 5).format('dd/MM/yy')
baselineDate.setFormValue(updatedDate)
}

Please note that the sample working code above is not 100% exact to your environment. Hence, you must make the required modifications.

Below is a screenshot of the Behaviour configuration:-

behaviour_config.png

 

If you would prefer to use the Listener, below is a sample working Listener code for your reference:-

def issue = event.issue
def sampleDateValue = issue.getCustomFieldValue('Sample Date') as Date

if (sampleDateValue) {
issue.update {
setCustomFieldValue('Baseline Date', sampleDateValue + 5)
}
}

Please note that the sample working code above is not 100% exact to your environment. Hence, you must make the required modifications.

Below is a screenshot of the Listener configuration:-

listener_config.png

I hope this helps to answer your question. :)

Thank you and Regards,

Ram

 

Vineela Durbha
Contributor
December 22, 2024

Hi @Ram Kumar Aravindakshan _Adaptavist_ 

Thank you for your advise. I cannot use behaviours because FTR field(other field ) will not be present on the edit screen. It will be only on view screen.
I tried to use listeners with below script but the value is not being set on the issue.

 

import java.time.*
import java.time.format.DateTimeFormatter
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.fields.CustomField
import com.atlassian.jira.issue.Issue
import java.util.*

Issue issue = event.issue
CustomField fsdCustomField = ComponentAccessor.getCustomFieldManager().getCustomFieldObjectByName("FSD (First Service Date)")
CustomField ftrCustomField = ComponentAccessor.getCustomFieldManager().getCustomFieldObjectByName("First Training Release Date")

// Get the value of the FSD Date field (it will be a Timestamp, so convert it to LocalDate)
def fsdTimestamp = issue.getCustomFieldValue(fsdCustomField)
log.warn(fsdTimestamp)
if (fsdTimestamp == null) {
    return "FSD Date is not set"
}

// Convert Timestamp to LocalDate
LocalDate fsdDate = fsdTimestamp.toInstant().atZone(ZoneId.systemDefault()).toLocalDate()

// Example of holidays (this can be updated with actual public holidays)
List<LocalDate> holidays = [
    LocalDate.of(2024, 1, 1),  // New Year's Day
    LocalDate.of(2024, 12, 25), // Christmas Day
    // Add more holidays here as needed
]

// Function to check if a date is a business day
boolean isBusinessDay(LocalDate date, List<LocalDate> holidays) {
    return !(date.dayOfWeek == DayOfWeek.SATURDAY || date.dayOfWeek == DayOfWeek.SUNDAY || holidays.contains(date))
}

// Function to calculate 28 business days before a given date
LocalDate subtractBusinessDays(LocalDate startDate, int businessDaysToSubtract, List<LocalDate> holidays) {
    LocalDate currentDate = startDate
    int daysSubtracted = 0

    while (daysSubtracted < businessDaysToSubtract) {
        currentDate = currentDate.minusDays(1)
        if (isBusinessDay(currentDate, holidays)) {
            daysSubtracted++
        }
    }
    return currentDate
}

// Calculate the FTR Date by subtracting 28 business days from the FSD Date
LocalDate ftrDate = subtractBusinessDays(fsdDate, 28, holidays)

// Format the date to match the 'd/MMM/yy' format (example: 4/Dec/24)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/MMM/yy")
String formattedFtrDate = ftrDate.format(formatter)

// Log to check if the formatted date is correct
log.warn("Formatted FTR Date (d/MMM/yy): " + formattedFtrDate)

// Set the FTR Date field to the calculated date (formatted as String)
issue.setCustomFieldValue(ftrCustomField, formattedFtrDate)

// Returning the result
return "FTR Date has been set to: " + formattedFtrDate
Is there anything I am missing related to date format or anything. Both the fields are date picker fields and in the logs i clearly see below
2024-12-23T06:41:14,940 WARN [runner.ScriptBindingsManager]: 2024-12-05 00:00:00.0 2024-12-23T06:41:14,941 WARN [runner.ScriptBindingsManager]: Formatted FTR Date (d/MMM/yy): 28/Oct/24
Screenshot 2024-12-23 121528.png
Ram Kumar Aravindakshan _Adaptavist_
Community Champion
December 23, 2024

Hi @Vineela Durbha

After reviewing your code, I can confirm it will not work.

You keep making the mistake of adding return messages at the very bottom of the code:-

return "FTR Date has been set to: " + formattedFtrDate

This will not work. You must only return a date value, e.g. 27/Dec/24, or according to the date format you have set in your Jira instance.

The date field will not recognize values like "FTR Date has been set to: ". Hence, the error message it is returning is expected.

Please clarify: Do you intend for the second date field to return the next working date? If yes, how many days should there be between the two date fields?

I suggest modifying your Listener code to something like this:-

import java.time.ZoneId

def issue = event.issue
def sampleDateValue = issue.getCustomFieldValue('Sample Date') as Date

if (sampleDateValue) {
issue.update {
setCustomFieldValue('Baseline Date', getNextBusinessDay(sampleDateValue))
}
}

def getNextBusinessDay(Date dateToConvert) {
def localDate = dateToConvert.toInstant().atZone(ZoneId.systemDefault()).toLocalDate()
def updatedDate

if (localDate.dayOfWeek.toString() == 'FRIDAY') {
updatedDate = localDate.plusDays(3) //Update the value of the days
} else if (localDate.dayOfWeek.toString() == 'SATURDAY') {
updatedDate = localDate.plusDays(2) //Update the value of the days
} else if (localDate.dayOfWeek.toString() == 'SUNDAY') {
updatedDate = localDate.plusDays(1) //Update the value of the days
} else {
updatedDate = localDate.plusDays(1) //Update the value of the days
}
java.sql.Date.valueOf(updatedDate).format('d/MMM/yy')
}

Please note that the sample working code above is not 100% exact to your environment. Hence, you must make the required modifications. 

I am looking forward to your feedback and clarification.

Thank you and Kind regards,
Ram

 

 

Vineela Durbha
Contributor
December 23, 2024

Hi @Ram Kumar Aravindakshan _Adaptavist_ 

I have removed return statement at the end and just made as 

issue.update {
        setCustomFieldValue('First Training Release Date', formattedFtrDate)
    }
Then I was able to set the fieldvalue. Thank you for the guidance provided. 
Appreciate  your help
0 votes
Ponnappan Ganapathiya
Contributor
December 20, 2024

Hi Vineela,

Could you please share the use case here. If there is no other actions then you can use smart values to update the field, instead of script!! Is it anything blocking that!

Suggest an answer

Log in or Sign up to answer