Read about our upcoming Code of Conduct on this issue

This instance was upgraded to Heptapod 0.28.0 today

issuable.rb 9.48 KB
Newer Older
1
# == Issuable concern
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
2
#
3
# Contains common functionality shared between Issues and MergeRequests
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
4
5
6
#
# Used by Issue, MergeRequest
#
7
module Issuable
8
  extend ActiveSupport::Concern
9
  include CacheMarkdownField
10
  include Participable
11
  include Mentionable
12
  include Subscribable
13
  include StripAttribute
14
  include Awardable
15
  include Taskable
16
17

  included do
18
19
20
    cache_markdown_field :title, pipeline: :single_line
    cache_markdown_field :description

21
22
    belongs_to :author, class_name: "User"
    belongs_to :assignee, class_name: "User"
23
    belongs_to :updated_by, class_name: "User"
24
    belongs_to :milestone
25
    has_many :notes, as: :noteable, inverse_of: :noteable, dependent: :destroy do
26
      def authors_loaded?
27
        # We check first if we're loaded to not load unnecessarily.
28
29
        loaded? && to_a.all? { |note| note.association(:author).loaded? }
      end
30
31
32
33
34

      def award_emojis_loaded?
        # We check first if we're loaded to not load unnecessarily.
        loaded? && to_a.all? { |note| note.association(:award_emoji).loaded? }
      end
35
    end
Timothy Andrew's avatar
Timothy Andrew committed
36

37
38
    has_many :label_links, as: :target, dependent: :destroy
    has_many :labels, through: :label_links
39
    has_many :todos, as: :target, dependent: :destroy
40

41
42
    has_one :metrics

Andrey Kumanyaev's avatar
Andrey Kumanyaev committed
43
    validates :author, presence: true
44
    validates :title, presence: true, length: { maximum: 255 }
45

46
    scope :authored, ->(user) { where(author_id: user) }
47
    scope :assigned_to, ->(u) { where(assignee_id: u.id)}
48
    scope :recent, -> { reorder(id: :desc) }
49
50
    scope :assigned, -> { where("assignee_id IS NOT NULL") }
    scope :unassigned, -> { where("assignee_id IS NULL") }
51
    scope :of_projects, ->(ids) { where(project_id: ids) }
52
    scope :of_milestones, ->(ids) { where(milestone_id: ids) }
53
    scope :with_milestone, ->(title) { left_joins_milestones.where(milestones: { title: title }) }
54
    scope :opened, -> { with_state(:opened, :reopened) }
55
56
    scope :only_opened, -> { with_state(:opened) }
    scope :only_reopened, -> { with_state(:reopened) }
57
    scope :closed, -> { with_state(:closed) }
58

59
    scope :left_joins_milestones,    -> { joins("LEFT OUTER JOIN milestones ON #{table_name}.milestone_id = milestones.id") }
60
61
    scope :order_milestone_due_desc, -> { left_joins_milestones.reorder('milestones.due_date IS NULL, milestones.id IS NULL, milestones.due_date DESC') }
    scope :order_milestone_due_asc,  -> { left_joins_milestones.reorder('milestones.due_date IS NULL, milestones.id IS NULL, milestones.due_date ASC') }
62

63
    scope :without_label, -> { joins("LEFT OUTER JOIN label_links ON label_links.target_type = '#{name}' AND label_links.target_id = #{table_name}.id").where(label_links: { id: nil }) }
64
    scope :join_project, -> { joins(:project) }
65
    scope :inc_notes_with_associations, -> { includes(notes: [ :project, :author, :award_emoji ]) }
66
    scope :references_project, -> { references(:project) }
67
    scope :non_archived, -> { join_project.where(projects: { archived: false }) }
68

69
70
    delegate :name,
             :email,
71
72
             to: :author,
             prefix: true
73
74
75

    delegate :name,
             :email,
76
77
78
             to: :assignee,
             allow_nil: true,
             prefix: true
79

80
    attr_mentionable :title, pipeline: :single_line
Yorick Peterse's avatar
Yorick Peterse committed
81
82
83
84
85
86
    attr_mentionable :description

    participant :author
    participant :assignee
    participant :notes_with_associations

