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