Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1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75x 75x 75x 75x 75x 75x 75x 75x 3x 3x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 3x 75x 75x 75x 75x 75x 1x 1x 1x 1x 1x 75x 75x 75x 75x 75x 8x 8x 1x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 8x 8x 8x 8x 8x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 8x 1x 1x 1x 1x 7x 7x 8x 7x 7x 8x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 6x 6x 6x 6x 6x 6x 6x 6x 6x 2x 2x 2x 1x 1x 1x 1x 6x 1x 4x 1x 3x 1x 1x 1x 1x 6x 8x 75x | import * as vscode from 'vscode';
import axios, { AxiosResponse } from 'axios';
export interface JiraIssue {
id: string;
key: string;
fields: {
summary: string;
description?: string;
status: {
name: string;
id: string;
};
priority?: {
name: string;
};
assignee?: {
accountId: string;
displayName: string;
emailAddress?: string;
};
reporter: {
displayName: string;
};
created: string;
updated: string;
issuetype: {
name: string;
};
sprint?: any;
customfield_10026?: number;
};
}
export interface JiraSprint {
id: number;
name: string;
state: 'active' | 'future' | 'closed';
startDate?: string;
endDate?: string;
completeDate?: string;
originBoardId: number;
}
export interface JiraTransition {
id: string;
name: string;
to: {
id: string;
name: string;
};
}
export interface JiraConfig {
id?: string;
team_id: string;
jira_url: string;
jira_project_key: string;
access_token: string;
refresh_token?: string;
admin_user_id: string;
created_at?: string;
updated_at?: string;
}
/**
* Service for integrating with Jira REST API.
* Handles authentication, issue fetching, and team-specific configurations.
*/
export class JiraService {
private static instance: JiraService;
private readonly baseUrl: string;
private constructor() {
// Use centralized backend configuration
// Note: Update TESTING flag in src/api/types/endpoints.ts after deploying to Render
const { BASE_URL } = require('../api/types/endpoints');
this.baseUrl = BASE_URL;
}
public static getInstance(): JiraService {
if (!JiraService.instance) {
JiraService.instance = new JiraService();
}
return JiraService.instance;
}
/**
* Initiates Jira OAuth flow for team admin.
* Opens browser for Jira authorization and handles callback.
*/
public async initiateJiraAuth(teamId: string, adminUserId: string): Promise<void> {
// For Jira Cloud, we'll use API tokens instead of full OAuth
// This is simpler and more common for Jira integrations
const jiraUrl = await vscode.window.showInputBox({
prompt: 'Enter your Jira instance URL',
placeHolder: 'https://yourcompany.atlassian.net',
validateInput: (value) => {
if (!value) return 'Jira URL is required';
try {
const url = new URL(value);
if (!url.hostname.includes('atlassian.net') && !url.hostname.includes('jira.com')) {
return 'Please enter a valid Jira Cloud URL (atlassian.net) or Jira Server URL';
}
return null;
} catch {
return 'Please enter a valid URL';
}
}
});
if (!jiraUrl) return;
const email = await vscode.window.showInputBox({
prompt: 'Enter your Jira email address',
placeHolder: 'your.email@company.com',
validateInput: (value) => {
if (!value) return 'Email is required';
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(value) ? null : 'Please enter a valid email address';
}
});
if (!email) return;
const apiToken = await vscode.window.showInputBox({
prompt: 'Enter your Jira API token',
placeHolder: 'ATATT3xFfGF0...',
password: true,
validateInput: (value) => {
if (!value) return 'API token is required';
if (value.length < 20) return 'API token appears to be too short';
return null;
}
});
if (!apiToken) return;
// Test the connection
const isValid = await this.testJiraConnection(jiraUrl, email, apiToken);
if (!isValid) {
vscode.window.showErrorMessage('Failed to connect to Jira. Please check your credentials and try again.');
return;
}
// Get project key
const projectKey = await this.getProjectKey(jiraUrl, email, apiToken);
if (!projectKey) return;
// Save configuration
await this.saveJiraConfig({
team_id: teamId,
jira_url: jiraUrl,
jira_project_key: projectKey,
access_token: Buffer.from(`${email}:${apiToken}`).toString('base64'), // Basic auth encoded
admin_user_id: adminUserId
});
vscode.window.showInformationMessage('Jira integration configured successfully! Tasks will be available for all team members.');
}
public async connectWithCredentials(teamId: string, adminUserId: string, jiraUrl: string, email: string, apiToken: string): Promise<void> {
// Validate URL format
try {
const url = new URL(jiraUrl);
if (!url.hostname.includes('atlassian.net') && !url.hostname.includes('jira.com')) {
throw new Error('Please enter a valid Jira Cloud URL (atlassian.net) or Jira Server URL');
}
} catch {
throw new Error('Invalid Jira URL format');
}
// Validate email format
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
throw new Error('Invalid email address format');
}
// Validate API token
if (!apiToken || apiToken.length < 20) {
throw new Error('API token appears to be invalid or too short');
}
// Test the connection
const isValid = await this.testJiraConnection(jiraUrl, email, apiToken);
if (!isValid) {
throw new Error('Failed to connect to Jira. Please check your credentials and try again.');
}
// Get project key
const projectKey = await this.getProjectKey(jiraUrl, email, apiToken);
if (!projectKey) {
throw new Error('No project selected or unable to fetch projects');
}
// Save configuration
await this.saveJiraConfig({
team_id: teamId,
jira_url: jiraUrl,
jira_project_key: projectKey,
access_token: Buffer.from(`${email}:${apiToken}`).toString('base64'), // Basic auth encoded
admin_user_id: adminUserId
});
vscode.window.showInformationMessage('Jira integration configured successfully! Tasks will be available for all team members.');
}
/**
* Tests Jira connection with provided credentials.
*/
private async testJiraConnection(jiraUrl: string, email: string, apiToken: string): Promise<boolean> {
try {
const auth = Buffer.from(`${email}:${apiToken}`).toString('base64');
console.log('Testing Jira connection to:', jiraUrl);
console.log('Using email:', email);
console.log('Auth header (first 20 chars):', `Basic ${auth.substring(0, 20)}...`);
const response = await axios.get(`${jiraUrl}/rest/api/3/myself`, {
headers: {
'Authorization': `Basic ${auth}`,
'Accept': 'application/json'
},
timeout: 10000
});
console.log('Jira connection successful! User:', response.data.displayName);
return response.status === 200;
} catch (error: any) {
console.error('Jira connection test failed:', {
status: error.response?.status,
statusText: error.response?.statusText,
data: error.response?.data,
message: error.message
});
// Provide helpful error message
if (error.response?.status === 401) {
vscode.window.showErrorMessage(
'Jira authentication failed. Please verify:\n' +
'1. Your email address is correct\n' +
'2. Your API token is correct (generate a new one if needed)\n' +
'3. You have access to this Jira instance'
);
}
return false;
}
}
/**
* Gets project key from user selection.
*/
private async getProjectKey(jiraUrl: string, email: string, apiToken: string): Promise<string | null> {
try {
const auth = Buffer.from(`${email}:${apiToken}`).toString('base64');
const response = await axios.get(`${jiraUrl}/rest/api/3/project`, {
headers: {
'Authorization': `Basic ${auth}`,
'Accept': 'application/json'
},
timeout: 10000
});
const projects = response.data;
if (!projects || projects.length === 0) {
vscode.window.showErrorMessage('No projects found in your Jira instance.');
return null;
}
const projectItems = projects.map((p: any) => ({
label: `${p.key} - ${p.name}`,
description: p.projectTypeKey,
project: p
}));
const selected = await vscode.window.showQuickPick(projectItems, {
placeHolder: 'Select the project to integrate with'
});
return selected ? (selected as any).project.key : null;
} catch (error) {
console.error('Failed to fetch Jira projects:', error);
vscode.window.showErrorMessage('Failed to fetch projects from Jira.');
return null;
}
}
/**
* Saves Jira configuration for a team.
*/
private async saveJiraConfig(config: JiraConfig): Promise<void> {
try {
// Call server endpoint to save Jira config
const response = await axios.post(`${this.baseUrl}/api/jira/config`, config, {
headers: {
'Content-Type': 'application/json'
}
});
if (response.status !== 200) {
throw new Error('Failed to save Jira configuration');
}
} catch (error) {
console.error('Failed to save Jira config:', error);
throw error;
}
}
/**
* Disconnects from Jira by deleting the team's Jira configuration.
*/
public async disconnectJira(teamId: string): Promise<void> {
try {
// Call server endpoint to delete Jira config
const response = await axios.delete(`${this.baseUrl}/api/jira/config/${teamId}`, {
headers: {
'Content-Type': 'application/json'
}
});
if (response.status !== 200) {
throw new Error('Failed to disconnect from Jira');
}
} catch (error) {
console.error('Failed to disconnect from Jira:', error);
throw error;
}
}
/**
* Fetches Jira configuration for a team.
*/
public async getJiraConfig(teamId: string): Promise<JiraConfig | null> {
try {
const response = await axios.get(`${this.baseUrl}/api/jira/config/${teamId}`, {
timeout: 10000
});
return response.data;
} catch (error: any) {
// 404 means no config exists yet - this is expected
if (error.response?.status === 404) {
return null;
}
console.error('Failed to fetch Jira config:', error.message);
return null;
}
}
/**
* Fetches issues from Jira for a team.
*/
public async fetchTeamIssues(teamId: string): Promise<JiraIssue[]> {
const config = await this.getJiraConfig(teamId);
if (!config) {
throw new Error('Jira not configured for this team');
}
// Build JQL query - get all issues from the project
const jql = `project = ${config.jira_project_key} ORDER BY updated DESC`;
const searchUrl = `${config.jira_url}/rest/api/3/search/jql`;
try {
console.log('Fetching Jira issue IDs:', {
url: searchUrl,
jql: jql,
projectKey: config.jira_project_key
});
// Step 1: Get issue IDs using /search/jql (only accepts JQL string in body)
const searchResponse = await axios.post(searchUrl, { jql }, {
headers: {
'Authorization': `Basic ${config.access_token}`,
'Accept': 'application/json',
'Content-Type': 'application/json'
},
timeout: 15000
});
const issueIds = searchResponse.data.issues || [];
console.log(`Fetched ${issueIds.length} issue IDs from Jira`);
if (issueIds.length === 0) {
return [];
}
// Step 2: Fetch full details for each issue
// Limit to first 100 to show more tasks
const limitedIds = issueIds.slice(0, 100);
const issueDetailsPromises = limitedIds.map(async (issue: any) => {
const issueUrl = `${config.jira_url}/rest/api/3/issue/${issue.id}`;
try {
const detailResponse = await axios.get(issueUrl, {
headers: {
'Authorization': `Basic ${config.access_token}`,
'Accept': 'application/json'
},
// Request ALL fields to find story points
timeout: 10000
});
// Debug: Log all custom fields for the first issue to find story points field
if (issue.id === issueIds[0].id) {
const allCustomFields = Object.keys(detailResponse.data.fields).filter(k => k.startsWith('customfield_'));
console.log('[Jira Debug] All custom fields:', allCustomFields);
// Log values of custom fields that have data
const customFieldsWithData: any = {};
allCustomFields.forEach(fieldKey => {
const value = detailResponse.data.fields[fieldKey];
if (value !== null && value !== undefined) {
customFieldsWithData[fieldKey] = value;
}
});
console.log('[Jira Debug] Custom fields with data:', JSON.stringify(customFieldsWithData, null, 2));
}
return detailResponse.data;
} catch (error) {
console.error(`Failed to fetch details for issue ${issue.id}:`, error);
return null;
}
});
const issuesWithDetails = await Promise.all(issueDetailsPromises);
const validIssues = issuesWithDetails.filter(issue => issue !== null);
console.log(`Successfully fetched full details for ${validIssues.length} issues`);
return validIssues;
} catch (error: any) {
console.error('Failed to fetch Jira issues:', {
status: error.response?.status,
statusText: error.response?.statusText,
data: error.response?.data,
message: error.message,
url: searchUrl,
projectKey: config.jira_project_key,
fullError: JSON.stringify(error.response?.data, null, 2)
});
// Log the exact error from Jira for debugging
if (error.response?.data) {
console.error('Jira error details:', error.response.data);
}
if (error.response?.status === 401) {
throw new Error('Jira authentication failed. Please reconfigure the integration.');
} else if (error.response?.status === 404) {
throw new Error('Jira project not found. Please check the project key.');
} else if (error.response?.status === 410) {
throw new Error('Jira API endpoint deprecated or project archived. Please verify the project is active and accessible.');
} else {
throw new Error(`Failed to fetch issues from Jira: ${error.message}`);
}
}
}
/**
* Removes Jira configuration for a team (admin only).
*/
public async removeJiraConfig(teamId: string): Promise<void> {
try {
await axios.delete(`${this.baseUrl}/api/jira/config/${teamId}`);
} catch (error) {
console.error('Failed to remove Jira config:', error);
throw error;
}
}
/**
* Fetches the board ID for a project.
*/
private async getBoardId(config: JiraConfig): Promise<number | null> {
try {
const response = await axios.get(`${config.jira_url}/rest/agile/1.0/board`, {
headers: {
'Authorization': `Basic ${config.access_token}`,
'Accept': 'application/json'
},
params: {
projectKeyOrId: config.jira_project_key
},
timeout: 10000
});
const boards = response.data.values || [];
if (boards.length === 0) {
console.error('No boards found for project:', config.jira_project_key);
return null;
}
// Return the first board found for this project
return boards[0].id;
} catch (error) {
console.error('Failed to fetch board ID:', error);
return null;
}
}
/**
* Fetches all sprints for a team's board.
*/
public async fetchSprints(teamId: string): Promise<JiraSprint[]> {
const config = await this.getJiraConfig(teamId);
if (!config) {
throw new Error('Jira not configured for this team');
}
const boardId = await this.getBoardId(config);
if (!boardId) {
throw new Error('Unable to find board for this project');
}
try {
const response = await axios.get(`${config.jira_url}/rest/agile/1.0/board/${boardId}/sprint`, {
headers: {
'Authorization': `Basic ${config.access_token}`,
'Accept': 'application/json'
},
timeout: 10000
});
return response.data.values || [];
} catch (error: any) {
console.error('Failed to fetch sprints:', error);
throw new Error(`Failed to fetch sprints: ${error.message}`);
}
}
/**
* Fetches issues for a specific sprint.
*/
public async fetchSprintIssues(teamId: string, sprintId: number): Promise<JiraIssue[]> {
const config = await this.getJiraConfig(teamId);
if (!config) {
throw new Error('Jira not configured for this team');
}
const boardId = await this.getBoardId(config);
if (!boardId) {
throw new Error('Unable to find board for this project');
}
try {
const response = await axios.get(
`${config.jira_url}/rest/agile/1.0/board/${boardId}/sprint/${sprintId}/issue`,
{
headers: {
'Authorization': `Basic ${config.access_token}`,
'Accept': 'application/json'
},
params: {
fields: 'summary,status,assignee,updated,reporter,created,issuetype,priority,sprint,customfield_10026'
},
timeout: 15000
}
);
return response.data.issues || [];
} catch (error: any) {
console.error('Failed to fetch sprint issues:', error);
throw new Error(`Failed to fetch sprint issues: ${error.message}`);
}
}
/**
* Fetches backlog issues (issues not assigned to any sprint).
*/
public async fetchBacklogIssues(teamId: string): Promise<JiraIssue[]> {
const config = await this.getJiraConfig(teamId);
if (!config) {
throw new Error('Jira not configured for this team');
}
const boardId = await this.getBoardId(config);
if (!boardId) {
throw new Error('Unable to find board for this project');
}
try {
const response = await axios.get(
`${config.jira_url}/rest/agile/1.0/board/${boardId}/backlog`,
{
headers: {
'Authorization': `Basic ${config.access_token}`,
'Accept': 'application/json'
},
params: {
fields: 'summary,status,assignee,updated,reporter,created,issuetype,priority,customfield_10026'
},
timeout: 15000
}
);
return response.data.issues || [];
} catch (error: any) {
console.error('Failed to fetch backlog issues:', error);
throw new Error(`Failed to fetch backlog issues: ${error.message}`);
}
}
/**
* Fetches available transitions for an issue.
*/
public async fetchTransitions(teamId: string, issueKey: string): Promise<JiraTransition[]> {
const config = await this.getJiraConfig(teamId);
if (!config) {
throw new Error('Jira not configured for this team');
}
try {
const response = await axios.get(
`${config.jira_url}/rest/api/3/issue/${issueKey}/transitions`,
{
headers: {
'Authorization': `Basic ${config.access_token}`,
'Accept': 'application/json'
},
timeout: 10000
}
);
return response.data.transitions || [];
} catch (error: any) {
console.error('Failed to fetch transitions:', error);
throw new Error(`Failed to fetch transitions: ${error.message}`);
}
}
/**
* Transitions an issue to a new status.
*/
public async transitionIssue(teamId: string, issueKey: string, transitionId: string): Promise<void> {
const config = await this.getJiraConfig(teamId);
if (!config) {
throw new Error('Jira not configured for this team');
}
try {
await axios.post(
`${config.jira_url}/rest/api/3/issue/${issueKey}/transitions`,
{
transition: {
id: transitionId
}
},
{
headers: {
'Authorization': `Basic ${config.access_token}`,
'Accept': 'application/json',
'Content-Type': 'application/json'
},
timeout: 10000
}
);
console.log(`Successfully transitioned issue ${issueKey} using transition ${transitionId}`);
} catch (error: any) {
console.error('Failed to transition issue:', error);
throw new Error(`Failed to transition issue: ${error.message}`);
}
}
/**
* Reassigns an issue to a different user.
* @param teamId
* @param issueKey
* @param accountId
*/
public async reassignIssue(teamId: string, issueKey: string, accountId: string | null): Promise<void> {
const config = await this.getJiraConfig(teamId);
if (!config) {
throw new Error('Jira not configured for this team');
}
try {
const payload = accountId ? { accountId } : null;
await axios.put(
`${config.jira_url}/rest/api/3/issue/${issueKey}/assignee`,
payload,
{
headers: {
'Authorization': `Basic ${config.access_token}`,
'Accept': 'application/json',
'Content-Type': 'application/json'
},
timeout: 10000
}
);
console.log(`Successfully reassigned issue ${issueKey} to ${accountId || 'unassigned'}`);
} catch (error: any) {
console.error('Failed to reassign issue:', error);
throw new Error(`Failed to reassign issue: ${error.message}`);
}
}
/**
* Updates the story points for an issue.
* @param teamId
* @param issueKey
* @param storyPoints
*/
public async updateStoryPoints(teamId: string, issueKey: string, storyPoints: number | null): Promise<void> {
const config = await this.getJiraConfig(teamId);
if (!config) {
throw new Error('Jira not configured for this team');
}
try {
await axios.put(
`${config.jira_url}/rest/api/3/issue/${issueKey}`,
{
fields: {
customfield_10026: storyPoints
}
},
{
headers: {
'Authorization': `Basic ${config.access_token}`,
'Accept': 'application/json',
'Content-Type': 'application/json'
},
timeout: 10000
}
);
console.log(`Successfully updated story points for ${issueKey} to ${storyPoints}`);
} catch (error: any) {
console.error('Failed to update story points:', error);
throw new Error(`Failed to update story points: ${error.message}`);
}
}
/**
* Updates the priority for an issue.
* @param teamId
* @param issueKey
* @param priorityName
*/
public async updatePriority(teamId: string, issueKey: string, priorityName: string): Promise<void> {
const config = await this.getJiraConfig(teamId);
if (!config) {
throw new Error('Jira not configured for this team');
}
try {
await axios.put(
`${config.jira_url}/rest/api/3/issue/${issueKey}`,
{
fields: {
priority: {
name: priorityName
}
}
},
{
headers: {
'Authorization': `Basic ${config.access_token}`,
'Accept': 'application/json',
'Content-Type': 'application/json'
},
timeout: 10000
}
);
console.log(`Successfully updated priority for ${issueKey} to ${priorityName}`);
} catch (error: any) {
console.error('Failed to update priority:', error);
throw new Error(`Failed to update priority: ${error.message}`);
}
}
/**
* Fetches assignable users for the project (for reassignment dropdown).
*/
public async fetchAssignableUsers(teamId: string): Promise<Array<{accountId: string, displayName: string, emailAddress?: string}>> {
const config = await this.getJiraConfig(teamId);
if (!config) {
throw new Error('Jira not configured for this team');
}
try {
// First, get all issues to find users who are actually working on the project
const issues = await this.fetchTeamIssues(teamId);
// Collect unique users from assignee and reporter fields
const activeUsers = new Map<string, {accountId: string, displayName: string, emailAddress?: string}>();
issues.forEach(issue => {
// Add assignee if present
if (issue.fields.assignee) {
activeUsers.set(issue.fields.assignee.accountId, {
accountId: issue.fields.assignee.accountId,
displayName: issue.fields.assignee.displayName,
emailAddress: issue.fields.assignee.emailAddress
});
}
// Add reporter if present (reporter only has displayName in the type)
if (issue.fields.reporter && issue.fields.reporter.displayName) {
// Reporter type only guarantees displayName, so we need to check if other fields exist
const reporter = issue.fields.reporter as any;
if (reporter.accountId) {
activeUsers.set(reporter.accountId, {
accountId: reporter.accountId,
displayName: reporter.displayName,
emailAddress: reporter.emailAddress
});
}
}
});
// Convert to array and sort by display name
return Array.from(activeUsers.values()).sort((a, b) =>
a.displayName.localeCompare(b.displayName)
);
} catch (error: any) {
console.error('Failed to fetch assignable users:', error);
throw new Error(`Failed to fetch assignable users: ${error.message}`);
}
}
/**
* Creates a new issue in Jira.
*/
public async createIssue(teamId: string, taskData: any): Promise<JiraIssue> {
const config = await this.getJiraConfig(teamId);
if (!config) {
throw new Error('Jira not configured for this team');
}
try {
// Build the issue payload according to Jira REST API v3 format
const issuePayload: any = {
fields: {
project: {
key: config.jira_project_key
},
summary: taskData.summary,
issuetype: {
name: taskData.issuetype || 'Task'
}
}
};
// Add optional description if provided
if (taskData.description) {
// Jira Cloud uses Atlassian Document Format (ADF) for descriptions
issuePayload.fields.description = {
type: 'doc',
version: 1,
content: [
{
type: 'paragraph',
content: [
{
type: 'text',
text: taskData.description
}
]
}
]
};
}
// Add optional priority if provided
if (taskData.priority) {
issuePayload.fields.priority = {
name: taskData.priority
};
}
// Add optional story points if provided
if (taskData.storypoints) {
const storyPointsValue = parseInt(taskData.storypoints, 10);
if (!isNaN(storyPointsValue) && storyPointsValue > 0) {
// Story Points are typically stored in customfield_10026 (Scrum field)
issuePayload.fields.customfield_10026 = storyPointsValue;
}
}
// Add optional assignee if provided
if (taskData.assignee) {
console.log('[createIssue] Assignee provided:', taskData.assignee);
// Fetch assignable users to get the accountId from displayName
try {
const assignableUsers = await this.fetchAssignableUsers(teamId);
console.log('[createIssue] Fetched assignable users:', assignableUsers.map(u => u.displayName));
const user = assignableUsers.find(u => u.displayName === taskData.assignee);
if (user) {
console.log('[createIssue] Found matching user:', user);
issuePayload.fields.assignee = {
accountId: user.accountId
};
} else {
console.warn(`[createIssue] Assignee "${taskData.assignee}" not found in assignable users. Available:`, assignableUsers.map(u => u.displayName));
}
} catch (error) {
console.error('[createIssue] Failed to fetch assignable users for assignee:', error);
// Continue without assignee if fetch fails
}
}
console.log('Creating Jira issue with payload:', JSON.stringify(issuePayload, null, 2));
// Create the issue
const response = await axios.post(
`${config.jira_url}/rest/api/3/issue`,
issuePayload,
{
headers: {
'Authorization': `Basic ${config.access_token}`,
'Accept': 'application/json',
'Content-Type': 'application/json'
},
timeout: 15000
}
);
console.log('Issue created successfully:', response.data);
// Fetch the full issue details to return
const issueKey = response.data.key;
const issueResponse = await axios.get(
`${config.jira_url}/rest/api/3/issue/${issueKey}`,
{
headers: {
'Authorization': `Basic ${config.access_token}`,
'Accept': 'application/json'
},
params: {
fields: 'summary,status,assignee,updated,reporter,created,issuetype,priority,description,customfield_10026'
},
timeout: 10000
}
);
return issueResponse.data;
} catch (error: any) {
console.error('Failed to create Jira issue:', {
status: error.response?.status,
statusText: error.response?.statusText,
data: error.response?.data,
message: error.message
});
// Provide detailed error messages
if (error.response?.status === 400) {
const errorMessages = error.response.data?.errors || {};
const errorKeys = Object.keys(errorMessages);
if (errorKeys.length > 0) {
const firstError = errorMessages[errorKeys[0]];
throw new Error(`Validation error: ${firstError}`);
}
throw new Error('Invalid issue data. Please check your input and try again.');
} else if (error.response?.status === 401) {
throw new Error('Jira authentication failed. Please reconfigure the integration.');
} else if (error.response?.status === 403) {
throw new Error('Permission denied. You may not have permission to create issues in this project.');
} else if (error.response?.status === 404) {
throw new Error('Jira project not found. Please check the project configuration.');
} else {
throw new Error(`Failed to create issue: ${error.message}`);
}
}
}
}
|