87
    strip_attributes :title
88
89

    acts_as_paranoid
Josh Frye's avatar
Josh Frye committed
90
91

    after_save :update_assignee_cache_counts, if: :assignee_id_changed?
92
    after_save :record_metrics
Josh Frye's avatar
Josh Frye committed
93
94
95
96

    def update_assignee_cache_counts
      # make sure we flush the cache for both the old *and* new assignee
      User.find(assignee_id_was).update_cache_counts if assignee_id_was
Josh Frye's avatar
Josh Frye committed
97
      assignee.update_cache_counts if assignee
Josh Frye's avatar
Josh Frye committed
98
    end
99
100
101
102
103
104

    # We want to use optimistic lock for cases when only title or description are involved
    # http://api.rubyonrails.org/classes/ActiveRecord/Locking/Optimistic.html
    def locking_enabled?
      title_changed? || description_changed?
    end
105
106
  end

107
  module ClassMethods
108
109
110
111
112
113
114
    # Searches for records with a matching title.
    #
    # This method uses ILIKE on PostgreSQL and LIKE on MySQL.
    #
    # query - The search query as a String
    #
    # Returns an ActiveRecord::Relation.
115
    def search(query)
116
      where(arel_table[:title].matches("%#{query}%"))
117
    end
118

119
120
121
122
123
124
125
    # Searches for records with a matching title or description.
    #
    # This method uses ILIKE on PostgreSQL and LIKE on MySQL.
    #
    # query - The search query as a String
    #
    # Returns an ActiveRecord::Relation.
126
    def full_search(query)
127
128
129
130
      t = arel_table
      pattern = "%#{query}%"

      where(t[:title].matches(pattern).or(t[:description].matches(pattern)))
131
132
    end

133
    def sort(method, excluded_labels: [])
134
135
136
137
138
139
140
141
142
143
144
145
      sorted = case method.to_s
               when 'milestone_due_asc' then order_milestone_due_asc
               when 'milestone_due_desc' then order_milestone_due_desc
               when 'downvotes_desc' then order_downvotes_desc
               when 'upvotes_desc' then order_upvotes_desc
               when 'priority' then order_labels_priority(excluded_labels: excluded_labels)
               else
                 order_by(method)
               end

      # Break ties with the ID column for pagination
      sorted.order(id: :desc)
146
    end
147

148
    def order_labels_priority(excluded_labels: [])
149
150
151
      params = {
        target_type: name,
        target_column: "#{table_name}.id",
152
        project_column: "#{table_name}.#{project_foreign_key}",
153
154
155
156
        excluded_labels: excluded_labels
      }

      highest_priority = highest_label_priority(params).to_sql
Felipe Artur's avatar
Felipe Artur committed
157
158

      select("#{table_name}.*, (#{highest_priority}) AS highest_priority").
159
160
161
162
        group(arel_table[:id]).
        reorder(Gitlab::Database.nulls_last_order('highest_priority', 'ASC'))
    end

163
    def with_label(title, sort = nil)
164
      if title.is_a?(Array) && title.size > 1
Felipe Artur's avatar
Felipe Artur committed
165
        joins(:labels).where(labels: { title: title }).group(*grouping_columns(sort)).having("COUNT(DISTINCT labels.title) = #{title.size}")
166
167
168
169
      else
        joins(:labels).where(labels: { title: title })
      end
    end
170
171
172
173
174

    # Includes table keys in group by clause when sorting
    # preventing errors in postgres
    #
    # Returns an array of arel columns
Felipe Artur's avatar
Felipe Artur committed
175
176
    def grouping_columns(sort)
      grouping_columns = [arel_table[:id]]
177
178
179

      if ["milestone_due_desc", "milestone_due_asc"].include?(sort)
        milestone_table = Milestone.arel_table
Felipe Artur's avatar
Felipe Artur committed
180
181
        grouping_columns << milestone_table[:id]
        grouping_columns << milestone_table[:due_date]
182
183
      end

Felipe Artur's avatar
Felipe Artur committed
184
      grouping_columns
