<commit_before>services = angular.module('cases.services', []);


DEFAULT_POST_OPTS = {transformRequest: angular.identity, headers: {'Content-Type': undefined}}

#=====================================================================
# Date utilities
#=====================================================================

parseIso8601 = (str) ->
  if str then new Date(Date.parse str) else null

formatIso8601 = (date) ->
  if date then date.toISOString() else null


#=====================================================================
# Message service
#=====================================================================

services.factory 'MessageService', ['$rootScope', '$http', ($rootScope, $http) ->
  new class MessageService

    #----------------------------------------------------------------------------
    # Fetches old messages for the given label
    #----------------------------------------------------------------------------
    fetchOld: (search, before, page, callback) ->
      params = @_searchToParams(search)
      params.before = formatIso8601(before)
      params.page = page

      $http.get('/message/?' + $.param(params))
      .success (data) =>
        @_processMessages(data.results)
        callback(data.results, data.total, data.has_more)

    #----------------------------------------------------------------------------
    # Fetches new messages for the given label
    #----------------------------------------------------------------------------
    fetchNew: (search, after, before, callback) ->
      params = @_searchToParams(search)
      params.after = formatIso8601(after)
      params.before = formatIso8601(before)

      $http.get('/message/?' + $.param(params))
      .success (data) =>
        @_processMessages(data.results)

        if data.results.length > 0
          maxTime = data.results[0].time
          maxId = data.results[0].id
        else
          maxTime = null
          maxId = null

        callback(data.results, maxTime, maxId)

    #----------------------------------------------------------------------------
    # Fetches history for a single message
    #----------------------------------------------------------------------------
    fetchHistory: (message, callback) ->
      $http.get('/message/history/' + message.id + '/')
      .success (data) =>
        @_processMessageActions(data.actions)
        callback(data.actions)

    #----------------------------------------------------------------------------
    # Starts a message export
    #----------------------------------------------------------------------------
    startExport: (search, callback) ->
      params = @_searchToParams(search)
      $http.post('/messageexport/create/?' + $.param(params))
      .success () =>
        callback()

    #----------------------------------------------------------------------------
    # Reply-to messages
    #----------------------------------------------------------------------------
    replyToMessages: (messages, text, callback) ->
      # it's generally better to send via URNs but anon orgs won't have them
      urns = []
      contacts = []
      for msg in messages
        if msg.urn
          urns.push(msg.urn)
        else
          contacts.push(msg.contact)

      @_messagesSend('B', text, urns, contacts, null, callback)

    #----------------------------------------------------------------------------
    # Flag or un-flag messages
    #----------------------------------------------------------------------------
    flagMessages: (messages, flagged, callback) ->
      action = if flagged then 'flag' else 'unflag'
      @_messagesAction(messages, action, null, () ->
        for msg in messages
          msg.flagged = flagged
        if callback
          callback()
      )

    #----------------------------------------------------------------------------
    # Label messages with the given label
    #----------------------------------------------------------------------------
    labelMessages: (messages, label, callback) ->
      without_label = []
      for msg in messages
        if label.name not in msg.labels
          without_label.push(msg)
          msg.labels.push(label)

      if without_label.length > 0
        @_messagesAction(without_label, 'label', label, callback)

    #----------------------------------------------------------------------------
    # Archive messages
    #----------------------------------------------------------------------------
    archiveMessages: (messages, callback) ->
      @_messagesAction(messages, 'archive', null, () ->
        for msg in messages
          msg.archived = true
        if callback
          callback()
      )

    #----------------------------------------------------------------------------
    # Restore (i.e. un-archive) messages
    #----------------------------------------------------------------------------
    restoreMessages: (messages, callback) ->
      @_messagesAction(messages, 'restore', null, () ->
        for msg in messages
          msg.archived = false
        if callback
          callback()
      )

    #----------------------------------------------------------------------------
    # Relabel the given message (removing labels if necessary)
    #----------------------------------------------------------------------------
    relabelMessage: (message, labels, callback) ->
      data = new FormData()
      data.append('labels', (l.id for l in labels))

      $http.post('/message/label/' + message.id + '/', data, DEFAULT_POST_OPTS)
      .success () ->
        message.labels = labels
        if callback
          callback()

    #----------------------------------------------------------------------------
    # Reply to a contact in a case
    #----------------------------------------------------------------------------
    replyInCase: (text, _case, callback) ->
      @_messagesSend('C', text, [], [_case.contact.uuid], _case, callback)

    #----------------------------------------------------------------------------
    # Forward a message to a URN
    #----------------------------------------------------------------------------
    forwardToUrn: (text, urn, callback) ->
        @_messagesSend('F', text, [urn.urn], [], null, callback)

    #----------------------------------------------------------------------------
    # Convert search object to URL params
    #----------------------------------------------------------------------------
    _searchToParams: (search) ->
      params = {}
      params.view = search.view
      params.text = search.text
      params.after = formatIso8601(search.after)
      params.before = formatIso8601(search.before)
      params.groups = (g.uuid for g in search.groups).join(',')
      params.contact = search.contact
      params.label = if search.label then search.label.id else null
      return params

    #----------------------------------------------------------------------------
    # POSTs to the messages action endpoint
    #----------------------------------------------------------------------------
    _messagesAction: (messages, action, label, callback) ->
      data = new FormData();
      data.append('messages', (m.id for m in messages))
      if label
        data.append('label', label.id)

      $http.post '/message/action/' + action + '/', data, DEFAULT_POST_OPTS
      .success () =>
        if callback
          callback()

    #----------------------------------------------------------------------------
    # POSTs to the messages send endpoint and returns new broadcast id
    #----------------------------------------------------------------------------
    _messagesSend: (activity, text, urns, contacts, _case, callback) ->
      data = new FormData();
      data.append('activity', activity)
      data.append('text', text)
      data.append('urns', urns)
      data.append('contacts', contacts)
      if _case
        data.append('case', _case.id)
      $http.post('/message/send/', data, DEFAULT_POST_OPTS)
      .success (data) =>
        callback()

    #----------------------------------------------------------------------------
    # Processes incoming messages
    #----------------------------------------------------------------------------
    _processMessages: (messages) ->
      for msg in messages
        # parse datetime string
        msg.time = parseIso8601(msg.time)

    #----------------------------------------------------------------------------
    # Processes incoming message actions
    #----------------------------------------------------------------------------
    _processMessageActions: (actions) ->
      for action in actions
        action.created_on = parseIso8601(action.created_on)
]

