Project

General

Profile

RE: patches for windows ยป issue.rb

 
1
# Redmine - project management software
2
# Copyright (C) 2006-2013  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
  include Redmine::Utils::DateCalculation
21

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

    
31
  has_many :journals, :as => :journalized, :dependent => :destroy
32
  has_many :visible_journals,
33
    :class_name => 'Journal',
34
    :as => :journalized,
35
    :conditions => Proc.new { 
36
      ["(#{Journal.table_name}.private_notes = ? OR (#{Project.allowed_to_condition(User.current, :view_private_notes)}))", false]
37
    },
38
    :readonly => true
39

    
40
  has_many :time_entries, :dependent => :delete_all
41
  has_and_belongs_to_many :changesets, :order => "#{Changeset.table_name}.committed_on ASC, #{Changeset.table_name}.id ASC"
42

    
43
  has_many :relations_from, :class_name => 'IssueRelation', :foreign_key => 'issue_from_id', :dependent => :delete_all
44
  has_many :relations_to, :class_name => 'IssueRelation', :foreign_key => 'issue_to_id', :dependent => :delete_all
45

    
46
  acts_as_nested_set :scope => 'root_id', :dependent => :destroy
47
  acts_as_attachable :after_add => :attachment_added, :after_remove => :attachment_removed
48
  acts_as_customizable
49
  acts_as_watchable
50
  acts_as_searchable :columns => ['subject', "#{table_name}.description", "#{Journal.table_name}.notes"],
51
                     :include => [:project, :visible_journals],
52
                     # sort by id so that limited eager loading doesn't break with postgresql
53
                     :order_column => "#{table_name}.id"
54
  acts_as_event :title => Proc.new {|o| "#{o.tracker.name} ##{o.id} (#{o.status}): #{o.subject}"},
55
                :url => Proc.new {|o| {:controller => 'issues', :action => 'show', :id => o.id}},
56
                :type => Proc.new {|o| 'issue' + (o.closed? ? ' closed' : '') }
57

    
58
  acts_as_activity_provider :find_options => {:include => [:project, :author, :tracker]},
59
                            :author_key => :author_id
60

    
61
  DONE_RATIO_OPTIONS = %w(issue_field issue_status)
62

    
63
  attr_reader :current_journal
64
  delegate :notes, :notes=, :private_notes, :private_notes=, :to => :current_journal, :allow_nil => true
65

    
66
  validates_presence_of :subject, :priority, :project, :tracker, :author, :status
67

    
68
  validates_length_of :subject, :maximum => 255
69
  validates_inclusion_of :done_ratio, :in => 0..100
70
  validates :estimated_hours, :numericality => {:greater_than_or_equal_to => 0, :allow_nil => true, :message => :invalid}
71
  validates :start_date, :date => true
72
  validates :due_date, :date => true
73
  validate :validate_issue, :validate_required_fields
74

    
75
  scope :visible, lambda {|*args|
76
    includes(:project).where(Issue.visible_condition(args.shift || User.current, *args))
77
  }
78

    
79
  scope :open, lambda {|*args|
80
    is_closed = args.size > 0 ? !args.first : false
81
    includes(:status).where("#{IssueStatus.table_name}.is_closed = ?", is_closed)
82
  }
83

    
84
  scope :recently_updated, lambda { order("#{Issue.table_name}.updated_on DESC") }
85
  scope :on_active_project, lambda {
86
    includes(:status, :project, :tracker).where("#{Project.table_name}.status = ?", Project::STATUS_ACTIVE)
87
  }
88
  scope :fixed_version, lambda {|versions|
89
    ids = [versions].flatten.compact.map {|v| v.is_a?(Version) ? v.id : v}
90
    ids.any? ? where(:fixed_version_id => ids) : where('1=0')
91
  }
92

    
93
  before_create :default_assign
94
  before_save :close_duplicates, :update_done_ratio_from_issue_status, :force_updated_on_change, :update_closed_on
95
  after_save {|issue| issue.send :after_project_change if !issue.id_changed? && issue.project_id_changed?} 
96
  after_save :reschedule_following_issues, :update_nested_set_attributes, :update_parent_attributes, :create_journal
97
  # Should be after_create but would be called before previous after_save callbacks
98
  after_save :after_create_from_copy
99
  after_destroy :update_parent_attributes
100

    
101
  # Returns a SQL conditions string used to find all issues visible by the specified user
102
  def self.visible_condition(user, options={})
103
    Project.allowed_to_condition(user, :view_issues, options) do |role, user|
104
      # Keep the code DRY
105
      if [ 'default', 'own' ].include?(role.issues_visibility)
106
        user_ids = [user.id] + user.groups.map(&:id)
107
        watched_issues = Issue.watched_by(user).map(&:id)
108
        watched_issues_clause = watched_issues.empty? ? "" : " OR #{table_name}.id IN (#{watched_issues.join(',')})"
109
      end
110

    
111
      if user.logged?
112
        case role.issues_visibility
113
        when 'all'
114
          nil
115
        when 'default'
116
          "(#{table_name}.is_private = #{connection.quoted_false} OR #{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id IN (#{user_ids.join(',')}) #{watched_issues_clause})"
117
        when 'own'
118
          "(#{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id IN (#{user_ids.join(',')}) #{watched_issues_clause})"
119
        else
120
          '1=0'
121
        end
122
      else
123
        "(#{table_name}.is_private = #{connection.quoted_false})"
124
      end
125
    end
126
  end
127

    
128
  # Returns true if usr or current user is allowed to view the issue
129
  def visible?(usr=nil)
130
    (usr || User.current).allowed_to?(:view_issues, self.project) do |role, user|
131
      if user.logged?
132
        case role.issues_visibility
133
        when 'all'
134
          true
135
        when 'default'
136
          !self.is_private? || (self.author == user || self.watched_by?(user) || user.is_or_belongs_to?(assigned_to))
137
        when 'own'
138
          self.author == user || self.watched_by?(user) || user.is_or_belongs_to?(assigned_to)
139
        else
140
          false
141
        end
142
      else
143
        !self.is_private?
144
      end
145
    end
146
  end
147

    
148
  # Returns true if user or current user is allowed to edit or add a note to the issue
149
  def editable?(user=User.current)
150
    user.allowed_to?(:edit_issues, project) || user.allowed_to?(:add_issue_notes, project)
151
  end
152

    
153
  # Override the acts_as_watchble default to allow any user with view issues
154
  # rights to watch/see this issue.
155
  def addable_watcher_users
156
    users = self.project.users.sort - self.watcher_users
157
    users.reject! {|user| !user.allowed_to?(:view_issues, self.project)}
158
    users
159
  end
160

    
161

    
162
  def initialize(attributes=nil, *args)
163
    super
164
    if new_record?
165
      # set default values for new records only
166
      self.status ||= IssueStatus.default
167
      self.priority ||= IssuePriority.default
168
      self.watcher_user_ids = []
169
    end
170
  end
171

    
172
  def create_or_update
173
    super
174
  ensure
175
    @status_was = nil
176
  end
