notification.rb 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class Transaction::Notification
  3. include ChecksHumanChanges
  4. # Following SMTP error codes will be handled gracefully.
  5. # They will be logged at info level only and the code will not propagate up the error.
  6. # Other SMTP error codes will stop processing and exit with logging it at error level.
  7. #
  8. # 4xx - temporary issues.
  9. # 52x - permanent receiving server errors.
  10. # 55x - permanent receiving mailbox errors.
  11. SILENCABLE_SMTP_ERROR_CODES = [400..499, 520..529, 550..559].freeze
  12. =begin
  13. {
  14. object: 'Ticket',
  15. type: 'update',
  16. object_id: 123,
  17. interface_handle: 'application_server', # application_server|websocket|scheduler
  18. changes: {
  19. 'attribute1' => [before, now],
  20. 'attribute2' => [before, now],
  21. },
  22. created_at: Time.zone.now,
  23. user_id: 123,
  24. },
  25. =end
  26. def initialize(item, params = {})
  27. @item = item
  28. @params = params
  29. end
  30. def perform
  31. # return if we run import mode
  32. return if Setting.get('import_mode')
  33. return if @item[:object] != 'Ticket'
  34. return if @params[:disable_notification]
  35. ticket = Ticket.find_by(id: @item[:object_id])
  36. return if !ticket
  37. if @item[:article_id]
  38. article = Ticket::Article.find(@item[:article_id])
  39. # ignore notifications
  40. sender = Ticket::Article::Sender.lookup(id: article.sender_id)
  41. if sender&.name == 'System'
  42. return if @item[:changes].blank? && article.preferences[:notification] != true
  43. if article.preferences[:notification] != true
  44. article = nil
  45. end
  46. end
  47. end
  48. (recipients_and_channels, recipients_reason) = recipients_and_reasons(ticket)
  49. # send notifications
  50. recipients_and_channels.each do |item|
  51. send_to_single_recipient(item, article, ticket, recipients_reason)
  52. end
  53. end
  54. def recipients_and_reasons(ticket)
  55. # find recipients
  56. recipients_and_channels = []
  57. recipients_reason = {}
  58. # loop through all group users
  59. possible_recipients = possible_recipients_of_group(ticket.group_id)
  60. # loop through all mention users
  61. mention_users = Mention.where(mentionable_type: @item[:object], mentionable_id: @item[:object_id]).map(&:user)
  62. if mention_users.present?
  63. # only notify if read permission on group are given
  64. mention_users.each do |mention_user|
  65. next if !mention_user.group_access?(ticket.group_id, 'read')
  66. possible_recipients.push mention_user
  67. recipients_reason[mention_user.id] = __('You are receiving this because you were mentioned in this ticket.')
  68. end
  69. end
  70. # apply owner
  71. if ticket.owner_id != 1
  72. possible_recipients.push ticket.owner
  73. recipients_reason[ticket.owner_id] = __('You are receiving this because you are the owner of this ticket.')
  74. end
  75. # apply out of office agents
  76. possible_recipients_additions = Set.new
  77. possible_recipients.each do |user|
  78. ooo_replacements(
  79. user: user,
  80. replacements: possible_recipients_additions,
  81. reasons: recipients_reason,
  82. ticket: ticket,
  83. )
  84. end
  85. if possible_recipients_additions.present?
  86. # join unique entries
  87. possible_recipients |= possible_recipients_additions.to_a
  88. end
  89. already_checked_recipient_ids = {}
  90. possible_recipients.each do |user|
  91. result = NotificationFactory::Mailer.notification_settings(user, ticket, @item[:type])
  92. next if !result
  93. next if already_checked_recipient_ids[user.id]
  94. already_checked_recipient_ids[user.id] = true
  95. recipients_and_channels.push result
  96. next if recipients_reason[user.id]
  97. recipients_reason[user.id] = __('You are receiving this because you are a member of the group of this ticket.')
  98. end
  99. [recipients_and_channels, recipients_reason]
  100. end
  101. def send_to_single_recipient(item, article, ticket, recipients_reason)
  102. user = item[:user]
  103. channels = item[:channels]
  104. # ignore user who changed it by him self via web
  105. if @params[:interface_handle] == 'application_server'
  106. return if article&.updated_by_id == user.id
  107. return if !article && @item[:user_id] == user.id
  108. end
  109. # ignore inactive users
  110. return if !user.active?
  111. # ignore if no changes has been done
  112. changes = human_changes(@item[:changes], ticket, user)
  113. return if @item[:type] == 'update' && !article && changes.blank?
  114. # check if today already notified
  115. if @item[:type] == 'reminder_reached' || @item[:type] == 'escalation' || @item[:type] == 'escalation_warning'
  116. identifier = user.email
  117. if !identifier || identifier == ''
  118. identifier = user.login
  119. end
  120. already_notified_cutoff = Time.use_zone(Setting.get('timezone_default')) { Time.current.beginning_of_day }
  121. already_notified = History.where(
  122. history_type_id: History.type_lookup('notification').id,
  123. history_object_id: History.object_lookup('Ticket').id,
  124. o_id: ticket.id
  125. ).where('created_at > ?', already_notified_cutoff).exists?(['value_to LIKE ?', "%#{SqlHelper.quote_like(identifier)}(#{SqlHelper.quote_like(@item[:type])}:%"])
  126. return if already_notified
  127. end
  128. # create online notification
  129. used_channels = []
  130. if channels['online']
  131. used_channels.push 'online'
  132. created_by_id = @item[:user_id] || 1
  133. # delete old notifications
  134. if @item[:type] == 'reminder_reached'
  135. seen = false
  136. created_by_id = 1
  137. OnlineNotification.remove_by_type('Ticket', ticket.id, @item[:type], user)
  138. elsif @item[:type] == 'escalation' || @item[:type] == 'escalation_warning'
  139. seen = false
  140. created_by_id = 1
  141. OnlineNotification.remove_by_type('Ticket', ticket.id, 'escalation', user)
  142. OnlineNotification.remove_by_type('Ticket', ticket.id, 'escalation_warning', user)
  143. # on updates without state changes create unseen messages
  144. elsif @item[:type] != 'create' && (@item[:changes].blank? || @item[:changes]['state_id'].blank?)
  145. seen = false
  146. else
  147. seen = OnlineNotification.seen_state?(ticket, user.id)
  148. end
  149. OnlineNotification.add(
  150. type: @item[:type],
  151. object: 'Ticket',
  152. o_id: ticket.id,
  153. seen: seen,
  154. created_by_id: created_by_id,
  155. user_id: user.id,
  156. )
  157. Rails.logger.debug { "sent ticket online notification to agent (#{@item[:type]}/#{ticket.id}/#{user.email})" }
  158. end
  159. # ignore email channel notification and empty emails
  160. if !channels['email'] || user.email.blank?
  161. add_recipient_list_to_history(ticket, user, used_channels, @item[:type])
  162. return
  163. end
  164. used_channels.push 'email'
  165. add_recipient_list_to_history(ticket, user, used_channels, @item[:type])
  166. # get user based notification template
  167. # if create, send create message / block update messages
  168. template = case @item[:type]
  169. when 'create'
  170. 'ticket_create'
  171. when 'update'
  172. 'ticket_update'
  173. when 'reminder_reached'
  174. 'ticket_reminder_reached'
  175. when 'escalation'
  176. 'ticket_escalation'
  177. when 'escalation_warning'
  178. 'ticket_escalation_warning'
  179. when 'update.merged_into'
  180. 'ticket_update_merged_into'
  181. when 'update.received_merge'
  182. 'ticket_update_received_merge'
  183. else
  184. raise "unknown type for notification #{@item[:type]}"
  185. end
  186. current_user = User.lookup(id: @item[:user_id])
  187. if !current_user
  188. current_user = User.lookup(id: 1)
  189. end
  190. attachments = []
  191. if article
  192. attachments = article.attachments_inline
  193. end
  194. NotificationFactory::Mailer.notification(
  195. template: template,
  196. user: user,
  197. objects: {
  198. ticket: ticket,
  199. article: article,
  200. recipient: user,
  201. current_user: current_user,
  202. changes: changes,
  203. reason: recipients_reason[user.id],
  204. },
  205. message_id: "<notification.#{DateTime.current.to_fs(:number)}.#{ticket.id}.#{user.id}.#{SecureRandom.uuid}@#{Setting.get('fqdn')}>",
  206. references: ticket.get_references,
  207. main_object: ticket,
  208. attachments: attachments,
  209. )
  210. Rails.logger.debug { "sent ticket email notification to agent (#{@item[:type]}/#{ticket.id}/#{user.email})" }
  211. rescue Channel::DeliveryError => e
  212. status_code = begin
  213. e.original_error.response.status.to_i
  214. rescue
  215. raise e
  216. end
  217. if SILENCABLE_SMTP_ERROR_CODES.any? { |elem| elem.include? status_code }
  218. Rails.logger.info do
  219. "could not send ticket email notification to agent (#{@item[:type]}/#{ticket.id}/#{user.email}) #{e.original_error}"
  220. end
  221. return
  222. end
  223. raise e
  224. end
  225. def add_recipient_list_to_history(ticket, user, channels, type)
  226. return if channels.blank?
  227. identifier = user.email.presence || user.login
  228. recipient_list = "#{identifier}(#{type}:#{channels.join(',')})"
  229. History.add(
  230. o_id: ticket.id,
  231. history_type: 'notification',
  232. history_object: 'Ticket',
  233. value_to: recipient_list,
  234. created_by_id: @item[:user_id] || 1
  235. )
  236. end
  237. private
  238. def ooo_replacements(user:, replacements:, ticket:, reasons:)
  239. replacement = user.out_of_office_agent
  240. return if !replacement
  241. return if !TicketPolicy.new(replacement, ticket).agent_read_access?
  242. return if !replacements.add?(replacement)
  243. reasons[replacement.id] = __('You are receiving this because you are out-of-office replacement for a participant of this ticket.')
  244. end
  245. def possible_recipients_of_group(group_id)
  246. Rails.cache.fetch("User/notification/possible_recipients_of_group/#{group_id}", expires_in: 20.seconds) do
  247. User.group_access(group_id, 'full').sort_by(&:login)
  248. end
  249. end
  250. end