##// END OF EJS Templates
Refactor: Replace @journal with @issue.current_journal...
Eric Davis -
r3426:c58dc83e74f2
parent child
Show More
@@ -1,590 +1,593
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2008 Jean-Philippe Lang
2 # Copyright (C) 2006-2008 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 IssuesController < ApplicationController
18 class IssuesController < ApplicationController
19 menu_item :new_issue, :only => :new
19 menu_item :new_issue, :only => :new
20 default_search_scope :issues
20 default_search_scope :issues
21
21
22 before_filter :find_issue, :only => [:show, :edit, :update, :reply]
22 before_filter :find_issue, :only => [:show, :edit, :update, :reply]
23 before_filter :find_issues, :only => [:bulk_edit, :move, :destroy]
23 before_filter :find_issues, :only => [:bulk_edit, :move, :destroy]
24 before_filter :find_project, :only => [:new, :update_form, :preview]
24 before_filter :find_project, :only => [:new, :update_form, :preview]
25 before_filter :authorize, :except => [:index, :changes, :gantt, :calendar, :preview, :context_menu]
25 before_filter :authorize, :except => [:index, :changes, :gantt, :calendar, :preview, :context_menu]
26 before_filter :find_optional_project, :only => [:index, :changes, :gantt, :calendar]
26 before_filter :find_optional_project, :only => [:index, :changes, :gantt, :calendar]
27 accept_key_auth :index, :show, :changes
27 accept_key_auth :index, :show, :changes
28
28
29 rescue_from Query::StatementInvalid, :with => :query_statement_invalid
29 rescue_from Query::StatementInvalid, :with => :query_statement_invalid
30
30
31 helper :journals
31 helper :journals
32 helper :projects
32 helper :projects
33 include ProjectsHelper
33 include ProjectsHelper
34 helper :custom_fields
34 helper :custom_fields
35 include CustomFieldsHelper
35 include CustomFieldsHelper
36 helper :issue_relations
36 helper :issue_relations
37 include IssueRelationsHelper
37 include IssueRelationsHelper
38 helper :watchers
38 helper :watchers
39 include WatchersHelper
39 include WatchersHelper
40 helper :attachments
40 helper :attachments
41 include AttachmentsHelper
41 include AttachmentsHelper
42 helper :queries
42 helper :queries
43 include QueriesHelper
43 include QueriesHelper
44 helper :sort
44 helper :sort
45 include SortHelper
45 include SortHelper
46 include IssuesHelper
46 include IssuesHelper
47 helper :timelog
47 helper :timelog
48 include Redmine::Export::PDF
48 include Redmine::Export::PDF
49
49
50 verify :method => [:post, :delete],
50 verify :method => [:post, :delete],
51 :only => :destroy,
51 :only => :destroy,
52 :render => { :nothing => true, :status => :method_not_allowed }
52 :render => { :nothing => true, :status => :method_not_allowed }
53
53
54 verify :method => :put, :only => :update, :render => {:nothing => true, :status => :method_not_allowed }
54 verify :method => :put, :only => :update, :render => {:nothing => true, :status => :method_not_allowed }
55
55
56 def index
56 def index
57 retrieve_query
57 retrieve_query
58 sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
58 sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
59 sort_update({'id' => "#{Issue.table_name}.id"}.merge(@query.available_columns.inject({}) {|h, c| h[c.name.to_s] = c.sortable; h}))
59 sort_update({'id' => "#{Issue.table_name}.id"}.merge(@query.available_columns.inject({}) {|h, c| h[c.name.to_s] = c.sortable; h}))
60
60
61 if @query.valid?
61 if @query.valid?
62 limit = case params[:format]
62 limit = case params[:format]
63 when 'csv', 'pdf'
63 when 'csv', 'pdf'
64 Setting.issues_export_limit.to_i
64 Setting.issues_export_limit.to_i
65 when 'atom'
65 when 'atom'
66 Setting.feeds_limit.to_i
66 Setting.feeds_limit.to_i
67 else
67 else
68 per_page_option
68 per_page_option
69 end
69 end
70
70
71 @issue_count = @query.issue_count
71 @issue_count = @query.issue_count
72 @issue_pages = Paginator.new self, @issue_count, limit, params['page']
72 @issue_pages = Paginator.new self, @issue_count, limit, params['page']
73 @issues = @query.issues(:include => [:assigned_to, :tracker, :priority, :category, :fixed_version],
73 @issues = @query.issues(:include => [:assigned_to, :tracker, :priority, :category, :fixed_version],
74 :order => sort_clause,
74 :order => sort_clause,
75 :offset => @issue_pages.current.offset,
75 :offset => @issue_pages.current.offset,
76 :limit => limit)
76 :limit => limit)
77 @issue_count_by_group = @query.issue_count_by_group
77 @issue_count_by_group = @query.issue_count_by_group
78
78
79 respond_to do |format|
79 respond_to do |format|
80 format.html { render :template => 'issues/index.rhtml', :layout => !request.xhr? }
80 format.html { render :template => 'issues/index.rhtml', :layout => !request.xhr? }
81 format.xml { render :layout => false }
81 format.xml { render :layout => false }
82 format.atom { render_feed(@issues, :title => "#{@project || Setting.app_title}: #{l(:label_issue_plural)}") }
82 format.atom { render_feed(@issues, :title => "#{@project || Setting.app_title}: #{l(:label_issue_plural)}") }
83 format.csv { send_data(issues_to_csv(@issues, @project), :type => 'text/csv; header=present', :filename => 'export.csv') }
83 format.csv { send_data(issues_to_csv(@issues, @project), :type => 'text/csv; header=present', :filename => 'export.csv') }
84 format.pdf { send_data(issues_to_pdf(@issues, @project, @query), :type => 'application/pdf', :filename => 'export.pdf') }
84 format.pdf { send_data(issues_to_pdf(@issues, @project, @query), :type => 'application/pdf', :filename => 'export.pdf') }
85 end
85 end
86 else
86 else
87 # Send html if the query is not valid
87 # Send html if the query is not valid
88 render(:template => 'issues/index.rhtml', :layout => !request.xhr?)
88 render(:template => 'issues/index.rhtml', :layout => !request.xhr?)
89 end
89 end
90 rescue ActiveRecord::RecordNotFound
90 rescue ActiveRecord::RecordNotFound
91 render_404
91 render_404
92 end
92 end
93
93
94 def changes
94 def changes
95 retrieve_query
95 retrieve_query
96 sort_init 'id', 'desc'
96 sort_init 'id', 'desc'
97 sort_update({'id' => "#{Issue.table_name}.id"}.merge(@query.available_columns.inject({}) {|h, c| h[c.name.to_s] = c.sortable; h}))
97 sort_update({'id' => "#{Issue.table_name}.id"}.merge(@query.available_columns.inject({}) {|h, c| h[c.name.to_s] = c.sortable; h}))
98
98
99 if @query.valid?
99 if @query.valid?
100 @journals = @query.journals(:order => "#{Journal.table_name}.created_on DESC",
100 @journals = @query.journals(:order => "#{Journal.table_name}.created_on DESC",
101 :limit => 25)
101 :limit => 25)
102 end
102 end
103 @title = (@project ? @project.name : Setting.app_title) + ": " + (@query.new_record? ? l(:label_changes_details) : @query.name)
103 @title = (@project ? @project.name : Setting.app_title) + ": " + (@query.new_record? ? l(:label_changes_details) : @query.name)
104 render :layout => false, :content_type => 'application/atom+xml'
104 render :layout => false, :content_type => 'application/atom+xml'
105 rescue ActiveRecord::RecordNotFound
105 rescue ActiveRecord::RecordNotFound
106 render_404
106 render_404
107 end
107 end
108
108
109 def show
109 def show
110 @journals = @issue.journals.find(:all, :include => [:user, :details], :order => "#{Journal.table_name}.created_on ASC")
110 @journals = @issue.journals.find(:all, :include => [:user, :details], :order => "#{Journal.table_name}.created_on ASC")
111 @journals.each_with_index {|j,i| j.indice = i+1}
111 @journals.each_with_index {|j,i| j.indice = i+1}
112 @journals.reverse! if User.current.wants_comments_in_reverse_order?
112 @journals.reverse! if User.current.wants_comments_in_reverse_order?
113 @changesets = @issue.changesets.visible.all
113 @changesets = @issue.changesets.visible.all
114 @changesets.reverse! if User.current.wants_comments_in_reverse_order?
114 @changesets.reverse! if User.current.wants_comments_in_reverse_order?
115 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
115 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
116 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
116 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
117 @priorities = IssuePriority.all
117 @priorities = IssuePriority.all
118 @time_entry = TimeEntry.new
118 @time_entry = TimeEntry.new
119 respond_to do |format|
119 respond_to do |format|
120 format.html { render :template => 'issues/show.rhtml' }
120 format.html { render :template => 'issues/show.rhtml' }
121 format.xml { render :layout => false }
121 format.xml { render :layout => false }
122 format.atom { render :action => 'changes', :layout => false, :content_type => 'application/atom+xml' }
122 format.atom { render :action => 'changes', :layout => false, :content_type => 'application/atom+xml' }
123 format.pdf { send_data(issue_to_pdf(@issue), :type => 'application/pdf', :filename => "#{@project.identifier}-#{@issue.id}.pdf") }
123 format.pdf { send_data(issue_to_pdf(@issue), :type => 'application/pdf', :filename => "#{@project.identifier}-#{@issue.id}.pdf") }
124 end
124 end
125 end
125 end
126
126
127 # Add a new issue
127 # Add a new issue
128 # The new issue will be created from an existing one if copy_from parameter is given
128 # The new issue will be created from an existing one if copy_from parameter is given
129 def new
129 def new
130 @issue = Issue.new
130 @issue = Issue.new
131 @issue.copy_from(params[:copy_from]) if params[:copy_from]
131 @issue.copy_from(params[:copy_from]) if params[:copy_from]
132 @issue.project = @project
132 @issue.project = @project
133 # Tracker must be set before custom field values
133 # Tracker must be set before custom field values
134 @issue.tracker ||= @project.trackers.find((params[:issue] && params[:issue][:tracker_id]) || params[:tracker_id] || :first)
134 @issue.tracker ||= @project.trackers.find((params[:issue] && params[:issue][:tracker_id]) || params[:tracker_id] || :first)
135 if @issue.tracker.nil?
135 if @issue.tracker.nil?
136 render_error l(:error_no_tracker_in_project)
136 render_error l(:error_no_tracker_in_project)
137 return
137 return
138 end
138 end
139 if params[:issue].is_a?(Hash)
139 if params[:issue].is_a?(Hash)
140 @issue.safe_attributes = params[:issue]
140 @issue.safe_attributes = params[:issue]
141 @issue.watcher_user_ids = params[:issue]['watcher_user_ids'] if User.current.allowed_to?(:add_issue_watchers, @project)
141 @issue.watcher_user_ids = params[:issue]['watcher_user_ids'] if User.current.allowed_to?(:add_issue_watchers, @project)
142 end
142 end
143 @issue.author = User.current
143 @issue.author = User.current
144
144
145 default_status = IssueStatus.default
145 default_status = IssueStatus.default
146 unless default_status
146 unless default_status
147 render_error l(:error_no_default_issue_status)
147 render_error l(:error_no_default_issue_status)
148 return
148 return
149 end
149 end
150 @issue.status = default_status
150 @issue.status = default_status
151 @allowed_statuses = @issue.new_statuses_allowed_to(User.current, true)
151 @allowed_statuses = @issue.new_statuses_allowed_to(User.current, true)
152
152
153 if request.get? || request.xhr?
153 if request.get? || request.xhr?
154 @issue.start_date ||= Date.today
154 @issue.start_date ||= Date.today
155 else
155 else
156 requested_status = IssueStatus.find_by_id(params[:issue][:status_id])
156 requested_status = IssueStatus.find_by_id(params[:issue][:status_id])
157 # Check that the user is allowed to apply the requested status
157 # Check that the user is allowed to apply the requested status
158 @issue.status = (@allowed_statuses.include? requested_status) ? requested_status : default_status
158 @issue.status = (@allowed_statuses.include? requested_status) ? requested_status : default_status
159 call_hook(:controller_issues_new_before_save, { :params => params, :issue => @issue })
159 call_hook(:controller_issues_new_before_save, { :params => params, :issue => @issue })
160 if @issue.save
160 if @issue.save
161 attachments = Attachment.attach_files(@issue, params[:attachments])
161 attachments = Attachment.attach_files(@issue, params[:attachments])
162 render_attachment_warning_if_needed(@issue)
162 render_attachment_warning_if_needed(@issue)
163 flash[:notice] = l(:notice_successful_create)
163 flash[:notice] = l(:notice_successful_create)
164 call_hook(:controller_issues_new_after_save, { :params => params, :issue => @issue})
164 call_hook(:controller_issues_new_after_save, { :params => params, :issue => @issue})
165 respond_to do |format|
165 respond_to do |format|
166 format.html {
166 format.html {
167 redirect_to(params[:continue] ? { :action => 'new', :tracker_id => @issue.tracker } :
167 redirect_to(params[:continue] ? { :action => 'new', :tracker_id => @issue.tracker } :
168 { :action => 'show', :id => @issue })
168 { :action => 'show', :id => @issue })
169 }
169 }
170 format.xml { render :action => 'show', :status => :created, :location => url_for(:controller => 'issues', :action => 'show', :id => @issue) }
170 format.xml { render :action => 'show', :status => :created, :location => url_for(:controller => 'issues', :action => 'show', :id => @issue) }
171 end
171 end
172 return
172 return
173 else
173 else
174 respond_to do |format|
174 respond_to do |format|
175 format.html { }
175 format.html { }
176 format.xml { render(:xml => @issue.errors, :status => :unprocessable_entity); return }
176 format.xml { render(:xml => @issue.errors, :status => :unprocessable_entity); return }
177 end
177 end
178 end
178 end
179 end
179 end
180 @priorities = IssuePriority.all
180 @priorities = IssuePriority.all
181 render :layout => !request.xhr?
181 render :layout => !request.xhr?
182 end
182 end
183
183
184 # Attributes that can be updated on workflow transition (without :edit permission)
184 # Attributes that can be updated on workflow transition (without :edit permission)
185 # TODO: make it configurable (at least per role)
185 # TODO: make it configurable (at least per role)
186 UPDATABLE_ATTRS_ON_TRANSITION = %w(status_id assigned_to_id fixed_version_id done_ratio) unless const_defined?(:UPDATABLE_ATTRS_ON_TRANSITION)
186 UPDATABLE_ATTRS_ON_TRANSITION = %w(status_id assigned_to_id fixed_version_id done_ratio) unless const_defined?(:UPDATABLE_ATTRS_ON_TRANSITION)
187
187
188 def edit
188 def edit
189 update_issue_from_params
189 update_issue_from_params
190
190
191 @journal = @issue.current_journal
192
191 respond_to do |format|
193 respond_to do |format|
192 format.html { }
194 format.html { }
193 format.xml { }
195 format.xml { }
194 end
196 end
195 end
197 end
196
198
197 def update
199 def update
198 update_issue_from_params
200 update_issue_from_params
199
201
200 if issue_update
202 if issue_update
201 respond_to do |format|
203 respond_to do |format|
202 format.html { redirect_back_or_default({:action => 'show', :id => @issue}) }
204 format.html { redirect_back_or_default({:action => 'show', :id => @issue}) }
203 format.xml { head :ok }
205 format.xml { head :ok }
204 end
206 end
205 else
207 else
208 @journal = @issue.current_journal
206 respond_to do |format|
209 respond_to do |format|
207 format.html { render :action => 'edit' }
210 format.html { render :action => 'edit' }
208 format.xml { render :xml => @issue.errors, :status => :unprocessable_entity }
211 format.xml { render :xml => @issue.errors, :status => :unprocessable_entity }
209 end
212 end
210 end
213 end
211
214
212 rescue ActiveRecord::StaleObjectError
215 rescue ActiveRecord::StaleObjectError
213 # Optimistic locking exception
216 # Optimistic locking exception
214 flash.now[:error] = l(:notice_locking_conflict)
217 flash.now[:error] = l(:notice_locking_conflict)
215 # Remove the previously added attachments if issue was not updated
218 # Remove the previously added attachments if issue was not updated
216 attachments[:files].each(&:destroy) if attachments[:files]
219 attachments[:files].each(&:destroy) if attachments[:files]
217 end
220 end
218
221
219 def reply
222 def reply
220 journal = Journal.find(params[:journal_id]) if params[:journal_id]
223 journal = Journal.find(params[:journal_id]) if params[:journal_id]
221 if journal
224 if journal
222 user = journal.user
225 user = journal.user
223 text = journal.notes
226 text = journal.notes
224 else
227 else
225 user = @issue.author
228 user = @issue.author
226 text = @issue.description
229 text = @issue.description
227 end
230 end
228 content = "#{ll(Setting.default_language, :text_user_wrote, user)}\\n> "
231 content = "#{ll(Setting.default_language, :text_user_wrote, user)}\\n> "
229 content << text.to_s.strip.gsub(%r{<pre>((.|\s)*?)</pre>}m, '[...]').gsub('"', '\"').gsub(/(\r?\n|\r\n?)/, "\\n> ") + "\\n\\n"
232 content << text.to_s.strip.gsub(%r{<pre>((.|\s)*?)</pre>}m, '[...]').gsub('"', '\"').gsub(/(\r?\n|\r\n?)/, "\\n> ") + "\\n\\n"
230 render(:update) { |page|
233 render(:update) { |page|
231 page.<< "$('notes').value = \"#{content}\";"
234 page.<< "$('notes').value = \"#{content}\";"
232 page.show 'update'
235 page.show 'update'
233 page << "Form.Element.focus('notes');"
236 page << "Form.Element.focus('notes');"
234 page << "Element.scrollTo('update');"
237 page << "Element.scrollTo('update');"
235 page << "$('notes').scrollTop = $('notes').scrollHeight - $('notes').clientHeight;"
238 page << "$('notes').scrollTop = $('notes').scrollHeight - $('notes').clientHeight;"
236 }
239 }
237 end
240 end
238
241
239 # Bulk edit a set of issues
242 # Bulk edit a set of issues
240 def bulk_edit
243 def bulk_edit
241 if request.post?
244 if request.post?
242 attributes = (params[:issue] || {}).reject {|k,v| v.blank?}
245 attributes = (params[:issue] || {}).reject {|k,v| v.blank?}
243 attributes.keys.each {|k| attributes[k] = '' if attributes[k] == 'none'}
246 attributes.keys.each {|k| attributes[k] = '' if attributes[k] == 'none'}
244 attributes[:custom_field_values].reject! {|k,v| v.blank?} if attributes[:custom_field_values]
247 attributes[:custom_field_values].reject! {|k,v| v.blank?} if attributes[:custom_field_values]
245
248
246 unsaved_issue_ids = []
249 unsaved_issue_ids = []
247 @issues.each do |issue|
250 @issues.each do |issue|
248 journal = issue.init_journal(User.current, params[:notes])
251 journal = issue.init_journal(User.current, params[:notes])
249 issue.safe_attributes = attributes
252 issue.safe_attributes = attributes
250 call_hook(:controller_issues_bulk_edit_before_save, { :params => params, :issue => issue })
253 call_hook(:controller_issues_bulk_edit_before_save, { :params => params, :issue => issue })
251 unless issue.save
254 unless issue.save
252 # Keep unsaved issue ids to display them in flash error
255 # Keep unsaved issue ids to display them in flash error
253 unsaved_issue_ids << issue.id
256 unsaved_issue_ids << issue.id
254 end
257 end
255 end
258 end
256 if unsaved_issue_ids.empty?
259 if unsaved_issue_ids.empty?
257 flash[:notice] = l(:notice_successful_update) unless @issues.empty?
260 flash[:notice] = l(:notice_successful_update) unless @issues.empty?
258 else
261 else
259 flash[:error] = l(:notice_failed_to_save_issues, :count => unsaved_issue_ids.size,
262 flash[:error] = l(:notice_failed_to_save_issues, :count => unsaved_issue_ids.size,
260 :total => @issues.size,
263 :total => @issues.size,
261 :ids => '#' + unsaved_issue_ids.join(', #'))
264 :ids => '#' + unsaved_issue_ids.join(', #'))
262 end
265 end
263 redirect_back_or_default({:controller => 'issues', :action => 'index', :project_id => @project})
266 redirect_back_or_default({:controller => 'issues', :action => 'index', :project_id => @project})
264 return
267 return
265 end
268 end
266 @available_statuses = Workflow.available_statuses(@project)
269 @available_statuses = Workflow.available_statuses(@project)
267 @custom_fields = @project.all_issue_custom_fields
270 @custom_fields = @project.all_issue_custom_fields
268 end
271 end
269
272
270 def move
273 def move
271 @copy = params[:copy_options] && params[:copy_options][:copy]
274 @copy = params[:copy_options] && params[:copy_options][:copy]
272 @allowed_projects = []
275 @allowed_projects = []
273 # find projects to which the user is allowed to move the issue
276 # find projects to which the user is allowed to move the issue
274 if User.current.admin?
277 if User.current.admin?
275 # admin is allowed to move issues to any active (visible) project
278 # admin is allowed to move issues to any active (visible) project
276 @allowed_projects = Project.find(:all, :conditions => Project.visible_by(User.current))
279 @allowed_projects = Project.find(:all, :conditions => Project.visible_by(User.current))
277 else
280 else
278 User.current.memberships.each {|m| @allowed_projects << m.project if m.roles.detect {|r| r.allowed_to?(:move_issues)}}
281 User.current.memberships.each {|m| @allowed_projects << m.project if m.roles.detect {|r| r.allowed_to?(:move_issues)}}
279 end
282 end
280 @target_project = @allowed_projects.detect {|p| p.id.to_s == params[:new_project_id]} if params[:new_project_id]
283 @target_project = @allowed_projects.detect {|p| p.id.to_s == params[:new_project_id]} if params[:new_project_id]
281 @target_project ||= @project
284 @target_project ||= @project
282 @trackers = @target_project.trackers
285 @trackers = @target_project.trackers
283 @available_statuses = Workflow.available_statuses(@project)
286 @available_statuses = Workflow.available_statuses(@project)
284 if request.post?
287 if request.post?
285 new_tracker = params[:new_tracker_id].blank? ? nil : @target_project.trackers.find_by_id(params[:new_tracker_id])
288 new_tracker = params[:new_tracker_id].blank? ? nil : @target_project.trackers.find_by_id(params[:new_tracker_id])
286 unsaved_issue_ids = []
289 unsaved_issue_ids = []
287 moved_issues = []
290 moved_issues = []
288 @issues.each do |issue|
291 @issues.each do |issue|
289 changed_attributes = {}
292 changed_attributes = {}
290 [:assigned_to_id, :status_id, :start_date, :due_date].each do |valid_attribute|
293 [:assigned_to_id, :status_id, :start_date, :due_date].each do |valid_attribute|
291 unless params[valid_attribute].blank?
294 unless params[valid_attribute].blank?
292 changed_attributes[valid_attribute] = (params[valid_attribute] == 'none' ? nil : params[valid_attribute])
295 changed_attributes[valid_attribute] = (params[valid_attribute] == 'none' ? nil : params[valid_attribute])
293 end
296 end
294 end
297 end
295 issue.init_journal(User.current)
298 issue.init_journal(User.current)
296 call_hook(:controller_issues_move_before_save, { :params => params, :issue => issue, :target_project => @target_project, :copy => !!@copy })
299 call_hook(:controller_issues_move_before_save, { :params => params, :issue => issue, :target_project => @target_project, :copy => !!@copy })
297 if r = issue.move_to(@target_project, new_tracker, {:copy => @copy, :attributes => changed_attributes})
300 if r = issue.move_to(@target_project, new_tracker, {:copy => @copy, :attributes => changed_attributes})
298 moved_issues << r
301 moved_issues << r
299 else
302 else
300 unsaved_issue_ids << issue.id
303 unsaved_issue_ids << issue.id
301 end
304 end
302 end
305 end
303 if unsaved_issue_ids.empty?
306 if unsaved_issue_ids.empty?
304 flash[:notice] = l(:notice_successful_update) unless @issues.empty?
307 flash[:notice] = l(:notice_successful_update) unless @issues.empty?
305 else
308 else
306 flash[:error] = l(:notice_failed_to_save_issues, :count => unsaved_issue_ids.size,
309 flash[:error] = l(:notice_failed_to_save_issues, :count => unsaved_issue_ids.size,
307 :total => @issues.size,
310 :total => @issues.size,
308 :ids => '#' + unsaved_issue_ids.join(', #'))
311 :ids => '#' + unsaved_issue_ids.join(', #'))
309 end
312 end
310 if params[:follow]
313 if params[:follow]
311 if @issues.size == 1 && moved_issues.size == 1
314 if @issues.size == 1 && moved_issues.size == 1
312 redirect_to :controller => 'issues', :action => 'show', :id => moved_issues.first
315 redirect_to :controller => 'issues', :action => 'show', :id => moved_issues.first
313 else
316 else
314 redirect_to :controller => 'issues', :action => 'index', :project_id => (@target_project || @project)
317 redirect_to :controller => 'issues', :action => 'index', :project_id => (@target_project || @project)
315 end
318 end
316 else
319 else
317 redirect_to :controller => 'issues', :action => 'index', :project_id => @project
320 redirect_to :controller => 'issues', :action => 'index', :project_id => @project
318 end
321 end
319 return
322 return
320 end
323 end
321 render :layout => false if request.xhr?
324 render :layout => false if request.xhr?
322 end
325 end
323
326
324 def destroy
327 def destroy
325 @hours = TimeEntry.sum(:hours, :conditions => ['issue_id IN (?)', @issues]).to_f
328 @hours = TimeEntry.sum(:hours, :conditions => ['issue_id IN (?)', @issues]).to_f
326 if @hours > 0
329 if @hours > 0
327 case params[:todo]
330 case params[:todo]
328 when 'destroy'
331 when 'destroy'
329 # nothing to do
332 # nothing to do
330 when 'nullify'
333 when 'nullify'
331 TimeEntry.update_all('issue_id = NULL', ['issue_id IN (?)', @issues])
334 TimeEntry.update_all('issue_id = NULL', ['issue_id IN (?)', @issues])
332 when 'reassign'
335 when 'reassign'
333 reassign_to = @project.issues.find_by_id(params[:reassign_to_id])
336 reassign_to = @project.issues.find_by_id(params[:reassign_to_id])
334 if reassign_to.nil?
337 if reassign_to.nil?
335 flash.now[:error] = l(:error_issue_not_found_in_project)
338 flash.now[:error] = l(:error_issue_not_found_in_project)
336 return
339 return
337 else
340 else
338 TimeEntry.update_all("issue_id = #{reassign_to.id}", ['issue_id IN (?)', @issues])
341 TimeEntry.update_all("issue_id = #{reassign_to.id}", ['issue_id IN (?)', @issues])
339 end
342 end
340 else
343 else
341 unless params[:format] == 'xml'
344 unless params[:format] == 'xml'
342 # display the destroy form if it's a user request
345 # display the destroy form if it's a user request
343 return
346 return
344 end
347 end
345 end
348 end
346 end
349 end
347 @issues.each(&:destroy)
350 @issues.each(&:destroy)
348 respond_to do |format|
351 respond_to do |format|
349 format.html { redirect_to :action => 'index', :project_id => @project }
352 format.html { redirect_to :action => 'index', :project_id => @project }
350 format.xml { head :ok }
353 format.xml { head :ok }
351 end
354 end
352 end
355 end
353
356
354 def gantt
357 def gantt
355 @gantt = Redmine::Helpers::Gantt.new(params)
358 @gantt = Redmine::Helpers::Gantt.new(params)
356 retrieve_query
359 retrieve_query
357 @query.group_by = nil
360 @query.group_by = nil
358 if @query.valid?
361 if @query.valid?
359 events = []
362 events = []
360 # Issues that have start and due dates
363 # Issues that have start and due dates
361 events += @query.issues(:include => [:tracker, :assigned_to, :priority],
364 events += @query.issues(:include => [:tracker, :assigned_to, :priority],
362 :order => "start_date, due_date",
365 :order => "start_date, due_date",
363 :conditions => ["(((start_date>=? and start_date<=?) or (due_date>=? and due_date<=?) or (start_date<? and due_date>?)) and start_date is not null and due_date is not null)", @gantt.date_from, @gantt.date_to, @gantt.date_from, @gantt.date_to, @gantt.date_from, @gantt.date_to]
366 :conditions => ["(((start_date>=? and start_date<=?) or (due_date>=? and due_date<=?) or (start_date<? and due_date>?)) and start_date is not null and due_date is not null)", @gantt.date_from, @gantt.date_to, @gantt.date_from, @gantt.date_to, @gantt.date_from, @gantt.date_to]
364 )
367 )
365 # Issues that don't have a due date but that are assigned to a version with a date
368 # Issues that don't have a due date but that are assigned to a version with a date
366 events += @query.issues(:include => [:tracker, :assigned_to, :priority, :fixed_version],
369 events += @query.issues(:include => [:tracker, :assigned_to, :priority, :fixed_version],
367 :order => "start_date, effective_date",
370 :order => "start_date, effective_date",
368 :conditions => ["(((start_date>=? and start_date<=?) or (effective_date>=? and effective_date<=?) or (start_date<? and effective_date>?)) and start_date is not null and due_date is null and effective_date is not null)", @gantt.date_from, @gantt.date_to, @gantt.date_from, @gantt.date_to, @gantt.date_from, @gantt.date_to]
371 :conditions => ["(((start_date>=? and start_date<=?) or (effective_date>=? and effective_date<=?) or (start_date<? and effective_date>?)) and start_date is not null and due_date is null and effective_date is not null)", @gantt.date_from, @gantt.date_to, @gantt.date_from, @gantt.date_to, @gantt.date_from, @gantt.date_to]
369 )
372 )
370 # Versions
373 # Versions
371 events += @query.versions(:conditions => ["effective_date BETWEEN ? AND ?", @gantt.date_from, @gantt.date_to])
374 events += @query.versions(:conditions => ["effective_date BETWEEN ? AND ?", @gantt.date_from, @gantt.date_to])
372
375
373 @gantt.events = events
376 @gantt.events = events
374 end
377 end
375
378
376 basename = (@project ? "#{@project.identifier}-" : '') + 'gantt'
379 basename = (@project ? "#{@project.identifier}-" : '') + 'gantt'
377
380
378 respond_to do |format|
381 respond_to do |format|
379 format.html { render :template => "issues/gantt.rhtml", :layout => !request.xhr? }
382 format.html { render :template => "issues/gantt.rhtml", :layout => !request.xhr? }
380 format.png { send_data(@gantt.to_image, :disposition => 'inline', :type => 'image/png', :filename => "#{basename}.png") } if @gantt.respond_to?('to_image')
383 format.png { send_data(@gantt.to_image, :disposition => 'inline', :type => 'image/png', :filename => "#{basename}.png") } if @gantt.respond_to?('to_image')
381 format.pdf { send_data(gantt_to_pdf(@gantt, @project), :type => 'application/pdf', :filename => "#{basename}.pdf") }
384 format.pdf { send_data(gantt_to_pdf(@gantt, @project), :type => 'application/pdf', :filename => "#{basename}.pdf") }
382 end
385 end
383 end
386 end
384
387
385 def calendar
388 def calendar
386 if params[:year] and params[:year].to_i > 1900
389 if params[:year] and params[:year].to_i > 1900
387 @year = params[:year].to_i
390 @year = params[:year].to_i
388 if params[:month] and params[:month].to_i > 0 and params[:month].to_i < 13
391 if params[:month] and params[:month].to_i > 0 and params[:month].to_i < 13
389 @month = params[:month].to_i
392 @month = params[:month].to_i
390 end
393 end
391 end
394 end
392 @year ||= Date.today.year
395 @year ||= Date.today.year
393 @month ||= Date.today.month
396 @month ||= Date.today.month
394
397
395 @calendar = Redmine::Helpers::Calendar.new(Date.civil(@year, @month, 1), current_language, :month)
398 @calendar = Redmine::Helpers::Calendar.new(Date.civil(@year, @month, 1), current_language, :month)
396 retrieve_query
399 retrieve_query
397 @query.group_by = nil
400 @query.group_by = nil
398 if @query.valid?
401 if @query.valid?
399 events = []
402 events = []
400 events += @query.issues(:include => [:tracker, :assigned_to, :priority],
403 events += @query.issues(:include => [:tracker, :assigned_to, :priority],
401 :conditions => ["((start_date BETWEEN ? AND ?) OR (due_date BETWEEN ? AND ?))", @calendar.startdt, @calendar.enddt, @calendar.startdt, @calendar.enddt]
404 :conditions => ["((start_date BETWEEN ? AND ?) OR (due_date BETWEEN ? AND ?))", @calendar.startdt, @calendar.enddt, @calendar.startdt, @calendar.enddt]
402 )
405 )
403 events += @query.versions(:conditions => ["effective_date BETWEEN ? AND ?", @calendar.startdt, @calendar.enddt])
406 events += @query.versions(:conditions => ["effective_date BETWEEN ? AND ?", @calendar.startdt, @calendar.enddt])
404
407
405 @calendar.events = events
408 @calendar.events = events
406 end
409 end
407
410
408 render :layout => false if request.xhr?
411 render :layout => false if request.xhr?
409 end
412 end
410
413
411 def context_menu
414 def context_menu
412 @issues = Issue.find_all_by_id(params[:ids], :include => :project)
415 @issues = Issue.find_all_by_id(params[:ids], :include => :project)
413 if (@issues.size == 1)
416 if (@issues.size == 1)
414 @issue = @issues.first
417 @issue = @issues.first
415 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
418 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
416 end
419 end
417 projects = @issues.collect(&:project).compact.uniq
420 projects = @issues.collect(&:project).compact.uniq
418 @project = projects.first if projects.size == 1
421 @project = projects.first if projects.size == 1
419
422
420 @can = {:edit => (@project && User.current.allowed_to?(:edit_issues, @project)),
423 @can = {:edit => (@project && User.current.allowed_to?(:edit_issues, @project)),
421 :log_time => (@project && User.current.allowed_to?(:log_time, @project)),
424 :log_time => (@project && User.current.allowed_to?(:log_time, @project)),
422 :update => (@project && (User.current.allowed_to?(:edit_issues, @project) || (User.current.allowed_to?(:change_status, @project) && @allowed_statuses && !@allowed_statuses.empty?))),
425 :update => (@project && (User.current.allowed_to?(:edit_issues, @project) || (User.current.allowed_to?(:change_status, @project) && @allowed_statuses && !@allowed_statuses.empty?))),
423 :move => (@project && User.current.allowed_to?(:move_issues, @project)),
426 :move => (@project && User.current.allowed_to?(:move_issues, @project)),
424 :copy => (@issue && @project.trackers.include?(@issue.tracker) && User.current.allowed_to?(:add_issues, @project)),
427 :copy => (@issue && @project.trackers.include?(@issue.tracker) && User.current.allowed_to?(:add_issues, @project)),
425 :delete => (@project && User.current.allowed_to?(:delete_issues, @project))
428 :delete => (@project && User.current.allowed_to?(:delete_issues, @project))
426 }
429 }
427 if @project
430 if @project
428 @assignables = @project.assignable_users
431 @assignables = @project.assignable_users
429 @assignables << @issue.assigned_to if @issue && @issue.assigned_to && !@assignables.include?(@issue.assigned_to)
432 @assignables << @issue.assigned_to if @issue && @issue.assigned_to && !@assignables.include?(@issue.assigned_to)
430 @trackers = @project.trackers
433 @trackers = @project.trackers
431 end
434 end
432
435
433 @priorities = IssuePriority.all.reverse
436 @priorities = IssuePriority.all.reverse
434 @statuses = IssueStatus.find(:all, :order => 'position')
437 @statuses = IssueStatus.find(:all, :order => 'position')
435 @back = params[:back_url] || request.env['HTTP_REFERER']
438 @back = params[:back_url] || request.env['HTTP_REFERER']
436
439
437 render :layout => false
440 render :layout => false
438 end
441 end
439
442
440 def update_form
443 def update_form
441 if params[:id].blank?
444 if params[:id].blank?
442 @issue = Issue.new
445 @issue = Issue.new
443 @issue.project = @project
446 @issue.project = @project
444 else
447 else
445 @issue = @project.issues.visible.find(params[:id])
448 @issue = @project.issues.visible.find(params[:id])
446 end
449 end
447 @issue.attributes = params[:issue]
450 @issue.attributes = params[:issue]
448 @allowed_statuses = ([@issue.status] + @issue.status.find_new_statuses_allowed_to(User.current.roles_for_project(@project), @issue.tracker)).uniq
451 @allowed_statuses = ([@issue.status] + @issue.status.find_new_statuses_allowed_to(User.current.roles_for_project(@project), @issue.tracker)).uniq
449 @priorities = IssuePriority.all
452 @priorities = IssuePriority.all
450
453
451 render :partial => 'attributes'
454 render :partial => 'attributes'
452 end
455 end
453
456
454 def preview
457 def preview
455 @issue = @project.issues.find_by_id(params[:id]) unless params[:id].blank?
458 @issue = @project.issues.find_by_id(params[:id]) unless params[:id].blank?
456 @attachements = @issue.attachments if @issue
459 @attachements = @issue.attachments if @issue
457 @text = params[:notes] || (params[:issue] ? params[:issue][:description] : nil)
460 @text = params[:notes] || (params[:issue] ? params[:issue][:description] : nil)
458 render :partial => 'common/preview'
461 render :partial => 'common/preview'
459 end
462 end
460
463
461 private
464 private
462 def find_issue
465 def find_issue
463 @issue = Issue.find(params[:id], :include => [:project, :tracker, :status, :author, :priority, :category])
466 @issue = Issue.find(params[:id], :include => [:project, :tracker, :status, :author, :priority, :category])
464 @project = @issue.project
467 @project = @issue.project
465 rescue ActiveRecord::RecordNotFound
468 rescue ActiveRecord::RecordNotFound
466 render_404
469 render_404
467 end
470 end
468
471
469 # Filter for bulk operations
472 # Filter for bulk operations
470 def find_issues
473 def find_issues
471 @issues = Issue.find_all_by_id(params[:id] || params[:ids])
474 @issues = Issue.find_all_by_id(params[:id] || params[:ids])
472 raise ActiveRecord::RecordNotFound if @issues.empty?
475 raise ActiveRecord::RecordNotFound if @issues.empty?
473 projects = @issues.collect(&:project).compact.uniq
476 projects = @issues.collect(&:project).compact.uniq
474 if projects.size == 1
477 if projects.size == 1
475 @project = projects.first
478 @project = projects.first
476 else
479 else
477 # TODO: let users bulk edit/move/destroy issues from different projects
480 # TODO: let users bulk edit/move/destroy issues from different projects
478 render_error 'Can not bulk edit/move/destroy issues from different projects'
481 render_error 'Can not bulk edit/move/destroy issues from different projects'
479 return false
482 return false
480 end
483 end
481 rescue ActiveRecord::RecordNotFound
484 rescue ActiveRecord::RecordNotFound
482 render_404
485 render_404
483 end
486 end
484
487
485 def find_project
488 def find_project
486 project_id = (params[:issue] && params[:issue][:project_id]) || params[:project_id]
489 project_id = (params[:issue] && params[:issue][:project_id]) || params[:project_id]
487 @project = Project.find(project_id)
490 @project = Project.find(project_id)
488 rescue ActiveRecord::RecordNotFound
491 rescue ActiveRecord::RecordNotFound
489 render_404
492 render_404
490 end
493 end
491
494
492 def find_optional_project
495 def find_optional_project
493 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
496 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
494 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
497 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
495 allowed ? true : deny_access
498 allowed ? true : deny_access
496 rescue ActiveRecord::RecordNotFound
499 rescue ActiveRecord::RecordNotFound
497 render_404
500 render_404
498 end
501 end
499
502
500 # Retrieve query from session or build a new query
503 # Retrieve query from session or build a new query
501 def retrieve_query
504 def retrieve_query
502 if !params[:query_id].blank?
505 if !params[:query_id].blank?
503 cond = "project_id IS NULL"
506 cond = "project_id IS NULL"
504 cond << " OR project_id = #{@project.id}" if @project
507 cond << " OR project_id = #{@project.id}" if @project
505 @query = Query.find(params[:query_id], :conditions => cond)
508 @query = Query.find(params[:query_id], :conditions => cond)
506 @query.project = @project
509 @query.project = @project
507 session[:query] = {:id => @query.id, :project_id => @query.project_id}
510 session[:query] = {:id => @query.id, :project_id => @query.project_id}
508 sort_clear
511 sort_clear
509 else
512 else
510 if api_request? || params[:set_filter] || session[:query].nil? || session[:query][:project_id] != (@project ? @project.id : nil)
513 if api_request? || params[:set_filter] || session[:query].nil? || session[:query][:project_id] != (@project ? @project.id : nil)
511 # Give it a name, required to be valid
514 # Give it a name, required to be valid
512 @query = Query.new(:name => "_")
515 @query = Query.new(:name => "_")
513 @query.project = @project
516 @query.project = @project
514 if params[:fields] and params[:fields].is_a? Array
517 if params[:fields] and params[:fields].is_a? Array
515 params[:fields].each do |field|
518 params[:fields].each do |field|
516 @query.add_filter(field, params[:operators][field], params[:values][field])
519 @query.add_filter(field, params[:operators][field], params[:values][field])
517 end
520 end
518 else
521 else
519 @query.available_filters.keys.each do |field|
522 @query.available_filters.keys.each do |field|
520 @query.add_short_filter(field, params[field]) if params[field]
523 @query.add_short_filter(field, params[field]) if params[field]
521 end
524 end
522 end
525 end
523 @query.group_by = params[:group_by]
526 @query.group_by = params[:group_by]
524 @query.column_names = params[:query] && params[:query][:column_names]
527 @query.column_names = params[:query] && params[:query][:column_names]
525 session[:query] = {:project_id => @query.project_id, :filters => @query.filters, :group_by => @query.group_by, :column_names => @query.column_names}
528 session[:query] = {:project_id => @query.project_id, :filters => @query.filters, :group_by => @query.group_by, :column_names => @query.column_names}
526 else
529 else
527 @query = Query.find_by_id(session[:query][:id]) if session[:query][:id]
530 @query = Query.find_by_id(session[:query][:id]) if session[:query][:id]
528 @query ||= Query.new(:name => "_", :project => @project, :filters => session[:query][:filters], :group_by => session[:query][:group_by], :column_names => session[:query][:column_names])
531 @query ||= Query.new(:name => "_", :project => @project, :filters => session[:query][:filters], :group_by => session[:query][:group_by], :column_names => session[:query][:column_names])
529 @query.project = @project
532 @query.project = @project
530 end
533 end
531 end
534 end
532 end
535 end
533
536
534 # Rescues an invalid query statement. Just in case...
537 # Rescues an invalid query statement. Just in case...
535 def query_statement_invalid(exception)
538 def query_statement_invalid(exception)
536 logger.error "Query::StatementInvalid: #{exception.message}" if logger
539 logger.error "Query::StatementInvalid: #{exception.message}" if logger
537 session.delete(:query)
540 session.delete(:query)
538 sort_clear
541 sort_clear
539 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
542 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
540 end
543 end
541
544
542 # Used by #edit and #update to set some common instance variables
545 # Used by #edit and #update to set some common instance variables
543 # from the params
546 # from the params
544 # TODO: Refactor, not everything in here is needed by #edit
547 # TODO: Refactor, not everything in here is needed by #edit
545 def update_issue_from_params
548 def update_issue_from_params
546 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
549 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
547 @priorities = IssuePriority.all
550 @priorities = IssuePriority.all
548 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
551 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
549 @time_entry = TimeEntry.new
552 @time_entry = TimeEntry.new
550
553
551 @notes = params[:notes]
554 @notes = params[:notes]
552 @journal = @issue.init_journal(User.current, @notes)
555 @issue.init_journal(User.current, @notes)
553 # User can change issue attributes only if he has :edit permission or if a workflow transition is allowed
556 # User can change issue attributes only if he has :edit permission or if a workflow transition is allowed
554 if (@edit_allowed || !@allowed_statuses.empty?) && params[:issue]
557 if (@edit_allowed || !@allowed_statuses.empty?) && params[:issue]
555 attrs = params[:issue].dup
558 attrs = params[:issue].dup
556 attrs.delete_if {|k,v| !UPDATABLE_ATTRS_ON_TRANSITION.include?(k) } unless @edit_allowed
559 attrs.delete_if {|k,v| !UPDATABLE_ATTRS_ON_TRANSITION.include?(k) } unless @edit_allowed
557 attrs.delete(:status_id) unless @allowed_statuses.detect {|s| s.id.to_s == attrs[:status_id].to_s}
560 attrs.delete(:status_id) unless @allowed_statuses.detect {|s| s.id.to_s == attrs[:status_id].to_s}
558 @issue.safe_attributes = attrs
561 @issue.safe_attributes = attrs
559 end
562 end
560
563
561 end
564 end
562
565
563 # TODO: Temporary utility method for #update. Should be split off
566 # TODO: Temporary utility method for #update. Should be split off
564 # and moved to the Issue model (accepts_nested_attributes_for maybe?)
567 # and moved to the Issue model (accepts_nested_attributes_for maybe?)
565 def issue_update
568 def issue_update
566 if params[:time_entry] && params[:time_entry][:hours].present? && User.current.allowed_to?(:log_time, @project)
569 if params[:time_entry] && params[:time_entry][:hours].present? && User.current.allowed_to?(:log_time, @project)
567 @time_entry = TimeEntry.new(:project => @project, :issue => @issue, :user => User.current, :spent_on => Date.today)
570 @time_entry = TimeEntry.new(:project => @project, :issue => @issue, :user => User.current, :spent_on => Date.today)
568 @time_entry.attributes = params[:time_entry]
571 @time_entry.attributes = params[:time_entry]
569 @issue.time_entries << @time_entry
572 @issue.time_entries << @time_entry
570 end
573 end
571
574
572 if @issue.valid?
575 if @issue.valid?
573 attachments = Attachment.attach_files(@issue, params[:attachments])
576 attachments = Attachment.attach_files(@issue, params[:attachments])
574 render_attachment_warning_if_needed(@issue)
577 render_attachment_warning_if_needed(@issue)
575
578
576 attachments[:files].each {|a| @journal.details << JournalDetail.new(:property => 'attachment', :prop_key => a.id, :value => a.filename)}
579 attachments[:files].each {|a| @issue.current_journal.details << JournalDetail.new(:property => 'attachment', :prop_key => a.id, :value => a.filename)}
577 call_hook(:controller_issues_edit_before_save, { :params => params, :issue => @issue, :time_entry => @time_entry, :journal => @journal})
580 call_hook(:controller_issues_edit_before_save, { :params => params, :issue => @issue, :time_entry => @time_entry, :journal => @issue.current_journal})
578 if @issue.save
581 if @issue.save
579 if !@journal.new_record?
582 if !@issue.current_journal.new_record?
580 # Only send notification if something was actually changed
583 # Only send notification if something was actually changed
581 flash[:notice] = l(:notice_successful_update)
584 flash[:notice] = l(:notice_successful_update)
582 end
585 end
583 call_hook(:controller_issues_edit_after_save, { :params => params, :issue => @issue, :time_entry => @time_entry, :journal => @journal})
586 call_hook(:controller_issues_edit_after_save, { :params => params, :issue => @issue, :time_entry => @time_entry, :journal => @issue.current_journal})
584 return true
587 return true
585 end
588 end
586 end
589 end
587 # failure, returns false
590 # failure, returns false
588
591
589 end
592 end
590 end
593 end
@@ -1,578 +1,580
1 # redMine - project management software
1 # redMine - project management software
2 # Copyright (C) 2006-2007 Jean-Philippe Lang
2 # Copyright (C) 2006-2007 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 belongs_to :project
19 belongs_to :project
20 belongs_to :tracker
20 belongs_to :tracker
21 belongs_to :status, :class_name => 'IssueStatus', :foreign_key => 'status_id'
21 belongs_to :status, :class_name => 'IssueStatus', :foreign_key => 'status_id'
22 belongs_to :author, :class_name => 'User', :foreign_key => 'author_id'
22 belongs_to :author, :class_name => 'User', :foreign_key => 'author_id'
23 belongs_to :assigned_to, :class_name => 'User', :foreign_key => 'assigned_to_id'
23 belongs_to :assigned_to, :class_name => 'User', :foreign_key => 'assigned_to_id'
24 belongs_to :fixed_version, :class_name => 'Version', :foreign_key => 'fixed_version_id'
24 belongs_to :fixed_version, :class_name => 'Version', :foreign_key => 'fixed_version_id'
25 belongs_to :priority, :class_name => 'IssuePriority', :foreign_key => 'priority_id'
25 belongs_to :priority, :class_name => 'IssuePriority', :foreign_key => 'priority_id'
26 belongs_to :category, :class_name => 'IssueCategory', :foreign_key => 'category_id'
26 belongs_to :category, :class_name => 'IssueCategory', :foreign_key => 'category_id'
27
27
28 has_many :journals, :as => :journalized, :dependent => :destroy
28 has_many :journals, :as => :journalized, :dependent => :destroy
29 has_many :time_entries, :dependent => :delete_all
29 has_many :time_entries, :dependent => :delete_all
30 has_and_belongs_to_many :changesets, :order => "#{Changeset.table_name}.committed_on ASC, #{Changeset.table_name}.id ASC"
30 has_and_belongs_to_many :changesets, :order => "#{Changeset.table_name}.committed_on ASC, #{Changeset.table_name}.id ASC"
31
31
32 has_many :relations_from, :class_name => 'IssueRelation', :foreign_key => 'issue_from_id', :dependent => :delete_all
32 has_many :relations_from, :class_name => 'IssueRelation', :foreign_key => 'issue_from_id', :dependent => :delete_all
33 has_many :relations_to, :class_name => 'IssueRelation', :foreign_key => 'issue_to_id', :dependent => :delete_all
33 has_many :relations_to, :class_name => 'IssueRelation', :foreign_key => 'issue_to_id', :dependent => :delete_all
34
34
35 acts_as_attachable :after_remove => :attachment_removed
35 acts_as_attachable :after_remove => :attachment_removed
36 acts_as_customizable
36 acts_as_customizable
37 acts_as_watchable
37 acts_as_watchable
38 acts_as_searchable :columns => ['subject', "#{table_name}.description", "#{Journal.table_name}.notes"],
38 acts_as_searchable :columns => ['subject', "#{table_name}.description", "#{Journal.table_name}.notes"],
39 :include => [:project, :journals],
39 :include => [:project, :journals],
40 # sort by id so that limited eager loading doesn't break with postgresql
40 # sort by id so that limited eager loading doesn't break with postgresql
41 :order_column => "#{table_name}.id"
41 :order_column => "#{table_name}.id"
42 acts_as_event :title => Proc.new {|o| "#{o.tracker.name} ##{o.id} (#{o.status}): #{o.subject}"},
42 acts_as_event :title => Proc.new {|o| "#{o.tracker.name} ##{o.id} (#{o.status}): #{o.subject}"},
43 :url => Proc.new {|o| {:controller => 'issues', :action => 'show', :id => o.id}},
43 :url => Proc.new {|o| {:controller => 'issues', :action => 'show', :id => o.id}},
44 :type => Proc.new {|o| 'issue' + (o.closed? ? ' closed' : '') }
44 :type => Proc.new {|o| 'issue' + (o.closed? ? ' closed' : '') }
45
45
46 acts_as_activity_provider :find_options => {:include => [:project, :author, :tracker]},
46 acts_as_activity_provider :find_options => {:include => [:project, :author, :tracker]},
47 :author_key => :author_id
47 :author_key => :author_id
48
48
49 DONE_RATIO_OPTIONS = %w(issue_field issue_status)
49 DONE_RATIO_OPTIONS = %w(issue_field issue_status)
50
51 attr_reader :current_journal
50
52
51 validates_presence_of :subject, :priority, :project, :tracker, :author, :status
53 validates_presence_of :subject, :priority, :project, :tracker, :author, :status
52 validates_length_of :subject, :maximum => 255
54 validates_length_of :subject, :maximum => 255
53 validates_inclusion_of :done_ratio, :in => 0..100
55 validates_inclusion_of :done_ratio, :in => 0..100
54 validates_numericality_of :estimated_hours, :allow_nil => true
56 validates_numericality_of :estimated_hours, :allow_nil => true
55
57
56 named_scope :visible, lambda {|*args| { :include => :project,
58 named_scope :visible, lambda {|*args| { :include => :project,
57 :conditions => Project.allowed_to_condition(args.first || User.current, :view_issues) } }
59 :conditions => Project.allowed_to_condition(args.first || User.current, :view_issues) } }
58
60
59 named_scope :open, :conditions => ["#{IssueStatus.table_name}.is_closed = ?", false], :include => :status
61 named_scope :open, :conditions => ["#{IssueStatus.table_name}.is_closed = ?", false], :include => :status
60
62
61 before_create :default_assign
63 before_create :default_assign
62 before_save :reschedule_following_issues, :close_duplicates, :update_done_ratio_from_issue_status
64 before_save :reschedule_following_issues, :close_duplicates, :update_done_ratio_from_issue_status
63 after_save :create_journal
65 after_save :create_journal
64
66
65 # Returns true if usr or current user is allowed to view the issue
67 # Returns true if usr or current user is allowed to view the issue
66 def visible?(usr=nil)
68 def visible?(usr=nil)
67 (usr || User.current).allowed_to?(:view_issues, self.project)
69 (usr || User.current).allowed_to?(:view_issues, self.project)
68 end
70 end
69
71
70 def after_initialize
72 def after_initialize
71 if new_record?
73 if new_record?
72 # set default values for new records only
74 # set default values for new records only
73 self.status ||= IssueStatus.default
75 self.status ||= IssueStatus.default
74 self.priority ||= IssuePriority.default
76 self.priority ||= IssuePriority.default
75 end
77 end
76 end
78 end
77
79
78 # Overrides Redmine::Acts::Customizable::InstanceMethods#available_custom_fields
80 # Overrides Redmine::Acts::Customizable::InstanceMethods#available_custom_fields
79 def available_custom_fields
81 def available_custom_fields
80 (project && tracker) ? project.all_issue_custom_fields.select {|c| tracker.custom_fields.include? c } : []
82 (project && tracker) ? project.all_issue_custom_fields.select {|c| tracker.custom_fields.include? c } : []
81 end
83 end
82
84
83 def copy_from(arg)
85 def copy_from(arg)
84 issue = arg.is_a?(Issue) ? arg : Issue.find(arg)
86 issue = arg.is_a?(Issue) ? arg : Issue.find(arg)
85 self.attributes = issue.attributes.dup.except("id", "created_on", "updated_on")
87 self.attributes = issue.attributes.dup.except("id", "created_on", "updated_on")
86 self.custom_values = issue.custom_values.collect {|v| v.clone}
88 self.custom_values = issue.custom_values.collect {|v| v.clone}
87 self.status = issue.status
89 self.status = issue.status
88 self
90 self
89 end
91 end
90
92
91 # Moves/copies an issue to a new project and tracker
93 # Moves/copies an issue to a new project and tracker
92 # Returns the moved/copied issue on success, false on failure
94 # Returns the moved/copied issue on success, false on failure
93 def move_to(new_project, new_tracker = nil, options = {})
95 def move_to(new_project, new_tracker = nil, options = {})
94 options ||= {}
96 options ||= {}
95 issue = options[:copy] ? self.clone : self
97 issue = options[:copy] ? self.clone : self
96 transaction do
98 transaction do
97 if new_project && issue.project_id != new_project.id
99 if new_project && issue.project_id != new_project.id
98 # delete issue relations
100 # delete issue relations
99 unless Setting.cross_project_issue_relations?
101 unless Setting.cross_project_issue_relations?
100 issue.relations_from.clear
102 issue.relations_from.clear
101 issue.relations_to.clear
103 issue.relations_to.clear
102 end
104 end
103 # issue is moved to another project
105 # issue is moved to another project
104 # reassign to the category with same name if any
106 # reassign to the category with same name if any
105 new_category = issue.category.nil? ? nil : new_project.issue_categories.find_by_name(issue.category.name)
107 new_category = issue.category.nil? ? nil : new_project.issue_categories.find_by_name(issue.category.name)
106 issue.category = new_category
108 issue.category = new_category
107 # Keep the fixed_version if it's still valid in the new_project
109 # Keep the fixed_version if it's still valid in the new_project
108 unless new_project.shared_versions.include?(issue.fixed_version)
110 unless new_project.shared_versions.include?(issue.fixed_version)
109 issue.fixed_version = nil
111 issue.fixed_version = nil
110 end
112 end
111 issue.project = new_project
113 issue.project = new_project
112 end
114 end
113 if new_tracker
115 if new_tracker
114 issue.tracker = new_tracker
116 issue.tracker = new_tracker
115 end
117 end
116 if options[:copy]
118 if options[:copy]
117 issue.custom_field_values = self.custom_field_values.inject({}) {|h,v| h[v.custom_field_id] = v.value; h}
119 issue.custom_field_values = self.custom_field_values.inject({}) {|h,v| h[v.custom_field_id] = v.value; h}
118 issue.status = if options[:attributes] && options[:attributes][:status_id]
120 issue.status = if options[:attributes] && options[:attributes][:status_id]
119 IssueStatus.find_by_id(options[:attributes][:status_id])
121 IssueStatus.find_by_id(options[:attributes][:status_id])
120 else
122 else
121 self.status
123 self.status
122 end
124 end
123 end
125 end
124 # Allow bulk setting of attributes on the issue
126 # Allow bulk setting of attributes on the issue
125 if options[:attributes]
127 if options[:attributes]
126 issue.attributes = options[:attributes]
128 issue.attributes = options[:attributes]
127 end
129 end
128 if issue.save
130 if issue.save
129 unless options[:copy]
131 unless options[:copy]
130 # Manually update project_id on related time entries
132 # Manually update project_id on related time entries
131 TimeEntry.update_all("project_id = #{new_project.id}", {:issue_id => id})
133 TimeEntry.update_all("project_id = #{new_project.id}", {:issue_id => id})
132 end
134 end
133 else
135 else
134 Issue.connection.rollback_db_transaction
136 Issue.connection.rollback_db_transaction
135 return false
137 return false
136 end
138 end
137 end
139 end
138 return issue
140 return issue
139 end
141 end
140
142
141 def priority_id=(pid)
143 def priority_id=(pid)
142 self.priority = nil
144 self.priority = nil
143 write_attribute(:priority_id, pid)
145 write_attribute(:priority_id, pid)
144 end
146 end
145
147
146 def tracker_id=(tid)
148 def tracker_id=(tid)
147 self.tracker = nil
149 self.tracker = nil
148 result = write_attribute(:tracker_id, tid)
150 result = write_attribute(:tracker_id, tid)
149 @custom_field_values = nil
151 @custom_field_values = nil
150 result
152 result
151 end
153 end
152
154
153 # Overrides attributes= so that tracker_id gets assigned first
155 # Overrides attributes= so that tracker_id gets assigned first
154 def attributes_with_tracker_first=(new_attributes, *args)
156 def attributes_with_tracker_first=(new_attributes, *args)
155 return if new_attributes.nil?
157 return if new_attributes.nil?
156 new_tracker_id = new_attributes['tracker_id'] || new_attributes[:tracker_id]
158 new_tracker_id = new_attributes['tracker_id'] || new_attributes[:tracker_id]
157 if new_tracker_id
159 if new_tracker_id
158 self.tracker_id = new_tracker_id
160 self.tracker_id = new_tracker_id
159 end
161 end
160 send :attributes_without_tracker_first=, new_attributes, *args
162 send :attributes_without_tracker_first=, new_attributes, *args
161 end
163 end
162 # Do not redefine alias chain on reload (see #4838)
164 # Do not redefine alias chain on reload (see #4838)
163 alias_method_chain(:attributes=, :tracker_first) unless method_defined?(:attributes_without_tracker_first=)
165 alias_method_chain(:attributes=, :tracker_first) unless method_defined?(:attributes_without_tracker_first=)
164
166
165 def estimated_hours=(h)
167 def estimated_hours=(h)
166 write_attribute :estimated_hours, (h.is_a?(String) ? h.to_hours : h)
168 write_attribute :estimated_hours, (h.is_a?(String) ? h.to_hours : h)
167 end
169 end
168
170
169 SAFE_ATTRIBUTES = %w(
171 SAFE_ATTRIBUTES = %w(
170 tracker_id
172 tracker_id
171 status_id
173 status_id
172 category_id
174 category_id
173 assigned_to_id
175 assigned_to_id
174 priority_id
176 priority_id
175 fixed_version_id
177 fixed_version_id
176 subject
178 subject
177 description
179 description
178 start_date
180 start_date
179 due_date
181 due_date
180 done_ratio
182 done_ratio
181 estimated_hours
183 estimated_hours
182 custom_field_values
184 custom_field_values
183 ) unless const_defined?(:SAFE_ATTRIBUTES)
185 ) unless const_defined?(:SAFE_ATTRIBUTES)
184
186
185 # Safely sets attributes
187 # Safely sets attributes
186 # Should be called from controllers instead of #attributes=
188 # Should be called from controllers instead of #attributes=
187 # attr_accessible is too rough because we still want things like
189 # attr_accessible is too rough because we still want things like
188 # Issue.new(:project => foo) to work
190 # Issue.new(:project => foo) to work
189 # TODO: move workflow/permission checks from controllers to here
191 # TODO: move workflow/permission checks from controllers to here
190 def safe_attributes=(attrs, user=User.current)
192 def safe_attributes=(attrs, user=User.current)
191 return if attrs.nil?
193 return if attrs.nil?
192 attrs = attrs.reject {|k,v| !SAFE_ATTRIBUTES.include?(k)}
194 attrs = attrs.reject {|k,v| !SAFE_ATTRIBUTES.include?(k)}
193 if attrs['status_id']
195 if attrs['status_id']
194 unless new_statuses_allowed_to(user).collect(&:id).include?(attrs['status_id'].to_i)
196 unless new_statuses_allowed_to(user).collect(&:id).include?(attrs['status_id'].to_i)
195 attrs.delete('status_id')
197 attrs.delete('status_id')
196 end
198 end
197 end
199 end
198 self.attributes = attrs
200 self.attributes = attrs
199 end
201 end
200
202
201 def done_ratio
203 def done_ratio
202 if Issue.use_status_for_done_ratio? && status && status.default_done_ratio?
204 if Issue.use_status_for_done_ratio? && status && status.default_done_ratio?
203 status.default_done_ratio
205 status.default_done_ratio
204 else
206 else
205 read_attribute(:done_ratio)
207 read_attribute(:done_ratio)
206 end
208 end
207 end
209 end
208
210
209 def self.use_status_for_done_ratio?
211 def self.use_status_for_done_ratio?
210 Setting.issue_done_ratio == 'issue_status'
212 Setting.issue_done_ratio == 'issue_status'
211 end
213 end
212
214
213 def self.use_field_for_done_ratio?
215 def self.use_field_for_done_ratio?
214 Setting.issue_done_ratio == 'issue_field'
216 Setting.issue_done_ratio == 'issue_field'
215 end
217 end
216
218
217 def validate
219 def validate
218 if self.due_date.nil? && @attributes['due_date'] && !@attributes['due_date'].empty?
220 if self.due_date.nil? && @attributes['due_date'] && !@attributes['due_date'].empty?
219 errors.add :due_date, :not_a_date
221 errors.add :due_date, :not_a_date
220 end
222 end
221
223
222 if self.due_date and self.start_date and self.due_date < self.start_date
224 if self.due_date and self.start_date and self.due_date < self.start_date
223 errors.add :due_date, :greater_than_start_date
225 errors.add :due_date, :greater_than_start_date
224 end
226 end
225
227
226 if start_date && soonest_start && start_date < soonest_start
228 if start_date && soonest_start && start_date < soonest_start
227 errors.add :start_date, :invalid
229 errors.add :start_date, :invalid
228 end
230 end
229
231
230 if fixed_version
232 if fixed_version
231 if !assignable_versions.include?(fixed_version)
233 if !assignable_versions.include?(fixed_version)
232 errors.add :fixed_version_id, :inclusion
234 errors.add :fixed_version_id, :inclusion
233 elsif reopened? && fixed_version.closed?
235 elsif reopened? && fixed_version.closed?
234 errors.add_to_base I18n.t(:error_can_not_reopen_issue_on_closed_version)
236 errors.add_to_base I18n.t(:error_can_not_reopen_issue_on_closed_version)
235 end
237 end
236 end
238 end
237
239
238 # Checks that the issue can not be added/moved to a disabled tracker
240 # Checks that the issue can not be added/moved to a disabled tracker
239 if project && (tracker_id_changed? || project_id_changed?)
241 if project && (tracker_id_changed? || project_id_changed?)
240 unless project.trackers.include?(tracker)
242 unless project.trackers.include?(tracker)
241 errors.add :tracker_id, :inclusion
243 errors.add :tracker_id, :inclusion
242 end
244 end
243 end
245 end
244 end
246 end
245
247
246 # Set the done_ratio using the status if that setting is set. This will keep the done_ratios
248 # Set the done_ratio using the status if that setting is set. This will keep the done_ratios
247 # even if the user turns off the setting later
249 # even if the user turns off the setting later
248 def update_done_ratio_from_issue_status
250 def update_done_ratio_from_issue_status
249 if Issue.use_status_for_done_ratio? && status && status.default_done_ratio?
251 if Issue.use_status_for_done_ratio? && status && status.default_done_ratio?
250 self.done_ratio = status.default_done_ratio
252 self.done_ratio = status.default_done_ratio
251 end
253 end
252 end
254 end
253
255
254 def init_journal(user, notes = "")
256 def init_journal(user, notes = "")
255 @current_journal ||= Journal.new(:journalized => self, :user => user, :notes => notes)
257 @current_journal ||= Journal.new(:journalized => self, :user => user, :notes => notes)
256 @issue_before_change = self.clone
258 @issue_before_change = self.clone
257 @issue_before_change.status = self.status
259 @issue_before_change.status = self.status
258 @custom_values_before_change = {}
260 @custom_values_before_change = {}
259 self.custom_values.each {|c| @custom_values_before_change.store c.custom_field_id, c.value }
261 self.custom_values.each {|c| @custom_values_before_change.store c.custom_field_id, c.value }
260 # Make sure updated_on is updated when adding a note.
262 # Make sure updated_on is updated when adding a note.
261 updated_on_will_change!
263 updated_on_will_change!
262 @current_journal
264 @current_journal
263 end
265 end
264
266
265 # Return true if the issue is closed, otherwise false
267 # Return true if the issue is closed, otherwise false
266 def closed?
268 def closed?
267 self.status.is_closed?
269 self.status.is_closed?
268 end
270 end
269
271
270 # Return true if the issue is being reopened
272 # Return true if the issue is being reopened
271 def reopened?
273 def reopened?
272 if !new_record? && status_id_changed?
274 if !new_record? && status_id_changed?
273 status_was = IssueStatus.find_by_id(status_id_was)
275 status_was = IssueStatus.find_by_id(status_id_was)
274 status_new = IssueStatus.find_by_id(status_id)
276 status_new = IssueStatus.find_by_id(status_id)
275 if status_was && status_new && status_was.is_closed? && !status_new.is_closed?
277 if status_was && status_new && status_was.is_closed? && !status_new.is_closed?
276 return true
278 return true
277 end
279 end
278 end
280 end
279 false
281 false
280 end
282 end
281
283
282 # Return true if the issue is being closed
284 # Return true if the issue is being closed
283 def closing?
285 def closing?
284 if !new_record? && status_id_changed?
286 if !new_record? && status_id_changed?
285 status_was = IssueStatus.find_by_id(status_id_was)
287 status_was = IssueStatus.find_by_id(status_id_was)
286 status_new = IssueStatus.find_by_id(status_id)
288 status_new = IssueStatus.find_by_id(status_id)
287 if status_was && status_new && !status_was.is_closed? && status_new.is_closed?
289 if status_was && status_new && !status_was.is_closed? && status_new.is_closed?
288 return true
290 return true
289 end
291 end
290 end
292 end
291 false
293 false
292 end
294 end
293
295
294 # Returns true if the issue is overdue
296 # Returns true if the issue is overdue
295 def overdue?
297 def overdue?
296 !due_date.nil? && (due_date < Date.today) && !status.is_closed?
298 !due_date.nil? && (due_date < Date.today) && !status.is_closed?
297 end
299 end
298
300
299 # Users the issue can be assigned to
301 # Users the issue can be assigned to
300 def assignable_users
302 def assignable_users
301 project.assignable_users
303 project.assignable_users
302 end
304 end
303
305
304 # Versions that the issue can be assigned to
306 # Versions that the issue can be assigned to
305 def assignable_versions
307 def assignable_versions
306 @assignable_versions ||= (project.shared_versions.open + [Version.find_by_id(fixed_version_id_was)]).compact.uniq.sort
308 @assignable_versions ||= (project.shared_versions.open + [Version.find_by_id(fixed_version_id_was)]).compact.uniq.sort
307 end
309 end
308
310
309 # Returns true if this issue is blocked by another issue that is still open
311 # Returns true if this issue is blocked by another issue that is still open
310 def blocked?
312 def blocked?
311 !relations_to.detect {|ir| ir.relation_type == 'blocks' && !ir.issue_from.closed?}.nil?
313 !relations_to.detect {|ir| ir.relation_type == 'blocks' && !ir.issue_from.closed?}.nil?
312 end
314 end
313
315
314 # Returns an array of status that user is able to apply
316 # Returns an array of status that user is able to apply
315 def new_statuses_allowed_to(user, include_default=false)
317 def new_statuses_allowed_to(user, include_default=false)
316 statuses = status.find_new_statuses_allowed_to(user.roles_for_project(project), tracker)
318 statuses = status.find_new_statuses_allowed_to(user.roles_for_project(project), tracker)
317 statuses << status unless statuses.empty?
319 statuses << status unless statuses.empty?
318 statuses << IssueStatus.default if include_default
320 statuses << IssueStatus.default if include_default
319 statuses = statuses.uniq.sort
321 statuses = statuses.uniq.sort
320 blocked? ? statuses.reject {|s| s.is_closed?} : statuses
322 blocked? ? statuses.reject {|s| s.is_closed?} : statuses
321 end
323 end
322
324
323 # Returns the mail adresses of users that should be notified
325 # Returns the mail adresses of users that should be notified
324 def recipients
326 def recipients
325 notified = project.notified_users
327 notified = project.notified_users
326 # Author and assignee are always notified unless they have been locked
328 # Author and assignee are always notified unless they have been locked
327 notified << author if author && author.active?
329 notified << author if author && author.active?
328 notified << assigned_to if assigned_to && assigned_to.active?
330 notified << assigned_to if assigned_to && assigned_to.active?
329 notified.uniq!
331 notified.uniq!
330 # Remove users that can not view the issue
332 # Remove users that can not view the issue
331 notified.reject! {|user| !visible?(user)}
333 notified.reject! {|user| !visible?(user)}
332 notified.collect(&:mail)
334 notified.collect(&:mail)
333 end
335 end
334
336
335 # Returns the total number of hours spent on this issue.
337 # Returns the total number of hours spent on this issue.
336 #
338 #
337 # Example:
339 # Example:
338 # spent_hours => 0
340 # spent_hours => 0
339 # spent_hours => 50
341 # spent_hours => 50
340 def spent_hours
342 def spent_hours
341 @spent_hours ||= time_entries.sum(:hours) || 0
343 @spent_hours ||= time_entries.sum(:hours) || 0
342 end
344 end
343
345
344 def relations
346 def relations
345 (relations_from + relations_to).sort
347 (relations_from + relations_to).sort
346 end
348 end
347
349
348 def all_dependent_issues
350 def all_dependent_issues
349 dependencies = []
351 dependencies = []
350 relations_from.each do |relation|
352 relations_from.each do |relation|
351 dependencies << relation.issue_to
353 dependencies << relation.issue_to
352 dependencies += relation.issue_to.all_dependent_issues
354 dependencies += relation.issue_to.all_dependent_issues
353 end
355 end
354 dependencies
356 dependencies
355 end
357 end
356
358
357 # Returns an array of issues that duplicate this one
359 # Returns an array of issues that duplicate this one
358 def duplicates
360 def duplicates
359 relations_to.select {|r| r.relation_type == IssueRelation::TYPE_DUPLICATES}.collect {|r| r.issue_from}
361 relations_to.select {|r| r.relation_type == IssueRelation::TYPE_DUPLICATES}.collect {|r| r.issue_from}
360 end
362 end
361
363
362 # Returns the due date or the target due date if any
364 # Returns the due date or the target due date if any
363 # Used on gantt chart
365 # Used on gantt chart
364 def due_before
366 def due_before
365 due_date || (fixed_version ? fixed_version.effective_date : nil)
367 due_date || (fixed_version ? fixed_version.effective_date : nil)
366 end
368 end
367
369
368 # Returns the time scheduled for this issue.
370 # Returns the time scheduled for this issue.
369 #
371 #
370 # Example:
372 # Example:
371 # Start Date: 2/26/09, End Date: 3/04/09
373 # Start Date: 2/26/09, End Date: 3/04/09
372 # duration => 6
374 # duration => 6
373 def duration
375 def duration
374 (start_date && due_date) ? due_date - start_date : 0
376 (start_date && due_date) ? due_date - start_date : 0
375 end
377 end
376
378
377 def soonest_start
379 def soonest_start
378 @soonest_start ||= relations_to.collect{|relation| relation.successor_soonest_start}.compact.min
380 @soonest_start ||= relations_to.collect{|relation| relation.successor_soonest_start}.compact.min
379 end
381 end
380
382
381 def to_s
383 def to_s
382 "#{tracker} ##{id}: #{subject}"
384 "#{tracker} ##{id}: #{subject}"
383 end
385 end
384
386
385 # Returns a string of css classes that apply to the issue
387 # Returns a string of css classes that apply to the issue
386 def css_classes
388 def css_classes
387 s = "issue status-#{status.position} priority-#{priority.position}"
389 s = "issue status-#{status.position} priority-#{priority.position}"
388 s << ' closed' if closed?
390 s << ' closed' if closed?
389 s << ' overdue' if overdue?
391 s << ' overdue' if overdue?
390 s << ' created-by-me' if User.current.logged? && author_id == User.current.id
392 s << ' created-by-me' if User.current.logged? && author_id == User.current.id
391 s << ' assigned-to-me' if User.current.logged? && assigned_to_id == User.current.id
393 s << ' assigned-to-me' if User.current.logged? && assigned_to_id == User.current.id
392 s
394 s
393 end
395 end
394
396
395 # Unassigns issues from +version+ if it's no longer shared with issue's project
397 # Unassigns issues from +version+ if it's no longer shared with issue's project
396 def self.update_versions_from_sharing_change(version)
398 def self.update_versions_from_sharing_change(version)
397 # Update issues assigned to the version
399 # Update issues assigned to the version
398 update_versions(["#{Issue.table_name}.fixed_version_id = ?", version.id])
400 update_versions(["#{Issue.table_name}.fixed_version_id = ?", version.id])
399 end
401 end
400
402
401 # Unassigns issues from versions that are no longer shared
403 # Unassigns issues from versions that are no longer shared
402 # after +project+ was moved
404 # after +project+ was moved
403 def self.update_versions_from_hierarchy_change(project)
405 def self.update_versions_from_hierarchy_change(project)
404 moved_project_ids = project.self_and_descendants.reload.collect(&:id)
406 moved_project_ids = project.self_and_descendants.reload.collect(&:id)
405 # Update issues of the moved projects and issues assigned to a version of a moved project
407 # Update issues of the moved projects and issues assigned to a version of a moved project
406 Issue.update_versions(["#{Version.table_name}.project_id IN (?) OR #{Issue.table_name}.project_id IN (?)", moved_project_ids, moved_project_ids])
408 Issue.update_versions(["#{Version.table_name}.project_id IN (?) OR #{Issue.table_name}.project_id IN (?)", moved_project_ids, moved_project_ids])
407 end
409 end
408
410
409 # Extracted from the ReportsController.
411 # Extracted from the ReportsController.
410 def self.by_tracker(project)
412 def self.by_tracker(project)
411 count_and_group_by(:project => project,
413 count_and_group_by(:project => project,
412 :field => 'tracker_id',
414 :field => 'tracker_id',
413 :joins => Tracker.table_name)
415 :joins => Tracker.table_name)
414 end
416 end
415
417
416 def self.by_version(project)
418 def self.by_version(project)
417 count_and_group_by(:project => project,
419 count_and_group_by(:project => project,
418 :field => 'fixed_version_id',
420 :field => 'fixed_version_id',
419 :joins => Version.table_name)
421 :joins => Version.table_name)
420 end
422 end
421
423
422 def self.by_priority(project)
424 def self.by_priority(project)
423 count_and_group_by(:project => project,
425 count_and_group_by(:project => project,
424 :field => 'priority_id',
426 :field => 'priority_id',
425 :joins => IssuePriority.table_name)
427 :joins => IssuePriority.table_name)
426 end
428 end
427
429
428 def self.by_category(project)
430 def self.by_category(project)
429 count_and_group_by(:project => project,
431 count_and_group_by(:project => project,
430 :field => 'category_id',
432 :field => 'category_id',
431 :joins => IssueCategory.table_name)
433 :joins => IssueCategory.table_name)
432 end
434 end
433
435
434 def self.by_assigned_to(project)
436 def self.by_assigned_to(project)
435 count_and_group_by(:project => project,
437 count_and_group_by(:project => project,
436 :field => 'assigned_to_id',
438 :field => 'assigned_to_id',
437 :joins => User.table_name)
439 :joins => User.table_name)
438 end
440 end
439
441
440 def self.by_author(project)
442 def self.by_author(project)
441 count_and_group_by(:project => project,
443 count_and_group_by(:project => project,
442 :field => 'author_id',
444 :field => 'author_id',
443 :joins => User.table_name)
445 :joins => User.table_name)
444 end
446 end
445
447
446 def self.by_subproject(project)
448 def self.by_subproject(project)
447 ActiveRecord::Base.connection.select_all("select s.id as status_id,
449 ActiveRecord::Base.connection.select_all("select s.id as status_id,
448 s.is_closed as closed,
450 s.is_closed as closed,
449 i.project_id as project_id,
451 i.project_id as project_id,
450 count(i.id) as total
452 count(i.id) as total
451 from
453 from
452 #{Issue.table_name} i, #{IssueStatus.table_name} s
454 #{Issue.table_name} i, #{IssueStatus.table_name} s
453 where
455 where
454 i.status_id=s.id
456 i.status_id=s.id
455 and i.project_id IN (#{project.descendants.active.collect{|p| p.id}.join(',')})
457 and i.project_id IN (#{project.descendants.active.collect{|p| p.id}.join(',')})
456 group by s.id, s.is_closed, i.project_id") if project.descendants.active.any?
458 group by s.id, s.is_closed, i.project_id") if project.descendants.active.any?
457 end
459 end
458 # End ReportsController extraction
460 # End ReportsController extraction
459
461
460 private
462 private
461
463
462 # Update issues so their versions are not pointing to a
464 # Update issues so their versions are not pointing to a
463 # fixed_version that is not shared with the issue's project
465 # fixed_version that is not shared with the issue's project
464 def self.update_versions(conditions=nil)
466 def self.update_versions(conditions=nil)
465 # Only need to update issues with a fixed_version from
467 # Only need to update issues with a fixed_version from
466 # a different project and that is not systemwide shared
468 # a different project and that is not systemwide shared
467 Issue.all(:conditions => merge_conditions("#{Issue.table_name}.fixed_version_id IS NOT NULL" +
469 Issue.all(:conditions => merge_conditions("#{Issue.table_name}.fixed_version_id IS NOT NULL" +
468 " AND #{Issue.table_name}.project_id <> #{Version.table_name}.project_id" +
470 " AND #{Issue.table_name}.project_id <> #{Version.table_name}.project_id" +
469 " AND #{Version.table_name}.sharing <> 'system'",
471 " AND #{Version.table_name}.sharing <> 'system'",
470 conditions),
472 conditions),
471 :include => [:project, :fixed_version]
473 :include => [:project, :fixed_version]
472 ).each do |issue|
474 ).each do |issue|
473 next if issue.project.nil? || issue.fixed_version.nil?
475 next if issue.project.nil? || issue.fixed_version.nil?
474 unless issue.project.shared_versions.include?(issue.fixed_version)
476 unless issue.project.shared_versions.include?(issue.fixed_version)
475 issue.init_journal(User.current)
477 issue.init_journal(User.current)
476 issue.fixed_version = nil
478 issue.fixed_version = nil
477 issue.save
479 issue.save
478 end
480 end
479 end
481 end
480 end
482 end
481
483
482 # Callback on attachment deletion
484 # Callback on attachment deletion
483 def attachment_removed(obj)
485 def attachment_removed(obj)
484 journal = init_journal(User.current)
486 journal = init_journal(User.current)
485 journal.details << JournalDetail.new(:property => 'attachment',
487 journal.details << JournalDetail.new(:property => 'attachment',
486 :prop_key => obj.id,
488 :prop_key => obj.id,
487 :old_value => obj.filename)
489 :old_value => obj.filename)
488 journal.save
490 journal.save
489 end
491 end
490
492
491 # Default assignment based on category
493 # Default assignment based on category
492 def default_assign
494 def default_assign
493 if assigned_to.nil? && category && category.assigned_to
495 if assigned_to.nil? && category && category.assigned_to
494 self.assigned_to = category.assigned_to
496 self.assigned_to = category.assigned_to
495 end
497 end
496 end
498 end
497
499
498 # Updates start/due dates of following issues
500 # Updates start/due dates of following issues
499 def reschedule_following_issues
501 def reschedule_following_issues
500 if start_date_changed? || due_date_changed?
502 if start_date_changed? || due_date_changed?
501 relations_from.each do |relation|
503 relations_from.each do |relation|
502 relation.set_issue_to_dates
504 relation.set_issue_to_dates
503 end
505 end
504 end
506 end
505 end
507 end
506
508
507 # Closes duplicates if the issue is being closed
509 # Closes duplicates if the issue is being closed
508 def close_duplicates
510 def close_duplicates
509 if closing?
511 if closing?
510 duplicates.each do |duplicate|
512 duplicates.each do |duplicate|
511 # Reload is need in case the duplicate was updated by a previous duplicate
513 # Reload is need in case the duplicate was updated by a previous duplicate
512 duplicate.reload
514 duplicate.reload
513 # Don't re-close it if it's already closed
515 # Don't re-close it if it's already closed
514 next if duplicate.closed?
516 next if duplicate.closed?
515 # Same user and notes
517 # Same user and notes
516 if @current_journal
518 if @current_journal
517 duplicate.init_journal(@current_journal.user, @current_journal.notes)
519 duplicate.init_journal(@current_journal.user, @current_journal.notes)
518 end
520 end
519 duplicate.update_attribute :status, self.status
521 duplicate.update_attribute :status, self.status
520 end
522 end
521 end
523 end
522 end
524 end
523
525
524 # Saves the changes in a Journal
526 # Saves the changes in a Journal
525 # Called after_save
527 # Called after_save
526 def create_journal
528 def create_journal
527 if @current_journal
529 if @current_journal
528 # attributes changes
530 # attributes changes
529 (Issue.column_names - %w(id description lock_version created_on updated_on)).each {|c|
531 (Issue.column_names - %w(id description lock_version created_on updated_on)).each {|c|
530 @current_journal.details << JournalDetail.new(:property => 'attr',
532 @current_journal.details << JournalDetail.new(:property => 'attr',
531 :prop_key => c,
533 :prop_key => c,
532 :old_value => @issue_before_change.send(c),
534 :old_value => @issue_before_change.send(c),
533 :value => send(c)) unless send(c)==@issue_before_change.send(c)
535 :value => send(c)) unless send(c)==@issue_before_change.send(c)
534 }
536 }
535 # custom fields changes
537 # custom fields changes
536 custom_values.each {|c|
538 custom_values.each {|c|
537 next if (@custom_values_before_change[c.custom_field_id]==c.value ||
539 next if (@custom_values_before_change[c.custom_field_id]==c.value ||
538 (@custom_values_before_change[c.custom_field_id].blank? && c.value.blank?))
540 (@custom_values_before_change[c.custom_field_id].blank? && c.value.blank?))
539 @current_journal.details << JournalDetail.new(:property => 'cf',
541 @current_journal.details << JournalDetail.new(:property => 'cf',
540 :prop_key => c.custom_field_id,
542 :prop_key => c.custom_field_id,
541 :old_value => @custom_values_before_change[c.custom_field_id],
543 :old_value => @custom_values_before_change[c.custom_field_id],
542 :value => c.value)
544 :value => c.value)
543 }
545 }
544 @current_journal.save
546 @current_journal.save
545 # reset current journal
547 # reset current journal
546 init_journal @current_journal.user, @current_journal.notes
548 init_journal @current_journal.user, @current_journal.notes
547 end
549 end
548 end
550 end
549
551
550 # Query generator for selecting groups of issue counts for a project
552 # Query generator for selecting groups of issue counts for a project
551 # based on specific criteria
553 # based on specific criteria
552 #
554 #
553 # Options
555 # Options
554 # * project - Project to search in.
556 # * project - Project to search in.
555 # * field - String. Issue field to key off of in the grouping.
557 # * field - String. Issue field to key off of in the grouping.
556 # * joins - String. The table name to join against.
558 # * joins - String. The table name to join against.
557 def self.count_and_group_by(options)
559 def self.count_and_group_by(options)
558 project = options.delete(:project)
560 project = options.delete(:project)
559 select_field = options.delete(:field)
561 select_field = options.delete(:field)
560 joins = options.delete(:joins)
562 joins = options.delete(:joins)
561
563
562 where = "i.#{select_field}=j.id"
564 where = "i.#{select_field}=j.id"
563
565
564 ActiveRecord::Base.connection.select_all("select s.id as status_id,
566 ActiveRecord::Base.connection.select_all("select s.id as status_id,
565 s.is_closed as closed,
567 s.is_closed as closed,
566 j.id as #{select_field},
568 j.id as #{select_field},
567 count(i.id) as total
569 count(i.id) as total
568 from
570 from
569 #{Issue.table_name} i, #{IssueStatus.table_name} s, #{joins} as j
571 #{Issue.table_name} i, #{IssueStatus.table_name} s, #{joins} as j
570 where
572 where
571 i.status_id=s.id
573 i.status_id=s.id
572 and #{where}
574 and #{where}
573 and i.project_id=#{project.id}
575 and i.project_id=#{project.id}
574 group by s.id, s.is_closed, j.id")
576 group by s.id, s.is_closed, j.id")
575 end
577 end
576
578
577
579
578 end
580 end
General Comments 0
You need to be logged in to leave comments. Login now