Read about our upcoming Code of Conduct on this issue

milestone.rb 9.41 KB
Newer Older
1
2
# frozen_string_literal: true

3
class Milestone < ApplicationRecord
4
5
  # Represents a "No Milestone" state used for filtering Issues and Merge
  # Requests that have no milestone assigned.
6
7
8
  MilestoneStruct = Struct.new(:title, :name, :id)
  None = MilestoneStruct.new('No Milestone', 'No Milestone', 0)
  Any = MilestoneStruct.new('Any Milestone', '', -1)
tiagonbotelho's avatar
tiagonbotelho committed
9
  Upcoming = MilestoneStruct.new('Upcoming', '#upcoming', -2)
10
  Started = MilestoneStruct.new('Started', '#started', -3)
11

12
  include CacheMarkdownField
13
  include AtomicInternalId
Shinya Maeda's avatar
Shinya Maeda committed
14
  include IidRoutes
15
  include Sortable
16
  include Referable
17
  include StripAttribute
18
  include Milestoneish
19
  include Gitlab::SQL::Pattern
20

21
22
23
  cache_markdown_field :title, pipeline: :single_line
  cache_markdown_field :description

Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
24
  belongs_to :project
Felipe Artur's avatar
Felipe Artur committed
25
26
  belongs_to :group

27
28
29
  has_internal_id :iid, scope: :project, init: ->(s) { s&.project&.milestones&.maximum(:iid) }
  has_internal_id :iid, scope: :group, init: ->(s) { s&.group&.milestones&.maximum(:iid) }

Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
30
  has_many :issues
31
  has_many :labels, -> { distinct.reorder('labels.title') }, through: :issues
32
  has_many :merge_requests
33
  has_many :events, as: :target, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
34

Felipe Artur's avatar
Felipe Artur committed
35
36
  scope :of_projects, ->(ids) { where(project_id: ids) }
  scope :of_groups, ->(ids) { where(group_id: ids) }
Andrew8xx8's avatar
Andrew8xx8 committed
37
38
  scope :active, -> { with_state(:active) }
  scope :closed, -> { with_state(:closed) }
Felipe Artur's avatar
Felipe Artur committed
39
  scope :for_projects, -> { where(group: nil).includes(:project) }
40
  scope :started, -> { active.where('milestones.start_date <= CURRENT_DATE') }
Felipe Artur's avatar
Felipe Artur committed
41

42
43
44
  scope :for_projects_and_groups, -> (projects, groups) do
    projects = projects.compact if projects.is_a? Array
    projects = [] if projects.nil?
Felipe Artur's avatar
Felipe Artur committed
45

46
47
    groups = groups.compact if groups.is_a? Array
    groups = [] if groups.nil?
Felipe Artur's avatar
Felipe Artur committed
48

49
    where(project_id: projects).or(where(group_id: groups))
Felipe Artur's avatar
Felipe Artur committed
50
51
  end

52
53
54
  scope :order_by_name_asc, -> { order(Arel::Nodes::Ascending.new(arel_table[:title].lower)) }
  scope :reorder_by_due_date_asc, -> { reorder(Gitlab::Database.nulls_last_order('due_date', 'ASC')) }

Felipe Artur's avatar
Felipe Artur committed
55
56
  validates :group, presence: true, unless: :project
  validates :project, presence: true, unless: :group
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
57

Felipe Artur's avatar
Felipe Artur committed
58
59
  validate :uniqueness_of_title, if: :title_changed?
  validate :milestone_type_check
mhasbini's avatar
mhasbini committed
60
  validate :start_date_should_be_less_than_due_date, if: proc { |m| m.start_date.present? && m.due_date.present? }
Andrew8xx8's avatar
Andrew8xx8 committed
61

62
63
  strip_attributes :title

Andrew8xx8's avatar
Andrew8xx8 committed
64
  state_machine :state, initial: :active do
Andrew8xx8's avatar
Andrew8xx8 committed
65
    event :close do
Andrew8xx8's avatar
Andrew8xx8 committed
66
      transition active: :closed
Andrew8xx8's avatar
Andrew8xx8 committed
67
68
69
    end

    event :activate do
Andrew8xx8's avatar
Andrew8xx8 committed
70
      transition closed: :active
Andrew8xx8's avatar
Andrew8xx8 committed
71
72
73
74
75
76
    end

    state :closed

    state :active
  end
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
77

78
79
  alias_attribute :name, :title

