mention.rb 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. class Mention < ApplicationModel
  3. include ChecksClientNotification
  4. include HasHistory
  5. include Mention::Assets
  6. after_create :update_mentionable
  7. after_destroy :update_mentionable
  8. belongs_to :created_by, class_name: 'User'
  9. belongs_to :updated_by, class_name: 'User'
  10. belongs_to :user, class_name: 'User'
  11. belongs_to :mentionable, polymorphic: true
  12. association_attributes_ignored :created_by, :updated_by
  13. client_notification_events_ignored :update, :touch
  14. validates_with Mention::Validation
  15. def notify_clients_data_attributes
  16. super.merge(
  17. 'mentionable_id' => mentionable_id,
  18. 'mentionable_type' => mentionable_type,
  19. )
  20. end
  21. def history_log_attributes
  22. {
  23. related_o_id: mentionable_id,
  24. related_history_object: mentionable_type,
  25. value_to: user.id,
  26. }
  27. end
  28. def history_destroy
  29. history_log('removed', created_by_id)
  30. end
  31. def self.duplicates(mentionable1, mentionable2)
  32. Mention.joins(', mentions as mentionsb').where('
  33. mentions.user_id = mentionsb.user_id
  34. AND mentions.mentionable_type = ?
  35. AND mentions.mentionable_id = ?
  36. AND mentionsb.mentionable_type = ?
  37. AND mentionsb.mentionable_id = ?
  38. ', mentionable1.class.to_s, mentionable1.id, mentionable2.class.to_s, mentionable2.id)
  39. end
  40. def update_mentionable
  41. mentionable.update(updated_by: updated_by)
  42. mentionable.touch # rubocop:disable Rails/SkipsModelValidations
  43. end
  44. # Check if user is subscribed to given object
  45. # @param target to check against
  46. # @param user
  47. # @return Boolean
  48. def self.subscribed?(object, user)
  49. object.mentions.exists? user: user
  50. end
  51. # Subscribe a user to changes of an object
  52. # @param target to subscribe to
  53. # @param user
  54. # @return Boolean
  55. def self.subscribe!(object, user)
  56. object
  57. .mentions
  58. .find_or_create_by! user: user
  59. true
  60. end
  61. # Unsubscribe a user from changes of an object
  62. # @param target to unsubscribe from
  63. # @param user
  64. # @return Boolean
  65. def self.unsubscribe!(object, user)
  66. object
  67. .mentions
  68. .find_by(user: user)
  69. &.destroy!
  70. true
  71. end
  72. # Check if given user is able to subscribe to a given object
  73. # @param object to subscribe to
  74. # @param mentioned user
  75. # @return Boolean
  76. def self.mentionable?(object, user)
  77. case object
  78. when Ticket
  79. TicketPolicy.new(user, object).agent_read_access?
  80. else
  81. false
  82. end
  83. end
  84. end