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