Valery Sizov's avatar
Valery Sizov committed
80
  class << self
Jacopo's avatar
Jacopo committed
81
    # Searches for milestones with a matching title or description.
82
83
84
85
86
87
    #
    # This method uses ILIKE on PostgreSQL and LIKE on MySQL.
    #
    # query - The search query as a String
    #
    # Returns an ActiveRecord::Relation.
Valery Sizov's avatar
Valery Sizov committed
88
    def search(query)
89
      fuzzy_search(query, [:title, :description])
Valery Sizov's avatar
Valery Sizov committed
90
    end
Felipe Artur's avatar
Felipe Artur committed
91

Jacopo's avatar
Jacopo committed
92
93
94
95
96
97
98
99
100
101
102
    # Searches for milestones 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.
    def search_title(query)
      fuzzy_search(query, [:title])
    end

Felipe Artur's avatar
Felipe Artur committed
103
104
105
106
107
108
109
    def filter_by_state(milestones, state)
      case state
      when 'closed' then milestones.closed
      when 'all' then milestones
      else milestones.active
      end
    end
110

111
112
113
114
    def count_by_state
      reorder(nil).group(:state).count
    end

115
116
117
118
119
120
    def predefined?(milestone)
      milestone == Any ||
        milestone == None ||
        milestone == Upcoming ||
        milestone == Started
    end
Valery Sizov's avatar
Valery Sizov committed
121
122
  end

123
124
125
126
  def self.reference_prefix
    '%'
  end

127
  def self.reference_pattern
128
129
130
    # NOTE: The iid pattern only matches when all characters on the expression
    # are digits, so it will match %2 but not %2.1 because that's probably a
    # milestone name and we want it to be matched as such.
