To check out this repository please hg clone the following URL, or open the URL using EasyMercurial or your preferred Mercurial client.

Statistics Download as Zip
| Branch: | Tag: | Revision:

root / app / models / issue.rb @ 440:6253d777aa12

History | View | Annotate | Download (31.6 KB)

1
# redMine - project management software
2
# Copyright (C) 2006-2007  Jean-Philippe Lang
3
#
4
# This program is free software; you can redistribute it and/or
5
# modify it under the terms of the GNU General Public License
6
# as published by the Free Software Foundation; either version 2
7
# of the License, or (at your option) any later version.
8
# 
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
# 
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17

    
18
class Issue < ActiveRecord::Base
19
  belongs_to :project
20
  belongs_to :tracker
21
  belongs_to :status, :class_name => 'IssueStatus', :foreign_key => 'status_id'
22
  belongs_to :author, :class_name => 'User', :foreign_key => 'author_id'
23
  belongs_to :assigned_to, :class_name => 'User', :foreign_key => 'assigned_to_id'
24
  belongs_to :fixed_version, :class_name => 'Version', :foreign_key => 'fixed_version_id'
25
  belongs_to :priority, :class_name => 'IssuePriority', :foreign_key => 'priority_id'
26
  belongs_to :category, :class_name => 'IssueCategory', :foreign_key => 'category_id'
27

    
28
  has_many :journals, :as => :journalized, :dependent => :destroy
29
  has_many :time_entries, :dependent => :delete_all
30
  has_and_belongs_to_many :changesets, :order => "#{Changeset.table_name}.id ASC"
31
  
32
  has_many :relations_from, :class_name => 'IssueRelation', :foreign_key => 'issue_from_id', :dependent => :delete_all
33
  has_many :relations_to, :class_name => 'IssueRelation', :foreign_key => 'issue_to_id', :dependent => :delete_all
34
  
35
  acts_as_nested_set :scope => 'root_id'
36
  acts_as_attachable :after_remove => :attachment_removed
37
  acts_as_customizable
38
  acts_as_watchable
39
  acts_as_searchable :columns => ['subject', "#{table_name}.description", "#{Journal.table_name}.notes"],
40
                     :include => [:project, :journals],
41
                     # sort by id so that limited eager loading doesn't break with postgresql
42
                     :order_column => "#{table_name}.id"
43
  acts_as_event :title => Proc.new {|o| "#{o.tracker.name} ##{o.id} (#{o.status}): #{o.subject}"},
44
                :url => Proc.new {|o| {:controller => 'issues', :action => 'show', :id => o.id}},
45
                :type => Proc.new {|o| 'issue' + (o.closed? ? ' closed' : '') }
46
  
47
  acts_as_activity_provider :find_options => {:include => [:project, :author, :tracker]},
48
                            :author_key => :author_id
49

    
50
  DONE_RATIO_OPTIONS = %w(issue_field issue_status)
51

    
52
  attr_reader :current_journal
53

    
54
  validates_presence_of :subject, :priority, :project, :tracker, :author, :status
55

    
56
  validates_length_of :subject, :maximum => 255
57
  validates_inclusion_of :done_ratio, :in => 0..100
58
  validates_numericality_of :estimated_hours, :allow_nil => true
59

    
60
  named_scope :visible, lambda {|*args| { :include => :project,
61
                                          :conditions => Project.allowed_to_condition(args.first || User.current, :view_issues) } }
62
  
63
  named_scope :open, :conditions => ["#{IssueStatus.table_name}.is_closed = ?", false], :include => :status
64

    
65
  named_scope :recently_updated, :order => "#{Issue.table_name}.updated_on DESC"
66
  named_scope :with_limit, lambda { |limit| { :limit => limit} }
67
  named_scope :on_active_project, :include => [:status, :project, :tracker],
68
                                  :conditions => ["#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"]
69
  named_scope :for_gantt, lambda {
70
    {
71
      :include => [:tracker, :status, :assigned_to, :priority, :project, :fixed_version],
72
      :order => "#{Issue.table_name}.due_date ASC, #{Issue.table_name}.start_date ASC, #{Issue.table_name}.id ASC"
73
    }
74
  }
75

    
76
  named_scope :without_version, lambda {
77
    {
78
      :conditions => { :fixed_version_id => nil}
79
    }
80
  }
