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