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