81

    
82
  named_scope :with_query, lambda {|query|
83
    {
84
      :conditions => Query.merge_conditions(query.statement)
85
    }
86
  }
87

    
88
  before_create :default_assign
89
  before_save :close_duplicates, :update_done_ratio_from_issue_status
90
  after_save :reschedule_following_issues, :update_nested_set_attributes, :update_parent_attributes, :create_journal
91
  after_destroy :destroy_children
92
  after_destroy :update_parent_attributes
93

    
94
  # Returns true if usr or current user is allowed to view the issue
95
  def visible?(usr=nil)
96
    (usr || User.current).allowed_to?(:view_issues, self.project)
97
  end
98
  
99
  def after_initialize
100
    if new_record?
101
      # set default values for new records only
102
      self.status ||= IssueStatus.default
103
      self.priority ||= IssuePriority.default
104
    end
105
  end
106
  
107
  # Overrides Redmine::Acts::Customizable::InstanceMethods#available_custom_fields
108
  def available_custom_fields
109
    (project && tracker) ? project.all_issue_custom_fields.select {|c| tracker.custom_fields.include? c } : []
110
  end
111
  
112
  def copy_from(arg)
113
    issue = arg.is_a?(Issue) ? arg : Issue.visible.find(arg)
114
    self.attributes = issue.attributes.dup.except("id", "root_id", "parent_id", "lft", "rgt", "created_on", "updated_on")
115
    self.custom_field_values = issue.custom_field_values.inject({}) {|h,v| h[v.custom_field_id] = v.value; h}
116
    self.status = issue.status
117
    self
118
  end
119
  
120
  # Moves/copies an issue to a new project and tracker
121
  # Returns the moved/copied issue on success, false on failure
122
  def move_to_project(*args)
123
    ret = Issue.transaction do
124
      move_to_project_without_transaction(*args) || raise(ActiveRecord::Rollback)
125
    end || false
126
  end
127
  
128
  def move_to_project_without_transaction(new_project, new_tracker = nil, options = {})
129
    options ||= {}
130
    issue = options[:copy] ? self.class.new.copy_from(self) : self
131
    
132
    if new_project && issue.project_id != new_project.id
133
      # delete issue relations
134
      unless Setting.cross_project_issue_relations?
135
        issue.relations_from.clear
136
        issue.relations_to.clear
137
      end
138
      # issue is moved to another project
139
      # reassign to the category with same name if any
140
      new_category = issue.category.nil? ? nil : new_project.issue_categories.find_by_name(issue.category.name)
141
      issue.category = new_category
142
      # Keep the fixed_version if it's still valid in the new_project
143
      unless new_project.shared_versions.include?(issue.fixed_version)
144
        issue.fixed_version = nil
145
      end
146
      issue.project = new_project
147
      if issue.parent && issue.parent.project_id != issue.project_id
148
        issue.parent_issue_id = nil
149
      end
150
    end
151
    if new_tracker
152
      issue.tracker = new_tracker
153
      issue.reset_custom_values!
154
    end
155
    if options[:copy]
156
      issue.custom_field_values = self.custom_field_values.inject({}) {|h,v| h[v.custom_field_id] = v.value; h}
157
      issue.status = if options[:attributes] && options[:attributes][:status_id]
158
                       IssueStatus.find_by_id(options[:attributes][:status_id])
159
                     else
160
                       self.status
161
                     end
162
    end
163
    # Allow bulk setting of attributes on the issue
164
    if options[:attributes]
165
      issue.attributes = options[:attributes]
166
    end
167
    if issue.save
168
      unless options[:copy]
169
        # Manually update project_id on related time entries
170
        TimeEntry.update_all("project_id = #{new_project.id}", {:issue_id => id})
171
        
172
        issue.children.each do |child|
173
          unless child.move_to_project_without_transaction(new_project)
174
            # Move failed and transaction was rollback'd
175
            return false
176
          end
177
        end
178
      end
179
    else
180
      return false
181
    end
182
    issue
183
  end
184

    
185
  def status_id=(sid)
186
    self.status = nil
187
    write_attribute(:status_id, sid)
188
  end
189
  
190
  def priority_id=(pid)
191
    self.priority = nil
192
    write_attribute(:priority_id, pid)
193
  end
194

    
195
  def tracker_id=(tid)
196
    self.tracker = nil