177
  private :create_or_update
178

    
179
  # AR#Persistence#destroy would raise and RecordNotFound exception
180
  # if the issue was already deleted or updated (non matching lock_version).
181
  # This is a problem when bulk deleting issues or deleting a project
182
  # (because an issue may already be deleted if its parent was deleted
183
  # first).
184
  # The issue is reloaded by the nested_set before being deleted so
185
  # the lock_version condition should not be an issue but we handle it.
186
  def destroy
187
    super
188
  rescue ActiveRecord::RecordNotFound
189
    # Stale or already deleted
190
    begin
191
      reload
192
    rescue ActiveRecord::RecordNotFound
193
      # The issue was actually already deleted
194
      @destroyed = true
195
      return freeze
196
    end
197
    # The issue was stale, retry to destroy
198
    super
199
  end
200

    
201
  alias :base_reload :reload
202
  def reload(*args)
203
    @workflow_rule_by_attribute = nil
204
    @assignable_versions = nil
205
    @relations = nil
206
    base_reload(*args)
207
  end
208

    
209
  # Overrides Redmine::Acts::Customizable::InstanceMethods#available_custom_fields
210
  def available_custom_fields
211
    (project && tracker) ? (project.all_issue_custom_fields & tracker.custom_fields.all) : []
212
  end
213

    
214
  # Copies attributes from another issue, arg can be an id or an Issue
215
  def copy_from(arg, options={})
216
    issue = arg.is_a?(Issue) ? arg : Issue.visible.find(arg)
217
    self.attributes = issue.attributes.dup.except("id", "root_id", "parent_id", "lft", "rgt", "created_on", "updated_on")
218
    self.custom_field_values = issue.custom_field_values.inject({}) {|h,v| h[v.custom_field_id] = v.value; h}
219
    self.status = issue.status
220
    self.author = User.current
221
    unless options[:attachments] == false
222
      self.attachments = issue.attachments.map do |attachement| 
223
        attachement.copy(:container => self)
224
      end
225
    end
226
    @copied_from = issue
227
    @copy_options = options
228
    self
229
  end
230

    
231
  # Returns an unsaved copy of the issue
232
  def copy(attributes=nil, copy_options={})
233
    copy = self.class.new.copy_from(self, copy_options)
234
    copy.attributes = attributes if attributes
235
    copy
236
  end
237

    
238
  # Returns true if the issue is a copy
239
  def copy?
240
    @copied_from.present?
241
  end
242

    
243
  # Moves/copies an issue to a new project and tracker
244
  # Returns the moved/copied issue on success, false on failure
245
  def move_to_project(new_project, new_tracker=nil, options={})
246
    ActiveSupport::Deprecation.warn "Issue#move_to_project is deprecated, use #project= instead."
247

    
248
    if options[:copy]
249
      issue = self.copy
250
    else
251
      issue = self
252
    end
253

    
254
    issue.init_journal(User.current, options[:notes])
255

    
256
    # Preserve previous behaviour
257
    # #move_to_project doesn't change tracker automatically
258
    issue.send :project=, new_project, true
259
    if new_tracker
260
      issue.tracker = new_tracker
261
    end
262
    # Allow bulk setting of attributes on the issue
263
    if options[:attributes]
264
      issue.attributes = options[:attributes]
265
    end
266

    
267
    issue.save ? issue : false
268
  end
269

    
270
  def status_id=(sid)
271
    self.status = nil
272
    result = write_attribute(:status_id, sid)
273
    @workflow_rule_by_attribute = nil
274
    result
275
  end
276

    
277
  def priority_id=(pid)
278
    self.priority = nil
279
    write_attribute(:priority_id, pid)
280
  end
281

    
282
  def category_id=(cid)
283
    self.category = nil
284
    write_attribute(:category_id, cid)
285
  end
286

    
287
  def fixed_version_id=(vid)
288
    self.fixed_version = nil
289
    write_attribute(:fixed_version_id, vid)
290
  end
291

    
292
  def tracker_id=(tid)
293
    self.tracker = nil
294
    result = write_attribute(:tracker_id, tid)
295
    @custom_field_values = nil
296
    @workflow_rule_by_attribute = nil
297
    result
298
  end
299

    
300
  def project_id=(project_id)
301
    if project_id.to_s != self.project_id.to_s
302
      self.project = (project_id.present? ? Project.find_by_id(project_id) : nil)
303
    end
304
  end
305

    
306
  def project=(project, keep_tracker=false)
307
    project_was = self.project
308
    write_attribute(:project_id, project ? project.id : nil)
309
    association_instance_set('project', project)
310
    if project_was && project && project_was != project
311
      @assignable_versions = nil
312

    
313
      unless keep_tracker || project.trackers.include?(tracker)
314
        self.tracker = project.trackers.first
315
      end
316
      # Reassign to the category with same name if any
317
      if category
318
        self.category = project.issue_categories.find_by_name(category.name)
319
      end
320
      # Keep the fixed_version if it's still valid in the new_project
321
      if fixed_version && fixed_version.project != project && !project.shared_versions.include?(fixed_version)
322
        self.fixed_version = nil
323
      end
324
      # Clear the parent task if it's no longer valid
325
      unless valid_parent_project?
326
        self.parent_issue_id = nil
327
      end
328
      @custom_field_values = nil
329
    end
330
  end
331

    
332
  def description=(arg)
333
    if arg.is_a?(String)
334
      arg = arg.gsub(/(\r\n|\n|\r)/, "\r\n")
335
    end
336
    write_attribute(:description, arg)
337
  end
338

    
339
  # Overrides assign_attributes so that project and tracker get assigned first
340
  def assign_attributes_with_project_and_tracker_first(new_attributes, *args)
341
    return if new_attributes.nil?
342
    attrs = new_attributes.dup
343
    attrs.stringify_keys!
344

    
345
    %w(project project_id tracker tracker_id).each do |attr|
346
      if attrs.has_key?(attr)
347
        send "#{attr}=", attrs.delete(attr)
348
      end
349
    end
350
    send :assign_attributes_without_project_and_tracker_first, attrs, *args
351
  end
352
  # Do not redefine alias chain on reload (see #4838)
353
  alias_method_chain(:assign_attributes, :project_and_tracker_first) unless method_defined?(:assign_attributes_without_project_and_tracker_first)
354

    
355
  def estimated_hours=(h)
356
    write_attribute :estimated_hours, (h.is_a?(String) ? h.to_hours : h)
357
  end
358

    
359
  safe_attributes 'project_id',
360
    :if => lambda {|issue, user|
361
      if issue.new_record?
362
        issue.copy?
363
      elsif user.allowed_to?(:move_issues, issue.project)
364
        projects = Issue.allowed_target_projects_on_move(user)
365
        projects.include?(issue.project) && projects.size > 1
366
      end
367
    }
368

    
369
  safe_attributes 'tracker_id',
370
    'status_id',
371
    'category_id',
372
    'assigned_to_id',
373
    'priority_id',
374
    'fixed_version_id',
375
    'subject',
376
    'description',
377
    'start_date',
