chat_session_start.rb 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class Sessions::Event::ChatSessionStart < Sessions::Event::ChatBase
  3. =begin
  4. a agent start`s a new chat session
  5. payload
  6. {
  7. event: 'chat_session_start',
  8. data: {},
  9. }
  10. return is sent as message back to peer
  11. =end
  12. def run
  13. return super if super
  14. return if !permission_check('chat.agent', 'chat')
  15. # find first in waiting list
  16. chat_user = User.lookup(id: @session['id'])
  17. chat_ids = Chat.agent_active_chat_ids(chat_user)
  18. chat_session = if @payload['chat_id']
  19. Chat::Session.where(state: 'waiting', chat_id: @payload['chat_id']).reorder(created_at: :asc).first
  20. else
  21. Chat::Session.where(state: 'waiting', chat_id: chat_ids).reorder(created_at: :asc).first
  22. end
  23. if !chat_session
  24. return {
  25. event: 'chat_session_start',
  26. data: {
  27. state: 'failed',
  28. message: __('No session available.'),
  29. },
  30. }
  31. end
  32. chat_session.user_id = chat_user.id
  33. chat_session.state = 'running'
  34. chat_session.preferences[:participants] = chat_session.add_recipient(@client_id)
  35. chat_session.save
  36. session_attributes = chat_session.attributes
  37. session_attributes['messages'] = []
  38. Chat::Message.where(chat_session_id: chat_session.id).reorder(created_at: :asc).each do |message|
  39. session_attributes['messages'].push message.attributes
  40. end
  41. # send chat_session_init to customer client
  42. if session_attributes['messages'].blank?
  43. user = chat_session.agent_user
  44. data = {
  45. event: 'chat_session_start',
  46. data: {
  47. state: 'ok',
  48. agent: user,
  49. session_id: chat_session.session_id,
  50. chat_id: chat_session.chat_id,
  51. },
  52. }
  53. chat_session.send_to_recipients(data, @client_id)
  54. end
  55. # send to agent
  56. data = {
  57. event: 'chat_session_start',
  58. data: {
  59. session: session_attributes,
  60. },
  61. }
  62. Sessions.send(@client_id, data)
  63. # send state update with sessions to agents
  64. Chat.broadcast_agent_state_update([chat_session.chat_id])
  65. # send position update to other waiting sessions
  66. Chat.broadcast_customer_state_update(chat_session.chat_id)
  67. nil
  68. end
  69. end