197
    result = write_attribute(:tracker_id, tid)
198
    @custom_field_values = nil
199
    result
200
  end
201
  
202
  # Overrides attributes= so that tracker_id gets assigned first
203
  def attributes_with_tracker_first=(new_attributes, *args)
204
    return if new_attributes.nil?
205
    new_tracker_id = new_attributes['tracker_id'] || new_attributes[:tracker_id]
206
    if new_tracker_id
207
      self.tracker_id = new_tracker_id
208
    end
209
    send :attributes_without_tracker_first=, new_attributes, *args
210
  end
211
  # Do not redefine alias chain on reload (see #4838)
212
  alias_method_chain(:attributes=, :tracker_first) unless method_defined?(:attributes_without_tracker_first=)
213
  
214
  def estimated_hours=(h)
215
    write_attribute :estimated_hours, (h.is_a?(String) ? h.to_hours : h)
216
  end
217
  
218
  SAFE_ATTRIBUTES = %w(
219
    tracker_id
220
    status_id
221
    parent_issue_id
222
    category_id
223
    assigned_to_id
224
    priority_id
225
    fixed_version_id
226
    subject
227
    description
228
    start_date
229
    due_date
230
    done_ratio
231
    estimated_hours
232
    custom_field_values
233
    lock_version
234
  ) unless const_defined?(:SAFE_ATTRIBUTES)
235
  
236
  SAFE_ATTRIBUTES_ON_TRANSITION = %w(
237
    status_id
238
    assigned_to_id
239
    fixed_version_id
240
    done_ratio
241
  ) unless const_defined?(:SAFE_ATTRIBUTES_ON_TRANSITION)
242

    
243
  # Safely sets attributes
244
  # Should be called from controllers instead of #attributes=
245
  # attr_accessible is too rough because we still want things like
246
  # Issue.new(:project => foo) to work
247
  # TODO: move workflow/permission checks from controllers to here
248
  def safe_attributes=(attrs, user=User.current)
249
    return unless attrs.is_a?(Hash)
250
    
251
    # User can change issue attributes only if he has :edit permission or if a workflow transition is allowed
252
    if new_record? || user.allowed_to?(:edit_issues, project)
253
      attrs = attrs.reject {|k,v| !SAFE_ATTRIBUTES.include?(k)}
254
    elsif new_statuses_allowed_to(user).any?
255
      attrs = attrs.reject {|k,v| !SAFE_ATTRIBUTES_ON_TRANSITION.include?(k)}
256
    else
257
      return
258
    end
259
    
260
    # Tracker must be set before since new_statuses_allowed_to depends on it.
261
    if t = attrs.delete('tracker_id')
262
      self.tracker_id = t
263
    end
264
    
265
    if attrs['status_id']
266
      unless new_statuses_allowed_to(user).collect(&:id).include?(attrs['status_id'].to_i)
267
        attrs.delete('status_id')
268
      end
269
    end
270
    
271
    unless leaf?
272
      attrs.reject! {|k,v| %w(priority_id done_ratio start_date due_date estimated_hours).include?(k)}
273
    end
274
    
275
    if attrs.has_key?('parent_issue_id')
276
      if !user.allowed_to?(:manage_subtasks, project)
277
        attrs.delete('parent_issue_id')
278
      elsif !attrs['parent_issue_id'].blank?
279
        attrs.delete('parent_issue_id') unless Issue.visible(user).exists?(attrs['parent_issue_id'])
280
      end
281
    end
282
    
283
    self.attributes = attrs
284
  end
285
  
286
  def done_ratio
287
    if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
288
      status.default_done_ratio
289
    else
290
      read_attribute(:done_ratio)
291
    end
292
  end
293

    
294
  def self.use_status_for_done_ratio?
295
    Setting.issue_done_ratio == 'issue_status'
296
  end
297

    
298
  def self.use_field_for_done_ratio?
299
    Setting.issue_done_ratio == 'issue_field'
300
  end
301
  
302
  def validate
303
    if self.due_date.nil? && @attributes['due_date'] && !@attributes['due_date'].empty?
304
      errors.add :due_date, :not_a_date
305
    end
306
    
307
    if self.due_date and self.start_date and self.due_date < self.start_date
308
      errors.add :due_date, :greater_than_start_date
309
    end
310
    
311
    if start_date && soonest_start && start_date < soonest_start
