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