notification.rb 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. blocked_in_days = user.mail_delivery_failed_blocked_days
  124. if blocked_in_days.positive?
  125. Rails.logger.info "Send no system notifications to #{user.email} because email is marked as mail_delivery_failed for #{blocked_in_days} day(s)"
  126. return
  127. end
  128. # ignore if no changes has been done
  129. changes = human_changes(@item[:changes], ticket, user)
  130. return if @item[:type] == 'update' && !article && changes.blank?
  131. # check if today already notified
  132. if @item[:type] == 'reminder_reached' || @item[:type] == 'escalation' || @item[:type] == 'escalation_warning'
  133. identifier = user.email
  134. if !identifier || identifier == ''
  135. identifier = user.login
  136. end
  137. already_notified_cutoff = Time.use_zone(Setting.get('timezone_default')) { Time.current.beginning_of_day }
  138. already_notified = History.where(
  139. history_type_id: History.type_lookup('notification').id,
  140. history_object_id: History.object_lookup('Ticket').id,
  141. o_id: ticket.id
  142. ).where('created_at > ?', already_notified_cutoff).exists?(['value_to LIKE ?', "%#{SqlHelper.quote_like(identifier)}(#{SqlHelper.quote_like(@item[:type])}:%"])
  143. return if already_notified
  144. end
  145. # create online notification
  146. used_channels = []
  147. if channels['online']
  148. used_channels.push 'online'
  149. created_by_id = @item[:user_id] || 1
  150. # delete old notifications
  151. if @item[:type] == 'reminder_reached'
  152. seen = false
  153. created_by_id = 1
  154. OnlineNotification.remove_by_type('Ticket', ticket.id, @item[:type], user)
  155. elsif @item[:type] == 'escalation' || @item[:type] == 'escalation_warning'
  156. seen = false
  157. created_by_id = 1
  158. OnlineNotification.remove_by_type('Ticket', ticket.id, 'escalation', user)
  159. OnlineNotification.remove_by_type('Ticket', ticket.id, 'escalation_warning', user)
  160. # on updates without state changes create unseen messages
  161. elsif @item[:type] != 'create' && (@item[:changes].blank? || @item[:changes]['state_id'].blank?)
  162. seen = false
  163. else
  164. seen = OnlineNotification.seen_state?(ticket, user.id)
  165. end
  166. OnlineNotification.add(
  167. type: @item[:type],
  168. object: @item[:object],
  169. o_id: @item[:object].eql?('Ticket') ? ticket.id : article.id,
  170. seen: seen,
  171. created_by_id: created_by_id,
  172. user_id: user.id,
  173. )
  174. Rails.logger.debug { "sent ticket online notification to agent (#{@item[:type]}/#{ticket.id}/#{user.email})" }
  175. end
  176. # ignore email channel notification and empty emails
  177. if !channels['email'] || user.email.blank?
  178. add_recipient_list_to_history(ticket, user, used_channels, @item[:type])
  179. return
  180. end
  181. used_channels.push 'email'
  182. add_recipient_list_to_history(ticket, user, used_channels, @item[:type])
  183. # get user based notification template
  184. # if create, send create message / block update messages
  185. template = case @item[:type]
  186. when 'create'
  187. 'ticket_create'
  188. when 'update'
  189. 'ticket_update'
  190. when 'reminder_reached'
  191. 'ticket_reminder_reached'
  192. when 'escalation'
  193. 'ticket_escalation'
  194. when 'escalation_warning'
  195. 'ticket_escalation_warning'
  196. when 'update.merged_into'
  197. 'ticket_update_merged_into'
  198. when 'update.received_merge'
  199. 'ticket_update_received_merge'
  200. when 'update.reaction'
  201. 'ticket_article_update_reaction'
  202. else
  203. raise "unknown type for notification #{@item[:type]}"
  204. end
  205. attachments = []
  206. if article
  207. attachments = article.attachments_inline
  208. end
  209. NotificationFactory::Mailer.notification(
  210. template: template,
  211. user: user,
  212. objects: {
  213. ticket: ticket,
  214. article: article,
  215. recipient: user,
  216. current_user: current_user,
  217. changes: changes,
  218. reason: recipients_reason[user.id],
  219. },
  220. message_id: "<notification.#{DateTime.current.to_fs(:number)}.#{ticket.id}.#{user.id}.#{SecureRandom.uuid}@#{Setting.get('fqdn')}>",
  221. references: ticket.get_references,
  222. main_object: ticket,
  223. attachments: attachments,
  224. )
  225. Rails.logger.debug { "sent ticket email notification to agent (#{@item[:type]}/#{ticket.id}/#{user.email})" }
  226. rescue Channel::DeliveryError => e
  227. status_code = begin
  228. e.original_error.response.status.to_i
  229. rescue
  230. raise e
  231. end
  232. if SILENCABLE_SMTP_ERROR_CODES.any? { |elem| elem.include? status_code }
  233. Rails.logger.info do
  234. "could not send ticket email notification to agent (#{@item[:type]}/#{ticket.id}/#{user.email}) #{e.original_error}"
  235. end
  236. return
  237. end
  238. raise e
  239. end
  240. def add_recipient_list_to_history(ticket, user, channels, type)
  241. return if channels.blank?
  242. identifier = user.email.presence || user.login
  243. recipient_list = "#{identifier}(#{type}:#{channels.join(',')})"
  244. History.add(
  245. o_id: ticket.id,
  246. history_type: 'notification',
  247. history_object: 'Ticket',
  248. value_to: recipient_list,
  249. created_by_id: @item[:user_id] || 1
  250. )
  251. end
  252. private
  253. def ooo_replacements(user:, replacements:, ticket:, reasons:)
  254. replacement = user.out_of_office_agent
  255. return if !replacement
  256. return if !TicketPolicy.new(replacement, ticket).agent_read_access?
  257. return if !replacements.add?(replacement)
  258. reasons[replacement.id] = __('You are receiving this because you are out-of-office replacement for a participant of this ticket.')
  259. end
  260. def possible_recipients_of_group(group_id)
  261. Rails.cache.fetch("User/notification/possible_recipients_of_group/#{group_id}/#{User.latest_change}", expires_in: 20.seconds) do
  262. User.group_access(group_id, 'full').sort_by(&:login)
  263. end
  264. end
  265. end