##// END OF EJS Templates
Fixed that entering #nnn as parent task should validate (#11979)....
Jean-Philippe Lang -
r10447:4b6b56863573
parent child
Show More

The requested changes are too big and content was truncated. Show full diff

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