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