##// END OF EJS Templates
Initialize watcher_user_ids for new records to prevent useless queries on each #watched_by?....
Jean-Philippe Lang -
r8434:906fcd290cac
parent child
Show More
@@ -1,1038 +1,1039
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2011 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
21 21 belongs_to :project
22 22 belongs_to :tracker
23 23 belongs_to :status, :class_name => 'IssueStatus', :foreign_key => 'status_id'
24 24 belongs_to :author, :class_name => 'User', :foreign_key => 'author_id'
25 25 belongs_to :assigned_to, :class_name => 'Principal', :foreign_key => 'assigned_to_id'
26 26 belongs_to :fixed_version, :class_name => 'Version', :foreign_key => 'fixed_version_id'
27 27 belongs_to :priority, :class_name => 'IssuePriority', :foreign_key => 'priority_id'
28 28 belongs_to :category, :class_name => 'IssueCategory', :foreign_key => 'category_id'
29 29
30 30 has_many :journals, :as => :journalized, :dependent => :destroy
31 31 has_many :time_entries, :dependent => :delete_all
32 32 has_and_belongs_to_many :changesets, :order => "#{Changeset.table_name}.committed_on ASC, #{Changeset.table_name}.id ASC"
33 33
34 34 has_many :relations_from, :class_name => 'IssueRelation', :foreign_key => 'issue_from_id', :dependent => :delete_all
35 35 has_many :relations_to, :class_name => 'IssueRelation', :foreign_key => 'issue_to_id', :dependent => :delete_all
36 36
37 37 acts_as_nested_set :scope => 'root_id', :dependent => :destroy
38 38 acts_as_attachable :after_add => :attachment_added, :after_remove => :attachment_removed
39 39 acts_as_customizable
40 40 acts_as_watchable
41 41 acts_as_searchable :columns => ['subject', "#{table_name}.description", "#{Journal.table_name}.notes"],
42 42 :include => [:project, :journals],
43 43 # sort by id so that limited eager loading doesn't break with postgresql
44 44 :order_column => "#{table_name}.id"
45 45 acts_as_event :title => Proc.new {|o| "#{o.tracker.name} ##{o.id} (#{o.status}): #{o.subject}"},
46 46 :url => Proc.new {|o| {:controller => 'issues', :action => 'show', :id => o.id}},
47 47 :type => Proc.new {|o| 'issue' + (o.closed? ? ' closed' : '') }
48 48
49 49 acts_as_activity_provider :find_options => {:include => [:project, :author, :tracker]},
50 50 :author_key => :author_id
51 51
52 52 DONE_RATIO_OPTIONS = %w(issue_field issue_status)
53 53
54 54 attr_reader :current_journal
55 55
56 56 validates_presence_of :subject, :priority, :project, :tracker, :author, :status
57 57
58 58 validates_length_of :subject, :maximum => 255
59 59 validates_inclusion_of :done_ratio, :in => 0..100
60 60 validates_numericality_of :estimated_hours, :allow_nil => true
61 61 validate :validate_issue
62 62
63 63 named_scope :visible, lambda {|*args| { :include => :project,
64 64 :conditions => Issue.visible_condition(args.shift || User.current, *args) } }
65 65
66 66 named_scope :open, lambda {|*args|
67 67 is_closed = args.size > 0 ? !args.first : false
68 68 {:conditions => ["#{IssueStatus.table_name}.is_closed = ?", is_closed], :include => :status}
69 69 }
70 70
71 71 named_scope :recently_updated, :order => "#{Issue.table_name}.updated_on DESC"
72 72 named_scope :with_limit, lambda { |limit| { :limit => limit} }
73 73 named_scope :on_active_project, :include => [:status, :project, :tracker],
74 74 :conditions => ["#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"]
75 75
76 76 before_create :default_assign
77 77 before_save :close_duplicates, :update_done_ratio_from_issue_status
78 78 after_save {|issue| issue.send :after_project_change if !issue.id_changed? && issue.project_id_changed?}
79 79 after_save :reschedule_following_issues, :update_nested_set_attributes, :update_parent_attributes, :create_journal
80 80 after_destroy :update_parent_attributes
81 81
82 82 # Returns a SQL conditions string used to find all issues visible by the specified user
83 83 def self.visible_condition(user, options={})
84 84 Project.allowed_to_condition(user, :view_issues, options) do |role, user|
85 85 case role.issues_visibility
86 86 when 'all'
87 87 nil
88 88 when 'default'
89 89 user_ids = [user.id] + user.groups.map(&:id)
90 90 "(#{table_name}.is_private = #{connection.quoted_false} OR #{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id IN (#{user_ids.join(',')}))"
91 91 when 'own'
92 92 user_ids = [user.id] + user.groups.map(&:id)
93 93 "(#{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id IN (#{user_ids.join(',')}))"
94 94 else
95 95 '1=0'
96 96 end
97 97 end
98 98 end
99 99
100 100 # Returns true if usr or current user is allowed to view the issue
101 101 def visible?(usr=nil)
102 102 (usr || User.current).allowed_to?(:view_issues, self.project) do |role, user|
103 103 case role.issues_visibility
104 104 when 'all'
105 105 true
106 106 when 'default'
107 107 !self.is_private? || self.author == user || user.is_or_belongs_to?(assigned_to)
108 108 when 'own'
109 109 self.author == user || user.is_or_belongs_to?(assigned_to)
110 110 else
111 111 false
112 112 end
113 113 end
114 114 end
115 115
116 116 def initialize(attributes=nil, *args)
117 117 super
118 118 if new_record?
119 119 # set default values for new records only
120 120 self.status ||= IssueStatus.default
121 121 self.priority ||= IssuePriority.default
122 self.watcher_user_ids = []
122 123 end
123 124 end
124 125
125 126 # Overrides Redmine::Acts::Customizable::InstanceMethods#available_custom_fields
126 127 def available_custom_fields
127 128 (project && tracker) ? (project.all_issue_custom_fields & tracker.custom_fields.all) : []
128 129 end
129 130
130 131 # Copies attributes from another issue, arg can be an id or an Issue
131 132 def copy_from(arg)
132 133 issue = arg.is_a?(Issue) ? arg : Issue.visible.find(arg)
133 134 self.attributes = issue.attributes.dup.except("id", "root_id", "parent_id", "lft", "rgt", "created_on", "updated_on")
134 135 self.custom_field_values = issue.custom_field_values.inject({}) {|h,v| h[v.custom_field_id] = v.value; h}
135 136 self.status = issue.status
136 137 self.author = User.current
137 138 @copied_from = issue
138 139 self
139 140 end
140 141
141 142 # Returns an unsaved copy of the issue
142 143 def copy(attributes=nil)
143 144 copy = self.class.new.copy_from(self)
144 145 copy.attributes = attributes if attributes
145 146 copy
146 147 end
147 148
148 149 # Returns true if the issue is a copy
149 150 def copy?
150 151 @copied_from.present?
151 152 end
152 153
153 154 # Moves/copies an issue to a new project and tracker
154 155 # Returns the moved/copied issue on success, false on failure
155 156 def move_to_project(new_project, new_tracker=nil, options={})
156 157 ActiveSupport::Deprecation.warn "Issue#move_to_project is deprecated, use #project= instead."
157 158
158 159 if options[:copy]
159 160 issue = self.copy
160 161 else
161 162 issue = self
162 163 end
163 164
164 165 issue.init_journal(User.current, options[:notes])
165 166
166 167 # Preserve previous behaviour
167 168 # #move_to_project doesn't change tracker automatically
168 169 issue.send :project=, new_project, true
169 170 if new_tracker
170 171 issue.tracker = new_tracker
171 172 end
172 173 # Allow bulk setting of attributes on the issue
173 174 if options[:attributes]
174 175 issue.attributes = options[:attributes]
175 176 end
176 177
177 178 issue.save ? issue : false
178 179 end
179 180
180 181 def status_id=(sid)
181 182 self.status = nil
182 183 write_attribute(:status_id, sid)
183 184 end
184 185
185 186 def priority_id=(pid)
186 187 self.priority = nil
187 188 write_attribute(:priority_id, pid)
188 189 end
189 190
190 191 def category_id=(cid)
191 192 self.category = nil
192 193 write_attribute(:category_id, cid)
193 194 end
194 195
195 196 def fixed_version_id=(vid)
196 197 self.fixed_version = nil
197 198 write_attribute(:fixed_version_id, vid)
198 199 end
199 200
200 201 def tracker_id=(tid)
201 202 self.tracker = nil
202 203 result = write_attribute(:tracker_id, tid)
203 204 @custom_field_values = nil
204 205 result
205 206 end
206 207
207 208 def project_id=(project_id)
208 209 if project_id.to_s != self.project_id.to_s
209 210 self.project = (project_id.present? ? Project.find_by_id(project_id) : nil)
210 211 end
211 212 end
212 213
213 214 def project=(project, keep_tracker=false)
214 215 project_was = self.project
215 216 write_attribute(:project_id, project ? project.id : nil)
216 217 association_instance_set('project', project)
217 218 if project_was && project && project_was != project
218 219 unless keep_tracker || project.trackers.include?(tracker)
219 220 self.tracker = project.trackers.first
220 221 end
221 222 # Reassign to the category with same name if any
222 223 if category
223 224 self.category = project.issue_categories.find_by_name(category.name)
224 225 end
225 226 # Keep the fixed_version if it's still valid in the new_project
226 227 if fixed_version && fixed_version.project != project && !project.shared_versions.include?(fixed_version)
227 228 self.fixed_version = nil
228 229 end
229 230 if parent && parent.project_id != project_id
230 231 self.parent_issue_id = nil
231 232 end
232 233 @custom_field_values = nil
233 234 end
234 235 end
235 236
236 237 def description=(arg)
237 238 if arg.is_a?(String)
238 239 arg = arg.gsub(/(\r\n|\n|\r)/, "\r\n")
239 240 end
240 241 write_attribute(:description, arg)
241 242 end
242 243
243 244 # Overrides attributes= so that project and tracker get assigned first
244 245 def attributes_with_project_and_tracker_first=(new_attributes, *args)
245 246 return if new_attributes.nil?
246 247 attrs = new_attributes.dup
247 248 attrs.stringify_keys!
248 249
249 250 %w(project project_id tracker tracker_id).each do |attr|
250 251 if attrs.has_key?(attr)
251 252 send "#{attr}=", attrs.delete(attr)
252 253 end
253 254 end
254 255 send :attributes_without_project_and_tracker_first=, attrs, *args
255 256 end
256 257 # Do not redefine alias chain on reload (see #4838)
257 258 alias_method_chain(:attributes=, :project_and_tracker_first) unless method_defined?(:attributes_without_project_and_tracker_first=)
258 259
259 260 def estimated_hours=(h)
260 261 write_attribute :estimated_hours, (h.is_a?(String) ? h.to_hours : h)
261 262 end
262 263
263 264 safe_attributes 'project_id',
264 265 :if => lambda {|issue, user|
265 266 if issue.new_record?
266 267 issue.copy?
267 268 elsif user.allowed_to?(:move_issues, issue.project)
268 269 projects = Issue.allowed_target_projects_on_move(user)
269 270 projects.include?(issue.project) && projects.size > 1
270 271 end
271 272 }
272 273
273 274 safe_attributes 'tracker_id',
274 275 'status_id',
275 276 'category_id',
276 277 'assigned_to_id',
277 278 'priority_id',
278 279 'fixed_version_id',
279 280 'subject',
280 281 'description',
281 282 'start_date',
282 283 'due_date',
283 284 'done_ratio',
284 285 'estimated_hours',
285 286 'custom_field_values',
286 287 'custom_fields',
287 288 'lock_version',
288 289 :if => lambda {|issue, user| issue.new_record? || user.allowed_to?(:edit_issues, issue.project) }
289 290
290 291 safe_attributes 'status_id',
291 292 'assigned_to_id',
292 293 'fixed_version_id',
293 294 'done_ratio',
294 295 'lock_version',
295 296 :if => lambda {|issue, user| issue.new_statuses_allowed_to(user).any? }
296 297
297 298 safe_attributes 'watcher_user_ids',
298 299 :if => lambda {|issue, user| issue.new_record? && user.allowed_to?(:add_issue_watchers, issue.project)}
299 300
300 301 safe_attributes 'is_private',
301 302 :if => lambda {|issue, user|
302 303 user.allowed_to?(:set_issues_private, issue.project) ||
303 304 (issue.author == user && user.allowed_to?(:set_own_issues_private, issue.project))
304 305 }
305 306
306 307 safe_attributes 'parent_issue_id',
307 308 :if => lambda {|issue, user| (issue.new_record? || user.allowed_to?(:edit_issues, issue.project)) &&
308 309 user.allowed_to?(:manage_subtasks, issue.project)}
309 310
310 311 # Safely sets attributes
311 312 # Should be called from controllers instead of #attributes=
312 313 # attr_accessible is too rough because we still want things like
313 314 # Issue.new(:project => foo) to work
314 315 def safe_attributes=(attrs, user=User.current)
315 316 return unless attrs.is_a?(Hash)
316 317
317 318 # User can change issue attributes only if he has :edit permission or if a workflow transition is allowed
318 319 attrs = delete_unsafe_attributes(attrs, user)
319 320 return if attrs.empty?
320 321
321 322 # Project and Tracker must be set before since new_statuses_allowed_to depends on it.
322 323 if p = attrs.delete('project_id')
323 324 if allowed_target_projects(user).collect(&:id).include?(p.to_i)
324 325 self.project_id = p
325 326 end
326 327 end
327 328
328 329 if t = attrs.delete('tracker_id')
329 330 self.tracker_id = t
330 331 end
331 332
332 333 if attrs['status_id']
333 334 unless new_statuses_allowed_to(user).collect(&:id).include?(attrs['status_id'].to_i)
334 335 attrs.delete('status_id')
335 336 end
336 337 end
337 338
338 339 unless leaf?
339 340 attrs.reject! {|k,v| %w(priority_id done_ratio start_date due_date estimated_hours).include?(k)}
340 341 end
341 342
342 343 if attrs['parent_issue_id'].present?
343 344 attrs.delete('parent_issue_id') unless Issue.visible(user).exists?(attrs['parent_issue_id'].to_i)
344 345 end
345 346
346 347 # mass-assignment security bypass
347 348 self.send :attributes=, attrs, false
348 349 end
349 350
350 351 def done_ratio
351 352 if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
352 353 status.default_done_ratio
353 354 else
354 355 read_attribute(:done_ratio)
355 356 end
356 357 end
357 358
358 359 def self.use_status_for_done_ratio?
359 360 Setting.issue_done_ratio == 'issue_status'
360 361 end
361 362
362 363 def self.use_field_for_done_ratio?
363 364 Setting.issue_done_ratio == 'issue_field'
364 365 end
365 366
366 367 def validate_issue
367 368 if self.due_date.nil? && @attributes['due_date'] && !@attributes['due_date'].empty?
368 369 errors.add :due_date, :not_a_date
369 370 end
370 371
371 372 if self.due_date and self.start_date and self.due_date < self.start_date
372 373 errors.add :due_date, :greater_than_start_date
373 374 end
374 375
375 376 if start_date && soonest_start && start_date < soonest_start
376 377 errors.add :start_date, :invalid
377 378 end
378 379
379 380 if fixed_version
380 381 if !assignable_versions.include?(fixed_version)
381 382 errors.add :fixed_version_id, :inclusion
382 383 elsif reopened? && fixed_version.closed?
383 384 errors.add :base, I18n.t(:error_can_not_reopen_issue_on_closed_version)
384 385 end
385 386 end
386 387
387 388 # Checks that the issue can not be added/moved to a disabled tracker
388 389 if project && (tracker_id_changed? || project_id_changed?)
389 390 unless project.trackers.include?(tracker)
390 391 errors.add :tracker_id, :inclusion
391 392 end
392 393 end
393 394
394 395 # Checks parent issue assignment
395 396 if @parent_issue
396 397 if @parent_issue.project_id != project_id
397 398 errors.add :parent_issue_id, :not_same_project
398 399 elsif !new_record?
399 400 # moving an existing issue
400 401 if @parent_issue.root_id != root_id
401 402 # we can always move to another tree
402 403 elsif move_possible?(@parent_issue)
403 404 # move accepted inside tree
404 405 else
405 406 errors.add :parent_issue_id, :not_a_valid_parent
406 407 end
407 408 end
408 409 end
409 410 end
410 411
411 412 # Set the done_ratio using the status if that setting is set. This will keep the done_ratios
412 413 # even if the user turns off the setting later
413 414 def update_done_ratio_from_issue_status
414 415 if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
415 416 self.done_ratio = status.default_done_ratio
416 417 end
417 418 end
418 419
419 420 def init_journal(user, notes = "")
420 421 @current_journal ||= Journal.new(:journalized => self, :user => user, :notes => notes)
421 422 if new_record?
422 423 @current_journal.notify = false
423 424 else
424 425 @attributes_before_change = attributes.dup
425 426 @custom_values_before_change = {}
426 427 self.custom_values.each {|c| @custom_values_before_change.store c.custom_field_id, c.value }
427 428 end
428 429 # Make sure updated_on is updated when adding a note.
429 430 updated_on_will_change!
430 431 @current_journal
431 432 end
432 433
433 434 # Return true if the issue is closed, otherwise false
434 435 def closed?
435 436 self.status.is_closed?
436 437 end
437 438
438 439 # Return true if the issue is being reopened
439 440 def reopened?
440 441 if !new_record? && status_id_changed?
441 442 status_was = IssueStatus.find_by_id(status_id_was)
442 443 status_new = IssueStatus.find_by_id(status_id)
443 444 if status_was && status_new && status_was.is_closed? && !status_new.is_closed?
444 445 return true
445 446 end
446 447 end
447 448 false
448 449 end
449 450
450 451 # Return true if the issue is being closed
451 452 def closing?
452 453 if !new_record? && status_id_changed?
453 454 status_was = IssueStatus.find_by_id(status_id_was)
454 455 status_new = IssueStatus.find_by_id(status_id)
455 456 if status_was && status_new && !status_was.is_closed? && status_new.is_closed?
456 457 return true
457 458 end
458 459 end
459 460 false
460 461 end
461 462
462 463 # Returns true if the issue is overdue
463 464 def overdue?
464 465 !due_date.nil? && (due_date < Date.today) && !status.is_closed?
465 466 end
466 467
467 468 # Is the amount of work done less than it should for the due date
468 469 def behind_schedule?
469 470 return false if start_date.nil? || due_date.nil?
470 471 done_date = start_date + ((due_date - start_date+1)* done_ratio/100).floor
471 472 return done_date <= Date.today
472 473 end
473 474
474 475 # Does this issue have children?
475 476 def children?
476 477 !leaf?
477 478 end
478 479
479 480 # Users the issue can be assigned to
480 481 def assignable_users
481 482 users = project.assignable_users
482 483 users << author if author
483 484 users << assigned_to if assigned_to
484 485 users.uniq.sort
485 486 end
486 487
487 488 # Versions that the issue can be assigned to
488 489 def assignable_versions
489 490 @assignable_versions ||= (project.shared_versions.open + [Version.find_by_id(fixed_version_id_was)]).compact.uniq.sort
490 491 end
491 492
492 493 # Returns true if this issue is blocked by another issue that is still open
493 494 def blocked?
494 495 !relations_to.detect {|ir| ir.relation_type == 'blocks' && !ir.issue_from.closed?}.nil?
495 496 end
496 497
497 498 # Returns an array of status that user is able to apply
498 499 def new_statuses_allowed_to(user, include_default=false)
499 500 statuses = status.find_new_statuses_allowed_to(
500 501 user.roles_for_project(project),
501 502 tracker,
502 503 author == user,
503 504 assigned_to_id_changed? ? assigned_to_id_was == user.id : assigned_to_id == user.id
504 505 )
505 506 statuses << status unless statuses.empty?
506 507 statuses << IssueStatus.default if include_default
507 508 statuses = statuses.uniq.sort
508 509 blocked? ? statuses.reject {|s| s.is_closed?} : statuses
509 510 end
510 511
511 512 # Returns the mail adresses of users that should be notified
512 513 def recipients
513 514 notified = project.notified_users
514 515 # Author and assignee are always notified unless they have been
515 516 # locked or don't want to be notified
516 517 notified << author if author && author.active? && author.notify_about?(self)
517 518 if assigned_to
518 519 if assigned_to.is_a?(Group)
519 520 notified += assigned_to.users.select {|u| u.active? && u.notify_about?(self)}
520 521 else
521 522 notified << assigned_to if assigned_to.active? && assigned_to.notify_about?(self)
522 523 end
523 524 end
524 525 notified.uniq!
525 526 # Remove users that can not view the issue
526 527 notified.reject! {|user| !visible?(user)}
527 528 notified.collect(&:mail)
528 529 end
529 530
530 531 # Returns the number of hours spent on this issue
531 532 def spent_hours
532 533 @spent_hours ||= time_entries.sum(:hours) || 0
533 534 end
534 535
535 536 # Returns the total number of hours spent on this issue and its descendants
536 537 #
537 538 # Example:
538 539 # spent_hours => 0.0
539 540 # spent_hours => 50.2
540 541 def total_spent_hours
541 542 @total_spent_hours ||= self_and_descendants.sum("#{TimeEntry.table_name}.hours",
542 543 :joins => "LEFT JOIN #{TimeEntry.table_name} ON #{TimeEntry.table_name}.issue_id = #{Issue.table_name}.id").to_f || 0.0
543 544 end
544 545
545 546 def relations
546 547 @relations ||= (relations_from + relations_to).sort
547 548 end
548 549
549 550 # Preloads relations for a collection of issues
550 551 def self.load_relations(issues)
551 552 if issues.any?
552 553 relations = IssueRelation.all(:conditions => ["issue_from_id IN (:ids) OR issue_to_id IN (:ids)", {:ids => issues.map(&:id)}])
553 554 issues.each do |issue|
554 555 issue.instance_variable_set "@relations", relations.select {|r| r.issue_from_id == issue.id || r.issue_to_id == issue.id}
555 556 end
556 557 end
557 558 end
558 559
559 560 # Preloads visible spent time for a collection of issues
560 561 def self.load_visible_spent_hours(issues, user=User.current)
561 562 if issues.any?
562 563 hours_by_issue_id = TimeEntry.visible(user).sum(:hours, :group => :issue_id)
563 564 issues.each do |issue|
564 565 issue.instance_variable_set "@spent_hours", (hours_by_issue_id[issue.id] || 0)
565 566 end
566 567 end
567 568 end
568 569
569 570 # Finds an issue relation given its id.
570 571 def find_relation(relation_id)
571 572 IssueRelation.find(relation_id, :conditions => ["issue_to_id = ? OR issue_from_id = ?", id, id])
572 573 end
573 574
574 575 def all_dependent_issues(except=[])
575 576 except << self
576 577 dependencies = []
577 578 relations_from.each do |relation|
578 579 if relation.issue_to && !except.include?(relation.issue_to)
579 580 dependencies << relation.issue_to
580 581 dependencies += relation.issue_to.all_dependent_issues(except)
581 582 end
582 583 end
583 584 dependencies
584 585 end
585 586
586 587 # Returns an array of issues that duplicate this one
587 588 def duplicates
588 589 relations_to.select {|r| r.relation_type == IssueRelation::TYPE_DUPLICATES}.collect {|r| r.issue_from}
589 590 end
590 591
591 592 # Returns the due date or the target due date if any
592 593 # Used on gantt chart
593 594 def due_before
594 595 due_date || (fixed_version ? fixed_version.effective_date : nil)
595 596 end
596 597
597 598 # Returns the time scheduled for this issue.
598 599 #
599 600 # Example:
600 601 # Start Date: 2/26/09, End Date: 3/04/09
601 602 # duration => 6
602 603 def duration
603 604 (start_date && due_date) ? due_date - start_date : 0
604 605 end
605 606
606 607 def soonest_start
607 608 @soonest_start ||= (
608 609 relations_to.collect{|relation| relation.successor_soonest_start} +
609 610 ancestors.collect(&:soonest_start)
610 611 ).compact.max
611 612 end
612 613
613 614 def reschedule_after(date)
614 615 return if date.nil?
615 616 if leaf?
616 617 if start_date.nil? || start_date < date
617 618 self.start_date, self.due_date = date, date + duration
618 619 save
619 620 end
620 621 else
621 622 leaves.each do |leaf|
622 623 leaf.reschedule_after(date)
623 624 end
624 625 end
625 626 end
626 627
627 628 def <=>(issue)
628 629 if issue.nil?
629 630 -1
630 631 elsif root_id != issue.root_id
631 632 (root_id || 0) <=> (issue.root_id || 0)
632 633 else
633 634 (lft || 0) <=> (issue.lft || 0)
634 635 end
635 636 end
636 637
637 638 def to_s
638 639 "#{tracker} ##{id}: #{subject}"
639 640 end
640 641
641 642 # Returns a string of css classes that apply to the issue
642 643 def css_classes
643 644 s = "issue status-#{status.position} priority-#{priority.position}"
644 645 s << ' closed' if closed?
645 646 s << ' overdue' if overdue?
646 647 s << ' child' if child?
647 648 s << ' parent' unless leaf?
648 649 s << ' private' if is_private?
649 650 s << ' created-by-me' if User.current.logged? && author_id == User.current.id
650 651 s << ' assigned-to-me' if User.current.logged? && assigned_to_id == User.current.id
651 652 s
652 653 end
653 654
654 655 # Saves an issue, time_entry, attachments, and a journal from the parameters
655 656 # Returns false if save fails
656 657 def save_issue_with_child_records(params, existing_time_entry=nil)
657 658 Issue.transaction do
658 659 if params[:time_entry] && (params[:time_entry][:hours].present? || params[:time_entry][:comments].present?) && User.current.allowed_to?(:log_time, project)
659 660 @time_entry = existing_time_entry || TimeEntry.new
660 661 @time_entry.project = project
661 662 @time_entry.issue = self
662 663 @time_entry.user = User.current
663 664 @time_entry.spent_on = User.current.today
664 665 @time_entry.attributes = params[:time_entry]
665 666 self.time_entries << @time_entry
666 667 end
667 668
668 669 if valid?
669 670 attachments = Attachment.attach_files(self, params[:attachments])
670 671 # TODO: Rename hook
671 672 Redmine::Hook.call_hook(:controller_issues_edit_before_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
672 673 begin
673 674 if save
674 675 # TODO: Rename hook
675 676 Redmine::Hook.call_hook(:controller_issues_edit_after_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
676 677 else
677 678 raise ActiveRecord::Rollback
678 679 end
679 680 rescue ActiveRecord::StaleObjectError
680 681 attachments[:files].each(&:destroy)
681 682 errors.add :base, l(:notice_locking_conflict)
682 683 raise ActiveRecord::Rollback
683 684 end
684 685 end
685 686 end
686 687 end
687 688
688 689 # Unassigns issues from +version+ if it's no longer shared with issue's project
689 690 def self.update_versions_from_sharing_change(version)
690 691 # Update issues assigned to the version
691 692 update_versions(["#{Issue.table_name}.fixed_version_id = ?", version.id])
692 693 end
693 694
694 695 # Unassigns issues from versions that are no longer shared
695 696 # after +project+ was moved
696 697 def self.update_versions_from_hierarchy_change(project)
697 698 moved_project_ids = project.self_and_descendants.reload.collect(&:id)
698 699 # Update issues of the moved projects and issues assigned to a version of a moved project
699 700 Issue.update_versions(["#{Version.table_name}.project_id IN (?) OR #{Issue.table_name}.project_id IN (?)", moved_project_ids, moved_project_ids])
700 701 end
701 702
702 703 def parent_issue_id=(arg)
703 704 parent_issue_id = arg.blank? ? nil : arg.to_i
704 705 if parent_issue_id && @parent_issue = Issue.find_by_id(parent_issue_id)
705 706 @parent_issue.id
706 707 else
707 708 @parent_issue = nil
708 709 nil
709 710 end
710 711 end
711 712
712 713 def parent_issue_id
713 714 if instance_variable_defined? :@parent_issue
714 715 @parent_issue.nil? ? nil : @parent_issue.id
715 716 else
716 717 parent_id
717 718 end
718 719 end
719 720
720 721 # Extracted from the ReportsController.
721 722 def self.by_tracker(project)
722 723 count_and_group_by(:project => project,
723 724 :field => 'tracker_id',
724 725 :joins => Tracker.table_name)
725 726 end
726 727
727 728 def self.by_version(project)
728 729 count_and_group_by(:project => project,
729 730 :field => 'fixed_version_id',
730 731 :joins => Version.table_name)
731 732 end
732 733
733 734 def self.by_priority(project)
734 735 count_and_group_by(:project => project,
735 736 :field => 'priority_id',
736 737 :joins => IssuePriority.table_name)
737 738 end
738 739
739 740 def self.by_category(project)
740 741 count_and_group_by(:project => project,
741 742 :field => 'category_id',
742 743 :joins => IssueCategory.table_name)
743 744 end
744 745
745 746 def self.by_assigned_to(project)
746 747 count_and_group_by(:project => project,
747 748 :field => 'assigned_to_id',
748 749 :joins => User.table_name)
749 750 end
750 751
751 752 def self.by_author(project)
752 753 count_and_group_by(:project => project,
753 754 :field => 'author_id',
754 755 :joins => User.table_name)
755 756 end
756 757
757 758 def self.by_subproject(project)
758 759 ActiveRecord::Base.connection.select_all("select s.id as status_id,
759 760 s.is_closed as closed,
760 761 #{Issue.table_name}.project_id as project_id,
761 762 count(#{Issue.table_name}.id) as total
762 763 from
763 764 #{Issue.table_name}, #{Project.table_name}, #{IssueStatus.table_name} s
764 765 where
765 766 #{Issue.table_name}.status_id=s.id
766 767 and #{Issue.table_name}.project_id = #{Project.table_name}.id
767 768 and #{visible_condition(User.current, :project => project, :with_subprojects => true)}
768 769 and #{Issue.table_name}.project_id <> #{project.id}
769 770 group by s.id, s.is_closed, #{Issue.table_name}.project_id") if project.descendants.active.any?
770 771 end
771 772 # End ReportsController extraction
772 773
773 774 # Returns an array of projects that user can assign the issue to
774 775 def allowed_target_projects(user=User.current)
775 776 if new_record?
776 777 Project.all(:conditions => Project.allowed_to_condition(user, :add_issues))
777 778 else
778 779 self.class.allowed_target_projects_on_move(user)
779 780 end
780 781 end
781 782
782 783 # Returns an array of projects that user can move issues to
783 784 def self.allowed_target_projects_on_move(user=User.current)
784 785 projects = []
785 786 if user.admin?
786 787 # admin is allowed to move issues to any active (visible) project
787 788 projects = Project.visible(user).all
788 789 elsif user.logged?
789 790 if Role.non_member.allowed_to?(:move_issues)
790 791 projects = Project.visible(user).all
791 792 else
792 793 user.memberships.each {|m| projects << m.project if m.roles.detect {|r| r.allowed_to?(:move_issues)}}
793 794 end
794 795 end
795 796 projects
796 797 end
797 798
798 799 private
799 800
800 801 def after_project_change
801 802 # Update project_id on related time entries
802 803 TimeEntry.update_all(["project_id = ?", project_id], {:issue_id => id})
803 804
804 805 # Delete issue relations
805 806 unless Setting.cross_project_issue_relations?
806 807 relations_from.clear
807 808 relations_to.clear
808 809 end
809 810
810 811 # Move subtasks
811 812 children.each do |child|
812 813 # Change project and keep project
813 814 child.send :project=, project, true
814 815 unless child.save
815 816 raise ActiveRecord::Rollback
816 817 end
817 818 end
818 819 end
819 820
820 821 def update_nested_set_attributes
821 822 if root_id.nil?
822 823 # issue was just created
823 824 self.root_id = (@parent_issue.nil? ? id : @parent_issue.root_id)
824 825 set_default_left_and_right
825 826 Issue.update_all("root_id = #{root_id}, lft = #{lft}, rgt = #{rgt}", ["id = ?", id])
826 827 if @parent_issue
827 828 move_to_child_of(@parent_issue)
828 829 end
829 830 reload
830 831 elsif parent_issue_id != parent_id
831 832 former_parent_id = parent_id
832 833 # moving an existing issue
833 834 if @parent_issue && @parent_issue.root_id == root_id
834 835 # inside the same tree
835 836 move_to_child_of(@parent_issue)
836 837 else
837 838 # to another tree
838 839 unless root?
839 840 move_to_right_of(root)
840 841 reload
841 842 end
842 843 old_root_id = root_id
843 844 self.root_id = (@parent_issue.nil? ? id : @parent_issue.root_id )
844 845 target_maxright = nested_set_scope.maximum(right_column_name) || 0
845 846 offset = target_maxright + 1 - lft
846 847 Issue.update_all("root_id = #{root_id}, lft = lft + #{offset}, rgt = rgt + #{offset}",
847 848 ["root_id = ? AND lft >= ? AND rgt <= ? ", old_root_id, lft, rgt])
848 849 self[left_column_name] = lft + offset
849 850 self[right_column_name] = rgt + offset
850 851 if @parent_issue
851 852 move_to_child_of(@parent_issue)
852 853 end
853 854 end
854 855 reload
855 856 # delete invalid relations of all descendants
856 857 self_and_descendants.each do |issue|
857 858 issue.relations.each do |relation|
858 859 relation.destroy unless relation.valid?
859 860 end
860 861 end
861 862 # update former parent
862 863 recalculate_attributes_for(former_parent_id) if former_parent_id
863 864 end
864 865 remove_instance_variable(:@parent_issue) if instance_variable_defined?(:@parent_issue)
865 866 end
866 867
867 868 def update_parent_attributes
868 869 recalculate_attributes_for(parent_id) if parent_id
869 870 end
870 871
871 872 def recalculate_attributes_for(issue_id)
872 873 if issue_id && p = Issue.find_by_id(issue_id)
873 874 # priority = highest priority of children
874 875 if priority_position = p.children.maximum("#{IssuePriority.table_name}.position", :joins => :priority)
875 876 p.priority = IssuePriority.find_by_position(priority_position)
876 877 end
877 878
878 879 # start/due dates = lowest/highest dates of children
879 880 p.start_date = p.children.minimum(:start_date)
880 881 p.due_date = p.children.maximum(:due_date)
881 882 if p.start_date && p.due_date && p.due_date < p.start_date
882 883 p.start_date, p.due_date = p.due_date, p.start_date
883 884 end
884 885
885 886 # done ratio = weighted average ratio of leaves
886 887 unless Issue.use_status_for_done_ratio? && p.status && p.status.default_done_ratio
887 888 leaves_count = p.leaves.count
888 889 if leaves_count > 0
889 890 average = p.leaves.average(:estimated_hours).to_f
890 891 if average == 0
891 892 average = 1
892 893 end
893 894 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
894 895 progress = done / (average * leaves_count)
895 896 p.done_ratio = progress.round
896 897 end
897 898 end
898 899
899 900 # estimate = sum of leaves estimates
900 901 p.estimated_hours = p.leaves.sum(:estimated_hours).to_f
901 902 p.estimated_hours = nil if p.estimated_hours == 0.0
902 903
903 904 # ancestors will be recursively updated
904 905 p.save(false)
905 906 end
906 907 end
907 908
908 909 # Update issues so their versions are not pointing to a
909 910 # fixed_version that is not shared with the issue's project
910 911 def self.update_versions(conditions=nil)
911 912 # Only need to update issues with a fixed_version from
912 913 # a different project and that is not systemwide shared
913 914 Issue.scoped(:conditions => conditions).all(
914 915 :conditions => "#{Issue.table_name}.fixed_version_id IS NOT NULL" +
915 916 " AND #{Issue.table_name}.project_id <> #{Version.table_name}.project_id" +
916 917 " AND #{Version.table_name}.sharing <> 'system'",
917 918 :include => [:project, :fixed_version]
918 919 ).each do |issue|
919 920 next if issue.project.nil? || issue.fixed_version.nil?
920 921 unless issue.project.shared_versions.include?(issue.fixed_version)
921 922 issue.init_journal(User.current)
922 923 issue.fixed_version = nil
923 924 issue.save
924 925 end
925 926 end
926 927 end
927 928
928 929 # Callback on attachment deletion
929 930 def attachment_added(obj)
930 931 if @current_journal && !obj.new_record?
931 932 @current_journal.details << JournalDetail.new(:property => 'attachment', :prop_key => obj.id, :value => obj.filename)
932 933 end
933 934 end
934 935
935 936 # Callback on attachment deletion
936 937 def attachment_removed(obj)
937 938 journal = init_journal(User.current)
938 939 journal.details << JournalDetail.new(:property => 'attachment',
939 940 :prop_key => obj.id,
940 941 :old_value => obj.filename)
941 942 journal.save
942 943 end
943 944
944 945 # Default assignment based on category
945 946 def default_assign
946 947 if assigned_to.nil? && category && category.assigned_to
947 948 self.assigned_to = category.assigned_to
948 949 end
949 950 end
950 951
951 952 # Updates start/due dates of following issues
952 953 def reschedule_following_issues
953 954 if start_date_changed? || due_date_changed?
954 955 relations_from.each do |relation|
955 956 relation.set_issue_to_dates
956 957 end
957 958 end
958 959 end
959 960
960 961 # Closes duplicates if the issue is being closed
961 962 def close_duplicates
962 963 if closing?
963 964 duplicates.each do |duplicate|
964 965 # Reload is need in case the duplicate was updated by a previous duplicate
965 966 duplicate.reload
966 967 # Don't re-close it if it's already closed
967 968 next if duplicate.closed?
968 969 # Same user and notes
969 970 if @current_journal
970 971 duplicate.init_journal(@current_journal.user, @current_journal.notes)
971 972 end
972 973 duplicate.update_attribute :status, self.status
973 974 end
974 975 end
975 976 end
976 977
977 978 # Saves the changes in a Journal
978 979 # Called after_save
979 980 def create_journal
980 981 if @current_journal
981 982 # attributes changes
982 983 if @attributes_before_change
983 984 (Issue.column_names - %w(id root_id lft rgt lock_version created_on updated_on)).each {|c|
984 985 before = @attributes_before_change[c]
985 986 after = send(c)
986 987 next if before == after || (before.blank? && after.blank?)
987 988 @current_journal.details << JournalDetail.new(:property => 'attr',
988 989 :prop_key => c,
989 990 :old_value => before,
990 991 :value => after)
991 992 }
992 993 end
993 994 if @custom_values_before_change
994 995 # custom fields changes
995 996 custom_values.each {|c|
996 997 before = @custom_values_before_change[c.custom_field_id]
997 998 after = c.value
998 999 next if before == after || (before.blank? && after.blank?)
999 1000 @current_journal.details << JournalDetail.new(:property => 'cf',
1000 1001 :prop_key => c.custom_field_id,
1001 1002 :old_value => before,
1002 1003 :value => after)
1003 1004 }
1004 1005 end
1005 1006 @current_journal.save
1006 1007 # reset current journal
1007 1008 init_journal @current_journal.user, @current_journal.notes
1008 1009 end
1009 1010 end
1010 1011
1011 1012 # Query generator for selecting groups of issue counts for a project
1012 1013 # based on specific criteria
1013 1014 #
1014 1015 # Options
1015 1016 # * project - Project to search in.
1016 1017 # * field - String. Issue field to key off of in the grouping.
1017 1018 # * joins - String. The table name to join against.
1018 1019 def self.count_and_group_by(options)
1019 1020 project = options.delete(:project)
1020 1021 select_field = options.delete(:field)
1021 1022 joins = options.delete(:joins)
1022 1023
1023 1024 where = "#{Issue.table_name}.#{select_field}=j.id"
1024 1025
1025 1026 ActiveRecord::Base.connection.select_all("select s.id as status_id,
1026 1027 s.is_closed as closed,
1027 1028 j.id as #{select_field},
1028 1029 count(#{Issue.table_name}.id) as total
1029 1030 from
1030 1031 #{Issue.table_name}, #{Project.table_name}, #{IssueStatus.table_name} s, #{joins} j
1031 1032 where
1032 1033 #{Issue.table_name}.status_id=s.id
1033 1034 and #{where}
1034 1035 and #{Issue.table_name}.project_id=#{Project.table_name}.id
1035 1036 and #{visible_condition(User.current, :project => project)}
1036 1037 group by s.id, s.is_closed, j.id")
1037 1038 end
1038 1039 end
General Comments 0
You need to be logged in to leave comments. Login now