floodmeadows / Jira append template to description

// ==UserScript==
// @name         Jira append template to description
// @namespace    https://openuserjs.org/users/floodmeadows
// @description  Adds buttons to quickly assign story points to the current issue.
// @copyright    2023, floodmeadows (https://openuserjs.org/users/floodmeadows)
// @license      MIT
// @version      0.2
// @include      https://jira.*.uk/browse/*
// @updateURL    https://openuserjs.org/meta/floodmeadows/Jira_append_template_to_description.meta.js
// @downloadURL  https://openuserjs.org/install/floodmeadows/Jira_append_template_to_description.user.js
// @grant        none
// ==/UserScript==

/* jshint esversion: 6 */

//--- Customise your template here ----//
const templateText = `
PASTE_YOUR_TEMPLATE_HERE
`;
//-------------------------------------//

const debug = false;
const targetElementForButton = document.getElementById('descriptionmodule-label');

(function () {
    'use strict';

    if (debug) addButton("Clear description", targetElementForButton, clearDescription);
    addButton("Apply template", targetElementForButton, appendTemplateTextToCurrentDescription);
})();

function addButton(buttonText, targetElement, functionName) {
    const button = document.createElement("button");
    button.setAttribute("class", "aui-button");
    button.addEventListener("click", functionName);
    const text = document.createTextNode(buttonText);
    button.appendChild(text);
    targetElement.after(button);
}

function appendTemplateTextToCurrentDescription() {
    //--- Get standard info ---//
    const currentUrl = new URL(document.URL);
    const jiraBaseUrl = currentUrl.protocol + '//' + currentUrl.host;
    const currentIssueKey = document.getElementById("key-val").childNodes[0].nodeValue;
    const apiUrl = `${jiraBaseUrl}/rest/api/latest/issue/${currentIssueKey}`;
    if(debug) console.log('URL: ' + apiUrl);

    var headers = new Headers();
    headers.append("Content-Type", "application/json");

    var requestOptions = {
        method: 'GET',
        headers: headers
    };

    fetch(apiUrl, requestOptions)
        .then(response => {
            const jsonPromise = response.json()
                .then(data => {
                    const currentIssue = data;
                    if (debug) console.log(currentIssue);
                    console.log("Current description = '" + currentIssue.fields.description + ".'");
                    const currentDescription = currentIssue.fields.description;
                    var newDescription = "";
                    if (currentDescription != null) {
                        newDescription = currentDescription + "\r\n" + templateText.trimStart();
                    } else {
                        newDescription = templateText.trimStart();
                    }
                    console.log("New description = '" + newDescription + ".'");
                    updateDescription(newDescription);

                });
            })
        .catch(error => {
            console.log('error', error);
            return false;
        });
}

function clearDescription() {
    updateDescription("");
}

function updateDescription(newDescription) {
    //--- Get standard info ---//
    const currentUrl = new URL(document.URL);
    const jiraBaseUrl = currentUrl.protocol + '//' + currentUrl.host;
    const currentIssueKey = document.getElementById("key-val").childNodes[0].nodeValue;
    const updateIssueUrl = `${jiraBaseUrl}/rest/api/latest/issue/${currentIssueKey}`;

    var headers = new Headers();
    headers.append("Content-Type", "application/json");

    var jsonToUpdateIssue = JSON.stringify({
        "fields": {
            "description": newDescription
        }
    });

    if (debug) console.log(jsonToUpdateIssue);

    var requestOptions = {
        method: 'PUT',
        headers: headers,
        body: jsonToUpdateIssue
    };

    fetch(updateIssueUrl, requestOptions)
        .then(response => {
            console.log(response.text());
            if(!debug) window.location.assign(currentUrl);
        })
        .catch(error => console.log('error', error));
}