Site icon Salesforce Diaries

Create Jira Issues from LWC in Salesforce

Create Jira Issues from LWC in Salesforce can help business in lot more ways. Jira Integration save lot of money and time. By creating Jira issues directly from Salesforce, teams can enhance their productivity and maintain seamless communication between their CRM and project management tools. Whether you are addressing bugs, managing projects, or handling customer service requests, this integration offers a unified solution to boost operational efficiency and team coordination.

Business usecase for Create Jira Issues from LWC in Salesforce

Consider a scenario, You recently launched MVP in Salesforce production. Business users are reporting lot of feedbaack and bugs via the emails. It is becoming very challenging for you to keep a track of all the request coming in. Business user can not access jira. You have the access. Hence, You decided to provide them a simple UI on their home page to directly log the issues to Jira.

Use LWC with an Apex action to invoke Jira Rest API

1. Prepare Jira: Obtain API Credentials

2. Understand Jira REST API Endpoints and Postman Collection

3. Setup Salesforce for Jira Integration

public class JiraIntegrationService {
    private static String getBasicAuth(String userName, String apiToken) {
        String authString = userName + ':' + apiToken;
        return 'Basic ' + EncodingUtil.base64Encode(Blob.valueOf(authString));
    }

    @auraEnabled
    public static String createJiraIssue(String userName, String apiToken, String baseUrl, String requestBody) {
        HttpRequest req = new HttpRequest();
        req.setEndpoint(baseUrl + '/rest/api/3/issue');        
        req.setMethod('POST');
        req.setHeader('Authorization', getBasicAuth(userName,apiToken));
        req.setHeader('Content-Type', 'application/json');
        req.setBody(requestBody);
        
        Http http = new Http();
        HttpResponse res = http.send(req);
        
        if (res.getStatusCode() == 201) {
            Map<String, Object> responseMap = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
            return '' + responseMap.get('key');
        } else {
            return 'Something went wrong';
        }
    }
}

createJiraItem.html

HTML provides a user-friendly interface to create Jira items directly from Salesforce. It allows users to input and submit Jira item details. Upon submitting the form, the onsubmit handler handleSubmit processes the input data, while the onsuccess handler navigateToNewJiraItem manages post-submission actions.

<template>
    <lightning-card title="Create Jira Item From LWC" icon-name="standard:contact">
        <lightning-spinner alternative-text="Loading" size="large" lwc:if={showSpinner}></lightning-spinner>
		<div class="slds-var-m-around_medium">
			<lightning-record-edit-form object-api-name="Jira__c" onsubmit={handleSubmit} onsuccess={navigateToNewJiraItem}>
				<lightning-messages></lightning-messages>
				<lightning-input-field field-name="summary__c"></lightning-input-field>
				<lightning-input-field field-name="Description__c"></lightning-input-field>
				<div class="slds-var-m-top_medium">
					<lightning-button variant="brand" type="submit" name="save" label="Save"></lightning-button>
				</div>
			</lightning-record-edit-form>
		</div>
	</lightning-card>
</template>

createJiraItem.js

Request Body has been created in js file and passed to apex method which calls the API. The details like project key, base url, access token and username are fetched from design attributes exposed to lightning app builder.

Onsubmit handler fetches the inpute details from user and pass it to request body. Onsave handler navigates to Jira salesforce record which shows the url to jira issue.

import { LightningElement, api } from 'lwc';
import createJiraIssue from '@salesforce/apex/JiraIntegrationService.createJiraIssue';
import { NavigationMixin } from 'lightning/navigation';

export default class CreateJiraItem extends NavigationMixin(LightningElement) {
    //replace these values according to your jira account
    @api jiraProjectKey = 'your project key from Jira';
    @api jiraUserName = 'your jira username';
    @api jiraApiToken = 'your access token created in jira';
    @api jiraBaseUrl = 'your base url of jira';
    summary = '';
    description = '';
    jiraResponseId = '';
    showSpinner;

    get requestBody() {
        return {
            "fields": {
                "project": {
                    "key": this.jiraProjectKey
                },
                "summary": this.summary,
                "description": {
                    "type": "doc",
                    "version": 1,
                    "content": [
                        {
                            "type": "paragraph",
                            "content": [
                                {
                                    "type": "text",
                                    "text": this.description
                                }
                            ]
                        }
                    ]
                },
                "issuetype": {
                    "name": "Task"
                }
            }
        }
    }

    async handleSubmit(event) {
        event.preventDefault();
        const formFields = event.detail.fields;
        this.showSpinner = true;
        this.summary = formFields.summary__c;
        this.description = formFields.Description__c;
        try {
            this.jiraResponseId = await createJiraIssue({
                userName: this.jiraUserName,
                apiToken: this.jiraApiToken,
                baseUrl: this.jiraBaseUrl,
                requestBody: JSON.stringify(this.requestBody)
            });
            formFields.Item_Link__c = 'https://yourjiradomain.atlassian.net/browse/'+ this.jiraResponseId;
            // Trigger form submission with the updated fields
            this.template
                .querySelector("lightning-record-edit-form")
                .submit(formFields);
        } catch (error) {
            this.jiraResponseId = '';
        }
        this.showSpinner = false;
    }

    navigateToNewJiraItem(event) {
        this[NavigationMixin.Navigate]({
            type: 'standard__recordPage',
            attributes: {
                recordId: event.detail.id,
                objectApiName: 'Jira__c',
                actionName: 'view'
            }
        });
    }
}

createJiraItem.js-meta.xml

<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
	<apiVersion>60.0</apiVersion>
	<isExposed>true</isExposed>
	<targets>
		<target>lightning__RecordPage</target>
		<target>lightning__AppPage</target>
		<target>lightning__HomePage</target>
	</targets>
	<targetConfigs>
        <targetConfig targets="lightning__RecordPage,lightning__AppPage,lightning__HomePage">
            <property name="jiraProjectKey" type="String" description="Key of your Jira Project" />
            <property name="jiraUserName" type="String" description="Username of your jira account" />
            <property name="jiraApiToken" type="String" description="Access API token Generated in JIRA" />
			<property name="jiraBaseUrl" type="String" description="Base URL of the Jira" />
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>

Demo – Create Jira Story from LWC in Salesforce

Do you need help?

Are you stuck while working on this requirement? Do you want to get review of your solution? Now, you can book dedicated 1:1 with me on Lightning Web Component completely free.

GET IN TOUCH

Schedule a 1:1 Meeting with me

Also checkout this https://salesforcediaries.com/category/lightning-w

Exit mobile version