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