##// END OF EJS Templates
Merged r12910 and r12911 (#16091)....
Jean-Philippe Lang -
r12645:805debddd0b5
parent child
Show More
@@ -1,481 +1,484
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2014 Jean-Philippe Lang
2 # Copyright (C) 2006-2014 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, :update_form]
24 before_filter :find_project, :only => [:new, :create, :update_form]
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, :update_form]
28 before_filter :build_new_issue_from_params, :only => [:new, :create, :update_form]
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 include Redmine::Export::PDF
53 include Redmine::Export::PDF
54
54
55 def index
55 def index
56 retrieve_query
56 retrieve_query
57 sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
57 sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
58 sort_update(@query.sortable_columns)
58 sort_update(@query.sortable_columns)
59 @query.sort_criteria = sort_criteria.to_a
59 @query.sort_criteria = sort_criteria.to_a
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 if params[:columns] == 'all'
66 @query.column_names = @query.available_inline_columns.map(&:name)
67 end
65 when 'atom'
68 when 'atom'
66 @limit = Setting.feeds_limit.to_i
69 @limit = Setting.feeds_limit.to_i
67 when 'xml', 'json'
70 when 'xml', 'json'
68 @offset, @limit = api_offset_and_limit
71 @offset, @limit = api_offset_and_limit
69 else
72 else
70 @limit = per_page_option
73 @limit = per_page_option
71 end
74 end
72
75
73 @issue_count = @query.issue_count
76 @issue_count = @query.issue_count
74 @issue_pages = Paginator.new @issue_count, @limit, params['page']
77 @issue_pages = Paginator.new @issue_count, @limit, params['page']
75 @offset ||= @issue_pages.offset
78 @offset ||= @issue_pages.offset
76 @issues = @query.issues(:include => [:assigned_to, :tracker, :priority, :category, :fixed_version],
79 @issues = @query.issues(:include => [:assigned_to, :tracker, :priority, :category, :fixed_version],
77 :order => sort_clause,
80 :order => sort_clause,
78 :offset => @offset,
81 :offset => @offset,
79 :limit => @limit)
82 :limit => @limit)
80 @issue_count_by_group = @query.issue_count_by_group
83 @issue_count_by_group = @query.issue_count_by_group
81
84
82 respond_to do |format|
85 respond_to do |format|
83 format.html { render :template => 'issues/index', :layout => !request.xhr? }
86 format.html { render :template => 'issues/index', :layout => !request.xhr? }
84 format.api {
87 format.api {
85 Issue.load_visible_relations(@issues) if include_in_api_response?('relations')
88 Issue.load_visible_relations(@issues) if include_in_api_response?('relations')
86 }
89 }
87 format.atom { render_feed(@issues, :title => "#{@project || Setting.app_title}: #{l(:label_issue_plural)}") }
90 format.atom { render_feed(@issues, :title => "#{@project || Setting.app_title}: #{l(:label_issue_plural)}") }
88 format.csv { send_data(query_to_csv(@issues, @query, params), :type => 'text/csv; header=present', :filename => 'issues.csv') }
91 format.csv { send_data(query_to_csv(@issues, @query, params), :type => 'text/csv; header=present', :filename => 'issues.csv') }
89 format.pdf { send_data(issues_to_pdf(@issues, @project, @query), :type => 'application/pdf', :filename => 'issues.pdf') }
92 format.pdf { send_data(issues_to_pdf(@issues, @project, @query), :type => 'application/pdf', :filename => 'issues.pdf') }
90 end
93 end
91 else
94 else
92 respond_to do |format|
95 respond_to do |format|
93 format.html { render(:template => 'issues/index', :layout => !request.xhr?) }
96 format.html { render(:template => 'issues/index', :layout => !request.xhr?) }
94 format.any(:atom, :csv, :pdf) { render(:nothing => true) }
97 format.any(:atom, :csv, :pdf) { render(:nothing => true) }
95 format.api { render_validation_errors(@query) }
98 format.api { render_validation_errors(@query) }
96 end
99 end
97 end
100 end
98 rescue ActiveRecord::RecordNotFound
101 rescue ActiveRecord::RecordNotFound
99 render_404
102 render_404
100 end
103 end
101
104
102 def show
105 def show
103 @journals = @issue.journals.includes(:user, :details).reorder("#{Journal.table_name}.id ASC").all
106 @journals = @issue.journals.includes(:user, :details).reorder("#{Journal.table_name}.id ASC").all
104 @journals.each_with_index {|j,i| j.indice = i+1}
107 @journals.each_with_index {|j,i| j.indice = i+1}
105 @journals.reject!(&:private_notes?) unless User.current.allowed_to?(:view_private_notes, @issue.project)
108 @journals.reject!(&:private_notes?) unless User.current.allowed_to?(:view_private_notes, @issue.project)
106 Journal.preload_journals_details_custom_fields(@journals)
109 Journal.preload_journals_details_custom_fields(@journals)
107 # TODO: use #select! when ruby1.8 support is dropped
110 # TODO: use #select! when ruby1.8 support is dropped
108 @journals.reject! {|journal| !journal.notes? && journal.visible_details.empty?}
111 @journals.reject! {|journal| !journal.notes? && journal.visible_details.empty?}
109 @journals.reverse! if User.current.wants_comments_in_reverse_order?
112 @journals.reverse! if User.current.wants_comments_in_reverse_order?
110
113
111 @changesets = @issue.changesets.visible.all
114 @changesets = @issue.changesets.visible.all
112 @changesets.reverse! if User.current.wants_comments_in_reverse_order?
115 @changesets.reverse! if User.current.wants_comments_in_reverse_order?
113
116
114 @relations = @issue.relations.select {|r| r.other_issue(@issue) && r.other_issue(@issue).visible? }
117 @relations = @issue.relations.select {|r| r.other_issue(@issue) && r.other_issue(@issue).visible? }
115 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
118 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
116 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
119 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
117 @priorities = IssuePriority.active
120 @priorities = IssuePriority.active
118 @time_entry = TimeEntry.new(:issue => @issue, :project => @issue.project)
121 @time_entry = TimeEntry.new(:issue => @issue, :project => @issue.project)
119 @relation = IssueRelation.new
122 @relation = IssueRelation.new
120
123
121 respond_to do |format|
124 respond_to do |format|
122 format.html {
125 format.html {
123 retrieve_previous_and_next_issue_ids
126 retrieve_previous_and_next_issue_ids
124 render :template => 'issues/show'
127 render :template => 'issues/show'
125 }
128 }
126 format.api
129 format.api
127 format.atom { render :template => 'journals/index', :layout => false, :content_type => 'application/atom+xml' }
130 format.atom { render :template => 'journals/index', :layout => false, :content_type => 'application/atom+xml' }
128 format.pdf {
131 format.pdf {
129 pdf = issue_to_pdf(@issue, :journals => @journals)
132 pdf = issue_to_pdf(@issue, :journals => @journals)
130 send_data(pdf, :type => 'application/pdf', :filename => "#{@project.identifier}-#{@issue.id}.pdf")
133 send_data(pdf, :type => 'application/pdf', :filename => "#{@project.identifier}-#{@issue.id}.pdf")
131 }
134 }
132 end
135 end
133 end
136 end
134
137
135 # Add a new issue
138 # Add a new issue
136 # The new issue will be created from an existing one if copy_from parameter is given
139 # The new issue will be created from an existing one if copy_from parameter is given
137 def new
140 def new
138 respond_to do |format|
141 respond_to do |format|
139 format.html { render :action => 'new', :layout => !request.xhr? }
142 format.html { render :action => 'new', :layout => !request.xhr? }
140 end
143 end
141 end
144 end
142
145
143 def create
146 def create
144 call_hook(:controller_issues_new_before_save, { :params => params, :issue => @issue })
147 call_hook(:controller_issues_new_before_save, { :params => params, :issue => @issue })
145 @issue.save_attachments(params[:attachments] || (params[:issue] && params[:issue][:uploads]))
148 @issue.save_attachments(params[:attachments] || (params[:issue] && params[:issue][:uploads]))
146 if @issue.save
149 if @issue.save
147 call_hook(:controller_issues_new_after_save, { :params => params, :issue => @issue})
150 call_hook(:controller_issues_new_after_save, { :params => params, :issue => @issue})
148 respond_to do |format|
151 respond_to do |format|
149 format.html {
152 format.html {
150 render_attachment_warning_if_needed(@issue)
153 render_attachment_warning_if_needed(@issue)
151 flash[:notice] = l(:notice_issue_successful_create, :id => view_context.link_to("##{@issue.id}", issue_path(@issue), :title => @issue.subject))
154 flash[:notice] = l(:notice_issue_successful_create, :id => view_context.link_to("##{@issue.id}", issue_path(@issue), :title => @issue.subject))
152 if params[:continue]
155 if params[:continue]
153 attrs = {:tracker_id => @issue.tracker, :parent_issue_id => @issue.parent_issue_id}.reject {|k,v| v.nil?}
156 attrs = {:tracker_id => @issue.tracker, :parent_issue_id => @issue.parent_issue_id}.reject {|k,v| v.nil?}
154 redirect_to new_project_issue_path(@issue.project, :issue => attrs)
157 redirect_to new_project_issue_path(@issue.project, :issue => attrs)
155 else
158 else
156 redirect_to issue_path(@issue)
159 redirect_to issue_path(@issue)
157 end
160 end
158 }
161 }
159 format.api { render :action => 'show', :status => :created, :location => issue_url(@issue) }
162 format.api { render :action => 'show', :status => :created, :location => issue_url(@issue) }
160 end
163 end
161 return
164 return
162 else
165 else
163 respond_to do |format|
166 respond_to do |format|
164 format.html { render :action => 'new' }
167 format.html { render :action => 'new' }
165 format.api { render_validation_errors(@issue) }
168 format.api { render_validation_errors(@issue) }
166 end
169 end
167 end
170 end
168 end
171 end
169
172
170 def edit
173 def edit
171 return unless update_issue_from_params
174 return unless update_issue_from_params
172
175
173 respond_to do |format|
176 respond_to do |format|
174 format.html { }
177 format.html { }
175 format.xml { }
178 format.xml { }
176 end
179 end
177 end
180 end
178
181
179 def update
182 def update
180 return unless update_issue_from_params
183 return unless update_issue_from_params
181 @issue.save_attachments(params[:attachments] || (params[:issue] && params[:issue][:uploads]))
184 @issue.save_attachments(params[:attachments] || (params[:issue] && params[:issue][:uploads]))
182 saved = false
185 saved = false
183 begin
186 begin
184 saved = save_issue_with_child_records
187 saved = save_issue_with_child_records
185 rescue ActiveRecord::StaleObjectError
188 rescue ActiveRecord::StaleObjectError
186 @conflict = true
189 @conflict = true
187 if params[:last_journal_id]
190 if params[:last_journal_id]
188 @conflict_journals = @issue.journals_after(params[:last_journal_id]).all
191 @conflict_journals = @issue.journals_after(params[:last_journal_id]).all
189 @conflict_journals.reject!(&:private_notes?) unless User.current.allowed_to?(:view_private_notes, @issue.project)
192 @conflict_journals.reject!(&:private_notes?) unless User.current.allowed_to?(:view_private_notes, @issue.project)
190 end
193 end
191 end
194 end
192
195
193 if saved
196 if saved
194 render_attachment_warning_if_needed(@issue)
197 render_attachment_warning_if_needed(@issue)
195 flash[:notice] = l(:notice_successful_update) unless @issue.current_journal.new_record?
198 flash[:notice] = l(:notice_successful_update) unless @issue.current_journal.new_record?
196
199
197 respond_to do |format|
200 respond_to do |format|
198 format.html { redirect_back_or_default issue_path(@issue) }
201 format.html { redirect_back_or_default issue_path(@issue) }
199 format.api { render_api_ok }
202 format.api { render_api_ok }
200 end
203 end
201 else
204 else
202 respond_to do |format|
205 respond_to do |format|
203 format.html { render :action => 'edit' }
206 format.html { render :action => 'edit' }
204 format.api { render_validation_errors(@issue) }
207 format.api { render_validation_errors(@issue) }
205 end
208 end
206 end
209 end
207 end
210 end
208
211
209 # Updates the issue form when changing the project, status or tracker
212 # Updates the issue form when changing the project, status or tracker
210 # on issue creation/update
213 # on issue creation/update
211 def update_form
214 def update_form
212 end
215 end
213
216
214 # Bulk edit/copy a set of issues
217 # Bulk edit/copy a set of issues
215 def bulk_edit
218 def bulk_edit
216 @issues.sort!
219 @issues.sort!
217 @copy = params[:copy].present?
220 @copy = params[:copy].present?
218 @notes = params[:notes]
221 @notes = params[:notes]
219
222
220 if User.current.allowed_to?(:move_issues, @projects)
223 if User.current.allowed_to?(:move_issues, @projects)
221 @allowed_projects = Issue.allowed_target_projects_on_move
224 @allowed_projects = Issue.allowed_target_projects_on_move
222 if params[:issue]
225 if params[:issue]
223 @target_project = @allowed_projects.detect {|p| p.id.to_s == params[:issue][:project_id].to_s}
226 @target_project = @allowed_projects.detect {|p| p.id.to_s == params[:issue][:project_id].to_s}
224 if @target_project
227 if @target_project
225 target_projects = [@target_project]
228 target_projects = [@target_project]
226 end
229 end
227 end
230 end
228 end
231 end
229 target_projects ||= @projects
232 target_projects ||= @projects
230
233
231 if @copy
234 if @copy
232 @available_statuses = [IssueStatus.default]
235 @available_statuses = [IssueStatus.default]
233 else
236 else
234 @available_statuses = @issues.map(&:new_statuses_allowed_to).reduce(:&)
237 @available_statuses = @issues.map(&:new_statuses_allowed_to).reduce(:&)
235 end
238 end
236 @custom_fields = target_projects.map{|p|p.all_issue_custom_fields.visible}.reduce(:&)
239 @custom_fields = target_projects.map{|p|p.all_issue_custom_fields.visible}.reduce(:&)
237 @assignables = target_projects.map(&:assignable_users).reduce(:&)
240 @assignables = target_projects.map(&:assignable_users).reduce(:&)
238 @trackers = target_projects.map(&:trackers).reduce(:&)
241 @trackers = target_projects.map(&:trackers).reduce(:&)
239 @versions = target_projects.map {|p| p.shared_versions.open}.reduce(:&)
242 @versions = target_projects.map {|p| p.shared_versions.open}.reduce(:&)
240 @categories = target_projects.map {|p| p.issue_categories}.reduce(:&)
243 @categories = target_projects.map {|p| p.issue_categories}.reduce(:&)
241 if @copy
244 if @copy
242 @attachments_present = @issues.detect {|i| i.attachments.any?}.present?
245 @attachments_present = @issues.detect {|i| i.attachments.any?}.present?
243 @subtasks_present = @issues.detect {|i| !i.leaf?}.present?
246 @subtasks_present = @issues.detect {|i| !i.leaf?}.present?
244 end
247 end
245
248
246 @safe_attributes = @issues.map(&:safe_attribute_names).reduce(:&)
249 @safe_attributes = @issues.map(&:safe_attribute_names).reduce(:&)
247
250
248 @issue_params = params[:issue] || {}
251 @issue_params = params[:issue] || {}
249 @issue_params[:custom_field_values] ||= {}
252 @issue_params[:custom_field_values] ||= {}
250 end
253 end
251
254
252 def bulk_update
255 def bulk_update
253 @issues.sort!
256 @issues.sort!
254 @copy = params[:copy].present?
257 @copy = params[:copy].present?
255 attributes = parse_params_for_bulk_issue_attributes(params)
258 attributes = parse_params_for_bulk_issue_attributes(params)
256
259
257 unsaved_issues = []
260 unsaved_issues = []
258 saved_issues = []
261 saved_issues = []
259
262
260 if @copy && params[:copy_subtasks].present?
263 if @copy && params[:copy_subtasks].present?
261 # Descendant issues will be copied with the parent task
264 # Descendant issues will be copied with the parent task
262 # Don't copy them twice
265 # Don't copy them twice
263 @issues.reject! {|issue| @issues.detect {|other| issue.is_descendant_of?(other)}}
266 @issues.reject! {|issue| @issues.detect {|other| issue.is_descendant_of?(other)}}
264 end
267 end
265
268
266 @issues.each do |orig_issue|
269 @issues.each do |orig_issue|
267 orig_issue.reload
270 orig_issue.reload
268 if @copy
271 if @copy
269 issue = orig_issue.copy({},
272 issue = orig_issue.copy({},
270 :attachments => params[:copy_attachments].present?,
273 :attachments => params[:copy_attachments].present?,
271 :subtasks => params[:copy_subtasks].present?
274 :subtasks => params[:copy_subtasks].present?
272 )
275 )
273 else
276 else
274 issue = orig_issue
277 issue = orig_issue
275 end
278 end
276 journal = issue.init_journal(User.current, params[:notes])
279 journal = issue.init_journal(User.current, params[:notes])
277 issue.safe_attributes = attributes
280 issue.safe_attributes = attributes
278 call_hook(:controller_issues_bulk_edit_before_save, { :params => params, :issue => issue })
281 call_hook(:controller_issues_bulk_edit_before_save, { :params => params, :issue => issue })
279 if issue.save
282 if issue.save
280 saved_issues << issue
283 saved_issues << issue
281 else
284 else
282 unsaved_issues << orig_issue
285 unsaved_issues << orig_issue
283 end
286 end
284 end
287 end
285
288
286 if unsaved_issues.empty?
289 if unsaved_issues.empty?
287 flash[:notice] = l(:notice_successful_update) unless saved_issues.empty?
290 flash[:notice] = l(:notice_successful_update) unless saved_issues.empty?
288 if params[:follow]
291 if params[:follow]
289 if @issues.size == 1 && saved_issues.size == 1
292 if @issues.size == 1 && saved_issues.size == 1
290 redirect_to issue_path(saved_issues.first)
293 redirect_to issue_path(saved_issues.first)
291 elsif saved_issues.map(&:project).uniq.size == 1
294 elsif saved_issues.map(&:project).uniq.size == 1
292 redirect_to project_issues_path(saved_issues.map(&:project).first)
295 redirect_to project_issues_path(saved_issues.map(&:project).first)
293 end
296 end
294 else
297 else
295 redirect_back_or_default _project_issues_path(@project)
298 redirect_back_or_default _project_issues_path(@project)
296 end
299 end
297 else
300 else
298 @saved_issues = @issues
301 @saved_issues = @issues
299 @unsaved_issues = unsaved_issues
302 @unsaved_issues = unsaved_issues
300 @issues = Issue.visible.where(:id => @unsaved_issues.map(&:id)).all
303 @issues = Issue.visible.where(:id => @unsaved_issues.map(&:id)).all
301 bulk_edit
304 bulk_edit
302 render :action => 'bulk_edit'
305 render :action => 'bulk_edit'
303 end
306 end
304 end
307 end
305
308
306 def destroy
309 def destroy
307 @hours = TimeEntry.where(:issue_id => @issues.map(&:id)).sum(:hours).to_f
310 @hours = TimeEntry.where(:issue_id => @issues.map(&:id)).sum(:hours).to_f
308 if @hours > 0
311 if @hours > 0
309 case params[:todo]
312 case params[:todo]
310 when 'destroy'
313 when 'destroy'
311 # nothing to do
314 # nothing to do
312 when 'nullify'
315 when 'nullify'
313 TimeEntry.where(['issue_id IN (?)', @issues]).update_all('issue_id = NULL')
316 TimeEntry.where(['issue_id IN (?)', @issues]).update_all('issue_id = NULL')
314 when 'reassign'
317 when 'reassign'
315 reassign_to = @project.issues.find_by_id(params[:reassign_to_id])
318 reassign_to = @project.issues.find_by_id(params[:reassign_to_id])
316 if reassign_to.nil?
319 if reassign_to.nil?
317 flash.now[:error] = l(:error_issue_not_found_in_project)
320 flash.now[:error] = l(:error_issue_not_found_in_project)
318 return
321 return
319 else
322 else
320 TimeEntry.where(['issue_id IN (?)', @issues]).
323 TimeEntry.where(['issue_id IN (?)', @issues]).
321 update_all("issue_id = #{reassign_to.id}")
324 update_all("issue_id = #{reassign_to.id}")
322 end
325 end
323 else
326 else
324 # display the destroy form if it's a user request
327 # display the destroy form if it's a user request
325 return unless api_request?
328 return unless api_request?
326 end
329 end
327 end
330 end
328 @issues.each do |issue|
331 @issues.each do |issue|
329 begin
332 begin
330 issue.reload.destroy
333 issue.reload.destroy
331 rescue ::ActiveRecord::RecordNotFound # raised by #reload if issue no longer exists
334 rescue ::ActiveRecord::RecordNotFound # raised by #reload if issue no longer exists
332 # nothing to do, issue was already deleted (eg. by a parent)
335 # nothing to do, issue was already deleted (eg. by a parent)
333 end
336 end
334 end
337 end
335 respond_to do |format|
338 respond_to do |format|
336 format.html { redirect_back_or_default _project_issues_path(@project) }
339 format.html { redirect_back_or_default _project_issues_path(@project) }
337 format.api { render_api_ok }
340 format.api { render_api_ok }
338 end
341 end
339 end
342 end
340
343
341 private
344 private
342
345
343 def find_project
346 def find_project
344 project_id = params[:project_id] || (params[:issue] && params[:issue][:project_id])
347 project_id = params[:project_id] || (params[:issue] && params[:issue][:project_id])
345 @project = Project.find(project_id)
348 @project = Project.find(project_id)
346 rescue ActiveRecord::RecordNotFound
349 rescue ActiveRecord::RecordNotFound
347 render_404
350 render_404
348 end
351 end
349
352
350 def retrieve_previous_and_next_issue_ids
353 def retrieve_previous_and_next_issue_ids
351 retrieve_query_from_session
354 retrieve_query_from_session
352 if @query
355 if @query
353 sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
356 sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
354 sort_update(@query.sortable_columns, 'issues_index_sort')
357 sort_update(@query.sortable_columns, 'issues_index_sort')
355 limit = 500
358 limit = 500
356 issue_ids = @query.issue_ids(:order => sort_clause, :limit => (limit + 1), :include => [:assigned_to, :tracker, :priority, :category, :fixed_version])
359 issue_ids = @query.issue_ids(:order => sort_clause, :limit => (limit + 1), :include => [:assigned_to, :tracker, :priority, :category, :fixed_version])
357 if (idx = issue_ids.index(@issue.id)) && idx < limit
360 if (idx = issue_ids.index(@issue.id)) && idx < limit
358 if issue_ids.size < 500
361 if issue_ids.size < 500
359 @issue_position = idx + 1
362 @issue_position = idx + 1
360 @issue_count = issue_ids.size
363 @issue_count = issue_ids.size
361 end
364 end
362 @prev_issue_id = issue_ids[idx - 1] if idx > 0
365 @prev_issue_id = issue_ids[idx - 1] if idx > 0
363 @next_issue_id = issue_ids[idx + 1] if idx < (issue_ids.size - 1)
366 @next_issue_id = issue_ids[idx + 1] if idx < (issue_ids.size - 1)
364 end
367 end
365 end
368 end
366 end
369 end
367
370
368 # Used by #edit and #update to set some common instance variables
371 # Used by #edit and #update to set some common instance variables
369 # from the params
372 # from the params
370 # TODO: Refactor, not everything in here is needed by #edit
373 # TODO: Refactor, not everything in here is needed by #edit
371 def update_issue_from_params
374 def update_issue_from_params
372 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
375 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
373 @time_entry = TimeEntry.new(:issue => @issue, :project => @issue.project)
376 @time_entry = TimeEntry.new(:issue => @issue, :project => @issue.project)
374 @time_entry.attributes = params[:time_entry]
377 @time_entry.attributes = params[:time_entry]
375
378
376 @issue.init_journal(User.current)
379 @issue.init_journal(User.current)
377
380
378 issue_attributes = params[:issue]
381 issue_attributes = params[:issue]
379 if issue_attributes && params[:conflict_resolution]
382 if issue_attributes && params[:conflict_resolution]
380 case params[:conflict_resolution]
383 case params[:conflict_resolution]
381 when 'overwrite'
384 when 'overwrite'
382 issue_attributes = issue_attributes.dup
385 issue_attributes = issue_attributes.dup
383 issue_attributes.delete(:lock_version)
386 issue_attributes.delete(:lock_version)
384 when 'add_notes'
387 when 'add_notes'
385 issue_attributes = issue_attributes.slice(:notes)
388 issue_attributes = issue_attributes.slice(:notes)
386 when 'cancel'
389 when 'cancel'
387 redirect_to issue_path(@issue)
390 redirect_to issue_path(@issue)
388 return false
391 return false
389 end
392 end
390 end
393 end
391 @issue.safe_attributes = issue_attributes
394 @issue.safe_attributes = issue_attributes
392 @priorities = IssuePriority.active
395 @priorities = IssuePriority.active
393 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
396 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
394 true
397 true
395 end
398 end
396
399
397 # TODO: Refactor, lots of extra code in here
400 # TODO: Refactor, lots of extra code in here
398 # TODO: Changing tracker on an existing issue should not trigger this
401 # TODO: Changing tracker on an existing issue should not trigger this
399 def build_new_issue_from_params
402 def build_new_issue_from_params
400 if params[:id].blank?
403 if params[:id].blank?
401 @issue = Issue.new
404 @issue = Issue.new
402 if params[:copy_from]
405 if params[:copy_from]
403 begin
406 begin
404 @copy_from = Issue.visible.find(params[:copy_from])
407 @copy_from = Issue.visible.find(params[:copy_from])
405 @copy_attachments = params[:copy_attachments].present? || request.get?
408 @copy_attachments = params[:copy_attachments].present? || request.get?
406 @copy_subtasks = params[:copy_subtasks].present? || request.get?
409 @copy_subtasks = params[:copy_subtasks].present? || request.get?
407 @issue.copy_from(@copy_from, :attachments => @copy_attachments, :subtasks => @copy_subtasks)
410 @issue.copy_from(@copy_from, :attachments => @copy_attachments, :subtasks => @copy_subtasks)
408 rescue ActiveRecord::RecordNotFound
411 rescue ActiveRecord::RecordNotFound
409 render_404
412 render_404
410 return
413 return
411 end
414 end
412 end
415 end
413 @issue.project = @project
416 @issue.project = @project
414 else
417 else
415 @issue = @project.issues.visible.find(params[:id])
418 @issue = @project.issues.visible.find(params[:id])
416 end
419 end
417
420
418 @issue.project = @project
421 @issue.project = @project
419 @issue.author ||= User.current
422 @issue.author ||= User.current
420 # Tracker must be set before custom field values
423 # Tracker must be set before custom field values
421 @issue.tracker ||= @project.trackers.find((params[:issue] && params[:issue][:tracker_id]) || params[:tracker_id] || :first)
424 @issue.tracker ||= @project.trackers.find((params[:issue] && params[:issue][:tracker_id]) || params[:tracker_id] || :first)
422 if @issue.tracker.nil?
425 if @issue.tracker.nil?
423 render_error l(:error_no_tracker_in_project)
426 render_error l(:error_no_tracker_in_project)
424 return false
427 return false
425 end
428 end
426 @issue.start_date ||= Date.today if Setting.default_issue_start_date_to_creation_date?
429 @issue.start_date ||= Date.today if Setting.default_issue_start_date_to_creation_date?
427 @issue.safe_attributes = params[:issue]
430 @issue.safe_attributes = params[:issue]
428
431
429 @priorities = IssuePriority.active
432 @priorities = IssuePriority.active
430 @allowed_statuses = @issue.new_statuses_allowed_to(User.current, @issue.new_record?)
433 @allowed_statuses = @issue.new_statuses_allowed_to(User.current, @issue.new_record?)
431 @available_watchers = @issue.watcher_users
434 @available_watchers = @issue.watcher_users
432 if @issue.project.users.count <= 20
435 if @issue.project.users.count <= 20
433 @available_watchers = (@available_watchers + @issue.project.users.sort).uniq
436 @available_watchers = (@available_watchers + @issue.project.users.sort).uniq
434 end
437 end
435 end
438 end
436
439
437 def check_for_default_issue_status
440 def check_for_default_issue_status
438 if IssueStatus.default.nil?
441 if IssueStatus.default.nil?
439 render_error l(:error_no_default_issue_status)
442 render_error l(:error_no_default_issue_status)
440 return false
443 return false
441 end
444 end
442 end
445 end
443
446
444 def parse_params_for_bulk_issue_attributes(params)
447 def parse_params_for_bulk_issue_attributes(params)
445 attributes = (params[:issue] || {}).reject {|k,v| v.blank?}
448 attributes = (params[:issue] || {}).reject {|k,v| v.blank?}
446 attributes.keys.each {|k| attributes[k] = '' if attributes[k] == 'none'}
449 attributes.keys.each {|k| attributes[k] = '' if attributes[k] == 'none'}
447 if custom = attributes[:custom_field_values]
450 if custom = attributes[:custom_field_values]
448 custom.reject! {|k,v| v.blank?}
451 custom.reject! {|k,v| v.blank?}
449 custom.keys.each do |k|
452 custom.keys.each do |k|
450 if custom[k].is_a?(Array)
453 if custom[k].is_a?(Array)
451 custom[k] << '' if custom[k].delete('__none__')
454 custom[k] << '' if custom[k].delete('__none__')
452 else
455 else
453 custom[k] = '' if custom[k] == '__none__'
456 custom[k] = '' if custom[k] == '__none__'
454 end
457 end
455 end
458 end
456 end
459 end
457 attributes
460 attributes
458 end
461 end
459
462
460 # Saves @issue and a time_entry from the parameters
463 # Saves @issue and a time_entry from the parameters
461 def save_issue_with_child_records
464 def save_issue_with_child_records
462 Issue.transaction do
465 Issue.transaction do
463 if params[:time_entry] && (params[:time_entry][:hours].present? || params[:time_entry][:comments].present?) && User.current.allowed_to?(:log_time, @issue.project)
466 if params[:time_entry] && (params[:time_entry][:hours].present? || params[:time_entry][:comments].present?) && User.current.allowed_to?(:log_time, @issue.project)
464 time_entry = @time_entry || TimeEntry.new
467 time_entry = @time_entry || TimeEntry.new
465 time_entry.project = @issue.project
468 time_entry.project = @issue.project
466 time_entry.issue = @issue
469 time_entry.issue = @issue
467 time_entry.user = User.current
470 time_entry.user = User.current
468 time_entry.spent_on = User.current.today
471 time_entry.spent_on = User.current.today
469 time_entry.attributes = params[:time_entry]
472 time_entry.attributes = params[:time_entry]
470 @issue.time_entries << time_entry
473 @issue.time_entries << time_entry
471 end
474 end
472
475
473 call_hook(:controller_issues_edit_before_save, { :params => params, :issue => @issue, :time_entry => time_entry, :journal => @issue.current_journal})
476 call_hook(:controller_issues_edit_before_save, { :params => params, :issue => @issue, :time_entry => time_entry, :journal => @issue.current_journal})
474 if @issue.save
477 if @issue.save
475 call_hook(:controller_issues_edit_after_save, { :params => params, :issue => @issue, :time_entry => time_entry, :journal => @issue.current_journal})
478 call_hook(:controller_issues_edit_after_save, { :params => params, :issue => @issue, :time_entry => time_entry, :journal => @issue.current_journal})
476 else
479 else
477 raise ActiveRecord::Rollback
480 raise ActiveRecord::Rollback
478 end
481 end
479 end
482 end
480 end
483 end
481 end
484 end
@@ -1,481 +1,484
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2014 Jean-Philippe Lang
2 # Copyright (C) 2006-2014 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 IssueQuery < Query
18 class IssueQuery < Query
19
19
20 self.queried_class = Issue
20 self.queried_class = Issue
21
21
22 self.available_columns = [
22 self.available_columns = [
23 QueryColumn.new(:id, :sortable => "#{Issue.table_name}.id", :default_order => 'desc', :caption => '#', :frozen => true),
23 QueryColumn.new(:id, :sortable => "#{Issue.table_name}.id", :default_order => 'desc', :caption => '#', :frozen => true),
24 QueryColumn.new(:project, :sortable => "#{Project.table_name}.name", :groupable => true),
24 QueryColumn.new(:project, :sortable => "#{Project.table_name}.name", :groupable => true),
25 QueryColumn.new(:tracker, :sortable => "#{Tracker.table_name}.position", :groupable => true),
25 QueryColumn.new(:tracker, :sortable => "#{Tracker.table_name}.position", :groupable => true),
26 QueryColumn.new(:parent, :sortable => ["#{Issue.table_name}.root_id", "#{Issue.table_name}.lft ASC"], :default_order => 'desc', :caption => :field_parent_issue),
26 QueryColumn.new(:parent, :sortable => ["#{Issue.table_name}.root_id", "#{Issue.table_name}.lft ASC"], :default_order => 'desc', :caption => :field_parent_issue),
27 QueryColumn.new(:status, :sortable => "#{IssueStatus.table_name}.position", :groupable => true),
27 QueryColumn.new(:status, :sortable => "#{IssueStatus.table_name}.position", :groupable => true),
28 QueryColumn.new(:priority, :sortable => "#{IssuePriority.table_name}.position", :default_order => 'desc', :groupable => true),
28 QueryColumn.new(:priority, :sortable => "#{IssuePriority.table_name}.position", :default_order => 'desc', :groupable => true),
29 QueryColumn.new(:subject, :sortable => "#{Issue.table_name}.subject"),
29 QueryColumn.new(:subject, :sortable => "#{Issue.table_name}.subject"),
30 QueryColumn.new(:author, :sortable => lambda {User.fields_for_order_statement("authors")}, :groupable => true),
30 QueryColumn.new(:author, :sortable => lambda {User.fields_for_order_statement("authors")}, :groupable => true),
31 QueryColumn.new(:assigned_to, :sortable => lambda {User.fields_for_order_statement}, :groupable => true),
31 QueryColumn.new(:assigned_to, :sortable => lambda {User.fields_for_order_statement}, :groupable => true),
32 QueryColumn.new(:updated_on, :sortable => "#{Issue.table_name}.updated_on", :default_order => 'desc'),
32 QueryColumn.new(:updated_on, :sortable => "#{Issue.table_name}.updated_on", :default_order => 'desc'),
33 QueryColumn.new(:category, :sortable => "#{IssueCategory.table_name}.name", :groupable => true),
33 QueryColumn.new(:category, :sortable => "#{IssueCategory.table_name}.name", :groupable => true),
34 QueryColumn.new(:fixed_version, :sortable => lambda {Version.fields_for_order_statement}, :groupable => true),
34 QueryColumn.new(:fixed_version, :sortable => lambda {Version.fields_for_order_statement}, :groupable => true),
35 QueryColumn.new(:start_date, :sortable => "#{Issue.table_name}.start_date"),
35 QueryColumn.new(:start_date, :sortable => "#{Issue.table_name}.start_date"),
36 QueryColumn.new(:due_date, :sortable => "#{Issue.table_name}.due_date"),
36 QueryColumn.new(:due_date, :sortable => "#{Issue.table_name}.due_date"),
37 QueryColumn.new(:estimated_hours, :sortable => "#{Issue.table_name}.estimated_hours"),
37 QueryColumn.new(:estimated_hours, :sortable => "#{Issue.table_name}.estimated_hours"),
38 QueryColumn.new(:done_ratio, :sortable => "#{Issue.table_name}.done_ratio", :groupable => true),
38 QueryColumn.new(:done_ratio, :sortable => "#{Issue.table_name}.done_ratio", :groupable => true),
39 QueryColumn.new(:created_on, :sortable => "#{Issue.table_name}.created_on", :default_order => 'desc'),
39 QueryColumn.new(:created_on, :sortable => "#{Issue.table_name}.created_on", :default_order => 'desc'),
40 QueryColumn.new(:closed_on, :sortable => "#{Issue.table_name}.closed_on", :default_order => 'desc'),
40 QueryColumn.new(:closed_on, :sortable => "#{Issue.table_name}.closed_on", :default_order => 'desc'),
41 QueryColumn.new(:relations, :caption => :label_related_issues),
41 QueryColumn.new(:relations, :caption => :label_related_issues),
42 QueryColumn.new(:description, :inline => false)
42 QueryColumn.new(:description, :inline => false)
43 ]
43 ]
44
44
45 scope :visible, lambda {|*args|
45 scope :visible, lambda {|*args|
46 user = args.shift || User.current
46 user = args.shift || User.current
47 base = Project.allowed_to_condition(user, :view_issues, *args)
47 base = Project.allowed_to_condition(user, :view_issues, *args)
48 scope = includes(:project).where("#{table_name}.project_id IS NULL OR (#{base})")
48 scope = includes(:project).where("#{table_name}.project_id IS NULL OR (#{base})")
49
49
50 if user.admin?
50 if user.admin?
51 scope.where("#{table_name}.visibility <> ? OR #{table_name}.user_id = ?", VISIBILITY_PRIVATE, user.id)
51 scope.where("#{table_name}.visibility <> ? OR #{table_name}.user_id = ?", VISIBILITY_PRIVATE, user.id)
52 elsif user.memberships.any?
52 elsif user.memberships.any?
53 scope.where("#{table_name}.visibility = ?" +
53 scope.where("#{table_name}.visibility = ?" +
54 " OR (#{table_name}.visibility = ? AND #{table_name}.id IN (" +
54 " OR (#{table_name}.visibility = ? AND #{table_name}.id IN (" +
55 "SELECT DISTINCT q.id FROM #{table_name} q" +
55 "SELECT DISTINCT q.id FROM #{table_name} q" +
56 " INNER JOIN #{table_name_prefix}queries_roles#{table_name_suffix} qr on qr.query_id = q.id" +
56 " INNER JOIN #{table_name_prefix}queries_roles#{table_name_suffix} qr on qr.query_id = q.id" +
57 " INNER JOIN #{MemberRole.table_name} mr ON mr.role_id = qr.role_id" +
57 " INNER JOIN #{MemberRole.table_name} mr ON mr.role_id = qr.role_id" +
58 " INNER JOIN #{Member.table_name} m ON m.id = mr.member_id AND m.user_id = ?" +
58 " INNER JOIN #{Member.table_name} m ON m.id = mr.member_id AND m.user_id = ?" +
59 " WHERE q.project_id IS NULL OR q.project_id = m.project_id))" +
59 " WHERE q.project_id IS NULL OR q.project_id = m.project_id))" +
60 " OR #{table_name}.user_id = ?",
60 " OR #{table_name}.user_id = ?",
61 VISIBILITY_PUBLIC, VISIBILITY_ROLES, user.id, user.id)
61 VISIBILITY_PUBLIC, VISIBILITY_ROLES, user.id, user.id)
62 elsif user.logged?
62 elsif user.logged?
63 scope.where("#{table_name}.visibility = ? OR #{table_name}.user_id = ?", VISIBILITY_PUBLIC, user.id)
63 scope.where("#{table_name}.visibility = ? OR #{table_name}.user_id = ?", VISIBILITY_PUBLIC, user.id)
64 else
64 else
65 scope.where("#{table_name}.visibility = ?", VISIBILITY_PUBLIC)
65 scope.where("#{table_name}.visibility = ?", VISIBILITY_PUBLIC)
66 end
66 end
67 }
67 }
68
68
69 def initialize(attributes=nil, *args)
69 def initialize(attributes=nil, *args)
70 super attributes
70 super attributes
71 self.filters ||= { 'status_id' => {:operator => "o", :values => [""]} }
71 self.filters ||= { 'status_id' => {:operator => "o", :values => [""]} }
72 end
72 end
73
73
74 # Returns true if the query is visible to +user+ or the current user.
74 # Returns true if the query is visible to +user+ or the current user.
75 def visible?(user=User.current)
75 def visible?(user=User.current)
76 return true if user.admin?
76 return true if user.admin?
77 return false unless project.nil? || user.allowed_to?(:view_issues, project)
77 return false unless project.nil? || user.allowed_to?(:view_issues, project)
78 case visibility
78 case visibility
79 when VISIBILITY_PUBLIC
79 when VISIBILITY_PUBLIC
80 true
80 true
81 when VISIBILITY_ROLES
81 when VISIBILITY_ROLES
82 if project
82 if project
83 (user.roles_for_project(project) & roles).any?
83 (user.roles_for_project(project) & roles).any?
84 else
84 else
85 Member.where(:user_id => user.id).joins(:roles).where(:member_roles => {:role_id => roles.map(&:id)}).any?
85 Member.where(:user_id => user.id).joins(:roles).where(:member_roles => {:role_id => roles.map(&:id)}).any?
86 end
86 end
87 else
87 else
88 user == self.user
88 user == self.user
89 end
89 end
90 end
90 end
91
91
92 def is_private?
92 def is_private?
93 visibility == VISIBILITY_PRIVATE
93 visibility == VISIBILITY_PRIVATE
94 end
94 end
95
95
96 def is_public?
96 def is_public?
97 !is_private?
97 !is_private?
98 end
98 end
99
99
100 def draw_relations
100 def draw_relations
101 r = options[:draw_relations]
101 r = options[:draw_relations]
102 r.nil? || r == '1'
102 r.nil? || r == '1'
103 end
103 end
104
104
105 def draw_relations=(arg)
105 def draw_relations=(arg)
106 options[:draw_relations] = (arg == '0' ? '0' : nil)
106 options[:draw_relations] = (arg == '0' ? '0' : nil)
107 end
107 end
108
108
109 def draw_progress_line
109 def draw_progress_line
110 r = options[:draw_progress_line]
110 r = options[:draw_progress_line]
111 r == '1'
111 r == '1'
112 end
112 end
113
113
114 def draw_progress_line=(arg)
114 def draw_progress_line=(arg)
115 options[:draw_progress_line] = (arg == '1' ? '1' : nil)
115 options[:draw_progress_line] = (arg == '1' ? '1' : nil)
116 end
116 end
117
117
118 def build_from_params(params)
118 def build_from_params(params)
119 super
119 super
120 self.draw_relations = params[:draw_relations] || (params[:query] && params[:query][:draw_relations])
120 self.draw_relations = params[:draw_relations] || (params[:query] && params[:query][:draw_relations])
121 self.draw_progress_line = params[:draw_progress_line] || (params[:query] && params[:query][:draw_progress_line])
121 self.draw_progress_line = params[:draw_progress_line] || (params[:query] && params[:query][:draw_progress_line])
122 self
122 self
123 end
123 end
124
124
125 def initialize_available_filters
125 def initialize_available_filters
126 principals = []
126 principals = []
127 subprojects = []
127 subprojects = []
128 versions = []
128 versions = []
129 categories = []
129 categories = []
130 issue_custom_fields = []
130 issue_custom_fields = []
131
131
132 if project
132 if project
133 principals += project.principals.sort
133 principals += project.principals.sort
134 unless project.leaf?
134 unless project.leaf?
135 subprojects = project.descendants.visible.all
135 subprojects = project.descendants.visible.all
136 principals += Principal.member_of(subprojects)
136 principals += Principal.member_of(subprojects)
137 end
137 end
138 versions = project.shared_versions.all
138 versions = project.shared_versions.all
139 categories = project.issue_categories.all
139 categories = project.issue_categories.all
140 issue_custom_fields = project.all_issue_custom_fields
140 issue_custom_fields = project.all_issue_custom_fields
141 else
141 else
142 if all_projects.any?
142 if all_projects.any?
143 principals += Principal.member_of(all_projects)
143 principals += Principal.member_of(all_projects)
144 end
144 end
145 versions = Version.visible.where(:sharing => 'system').all
145 versions = Version.visible.where(:sharing => 'system').all
146 issue_custom_fields = IssueCustomField.where(:is_for_all => true)
146 issue_custom_fields = IssueCustomField.where(:is_for_all => true)
147 end
147 end
148 principals.uniq!
148 principals.uniq!
149 principals.sort!
149 principals.sort!
150 users = principals.select {|p| p.is_a?(User)}
150 users = principals.select {|p| p.is_a?(User)}
151
151
152 add_available_filter "status_id",
152 add_available_filter "status_id",
153 :type => :list_status, :values => IssueStatus.sorted.collect{|s| [s.name, s.id.to_s] }
153 :type => :list_status, :values => IssueStatus.sorted.collect{|s| [s.name, s.id.to_s] }
154
154
155 if project.nil?
155 if project.nil?
156 project_values = []
156 project_values = []
157 if User.current.logged? && User.current.memberships.any?
157 if User.current.logged? && User.current.memberships.any?
158 project_values << ["<< #{l(:label_my_projects).downcase} >>", "mine"]
158 project_values << ["<< #{l(:label_my_projects).downcase} >>", "mine"]
159 end
159 end
160 project_values += all_projects_values
160 project_values += all_projects_values
161 add_available_filter("project_id",
161 add_available_filter("project_id",
162 :type => :list, :values => project_values
162 :type => :list, :values => project_values
163 ) unless project_values.empty?
163 ) unless project_values.empty?
164 end
164 end
165
165
166 add_available_filter "tracker_id",
166 add_available_filter "tracker_id",
167 :type => :list, :values => trackers.collect{|s| [s.name, s.id.to_s] }
167 :type => :list, :values => trackers.collect{|s| [s.name, s.id.to_s] }
168 add_available_filter "priority_id",
168 add_available_filter "priority_id",
169 :type => :list, :values => IssuePriority.all.collect{|s| [s.name, s.id.to_s] }
169 :type => :list, :values => IssuePriority.all.collect{|s| [s.name, s.id.to_s] }
170
170
171 author_values = []
171 author_values = []
172 author_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged?
172 author_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged?
173 author_values += users.collect{|s| [s.name, s.id.to_s] }
173 author_values += users.collect{|s| [s.name, s.id.to_s] }
174 add_available_filter("author_id",
174 add_available_filter("author_id",
175 :type => :list, :values => author_values
175 :type => :list, :values => author_values
176 ) unless author_values.empty?
176 ) unless author_values.empty?
177
177
178 assigned_to_values = []
178 assigned_to_values = []
179 assigned_to_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged?
179 assigned_to_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged?
180 assigned_to_values += (Setting.issue_group_assignment? ?
180 assigned_to_values += (Setting.issue_group_assignment? ?
181 principals : users).collect{|s| [s.name, s.id.to_s] }
181 principals : users).collect{|s| [s.name, s.id.to_s] }
182 add_available_filter("assigned_to_id",
182 add_available_filter("assigned_to_id",
183 :type => :list_optional, :values => assigned_to_values
183 :type => :list_optional, :values => assigned_to_values
184 ) unless assigned_to_values.empty?
184 ) unless assigned_to_values.empty?
185
185
186 group_values = Group.all.collect {|g| [g.name, g.id.to_s] }
186 group_values = Group.all.collect {|g| [g.name, g.id.to_s] }
187 add_available_filter("member_of_group",
187 add_available_filter("member_of_group",
188 :type => :list_optional, :values => group_values
188 :type => :list_optional, :values => group_values
189 ) unless group_values.empty?
189 ) unless group_values.empty?
190
190
191 role_values = Role.givable.collect {|r| [r.name, r.id.to_s] }
191 role_values = Role.givable.collect {|r| [r.name, r.id.to_s] }
192 add_available_filter("assigned_to_role",
192 add_available_filter("assigned_to_role",
193 :type => :list_optional, :values => role_values
193 :type => :list_optional, :values => role_values
194 ) unless role_values.empty?
194 ) unless role_values.empty?
195
195
196 if versions.any?
196 if versions.any?
197 add_available_filter "fixed_version_id",
197 add_available_filter "fixed_version_id",
198 :type => :list_optional,
198 :type => :list_optional,
199 :values => versions.sort.collect{|s| ["#{s.project.name} - #{s.name}", s.id.to_s] }
199 :values => versions.sort.collect{|s| ["#{s.project.name} - #{s.name}", s.id.to_s] }
200 end
200 end
201
201
202 if categories.any?
202 if categories.any?
203 add_available_filter "category_id",
203 add_available_filter "category_id",
204 :type => :list_optional,
204 :type => :list_optional,
205 :values => categories.collect{|s| [s.name, s.id.to_s] }
205 :values => categories.collect{|s| [s.name, s.id.to_s] }
206 end
206 end
207
207
208 add_available_filter "subject", :type => :text
208 add_available_filter "subject", :type => :text
209 add_available_filter "created_on", :type => :date_past
209 add_available_filter "created_on", :type => :date_past
210 add_available_filter "updated_on", :type => :date_past
210 add_available_filter "updated_on", :type => :date_past
211 add_available_filter "closed_on", :type => :date_past
211 add_available_filter "closed_on", :type => :date_past
212 add_available_filter "start_date", :type => :date
212 add_available_filter "start_date", :type => :date
213 add_available_filter "due_date", :type => :date
213 add_available_filter "due_date", :type => :date
214 add_available_filter "estimated_hours", :type => :float
214 add_available_filter "estimated_hours", :type => :float
215 add_available_filter "done_ratio", :type => :integer
215 add_available_filter "done_ratio", :type => :integer
216
216
217 if User.current.allowed_to?(:set_issues_private, nil, :global => true) ||
217 if User.current.allowed_to?(:set_issues_private, nil, :global => true) ||
218 User.current.allowed_to?(:set_own_issues_private, nil, :global => true)
218 User.current.allowed_to?(:set_own_issues_private, nil, :global => true)
219 add_available_filter "is_private",
219 add_available_filter "is_private",
220 :type => :list,
220 :type => :list,
221 :values => [[l(:general_text_yes), "1"], [l(:general_text_no), "0"]]
221 :values => [[l(:general_text_yes), "1"], [l(:general_text_no), "0"]]
222 end
222 end
223
223
224 if User.current.logged?
224 if User.current.logged?
225 add_available_filter "watcher_id",
225 add_available_filter "watcher_id",
226 :type => :list, :values => [["<< #{l(:label_me)} >>", "me"]]
226 :type => :list, :values => [["<< #{l(:label_me)} >>", "me"]]
227 end
227 end
228
228
229 if subprojects.any?
229 if subprojects.any?
230 add_available_filter "subproject_id",
230 add_available_filter "subproject_id",
231 :type => :list_subprojects,
231 :type => :list_subprojects,
232 :values => subprojects.collect{|s| [s.name, s.id.to_s] }
232 :values => subprojects.collect{|s| [s.name, s.id.to_s] }
233 end
233 end
234
234
235 add_custom_fields_filters(issue_custom_fields)
235 add_custom_fields_filters(issue_custom_fields)
236
236
237 add_associations_custom_fields_filters :project, :author, :assigned_to, :fixed_version
237 add_associations_custom_fields_filters :project, :author, :assigned_to, :fixed_version
238
238
239 IssueRelation::TYPES.each do |relation_type, options|
239 IssueRelation::TYPES.each do |relation_type, options|
240 add_available_filter relation_type, :type => :relation, :label => options[:name]
240 add_available_filter relation_type, :type => :relation, :label => options[:name]
241 end
241 end
242
242
243 Tracker.disabled_core_fields(trackers).each {|field|
243 Tracker.disabled_core_fields(trackers).each {|field|
244 delete_available_filter field
244 delete_available_filter field
245 }
245 }
246 end
246 end
247
247
248 def available_columns
248 def available_columns
249 return @available_columns if @available_columns
249 return @available_columns if @available_columns
250 @available_columns = self.class.available_columns.dup
250 @available_columns = self.class.available_columns.dup
251 @available_columns += (project ?
251 @available_columns += (project ?
252 project.all_issue_custom_fields :
252 project.all_issue_custom_fields :
253 IssueCustomField
253 IssueCustomField
254 ).visible.collect {|cf| QueryCustomFieldColumn.new(cf) }
254 ).visible.collect {|cf| QueryCustomFieldColumn.new(cf) }
255
255
256 if User.current.allowed_to?(:view_time_entries, project, :global => true)
256 if User.current.allowed_to?(:view_time_entries, project, :global => true)
257 index = nil
257 index = nil
258 @available_columns.each_with_index {|column, i| index = i if column.name == :estimated_hours}
258 @available_columns.each_with_index {|column, i| index = i if column.name == :estimated_hours}
259 index = (index ? index + 1 : -1)
259 index = (index ? index + 1 : -1)
260 # insert the column after estimated_hours or at the end
260 # insert the column after estimated_hours or at the end
261 @available_columns.insert index, QueryColumn.new(:spent_hours,
261 @available_columns.insert index, QueryColumn.new(:spent_hours,
262 :sortable => "COALESCE((SELECT SUM(hours) FROM #{TimeEntry.table_name} WHERE #{TimeEntry.table_name}.issue_id = #{Issue.table_name}.id), 0)",
262 :sortable => "COALESCE((SELECT SUM(hours) FROM #{TimeEntry.table_name} WHERE #{TimeEntry.table_name}.issue_id = #{Issue.table_name}.id), 0)",
263 :default_order => 'desc',
263 :default_order => 'desc',
264 :caption => :label_spent_time
264 :caption => :label_spent_time
265 )
265 )
266 end
266 end
267
267
268 if User.current.allowed_to?(:set_issues_private, nil, :global => true) ||
268 if User.current.allowed_to?(:set_issues_private, nil, :global => true) ||
269 User.current.allowed_to?(:set_own_issues_private, nil, :global => true)
269 User.current.allowed_to?(:set_own_issues_private, nil, :global => true)
270 @available_columns << QueryColumn.new(:is_private, :sortable => "#{Issue.table_name}.is_private")
270 @available_columns << QueryColumn.new(:is_private, :sortable => "#{Issue.table_name}.is_private")
271 end
271 end
272
272
273 disabled_fields = Tracker.disabled_core_fields(trackers).map {|field| field.sub(/_id$/, '')}
273 disabled_fields = Tracker.disabled_core_fields(trackers).map {|field| field.sub(/_id$/, '')}
274 @available_columns.reject! {|column|
274 @available_columns.reject! {|column|
275 disabled_fields.include?(column.name.to_s)
275 disabled_fields.include?(column.name.to_s)
276 }
276 }
277
277
278 @available_columns
278 @available_columns
279 end
279 end
280
280
281 def default_columns_names
281 def default_columns_names
282 @default_columns_names ||= begin
282 @default_columns_names ||= begin
283 default_columns = Setting.issue_list_default_columns.map(&:to_sym)
283 default_columns = Setting.issue_list_default_columns.map(&:to_sym)
284
284
285 project.present? ? default_columns : [:project] | default_columns
285 project.present? ? default_columns : [:project] | default_columns
286 end
286 end
287 end
287 end
288
288
289 # Returns the issue count
289 # Returns the issue count
290 def issue_count
290 def issue_count
291 Issue.visible.joins(:status, :project).where(statement).count
291 Issue.visible.joins(:status, :project).where(statement).count
292 rescue ::ActiveRecord::StatementInvalid => e
292 rescue ::ActiveRecord::StatementInvalid => e
293 raise StatementInvalid.new(e.message)
293 raise StatementInvalid.new(e.message)
294 end
294 end
295
295
296 # Returns the issue count by group or nil if query is not grouped
296 # Returns the issue count by group or nil if query is not grouped
297 def issue_count_by_group
297 def issue_count_by_group
298 r = nil
298 r = nil
299 if grouped?
299 if grouped?
300 begin
300 begin
301 # Rails3 will raise an (unexpected) RecordNotFound if there's only a nil group value
301 # Rails3 will raise an (unexpected) RecordNotFound if there's only a nil group value
302 r = Issue.visible.
302 r = Issue.visible.
303 joins(:status, :project).
303 joins(:status, :project).
304 where(statement).
304 where(statement).
305 joins(joins_for_order_statement(group_by_statement)).
305 joins(joins_for_order_statement(group_by_statement)).
306 group(group_by_statement).
306 group(group_by_statement).
307 count
307 count
308 rescue ActiveRecord::RecordNotFound
308 rescue ActiveRecord::RecordNotFound
309 r = {nil => issue_count}
309 r = {nil => issue_count}
310 end
310 end
311 c = group_by_column
311 c = group_by_column
312 if c.is_a?(QueryCustomFieldColumn)
312 if c.is_a?(QueryCustomFieldColumn)
313 r = r.keys.inject({}) {|h, k| h[c.custom_field.cast_value(k)] = r[k]; h}
313 r = r.keys.inject({}) {|h, k| h[c.custom_field.cast_value(k)] = r[k]; h}
314 end
314 end
315 end
315 end
316 r
316 r
317 rescue ::ActiveRecord::StatementInvalid => e
317 rescue ::ActiveRecord::StatementInvalid => e
318 raise StatementInvalid.new(e.message)
318 raise StatementInvalid.new(e.message)
319 end
319 end
320
320
321 # Returns the issues
321 # Returns the issues
322 # Valid options are :order, :offset, :limit, :include, :conditions
322 # Valid options are :order, :offset, :limit, :include, :conditions
323 def issues(options={})
323 def issues(options={})
324 order_option = [group_by_sort_order, options[:order]].flatten.reject(&:blank?)
324 order_option = [group_by_sort_order, options[:order]].flatten.reject(&:blank?)
325
325
326 scope = Issue.visible.
326 scope = Issue.visible.
327 joins(:status, :project).
327 joins(:status, :project).
328 where(statement).
328 where(statement).
329 includes(([:status, :project] + (options[:include] || [])).uniq).
329 includes(([:status, :project] + (options[:include] || [])).uniq).
330 where(options[:conditions]).
330 where(options[:conditions]).
331 order(order_option).
331 order(order_option).
332 joins(joins_for_order_statement(order_option.join(','))).
332 joins(joins_for_order_statement(order_option.join(','))).
333 limit(options[:limit]).
333 limit(options[:limit]).
334 offset(options[:offset])
334 offset(options[:offset])
335
335
336 scope = scope.preload(:custom_values)
336 scope = scope.preload(:custom_values)
337 if has_column?(:author)
338 scope = scope.preload(:author)
339 end
337
340
338 issues = scope.all
341 issues = scope.all
339
342
340 if has_column?(:spent_hours)
343 if has_column?(:spent_hours)
341 Issue.load_visible_spent_hours(issues)
344 Issue.load_visible_spent_hours(issues)
342 end
345 end
343 if has_column?(:relations)
346 if has_column?(:relations)
344 Issue.load_visible_relations(issues)
347 Issue.load_visible_relations(issues)
345 end
348 end
346 issues
349 issues
347 rescue ::ActiveRecord::StatementInvalid => e
350 rescue ::ActiveRecord::StatementInvalid => e
348 raise StatementInvalid.new(e.message)
351 raise StatementInvalid.new(e.message)
349 end
352 end
350
353
351 # Returns the issues ids
354 # Returns the issues ids
352 def issue_ids(options={})
355 def issue_ids(options={})
353 order_option = [group_by_sort_order, options[:order]].flatten.reject(&:blank?)
356 order_option = [group_by_sort_order, options[:order]].flatten.reject(&:blank?)
354
357
355 Issue.visible.
358 Issue.visible.
356 joins(:status, :project).
359 joins(:status, :project).
357 where(statement).
360 where(statement).
358 includes(([:status, :project] + (options[:include] || [])).uniq).
361 includes(([:status, :project] + (options[:include] || [])).uniq).
359 where(options[:conditions]).
362 where(options[:conditions]).
360 order(order_option).
363 order(order_option).
361 joins(joins_for_order_statement(order_option.join(','))).
364 joins(joins_for_order_statement(order_option.join(','))).
362 limit(options[:limit]).
365 limit(options[:limit]).
363 offset(options[:offset]).
366 offset(options[:offset]).
364 find_ids
367 find_ids
365 rescue ::ActiveRecord::StatementInvalid => e
368 rescue ::ActiveRecord::StatementInvalid => e
366 raise StatementInvalid.new(e.message)
369 raise StatementInvalid.new(e.message)
367 end
370 end
368
371
369 # Returns the journals
372 # Returns the journals
370 # Valid options are :order, :offset, :limit
373 # Valid options are :order, :offset, :limit
371 def journals(options={})
374 def journals(options={})
372 Journal.visible.
375 Journal.visible.
373 joins(:issue => [:project, :status]).
376 joins(:issue => [:project, :status]).
374 where(statement).
377 where(statement).
375 order(options[:order]).
378 order(options[:order]).
376 limit(options[:limit]).
379 limit(options[:limit]).
377 offset(options[:offset]).
380 offset(options[:offset]).
378 preload(:details, :user, {:issue => [:project, :author, :tracker, :status]}).
381 preload(:details, :user, {:issue => [:project, :author, :tracker, :status]}).
379 all
382 all
380 rescue ::ActiveRecord::StatementInvalid => e
383 rescue ::ActiveRecord::StatementInvalid => e
381 raise StatementInvalid.new(e.message)
384 raise StatementInvalid.new(e.message)
382 end
385 end
383
386
384 # Returns the versions
387 # Returns the versions
385 # Valid options are :conditions
388 # Valid options are :conditions
386 def versions(options={})
389 def versions(options={})
387 Version.visible.
390 Version.visible.
388 where(project_statement).
391 where(project_statement).
389 where(options[:conditions]).
392 where(options[:conditions]).
390 includes(:project).
393 includes(:project).
391 all
394 all
392 rescue ::ActiveRecord::StatementInvalid => e
395 rescue ::ActiveRecord::StatementInvalid => e
393 raise StatementInvalid.new(e.message)
396 raise StatementInvalid.new(e.message)
394 end
397 end
395
398
396 def sql_for_watcher_id_field(field, operator, value)
399 def sql_for_watcher_id_field(field, operator, value)
397 db_table = Watcher.table_name
400 db_table = Watcher.table_name
398 "#{Issue.table_name}.id #{ operator == '=' ? 'IN' : 'NOT IN' } (SELECT #{db_table}.watchable_id FROM #{db_table} WHERE #{db_table}.watchable_type='Issue' AND " +
401 "#{Issue.table_name}.id #{ operator == '=' ? 'IN' : 'NOT IN' } (SELECT #{db_table}.watchable_id FROM #{db_table} WHERE #{db_table}.watchable_type='Issue' AND " +
399 sql_for_field(field, '=', value, db_table, 'user_id') + ')'
402 sql_for_field(field, '=', value, db_table, 'user_id') + ')'
400 end
403 end
401
404
402 def sql_for_member_of_group_field(field, operator, value)
405 def sql_for_member_of_group_field(field, operator, value)
403 if operator == '*' # Any group
406 if operator == '*' # Any group
404 groups = Group.all
407 groups = Group.all
405 operator = '=' # Override the operator since we want to find by assigned_to
408 operator = '=' # Override the operator since we want to find by assigned_to
406 elsif operator == "!*"
409 elsif operator == "!*"
407 groups = Group.all
410 groups = Group.all
408 operator = '!' # Override the operator since we want to find by assigned_to
411 operator = '!' # Override the operator since we want to find by assigned_to
409 else
412 else
410 groups = Group.where(:id => value).all
413 groups = Group.where(:id => value).all
411 end
414 end
412 groups ||= []
415 groups ||= []
413
416
414 members_of_groups = groups.inject([]) {|user_ids, group|
417 members_of_groups = groups.inject([]) {|user_ids, group|
415 user_ids + group.user_ids + [group.id]
418 user_ids + group.user_ids + [group.id]
416 }.uniq.compact.sort.collect(&:to_s)
419 }.uniq.compact.sort.collect(&:to_s)
417
420
418 '(' + sql_for_field("assigned_to_id", operator, members_of_groups, Issue.table_name, "assigned_to_id", false) + ')'
421 '(' + sql_for_field("assigned_to_id", operator, members_of_groups, Issue.table_name, "assigned_to_id", false) + ')'
419 end
422 end
420
423
421 def sql_for_assigned_to_role_field(field, operator, value)
424 def sql_for_assigned_to_role_field(field, operator, value)
422 case operator
425 case operator
423 when "*", "!*" # Member / Not member
426 when "*", "!*" # Member / Not member
424 sw = operator == "!*" ? 'NOT' : ''
427 sw = operator == "!*" ? 'NOT' : ''
425 nl = operator == "!*" ? "#{Issue.table_name}.assigned_to_id IS NULL OR" : ''
428 nl = operator == "!*" ? "#{Issue.table_name}.assigned_to_id IS NULL OR" : ''
426 "(#{nl} #{Issue.table_name}.assigned_to_id #{sw} IN (SELECT DISTINCT #{Member.table_name}.user_id FROM #{Member.table_name}" +
429 "(#{nl} #{Issue.table_name}.assigned_to_id #{sw} IN (SELECT DISTINCT #{Member.table_name}.user_id FROM #{Member.table_name}" +
427 " WHERE #{Member.table_name}.project_id = #{Issue.table_name}.project_id))"
430 " WHERE #{Member.table_name}.project_id = #{Issue.table_name}.project_id))"
428 when "=", "!"
431 when "=", "!"
429 role_cond = value.any? ?
432 role_cond = value.any? ?
430 "#{MemberRole.table_name}.role_id IN (" + value.collect{|val| "'#{connection.quote_string(val)}'"}.join(",") + ")" :
433 "#{MemberRole.table_name}.role_id IN (" + value.collect{|val| "'#{connection.quote_string(val)}'"}.join(",") + ")" :
431 "1=0"
434 "1=0"
432
435
433 sw = operator == "!" ? 'NOT' : ''
436 sw = operator == "!" ? 'NOT' : ''
434 nl = operator == "!" ? "#{Issue.table_name}.assigned_to_id IS NULL OR" : ''
437 nl = operator == "!" ? "#{Issue.table_name}.assigned_to_id IS NULL OR" : ''
435 "(#{nl} #{Issue.table_name}.assigned_to_id #{sw} IN (SELECT DISTINCT #{Member.table_name}.user_id FROM #{Member.table_name}, #{MemberRole.table_name}" +
438 "(#{nl} #{Issue.table_name}.assigned_to_id #{sw} IN (SELECT DISTINCT #{Member.table_name}.user_id FROM #{Member.table_name}, #{MemberRole.table_name}" +
436 " WHERE #{Member.table_name}.project_id = #{Issue.table_name}.project_id AND #{Member.table_name}.id = #{MemberRole.table_name}.member_id AND #{role_cond}))"
439 " WHERE #{Member.table_name}.project_id = #{Issue.table_name}.project_id AND #{Member.table_name}.id = #{MemberRole.table_name}.member_id AND #{role_cond}))"
437 end
440 end
438 end
441 end
439
442
440 def sql_for_is_private_field(field, operator, value)
443 def sql_for_is_private_field(field, operator, value)
441 op = (operator == "=" ? 'IN' : 'NOT IN')
444 op = (operator == "=" ? 'IN' : 'NOT IN')
442 va = value.map {|v| v == '0' ? connection.quoted_false : connection.quoted_true}.uniq.join(',')
445 va = value.map {|v| v == '0' ? connection.quoted_false : connection.quoted_true}.uniq.join(',')
443
446
444 "#{Issue.table_name}.is_private #{op} (#{va})"
447 "#{Issue.table_name}.is_private #{op} (#{va})"
445 end
448 end
446
449
447 def sql_for_relations(field, operator, value, options={})
450 def sql_for_relations(field, operator, value, options={})
448 relation_options = IssueRelation::TYPES[field]
451 relation_options = IssueRelation::TYPES[field]
449 return relation_options unless relation_options
452 return relation_options unless relation_options
450
453
451 relation_type = field
454 relation_type = field
452 join_column, target_join_column = "issue_from_id", "issue_to_id"
455 join_column, target_join_column = "issue_from_id", "issue_to_id"
453 if relation_options[:reverse] || options[:reverse]
456 if relation_options[:reverse] || options[:reverse]
454 relation_type = relation_options[:reverse] || relation_type
457 relation_type = relation_options[:reverse] || relation_type
455 join_column, target_join_column = target_join_column, join_column
458 join_column, target_join_column = target_join_column, join_column
456 end
459 end
457
460
458 sql = case operator
461 sql = case operator
459 when "*", "!*"
462 when "*", "!*"
460 op = (operator == "*" ? 'IN' : 'NOT IN')
463 op = (operator == "*" ? 'IN' : 'NOT IN')
461 "#{Issue.table_name}.id #{op} (SELECT DISTINCT #{IssueRelation.table_name}.#{join_column} FROM #{IssueRelation.table_name} WHERE #{IssueRelation.table_name}.relation_type = '#{connection.quote_string(relation_type)}')"
464 "#{Issue.table_name}.id #{op} (SELECT DISTINCT #{IssueRelation.table_name}.#{join_column} FROM #{IssueRelation.table_name} WHERE #{IssueRelation.table_name}.relation_type = '#{connection.quote_string(relation_type)}')"
462 when "=", "!"
465 when "=", "!"
463 op = (operator == "=" ? 'IN' : 'NOT IN')
466 op = (operator == "=" ? 'IN' : 'NOT IN')
464 "#{Issue.table_name}.id #{op} (SELECT DISTINCT #{IssueRelation.table_name}.#{join_column} FROM #{IssueRelation.table_name} WHERE #{IssueRelation.table_name}.relation_type = '#{connection.quote_string(relation_type)}' AND #{IssueRelation.table_name}.#{target_join_column} = #{value.first.to_i})"
467 "#{Issue.table_name}.id #{op} (SELECT DISTINCT #{IssueRelation.table_name}.#{join_column} FROM #{IssueRelation.table_name} WHERE #{IssueRelation.table_name}.relation_type = '#{connection.quote_string(relation_type)}' AND #{IssueRelation.table_name}.#{target_join_column} = #{value.first.to_i})"
465 when "=p", "=!p", "!p"
468 when "=p", "=!p", "!p"
466 op = (operator == "!p" ? 'NOT IN' : 'IN')
469 op = (operator == "!p" ? 'NOT IN' : 'IN')
467 comp = (operator == "=!p" ? '<>' : '=')
470 comp = (operator == "=!p" ? '<>' : '=')
468 "#{Issue.table_name}.id #{op} (SELECT DISTINCT #{IssueRelation.table_name}.#{join_column} FROM #{IssueRelation.table_name}, #{Issue.table_name} relissues WHERE #{IssueRelation.table_name}.relation_type = '#{connection.quote_string(relation_type)}' AND #{IssueRelation.table_name}.#{target_join_column} = relissues.id AND relissues.project_id #{comp} #{value.first.to_i})"
471 "#{Issue.table_name}.id #{op} (SELECT DISTINCT #{IssueRelation.table_name}.#{join_column} FROM #{IssueRelation.table_name}, #{Issue.table_name} relissues WHERE #{IssueRelation.table_name}.relation_type = '#{connection.quote_string(relation_type)}' AND #{IssueRelation.table_name}.#{target_join_column} = relissues.id AND relissues.project_id #{comp} #{value.first.to_i})"
469 end
472 end
470
473
471 if relation_options[:sym] == field && !options[:reverse]
474 if relation_options[:sym] == field && !options[:reverse]
472 sqls = [sql, sql_for_relations(field, operator, value, :reverse => true)]
475 sqls = [sql, sql_for_relations(field, operator, value, :reverse => true)]
473 sql = sqls.join(["!", "!*", "!p"].include?(operator) ? " AND " : " OR ")
476 sql = sqls.join(["!", "!*", "!p"].include?(operator) ? " AND " : " OR ")
474 end
477 end
475 "(#{sql})"
478 "(#{sql})"
476 end
479 end
477
480
478 IssueRelation::TYPES.keys.each do |relation_type|
481 IssueRelation::TYPES.keys.each do |relation_type|
479 alias_method "sql_for_#{relation_type}_field".to_sym, :sql_for_relations
482 alias_method "sql_for_#{relation_type}_field".to_sym, :sql_for_relations
480 end
483 end
481 end
484 end
General Comments 0
You need to be logged in to leave comments. Login now