annotate .svn/pristine/b5/b582b98d925d01a2fdc9c5e286bdae900edab917.svn-base @ 1519:afce8026aaeb redmine-2.4-integration

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