notification.rb 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. module TriggerWebhookJob::CustomPayload::Notification
  3. Notification = Struct.new('Notification', :subject, :message, :link, :changes, :body)
  4. def self.generate(tracks = {}, event)
  5. return '\#{bad event}' if event.exclude?(:execution)
  6. type = type!(event)
  7. return '\#{bad type}' if type.blank?
  8. template = fetch(tracks, event, type)
  9. assemble(template, has_article: tracks[:article].present?)
  10. end
  11. # private class methods
  12. def self.fetch(tracks, event, type)
  13. NotificationFactory::Messaging.template(
  14. template: "ticket_#{type}",
  15. locale: Setting.get('locale_default') || 'en-us',
  16. timezone: Setting.get('timezone_default_sanitized'),
  17. objects: {
  18. ticket: tracks.fetch(:ticket, nil),
  19. article: tracks.fetch(:article, nil),
  20. current_user: event[:user_id].present? ? User.lookup(id: event[:user_id]) : nil,
  21. changes: event[:changes],
  22. },
  23. )
  24. end
  25. def self.type!(event)
  26. return 'info' if event[:execution].eql?('job')
  27. return event[:type] if event[:execution].eql?('trigger')
  28. nil
  29. end
  30. def self.assemble(template, has_article: false)
  31. match = regex(has_article).match(template[:body])
  32. notification = {
  33. subject: template[:subject][2..],
  34. message: match[:message].presence || '',
  35. link: match[:link].presence || '',
  36. changes: match[:changes].presence || '',
  37. body: has_article ? match[:body].presence || '' : '',
  38. }
  39. sanitize(notification)
  40. Notification.new(*notification.values)
  41. end
  42. def self.regex(extended)
  43. source = '_<(?<link>.+)>:(?<message>.+)_\n(?<changes>.+)'
  44. source = "#{source}\n{3,4}(?<body>.+)?" if extended
  45. Regexp.new(source, Regexp::MULTILINE)
  46. end
  47. def self.sanitize(hash)
  48. hash.each do |key, value|
  49. if key.eql?(:changes)
  50. value = value
  51. .split(%r{\n})
  52. .map(&:strip)
  53. .compact_blank
  54. .join('\n')
  55. end
  56. hash[key] = value.strip
  57. end
  58. end
  59. private_class_method %i[
  60. assemble
  61. fetch
  62. regex
  63. sanitize
  64. type!
  65. ]
  66. end