Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
j_platform / app / assets / javascripts / j_platform / tickets / tickets.js.coffee
Size: Mime:
#= require utilities/jugnoo_helpers.js.coffee

###*
 * Namespace for JPlatformGem functions.
###
window.JPlatformGem ?= {}

$(document).on "page:change", ->

  _bodyTicketsShow = $('body.tickets-show')
  if _bodyTicketsShow.length
    hideEmptyDraft()
    $('#comment-box').jTextareaAutoHeight()

    #Show Resolve Ticket modal
    _bodyTicketsShow.on 'click', "#btn-resolve-ticket", (e) ->
      e.preventDefault()
      hasResolutionCodes = $('#ticket_resolution_id option').length

      if hasResolutionCodes
        $("#modal-resolve-ticket").modal('show')
        $('#ticket_resolution_id').trigger("chosen:updated")
      else
        removeButtonSpinner()
        noty
          text: "Sorry, you cannot resolve this task because there are no resolution codes available. Please contact your Administrator."
          type: 'info'

# Set task history height according comment box height
$(document).on 'keyup', '.tickets-show #comment-box', ->
  setTicketHistoryHeight()

#Show Create/Edit Ticket modals
$(document).on 'click', ".btn-create-ticket, #btn-edit-ticket", (e) ->
  e.preventDefault()
  $this = $(this)
  if $this.hasClass 'disabledItem'
    return false

  opts = {}

  isCreating = $this.hasClass 'btn-create-ticket'
  if isCreating
    opts.ticketMessageID = $this.attr("data-social-message-origin-ids")
    opts.ticketSocialAccountID = $this.attr("data-social-account-id")
    if(opts.ticketMessageID.split(',').length > 50)
      noty
        text: "We're sorry, you are currently limited to the creation of 50 tasks at a time."
        type: 'error'
      return false

  JPlatformGem.requestTicketFormModal ($ @).attr("href"), opts

###*
 * Request a TicketForm
 * @param  {String} href The target url
 * @param  {Object} opts Options for the modal. Currently supports ticketMessageID and ticketSocialAccountID
 * @return {jQuery}      jQuery XHR promise object.
###
JPlatformGem.requestTicketFormModal = (href, opts) ->
  $.ajax
      url: href
      method: "get"
      beforeSend: ->
        if $("#btn-edit-ticket").attr("data-disabled")
          xhr.abort()

      success: (data) ->
        if ($("#modal-new-ticket").length + $("#modal-edit-ticket").length) > 0
          if $("#modal-new-ticket").length > 0
            $("#modal-new-ticket").html($($.parseHTML(data, document, true)[1]).html())

          if $("#modal-edit-ticket").length > 0 then $("#modal-edit-ticket").html($($.parseHTML(data, document, true)[1]).html())
        else
          $("#modal-holder").append(data)

        if $("#modal-new-ticket").length
          $("#ticket_social_message_origin_ids").val(opts.ticketMessageID) if !!opts.ticketMessageID
          $("#ticket_social_account_id").val(opts.ticketSocialAccountID) if !!opts.ticketSocialAccountID

        $("#modal-new-ticket, #modal-edit-ticket").modal('show')
        $("#modal-holder").trigger('newTicketModalLoaded')
        enableTicketForm()

validateNewTicket = ->
  invalid = false
  $("#new_ticket").find("select.required").each ->
    invalid ||= ($(this).val().length == 0)
  !invalid

onNewTicketSent = ->
  $("#modal-new-ticket").modal('hide')
  noty({ text: "Your tasks are being processed", type: 'success' })

# For now (to be reverted in future)
$(document).on 'ajax:beforeSend', "#new_ticket", ->
  if validateNewTicket()
    onNewTicketSent()

#Make each ticket row clickable
$(document).on 'click', ".ticket-row", (e) ->
  if $(@).hasClass('pending')
    hideLoadingIndicator()
  else
    ticket_href = $(this).attr('data-link')
    Turbolinks.visit ticket_href

$(document).on 'click', ".ticket-row .tag", (e) ->
  $(".ticket-row").preventDefault()

$(document).on "page:change", ->
  JugnooUtils.setUploaderFactory('#customer-engagement footer .uploader', '#project_post_message')

$(document).on "ajax:success", "#modal-new-ticket", (e, data) ->
  e.preventDefault()
  if data? && data != ""
    noty({ text: data.message, type: 'success' })
    $("#modal-holder").trigger('ticketCreated', [data.id])

$(document).on "ajax:error", "#modal-new-ticket", (e, xhr) ->
  e.preventDefault()
  if (data = xhr.responseJSON)? && data != ""
    noty({ text: data.message, type: 'error' })

$(document).on "ajax:success", "#modal-edit-ticket", (e, data) ->
  e.preventDefault()
  window.destroyModal("#modal-edit-ticket")
  noty({ text: data.message, type: 'success' })
  $('#ticket-view').replaceWith(data.object)
  updateEngagementBox()

$(document).on "ajax:error", "#btn-reopen-ticket", (e, xhr, status, error) ->
  noty({ text: xhr.responseText, type: 'error' })

$(document).on "ajax:success", "#modal-resolve-ticket", (e, data) ->
  e.preventDefault()
  $("#modal-resolve-ticket").modal('hide')
  $('#ticket-view').replaceWith(data.object)
  setCustomerEngagementHeight()
  setTicketHistoryHeight()

$(document).on "ajax:error", "#modal-resolve-ticket", (e, data) ->
  message = $.parseJSON(data.responseText)
  noty {text: message.message, type: "error"}

$(document).on "ajax:success", "#btn-reopen-ticket", (e, data) ->
  e.preventDefault()
  $('#ticket-view').replaceWith(data.object)
  noty
    text: $(@).data('reopen-success')
    type: 'success'
  updateEngagementBox()