185
    end
186
187
188
189

    def to_ability_name
      model_name.singular
    end
190
191
192
193
194
195
196
197
198
  end

  def today?
    Date.today == created_at.to_date
  end

  def new?
    today? && created_at == updated_at
  end
199
200
201
202
203

  def is_being_reassigned?
    assignee_id_changed?
  end

204
205
206
207
  def open?
    opened? || reopened?
  end

Z.J. van de Weg's avatar
Z.J. van de Weg committed
208
  def user_notes_count
209
210
211
212
213
214
215
    if notes.loaded?
      # Use the in-memory association to select and count to avoid hitting the db
      notes.to_a.count { |note| !note.system? }
    else
      # do the count query
      notes.user.count
    end
Z.J. van de Weg's avatar
Z.J. van de Weg committed
216
217
  end

218
  def subscribed_without_subscriptions?(user, project)
219
220
221
    participants(user).include?(user)
  end

Kirill Zaitsev's avatar
Kirill Zaitsev committed
222
  def to_hook_data(user)
223
    hook_data = {
224
      object_kind: self.class.name.underscore,
Kirill Zaitsev's avatar
Kirill Zaitsev committed
225
      user: user.hook_attrs,
226
227
228
229
      project: project.hook_attrs,
      object_attributes: hook_attrs,
      # DEPRECATED
      repository: project.hook_attrs.slice(:name, :url, :description, :homepage)
230
    }
231
232
233
    hook_data.merge!(assignee: assignee.hook_attrs) if assignee

    hook_data
234
  end
235

236
237
238
239
  def labels_array
    labels.to_a
  end

240
241
242
243
  def label_names
    labels.order('title ASC').pluck(:title)
  end

Robert Speicher's avatar
Robert Speicher committed
244
245
246
247
248
249
250
  # Convert this Issuable class name to a format usable by Ability definitions
  #
  # Examples:
  #
  #   issuable.class           # => MergeRequest
  #   issuable.to_ability_name # => "merge_request"
  def to_ability_name
251
    self.class.to_ability_name
Robert Speicher's avatar
Robert Speicher committed
252
253
  end

254
255
256
257
258
259
260
261
262
263
264
  # Convert this Issuable class name to a format usable by notifications.
  #
  # Examples:
  #
  #   issuable.class           # => MergeRequest
  #   issuable.human_class_name # => "merge request"

  def human_class_name
    @human_class_name ||= self.class.name.titleize.downcase
  end

265
266
267
268
269
270
271
272
  # Returns a Hash of attributes to be used for Twitter card metadata
  def card_attributes
    {
      'Author'   => author.try(:name),
      'Assignee' => assignee.try(:name)
    }
  end

273
  def notes_with_associations
274
275
276
277
278
279
    # If A has_many Bs, and B has_many Cs, and you do
    # `A.includes(b: :c).each { |a| a.b.includes(:c) }`, sadly ActiveRecord
    # will do the inclusion again. So, we check if all notes in the relation
    # already have their authors loaded (possibly because the scope
    # `inc_notes_with_associations` was used) and skip the inclusion if that's
    # the case.
280
281
282
283
284
285
286
287
    includes = []
    includes << :author unless notes.authors_loaded?
    includes << :award_emoji unless notes.award_emojis_loaded?
    if includes.any?
      notes.includes(includes)
    else
      notes
    end
288
289
  end

290
291
292
  def updated_tasks
    Taskable.get_updated_tasks(old_content: previous_changes['description'].first,
                               new_content: description)
293
  end
294
295
296
297
298
299
300
301
302

  ##
  # Method that checks if issuable can be moved to another project.
  #
  # Should be overridden if issuable can be moved.
  #
  def can_move?(*)
    false
  end
303

Yorick Peterse's avatar
Yorick Peterse committed
304
305
306
307
308
  def assignee_or_author?(user)
    # We're comparing IDs here so we don't need to load any associations.
    author_id == user.id || assignee_id == user.id
  end

309
310
311
312
  def record_metrics
    metrics = self.metrics || create_metrics
    metrics.record!
  end
313
end