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