notify_mentioned_users_job.rb 1.47 KB
class NotifyMentionedUsersJob < Struct.new(:tracked_action_id)
  include MentionHelper

  def perform
    return unless ActionTracker::Record.exists?(tracked_action_id)
    tracked_action = ActionTracker::Record.find(tracked_action_id)

    mention_creator = Person.find(tracked_action.user_id)

    remove_followers = false
    mention_text = if tracked_action.target_type == "Comment"
                      tracked_action.params["body"]
                   else #scrap
                      remove_followers = true #scraps already notify followers.
                      tracked_action.params["content"]
                   end

    people_identifiers = get_mentions mention_text
    people_identifiers -= [mention_creator.identifier]

    followers = mention_creator.followers
    people_identifiers -= followers.map(&:identifier) if (followers.present? && remove_followers)

    return if people_identifiers.empty?

    people_identifiers = "'" + people_identifiers.join("','") + "'"

    notification_sql = "INSERT INTO action_tracker_notifications(profile_id,action_tracker_id) " +
                       "SELECT p.id, #{tracked_action.id} FROM profiles AS p " +
                       "WHERE p.identifier IN (#{people_identifiers}) AND " +
                       "p.id NOT IN (SELECT atn.profile_id FROM action_tracker_notifications AS atn " +
                       "WHERE atn.action_tracker_id = #{tracked_action.id})"

    ActionTrackerNotification.connection.execute(notification_sql)
  end
end