notification.rb 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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. attr_accessor :recipients_and_channels, :recipients_reason
  27. def initialize(item, params = {})
  28. @item = item
  29. @params = params
  30. @recipients_and_channels = []
  31. @recipients_reason = {}
  32. end
  33. def ticket
  34. @ticket ||= Ticket.find_by(id: @item[:object_id])
  35. end
  36. def article_by_item
  37. return 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. article
  48. end
  49. def article
  50. @article ||= article_by_item
  51. end
  52. def current_user
  53. @current_user ||= User.lookup(id: @item[:user_id]) || User.lookup(id: 1)
  54. end
  55. def perform
  56. # return if we run import mode
  57. return if Setting.get('import_mode')
  58. return if %w[Ticket Ticket::Article].exclude?(@item[:object])
  59. return if @params[:disable_notification]
  60. return if !ticket
  61. prepare_recipients_and_reasons
  62. # send notifications
  63. recipients_and_channels.each do |recipient_settings|
  64. send_to_single_recipient(recipient_settings)
  65. end
  66. end
  67. def prepare_recipients_and_reasons
  68. # loop through all group users
  69. possible_recipients = possible_recipients_of_group(ticket.group_id)
  70. # loop through all mention users
  71. mention_users = Mention.where(mentionable_type: @item[:object], mentionable_id: @item[:object_id]).map(&:user)
  72. if mention_users.present?
  73. # only notify if read permission on group are given
  74. mention_users.each do |mention_user|
  75. next if !mention_user.group_access?(ticket.group_id, 'read')
  76. possible_recipients.push mention_user
  77. @recipients_reason[mention_user.id] = __('You are receiving this because you were mentioned in this ticket.')
  78. end
  79. end
  80. # apply owner
  81. if ticket.owner_id != 1
  82. possible_recipients.push ticket.owner
  83. @recipients_reason[ticket.owner_id] = __('You are receiving this because you are the owner of this ticket.')
  84. end
  85. # apply out of office agents
  86. possible_recipients_additions = Set.new
  87. possible_recipients.each do |user|
  88. ooo_replacements(
  89. user: user,
  90. replacements: possible_recipients_additions,
  91. reasons: recipients_reason,
  92. ticket: ticket,
  93. )
  94. end
  95. if possible_recipients_additions.present?
  96. # join unique entries
  97. possible_recipients |= possible_recipients_additions.to_a
  98. end
  99. recipients_reason_by_notifications_settings(possible_recipients)
  100. end
  101. def recipients_reason_by_notifications_settings(possible_recipients)
  102. already_checked_recipient_ids = {}
  103. possible_recipients.each do |user|
  104. result = NotificationFactory::Mailer.notification_settings(user, ticket, @item[:type])
  105. next if !result
  106. next if already_checked_recipient_ids[user.id]
  107. already_checked_recipient_ids[user.id] = true
  108. @recipients_and_channels.push result
  109. next if recipients_reason[user.id]
  110. @recipients_reason[user.id] = __('You are receiving this because you are a member of the group of this ticket.')
  111. end
  112. end
  113. def send_to_single_recipient(recipient_settings)
  114. user = recipient_settings[:user]
  115. channels = recipient_settings[:channels]
  116. # ignore user who changed it by him self via web
  117. if @params[:interface_handle] == 'application_server'
  118. return if article&.updated_by_id == user.id
  119. return if !article && @item[:user_id] == user.id
  120. end
  121. # ignore inactive users
  122. return if !user.active?
  123. # ignore if no changes has been done
  124. changes = human_changes(@item[:changes], ticket, user)
  125. return if @item[:type] == 'update' && !article && changes.blank?
  126. # check if today already notified
  127. if @item[:type] == 'reminder_reached' || @item[:type] == 'escalation' || @item[:type] == 'escalation_warning'
  128. identifier = user.email
  129. if !identifier || identifier == ''
  130. identifier = user.login
  131. end
  132. already_notified_cutoff = Time.use_zone(Setting.get('timezone_default')) { Time.current.beginning_of_day }
  133. already_notified = History.where(
  134. history_type_id: History.type_lookup('notification').id,
  135. history_object_id: History.object_lookup('Ticket').id,
  136. o_id: ticket.id
  137. ).where('created_at > ?', already_notified_cutoff).exists?(['value_to LIKE ?', "%#{SqlHelper.quote_like(identifier)}(#{SqlHelper.quote_like(@item[:type])}:%"])
  138. return if already_notified
  139. end
  140. # create online notification
  141. used_channels = []
  142. if channels['online']
  143. used_channels.push 'online'
  144. created_by_id = @item[:user_id] || 1
  145. # delete old notifications
  146. if @item[:type] == 'reminder_reached'
  147. seen = false
  148. created_by_id = 1
  149. OnlineNotification.remove_by_type('Ticket', ticket.id, @item[:type], user)
  150. elsif @item[:type] == 'escalation' || @item[:type] == 'escalation_warning'
  151. seen = false
  152. created_by_id = 1
  153. OnlineNotification.remove_by_type('Ticket', ticket.id, 'escalation', user)
  154. OnlineNotification.remove_by_type('Ticket', ticket.id, 'escalation_warning', user)
  155. # on updates without state changes create unseen messages
  156. elsif @item[:type] != 'create' && (@item[:changes].blank? || @item[:changes]['state_id'].blank?)
  157. seen = false
  158. else
  159. seen = OnlineNotification.seen_state?(ticket, user.id)
  160. end
  161. OnlineNotification.add(
  162. type: @item[:type],
  163. object: @item[:object],
  164. o_id: @item[:object].eql?('Ticket') ? ticket.id : article.id,
  165. seen: seen,
  166. created_by_id: created_by_id,
  167. user_id: user.id,
  168. )
  169. Rails.logger.debug { "sent ticket online notification to agent (#{@item[:type]}/#{ticket.id}/#{user.email})" }
  170. end
  171. # ignore email channel notification and empty emails
  172. if !channels['email'] || user.email.blank?
  173. add_recipient_list_to_history(ticket, user, used_channels, @item[:type])
  174. return
  175. end
  176. used_channels.push 'email'
  177. add_recipient_list_to_history(ticket, user, used_channels, @item[:type])
  178. # get user based notification template
  179. # if create, send create message / block update messages
  180. template = case @item[:type]
  181. when 'create'
  182. 'ticket_create'
  183. when 'update'
  184. 'ticket_update'
  185. when 'reminder_reached'
  186. 'ticket_reminder_reached'
  187. when 'escalation'
  188. 'ticket_escalation'
  189. when 'escalation_warning'
  190. 'ticket_escalation_warning'
  191. when 'update.merged_into'
  192. 'ticket_update_merged_into'
  193. when 'update.received_merge'
  194. 'ticket_update_received_merge'
  195. when 'update.reaction'
  196. 'ticket_article_update_reaction'
  197. else
  198. raise "unknown type for notification #{@item[:type]}"
  199. end
  200. attachments = []
  201. if article
  202. attachments = article.attachments_inline
  203. end
  204. NotificationFactory::Mailer.notification(
  205. template: template,
  206. user: user,
  207. objects: {
  208. ticket: ticket,
  209. article: article,
  210. recipient: user,
  211. current_user: current_user,
  212. changes: changes,
  213. reason: recipients_reason[user.id],
  214. },
  215. message_id: "<notification.#{DateTime.current.to_fs(:number)}.#{ticket.id}.#{user.id}.#{SecureRandom.uuid}@#{Setting.get('fqdn')}>",
  216. references: ticket.get_references,
  217. main_object: ticket,
  218. attachments: attachments,
  219. )
  220. Rails.logger.debug { "sent ticket email notification to agent (#{@item[:type]}/#{ticket.id}/#{user.email})" }
  221. rescue Channel::DeliveryError => e
  222. status_code = begin
  223. e.original_error.response.status.to_i
  224. rescue
  225. raise e
  226. end
  227. if SILENCABLE_SMTP_ERROR_CODES.any? { |elem| elem.include? status_code }
  228. Rails.logger.info do
  229. "could not send ticket email notification to agent (#{@item[:type]}/#{ticket.id}/#{user.email}) #{e.original_error}"
  230. end
  231. return
  232. end
  233. raise e
  234. end
  235. def add_recipient_list_to_history(ticket, user, channels, type)
  236. return if channels.blank?
  237. identifier = user.email.presence || user.login
  238. recipient_list = "#{identifier}(#{type}:#{channels.join(',')})"
  239. History.add(
  240. o_id: ticket.id,
  241. history_type: 'notification',
  242. history_object: 'Ticket',
  243. value_to: recipient_list,
  244. created_by_id: @item[:user_id] || 1
  245. )
  246. end
  247. private
  248. def ooo_replacements(user:, replacements:, ticket:, reasons:)
  249. replacement = user.out_of_office_agent
  250. return if !replacement
  251. return if !TicketPolicy.new(replacement, ticket).agent_read_access?
  252. return if !replacements.add?(replacement)
  253. reasons[replacement.id] = __('You are receiving this because you are out-of-office replacement for a participant of this ticket.')
  254. end
  255. def possible_recipients_of_group(group_id)
  256. Rails.cache.fetch("User/notification/possible_recipients_of_group/#{group_id}", expires_in: 20.seconds) do
  257. User.group_access(group_id, 'full').sort_by(&:login)
  258. end
  259. end
  260. end