312
      errors.add :start_date, :invalid
313
    end
314
    
315
    if fixed_version
316
      if !assignable_versions.include?(fixed_version)
317
        errors.add :fixed_version_id, :inclusion
318
      elsif reopened? && fixed_version.closed?
319
        errors.add_to_base I18n.t(:error_can_not_reopen_issue_on_closed_version)
320
      end
321
    end
322
    
323
    # Checks that the issue can not be added/moved to a disabled tracker
324
    if project && (tracker_id_changed? || project_id_changed?)
325
      unless project.trackers.include?(tracker)
326
        errors.add :tracker_id, :inclusion
327
      end
328
    end
329
    
330
    # Checks parent issue assignment
331
    if @parent_issue
332
      if @parent_issue.project_id != project_id
333
        errors.add :parent_issue_id, :not_same_project
334
      elsif !new_record?
335
        # moving an existing issue
336
        if @parent_issue.root_id != root_id
337
          # we can always move to another tree
338
        elsif move_possible?(@parent_issue)
339
          # move accepted inside tree
340
        else
341
          errors.add :parent_issue_id, :not_a_valid_parent
342
        end
343
      end
344
    end
345
  end
346
  
347
  # Set the done_ratio using the status if that setting is set.  This will keep the done_ratios
348
  # even if the user turns off the setting later
349
  def update_done_ratio_from_issue_status
350
    if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
351
      self.done_ratio = status.default_done_ratio
352
    end
353
  end
354
  
355
  def init_journal(user, notes = "")
356
    @current_journal ||= Journal.new(:journalized => self, :user => user, :notes => notes)
357
    @issue_before_change = self.clone
358
    @issue_before_change.status = self.status
359
    @custom_values_before_change = {}
360
    self.custom_values.each {|c| @custom_values_before_change.store c.custom_field_id, c.value }
361
    # Make sure updated_on is updated when adding a note.
362
    updated_on_will_change!
363
    @current_journal
364
  end
365
  
366
  # Return true if the issue is closed, otherwise false
367
  def closed?
368
    self.status.is_closed?
369
  end
370
  
371
  # Return true if the issue is being reopened
372
  def reopened?
373
    if !new_record? && status_id_changed?
374
      status_was = IssueStatus.find_by_id(status_id_was)
375
      status_new = IssueStatus.find_by_id(status_id)
376
      if status_was && status_new && status_was.is_closed? && !status_new.is_closed?
377
        return true
378
      end
379
    end
380
    false
381
  end
382

    
383
  # Return true if the issue is being closed
384
  def closing?
385
    if !new_record? && status_id_changed?
386
      status_was = IssueStatus.find_by_id(status_id_was)
387
      status_new = IssueStatus.find_by_id(status_id)
388
      if status_was && status_new && !status_was.is_closed? && status_new.is_closed?
389
        return true
390
      end
391
    end
392
    false
393
  end
394
  
395
  # Returns true if the issue is overdue
396
  def overdue?
397
    !due_date.nil? && (due_date < Date.today) && !status.is_closed?
398
  end
399

    
400
  # Is the amount of work done less than it should for the due date
401
  def behind_schedule?
402
    return false if start_date.nil? || due_date.nil?
403
    done_date = start_date + ((due_date - start_date+1)* done_ratio/100).floor
404
    return done_date <= Date.today
405
  end
406

    
407
  # Does this issue have children?
408
  def children?
409
    !leaf?
410
  end
411
  
412
  # Users the issue can be assigned to
413
  def assignable_users
414
    users = project.assignable_users
415
    users << author if author
416
    users.uniq.sort
417
  end
418
  
419
  # Versions that the issue can be assigned to
420
  def assignable_versions
421
    @assignable_versions ||= (project.shared_versions.open + [Version.find_by_id(fixed_version_id_was)]).compact.uniq.sort
422
  end
423
  
424
  # Returns true if this issue is blocked by another issue that is still open
425
  def blocked?
426
    !relations_to.detect {|ir| ir.relation_type == 'blocks' && !ir.issue_from.closed?}.nil?
427
  end
428
  
429
  # Returns an array of status that user is able to apply
430
  def new_statuses_allowed_to(user, include_default=false)
431
    statuses = status.find_new_statuses_allowed_to(user.roles_for_project(project), tracker)
