BigW Consortium Gitlab

milestone.rb 5.64 KB
Newer Older
1
class Milestone < ActiveRecord::Base
2 3
  # Represents a "No Milestone" state used for filtering Issues and Merge
  # Requests that have no milestone assigned.
4 5 6
  MilestoneStruct = Struct.new(:title, :name, :id)
  None = MilestoneStruct.new('No Milestone', 'No Milestone', 0)
  Any = MilestoneStruct.new('Any Milestone', '', -1)
7
  Upcoming = MilestoneStruct.new('Upcoming', '#upcoming', -2)
8

9
  include CacheMarkdownField
10
  include InternalId
11
  include Sortable
12
  include Referable
13
  include StripAttribute
14
  include Milestoneish
15

16 17 18
  cache_markdown_field :title, pipeline: :single_line
  cache_markdown_field :description

19 20
  belongs_to :project
  has_many :issues
21
  has_many :labels, -> { distinct.reorder('labels.title') },  through: :issues
22
  has_many :merge_requests
23
  has_many :participants, -> { distinct.reorder('users.name') }, through: :issues, source: :assignee
24
  has_many :events, as: :target, dependent: :destroy
25

26 27
  scope :active, -> { with_state(:active) }
  scope :closed, -> { with_state(:closed) }
28
  scope :of_projects, ->(ids) { where(project_id: ids) }
29

30
  validates :title, presence: true, uniqueness: { scope: :project_id }
Andrey Kumanyaev committed
31
  validates :project, presence: true
32
  validate :start_date_should_be_less_than_due_date, if: Proc.new { |m| m.start_date.present? && m.due_date.present? }
33

34 35
  strip_attributes :title

Andrew8xx8 committed
36
  state_machine :state, initial: :active do
37
    event :close do
Andrew8xx8 committed
38
      transition active: :closed
39 40 41
    end

    event :activate do
Andrew8xx8 committed
42
      transition closed: :active
43 44 45 46 47 48
    end

    state :closed

    state :active
  end
49

50 51
  alias_attribute :name, :title

52
  class << self
53 54 55 56 57 58 59
    # Searches for milestones matching the given query.
    #
    # This method uses ILIKE on PostgreSQL and LIKE on MySQL.
    #
    # query - The search query as a String
    #
    # Returns an ActiveRecord::Relation.
60
    def search(query)
61 62 63 64
      t = arel_table
      pattern = "%#{query}%"

      where(t[:title].matches(pattern).or(t[:description].matches(pattern)))
65 66 67
    end
  end

68 69 70 71
  def self.reference_prefix
    '%'
  end

72
  def self.reference_pattern
73 74 75
    # 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.
76
    @reference_pattern ||= %r{
77 78 79
      (#{Project.reference_pattern})?
      #{Regexp.escape(reference_prefix)}
      (?:
80 81 82
        (?<milestone_iid>
          \d+(?!\S\w)\b # Integer-based milestone iid, or
        ) |
83
        (?<milestone_name>
84 85
          [^"\s]+\b |  # String-based single-word milestone title, or
          "[^"]+"      # String-based multi-word milestone surrounded in quotes
86 87 88
        )
      )
    }x
89 90 91
  end

  def self.link_reference_pattern
92
    @link_reference_pattern ||= super("milestones", /(?<milestone>\d+)/)
93 94
  end

95 96 97 98
  def self.upcoming_ids_by_projects(projects)
    rel = unscoped.of_projects(projects).active.where('due_date > ?', Time.now)

    if Gitlab::Database.postgresql?
99
      rel.order(:project_id, :due_date).select('DISTINCT ON (project_id) id')
100 101 102 103 104 105 106
    else
      rel.
        group(:project_id).
        having('due_date = MIN(due_date)').
        pluck(:id, :project_id, :due_date).
        map(&:first)
    end
107 108
  end

109 110 111 112 113 114 115
  ##
  # Returns the String necessary to reference this Milestone in Markdown
  #
  # format - Symbol format to use (default: :iid, optional: :name)
  #
  # Examples:
  #
116 117 118 119
  #   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"
120
  #
121
  def to_reference(from_project = nil, format: :iid, full: false)
122 123
    format_reference = milestone_format_reference(format)
    reference = "#{self.class.reference_prefix}#{format_reference}"
124

125
    "#{project.to_reference(from_project, full: full)}#{reference}"
126 127 128
  end

  def reference_link_text(from_project = nil)
129
    self.title
130 131
  end

132 133 134 135
  def milestoneish_ids
    id
  end

136
  def can_be_closed?
137
    active? && issues.opened.count.zero?
138 139
  end

140 141
  def is_empty?(user = nil)
    total_items_count(user).zero?
142 143
  end

144
  def author_id
145
    nil
146
  end
147

148
  def title=(value)
149
    write_attribute(:title, sanitize_title(value)) if value.present?
150 151
  end

152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
  # Sorts the issues for the given IDs.
  #
  # This method runs a single SQL query using a CASE statement to update the
  # position of all issues in the current milestone (scoped to the list of IDs).
  #
  # Given the ids [10, 20, 30] this method produces a SQL query something like
  # the following:
  #
  #     UPDATE issues
  #     SET position = CASE
  #       WHEN id = 10 THEN 1
  #       WHEN id = 20 THEN 2
  #       WHEN id = 30 THEN 3
  #       ELSE position
  #     END
  #     WHERE id IN (10, 20, 30);
  #
  # This method expects that the IDs given in `ids` are already Fixnums.
  def sort_issues(ids)
    pairs = []

    ids.each_with_index do |id, index|
      pairs << id
      pairs << index + 1
    end

    conditions = 'WHEN id = ? THEN ? ' * ids.length

    issues.where(id: ids).
      update_all(["position = CASE #{conditions} ELSE position END", *pairs])
  end
183 184 185

  private

186
  def milestone_format_reference(format = :iid)
187
    raise ArgumentError, 'Unknown format' unless [:iid, :name].include?(format)
188 189 190 191

    if format == :name && !name.include?('"')
      %("#{name}")
    else
192
      iid
193 194
    end
  end
195 196 197 198

  def sanitize_title(value)
    CGI.unescape_html(Sanitize.clean(value.to_s))
  end
199 200 201 202 203 204

  def start_date_should_be_less_than_due_date
    if due_date <= start_date
      errors.add(:start_date, "Can't be greater than due date")
    end
  end
205 206 207 208

  def issues_finder_params
    { project_id: project_id }
  end
209
end