378
    'due_date',
379
    'done_ratio',
380
    'estimated_hours',
381
    'custom_field_values',
382
    'custom_fields',
383
    'lock_version',
384
    'notes',
385
    :if => lambda {|issue, user| issue.new_record? || user.allowed_to?(:edit_issues, issue.project) }
386

    
387
  safe_attributes 'status_id',
388
    'assigned_to_id',
389
    'fixed_version_id',
390
    'done_ratio',
391
    'lock_version',
392
    'notes',
393
    :if => lambda {|issue, user| issue.new_statuses_allowed_to(user).any? }
394

    
395
  safe_attributes 'notes',
396
    :if => lambda {|issue, user| user.allowed_to?(:add_issue_notes, issue.project)}
397

    
398
  safe_attributes 'private_notes',
399
    :if => lambda {|issue, user| !issue.new_record? && user.allowed_to?(:set_notes_private, issue.project)} 
400

    
401
  safe_attributes 'watcher_user_ids',
402
    :if => lambda {|issue, user| issue.new_record? && user.allowed_to?(:add_issue_watchers, issue.project)} 
403

    
404
  safe_attributes 'is_private',
405
    :if => lambda {|issue, user|
406
      user.allowed_to?(:set_issues_private, issue.project) ||
407
        (issue.author == user && user.allowed_to?(:set_own_issues_private, issue.project))
408
    }
409

    
410
  safe_attributes 'parent_issue_id',
411
    :if => lambda {|issue, user| (issue.new_record? || user.allowed_to?(:edit_issues, issue.project)) &&
412
      user.allowed_to?(:manage_subtasks, issue.project)}
413

    
414
  def safe_attribute_names(user=nil)
415
    names = super
416
    names -= disabled_core_fields
417
    names -= read_only_attribute_names(user)
418
    names
419
  end
420

    
421
  # Safely sets attributes
422
  # Should be called from controllers instead of #attributes=
423
  # attr_accessible is too rough because we still want things like
424
  # Issue.new(:project => foo) to work
425
  def safe_attributes=(attrs, user=User.current)
426
    return unless attrs.is_a?(Hash)
427

    
428
    attrs = attrs.dup
429

    
430
    # Project and Tracker must be set before since new_statuses_allowed_to depends on it.
431
    if (p = attrs.delete('project_id')) && safe_attribute?('project_id')
432
      if allowed_target_projects(user).collect(&:id).include?(p.to_i)
433
        self.project_id = p
434
      end
435
    end
436

    
437
    if (t = attrs.delete('tracker_id')) && safe_attribute?('tracker_id')
438
      self.tracker_id = t
439
    end
440

    
441
    if (s = attrs.delete('status_id')) && safe_attribute?('status_id')
442
      if new_statuses_allowed_to(user).collect(&:id).include?(s.to_i)
443
        self.status_id = s
444
      end
445
    end
446

    
447
    attrs = delete_unsafe_attributes(attrs, user)
448
    return if attrs.empty?
449

    
450
    unless leaf?
451
      attrs.reject! {|k,v| %w(priority_id done_ratio start_date due_date estimated_hours).include?(k)}
452
    end
453

    
454
    if attrs['parent_issue_id'].present?
455
      s = attrs['parent_issue_id'].to_s