432
    statuses << status unless statuses.empty?
433
    statuses << IssueStatus.default if include_default
434
    statuses = statuses.uniq.sort
435
    blocked? ? statuses.reject {|s| s.is_closed?} : statuses
436
  end
437
  
438
  # Returns the mail adresses of users that should be notified
439
  def recipients
440
    notified = project.notified_users
441
    # Author and assignee are always notified unless they have been
442
    # locked or don't want to be notified
443
    notified << author if author && author.active? && author.notify_about?(self)
444
    notified << assigned_to if assigned_to && assigned_to.active? && assigned_to.notify_about?(self)
445
    notified.uniq!
446
    # Remove users that can not view the issue
447
    notified.reject! {|user| !visible?(user)}
448
    notified.collect(&:mail)
449
  end
450
  
451
  # Returns the total number of hours spent on this issue and its descendants
452
  #
453
  # Example:
454
  #   spent_hours => 0.0
455
  #   spent_hours => 50.2
456
  def spent_hours
457
    @spent_hours ||= self_and_descendants.sum("#{TimeEntry.table_name}.hours", :include => :time_entries).to_f || 0.0
458
  end
459
  
460
  def relations
461
    (relations_from + relations_to).sort
462
  end
463
  
464
  def all_dependent_issues
465
    dependencies = []
466
    relations_from.each do |relation|
467
      dependencies << relation.issue_to
468
      dependencies += relation.issue_to.all_dependent_issues
469
    end
470
    dependencies
471
  end
472
  
473
  # Returns an array of issues that duplicate this one
474
  def duplicates
475
    relations_to.select {|r| r.relation_type == IssueRelation::TYPE_DUPLICATES}.collect {|r| r.issue_from}
476
  end
477
  
478
  # Returns the due date or the target due date if any
479
  # Used on gantt chart
480
  def due_before
481
    due_date || (fixed_version ? fixed_version.effective_date : nil)
482
  end
483
  
484
  # Returns the time scheduled for this issue.
485
  # 
486
  # Example:
487
  #   Start Date: 2/26/09, End Date: 3/04/09
488
  #   duration => 6
489
  def duration
490
    (start_date && due_date) ? due_date - start_date : 0
491
  end
492
  
493
  def soonest_start
494
    @soonest_start ||= (
495
        relations_to.collect{|relation| relation.successor_soonest_start} +
496
        ancestors.collect(&:soonest_start)
497
      ).compact.max
498
  end
499
  
500
  def reschedule_after(date)
501
    return if date.nil?
502
    if leaf?
503
      if start_date.nil? || start_date < date
504
        self.start_date, self.due_date = date, date + duration
505
        save
506
      end
507
    else
508
      leaves.each do |leaf|
509
        leaf.reschedule_after(date)
510
      end
511
    end
512
  end
513
  
514
  def <=>(issue)
515
    if issue.nil?
516
      -1
517
    elsif root_id != issue.root_id
518
      (root_id || 0) <=> (issue.root_id || 0)
519
    else
520
      (lft || 0) <=> (issue.lft || 0)
521
    end
522
  end
523
  
524
  def to_s
525
    "#{tracker} ##{id}: #{subject}"
526
  end
527
  
528
  # Returns a string of css classes that apply to the issue
529
  def css_classes
530
    s = "issue status-#{status.position} "
531
    s << "priority-#{priority.position}"
532
    s << ' closed' if closed?
533
    s << ' overdue' if overdue?
534
    s << ' created-by-me' if User.current.logged? && author_id == User.current.id
535
    s << ' assigned-to-me' if User.current.logged? && assigned_to_id == User.current.id
536
    s
537
  end
538

    
539
  # Saves an issue, time_entry, attachments, and a journal from the parameters
540
  # Returns false if save fails
541
  def save_issue_with_child_records(params, existing_time_entry=nil)
542
    Issue.transaction do
543
      if params[:time_entry] && params[:time_entry][:hours].present? && User.current.allowed_to?(:log_time, project)
544
        @time_entry = existing_time_entry || TimeEntry.new
545
        @time_entry.project = project
546
        @time_entry.issue = self
547
        @time_entry.user = User.current
548
        @time_entry.spent_on = Date.today
549
        @time_entry.attributes = params[:time_entry]
550
        self.time_entries << @time_entry
551
      end
552
  
553
      if valid?
