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