updateEngagementBox = ()->
  hideEmptyDraft()
  window.enableChosen()
  externalConversationStyling()
  setCustomerEngagementHeight()
  $('#comment-box').jTextareaAutoHeight()
  setTicketHistoryHeight()
  unless $('#customer-engagement').data('jPostObj')
    new JPost($('#customer-engagement'))

# Hiding empty draft message
hideEmptyDraft = ->
  if $('.message-text').html()
    $('.external-conversation .feeds').addClass('draft')
  else
    $('.external-conversation .feeds').removeClass('draft')
    $('.draft-message').addClass('hide')


###
  formTagList:
  Private Object (this file only) used for enabling and validating the tagit area
  TODO: (By Gabe's request) Consider making it a global class for other Tag areas.
###
formTagList =
  MAX_TAG_LENGTH: 20
  MAX_TAGS: 4
  tagListSelector: "#ticket_tag_names"
  tagInputSelector: ".tagit input"

  # ControlGroup is the parent container of this tag section of the form
  getControlGroup: ->
    tagList = $ @.tagListSelector
    controlGroup = tagList.closest('.control-group')

  # Enable sets the tagit functionality for this tagList input
  enable: () ->
    placeHolder = I18n.t('tickets._create_edit_ticket.tags.placeholder')
    ticketList = $ @.tagListSelector

    formTagListContext = @
    ticketList.tagit
      allowSpaces: true
      tagLimit: formTagListContext.MAX_TAGS
      placeholderText: placeHolder
      beforeTagAdded: (e, tag) ->
        valid = formTagListContext.validate()
        ticketList.attr('is_disabled', valid)
        valid
      afterTagAdded: ->
        if ticketList.tagit("assignedTags").length >= formTagListContext.MAX_TAGS
          ticketList.parent().find('.tagit-new input').attr 'placeholder', ""
      afterTagRemoved: ->
        ticketList.parent().find('.tagit-new input').attr 'placeholder', placeHolder

  # validate runs all validations for the tagList,
  # If any errors are found, it displays the first of them in our typical way;
  # Returns the Boolean result of the validity of the tagList
  validate: () ->
    error = null #Required for `?=`
    controlGroup = @.getControlGroup()
    controls = controlGroup.find('.controls').first()
    for own _, thisValidation of @._validations
      error ?= thisValidation(@)
    hasError = !!error

    controlGroup.toggleClass "error", hasError
    controls.find('span.help-block').remove()
    if hasError
      controls.append($("<span/>", {class: "help-block", text: error}))
    return !hasError # (Valid / true if no error, invalid / false otherwise)

  # _validations is an object list of all validations used for tagList,
  # Each validation returns an error String if it fails, otherwise returns null/undefined
  _validations:
    inputTooLong: (tagList) ->
      controlGroup = tagList.getControlGroup()
      input = controlGroup.find tagList.tagInputSelector
      if input.val().length > tagList.MAX_TAG_LENGTH
        error = I18n.t('tickets._create_edit_ticket.tags.error.too_long')
    attemptingToAddTooManyTags: (tagList) ->
      controlGroup = tagList.getControlGroup()
      tags = $(tagList.tagListSelector).tagit("assignedTags")
      input = controlGroup.find(tagList.tagInputSelector)
      if (tags.length >= tagList.MAX_TAGS) and (input.val().length)
        error = I18n.t('tickets._create_edit_ticket.tags.error.too_many', {max_tags: tagList.MAX_TAGS})

@enableTicketForm = ->
  enableChosen()
  enableDatePicker()
  formTagList.enable()
  $("#modal-new-ticket, #modal-edit-ticket").on "shown.bs.modal", ->
    $('.ticket-modal').enableClientSideValidations?().resetClientSideValidations()

# Modified from StackOverflow: http://stackoverflow.com/a/4180715/624590
# Added tab and enter codes.
isCharacterKeyPress = (evt) ->
  if typeof evt.which is "undefined"
    return true
  else if typeof evt.which is "number" and evt.which > 0
    return (not evt.ctrlKey and not evt.metaKey and not evt.altKey) && (([13, 16, 17, 18, 19, 20, 27, 37, 38, 39, 40].indexOf evt.keyCode) < 0)
  false
$(document).on 'keyup', ".ticket_tag_names input", (e) ->
  e.preventDefault()
  if isCharacterKeyPress(e) or e.keyCode is 8 # Del key
    return formTagList.validate()

# Set Ticket history height
@setTicketHistoryHeight = ->
  $_ticketFeedContainer = $('#ticket-view #ticket-feed')
  _ticketFeedFooterHeight = $_ticketFeedContainer.find('footer').first().outerHeight()/10
  $_ticketHisoryMessageList = $_ticketFeedContainer.find('ul').first()
  $_ticketHisoryMessageList.css('bottom', _ticketFeedFooterHeight+'rem')

# Wire up comment form ajax to insert a new feed item to top on success
$(document).on "ajax:success", "#ticket_comment_form", (e, data) ->
  $("#ticket-feed ul").html data.object
  ($ @).find("#comment-box").val("").keyup()
  removeButtonSpinner()

$(document).on "click", ".feed-likes a, .feed-comments a", (e) ->
  e.preventDefault()

@loadPostAvatar = ->
  accountSelect = $('#ticket_default_social_account')
  postAvatar = $('.post-social-account-avatar')

  if accountSelect.length
    avatarPath = accountSelect.find('option:selected').attr('data-url')
  else
    avatarPath = $('#project_post_social_account_id').find('option:selected').attr('data-url')

  postAvatar.each ->
    $(@).attr('src', avatarPath )