##// END OF EJS Templates
Fixed that entering #nnn as parent task should validate (#11979)....
Jean-Philippe Lang -
r10447:4b6b56863573
parent child
Show More

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

@@ -1,1360 +1,1361
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 unless Issue.visible(user).exists?(attrs['parent_issue_id'].to_i)
419 s = attrs['parent_issue_id'].to_s
420 unless (m = s.match(%r{\A#?(\d+)\z})) && Issue.visible(user).exists?(m[1])
420 421 @invalid_parent_issue_id = attrs.delete('parent_issue_id')
421 422 end
422 423 end
423 424
424 425 if attrs['custom_field_values'].present?
425 426 attrs['custom_field_values'] = attrs['custom_field_values'].reject {|k, v| read_only_attribute_names(user).include? k.to_s}
426 427 end
427 428
428 429 if attrs['custom_fields'].present?
429 430 attrs['custom_fields'] = attrs['custom_fields'].reject {|c| read_only_attribute_names(user).include? c['id'].to_s}
430 431 end
431 432
432 433 # mass-assignment security bypass
433 434 assign_attributes attrs, :without_protection => true
434 435 end
435 436
436 437 def disabled_core_fields
437 438 tracker ? tracker.disabled_core_fields : []
438 439 end
439 440
440 441 # Returns the custom_field_values that can be edited by the given user
441 442 def editable_custom_field_values(user=nil)
442 443 custom_field_values.reject do |value|
443 444 read_only_attribute_names(user).include?(value.custom_field_id.to_s)
444 445 end
445 446 end
446 447
447 448 # Returns the names of attributes that are read-only for user or the current user
448 449 # For users with multiple roles, the read-only fields are the intersection of
449 450 # read-only fields of each role
450 451 # The result is an array of strings where sustom fields are represented with their ids
451 452 #
452 453 # Examples:
453 454 # issue.read_only_attribute_names # => ['due_date', '2']
454 455 # issue.read_only_attribute_names(user) # => []
455 456 def read_only_attribute_names(user=nil)
456 457 workflow_rule_by_attribute(user).reject {|attr, rule| rule != 'readonly'}.keys
457 458 end
458 459
459 460 # Returns the names of required attributes for user or the current user
460 461 # For users with multiple roles, the required fields are the intersection of
461 462 # required fields of each role
462 463 # The result is an array of strings where sustom fields are represented with their ids
463 464 #
464 465 # Examples:
465 466 # issue.required_attribute_names # => ['due_date', '2']
466 467 # issue.required_attribute_names(user) # => []
467 468 def required_attribute_names(user=nil)
468 469 workflow_rule_by_attribute(user).reject {|attr, rule| rule != 'required'}.keys
469 470 end
470 471
471 472 # Returns true if the attribute is required for user
472 473 def required_attribute?(name, user=nil)
473 474 required_attribute_names(user).include?(name.to_s)
474 475 end
475 476
476 477 # Returns a hash of the workflow rule by attribute for the given user
477 478 #
478 479 # Examples:
479 480 # issue.workflow_rule_by_attribute # => {'due_date' => 'required', 'start_date' => 'readonly'}
480 481 def workflow_rule_by_attribute(user=nil)
481 482 return @workflow_rule_by_attribute if @workflow_rule_by_attribute && user.nil?
482 483
483 484 user_real = user || User.current
484 485 roles = user_real.admin ? Role.all : user_real.roles_for_project(project)
485 486 return {} if roles.empty?
486 487
487 488 result = {}
488 489 workflow_permissions = WorkflowPermission.where(:tracker_id => tracker_id, :old_status_id => status_id, :role_id => roles.map(&:id)).all
489 490 if workflow_permissions.any?
490 491 workflow_rules = workflow_permissions.inject({}) do |h, wp|
491 492 h[wp.field_name] ||= []
492 493 h[wp.field_name] << wp.rule
493 494 h
494 495 end
495 496 workflow_rules.each do |attr, rules|
496 497 next if rules.size < roles.size
497 498 uniq_rules = rules.uniq
498 499 if uniq_rules.size == 1
499 500 result[attr] = uniq_rules.first
500 501 else
501 502 result[attr] = 'required'
502 503 end
503 504 end
504 505 end
505 506 @workflow_rule_by_attribute = result if user.nil?
506 507 result
507 508 end
508 509 private :workflow_rule_by_attribute
509 510
510 511 def done_ratio
511 512 if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
512 513 status.default_done_ratio
513 514 else
514 515 read_attribute(:done_ratio)
515 516 end
516 517 end
517 518
518 519 def self.use_status_for_done_ratio?
519 520 Setting.issue_done_ratio == 'issue_status'
520 521 end
521 522
522 523 def self.use_field_for_done_ratio?
523 524 Setting.issue_done_ratio == 'issue_field'
524 525 end
525 526
526 527 def validate_issue
527 528 if self.due_date.nil? && @attributes['due_date'] && !@attributes['due_date'].empty?
528 529 errors.add :due_date, :not_a_date
529 530 end
530 531
531 532 if self.due_date and self.start_date and self.due_date < self.start_date
532 533 errors.add :due_date, :greater_than_start_date
533 534 end
534 535
535 536 if start_date && soonest_start && start_date < soonest_start
536 537 errors.add :start_date, :invalid
537 538 end
538 539
539 540 if fixed_version
540 541 if !assignable_versions.include?(fixed_version)
541 542 errors.add :fixed_version_id, :inclusion
542 543 elsif reopened? && fixed_version.closed?
543 544 errors.add :base, I18n.t(:error_can_not_reopen_issue_on_closed_version)
544 545 end
545 546 end
546 547
547 548 # Checks that the issue can not be added/moved to a disabled tracker
548 549 if project && (tracker_id_changed? || project_id_changed?)
549 550 unless project.trackers.include?(tracker)
550 551 errors.add :tracker_id, :inclusion
551 552 end
552 553 end
553 554
554 555 # Checks parent issue assignment
555 556 if @invalid_parent_issue_id.present?
556 557 errors.add :parent_issue_id, :invalid
557 558 elsif @parent_issue
558 559 if !valid_parent_project?(@parent_issue)
559 560 errors.add :parent_issue_id, :invalid
560 561 elsif !new_record?
561 562 # moving an existing issue
562 563 if @parent_issue.root_id != root_id
563 564 # we can always move to another tree
564 565 elsif move_possible?(@parent_issue)
565 566 # move accepted inside tree
566 567 else
567 568 errors.add :parent_issue_id, :invalid
568 569 end
569 570 end
570 571 end
571 572 end
572 573
573 574 # Validates the issue against additional workflow requirements
574 575 def validate_required_fields
575 576 user = new_record? ? author : current_journal.try(:user)
576 577
577 578 required_attribute_names(user).each do |attribute|
578 579 if attribute =~ /^\d+$/
579 580 attribute = attribute.to_i
580 581 v = custom_field_values.detect {|v| v.custom_field_id == attribute }
581 582 if v && v.value.blank?
582 583 errors.add :base, v.custom_field.name + ' ' + l('activerecord.errors.messages.blank')
583 584 end
584 585 else
585 586 if respond_to?(attribute) && send(attribute).blank?
586 587 errors.add attribute, :blank
587 588 end
588 589 end
589 590 end
590 591 end
591 592
592 593 # Set the done_ratio using the status if that setting is set. This will keep the done_ratios
593 594 # even if the user turns off the setting later
594 595 def update_done_ratio_from_issue_status
595 596 if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
596 597 self.done_ratio = status.default_done_ratio
597 598 end
598 599 end
599 600
600 601 def init_journal(user, notes = "")
601 602 @current_journal ||= Journal.new(:journalized => self, :user => user, :notes => notes)
602 603 if new_record?
603 604 @current_journal.notify = false
604 605 else
605 606 @attributes_before_change = attributes.dup
606 607 @custom_values_before_change = {}
607 608 self.custom_field_values.each {|c| @custom_values_before_change.store c.custom_field_id, c.value }
608 609 end
609 610 @current_journal
610 611 end
611 612
612 613 # Returns the id of the last journal or nil
613 614 def last_journal_id
614 615 if new_record?
615 616 nil
616 617 else
617 618 journals.maximum(:id)
618 619 end
619 620 end
620 621
621 622 # Returns a scope for journals that have an id greater than journal_id
622 623 def journals_after(journal_id)
623 624 scope = journals.reorder("#{Journal.table_name}.id ASC")
624 625 if journal_id.present?
625 626 scope = scope.where("#{Journal.table_name}.id > ?", journal_id.to_i)
626 627 end
627 628 scope
628 629 end
629 630
630 631 # Return true if the issue is closed, otherwise false
631 632 def closed?
632 633 self.status.is_closed?
633 634 end
634 635
635 636 # Return true if the issue is being reopened
636 637 def reopened?
637 638 if !new_record? && status_id_changed?
638 639 status_was = IssueStatus.find_by_id(status_id_was)
639 640 status_new = IssueStatus.find_by_id(status_id)
640 641 if status_was && status_new && status_was.is_closed? && !status_new.is_closed?
641 642 return true
642 643 end
643 644 end
644 645 false
645 646 end
646 647
647 648 # Return true if the issue is being closed
648 649 def closing?
649 650 if !new_record? && status_id_changed?
650 651 status_was = IssueStatus.find_by_id(status_id_was)
651 652 status_new = IssueStatus.find_by_id(status_id)
652 653 if status_was && status_new && !status_was.is_closed? && status_new.is_closed?
653 654 return true
654 655 end
655 656 end
656 657 false
657 658 end
658 659
659 660 # Returns true if the issue is overdue
660 661 def overdue?
661 662 !due_date.nil? && (due_date < Date.today) && !status.is_closed?
662 663 end
663 664
664 665 # Is the amount of work done less than it should for the due date
665 666 def behind_schedule?
666 667 return false if start_date.nil? || due_date.nil?
667 668 done_date = start_date + ((due_date - start_date+1)* done_ratio/100).floor
668 669 return done_date <= Date.today
669 670 end
670 671
671 672 # Does this issue have children?
672 673 def children?
673 674 !leaf?
674 675 end
675 676
676 677 # Users the issue can be assigned to
677 678 def assignable_users
678 679 users = project.assignable_users
679 680 users << author if author
680 681 users << assigned_to if assigned_to
681 682 users.uniq.sort
682 683 end
683 684
684 685 # Versions that the issue can be assigned to
685 686 def assignable_versions
686 687 return @assignable_versions if @assignable_versions
687 688
688 689 versions = project.shared_versions.open.all
689 690 if fixed_version
690 691 if fixed_version_id_changed?
691 692 # nothing to do
692 693 elsif project_id_changed?
693 694 if project.shared_versions.include?(fixed_version)
694 695 versions << fixed_version
695 696 end
696 697 else
697 698 versions << fixed_version
698 699 end
699 700 end
700 701 @assignable_versions = versions.uniq.sort
701 702 end
702 703
703 704 # Returns true if this issue is blocked by another issue that is still open
704 705 def blocked?
705 706 !relations_to.detect {|ir| ir.relation_type == 'blocks' && !ir.issue_from.closed?}.nil?
706 707 end
707 708
708 709 # Returns an array of statuses that user is able to apply
709 710 def new_statuses_allowed_to(user=User.current, include_default=false)
710 711 if new_record? && @copied_from
711 712 [IssueStatus.default, @copied_from.status].compact.uniq.sort
712 713 else
713 714 initial_status = nil
714 715 if new_record?
715 716 initial_status = IssueStatus.default
716 717 elsif status_id_was
717 718 initial_status = IssueStatus.find_by_id(status_id_was)
718 719 end
719 720 initial_status ||= status
720 721
721 722 statuses = initial_status.find_new_statuses_allowed_to(
722 723 user.admin ? Role.all : user.roles_for_project(project),
723 724 tracker,
724 725 author == user,
725 726 assigned_to_id_changed? ? assigned_to_id_was == user.id : assigned_to_id == user.id
726 727 )
727 728 statuses << initial_status unless statuses.empty?
728 729 statuses << IssueStatus.default if include_default
729 730 statuses = statuses.compact.uniq.sort
730 731 blocked? ? statuses.reject {|s| s.is_closed?} : statuses
731 732 end
732 733 end
733 734
734 735 def assigned_to_was
735 736 if assigned_to_id_changed? && assigned_to_id_was.present?
736 737 @assigned_to_was ||= User.find_by_id(assigned_to_id_was)
737 738 end
738 739 end
739 740
740 741 # Returns the users that should be notified
741 742 def notified_users
742 743 notified = []
743 744 # Author and assignee are always notified unless they have been
744 745 # locked or don't want to be notified
745 746 notified << author if author
746 747 if assigned_to
747 748 notified += (assigned_to.is_a?(Group) ? assigned_to.users : [assigned_to])
748 749 end
749 750 if assigned_to_was
750 751 notified += (assigned_to_was.is_a?(Group) ? assigned_to_was.users : [assigned_to_was])
751 752 end
752 753 notified = notified.select {|u| u.active? && u.notify_about?(self)}
753 754
754 755 notified += project.notified_users
755 756 notified.uniq!
756 757 # Remove users that can not view the issue
757 758 notified.reject! {|user| !visible?(user)}
758 759 notified
759 760 end
760 761
761 762 # Returns the email addresses that should be notified
762 763 def recipients
763 764 notified_users.collect(&:mail)
764 765 end
765 766
766 767 # Returns the number of hours spent on this issue
767 768 def spent_hours
768 769 @spent_hours ||= time_entries.sum(:hours) || 0
769 770 end
770 771
771 772 # Returns the total number of hours spent on this issue and its descendants
772 773 #
773 774 # Example:
774 775 # spent_hours => 0.0
775 776 # spent_hours => 50.2
776 777 def total_spent_hours
777 778 @total_spent_hours ||= self_and_descendants.sum("#{TimeEntry.table_name}.hours",
778 779 :joins => "LEFT JOIN #{TimeEntry.table_name} ON #{TimeEntry.table_name}.issue_id = #{Issue.table_name}.id").to_f || 0.0
779 780 end
780 781
781 782 def relations
782 783 @relations ||= IssueRelations.new(self, (relations_from + relations_to).sort)
783 784 end
784 785
785 786 # Preloads relations for a collection of issues
786 787 def self.load_relations(issues)
787 788 if issues.any?
788 789 relations = IssueRelation.all(:conditions => ["issue_from_id IN (:ids) OR issue_to_id IN (:ids)", {:ids => issues.map(&:id)}])
789 790 issues.each do |issue|
790 791 issue.instance_variable_set "@relations", relations.select {|r| r.issue_from_id == issue.id || r.issue_to_id == issue.id}
791 792 end
792 793 end
793 794 end
794 795
795 796 # Preloads visible spent time for a collection of issues
796 797 def self.load_visible_spent_hours(issues, user=User.current)
797 798 if issues.any?
798 799 hours_by_issue_id = TimeEntry.visible(user).sum(:hours, :group => :issue_id)
799 800 issues.each do |issue|
800 801 issue.instance_variable_set "@spent_hours", (hours_by_issue_id[issue.id] || 0)
801 802 end
802 803 end
803 804 end
804 805
805 806 # Preloads visible relations for a collection of issues
806 807 def self.load_visible_relations(issues, user=User.current)
807 808 if issues.any?
808 809 issue_ids = issues.map(&:id)
809 810 # Relations with issue_from in given issues and visible issue_to
810 811 relations_from = IssueRelation.includes(:issue_to => [:status, :project]).where(visible_condition(user)).where(:issue_from_id => issue_ids).all
811 812 # Relations with issue_to in given issues and visible issue_from
812 813 relations_to = IssueRelation.includes(:issue_from => [:status, :project]).where(visible_condition(user)).where(:issue_to_id => issue_ids).all
813 814
814 815 issues.each do |issue|
815 816 relations =
816 817 relations_from.select {|relation| relation.issue_from_id == issue.id} +
817 818 relations_to.select {|relation| relation.issue_to_id == issue.id}
818 819
819 820 issue.instance_variable_set "@relations", IssueRelations.new(issue, relations.sort)
820 821 end
821 822 end
822 823 end
823 824
824 825 # Finds an issue relation given its id.
825 826 def find_relation(relation_id)
826 827 IssueRelation.find(relation_id, :conditions => ["issue_to_id = ? OR issue_from_id = ?", id, id])
827 828 end
828 829
829 830 def all_dependent_issues(except=[])
830 831 except << self
831 832 dependencies = []
832 833 relations_from.each do |relation|
833 834 if relation.issue_to && !except.include?(relation.issue_to)
834 835 dependencies << relation.issue_to
835 836 dependencies += relation.issue_to.all_dependent_issues(except)
836 837 end
837 838 end
838 839 dependencies
839 840 end
840 841
841 842 # Returns an array of issues that duplicate this one
842 843 def duplicates
843 844 relations_to.select {|r| r.relation_type == IssueRelation::TYPE_DUPLICATES}.collect {|r| r.issue_from}
844 845 end
845 846
846 847 # Returns the due date or the target due date if any
847 848 # Used on gantt chart
848 849 def due_before
849 850 due_date || (fixed_version ? fixed_version.effective_date : nil)
850 851 end
851 852
852 853 # Returns the time scheduled for this issue.
853 854 #
854 855 # Example:
855 856 # Start Date: 2/26/09, End Date: 3/04/09
856 857 # duration => 6
857 858 def duration
858 859 (start_date && due_date) ? due_date - start_date : 0
859 860 end
860 861
861 862 def soonest_start
862 863 @soonest_start ||= (
863 864 relations_to.collect{|relation| relation.successor_soonest_start} +
864 865 ancestors.collect(&:soonest_start)
865 866 ).compact.max
866 867 end
867 868
868 869 def reschedule_after(date)
869 870 return if date.nil?
870 871 if leaf?
871 872 if start_date.nil? || start_date < date
872 873 self.start_date, self.due_date = date, date + duration
873 874 begin
874 875 save
875 876 rescue ActiveRecord::StaleObjectError
876 877 reload
877 878 self.start_date, self.due_date = date, date + duration
878 879 save
879 880 end
880 881 end
881 882 else
882 883 leaves.each do |leaf|
883 884 leaf.reschedule_after(date)
884 885 end
885 886 end
886 887 end
887 888
888 889 def <=>(issue)
889 890 if issue.nil?
890 891 -1
891 892 elsif root_id != issue.root_id
892 893 (root_id || 0) <=> (issue.root_id || 0)
893 894 else
894 895 (lft || 0) <=> (issue.lft || 0)
895 896 end
896 897 end
897 898
898 899 def to_s
899 900 "#{tracker} ##{id}: #{subject}"
900 901 end
901 902
902 903 # Returns a string of css classes that apply to the issue
903 904 def css_classes
904 905 s = "issue status-#{status_id} priority-#{priority_id}"
905 906 s << ' closed' if closed?
906 907 s << ' overdue' if overdue?
907 908 s << ' child' if child?
908 909 s << ' parent' unless leaf?
909 910 s << ' private' if is_private?
910 911 s << ' created-by-me' if User.current.logged? && author_id == User.current.id
911 912 s << ' assigned-to-me' if User.current.logged? && assigned_to_id == User.current.id
912 913 s
913 914 end
914 915
915 916 # Saves an issue and a time_entry from the parameters
916 917 def save_issue_with_child_records(params, existing_time_entry=nil)
917 918 Issue.transaction do
918 919 if params[:time_entry] && (params[:time_entry][:hours].present? || params[:time_entry][:comments].present?) && User.current.allowed_to?(:log_time, project)
919 920 @time_entry = existing_time_entry || TimeEntry.new
920 921 @time_entry.project = project
921 922 @time_entry.issue = self
922 923 @time_entry.user = User.current
923 924 @time_entry.spent_on = User.current.today
924 925 @time_entry.attributes = params[:time_entry]
925 926 self.time_entries << @time_entry
926 927 end
927 928
928 929 # TODO: Rename hook
929 930 Redmine::Hook.call_hook(:controller_issues_edit_before_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
930 931 if save
931 932 # TODO: Rename hook
932 933 Redmine::Hook.call_hook(:controller_issues_edit_after_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
933 934 else
934 935 raise ActiveRecord::Rollback
935 936 end
936 937 end
937 938 end
938 939
939 940 # Unassigns issues from +version+ if it's no longer shared with issue's project
940 941 def self.update_versions_from_sharing_change(version)
941 942 # Update issues assigned to the version
942 943 update_versions(["#{Issue.table_name}.fixed_version_id = ?", version.id])
943 944 end
944 945
945 946 # Unassigns issues from versions that are no longer shared
946 947 # after +project+ was moved
947 948 def self.update_versions_from_hierarchy_change(project)
948 949 moved_project_ids = project.self_and_descendants.reload.collect(&:id)
949 950 # Update issues of the moved projects and issues assigned to a version of a moved project
950 951 Issue.update_versions(["#{Version.table_name}.project_id IN (?) OR #{Issue.table_name}.project_id IN (?)", moved_project_ids, moved_project_ids])
951 952 end
952 953
953 954 def parent_issue_id=(arg)
954 955 s = arg.to_s.strip.presence
955 956 if s && (m = s.match(%r{\A#?(\d+)\z})) && (@parent_issue = Issue.find_by_id(m[1]))
956 957 @parent_issue.id
957 958 else
958 959 @parent_issue = nil
959 960 @invalid_parent_issue_id = arg
960 961 end
961 962 end
962 963
963 964 def parent_issue_id
964 965 if @invalid_parent_issue_id
965 966 @invalid_parent_issue_id
966 967 elsif instance_variable_defined? :@parent_issue
967 968 @parent_issue.nil? ? nil : @parent_issue.id
968 969 else
969 970 parent_id
970 971 end
971 972 end
972 973
973 974 # Returns true if issue's project is a valid
974 975 # parent issue project
975 976 def valid_parent_project?(issue=parent)
976 977 return true if issue.nil? || issue.project_id == project_id
977 978
978 979 case Setting.cross_project_subtasks
979 980 when 'system'
980 981 true
981 982 when 'tree'
982 983 issue.project.root == project.root
983 984 when 'hierarchy'
984 985 issue.project.is_or_is_ancestor_of?(project) || issue.project.is_descendant_of?(project)
985 986 when 'descendants'
986 987 issue.project.is_or_is_ancestor_of?(project)
987 988 else
988 989 false
989 990 end
990 991 end
991 992
992 993 # Extracted from the ReportsController.
993 994 def self.by_tracker(project)
994 995 count_and_group_by(:project => project,
995 996 :field => 'tracker_id',
996 997 :joins => Tracker.table_name)
997 998 end
998 999
999 1000 def self.by_version(project)
1000 1001 count_and_group_by(:project => project,
1001 1002 :field => 'fixed_version_id',
1002 1003 :joins => Version.table_name)
1003 1004 end
1004 1005
1005 1006 def self.by_priority(project)
1006 1007 count_and_group_by(:project => project,
1007 1008 :field => 'priority_id',
1008 1009 :joins => IssuePriority.table_name)
1009 1010 end
1010 1011
1011 1012 def self.by_category(project)
1012 1013 count_and_group_by(:project => project,
1013 1014 :field => 'category_id',
1014 1015 :joins => IssueCategory.table_name)
1015 1016 end
1016 1017
1017 1018 def self.by_assigned_to(project)
1018 1019 count_and_group_by(:project => project,
1019 1020 :field => 'assigned_to_id',
1020 1021 :joins => User.table_name)
1021 1022 end
1022 1023
1023 1024 def self.by_author(project)
1024 1025 count_and_group_by(:project => project,
1025 1026 :field => 'author_id',
1026 1027 :joins => User.table_name)
1027 1028 end
1028 1029
1029 1030 def self.by_subproject(project)
1030 1031 ActiveRecord::Base.connection.select_all("select s.id as status_id,
1031 1032 s.is_closed as closed,
1032 1033 #{Issue.table_name}.project_id as project_id,
1033 1034 count(#{Issue.table_name}.id) as total
1034 1035 from
1035 1036 #{Issue.table_name}, #{Project.table_name}, #{IssueStatus.table_name} s
1036 1037 where
1037 1038 #{Issue.table_name}.status_id=s.id
1038 1039 and #{Issue.table_name}.project_id = #{Project.table_name}.id
1039 1040 and #{visible_condition(User.current, :project => project, :with_subprojects => true)}
1040 1041 and #{Issue.table_name}.project_id <> #{project.id}
1041 1042 group by s.id, s.is_closed, #{Issue.table_name}.project_id") if project.descendants.active.any?
1042 1043 end
1043 1044 # End ReportsController extraction
1044 1045
1045 1046 # Returns an array of projects that user can assign the issue to
1046 1047 def allowed_target_projects(user=User.current)
1047 1048 if new_record?
1048 1049 Project.all(:conditions => Project.allowed_to_condition(user, :add_issues))
1049 1050 else
1050 1051 self.class.allowed_target_projects_on_move(user)
1051 1052 end
1052 1053 end
1053 1054
1054 1055 # Returns an array of projects that user can move issues to
1055 1056 def self.allowed_target_projects_on_move(user=User.current)
1056 1057 Project.all(:conditions => Project.allowed_to_condition(user, :move_issues))
1057 1058 end
1058 1059
1059 1060 private
1060 1061
1061 1062 def after_project_change
1062 1063 # Update project_id on related time entries
1063 1064 TimeEntry.update_all(["project_id = ?", project_id], {:issue_id => id})
1064 1065
1065 1066 # Delete issue relations
1066 1067 unless Setting.cross_project_issue_relations?
1067 1068 relations_from.clear
1068 1069 relations_to.clear
1069 1070 end
1070 1071
1071 1072 # Move subtasks that were in the same project
1072 1073 children.each do |child|
1073 1074 next unless child.project_id == project_id_was
1074 1075 # Change project and keep project
1075 1076 child.send :project=, project, true
1076 1077 unless child.save
1077 1078 raise ActiveRecord::Rollback
1078 1079 end
1079 1080 end
1080 1081 end
1081 1082
1082 1083 # Callback for after the creation of an issue by copy
1083 1084 # * adds a "copied to" relation with the copied issue
1084 1085 # * copies subtasks from the copied issue
1085 1086 def after_create_from_copy
1086 1087 return unless copy? && !@after_create_from_copy_handled
1087 1088
1088 1089 if (@copied_from.project_id == project_id || Setting.cross_project_issue_relations?) && @copy_options[:link] != false
1089 1090 relation = IssueRelation.new(:issue_from => @copied_from, :issue_to => self, :relation_type => IssueRelation::TYPE_COPIED_TO)
1090 1091 unless relation.save
1091 1092 logger.error "Could not create relation while copying ##{@copied_from.id} to ##{id} due to validation errors: #{relation.errors.full_messages.join(', ')}" if logger
1092 1093 end
1093 1094 end
1094 1095
1095 1096 unless @copied_from.leaf? || @copy_options[:subtasks] == false
1096 1097 @copied_from.children.each do |child|
1097 1098 unless child.visible?
1098 1099 # Do not copy subtasks that are not visible to avoid potential disclosure of private data
1099 1100 logger.error "Subtask ##{child.id} was not copied during ##{@copied_from.id} copy because it is not visible to the current user" if logger
1100 1101 next
1101 1102 end
1102 1103 copy = Issue.new.copy_from(child, @copy_options)
1103 1104 copy.author = author
1104 1105 copy.project = project
1105 1106 copy.parent_issue_id = id
1106 1107 # Children subtasks are copied recursively
1107 1108 unless copy.save
1108 1109 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
1109 1110 end
1110 1111 end
1111 1112 end
1112 1113 @after_create_from_copy_handled = true
1113 1114 end
1114 1115
1115 1116 def update_nested_set_attributes
1116 1117 if root_id.nil?
1117 1118 # issue was just created
1118 1119 self.root_id = (@parent_issue.nil? ? id : @parent_issue.root_id)
1119 1120 set_default_left_and_right
1120 1121 Issue.update_all("root_id = #{root_id}, lft = #{lft}, rgt = #{rgt}", ["id = ?", id])
1121 1122 if @parent_issue
1122 1123 move_to_child_of(@parent_issue)
1123 1124 end
1124 1125 reload
1125 1126 elsif parent_issue_id != parent_id
1126 1127 former_parent_id = parent_id
1127 1128 # moving an existing issue
1128 1129 if @parent_issue && @parent_issue.root_id == root_id
1129 1130 # inside the same tree
1130 1131 move_to_child_of(@parent_issue)
1131 1132 else
1132 1133 # to another tree
1133 1134 unless root?
1134 1135 move_to_right_of(root)
1135 1136 reload
1136 1137 end
1137 1138 old_root_id = root_id
1138 1139 self.root_id = (@parent_issue.nil? ? id : @parent_issue.root_id )
1139 1140 target_maxright = nested_set_scope.maximum(right_column_name) || 0
1140 1141 offset = target_maxright + 1 - lft
1141 1142 Issue.update_all("root_id = #{root_id}, lft = lft + #{offset}, rgt = rgt + #{offset}",
1142 1143 ["root_id = ? AND lft >= ? AND rgt <= ? ", old_root_id, lft, rgt])
1143 1144 self[left_column_name] = lft + offset
1144 1145 self[right_column_name] = rgt + offset
1145 1146 if @parent_issue
1146 1147 move_to_child_of(@parent_issue)
1147 1148 end
1148 1149 end
1149 1150 reload
1150 1151 # delete invalid relations of all descendants
1151 1152 self_and_descendants.each do |issue|
1152 1153 issue.relations.each do |relation|
1153 1154 relation.destroy unless relation.valid?
1154 1155 end
1155 1156 end
1156 1157 # update former parent
1157 1158 recalculate_attributes_for(former_parent_id) if former_parent_id
1158 1159 end
1159 1160 remove_instance_variable(:@parent_issue) if instance_variable_defined?(:@parent_issue)
1160 1161 end
1161 1162
1162 1163 def update_parent_attributes
1163 1164 recalculate_attributes_for(parent_id) if parent_id
1164 1165 end
1165 1166
1166 1167 def recalculate_attributes_for(issue_id)
1167 1168 if issue_id && p = Issue.find_by_id(issue_id)
1168 1169 # priority = highest priority of children
1169 1170 if priority_position = p.children.maximum("#{IssuePriority.table_name}.position", :joins => :priority)
1170 1171 p.priority = IssuePriority.find_by_position(priority_position)
1171 1172 end
1172 1173
1173 1174 # start/due dates = lowest/highest dates of children
1174 1175 p.start_date = p.children.minimum(:start_date)
1175 1176 p.due_date = p.children.maximum(:due_date)
1176 1177 if p.start_date && p.due_date && p.due_date < p.start_date
1177 1178 p.start_date, p.due_date = p.due_date, p.start_date
1178 1179 end
1179 1180
1180 1181 # done ratio = weighted average ratio of leaves
1181 1182 unless Issue.use_status_for_done_ratio? && p.status && p.status.default_done_ratio
1182 1183 leaves_count = p.leaves.count
1183 1184 if leaves_count > 0
1184 1185 average = p.leaves.average(:estimated_hours).to_f
1185 1186 if average == 0
1186 1187 average = 1
1187 1188 end
1188 1189 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
1189 1190 progress = done / (average * leaves_count)
1190 1191 p.done_ratio = progress.round
1191 1192 end
1192 1193 end
1193 1194
1194 1195 # estimate = sum of leaves estimates
1195 1196 p.estimated_hours = p.leaves.sum(:estimated_hours).to_f
1196 1197 p.estimated_hours = nil if p.estimated_hours == 0.0
1197 1198
1198 1199 # ancestors will be recursively updated
1199 1200 p.save(:validate => false)
1200 1201 end
1201 1202 end
1202 1203
1203 1204 # Update issues so their versions are not pointing to a
1204 1205 # fixed_version that is not shared with the issue's project
1205 1206 def self.update_versions(conditions=nil)
1206 1207 # Only need to update issues with a fixed_version from
1207 1208 # a different project and that is not systemwide shared
1208 1209 Issue.scoped(:conditions => conditions).all(
1209 1210 :conditions => "#{Issue.table_name}.fixed_version_id IS NOT NULL" +
1210 1211 " AND #{Issue.table_name}.project_id <> #{Version.table_name}.project_id" +
1211 1212 " AND #{Version.table_name}.sharing <> 'system'",
1212 1213 :include => [:project, :fixed_version]
1213 1214 ).each do |issue|
1214 1215 next if issue.project.nil? || issue.fixed_version.nil?
1215 1216 unless issue.project.shared_versions.include?(issue.fixed_version)
1216 1217 issue.init_journal(User.current)
1217 1218 issue.fixed_version = nil
1218 1219 issue.save
1219 1220 end
1220 1221 end
1221 1222 end
1222 1223
1223 1224 # Callback on file attachment
1224 1225 def attachment_added(obj)
1225 1226 if @current_journal && !obj.new_record?
1226 1227 @current_journal.details << JournalDetail.new(:property => 'attachment', :prop_key => obj.id, :value => obj.filename)
1227 1228 end
1228 1229 end
1229 1230
1230 1231 # Callback on attachment deletion
1231 1232 def attachment_removed(obj)
1232 1233 if @current_journal && !obj.new_record?
1233 1234 @current_journal.details << JournalDetail.new(:property => 'attachment', :prop_key => obj.id, :old_value => obj.filename)
1234 1235 @current_journal.save
1235 1236 end
1236 1237 end
1237 1238
1238 1239 # Default assignment based on category
1239 1240 def default_assign
1240 1241 if assigned_to.nil? && category && category.assigned_to
1241 1242 self.assigned_to = category.assigned_to
1242 1243 end
1243 1244 end
1244 1245
1245 1246 # Updates start/due dates of following issues
1246 1247 def reschedule_following_issues
1247 1248 if start_date_changed? || due_date_changed?
1248 1249 relations_from.each do |relation|
1249 1250 relation.set_issue_to_dates
1250 1251 end
1251 1252 end
1252 1253 end
1253 1254
1254 1255 # Closes duplicates if the issue is being closed
1255 1256 def close_duplicates
1256 1257 if closing?
1257 1258 duplicates.each do |duplicate|
1258 1259 # Reload is need in case the duplicate was updated by a previous duplicate
1259 1260 duplicate.reload
1260 1261 # Don't re-close it if it's already closed
1261 1262 next if duplicate.closed?
1262 1263 # Same user and notes
1263 1264 if @current_journal
1264 1265 duplicate.init_journal(@current_journal.user, @current_journal.notes)
1265 1266 end
1266 1267 duplicate.update_attribute :status, self.status
1267 1268 end
1268 1269 end
1269 1270 end
1270 1271
1271 1272 # Make sure updated_on is updated when adding a note
1272 1273 def force_updated_on_change
1273 1274 if @current_journal
1274 1275 self.updated_on = current_time_from_proper_timezone
1275 1276 end
1276 1277 end
1277 1278
1278 1279 # Saves the changes in a Journal
1279 1280 # Called after_save
1280 1281 def create_journal
1281 1282 if @current_journal
1282 1283 # attributes changes
1283 1284 if @attributes_before_change
1284 1285 (Issue.column_names - %w(id root_id lft rgt lock_version created_on updated_on)).each {|c|
1285 1286 before = @attributes_before_change[c]
1286 1287 after = send(c)
1287 1288 next if before == after || (before.blank? && after.blank?)
1288 1289 @current_journal.details << JournalDetail.new(:property => 'attr',
1289 1290 :prop_key => c,
1290 1291 :old_value => before,
1291 1292 :value => after)
1292 1293 }
1293 1294 end
1294 1295 if @custom_values_before_change
1295 1296 # custom fields changes
1296 1297 custom_field_values.each {|c|
1297 1298 before = @custom_values_before_change[c.custom_field_id]
1298 1299 after = c.value
1299 1300 next if before == after || (before.blank? && after.blank?)
1300 1301
1301 1302 if before.is_a?(Array) || after.is_a?(Array)
1302 1303 before = [before] unless before.is_a?(Array)
1303 1304 after = [after] unless after.is_a?(Array)
1304 1305
1305 1306 # values removed
1306 1307 (before - after).reject(&:blank?).each do |value|
1307 1308 @current_journal.details << JournalDetail.new(:property => 'cf',
1308 1309 :prop_key => c.custom_field_id,
1309 1310 :old_value => value,
1310 1311 :value => nil)
1311 1312 end
1312 1313 # values added
1313 1314 (after - before).reject(&:blank?).each do |value|
1314 1315 @current_journal.details << JournalDetail.new(:property => 'cf',
1315 1316 :prop_key => c.custom_field_id,
1316 1317 :old_value => nil,
1317 1318 :value => value)
1318 1319 end
1319 1320 else
1320 1321 @current_journal.details << JournalDetail.new(:property => 'cf',
1321 1322 :prop_key => c.custom_field_id,
1322 1323 :old_value => before,
1323 1324 :value => after)
1324 1325 end
1325 1326 }
1326 1327 end
1327 1328 @current_journal.save
1328 1329 # reset current journal
1329 1330 init_journal @current_journal.user, @current_journal.notes
1330 1331 end
1331 1332 end
1332 1333
1333 1334 # Query generator for selecting groups of issue counts for a project
1334 1335 # based on specific criteria
1335 1336 #
1336 1337 # Options
1337 1338 # * project - Project to search in.
1338 1339 # * field - String. Issue field to key off of in the grouping.
1339 1340 # * joins - String. The table name to join against.
1340 1341 def self.count_and_group_by(options)
1341 1342 project = options.delete(:project)
1342 1343 select_field = options.delete(:field)
1343 1344 joins = options.delete(:joins)
1344 1345
1345 1346 where = "#{Issue.table_name}.#{select_field}=j.id"
1346 1347
1347 1348 ActiveRecord::Base.connection.select_all("select s.id as status_id,
1348 1349 s.is_closed as closed,
1349 1350 j.id as #{select_field},
1350 1351 count(#{Issue.table_name}.id) as total
1351 1352 from
1352 1353 #{Issue.table_name}, #{Project.table_name}, #{IssueStatus.table_name} s, #{joins} j
1353 1354 where
1354 1355 #{Issue.table_name}.status_id=s.id
1355 1356 and #{where}
1356 1357 and #{Issue.table_name}.project_id=#{Project.table_name}.id
1357 1358 and #{visible_condition(User.current, :project => project)}
1358 1359 group by s.id, s.is_closed, j.id")
1359 1360 end
1360 1361 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