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