notification.rb 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. # Copyright (C) 2012-2021 Zammad Foundation, http://zammad-foundation.org/
  2. class Transaction::Notification
  3. =begin
  4. {
  5. object: 'Ticket',
  6. type: 'update',
  7. object_id: 123,
  8. interface_handle: 'application_server', # application_server|websocket|scheduler
  9. changes: {
  10. 'attribute1' => [before, now],
  11. 'attribute2' => [before, now],
  12. },
  13. created_at: Time.zone.now,
  14. user_id: 123,
  15. },
  16. =end
  17. def initialize(item, params = {})
  18. @item = item
  19. @params = params
  20. end
  21. def perform
  22. # return if we run import mode
  23. return if Setting.get('import_mode')
  24. return if @item[:object] != 'Ticket'
  25. return if @params[:disable_notification]
  26. ticket = Ticket.find_by(id: @item[:object_id])
  27. return if !ticket
  28. if @item[:article_id]
  29. article = Ticket::Article.find(@item[:article_id])
  30. # ignore notifications
  31. sender = Ticket::Article::Sender.lookup(id: article.sender_id)
  32. if sender&.name == 'System'
  33. return if @item[:changes].blank? && article.preferences[:notification] != true
  34. if article.preferences[:notification] != true
  35. article = nil
  36. end
  37. end
  38. end
  39. # find recipients
  40. recipients_and_channels = []
  41. recipients_reason = {}
  42. # loop through all group users
  43. possible_recipients = possible_recipients_of_group(ticket.group_id)
  44. # loop through all mention users
  45. mention_users = Mention.where(mentionable_type: @item[:object], mentionable_id: @item[:object_id]).map(&:user)
  46. if mention_users.present?
  47. # only notify if read permission on group are given
  48. mention_users.each do |mention_user|
  49. next if !mention_user.group_access?(ticket.group_id, 'read')
  50. possible_recipients.push mention_user
  51. recipients_reason[mention_user.id] = 'are subscribed'
  52. end
  53. end
  54. # apply owner
  55. if ticket.owner_id != 1
  56. possible_recipients.push ticket.owner
  57. recipients_reason[ticket.owner_id] = 'are assigned'
  58. end
  59. # apply out of office agents
  60. possible_recipients_additions = Set.new
  61. possible_recipients.each do |user|
  62. recursive_ooo_replacements(
  63. user: user,
  64. replacements: possible_recipients_additions,
  65. reasons: recipients_reason,
  66. )
  67. end
  68. if possible_recipients_additions.present?
  69. # join unique entries
  70. possible_recipients |= possible_recipients_additions.to_a
  71. end
  72. already_checked_recipient_ids = {}
  73. possible_recipients.each do |user|
  74. result = NotificationFactory::Mailer.notification_settings(user, ticket, @item[:type])
  75. next if !result
  76. next if already_checked_recipient_ids[user.id]
  77. already_checked_recipient_ids[user.id] = true
  78. recipients_and_channels.push result
  79. next if recipients_reason[user.id]
  80. recipients_reason[user.id] = 'are in group'
  81. end
  82. # send notifications
  83. recipients_and_channels.each do |item|
  84. user = item[:user]
  85. channels = item[:channels]
  86. # ignore user who changed it by him self via web
  87. if @params[:interface_handle] == 'application_server'
  88. next if article&.updated_by_id == user.id
  89. next if !article && @item[:user_id] == user.id
  90. end
  91. # ignore inactive users
  92. next if !user.active?
  93. # ignore if no changes has been done
  94. changes = human_changes(user, ticket)
  95. next if @item[:type] == 'update' && !article && changes.blank?
  96. # check if today already notified
  97. if @item[:type] == 'reminder_reached' || @item[:type] == 'escalation' || @item[:type] == 'escalation_warning'
  98. identifier = user.email
  99. if !identifier || identifier == ''
  100. identifier = user.login
  101. end
  102. already_notified = History.where(
  103. history_type_id: History.type_lookup('notification').id,
  104. history_object_id: History.object_lookup('Ticket').id,
  105. o_id: ticket.id
  106. ).where('created_at > ?', Time.zone.now.beginning_of_day).exists?(['value_to LIKE ?', "%#{identifier}(#{@item[:type]}:%"])
  107. next if already_notified
  108. end
  109. # create online notification
  110. used_channels = []
  111. if channels['online']
  112. used_channels.push 'online'
  113. created_by_id = @item[:user_id] || 1
  114. # delete old notifications
  115. if @item[:type] == 'reminder_reached'
  116. seen = false
  117. created_by_id = 1
  118. OnlineNotification.remove_by_type('Ticket', ticket.id, @item[:type], user)
  119. elsif @item[:type] == 'escalation' || @item[:type] == 'escalation_warning'
  120. seen = false
  121. created_by_id = 1
  122. OnlineNotification.remove_by_type('Ticket', ticket.id, 'escalation', user)
  123. OnlineNotification.remove_by_type('Ticket', ticket.id, 'escalation_warning', user)
  124. # on updates without state changes create unseen messages
  125. elsif @item[:type] != 'create' && (@item[:changes].blank? || @item[:changes]['state_id'].blank?)
  126. seen = false
  127. else
  128. seen = ticket.online_notification_seen_state(user.id)
  129. end
  130. OnlineNotification.add(
  131. type: @item[:type],
  132. object: 'Ticket',
  133. o_id: ticket.id,
  134. seen: seen,
  135. created_by_id: created_by_id,
  136. user_id: user.id,
  137. )
  138. Rails.logger.debug { "sent ticket online notifiaction to agent (#{@item[:type]}/#{ticket.id}/#{user.email})" }
  139. end
  140. # ignore email channel notification and empty emails
  141. if !channels['email'] || user.email.blank?
  142. add_recipient_list(ticket, user, used_channels, @item[:type])
  143. next
  144. end
  145. used_channels.push 'email'
  146. add_recipient_list(ticket, user, used_channels, @item[:type])
  147. # get user based notification template
  148. # if create, send create message / block update messages
  149. template = case @item[:type]
  150. when 'create'
  151. 'ticket_create'
  152. when 'update'
  153. 'ticket_update'
  154. when 'reminder_reached'
  155. 'ticket_reminder_reached'
  156. when 'escalation'
  157. 'ticket_escalation'
  158. when 'escalation_warning'
  159. 'ticket_escalation_warning'
  160. when 'update.merged_into'
  161. 'ticket_update_merged_into'
  162. when 'update.received_merge'
  163. 'ticket_update_received_merge'
  164. else
  165. raise "unknown type for notification #{@item[:type]}"
  166. end
  167. current_user = User.lookup(id: @item[:user_id])
  168. if !current_user
  169. current_user = User.lookup(id: 1)
  170. end
  171. attachments = []
  172. if article
  173. attachments = article.attachments_inline
  174. end
  175. NotificationFactory::Mailer.notification(
  176. template: template,
  177. user: user,
  178. objects: {
  179. ticket: ticket,
  180. article: article,
  181. recipient: user,
  182. current_user: current_user,
  183. changes: changes,
  184. reason: recipients_reason[user.id],
  185. },
  186. message_id: "<notification.#{DateTime.current.to_s(:number)}.#{ticket.id}.#{user.id}.#{rand(999_999)}@#{Setting.get('fqdn')}>",
  187. references: ticket.get_references,
  188. main_object: ticket,
  189. attachments: attachments,
  190. )
  191. Rails.logger.debug { "sent ticket email notifiaction to agent (#{@item[:type]}/#{ticket.id}/#{user.email})" }
  192. end
  193. end
  194. def add_recipient_list(ticket, user, channels, type)
  195. return if channels.blank?
  196. identifier = user.email
  197. if !identifier || identifier == ''
  198. identifier = user.login
  199. end
  200. recipient_list = "#{identifier}(#{type}:#{channels.join(',')})"
  201. History.add(
  202. o_id: ticket.id,
  203. history_type: 'notification',
  204. history_object: 'Ticket',
  205. value_to: recipient_list,
  206. created_by_id: @item[:user_id] || 1
  207. )
  208. end
  209. def human_changes(user, record)
  210. return {} if !@item[:changes]
  211. locale = user.locale
  212. # only show allowed attributes
  213. attribute_list = ObjectManager::Object.new('Ticket').attributes(user).index_by { |item| item[:name] }
  214. user_related_changes = {}
  215. @item[:changes].each do |key, value|
  216. # if no config exists, use all attributes
  217. # or if config exists, just use existing attributes for user
  218. if attribute_list.blank? || attribute_list[key.to_s]
  219. user_related_changes[key] = value
  220. end
  221. end
  222. changes = {}
  223. user_related_changes.each do |key, value|
  224. # get attribute name
  225. attribute_name = key.to_s
  226. object_manager_attribute = attribute_list[attribute_name]
  227. if attribute_name[-3, 3] == '_id'
  228. attribute_name = attribute_name[ 0, attribute_name.length - 3 ].to_s
  229. end
  230. # add item to changes hash
  231. if key.to_s == attribute_name
  232. changes[attribute_name] = value
  233. end
  234. # if changed item is an _id field/reference, look up the real values
  235. value_id = []
  236. value_str = [ value[0], value[1] ]
  237. if key.to_s[-3, 3] == '_id'
  238. value_id[0] = value[0]
  239. value_id[1] = value[1]
  240. if record.respond_to?(attribute_name) && record.send(attribute_name)
  241. relation_class = record.send(attribute_name).class
  242. if relation_class && value_id[0]
  243. relation_model = relation_class.lookup(id: value_id[0])
  244. if relation_model
  245. if relation_model['name']
  246. value_str[0] = relation_model['name']
  247. elsif relation_model.respond_to?('fullname')
  248. value_str[0] = relation_model.send('fullname')
  249. end
  250. end
  251. end
  252. if relation_class && value_id[1]
  253. relation_model = relation_class.lookup(id: value_id[1])
  254. if relation_model
  255. if relation_model['name']
  256. value_str[1] = relation_model['name']
  257. elsif relation_model.respond_to?('fullname')
  258. value_str[1] = relation_model.send('fullname')
  259. end
  260. end
  261. end
  262. end
  263. end
  264. # check if we have a dedicated display name for it
  265. display = attribute_name
  266. if object_manager_attribute && object_manager_attribute[:display]
  267. # delete old key
  268. changes.delete(display)
  269. # set new key
  270. display = object_manager_attribute[:display].to_s
  271. end
  272. changes[display] = if object_manager_attribute && object_manager_attribute[:translate]
  273. from = Translation.translate(locale, value_str[0])
  274. to = Translation.translate(locale, value_str[1])
  275. [from, to]
  276. else
  277. [value_str[0].to_s, value_str[1].to_s]
  278. end
  279. end
  280. changes
  281. end
  282. private
  283. def recursive_ooo_replacements(user:, replacements:, reasons:, level: 0)
  284. if level == 10
  285. Rails.logger.warn("Found more than 10 replacement levels for agent #{user}.")
  286. return
  287. end
  288. replacement = user.out_of_office_agent
  289. return if !replacement
  290. # return for already found, added and checked users
  291. # to prevent re-doing complete lookup paths
  292. return if !replacements.add?(replacement)
  293. reasons[replacement.id] = 'are the out-of-office replacement of the owner'
  294. recursive_ooo_replacements(
  295. user: replacement,
  296. replacements: replacements,
  297. reasons: reasons,
  298. level: level + 1
  299. )
  300. end
  301. def possible_recipients_of_group(group_id)
  302. cache = Cache.read("Transaction::Notification.group_access.full::#{group_id}")
  303. return cache if cache
  304. possible_recipients = User.group_access(group_id, 'full').sort_by(&:login)
  305. Cache.write("Transaction::Notification.group_access.full::#{group_id}", possible_recipients, expires_in: 20.seconds)
  306. possible_recipients
  307. end
  308. end