annotate app/models/issue.rb @ 976:0befb332f41a get_statistics

get stats up to current date
author luisf <luis.figueira@eecs.qmul.ac.uk>
date Thu, 25 Oct 2012 13:50:45 +0100
parents 5e80956cc792
children bb32da3bea34
rev   line source
Chris@245 1 # Redmine - project management software
Chris@245 2 # Copyright (C) 2006-2011 Jean-Philippe Lang
Chris@0 3 #
Chris@0 4 # This program is free software; you can redistribute it and/or
Chris@0 5 # modify it under the terms of the GNU General Public License
Chris@0 6 # as published by the Free Software Foundation; either version 2
Chris@0 7 # of the License, or (at your option) any later version.
Chris@441 8 #
Chris@0 9 # This program is distributed in the hope that it will be useful,
Chris@0 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
Chris@0 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Chris@0 12 # GNU General Public License for more details.
Chris@441 13 #
Chris@0 14 # You should have received a copy of the GNU General Public License
Chris@0 15 # along with this program; if not, write to the Free Software
Chris@0 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Chris@0 17
Chris@0 18 class Issue < ActiveRecord::Base
Chris@117 19 include Redmine::SafeAttributes
Chris@441 20
Chris@0 21 belongs_to :project
Chris@0 22 belongs_to :tracker
Chris@0 23 belongs_to :status, :class_name => 'IssueStatus', :foreign_key => 'status_id'
Chris@0 24 belongs_to :author, :class_name => 'User', :foreign_key => 'author_id'
Chris@909 25 belongs_to :assigned_to, :class_name => 'Principal', :foreign_key => 'assigned_to_id'
Chris@0 26 belongs_to :fixed_version, :class_name => 'Version', :foreign_key => 'fixed_version_id'
Chris@0 27 belongs_to :priority, :class_name => 'IssuePriority', :foreign_key => 'priority_id'
Chris@0 28 belongs_to :category, :class_name => 'IssueCategory', :foreign_key => 'category_id'
Chris@0 29
Chris@0 30 has_many :journals, :as => :journalized, :dependent => :destroy
Chris@0 31 has_many :time_entries, :dependent => :delete_all
Chris@0 32 has_and_belongs_to_many :changesets, :order => "#{Changeset.table_name}.committed_on ASC, #{Changeset.table_name}.id ASC"
Chris@441 33
Chris@0 34 has_many :relations_from, :class_name => 'IssueRelation', :foreign_key => 'issue_from_id', :dependent => :delete_all
Chris@0 35 has_many :relations_to, :class_name => 'IssueRelation', :foreign_key => 'issue_to_id', :dependent => :delete_all
Chris@441 36
Chris@210 37 acts_as_nested_set :scope => 'root_id', :dependent => :destroy
Chris@909 38 acts_as_attachable :after_add => :attachment_added, :after_remove => :attachment_removed
Chris@0 39 acts_as_customizable
Chris@0 40 acts_as_watchable
Chris@0 41 acts_as_searchable :columns => ['subject', "#{table_name}.description", "#{Journal.table_name}.notes"],
Chris@0 42 :include => [:project, :journals],
Chris@0 43 # sort by id so that limited eager loading doesn't break with postgresql
Chris@0 44 :order_column => "#{table_name}.id"
Chris@0 45 acts_as_event :title => Proc.new {|o| "#{o.tracker.name} ##{o.id} (#{o.status}): #{o.subject}"},
Chris@0 46 :url => Proc.new {|o| {:controller => 'issues', :action => 'show', :id => o.id}},
Chris@0 47 :type => Proc.new {|o| 'issue' + (o.closed? ? ' closed' : '') }
Chris@441 48
Chris@0 49 acts_as_activity_provider :find_options => {:include => [:project, :author, :tracker]},
Chris@0 50 :author_key => :author_id
Chris@0 51
Chris@0 52 DONE_RATIO_OPTIONS = %w(issue_field issue_status)
Chris@0 53
Chris@0 54 attr_reader :current_journal
Chris@0 55
Chris@0 56 validates_presence_of :subject, :priority, :project, :tracker, :author, :status
Chris@0 57
Chris@0 58 validates_length_of :subject, :maximum => 255
Chris@0 59 validates_inclusion_of :done_ratio, :in => 0..100
Chris@0 60 validates_numericality_of :estimated_hours, :allow_nil => true
Chris@909 61 validate :validate_issue
Chris@0 62
Chris@0 63 named_scope :visible, lambda {|*args| { :include => :project,
Chris@441 64 :conditions => Issue.visible_condition(args.shift || User.current, *args) } }
Chris@441 65
Chris@0 66 named_scope :open, :conditions => ["#{IssueStatus.table_name}.is_closed = ?", false], :include => :status
Chris@0 67
chris@22 68 named_scope :recently_updated, :order => "#{Issue.table_name}.updated_on DESC"
Chris@0 69 named_scope :with_limit, lambda { |limit| { :limit => limit} }
Chris@0 70 named_scope :on_active_project, :include => [:status, :project, :tracker],
Chris@0 71 :conditions => ["#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"]
chris@22 72
chris@22 73 named_scope :without_version, lambda {
chris@22 74 {
chris@22 75 :conditions => { :fixed_version_id => nil}
chris@22 76 }
chris@22 77 }
chris@22 78
chris@22 79 named_scope :with_query, lambda {|query|
chris@22 80 {
chris@22 81 :conditions => Query.merge_conditions(query.statement)
chris@22 82 }
chris@22 83 }
Chris@0 84
Chris@0 85 before_create :default_assign
chris@37 86 before_save :close_duplicates, :update_done_ratio_from_issue_status
chris@37 87 after_save :reschedule_following_issues, :update_nested_set_attributes, :update_parent_attributes, :create_journal
Chris@0 88 after_destroy :update_parent_attributes
Chris@441 89
Chris@441 90 # Returns a SQL conditions string used to find all issues visible by the specified user
Chris@441 91 def self.visible_condition(user, options={})
Chris@441 92 Project.allowed_to_condition(user, :view_issues, options) do |role, user|
Chris@441 93 case role.issues_visibility
Chris@441 94 when 'all'
Chris@441 95 nil
Chris@441 96 when 'default'
Chris@909 97 user_ids = [user.id] + user.groups.map(&:id)
Chris@909 98 "(#{table_name}.is_private = #{connection.quoted_false} OR #{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id IN (#{user_ids.join(',')}))"
Chris@441 99 when 'own'
Chris@909 100 user_ids = [user.id] + user.groups.map(&:id)
Chris@909 101 "(#{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id IN (#{user_ids.join(',')}))"
Chris@441 102 else
Chris@441 103 '1=0'
Chris@441 104 end
Chris@441 105 end
Chris@441 106 end
Chris@441 107
Chris@0 108 # Returns true if usr or current user is allowed to view the issue
Chris@0 109 def visible?(usr=nil)
Chris@441 110 (usr || User.current).allowed_to?(:view_issues, self.project) do |role, user|
Chris@441 111 case role.issues_visibility
Chris@441 112 when 'all'
Chris@441 113 true
Chris@441 114 when 'default'
Chris@909 115 !self.is_private? || self.author == user || user.is_or_belongs_to?(assigned_to)
Chris@441 116 when 'own'
Chris@909 117 self.author == user || user.is_or_belongs_to?(assigned_to)
Chris@441 118 else
Chris@441 119 false
Chris@441 120 end
Chris@441 121 end
Chris@0 122 end
Chris@441 123
Chris@0 124 def after_initialize
Chris@0 125 if new_record?
Chris@0 126 # set default values for new records only
Chris@0 127 self.status ||= IssueStatus.default
Chris@0 128 self.priority ||= IssuePriority.default
Chris@0 129 end
Chris@0 130 end
Chris@441 131
Chris@0 132 # Overrides Redmine::Acts::Customizable::InstanceMethods#available_custom_fields
Chris@0 133 def available_custom_fields
Chris@441 134 (project && tracker) ? (project.all_issue_custom_fields & tracker.custom_fields.all) : []
Chris@0 135 end
Chris@441 136
Chris@0 137 def copy_from(arg)
Chris@0 138 issue = arg.is_a?(Issue) ? arg : Issue.visible.find(arg)
Chris@0 139 self.attributes = issue.attributes.dup.except("id", "root_id", "parent_id", "lft", "rgt", "created_on", "updated_on")
Chris@0 140 self.custom_field_values = issue.custom_field_values.inject({}) {|h,v| h[v.custom_field_id] = v.value; h}
Chris@0 141 self.status = issue.status
Chris@0 142 self
Chris@0 143 end
Chris@441 144
Chris@0 145 # Moves/copies an issue to a new project and tracker
Chris@0 146 # Returns the moved/copied issue on success, false on failure
Chris@0 147 def move_to_project(*args)
Chris@0 148 ret = Issue.transaction do
Chris@0 149 move_to_project_without_transaction(*args) || raise(ActiveRecord::Rollback)
Chris@0 150 end || false
Chris@0 151 end
Chris@441 152
Chris@0 153 def move_to_project_without_transaction(new_project, new_tracker = nil, options = {})
Chris@0 154 options ||= {}
Chris@0 155 issue = options[:copy] ? self.class.new.copy_from(self) : self
Chris@441 156
Chris@0 157 if new_project && issue.project_id != new_project.id
Chris@0 158 # delete issue relations
Chris@0 159 unless Setting.cross_project_issue_relations?
Chris@0 160 issue.relations_from.clear
Chris@0 161 issue.relations_to.clear
Chris@0 162 end
Chris@0 163 # issue is moved to another project
Chris@0 164 # reassign to the category with same name if any
Chris@0 165 new_category = issue.category.nil? ? nil : new_project.issue_categories.find_by_name(issue.category.name)
Chris@0 166 issue.category = new_category
Chris@0 167 # Keep the fixed_version if it's still valid in the new_project
Chris@0 168 unless new_project.shared_versions.include?(issue.fixed_version)
Chris@0 169 issue.fixed_version = nil
Chris@0 170 end
Chris@0 171 issue.project = new_project
Chris@0 172 if issue.parent && issue.parent.project_id != issue.project_id
Chris@0 173 issue.parent_issue_id = nil
Chris@0 174 end
Chris@0 175 end
Chris@0 176 if new_tracker
Chris@0 177 issue.tracker = new_tracker
Chris@0 178 issue.reset_custom_values!
Chris@0 179 end
Chris@0 180 if options[:copy]
Chris@441 181 issue.author = User.current
Chris@0 182 issue.custom_field_values = self.custom_field_values.inject({}) {|h,v| h[v.custom_field_id] = v.value; h}
Chris@0 183 issue.status = if options[:attributes] && options[:attributes][:status_id]
Chris@0 184 IssueStatus.find_by_id(options[:attributes][:status_id])
Chris@0 185 else
Chris@0 186 self.status
Chris@0 187 end
Chris@0 188 end
Chris@0 189 # Allow bulk setting of attributes on the issue
Chris@0 190 if options[:attributes]
Chris@0 191 issue.attributes = options[:attributes]
Chris@0 192 end
Chris@0 193 if issue.save
Chris@441 194 if options[:copy]
Chris@441 195 if current_journal && current_journal.notes.present?
Chris@441 196 issue.init_journal(current_journal.user, current_journal.notes)
Chris@441 197 issue.current_journal.notify = false
Chris@441 198 issue.save
Chris@441 199 end
Chris@441 200 else
Chris@0 201 # Manually update project_id on related time entries
Chris@0 202 TimeEntry.update_all("project_id = #{new_project.id}", {:issue_id => id})
Chris@441 203
Chris@0 204 issue.children.each do |child|
Chris@0 205 unless child.move_to_project_without_transaction(new_project)
Chris@0 206 # Move failed and transaction was rollback'd
Chris@0 207 return false
Chris@0 208 end
Chris@0 209 end
Chris@0 210 end
Chris@0 211 else
Chris@0 212 return false
Chris@0 213 end
Chris@0 214 issue
Chris@0 215 end
Chris@0 216
Chris@0 217 def status_id=(sid)
Chris@0 218 self.status = nil
Chris@0 219 write_attribute(:status_id, sid)
Chris@0 220 end
Chris@441 221
Chris@0 222 def priority_id=(pid)
Chris@0 223 self.priority = nil
Chris@0 224 write_attribute(:priority_id, pid)
Chris@0 225 end
Chris@0 226
Chris@0 227 def tracker_id=(tid)
Chris@0 228 self.tracker = nil
Chris@0 229 result = write_attribute(:tracker_id, tid)
Chris@0 230 @custom_field_values = nil
Chris@0 231 result
Chris@0 232 end
Chris@909 233
Chris@507 234 def description=(arg)
Chris@507 235 if arg.is_a?(String)
Chris@507 236 arg = arg.gsub(/(\r\n|\n|\r)/, "\r\n")
Chris@507 237 end
Chris@507 238 write_attribute(:description, arg)
Chris@507 239 end
Chris@441 240
Chris@0 241 # Overrides attributes= so that tracker_id gets assigned first
Chris@0 242 def attributes_with_tracker_first=(new_attributes, *args)
Chris@0 243 return if new_attributes.nil?
Chris@0 244 new_tracker_id = new_attributes['tracker_id'] || new_attributes[:tracker_id]
Chris@0 245 if new_tracker_id
Chris@0 246 self.tracker_id = new_tracker_id
Chris@0 247 end
Chris@0 248 send :attributes_without_tracker_first=, new_attributes, *args
Chris@0 249 end
Chris@0 250 # Do not redefine alias chain on reload (see #4838)
Chris@0 251 alias_method_chain(:attributes=, :tracker_first) unless method_defined?(:attributes_without_tracker_first=)
Chris@441 252
Chris@0 253 def estimated_hours=(h)
Chris@0 254 write_attribute :estimated_hours, (h.is_a?(String) ? h.to_hours : h)
Chris@0 255 end
Chris@441 256
Chris@117 257 safe_attributes 'tracker_id',
Chris@117 258 'status_id',
Chris@117 259 'parent_issue_id',
Chris@117 260 'category_id',
Chris@117 261 'assigned_to_id',
Chris@117 262 'priority_id',
Chris@117 263 'fixed_version_id',
Chris@117 264 'subject',
Chris@117 265 'description',
Chris@117 266 'start_date',
Chris@117 267 'due_date',
Chris@117 268 'done_ratio',
Chris@117 269 'estimated_hours',
Chris@117 270 'custom_field_values',
Chris@117 271 'custom_fields',
Chris@117 272 'lock_version',
Chris@117 273 :if => lambda {|issue, user| issue.new_record? || user.allowed_to?(:edit_issues, issue.project) }
Chris@441 274
Chris@117 275 safe_attributes 'status_id',
Chris@117 276 'assigned_to_id',
Chris@117 277 'fixed_version_id',
Chris@117 278 'done_ratio',
Chris@117 279 :if => lambda {|issue, user| issue.new_statuses_allowed_to(user).any? }
chris@37 280
Chris@441 281 safe_attributes 'is_private',
Chris@441 282 :if => lambda {|issue, user|
Chris@441 283 user.allowed_to?(:set_issues_private, issue.project) ||
Chris@441 284 (issue.author == user && user.allowed_to?(:set_own_issues_private, issue.project))
Chris@441 285 }
Chris@441 286
Chris@0 287 # Safely sets attributes
Chris@0 288 # Should be called from controllers instead of #attributes=
Chris@0 289 # attr_accessible is too rough because we still want things like
Chris@0 290 # Issue.new(:project => foo) to work
Chris@0 291 # TODO: move workflow/permission checks from controllers to here
Chris@0 292 def safe_attributes=(attrs, user=User.current)
chris@37 293 return unless attrs.is_a?(Hash)
Chris@441 294
chris@37 295 # User can change issue attributes only if he has :edit permission or if a workflow transition is allowed
Chris@117 296 attrs = delete_unsafe_attributes(attrs, user)
Chris@441 297 return if attrs.empty?
Chris@441 298
chris@37 299 # Tracker must be set before since new_statuses_allowed_to depends on it.
chris@37 300 if t = attrs.delete('tracker_id')
chris@37 301 self.tracker_id = t
chris@37 302 end
Chris@441 303
Chris@0 304 if attrs['status_id']
Chris@0 305 unless new_statuses_allowed_to(user).collect(&:id).include?(attrs['status_id'].to_i)
Chris@0 306 attrs.delete('status_id')
Chris@0 307 end
Chris@0 308 end
Chris@441 309
Chris@0 310 unless leaf?
Chris@0 311 attrs.reject! {|k,v| %w(priority_id done_ratio start_date due_date estimated_hours).include?(k)}
Chris@0 312 end
Chris@441 313
Chris@0 314 if attrs.has_key?('parent_issue_id')
Chris@0 315 if !user.allowed_to?(:manage_subtasks, project)
Chris@0 316 attrs.delete('parent_issue_id')
Chris@0 317 elsif !attrs['parent_issue_id'].blank?
Chris@117 318 attrs.delete('parent_issue_id') unless Issue.visible(user).exists?(attrs['parent_issue_id'].to_i)
Chris@0 319 end
Chris@0 320 end
Chris@441 321
Chris@0 322 self.attributes = attrs
Chris@0 323 end
Chris@441 324
Chris@0 325 def done_ratio
chris@37 326 if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
Chris@0 327 status.default_done_ratio
Chris@0 328 else
Chris@0 329 read_attribute(:done_ratio)
Chris@0 330 end
Chris@0 331 end
Chris@0 332
Chris@0 333 def self.use_status_for_done_ratio?
Chris@0 334 Setting.issue_done_ratio == 'issue_status'
Chris@0 335 end
Chris@0 336
Chris@0 337 def self.use_field_for_done_ratio?
Chris@0 338 Setting.issue_done_ratio == 'issue_field'
Chris@0 339 end
Chris@441 340
Chris@909 341 def validate_issue
Chris@0 342 if self.due_date.nil? && @attributes['due_date'] && !@attributes['due_date'].empty?
Chris@0 343 errors.add :due_date, :not_a_date
Chris@0 344 end
Chris@441 345
Chris@0 346 if self.due_date and self.start_date and self.due_date < self.start_date
Chris@0 347 errors.add :due_date, :greater_than_start_date
Chris@0 348 end
Chris@441 349
Chris@0 350 if start_date && soonest_start && start_date < soonest_start
Chris@0 351 errors.add :start_date, :invalid
Chris@0 352 end
Chris@441 353
Chris@0 354 if fixed_version
Chris@0 355 if !assignable_versions.include?(fixed_version)
Chris@0 356 errors.add :fixed_version_id, :inclusion
Chris@0 357 elsif reopened? && fixed_version.closed?
Chris@909 358 errors.add :base, I18n.t(:error_can_not_reopen_issue_on_closed_version)
Chris@0 359 end
Chris@0 360 end
Chris@441 361
Chris@0 362 # Checks that the issue can not be added/moved to a disabled tracker
Chris@0 363 if project && (tracker_id_changed? || project_id_changed?)
Chris@0 364 unless project.trackers.include?(tracker)
Chris@0 365 errors.add :tracker_id, :inclusion
Chris@0 366 end
Chris@0 367 end
Chris@441 368
Chris@0 369 # Checks parent issue assignment
Chris@0 370 if @parent_issue
Chris@0 371 if @parent_issue.project_id != project_id
Chris@0 372 errors.add :parent_issue_id, :not_same_project
Chris@0 373 elsif !new_record?
Chris@0 374 # moving an existing issue
Chris@0 375 if @parent_issue.root_id != root_id
Chris@0 376 # we can always move to another tree
Chris@0 377 elsif move_possible?(@parent_issue)
Chris@0 378 # move accepted inside tree
Chris@0 379 else
Chris@0 380 errors.add :parent_issue_id, :not_a_valid_parent
Chris@0 381 end
Chris@0 382 end
Chris@0 383 end
Chris@0 384 end
Chris@441 385
Chris@0 386 # Set the done_ratio using the status if that setting is set. This will keep the done_ratios
Chris@0 387 # even if the user turns off the setting later
Chris@0 388 def update_done_ratio_from_issue_status
chris@37 389 if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
Chris@0 390 self.done_ratio = status.default_done_ratio
Chris@0 391 end
Chris@0 392 end
Chris@441 393
Chris@0 394 def init_journal(user, notes = "")
Chris@0 395 @current_journal ||= Journal.new(:journalized => self, :user => user, :notes => notes)
Chris@0 396 @issue_before_change = self.clone
Chris@0 397 @issue_before_change.status = self.status
Chris@0 398 @custom_values_before_change = {}
Chris@0 399 self.custom_values.each {|c| @custom_values_before_change.store c.custom_field_id, c.value }
Chris@0 400 # Make sure updated_on is updated when adding a note.
Chris@0 401 updated_on_will_change!
Chris@0 402 @current_journal
Chris@0 403 end
Chris@441 404
Chris@0 405 # Return true if the issue is closed, otherwise false
Chris@0 406 def closed?
Chris@0 407 self.status.is_closed?
Chris@0 408 end
Chris@441 409
Chris@0 410 # Return true if the issue is being reopened
Chris@0 411 def reopened?
Chris@0 412 if !new_record? && status_id_changed?
Chris@0 413 status_was = IssueStatus.find_by_id(status_id_was)
Chris@0 414 status_new = IssueStatus.find_by_id(status_id)
Chris@0 415 if status_was && status_new && status_was.is_closed? && !status_new.is_closed?
Chris@0 416 return true
Chris@0 417 end
Chris@0 418 end
Chris@0 419 false
Chris@0 420 end
Chris@0 421
Chris@0 422 # Return true if the issue is being closed
Chris@0 423 def closing?
Chris@0 424 if !new_record? && status_id_changed?
Chris@0 425 status_was = IssueStatus.find_by_id(status_id_was)
Chris@0 426 status_new = IssueStatus.find_by_id(status_id)
Chris@0 427 if status_was && status_new && !status_was.is_closed? && status_new.is_closed?
Chris@0 428 return true
Chris@0 429 end
Chris@0 430 end
Chris@0 431 false
Chris@0 432 end
Chris@441 433
Chris@0 434 # Returns true if the issue is overdue
Chris@0 435 def overdue?
Chris@0 436 !due_date.nil? && (due_date < Date.today) && !status.is_closed?
Chris@0 437 end
chris@22 438
chris@22 439 # Is the amount of work done less than it should for the due date
chris@22 440 def behind_schedule?
chris@22 441 return false if start_date.nil? || due_date.nil?
chris@22 442 done_date = start_date + ((due_date - start_date+1)* done_ratio/100).floor
chris@22 443 return done_date <= Date.today
chris@22 444 end
chris@22 445
chris@22 446 # Does this issue have children?
chris@22 447 def children?
chris@22 448 !leaf?
chris@22 449 end
Chris@441 450
Chris@0 451 # Users the issue can be assigned to
Chris@0 452 def assignable_users
chris@37 453 users = project.assignable_users
chris@37 454 users << author if author
Chris@909 455 users << assigned_to if assigned_to
chris@37 456 users.uniq.sort
Chris@0 457 end
Chris@441 458
Chris@0 459 # Versions that the issue can be assigned to
Chris@0 460 def assignable_versions
Chris@0 461 @assignable_versions ||= (project.shared_versions.open + [Version.find_by_id(fixed_version_id_was)]).compact.uniq.sort
Chris@0 462 end
Chris@441 463
Chris@0 464 # Returns true if this issue is blocked by another issue that is still open
Chris@0 465 def blocked?
Chris@0 466 !relations_to.detect {|ir| ir.relation_type == 'blocks' && !ir.issue_from.closed?}.nil?
Chris@0 467 end
Chris@441 468
Chris@0 469 # Returns an array of status that user is able to apply
Chris@0 470 def new_statuses_allowed_to(user, include_default=false)
Chris@245 471 statuses = status.find_new_statuses_allowed_to(
Chris@245 472 user.roles_for_project(project),
Chris@245 473 tracker,
Chris@245 474 author == user,
Chris@245 475 assigned_to_id_changed? ? assigned_to_id_was == user.id : assigned_to_id == user.id
Chris@245 476 )
Chris@0 477 statuses << status unless statuses.empty?
Chris@0 478 statuses << IssueStatus.default if include_default
Chris@0 479 statuses = statuses.uniq.sort
Chris@0 480 blocked? ? statuses.reject {|s| s.is_closed?} : statuses
Chris@0 481 end
Chris@441 482
Chris@0 483 # Returns the mail adresses of users that should be notified
Chris@0 484 def recipients
Chris@0 485 notified = project.notified_users
chris@37 486 # Author and assignee are always notified unless they have been
chris@37 487 # locked or don't want to be notified
chris@37 488 notified << author if author && author.active? && author.notify_about?(self)
Chris@909 489 if assigned_to
Chris@909 490 if assigned_to.is_a?(Group)
Chris@909 491 notified += assigned_to.users.select {|u| u.active? && u.notify_about?(self)}
Chris@909 492 else
Chris@909 493 notified << assigned_to if assigned_to.active? && assigned_to.notify_about?(self)
Chris@909 494 end
Chris@909 495 end
Chris@0 496 notified.uniq!
Chris@0 497 # Remove users that can not view the issue
Chris@0 498 notified.reject! {|user| !visible?(user)}
Chris@0 499 notified.collect(&:mail)
Chris@0 500 end
Chris@441 501
Chris@0 502 # Returns the total number of hours spent on this issue and its descendants
Chris@0 503 #
Chris@0 504 # Example:
Chris@0 505 # spent_hours => 0.0
Chris@0 506 # spent_hours => 50.2
Chris@0 507 def spent_hours
Chris@0 508 @spent_hours ||= self_and_descendants.sum("#{TimeEntry.table_name}.hours", :include => :time_entries).to_f || 0.0
Chris@0 509 end
Chris@441 510
Chris@0 511 def relations
Chris@909 512 @relations ||= (relations_from + relations_to).sort
Chris@909 513 end
Chris@909 514
Chris@909 515 # Preloads relations for a collection of issues
Chris@909 516 def self.load_relations(issues)
Chris@909 517 if issues.any?
Chris@909 518 relations = IssueRelation.all(:conditions => ["issue_from_id IN (:ids) OR issue_to_id IN (:ids)", {:ids => issues.map(&:id)}])
Chris@909 519 issues.each do |issue|
Chris@909 520 issue.instance_variable_set "@relations", relations.select {|r| r.issue_from_id == issue.id || r.issue_to_id == issue.id}
Chris@909 521 end
Chris@909 522 end
Chris@909 523 end
Chris@909 524
Chris@909 525 # Finds an issue relation given its id.
Chris@909 526 def find_relation(relation_id)
Chris@909 527 IssueRelation.find(relation_id, :conditions => ["issue_to_id = ? OR issue_from_id = ?", id, id])
Chris@0 528 end
Chris@441 529
Chris@441 530 def all_dependent_issues(except=[])
Chris@441 531 except << self
Chris@0 532 dependencies = []
Chris@0 533 relations_from.each do |relation|
Chris@441 534 if relation.issue_to && !except.include?(relation.issue_to)
Chris@128 535 dependencies << relation.issue_to
Chris@128 536 dependencies += relation.issue_to.all_dependent_issues(except)
Chris@128 537 end
Chris@0 538 end
Chris@0 539 dependencies
Chris@0 540 end
Chris@441 541
Chris@0 542 # Returns an array of issues that duplicate this one
Chris@0 543 def duplicates
Chris@0 544 relations_to.select {|r| r.relation_type == IssueRelation::TYPE_DUPLICATES}.collect {|r| r.issue_from}
Chris@0 545 end
Chris@441 546
Chris@0 547 # Returns the due date or the target due date if any
Chris@0 548 # Used on gantt chart
Chris@0 549 def due_before
Chris@0 550 due_date || (fixed_version ? fixed_version.effective_date : nil)
Chris@0 551 end
Chris@441 552
Chris@0 553 # Returns the time scheduled for this issue.
Chris@441 554 #
Chris@0 555 # Example:
Chris@0 556 # Start Date: 2/26/09, End Date: 3/04/09
Chris@0 557 # duration => 6
Chris@0 558 def duration
Chris@0 559 (start_date && due_date) ? due_date - start_date : 0
Chris@0 560 end
Chris@441 561
Chris@0 562 def soonest_start
Chris@0 563 @soonest_start ||= (
Chris@0 564 relations_to.collect{|relation| relation.successor_soonest_start} +
Chris@0 565 ancestors.collect(&:soonest_start)
Chris@0 566 ).compact.max
Chris@0 567 end
Chris@441 568
Chris@0 569 def reschedule_after(date)
Chris@0 570 return if date.nil?
Chris@0 571 if leaf?
Chris@0 572 if start_date.nil? || start_date < date
Chris@0 573 self.start_date, self.due_date = date, date + duration
Chris@0 574 save
Chris@0 575 end
Chris@0 576 else
Chris@0 577 leaves.each do |leaf|
Chris@0 578 leaf.reschedule_after(date)
Chris@0 579 end
Chris@0 580 end
Chris@0 581 end
Chris@441 582
Chris@0 583 def <=>(issue)
Chris@0 584 if issue.nil?
Chris@0 585 -1
Chris@0 586 elsif root_id != issue.root_id
Chris@0 587 (root_id || 0) <=> (issue.root_id || 0)
Chris@0 588 else
Chris@0 589 (lft || 0) <=> (issue.lft || 0)
Chris@0 590 end
Chris@0 591 end
Chris@441 592
Chris@0 593 def to_s
Chris@0 594 "#{tracker} ##{id}: #{subject}"
Chris@0 595 end
Chris@441 596
Chris@0 597 # Returns a string of css classes that apply to the issue
Chris@0 598 def css_classes
Chris@112 599 s = "issue status-#{status.position} "
Chris@112 600 s << "priority-#{priority.position}"
Chris@0 601 s << ' closed' if closed?
Chris@0 602 s << ' overdue' if overdue?
Chris@441 603 s << ' child' if child?
Chris@441 604 s << ' parent' unless leaf?
Chris@441 605 s << ' private' if is_private?
Chris@0 606 s << ' created-by-me' if User.current.logged? && author_id == User.current.id
Chris@0 607 s << ' assigned-to-me' if User.current.logged? && assigned_to_id == User.current.id
Chris@0 608 s
Chris@0 609 end
Chris@0 610
Chris@0 611 # Saves an issue, time_entry, attachments, and a journal from the parameters
Chris@0 612 # Returns false if save fails
Chris@0 613 def save_issue_with_child_records(params, existing_time_entry=nil)
Chris@0 614 Issue.transaction do
Chris@441 615 if params[:time_entry] && (params[:time_entry][:hours].present? || params[:time_entry][:comments].present?) && User.current.allowed_to?(:log_time, project)
Chris@0 616 @time_entry = existing_time_entry || TimeEntry.new
Chris@0 617 @time_entry.project = project
Chris@0 618 @time_entry.issue = self
Chris@0 619 @time_entry.user = User.current
Chris@909 620 @time_entry.spent_on = User.current.today
Chris@0 621 @time_entry.attributes = params[:time_entry]
Chris@0 622 self.time_entries << @time_entry
Chris@0 623 end
Chris@441 624
Chris@0 625 if valid?
Chris@0 626 attachments = Attachment.attach_files(self, params[:attachments])
Chris@0 627 # TODO: Rename hook
Chris@0 628 Redmine::Hook.call_hook(:controller_issues_edit_before_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
Chris@0 629 begin
Chris@0 630 if save
Chris@0 631 # TODO: Rename hook
Chris@0 632 Redmine::Hook.call_hook(:controller_issues_edit_after_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
Chris@0 633 else
Chris@0 634 raise ActiveRecord::Rollback
Chris@0 635 end
Chris@0 636 rescue ActiveRecord::StaleObjectError
Chris@0 637 attachments[:files].each(&:destroy)
Chris@909 638 errors.add :base, l(:notice_locking_conflict)
Chris@0 639 raise ActiveRecord::Rollback
Chris@0 640 end
Chris@0 641 end
Chris@0 642 end
Chris@0 643 end
Chris@0 644
Chris@0 645 # Unassigns issues from +version+ if it's no longer shared with issue's project
Chris@0 646 def self.update_versions_from_sharing_change(version)
Chris@0 647 # Update issues assigned to the version
Chris@0 648 update_versions(["#{Issue.table_name}.fixed_version_id = ?", version.id])
Chris@0 649 end
Chris@441 650
Chris@0 651 # Unassigns issues from versions that are no longer shared
Chris@0 652 # after +project+ was moved
Chris@0 653 def self.update_versions_from_hierarchy_change(project)
Chris@0 654 moved_project_ids = project.self_and_descendants.reload.collect(&:id)
Chris@0 655 # Update issues of the moved projects and issues assigned to a version of a moved project
Chris@0 656 Issue.update_versions(["#{Version.table_name}.project_id IN (?) OR #{Issue.table_name}.project_id IN (?)", moved_project_ids, moved_project_ids])
Chris@0 657 end
Chris@0 658
Chris@0 659 def parent_issue_id=(arg)
Chris@0 660 parent_issue_id = arg.blank? ? nil : arg.to_i
Chris@0 661 if parent_issue_id && @parent_issue = Issue.find_by_id(parent_issue_id)
Chris@0 662 @parent_issue.id
Chris@0 663 else
Chris@0 664 @parent_issue = nil
Chris@0 665 nil
Chris@0 666 end
Chris@0 667 end
Chris@441 668
Chris@0 669 def parent_issue_id
Chris@0 670 if instance_variable_defined? :@parent_issue
Chris@0 671 @parent_issue.nil? ? nil : @parent_issue.id
Chris@0 672 else
Chris@0 673 parent_id
Chris@0 674 end
Chris@0 675 end
Chris@0 676
Chris@0 677 # Extracted from the ReportsController.
Chris@0 678 def self.by_tracker(project)
Chris@0 679 count_and_group_by(:project => project,
Chris@0 680 :field => 'tracker_id',
Chris@0 681 :joins => Tracker.table_name)
Chris@0 682 end
Chris@0 683
Chris@0 684 def self.by_version(project)
Chris@0 685 count_and_group_by(:project => project,
Chris@0 686 :field => 'fixed_version_id',
Chris@0 687 :joins => Version.table_name)
Chris@0 688 end
Chris@0 689
Chris@0 690 def self.by_priority(project)
Chris@0 691 count_and_group_by(:project => project,
Chris@0 692 :field => 'priority_id',
Chris@0 693 :joins => IssuePriority.table_name)
Chris@0 694 end
Chris@0 695
Chris@0 696 def self.by_category(project)
Chris@0 697 count_and_group_by(:project => project,
Chris@0 698 :field => 'category_id',
Chris@0 699 :joins => IssueCategory.table_name)
Chris@0 700 end
Chris@0 701
Chris@0 702 def self.by_assigned_to(project)
Chris@0 703 count_and_group_by(:project => project,
Chris@0 704 :field => 'assigned_to_id',
Chris@0 705 :joins => User.table_name)
Chris@0 706 end
Chris@0 707
Chris@0 708 def self.by_author(project)
Chris@0 709 count_and_group_by(:project => project,
Chris@0 710 :field => 'author_id',
Chris@0 711 :joins => User.table_name)
Chris@0 712 end
Chris@0 713
Chris@0 714 def self.by_subproject(project)
Chris@0 715 ActiveRecord::Base.connection.select_all("select s.id as status_id,
Chris@0 716 s.is_closed as closed,
Chris@441 717 #{Issue.table_name}.project_id as project_id,
Chris@441 718 count(#{Issue.table_name}.id) as total
Chris@0 719 from
Chris@441 720 #{Issue.table_name}, #{Project.table_name}, #{IssueStatus.table_name} s
Chris@0 721 where
Chris@441 722 #{Issue.table_name}.status_id=s.id
Chris@441 723 and #{Issue.table_name}.project_id = #{Project.table_name}.id
Chris@441 724 and #{visible_condition(User.current, :project => project, :with_subprojects => true)}
Chris@441 725 and #{Issue.table_name}.project_id <> #{project.id}
Chris@441 726 group by s.id, s.is_closed, #{Issue.table_name}.project_id") if project.descendants.active.any?
Chris@0 727 end
Chris@0 728 # End ReportsController extraction
Chris@441 729
Chris@0 730 # Returns an array of projects that current user can move issues to
Chris@0 731 def self.allowed_target_projects_on_move
Chris@0 732 projects = []
Chris@0 733 if User.current.admin?
Chris@0 734 # admin is allowed to move issues to any active (visible) project
Chris@0 735 projects = Project.visible.all
Chris@0 736 elsif User.current.logged?
Chris@0 737 if Role.non_member.allowed_to?(:move_issues)
Chris@0 738 projects = Project.visible.all
Chris@0 739 else
Chris@0 740 User.current.memberships.each {|m| projects << m.project if m.roles.detect {|r| r.allowed_to?(:move_issues)}}
Chris@0 741 end
Chris@0 742 end
Chris@0 743 projects
Chris@0 744 end
Chris@441 745
Chris@0 746 private
Chris@441 747
Chris@0 748 def update_nested_set_attributes
Chris@0 749 if root_id.nil?
Chris@0 750 # issue was just created
Chris@0 751 self.root_id = (@parent_issue.nil? ? id : @parent_issue.root_id)
Chris@0 752 set_default_left_and_right
Chris@0 753 Issue.update_all("root_id = #{root_id}, lft = #{lft}, rgt = #{rgt}", ["id = ?", id])
Chris@0 754 if @parent_issue
Chris@0 755 move_to_child_of(@parent_issue)
Chris@0 756 end
Chris@0 757 reload
Chris@0 758 elsif parent_issue_id != parent_id
Chris@0 759 former_parent_id = parent_id
Chris@0 760 # moving an existing issue
Chris@0 761 if @parent_issue && @parent_issue.root_id == root_id
Chris@0 762 # inside the same tree
Chris@0 763 move_to_child_of(@parent_issue)
Chris@0 764 else
Chris@0 765 # to another tree
Chris@0 766 unless root?
Chris@0 767 move_to_right_of(root)
Chris@0 768 reload
Chris@0 769 end
Chris@0 770 old_root_id = root_id
Chris@0 771 self.root_id = (@parent_issue.nil? ? id : @parent_issue.root_id )
Chris@0 772 target_maxright = nested_set_scope.maximum(right_column_name) || 0
Chris@0 773 offset = target_maxright + 1 - lft
Chris@0 774 Issue.update_all("root_id = #{root_id}, lft = lft + #{offset}, rgt = rgt + #{offset}",
Chris@0 775 ["root_id = ? AND lft >= ? AND rgt <= ? ", old_root_id, lft, rgt])
Chris@0 776 self[left_column_name] = lft + offset
Chris@0 777 self[right_column_name] = rgt + offset
Chris@0 778 if @parent_issue
Chris@0 779 move_to_child_of(@parent_issue)
Chris@0 780 end
Chris@0 781 end
Chris@0 782 reload
Chris@0 783 # delete invalid relations of all descendants
Chris@0 784 self_and_descendants.each do |issue|
Chris@0 785 issue.relations.each do |relation|
Chris@0 786 relation.destroy unless relation.valid?
Chris@0 787 end
Chris@0 788 end
Chris@0 789 # update former parent
Chris@0 790 recalculate_attributes_for(former_parent_id) if former_parent_id
Chris@0 791 end
Chris@0 792 remove_instance_variable(:@parent_issue) if instance_variable_defined?(:@parent_issue)
Chris@0 793 end
Chris@441 794
Chris@0 795 def update_parent_attributes
Chris@0 796 recalculate_attributes_for(parent_id) if parent_id
Chris@0 797 end
Chris@0 798
Chris@0 799 def recalculate_attributes_for(issue_id)
Chris@0 800 if issue_id && p = Issue.find_by_id(issue_id)
Chris@0 801 # priority = highest priority of children
Chris@0 802 if priority_position = p.children.maximum("#{IssuePriority.table_name}.position", :include => :priority)
Chris@0 803 p.priority = IssuePriority.find_by_position(priority_position)
Chris@0 804 end
Chris@441 805
Chris@0 806 # start/due dates = lowest/highest dates of children
Chris@0 807 p.start_date = p.children.minimum(:start_date)
Chris@0 808 p.due_date = p.children.maximum(:due_date)
Chris@0 809 if p.start_date && p.due_date && p.due_date < p.start_date
Chris@0 810 p.start_date, p.due_date = p.due_date, p.start_date
Chris@0 811 end
Chris@441 812
Chris@0 813 # done ratio = weighted average ratio of leaves
chris@37 814 unless Issue.use_status_for_done_ratio? && p.status && p.status.default_done_ratio
Chris@0 815 leaves_count = p.leaves.count
Chris@0 816 if leaves_count > 0
Chris@0 817 average = p.leaves.average(:estimated_hours).to_f
Chris@0 818 if average == 0
Chris@0 819 average = 1
Chris@0 820 end
Chris@0 821 done = p.leaves.sum("COALESCE(estimated_hours, #{average}) * (CASE WHEN is_closed = #{connection.quoted_true} THEN 100 ELSE COALESCE(done_ratio, 0) END)", :include => :status).to_f
Chris@0 822 progress = done / (average * leaves_count)
Chris@0 823 p.done_ratio = progress.round
Chris@0 824 end
Chris@0 825 end
Chris@441 826
Chris@0 827 # estimate = sum of leaves estimates
Chris@0 828 p.estimated_hours = p.leaves.sum(:estimated_hours).to_f
Chris@0 829 p.estimated_hours = nil if p.estimated_hours == 0.0
Chris@441 830
Chris@0 831 # ancestors will be recursively updated
Chris@0 832 p.save(false)
Chris@0 833 end
Chris@0 834 end
Chris@441 835
Chris@0 836 # Update issues so their versions are not pointing to a
Chris@0 837 # fixed_version that is not shared with the issue's project
Chris@0 838 def self.update_versions(conditions=nil)
Chris@0 839 # Only need to update issues with a fixed_version from
Chris@0 840 # a different project and that is not systemwide shared
Chris@0 841 Issue.all(:conditions => merge_conditions("#{Issue.table_name}.fixed_version_id IS NOT NULL" +
Chris@0 842 " AND #{Issue.table_name}.project_id <> #{Version.table_name}.project_id" +
Chris@0 843 " AND #{Version.table_name}.sharing <> 'system'",
Chris@0 844 conditions),
Chris@0 845 :include => [:project, :fixed_version]
Chris@0 846 ).each do |issue|
Chris@0 847 next if issue.project.nil? || issue.fixed_version.nil?
Chris@0 848 unless issue.project.shared_versions.include?(issue.fixed_version)
Chris@0 849 issue.init_journal(User.current)
Chris@0 850 issue.fixed_version = nil
Chris@0 851 issue.save
Chris@0 852 end
Chris@0 853 end
Chris@0 854 end
Chris@441 855
Chris@0 856 # Callback on attachment deletion
Chris@909 857 def attachment_added(obj)
Chris@909 858 if @current_journal && !obj.new_record?
Chris@909 859 @current_journal.details << JournalDetail.new(:property => 'attachment', :prop_key => obj.id, :value => obj.filename)
Chris@909 860 end
Chris@909 861 end
Chris@909 862
Chris@909 863 # Callback on attachment deletion
Chris@0 864 def attachment_removed(obj)
Chris@0 865 journal = init_journal(User.current)
Chris@0 866 journal.details << JournalDetail.new(:property => 'attachment',
Chris@0 867 :prop_key => obj.id,
Chris@0 868 :old_value => obj.filename)
Chris@0 869 journal.save
Chris@0 870 end
Chris@441 871
Chris@0 872 # Default assignment based on category
Chris@0 873 def default_assign
Chris@0 874 if assigned_to.nil? && category && category.assigned_to
Chris@0 875 self.assigned_to = category.assigned_to
Chris@0 876 end
Chris@0 877 end
Chris@0 878
Chris@0 879 # Updates start/due dates of following issues
Chris@0 880 def reschedule_following_issues
Chris@0 881 if start_date_changed? || due_date_changed?
Chris@0 882 relations_from.each do |relation|
Chris@0 883 relation.set_issue_to_dates
Chris@0 884 end
Chris@0 885 end
Chris@0 886 end
Chris@0 887
Chris@0 888 # Closes duplicates if the issue is being closed
Chris@0 889 def close_duplicates
Chris@0 890 if closing?
Chris@0 891 duplicates.each do |duplicate|
Chris@0 892 # Reload is need in case the duplicate was updated by a previous duplicate
Chris@0 893 duplicate.reload
Chris@0 894 # Don't re-close it if it's already closed
Chris@0 895 next if duplicate.closed?
Chris@0 896 # Same user and notes
Chris@0 897 if @current_journal
Chris@0 898 duplicate.init_journal(@current_journal.user, @current_journal.notes)
Chris@0 899 end
Chris@0 900 duplicate.update_attribute :status, self.status
Chris@0 901 end
Chris@0 902 end
Chris@0 903 end
Chris@441 904
Chris@0 905 # Saves the changes in a Journal
Chris@0 906 # Called after_save
Chris@0 907 def create_journal
Chris@0 908 if @current_journal
Chris@0 909 # attributes changes
Chris@245 910 (Issue.column_names - %w(id root_id lft rgt lock_version created_on updated_on)).each {|c|
Chris@507 911 before = @issue_before_change.send(c)
Chris@507 912 after = send(c)
Chris@507 913 next if before == after || (before.blank? && after.blank?)
Chris@0 914 @current_journal.details << JournalDetail.new(:property => 'attr',
Chris@0 915 :prop_key => c,
Chris@0 916 :old_value => @issue_before_change.send(c),
Chris@507 917 :value => send(c))
Chris@0 918 }
Chris@0 919 # custom fields changes
Chris@0 920 custom_values.each {|c|
Chris@0 921 next if (@custom_values_before_change[c.custom_field_id]==c.value ||
Chris@0 922 (@custom_values_before_change[c.custom_field_id].blank? && c.value.blank?))
Chris@441 923 @current_journal.details << JournalDetail.new(:property => 'cf',
Chris@0 924 :prop_key => c.custom_field_id,
Chris@0 925 :old_value => @custom_values_before_change[c.custom_field_id],
Chris@0 926 :value => c.value)
Chris@441 927 }
Chris@0 928 @current_journal.save
Chris@0 929 # reset current journal
Chris@0 930 init_journal @current_journal.user, @current_journal.notes
Chris@0 931 end
Chris@0 932 end
Chris@0 933
Chris@0 934 # Query generator for selecting groups of issue counts for a project
Chris@0 935 # based on specific criteria
Chris@0 936 #
Chris@0 937 # Options
Chris@0 938 # * project - Project to search in.
Chris@0 939 # * field - String. Issue field to key off of in the grouping.
Chris@0 940 # * joins - String. The table name to join against.
Chris@0 941 def self.count_and_group_by(options)
Chris@0 942 project = options.delete(:project)
Chris@0 943 select_field = options.delete(:field)
Chris@0 944 joins = options.delete(:joins)
Chris@0 945
Chris@441 946 where = "#{Issue.table_name}.#{select_field}=j.id"
Chris@441 947
Chris@0 948 ActiveRecord::Base.connection.select_all("select s.id as status_id,
Chris@0 949 s.is_closed as closed,
Chris@0 950 j.id as #{select_field},
Chris@441 951 count(#{Issue.table_name}.id) as total
Chris@0 952 from
Chris@441 953 #{Issue.table_name}, #{Project.table_name}, #{IssueStatus.table_name} s, #{joins} j
Chris@0 954 where
Chris@441 955 #{Issue.table_name}.status_id=s.id
Chris@0 956 and #{where}
Chris@441 957 and #{Issue.table_name}.project_id=#{Project.table_name}.id
Chris@441 958 and #{visible_condition(User.current, :project => project)}
Chris@0 959 group by s.id, s.is_closed, j.id")
Chris@0 960 end
Chris@0 961 end