annotate app/models/issue.rb @ 1459:cf78a7ade302 luisf

Merge from branch "bug_794"
author luisf <luis.figueira@eecs.qmul.ac.uk>
date Mon, 11 Nov 2013 18:25:50 +0000
parents 0a574315af3e
children 4f746d8966dd fb9a13467253
rev   line source
Chris@245 1 # Redmine - project management software
Chris@1115 2 # Copyright (C) 2006-2012 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@1115 20 include Redmine::Utils::DateCalculation
Chris@441 21
Chris@0 22 belongs_to :project
Chris@0 23 belongs_to :tracker
Chris@0 24 belongs_to :status, :class_name => 'IssueStatus', :foreign_key => 'status_id'
Chris@0 25 belongs_to :author, :class_name => 'User', :foreign_key => 'author_id'
Chris@909 26 belongs_to :assigned_to, :class_name => 'Principal', :foreign_key => 'assigned_to_id'
Chris@0 27 belongs_to :fixed_version, :class_name => 'Version', :foreign_key => 'fixed_version_id'
Chris@0 28 belongs_to :priority, :class_name => 'IssuePriority', :foreign_key => 'priority_id'
Chris@0 29 belongs_to :category, :class_name => 'IssueCategory', :foreign_key => 'category_id'
Chris@0 30
Chris@0 31 has_many :journals, :as => :journalized, :dependent => :destroy
Chris@1115 32 has_many :visible_journals,
Chris@1115 33 :class_name => 'Journal',
Chris@1115 34 :as => :journalized,
Chris@1115 35 :conditions => Proc.new {
Chris@1115 36 ["(#{Journal.table_name}.private_notes = ? OR (#{Project.allowed_to_condition(User.current, :view_private_notes)}))", false]
Chris@1115 37 },
Chris@1115 38 :readonly => true
Chris@1115 39
Chris@0 40 has_many :time_entries, :dependent => :delete_all
Chris@0 41 has_and_belongs_to_many :changesets, :order => "#{Changeset.table_name}.committed_on ASC, #{Changeset.table_name}.id ASC"
Chris@441 42
Chris@0 43 has_many :relations_from, :class_name => 'IssueRelation', :foreign_key => 'issue_from_id', :dependent => :delete_all
Chris@0 44 has_many :relations_to, :class_name => 'IssueRelation', :foreign_key => 'issue_to_id', :dependent => :delete_all
Chris@441 45
Chris@210 46 acts_as_nested_set :scope => 'root_id', :dependent => :destroy
Chris@909 47 acts_as_attachable :after_add => :attachment_added, :after_remove => :attachment_removed
Chris@0 48 acts_as_customizable
Chris@0 49 acts_as_watchable
Chris@0 50 acts_as_searchable :columns => ['subject', "#{table_name}.description", "#{Journal.table_name}.notes"],
Chris@1115 51 :include => [:project, :visible_journals],
Chris@0 52 # sort by id so that limited eager loading doesn't break with postgresql
Chris@0 53 :order_column => "#{table_name}.id"
Chris@0 54 acts_as_event :title => Proc.new {|o| "#{o.tracker.name} ##{o.id} (#{o.status}): #{o.subject}"},
Chris@0 55 :url => Proc.new {|o| {:controller => 'issues', :action => 'show', :id => o.id}},
Chris@0 56 :type => Proc.new {|o| 'issue' + (o.closed? ? ' closed' : '') }
Chris@441 57
Chris@0 58 acts_as_activity_provider :find_options => {:include => [:project, :author, :tracker]},
Chris@0 59 :author_key => :author_id
Chris@0 60
Chris@0 61 DONE_RATIO_OPTIONS = %w(issue_field issue_status)
Chris@0 62
Chris@0 63 attr_reader :current_journal
Chris@1115 64 delegate :notes, :notes=, :private_notes, :private_notes=, :to => :current_journal, :allow_nil => true
Chris@0 65
Chris@0 66 validates_presence_of :subject, :priority, :project, :tracker, :author, :status
Chris@0 67
Chris@0 68 validates_length_of :subject, :maximum => 255
Chris@0 69 validates_inclusion_of :done_ratio, :in => 0..100
Chris@0 70 validates_numericality_of :estimated_hours, :allow_nil => true
Chris@1115 71 validate :validate_issue, :validate_required_fields
Chris@0 72
Chris@1115 73 scope :visible,
Chris@1115 74 lambda {|*args| { :include => :project,
Chris@1115 75 :conditions => Issue.visible_condition(args.shift || User.current, *args) } }
Chris@441 76
Chris@1115 77 scope :open, lambda {|*args|
Chris@1115 78 is_closed = args.size > 0 ? !args.first : false
Chris@1115 79 {:conditions => ["#{IssueStatus.table_name}.is_closed = ?", is_closed], :include => :status}
chris@22 80 }
chris@22 81
Chris@1115 82 scope :recently_updated, :order => "#{Issue.table_name}.updated_on DESC"
Chris@1115 83 scope :on_active_project, :include => [:status, :project, :tracker],
Chris@1115 84 :conditions => ["#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"]
Chris@0 85
Chris@0 86 before_create :default_assign
Chris@1115 87 before_save :close_duplicates, :update_done_ratio_from_issue_status, :force_updated_on_change
Chris@1115 88 after_save {|issue| issue.send :after_project_change if !issue.id_changed? && issue.project_id_changed?}
chris@37 89 after_save :reschedule_following_issues, :update_nested_set_attributes, :update_parent_attributes, :create_journal
Chris@1115 90 # Should be after_create but would be called before previous after_save callbacks
Chris@1115 91 after_save :after_create_from_copy
Chris@0 92 after_destroy :update_parent_attributes
Chris@441 93
Chris@441 94 # Returns a SQL conditions string used to find all issues visible by the specified user
Chris@441 95 def self.visible_condition(user, options={})
Chris@441 96 Project.allowed_to_condition(user, :view_issues, options) do |role, user|
Chris@1115 97 if user.logged?
Chris@1115 98 case role.issues_visibility
Chris@1115 99 when 'all'
Chris@1115 100 nil
Chris@1115 101 when 'default'
Chris@1115 102 user_ids = [user.id] + user.groups.map(&:id)
Chris@1115 103 "(#{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@1115 104 when 'own'
Chris@1115 105 user_ids = [user.id] + user.groups.map(&:id)
Chris@1115 106 "(#{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id IN (#{user_ids.join(',')}))"
Chris@1115 107 else
Chris@1115 108 '1=0'
Chris@1115 109 end
Chris@441 110 else
Chris@1115 111 "(#{table_name}.is_private = #{connection.quoted_false})"
Chris@441 112 end
Chris@441 113 end
Chris@441 114 end
Chris@441 115
Chris@0 116 # Returns true if usr or current user is allowed to view the issue
Chris@0 117 def visible?(usr=nil)
Chris@441 118 (usr || User.current).allowed_to?(:view_issues, self.project) do |role, user|
Chris@1115 119 if user.logged?
Chris@1115 120 case role.issues_visibility
Chris@1115 121 when 'all'
Chris@1115 122 true
Chris@1115 123 when 'default'
Chris@1115 124 !self.is_private? || (self.author == user || user.is_or_belongs_to?(assigned_to))
Chris@1115 125 when 'own'
Chris@1115 126 self.author == user || user.is_or_belongs_to?(assigned_to)
Chris@1115 127 else
Chris@1115 128 false
Chris@1115 129 end
Chris@441 130 else
Chris@1115 131 !self.is_private?
Chris@441 132 end
Chris@441 133 end
Chris@0 134 end
Chris@441 135
Chris@1115 136 def initialize(attributes=nil, *args)
Chris@1115 137 super
Chris@0 138 if new_record?
Chris@0 139 # set default values for new records only
Chris@0 140 self.status ||= IssueStatus.default
Chris@0 141 self.priority ||= IssuePriority.default
Chris@1115 142 self.watcher_user_ids = []
Chris@0 143 end
Chris@0 144 end
Chris@441 145
Chris@1115 146 # AR#Persistence#destroy would raise and RecordNotFound exception
Chris@1115 147 # if the issue was already deleted or updated (non matching lock_version).
Chris@1115 148 # This is a problem when bulk deleting issues or deleting a project
Chris@1115 149 # (because an issue may already be deleted if its parent was deleted
Chris@1115 150 # first).
Chris@1115 151 # The issue is reloaded by the nested_set before being deleted so
Chris@1115 152 # the lock_version condition should not be an issue but we handle it.
Chris@1115 153 def destroy
Chris@1115 154 super
Chris@1115 155 rescue ActiveRecord::RecordNotFound
Chris@1115 156 # Stale or already deleted
Chris@1115 157 begin
Chris@1115 158 reload
Chris@1115 159 rescue ActiveRecord::RecordNotFound
Chris@1115 160 # The issue was actually already deleted
Chris@1115 161 @destroyed = true
Chris@1115 162 return freeze
Chris@1115 163 end
Chris@1115 164 # The issue was stale, retry to destroy
Chris@1115 165 super
Chris@1115 166 end
Chris@1115 167
Chris@1115 168 def reload(*args)
Chris@1115 169 @workflow_rule_by_attribute = nil
Chris@1115 170 @assignable_versions = nil
Chris@1115 171 super
Chris@1115 172 end
Chris@1115 173
Chris@0 174 # Overrides Redmine::Acts::Customizable::InstanceMethods#available_custom_fields
Chris@0 175 def available_custom_fields
Chris@441 176 (project && tracker) ? (project.all_issue_custom_fields & tracker.custom_fields.all) : []
Chris@0 177 end
Chris@441 178
Chris@1115 179 # Copies attributes from another issue, arg can be an id or an Issue
Chris@1115 180 def copy_from(arg, options={})
Chris@0 181 issue = arg.is_a?(Issue) ? arg : Issue.visible.find(arg)
Chris@0 182 self.attributes = issue.attributes.dup.except("id", "root_id", "parent_id", "lft", "rgt", "created_on", "updated_on")
Chris@0 183 self.custom_field_values = issue.custom_field_values.inject({}) {|h,v| h[v.custom_field_id] = v.value; h}
Chris@0 184 self.status = issue.status
Chris@1115 185 self.author = User.current
Chris@1115 186 unless options[:attachments] == false
Chris@1115 187 self.attachments = issue.attachments.map do |attachement|
Chris@1115 188 attachement.copy(:container => self)
Chris@1115 189 end
Chris@1115 190 end
Chris@1115 191 @copied_from = issue
Chris@1115 192 @copy_options = options
Chris@0 193 self
Chris@0 194 end
Chris@441 195
Chris@1115 196 # Returns an unsaved copy of the issue
Chris@1115 197 def copy(attributes=nil, copy_options={})
Chris@1115 198 copy = self.class.new.copy_from(self, copy_options)
Chris@1115 199 copy.attributes = attributes if attributes
Chris@1115 200 copy
Chris@1115 201 end
Chris@1115 202
Chris@1115 203 # Returns true if the issue is a copy
Chris@1115 204 def copy?
Chris@1115 205 @copied_from.present?
Chris@1115 206 end
Chris@1115 207
Chris@0 208 # Moves/copies an issue to a new project and tracker
Chris@0 209 # Returns the moved/copied issue on success, false on failure
Chris@1115 210 def move_to_project(new_project, new_tracker=nil, options={})
Chris@1115 211 ActiveSupport::Deprecation.warn "Issue#move_to_project is deprecated, use #project= instead."
Chris@441 212
Chris@1115 213 if options[:copy]
Chris@1115 214 issue = self.copy
Chris@1115 215 else
Chris@1115 216 issue = self
Chris@1115 217 end
Chris@441 218
Chris@1115 219 issue.init_journal(User.current, options[:notes])
Chris@1115 220
Chris@1115 221 # Preserve previous behaviour
Chris@1115 222 # #move_to_project doesn't change tracker automatically
Chris@1115 223 issue.send :project=, new_project, true
Chris@0 224 if new_tracker
Chris@0 225 issue.tracker = new_tracker
Chris@0 226 end
Chris@0 227 # Allow bulk setting of attributes on the issue
Chris@0 228 if options[:attributes]
Chris@0 229 issue.attributes = options[:attributes]
Chris@0 230 end
Chris@441 231
Chris@1115 232 issue.save ? issue : false
Chris@0 233 end
Chris@0 234
Chris@0 235 def status_id=(sid)
Chris@0 236 self.status = nil
Chris@1115 237 result = write_attribute(:status_id, sid)
Chris@1115 238 @workflow_rule_by_attribute = nil
Chris@1115 239 result
Chris@0 240 end
Chris@441 241
Chris@0 242 def priority_id=(pid)
Chris@0 243 self.priority = nil
Chris@0 244 write_attribute(:priority_id, pid)
Chris@0 245 end
Chris@0 246
Chris@1115 247 def category_id=(cid)
Chris@1115 248 self.category = nil
Chris@1115 249 write_attribute(:category_id, cid)
Chris@1115 250 end
Chris@1115 251
Chris@1115 252 def fixed_version_id=(vid)
Chris@1115 253 self.fixed_version = nil
Chris@1115 254 write_attribute(:fixed_version_id, vid)
Chris@1115 255 end
Chris@1115 256
Chris@0 257 def tracker_id=(tid)
Chris@0 258 self.tracker = nil
Chris@0 259 result = write_attribute(:tracker_id, tid)
Chris@0 260 @custom_field_values = nil
Chris@1115 261 @workflow_rule_by_attribute = nil
Chris@0 262 result
Chris@0 263 end
Chris@909 264
Chris@1115 265 def project_id=(project_id)
Chris@1115 266 if project_id.to_s != self.project_id.to_s
Chris@1115 267 self.project = (project_id.present? ? Project.find_by_id(project_id) : nil)
Chris@1115 268 end
Chris@1115 269 end
Chris@1115 270
Chris@1115 271 def project=(project, keep_tracker=false)
Chris@1115 272 project_was = self.project
Chris@1115 273 write_attribute(:project_id, project ? project.id : nil)
Chris@1115 274 association_instance_set('project', project)
Chris@1115 275 if project_was && project && project_was != project
Chris@1115 276 @assignable_versions = nil
Chris@1115 277
Chris@1115 278 unless keep_tracker || project.trackers.include?(tracker)
Chris@1115 279 self.tracker = project.trackers.first
Chris@1115 280 end
Chris@1115 281 # Reassign to the category with same name if any
Chris@1115 282 if category
Chris@1115 283 self.category = project.issue_categories.find_by_name(category.name)
Chris@1115 284 end
Chris@1115 285 # Keep the fixed_version if it's still valid in the new_project
Chris@1115 286 if fixed_version && fixed_version.project != project && !project.shared_versions.include?(fixed_version)
Chris@1115 287 self.fixed_version = nil
Chris@1115 288 end
Chris@1115 289 # Clear the parent task if it's no longer valid
Chris@1115 290 unless valid_parent_project?
Chris@1115 291 self.parent_issue_id = nil
Chris@1115 292 end
Chris@1115 293 @custom_field_values = nil
Chris@1115 294 end
Chris@1115 295 end
Chris@1115 296
Chris@507 297 def description=(arg)
Chris@507 298 if arg.is_a?(String)
Chris@507 299 arg = arg.gsub(/(\r\n|\n|\r)/, "\r\n")
Chris@507 300 end
Chris@507 301 write_attribute(:description, arg)
Chris@507 302 end
Chris@441 303
Chris@1115 304 # Overrides assign_attributes so that project and tracker get assigned first
Chris@1115 305 def assign_attributes_with_project_and_tracker_first(new_attributes, *args)
Chris@0 306 return if new_attributes.nil?
Chris@1115 307 attrs = new_attributes.dup
Chris@1115 308 attrs.stringify_keys!
Chris@1115 309
Chris@1115 310 %w(project project_id tracker tracker_id).each do |attr|
Chris@1115 311 if attrs.has_key?(attr)
Chris@1115 312 send "#{attr}=", attrs.delete(attr)
Chris@1115 313 end
Chris@0 314 end
Chris@1115 315 send :assign_attributes_without_project_and_tracker_first, attrs, *args
Chris@0 316 end
Chris@0 317 # Do not redefine alias chain on reload (see #4838)
Chris@1115 318 alias_method_chain(:assign_attributes, :project_and_tracker_first) unless method_defined?(:assign_attributes_without_project_and_tracker_first)
Chris@441 319
Chris@0 320 def estimated_hours=(h)
Chris@0 321 write_attribute :estimated_hours, (h.is_a?(String) ? h.to_hours : h)
Chris@0 322 end
Chris@441 323
Chris@1115 324 safe_attributes 'project_id',
Chris@1115 325 :if => lambda {|issue, user|
Chris@1115 326 if issue.new_record?
Chris@1115 327 issue.copy?
Chris@1115 328 elsif user.allowed_to?(:move_issues, issue.project)
Chris@1115 329 projects = Issue.allowed_target_projects_on_move(user)
Chris@1115 330 projects.include?(issue.project) && projects.size > 1
Chris@1115 331 end
Chris@1115 332 }
Chris@1115 333
Chris@117 334 safe_attributes 'tracker_id',
Chris@117 335 'status_id',
Chris@117 336 'category_id',
Chris@117 337 'assigned_to_id',
Chris@117 338 'priority_id',
Chris@117 339 'fixed_version_id',
Chris@117 340 'subject',
Chris@117 341 'description',
Chris@117 342 'start_date',
Chris@117 343 'due_date',
Chris@117 344 'done_ratio',
Chris@117 345 'estimated_hours',
Chris@117 346 'custom_field_values',
Chris@117 347 'custom_fields',
Chris@117 348 'lock_version',
Chris@1115 349 'notes',
Chris@117 350 :if => lambda {|issue, user| issue.new_record? || user.allowed_to?(:edit_issues, issue.project) }
Chris@441 351
Chris@117 352 safe_attributes 'status_id',
Chris@117 353 'assigned_to_id',
Chris@117 354 'fixed_version_id',
Chris@117 355 'done_ratio',
Chris@1115 356 'lock_version',
Chris@1115 357 'notes',
Chris@117 358 :if => lambda {|issue, user| issue.new_statuses_allowed_to(user).any? }
chris@37 359
Chris@1115 360 safe_attributes 'notes',
Chris@1115 361 :if => lambda {|issue, user| user.allowed_to?(:add_issue_notes, issue.project)}
Chris@1115 362
Chris@1115 363 safe_attributes 'private_notes',
Chris@1115 364 :if => lambda {|issue, user| !issue.new_record? && user.allowed_to?(:set_notes_private, issue.project)}
Chris@1115 365
Chris@1115 366 safe_attributes 'watcher_user_ids',
Chris@1115 367 :if => lambda {|issue, user| issue.new_record? && user.allowed_to?(:add_issue_watchers, issue.project)}
Chris@1115 368
Chris@441 369 safe_attributes 'is_private',
Chris@441 370 :if => lambda {|issue, user|
Chris@441 371 user.allowed_to?(:set_issues_private, issue.project) ||
Chris@441 372 (issue.author == user && user.allowed_to?(:set_own_issues_private, issue.project))
Chris@441 373 }
Chris@441 374
Chris@1115 375 safe_attributes 'parent_issue_id',
Chris@1115 376 :if => lambda {|issue, user| (issue.new_record? || user.allowed_to?(:edit_issues, issue.project)) &&
Chris@1115 377 user.allowed_to?(:manage_subtasks, issue.project)}
Chris@1115 378
Chris@1115 379 def safe_attribute_names(user=nil)
Chris@1115 380 names = super
Chris@1115 381 names -= disabled_core_fields
Chris@1115 382 names -= read_only_attribute_names(user)
Chris@1115 383 names
Chris@1115 384 end
Chris@1115 385
Chris@0 386 # Safely sets attributes
Chris@0 387 # Should be called from controllers instead of #attributes=
Chris@0 388 # attr_accessible is too rough because we still want things like
Chris@0 389 # Issue.new(:project => foo) to work
Chris@0 390 def safe_attributes=(attrs, user=User.current)
chris@37 391 return unless attrs.is_a?(Hash)
Chris@441 392
Chris@1115 393 attrs = attrs.dup
Chris@441 394
Chris@1115 395 # Project and Tracker must be set before since new_statuses_allowed_to depends on it.
Chris@1115 396 if (p = attrs.delete('project_id')) && safe_attribute?('project_id')
Chris@1115 397 if allowed_target_projects(user).collect(&:id).include?(p.to_i)
Chris@1115 398 self.project_id = p
Chris@1115 399 end
Chris@1115 400 end
Chris@1115 401
Chris@1115 402 if (t = attrs.delete('tracker_id')) && safe_attribute?('tracker_id')
chris@37 403 self.tracker_id = t
chris@37 404 end
Chris@441 405
Chris@1115 406 if (s = attrs.delete('status_id')) && safe_attribute?('status_id')
Chris@1115 407 if new_statuses_allowed_to(user).collect(&:id).include?(s.to_i)
Chris@1115 408 self.status_id = s
Chris@0 409 end
Chris@0 410 end
Chris@441 411
Chris@1115 412 attrs = delete_unsafe_attributes(attrs, user)
Chris@1115 413 return if attrs.empty?
Chris@1115 414
Chris@0 415 unless leaf?
Chris@0 416 attrs.reject! {|k,v| %w(priority_id done_ratio start_date due_date estimated_hours).include?(k)}
Chris@0 417 end
Chris@441 418
Chris@1115 419 if attrs['parent_issue_id'].present?
Chris@1115 420 s = attrs['parent_issue_id'].to_s
Chris@1294 421 unless (m = s.match(%r{\A#?(\d+)\z})) && (m[1] == parent_id.to_s || Issue.visible(user).exists?(m[1]))
Chris@1115 422 @invalid_parent_issue_id = attrs.delete('parent_issue_id')
Chris@0 423 end
Chris@0 424 end
Chris@441 425
Chris@1115 426 if attrs['custom_field_values'].present?
Chris@1115 427 attrs['custom_field_values'] = attrs['custom_field_values'].reject {|k, v| read_only_attribute_names(user).include? k.to_s}
Chris@1115 428 end
Chris@1115 429
Chris@1115 430 if attrs['custom_fields'].present?
Chris@1115 431 attrs['custom_fields'] = attrs['custom_fields'].reject {|c| read_only_attribute_names(user).include? c['id'].to_s}
Chris@1115 432 end
Chris@1115 433
Chris@1115 434 # mass-assignment security bypass
Chris@1115 435 assign_attributes attrs, :without_protection => true
Chris@0 436 end
Chris@441 437
Chris@1115 438 def disabled_core_fields
Chris@1115 439 tracker ? tracker.disabled_core_fields : []
Chris@1115 440 end
Chris@1115 441
Chris@1115 442 # Returns the custom_field_values that can be edited by the given user
Chris@1115 443 def editable_custom_field_values(user=nil)
Chris@1115 444 custom_field_values.reject do |value|
Chris@1115 445 read_only_attribute_names(user).include?(value.custom_field_id.to_s)
Chris@1115 446 end
Chris@1115 447 end
Chris@1115 448
Chris@1115 449 # Returns the names of attributes that are read-only for user or the current user
Chris@1115 450 # For users with multiple roles, the read-only fields are the intersection of
Chris@1115 451 # read-only fields of each role
Chris@1115 452 # The result is an array of strings where sustom fields are represented with their ids
Chris@1115 453 #
Chris@1115 454 # Examples:
Chris@1115 455 # issue.read_only_attribute_names # => ['due_date', '2']
Chris@1115 456 # issue.read_only_attribute_names(user) # => []
Chris@1115 457 def read_only_attribute_names(user=nil)
Chris@1115 458 workflow_rule_by_attribute(user).reject {|attr, rule| rule != 'readonly'}.keys
Chris@1115 459 end
Chris@1115 460
Chris@1115 461 # Returns the names of required attributes for user or the current user
Chris@1115 462 # For users with multiple roles, the required fields are the intersection of
Chris@1115 463 # required fields of each role
Chris@1115 464 # The result is an array of strings where sustom fields are represented with their ids
Chris@1115 465 #
Chris@1115 466 # Examples:
Chris@1115 467 # issue.required_attribute_names # => ['due_date', '2']
Chris@1115 468 # issue.required_attribute_names(user) # => []
Chris@1115 469 def required_attribute_names(user=nil)
Chris@1115 470 workflow_rule_by_attribute(user).reject {|attr, rule| rule != 'required'}.keys
Chris@1115 471 end
Chris@1115 472
Chris@1115 473 # Returns true if the attribute is required for user
Chris@1115 474 def required_attribute?(name, user=nil)
Chris@1115 475 required_attribute_names(user).include?(name.to_s)
Chris@1115 476 end
Chris@1115 477
Chris@1115 478 # Returns a hash of the workflow rule by attribute for the given user
Chris@1115 479 #
Chris@1115 480 # Examples:
Chris@1115 481 # issue.workflow_rule_by_attribute # => {'due_date' => 'required', 'start_date' => 'readonly'}
Chris@1115 482 def workflow_rule_by_attribute(user=nil)
Chris@1115 483 return @workflow_rule_by_attribute if @workflow_rule_by_attribute && user.nil?
Chris@1115 484
Chris@1115 485 user_real = user || User.current
Chris@1115 486 roles = user_real.admin ? Role.all : user_real.roles_for_project(project)
Chris@1115 487 return {} if roles.empty?
Chris@1115 488
Chris@1115 489 result = {}
Chris@1115 490 workflow_permissions = WorkflowPermission.where(:tracker_id => tracker_id, :old_status_id => status_id, :role_id => roles.map(&:id)).all
Chris@1115 491 if workflow_permissions.any?
Chris@1115 492 workflow_rules = workflow_permissions.inject({}) do |h, wp|
Chris@1115 493 h[wp.field_name] ||= []
Chris@1115 494 h[wp.field_name] << wp.rule
Chris@1115 495 h
Chris@1115 496 end
Chris@1115 497 workflow_rules.each do |attr, rules|
Chris@1115 498 next if rules.size < roles.size
Chris@1115 499 uniq_rules = rules.uniq
Chris@1115 500 if uniq_rules.size == 1
Chris@1115 501 result[attr] = uniq_rules.first
Chris@1115 502 else
Chris@1115 503 result[attr] = 'required'
Chris@1115 504 end
Chris@1115 505 end
Chris@1115 506 end
Chris@1115 507 @workflow_rule_by_attribute = result if user.nil?
Chris@1115 508 result
Chris@1115 509 end
Chris@1115 510 private :workflow_rule_by_attribute
Chris@1115 511
Chris@0 512 def done_ratio
chris@37 513 if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
Chris@0 514 status.default_done_ratio
Chris@0 515 else
Chris@0 516 read_attribute(:done_ratio)
Chris@0 517 end
Chris@0 518 end
Chris@0 519
Chris@0 520 def self.use_status_for_done_ratio?
Chris@0 521 Setting.issue_done_ratio == 'issue_status'
Chris@0 522 end
Chris@0 523
Chris@0 524 def self.use_field_for_done_ratio?
Chris@0 525 Setting.issue_done_ratio == 'issue_field'
Chris@0 526 end
Chris@441 527
Chris@909 528 def validate_issue
Chris@1115 529 if due_date.nil? && @attributes['due_date'].present?
Chris@0 530 errors.add :due_date, :not_a_date
Chris@0 531 end
Chris@441 532
Chris@1115 533 if start_date.nil? && @attributes['start_date'].present?
Chris@1115 534 errors.add :start_date, :not_a_date
Chris@1115 535 end
Chris@1115 536
Chris@1115 537 if due_date && start_date && due_date < start_date
Chris@0 538 errors.add :due_date, :greater_than_start_date
Chris@0 539 end
Chris@441 540
Chris@0 541 if start_date && soonest_start && start_date < soonest_start
Chris@0 542 errors.add :start_date, :invalid
Chris@0 543 end
Chris@441 544
Chris@0 545 if fixed_version
Chris@0 546 if !assignable_versions.include?(fixed_version)
Chris@0 547 errors.add :fixed_version_id, :inclusion
Chris@0 548 elsif reopened? && fixed_version.closed?
Chris@909 549 errors.add :base, I18n.t(:error_can_not_reopen_issue_on_closed_version)
Chris@0 550 end
Chris@0 551 end
Chris@441 552
Chris@0 553 # Checks that the issue can not be added/moved to a disabled tracker
Chris@0 554 if project && (tracker_id_changed? || project_id_changed?)
Chris@0 555 unless project.trackers.include?(tracker)
Chris@0 556 errors.add :tracker_id, :inclusion
Chris@0 557 end
Chris@0 558 end
Chris@441 559
Chris@0 560 # Checks parent issue assignment
Chris@1115 561 if @invalid_parent_issue_id.present?
Chris@1115 562 errors.add :parent_issue_id, :invalid
Chris@1115 563 elsif @parent_issue
Chris@1115 564 if !valid_parent_project?(@parent_issue)
Chris@1115 565 errors.add :parent_issue_id, :invalid
Chris@0 566 elsif !new_record?
Chris@0 567 # moving an existing issue
Chris@0 568 if @parent_issue.root_id != root_id
Chris@0 569 # we can always move to another tree
Chris@0 570 elsif move_possible?(@parent_issue)
Chris@0 571 # move accepted inside tree
Chris@0 572 else
Chris@1115 573 errors.add :parent_issue_id, :invalid
Chris@1115 574 end
Chris@1115 575 end
Chris@1115 576 end
Chris@1115 577 end
Chris@1115 578
Chris@1115 579 # Validates the issue against additional workflow requirements
Chris@1115 580 def validate_required_fields
Chris@1115 581 user = new_record? ? author : current_journal.try(:user)
Chris@1115 582
Chris@1115 583 required_attribute_names(user).each do |attribute|
Chris@1115 584 if attribute =~ /^\d+$/
Chris@1115 585 attribute = attribute.to_i
Chris@1115 586 v = custom_field_values.detect {|v| v.custom_field_id == attribute }
Chris@1115 587 if v && v.value.blank?
Chris@1115 588 errors.add :base, v.custom_field.name + ' ' + l('activerecord.errors.messages.blank')
Chris@1115 589 end
Chris@1115 590 else
Chris@1115 591 if respond_to?(attribute) && send(attribute).blank?
Chris@1115 592 errors.add attribute, :blank
Chris@0 593 end
Chris@0 594 end
Chris@0 595 end
Chris@0 596 end
Chris@441 597
Chris@0 598 # Set the done_ratio using the status if that setting is set. This will keep the done_ratios
Chris@0 599 # even if the user turns off the setting later
Chris@0 600 def update_done_ratio_from_issue_status
chris@37 601 if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
Chris@0 602 self.done_ratio = status.default_done_ratio
Chris@0 603 end
Chris@0 604 end
Chris@441 605
Chris@0 606 def init_journal(user, notes = "")
Chris@0 607 @current_journal ||= Journal.new(:journalized => self, :user => user, :notes => notes)
Chris@1115 608 if new_record?
Chris@1115 609 @current_journal.notify = false
Chris@1115 610 else
Chris@1115 611 @attributes_before_change = attributes.dup
Chris@1115 612 @custom_values_before_change = {}
Chris@1115 613 self.custom_field_values.each {|c| @custom_values_before_change.store c.custom_field_id, c.value }
Chris@1115 614 end
Chris@0 615 @current_journal
Chris@0 616 end
Chris@441 617
Chris@1115 618 # Returns the id of the last journal or nil
Chris@1115 619 def last_journal_id
Chris@1115 620 if new_record?
Chris@1115 621 nil
Chris@1115 622 else
Chris@1115 623 journals.maximum(:id)
Chris@1115 624 end
Chris@1115 625 end
Chris@1115 626
Chris@1115 627 # Returns a scope for journals that have an id greater than journal_id
Chris@1115 628 def journals_after(journal_id)
Chris@1115 629 scope = journals.reorder("#{Journal.table_name}.id ASC")
Chris@1115 630 if journal_id.present?
Chris@1115 631 scope = scope.where("#{Journal.table_name}.id > ?", journal_id.to_i)
Chris@1115 632 end
Chris@1115 633 scope
Chris@1115 634 end
Chris@1115 635
Chris@0 636 # Return true if the issue is closed, otherwise false
Chris@0 637 def closed?
Chris@0 638 self.status.is_closed?
Chris@0 639 end
Chris@441 640
Chris@0 641 # Return true if the issue is being reopened
Chris@0 642 def reopened?
Chris@0 643 if !new_record? && status_id_changed?
Chris@0 644 status_was = IssueStatus.find_by_id(status_id_was)
Chris@0 645 status_new = IssueStatus.find_by_id(status_id)
Chris@0 646 if status_was && status_new && status_was.is_closed? && !status_new.is_closed?
Chris@0 647 return true
Chris@0 648 end
Chris@0 649 end
Chris@0 650 false
Chris@0 651 end
Chris@0 652
Chris@0 653 # Return true if the issue is being closed
Chris@0 654 def closing?
Chris@0 655 if !new_record? && status_id_changed?
Chris@0 656 status_was = IssueStatus.find_by_id(status_id_was)
Chris@0 657 status_new = IssueStatus.find_by_id(status_id)
Chris@0 658 if status_was && status_new && !status_was.is_closed? && status_new.is_closed?
Chris@0 659 return true
Chris@0 660 end
Chris@0 661 end
Chris@0 662 false
Chris@0 663 end
Chris@441 664
Chris@0 665 # Returns true if the issue is overdue
Chris@0 666 def overdue?
Chris@0 667 !due_date.nil? && (due_date < Date.today) && !status.is_closed?
Chris@0 668 end
chris@22 669
chris@22 670 # Is the amount of work done less than it should for the due date
chris@22 671 def behind_schedule?
chris@22 672 return false if start_date.nil? || due_date.nil?
chris@22 673 done_date = start_date + ((due_date - start_date+1)* done_ratio/100).floor
chris@22 674 return done_date <= Date.today
chris@22 675 end
chris@22 676
chris@22 677 # Does this issue have children?
chris@22 678 def children?
chris@22 679 !leaf?
chris@22 680 end
Chris@441 681
Chris@0 682 # Users the issue can be assigned to
Chris@0 683 def assignable_users
chris@37 684 users = project.assignable_users
chris@37 685 users << author if author
Chris@909 686 users << assigned_to if assigned_to
chris@37 687 users.uniq.sort
Chris@0 688 end
Chris@441 689
Chris@0 690 # Versions that the issue can be assigned to
Chris@0 691 def assignable_versions
Chris@1115 692 return @assignable_versions if @assignable_versions
Chris@1115 693
Chris@1115 694 versions = project.shared_versions.open.all
Chris@1115 695 if fixed_version
Chris@1115 696 if fixed_version_id_changed?
Chris@1115 697 # nothing to do
Chris@1115 698 elsif project_id_changed?
Chris@1115 699 if project.shared_versions.include?(fixed_version)
Chris@1115 700 versions << fixed_version
Chris@1115 701 end
Chris@1115 702 else
Chris@1115 703 versions << fixed_version
Chris@1115 704 end
Chris@1115 705 end
Chris@1115 706 @assignable_versions = versions.uniq.sort
Chris@0 707 end
Chris@441 708
Chris@0 709 # Returns true if this issue is blocked by another issue that is still open
Chris@0 710 def blocked?
Chris@0 711 !relations_to.detect {|ir| ir.relation_type == 'blocks' && !ir.issue_from.closed?}.nil?
Chris@0 712 end
Chris@441 713
Chris@1115 714 # Returns an array of statuses that user is able to apply
Chris@1115 715 def new_statuses_allowed_to(user=User.current, include_default=false)
Chris@1115 716 if new_record? && @copied_from
Chris@1115 717 [IssueStatus.default, @copied_from.status].compact.uniq.sort
Chris@1115 718 else
Chris@1115 719 initial_status = nil
Chris@1115 720 if new_record?
Chris@1115 721 initial_status = IssueStatus.default
Chris@1115 722 elsif status_id_was
Chris@1115 723 initial_status = IssueStatus.find_by_id(status_id_was)
Chris@1115 724 end
Chris@1115 725 initial_status ||= status
Chris@1115 726
Chris@1115 727 statuses = initial_status.find_new_statuses_allowed_to(
Chris@1115 728 user.admin ? Role.all : user.roles_for_project(project),
Chris@1115 729 tracker,
Chris@1115 730 author == user,
Chris@1115 731 assigned_to_id_changed? ? assigned_to_id_was == user.id : assigned_to_id == user.id
Chris@1115 732 )
Chris@1115 733 statuses << initial_status unless statuses.empty?
Chris@1115 734 statuses << IssueStatus.default if include_default
Chris@1115 735 statuses = statuses.compact.uniq.sort
Chris@1115 736 blocked? ? statuses.reject {|s| s.is_closed?} : statuses
Chris@1115 737 end
Chris@0 738 end
Chris@441 739
Chris@1115 740 def assigned_to_was
Chris@1115 741 if assigned_to_id_changed? && assigned_to_id_was.present?
Chris@1115 742 @assigned_to_was ||= User.find_by_id(assigned_to_id_was)
Chris@1115 743 end
Chris@1115 744 end
Chris@1115 745
Chris@1115 746 # Returns the users that should be notified
Chris@1115 747 def notified_users
Chris@1115 748 notified = []
chris@37 749 # Author and assignee are always notified unless they have been
chris@37 750 # locked or don't want to be notified
Chris@1115 751 notified << author if author
Chris@909 752 if assigned_to
Chris@1115 753 notified += (assigned_to.is_a?(Group) ? assigned_to.users : [assigned_to])
Chris@909 754 end
Chris@1115 755 if assigned_to_was
Chris@1115 756 notified += (assigned_to_was.is_a?(Group) ? assigned_to_was.users : [assigned_to_was])
Chris@1115 757 end
Chris@1115 758 notified = notified.select {|u| u.active? && u.notify_about?(self)}
Chris@1115 759
Chris@1115 760 notified += project.notified_users
Chris@0 761 notified.uniq!
Chris@0 762 # Remove users that can not view the issue
Chris@0 763 notified.reject! {|user| !visible?(user)}
Chris@1115 764 notified
Chris@1115 765 end
Chris@1115 766
Chris@1115 767 # Returns the email addresses that should be notified
Chris@1115 768 def recipients
Chris@1115 769 notified_users.collect(&:mail)
Chris@1115 770 end
Chris@1115 771
Chris@1115 772 # Returns the number of hours spent on this issue
Chris@1115 773 def spent_hours
Chris@1115 774 @spent_hours ||= time_entries.sum(:hours) || 0
Chris@0 775 end
Chris@441 776
Chris@0 777 # Returns the total number of hours spent on this issue and its descendants
Chris@0 778 #
Chris@0 779 # Example:
Chris@0 780 # spent_hours => 0.0
Chris@0 781 # spent_hours => 50.2
Chris@1115 782 def total_spent_hours
Chris@1115 783 @total_spent_hours ||= self_and_descendants.sum("#{TimeEntry.table_name}.hours",
Chris@1115 784 :joins => "LEFT JOIN #{TimeEntry.table_name} ON #{TimeEntry.table_name}.issue_id = #{Issue.table_name}.id").to_f || 0.0
Chris@0 785 end
Chris@441 786
Chris@0 787 def relations
Chris@1115 788 @relations ||= IssueRelations.new(self, (relations_from + relations_to).sort)
Chris@909 789 end
Chris@909 790
Chris@909 791 # Preloads relations for a collection of issues
Chris@909 792 def self.load_relations(issues)
Chris@909 793 if issues.any?
Chris@909 794 relations = IssueRelation.all(:conditions => ["issue_from_id IN (:ids) OR issue_to_id IN (:ids)", {:ids => issues.map(&:id)}])
Chris@909 795 issues.each do |issue|
Chris@909 796 issue.instance_variable_set "@relations", relations.select {|r| r.issue_from_id == issue.id || r.issue_to_id == issue.id}
Chris@909 797 end
Chris@909 798 end
Chris@909 799 end
Chris@909 800
Chris@1115 801 # Preloads visible spent time for a collection of issues
Chris@1115 802 def self.load_visible_spent_hours(issues, user=User.current)
Chris@1115 803 if issues.any?
Chris@1115 804 hours_by_issue_id = TimeEntry.visible(user).sum(:hours, :group => :issue_id)
Chris@1115 805 issues.each do |issue|
Chris@1115 806 issue.instance_variable_set "@spent_hours", (hours_by_issue_id[issue.id] || 0)
Chris@1115 807 end
Chris@1115 808 end
Chris@1115 809 end
Chris@1115 810
Chris@1115 811 # Preloads visible relations for a collection of issues
Chris@1115 812 def self.load_visible_relations(issues, user=User.current)
Chris@1115 813 if issues.any?
Chris@1115 814 issue_ids = issues.map(&:id)
Chris@1115 815 # Relations with issue_from in given issues and visible issue_to
Chris@1115 816 relations_from = IssueRelation.includes(:issue_to => [:status, :project]).where(visible_condition(user)).where(:issue_from_id => issue_ids).all
Chris@1115 817 # Relations with issue_to in given issues and visible issue_from
Chris@1115 818 relations_to = IssueRelation.includes(:issue_from => [:status, :project]).where(visible_condition(user)).where(:issue_to_id => issue_ids).all
Chris@1115 819
Chris@1115 820 issues.each do |issue|
Chris@1115 821 relations =
Chris@1115 822 relations_from.select {|relation| relation.issue_from_id == issue.id} +
Chris@1115 823 relations_to.select {|relation| relation.issue_to_id == issue.id}
Chris@1115 824
Chris@1115 825 issue.instance_variable_set "@relations", IssueRelations.new(issue, relations.sort)
Chris@1115 826 end
Chris@1115 827 end
Chris@1115 828 end
Chris@1115 829
Chris@909 830 # Finds an issue relation given its id.
Chris@909 831 def find_relation(relation_id)
Chris@909 832 IssueRelation.find(relation_id, :conditions => ["issue_to_id = ? OR issue_from_id = ?", id, id])
Chris@0 833 end
Chris@441 834
Chris@441 835 def all_dependent_issues(except=[])
Chris@441 836 except << self
Chris@0 837 dependencies = []
Chris@0 838 relations_from.each do |relation|
Chris@441 839 if relation.issue_to && !except.include?(relation.issue_to)
Chris@128 840 dependencies << relation.issue_to
Chris@128 841 dependencies += relation.issue_to.all_dependent_issues(except)
Chris@128 842 end
Chris@0 843 end
Chris@0 844 dependencies
Chris@0 845 end
Chris@441 846
Chris@0 847 # Returns an array of issues that duplicate this one
Chris@0 848 def duplicates
Chris@0 849 relations_to.select {|r| r.relation_type == IssueRelation::TYPE_DUPLICATES}.collect {|r| r.issue_from}
Chris@0 850 end
Chris@441 851
Chris@0 852 # Returns the due date or the target due date if any
Chris@0 853 # Used on gantt chart
Chris@0 854 def due_before
Chris@0 855 due_date || (fixed_version ? fixed_version.effective_date : nil)
Chris@0 856 end
Chris@441 857
Chris@0 858 # Returns the time scheduled for this issue.
Chris@441 859 #
Chris@0 860 # Example:
Chris@0 861 # Start Date: 2/26/09, End Date: 3/04/09
Chris@0 862 # duration => 6
Chris@0 863 def duration
Chris@0 864 (start_date && due_date) ? due_date - start_date : 0
Chris@0 865 end
Chris@441 866
Chris@1115 867 # Returns the duration in working days
Chris@1115 868 def working_duration
Chris@1115 869 (start_date && due_date) ? working_days(start_date, due_date) : 0
Chris@1115 870 end
Chris@1115 871
Chris@1115 872 def soonest_start(reload=false)
Chris@1115 873 @soonest_start = nil if reload
Chris@0 874 @soonest_start ||= (
Chris@1115 875 relations_to(reload).collect{|relation| relation.successor_soonest_start} +
Chris@0 876 ancestors.collect(&:soonest_start)
Chris@0 877 ).compact.max
Chris@0 878 end
Chris@441 879
Chris@1115 880 # Sets start_date on the given date or the next working day
Chris@1115 881 # and changes due_date to keep the same working duration.
Chris@1115 882 def reschedule_on(date)
Chris@1115 883 wd = working_duration
Chris@1115 884 date = next_working_date(date)
Chris@1115 885 self.start_date = date
Chris@1115 886 self.due_date = add_working_days(date, wd)
Chris@1115 887 end
Chris@1115 888
Chris@1115 889 # Reschedules the issue on the given date or the next working day and saves the record.
Chris@1115 890 # If the issue is a parent task, this is done by rescheduling its subtasks.
Chris@1115 891 def reschedule_on!(date)
Chris@0 892 return if date.nil?
Chris@0 893 if leaf?
Chris@1115 894 if start_date.nil? || start_date != date
Chris@1115 895 if start_date && start_date > date
Chris@1115 896 # Issue can not be moved earlier than its soonest start date
Chris@1115 897 date = [soonest_start(true), date].compact.max
Chris@1115 898 end
Chris@1115 899 reschedule_on(date)
Chris@1115 900 begin
Chris@1115 901 save
Chris@1115 902 rescue ActiveRecord::StaleObjectError
Chris@1115 903 reload
Chris@1115 904 reschedule_on(date)
Chris@1115 905 save
Chris@1115 906 end
Chris@0 907 end
Chris@0 908 else
Chris@0 909 leaves.each do |leaf|
Chris@1115 910 if leaf.start_date
Chris@1115 911 # Only move subtask if it starts at the same date as the parent
Chris@1115 912 # or if it starts before the given date
Chris@1115 913 if start_date == leaf.start_date || date > leaf.start_date
Chris@1115 914 leaf.reschedule_on!(date)
Chris@1115 915 end
Chris@1115 916 else
Chris@1115 917 leaf.reschedule_on!(date)
Chris@1115 918 end
Chris@0 919 end
Chris@0 920 end
Chris@0 921 end
Chris@441 922
Chris@0 923 def <=>(issue)
Chris@0 924 if issue.nil?
Chris@0 925 -1
Chris@0 926 elsif root_id != issue.root_id
Chris@0 927 (root_id || 0) <=> (issue.root_id || 0)
Chris@0 928 else
Chris@0 929 (lft || 0) <=> (issue.lft || 0)
Chris@0 930 end
Chris@0 931 end
Chris@441 932
Chris@0 933 def to_s
Chris@0 934 "#{tracker} ##{id}: #{subject}"
Chris@0 935 end
Chris@441 936
Chris@0 937 # Returns a string of css classes that apply to the issue
Chris@0 938 def css_classes
Chris@1115 939 s = "issue status-#{status_id} #{priority.try(:css_classes)}"
Chris@0 940 s << ' closed' if closed?
Chris@0 941 s << ' overdue' if overdue?
Chris@441 942 s << ' child' if child?
Chris@441 943 s << ' parent' unless leaf?
Chris@441 944 s << ' private' if is_private?
Chris@0 945 s << ' created-by-me' if User.current.logged? && author_id == User.current.id
Chris@0 946 s << ' assigned-to-me' if User.current.logged? && assigned_to_id == User.current.id
Chris@0 947 s
Chris@0 948 end
Chris@0 949
Chris@1115 950 # Saves an issue and a time_entry from the parameters
Chris@0 951 def save_issue_with_child_records(params, existing_time_entry=nil)
Chris@0 952 Issue.transaction do
Chris@441 953 if params[:time_entry] && (params[:time_entry][:hours].present? || params[:time_entry][:comments].present?) && User.current.allowed_to?(:log_time, project)
Chris@0 954 @time_entry = existing_time_entry || TimeEntry.new
Chris@0 955 @time_entry.project = project
Chris@0 956 @time_entry.issue = self
Chris@0 957 @time_entry.user = User.current
Chris@909 958 @time_entry.spent_on = User.current.today
Chris@0 959 @time_entry.attributes = params[:time_entry]
Chris@0 960 self.time_entries << @time_entry
Chris@0 961 end
Chris@441 962
Chris@1115 963 # TODO: Rename hook
Chris@1115 964 Redmine::Hook.call_hook(:controller_issues_edit_before_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
Chris@1115 965 if save
Chris@0 966 # TODO: Rename hook
Chris@1115 967 Redmine::Hook.call_hook(:controller_issues_edit_after_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
Chris@1115 968 else
Chris@1115 969 raise ActiveRecord::Rollback
Chris@0 970 end
Chris@0 971 end
Chris@0 972 end
Chris@0 973
Chris@0 974 # Unassigns issues from +version+ if it's no longer shared with issue's project
Chris@0 975 def self.update_versions_from_sharing_change(version)
Chris@0 976 # Update issues assigned to the version
Chris@0 977 update_versions(["#{Issue.table_name}.fixed_version_id = ?", version.id])
Chris@0 978 end
Chris@441 979
Chris@0 980 # Unassigns issues from versions that are no longer shared
Chris@0 981 # after +project+ was moved
Chris@0 982 def self.update_versions_from_hierarchy_change(project)
Chris@0 983 moved_project_ids = project.self_and_descendants.reload.collect(&:id)
Chris@0 984 # Update issues of the moved projects and issues assigned to a version of a moved project
Chris@0 985 Issue.update_versions(["#{Version.table_name}.project_id IN (?) OR #{Issue.table_name}.project_id IN (?)", moved_project_ids, moved_project_ids])
Chris@0 986 end
Chris@0 987
Chris@0 988 def parent_issue_id=(arg)
Chris@1115 989 s = arg.to_s.strip.presence
Chris@1115 990 if s && (m = s.match(%r{\A#?(\d+)\z})) && (@parent_issue = Issue.find_by_id(m[1]))
Chris@0 991 @parent_issue.id
Chris@0 992 else
Chris@0 993 @parent_issue = nil
Chris@1115 994 @invalid_parent_issue_id = arg
Chris@0 995 end
Chris@0 996 end
Chris@441 997
Chris@0 998 def parent_issue_id
Chris@1115 999 if @invalid_parent_issue_id
Chris@1115 1000 @invalid_parent_issue_id
Chris@1115 1001 elsif instance_variable_defined? :@parent_issue
Chris@0 1002 @parent_issue.nil? ? nil : @parent_issue.id
Chris@0 1003 else
Chris@0 1004 parent_id
Chris@0 1005 end
Chris@0 1006 end
Chris@0 1007
Chris@1115 1008 # Returns true if issue's project is a valid
Chris@1115 1009 # parent issue project
Chris@1115 1010 def valid_parent_project?(issue=parent)
Chris@1115 1011 return true if issue.nil? || issue.project_id == project_id
Chris@1115 1012
Chris@1115 1013 case Setting.cross_project_subtasks
Chris@1115 1014 when 'system'
Chris@1115 1015 true
Chris@1115 1016 when 'tree'
Chris@1115 1017 issue.project.root == project.root
Chris@1115 1018 when 'hierarchy'
Chris@1115 1019 issue.project.is_or_is_ancestor_of?(project) || issue.project.is_descendant_of?(project)
Chris@1115 1020 when 'descendants'
Chris@1115 1021 issue.project.is_or_is_ancestor_of?(project)
Chris@1115 1022 else
Chris@1115 1023 false
Chris@1115 1024 end
Chris@1115 1025 end
Chris@1115 1026
Chris@0 1027 # Extracted from the ReportsController.
Chris@0 1028 def self.by_tracker(project)
Chris@0 1029 count_and_group_by(:project => project,
Chris@0 1030 :field => 'tracker_id',
Chris@0 1031 :joins => Tracker.table_name)
Chris@0 1032 end
Chris@0 1033
Chris@0 1034 def self.by_version(project)
Chris@0 1035 count_and_group_by(:project => project,
Chris@0 1036 :field => 'fixed_version_id',
Chris@0 1037 :joins => Version.table_name)
Chris@0 1038 end
Chris@0 1039
Chris@0 1040 def self.by_priority(project)
Chris@0 1041 count_and_group_by(:project => project,
Chris@0 1042 :field => 'priority_id',
Chris@0 1043 :joins => IssuePriority.table_name)
Chris@0 1044 end
Chris@0 1045
Chris@0 1046 def self.by_category(project)
Chris@0 1047 count_and_group_by(:project => project,
Chris@0 1048 :field => 'category_id',
Chris@0 1049 :joins => IssueCategory.table_name)
Chris@0 1050 end
Chris@0 1051
Chris@0 1052 def self.by_assigned_to(project)
Chris@0 1053 count_and_group_by(:project => project,
Chris@0 1054 :field => 'assigned_to_id',
Chris@0 1055 :joins => User.table_name)
Chris@0 1056 end
Chris@0 1057
Chris@0 1058 def self.by_author(project)
Chris@0 1059 count_and_group_by(:project => project,
Chris@0 1060 :field => 'author_id',
Chris@0 1061 :joins => User.table_name)
Chris@0 1062 end
Chris@0 1063
Chris@0 1064 def self.by_subproject(project)
Chris@0 1065 ActiveRecord::Base.connection.select_all("select s.id as status_id,
Chris@0 1066 s.is_closed as closed,
Chris@441 1067 #{Issue.table_name}.project_id as project_id,
Chris@441 1068 count(#{Issue.table_name}.id) as total
Chris@0 1069 from
Chris@441 1070 #{Issue.table_name}, #{Project.table_name}, #{IssueStatus.table_name} s
Chris@0 1071 where
Chris@441 1072 #{Issue.table_name}.status_id=s.id
Chris@441 1073 and #{Issue.table_name}.project_id = #{Project.table_name}.id
Chris@441 1074 and #{visible_condition(User.current, :project => project, :with_subprojects => true)}
Chris@441 1075 and #{Issue.table_name}.project_id <> #{project.id}
Chris@441 1076 group by s.id, s.is_closed, #{Issue.table_name}.project_id") if project.descendants.active.any?
Chris@0 1077 end
Chris@0 1078 # End ReportsController extraction
Chris@441 1079
Chris@1115 1080 # Returns an array of projects that user can assign the issue to
Chris@1115 1081 def allowed_target_projects(user=User.current)
Chris@1115 1082 if new_record?
Chris@1115 1083 Project.all(:conditions => Project.allowed_to_condition(user, :add_issues))
Chris@1115 1084 else
Chris@1115 1085 self.class.allowed_target_projects_on_move(user)
Chris@0 1086 end
Chris@1115 1087 end
Chris@1115 1088
Chris@1115 1089 # Returns an array of projects that user can move issues to
Chris@1115 1090 def self.allowed_target_projects_on_move(user=User.current)
Chris@1115 1091 Project.all(:conditions => Project.allowed_to_condition(user, :move_issues))
Chris@0 1092 end
Chris@441 1093
Chris@0 1094 private
Chris@441 1095
Chris@1115 1096 def after_project_change
Chris@1115 1097 # Update project_id on related time entries
Chris@1115 1098 TimeEntry.update_all(["project_id = ?", project_id], {:issue_id => id})
Chris@1115 1099
Chris@1115 1100 # Delete issue relations
Chris@1115 1101 unless Setting.cross_project_issue_relations?
Chris@1115 1102 relations_from.clear
Chris@1115 1103 relations_to.clear
Chris@1115 1104 end
Chris@1115 1105
Chris@1115 1106 # Move subtasks that were in the same project
Chris@1115 1107 children.each do |child|
Chris@1115 1108 next unless child.project_id == project_id_was
Chris@1115 1109 # Change project and keep project
Chris@1115 1110 child.send :project=, project, true
Chris@1115 1111 unless child.save
Chris@1115 1112 raise ActiveRecord::Rollback
Chris@1115 1113 end
Chris@1115 1114 end
Chris@1115 1115 end
Chris@1115 1116
Chris@1115 1117 # Callback for after the creation of an issue by copy
Chris@1115 1118 # * adds a "copied to" relation with the copied issue
Chris@1115 1119 # * copies subtasks from the copied issue
Chris@1115 1120 def after_create_from_copy
Chris@1115 1121 return unless copy? && !@after_create_from_copy_handled
Chris@1115 1122
Chris@1115 1123 if (@copied_from.project_id == project_id || Setting.cross_project_issue_relations?) && @copy_options[:link] != false
Chris@1115 1124 relation = IssueRelation.new(:issue_from => @copied_from, :issue_to => self, :relation_type => IssueRelation::TYPE_COPIED_TO)
Chris@1115 1125 unless relation.save
Chris@1115 1126 logger.error "Could not create relation while copying ##{@copied_from.id} to ##{id} due to validation errors: #{relation.errors.full_messages.join(', ')}" if logger
Chris@1115 1127 end
Chris@1115 1128 end
Chris@1115 1129
Chris@1115 1130 unless @copied_from.leaf? || @copy_options[:subtasks] == false
Chris@1115 1131 @copied_from.children.each do |child|
Chris@1115 1132 unless child.visible?
Chris@1115 1133 # Do not copy subtasks that are not visible to avoid potential disclosure of private data
Chris@1115 1134 logger.error "Subtask ##{child.id} was not copied during ##{@copied_from.id} copy because it is not visible to the current user" if logger
Chris@1115 1135 next
Chris@1115 1136 end
Chris@1115 1137 copy = Issue.new.copy_from(child, @copy_options)
Chris@1115 1138 copy.author = author
Chris@1115 1139 copy.project = project
Chris@1115 1140 copy.parent_issue_id = id
Chris@1115 1141 # Children subtasks are copied recursively
Chris@1115 1142 unless copy.save
Chris@1115 1143 logger.error "Could not copy subtask ##{child.id} while copying ##{@copied_from.id} to ##{id} due to validation errors: #{copy.errors.full_messages.join(', ')}" if logger
Chris@1115 1144 end
Chris@1115 1145 end
Chris@1115 1146 end
Chris@1115 1147 @after_create_from_copy_handled = true
Chris@1115 1148 end
Chris@1115 1149
Chris@0 1150 def update_nested_set_attributes
Chris@0 1151 if root_id.nil?
Chris@0 1152 # issue was just created
Chris@0 1153 self.root_id = (@parent_issue.nil? ? id : @parent_issue.root_id)
Chris@0 1154 set_default_left_and_right
Chris@0 1155 Issue.update_all("root_id = #{root_id}, lft = #{lft}, rgt = #{rgt}", ["id = ?", id])
Chris@0 1156 if @parent_issue
Chris@0 1157 move_to_child_of(@parent_issue)
Chris@0 1158 end
Chris@0 1159 reload
Chris@0 1160 elsif parent_issue_id != parent_id
Chris@0 1161 former_parent_id = parent_id
Chris@0 1162 # moving an existing issue
Chris@0 1163 if @parent_issue && @parent_issue.root_id == root_id
Chris@0 1164 # inside the same tree
Chris@0 1165 move_to_child_of(@parent_issue)
Chris@0 1166 else
Chris@0 1167 # to another tree
Chris@0 1168 unless root?
Chris@0 1169 move_to_right_of(root)
Chris@0 1170 reload
Chris@0 1171 end
Chris@0 1172 old_root_id = root_id
Chris@0 1173 self.root_id = (@parent_issue.nil? ? id : @parent_issue.root_id )
Chris@0 1174 target_maxright = nested_set_scope.maximum(right_column_name) || 0
Chris@0 1175 offset = target_maxright + 1 - lft
Chris@0 1176 Issue.update_all("root_id = #{root_id}, lft = lft + #{offset}, rgt = rgt + #{offset}",
Chris@0 1177 ["root_id = ? AND lft >= ? AND rgt <= ? ", old_root_id, lft, rgt])
Chris@0 1178 self[left_column_name] = lft + offset
Chris@0 1179 self[right_column_name] = rgt + offset
Chris@0 1180 if @parent_issue
Chris@0 1181 move_to_child_of(@parent_issue)
Chris@0 1182 end
Chris@0 1183 end
Chris@0 1184 reload
Chris@0 1185 # delete invalid relations of all descendants
Chris@0 1186 self_and_descendants.each do |issue|
Chris@0 1187 issue.relations.each do |relation|
Chris@0 1188 relation.destroy unless relation.valid?
Chris@0 1189 end
Chris@0 1190 end
Chris@0 1191 # update former parent
Chris@0 1192 recalculate_attributes_for(former_parent_id) if former_parent_id
Chris@0 1193 end
Chris@0 1194 remove_instance_variable(:@parent_issue) if instance_variable_defined?(:@parent_issue)
Chris@0 1195 end
Chris@441 1196
Chris@0 1197 def update_parent_attributes
Chris@0 1198 recalculate_attributes_for(parent_id) if parent_id
Chris@0 1199 end
Chris@0 1200
Chris@0 1201 def recalculate_attributes_for(issue_id)
Chris@0 1202 if issue_id && p = Issue.find_by_id(issue_id)
Chris@0 1203 # priority = highest priority of children
Chris@1115 1204 if priority_position = p.children.maximum("#{IssuePriority.table_name}.position", :joins => :priority)
Chris@0 1205 p.priority = IssuePriority.find_by_position(priority_position)
Chris@0 1206 end
Chris@441 1207
Chris@0 1208 # start/due dates = lowest/highest dates of children
Chris@0 1209 p.start_date = p.children.minimum(:start_date)
Chris@0 1210 p.due_date = p.children.maximum(:due_date)
Chris@0 1211 if p.start_date && p.due_date && p.due_date < p.start_date
Chris@0 1212 p.start_date, p.due_date = p.due_date, p.start_date
Chris@0 1213 end
Chris@441 1214
Chris@0 1215 # done ratio = weighted average ratio of leaves
chris@37 1216 unless Issue.use_status_for_done_ratio? && p.status && p.status.default_done_ratio
Chris@0 1217 leaves_count = p.leaves.count
Chris@0 1218 if leaves_count > 0
Chris@0 1219 average = p.leaves.average(:estimated_hours).to_f
Chris@0 1220 if average == 0
Chris@0 1221 average = 1
Chris@0 1222 end
Chris@1115 1223 done = p.leaves.sum("COALESCE(estimated_hours, #{average}) * (CASE WHEN is_closed = #{connection.quoted_true} THEN 100 ELSE COALESCE(done_ratio, 0) END)", :joins => :status).to_f
Chris@0 1224 progress = done / (average * leaves_count)
Chris@0 1225 p.done_ratio = progress.round
Chris@0 1226 end
Chris@0 1227 end
Chris@441 1228
Chris@0 1229 # estimate = sum of leaves estimates
Chris@0 1230 p.estimated_hours = p.leaves.sum(:estimated_hours).to_f
Chris@0 1231 p.estimated_hours = nil if p.estimated_hours == 0.0
Chris@441 1232
Chris@0 1233 # ancestors will be recursively updated
Chris@1115 1234 p.save(:validate => false)
Chris@0 1235 end
Chris@0 1236 end
Chris@441 1237
Chris@0 1238 # Update issues so their versions are not pointing to a
Chris@0 1239 # fixed_version that is not shared with the issue's project
Chris@0 1240 def self.update_versions(conditions=nil)
Chris@0 1241 # Only need to update issues with a fixed_version from
Chris@0 1242 # a different project and that is not systemwide shared
Chris@1115 1243 Issue.scoped(:conditions => conditions).all(
Chris@1115 1244 :conditions => "#{Issue.table_name}.fixed_version_id IS NOT NULL" +
Chris@1115 1245 " AND #{Issue.table_name}.project_id <> #{Version.table_name}.project_id" +
Chris@1115 1246 " AND #{Version.table_name}.sharing <> 'system'",
Chris@1115 1247 :include => [:project, :fixed_version]
Chris@1115 1248 ).each do |issue|
Chris@0 1249 next if issue.project.nil? || issue.fixed_version.nil?
Chris@0 1250 unless issue.project.shared_versions.include?(issue.fixed_version)
Chris@0 1251 issue.init_journal(User.current)
Chris@0 1252 issue.fixed_version = nil
Chris@0 1253 issue.save
Chris@0 1254 end
Chris@0 1255 end
Chris@0 1256 end
Chris@441 1257
Chris@1115 1258 # Callback on file attachment
Chris@909 1259 def attachment_added(obj)
Chris@909 1260 if @current_journal && !obj.new_record?
Chris@909 1261 @current_journal.details << JournalDetail.new(:property => 'attachment', :prop_key => obj.id, :value => obj.filename)
Chris@909 1262 end
Chris@909 1263 end
Chris@909 1264
Chris@909 1265 # Callback on attachment deletion
Chris@0 1266 def attachment_removed(obj)
Chris@1115 1267 if @current_journal && !obj.new_record?
Chris@1115 1268 @current_journal.details << JournalDetail.new(:property => 'attachment', :prop_key => obj.id, :old_value => obj.filename)
Chris@1115 1269 @current_journal.save
Chris@1115 1270 end
Chris@0 1271 end
Chris@441 1272
Chris@0 1273 # Default assignment based on category
Chris@0 1274 def default_assign
Chris@0 1275 if assigned_to.nil? && category && category.assigned_to
Chris@0 1276 self.assigned_to = category.assigned_to
Chris@0 1277 end
Chris@0 1278 end
Chris@0 1279
Chris@0 1280 # Updates start/due dates of following issues
Chris@0 1281 def reschedule_following_issues
Chris@0 1282 if start_date_changed? || due_date_changed?
Chris@0 1283 relations_from.each do |relation|
Chris@0 1284 relation.set_issue_to_dates
Chris@0 1285 end
Chris@0 1286 end
Chris@0 1287 end
Chris@0 1288
Chris@0 1289 # Closes duplicates if the issue is being closed
Chris@0 1290 def close_duplicates
Chris@0 1291 if closing?
Chris@0 1292 duplicates.each do |duplicate|
Chris@0 1293 # Reload is need in case the duplicate was updated by a previous duplicate
Chris@0 1294 duplicate.reload
Chris@0 1295 # Don't re-close it if it's already closed
Chris@0 1296 next if duplicate.closed?
Chris@0 1297 # Same user and notes
Chris@0 1298 if @current_journal
Chris@0 1299 duplicate.init_journal(@current_journal.user, @current_journal.notes)
Chris@0 1300 end
Chris@0 1301 duplicate.update_attribute :status, self.status
Chris@0 1302 end
Chris@0 1303 end
Chris@0 1304 end
Chris@441 1305
Chris@1115 1306 # Make sure updated_on is updated when adding a note
Chris@1115 1307 def force_updated_on_change
Chris@1115 1308 if @current_journal
Chris@1115 1309 self.updated_on = current_time_from_proper_timezone
Chris@1115 1310 end
Chris@1115 1311 end
Chris@1115 1312
Chris@0 1313 # Saves the changes in a Journal
Chris@0 1314 # Called after_save
Chris@0 1315 def create_journal
Chris@0 1316 if @current_journal
Chris@0 1317 # attributes changes
Chris@1115 1318 if @attributes_before_change
Chris@1115 1319 (Issue.column_names - %w(id root_id lft rgt lock_version created_on updated_on)).each {|c|
Chris@1115 1320 before = @attributes_before_change[c]
Chris@1115 1321 after = send(c)
Chris@1115 1322 next if before == after || (before.blank? && after.blank?)
Chris@1115 1323 @current_journal.details << JournalDetail.new(:property => 'attr',
Chris@1115 1324 :prop_key => c,
Chris@1115 1325 :old_value => before,
Chris@1115 1326 :value => after)
Chris@1115 1327 }
Chris@1115 1328 end
Chris@1115 1329 if @custom_values_before_change
Chris@1115 1330 # custom fields changes
Chris@1115 1331 custom_field_values.each {|c|
Chris@1115 1332 before = @custom_values_before_change[c.custom_field_id]
Chris@1115 1333 after = c.value
Chris@1115 1334 next if before == after || (before.blank? && after.blank?)
Chris@1115 1335
Chris@1115 1336 if before.is_a?(Array) || after.is_a?(Array)
Chris@1115 1337 before = [before] unless before.is_a?(Array)
Chris@1115 1338 after = [after] unless after.is_a?(Array)
Chris@1115 1339
Chris@1115 1340 # values removed
Chris@1115 1341 (before - after).reject(&:blank?).each do |value|
Chris@1115 1342 @current_journal.details << JournalDetail.new(:property => 'cf',
Chris@1115 1343 :prop_key => c.custom_field_id,
Chris@1115 1344 :old_value => value,
Chris@1115 1345 :value => nil)
Chris@1115 1346 end
Chris@1115 1347 # values added
Chris@1115 1348 (after - before).reject(&:blank?).each do |value|
Chris@1115 1349 @current_journal.details << JournalDetail.new(:property => 'cf',
Chris@1115 1350 :prop_key => c.custom_field_id,
Chris@1115 1351 :old_value => nil,
Chris@1115 1352 :value => value)
Chris@1115 1353 end
Chris@1115 1354 else
Chris@1115 1355 @current_journal.details << JournalDetail.new(:property => 'cf',
Chris@1115 1356 :prop_key => c.custom_field_id,
Chris@1115 1357 :old_value => before,
Chris@1115 1358 :value => after)
Chris@1115 1359 end
Chris@1115 1360 }
Chris@1115 1361 end
Chris@0 1362 @current_journal.save
Chris@0 1363 # reset current journal
Chris@0 1364 init_journal @current_journal.user, @current_journal.notes
Chris@0 1365 end
Chris@0 1366 end
Chris@0 1367
Chris@0 1368 # Query generator for selecting groups of issue counts for a project
Chris@0 1369 # based on specific criteria
Chris@0 1370 #
Chris@0 1371 # Options
Chris@0 1372 # * project - Project to search in.
Chris@0 1373 # * field - String. Issue field to key off of in the grouping.
Chris@0 1374 # * joins - String. The table name to join against.
Chris@0 1375 def self.count_and_group_by(options)
Chris@0 1376 project = options.delete(:project)
Chris@0 1377 select_field = options.delete(:field)
Chris@0 1378 joins = options.delete(:joins)
Chris@0 1379
Chris@441 1380 where = "#{Issue.table_name}.#{select_field}=j.id"
Chris@441 1381
Chris@0 1382 ActiveRecord::Base.connection.select_all("select s.id as status_id,
Chris@0 1383 s.is_closed as closed,
Chris@0 1384 j.id as #{select_field},
Chris@441 1385 count(#{Issue.table_name}.id) as total
Chris@0 1386 from
Chris@441 1387 #{Issue.table_name}, #{Project.table_name}, #{IssueStatus.table_name} s, #{joins} j
Chris@0 1388 where
Chris@441 1389 #{Issue.table_name}.status_id=s.id
Chris@0 1390 and #{where}
Chris@441 1391 and #{Issue.table_name}.project_id=#{Project.table_name}.id
Chris@441 1392 and #{visible_condition(User.current, :project => project)}
Chris@0 1393 group by s.id, s.is_closed, j.id")
Chris@0 1394 end
Chris@0 1395 end