456
      unless (m = s.match(%r{\A#?(\d+)\z})) && (m[1] == parent_id.to_s || Issue.visible(user).exists?(m[1]))
457
        @invalid_parent_issue_id = attrs.delete('parent_issue_id')
458
      end
459
    end
460

    
461
    if attrs['custom_field_values'].present?
462
      attrs['custom_field_values'] = attrs['custom_field_values'].reject {|k, v| read_only_attribute_names(user).include? k.to_s}
463
    end
464

    
465
    if attrs['custom_fields'].present?
466
      attrs['custom_fields'] = attrs['custom_fields'].reject {|c| read_only_attribute_names(user).include? c['id'].to_s}
467
    end
468

    
469
    # mass-assignment security bypass
470
    assign_attributes attrs, :without_protection => true
471
  end
472

    
473
  def disabled_core_fields
474
    tracker ? tracker.disabled_core_fields : []
475
  end
476

    
477
  # Returns the custom_field_values that can be edited by the given user
478
  def editable_custom_field_values(user=nil)
479
    custom_field_values.reject do |value|
480
      read_only_attribute_names(user).include?(value.custom_field_id.to_s)
481
    end
482
  end
483

    
484
  # Returns the names of attributes that are read-only for user or the current user
485
  # For users with multiple roles, the read-only fields are the intersection of
486
  # read-only fields of each role
487
  # The result is an array of strings where sustom fields are represented with their ids
488
  #
489
  # Examples:
490
  #   issue.read_only_attribute_names # => ['due_date', '2']
491
  #   issue.read_only_attribute_names(user) # => []
492
  def read_only_attribute_names(user=nil)
493
    workflow_rule_by_attribute(user).reject {|attr, rule| rule != 'readonly'}.keys
494
  end
495

    
496
  # Returns the names of required attributes for user or the current user
497
  # For users with multiple roles, the required fields are the intersection of
498
  # required fields of each role
499
  # The result is an array of strings where sustom fields are represented with their ids
500
  #
501
  # Examples:
502
  #   issue.required_attribute_names # => ['due_date', '2']
503
  #   issue.required_attribute_names(user) # => []
504
  def required_attribute_names(user=nil)
505
    workflow_rule_by_attribute(user).reject {|attr, rule| rule != 'required'}.keys
506
  end
507

    
508
  # Returns true if the attribute is required for user
509
  def required_attribute?(name, user=nil)
510
    required_attribute_names(user).include?(name.to_s)
511
  end
512

    
513
  # Returns a hash of the workflow rule by attribute for the given user
514
  #
515
  # Examples:
516
  #   issue.workflow_rule_by_attribute # => {'due_date' => 'required', 'start_date' => 'readonly'}
517
  def workflow_rule_by_attribute(user=nil)
518
    return @workflow_rule_by_attribute if @workflow_rule_by_attribute && user.nil?
519

    
520
    user_real = user || User.current
521
    roles = user_real.admin ? Role.all : user_real.roles_for_project(project)
522
    return {} if roles.empty?
523

    
524
    result = {}
525
    workflow_permissions = WorkflowPermission.where(:tracker_id => tracker_id, :old_status_id => status_id, :role_id => roles.map(&:id)).all
526
    if workflow_permissions.any?
527
      workflow_rules = workflow_permissions.inject({}) do |h, wp|
528
        h[wp.field_name] ||= []
529
        h[wp.field_name] << wp.rule
530
        h
531
      end
532
      workflow_rules.each do |attr, rules|
533
        next if rules.size < roles.size
534
        uniq_rules = rules.uniq
535
        if uniq_rules.size == 1
536
          result[attr] = uniq_rules.first
537
        else
538
          result[attr] = 'required'
539
        end
540
      end
541
    end
542
    @workflow_rule_by_attribute = result if user.nil?
543
    result
544
  end
545
  private :workflow_rule_by_attribute
546

    
547
  def done_ratio
548
    if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
549
      status.default_done_ratio
550
    else
551
      read_attribute(:done_ratio)
552
    end
553
  end
554

    
555
  def self.use_status_for_done_ratio?
556
    Setting.issue_done_ratio == 'issue_status'
557
  end
558

    
559
  def self.use_field_for_done_ratio?
560
    Setting.issue_done_ratio == 'issue_field'
561
  end
562

    
563
  def validate_issue
564
    if due_date && start_date && due_date < start_date
565
      errors.add :due_date, :greater_than_start_date
566
    end
567

    
568
    if start_date && soonest_start && start_date < soonest_start
569
      errors.add :start_date, :invalid
570
    end
571

    
572
    if fixed_version
573
      if !assignable_versions.include?(fixed_version)
574
        errors.add :fixed_version_id, :inclusion
575
      elsif reopened? && fixed_version.closed?
576
        errors.add :base, I18n.t(:error_can_not_reopen_issue_on_closed_version)
577
      end
578
    end
579

    
580
    # Checks that the issue can not be added/moved to a disabled tracker
581
    if project && (tracker_id_changed? || project_id_changed?)
582
      unless project.trackers.include?(tracker)
583
        errors.add :tracker_id, :inclusion
584
      end
585
    end
586

    
587
    # Checks parent issue assignment
588
    if @invalid_parent_issue_id.present?
589
      errors.add :parent_issue_id, :invalid
590
    elsif @parent_issue
591
      if !valid_parent_project?(@parent_issue)
592
        errors.add :parent_issue_id, :invalid
593
      elsif (@parent_issue != parent) && (all_dependent_issues.include?(@parent_issue) || @parent_issue.all_dependent_issues.include?(self))
594
        errors.add :parent_issue_id, :invalid
595
      elsif !new_record?
596
        # moving an existing issue
597
        if @parent_issue.root_id != root_id
598
          # we can always move to another tree
599
        elsif move_possible?(@parent_issue)
600
          # move accepted inside tree
601
        else
602
          errors.add :parent_issue_id, :invalid
603
        end
604
      end
605
    end
606
  end
607

    
608
  # Validates the issue against additional workflow requirements
609
  def validate_required_fields
610
    user = new_record? ? author : current_journal.try(:user)
611

    
612
    required_attribute_names(user).each do |attribute|
613
      if attribute =~ /^\d+$/
614
        attribute = attribute.to_i
615
        v = custom_field_values.detect {|v| v.custom_field_id == attribute }
616
        if v && v.value.blank?
617
          errors.add :base, v.custom_field.name + ' ' + l('activerecord.errors.messages.blank')
618
        end
619
      else
620
        if respond_to?(attribute) && send(attribute).blank?
621
          errors.add attribute, :blank
622
        end
623
      end
624
    end
625
  end
626

    
627
  # Set the done_ratio using the status if that setting is set.  This will keep the done_ratios
628
  # even if the user turns off the setting later
629
  def update_done_ratio_from_issue_status
630
    if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
631
      self.done_ratio = status.default_done_ratio
632
    end
633
  end
634

    
635
  def init_journal(user, notes = "")
636
    @current_journal ||= Journal.new(:journalized => self, :user => user, :notes => notes)
637
    if new_record?
638
      @current_journal.notify = false
639
    else
640
      @attributes_before_change = attributes.dup
641
      @custom_values_before_change = {}
642
      self.custom_field_values.each {|c| @custom_values_before_change.store c.custom_field_id, c.value }
643
    end
644
    @current_journal
645
  end
646

    
647
  # Returns the id of the last journal or nil
648
  def last_journal_id
649
    if new_record?
650
      nil
651
    else
652
      journals.maximum(:id)
653
    end
654
  end
655

    
656
  # Returns a scope for journals that have an id greater than journal_id
657
  def journals_after(journal_id)
658
    scope = journals.reorder("#{Journal.table_name}.id ASC")
659
    if journal_id.present?
660
      scope = scope.where("#{Journal.table_name}.id > ?", journal_id.to_i)
661
    end
662
    scope
663
  end
664

    
665
  # Returns the initial status of the issue
666
  # Returns nil for a new issue
667
  def status_was
668
    if status_id_was && status_id_was.to_i > 0
669
      @status_was ||= IssueStatus.find_by_id(status_id_was)
670
    end
671
  end
672

    
673
  # Return true if the issue is closed, otherwise false
674
  def closed?
675
    self.status.is_closed?
676
  end
677

    
678
  # Return true if the issue is being reopened
679
  def reopened?
680
    if !new_record? && status_id_changed?
681
      status_was = IssueStatus.find_by_id(status_id_was)
682
      status_new = IssueStatus.find_by_id(status_id)
683
      if status_was && status_new && status_was.is_closed? && !status_new.is_closed?
684
        return true
685
      end
686
    end
687
    false
688
  end
689

    
690
  # Return true if the issue is being closed
691
  def closing?
692
    if !new_record? && status_id_changed?
693
      if status_was && status && !status_was.is_closed? && status.is_closed?
694
        return true
695
      end
696
    end
697
    false
698
  end
699

    
700
  # Returns true if the issue is overdue
701
  def overdue?
702
    !due_date.nil? && (due_date < Date.today) && !status.is_closed?
703
  end
704

    
705
  # Is the amount of work done less than it should for the due date
706
  def behind_schedule?
707
    return false if start_date.nil? || due_date.nil?
708
    done_date = start_date + ((due_date - start_date+1)* done_ratio/100).floor
709
    return done_date <= Date.today
710
  end
711

    
712
  # Does this issue have children?
713
  def children?
714
    !leaf?
715
  end
716

    
717
  # Users the issue can be assigned to
718
  def assignable_users
719
    users = project.assignable_users
720
    users << author if author
721
    users << assigned_to if assigned_to
722
    users.uniq.sort
723
  end
724

    
725
  # Versions that the issue can be assigned to
726
  def assignable_versions
727
    return @assignable_versions if @assignable_versions
728

    
729
    versions = project.shared_versions.open.all
730
    if fixed_version
731
      if fixed_version_id_changed?
732
        # nothing to do
733
      elsif project_id_changed?
734
        if project.shared_versions.include?(fixed_version)
735
          versions << fixed_version
736
        end
737
      else
738
        versions << fixed_version
739
      end
740
    end
741
    @assignable_versions = versions.uniq.sort
742
  end
743

    
744
  # Returns true if this issue is blocked by another issue that is still open
745
  def blocked?
746
    !relations_to.detect {|ir| ir.relation_type == 'blocks' && !ir.issue_from.closed?}.nil?
747
  end
748

    
749
  # Returns an array of statuses that user is able to apply
750
  def new_statuses_allowed_to(user=User.current, include_default=false)
751
    if new_record? && @copied_from
752
      [IssueStatus.default, @copied_from.status].compact.uniq.sort
753
    else
754
      initial_status = nil
755
      if new_record?
756
        initial_status = IssueStatus.default
757
      elsif status_id_was
758
        initial_status = IssueStatus.find_by_id(status_id_was)
759
      end
760
      initial_status ||= status
761
  
762
      statuses = initial_status.find_new_statuses_allowed_to(
763
        user.admin ? Role.all : user.roles_for_project(project),
764
        tracker,
765
        author == user,
766
        assigned_to_id_changed? ? assigned_to_id_was == user.id : assigned_to_id == user.id
767
        )
768
      statuses << initial_status unless statuses.empty?
769
      statuses << IssueStatus.default if include_default
770
      statuses = statuses.compact.uniq.sort
771
      blocked? ? statuses.reject {|s| s.is_closed?} : statuses
772
    end
773
  end
774

    
775
  def assigned_to_was
776
    if assigned_to_id_changed? && assigned_to_id_was.present?
777
      @assigned_to_was ||= User.find_by_id(assigned_to_id_was)
778
    end
779
  end
780

    
781
  # Returns the users that should be notified
782
  def notified_users
783
    notified = []
784
    # Author and assignee are always notified unless they have been
785
    # locked or don't want to be notified
786
    notified << author if author
787
    if assigned_to
788
      notified += (assigned_to.is_a?(Group) ? assigned_to.users : [assigned_to])
789
    end
790
    if assigned_to_was
791
      notified += (assigned_to_was.is_a?(Group) ? assigned_to_was.users : [assigned_to_was])
792
    end
793
    notified = notified.select {|u| u.active? && u.notify_about?(self)}
794

    
795
    notified += project.notified_users
796
    notified.uniq!
797
    # Remove users that can not view the issue
798
    notified.reject! {|user| !visible?(user)}
799
    notified
800
  end
801

    
802
  # Returns the email addresses that should be notified
803
  def recipients
804
    notified_users.collect(&:mail)
805
  end
806

    
807
  # Returns the number of hours spent on this issue
808
  def spent_hours
809
    @spent_hours ||= time_entries.sum(:hours) || 0
810
  end
811

    
812
  # Returns the total number of hours spent on this issue and its descendants
813
  #
814
  # Example:
815
  #   spent_hours => 0.0
816
  #   spent_hours => 50.2
817
  def total_spent_hours
818
    @total_spent_hours ||= self_and_descendants.sum("#{TimeEntry.table_name}.hours",
819
      :joins => "LEFT JOIN #{TimeEntry.table_name} ON #{TimeEntry.table_name}.issue_id = #{Issue.table_name}.id").to_f || 0.0
820
  end
821

    
822
  def relations
823
    @relations ||= IssueRelation::Relations.new(self, (relations_from + relations_to).sort)
824
  end
825

    
826
  # Preloads relations for a collection of issues
827
  def self.load_relations(issues)
828
    if issues.any?
829
      relations = IssueRelation.all(:conditions => ["issue_from_id IN (:ids) OR issue_to_id IN (:ids)", {:ids => issues.map(&:id)}])
830
      issues.each do |issue|
831
        issue.instance_variable_set "@relations", relations.select {|r| r.issue_from_id == issue.id || r.issue_to_id == issue.id}
832
      end
833
    end
834
  end
835

    
836
  # Preloads visible spent time for a collection of issues
837
  def self.load_visible_spent_hours(issues, user=User.current)
838
    if issues.any?
839
      hours_by_issue_id = TimeEntry.visible(user).sum(:hours, :group => :issue_id)
840
      issues.each do |issue|
841
        issue.instance_variable_set "@spent_hours", (hours_by_issue_id[issue.id] || 0)
842
      end
843
    end
844
  end
845

    
846
  # Preloads visible relations for a collection of issues
847
  def self.load_visible_relations(issues, user=User.current)
848
    if issues.any?
849
      issue_ids = issues.map(&:id)
850
      # Relations with issue_from in given issues and visible issue_to
851
      relations_from = IssueRelation.includes(:issue_to => [:status, :project]).where(visible_condition(user)).where(:issue_from_id => issue_ids).all
852
      # Relations with issue_to in given issues and visible issue_from
853
      relations_to = IssueRelation.includes(:issue_from => [:status, :project]).where(visible_condition(user)).where(:issue_to_id => issue_ids).all
854

    
855
      issues.each do |issue|
856
        relations =
857
          relations_from.select {|relation| relation.issue_from_id == issue.id} +
858
          relations_to.select {|relation| relation.issue_to_id == issue.id}
859

    
860
        issue.instance_variable_set "@relations", IssueRelation::Relations.new(issue, relations.sort)
861
      end
862
    end
863
  end
864

    
865
  # Finds an issue relation given its id.
866
  def find_relation(relation_id)
867
    IssueRelation.find(relation_id, :conditions => ["issue_to_id = ? OR issue_from_id = ?", id, id])
868
  end
869

    
870
  # Returns all the other issues that depend on the issue
871
  def all_dependent_issues(except=[])
872
    except << self
873
    dependencies = []
874
    dependencies += relations_from.map(&:issue_to)
875
    dependencies += children unless leaf?
876
    dependencies.compact!
877
    dependencies -= except
878
    dependencies += dependencies.map {|issue| issue.all_dependent_issues(except)}.flatten
879
    if parent
880
      dependencies << parent
881
      dependencies += parent.all_dependent_issues(except + parent.descendants)
882
    end
883
    dependencies
884
  end
885

    
886
  # Returns an array of issues that duplicate this one
887
  def duplicates
888
    relations_to.select {|r| r.relation_type == IssueRelation::TYPE_DUPLICATES}.collect {|r| r.issue_from}
889
  end
890

    
891
  # Returns the due date or the target due date if any
892
  # Used on gantt chart
893
  def due_before
894
    due_date || (fixed_version ? fixed_version.effective_date : nil)
895
  end
896

    
897
  # Returns the time scheduled for this issue.
898
  #
899
  # Example:
900
  #   Start Date: 2/26/09, End Date: 3/04/09
901
  #   duration => 6
902
  def duration
903
    (start_date && due_date) ? due_date - start_date : 0
904
  end
905

    
906
  # Returns the duration in working days
907
  def working_duration
908
    (start_date && due_date) ? working_days(start_date, due_date) : 0
909
  end
910

    
911
  def soonest_start(reload=false)
912
    @soonest_start = nil if reload
913
    @soonest_start ||= (
914
        relations_to(reload).collect{|relation| relation.successor_soonest_start} +
915
        [(@parent_issue || parent).try(:soonest_start)]
916
      ).compact.max
917
  end
918

    
919
  # Sets start_date on the given date or the next working day
920
  # and changes due_date to keep the same working duration.
921
  def reschedule_on(date)
922
    wd = working_duration
923
    date = next_working_date(date)
924
    self.start_date = date
925
    self.due_date = add_working_days(date, wd)
926
  end
927

    
928
  # Reschedules the issue on the given date or the next working day and saves the record.
929
  # If the issue is a parent task, this is done by rescheduling its subtasks.
930
  def reschedule_on!(date)
931
    return if date.nil?
932
    if leaf?
933
      if start_date.nil? || start_date != date
934
        if start_date && start_date > date
935
          # Issue can not be moved earlier than its soonest start date
936
          date = [soonest_start(true), date].compact.max
937
        end
938
        reschedule_on(date)
939
        begin
940
          save
941
        rescue ActiveRecord::StaleObjectError
942
          reload
943
          reschedule_on(date)
944
          save
945
        end
946
      end
947
    else
948
      leaves.each do |leaf|
949
        if leaf.start_date
950
          # Only move subtask if it starts at the same date as the parent
951
          # or if it starts before the given date
952
          if start_date == leaf.start_date || date > leaf.start_date 
953
            leaf.reschedule_on!(date)
954
          end
955
        else
956
          leaf.reschedule_on!(date)
957
        end
958
      end
959
    end
960
  end
961

    
962
  def <=>(issue)
963
    if issue.nil?
964
      -1
965
    elsif root_id != issue.root_id
966
      (root_id || 0) <=> (issue.root_id || 0)
967
    else
968
      (lft || 0) <=> (issue.lft || 0)
969
    end
970
  end
971

    
972
  def to_s
973
    "#{tracker} ##{id}: #{subject}"
974
  end
975

    
976
  # Returns a string of css classes that apply to the issue
977
  def css_classes
978
    s = "issue tracker-#{tracker_id} status-#{status_id} #{priority.try(:css_classes)}"
979
    s << ' closed' if closed?
980
    s << ' overdue' if overdue?
981
    s << ' child' if child?
982
    s << ' parent' unless leaf?
983
    s << ' private' if is_private?
984
    s << ' created-by-me' if User.current.logged? && author_id == User.current.id
985
    s << ' assigned-to-me' if User.current.logged? && assigned_to_id == User.current.id
986
    s
987
  end
988

    
989
  # Saves an issue and a time_entry from the parameters
990
  def save_issue_with_child_records(params, existing_time_entry=nil)
991
    Issue.transaction do
992
      if params[:time_entry] && (params[:time_entry][:hours].present? || params[:time_entry][:comments].present?) && User.current.allowed_to?(:log_time, project)
993
        @time_entry = existing_time_entry || TimeEntry.new
994
        @time_entry.project = project
995
        @time_entry.issue = self
996
        @time_entry.user = User.current
997
        @time_entry.spent_on = User.current.today
998
        @time_entry.attributes = params[:time_entry]
999
        self.time_entries << @time_entry
1000
      end
1001

    
1002
      # TODO: Rename hook
1003
      Redmine::Hook.call_hook(:controller_issues_edit_before_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
1004
      if save
1005
        # TODO: Rename hook
1006
        Redmine::Hook.call_hook(:controller_issues_edit_after_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
1007
      else
1008
        raise ActiveRecord::Rollback
1009
      end
1010
    end
1011
  end
1012

    
1013
  # Unassigns issues from +version+ if it's no longer shared with issue's project
1014
  def self.update_versions_from_sharing_change(version)
1015
    # Update issues assigned to the version
1016
    update_versions(["#{Issue.table_name}.fixed_version_id = ?", version.id])
1017
  end
1018

    
1019
  # Unassigns issues from versions that are no longer shared
1020
  # after +project+ was moved
1021
  def self.update_versions_from_hierarchy_change(project)
1022
    moved_project_ids = project.self_and_descendants.reload.collect(&:id)
1023
    # Update issues of the moved projects and issues assigned to a version of a moved project
1024
    Issue.update_versions(["#{Version.table_name}.project_id IN (?) OR #{Issue.table_name}.project_id IN (?)", moved_project_ids, moved_project_ids])
1025
  end
1026

    
1027
  def parent_issue_id=(arg)
1028
    s = arg.to_s.strip.presence
1029
    if s && (m = s.match(%r{\A#?(\d+)\z})) && (@parent_issue = Issue.find_by_id(m[1]))
1030
      @parent_issue.id
1031
    else
1032
      @parent_issue = nil
1033
      @invalid_parent_issue_id = arg
1034
    end
1035
  end
1036

    
1037
  def parent_issue_id
1038
    if @invalid_parent_issue_id
1039
      @invalid_parent_issue_id
1040
    elsif instance_variable_defined? :@parent_issue
1041
      @parent_issue.nil? ? nil : @parent_issue.id
1042
    else
1043
      parent_id
1044
    end
1045
  end
1046

    
1047
  # Returns true if issue's project is a valid
1048
  # parent issue project
1049
  def valid_parent_project?(issue=parent)
1050
    return true if issue.nil? || issue.project_id == project_id
1051

    
1052
    case Setting.cross_project_subtasks
1053
    when 'system'
1054
      true
1055
    when 'tree'
1056
      issue.project.root == project.root
1057
    when 'hierarchy'
1058
      issue.project.is_or_is_ancestor_of?(project) || issue.project.is_descendant_of?(project)
1059
    when 'descendants'
1060
      issue.project.is_or_is_ancestor_of?(project)
1061
    else
1062
      false
1063
    end
1064
  end
1065

    
1066
  # Extracted from the ReportsController.
1067
  def self.by_tracker(project)
1068
    count_and_group_by(:project => project,
1069
                       :field => 'tracker_id',
1070
                       :joins => Tracker.table_name)
1071
  end
1072

    
1073
  def self.by_version(project)
1074
    count_and_group_by(:project => project,
1075
                       :field => 'fixed_version_id',
1076
                       :joins => Version.table_name)
1077
  end
1078

    
1079
  def self.by_priority(project)
1080
    count_and_group_by(:project => project,
1081
                       :field => 'priority_id',
1082
                       :joins => IssuePriority.table_name)
1083
  end
1084

    
1085
  def self.by_category(project)
1086
    count_and_group_by(:project => project,
1087
                       :field => 'category_id',
1088
                       :joins => IssueCategory.table_name)
1089
  end
1090

    
1091
  def self.by_assigned_to(project)
1092
    count_and_group_by(:project => project,
1093
                       :field => 'assigned_to_id',
1094
                       :joins => User.table_name)
1095
  end
1096

    
1097
  def self.by_author(project)
1098
    count_and_group_by(:project => project,
1099
                       :field => 'author_id',
1100
                       :joins => User.table_name)
1101
  end
1102

    
1103
  def self.by_subproject(project)
1104
    ActiveRecord::Base.connection.select_all("select    s.id as status_id, 
1105
                                                s.is_closed as closed, 
1106
                                                #{Issue.table_name}.project_id as project_id,
1107
                                                count(#{Issue.table_name}.id) as total 
1108
                                              from 
1109
                                                #{Issue.table_name}, #{Project.table_name}, #{IssueStatus.table_name} s
1110
                                              where 
1111
                                                #{Issue.table_name}.status_id=s.id
1112
                                                and #{Issue.table_name}.project_id = #{Project.table_name}.id
1113
                                                and #{visible_condition(User.current, :project => project, :with_subprojects => true)}
1114
                                                and #{Issue.table_name}.project_id <> #{project.id}
1115
                                              group by s.id, s.is_closed, #{Issue.table_name}.project_id") if project.descendants.active.any?
1116
  end
1117
  # End ReportsController extraction
1118

    
1119
  # Returns an array of projects that user can assign the issue to
1120
  def allowed_target_projects(user=User.current)
1121
    if new_record?
1122
      Project.all(:conditions => Project.allowed_to_condition(user, :add_issues))
1123
    else
1124
      self.class.allowed_target_projects_on_move(user)
1125
    end
1126
  end
1127

    
1128
  # Returns an array of projects that user can move issues to
1129
  def self.allowed_target_projects_on_move(user=User.current)
1130
    Project.all(:conditions => Project.allowed_to_condition(user, :move_issues))
1131
  end
1132

    
1133
  private
1134

    
1135
  def after_project_change
1136
    # Update project_id on related time entries
1137
    TimeEntry.update_all(["project_id = ?", project_id], {:issue_id => id})
1138

    
1139
    # Delete issue relations
1140
    unless Setting.cross_project_issue_relations?
1141
      relations_from.clear
1142
      relations_to.clear
1143
    end
1144

    
1145
    # Move subtasks that were in the same project
1146
    children.each do |child|
1147
      next unless child.project_id == project_id_was
1148
      # Change project and keep project
1149
      child.send :project=, project, true
1150
      unless child.save
1151
        raise ActiveRecord::Rollback
1152
      end
1153
    end
1154
  end
1155

    
1156
  # Callback for after the creation of an issue by copy
1157
  # * adds a "copied to" relation with the copied issue
1158
  # * copies subtasks from the copied issue
1159
  def after_create_from_copy
1160
    return unless copy? && !@after_create_from_copy_handled
1161

    
1162
    if (@copied_from.project_id == project_id || Setting.cross_project_issue_relations?) && @copy_options[:link] != false
1163
      relation = IssueRelation.new(:issue_from => @copied_from, :issue_to => self, :relation_type => IssueRelation::TYPE_COPIED_TO)
1164
      unless relation.save
1165
        logger.error "Could not create relation while copying ##{@copied_from.id} to ##{id} due to validation errors: #{relation.errors.full_messages.join(', ')}" if logger
1166
      end
1167
    end
1168

    
1169
    unless @copied_from.leaf? || @copy_options[:subtasks] == false
1170
      copy_options = (@copy_options || {}).merge(:subtasks => false)
1171
      copied_issue_ids = {@copied_from.id => self.id}
1172
      @copied_from.reload.descendants.reorder("#{Issue.table_name}.lft").each do |child|
1173
        # Do not copy self when copying an issue as a descendant of the copied issue
1174
        next if child == self
1175
        # Do not copy subtasks of issues that were not copied
1176
        next unless copied_issue_ids[child.parent_id]
1177
        # Do not copy subtasks that are not visible to avoid potential disclosure of private data
1178
        unless child.visible?
1179
          logger.error "Subtask ##{child.id} was not copied during ##{@copied_from.id} copy because it is not visible to the current user" if logger
1180
          next
1181
        end
1182
        copy = Issue.new.copy_from(child, copy_options)
1183
        copy.author = author
1184
        copy.project = project
1185
        copy.parent_issue_id = copied_issue_ids[child.parent_id]
1186
        unless copy.save
1187
          logger.error "Could not copy subtask ##{child.id} while copying ##{@copied_from.id} to ##{id} due to validation errors: #{copy.errors.full_messages.join(', ')}" if logger
1188
          next
1189
        end
1190
        copied_issue_ids[child.id] = copy.id
1191
      end
1192
    end
1193
    @after_create_from_copy_handled = true
1194
  end
1195

    
1196
  def update_nested_set_attributes
1197
    if root_id.nil?
1198
      # issue was just created
1199
      self.root_id = (@parent_issue.nil? ? id : @parent_issue.root_id)
1200
      set_default_left_and_right
1201
      Issue.update_all("root_id = #{root_id}, lft = #{lft}, rgt = #{rgt}", ["id = ?", id])
1202
      if @parent_issue
1203
        move_to_child_of(@parent_issue)
1204
      end
1205
      reload
1206
    elsif parent_issue_id != parent_id
1207
      former_parent_id = parent_id
1208
      # moving an existing issue
1209
      if @parent_issue && @parent_issue.root_id == root_id
1210
        # inside the same tree
1211
        move_to_child_of(@parent_issue)
1212
      else
1213
        # to another tree
1214
        unless root?
1215
          move_to_right_of(root)
1216
          reload
1217
        end
1218
        old_root_id = root_id
1219
        self.root_id = (@parent_issue.nil? ? id : @parent_issue.root_id )
1220
        target_maxright = nested_set_scope.maximum(right_column_name) || 0
1221
        offset = target_maxright + 1 - lft
1222
        Issue.update_all("root_id = #{root_id}, lft = lft + #{offset}, rgt = rgt + #{offset}",
1223
                          ["root_id = ? AND lft >= ? AND rgt <= ? ", old_root_id, lft, rgt])
1224
        self[left_column_name] = lft + offset
1225
        self[right_column_name] = rgt + offset
1226
        if @parent_issue
1227
          move_to_child_of(@parent_issue)
1228
        end
1229
      end
1230
      reload
1231
      # delete invalid relations of all descendants
1232
      self_and_descendants.each do |issue|
1233
        issue.relations.each do |relation|
1234
          relation.destroy unless relation.valid?
1235
        end
1236
      end
1237
      # update former parent
1238
      recalculate_attributes_for(former_parent_id) if former_parent_id
1239
    end
1240
    remove_instance_variable(:@parent_issue) if instance_variable_defined?(:@parent_issue)
1241
  end
1242

    
1243
  def update_parent_attributes
1244
    recalculate_attributes_for(parent_id) if parent_id
1245
  end
1246

    
1247
  def recalculate_attributes_for(issue_id)
1248
    if issue_id && p = Issue.find_by_id(issue_id)
1249
      # priority = highest priority of children
1250
      if priority_position = p.children.maximum("#{IssuePriority.table_name}.position", :joins => :priority)
1251
        p.priority = IssuePriority.find_by_position(priority_position)
1252
      end
1253

    
1254
      # start/due dates = lowest/highest dates of children
1255
      p.start_date = p.children.minimum(:start_date)
1256
      p.due_date = p.children.maximum(:due_date)
1257
      if p.start_date && p.due_date && p.due_date < p.start_date
1258
        p.start_date, p.due_date = p.due_date, p.start_date
1259
      end
1260

    
1261
      # done ratio = weighted average ratio of leaves
1262
      unless Issue.use_status_for_done_ratio? && p.status && p.status.default_done_ratio
1263
        leaves_count = p.leaves.count
1264
        if leaves_count > 0
1265
          average = p.leaves.average(:estimated_hours).to_f
1266
          if average == 0
1267
            average = 1
1268
          end
1269
          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
1270
          progress = done / (average * leaves_count)
1271
          p.done_ratio = progress.round
1272
        end
1273
      end
1274

    
1275
      # estimate = sum of leaves estimates
1276
      p.estimated_hours = p.leaves.sum(:estimated_hours).to_f
1277
      p.estimated_hours = nil if p.estimated_hours == 0.0
1278

    
1279
      # ancestors will be recursively updated
1280
      p.save(:validate => false)
1281
    end
1282
  end
1283

    
1284
  # Update issues so their versions are not pointing to a
1285
  # fixed_version that is not shared with the issue's project
1286
  def self.update_versions(conditions=nil)
1287
    # Only need to update issues with a fixed_version from
1288
    # a different project and that is not systemwide shared
1289
    Issue.scoped(:conditions => conditions).all(
1290
      :conditions => "#{Issue.table_name}.fixed_version_id IS NOT NULL" +
1291
        " AND #{Issue.table_name}.project_id <> #{Version.table_name}.project_id" +
1292
        " AND #{Version.table_name}.sharing <> 'system'",
1293
      :include => [:project, :fixed_version]
1294
    ).each do |issue|
1295
      next if issue.project.nil? || issue.fixed_version.nil?
1296
      unless issue.project.shared_versions.include?(issue.fixed_version)
1297
        issue.init_journal(User.current)
1298
        issue.fixed_version = nil
1299
        issue.save
1300
      end
1301
    end
1302
  end
1303

    
1304
  # Callback on file attachment
1305
  def attachment_added(obj)
1306
    if @current_journal && !obj.new_record?
1307
      @current_journal.details << JournalDetail.new(:property => 'attachment', :prop_key => obj.id, :value => obj.filename)
1308
    end
1309
  end
1310

    
1311
  # Callback on attachment deletion
1312
  def attachment_removed(obj)
1313
    if @current_journal && !obj.new_record?
1314
      @current_journal.details << JournalDetail.new(:property => 'attachment', :prop_key => obj.id, :old_value => obj.filename)
1315
      @current_journal.save
1316
    end
1317
  end
1318

    
1319
  # Default assignment based on category
1320
  def default_assign
1321
    if assigned_to.nil? && category && category.assigned_to
1322
      self.assigned_to = category.assigned_to
1323
    end
1324
  end
1325

    
1326
  # Updates start/due dates of following issues
1327
  def reschedule_following_issues
1328
    if start_date_changed? || due_date_changed?
1329
      relations_from.each do |relation|
1330
        relation.set_issue_to_dates
1331
      end
1332
    end
1333
  end
1334

    
1335
  # Closes duplicates if the issue is being closed
1336
  def close_duplicates
1337
    if closing?
1338
      duplicates.each do |duplicate|
1339
        # Reload is need in case the duplicate was updated by a previous duplicate
1340
        duplicate.reload
1341
        # Don't re-close it if it's already closed
1342
        next if duplicate.closed?
1343
        # Same user and notes
1344
        if @current_journal
1345
          duplicate.init_journal(@current_journal.user, @current_journal.notes)
1346
        end
1347
        duplicate.update_attribute :status, self.status
1348
      end
1349
    end
1350
  end
1351

    
1352
  # Make sure updated_on is updated when adding a note and set updated_on now
1353
  # so we can set closed_on with the same value on closing
1354
  def force_updated_on_change
1355
    if @current_journal || changed?
1356
      self.updated_on = current_time_from_proper_timezone
1357
      if new_record?
1358
        self.created_on = updated_on
1359
      end
1360
    end
1361
  end
1362

    
1363
  # Callback for setting closed_on when the issue is closed.
1364
  # The closed_on attribute stores the time of the last closing
1365
  # and is preserved when the issue is reopened.
1366
  def update_closed_on
1367
    if closing? || (new_record? && closed?)
1368
      self.closed_on = updated_on
1369
    end
1370
  end
1371

    
1372
  # Saves the changes in a Journal
1373
  # Called after_save
1374
  def create_journal
1375
    if @current_journal
1376
      # attributes changes
1377
      if @attributes_before_change
1378
        (Issue.column_names - %w(id root_id lft rgt lock_version created_on updated_on closed_on)).each {|c|
1379
          before = @attributes_before_change[c]
1380
          after = send(c)
1381
          next if before == after || (before.blank? && after.blank?)
1382
          @current_journal.details << JournalDetail.new(:property => 'attr',
1383
                                                        :prop_key => c,
1384
                                                        :old_value => before,
1385
                                                        :value => after)
1386
        }
1387
      end
1388
      if @custom_values_before_change
1389
        # custom fields changes
1390
        custom_field_values.each {|c|
1391
          before = @custom_values_before_change[c.custom_field_id]
1392
          after = c.value
1393
          next if before == after || (before.blank? && after.blank?)
1394
          
1395
          if before.is_a?(Array) || after.is_a?(Array)
1396
            before = [before] unless before.is_a?(Array)
1397
            after = [after] unless after.is_a?(Array)
1398
            
1399
            # values removed
1400
            (before - after).reject(&:blank?).each do |value|
1401
              @current_journal.details << JournalDetail.new(:property => 'cf',
1402
                                                            :prop_key => c.custom_field_id,
1403
                                                            :old_value => value,
1404
                                                            :value => nil)
1405
            end
1406
            # values added
1407
            (after - before).reject(&:blank?).each do |value|
1408
              @current_journal.details << JournalDetail.new(:property => 'cf',
1409
                                                            :prop_key => c.custom_field_id,
1410
                                                            :old_value => nil,
1411
                                                            :value => value)
1412
            end
1413
          else
1414
            @current_journal.details << JournalDetail.new(:property => 'cf',
1415
                                                          :prop_key => c.custom_field_id,
1416
                                                          :old_value => before,
1417
                                                          :value => after)
1418
          end
1419
        }
1420
      end
1421
      @current_journal.save
1422
      # reset current journal
1423
      init_journal @current_journal.user, @current_journal.notes
1424
    end
1425
  end
1426

    
1427
  # Query generator for selecting groups of issue counts for a project
1428
  # based on specific criteria
1429
  #
1430
  # Options
1431
  # * project - Project to search in.
1432
  # * field - String. Issue field to key off of in the grouping.
1433
  # * joins - String. The table name to join against.
1434
  def self.count_and_group_by(options)
1435
    project = options.delete(:project)
1436
    select_field = options.delete(:field)
1437
    joins = options.delete(:joins)
1438

    
1439
    where = "#{Issue.table_name}.#{select_field}=j.id"
1440

    
1441
    ActiveRecord::Base.connection.select_all("select    s.id as status_id, 
1442
                                                s.is_closed as closed, 
1443
                                                j.id as #{select_field},
1444
                                                count(#{Issue.table_name}.id) as total 
1445
                                              from 
1446
                                                  #{Issue.table_name}, #{Project.table_name}, #{IssueStatus.table_name} s, #{joins} j
1447
                                              where 
1448
                                                #{Issue.table_name}.status_id=s.id 
1449
                                                and #{where}
1450
                                                and #{Issue.table_name}.project_id=#{Project.table_name}.id
1451
                                                and #{visible_condition(User.current, :project => project)}
1452
                                              group by s.id, s.is_closed, j.id")
1453
  end
1454
end
    (1-1/1)