#=====================================================================
# Label service
#=====================================================================

services.factory 'LabelService', ['$http', ($http) ->
  new class LabelService

    #----------------------------------------------------------------------------
    # Deletes a label
    #----------------------------------------------------------------------------
    deleteLabel: (label, callback) ->
      $http.post('/label/delete/' + label.id + '/')
      .success () ->
        callback()
]


#=====================================================================
# Case service
#=====================================================================

services.factory 'CaseService', ['$http', ($http) ->
  new class CaseService

    #----------------------------------------------------------------------------
    # Fetches old cases
    #----------------------------------------------------------------------------
    fetchOld: (search, before, page, callback) ->
      params = @_searchToParams(search)
      params.before = formatIso8601(before)
      params.page = page

      $http.get('/case/search/?' + $.param(params))
      .success (data) =>
        @_processCases(data.results)
        callback(data.results, data.total, data.has_more)

    #----------------------------------------------------------------------------
    # Fetches new cases
    #----------------------------------------------------------------------------
    fetchNew: (search, after, before, callback) ->
      params = @_searchToParams(search)
      params.after = formatIso8601(after)
      params.before = formatIso8601(before)

      $http.get('/case/search/?' + $.param(params))
      .success (data) =>
        @_processCases(data.results)
        callback(data.results)

    #----------------------------------------------------------------------------
    # Fetches an existing case by it's id
    #----------------------------------------------------------------------------
    fetchCase: (caseId, callback) ->
      $http.get('/case/fetch/' + caseId + '/')
      .success (_case) =>
        @_processCases([_case])
        callback(_case)

    #----------------------------------------------------------------------------
    # Opens a new case
    #----------------------------------------------------------------------------
    openCase: (message, summary, assignee, callback) ->
      data = new FormData()
      data.append('message', message.id)
      data.append('summary', summary)
      data.append('assignee', if assignee then assignee.id else null)
      $http.post('/case/open/', data, DEFAULT_POST_OPTS)
      .success (_case) ->
        callback(_case)

    #----------------------------------------------------------------------------
    # Adds a note to a case
    #----------------------------------------------------------------------------<commit_msg>Fix opening cases<commit_after>services = angular.module('cases.services', []);


DEFAULT_POST_OPTS = {transformRequest: angular.identity, headers: {'Content-Type': undefined}}

#=====================================================================
# Date utilities
#=====================================================================

parseIso8601 = (str) ->
  if str then new Date(Date.parse str) else null

formatIso8601 = (date) ->
  if date then date.toISOString() else null


#=====================================================================
# Message service
#=====================================================================

services.factory 'MessageService', ['$rootScope', '$http', ($rootScope, $http) ->
  new class MessageService

    #----------------------------------------------------------------------------
    # Fetches old messages for the given label
    #----------------------------------------------------------------------------
    fetchOld: (search, before, page, callback) ->
      params = @_searchToParams(search)
      params.before = formatIso8601(before)
      params.page = page

      $http.get('/message/?' + $.param(params))
      .success (data) =>
        @_processMessages(data.results)
        callback(data.results, data.total, data.has_more)

    #----------------------------------------------------------------------------
    # Fetches new messages for the given label
    #----------------------------------------------------------------------------
    fetchNew: (search, after, before, callback) ->
      params = @_searchToParams(search)
      params.after = formatIso8601(after)
      params.before = formatIso8601(before)

      $http.get('/message/?' + $.param(params))
      .success (data) =>
        @_processMessages(data.results)

        if data.results.length > 0
          maxTime = data.results[0].time
          maxId = data.results[0].id
        else
          maxTime = null
          maxId = null

        callback(data.results, maxTime, maxId)

    #----------------------------------------------------------------------------
    # Fetches history for a single message
    #----------------------------------------------------------------------------
    fetchHistory: (message, callback) ->
      $http.get('/message/history/' + message.id + '/')
      .success (data) =>
        @_processMessageActions(data.actions)
        callback(data.actions)

    #----------------------------------------------------------------------------
    # Starts a message export
    #----------------------------------------------------------------------------
    startExport: (search, callback) ->
      params = @_searchToParams(search)
      $http.post('/messageexport/create/?' + $.param(params))
      .success () =>
        callback()

    #----------------------------------------------------------------------------
    # Reply-to messages
    #----------------------------------------------------------------------------
    replyToMessages: (messages, text, callback) ->
      # it's generally better to send via URNs but anon orgs won't have them
      urns = []
      contacts = []
      for msg in messages
        if msg.urn
          urns.push(msg.urn)
        else
          contacts.push(msg.contact)

      @_messagesSend('B', text, urns, contacts, null, callback)

    #----------------------------------------------------------------------------
    # Flag or un-flag messages
    #----------------------------------------------------------------------------
    flagMessages: (messages, flagged, callback) ->
      action = if flagged then 'flag' else 'unflag'
      @_messagesAction(messages, action, null, () ->
        for msg in messages
          msg.flagged = flagged
        if callback
          callback()
      )

    #----------------------------------------------------------------------------
    # Label messages with the given label
    #----------------------------------------------------------------------------
    labelMessages: (messages, label, callback) ->
      without_label = []
      for msg in messages
        if label.name not in msg.labels
          without_label.push(msg)
          msg.labels.push(label)

      if without_label.length > 0
        @_messagesAction(without_label, 'label', label, callback)

    #----------------------------------------------------------------------------
    # Archive messages
    #----------------------------------------------------------------------------
    archiveMessages: (messages, callback) ->
      @_messagesAction(messages, 'archive', null, () ->
        for msg in messages
          msg.archived = true
        if callback
          callback()
      )

    #----------------------------------------------------------------------------
    # Restore (i.e. un-archive) messages
    #----------------------------------------------------------------------------
    restoreMessages: (messages, callback) ->
      @_messagesAction(messages, 'restore', null, () ->
        for msg in messages
          msg.archived = false
        if callback
          callback()
      )

    #----------------------------------------------------------------------------
    # Relabel the given message (removing labels if necessary)
    #----------------------------------------------------------------------------
    relabelMessage: (message, labels, callback) ->
      data = new FormData()
      data.append('labels', (l.id for l in labels))

      $http.post('/message/label/' + message.id + '/', data, DEFAULT_POST_OPTS)
      .success () ->
        message.labels = labels
        if callback
          callback()

    #----------------------------------------------------------------------------
    # Reply to a contact in a case
    #----------------------------------------------------------------------------
    replyInCase: (text, _case, callback) ->
      @_messagesSend('C', text, [], [_case.contact.uuid], _case, callback)

    #----------------------------------------------------------------------------
    # Forward a message to a URN
    #----------------------------------------------------------------------------
    forwardToUrn: (text, urn, callback) ->
        @_messagesSend('F', text, [urn.urn], [], null, callback)

    #----------------------------------------------------------------------------
    # Convert search object to URL params
    #----------------------------------------------------------------------------
    _searchToParams: (search) ->
      params = {}
      params.view = search.view
      params.text = search.text
      params.after = formatIso8601(search.after)
      params.before = formatIso8601(search.before)
      params.groups = (g.uuid for g in search.groups).join(',')
      params.contact = search.contact
      params.label = if search.label then search.label.id else null
      return params

    #----------------------------------------------------------------------------
    # POSTs to the messages action endpoint
    #----------------------------------------------------------------------------
    _messagesAction: (messages, action, label, callback) ->
      data = new FormData();
      data.append('messages', (m.id for m in messages))
      if label
        data.append('label', label.id)

      $http.post '/message/action/' + action + '/', data, DEFAULT_POST_OPTS
      .success () =>
        if callback
          callback()

    #----------------------------------------------------------------------------
    # POSTs to the messages send endpoint and returns new broadcast id
    #----------------------------------------------------------------------------
    _messagesSend: (activity, text, urns, contacts, _case, callback) ->
      data = new FormData();
      data.append('activity', activity)
      data.append('text', text)
      data.append('urns', urns)
      data.append('contacts', contacts)
      if _case
        data.append('case', _case.id)
      $http.post('/message/send/', data, DEFAULT_POST_OPTS)
      .success (data) =>
        callback()

    #----------------------------------------------------------------------------
    # Processes incoming messages
    #----------------------------------------------------------------------------
    _processMessages: (messages) ->
      for msg in messages
        # parse datetime string
        msg.time = parseIso8601(msg.time)

    #----------------------------------------------------------------------------
    # Processes incoming message actions
    #----------------------------------------------------------------------------
    _processMessageActions: (actions) ->
      for action in actions
        action.created_on = parseIso8601(action.created_on)
]

#=====================================================================
# Label service
#=====================================================================

services.factory 'LabelService', ['$http', ($http) ->
  new class LabelService

    #----------------------------------------------------------------------------
    # Deletes a label
    #----------------------------------------------------------------------------
    deleteLabel: (label, callback) ->
      $http.post('/label/delete/' + label.id + '/')
      .success () ->
        callback()
]


#=====================================================================
# Case service
#=====================================================================

services.factory 'CaseService', ['$http', ($http) ->
  new class CaseService

    #----------------------------------------------------------------------------
    # Fetches old cases
    #----------------------------------------------------------------------------
    fetchOld: (search, before, page, callback) ->
      params = @_searchToParams(search)
      params.before = formatIso8601(before)
      params.page = page

      $http.get('/case/search/?' + $.param(params))
      .success (data) =>
        @_processCases(data.results)
        callback(data.results, data.total, data.has_more)

    #----------------------------------------------------------------------------
    # Fetches new cases
    #----------------------------------------------------------------------------
    fetchNew: (search, after, before, callback) ->
      params = @_searchToParams(search)
      params.after = formatIso8601(after)
      params.before = formatIso8601(before)

      $http.get('/case/search/?' + $.param(params))
      .success (data) =>
        @_processCases(data.results)
        callback(data.results)

    #----------------------------------------------------------------------------
    # Fetches an existing case by it's id
    #----------------------------------------------------------------------------
    fetchCase: (caseId, callback) ->
      $http.get('/case/fetch/' + caseId + '/')
      .success (_case) =>
        @_processCases([_case])
        callback(_case)

    #----------------------------------------------------------------------------
    # Opens a new case
    #----------------------------------------------------------------------------
    openCase: (message, summary, assignee, callback) ->
      data = new FormData()
      data.append('message', message.id)
      data.append('summary', summary)
      if assignee
        data.append('assignee', assignee.id)

      $http.post('/case/open/', data, DEFAULT_POST_OPTS)
      .success (_case) ->
        callback(_case)

    #----------------------------------------------------------------------------
    # Adds a note to a case
    #----------------------------------------------------------------------------
{'fraction_non_alphanumeric': 0.4292808219178082, 'fraction_numerical': 0.004452054794520548, 'mean_word_length': 1.0016279667552053, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 91, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4642687', 'n_tokens_mistral': 4913, 'n_tokens_neox': 4679, 'n_words': 1147}