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