ruby-on-rails 我想使用Jira API和脚本将第一个完成的过渡日期放在JIRA中已完成问题的自定义字段中

dbf7pr2w  于 2023-02-14  发布在  Ruby
关注(0)|答案(1)|浏览(106)

假设这是Jira问题的更改日志

{
    "expand": "renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations",
    "id": "72194",
    "self": "https://jira.instance.net/rest/api/2/issue/72194",
    "key": "TII-627",
    "changelog": {
        "startAt": 0,
        "maxResults": 1,
        "total": 1,
        "histories": [
            {
                "id": "12345",
                "author": {
                    "self": "https://jira.instance.net/rest/api/2/user?accountId=xxxxxxxxxxx",
                    "accountId": "xxxxxxxxxxxx",
                    "emailAddress": "xxx@yy.com",
                    "avatarUrls": {},
                    "displayName": "John Doe",
                    "active": true,
                    "timeZone": "Anywhere",
                    "accountType": "atlassian"
                },
                "created": "2023-02-07T10:30:02.897+0530",
                "items": [
                    {
                        "field": "status",
                        "fieldtype": "jira",
                        "fieldId": "status",
                        "from": "10000",
                        "fromString": "To Do",
                        "to": "5",
                        "toString": "Resolved"
                    }
                ]
            }
        ]
    },
    "fields": {
        "status": {
            "self": "https://jira.instance.net/rest/api/2/status/5",
            "description": "A resolution has been taken, and it is awaiting verification by reporter. From here issues are either reopened, or are closed.",
            "iconUrl": "something",
            "name": "Resolved",
            "id": "5",
            "statusCategory": {
                "self": "https://jira.instance.net/rest/api/2/statuscategory/3",
                "id": 3,
                "key": "done",
                "colorName": "green",
                "name": "Done"
            }
        }
    }
}

在此更改日志中,您可以看到“key”的问题:“TII-627”是第一个转换到完成状态类别,也称为“已创建”的已解决状态:“2023年2月7日上午10时30分02.897+0530秒”
我希望完成第一次转换,并将其打印在项目中所有问题的表格中,如下所示
问题关键字,第一个解决时间
对于上面的例子,它看起来像这样
TII-627,2023年2月7日10时30分:02.897+0530秒
我已经尝试使用下面的ruby脚本,但是我得到的第一个解析日期为空,请告诉我该怎么做

require 'jira-ruby'

# JIRA API credentials
jira_username = '<your-jira-username>'
jira_token = '<your-jira-api-token>'
jira_domain = '<your-jira-instance-domain>'

# initialize client
options = {
    :username => jira_username,
    :password => jira_token,
    :site => "https://#{jira_domain}",
    :context_path => '',
    :auth_type => :basic
}
client = JIRA::Client.new(options)

# Define the issue key as a command line argument
issue_key = ARGV[0]

# Log the start time of the script
start_time = Time.now
puts "Start time: #{start_time}"

# Get the issue information
begin
  issue = client.Issue.find(issue_key)
  issue_status_category = issue.fields['status']['statusCategory']['name']

 # If issue has already reached done status, retrieve the transitions
  if issue_status_category == 'Done'
    transitions = issue.transitions
    first_resolved_at = nil
    last_resolved_at = nil

    # Retrieve the first and last resolved dates
    transitions.each do |transition|
      transition_status_category = transition['to']['statusCategory']['name']
      if transition_status_category == 'Done'
        transition_created_at = DateTime.parse(transition['created'])
        if first_resolved_at.nil?
          first_resolved_at = transition_created_at
        end
        last_resolved_at = transition_created_at
      end
    end

    # Print the results
    puts "Issue Key: #{issue.key}"
    puts "First Resolved At: #{first_resolved_at}"
    puts "Last Resolved At: #{last_resolved_at}"
  else
    puts "Issue has not yet reached Done status."
  end
rescue Exception => e
  # Log the error
  puts "Error: #{e}"
end

# Log the end time of the script
end_time = Time.now
puts "End time: #{end_time}"
hpcdzsge

hpcdzsge1#

我正在结束这个问题。我能够使用JS找到另一种方法

const axios = require("axios");
​
async function getFirstResolvedDate(jiraUsername, jiraToken, jiraDomain, issues) {
for (const issue of issues) {
let changelogs = [];
let url = jiraDomain + "/rest/api/2/issue/" + issue + "?expand=changelog";
let response = await axios({
method: "get",
url: url,
headers: {
"Authorization": "Basic " + Buffer.from(jiraUsername + ":" + jiraToken).toString("base64"),
"Content-Type": "application/json",
}
});
let data = response.data;
let changelog = data.changelog.histories;
if (!Array.isArray(changelog)) {
changelog = [changelog];
}
for (const history of changelog) {
let items = history.items;
for (const item of items) {
if (item.field === "status" && (item.toString === "Resolved" || item.toString === "Invalid")) {
let firstResolvedAt = history.created;
changelogs.push({
issue_key: issue,
first_resolved_at: firstResolvedAt
});
break;
}
}
}
let earliestDate = new Date(Math.min.apply(null, changelogs.map(function(c) {
return new Date(c.first_resolved_at);
})));
let formattedDate = earliestDate.toISOString();
url = jiraDomain + "/rest/api/2/issue/" + issue;
let body = {
fields: {
customfield_xxx: formattedDate
}
};
response = await axios({
method: "put",
url: url,
headers: {
"Authorization": "Basic " + Buffer.from(jiraUsername + ":" + jiraToken).toString("base64"),
"Content-Type": "application/json",
},
data: body
});
if (response.status === 200 || response.status === 204) {
console.log("Successfully updated first resolved date for issue " + issue);
} else {
console.error(response);
}
}
}
​
const jiraUsername = 'xxx';
const jiraToken = "xxx";
const jiraDomain = "https://xxx";
const issues = ['xxx-1'];
​
getFirstResolvedDate(jiraUsername, jiraToken, jiraDomain, issues)
  .then(result => {
    console.log(result);
  })
  .catch(error => {
    console.error(error);
  });

相关问题