554
        attachments = Attachment.attach_files(self, params[:attachments])
555
  
556
        attachments[:files].each {|a| @current_journal.details << JournalDetail.new(:property => 'attachment', :prop_key => a.id, :value => a.filename)}
557
        # TODO: Rename hook
558
        Redmine::Hook.call_hook(:controller_issues_edit_before_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
559
        begin
560
          if save
561
            # TODO: Rename hook
562
            Redmine::Hook.call_hook(:controller_issues_edit_after_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
563
          else
564
            raise ActiveRecord::Rollback
565
          end
566
        rescue ActiveRecord::StaleObjectError
567
          attachments[:files].each(&:destroy)
568
          errors.add_to_base l(:notice_locking_conflict)
569
          raise ActiveRecord::Rollback
570
        end
571
      end
572
    end
573
  end
574

    
575
  # Unassigns issues from +version+ if it's no longer shared with issue's project
576
  def self.update_versions_from_sharing_change(version)
577
    # Update issues assigned to the version
578
    update_versions(["#{Issue.table_name}.fixed_version_id = ?", version.id])
579
  end
580
  
581
  # Unassigns issues from versions that are no longer shared
582
  # after +project+ was moved
583
  def self.update_versions_from_hierarchy_change(project)
584
    moved_project_ids = project.self_and_descendants.reload.collect(&:id)
585
    # Update issues of the moved projects and issues assigned to a version of a moved project
586
    Issue.update_versions(["#{Version.table_name}.project_id IN (?) OR #{Issue.table_name}.project_id IN (?)", moved_project_ids, moved_project_ids])
587
  end
588

    
589
  def parent_issue_id=(arg)
590
    parent_issue_id = arg.blank? ? nil : arg.to_i
591
    if parent_issue_id && @parent_issue = Issue.find_by_id(parent_issue_id)
592
      @parent_issue.id
593
    else
594
      @parent_issue = nil
595
      nil
596
    end
597
  end
598
  
599
  def parent_issue_id
600
    if instance_variable_defined? :@parent_issue
601
      @parent_issue.nil? ? nil : @parent_issue.id
602
    else
603
      parent_id
604
    end
605
  end
606

    
607
  # Extracted from the ReportsController.
608
  def self.by_tracker(project)
609
    count_and_group_by(:project => project,
610
                       :field => 'tracker_id',
611
                       :joins => Tracker.table_name)
612
  end
613

    
614
  def self.by_version(project)
615
    count_and_group_by(:project => project,
616
                       :field => 'fixed_version_id',
617
                       :joins => Version.table_name)
618
  end
619

    
620
  def self.by_priority(project)
621
    count_and_group_by(:project => project,
622
                       :field => 'priority_id',
623
                       :joins => IssuePriority.table_name)
624
  end
625

    
626
  def self.by_category(project)
627
    count_and_group_by(:project => project,
628
                       :field => 'category_id',
629
                       :joins => IssueCategory.table_name)
630
  end
631

    
632
  def self.by_assigned_to(project)
633
    count_and_group_by(:project => project,
634
                       :field => 'assigned_to_id',
635
                       :joins => User.table_name)
636
  end
637

    
638
  def self.by_author(project)
639
    count_and_group_by(:project => project,
640
                       :field => 'author_id',
641
                       :joins => User.table_name)
642
  end
643

    
644
  def self.by_subproject(project)
645
    ActiveRecord::Base.connection.select_all("select    s.id as status_id, 
646
                                                s.is_closed as closed, 
647
                                                i.project_id as project_id,
648
                                                count(i.id) as total 
649
                                              from 
650
                                                #{Issue.table_name} i, #{IssueStatus.table_name} s
651
                                              where 
652
                                                i.status_id=s.id 
653
                                                and i.project_id IN (#{project.descendants.active.collect{|p| p.id}.join(',')})
654
                                              group by s.id, s.is_closed, i.project_id") if project.descendants.active.any?
655
  end
656
  # End ReportsController extraction
657
  
658
  # Returns an array of projects that current user can move issues to
659
  def self.allowed_target_projects_on_move
660
    projects = []
661
    if User.current.admin?
662
      # admin is allowed to move issues to any active (visible) project
663
      projects = Project.visible.all
664
    elsif User.current.logged?
665
      if Role.non_member.allowed_to?(:move_issues)
666
        projects = Project.visible.all
667
      else
668
        User.current.memberships.each {|m| projects << m.project if m.roles.detect {|r| r.allowed_to?(:move_issues)}}
669
      end
670
    end
671
    projects
672
  end
673
   
674
  private
675
  
676
  def update_nested_set_attributes
677
    if root_id.nil?
678
      # issue was just created
679
      self.root_id = (@parent_issue.nil? ? id : @parent_issue.root_id)
680
      set_default_left_and_right
681
      Issue.update_all("root_id = #{root_id}, lft = #{lft}, rgt = #{rgt}", ["id = ?", id])
682
      if @parent_issue
683
        move_to_child_of(@parent_issue)
684
      end
685
      reload
686
    elsif parent_issue_id != parent_id
687
      former_parent_id = parent_id
688
      # moving an existing issue
689
      if @parent_issue && @parent_issue.root_id == root_id
690
        # inside the same tree
691
        move_to_child_of(@parent_issue)
692
      else
693
        # to another tree
694
        unless root?
695
          move_to_right_of(root)
696
          reload
697
        end
698
        old_root_id = root_id
699
        self.root_id = (@parent_issue.nil? ? id : @parent_issue.root_id )
700
        target_maxright = nested_set_scope.maximum(right_column_name) || 0
701
        offset = target_maxright + 1 - lft
702
        Issue.update_all("root_id = #{root_id}, lft = lft + #{offset}, rgt = rgt + #{offset}",
703
                          ["root_id = ? AND lft >= ? AND rgt <= ? ", old_root_id, lft, rgt])
704
        self[left_column_name] = lft + offset
705
        self[right_column_name] = rgt + offset
706
        if @parent_issue
707
          move_to_child_of(@parent_issue)
708
        end
709
      end
710
      reload
711
      # delete invalid relations of all descendants
712
      self_and_descendants.each do |issue|
713
        issue.relations.each do |relation|
714
          relation.destroy unless relation.valid?
715
        end
716
      end
717
      # update former parent
718
      recalculate_attributes_for(former_parent_id) if former_parent_id
719
    end
720
    remove_instance_variable(:@parent_issue) if instance_variable_defined?(:@parent_issue)
721
  end
722
  
723
  def update_parent_attributes
724
    recalculate_attributes_for(parent_id) if parent_id
725
  end
726

    
727
  def recalculate_attributes_for(issue_id)
728
    if issue_id && p = Issue.find_by_id(issue_id)
729
      # priority = highest priority of children
730
      if priority_position = p.children.maximum("#{IssuePriority.table_name}.position", :include => :priority)
731
        p.priority = IssuePriority.find_by_position(priority_position)
732
      end
733
      
734
      # start/due dates = lowest/highest dates of children
735
      p.start_date = p.children.minimum(:start_date)
736
      p.due_date = p.children.maximum(:due_date)
737
      if p.start_date && p.due_date && p.due_date < p.start_date
738
        p.start_date, p.due_date = p.due_date, p.start_date
739
      end
740
      
741
      # done ratio = weighted average ratio of leaves
742
      unless Issue.use_status_for_done_ratio? && p.status && p.status.default_done_ratio
743
        leaves_count = p.leaves.count
744
        if leaves_count > 0
745
          average = p.leaves.average(:estimated_hours).to_f
746
          if average == 0
747
            average = 1
748
          end
749
          done = p.leaves.sum("COALESCE(estimated_hours, #{average}) * (CASE WHEN is_closed = #{connection.quoted_true} THEN 100 ELSE COALESCE(done_ratio, 0) END)", :include => :status).to_f
750
          progress = done / (average * leaves_count)
751
          p.done_ratio = progress.round
752
        end
753
      end
754
      
755
      # estimate = sum of leaves estimates
756
      p.estimated_hours = p.leaves.sum(:estimated_hours).to_f
757
      p.estimated_hours = nil if p.estimated_hours == 0.0
758
      
759
      # ancestors will be recursively updated
760
      p.save(false)
761
    end
762
  end
763
  
764
  def destroy_children
765
    unless leaf?
766
      children.each do |child|
767
        child.destroy
768
      end
769
    end
770
  end
771
  
772
  # Update issues so their versions are not pointing to a
773
  # fixed_version that is not shared with the issue's project
774
  def self.update_versions(conditions=nil)
775
    # Only need to update issues with a fixed_version from
776
    # a different project and that is not systemwide shared
777
    Issue.all(:conditions => merge_conditions("#{Issue.table_name}.fixed_version_id IS NOT NULL" +
778
                                                " AND #{Issue.table_name}.project_id <> #{Version.table_name}.project_id" +
779
                                                " AND #{Version.table_name}.sharing <> 'system'",
780
                                                conditions),
781
              :include => [:project, :fixed_version]
782
              ).each do |issue|
783
      next if issue.project.nil? || issue.fixed_version.nil?
784
      unless issue.project.shared_versions.include?(issue.fixed_version)
785
        issue.init_journal(User.current)
786
        issue.fixed_version = nil
787
        issue.save
788
      end
789
    end
790
  end
791
  
792
  # Callback on attachment deletion
793
  def attachment_removed(obj)
794
    journal = init_journal(User.current)
795
    journal.details << JournalDetail.new(:property => 'attachment',
796
                                         :prop_key => obj.id,
797
                                         :old_value => obj.filename)
798
    journal.save
799
  end
800
  
801
  # Default assignment based on category
802
  def default_assign
803
    if assigned_to.nil? && category && category.assigned_to
804
      self.assigned_to = category.assigned_to
805
    end
806
  end
807

    
808
  # Updates start/due dates of following issues
809
  def reschedule_following_issues
810
    if start_date_changed? || due_date_changed?
811
      relations_from.each do |relation|
812
        relation.set_issue_to_dates
813
      end
814
    end
815
  end
816

    
817
  # Closes duplicates if the issue is being closed
818
  def close_duplicates
819
    if closing?
820
      duplicates.each do |duplicate|
821
        # Reload is need in case the duplicate was updated by a previous duplicate
822
        duplicate.reload
823
        # Don't re-close it if it's already closed
824
        next if duplicate.closed?
825
        # Same user and notes
826
        if @current_journal
827
          duplicate.init_journal(@current_journal.user, @current_journal.notes)
828
        end
829
        duplicate.update_attribute :status, self.status
830
      end
831
    end
832
  end
833
  
834
  # Saves the changes in a Journal
835
  # Called after_save
836
  def create_journal
837
    if @current_journal
838
      # attributes changes
839
      (Issue.column_names - %w(id description root_id lft rgt lock_version created_on updated_on)).each {|c|
840
        @current_journal.details << JournalDetail.new(:property => 'attr',
841
                                                      :prop_key => c,
842
                                                      :old_value => @issue_before_change.send(c),
843
                                                      :value => send(c)) unless send(c)==@issue_before_change.send(c)
844
      }
845
      # custom fields changes
846
      custom_values.each {|c|
847
        next if (@custom_values_before_change[c.custom_field_id]==c.value ||
848
                  (@custom_values_before_change[c.custom_field_id].blank? && c.value.blank?))
849
        @current_journal.details << JournalDetail.new(:property => 'cf', 
850
                                                      :prop_key => c.custom_field_id,
851
                                                      :old_value => @custom_values_before_change[c.custom_field_id],
852
                                                      :value => c.value)
853
      }      
854
      @current_journal.save
855
      # reset current journal
856
      init_journal @current_journal.user, @current_journal.notes
857
    end
858
  end
859

    
860
  # Query generator for selecting groups of issue counts for a project
861
  # based on specific criteria
862
  #
863
  # Options
864
  # * project - Project to search in.
865
  # * field - String. Issue field to key off of in the grouping.
866
  # * joins - String. The table name to join against.
867
  def self.count_and_group_by(options)
868
    project = options.delete(:project)
869
    select_field = options.delete(:field)
870
    joins = options.delete(:joins)
871

    
872
    where = "i.#{select_field}=j.id"
873
    
874
    ActiveRecord::Base.connection.select_all("select    s.id as status_id, 
875
                                                s.is_closed as closed, 
876
                                                j.id as #{select_field},
877
                                                count(i.id) as total 
878
                                              from 
879
                                                  #{Issue.table_name} i, #{IssueStatus.table_name} s, #{joins} j
880
                                              where 
881
                                                i.status_id=s.id 
882
                                                and #{where}
883
                                                and i.project_id=#{project.id}
884
                                              group by s.id, s.is_closed, j.id")
885
  end
886
  
887

    
888
end