Skip to content

Instantly share code, notes, and snippets.

@jenseng
Forked from brainlid/instructurezendesk.js
Created November 6, 2013 22:10
Show Gist options
  • Save jenseng/7345025 to your computer and use it in GitHub Desktop.
Save jenseng/7345025 to your computer and use it in GitHub Desktop.
previousjQuery = jQuery;
jQuery(function($){
// only run in browsers that can do localStorage (not IE) and only on the tickets page
if ('localStorage' in window && $('body').hasClass('tickets-show') || $('body').hasClass('tickets-new')) {
// I want to make sure that this always runs with my version of jquery, not zendesk's
$.getScript('http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js', function(){
jQuery(function($){
//var username = 'testuser';
//var password = 'testpass';
//var jiraPushUrlBase = 'http://127.0.0.1:3000/zendesk_push/';
var username = "caturday";
var password = "nVFnKf2rZD7KFSbVXxfq7Ze1";
var jiraPushUrlBase = 'https://peaceful-tor-9607.herokuapp.com/zendesk_push/';
// Custom Fields Referenced - Production Server
var customFieldUserId = '#ticket_fields_340637';
var customFieldRequestContextId = '#ticket_fields_339688';
var customFieldUrl = '#ticket_fields_340638';
var customFieldBecomeUserUrl = '#ticket_fields_339456';
var customFieldStacktrace = '#ticket_fields_339429';
var customFieldHttpEnv = '#ticket_fields_339428';
var customFieldRedmineId = '#ticket_fields_349517';
var customFieldJiraId = '#ticket_fields_21072020';
var customFieldTimeOpen = '#ticket_fields_20485213';
var customFieldTimePending = '#ticket_fields_20485208';
var customFieldFirstResponse = '#ticket_fields_20510153';
var customFieldAccountId = '#ticket_fields_20485203';
var customFieldNeedInfo = '#ticket_fields_20687897';
// Custom Fields Referenced - Testing Server Instance
//var customFieldUserId = '#ticket_fields_21071800';
//var customFieldRequestContextId = '#ticket_fields_20962775';
//var customFieldUrl = '#ticket_fields_20962759';
//var customFieldBecomeUserUrl = '#ticket_fields_20962785';
//var customFieldStacktrace = '#ticket_fields_20962749';
//var customFieldHttpEnv = '#ticket_fields_20962769';
//var customFieldRedmineId = '#ticket_fields_20962795';
//var customFieldJiraId = '#ticket_fields_20962574';
//var customFieldTimeOpen = '#ticket_fields_21071810';
//var customFieldTimePending = '#ticket_fields_21071820';
//var customFieldFirstResponse = '#ticket_fields_21071830';
//var customFieldAccountId = '#ticket_fields_20962564';
//var customFieldNeedInfo = '#ticket_fields_21071840';
// hide time_open, time_pending, first_response_time, account_id, and 'need more info from support?'
$(customFieldTimeOpen+', '+customFieldTimePending+', '+customFieldFirstResponse+', '+customFieldAccountId+', '+customFieldNeedInfo).each(function() {
$(this).closest('.select').hide();
});
// Stop at this point if on the new page. Just hide elements that shouldn't show up.
if ($('body').hasClass('tickets-new')) {
return;
}
// Code for handling base64 encoding - http://www.webtoolkit.info/javascript-base64.html
var Base64 = {
// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode : function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
}
return output;
},
// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
}
}
// Get Zendesk Ticket from API as JSON
function getThisZendeskTicketFromRestApi(callback){
var UrlToThisTicket = window.location.protocol + "//" + window.location.host + window.location.port + window.location.pathname;
$.getJSON(UrlToThisTicket + '.json', callback);
}
// Get Zendesk User from API as JSON
function getCurrentZendeskUserFromRestApi(callback){
var UrlToThisUser = window.location.protocol + "//" + window.location.host + window.location.port + '/users/current';
$.getJSON(UrlToThisUser + '.json', callback);
}
// JIRA - Start ============================================
function updateZendeskIdsInJira() {
function error(){
alert("ERROR: Something went wrong updating Zendesk IDs In JIRA, see console");
debugger;
console && console.log('failure', this, arguments);
}
var jiraIssueKey = $.trim($jiraIssue.val()),
url = jiraPushUrlBase + 'update_jira_issue';
// Get the current zendesk ticket as JSON via the API. Execute passed function when successful.
// Using the current ticket, we get the original linked JIRA issue value
// to know how it should be updated.
getThisZendeskTicketFromRestApi(function(zenTicket){
console && console.log('updating Zendesk IDs In JIRA', jiraIssueKey, zenTicket);
// If we have an old key, instruct to remove the link
// If we have a new key, have link added
$.ajax({
type: 'POST',
url: url,
headers: {"X-Requested-With" : "XMLHttpRequest"},
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + Base64.encode(username + ":" + password))
},
data: {
zendeskId: zenTicket.nice_id,
addToIssue: jiraIssueKey,
removeFromIssue: originalJiraKeyLink
},
success: function(res){
console && console.log('updateRepsonse', res);
// Build up the response message.
var message = '';
var changed = false;
// Report which issue it was added to.
if (res.added_to_issue){
message = message + 'This Zendesk ticket was added to JIRA "'+res.added_to_issue+'".\n\n';
changed = true;
originalJiraKeyLink = jiraIssueKey; // update the tracked key
}
// Report which issue it was removed from.
if (res.removed_from_issue){
message = message + 'This Zendesk ticket was removed from JIRA "'+res.removed_from_issue+'".\n\n';
changed = true;
}
// If a change was made, instruct user to save Zendesk ticket change.
if (changed){
message = message + 'Changes were made, make sure you save this page to have it stick here. \n';
}
else {
message = message + 'No changes were made. \n';
}
// If an error occurred in JIRA update service, attempt to inform the user.
if (res.error) {
message = message + 'ERROR: Error occurred updating JIRA. Message: '+res.error;
}
alert(message);
},
error: error
});
});
}
var $divToAppendAfter = $('<hr style="clear:both;" />').insertAfter('.selects:last');
$(customFieldUserId+','+customFieldRequestContextId).each(function(){
$divToAppendAfter.after('<div class="debug-info"><strong>' + $(this).prev('label').text() + ':</strong> ' + $(this).val() + '</div>');
$(this).parents('.select').hide();
});
$(customFieldUrl+','+customFieldBecomeUserUrl).each(function() {
$divToAppendAfter.after('<div><strong>' + $(this).prev('label').text() + ':</strong> ' +
'<a href="' + $(this).val() + '" target="_blank">' + $(this).val() + '</a>' +
'</div>');
$(this).parents('.select').hide();
});
var $jiraIssue = $(customFieldJiraId).css({width: '120px', padding: '1px'});
$jiraIssue.one('change', function(){
$('<button>update on JIRA</button>')
.insertAfter($jiraIssue)
.click(function(event){
event.preventDefault();
updateZendeskIdsInJira();
});
});
if ($jiraIssue.val()) {
$jiraIssue.prev('label').html("<a href='https://instructure.atlassian.net/browse/"+ $jiraIssue.val() +"' rel='iframe' title='JIRA Issue Preview :: :: fullscreen: true' class='lightview'>JIRA #</a>");
}
// Store the original (when page loaded) linked JIRA issue.
var originalJiraKeyLink = $jiraIssue.val();
var $httpEnv = $(customFieldHttpEnv);
if ($httpEnv.val()) {
$divToAppendAfter.after("<div class='debug-info'><label><strong>HTTP-env</strong></label><div style='border: 1px solid #ccc; max-height: 100px; overflow: auto; white-space: nowrap; margin-bottom: 0.5em'>" + $httpEnv.val().replace(/\n/g, '<br />') + "</div></div>");
}
$httpEnv.closest('.select').hide();
// Get the stacktrace information. Don't error if input not found (as with test zendesk site)
var $stacktrace = $(customFieldStacktrace),
newHtml = [],
headerAndLines = ($stacktrace.val() || '').split('-----------------------------------------');
$stacktrace.closest('.select').hide();
// if there is some stuff in a stack trace, linkifiy it. otherwise hide it completely.
if (headerAndLines[1]) {
var $stacktraceDiv = $('<div style="border: 1px solid #ccc; max-height: 80px; overflow: auto; white-space: nowrap; margin-bottom: 0.5em;">')
.append($('<h4 />').text(headerAndLines[0]));
$('<div class="debug-info">')
.append('<label><strong>Stacktrace</strong></label>')
.append($stacktraceDiv.append('<pre>'+headerAndLines[1]+'/<pre>'))
.insertAfter($divToAppendAfter);
}
if ($('.debug-info').length) {
var $hideShowDebugInfo = $('<a href="#" style="float:right">Hide Debug Info</a>').click(function(){
if ( $(this).text() == 'Hide Debug Info' ) {
$(this).text('Show Debug Info');
$('.debug-info').hide();
} else {
$(this).text('Hide Debug Info');
$('.debug-info').show();
}
return false;
}).insertAfter($divToAppendAfter);
var hideDebugInfo = window.localStorage.getItem('hideDebugInfo');
if (!hideDebugInfo) {
hideDebugInfo = confirm('hide stack trace and HTTP-env by default (unless you are a programmer, you probably want to say yes)?') ? 'yes' : 'no';
window.localStorage.setItem('hideDebugInfo', hideDebugInfo);
}
if (hideDebugInfo == 'yes') {
$hideShowDebugInfo.click();
}
}
// JIRA - End ============================================
});
jQuery.noConflict(true);
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment