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 @ 723:d41bf754c0f2

History | View | Annotate | Download (33.4 KB)

1
# Redmine - project management software
2
# Copyright (C) 2006-2011  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
  include Redmine::SafeAttributes
20

    
21
  belongs_to :project
22
  belongs_to :tracker
23
  belongs_to :status, :class_name => 'IssueStatus', :foreign_key => 'status_id'
24
  belongs_to :author, :class_name => 'User', :foreign_key => 'author_id'
25
  belongs_to :assigned_to, :class_name => 'User', :foreign_key => 'assigned_to_id'
26
  belongs_to :fixed_version, :class_name => 'Version', :foreign_key => 'fixed_version_id'
27
  belongs_to :priority, :class_name => 'IssuePriority', :foreign_key => 'priority_id'
28
  belongs_to :category, :class_name => 'IssueCategory', :foreign_key => 'category_id'
29

    
30
  has_many :journals, :as => :journalized, :dependent => :destroy
31
  has_many :time_entries, :dependent => :delete_all
32
  has_and_belongs_to_many :changesets, :order => "#{Changeset.table_name}.committed_on ASC, #{Changeset.table_name}.id ASC"
33

    
34
  has_many :relations_from, :class_name => 'IssueRelation', :foreign_key => 'issue_from_id', :dependent => :delete_all
35
  has_many :relations_to, :class_name => 'IssueRelation', :foreign_key => 'issue_to_id', :dependent => :delete_all
36

    
37
  acts_as_nested_set :scope => 'root_id', :dependent => :destroy
38
  acts_as_attachable :after_remove => :attachment_removed
39
  acts_as_customizable
40
  acts_as_watchable
41
  acts_as_searchable :columns => ['subject', "#{table_name}.description", "#{Journal.table_name}.notes"],
42
                     :include => [:project, :journals],
43
                     # sort by id so that limited eager loading doesn't break with postgresql
44
                     :order_column => "#{table_name}.id"
45
  acts_as_event :title => Proc.new {|o| "#{o.tracker.name} ##{o.id} (#{o.status}): #{o.subject}"},
46
                :url => Proc.new {|o| {:controller => 'issues', :action => 'show', :id => o.id}},
47
                :type => Proc.new {|o| 'issue' + (o.closed? ? ' closed' : '') }
48

    
49
  acts_as_activity_provider :find_options => {:include => [:project, :author, :tracker]},
50
                            :author_key => :author_id
51

    
52
  DONE_RATIO_OPTIONS = %w(issue_field issue_status)
53

    
54
  attr_reader :current_journal
55

    
56
  validates_presence_of :subject, :priority, :project, :tracker, :author, :status
57

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

    
62
  named_scope :visible, lambda {|*args| { :include => :project,
63
                                          :conditions => Issue.visible_condition(args.shift || User.current, *args) } }
64

    
65
  named_scope :open, :conditions => ["#{IssueStatus.table_name}.is_closed = ?", false], :include => :status
66

    
67
  named_scope :recently_updated, :order => "#{Issue.table_name}.updated_on DESC"
68
  named_scope :with_limit, lambda { |limit| { :limit => limit} }
69
  named_scope :on_active_project, :include => [:status, :project, :tracker],
70
                                  :conditions => ["#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"]
71

    
72
  named_scope :without_version, lambda {
73
    {
74
      :conditions => { :fixed_version_id => nil}
75
    }
76
  }
77

    
78
  named_scope :with_query, lambda {|query|
79
    {
80
      :conditions => Query.merge_conditions(query.statement)
81
    }
82
  }
83

    
84
  before_create :default_assign
85
  before_save :close_duplicates, :update_done_ratio_from_issue_status
86
  after_save :reschedule_following_issues, :update_nested_set_attributes, :update_parent_attributes, :create_journal
87
  after_destroy :update_parent_attributes
88

    
89
  # Returns a SQL conditions string used to find all issues visible by the specified user
90
  def self.visible_condition(user, options={})
91
    Project.allowed_to_condition(user, :view_issues, options) do |role, user|
92
      case role.issues_visibility
93
      when 'all'
94
        nil
95
      when 'default'
96
        "(#{table_name}.is_private = #{connection.quoted_false} OR #{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id = #{user.id})"
97
      when 'own'
98
        "(#{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id = #{user.id})"
99
      else
100
        '1=0'
101
      end
102
    end
103
  end
104

    
105
  # Returns true if usr or current user is allowed to view the issue
106
  def visible?(usr=nil)
107
    (usr || User.current).allowed_to?(:view_issues, self.project) do |role, user|
108
      case role.issues_visibility
109
      when 'all'
110
        true
111
      when 'default'
112
        !self.is_private? || self.author == user || self.assigned_to == user
113
      when 'own'
114
        self.author == user || self.assigned_to == user
115
      else
116
        false
117
      end
118
    end
119
  end
120

    
121
  def after_initialize
122
    if new_record?
123
      # set default values for new records only
124
      self.status ||= IssueStatus.default
125
      self.priority ||= IssuePriority.default
126
    end
127
  end
128

    
129
  # Overrides Redmine::Acts::Customizable::InstanceMethods#available_custom_fields
130
  def available_custom_fields
131
    (project && tracker) ? (project.all_issue_custom_fields & tracker.custom_fields.all) : []
132
  end
133

    
134
  def copy_from(arg)
135
    issue = arg.is_a?(Issue) ? arg : Issue.visible.find(arg)
136
    self.attributes = issue.attributes.dup.except("id", "root_id", "parent_id", "lft", "rgt", "created_on", "updated_on")
137
    self.custom_field_values = issue.custom_field_values.inject({}) {|h,v| h[v.custom_field_id] = v.value; h}
138
    self.status = issue.status
139
    self
140
  end
141

    
142
  # Moves/copies an issue to a new project and tracker
143
  # Returns the moved/copied issue on success, false on failure
144
  def move_to_project(*args)
145
    ret = Issue.transaction do
146
      move_to_project_without_transaction(*args) || raise(ActiveRecord::Rollback)
147
    end || false
148
  end
149

    
150
  def move_to_project_without_transaction(new_project, new_tracker = nil, options = {})
151
    options ||= {}
152
    issue = options[:copy] ? self.class.new.copy_from(self) : self
153

    
154
    if new_project && issue.project_id != new_project.id
155
      # delete issue relations
156
      unless Setting.cross_project_issue_relations?
157
        issue.relations_from.clear
158
        issue.relations_to.clear
159
      end
160
      # issue is moved to another project
161
      # reassign to the category with same name if any
162
      new_category = issue.category.nil? ? nil : new_project.issue_categories.find_by_name(issue.category.name)
163
      issue.category = new_category
164
      # Keep the fixed_version if it's still valid in the new_project
165
      unless new_project.shared_versions.include?(issue.fixed_version)
166
        issue.fixed_version = nil
167
      end
168
      issue.project = new_project
169
      if issue.parent && issue.parent.project_id != issue.project_id
170
        issue.parent_issue_id = nil
171
      end
172
    end
173
    if new_tracker
174
      issue.tracker = new_tracker
175
      issue.reset_custom_values!
176
    end
177
    if options[:copy]
178
      issue.author = User.current
179
      issue.custom_field_values = self.custom_field_values.inject({}) {|h,v| h[v.custom_field_id] = v.value; h}
180
      issue.status = if options[:attributes] && options[:attributes][:status_id]
181
                       IssueStatus.find_by_id(options[:attributes][:status_id])
182
                     else
183
                       self.status
184
                     end
185
    end
186
    # Allow bulk setting of attributes on the issue
187
    if options[:attributes]
188
      issue.attributes = options[:attributes]
189
    end
190
    if issue.save
191
      if options[:copy]
192
        if current_journal && current_journal.notes.present?
193
          issue.init_journal(current_journal.user, current_journal.notes)
194
          issue.current_journal.notify = false
195
          issue.save
196
        end
197
      else
198
        # Manually update project_id on related time entries
199
        TimeEntry.update_all("project_id = #{new_project.id}", {:issue_id => id})
200

    
201
        issue.children.each do |child|
202
          unless child.move_to_project_without_transaction(new_project)
203
            # Move failed and transaction was rollback'd
204
            return false
205
          end
206
        end
207
      end
208
    else
209
      return false
210
    end
211
    issue
212
  end
213

    
214
  def status_id=(sid)
215
    self.status = nil
216
    write_attribute(:status_id, sid)
217
  end
218

    
219
  def priority_id=(pid)
220
    self.priority = nil
221
    write_attribute(:priority_id, pid)
222
  end
223

    
224
  def tracker_id=(tid)
225
    self.tracker = nil
226
    result = write_attribute(:tracker_id, tid)
227
    @custom_field_values = nil
228
    result
229
  end
230
  
231
  def description=(arg)
232
    if arg.is_a?(String)
233
      arg = arg.gsub(/(\r\n|\n|\r)/, "\r\n")
234
    end
235
    write_attribute(:description, arg)
236
  end
237

    
238
  # Overrides attributes= so that tracker_id gets assigned first
239
  def attributes_with_tracker_first=(new_attributes, *args)
240
    return if new_attributes.nil?
241
    new_tracker_id = new_attributes['tracker_id'] || new_attributes[:tracker_id]
242
    if new_tracker_id
243
      self.tracker_id = new_tracker_id
244
    end
245
    send :attributes_without_tracker_first=, new_attributes, *args
246
  end
247
  # Do not redefine alias chain on reload (see #4838)
248
  alias_method_chain(:attributes=, :tracker_first) unless method_defined?(:attributes_without_tracker_first=)
249

    
250
  def estimated_hours=(h)
251
    write_attribute :estimated_hours, (h.is_a?(String) ? h.to_hours : h)
252
  end
253

    
254
  safe_attributes 'tracker_id',
255
    'status_id',
256
    'parent_issue_id',
257
    'category_id',
258
    'assigned_to_id',
259
    'priority_id',
260
    'fixed_version_id',
261
    'subject',
262
    'description',
263
    'start_date',
264
    'due_date',
265
    'done_ratio',
266
    'estimated_hours',
267
    'custom_field_values',
268
    'custom_fields',
269
    'lock_version',
270
    :if => lambda {|issue, user| issue.new_record? || user.allowed_to?(:edit_issues, issue.project) }
271

    
272
  safe_attributes 'status_id',
273
    'assigned_to_id',
274
    'fixed_version_id',
275
    'done_ratio',
276
    :if => lambda {|issue, user| issue.new_statuses_allowed_to(user).any? }
277

    
278
  safe_attributes 'is_private',
279
    :if => lambda {|issue, user|
280
      user.allowed_to?(:set_issues_private, issue.project) ||
281
        (issue.author == user && user.allowed_to?(:set_own_issues_private, issue.project))
282
    }
283

    
284
  # Safely sets attributes
285
  # Should be called from controllers instead of #attributes=
286
  # attr_accessible is too rough because we still want things like
287
  # Issue.new(:project => foo) to work
288
  # TODO: move workflow/permission checks from controllers to here
289
  def safe_attributes=(attrs, user=User.current)
290
    return unless attrs.is_a?(Hash)
291

    
292
    # User can change issue attributes only if he has :edit permission or if a workflow transition is allowed
293
    attrs = delete_unsafe_attributes(attrs, user)
294
    return if attrs.empty?
295

    
296
    # Tracker must be set before since new_statuses_allowed_to depends on it.
297
    if t = attrs.delete('tracker_id')
298
      self.tracker_id = t
299
    end
300

    
301
    if attrs['status_id']
302
      unless new_statuses_allowed_to(user).collect(&:id).include?(attrs['status_id'].to_i)
303
        attrs.delete('status_id')
304
      end
305
    end
306

    
307
    unless leaf?
308
      attrs.reject! {|k,v| %w(priority_id done_ratio start_date due_date estimated_hours).include?(k)}
309
    end
310

    
311
    if attrs.has_key?('parent_issue_id')
312
      if !user.allowed_to?(:manage_subtasks, project)
313
        attrs.delete('parent_issue_id')
314
      elsif !attrs['parent_issue_id'].blank?
315
        attrs.delete('parent_issue_id') unless Issue.visible(user).exists?(attrs['parent_issue_id'].to_i)
316
      end
317
    end
318

    
319
    self.attributes = attrs
320
  end
321

    
322
  def done_ratio
323
    if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
324
      status.default_done_ratio
325
    else
326
      read_attribute(:done_ratio)
327
    end
328
  end
329

    
330
  def self.use_status_for_done_ratio?
331
    Setting.issue_done_ratio == 'issue_status'
332
  end
333

    
334
  def self.use_field_for_done_ratio?
335
    Setting.issue_done_ratio == 'issue_field'
336
  end
337

    
338
  def validate
339
    if self.due_date.nil? && @attributes['due_date'] && !@attributes['due_date'].empty?
340
      errors.add :due_date, :not_a_date
341
    end
342

    
343
    if self.due_date and self.start_date and self.due_date < self.start_date
344
      errors.add :due_date, :greater_than_start_date
345
    end
346

    
347
    if start_date && soonest_start && start_date < soonest_start
348
      errors.add :start_date, :invalid
349
    end
350

    
351
    if fixed_version
352
      if !assignable_versions.include?(fixed_version)
353
        errors.add :fixed_version_id, :inclusion
354
      elsif reopened? && fixed_version.closed?
355
        errors.add_to_base I18n.t(:error_can_not_reopen_issue_on_closed_version)
356
      end
357
    end
358

    
359
    # Checks that the issue can not be added/moved to a disabled tracker
360
    if project && (tracker_id_changed? || project_id_changed?)
361
      unless project.trackers.include?(tracker)
362
        errors.add :tracker_id, :inclusion
363
      end
364
    end
365

    
366
    # Checks parent issue assignment
367
    if @parent_issue
368
      if @parent_issue.project_id != project_id
369
        errors.add :parent_issue_id, :not_same_project
370
      elsif !new_record?
371
        # moving an existing issue
372
        if @parent_issue.root_id != root_id
373
          # we can always move to another tree
374
        elsif move_possible?(@parent_issue)
375
          # move accepted inside tree
376
        else
377
          errors.add :parent_issue_id, :not_a_valid_parent
378
        end
379
      end
380
    end
381
  end
382

    
383
  # Set the done_ratio using the status if that setting is set.  This will keep the done_ratios
384
  # even if the user turns off the setting later
385
  def update_done_ratio_from_issue_status
386
    if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
387
      self.done_ratio = status.default_done_ratio
388
    end
389
  end
390

    
391
  def init_journal(user, notes = "")
392
    @current_journal ||= Journal.new(:journalized => self, :user => user, :notes => notes)
393
    @issue_before_change = self.clone
394
    @issue_before_change.status = self.status
395
    @custom_values_before_change = {}
396
    self.custom_values.each {|c| @custom_values_before_change.store c.custom_field_id, c.value }
397
    # Make sure updated_on is updated when adding a note.
398
    updated_on_will_change!
399
    @current_journal
400
  end
401

    
402
  # Return true if the issue is closed, otherwise false
403
  def closed?
404
    self.status.is_closed?
405
  end
406

    
407
  # Return true if the issue is being reopened
408
  def reopened?
409
    if !new_record? && status_id_changed?
410
      status_was = IssueStatus.find_by_id(status_id_was)
411
      status_new = IssueStatus.find_by_id(status_id)
412
      if status_was && status_new && status_was.is_closed? && !status_new.is_closed?
413
        return true
414
      end
415
    end
416
    false
417
  end
418

    
419
  # Return true if the issue is being closed
420
  def closing?
421
    if !new_record? && status_id_changed?
422
      status_was = IssueStatus.find_by_id(status_id_was)
423
      status_new = IssueStatus.find_by_id(status_id)
424
      if status_was && status_new && !status_was.is_closed? && status_new.is_closed?
425
        return true
426
      end
427
    end
428
    false
429
  end
430

    
431
  # Returns true if the issue is overdue
432
  def overdue?
433
    !due_date.nil? && (due_date < Date.today) && !status.is_closed?
434
  end
435

    
436
  # Is the amount of work done less than it should for the due date
437
  def behind_schedule?
438
    return false if start_date.nil? || due_date.nil?
439
    done_date = start_date + ((due_date - start_date+1)* done_ratio/100).floor
440
    return done_date <= Date.today
441
  end
442

    
443
  # Does this issue have children?
444
  def children?
445
    !leaf?
446
  end
447

    
448
  # Users the issue can be assigned to
449
  def assignable_users
450
    users = project.assignable_users
451
    users << author if author
452
    users.uniq.sort
453
  end
454

    
455
  # Versions that the issue can be assigned to
456
  def assignable_versions
457
    @assignable_versions ||= (project.shared_versions.open + [Version.find_by_id(fixed_version_id_was)]).compact.uniq.sort
458
  end
459

    
460
  # Returns true if this issue is blocked by another issue that is still open
461
  def blocked?
462
    !relations_to.detect {|ir| ir.relation_type == 'blocks' && !ir.issue_from.closed?}.nil?
463
  end
464

    
465
  # Returns an array of status that user is able to apply
466
  def new_statuses_allowed_to(user, include_default=false)
467
    statuses = status.find_new_statuses_allowed_to(
468
      user.roles_for_project(project),
469
      tracker,
470
      author == user,
471
      assigned_to_id_changed? ? assigned_to_id_was == user.id : assigned_to_id == user.id
472
      )
473
    statuses << status unless statuses.empty?
474
    statuses << IssueStatus.default if include_default
475
    statuses = statuses.uniq.sort
476
    blocked? ? statuses.reject {|s| s.is_closed?} : statuses
477
  end
478

    
479
  # Returns the mail adresses of users that should be notified
480
  def recipients
481
    notified = project.notified_users
482
    # Author and assignee are always notified unless they have been
483
    # locked or don't want to be notified
484
    notified << author if author && author.active? && author.notify_about?(self)
485
    notified << assigned_to if assigned_to && assigned_to.active? && assigned_to.notify_about?(self)
486
    notified.uniq!
487
    # Remove users that can not view the issue
488
    notified.reject! {|user| !visible?(user)}
489
    notified.collect(&:mail)
490
  end
491

    
492
  # Returns the total number of hours spent on this issue and its descendants
493
  #
494
  # Example:
495
  #   spent_hours => 0.0
496
  #   spent_hours => 50.2
497
  def spent_hours
498
    @spent_hours ||= self_and_descendants.sum("#{TimeEntry.table_name}.hours", :include => :time_entries).to_f || 0.0
499
  end
500

    
501
  def relations
502
    (relations_from + relations_to).sort
503
  end
504

    
505
  def all_dependent_issues(except=[])
506
    except << self
507
    dependencies = []
508
    relations_from.each do |relation|
509
      if relation.issue_to && !except.include?(relation.issue_to)
510
        dependencies << relation.issue_to
511
        dependencies += relation.issue_to.all_dependent_issues(except)
512
      end
513
    end
514
    dependencies
515
  end
516

    
517
  # Returns an array of issues that duplicate this one
518
  def duplicates
519
    relations_to.select {|r| r.relation_type == IssueRelation::TYPE_DUPLICATES}.collect {|r| r.issue_from}
520
  end
521

    
522
  # Returns the due date or the target due date if any
523
  # Used on gantt chart
524
  def due_before
525
    due_date || (fixed_version ? fixed_version.effective_date : nil)
526
  end
527

    
528
  # Returns the time scheduled for this issue.
529
  #
530
  # Example:
531
  #   Start Date: 2/26/09, End Date: 3/04/09
532
  #   duration => 6
533
  def duration
534
    (start_date && due_date) ? due_date - start_date : 0
535
  end
536

    
537
  def soonest_start
538
    @soonest_start ||= (
539
        relations_to.collect{|relation| relation.successor_soonest_start} +
540
        ancestors.collect(&:soonest_start)
541
      ).compact.max
542
  end
543

    
544
  def reschedule_after(date)
545
    return if date.nil?
546
    if leaf?
547
      if start_date.nil? || start_date < date
548
        self.start_date, self.due_date = date, date + duration
549
        save
550
      end
551
    else
552
      leaves.each do |leaf|
553
        leaf.reschedule_after(date)
554
      end
555
    end
556
  end
557

    
558
  def <=>(issue)
559
    if issue.nil?
560
      -1
561
    elsif root_id != issue.root_id
562
      (root_id || 0) <=> (issue.root_id || 0)
563
    else
564
      (lft || 0) <=> (issue.lft || 0)
565
    end
566
  end
567

    
568
  def to_s
569
    "#{tracker} ##{id}: #{subject}"
570
  end
571

    
572
  # Returns a string of css classes that apply to the issue
573
  def css_classes
574
    s = "issue status-#{status.position} "
575
    s << "priority-#{priority.position}"
576
    s << ' closed' if closed?
577
    s << ' overdue' if overdue?
578
    s << ' child' if child?
579
    s << ' parent' unless leaf?
580
    s << ' private' if is_private?
581
    s << ' created-by-me' if User.current.logged? && author_id == User.current.id
582
    s << ' assigned-to-me' if User.current.logged? && assigned_to_id == User.current.id
583
    s
584
  end
585

    
586
  # Saves an issue, time_entry, attachments, and a journal from the parameters
587
  # Returns false if save fails
588
  def save_issue_with_child_records(params, existing_time_entry=nil)
589
    Issue.transaction do
590
      if params[:time_entry] && (params[:time_entry][:hours].present? || params[:time_entry][:comments].present?) && User.current.allowed_to?(:log_time, project)
591
        @time_entry = existing_time_entry || TimeEntry.new
592
        @time_entry.project = project
593
        @time_entry.issue = self
594
        @time_entry.user = User.current
595
        @time_entry.spent_on = Date.today
596
        @time_entry.attributes = params[:time_entry]
597
        self.time_entries << @time_entry
598
      end
599

    
600
      if valid?
601
        attachments = Attachment.attach_files(self, params[:attachments])
602

    
603
        attachments[:files].each {|a| @current_journal.details << JournalDetail.new(:property => 'attachment', :prop_key => a.id, :value => a.filename)}
604
        # TODO: Rename hook
605
        Redmine::Hook.call_hook(:controller_issues_edit_before_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
606
        begin
607
          if save
608
            # TODO: Rename hook
609
            Redmine::Hook.call_hook(:controller_issues_edit_after_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
610
          else
611
            raise ActiveRecord::Rollback
612
          end
613
        rescue ActiveRecord::StaleObjectError
614
          attachments[:files].each(&:destroy)
615
          errors.add_to_base l(:notice_locking_conflict)
616
          raise ActiveRecord::Rollback
617
        end
618
      end
619
    end
620
  end
621

    
622
  # Unassigns issues from +version+ if it's no longer shared with issue's project
623
  def self.update_versions_from_sharing_change(version)
624
    # Update issues assigned to the version
625
    update_versions(["#{Issue.table_name}.fixed_version_id = ?", version.id])
626
  end
627

    
628
  # Unassigns issues from versions that are no longer shared
629
  # after +project+ was moved
630
  def self.update_versions_from_hierarchy_change(project)
631
    moved_project_ids = project.self_and_descendants.reload.collect(&:id)
632
    # Update issues of the moved projects and issues assigned to a version of a moved project
633
    Issue.update_versions(["#{Version.table_name}.project_id IN (?) OR #{Issue.table_name}.project_id IN (?)", moved_project_ids, moved_project_ids])
634
  end
635

    
636
  def parent_issue_id=(arg)
637
    parent_issue_id = arg.blank? ? nil : arg.to_i
638
    if parent_issue_id && @parent_issue = Issue.find_by_id(parent_issue_id)
639
      @parent_issue.id
640
    else
641
      @parent_issue = nil
642
      nil
643
    end
644
  end
645

    
646
  def parent_issue_id
647
    if instance_variable_defined? :@parent_issue
648
      @parent_issue.nil? ? nil : @parent_issue.id
649
    else
650
      parent_id
651
    end
652
  end
653

    
654
  # Extracted from the ReportsController.
655
  def self.by_tracker(project)
656
    count_and_group_by(:project => project,
657
                       :field => 'tracker_id',
658
                       :joins => Tracker.table_name)
659
  end
660

    
661
  def self.by_version(project)
662
    count_and_group_by(:project => project,
663
                       :field => 'fixed_version_id',
664
                       :joins => Version.table_name)
665
  end
666

    
667
  def self.by_priority(project)
668
    count_and_group_by(:project => project,
669
                       :field => 'priority_id',
670
                       :joins => IssuePriority.table_name)
671
  end
672

    
673
  def self.by_category(project)
674
    count_and_group_by(:project => project,
675
                       :field => 'category_id',
676
                       :joins => IssueCategory.table_name)
677
  end
678

    
679
  def self.by_assigned_to(project)
680
    count_and_group_by(:project => project,
681
                       :field => 'assigned_to_id',
682
                       :joins => User.table_name)
683
  end
684

    
685
  def self.by_author(project)
686
    count_and_group_by(:project => project,
687
                       :field => 'author_id',
688
                       :joins => User.table_name)
689
  end
690

    
691
  def self.by_subproject(project)
692
    ActiveRecord::Base.connection.select_all("select    s.id as status_id, 
693
                                                s.is_closed as closed, 
694
                                                #{Issue.table_name}.project_id as project_id,
695
                                                count(#{Issue.table_name}.id) as total 
696
                                              from 
697
                                                #{Issue.table_name}, #{Project.table_name}, #{IssueStatus.table_name} s
698
                                              where 
699
                                                #{Issue.table_name}.status_id=s.id
700
                                                and #{Issue.table_name}.project_id = #{Project.table_name}.id
701
                                                and #{visible_condition(User.current, :project => project, :with_subprojects => true)}
702
                                                and #{Issue.table_name}.project_id <> #{project.id}
703
                                              group by s.id, s.is_closed, #{Issue.table_name}.project_id") if project.descendants.active.any?
704
  end
705
  # End ReportsController extraction
706

    
707
  # Returns an array of projects that current user can move issues to
708
  def self.allowed_target_projects_on_move
709
    projects = []
710
    if User.current.admin?
711
      # admin is allowed to move issues to any active (visible) project
712
      projects = Project.visible.all
713
    elsif User.current.logged?
714
      if Role.non_member.allowed_to?(:move_issues)
715
        projects = Project.visible.all
716
      else
717
        User.current.memberships.each {|m| projects << m.project if m.roles.detect {|r| r.allowed_to?(:move_issues)}}
718
      end
719
    end
720
    projects
721
  end
722

    
723
  private
724

    
725
  def update_nested_set_attributes
726
    if root_id.nil?
727
      # issue was just created
728
      self.root_id = (@parent_issue.nil? ? id : @parent_issue.root_id)
729
      set_default_left_and_right
730
      Issue.update_all("root_id = #{root_id}, lft = #{lft}, rgt = #{rgt}", ["id = ?", id])
731
      if @parent_issue
732
        move_to_child_of(@parent_issue)
733
      end
734
      reload
735
    elsif parent_issue_id != parent_id
736
      former_parent_id = parent_id
737
      # moving an existing issue
738
      if @parent_issue && @parent_issue.root_id == root_id
739
        # inside the same tree
740
        move_to_child_of(@parent_issue)
741
      else
742
        # to another tree
743
        unless root?
744
          move_to_right_of(root)
745
          reload
746
        end
747
        old_root_id = root_id
748
        self.root_id = (@parent_issue.nil? ? id : @parent_issue.root_id )
749
        target_maxright = nested_set_scope.maximum(right_column_name) || 0
750
        offset = target_maxright + 1 - lft
751
        Issue.update_all("root_id = #{root_id}, lft = lft + #{offset}, rgt = rgt + #{offset}",
752
                          ["root_id = ? AND lft >= ? AND rgt <= ? ", old_root_id, lft, rgt])
753
        self[left_column_name] = lft + offset
754
        self[right_column_name] = rgt + offset
755
        if @parent_issue
756
          move_to_child_of(@parent_issue)
757
        end
758
      end
759
      reload
760
      # delete invalid relations of all descendants
761
      self_and_descendants.each do |issue|
762
        issue.relations.each do |relation|
763
          relation.destroy unless relation.valid?
764
        end
765
      end
766
      # update former parent
767
      recalculate_attributes_for(former_parent_id) if former_parent_id
768
    end
769
    remove_instance_variable(:@parent_issue) if instance_variable_defined?(:@parent_issue)
770
  end
771

    
772
  def update_parent_attributes
773
    recalculate_attributes_for(parent_id) if parent_id
774
  end
775

    
776
  def recalculate_attributes_for(issue_id)
777
    if issue_id && p = Issue.find_by_id(issue_id)
778
      # priority = highest priority of children
779
      if priority_position = p.children.maximum("#{IssuePriority.table_name}.position", :include => :priority)
780
        p.priority = IssuePriority.find_by_position(priority_position)
781
      end
782

    
783
      # start/due dates = lowest/highest dates of children
784
      p.start_date = p.children.minimum(:start_date)
785
      p.due_date = p.children.maximum(:due_date)
786
      if p.start_date && p.due_date && p.due_date < p.start_date
787
        p.start_date, p.due_date = p.due_date, p.start_date
788
      end
789

    
790
      # done ratio = weighted average ratio of leaves
791
      unless Issue.use_status_for_done_ratio? && p.status && p.status.default_done_ratio
792
        leaves_count = p.leaves.count
793
        if leaves_count > 0
794
          average = p.leaves.average(:estimated_hours).to_f
795
          if average == 0
796
            average = 1
797
          end
798
          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
799
          progress = done / (average * leaves_count)
800
          p.done_ratio = progress.round
801
        end
802
      end
803

    
804
      # estimate = sum of leaves estimates
805
      p.estimated_hours = p.leaves.sum(:estimated_hours).to_f
806
      p.estimated_hours = nil if p.estimated_hours == 0.0
807

    
808
      # ancestors will be recursively updated
809
      p.save(false)
810
    end
811
  end
812

    
813
  # Update issues so their versions are not pointing to a
814
  # fixed_version that is not shared with the issue's project
815
  def self.update_versions(conditions=nil)
816
    # Only need to update issues with a fixed_version from
817
    # a different project and that is not systemwide shared
818
    Issue.all(:conditions => merge_conditions("#{Issue.table_name}.fixed_version_id IS NOT NULL" +
819
                                                " AND #{Issue.table_name}.project_id <> #{Version.table_name}.project_id" +
820
                                                " AND #{Version.table_name}.sharing <> 'system'",
821
                                                conditions),
822
              :include => [:project, :fixed_version]
823
              ).each do |issue|
824
      next if issue.project.nil? || issue.fixed_version.nil?
825
      unless issue.project.shared_versions.include?(issue.fixed_version)
826
        issue.init_journal(User.current)
827
        issue.fixed_version = nil
828
        issue.save
829
      end
830
    end
831
  end
832

    
833
  # Callback on attachment deletion
834
  def attachment_removed(obj)
835
    journal = init_journal(User.current)
836
    journal.details << JournalDetail.new(:property => 'attachment',
837
                                         :prop_key => obj.id,
838
                                         :old_value => obj.filename)
839
    journal.save
840
  end
841

    
842
  # Default assignment based on category
843
  def default_assign
844
    if assigned_to.nil? && category && category.assigned_to
845
      self.assigned_to = category.assigned_to
846
    end
847
  end
848

    
849
  # Updates start/due dates of following issues
850
  def reschedule_following_issues
851
    if start_date_changed? || due_date_changed?
852
      relations_from.each do |relation|
853
        relation.set_issue_to_dates
854
      end
855
    end
856
  end
857

    
858
  # Closes duplicates if the issue is being closed
859
  def close_duplicates
860
    if closing?
861
      duplicates.each do |duplicate|
862
        # Reload is need in case the duplicate was updated by a previous duplicate
863
        duplicate.reload
864
        # Don't re-close it if it's already closed
865
        next if duplicate.closed?
866
        # Same user and notes
867
        if @current_journal
868
          duplicate.init_journal(@current_journal.user, @current_journal.notes)
869
        end
870
        duplicate.update_attribute :status, self.status
871
      end
872
    end
873
  end
874

    
875
  # Saves the changes in a Journal
876
  # Called after_save
877
  def create_journal
878
    if @current_journal
879
      # attributes changes
880
      (Issue.column_names - %w(id root_id lft rgt lock_version created_on updated_on)).each {|c|
881
        before = @issue_before_change.send(c)
882
        after = send(c)
883
        next if before == after || (before.blank? && after.blank?)
884
        @current_journal.details << JournalDetail.new(:property => 'attr',
885
                                                      :prop_key => c,
886
                                                      :old_value => @issue_before_change.send(c),
887
                                                      :value => send(c))
888
      }
889
      # custom fields changes
890
      custom_values.each {|c|
891
        next if (@custom_values_before_change[c.custom_field_id]==c.value ||
892
                  (@custom_values_before_change[c.custom_field_id].blank? && c.value.blank?))
893
        @current_journal.details << JournalDetail.new(:property => 'cf',
894
                                                      :prop_key => c.custom_field_id,
895
                                                      :old_value => @custom_values_before_change[c.custom_field_id],
896
                                                      :value => c.value)
897
      }
898
      @current_journal.save
899
      # reset current journal
900
      init_journal @current_journal.user, @current_journal.notes
901
    end
902
  end
903

    
904
  # Query generator for selecting groups of issue counts for a project
905
  # based on specific criteria
906
  #
907
  # Options
908
  # * project - Project to search in.
909
  # * field - String. Issue field to key off of in the grouping.
910
  # * joins - String. The table name to join against.
911
  def self.count_and_group_by(options)
912
    project = options.delete(:project)
913
    select_field = options.delete(:field)
914
    joins = options.delete(:joins)
915

    
916
    where = "#{Issue.table_name}.#{select_field}=j.id"
917

    
918
    ActiveRecord::Base.connection.select_all("select    s.id as status_id, 
919
                                                s.is_closed as closed, 
920
                                                j.id as #{select_field},
921
                                                count(#{Issue.table_name}.id) as total 
922
                                              from 
923
                                                  #{Issue.table_name}, #{Project.table_name}, #{IssueStatus.table_name} s, #{joins} j
924
                                              where 
925
                                                #{Issue.table_name}.status_id=s.id 
926
                                                and #{where}
927
                                                and #{Issue.table_name}.project_id=#{Project.table_name}.id
928
                                                and #{visible_condition(User.current, :project => project)}
929
                                              group by s.id, s.is_closed, j.id")
930
  end
931
end