##// END OF EJS Templates
Check permission before retrieving projects....
Jean-Philippe Lang -
r8412:6539d04622fb
parent child
Show More
@@ -1,1008 +1,1010
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2011 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 class Issue < ActiveRecord::Base
19 19 include Redmine::SafeAttributes
20 20
21 21 belongs_to :project
22 22 belongs_to :tracker
23 23 belongs_to :status, :class_name => 'IssueStatus', :foreign_key => 'status_id'
24 24 belongs_to :author, :class_name => 'User', :foreign_key => 'author_id'
25 25 belongs_to :assigned_to, :class_name => 'Principal', :foreign_key => 'assigned_to_id'
26 26 belongs_to :fixed_version, :class_name => 'Version', :foreign_key => 'fixed_version_id'
27 27 belongs_to :priority, :class_name => 'IssuePriority', :foreign_key => 'priority_id'
28 28 belongs_to :category, :class_name => 'IssueCategory', :foreign_key => 'category_id'
29 29
30 30 has_many :journals, :as => :journalized, :dependent => :destroy
31 31 has_many :time_entries, :dependent => :delete_all
32 32 has_and_belongs_to_many :changesets, :order => "#{Changeset.table_name}.committed_on ASC, #{Changeset.table_name}.id ASC"
33 33
34 34 has_many :relations_from, :class_name => 'IssueRelation', :foreign_key => 'issue_from_id', :dependent => :delete_all
35 35 has_many :relations_to, :class_name => 'IssueRelation', :foreign_key => 'issue_to_id', :dependent => :delete_all
36 36
37 37 acts_as_nested_set :scope => 'root_id', :dependent => :destroy
38 38 acts_as_attachable :after_add => :attachment_added, :after_remove => :attachment_removed
39 39 acts_as_customizable
40 40 acts_as_watchable
41 41 acts_as_searchable :columns => ['subject', "#{table_name}.description", "#{Journal.table_name}.notes"],
42 42 :include => [:project, :journals],
43 43 # sort by id so that limited eager loading doesn't break with postgresql
44 44 :order_column => "#{table_name}.id"
45 45 acts_as_event :title => Proc.new {|o| "#{o.tracker.name} ##{o.id} (#{o.status}): #{o.subject}"},
46 46 :url => Proc.new {|o| {:controller => 'issues', :action => 'show', :id => o.id}},
47 47 :type => Proc.new {|o| 'issue' + (o.closed? ? ' closed' : '') }
48 48
49 49 acts_as_activity_provider :find_options => {:include => [:project, :author, :tracker]},
50 50 :author_key => :author_id
51 51
52 52 DONE_RATIO_OPTIONS = %w(issue_field issue_status)
53 53
54 54 attr_reader :current_journal
55 55
56 56 validates_presence_of :subject, :priority, :project, :tracker, :author, :status
57 57
58 58 validates_length_of :subject, :maximum => 255
59 59 validates_inclusion_of :done_ratio, :in => 0..100
60 60 validates_numericality_of :estimated_hours, :allow_nil => true
61 61 validate :validate_issue
62 62
63 63 named_scope :visible, lambda {|*args| { :include => :project,
64 64 :conditions => Issue.visible_condition(args.shift || User.current, *args) } }
65 65
66 66 named_scope :open, lambda {|*args|
67 67 is_closed = args.size > 0 ? !args.first : false
68 68 {:conditions => ["#{IssueStatus.table_name}.is_closed = ?", is_closed], :include => :status}
69 69 }
70 70
71 71 named_scope :recently_updated, :order => "#{Issue.table_name}.updated_on DESC"
72 72 named_scope :with_limit, lambda { |limit| { :limit => limit} }
73 73 named_scope :on_active_project, :include => [:status, :project, :tracker],
74 74 :conditions => ["#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"]
75 75
76 76 before_create :default_assign
77 77 before_save :close_duplicates, :update_done_ratio_from_issue_status
78 78 after_save {|issue| issue.send :after_project_change if !issue.id_changed? && issue.project_id_changed?}
79 79 after_save :reschedule_following_issues, :update_nested_set_attributes, :update_parent_attributes, :create_journal
80 80 after_destroy :update_parent_attributes
81 81
82 82 # Returns a SQL conditions string used to find all issues visible by the specified user
83 83 def self.visible_condition(user, options={})
84 84 Project.allowed_to_condition(user, :view_issues, options) do |role, user|
85 85 case role.issues_visibility
86 86 when 'all'
87 87 nil
88 88 when 'default'
89 89 user_ids = [user.id] + user.groups.map(&:id)
90 90 "(#{table_name}.is_private = #{connection.quoted_false} OR #{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id IN (#{user_ids.join(',')}))"
91 91 when 'own'
92 92 user_ids = [user.id] + user.groups.map(&:id)
93 93 "(#{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id IN (#{user_ids.join(',')}))"
94 94 else
95 95 '1=0'
96 96 end
97 97 end
98 98 end
99 99
100 100 # Returns true if usr or current user is allowed to view the issue
101 101 def visible?(usr=nil)
102 102 (usr || User.current).allowed_to?(:view_issues, self.project) do |role, user|
103 103 case role.issues_visibility
104 104 when 'all'
105 105 true
106 106 when 'default'
107 107 !self.is_private? || self.author == user || user.is_or_belongs_to?(assigned_to)
108 108 when 'own'
109 109 self.author == user || user.is_or_belongs_to?(assigned_to)
110 110 else
111 111 false
112 112 end
113 113 end
114 114 end
115 115
116 116 def initialize(attributes=nil, *args)
117 117 super
118 118 if new_record?
119 119 # set default values for new records only
120 120 self.status ||= IssueStatus.default
121 121 self.priority ||= IssuePriority.default
122 122 end
123 123 end
124 124
125 125 # Overrides Redmine::Acts::Customizable::InstanceMethods#available_custom_fields
126 126 def available_custom_fields
127 127 (project && tracker) ? (project.all_issue_custom_fields & tracker.custom_fields.all) : []
128 128 end
129 129
130 130 def copy_from(arg)
131 131 issue = arg.is_a?(Issue) ? arg : Issue.visible.find(arg)
132 132 self.attributes = issue.attributes.dup.except("id", "root_id", "parent_id", "lft", "rgt", "created_on", "updated_on")
133 133 self.custom_field_values = issue.custom_field_values.inject({}) {|h,v| h[v.custom_field_id] = v.value; h}
134 134 self.status = issue.status
135 135 self.author = User.current
136 136 self
137 137 end
138 138
139 139 # Moves/copies an issue to a new project and tracker
140 140 # Returns the moved/copied issue on success, false on failure
141 141 def move_to_project(new_project, new_tracker=nil, options={})
142 142 if options[:copy]
143 143 issue = self.class.new.copy_from(self)
144 144 else
145 145 issue = self
146 146 end
147 147
148 148 issue.init_journal(User.current, options[:notes])
149 149
150 150 # Preserve previous behaviour
151 151 # #move_to_project doesn't change tracker automatically
152 152 issue.send :project=, new_project, true
153 153 if new_tracker
154 154 issue.tracker = new_tracker
155 155 end
156 156 # Allow bulk setting of attributes on the issue
157 157 if options[:attributes]
158 158 issue.attributes = options[:attributes]
159 159 end
160 160
161 161 issue.save ? issue : false
162 162 end
163 163
164 164 def status_id=(sid)
165 165 self.status = nil
166 166 write_attribute(:status_id, sid)
167 167 end
168 168
169 169 def priority_id=(pid)
170 170 self.priority = nil
171 171 write_attribute(:priority_id, pid)
172 172 end
173 173
174 174 def category_id=(cid)
175 175 self.category = nil
176 176 write_attribute(:category_id, cid)
177 177 end
178 178
179 179 def fixed_version_id=(vid)
180 180 self.fixed_version = nil
181 181 write_attribute(:fixed_version_id, vid)
182 182 end
183 183
184 184 def tracker_id=(tid)
185 185 self.tracker = nil
186 186 result = write_attribute(:tracker_id, tid)
187 187 @custom_field_values = nil
188 188 result
189 189 end
190 190
191 191 def project_id=(project_id)
192 192 if project_id.to_s != self.project_id.to_s
193 193 self.project = (project_id.present? ? Project.find_by_id(project_id) : nil)
194 194 end
195 195 end
196 196
197 197 def project=(project, keep_tracker=false)
198 198 project_was = self.project
199 199 write_attribute(:project_id, project ? project.id : nil)
200 200 association_instance_set('project', project)
201 201 if project_was && project && project_was != project
202 202 unless keep_tracker || project.trackers.include?(tracker)
203 203 self.tracker = project.trackers.first
204 204 end
205 205 # Reassign to the category with same name if any
206 206 if category
207 207 self.category = project.issue_categories.find_by_name(category.name)
208 208 end
209 209 # Keep the fixed_version if it's still valid in the new_project
210 210 if fixed_version && fixed_version.project != project && !project.shared_versions.include?(fixed_version)
211 211 self.fixed_version = nil
212 212 end
213 213 if parent && parent.project_id != project_id
214 214 self.parent_issue_id = nil
215 215 end
216 216 @custom_field_values = nil
217 217 end
218 218 end
219 219
220 220 def description=(arg)
221 221 if arg.is_a?(String)
222 222 arg = arg.gsub(/(\r\n|\n|\r)/, "\r\n")
223 223 end
224 224 write_attribute(:description, arg)
225 225 end
226 226
227 227 # Overrides attributes= so that project and tracker get assigned first
228 228 def attributes_with_project_and_tracker_first=(new_attributes, *args)
229 229 return if new_attributes.nil?
230 230 attrs = new_attributes.dup
231 231 attrs.stringify_keys!
232 232
233 233 %w(project project_id tracker tracker_id).each do |attr|
234 234 if attrs.has_key?(attr)
235 235 send "#{attr}=", attrs.delete(attr)
236 236 end
237 237 end
238 238 send :attributes_without_project_and_tracker_first=, attrs, *args
239 239 end
240 240 # Do not redefine alias chain on reload (see #4838)
241 241 alias_method_chain(:attributes=, :project_and_tracker_first) unless method_defined?(:attributes_without_project_and_tracker_first=)
242 242
243 243 def estimated_hours=(h)
244 244 write_attribute :estimated_hours, (h.is_a?(String) ? h.to_hours : h)
245 245 end
246 246
247 247 safe_attributes 'project_id',
248 248 :if => lambda {|issue, user|
249 projects = Issue.allowed_target_projects_on_move(user)
250 projects.include?(issue.project) && projects.size > 1
249 if user.allowed_to?(:move_issues, issue.project)
250 projects = Issue.allowed_target_projects_on_move(user)
251 projects.include?(issue.project) && projects.size > 1
252 end
251 253 }
252 254
253 255 safe_attributes 'tracker_id',
254 256 'status_id',
255 257 'category_id',
256 258 'assigned_to_id',
257 259 'priority_id',
258 260 'fixed_version_id',
259 261 'subject',
260 262 'description',
261 263 'start_date',
262 264 'due_date',
263 265 'done_ratio',
264 266 'estimated_hours',
265 267 'custom_field_values',
266 268 'custom_fields',
267 269 'lock_version',
268 270 :if => lambda {|issue, user| issue.new_record? || user.allowed_to?(:edit_issues, issue.project) }
269 271
270 272 safe_attributes 'status_id',
271 273 'assigned_to_id',
272 274 'fixed_version_id',
273 275 'done_ratio',
274 276 'lock_version',
275 277 :if => lambda {|issue, user| issue.new_statuses_allowed_to(user).any? }
276 278
277 279 safe_attributes 'watcher_user_ids',
278 280 :if => lambda {|issue, user| issue.new_record? && user.allowed_to?(:add_issue_watchers, issue.project)}
279 281
280 282 safe_attributes 'is_private',
281 283 :if => lambda {|issue, user|
282 284 user.allowed_to?(:set_issues_private, issue.project) ||
283 285 (issue.author == user && user.allowed_to?(:set_own_issues_private, issue.project))
284 286 }
285 287
286 288 safe_attributes 'parent_issue_id',
287 289 :if => lambda {|issue, user| (issue.new_record? || user.allowed_to?(:edit_issues, issue.project)) &&
288 290 user.allowed_to?(:manage_subtasks, issue.project)}
289 291
290 292 # Safely sets attributes
291 293 # Should be called from controllers instead of #attributes=
292 294 # attr_accessible is too rough because we still want things like
293 295 # Issue.new(:project => foo) to work
294 296 # TODO: move workflow/permission checks from controllers to here
295 297 def safe_attributes=(attrs, user=User.current)
296 298 return unless attrs.is_a?(Hash)
297 299
298 300 # User can change issue attributes only if he has :edit permission or if a workflow transition is allowed
299 301 attrs = delete_unsafe_attributes(attrs, user)
300 302 return if attrs.empty?
301 303
302 304 # Project and Tracker must be set before since new_statuses_allowed_to depends on it.
303 305 if p = attrs.delete('project_id')
304 306 self.project_id = p
305 307 end
306 308
307 309 if t = attrs.delete('tracker_id')
308 310 self.tracker_id = t
309 311 end
310 312
311 313 if attrs['status_id']
312 314 unless new_statuses_allowed_to(user).collect(&:id).include?(attrs['status_id'].to_i)
313 315 attrs.delete('status_id')
314 316 end
315 317 end
316 318
317 319 unless leaf?
318 320 attrs.reject! {|k,v| %w(priority_id done_ratio start_date due_date estimated_hours).include?(k)}
319 321 end
320 322
321 323 if attrs['parent_issue_id'].present?
322 324 attrs.delete('parent_issue_id') unless Issue.visible(user).exists?(attrs['parent_issue_id'].to_i)
323 325 end
324 326
325 327 # mass-assignment security bypass
326 328 self.send :attributes=, attrs, false
327 329 end
328 330
329 331 def done_ratio
330 332 if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
331 333 status.default_done_ratio
332 334 else
333 335 read_attribute(:done_ratio)
334 336 end
335 337 end
336 338
337 339 def self.use_status_for_done_ratio?
338 340 Setting.issue_done_ratio == 'issue_status'
339 341 end
340 342
341 343 def self.use_field_for_done_ratio?
342 344 Setting.issue_done_ratio == 'issue_field'
343 345 end
344 346
345 347 def validate_issue
346 348 if self.due_date.nil? && @attributes['due_date'] && !@attributes['due_date'].empty?
347 349 errors.add :due_date, :not_a_date
348 350 end
349 351
350 352 if self.due_date and self.start_date and self.due_date < self.start_date
351 353 errors.add :due_date, :greater_than_start_date
352 354 end
353 355
354 356 if start_date && soonest_start && start_date < soonest_start
355 357 errors.add :start_date, :invalid
356 358 end
357 359
358 360 if fixed_version
359 361 if !assignable_versions.include?(fixed_version)
360 362 errors.add :fixed_version_id, :inclusion
361 363 elsif reopened? && fixed_version.closed?
362 364 errors.add :base, I18n.t(:error_can_not_reopen_issue_on_closed_version)
363 365 end
364 366 end
365 367
366 368 # Checks that the issue can not be added/moved to a disabled tracker
367 369 if project && (tracker_id_changed? || project_id_changed?)
368 370 unless project.trackers.include?(tracker)
369 371 errors.add :tracker_id, :inclusion
370 372 end
371 373 end
372 374
373 375 # Checks parent issue assignment
374 376 if @parent_issue
375 377 if @parent_issue.project_id != project_id
376 378 errors.add :parent_issue_id, :not_same_project
377 379 elsif !new_record?
378 380 # moving an existing issue
379 381 if @parent_issue.root_id != root_id
380 382 # we can always move to another tree
381 383 elsif move_possible?(@parent_issue)
382 384 # move accepted inside tree
383 385 else
384 386 errors.add :parent_issue_id, :not_a_valid_parent
385 387 end
386 388 end
387 389 end
388 390 end
389 391
390 392 # Set the done_ratio using the status if that setting is set. This will keep the done_ratios
391 393 # even if the user turns off the setting later
392 394 def update_done_ratio_from_issue_status
393 395 if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
394 396 self.done_ratio = status.default_done_ratio
395 397 end
396 398 end
397 399
398 400 def init_journal(user, notes = "")
399 401 @current_journal ||= Journal.new(:journalized => self, :user => user, :notes => notes)
400 402 if new_record?
401 403 @current_journal.notify = false
402 404 else
403 405 @attributes_before_change = attributes.dup
404 406 @custom_values_before_change = {}
405 407 self.custom_values.each {|c| @custom_values_before_change.store c.custom_field_id, c.value }
406 408 end
407 409 # Make sure updated_on is updated when adding a note.
408 410 updated_on_will_change!
409 411 @current_journal
410 412 end
411 413
412 414 # Return true if the issue is closed, otherwise false
413 415 def closed?
414 416 self.status.is_closed?
415 417 end
416 418
417 419 # Return true if the issue is being reopened
418 420 def reopened?
419 421 if !new_record? && status_id_changed?
420 422 status_was = IssueStatus.find_by_id(status_id_was)
421 423 status_new = IssueStatus.find_by_id(status_id)
422 424 if status_was && status_new && status_was.is_closed? && !status_new.is_closed?
423 425 return true
424 426 end
425 427 end
426 428 false
427 429 end
428 430
429 431 # Return true if the issue is being closed
430 432 def closing?
431 433 if !new_record? && status_id_changed?
432 434 status_was = IssueStatus.find_by_id(status_id_was)
433 435 status_new = IssueStatus.find_by_id(status_id)
434 436 if status_was && status_new && !status_was.is_closed? && status_new.is_closed?
435 437 return true
436 438 end
437 439 end
438 440 false
439 441 end
440 442
441 443 # Returns true if the issue is overdue
442 444 def overdue?
443 445 !due_date.nil? && (due_date < Date.today) && !status.is_closed?
444 446 end
445 447
446 448 # Is the amount of work done less than it should for the due date
447 449 def behind_schedule?
448 450 return false if start_date.nil? || due_date.nil?
449 451 done_date = start_date + ((due_date - start_date+1)* done_ratio/100).floor
450 452 return done_date <= Date.today
451 453 end
452 454
453 455 # Does this issue have children?
454 456 def children?
455 457 !leaf?
456 458 end
457 459
458 460 # Users the issue can be assigned to
459 461 def assignable_users
460 462 users = project.assignable_users
461 463 users << author if author
462 464 users << assigned_to if assigned_to
463 465 users.uniq.sort
464 466 end
465 467
466 468 # Versions that the issue can be assigned to
467 469 def assignable_versions
468 470 @assignable_versions ||= (project.shared_versions.open + [Version.find_by_id(fixed_version_id_was)]).compact.uniq.sort
469 471 end
470 472
471 473 # Returns true if this issue is blocked by another issue that is still open
472 474 def blocked?
473 475 !relations_to.detect {|ir| ir.relation_type == 'blocks' && !ir.issue_from.closed?}.nil?
474 476 end
475 477
476 478 # Returns an array of status that user is able to apply
477 479 def new_statuses_allowed_to(user, include_default=false)
478 480 statuses = status.find_new_statuses_allowed_to(
479 481 user.roles_for_project(project),
480 482 tracker,
481 483 author == user,
482 484 assigned_to_id_changed? ? assigned_to_id_was == user.id : assigned_to_id == user.id
483 485 )
484 486 statuses << status unless statuses.empty?
485 487 statuses << IssueStatus.default if include_default
486 488 statuses = statuses.uniq.sort
487 489 blocked? ? statuses.reject {|s| s.is_closed?} : statuses
488 490 end
489 491
490 492 # Returns the mail adresses of users that should be notified
491 493 def recipients
492 494 notified = project.notified_users
493 495 # Author and assignee are always notified unless they have been
494 496 # locked or don't want to be notified
495 497 notified << author if author && author.active? && author.notify_about?(self)
496 498 if assigned_to
497 499 if assigned_to.is_a?(Group)
498 500 notified += assigned_to.users.select {|u| u.active? && u.notify_about?(self)}
499 501 else
500 502 notified << assigned_to if assigned_to.active? && assigned_to.notify_about?(self)
501 503 end
502 504 end
503 505 notified.uniq!
504 506 # Remove users that can not view the issue
505 507 notified.reject! {|user| !visible?(user)}
506 508 notified.collect(&:mail)
507 509 end
508 510
509 511 # Returns the number of hours spent on this issue
510 512 def spent_hours
511 513 @spent_hours ||= time_entries.sum(:hours) || 0
512 514 end
513 515
514 516 # Returns the total number of hours spent on this issue and its descendants
515 517 #
516 518 # Example:
517 519 # spent_hours => 0.0
518 520 # spent_hours => 50.2
519 521 def total_spent_hours
520 522 @total_spent_hours ||= self_and_descendants.sum("#{TimeEntry.table_name}.hours",
521 523 :joins => "LEFT JOIN #{TimeEntry.table_name} ON #{TimeEntry.table_name}.issue_id = #{Issue.table_name}.id").to_f || 0.0
522 524 end
523 525
524 526 def relations
525 527 @relations ||= (relations_from + relations_to).sort
526 528 end
527 529
528 530 # Preloads relations for a collection of issues
529 531 def self.load_relations(issues)
530 532 if issues.any?
531 533 relations = IssueRelation.all(:conditions => ["issue_from_id IN (:ids) OR issue_to_id IN (:ids)", {:ids => issues.map(&:id)}])
532 534 issues.each do |issue|
533 535 issue.instance_variable_set "@relations", relations.select {|r| r.issue_from_id == issue.id || r.issue_to_id == issue.id}
534 536 end
535 537 end
536 538 end
537 539
538 540 # Preloads visible spent time for a collection of issues
539 541 def self.load_visible_spent_hours(issues, user=User.current)
540 542 if issues.any?
541 543 hours_by_issue_id = TimeEntry.visible(user).sum(:hours, :group => :issue_id)
542 544 issues.each do |issue|
543 545 issue.instance_variable_set "@spent_hours", (hours_by_issue_id[issue.id] || 0)
544 546 end
545 547 end
546 548 end
547 549
548 550 # Finds an issue relation given its id.
549 551 def find_relation(relation_id)
550 552 IssueRelation.find(relation_id, :conditions => ["issue_to_id = ? OR issue_from_id = ?", id, id])
551 553 end
552 554
553 555 def all_dependent_issues(except=[])
554 556 except << self
555 557 dependencies = []
556 558 relations_from.each do |relation|
557 559 if relation.issue_to && !except.include?(relation.issue_to)
558 560 dependencies << relation.issue_to
559 561 dependencies += relation.issue_to.all_dependent_issues(except)
560 562 end
561 563 end
562 564 dependencies
563 565 end
564 566
565 567 # Returns an array of issues that duplicate this one
566 568 def duplicates
567 569 relations_to.select {|r| r.relation_type == IssueRelation::TYPE_DUPLICATES}.collect {|r| r.issue_from}
568 570 end
569 571
570 572 # Returns the due date or the target due date if any
571 573 # Used on gantt chart
572 574 def due_before
573 575 due_date || (fixed_version ? fixed_version.effective_date : nil)
574 576 end
575 577
576 578 # Returns the time scheduled for this issue.
577 579 #
578 580 # Example:
579 581 # Start Date: 2/26/09, End Date: 3/04/09
580 582 # duration => 6
581 583 def duration
582 584 (start_date && due_date) ? due_date - start_date : 0
583 585 end
584 586
585 587 def soonest_start
586 588 @soonest_start ||= (
587 589 relations_to.collect{|relation| relation.successor_soonest_start} +
588 590 ancestors.collect(&:soonest_start)
589 591 ).compact.max
590 592 end
591 593
592 594 def reschedule_after(date)
593 595 return if date.nil?
594 596 if leaf?
595 597 if start_date.nil? || start_date < date
596 598 self.start_date, self.due_date = date, date + duration
597 599 save
598 600 end
599 601 else
600 602 leaves.each do |leaf|
601 603 leaf.reschedule_after(date)
602 604 end
603 605 end
604 606 end
605 607
606 608 def <=>(issue)
607 609 if issue.nil?
608 610 -1
609 611 elsif root_id != issue.root_id
610 612 (root_id || 0) <=> (issue.root_id || 0)
611 613 else
612 614 (lft || 0) <=> (issue.lft || 0)
613 615 end
614 616 end
615 617
616 618 def to_s
617 619 "#{tracker} ##{id}: #{subject}"
618 620 end
619 621
620 622 # Returns a string of css classes that apply to the issue
621 623 def css_classes
622 624 s = "issue status-#{status.position} priority-#{priority.position}"
623 625 s << ' closed' if closed?
624 626 s << ' overdue' if overdue?
625 627 s << ' child' if child?
626 628 s << ' parent' unless leaf?
627 629 s << ' private' if is_private?
628 630 s << ' created-by-me' if User.current.logged? && author_id == User.current.id
629 631 s << ' assigned-to-me' if User.current.logged? && assigned_to_id == User.current.id
630 632 s
631 633 end
632 634
633 635 # Saves an issue, time_entry, attachments, and a journal from the parameters
634 636 # Returns false if save fails
635 637 def save_issue_with_child_records(params, existing_time_entry=nil)
636 638 Issue.transaction do
637 639 if params[:time_entry] && (params[:time_entry][:hours].present? || params[:time_entry][:comments].present?) && User.current.allowed_to?(:log_time, project)
638 640 @time_entry = existing_time_entry || TimeEntry.new
639 641 @time_entry.project = project
640 642 @time_entry.issue = self
641 643 @time_entry.user = User.current
642 644 @time_entry.spent_on = User.current.today
643 645 @time_entry.attributes = params[:time_entry]
644 646 self.time_entries << @time_entry
645 647 end
646 648
647 649 if valid?
648 650 attachments = Attachment.attach_files(self, params[:attachments])
649 651 # TODO: Rename hook
650 652 Redmine::Hook.call_hook(:controller_issues_edit_before_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
651 653 begin
652 654 if save
653 655 # TODO: Rename hook
654 656 Redmine::Hook.call_hook(:controller_issues_edit_after_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
655 657 else
656 658 raise ActiveRecord::Rollback
657 659 end
658 660 rescue ActiveRecord::StaleObjectError
659 661 attachments[:files].each(&:destroy)
660 662 errors.add :base, l(:notice_locking_conflict)
661 663 raise ActiveRecord::Rollback
662 664 end
663 665 end
664 666 end
665 667 end
666 668
667 669 # Unassigns issues from +version+ if it's no longer shared with issue's project
668 670 def self.update_versions_from_sharing_change(version)
669 671 # Update issues assigned to the version
670 672 update_versions(["#{Issue.table_name}.fixed_version_id = ?", version.id])
671 673 end
672 674
673 675 # Unassigns issues from versions that are no longer shared
674 676 # after +project+ was moved
675 677 def self.update_versions_from_hierarchy_change(project)
676 678 moved_project_ids = project.self_and_descendants.reload.collect(&:id)
677 679 # Update issues of the moved projects and issues assigned to a version of a moved project
678 680 Issue.update_versions(["#{Version.table_name}.project_id IN (?) OR #{Issue.table_name}.project_id IN (?)", moved_project_ids, moved_project_ids])
679 681 end
680 682
681 683 def parent_issue_id=(arg)
682 684 parent_issue_id = arg.blank? ? nil : arg.to_i
683 685 if parent_issue_id && @parent_issue = Issue.find_by_id(parent_issue_id)
684 686 @parent_issue.id
685 687 else
686 688 @parent_issue = nil
687 689 nil
688 690 end
689 691 end
690 692
691 693 def parent_issue_id
692 694 if instance_variable_defined? :@parent_issue
693 695 @parent_issue.nil? ? nil : @parent_issue.id
694 696 else
695 697 parent_id
696 698 end
697 699 end
698 700
699 701 # Extracted from the ReportsController.
700 702 def self.by_tracker(project)
701 703 count_and_group_by(:project => project,
702 704 :field => 'tracker_id',
703 705 :joins => Tracker.table_name)
704 706 end
705 707
706 708 def self.by_version(project)
707 709 count_and_group_by(:project => project,
708 710 :field => 'fixed_version_id',
709 711 :joins => Version.table_name)
710 712 end
711 713
712 714 def self.by_priority(project)
713 715 count_and_group_by(:project => project,
714 716 :field => 'priority_id',
715 717 :joins => IssuePriority.table_name)
716 718 end
717 719
718 720 def self.by_category(project)
719 721 count_and_group_by(:project => project,
720 722 :field => 'category_id',
721 723 :joins => IssueCategory.table_name)
722 724 end
723 725
724 726 def self.by_assigned_to(project)
725 727 count_and_group_by(:project => project,
726 728 :field => 'assigned_to_id',
727 729 :joins => User.table_name)
728 730 end
729 731
730 732 def self.by_author(project)
731 733 count_and_group_by(:project => project,
732 734 :field => 'author_id',
733 735 :joins => User.table_name)
734 736 end
735 737
736 738 def self.by_subproject(project)
737 739 ActiveRecord::Base.connection.select_all("select s.id as status_id,
738 740 s.is_closed as closed,
739 741 #{Issue.table_name}.project_id as project_id,
740 742 count(#{Issue.table_name}.id) as total
741 743 from
742 744 #{Issue.table_name}, #{Project.table_name}, #{IssueStatus.table_name} s
743 745 where
744 746 #{Issue.table_name}.status_id=s.id
745 747 and #{Issue.table_name}.project_id = #{Project.table_name}.id
746 748 and #{visible_condition(User.current, :project => project, :with_subprojects => true)}
747 749 and #{Issue.table_name}.project_id <> #{project.id}
748 750 group by s.id, s.is_closed, #{Issue.table_name}.project_id") if project.descendants.active.any?
749 751 end
750 752 # End ReportsController extraction
751 753
752 754 # Returns an array of projects that current user can move issues to
753 755 def self.allowed_target_projects_on_move(user=User.current)
754 756 projects = []
755 757 if user.admin?
756 758 # admin is allowed to move issues to any active (visible) project
757 759 projects = Project.visible(user).all
758 760 elsif user.logged?
759 761 if Role.non_member.allowed_to?(:move_issues)
760 762 projects = Project.visible(user).all
761 763 else
762 764 user.memberships.each {|m| projects << m.project if m.roles.detect {|r| r.allowed_to?(:move_issues)}}
763 765 end
764 766 end
765 767 projects
766 768 end
767 769
768 770 private
769 771
770 772 def after_project_change
771 773 # Update project_id on related time entries
772 774 TimeEntry.update_all(["project_id = ?", project_id], {:issue_id => id})
773 775
774 776 # Delete issue relations
775 777 unless Setting.cross_project_issue_relations?
776 778 relations_from.clear
777 779 relations_to.clear
778 780 end
779 781
780 782 # Move subtasks
781 783 children.each do |child|
782 784 # Change project and keep project
783 785 child.send :project=, project, true
784 786 unless child.save
785 787 raise ActiveRecord::Rollback
786 788 end
787 789 end
788 790 end
789 791
790 792 def update_nested_set_attributes
791 793 if root_id.nil?
792 794 # issue was just created
793 795 self.root_id = (@parent_issue.nil? ? id : @parent_issue.root_id)
794 796 set_default_left_and_right
795 797 Issue.update_all("root_id = #{root_id}, lft = #{lft}, rgt = #{rgt}", ["id = ?", id])
796 798 if @parent_issue
797 799 move_to_child_of(@parent_issue)
798 800 end
799 801 reload
800 802 elsif parent_issue_id != parent_id
801 803 former_parent_id = parent_id
802 804 # moving an existing issue
803 805 if @parent_issue && @parent_issue.root_id == root_id
804 806 # inside the same tree
805 807 move_to_child_of(@parent_issue)
806 808 else
807 809 # to another tree
808 810 unless root?
809 811 move_to_right_of(root)
810 812 reload
811 813 end
812 814 old_root_id = root_id
813 815 self.root_id = (@parent_issue.nil? ? id : @parent_issue.root_id )
814 816 target_maxright = nested_set_scope.maximum(right_column_name) || 0
815 817 offset = target_maxright + 1 - lft
816 818 Issue.update_all("root_id = #{root_id}, lft = lft + #{offset}, rgt = rgt + #{offset}",
817 819 ["root_id = ? AND lft >= ? AND rgt <= ? ", old_root_id, lft, rgt])
818 820 self[left_column_name] = lft + offset
819 821 self[right_column_name] = rgt + offset
820 822 if @parent_issue
821 823 move_to_child_of(@parent_issue)
822 824 end
823 825 end
824 826 reload
825 827 # delete invalid relations of all descendants
826 828 self_and_descendants.each do |issue|
827 829 issue.relations.each do |relation|
828 830 relation.destroy unless relation.valid?
829 831 end
830 832 end
831 833 # update former parent
832 834 recalculate_attributes_for(former_parent_id) if former_parent_id
833 835 end
834 836 remove_instance_variable(:@parent_issue) if instance_variable_defined?(:@parent_issue)
835 837 end
836 838
837 839 def update_parent_attributes
838 840 recalculate_attributes_for(parent_id) if parent_id
839 841 end
840 842
841 843 def recalculate_attributes_for(issue_id)
842 844 if issue_id && p = Issue.find_by_id(issue_id)
843 845 # priority = highest priority of children
844 846 if priority_position = p.children.maximum("#{IssuePriority.table_name}.position", :joins => :priority)
845 847 p.priority = IssuePriority.find_by_position(priority_position)
846 848 end
847 849
848 850 # start/due dates = lowest/highest dates of children
849 851 p.start_date = p.children.minimum(:start_date)
850 852 p.due_date = p.children.maximum(:due_date)
851 853 if p.start_date && p.due_date && p.due_date < p.start_date
852 854 p.start_date, p.due_date = p.due_date, p.start_date
853 855 end
854 856
855 857 # done ratio = weighted average ratio of leaves
856 858 unless Issue.use_status_for_done_ratio? && p.status && p.status.default_done_ratio
857 859 leaves_count = p.leaves.count
858 860 if leaves_count > 0
859 861 average = p.leaves.average(:estimated_hours).to_f
860 862 if average == 0
861 863 average = 1
862 864 end
863 865 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
864 866 progress = done / (average * leaves_count)
865 867 p.done_ratio = progress.round
866 868 end
867 869 end
868 870
869 871 # estimate = sum of leaves estimates
870 872 p.estimated_hours = p.leaves.sum(:estimated_hours).to_f
871 873 p.estimated_hours = nil if p.estimated_hours == 0.0
872 874
873 875 # ancestors will be recursively updated
874 876 p.save(false)
875 877 end
876 878 end
877 879
878 880 # Update issues so their versions are not pointing to a
879 881 # fixed_version that is not shared with the issue's project
880 882 def self.update_versions(conditions=nil)
881 883 # Only need to update issues with a fixed_version from
882 884 # a different project and that is not systemwide shared
883 885 Issue.scoped(:conditions => conditions).all(
884 886 :conditions => "#{Issue.table_name}.fixed_version_id IS NOT NULL" +
885 887 " AND #{Issue.table_name}.project_id <> #{Version.table_name}.project_id" +
886 888 " AND #{Version.table_name}.sharing <> 'system'",
887 889 :include => [:project, :fixed_version]
888 890 ).each do |issue|
889 891 next if issue.project.nil? || issue.fixed_version.nil?
890 892 unless issue.project.shared_versions.include?(issue.fixed_version)
891 893 issue.init_journal(User.current)
892 894 issue.fixed_version = nil
893 895 issue.save
894 896 end
895 897 end
896 898 end
897 899
898 900 # Callback on attachment deletion
899 901 def attachment_added(obj)
900 902 if @current_journal && !obj.new_record?
901 903 @current_journal.details << JournalDetail.new(:property => 'attachment', :prop_key => obj.id, :value => obj.filename)
902 904 end
903 905 end
904 906
905 907 # Callback on attachment deletion
906 908 def attachment_removed(obj)
907 909 journal = init_journal(User.current)
908 910 journal.details << JournalDetail.new(:property => 'attachment',
909 911 :prop_key => obj.id,
910 912 :old_value => obj.filename)
911 913 journal.save
912 914 end
913 915
914 916 # Default assignment based on category
915 917 def default_assign
916 918 if assigned_to.nil? && category && category.assigned_to
917 919 self.assigned_to = category.assigned_to
918 920 end
919 921 end
920 922
921 923 # Updates start/due dates of following issues
922 924 def reschedule_following_issues
923 925 if start_date_changed? || due_date_changed?
924 926 relations_from.each do |relation|
925 927 relation.set_issue_to_dates
926 928 end
927 929 end
928 930 end
929 931
930 932 # Closes duplicates if the issue is being closed
931 933 def close_duplicates
932 934 if closing?
933 935 duplicates.each do |duplicate|
934 936 # Reload is need in case the duplicate was updated by a previous duplicate
935 937 duplicate.reload
936 938 # Don't re-close it if it's already closed
937 939 next if duplicate.closed?
938 940 # Same user and notes
939 941 if @current_journal
940 942 duplicate.init_journal(@current_journal.user, @current_journal.notes)
941 943 end
942 944 duplicate.update_attribute :status, self.status
943 945 end
944 946 end
945 947 end
946 948
947 949 # Saves the changes in a Journal
948 950 # Called after_save
949 951 def create_journal
950 952 if @current_journal
951 953 # attributes changes
952 954 if @attributes_before_change
953 955 (Issue.column_names - %w(id root_id lft rgt lock_version created_on updated_on)).each {|c|
954 956 before = @attributes_before_change[c]
955 957 after = send(c)
956 958 next if before == after || (before.blank? && after.blank?)
957 959 @current_journal.details << JournalDetail.new(:property => 'attr',
958 960 :prop_key => c,
959 961 :old_value => before,
960 962 :value => after)
961 963 }
962 964 end
963 965 if @custom_values_before_change
964 966 # custom fields changes
965 967 custom_values.each {|c|
966 968 before = @custom_values_before_change[c.custom_field_id]
967 969 after = c.value
968 970 next if before == after || (before.blank? && after.blank?)
969 971 @current_journal.details << JournalDetail.new(:property => 'cf',
970 972 :prop_key => c.custom_field_id,
971 973 :old_value => before,
972 974 :value => after)
973 975 }
974 976 end
975 977 @current_journal.save
976 978 # reset current journal
977 979 init_journal @current_journal.user, @current_journal.notes
978 980 end
979 981 end
980 982
981 983 # Query generator for selecting groups of issue counts for a project
982 984 # based on specific criteria
983 985 #
984 986 # Options
985 987 # * project - Project to search in.
986 988 # * field - String. Issue field to key off of in the grouping.
987 989 # * joins - String. The table name to join against.
988 990 def self.count_and_group_by(options)
989 991 project = options.delete(:project)
990 992 select_field = options.delete(:field)
991 993 joins = options.delete(:joins)
992 994
993 995 where = "#{Issue.table_name}.#{select_field}=j.id"
994 996
995 997 ActiveRecord::Base.connection.select_all("select s.id as status_id,
996 998 s.is_closed as closed,
997 999 j.id as #{select_field},
998 1000 count(#{Issue.table_name}.id) as total
999 1001 from
1000 1002 #{Issue.table_name}, #{Project.table_name}, #{IssueStatus.table_name} s, #{joins} j
1001 1003 where
1002 1004 #{Issue.table_name}.status_id=s.id
1003 1005 and #{where}
1004 1006 and #{Issue.table_name}.project_id=#{Project.table_name}.id
1005 1007 and #{visible_condition(User.current, :project => project)}
1006 1008 group by s.id, s.is_closed, j.id")
1007 1009 end
1008 1010 end
General Comments 0
You need to be logged in to leave comments. Login now