##// END OF EJS Templates
Fixed MissingFeatureException: let user choose to copy attachments or not when bulk copying issues....
Jean-Philippe Lang -
r9271:231282ddcb73
parent child
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -1,439 +1,442
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2011 Jean-Philippe Lang
2 # Copyright (C) 2006-2011 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, :create]
19 menu_item :new_issue, :only => [:new, :create]
20 default_search_scope :issues
20 default_search_scope :issues
21
21
22 before_filter :find_issue, :only => [:show, :edit, :update]
22 before_filter :find_issue, :only => [:show, :edit, :update]
23 before_filter :find_issues, :only => [:bulk_edit, :bulk_update, :destroy]
23 before_filter :find_issues, :only => [:bulk_edit, :bulk_update, :destroy]
24 before_filter :find_project, :only => [:new, :create]
24 before_filter :find_project, :only => [:new, :create]
25 before_filter :authorize, :except => [:index]
25 before_filter :authorize, :except => [:index]
26 before_filter :find_optional_project, :only => [:index]
26 before_filter :find_optional_project, :only => [:index]
27 before_filter :check_for_default_issue_status, :only => [:new, :create]
27 before_filter :check_for_default_issue_status, :only => [:new, :create]
28 before_filter :build_new_issue_from_params, :only => [:new, :create]
28 before_filter :build_new_issue_from_params, :only => [:new, :create]
29 accept_rss_auth :index, :show
29 accept_rss_auth :index, :show
30 accept_api_auth :index, :show, :create, :update, :destroy
30 accept_api_auth :index, :show, :create, :update, :destroy
31
31
32 rescue_from Query::StatementInvalid, :with => :query_statement_invalid
32 rescue_from Query::StatementInvalid, :with => :query_statement_invalid
33
33
34 helper :journals
34 helper :journals
35 helper :projects
35 helper :projects
36 include ProjectsHelper
36 include ProjectsHelper
37 helper :custom_fields
37 helper :custom_fields
38 include CustomFieldsHelper
38 include CustomFieldsHelper
39 helper :issue_relations
39 helper :issue_relations
40 include IssueRelationsHelper
40 include IssueRelationsHelper
41 helper :watchers
41 helper :watchers
42 include WatchersHelper
42 include WatchersHelper
43 helper :attachments
43 helper :attachments
44 include AttachmentsHelper
44 include AttachmentsHelper
45 helper :queries
45 helper :queries
46 include QueriesHelper
46 include QueriesHelper
47 helper :repositories
47 helper :repositories
48 include RepositoriesHelper
48 include RepositoriesHelper
49 helper :sort
49 helper :sort
50 include SortHelper
50 include SortHelper
51 include IssuesHelper
51 include IssuesHelper
52 helper :timelog
52 helper :timelog
53 helper :gantt
53 helper :gantt
54 include Redmine::Export::PDF
54 include Redmine::Export::PDF
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(@query.sortable_columns)
59 sort_update(@query.sortable_columns)
60
60
61 if @query.valid?
61 if @query.valid?
62 case params[:format]
62 case params[:format]
63 when 'csv', 'pdf'
63 when 'csv', 'pdf'
64 @limit = Setting.issues_export_limit.to_i
64 @limit = Setting.issues_export_limit.to_i
65 when 'atom'
65 when 'atom'
66 @limit = Setting.feeds_limit.to_i
66 @limit = Setting.feeds_limit.to_i
67 when 'xml', 'json'
67 when 'xml', 'json'
68 @offset, @limit = api_offset_and_limit
68 @offset, @limit = api_offset_and_limit
69 else
69 else
70 @limit = per_page_option
70 @limit = per_page_option
71 end
71 end
72
72
73 @issue_count = @query.issue_count
73 @issue_count = @query.issue_count
74 @issue_pages = Paginator.new self, @issue_count, @limit, params['page']
74 @issue_pages = Paginator.new self, @issue_count, @limit, params['page']
75 @offset ||= @issue_pages.current.offset
75 @offset ||= @issue_pages.current.offset
76 @issues = @query.issues(:include => [:assigned_to, :tracker, :priority, :category, :fixed_version],
76 @issues = @query.issues(:include => [:assigned_to, :tracker, :priority, :category, :fixed_version],
77 :order => sort_clause,
77 :order => sort_clause,
78 :offset => @offset,
78 :offset => @offset,
79 :limit => @limit)
79 :limit => @limit)
80 @issue_count_by_group = @query.issue_count_by_group
80 @issue_count_by_group = @query.issue_count_by_group
81
81
82 respond_to do |format|
82 respond_to do |format|
83 format.html { render :template => 'issues/index', :layout => !request.xhr? }
83 format.html { render :template => 'issues/index', :layout => !request.xhr? }
84 format.api {
84 format.api {
85 Issue.load_relations(@issues) if include_in_api_response?('relations')
85 Issue.load_relations(@issues) if include_in_api_response?('relations')
86 }
86 }
87 format.atom { render_feed(@issues, :title => "#{@project || Setting.app_title}: #{l(:label_issue_plural)}") }
87 format.atom { render_feed(@issues, :title => "#{@project || Setting.app_title}: #{l(:label_issue_plural)}") }
88 format.csv { send_data(issues_to_csv(@issues, @project, @query, params), :type => 'text/csv; header=present', :filename => 'export.csv') }
88 format.csv { send_data(issues_to_csv(@issues, @project, @query, params), :type => 'text/csv; header=present', :filename => 'export.csv') }
89 format.pdf { send_data(issues_to_pdf(@issues, @project, @query), :type => 'application/pdf', :filename => 'export.pdf') }
89 format.pdf { send_data(issues_to_pdf(@issues, @project, @query), :type => 'application/pdf', :filename => 'export.pdf') }
90 end
90 end
91 else
91 else
92 respond_to do |format|
92 respond_to do |format|
93 format.html { render(:template => 'issues/index', :layout => !request.xhr?) }
93 format.html { render(:template => 'issues/index', :layout => !request.xhr?) }
94 format.any(:atom, :csv, :pdf) { render(:nothing => true) }
94 format.any(:atom, :csv, :pdf) { render(:nothing => true) }
95 format.api { render_validation_errors(@query) }
95 format.api { render_validation_errors(@query) }
96 end
96 end
97 end
97 end
98 rescue ActiveRecord::RecordNotFound
98 rescue ActiveRecord::RecordNotFound
99 render_404
99 render_404
100 end
100 end
101
101
102 def show
102 def show
103 @journals = @issue.journals.find(:all, :include => [:user, :details], :order => "#{Journal.table_name}.created_on ASC")
103 @journals = @issue.journals.find(:all, :include => [:user, :details], :order => "#{Journal.table_name}.created_on ASC")
104 @journals.each_with_index {|j,i| j.indice = i+1}
104 @journals.each_with_index {|j,i| j.indice = i+1}
105 @journals.reverse! if User.current.wants_comments_in_reverse_order?
105 @journals.reverse! if User.current.wants_comments_in_reverse_order?
106
106
107 @changesets = @issue.changesets.visible.all
107 @changesets = @issue.changesets.visible.all
108 @changesets.reverse! if User.current.wants_comments_in_reverse_order?
108 @changesets.reverse! if User.current.wants_comments_in_reverse_order?
109
109
110 @relations = @issue.relations.select {|r| r.other_issue(@issue) && r.other_issue(@issue).visible? }
110 @relations = @issue.relations.select {|r| r.other_issue(@issue) && r.other_issue(@issue).visible? }
111 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
111 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
112 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
112 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
113 @priorities = IssuePriority.active
113 @priorities = IssuePriority.active
114 @time_entry = TimeEntry.new(:issue => @issue, :project => @issue.project)
114 @time_entry = TimeEntry.new(:issue => @issue, :project => @issue.project)
115 respond_to do |format|
115 respond_to do |format|
116 format.html {
116 format.html {
117 retrieve_previous_and_next_issue_ids
117 retrieve_previous_and_next_issue_ids
118 render :template => 'issues/show'
118 render :template => 'issues/show'
119 }
119 }
120 format.api
120 format.api
121 format.atom { render :template => 'journals/index', :layout => false, :content_type => 'application/atom+xml' }
121 format.atom { render :template => 'journals/index', :layout => false, :content_type => 'application/atom+xml' }
122 format.pdf { send_data(issue_to_pdf(@issue), :type => 'application/pdf', :filename => "#{@project.identifier}-#{@issue.id}.pdf") }
122 format.pdf { send_data(issue_to_pdf(@issue), :type => 'application/pdf', :filename => "#{@project.identifier}-#{@issue.id}.pdf") }
123 end
123 end
124 end
124 end
125
125
126 # Add a new issue
126 # Add a new issue
127 # The new issue will be created from an existing one if copy_from parameter is given
127 # The new issue will be created from an existing one if copy_from parameter is given
128 def new
128 def new
129 respond_to do |format|
129 respond_to do |format|
130 format.html { render :action => 'new', :layout => !request.xhr? }
130 format.html { render :action => 'new', :layout => !request.xhr? }
131 format.js {
131 format.js {
132 render(:update) { |page|
132 render(:update) { |page|
133 if params[:project_change]
133 if params[:project_change]
134 page.replace_html 'all_attributes', :partial => 'form'
134 page.replace_html 'all_attributes', :partial => 'form'
135 else
135 else
136 page.replace_html 'attributes', :partial => 'attributes'
136 page.replace_html 'attributes', :partial => 'attributes'
137 end
137 end
138 m = User.current.allowed_to?(:log_time, @issue.project) ? 'show' : 'hide'
138 m = User.current.allowed_to?(:log_time, @issue.project) ? 'show' : 'hide'
139 page << "if ($('log_time')) {Element.#{m}('log_time');}"
139 page << "if ($('log_time')) {Element.#{m}('log_time');}"
140 }
140 }
141 }
141 }
142 end
142 end
143 end
143 end
144
144
145 def create
145 def create
146 call_hook(:controller_issues_new_before_save, { :params => params, :issue => @issue })
146 call_hook(:controller_issues_new_before_save, { :params => params, :issue => @issue })
147 @issue.save_attachments(params[:attachments] || (params[:issue] && params[:issue][:uploads]))
147 @issue.save_attachments(params[:attachments] || (params[:issue] && params[:issue][:uploads]))
148 if @issue.save
148 if @issue.save
149 call_hook(:controller_issues_new_after_save, { :params => params, :issue => @issue})
149 call_hook(:controller_issues_new_after_save, { :params => params, :issue => @issue})
150 respond_to do |format|
150 respond_to do |format|
151 format.html {
151 format.html {
152 render_attachment_warning_if_needed(@issue)
152 render_attachment_warning_if_needed(@issue)
153 flash[:notice] = l(:notice_issue_successful_create, :id => "<a href='#{issue_path(@issue)}'>##{@issue.id}</a>")
153 flash[:notice] = l(:notice_issue_successful_create, :id => "<a href='#{issue_path(@issue)}'>##{@issue.id}</a>")
154 redirect_to(params[:continue] ? { :action => 'new', :project_id => @issue.project, :issue => {:tracker_id => @issue.tracker, :parent_issue_id => @issue.parent_issue_id}.reject {|k,v| v.nil?} } :
154 redirect_to(params[:continue] ? { :action => 'new', :project_id => @issue.project, :issue => {:tracker_id => @issue.tracker, :parent_issue_id => @issue.parent_issue_id}.reject {|k,v| v.nil?} } :
155 { :action => 'show', :id => @issue })
155 { :action => 'show', :id => @issue })
156 }
156 }
157 format.api { render :action => 'show', :status => :created, :location => issue_url(@issue) }
157 format.api { render :action => 'show', :status => :created, :location => issue_url(@issue) }
158 end
158 end
159 return
159 return
160 else
160 else
161 respond_to do |format|
161 respond_to do |format|
162 format.html { render :action => 'new' }
162 format.html { render :action => 'new' }
163 format.api { render_validation_errors(@issue) }
163 format.api { render_validation_errors(@issue) }
164 end
164 end
165 end
165 end
166 end
166 end
167
167
168 def edit
168 def edit
169 return unless update_issue_from_params
169 return unless update_issue_from_params
170
170
171 respond_to do |format|
171 respond_to do |format|
172 format.html { }
172 format.html { }
173 format.xml { }
173 format.xml { }
174 end
174 end
175 end
175 end
176
176
177 def update
177 def update
178 return unless update_issue_from_params
178 return unless update_issue_from_params
179 @issue.save_attachments(params[:attachments] || (params[:issue] && params[:issue][:uploads]))
179 @issue.save_attachments(params[:attachments] || (params[:issue] && params[:issue][:uploads]))
180 saved = false
180 saved = false
181 begin
181 begin
182 saved = @issue.save_issue_with_child_records(params, @time_entry)
182 saved = @issue.save_issue_with_child_records(params, @time_entry)
183 rescue ActiveRecord::StaleObjectError
183 rescue ActiveRecord::StaleObjectError
184 @conflict = true
184 @conflict = true
185 if params[:last_journal_id]
185 if params[:last_journal_id]
186 if params[:last_journal_id].present?
186 if params[:last_journal_id].present?
187 last_journal_id = params[:last_journal_id].to_i
187 last_journal_id = params[:last_journal_id].to_i
188 @conflict_journals = @issue.journals.all(:conditions => ["#{Journal.table_name}.id > ?", last_journal_id])
188 @conflict_journals = @issue.journals.all(:conditions => ["#{Journal.table_name}.id > ?", last_journal_id])
189 else
189 else
190 @conflict_journals = @issue.journals.all
190 @conflict_journals = @issue.journals.all
191 end
191 end
192 end
192 end
193 end
193 end
194
194
195 if saved
195 if saved
196 render_attachment_warning_if_needed(@issue)
196 render_attachment_warning_if_needed(@issue)
197 flash[:notice] = l(:notice_successful_update) unless @issue.current_journal.new_record?
197 flash[:notice] = l(:notice_successful_update) unless @issue.current_journal.new_record?
198
198
199 respond_to do |format|
199 respond_to do |format|
200 format.html { redirect_back_or_default({:action => 'show', :id => @issue}) }
200 format.html { redirect_back_or_default({:action => 'show', :id => @issue}) }
201 format.api { head :ok }
201 format.api { head :ok }
202 end
202 end
203 else
203 else
204 respond_to do |format|
204 respond_to do |format|
205 format.html { render :action => 'edit' }
205 format.html { render :action => 'edit' }
206 format.api { render_validation_errors(@issue) }
206 format.api { render_validation_errors(@issue) }
207 end
207 end
208 end
208 end
209 end
209 end
210
210
211 # Bulk edit/copy a set of issues
211 # Bulk edit/copy a set of issues
212 def bulk_edit
212 def bulk_edit
213 @issues.sort!
213 @issues.sort!
214 @copy = params[:copy].present?
214 @copy = params[:copy].present?
215 @notes = params[:notes]
215 @notes = params[:notes]
216
216
217 if User.current.allowed_to?(:move_issues, @projects)
217 if User.current.allowed_to?(:move_issues, @projects)
218 @allowed_projects = Issue.allowed_target_projects_on_move
218 @allowed_projects = Issue.allowed_target_projects_on_move
219 if params[:issue]
219 if params[:issue]
220 @target_project = @allowed_projects.detect {|p| p.id.to_s == params[:issue][:project_id].to_s}
220 @target_project = @allowed_projects.detect {|p| p.id.to_s == params[:issue][:project_id].to_s}
221 if @target_project
221 if @target_project
222 target_projects = [@target_project]
222 target_projects = [@target_project]
223 end
223 end
224 end
224 end
225 end
225 end
226 target_projects ||= @projects
226 target_projects ||= @projects
227
227
228 if @copy
228 if @copy
229 @available_statuses = [IssueStatus.default]
229 @available_statuses = [IssueStatus.default]
230 else
230 else
231 @available_statuses = @issues.map(&:new_statuses_allowed_to).reduce(:&)
231 @available_statuses = @issues.map(&:new_statuses_allowed_to).reduce(:&)
232 end
232 end
233 @custom_fields = target_projects.map{|p|p.all_issue_custom_fields}.reduce(:&)
233 @custom_fields = target_projects.map{|p|p.all_issue_custom_fields}.reduce(:&)
234 @assignables = target_projects.map(&:assignable_users).reduce(:&)
234 @assignables = target_projects.map(&:assignable_users).reduce(:&)
235 @trackers = target_projects.map(&:trackers).reduce(:&)
235 @trackers = target_projects.map(&:trackers).reduce(:&)
236 @versions = target_projects.map {|p| p.shared_versions.open}.reduce(:&)
236 @versions = target_projects.map {|p| p.shared_versions.open}.reduce(:&)
237 @categories = target_projects.map {|p| p.issue_categories}.reduce(:&)
237 @categories = target_projects.map {|p| p.issue_categories}.reduce(:&)
238 if @copy
239 @attachments_present = @issues.detect {|i| i.attachments.any?}.present?
240 end
238
241
239 @safe_attributes = @issues.map(&:safe_attribute_names).reduce(:&)
242 @safe_attributes = @issues.map(&:safe_attribute_names).reduce(:&)
240 render :layout => false if request.xhr?
243 render :layout => false if request.xhr?
241 end
244 end
242
245
243 def bulk_update
246 def bulk_update
244 @issues.sort!
247 @issues.sort!
245 @copy = params[:copy].present?
248 @copy = params[:copy].present?
246 attributes = parse_params_for_bulk_issue_attributes(params)
249 attributes = parse_params_for_bulk_issue_attributes(params)
247
250
248 unsaved_issue_ids = []
251 unsaved_issue_ids = []
249 moved_issues = []
252 moved_issues = []
250 @issues.each do |issue|
253 @issues.each do |issue|
251 issue.reload
254 issue.reload
252 if @copy
255 if @copy
253 issue = issue.copy
256 issue = issue.copy({}, :attachments => params[:copy_attachments].present?)
254 end
257 end
255 journal = issue.init_journal(User.current, params[:notes])
258 journal = issue.init_journal(User.current, params[:notes])
256 issue.safe_attributes = attributes
259 issue.safe_attributes = attributes
257 call_hook(:controller_issues_bulk_edit_before_save, { :params => params, :issue => issue })
260 call_hook(:controller_issues_bulk_edit_before_save, { :params => params, :issue => issue })
258 if issue.save
261 if issue.save
259 moved_issues << issue
262 moved_issues << issue
260 else
263 else
261 # Keep unsaved issue ids to display them in flash error
264 # Keep unsaved issue ids to display them in flash error
262 unsaved_issue_ids << issue.id
265 unsaved_issue_ids << issue.id
263 end
266 end
264 end
267 end
265 set_flash_from_bulk_issue_save(@issues, unsaved_issue_ids)
268 set_flash_from_bulk_issue_save(@issues, unsaved_issue_ids)
266
269
267 if params[:follow]
270 if params[:follow]
268 if @issues.size == 1 && moved_issues.size == 1
271 if @issues.size == 1 && moved_issues.size == 1
269 redirect_to :controller => 'issues', :action => 'show', :id => moved_issues.first
272 redirect_to :controller => 'issues', :action => 'show', :id => moved_issues.first
270 elsif moved_issues.map(&:project).uniq.size == 1
273 elsif moved_issues.map(&:project).uniq.size == 1
271 redirect_to :controller => 'issues', :action => 'index', :project_id => moved_issues.map(&:project).first
274 redirect_to :controller => 'issues', :action => 'index', :project_id => moved_issues.map(&:project).first
272 end
275 end
273 else
276 else
274 redirect_back_or_default({:controller => 'issues', :action => 'index', :project_id => @project})
277 redirect_back_or_default({:controller => 'issues', :action => 'index', :project_id => @project})
275 end
278 end
276 end
279 end
277
280
278 def destroy
281 def destroy
279 @hours = TimeEntry.sum(:hours, :conditions => ['issue_id IN (?)', @issues]).to_f
282 @hours = TimeEntry.sum(:hours, :conditions => ['issue_id IN (?)', @issues]).to_f
280 if @hours > 0
283 if @hours > 0
281 case params[:todo]
284 case params[:todo]
282 when 'destroy'
285 when 'destroy'
283 # nothing to do
286 # nothing to do
284 when 'nullify'
287 when 'nullify'
285 TimeEntry.update_all('issue_id = NULL', ['issue_id IN (?)', @issues])
288 TimeEntry.update_all('issue_id = NULL', ['issue_id IN (?)', @issues])
286 when 'reassign'
289 when 'reassign'
287 reassign_to = @project.issues.find_by_id(params[:reassign_to_id])
290 reassign_to = @project.issues.find_by_id(params[:reassign_to_id])
288 if reassign_to.nil?
291 if reassign_to.nil?
289 flash.now[:error] = l(:error_issue_not_found_in_project)
292 flash.now[:error] = l(:error_issue_not_found_in_project)
290 return
293 return
291 else
294 else
292 TimeEntry.update_all("issue_id = #{reassign_to.id}", ['issue_id IN (?)', @issues])
295 TimeEntry.update_all("issue_id = #{reassign_to.id}", ['issue_id IN (?)', @issues])
293 end
296 end
294 else
297 else
295 # display the destroy form if it's a user request
298 # display the destroy form if it's a user request
296 return unless api_request?
299 return unless api_request?
297 end
300 end
298 end
301 end
299 @issues.each do |issue|
302 @issues.each do |issue|
300 begin
303 begin
301 issue.reload.destroy
304 issue.reload.destroy
302 rescue ::ActiveRecord::RecordNotFound # raised by #reload if issue no longer exists
305 rescue ::ActiveRecord::RecordNotFound # raised by #reload if issue no longer exists
303 # nothing to do, issue was already deleted (eg. by a parent)
306 # nothing to do, issue was already deleted (eg. by a parent)
304 end
307 end
305 end
308 end
306 respond_to do |format|
309 respond_to do |format|
307 format.html { redirect_back_or_default(:action => 'index', :project_id => @project) }
310 format.html { redirect_back_or_default(:action => 'index', :project_id => @project) }
308 format.api { head :ok }
311 format.api { head :ok }
309 end
312 end
310 end
313 end
311
314
312 private
315 private
313 def find_issue
316 def find_issue
314 # Issue.visible.find(...) can not be used to redirect user to the login form
317 # Issue.visible.find(...) can not be used to redirect user to the login form
315 # if the issue actually exists but requires authentication
318 # if the issue actually exists but requires authentication
316 @issue = Issue.find(params[:id], :include => [:project, :tracker, :status, :author, :priority, :category])
319 @issue = Issue.find(params[:id], :include => [:project, :tracker, :status, :author, :priority, :category])
317 unless @issue.visible?
320 unless @issue.visible?
318 deny_access
321 deny_access
319 return
322 return
320 end
323 end
321 @project = @issue.project
324 @project = @issue.project
322 rescue ActiveRecord::RecordNotFound
325 rescue ActiveRecord::RecordNotFound
323 render_404
326 render_404
324 end
327 end
325
328
326 def find_project
329 def find_project
327 project_id = params[:project_id] || (params[:issue] && params[:issue][:project_id])
330 project_id = params[:project_id] || (params[:issue] && params[:issue][:project_id])
328 @project = Project.find(project_id)
331 @project = Project.find(project_id)
329 rescue ActiveRecord::RecordNotFound
332 rescue ActiveRecord::RecordNotFound
330 render_404
333 render_404
331 end
334 end
332
335
333 def retrieve_previous_and_next_issue_ids
336 def retrieve_previous_and_next_issue_ids
334 retrieve_query_from_session
337 retrieve_query_from_session
335 if @query
338 if @query
336 sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
339 sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
337 sort_update(@query.sortable_columns, 'issues_index_sort')
340 sort_update(@query.sortable_columns, 'issues_index_sort')
338 limit = 500
341 limit = 500
339 issue_ids = @query.issue_ids(:order => sort_clause, :limit => (limit + 1), :include => [:assigned_to, :tracker, :priority, :category, :fixed_version])
342 issue_ids = @query.issue_ids(:order => sort_clause, :limit => (limit + 1), :include => [:assigned_to, :tracker, :priority, :category, :fixed_version])
340 if (idx = issue_ids.index(@issue.id)) && idx < limit
343 if (idx = issue_ids.index(@issue.id)) && idx < limit
341 if issue_ids.size < 500
344 if issue_ids.size < 500
342 @issue_position = idx + 1
345 @issue_position = idx + 1
343 @issue_count = issue_ids.size
346 @issue_count = issue_ids.size
344 end
347 end
345 @prev_issue_id = issue_ids[idx - 1] if idx > 0
348 @prev_issue_id = issue_ids[idx - 1] if idx > 0
346 @next_issue_id = issue_ids[idx + 1] if idx < (issue_ids.size - 1)
349 @next_issue_id = issue_ids[idx + 1] if idx < (issue_ids.size - 1)
347 end
350 end
348 end
351 end
349 end
352 end
350
353
351 # Used by #edit and #update to set some common instance variables
354 # Used by #edit and #update to set some common instance variables
352 # from the params
355 # from the params
353 # TODO: Refactor, not everything in here is needed by #edit
356 # TODO: Refactor, not everything in here is needed by #edit
354 def update_issue_from_params
357 def update_issue_from_params
355 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
358 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
356 @time_entry = TimeEntry.new(:issue => @issue, :project => @issue.project)
359 @time_entry = TimeEntry.new(:issue => @issue, :project => @issue.project)
357 @time_entry.attributes = params[:time_entry]
360 @time_entry.attributes = params[:time_entry]
358
361
359 @notes = params[:notes] || (params[:issue].present? ? params[:issue][:notes] : nil)
362 @notes = params[:notes] || (params[:issue].present? ? params[:issue][:notes] : nil)
360 @issue.init_journal(User.current, @notes)
363 @issue.init_journal(User.current, @notes)
361
364
362 issue_attributes = params[:issue]
365 issue_attributes = params[:issue]
363 if issue_attributes && params[:conflict_resolution]
366 if issue_attributes && params[:conflict_resolution]
364 case params[:conflict_resolution]
367 case params[:conflict_resolution]
365 when 'overwrite'
368 when 'overwrite'
366 issue_attributes = issue_attributes.dup
369 issue_attributes = issue_attributes.dup
367 issue_attributes.delete(:lock_version)
370 issue_attributes.delete(:lock_version)
368 when 'add_notes'
371 when 'add_notes'
369 issue_attributes = {}
372 issue_attributes = {}
370 when 'cancel'
373 when 'cancel'
371 redirect_to issue_path(@issue)
374 redirect_to issue_path(@issue)
372 return false
375 return false
373 end
376 end
374 end
377 end
375 @issue.safe_attributes = issue_attributes
378 @issue.safe_attributes = issue_attributes
376 @priorities = IssuePriority.active
379 @priorities = IssuePriority.active
377 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
380 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
378 true
381 true
379 end
382 end
380
383
381 # TODO: Refactor, lots of extra code in here
384 # TODO: Refactor, lots of extra code in here
382 # TODO: Changing tracker on an existing issue should not trigger this
385 # TODO: Changing tracker on an existing issue should not trigger this
383 def build_new_issue_from_params
386 def build_new_issue_from_params
384 if params[:id].blank?
387 if params[:id].blank?
385 @issue = Issue.new
388 @issue = Issue.new
386 if params[:copy_from]
389 if params[:copy_from]
387 begin
390 begin
388 @copy_from = Issue.visible.find(params[:copy_from])
391 @copy_from = Issue.visible.find(params[:copy_from])
389 @copy_attachments = params[:copy_attachments].present? || request.get?
392 @copy_attachments = params[:copy_attachments].present? || request.get?
390 @issue.copy_from(@copy_from, :attachments => @copy_attachments)
393 @issue.copy_from(@copy_from, :attachments => @copy_attachments)
391 rescue ActiveRecord::RecordNotFound
394 rescue ActiveRecord::RecordNotFound
392 render_404
395 render_404
393 return
396 return
394 end
397 end
395 end
398 end
396 @issue.project = @project
399 @issue.project = @project
397 else
400 else
398 @issue = @project.issues.visible.find(params[:id])
401 @issue = @project.issues.visible.find(params[:id])
399 end
402 end
400
403
401 @issue.project = @project
404 @issue.project = @project
402 @issue.author = User.current
405 @issue.author = User.current
403 # Tracker must be set before custom field values
406 # Tracker must be set before custom field values
404 @issue.tracker ||= @project.trackers.find((params[:issue] && params[:issue][:tracker_id]) || params[:tracker_id] || :first)
407 @issue.tracker ||= @project.trackers.find((params[:issue] && params[:issue][:tracker_id]) || params[:tracker_id] || :first)
405 if @issue.tracker.nil?
408 if @issue.tracker.nil?
406 render_error l(:error_no_tracker_in_project)
409 render_error l(:error_no_tracker_in_project)
407 return false
410 return false
408 end
411 end
409 @issue.start_date ||= Date.today if Setting.default_issue_start_date_to_creation_date?
412 @issue.start_date ||= Date.today if Setting.default_issue_start_date_to_creation_date?
410 @issue.safe_attributes = params[:issue]
413 @issue.safe_attributes = params[:issue]
411
414
412 @priorities = IssuePriority.active
415 @priorities = IssuePriority.active
413 @allowed_statuses = @issue.new_statuses_allowed_to(User.current, true)
416 @allowed_statuses = @issue.new_statuses_allowed_to(User.current, true)
414 @available_watchers = (@issue.project.users.sort + @issue.watcher_users).uniq
417 @available_watchers = (@issue.project.users.sort + @issue.watcher_users).uniq
415 end
418 end
416
419
417 def check_for_default_issue_status
420 def check_for_default_issue_status
418 if IssueStatus.default.nil?
421 if IssueStatus.default.nil?
419 render_error l(:error_no_default_issue_status)
422 render_error l(:error_no_default_issue_status)
420 return false
423 return false
421 end
424 end
422 end
425 end
423
426
424 def parse_params_for_bulk_issue_attributes(params)
427 def parse_params_for_bulk_issue_attributes(params)
425 attributes = (params[:issue] || {}).reject {|k,v| v.blank?}
428 attributes = (params[:issue] || {}).reject {|k,v| v.blank?}
426 attributes.keys.each {|k| attributes[k] = '' if attributes[k] == 'none'}
429 attributes.keys.each {|k| attributes[k] = '' if attributes[k] == 'none'}
427 if custom = attributes[:custom_field_values]
430 if custom = attributes[:custom_field_values]
428 custom.reject! {|k,v| v.blank?}
431 custom.reject! {|k,v| v.blank?}
429 custom.keys.each do |k|
432 custom.keys.each do |k|
430 if custom[k].is_a?(Array)
433 if custom[k].is_a?(Array)
431 custom[k] << '' if custom[k].delete('__none__')
434 custom[k] << '' if custom[k].delete('__none__')
432 else
435 else
433 custom[k] = '' if custom[k] == '__none__'
436 custom[k] = '' if custom[k] == '__none__'
434 end
437 end
435 end
438 end
436 end
439 end
437 attributes
440 attributes
438 end
441 end
439 end
442 end
@@ -1,1078 +1,1078
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2011 Jean-Philippe Lang
2 # Copyright (C) 2006-2011 Jean-Philippe Lang
3 #
3 #
4 # This program is free software; you can redistribute it and/or
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
7 # of the License, or (at your option) any later version.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU General Public License
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
17
18 class Issue < ActiveRecord::Base
18 class Issue < ActiveRecord::Base
19 include Redmine::SafeAttributes
19 include Redmine::SafeAttributes
20
20
21 belongs_to :project
21 belongs_to :project
22 belongs_to :tracker
22 belongs_to :tracker
23 belongs_to :status, :class_name => 'IssueStatus', :foreign_key => 'status_id'
23 belongs_to :status, :class_name => 'IssueStatus', :foreign_key => 'status_id'
24 belongs_to :author, :class_name => 'User', :foreign_key => 'author_id'
24 belongs_to :author, :class_name => 'User', :foreign_key => 'author_id'
25 belongs_to :assigned_to, :class_name => 'Principal', :foreign_key => 'assigned_to_id'
25 belongs_to :assigned_to, :class_name => 'Principal', :foreign_key => 'assigned_to_id'
26 belongs_to :fixed_version, :class_name => 'Version', :foreign_key => 'fixed_version_id'
26 belongs_to :fixed_version, :class_name => 'Version', :foreign_key => 'fixed_version_id'
27 belongs_to :priority, :class_name => 'IssuePriority', :foreign_key => 'priority_id'
27 belongs_to :priority, :class_name => 'IssuePriority', :foreign_key => 'priority_id'
28 belongs_to :category, :class_name => 'IssueCategory', :foreign_key => 'category_id'
28 belongs_to :category, :class_name => 'IssueCategory', :foreign_key => 'category_id'
29
29
30 has_many :journals, :as => :journalized, :dependent => :destroy
30 has_many :journals, :as => :journalized, :dependent => :destroy
31 has_many :time_entries, :dependent => :delete_all
31 has_many :time_entries, :dependent => :delete_all
32 has_and_belongs_to_many :changesets, :order => "#{Changeset.table_name}.committed_on ASC, #{Changeset.table_name}.id ASC"
32 has_and_belongs_to_many :changesets, :order => "#{Changeset.table_name}.committed_on ASC, #{Changeset.table_name}.id ASC"
33
33
34 has_many :relations_from, :class_name => 'IssueRelation', :foreign_key => 'issue_from_id', :dependent => :delete_all
34 has_many :relations_from, :class_name => 'IssueRelation', :foreign_key => 'issue_from_id', :dependent => :delete_all
35 has_many :relations_to, :class_name => 'IssueRelation', :foreign_key => 'issue_to_id', :dependent => :delete_all
35 has_many :relations_to, :class_name => 'IssueRelation', :foreign_key => 'issue_to_id', :dependent => :delete_all
36
36
37 acts_as_nested_set :scope => 'root_id', :dependent => :destroy
37 acts_as_nested_set :scope => 'root_id', :dependent => :destroy
38 acts_as_attachable :after_add => :attachment_added, :after_remove => :attachment_removed
38 acts_as_attachable :after_add => :attachment_added, :after_remove => :attachment_removed
39 acts_as_customizable
39 acts_as_customizable
40 acts_as_watchable
40 acts_as_watchable
41 acts_as_searchable :columns => ['subject', "#{table_name}.description", "#{Journal.table_name}.notes"],
41 acts_as_searchable :columns => ['subject', "#{table_name}.description", "#{Journal.table_name}.notes"],
42 :include => [:project, :journals],
42 :include => [:project, :journals],
43 # sort by id so that limited eager loading doesn't break with postgresql
43 # sort by id so that limited eager loading doesn't break with postgresql
44 :order_column => "#{table_name}.id"
44 :order_column => "#{table_name}.id"
45 acts_as_event :title => Proc.new {|o| "#{o.tracker.name} ##{o.id} (#{o.status}): #{o.subject}"},
45 acts_as_event :title => Proc.new {|o| "#{o.tracker.name} ##{o.id} (#{o.status}): #{o.subject}"},
46 :url => Proc.new {|o| {:controller => 'issues', :action => 'show', :id => o.id}},
46 :url => Proc.new {|o| {:controller => 'issues', :action => 'show', :id => o.id}},
47 :type => Proc.new {|o| 'issue' + (o.closed? ? ' closed' : '') }
47 :type => Proc.new {|o| 'issue' + (o.closed? ? ' closed' : '') }
48
48
49 acts_as_activity_provider :find_options => {:include => [:project, :author, :tracker]},
49 acts_as_activity_provider :find_options => {:include => [:project, :author, :tracker]},
50 :author_key => :author_id
50 :author_key => :author_id
51
51
52 DONE_RATIO_OPTIONS = %w(issue_field issue_status)
52 DONE_RATIO_OPTIONS = %w(issue_field issue_status)
53
53
54 attr_reader :current_journal
54 attr_reader :current_journal
55
55
56 validates_presence_of :subject, :priority, :project, :tracker, :author, :status
56 validates_presence_of :subject, :priority, :project, :tracker, :author, :status
57
57
58 validates_length_of :subject, :maximum => 255
58 validates_length_of :subject, :maximum => 255
59 validates_inclusion_of :done_ratio, :in => 0..100
59 validates_inclusion_of :done_ratio, :in => 0..100
60 validates_numericality_of :estimated_hours, :allow_nil => true
60 validates_numericality_of :estimated_hours, :allow_nil => true
61 validate :validate_issue
61 validate :validate_issue
62
62
63 named_scope :visible, lambda {|*args| { :include => :project,
63 named_scope :visible, lambda {|*args| { :include => :project,
64 :conditions => Issue.visible_condition(args.shift || User.current, *args) } }
64 :conditions => Issue.visible_condition(args.shift || User.current, *args) } }
65
65
66 named_scope :open, lambda {|*args|
66 named_scope :open, lambda {|*args|
67 is_closed = args.size > 0 ? !args.first : false
67 is_closed = args.size > 0 ? !args.first : false
68 {:conditions => ["#{IssueStatus.table_name}.is_closed = ?", is_closed], :include => :status}
68 {:conditions => ["#{IssueStatus.table_name}.is_closed = ?", is_closed], :include => :status}
69 }
69 }
70
70
71 named_scope :recently_updated, :order => "#{Issue.table_name}.updated_on DESC"
71 named_scope :recently_updated, :order => "#{Issue.table_name}.updated_on DESC"
72 named_scope :with_limit, lambda { |limit| { :limit => limit} }
72 named_scope :with_limit, lambda { |limit| { :limit => limit} }
73 named_scope :on_active_project, :include => [:status, :project, :tracker],
73 named_scope :on_active_project, :include => [:status, :project, :tracker],
74 :conditions => ["#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"]
74 :conditions => ["#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"]
75
75
76 before_create :default_assign
76 before_create :default_assign
77 before_save :close_duplicates, :update_done_ratio_from_issue_status
77 before_save :close_duplicates, :update_done_ratio_from_issue_status
78 after_save {|issue| issue.send :after_project_change if !issue.id_changed? && issue.project_id_changed?}
78 after_save {|issue| issue.send :after_project_change if !issue.id_changed? && issue.project_id_changed?}
79 after_save :reschedule_following_issues, :update_nested_set_attributes, :update_parent_attributes, :create_journal
79 after_save :reschedule_following_issues, :update_nested_set_attributes, :update_parent_attributes, :create_journal
80 after_destroy :update_parent_attributes
80 after_destroy :update_parent_attributes
81
81
82 # Returns a SQL conditions string used to find all issues visible by the specified user
82 # Returns a SQL conditions string used to find all issues visible by the specified user
83 def self.visible_condition(user, options={})
83 def self.visible_condition(user, options={})
84 Project.allowed_to_condition(user, :view_issues, options) do |role, user|
84 Project.allowed_to_condition(user, :view_issues, options) do |role, user|
85 case role.issues_visibility
85 case role.issues_visibility
86 when 'all'
86 when 'all'
87 nil
87 nil
88 when 'default'
88 when 'default'
89 user_ids = [user.id] + user.groups.map(&:id)
89 user_ids = [user.id] + user.groups.map(&:id)
90 "(#{table_name}.is_private = #{connection.quoted_false} OR #{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id IN (#{user_ids.join(',')}))"
90 "(#{table_name}.is_private = #{connection.quoted_false} OR #{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id IN (#{user_ids.join(',')}))"
91 when 'own'
91 when 'own'
92 user_ids = [user.id] + user.groups.map(&:id)
92 user_ids = [user.id] + user.groups.map(&:id)
93 "(#{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id IN (#{user_ids.join(',')}))"
93 "(#{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id IN (#{user_ids.join(',')}))"
94 else
94 else
95 '1=0'
95 '1=0'
96 end
96 end
97 end
97 end
98 end
98 end
99
99
100 # Returns true if usr or current user is allowed to view the issue
100 # Returns true if usr or current user is allowed to view the issue
101 def visible?(usr=nil)
101 def visible?(usr=nil)
102 (usr || User.current).allowed_to?(:view_issues, self.project) do |role, user|
102 (usr || User.current).allowed_to?(:view_issues, self.project) do |role, user|
103 case role.issues_visibility
103 case role.issues_visibility
104 when 'all'
104 when 'all'
105 true
105 true
106 when 'default'
106 when 'default'
107 !self.is_private? || self.author == user || user.is_or_belongs_to?(assigned_to)
107 !self.is_private? || self.author == user || user.is_or_belongs_to?(assigned_to)
108 when 'own'
108 when 'own'
109 self.author == user || user.is_or_belongs_to?(assigned_to)
109 self.author == user || user.is_or_belongs_to?(assigned_to)
110 else
110 else
111 false
111 false
112 end
112 end
113 end
113 end
114 end
114 end
115
115
116 def initialize(attributes=nil, *args)
116 def initialize(attributes=nil, *args)
117 super
117 super
118 if new_record?
118 if new_record?
119 # set default values for new records only
119 # set default values for new records only
120 self.status ||= IssueStatus.default
120 self.status ||= IssueStatus.default
121 self.priority ||= IssuePriority.default
121 self.priority ||= IssuePriority.default
122 self.watcher_user_ids = []
122 self.watcher_user_ids = []
123 end
123 end
124 end
124 end
125
125
126 # Overrides Redmine::Acts::Customizable::InstanceMethods#available_custom_fields
126 # Overrides Redmine::Acts::Customizable::InstanceMethods#available_custom_fields
127 def available_custom_fields
127 def available_custom_fields
128 (project && tracker) ? (project.all_issue_custom_fields & tracker.custom_fields.all) : []
128 (project && tracker) ? (project.all_issue_custom_fields & tracker.custom_fields.all) : []
129 end
129 end
130
130
131 # Copies attributes from another issue, arg can be an id or an Issue
131 # Copies attributes from another issue, arg can be an id or an Issue
132 def copy_from(arg, options={})
132 def copy_from(arg, options={})
133 issue = arg.is_a?(Issue) ? arg : Issue.visible.find(arg)
133 issue = arg.is_a?(Issue) ? arg : Issue.visible.find(arg)
134 self.attributes = issue.attributes.dup.except("id", "root_id", "parent_id", "lft", "rgt", "created_on", "updated_on")
134 self.attributes = issue.attributes.dup.except("id", "root_id", "parent_id", "lft", "rgt", "created_on", "updated_on")
135 self.custom_field_values = issue.custom_field_values.inject({}) {|h,v| h[v.custom_field_id] = v.value; h}
135 self.custom_field_values = issue.custom_field_values.inject({}) {|h,v| h[v.custom_field_id] = v.value; h}
136 self.status = issue.status
136 self.status = issue.status
137 self.author = User.current
137 self.author = User.current
138 unless options[:attachments] == false
138 unless options[:attachments] == false
139 self.attachments = issue.attachments.map do |attachement|
139 self.attachments = issue.attachments.map do |attachement|
140 attachement.copy(:container => self)
140 attachement.copy(:container => self)
141 end
141 end
142 end
142 end
143 @copied_from = issue
143 @copied_from = issue
144 self
144 self
145 end
145 end
146
146
147 # Returns an unsaved copy of the issue
147 # Returns an unsaved copy of the issue
148 def copy(attributes=nil)
148 def copy(attributes=nil, copy_options={})
149 copy = self.class.new.copy_from(self)
149 copy = self.class.new.copy_from(self, copy_options)
150 copy.attributes = attributes if attributes
150 copy.attributes = attributes if attributes
151 copy
151 copy
152 end
152 end
153
153
154 # Returns true if the issue is a copy
154 # Returns true if the issue is a copy
155 def copy?
155 def copy?
156 @copied_from.present?
156 @copied_from.present?
157 end
157 end
158
158
159 # Moves/copies an issue to a new project and tracker
159 # Moves/copies an issue to a new project and tracker
160 # Returns the moved/copied issue on success, false on failure
160 # Returns the moved/copied issue on success, false on failure
161 def move_to_project(new_project, new_tracker=nil, options={})
161 def move_to_project(new_project, new_tracker=nil, options={})
162 ActiveSupport::Deprecation.warn "Issue#move_to_project is deprecated, use #project= instead."
162 ActiveSupport::Deprecation.warn "Issue#move_to_project is deprecated, use #project= instead."
163
163
164 if options[:copy]
164 if options[:copy]
165 issue = self.copy
165 issue = self.copy
166 else
166 else
167 issue = self
167 issue = self
168 end
168 end
169
169
170 issue.init_journal(User.current, options[:notes])
170 issue.init_journal(User.current, options[:notes])
171
171
172 # Preserve previous behaviour
172 # Preserve previous behaviour
173 # #move_to_project doesn't change tracker automatically
173 # #move_to_project doesn't change tracker automatically
174 issue.send :project=, new_project, true
174 issue.send :project=, new_project, true
175 if new_tracker
175 if new_tracker
176 issue.tracker = new_tracker
176 issue.tracker = new_tracker
177 end
177 end
178 # Allow bulk setting of attributes on the issue
178 # Allow bulk setting of attributes on the issue
179 if options[:attributes]
179 if options[:attributes]
180 issue.attributes = options[:attributes]
180 issue.attributes = options[:attributes]
181 end
181 end
182
182
183 issue.save ? issue : false
183 issue.save ? issue : false
184 end
184 end
185
185
186 def status_id=(sid)
186 def status_id=(sid)
187 self.status = nil
187 self.status = nil
188 write_attribute(:status_id, sid)
188 write_attribute(:status_id, sid)
189 end
189 end
190
190
191 def priority_id=(pid)
191 def priority_id=(pid)
192 self.priority = nil
192 self.priority = nil
193 write_attribute(:priority_id, pid)
193 write_attribute(:priority_id, pid)
194 end
194 end
195
195
196 def category_id=(cid)
196 def category_id=(cid)
197 self.category = nil
197 self.category = nil
198 write_attribute(:category_id, cid)
198 write_attribute(:category_id, cid)
199 end
199 end
200
200
201 def fixed_version_id=(vid)
201 def fixed_version_id=(vid)
202 self.fixed_version = nil
202 self.fixed_version = nil
203 write_attribute(:fixed_version_id, vid)
203 write_attribute(:fixed_version_id, vid)
204 end
204 end
205
205
206 def tracker_id=(tid)
206 def tracker_id=(tid)
207 self.tracker = nil
207 self.tracker = nil
208 result = write_attribute(:tracker_id, tid)
208 result = write_attribute(:tracker_id, tid)
209 @custom_field_values = nil
209 @custom_field_values = nil
210 result
210 result
211 end
211 end
212
212
213 def project_id=(project_id)
213 def project_id=(project_id)
214 if project_id.to_s != self.project_id.to_s
214 if project_id.to_s != self.project_id.to_s
215 self.project = (project_id.present? ? Project.find_by_id(project_id) : nil)
215 self.project = (project_id.present? ? Project.find_by_id(project_id) : nil)
216 end
216 end
217 end
217 end
218
218
219 def project=(project, keep_tracker=false)
219 def project=(project, keep_tracker=false)
220 project_was = self.project
220 project_was = self.project
221 write_attribute(:project_id, project ? project.id : nil)
221 write_attribute(:project_id, project ? project.id : nil)
222 association_instance_set('project', project)
222 association_instance_set('project', project)
223 if project_was && project && project_was != project
223 if project_was && project && project_was != project
224 unless keep_tracker || project.trackers.include?(tracker)
224 unless keep_tracker || project.trackers.include?(tracker)
225 self.tracker = project.trackers.first
225 self.tracker = project.trackers.first
226 end
226 end
227 # Reassign to the category with same name if any
227 # Reassign to the category with same name if any
228 if category
228 if category
229 self.category = project.issue_categories.find_by_name(category.name)
229 self.category = project.issue_categories.find_by_name(category.name)
230 end
230 end
231 # Keep the fixed_version if it's still valid in the new_project
231 # Keep the fixed_version if it's still valid in the new_project
232 if fixed_version && fixed_version.project != project && !project.shared_versions.include?(fixed_version)
232 if fixed_version && fixed_version.project != project && !project.shared_versions.include?(fixed_version)
233 self.fixed_version = nil
233 self.fixed_version = nil
234 end
234 end
235 if parent && parent.project_id != project_id
235 if parent && parent.project_id != project_id
236 self.parent_issue_id = nil
236 self.parent_issue_id = nil
237 end
237 end
238 @custom_field_values = nil
238 @custom_field_values = nil
239 end
239 end
240 end
240 end
241
241
242 def description=(arg)
242 def description=(arg)
243 if arg.is_a?(String)
243 if arg.is_a?(String)
244 arg = arg.gsub(/(\r\n|\n|\r)/, "\r\n")
244 arg = arg.gsub(/(\r\n|\n|\r)/, "\r\n")
245 end
245 end
246 write_attribute(:description, arg)
246 write_attribute(:description, arg)
247 end
247 end
248
248
249 # Overrides attributes= so that project and tracker get assigned first
249 # Overrides attributes= so that project and tracker get assigned first
250 def attributes_with_project_and_tracker_first=(new_attributes, *args)
250 def attributes_with_project_and_tracker_first=(new_attributes, *args)
251 return if new_attributes.nil?
251 return if new_attributes.nil?
252 attrs = new_attributes.dup
252 attrs = new_attributes.dup
253 attrs.stringify_keys!
253 attrs.stringify_keys!
254
254
255 %w(project project_id tracker tracker_id).each do |attr|
255 %w(project project_id tracker tracker_id).each do |attr|
256 if attrs.has_key?(attr)
256 if attrs.has_key?(attr)
257 send "#{attr}=", attrs.delete(attr)
257 send "#{attr}=", attrs.delete(attr)
258 end
258 end
259 end
259 end
260 send :attributes_without_project_and_tracker_first=, attrs, *args
260 send :attributes_without_project_and_tracker_first=, attrs, *args
261 end
261 end
262 # Do not redefine alias chain on reload (see #4838)
262 # Do not redefine alias chain on reload (see #4838)
263 alias_method_chain(:attributes=, :project_and_tracker_first) unless method_defined?(:attributes_without_project_and_tracker_first=)
263 alias_method_chain(:attributes=, :project_and_tracker_first) unless method_defined?(:attributes_without_project_and_tracker_first=)
264
264
265 def estimated_hours=(h)
265 def estimated_hours=(h)
266 write_attribute :estimated_hours, (h.is_a?(String) ? h.to_hours : h)
266 write_attribute :estimated_hours, (h.is_a?(String) ? h.to_hours : h)
267 end
267 end
268
268
269 safe_attributes 'project_id',
269 safe_attributes 'project_id',
270 :if => lambda {|issue, user|
270 :if => lambda {|issue, user|
271 if issue.new_record?
271 if issue.new_record?
272 issue.copy?
272 issue.copy?
273 elsif user.allowed_to?(:move_issues, issue.project)
273 elsif user.allowed_to?(:move_issues, issue.project)
274 projects = Issue.allowed_target_projects_on_move(user)
274 projects = Issue.allowed_target_projects_on_move(user)
275 projects.include?(issue.project) && projects.size > 1
275 projects.include?(issue.project) && projects.size > 1
276 end
276 end
277 }
277 }
278
278
279 safe_attributes 'tracker_id',
279 safe_attributes 'tracker_id',
280 'status_id',
280 'status_id',
281 'category_id',
281 'category_id',
282 'assigned_to_id',
282 'assigned_to_id',
283 'priority_id',
283 'priority_id',
284 'fixed_version_id',
284 'fixed_version_id',
285 'subject',
285 'subject',
286 'description',
286 'description',
287 'start_date',
287 'start_date',
288 'due_date',
288 'due_date',
289 'done_ratio',
289 'done_ratio',
290 'estimated_hours',
290 'estimated_hours',
291 'custom_field_values',
291 'custom_field_values',
292 'custom_fields',
292 'custom_fields',
293 'lock_version',
293 'lock_version',
294 :if => lambda {|issue, user| issue.new_record? || user.allowed_to?(:edit_issues, issue.project) }
294 :if => lambda {|issue, user| issue.new_record? || user.allowed_to?(:edit_issues, issue.project) }
295
295
296 safe_attributes 'status_id',
296 safe_attributes 'status_id',
297 'assigned_to_id',
297 'assigned_to_id',
298 'fixed_version_id',
298 'fixed_version_id',
299 'done_ratio',
299 'done_ratio',
300 'lock_version',
300 'lock_version',
301 :if => lambda {|issue, user| issue.new_statuses_allowed_to(user).any? }
301 :if => lambda {|issue, user| issue.new_statuses_allowed_to(user).any? }
302
302
303 safe_attributes 'watcher_user_ids',
303 safe_attributes 'watcher_user_ids',
304 :if => lambda {|issue, user| issue.new_record? && user.allowed_to?(:add_issue_watchers, issue.project)}
304 :if => lambda {|issue, user| issue.new_record? && user.allowed_to?(:add_issue_watchers, issue.project)}
305
305
306 safe_attributes 'is_private',
306 safe_attributes 'is_private',
307 :if => lambda {|issue, user|
307 :if => lambda {|issue, user|
308 user.allowed_to?(:set_issues_private, issue.project) ||
308 user.allowed_to?(:set_issues_private, issue.project) ||
309 (issue.author == user && user.allowed_to?(:set_own_issues_private, issue.project))
309 (issue.author == user && user.allowed_to?(:set_own_issues_private, issue.project))
310 }
310 }
311
311
312 safe_attributes 'parent_issue_id',
312 safe_attributes 'parent_issue_id',
313 :if => lambda {|issue, user| (issue.new_record? || user.allowed_to?(:edit_issues, issue.project)) &&
313 :if => lambda {|issue, user| (issue.new_record? || user.allowed_to?(:edit_issues, issue.project)) &&
314 user.allowed_to?(:manage_subtasks, issue.project)}
314 user.allowed_to?(:manage_subtasks, issue.project)}
315
315
316 # Safely sets attributes
316 # Safely sets attributes
317 # Should be called from controllers instead of #attributes=
317 # Should be called from controllers instead of #attributes=
318 # attr_accessible is too rough because we still want things like
318 # attr_accessible is too rough because we still want things like
319 # Issue.new(:project => foo) to work
319 # Issue.new(:project => foo) to work
320 def safe_attributes=(attrs, user=User.current)
320 def safe_attributes=(attrs, user=User.current)
321 return unless attrs.is_a?(Hash)
321 return unless attrs.is_a?(Hash)
322
322
323 # User can change issue attributes only if he has :edit permission or if a workflow transition is allowed
323 # User can change issue attributes only if he has :edit permission or if a workflow transition is allowed
324 attrs = delete_unsafe_attributes(attrs, user)
324 attrs = delete_unsafe_attributes(attrs, user)
325 return if attrs.empty?
325 return if attrs.empty?
326
326
327 # Project and Tracker must be set before since new_statuses_allowed_to depends on it.
327 # Project and Tracker must be set before since new_statuses_allowed_to depends on it.
328 if p = attrs.delete('project_id')
328 if p = attrs.delete('project_id')
329 if allowed_target_projects(user).collect(&:id).include?(p.to_i)
329 if allowed_target_projects(user).collect(&:id).include?(p.to_i)
330 self.project_id = p
330 self.project_id = p
331 end
331 end
332 end
332 end
333
333
334 if t = attrs.delete('tracker_id')
334 if t = attrs.delete('tracker_id')
335 self.tracker_id = t
335 self.tracker_id = t
336 end
336 end
337
337
338 if attrs['status_id']
338 if attrs['status_id']
339 unless new_statuses_allowed_to(user).collect(&:id).include?(attrs['status_id'].to_i)
339 unless new_statuses_allowed_to(user).collect(&:id).include?(attrs['status_id'].to_i)
340 attrs.delete('status_id')
340 attrs.delete('status_id')
341 end
341 end
342 end
342 end
343
343
344 unless leaf?
344 unless leaf?
345 attrs.reject! {|k,v| %w(priority_id done_ratio start_date due_date estimated_hours).include?(k)}
345 attrs.reject! {|k,v| %w(priority_id done_ratio start_date due_date estimated_hours).include?(k)}
346 end
346 end
347
347
348 if attrs['parent_issue_id'].present?
348 if attrs['parent_issue_id'].present?
349 attrs.delete('parent_issue_id') unless Issue.visible(user).exists?(attrs['parent_issue_id'].to_i)
349 attrs.delete('parent_issue_id') unless Issue.visible(user).exists?(attrs['parent_issue_id'].to_i)
350 end
350 end
351
351
352 # mass-assignment security bypass
352 # mass-assignment security bypass
353 self.send :attributes=, attrs, false
353 self.send :attributes=, attrs, false
354 end
354 end
355
355
356 def done_ratio
356 def done_ratio
357 if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
357 if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
358 status.default_done_ratio
358 status.default_done_ratio
359 else
359 else
360 read_attribute(:done_ratio)
360 read_attribute(:done_ratio)
361 end
361 end
362 end
362 end
363
363
364 def self.use_status_for_done_ratio?
364 def self.use_status_for_done_ratio?
365 Setting.issue_done_ratio == 'issue_status'
365 Setting.issue_done_ratio == 'issue_status'
366 end
366 end
367
367
368 def self.use_field_for_done_ratio?
368 def self.use_field_for_done_ratio?
369 Setting.issue_done_ratio == 'issue_field'
369 Setting.issue_done_ratio == 'issue_field'
370 end
370 end
371
371
372 def validate_issue
372 def validate_issue
373 if self.due_date.nil? && @attributes['due_date'] && !@attributes['due_date'].empty?
373 if self.due_date.nil? && @attributes['due_date'] && !@attributes['due_date'].empty?
374 errors.add :due_date, :not_a_date
374 errors.add :due_date, :not_a_date
375 end
375 end
376
376
377 if self.due_date and self.start_date and self.due_date < self.start_date
377 if self.due_date and self.start_date and self.due_date < self.start_date
378 errors.add :due_date, :greater_than_start_date
378 errors.add :due_date, :greater_than_start_date
379 end
379 end
380
380
381 if start_date && soonest_start && start_date < soonest_start
381 if start_date && soonest_start && start_date < soonest_start
382 errors.add :start_date, :invalid
382 errors.add :start_date, :invalid
383 end
383 end
384
384
385 if fixed_version
385 if fixed_version
386 if !assignable_versions.include?(fixed_version)
386 if !assignable_versions.include?(fixed_version)
387 errors.add :fixed_version_id, :inclusion
387 errors.add :fixed_version_id, :inclusion
388 elsif reopened? && fixed_version.closed?
388 elsif reopened? && fixed_version.closed?
389 errors.add :base, I18n.t(:error_can_not_reopen_issue_on_closed_version)
389 errors.add :base, I18n.t(:error_can_not_reopen_issue_on_closed_version)
390 end
390 end
391 end
391 end
392
392
393 # Checks that the issue can not be added/moved to a disabled tracker
393 # Checks that the issue can not be added/moved to a disabled tracker
394 if project && (tracker_id_changed? || project_id_changed?)
394 if project && (tracker_id_changed? || project_id_changed?)
395 unless project.trackers.include?(tracker)
395 unless project.trackers.include?(tracker)
396 errors.add :tracker_id, :inclusion
396 errors.add :tracker_id, :inclusion
397 end
397 end
398 end
398 end
399
399
400 # Checks parent issue assignment
400 # Checks parent issue assignment
401 if @parent_issue
401 if @parent_issue
402 if @parent_issue.project_id != project_id
402 if @parent_issue.project_id != project_id
403 errors.add :parent_issue_id, :not_same_project
403 errors.add :parent_issue_id, :not_same_project
404 elsif !new_record?
404 elsif !new_record?
405 # moving an existing issue
405 # moving an existing issue
406 if @parent_issue.root_id != root_id
406 if @parent_issue.root_id != root_id
407 # we can always move to another tree
407 # we can always move to another tree
408 elsif move_possible?(@parent_issue)
408 elsif move_possible?(@parent_issue)
409 # move accepted inside tree
409 # move accepted inside tree
410 else
410 else
411 errors.add :parent_issue_id, :not_a_valid_parent
411 errors.add :parent_issue_id, :not_a_valid_parent
412 end
412 end
413 end
413 end
414 end
414 end
415 end
415 end
416
416
417 # Set the done_ratio using the status if that setting is set. This will keep the done_ratios
417 # Set the done_ratio using the status if that setting is set. This will keep the done_ratios
418 # even if the user turns off the setting later
418 # even if the user turns off the setting later
419 def update_done_ratio_from_issue_status
419 def update_done_ratio_from_issue_status
420 if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
420 if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
421 self.done_ratio = status.default_done_ratio
421 self.done_ratio = status.default_done_ratio
422 end
422 end
423 end
423 end
424
424
425 def init_journal(user, notes = "")
425 def init_journal(user, notes = "")
426 @current_journal ||= Journal.new(:journalized => self, :user => user, :notes => notes)
426 @current_journal ||= Journal.new(:journalized => self, :user => user, :notes => notes)
427 if new_record?
427 if new_record?
428 @current_journal.notify = false
428 @current_journal.notify = false
429 else
429 else
430 @attributes_before_change = attributes.dup
430 @attributes_before_change = attributes.dup
431 @custom_values_before_change = {}
431 @custom_values_before_change = {}
432 self.custom_field_values.each {|c| @custom_values_before_change.store c.custom_field_id, c.value }
432 self.custom_field_values.each {|c| @custom_values_before_change.store c.custom_field_id, c.value }
433 end
433 end
434 # Make sure updated_on is updated when adding a note.
434 # Make sure updated_on is updated when adding a note.
435 updated_on_will_change!
435 updated_on_will_change!
436 @current_journal
436 @current_journal
437 end
437 end
438
438
439 # Returns the id of the last journal or nil
439 # Returns the id of the last journal or nil
440 def last_journal_id
440 def last_journal_id
441 if new_record?
441 if new_record?
442 nil
442 nil
443 else
443 else
444 journals.first(:order => "#{Journal.table_name}.id DESC").try(:id)
444 journals.first(:order => "#{Journal.table_name}.id DESC").try(:id)
445 end
445 end
446 end
446 end
447
447
448 # Return true if the issue is closed, otherwise false
448 # Return true if the issue is closed, otherwise false
449 def closed?
449 def closed?
450 self.status.is_closed?
450 self.status.is_closed?
451 end
451 end
452
452
453 # Return true if the issue is being reopened
453 # Return true if the issue is being reopened
454 def reopened?
454 def reopened?
455 if !new_record? && status_id_changed?
455 if !new_record? && status_id_changed?
456 status_was = IssueStatus.find_by_id(status_id_was)
456 status_was = IssueStatus.find_by_id(status_id_was)
457 status_new = IssueStatus.find_by_id(status_id)
457 status_new = IssueStatus.find_by_id(status_id)
458 if status_was && status_new && status_was.is_closed? && !status_new.is_closed?
458 if status_was && status_new && status_was.is_closed? && !status_new.is_closed?
459 return true
459 return true
460 end
460 end
461 end
461 end
462 false
462 false
463 end
463 end
464
464
465 # Return true if the issue is being closed
465 # Return true if the issue is being closed
466 def closing?
466 def closing?
467 if !new_record? && status_id_changed?
467 if !new_record? && status_id_changed?
468 status_was = IssueStatus.find_by_id(status_id_was)
468 status_was = IssueStatus.find_by_id(status_id_was)
469 status_new = IssueStatus.find_by_id(status_id)
469 status_new = IssueStatus.find_by_id(status_id)
470 if status_was && status_new && !status_was.is_closed? && status_new.is_closed?
470 if status_was && status_new && !status_was.is_closed? && status_new.is_closed?
471 return true
471 return true
472 end
472 end
473 end
473 end
474 false
474 false
475 end
475 end
476
476
477 # Returns true if the issue is overdue
477 # Returns true if the issue is overdue
478 def overdue?
478 def overdue?
479 !due_date.nil? && (due_date < Date.today) && !status.is_closed?
479 !due_date.nil? && (due_date < Date.today) && !status.is_closed?
480 end
480 end
481
481
482 # Is the amount of work done less than it should for the due date
482 # Is the amount of work done less than it should for the due date
483 def behind_schedule?
483 def behind_schedule?
484 return false if start_date.nil? || due_date.nil?
484 return false if start_date.nil? || due_date.nil?
485 done_date = start_date + ((due_date - start_date+1)* done_ratio/100).floor
485 done_date = start_date + ((due_date - start_date+1)* done_ratio/100).floor
486 return done_date <= Date.today
486 return done_date <= Date.today
487 end
487 end
488
488
489 # Does this issue have children?
489 # Does this issue have children?
490 def children?
490 def children?
491 !leaf?
491 !leaf?
492 end
492 end
493
493
494 # Users the issue can be assigned to
494 # Users the issue can be assigned to
495 def assignable_users
495 def assignable_users
496 users = project.assignable_users
496 users = project.assignable_users
497 users << author if author
497 users << author if author
498 users << assigned_to if assigned_to
498 users << assigned_to if assigned_to
499 users.uniq.sort
499 users.uniq.sort
500 end
500 end
501
501
502 # Versions that the issue can be assigned to
502 # Versions that the issue can be assigned to
503 def assignable_versions
503 def assignable_versions
504 @assignable_versions ||= (project.shared_versions.open + [Version.find_by_id(fixed_version_id_was)]).compact.uniq.sort
504 @assignable_versions ||= (project.shared_versions.open + [Version.find_by_id(fixed_version_id_was)]).compact.uniq.sort
505 end
505 end
506
506
507 # Returns true if this issue is blocked by another issue that is still open
507 # Returns true if this issue is blocked by another issue that is still open
508 def blocked?
508 def blocked?
509 !relations_to.detect {|ir| ir.relation_type == 'blocks' && !ir.issue_from.closed?}.nil?
509 !relations_to.detect {|ir| ir.relation_type == 'blocks' && !ir.issue_from.closed?}.nil?
510 end
510 end
511
511
512 # Returns an array of statuses that user is able to apply
512 # Returns an array of statuses that user is able to apply
513 def new_statuses_allowed_to(user=User.current, include_default=false)
513 def new_statuses_allowed_to(user=User.current, include_default=false)
514 if new_record? && @copied_from
514 if new_record? && @copied_from
515 [IssueStatus.default, @copied_from.status].compact.uniq.sort
515 [IssueStatus.default, @copied_from.status].compact.uniq.sort
516 else
516 else
517 initial_status = nil
517 initial_status = nil
518 if new_record?
518 if new_record?
519 initial_status = IssueStatus.default
519 initial_status = IssueStatus.default
520 elsif status_id_was
520 elsif status_id_was
521 initial_status = IssueStatus.find_by_id(status_id_was)
521 initial_status = IssueStatus.find_by_id(status_id_was)
522 end
522 end
523 initial_status ||= status
523 initial_status ||= status
524
524
525 statuses = initial_status.find_new_statuses_allowed_to(
525 statuses = initial_status.find_new_statuses_allowed_to(
526 user.admin ? Role.all : user.roles_for_project(project),
526 user.admin ? Role.all : user.roles_for_project(project),
527 tracker,
527 tracker,
528 author == user,
528 author == user,
529 assigned_to_id_changed? ? assigned_to_id_was == user.id : assigned_to_id == user.id
529 assigned_to_id_changed? ? assigned_to_id_was == user.id : assigned_to_id == user.id
530 )
530 )
531 statuses << initial_status unless statuses.empty?
531 statuses << initial_status unless statuses.empty?
532 statuses << IssueStatus.default if include_default
532 statuses << IssueStatus.default if include_default
533 statuses = statuses.compact.uniq.sort
533 statuses = statuses.compact.uniq.sort
534 blocked? ? statuses.reject {|s| s.is_closed?} : statuses
534 blocked? ? statuses.reject {|s| s.is_closed?} : statuses
535 end
535 end
536 end
536 end
537
537
538 def assigned_to_was
538 def assigned_to_was
539 if assigned_to_id_changed? && assigned_to_id_was.present?
539 if assigned_to_id_changed? && assigned_to_id_was.present?
540 @assigned_to_was ||= User.find_by_id(assigned_to_id_was)
540 @assigned_to_was ||= User.find_by_id(assigned_to_id_was)
541 end
541 end
542 end
542 end
543
543
544 # Returns the mail adresses of users that should be notified
544 # Returns the mail adresses of users that should be notified
545 def recipients
545 def recipients
546 notified = []
546 notified = []
547 # Author and assignee are always notified unless they have been
547 # Author and assignee are always notified unless they have been
548 # locked or don't want to be notified
548 # locked or don't want to be notified
549 notified << author if author
549 notified << author if author
550 if assigned_to
550 if assigned_to
551 notified += (assigned_to.is_a?(Group) ? assigned_to.users : [assigned_to])
551 notified += (assigned_to.is_a?(Group) ? assigned_to.users : [assigned_to])
552 end
552 end
553 if assigned_to_was
553 if assigned_to_was
554 notified += (assigned_to_was.is_a?(Group) ? assigned_to_was.users : [assigned_to_was])
554 notified += (assigned_to_was.is_a?(Group) ? assigned_to_was.users : [assigned_to_was])
555 end
555 end
556 notified = notified.select {|u| u.active? && u.notify_about?(self)}
556 notified = notified.select {|u| u.active? && u.notify_about?(self)}
557
557
558 notified += project.notified_users
558 notified += project.notified_users
559 notified.uniq!
559 notified.uniq!
560 # Remove users that can not view the issue
560 # Remove users that can not view the issue
561 notified.reject! {|user| !visible?(user)}
561 notified.reject! {|user| !visible?(user)}
562 notified.collect(&:mail)
562 notified.collect(&:mail)
563 end
563 end
564
564
565 # Returns the number of hours spent on this issue
565 # Returns the number of hours spent on this issue
566 def spent_hours
566 def spent_hours
567 @spent_hours ||= time_entries.sum(:hours) || 0
567 @spent_hours ||= time_entries.sum(:hours) || 0
568 end
568 end
569
569
570 # Returns the total number of hours spent on this issue and its descendants
570 # Returns the total number of hours spent on this issue and its descendants
571 #
571 #
572 # Example:
572 # Example:
573 # spent_hours => 0.0
573 # spent_hours => 0.0
574 # spent_hours => 50.2
574 # spent_hours => 50.2
575 def total_spent_hours
575 def total_spent_hours
576 @total_spent_hours ||= self_and_descendants.sum("#{TimeEntry.table_name}.hours",
576 @total_spent_hours ||= self_and_descendants.sum("#{TimeEntry.table_name}.hours",
577 :joins => "LEFT JOIN #{TimeEntry.table_name} ON #{TimeEntry.table_name}.issue_id = #{Issue.table_name}.id").to_f || 0.0
577 :joins => "LEFT JOIN #{TimeEntry.table_name} ON #{TimeEntry.table_name}.issue_id = #{Issue.table_name}.id").to_f || 0.0
578 end
578 end
579
579
580 def relations
580 def relations
581 @relations ||= (relations_from + relations_to).sort
581 @relations ||= (relations_from + relations_to).sort
582 end
582 end
583
583
584 # Preloads relations for a collection of issues
584 # Preloads relations for a collection of issues
585 def self.load_relations(issues)
585 def self.load_relations(issues)
586 if issues.any?
586 if issues.any?
587 relations = IssueRelation.all(:conditions => ["issue_from_id IN (:ids) OR issue_to_id IN (:ids)", {:ids => issues.map(&:id)}])
587 relations = IssueRelation.all(:conditions => ["issue_from_id IN (:ids) OR issue_to_id IN (:ids)", {:ids => issues.map(&:id)}])
588 issues.each do |issue|
588 issues.each do |issue|
589 issue.instance_variable_set "@relations", relations.select {|r| r.issue_from_id == issue.id || r.issue_to_id == issue.id}
589 issue.instance_variable_set "@relations", relations.select {|r| r.issue_from_id == issue.id || r.issue_to_id == issue.id}
590 end
590 end
591 end
591 end
592 end
592 end
593
593
594 # Preloads visible spent time for a collection of issues
594 # Preloads visible spent time for a collection of issues
595 def self.load_visible_spent_hours(issues, user=User.current)
595 def self.load_visible_spent_hours(issues, user=User.current)
596 if issues.any?
596 if issues.any?
597 hours_by_issue_id = TimeEntry.visible(user).sum(:hours, :group => :issue_id)
597 hours_by_issue_id = TimeEntry.visible(user).sum(:hours, :group => :issue_id)
598 issues.each do |issue|
598 issues.each do |issue|
599 issue.instance_variable_set "@spent_hours", (hours_by_issue_id[issue.id] || 0)
599 issue.instance_variable_set "@spent_hours", (hours_by_issue_id[issue.id] || 0)
600 end
600 end
601 end
601 end
602 end
602 end
603
603
604 # Finds an issue relation given its id.
604 # Finds an issue relation given its id.
605 def find_relation(relation_id)
605 def find_relation(relation_id)
606 IssueRelation.find(relation_id, :conditions => ["issue_to_id = ? OR issue_from_id = ?", id, id])
606 IssueRelation.find(relation_id, :conditions => ["issue_to_id = ? OR issue_from_id = ?", id, id])
607 end
607 end
608
608
609 def all_dependent_issues(except=[])
609 def all_dependent_issues(except=[])
610 except << self
610 except << self
611 dependencies = []
611 dependencies = []
612 relations_from.each do |relation|
612 relations_from.each do |relation|
613 if relation.issue_to && !except.include?(relation.issue_to)
613 if relation.issue_to && !except.include?(relation.issue_to)
614 dependencies << relation.issue_to
614 dependencies << relation.issue_to
615 dependencies += relation.issue_to.all_dependent_issues(except)
615 dependencies += relation.issue_to.all_dependent_issues(except)
616 end
616 end
617 end
617 end
618 dependencies
618 dependencies
619 end
619 end
620
620
621 # Returns an array of issues that duplicate this one
621 # Returns an array of issues that duplicate this one
622 def duplicates
622 def duplicates
623 relations_to.select {|r| r.relation_type == IssueRelation::TYPE_DUPLICATES}.collect {|r| r.issue_from}
623 relations_to.select {|r| r.relation_type == IssueRelation::TYPE_DUPLICATES}.collect {|r| r.issue_from}
624 end
624 end
625
625
626 # Returns the due date or the target due date if any
626 # Returns the due date or the target due date if any
627 # Used on gantt chart
627 # Used on gantt chart
628 def due_before
628 def due_before
629 due_date || (fixed_version ? fixed_version.effective_date : nil)
629 due_date || (fixed_version ? fixed_version.effective_date : nil)
630 end
630 end
631
631
632 # Returns the time scheduled for this issue.
632 # Returns the time scheduled for this issue.
633 #
633 #
634 # Example:
634 # Example:
635 # Start Date: 2/26/09, End Date: 3/04/09
635 # Start Date: 2/26/09, End Date: 3/04/09
636 # duration => 6
636 # duration => 6
637 def duration
637 def duration
638 (start_date && due_date) ? due_date - start_date : 0
638 (start_date && due_date) ? due_date - start_date : 0
639 end
639 end
640
640
641 def soonest_start
641 def soonest_start
642 @soonest_start ||= (
642 @soonest_start ||= (
643 relations_to.collect{|relation| relation.successor_soonest_start} +
643 relations_to.collect{|relation| relation.successor_soonest_start} +
644 ancestors.collect(&:soonest_start)
644 ancestors.collect(&:soonest_start)
645 ).compact.max
645 ).compact.max
646 end
646 end
647
647
648 def reschedule_after(date)
648 def reschedule_after(date)
649 return if date.nil?
649 return if date.nil?
650 if leaf?
650 if leaf?
651 if start_date.nil? || start_date < date
651 if start_date.nil? || start_date < date
652 self.start_date, self.due_date = date, date + duration
652 self.start_date, self.due_date = date, date + duration
653 begin
653 begin
654 save
654 save
655 rescue ActiveRecord::StaleObjectError
655 rescue ActiveRecord::StaleObjectError
656 reload
656 reload
657 self.start_date, self.due_date = date, date + duration
657 self.start_date, self.due_date = date, date + duration
658 save
658 save
659 end
659 end
660 end
660 end
661 else
661 else
662 leaves.each do |leaf|
662 leaves.each do |leaf|
663 leaf.reschedule_after(date)
663 leaf.reschedule_after(date)
664 end
664 end
665 end
665 end
666 end
666 end
667
667
668 def <=>(issue)
668 def <=>(issue)
669 if issue.nil?
669 if issue.nil?
670 -1
670 -1
671 elsif root_id != issue.root_id
671 elsif root_id != issue.root_id
672 (root_id || 0) <=> (issue.root_id || 0)
672 (root_id || 0) <=> (issue.root_id || 0)
673 else
673 else
674 (lft || 0) <=> (issue.lft || 0)
674 (lft || 0) <=> (issue.lft || 0)
675 end
675 end
676 end
676 end
677
677
678 def to_s
678 def to_s
679 "#{tracker} ##{id}: #{subject}"
679 "#{tracker} ##{id}: #{subject}"
680 end
680 end
681
681
682 # Returns a string of css classes that apply to the issue
682 # Returns a string of css classes that apply to the issue
683 def css_classes
683 def css_classes
684 s = "issue status-#{status.position} priority-#{priority.position}"
684 s = "issue status-#{status.position} priority-#{priority.position}"
685 s << ' closed' if closed?
685 s << ' closed' if closed?
686 s << ' overdue' if overdue?
686 s << ' overdue' if overdue?
687 s << ' child' if child?
687 s << ' child' if child?
688 s << ' parent' unless leaf?
688 s << ' parent' unless leaf?
689 s << ' private' if is_private?
689 s << ' private' if is_private?
690 s << ' created-by-me' if User.current.logged? && author_id == User.current.id
690 s << ' created-by-me' if User.current.logged? && author_id == User.current.id
691 s << ' assigned-to-me' if User.current.logged? && assigned_to_id == User.current.id
691 s << ' assigned-to-me' if User.current.logged? && assigned_to_id == User.current.id
692 s
692 s
693 end
693 end
694
694
695 # Saves an issue and a time_entry from the parameters
695 # Saves an issue and a time_entry from the parameters
696 def save_issue_with_child_records(params, existing_time_entry=nil)
696 def save_issue_with_child_records(params, existing_time_entry=nil)
697 Issue.transaction do
697 Issue.transaction do
698 if params[:time_entry] && (params[:time_entry][:hours].present? || params[:time_entry][:comments].present?) && User.current.allowed_to?(:log_time, project)
698 if params[:time_entry] && (params[:time_entry][:hours].present? || params[:time_entry][:comments].present?) && User.current.allowed_to?(:log_time, project)
699 @time_entry = existing_time_entry || TimeEntry.new
699 @time_entry = existing_time_entry || TimeEntry.new
700 @time_entry.project = project
700 @time_entry.project = project
701 @time_entry.issue = self
701 @time_entry.issue = self
702 @time_entry.user = User.current
702 @time_entry.user = User.current
703 @time_entry.spent_on = User.current.today
703 @time_entry.spent_on = User.current.today
704 @time_entry.attributes = params[:time_entry]
704 @time_entry.attributes = params[:time_entry]
705 self.time_entries << @time_entry
705 self.time_entries << @time_entry
706 end
706 end
707
707
708 # TODO: Rename hook
708 # TODO: Rename hook
709 Redmine::Hook.call_hook(:controller_issues_edit_before_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
709 Redmine::Hook.call_hook(:controller_issues_edit_before_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
710 if save
710 if save
711 # TODO: Rename hook
711 # TODO: Rename hook
712 Redmine::Hook.call_hook(:controller_issues_edit_after_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
712 Redmine::Hook.call_hook(:controller_issues_edit_after_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
713 else
713 else
714 raise ActiveRecord::Rollback
714 raise ActiveRecord::Rollback
715 end
715 end
716 end
716 end
717 end
717 end
718
718
719 # Unassigns issues from +version+ if it's no longer shared with issue's project
719 # Unassigns issues from +version+ if it's no longer shared with issue's project
720 def self.update_versions_from_sharing_change(version)
720 def self.update_versions_from_sharing_change(version)
721 # Update issues assigned to the version
721 # Update issues assigned to the version
722 update_versions(["#{Issue.table_name}.fixed_version_id = ?", version.id])
722 update_versions(["#{Issue.table_name}.fixed_version_id = ?", version.id])
723 end
723 end
724
724
725 # Unassigns issues from versions that are no longer shared
725 # Unassigns issues from versions that are no longer shared
726 # after +project+ was moved
726 # after +project+ was moved
727 def self.update_versions_from_hierarchy_change(project)
727 def self.update_versions_from_hierarchy_change(project)
728 moved_project_ids = project.self_and_descendants.reload.collect(&:id)
728 moved_project_ids = project.self_and_descendants.reload.collect(&:id)
729 # Update issues of the moved projects and issues assigned to a version of a moved project
729 # Update issues of the moved projects and issues assigned to a version of a moved project
730 Issue.update_versions(["#{Version.table_name}.project_id IN (?) OR #{Issue.table_name}.project_id IN (?)", moved_project_ids, moved_project_ids])
730 Issue.update_versions(["#{Version.table_name}.project_id IN (?) OR #{Issue.table_name}.project_id IN (?)", moved_project_ids, moved_project_ids])
731 end
731 end
732
732
733 def parent_issue_id=(arg)
733 def parent_issue_id=(arg)
734 parent_issue_id = arg.blank? ? nil : arg.to_i
734 parent_issue_id = arg.blank? ? nil : arg.to_i
735 if parent_issue_id && @parent_issue = Issue.find_by_id(parent_issue_id)
735 if parent_issue_id && @parent_issue = Issue.find_by_id(parent_issue_id)
736 @parent_issue.id
736 @parent_issue.id
737 else
737 else
738 @parent_issue = nil
738 @parent_issue = nil
739 nil
739 nil
740 end
740 end
741 end
741 end
742
742
743 def parent_issue_id
743 def parent_issue_id
744 if instance_variable_defined? :@parent_issue
744 if instance_variable_defined? :@parent_issue
745 @parent_issue.nil? ? nil : @parent_issue.id
745 @parent_issue.nil? ? nil : @parent_issue.id
746 else
746 else
747 parent_id
747 parent_id
748 end
748 end
749 end
749 end
750
750
751 # Extracted from the ReportsController.
751 # Extracted from the ReportsController.
752 def self.by_tracker(project)
752 def self.by_tracker(project)
753 count_and_group_by(:project => project,
753 count_and_group_by(:project => project,
754 :field => 'tracker_id',
754 :field => 'tracker_id',
755 :joins => Tracker.table_name)
755 :joins => Tracker.table_name)
756 end
756 end
757
757
758 def self.by_version(project)
758 def self.by_version(project)
759 count_and_group_by(:project => project,
759 count_and_group_by(:project => project,
760 :field => 'fixed_version_id',
760 :field => 'fixed_version_id',
761 :joins => Version.table_name)
761 :joins => Version.table_name)
762 end
762 end
763
763
764 def self.by_priority(project)
764 def self.by_priority(project)
765 count_and_group_by(:project => project,
765 count_and_group_by(:project => project,
766 :field => 'priority_id',
766 :field => 'priority_id',
767 :joins => IssuePriority.table_name)
767 :joins => IssuePriority.table_name)
768 end
768 end
769
769
770 def self.by_category(project)
770 def self.by_category(project)
771 count_and_group_by(:project => project,
771 count_and_group_by(:project => project,
772 :field => 'category_id',
772 :field => 'category_id',
773 :joins => IssueCategory.table_name)
773 :joins => IssueCategory.table_name)
774 end
774 end
775
775
776 def self.by_assigned_to(project)
776 def self.by_assigned_to(project)
777 count_and_group_by(:project => project,
777 count_and_group_by(:project => project,
778 :field => 'assigned_to_id',
778 :field => 'assigned_to_id',
779 :joins => User.table_name)
779 :joins => User.table_name)
780 end
780 end
781
781
782 def self.by_author(project)
782 def self.by_author(project)
783 count_and_group_by(:project => project,
783 count_and_group_by(:project => project,
784 :field => 'author_id',
784 :field => 'author_id',
785 :joins => User.table_name)
785 :joins => User.table_name)
786 end
786 end
787
787
788 def self.by_subproject(project)
788 def self.by_subproject(project)
789 ActiveRecord::Base.connection.select_all("select s.id as status_id,
789 ActiveRecord::Base.connection.select_all("select s.id as status_id,
790 s.is_closed as closed,
790 s.is_closed as closed,
791 #{Issue.table_name}.project_id as project_id,
791 #{Issue.table_name}.project_id as project_id,
792 count(#{Issue.table_name}.id) as total
792 count(#{Issue.table_name}.id) as total
793 from
793 from
794 #{Issue.table_name}, #{Project.table_name}, #{IssueStatus.table_name} s
794 #{Issue.table_name}, #{Project.table_name}, #{IssueStatus.table_name} s
795 where
795 where
796 #{Issue.table_name}.status_id=s.id
796 #{Issue.table_name}.status_id=s.id
797 and #{Issue.table_name}.project_id = #{Project.table_name}.id
797 and #{Issue.table_name}.project_id = #{Project.table_name}.id
798 and #{visible_condition(User.current, :project => project, :with_subprojects => true)}
798 and #{visible_condition(User.current, :project => project, :with_subprojects => true)}
799 and #{Issue.table_name}.project_id <> #{project.id}
799 and #{Issue.table_name}.project_id <> #{project.id}
800 group by s.id, s.is_closed, #{Issue.table_name}.project_id") if project.descendants.active.any?
800 group by s.id, s.is_closed, #{Issue.table_name}.project_id") if project.descendants.active.any?
801 end
801 end
802 # End ReportsController extraction
802 # End ReportsController extraction
803
803
804 # Returns an array of projects that user can assign the issue to
804 # Returns an array of projects that user can assign the issue to
805 def allowed_target_projects(user=User.current)
805 def allowed_target_projects(user=User.current)
806 if new_record?
806 if new_record?
807 Project.all(:conditions => Project.allowed_to_condition(user, :add_issues))
807 Project.all(:conditions => Project.allowed_to_condition(user, :add_issues))
808 else
808 else
809 self.class.allowed_target_projects_on_move(user)
809 self.class.allowed_target_projects_on_move(user)
810 end
810 end
811 end
811 end
812
812
813 # Returns an array of projects that user can move issues to
813 # Returns an array of projects that user can move issues to
814 def self.allowed_target_projects_on_move(user=User.current)
814 def self.allowed_target_projects_on_move(user=User.current)
815 Project.all(:conditions => Project.allowed_to_condition(user, :move_issues))
815 Project.all(:conditions => Project.allowed_to_condition(user, :move_issues))
816 end
816 end
817
817
818 private
818 private
819
819
820 def after_project_change
820 def after_project_change
821 # Update project_id on related time entries
821 # Update project_id on related time entries
822 TimeEntry.update_all(["project_id = ?", project_id], {:issue_id => id})
822 TimeEntry.update_all(["project_id = ?", project_id], {:issue_id => id})
823
823
824 # Delete issue relations
824 # Delete issue relations
825 unless Setting.cross_project_issue_relations?
825 unless Setting.cross_project_issue_relations?
826 relations_from.clear
826 relations_from.clear
827 relations_to.clear
827 relations_to.clear
828 end
828 end
829
829
830 # Move subtasks
830 # Move subtasks
831 children.each do |child|
831 children.each do |child|
832 # Change project and keep project
832 # Change project and keep project
833 child.send :project=, project, true
833 child.send :project=, project, true
834 unless child.save
834 unless child.save
835 raise ActiveRecord::Rollback
835 raise ActiveRecord::Rollback
836 end
836 end
837 end
837 end
838 end
838 end
839
839
840 def update_nested_set_attributes
840 def update_nested_set_attributes
841 if root_id.nil?
841 if root_id.nil?
842 # issue was just created
842 # issue was just created
843 self.root_id = (@parent_issue.nil? ? id : @parent_issue.root_id)
843 self.root_id = (@parent_issue.nil? ? id : @parent_issue.root_id)
844 set_default_left_and_right
844 set_default_left_and_right
845 Issue.update_all("root_id = #{root_id}, lft = #{lft}, rgt = #{rgt}", ["id = ?", id])
845 Issue.update_all("root_id = #{root_id}, lft = #{lft}, rgt = #{rgt}", ["id = ?", id])
846 if @parent_issue
846 if @parent_issue
847 move_to_child_of(@parent_issue)
847 move_to_child_of(@parent_issue)
848 end
848 end
849 reload
849 reload
850 elsif parent_issue_id != parent_id
850 elsif parent_issue_id != parent_id
851 former_parent_id = parent_id
851 former_parent_id = parent_id
852 # moving an existing issue
852 # moving an existing issue
853 if @parent_issue && @parent_issue.root_id == root_id
853 if @parent_issue && @parent_issue.root_id == root_id
854 # inside the same tree
854 # inside the same tree
855 move_to_child_of(@parent_issue)
855 move_to_child_of(@parent_issue)
856 else
856 else
857 # to another tree
857 # to another tree
858 unless root?
858 unless root?
859 move_to_right_of(root)
859 move_to_right_of(root)
860 reload
860 reload
861 end
861 end
862 old_root_id = root_id
862 old_root_id = root_id
863 self.root_id = (@parent_issue.nil? ? id : @parent_issue.root_id )
863 self.root_id = (@parent_issue.nil? ? id : @parent_issue.root_id )
864 target_maxright = nested_set_scope.maximum(right_column_name) || 0
864 target_maxright = nested_set_scope.maximum(right_column_name) || 0
865 offset = target_maxright + 1 - lft
865 offset = target_maxright + 1 - lft
866 Issue.update_all("root_id = #{root_id}, lft = lft + #{offset}, rgt = rgt + #{offset}",
866 Issue.update_all("root_id = #{root_id}, lft = lft + #{offset}, rgt = rgt + #{offset}",
867 ["root_id = ? AND lft >= ? AND rgt <= ? ", old_root_id, lft, rgt])
867 ["root_id = ? AND lft >= ? AND rgt <= ? ", old_root_id, lft, rgt])
868 self[left_column_name] = lft + offset
868 self[left_column_name] = lft + offset
869 self[right_column_name] = rgt + offset
869 self[right_column_name] = rgt + offset
870 if @parent_issue
870 if @parent_issue
871 move_to_child_of(@parent_issue)
871 move_to_child_of(@parent_issue)
872 end
872 end
873 end
873 end
874 reload
874 reload
875 # delete invalid relations of all descendants
875 # delete invalid relations of all descendants
876 self_and_descendants.each do |issue|
876 self_and_descendants.each do |issue|
877 issue.relations.each do |relation|
877 issue.relations.each do |relation|
878 relation.destroy unless relation.valid?
878 relation.destroy unless relation.valid?
879 end
879 end
880 end
880 end
881 # update former parent
881 # update former parent
882 recalculate_attributes_for(former_parent_id) if former_parent_id
882 recalculate_attributes_for(former_parent_id) if former_parent_id
883 end
883 end
884 remove_instance_variable(:@parent_issue) if instance_variable_defined?(:@parent_issue)
884 remove_instance_variable(:@parent_issue) if instance_variable_defined?(:@parent_issue)
885 end
885 end
886
886
887 def update_parent_attributes
887 def update_parent_attributes
888 recalculate_attributes_for(parent_id) if parent_id
888 recalculate_attributes_for(parent_id) if parent_id
889 end
889 end
890
890
891 def recalculate_attributes_for(issue_id)
891 def recalculate_attributes_for(issue_id)
892 if issue_id && p = Issue.find_by_id(issue_id)
892 if issue_id && p = Issue.find_by_id(issue_id)
893 # priority = highest priority of children
893 # priority = highest priority of children
894 if priority_position = p.children.maximum("#{IssuePriority.table_name}.position", :joins => :priority)
894 if priority_position = p.children.maximum("#{IssuePriority.table_name}.position", :joins => :priority)
895 p.priority = IssuePriority.find_by_position(priority_position)
895 p.priority = IssuePriority.find_by_position(priority_position)
896 end
896 end
897
897
898 # start/due dates = lowest/highest dates of children
898 # start/due dates = lowest/highest dates of children
899 p.start_date = p.children.minimum(:start_date)
899 p.start_date = p.children.minimum(:start_date)
900 p.due_date = p.children.maximum(:due_date)
900 p.due_date = p.children.maximum(:due_date)
901 if p.start_date && p.due_date && p.due_date < p.start_date
901 if p.start_date && p.due_date && p.due_date < p.start_date
902 p.start_date, p.due_date = p.due_date, p.start_date
902 p.start_date, p.due_date = p.due_date, p.start_date
903 end
903 end
904
904
905 # done ratio = weighted average ratio of leaves
905 # done ratio = weighted average ratio of leaves
906 unless Issue.use_status_for_done_ratio? && p.status && p.status.default_done_ratio
906 unless Issue.use_status_for_done_ratio? && p.status && p.status.default_done_ratio
907 leaves_count = p.leaves.count
907 leaves_count = p.leaves.count
908 if leaves_count > 0
908 if leaves_count > 0
909 average = p.leaves.average(:estimated_hours).to_f
909 average = p.leaves.average(:estimated_hours).to_f
910 if average == 0
910 if average == 0
911 average = 1
911 average = 1
912 end
912 end
913 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
913 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
914 progress = done / (average * leaves_count)
914 progress = done / (average * leaves_count)
915 p.done_ratio = progress.round
915 p.done_ratio = progress.round
916 end
916 end
917 end
917 end
918
918
919 # estimate = sum of leaves estimates
919 # estimate = sum of leaves estimates
920 p.estimated_hours = p.leaves.sum(:estimated_hours).to_f
920 p.estimated_hours = p.leaves.sum(:estimated_hours).to_f
921 p.estimated_hours = nil if p.estimated_hours == 0.0
921 p.estimated_hours = nil if p.estimated_hours == 0.0
922
922
923 # ancestors will be recursively updated
923 # ancestors will be recursively updated
924 p.save(false)
924 p.save(false)
925 end
925 end
926 end
926 end
927
927
928 # Update issues so their versions are not pointing to a
928 # Update issues so their versions are not pointing to a
929 # fixed_version that is not shared with the issue's project
929 # fixed_version that is not shared with the issue's project
930 def self.update_versions(conditions=nil)
930 def self.update_versions(conditions=nil)
931 # Only need to update issues with a fixed_version from
931 # Only need to update issues with a fixed_version from
932 # a different project and that is not systemwide shared
932 # a different project and that is not systemwide shared
933 Issue.scoped(:conditions => conditions).all(
933 Issue.scoped(:conditions => conditions).all(
934 :conditions => "#{Issue.table_name}.fixed_version_id IS NOT NULL" +
934 :conditions => "#{Issue.table_name}.fixed_version_id IS NOT NULL" +
935 " AND #{Issue.table_name}.project_id <> #{Version.table_name}.project_id" +
935 " AND #{Issue.table_name}.project_id <> #{Version.table_name}.project_id" +
936 " AND #{Version.table_name}.sharing <> 'system'",
936 " AND #{Version.table_name}.sharing <> 'system'",
937 :include => [:project, :fixed_version]
937 :include => [:project, :fixed_version]
938 ).each do |issue|
938 ).each do |issue|
939 next if issue.project.nil? || issue.fixed_version.nil?
939 next if issue.project.nil? || issue.fixed_version.nil?
940 unless issue.project.shared_versions.include?(issue.fixed_version)
940 unless issue.project.shared_versions.include?(issue.fixed_version)
941 issue.init_journal(User.current)
941 issue.init_journal(User.current)
942 issue.fixed_version = nil
942 issue.fixed_version = nil
943 issue.save
943 issue.save
944 end
944 end
945 end
945 end
946 end
946 end
947
947
948 # Callback on attachment deletion
948 # Callback on attachment deletion
949 def attachment_added(obj)
949 def attachment_added(obj)
950 if @current_journal && !obj.new_record?
950 if @current_journal && !obj.new_record?
951 @current_journal.details << JournalDetail.new(:property => 'attachment', :prop_key => obj.id, :value => obj.filename)
951 @current_journal.details << JournalDetail.new(:property => 'attachment', :prop_key => obj.id, :value => obj.filename)
952 end
952 end
953 end
953 end
954
954
955 # Callback on attachment deletion
955 # Callback on attachment deletion
956 def attachment_removed(obj)
956 def attachment_removed(obj)
957 if @current_journal && !obj.new_record?
957 if @current_journal && !obj.new_record?
958 @current_journal.details << JournalDetail.new(:property => 'attachment', :prop_key => obj.id, :old_value => obj.filename)
958 @current_journal.details << JournalDetail.new(:property => 'attachment', :prop_key => obj.id, :old_value => obj.filename)
959 @current_journal.save
959 @current_journal.save
960 end
960 end
961 end
961 end
962
962
963 # Default assignment based on category
963 # Default assignment based on category
964 def default_assign
964 def default_assign
965 if assigned_to.nil? && category && category.assigned_to
965 if assigned_to.nil? && category && category.assigned_to
966 self.assigned_to = category.assigned_to
966 self.assigned_to = category.assigned_to
967 end
967 end
968 end
968 end
969
969
970 # Updates start/due dates of following issues
970 # Updates start/due dates of following issues
971 def reschedule_following_issues
971 def reschedule_following_issues
972 if start_date_changed? || due_date_changed?
972 if start_date_changed? || due_date_changed?
973 relations_from.each do |relation|
973 relations_from.each do |relation|
974 relation.set_issue_to_dates
974 relation.set_issue_to_dates
975 end
975 end
976 end
976 end
977 end
977 end
978
978
979 # Closes duplicates if the issue is being closed
979 # Closes duplicates if the issue is being closed
980 def close_duplicates
980 def close_duplicates
981 if closing?
981 if closing?
982 duplicates.each do |duplicate|
982 duplicates.each do |duplicate|
983 # Reload is need in case the duplicate was updated by a previous duplicate
983 # Reload is need in case the duplicate was updated by a previous duplicate
984 duplicate.reload
984 duplicate.reload
985 # Don't re-close it if it's already closed
985 # Don't re-close it if it's already closed
986 next if duplicate.closed?
986 next if duplicate.closed?
987 # Same user and notes
987 # Same user and notes
988 if @current_journal
988 if @current_journal
989 duplicate.init_journal(@current_journal.user, @current_journal.notes)
989 duplicate.init_journal(@current_journal.user, @current_journal.notes)
990 end
990 end
991 duplicate.update_attribute :status, self.status
991 duplicate.update_attribute :status, self.status
992 end
992 end
993 end
993 end
994 end
994 end
995
995
996 # Saves the changes in a Journal
996 # Saves the changes in a Journal
997 # Called after_save
997 # Called after_save
998 def create_journal
998 def create_journal
999 if @current_journal
999 if @current_journal
1000 # attributes changes
1000 # attributes changes
1001 if @attributes_before_change
1001 if @attributes_before_change
1002 (Issue.column_names - %w(id root_id lft rgt lock_version created_on updated_on)).each {|c|
1002 (Issue.column_names - %w(id root_id lft rgt lock_version created_on updated_on)).each {|c|
1003 before = @attributes_before_change[c]
1003 before = @attributes_before_change[c]
1004 after = send(c)
1004 after = send(c)
1005 next if before == after || (before.blank? && after.blank?)
1005 next if before == after || (before.blank? && after.blank?)
1006 @current_journal.details << JournalDetail.new(:property => 'attr',
1006 @current_journal.details << JournalDetail.new(:property => 'attr',
1007 :prop_key => c,
1007 :prop_key => c,
1008 :old_value => before,
1008 :old_value => before,
1009 :value => after)
1009 :value => after)
1010 }
1010 }
1011 end
1011 end
1012 if @custom_values_before_change
1012 if @custom_values_before_change
1013 # custom fields changes
1013 # custom fields changes
1014 custom_field_values.each {|c|
1014 custom_field_values.each {|c|
1015 before = @custom_values_before_change[c.custom_field_id]
1015 before = @custom_values_before_change[c.custom_field_id]
1016 after = c.value
1016 after = c.value
1017 next if before == after || (before.blank? && after.blank?)
1017 next if before == after || (before.blank? && after.blank?)
1018
1018
1019 if before.is_a?(Array) || after.is_a?(Array)
1019 if before.is_a?(Array) || after.is_a?(Array)
1020 before = [before] unless before.is_a?(Array)
1020 before = [before] unless before.is_a?(Array)
1021 after = [after] unless after.is_a?(Array)
1021 after = [after] unless after.is_a?(Array)
1022
1022
1023 # values removed
1023 # values removed
1024 (before - after).reject(&:blank?).each do |value|
1024 (before - after).reject(&:blank?).each do |value|
1025 @current_journal.details << JournalDetail.new(:property => 'cf',
1025 @current_journal.details << JournalDetail.new(:property => 'cf',
1026 :prop_key => c.custom_field_id,
1026 :prop_key => c.custom_field_id,
1027 :old_value => value,
1027 :old_value => value,
1028 :value => nil)
1028 :value => nil)
1029 end
1029 end
1030 # values added
1030 # values added
1031 (after - before).reject(&:blank?).each do |value|
1031 (after - before).reject(&:blank?).each do |value|
1032 @current_journal.details << JournalDetail.new(:property => 'cf',
1032 @current_journal.details << JournalDetail.new(:property => 'cf',
1033 :prop_key => c.custom_field_id,
1033 :prop_key => c.custom_field_id,
1034 :old_value => nil,
1034 :old_value => nil,
1035 :value => value)
1035 :value => value)
1036 end
1036 end
1037 else
1037 else
1038 @current_journal.details << JournalDetail.new(:property => 'cf',
1038 @current_journal.details << JournalDetail.new(:property => 'cf',
1039 :prop_key => c.custom_field_id,
1039 :prop_key => c.custom_field_id,
1040 :old_value => before,
1040 :old_value => before,
1041 :value => after)
1041 :value => after)
1042 end
1042 end
1043 }
1043 }
1044 end
1044 end
1045 @current_journal.save
1045 @current_journal.save
1046 # reset current journal
1046 # reset current journal
1047 init_journal @current_journal.user, @current_journal.notes
1047 init_journal @current_journal.user, @current_journal.notes
1048 end
1048 end
1049 end
1049 end
1050
1050
1051 # Query generator for selecting groups of issue counts for a project
1051 # Query generator for selecting groups of issue counts for a project
1052 # based on specific criteria
1052 # based on specific criteria
1053 #
1053 #
1054 # Options
1054 # Options
1055 # * project - Project to search in.
1055 # * project - Project to search in.
1056 # * field - String. Issue field to key off of in the grouping.
1056 # * field - String. Issue field to key off of in the grouping.
1057 # * joins - String. The table name to join against.
1057 # * joins - String. The table name to join against.
1058 def self.count_and_group_by(options)
1058 def self.count_and_group_by(options)
1059 project = options.delete(:project)
1059 project = options.delete(:project)
1060 select_field = options.delete(:field)
1060 select_field = options.delete(:field)
1061 joins = options.delete(:joins)
1061 joins = options.delete(:joins)
1062
1062
1063 where = "#{Issue.table_name}.#{select_field}=j.id"
1063 where = "#{Issue.table_name}.#{select_field}=j.id"
1064
1064
1065 ActiveRecord::Base.connection.select_all("select s.id as status_id,
1065 ActiveRecord::Base.connection.select_all("select s.id as status_id,
1066 s.is_closed as closed,
1066 s.is_closed as closed,
1067 j.id as #{select_field},
1067 j.id as #{select_field},
1068 count(#{Issue.table_name}.id) as total
1068 count(#{Issue.table_name}.id) as total
1069 from
1069 from
1070 #{Issue.table_name}, #{Project.table_name}, #{IssueStatus.table_name} s, #{joins} j
1070 #{Issue.table_name}, #{Project.table_name}, #{IssueStatus.table_name} s, #{joins} j
1071 where
1071 where
1072 #{Issue.table_name}.status_id=s.id
1072 #{Issue.table_name}.status_id=s.id
1073 and #{where}
1073 and #{where}
1074 and #{Issue.table_name}.project_id=#{Project.table_name}.id
1074 and #{Issue.table_name}.project_id=#{Project.table_name}.id
1075 and #{visible_condition(User.current, :project => project)}
1075 and #{visible_condition(User.current, :project => project)}
1076 group by s.id, s.is_closed, j.id")
1076 group by s.id, s.is_closed, j.id")
1077 end
1077 end
1078 end
1078 end
@@ -1,120 +1,127
1 <h2><%= @copy ? l(:button_copy) : l(:label_bulk_edit_selected_issues) %></h2>
1 <h2><%= @copy ? l(:button_copy) : l(:label_bulk_edit_selected_issues) %></h2>
2
2
3 <ul><%= @issues.collect {|i|
3 <ul><%= @issues.collect {|i|
4 content_tag('li',
4 content_tag('li',
5 link_to(h("#{i.tracker} ##{i.id}"),
5 link_to(h("#{i.tracker} ##{i.id}"),
6 { :action => 'show', :id => i }
6 { :action => 'show', :id => i }
7 ) + h(": #{i.subject}"))
7 ) + h(": #{i.subject}"))
8 }.join("\n").html_safe %></ul>
8 }.join("\n").html_safe %></ul>
9
9
10 <% form_tag({:action => 'bulk_update'}, :id => 'bulk_edit_form') do %>
10 <% form_tag({:action => 'bulk_update'}, :id => 'bulk_edit_form') do %>
11 <%= @issues.collect {|i| hidden_field_tag('ids[]', i.id)}.join("\n").html_safe %>
11 <%= @issues.collect {|i| hidden_field_tag('ids[]', i.id)}.join("\n").html_safe %>
12 <div class="box tabular">
12 <div class="box tabular">
13 <fieldset class="attributes">
13 <fieldset class="attributes">
14 <legend><%= l(:label_change_properties) %></legend>
14 <legend><%= l(:label_change_properties) %></legend>
15
15
16 <div class="splitcontentleft">
16 <div class="splitcontentleft">
17 <% if @allowed_projects.present? %>
17 <% if @allowed_projects.present? %>
18 <p>
18 <p>
19 <label for="issue_project_id"><%= l(:field_project) %></label>
19 <label for="issue_project_id"><%= l(:field_project) %></label>
20 <%= select_tag('issue[project_id]', content_tag('option', l(:label_no_change_option), :value => '') + project_tree_options_for_select(@allowed_projects, :selected => @target_project)) %>
20 <%= select_tag('issue[project_id]', content_tag('option', l(:label_no_change_option), :value => '') + project_tree_options_for_select(@allowed_projects, :selected => @target_project)) %>
21 </p>
21 </p>
22 <%= observe_field :issue_project_id, :url => {:action => 'bulk_edit'},
22 <%= observe_field :issue_project_id, :url => {:action => 'bulk_edit'},
23 :update => 'content',
23 :update => 'content',
24 :with => "Form.serialize('bulk_edit_form')" %>
24 :with => "Form.serialize('bulk_edit_form')" %>
25 <% end %>
25 <% end %>
26 <p>
26 <p>
27 <label for="issue_tracker_id"><%= l(:field_tracker) %></label>
27 <label for="issue_tracker_id"><%= l(:field_tracker) %></label>
28 <%= select_tag('issue[tracker_id]', content_tag('option', l(:label_no_change_option), :value => '') + options_from_collection_for_select(@trackers, :id, :name)) %>
28 <%= select_tag('issue[tracker_id]', content_tag('option', l(:label_no_change_option), :value => '') + options_from_collection_for_select(@trackers, :id, :name)) %>
29 </p>
29 </p>
30 <% if @available_statuses.any? %>
30 <% if @available_statuses.any? %>
31 <p>
31 <p>
32 <label for='issue_status_id'><%= l(:field_status) %></label>
32 <label for='issue_status_id'><%= l(:field_status) %></label>
33 <%= select_tag('issue[status_id]',content_tag('option', l(:label_no_change_option), :value => '') + options_from_collection_for_select(@available_statuses, :id, :name)) %>
33 <%= select_tag('issue[status_id]',content_tag('option', l(:label_no_change_option), :value => '') + options_from_collection_for_select(@available_statuses, :id, :name)) %>
34 </p>
34 </p>
35 <% end %>
35 <% end %>
36 <p>
36 <p>
37 <label for='issue_priority_id'><%= l(:field_priority) %></label>
37 <label for='issue_priority_id'><%= l(:field_priority) %></label>
38 <%= select_tag('issue[priority_id]', content_tag('option', l(:label_no_change_option), :value => '') + options_from_collection_for_select(IssuePriority.active, :id, :name)) %>
38 <%= select_tag('issue[priority_id]', content_tag('option', l(:label_no_change_option), :value => '') + options_from_collection_for_select(IssuePriority.active, :id, :name)) %>
39 </p>
39 </p>
40 <p>
40 <p>
41 <label for='issue_assigned_to_id'><%= l(:field_assigned_to) %></label>
41 <label for='issue_assigned_to_id'><%= l(:field_assigned_to) %></label>
42 <%= select_tag('issue[assigned_to_id]', content_tag('option', l(:label_no_change_option), :value => '') +
42 <%= select_tag('issue[assigned_to_id]', content_tag('option', l(:label_no_change_option), :value => '') +
43 content_tag('option', l(:label_nobody), :value => 'none') +
43 content_tag('option', l(:label_nobody), :value => 'none') +
44 principals_options_for_select(@assignables)) %>
44 principals_options_for_select(@assignables)) %>
45 </p>
45 </p>
46 <p>
46 <p>
47 <label for='issue_category_id'><%= l(:field_category) %></label>
47 <label for='issue_category_id'><%= l(:field_category) %></label>
48 <%= select_tag('issue[category_id]', content_tag('option', l(:label_no_change_option), :value => '') +
48 <%= select_tag('issue[category_id]', content_tag('option', l(:label_no_change_option), :value => '') +
49 content_tag('option', l(:label_none), :value => 'none') +
49 content_tag('option', l(:label_none), :value => 'none') +
50 options_from_collection_for_select(@categories, :id, :name)) %>
50 options_from_collection_for_select(@categories, :id, :name)) %>
51 </p>
51 </p>
52 <p>
52 <p>
53 <label for='issue_fixed_version_id'><%= l(:field_fixed_version) %></label>
53 <label for='issue_fixed_version_id'><%= l(:field_fixed_version) %></label>
54 <%= select_tag('issue[fixed_version_id]', content_tag('option', l(:label_no_change_option), :value => '') +
54 <%= select_tag('issue[fixed_version_id]', content_tag('option', l(:label_no_change_option), :value => '') +
55 content_tag('option', l(:label_none), :value => 'none') +
55 content_tag('option', l(:label_none), :value => 'none') +
56 version_options_for_select(@versions.sort)) %>
56 version_options_for_select(@versions.sort)) %>
57 </p>
57 </p>
58
58
59 <% @custom_fields.each do |custom_field| %>
59 <% @custom_fields.each do |custom_field| %>
60 <p><label><%= h(custom_field.name) %></label> <%= custom_field_tag_for_bulk_edit('issue', custom_field, @projects) %></p>
60 <p><label><%= h(custom_field.name) %></label> <%= custom_field_tag_for_bulk_edit('issue', custom_field, @projects) %></p>
61 <% end %>
61 <% end %>
62
62
63 <% if @copy && @attachments_present %>
64 <p>
65 <label for='copy_attachments'><%= l(:label_copy_attachments) %></label>
66 <%= check_box_tag 'copy_attachments', '1', true %>
67 </p>
68 <% end %>
69
63 <%= call_hook(:view_issues_bulk_edit_details_bottom, { :issues => @issues }) %>
70 <%= call_hook(:view_issues_bulk_edit_details_bottom, { :issues => @issues }) %>
64 </div>
71 </div>
65
72
66 <div class="splitcontentright">
73 <div class="splitcontentright">
67 <% if @safe_attributes.include?('is_private') %>
74 <% if @safe_attributes.include?('is_private') %>
68 <p>
75 <p>
69 <label for='issue_is_private'><%= l(:field_is_private) %></label>
76 <label for='issue_is_private'><%= l(:field_is_private) %></label>
70 <%= select_tag('issue[is_private]', content_tag('option', l(:label_no_change_option), :value => '') +
77 <%= select_tag('issue[is_private]', content_tag('option', l(:label_no_change_option), :value => '') +
71 content_tag('option', l(:general_text_Yes), :value => '1') +
78 content_tag('option', l(:general_text_Yes), :value => '1') +
72 content_tag('option', l(:general_text_No), :value => '0')) %>
79 content_tag('option', l(:general_text_No), :value => '0')) %>
73 </p>
80 </p>
74 <% end %>
81 <% end %>
75 <% if @project && User.current.allowed_to?(:manage_subtasks, @project) %>
82 <% if @project && User.current.allowed_to?(:manage_subtasks, @project) %>
76 <p>
83 <p>
77 <label for='issue_parent_issue_id'><%= l(:field_parent_issue) %></label>
84 <label for='issue_parent_issue_id'><%= l(:field_parent_issue) %></label>
78 <%= text_field_tag 'issue[parent_issue_id]', '', :size => 10 %>
85 <%= text_field_tag 'issue[parent_issue_id]', '', :size => 10 %>
79 </p>
86 </p>
80 <div id="parent_issue_candidates" class="autocomplete"></div>
87 <div id="parent_issue_candidates" class="autocomplete"></div>
81 <%= javascript_tag "observeParentIssueField('#{auto_complete_issues_path(:project_id => @project) }')" %>
88 <%= javascript_tag "observeParentIssueField('#{auto_complete_issues_path(:project_id => @project) }')" %>
82 <% end %>
89 <% end %>
83 <p>
90 <p>
84 <label for='issue_start_date'><%= l(:field_start_date) %></label>
91 <label for='issue_start_date'><%= l(:field_start_date) %></label>
85 <%= text_field_tag 'issue[start_date]', '', :size => 10 %><%= calendar_for('issue_start_date') %>
92 <%= text_field_tag 'issue[start_date]', '', :size => 10 %><%= calendar_for('issue_start_date') %>
86 </p>
93 </p>
87 <p>
94 <p>
88 <label for='issue_due_date'><%= l(:field_due_date) %></label>
95 <label for='issue_due_date'><%= l(:field_due_date) %></label>
89 <%= text_field_tag 'issue[due_date]', '', :size => 10 %><%= calendar_for('issue_due_date') %>
96 <%= text_field_tag 'issue[due_date]', '', :size => 10 %><%= calendar_for('issue_due_date') %>
90 </p>
97 </p>
91 <% if Issue.use_field_for_done_ratio? %>
98 <% if Issue.use_field_for_done_ratio? %>
92 <p>
99 <p>
93 <label for='issue_done_ratio'><%= l(:field_done_ratio) %></label>
100 <label for='issue_done_ratio'><%= l(:field_done_ratio) %></label>
94 <%= select_tag 'issue[done_ratio]', options_for_select([[l(:label_no_change_option), '']] + (0..10).to_a.collect {|r| ["#{r*10} %", r*10] }) %>
101 <%= select_tag 'issue[done_ratio]', options_for_select([[l(:label_no_change_option), '']] + (0..10).to_a.collect {|r| ["#{r*10} %", r*10] }) %>
95 </p>
102 </p>
96 <% end %>
103 <% end %>
97 </div>
104 </div>
98
105
99 </fieldset>
106 </fieldset>
100
107
101 <fieldset><legend><%= l(:field_notes) %></legend>
108 <fieldset><legend><%= l(:field_notes) %></legend>
102 <%= text_area_tag 'notes', @notes, :cols => 60, :rows => 10, :class => 'wiki-edit' %>
109 <%= text_area_tag 'notes', @notes, :cols => 60, :rows => 10, :class => 'wiki-edit' %>
103 <%= wikitoolbar_for 'notes' %>
110 <%= wikitoolbar_for 'notes' %>
104 </fieldset>
111 </fieldset>
105 </div>
112 </div>
106
113
107 <p>
114 <p>
108 <% if @copy %>
115 <% if @copy %>
109 <%= hidden_field_tag 'copy', '1' %>
116 <%= hidden_field_tag 'copy', '1' %>
110 <%= submit_tag l(:button_copy) %>
117 <%= submit_tag l(:button_copy) %>
111 <%= submit_tag l(:button_copy_and_follow), :name => 'follow' %>
118 <%= submit_tag l(:button_copy_and_follow), :name => 'follow' %>
112 <% elsif @target_project %>
119 <% elsif @target_project %>
113 <%= submit_tag l(:button_move) %>
120 <%= submit_tag l(:button_move) %>
114 <%= submit_tag l(:button_move_and_follow), :name => 'follow' %>
121 <%= submit_tag l(:button_move_and_follow), :name => 'follow' %>
115 <% else %>
122 <% else %>
116 <%= submit_tag l(:button_submit) %>
123 <%= submit_tag l(:button_submit) %>
117 <% end %>
124 <% end %>
118 </p>
125 </p>
119
126
120 <% end %>
127 <% end %>
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now