Rémy Coutable's avatar
Rémy Coutable committed
131
    @reference_pattern ||= %r{
132
133
134
      (#{Project.reference_pattern})?
      #{Regexp.escape(reference_prefix)}
      (?:
135
136
137
        (?<milestone_iid>
          \d+(?!\S\w)\b # Integer-based milestone iid, or
        ) |
138
        (?<milestone_name>
139
140
          [^"\s]+\b |  # String-based single-word milestone title, or
          "[^"]+"      # String-based multi-word milestone surrounded in quotes
141
142
143
        )
      )
    }x
144
145
146
  end

  def self.link_reference_pattern
147
    @link_reference_pattern ||= super("milestones", /(?<milestone>\d+)/)
148
149
  end

150
151
  def self.upcoming_ids(projects, groups)
    rel = unscoped
152
            .for_projects_and_groups(projects, groups)
153
            .active.where('milestones.due_date > CURRENT_DATE')
154
155

    if Gitlab::Database.postgresql?
156
      rel.order(:project_id, :group_id, :due_date).select('DISTINCT ON (project_id, group_id) id')
157
    else
158
159
160
161
162
163
164
      # We need to use MySQL's NULL-safe comparison operator `<=>` here
      # because one of `project_id` or `group_id` is always NULL
      join_clause = <<~HEREDOC
        LEFT OUTER JOIN milestones earlier_milestones
          ON milestones.project_id <=> earlier_milestones.project_id
            AND milestones.group_id <=> earlier_milestones.group_id
            AND milestones.due_date > earlier_milestones.due_date
165
            AND earlier_milestones.due_date > CURRENT_DATE
166
167
168
            AND earlier_milestones.state = 'active'
      HEREDOC

169
      rel
170
171
172
        .joins(join_clause)
        .where('earlier_milestones.id IS NULL')
        .select(:id)
173
    end
tiagonbotelho's avatar
tiagonbotelho committed
174
175
  end

176
  def participants
177
    User.joins(assigned_issues: :milestone).where("milestones.id = ?", id).distinct
178
179
  end

180
  def self.sort_by_attribute(method)
181
182
183
    sorted =
      case method.to_s
      when 'due_date_asc'
184
        reorder_by_due_date_asc
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
      when 'due_date_desc'
        reorder(Gitlab::Database.nulls_last_order('due_date', 'DESC'))
      when 'name_asc'
        reorder(Arel::Nodes::Ascending.new(arel_table[:title].lower))
      when 'name_desc'
        reorder(Arel::Nodes::Descending.new(arel_table[:title].lower))
      when 'start_date_asc'
        reorder(Gitlab::Database.nulls_last_order('start_date', 'ASC'))
      when 'start_date_desc'
        reorder(Gitlab::Database.nulls_last_order('start_date', 'DESC'))
      else
        order_by(method)
      end

    sorted.with_order_id_desc
200
201
  end

202
203
204
205
  def self.states_count(projects, groups = nil)
    return STATE_COUNT_HASH unless projects || groups

    counts = Milestone
206
               .for_projects_and_groups(projects, groups)
207
208
209
210
211
212
213
214
215
216
217
               .reorder(nil)
               .group(:state)
               .count

    {
        opened: counts['active'] || 0,
        closed: counts['closed'] || 0,
        all: counts.values.sum
    }
  end

218
  ##
219
220
221
  # Returns the String necessary to reference this Milestone in Markdown. Group
  # milestones only support name references, and do not support cross-project
  # references.
222
223
224
225
226
  #
  # format - Symbol format to use (default: :iid, optional: :name)
  #
  # Examples:
  #
227
228
229
230
  #   Milestone.first.to_reference                           # => "%1"
  #   Milestone.first.to_reference(format: :name)            # => "%\"goal\""
  #   Milestone.first.to_reference(cross_namespace_project)  # => "gitlab-org/gitlab-ce%1"
  #   Milestone.first.to_reference(same_namespace_project)   # => "gitlab-ce%1"
231
  #
232
  def to_reference(from = nil, format: :name, full: false)
233
234
    format_reference = milestone_format_reference(format)
    reference = "#{self.class.reference_prefix}#{format_reference}"
235

236
    if project
237
      "#{project.to_reference(from, full: full)}#{reference}"
238
239
240
    else
      reference
    end
241
242
  end

243
  def reference_link_text(from = nil)
244
    self.class.reference_prefix + self.title
245
246
  end

247
  def milestoneish_id
248
249
250
    id
  end

Felipe Artur's avatar
Felipe Artur committed
251
252
253
254
  def for_display
    self
  end

Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
255
  def can_be_closed?
Andrew8xx8's avatar
Andrew8xx8 committed
256
    active? && issues.opened.count.zero?
257
258
  end

259
  def author_id
260
    nil
261
  end
262

263
  def title=(value)
264
    write_attribute(:title, sanitize_title(value)) if value.present?
265
266
  end

Felipe Artur's avatar
Felipe Artur committed
267
268
269
270
271
272
273
274
  def safe_title
    title.to_slug.normalize.to_s
  end

  def parent
    group || project
  end

275
  def group_milestone?
Felipe Artur's avatar
Felipe Artur committed
276
277
278
    group_id.present?
  end

279
  def project_milestone?
Felipe Artur's avatar
Felipe Artur committed
280
281
282
    project_id.present?
  end

283
284
  private

Felipe Artur's avatar
Felipe Artur committed
285
286
287
288
289
  # Milestone titles must be unique across project milestones and group milestones
  def uniqueness_of_title
    if project
      relation = Milestone.for_projects_and_groups([project_id], [project.group&.id])
    elsif group
290
      relation = Milestone.for_projects_and_groups(group.projects.select(:id), [group.id])
Felipe Artur's avatar
Felipe Artur committed
291
292
293
    end

    title_exists = relation.find_by_title(title)
294
    errors.add(:title, _("already being used for another group or project milestone.")) if title_exists
Felipe Artur's avatar
Felipe Artur committed
295
296
297
298
299
300
  end

  # Milestone should be either a project milestone or a group milestone
  def milestone_type_check
    if group_id && project_id
      field = project_id_changed? ? :project_id : :group_id
301
      errors.add(field, _("milestone should belong either to a project or a group."))
Felipe Artur's avatar
Felipe Artur committed
302
303
304
    end
  end

305
  def milestone_format_reference(format = :iid)
306
    raise ArgumentError, _('Unknown format') unless [:iid, :name].include?(format)
307

308
    if group_milestone? && format == :iid
309
      raise ArgumentError, _('Cannot refer to a group milestone by an internal id!')
310
311
    end

312
313
314
    if format == :name && !name.include?('"')
      %("#{name}")
    else
315
      iid
316
317
    end
  end
318
319
320
321

  def sanitize_title(value)
    CGI.unescape_html(Sanitize.clean(value.to_s))
  end
322
323
324

  def start_date_should_be_less_than_due_date
    if due_date <= start_date
325
      errors.add(:due_date, _("must be greater than start date"))
326
327
    end
  end
328
329

  def issues_finder_params
330
    { project_id: project_id }
331
  end
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
332
end