annotate .svn/pristine/b5/b582b98d925d01a2fdc9c5e286bdae900edab917.svn-base @ 1295:622f24f53b42 redmine-2.3

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