##// END OF EJS Templates
Merged r11228 from trunk (#12851)....
Jean-Philippe Lang -
r11006:c99eef1aff84
parent child
Show More

The requested changes are too big and content was truncated. Show full diff

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