##// END OF EJS Templates
change "is_private" issue filter order from 15 to 16 (#12018)...
Toshi MARUYAMA -
r10341:7c0c699f95a7
parent child
Show More
@@ -1,1057 +1,1057
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2012 Jean-Philippe Lang
2 # Copyright (C) 2006-2012 Jean-Philippe Lang
3 #
3 #
4 # This program is free software; you can redistribute it and/or
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
7 # of the License, or (at your option) any later version.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU General Public License
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
17
18 class QueryColumn
18 class QueryColumn
19 attr_accessor :name, :sortable, :groupable, :default_order
19 attr_accessor :name, :sortable, :groupable, :default_order
20 include Redmine::I18n
20 include Redmine::I18n
21
21
22 def initialize(name, options={})
22 def initialize(name, options={})
23 self.name = name
23 self.name = name
24 self.sortable = options[:sortable]
24 self.sortable = options[:sortable]
25 self.groupable = options[:groupable] || false
25 self.groupable = options[:groupable] || false
26 if groupable == true
26 if groupable == true
27 self.groupable = name.to_s
27 self.groupable = name.to_s
28 end
28 end
29 self.default_order = options[:default_order]
29 self.default_order = options[:default_order]
30 @caption_key = options[:caption] || "field_#{name}"
30 @caption_key = options[:caption] || "field_#{name}"
31 end
31 end
32
32
33 def caption
33 def caption
34 l(@caption_key)
34 l(@caption_key)
35 end
35 end
36
36
37 # Returns true if the column is sortable, otherwise false
37 # Returns true if the column is sortable, otherwise false
38 def sortable?
38 def sortable?
39 !@sortable.nil?
39 !@sortable.nil?
40 end
40 end
41
41
42 def sortable
42 def sortable
43 @sortable.is_a?(Proc) ? @sortable.call : @sortable
43 @sortable.is_a?(Proc) ? @sortable.call : @sortable
44 end
44 end
45
45
46 def value(issue)
46 def value(issue)
47 issue.send name
47 issue.send name
48 end
48 end
49
49
50 def css_classes
50 def css_classes
51 name
51 name
52 end
52 end
53 end
53 end
54
54
55 class QueryCustomFieldColumn < QueryColumn
55 class QueryCustomFieldColumn < QueryColumn
56
56
57 def initialize(custom_field)
57 def initialize(custom_field)
58 self.name = "cf_#{custom_field.id}".to_sym
58 self.name = "cf_#{custom_field.id}".to_sym
59 self.sortable = custom_field.order_statement || false
59 self.sortable = custom_field.order_statement || false
60 self.groupable = custom_field.group_statement || false
60 self.groupable = custom_field.group_statement || false
61 @cf = custom_field
61 @cf = custom_field
62 end
62 end
63
63
64 def caption
64 def caption
65 @cf.name
65 @cf.name
66 end
66 end
67
67
68 def custom_field
68 def custom_field
69 @cf
69 @cf
70 end
70 end
71
71
72 def value(issue)
72 def value(issue)
73 cv = issue.custom_values.select {|v| v.custom_field_id == @cf.id}.collect {|v| @cf.cast_value(v.value)}
73 cv = issue.custom_values.select {|v| v.custom_field_id == @cf.id}.collect {|v| @cf.cast_value(v.value)}
74 cv.size > 1 ? cv.sort {|a,b| a.to_s <=> b.to_s} : cv.first
74 cv.size > 1 ? cv.sort {|a,b| a.to_s <=> b.to_s} : cv.first
75 end
75 end
76
76
77 def css_classes
77 def css_classes
78 @css_classes ||= "#{name} #{@cf.field_format}"
78 @css_classes ||= "#{name} #{@cf.field_format}"
79 end
79 end
80 end
80 end
81
81
82 class Query < ActiveRecord::Base
82 class Query < ActiveRecord::Base
83 class StatementInvalid < ::ActiveRecord::StatementInvalid
83 class StatementInvalid < ::ActiveRecord::StatementInvalid
84 end
84 end
85
85
86 belongs_to :project
86 belongs_to :project
87 belongs_to :user
87 belongs_to :user
88 serialize :filters
88 serialize :filters
89 serialize :column_names
89 serialize :column_names
90 serialize :sort_criteria, Array
90 serialize :sort_criteria, Array
91
91
92 attr_protected :project_id, :user_id
92 attr_protected :project_id, :user_id
93
93
94 validates_presence_of :name
94 validates_presence_of :name
95 validates_length_of :name, :maximum => 255
95 validates_length_of :name, :maximum => 255
96 validate :validate_query_filters
96 validate :validate_query_filters
97
97
98 @@operators = { "=" => :label_equals,
98 @@operators = { "=" => :label_equals,
99 "!" => :label_not_equals,
99 "!" => :label_not_equals,
100 "o" => :label_open_issues,
100 "o" => :label_open_issues,
101 "c" => :label_closed_issues,
101 "c" => :label_closed_issues,
102 "!*" => :label_none,
102 "!*" => :label_none,
103 "*" => :label_all,
103 "*" => :label_all,
104 ">=" => :label_greater_or_equal,
104 ">=" => :label_greater_or_equal,
105 "<=" => :label_less_or_equal,
105 "<=" => :label_less_or_equal,
106 "><" => :label_between,
106 "><" => :label_between,
107 "<t+" => :label_in_less_than,
107 "<t+" => :label_in_less_than,
108 ">t+" => :label_in_more_than,
108 ">t+" => :label_in_more_than,
109 "t+" => :label_in,
109 "t+" => :label_in,
110 "t" => :label_today,
110 "t" => :label_today,
111 "w" => :label_this_week,
111 "w" => :label_this_week,
112 ">t-" => :label_less_than_ago,
112 ">t-" => :label_less_than_ago,
113 "<t-" => :label_more_than_ago,
113 "<t-" => :label_more_than_ago,
114 "t-" => :label_ago,
114 "t-" => :label_ago,
115 "~" => :label_contains,
115 "~" => :label_contains,
116 "!~" => :label_not_contains,
116 "!~" => :label_not_contains,
117 "=p" => :label_any_issues_in_project,
117 "=p" => :label_any_issues_in_project,
118 "=!p" => :label_any_issues_not_in_project}
118 "=!p" => :label_any_issues_not_in_project}
119
119
120 cattr_reader :operators
120 cattr_reader :operators
121
121
122 @@operators_by_filter_type = { :list => [ "=", "!" ],
122 @@operators_by_filter_type = { :list => [ "=", "!" ],
123 :list_status => [ "o", "=", "!", "c", "*" ],
123 :list_status => [ "o", "=", "!", "c", "*" ],
124 :list_optional => [ "=", "!", "!*", "*" ],
124 :list_optional => [ "=", "!", "!*", "*" ],
125 :list_subprojects => [ "*", "!*", "=" ],
125 :list_subprojects => [ "*", "!*", "=" ],
126 :date => [ "=", ">=", "<=", "><", "<t+", ">t+", "t+", "t", "w", ">t-", "<t-", "t-", "!*", "*" ],
126 :date => [ "=", ">=", "<=", "><", "<t+", ">t+", "t+", "t", "w", ">t-", "<t-", "t-", "!*", "*" ],
127 :date_past => [ "=", ">=", "<=", "><", ">t-", "<t-", "t-", "t", "w", "!*", "*" ],
127 :date_past => [ "=", ">=", "<=", "><", ">t-", "<t-", "t-", "t", "w", "!*", "*" ],
128 :string => [ "=", "~", "!", "!~", "!*", "*" ],
128 :string => [ "=", "~", "!", "!~", "!*", "*" ],
129 :text => [ "~", "!~", "!*", "*" ],
129 :text => [ "~", "!~", "!*", "*" ],
130 :integer => [ "=", ">=", "<=", "><", "!*", "*" ],
130 :integer => [ "=", ">=", "<=", "><", "!*", "*" ],
131 :float => [ "=", ">=", "<=", "><", "!*", "*" ],
131 :float => [ "=", ">=", "<=", "><", "!*", "*" ],
132 :relation => ["=", "=p", "=!p", "!*", "*"]}
132 :relation => ["=", "=p", "=!p", "!*", "*"]}
133
133
134 cattr_reader :operators_by_filter_type
134 cattr_reader :operators_by_filter_type
135
135
136 @@available_columns = [
136 @@available_columns = [
137 QueryColumn.new(:project, :sortable => "#{Project.table_name}.name", :groupable => true),
137 QueryColumn.new(:project, :sortable => "#{Project.table_name}.name", :groupable => true),
138 QueryColumn.new(:tracker, :sortable => "#{Tracker.table_name}.position", :groupable => true),
138 QueryColumn.new(:tracker, :sortable => "#{Tracker.table_name}.position", :groupable => true),
139 QueryColumn.new(:parent, :sortable => ["#{Issue.table_name}.root_id", "#{Issue.table_name}.lft ASC"], :default_order => 'desc', :caption => :field_parent_issue),
139 QueryColumn.new(:parent, :sortable => ["#{Issue.table_name}.root_id", "#{Issue.table_name}.lft ASC"], :default_order => 'desc', :caption => :field_parent_issue),
140 QueryColumn.new(:status, :sortable => "#{IssueStatus.table_name}.position", :groupable => true),
140 QueryColumn.new(:status, :sortable => "#{IssueStatus.table_name}.position", :groupable => true),
141 QueryColumn.new(:priority, :sortable => "#{IssuePriority.table_name}.position", :default_order => 'desc', :groupable => true),
141 QueryColumn.new(:priority, :sortable => "#{IssuePriority.table_name}.position", :default_order => 'desc', :groupable => true),
142 QueryColumn.new(:subject, :sortable => "#{Issue.table_name}.subject"),
142 QueryColumn.new(:subject, :sortable => "#{Issue.table_name}.subject"),
143 QueryColumn.new(:author, :sortable => lambda {User.fields_for_order_statement("authors")}, :groupable => true),
143 QueryColumn.new(:author, :sortable => lambda {User.fields_for_order_statement("authors")}, :groupable => true),
144 QueryColumn.new(:assigned_to, :sortable => lambda {User.fields_for_order_statement}, :groupable => true),
144 QueryColumn.new(:assigned_to, :sortable => lambda {User.fields_for_order_statement}, :groupable => true),
145 QueryColumn.new(:updated_on, :sortable => "#{Issue.table_name}.updated_on", :default_order => 'desc'),
145 QueryColumn.new(:updated_on, :sortable => "#{Issue.table_name}.updated_on", :default_order => 'desc'),
146 QueryColumn.new(:category, :sortable => "#{IssueCategory.table_name}.name", :groupable => true),
146 QueryColumn.new(:category, :sortable => "#{IssueCategory.table_name}.name", :groupable => true),
147 QueryColumn.new(:fixed_version, :sortable => lambda {Version.fields_for_order_statement}, :groupable => true),
147 QueryColumn.new(:fixed_version, :sortable => lambda {Version.fields_for_order_statement}, :groupable => true),
148 QueryColumn.new(:start_date, :sortable => "#{Issue.table_name}.start_date"),
148 QueryColumn.new(:start_date, :sortable => "#{Issue.table_name}.start_date"),
149 QueryColumn.new(:due_date, :sortable => "#{Issue.table_name}.due_date"),
149 QueryColumn.new(:due_date, :sortable => "#{Issue.table_name}.due_date"),
150 QueryColumn.new(:estimated_hours, :sortable => "#{Issue.table_name}.estimated_hours"),
150 QueryColumn.new(:estimated_hours, :sortable => "#{Issue.table_name}.estimated_hours"),
151 QueryColumn.new(:done_ratio, :sortable => "#{Issue.table_name}.done_ratio", :groupable => true),
151 QueryColumn.new(:done_ratio, :sortable => "#{Issue.table_name}.done_ratio", :groupable => true),
152 QueryColumn.new(:created_on, :sortable => "#{Issue.table_name}.created_on", :default_order => 'desc'),
152 QueryColumn.new(:created_on, :sortable => "#{Issue.table_name}.created_on", :default_order => 'desc'),
153 QueryColumn.new(:relations, :caption => :label_related_issues)
153 QueryColumn.new(:relations, :caption => :label_related_issues)
154 ]
154 ]
155 cattr_reader :available_columns
155 cattr_reader :available_columns
156
156
157 scope :visible, lambda {|*args|
157 scope :visible, lambda {|*args|
158 user = args.shift || User.current
158 user = args.shift || User.current
159 base = Project.allowed_to_condition(user, :view_issues, *args)
159 base = Project.allowed_to_condition(user, :view_issues, *args)
160 user_id = user.logged? ? user.id : 0
160 user_id = user.logged? ? user.id : 0
161 {
161 {
162 :conditions => ["(#{table_name}.project_id IS NULL OR (#{base})) AND (#{table_name}.is_public = ? OR #{table_name}.user_id = ?)", true, user_id],
162 :conditions => ["(#{table_name}.project_id IS NULL OR (#{base})) AND (#{table_name}.is_public = ? OR #{table_name}.user_id = ?)", true, user_id],
163 :include => :project
163 :include => :project
164 }
164 }
165 }
165 }
166
166
167 def initialize(attributes=nil, *args)
167 def initialize(attributes=nil, *args)
168 super attributes
168 super attributes
169 self.filters ||= { 'status_id' => {:operator => "o", :values => [""]} }
169 self.filters ||= { 'status_id' => {:operator => "o", :values => [""]} }
170 @is_for_all = project.nil?
170 @is_for_all = project.nil?
171 end
171 end
172
172
173 def validate_query_filters
173 def validate_query_filters
174 filters.each_key do |field|
174 filters.each_key do |field|
175 if values_for(field)
175 if values_for(field)
176 case type_for(field)
176 case type_for(field)
177 when :integer
177 when :integer
178 add_filter_error(field, :invalid) if values_for(field).detect {|v| v.present? && !v.match(/^[+-]?\d+$/) }
178 add_filter_error(field, :invalid) if values_for(field).detect {|v| v.present? && !v.match(/^[+-]?\d+$/) }
179 when :float
179 when :float
180 add_filter_error(field, :invalid) if values_for(field).detect {|v| v.present? && !v.match(/^[+-]?\d+(\.\d*)?$/) }
180 add_filter_error(field, :invalid) if values_for(field).detect {|v| v.present? && !v.match(/^[+-]?\d+(\.\d*)?$/) }
181 when :date, :date_past
181 when :date, :date_past
182 case operator_for(field)
182 case operator_for(field)
183 when "=", ">=", "<=", "><"
183 when "=", ">=", "<=", "><"
184 add_filter_error(field, :invalid) if values_for(field).detect {|v| v.present? && (!v.match(/^\d{4}-\d{2}-\d{2}$/) || (Date.parse(v) rescue nil).nil?) }
184 add_filter_error(field, :invalid) if values_for(field).detect {|v| v.present? && (!v.match(/^\d{4}-\d{2}-\d{2}$/) || (Date.parse(v) rescue nil).nil?) }
185 when ">t-", "<t-", "t-"
185 when ">t-", "<t-", "t-"
186 add_filter_error(field, :invalid) if values_for(field).detect {|v| v.present? && !v.match(/^\d+$/) }
186 add_filter_error(field, :invalid) if values_for(field).detect {|v| v.present? && !v.match(/^\d+$/) }
187 end
187 end
188 end
188 end
189 end
189 end
190
190
191 add_filter_error(field, :blank) unless
191 add_filter_error(field, :blank) unless
192 # filter requires one or more values
192 # filter requires one or more values
193 (values_for(field) and !values_for(field).first.blank?) or
193 (values_for(field) and !values_for(field).first.blank?) or
194 # filter doesn't require any value
194 # filter doesn't require any value
195 ["o", "c", "!*", "*", "t", "w"].include? operator_for(field)
195 ["o", "c", "!*", "*", "t", "w"].include? operator_for(field)
196 end if filters
196 end if filters
197 end
197 end
198
198
199 def add_filter_error(field, message)
199 def add_filter_error(field, message)
200 m = label_for(field) + " " + l(message, :scope => 'activerecord.errors.messages')
200 m = label_for(field) + " " + l(message, :scope => 'activerecord.errors.messages')
201 errors.add(:base, m)
201 errors.add(:base, m)
202 end
202 end
203
203
204 # Returns true if the query is visible to +user+ or the current user.
204 # Returns true if the query is visible to +user+ or the current user.
205 def visible?(user=User.current)
205 def visible?(user=User.current)
206 (project.nil? || user.allowed_to?(:view_issues, project)) && (self.is_public? || self.user_id == user.id)
206 (project.nil? || user.allowed_to?(:view_issues, project)) && (self.is_public? || self.user_id == user.id)
207 end
207 end
208
208
209 def editable_by?(user)
209 def editable_by?(user)
210 return false unless user
210 return false unless user
211 # Admin can edit them all and regular users can edit their private queries
211 # Admin can edit them all and regular users can edit their private queries
212 return true if user.admin? || (!is_public && self.user_id == user.id)
212 return true if user.admin? || (!is_public && self.user_id == user.id)
213 # Members can not edit public queries that are for all project (only admin is allowed to)
213 # Members can not edit public queries that are for all project (only admin is allowed to)
214 is_public && !@is_for_all && user.allowed_to?(:manage_public_queries, project)
214 is_public && !@is_for_all && user.allowed_to?(:manage_public_queries, project)
215 end
215 end
216
216
217 def trackers
217 def trackers
218 @trackers ||= project.nil? ? Tracker.find(:all, :order => 'position') : project.rolled_up_trackers
218 @trackers ||= project.nil? ? Tracker.find(:all, :order => 'position') : project.rolled_up_trackers
219 end
219 end
220
220
221 # Returns a hash of localized labels for all filter operators
221 # Returns a hash of localized labels for all filter operators
222 def self.operators_labels
222 def self.operators_labels
223 operators.inject({}) {|h, operator| h[operator.first] = l(operator.last); h}
223 operators.inject({}) {|h, operator| h[operator.first] = l(operator.last); h}
224 end
224 end
225
225
226 def available_filters
226 def available_filters
227 return @available_filters if @available_filters
227 return @available_filters if @available_filters
228 @available_filters = {
228 @available_filters = {
229 "status_id" => {
229 "status_id" => {
230 :type => :list_status, :order => 0,
230 :type => :list_status, :order => 0,
231 :values => IssueStatus.find(:all, :order => 'position').collect{|s| [s.name, s.id.to_s] }
231 :values => IssueStatus.find(:all, :order => 'position').collect{|s| [s.name, s.id.to_s] }
232 },
232 },
233 "tracker_id" => {
233 "tracker_id" => {
234 :type => :list, :order => 2, :values => trackers.collect{|s| [s.name, s.id.to_s] }
234 :type => :list, :order => 2, :values => trackers.collect{|s| [s.name, s.id.to_s] }
235 },
235 },
236 "priority_id" => {
236 "priority_id" => {
237 :type => :list, :order => 3, :values => IssuePriority.all.collect{|s| [s.name, s.id.to_s] }
237 :type => :list, :order => 3, :values => IssuePriority.all.collect{|s| [s.name, s.id.to_s] }
238 },
238 },
239 "subject" => { :type => :text, :order => 8 },
239 "subject" => { :type => :text, :order => 8 },
240 "created_on" => { :type => :date_past, :order => 9 },
240 "created_on" => { :type => :date_past, :order => 9 },
241 "updated_on" => { :type => :date_past, :order => 10 },
241 "updated_on" => { :type => :date_past, :order => 10 },
242 "start_date" => { :type => :date, :order => 11 },
242 "start_date" => { :type => :date, :order => 11 },
243 "due_date" => { :type => :date, :order => 12 },
243 "due_date" => { :type => :date, :order => 12 },
244 "estimated_hours" => { :type => :float, :order => 13 },
244 "estimated_hours" => { :type => :float, :order => 13 },
245 "done_ratio" => { :type => :integer, :order => 14 }
245 "done_ratio" => { :type => :integer, :order => 14 }
246 }
246 }
247 IssueRelation::TYPES.each do |relation_type, options|
247 IssueRelation::TYPES.each do |relation_type, options|
248 @available_filters[relation_type] = {
248 @available_filters[relation_type] = {
249 :type => :relation, :order => @available_filters.size + 100,
249 :type => :relation, :order => @available_filters.size + 100,
250 :label => options[:name]
250 :label => options[:name]
251 }
251 }
252 end
252 end
253 principals = []
253 principals = []
254 if project
254 if project
255 principals += project.principals.sort
255 principals += project.principals.sort
256 unless project.leaf?
256 unless project.leaf?
257 subprojects = project.descendants.visible.all
257 subprojects = project.descendants.visible.all
258 if subprojects.any?
258 if subprojects.any?
259 @available_filters["subproject_id"] = {
259 @available_filters["subproject_id"] = {
260 :type => :list_subprojects, :order => 13,
260 :type => :list_subprojects, :order => 13,
261 :values => subprojects.collect{|s| [s.name, s.id.to_s] }
261 :values => subprojects.collect{|s| [s.name, s.id.to_s] }
262 }
262 }
263 principals += Principal.member_of(subprojects)
263 principals += Principal.member_of(subprojects)
264 end
264 end
265 end
265 end
266 else
266 else
267 if all_projects.any?
267 if all_projects.any?
268 # members of visible projects
268 # members of visible projects
269 principals += Principal.member_of(all_projects)
269 principals += Principal.member_of(all_projects)
270 # project filter
270 # project filter
271 project_values = []
271 project_values = []
272 if User.current.logged? && User.current.memberships.any?
272 if User.current.logged? && User.current.memberships.any?
273 project_values << ["<< #{l(:label_my_projects).downcase} >>", "mine"]
273 project_values << ["<< #{l(:label_my_projects).downcase} >>", "mine"]
274 end
274 end
275 project_values += all_projects_values
275 project_values += all_projects_values
276 @available_filters["project_id"] = {
276 @available_filters["project_id"] = {
277 :type => :list, :order => 1, :values => project_values
277 :type => :list, :order => 1, :values => project_values
278 } unless project_values.empty?
278 } unless project_values.empty?
279 end
279 end
280 end
280 end
281 principals.uniq!
281 principals.uniq!
282 principals.sort!
282 principals.sort!
283 users = principals.select {|p| p.is_a?(User)}
283 users = principals.select {|p| p.is_a?(User)}
284
284
285 assigned_to_values = []
285 assigned_to_values = []
286 assigned_to_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged?
286 assigned_to_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged?
287 assigned_to_values += (Setting.issue_group_assignment? ?
287 assigned_to_values += (Setting.issue_group_assignment? ?
288 principals : users).collect{|s| [s.name, s.id.to_s] }
288 principals : users).collect{|s| [s.name, s.id.to_s] }
289 @available_filters["assigned_to_id"] = {
289 @available_filters["assigned_to_id"] = {
290 :type => :list_optional, :order => 4, :values => assigned_to_values
290 :type => :list_optional, :order => 4, :values => assigned_to_values
291 } unless assigned_to_values.empty?
291 } unless assigned_to_values.empty?
292
292
293 author_values = []
293 author_values = []
294 author_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged?
294 author_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged?
295 author_values += users.collect{|s| [s.name, s.id.to_s] }
295 author_values += users.collect{|s| [s.name, s.id.to_s] }
296 @available_filters["author_id"] = {
296 @available_filters["author_id"] = {
297 :type => :list, :order => 5, :values => author_values
297 :type => :list, :order => 5, :values => author_values
298 } unless author_values.empty?
298 } unless author_values.empty?
299
299
300 group_values = Group.all.collect {|g| [g.name, g.id.to_s] }
300 group_values = Group.all.collect {|g| [g.name, g.id.to_s] }
301 @available_filters["member_of_group"] = {
301 @available_filters["member_of_group"] = {
302 :type => :list_optional, :order => 6, :values => group_values
302 :type => :list_optional, :order => 6, :values => group_values
303 } unless group_values.empty?
303 } unless group_values.empty?
304
304
305 role_values = Role.givable.collect {|r| [r.name, r.id.to_s] }
305 role_values = Role.givable.collect {|r| [r.name, r.id.to_s] }
306 @available_filters["assigned_to_role"] = {
306 @available_filters["assigned_to_role"] = {
307 :type => :list_optional, :order => 7, :values => role_values
307 :type => :list_optional, :order => 7, :values => role_values
308 } unless role_values.empty?
308 } unless role_values.empty?
309
309
310 if User.current.logged?
310 if User.current.logged?
311 @available_filters["watcher_id"] = {
311 @available_filters["watcher_id"] = {
312 :type => :list, :order => 15, :values => [["<< #{l(:label_me)} >>", "me"]]
312 :type => :list, :order => 15, :values => [["<< #{l(:label_me)} >>", "me"]]
313 }
313 }
314 end
314 end
315
315
316 if project
316 if project
317 # project specific filters
317 # project specific filters
318 categories = project.issue_categories.all
318 categories = project.issue_categories.all
319 unless categories.empty?
319 unless categories.empty?
320 @available_filters["category_id"] = {
320 @available_filters["category_id"] = {
321 :type => :list_optional, :order => 6,
321 :type => :list_optional, :order => 6,
322 :values => categories.collect{|s| [s.name, s.id.to_s] }
322 :values => categories.collect{|s| [s.name, s.id.to_s] }
323 }
323 }
324 end
324 end
325 versions = project.shared_versions.all
325 versions = project.shared_versions.all
326 unless versions.empty?
326 unless versions.empty?
327 @available_filters["fixed_version_id"] = {
327 @available_filters["fixed_version_id"] = {
328 :type => :list_optional, :order => 7,
328 :type => :list_optional, :order => 7,
329 :values => versions.sort.collect{|s| ["#{s.project.name} - #{s.name}", s.id.to_s] }
329 :values => versions.sort.collect{|s| ["#{s.project.name} - #{s.name}", s.id.to_s] }
330 }
330 }
331 end
331 end
332 add_custom_fields_filters(project.all_issue_custom_fields)
332 add_custom_fields_filters(project.all_issue_custom_fields)
333 else
333 else
334 # global filters for cross project issue list
334 # global filters for cross project issue list
335 system_shared_versions = Version.visible.find_all_by_sharing('system')
335 system_shared_versions = Version.visible.find_all_by_sharing('system')
336 unless system_shared_versions.empty?
336 unless system_shared_versions.empty?
337 @available_filters["fixed_version_id"] = {
337 @available_filters["fixed_version_id"] = {
338 :type => :list_optional, :order => 7,
338 :type => :list_optional, :order => 7,
339 :values => system_shared_versions.sort.collect{|s|
339 :values => system_shared_versions.sort.collect{|s|
340 ["#{s.project.name} - #{s.name}", s.id.to_s]
340 ["#{s.project.name} - #{s.name}", s.id.to_s]
341 }
341 }
342 }
342 }
343 end
343 end
344 add_custom_fields_filters(
344 add_custom_fields_filters(
345 IssueCustomField.find(:all,
345 IssueCustomField.find(:all,
346 :conditions => {
346 :conditions => {
347 :is_filter => true,
347 :is_filter => true,
348 :is_for_all => true
348 :is_for_all => true
349 }))
349 }))
350 end
350 end
351 add_associations_custom_fields_filters :project, :author, :assigned_to, :fixed_version
351 add_associations_custom_fields_filters :project, :author, :assigned_to, :fixed_version
352 if User.current.allowed_to?(:set_issues_private, nil, :global => true) ||
352 if User.current.allowed_to?(:set_issues_private, nil, :global => true) ||
353 User.current.allowed_to?(:set_own_issues_private, nil, :global => true)
353 User.current.allowed_to?(:set_own_issues_private, nil, :global => true)
354 @available_filters["is_private"] = {
354 @available_filters["is_private"] = {
355 :type => :list, :order => 15,
355 :type => :list, :order => 16,
356 :values => [[l(:general_text_yes), "1"], [l(:general_text_no), "0"]]
356 :values => [[l(:general_text_yes), "1"], [l(:general_text_no), "0"]]
357 }
357 }
358 end
358 end
359 Tracker.disabled_core_fields(trackers).each {|field|
359 Tracker.disabled_core_fields(trackers).each {|field|
360 @available_filters.delete field
360 @available_filters.delete field
361 }
361 }
362 @available_filters.each do |field, options|
362 @available_filters.each do |field, options|
363 options[:name] ||= l(options[:label] || "field_#{field}".gsub(/_id$/, ''))
363 options[:name] ||= l(options[:label] || "field_#{field}".gsub(/_id$/, ''))
364 end
364 end
365 @available_filters
365 @available_filters
366 end
366 end
367
367
368 # Returns a representation of the available filters for JSON serialization
368 # Returns a representation of the available filters for JSON serialization
369 def available_filters_as_json
369 def available_filters_as_json
370 json = {}
370 json = {}
371 available_filters.each do |field, options|
371 available_filters.each do |field, options|
372 json[field] = options.slice(:type, :name, :values).stringify_keys
372 json[field] = options.slice(:type, :name, :values).stringify_keys
373 end
373 end
374 json
374 json
375 end
375 end
376
376
377 def all_projects
377 def all_projects
378 @all_projects ||= Project.visible.all
378 @all_projects ||= Project.visible.all
379 end
379 end
380
380
381 def all_projects_values
381 def all_projects_values
382 return @all_projects_values if @all_projects_values
382 return @all_projects_values if @all_projects_values
383
383
384 values = []
384 values = []
385 Project.project_tree(all_projects) do |p, level|
385 Project.project_tree(all_projects) do |p, level|
386 prefix = (level > 0 ? ('--' * level + ' ') : '')
386 prefix = (level > 0 ? ('--' * level + ' ') : '')
387 values << ["#{prefix}#{p.name}", p.id.to_s]
387 values << ["#{prefix}#{p.name}", p.id.to_s]
388 end
388 end
389 @all_projects_values = values
389 @all_projects_values = values
390 end
390 end
391
391
392 def add_filter(field, operator, values)
392 def add_filter(field, operator, values)
393 # values must be an array
393 # values must be an array
394 return unless values.nil? || values.is_a?(Array)
394 return unless values.nil? || values.is_a?(Array)
395 # check if field is defined as an available filter
395 # check if field is defined as an available filter
396 if available_filters.has_key? field
396 if available_filters.has_key? field
397 filter_options = available_filters[field]
397 filter_options = available_filters[field]
398 # check if operator is allowed for that filter
398 # check if operator is allowed for that filter
399 #if @@operators_by_filter_type[filter_options[:type]].include? operator
399 #if @@operators_by_filter_type[filter_options[:type]].include? operator
400 # allowed_values = values & ([""] + (filter_options[:values] || []).collect {|val| val[1]})
400 # allowed_values = values & ([""] + (filter_options[:values] || []).collect {|val| val[1]})
401 # filters[field] = {:operator => operator, :values => allowed_values } if (allowed_values.first and !allowed_values.first.empty?) or ["o", "c", "!*", "*", "t"].include? operator
401 # filters[field] = {:operator => operator, :values => allowed_values } if (allowed_values.first and !allowed_values.first.empty?) or ["o", "c", "!*", "*", "t"].include? operator
402 #end
402 #end
403 filters[field] = {:operator => operator, :values => (values || [''])}
403 filters[field] = {:operator => operator, :values => (values || [''])}
404 end
404 end
405 end
405 end
406
406
407 def add_short_filter(field, expression)
407 def add_short_filter(field, expression)
408 return unless expression && available_filters.has_key?(field)
408 return unless expression && available_filters.has_key?(field)
409 field_type = available_filters[field][:type]
409 field_type = available_filters[field][:type]
410 @@operators_by_filter_type[field_type].sort.reverse.detect do |operator|
410 @@operators_by_filter_type[field_type].sort.reverse.detect do |operator|
411 next unless expression =~ /^#{Regexp.escape(operator)}(.*)$/
411 next unless expression =~ /^#{Regexp.escape(operator)}(.*)$/
412 add_filter field, operator, $1.present? ? $1.split('|') : ['']
412 add_filter field, operator, $1.present? ? $1.split('|') : ['']
413 end || add_filter(field, '=', expression.split('|'))
413 end || add_filter(field, '=', expression.split('|'))
414 end
414 end
415
415
416 # Add multiple filters using +add_filter+
416 # Add multiple filters using +add_filter+
417 def add_filters(fields, operators, values)
417 def add_filters(fields, operators, values)
418 if fields.is_a?(Array) && operators.is_a?(Hash) && (values.nil? || values.is_a?(Hash))
418 if fields.is_a?(Array) && operators.is_a?(Hash) && (values.nil? || values.is_a?(Hash))
419 fields.each do |field|
419 fields.each do |field|
420 add_filter(field, operators[field], values && values[field])
420 add_filter(field, operators[field], values && values[field])
421 end
421 end
422 end
422 end
423 end
423 end
424
424
425 def has_filter?(field)
425 def has_filter?(field)
426 filters and filters[field]
426 filters and filters[field]
427 end
427 end
428
428
429 def type_for(field)
429 def type_for(field)
430 available_filters[field][:type] if available_filters.has_key?(field)
430 available_filters[field][:type] if available_filters.has_key?(field)
431 end
431 end
432
432
433 def operator_for(field)
433 def operator_for(field)
434 has_filter?(field) ? filters[field][:operator] : nil
434 has_filter?(field) ? filters[field][:operator] : nil
435 end
435 end
436
436
437 def values_for(field)
437 def values_for(field)
438 has_filter?(field) ? filters[field][:values] : nil
438 has_filter?(field) ? filters[field][:values] : nil
439 end
439 end
440
440
441 def value_for(field, index=0)
441 def value_for(field, index=0)
442 (values_for(field) || [])[index]
442 (values_for(field) || [])[index]
443 end
443 end
444
444
445 def label_for(field)
445 def label_for(field)
446 label = available_filters[field][:name] if available_filters.has_key?(field)
446 label = available_filters[field][:name] if available_filters.has_key?(field)
447 label ||= l("field_#{field.to_s.gsub(/_id$/, '')}", :default => field)
447 label ||= l("field_#{field.to_s.gsub(/_id$/, '')}", :default => field)
448 end
448 end
449
449
450 def available_columns
450 def available_columns
451 return @available_columns if @available_columns
451 return @available_columns if @available_columns
452 @available_columns = ::Query.available_columns.dup
452 @available_columns = ::Query.available_columns.dup
453 @available_columns += (project ?
453 @available_columns += (project ?
454 project.all_issue_custom_fields :
454 project.all_issue_custom_fields :
455 IssueCustomField.find(:all)
455 IssueCustomField.find(:all)
456 ).collect {|cf| QueryCustomFieldColumn.new(cf) }
456 ).collect {|cf| QueryCustomFieldColumn.new(cf) }
457
457
458 if User.current.allowed_to?(:view_time_entries, project, :global => true)
458 if User.current.allowed_to?(:view_time_entries, project, :global => true)
459 index = nil
459 index = nil
460 @available_columns.each_with_index {|column, i| index = i if column.name == :estimated_hours}
460 @available_columns.each_with_index {|column, i| index = i if column.name == :estimated_hours}
461 index = (index ? index + 1 : -1)
461 index = (index ? index + 1 : -1)
462 # insert the column after estimated_hours or at the end
462 # insert the column after estimated_hours or at the end
463 @available_columns.insert index, QueryColumn.new(:spent_hours,
463 @available_columns.insert index, QueryColumn.new(:spent_hours,
464 :sortable => "(SELECT COALESCE(SUM(hours), 0) FROM #{TimeEntry.table_name} WHERE #{TimeEntry.table_name}.issue_id = #{Issue.table_name}.id)",
464 :sortable => "(SELECT COALESCE(SUM(hours), 0) FROM #{TimeEntry.table_name} WHERE #{TimeEntry.table_name}.issue_id = #{Issue.table_name}.id)",
465 :default_order => 'desc',
465 :default_order => 'desc',
466 :caption => :label_spent_time
466 :caption => :label_spent_time
467 )
467 )
468 end
468 end
469
469
470 if User.current.allowed_to?(:set_issues_private, nil, :global => true) ||
470 if User.current.allowed_to?(:set_issues_private, nil, :global => true) ||
471 User.current.allowed_to?(:set_own_issues_private, nil, :global => true)
471 User.current.allowed_to?(:set_own_issues_private, nil, :global => true)
472 @available_columns << QueryColumn.new(:is_private, :sortable => "#{Issue.table_name}.is_private")
472 @available_columns << QueryColumn.new(:is_private, :sortable => "#{Issue.table_name}.is_private")
473 end
473 end
474
474
475 disabled_fields = Tracker.disabled_core_fields(trackers).map {|field| field.sub(/_id$/, '')}
475 disabled_fields = Tracker.disabled_core_fields(trackers).map {|field| field.sub(/_id$/, '')}
476 @available_columns.reject! {|column|
476 @available_columns.reject! {|column|
477 disabled_fields.include?(column.name.to_s)
477 disabled_fields.include?(column.name.to_s)
478 }
478 }
479
479
480 @available_columns
480 @available_columns
481 end
481 end
482
482
483 def self.available_columns=(v)
483 def self.available_columns=(v)
484 self.available_columns = (v)
484 self.available_columns = (v)
485 end
485 end
486
486
487 def self.add_available_column(column)
487 def self.add_available_column(column)
488 self.available_columns << (column) if column.is_a?(QueryColumn)
488 self.available_columns << (column) if column.is_a?(QueryColumn)
489 end
489 end
490
490
491 # Returns an array of columns that can be used to group the results
491 # Returns an array of columns that can be used to group the results
492 def groupable_columns
492 def groupable_columns
493 available_columns.select {|c| c.groupable}
493 available_columns.select {|c| c.groupable}
494 end
494 end
495
495
496 # Returns a Hash of columns and the key for sorting
496 # Returns a Hash of columns and the key for sorting
497 def sortable_columns
497 def sortable_columns
498 {'id' => "#{Issue.table_name}.id"}.merge(available_columns.inject({}) {|h, column|
498 {'id' => "#{Issue.table_name}.id"}.merge(available_columns.inject({}) {|h, column|
499 h[column.name.to_s] = column.sortable
499 h[column.name.to_s] = column.sortable
500 h
500 h
501 })
501 })
502 end
502 end
503
503
504 def columns
504 def columns
505 # preserve the column_names order
505 # preserve the column_names order
506 (has_default_columns? ? default_columns_names : column_names).collect do |name|
506 (has_default_columns? ? default_columns_names : column_names).collect do |name|
507 available_columns.find { |col| col.name == name }
507 available_columns.find { |col| col.name == name }
508 end.compact
508 end.compact
509 end
509 end
510
510
511 def default_columns_names
511 def default_columns_names
512 @default_columns_names ||= begin
512 @default_columns_names ||= begin
513 default_columns = Setting.issue_list_default_columns.map(&:to_sym)
513 default_columns = Setting.issue_list_default_columns.map(&:to_sym)
514
514
515 project.present? ? default_columns : [:project] | default_columns
515 project.present? ? default_columns : [:project] | default_columns
516 end
516 end
517 end
517 end
518
518
519 def column_names=(names)
519 def column_names=(names)
520 if names
520 if names
521 names = names.select {|n| n.is_a?(Symbol) || !n.blank? }
521 names = names.select {|n| n.is_a?(Symbol) || !n.blank? }
522 names = names.collect {|n| n.is_a?(Symbol) ? n : n.to_sym }
522 names = names.collect {|n| n.is_a?(Symbol) ? n : n.to_sym }
523 # Set column_names to nil if default columns
523 # Set column_names to nil if default columns
524 if names == default_columns_names
524 if names == default_columns_names
525 names = nil
525 names = nil
526 end
526 end
527 end
527 end
528 write_attribute(:column_names, names)
528 write_attribute(:column_names, names)
529 end
529 end
530
530
531 def has_column?(column)
531 def has_column?(column)
532 column_names && column_names.include?(column.is_a?(QueryColumn) ? column.name : column)
532 column_names && column_names.include?(column.is_a?(QueryColumn) ? column.name : column)
533 end
533 end
534
534
535 def has_default_columns?
535 def has_default_columns?
536 column_names.nil? || column_names.empty?
536 column_names.nil? || column_names.empty?
537 end
537 end
538
538
539 def sort_criteria=(arg)
539 def sort_criteria=(arg)
540 c = []
540 c = []
541 if arg.is_a?(Hash)
541 if arg.is_a?(Hash)
542 arg = arg.keys.sort.collect {|k| arg[k]}
542 arg = arg.keys.sort.collect {|k| arg[k]}
543 end
543 end
544 c = arg.select {|k,o| !k.to_s.blank?}.slice(0,3).collect {|k,o| [k.to_s, o == 'desc' ? o : 'asc']}
544 c = arg.select {|k,o| !k.to_s.blank?}.slice(0,3).collect {|k,o| [k.to_s, o == 'desc' ? o : 'asc']}
545 write_attribute(:sort_criteria, c)
545 write_attribute(:sort_criteria, c)
546 end
546 end
547
547
548 def sort_criteria
548 def sort_criteria
549 read_attribute(:sort_criteria) || []
549 read_attribute(:sort_criteria) || []
550 end
550 end
551
551
552 def sort_criteria_key(arg)
552 def sort_criteria_key(arg)
553 sort_criteria && sort_criteria[arg] && sort_criteria[arg].first
553 sort_criteria && sort_criteria[arg] && sort_criteria[arg].first
554 end
554 end
555
555
556 def sort_criteria_order(arg)
556 def sort_criteria_order(arg)
557 sort_criteria && sort_criteria[arg] && sort_criteria[arg].last
557 sort_criteria && sort_criteria[arg] && sort_criteria[arg].last
558 end
558 end
559
559
560 # Returns the SQL sort order that should be prepended for grouping
560 # Returns the SQL sort order that should be prepended for grouping
561 def group_by_sort_order
561 def group_by_sort_order
562 if grouped? && (column = group_by_column)
562 if grouped? && (column = group_by_column)
563 column.sortable.is_a?(Array) ?
563 column.sortable.is_a?(Array) ?
564 column.sortable.collect {|s| "#{s} #{column.default_order}"}.join(',') :
564 column.sortable.collect {|s| "#{s} #{column.default_order}"}.join(',') :
565 "#{column.sortable} #{column.default_order}"
565 "#{column.sortable} #{column.default_order}"
566 end
566 end
567 end
567 end
568
568
569 # Returns true if the query is a grouped query
569 # Returns true if the query is a grouped query
570 def grouped?
570 def grouped?
571 !group_by_column.nil?
571 !group_by_column.nil?
572 end
572 end
573
573
574 def group_by_column
574 def group_by_column
575 groupable_columns.detect {|c| c.groupable && c.name.to_s == group_by}
575 groupable_columns.detect {|c| c.groupable && c.name.to_s == group_by}
576 end
576 end
577
577
578 def group_by_statement
578 def group_by_statement
579 group_by_column.try(:groupable)
579 group_by_column.try(:groupable)
580 end
580 end
581
581
582 def project_statement
582 def project_statement
583 project_clauses = []
583 project_clauses = []
584 if project && !project.descendants.active.empty?
584 if project && !project.descendants.active.empty?
585 ids = [project.id]
585 ids = [project.id]
586 if has_filter?("subproject_id")
586 if has_filter?("subproject_id")
587 case operator_for("subproject_id")
587 case operator_for("subproject_id")
588 when '='
588 when '='
589 # include the selected subprojects
589 # include the selected subprojects
590 ids += values_for("subproject_id").each(&:to_i)
590 ids += values_for("subproject_id").each(&:to_i)
591 when '!*'
591 when '!*'
592 # main project only
592 # main project only
593 else
593 else
594 # all subprojects
594 # all subprojects
595 ids += project.descendants.collect(&:id)
595 ids += project.descendants.collect(&:id)
596 end
596 end
597 elsif Setting.display_subprojects_issues?
597 elsif Setting.display_subprojects_issues?
598 ids += project.descendants.collect(&:id)
598 ids += project.descendants.collect(&:id)
599 end
599 end
600 project_clauses << "#{Project.table_name}.id IN (%s)" % ids.join(',')
600 project_clauses << "#{Project.table_name}.id IN (%s)" % ids.join(',')
601 elsif project
601 elsif project
602 project_clauses << "#{Project.table_name}.id = %d" % project.id
602 project_clauses << "#{Project.table_name}.id = %d" % project.id
603 end
603 end
604 project_clauses.any? ? project_clauses.join(' AND ') : nil
604 project_clauses.any? ? project_clauses.join(' AND ') : nil
605 end
605 end
606
606
607 def statement
607 def statement
608 # filters clauses
608 # filters clauses
609 filters_clauses = []
609 filters_clauses = []
610 filters.each_key do |field|
610 filters.each_key do |field|
611 next if field == "subproject_id"
611 next if field == "subproject_id"
612 v = values_for(field).clone
612 v = values_for(field).clone
613 next unless v and !v.empty?
613 next unless v and !v.empty?
614 operator = operator_for(field)
614 operator = operator_for(field)
615
615
616 # "me" value subsitution
616 # "me" value subsitution
617 if %w(assigned_to_id author_id watcher_id).include?(field)
617 if %w(assigned_to_id author_id watcher_id).include?(field)
618 if v.delete("me")
618 if v.delete("me")
619 if User.current.logged?
619 if User.current.logged?
620 v.push(User.current.id.to_s)
620 v.push(User.current.id.to_s)
621 v += User.current.group_ids.map(&:to_s) if field == 'assigned_to_id'
621 v += User.current.group_ids.map(&:to_s) if field == 'assigned_to_id'
622 else
622 else
623 v.push("0")
623 v.push("0")
624 end
624 end
625 end
625 end
626 end
626 end
627
627
628 if field == 'project_id'
628 if field == 'project_id'
629 if v.delete('mine')
629 if v.delete('mine')
630 v += User.current.memberships.map(&:project_id).map(&:to_s)
630 v += User.current.memberships.map(&:project_id).map(&:to_s)
631 end
631 end
632 end
632 end
633
633
634 if field =~ /cf_(\d+)$/
634 if field =~ /cf_(\d+)$/
635 # custom field
635 # custom field
636 filters_clauses << sql_for_custom_field(field, operator, v, $1)
636 filters_clauses << sql_for_custom_field(field, operator, v, $1)
637 elsif respond_to?("sql_for_#{field}_field")
637 elsif respond_to?("sql_for_#{field}_field")
638 # specific statement
638 # specific statement
639 filters_clauses << send("sql_for_#{field}_field", field, operator, v)
639 filters_clauses << send("sql_for_#{field}_field", field, operator, v)
640 else
640 else
641 # regular field
641 # regular field
642 filters_clauses << '(' + sql_for_field(field, operator, v, Issue.table_name, field) + ')'
642 filters_clauses << '(' + sql_for_field(field, operator, v, Issue.table_name, field) + ')'
643 end
643 end
644 end if filters and valid?
644 end if filters and valid?
645
645
646 filters_clauses << project_statement
646 filters_clauses << project_statement
647 filters_clauses.reject!(&:blank?)
647 filters_clauses.reject!(&:blank?)
648
648
649 filters_clauses.any? ? filters_clauses.join(' AND ') : nil
649 filters_clauses.any? ? filters_clauses.join(' AND ') : nil
650 end
650 end
651
651
652 # Returns the issue count
652 # Returns the issue count
653 def issue_count
653 def issue_count
654 Issue.visible.count(:include => [:status, :project], :conditions => statement)
654 Issue.visible.count(:include => [:status, :project], :conditions => statement)
655 rescue ::ActiveRecord::StatementInvalid => e
655 rescue ::ActiveRecord::StatementInvalid => e
656 raise StatementInvalid.new(e.message)
656 raise StatementInvalid.new(e.message)
657 end
657 end
658
658
659 # Returns the issue count by group or nil if query is not grouped
659 # Returns the issue count by group or nil if query is not grouped
660 def issue_count_by_group
660 def issue_count_by_group
661 r = nil
661 r = nil
662 if grouped?
662 if grouped?
663 begin
663 begin
664 # Rails3 will raise an (unexpected) RecordNotFound if there's only a nil group value
664 # Rails3 will raise an (unexpected) RecordNotFound if there's only a nil group value
665 r = Issue.visible.count(:group => group_by_statement, :include => [:status, :project], :conditions => statement)
665 r = Issue.visible.count(:group => group_by_statement, :include => [:status, :project], :conditions => statement)
666 rescue ActiveRecord::RecordNotFound
666 rescue ActiveRecord::RecordNotFound
667 r = {nil => issue_count}
667 r = {nil => issue_count}
668 end
668 end
669 c = group_by_column
669 c = group_by_column
670 if c.is_a?(QueryCustomFieldColumn)
670 if c.is_a?(QueryCustomFieldColumn)
671 r = r.keys.inject({}) {|h, k| h[c.custom_field.cast_value(k)] = r[k]; h}
671 r = r.keys.inject({}) {|h, k| h[c.custom_field.cast_value(k)] = r[k]; h}
672 end
672 end
673 end
673 end
674 r
674 r
675 rescue ::ActiveRecord::StatementInvalid => e
675 rescue ::ActiveRecord::StatementInvalid => e
676 raise StatementInvalid.new(e.message)
676 raise StatementInvalid.new(e.message)
677 end
677 end
678
678
679 # Returns the issues
679 # Returns the issues
680 # Valid options are :order, :offset, :limit, :include, :conditions
680 # Valid options are :order, :offset, :limit, :include, :conditions
681 def issues(options={})
681 def issues(options={})
682 order_option = [group_by_sort_order, options[:order]].reject {|s| s.blank?}.join(',')
682 order_option = [group_by_sort_order, options[:order]].reject {|s| s.blank?}.join(',')
683 order_option = nil if order_option.blank?
683 order_option = nil if order_option.blank?
684
684
685 issues = Issue.visible.scoped(:conditions => options[:conditions]).find :all, :include => ([:status, :project] + (options[:include] || [])).uniq,
685 issues = Issue.visible.scoped(:conditions => options[:conditions]).find :all, :include => ([:status, :project] + (options[:include] || [])).uniq,
686 :conditions => statement,
686 :conditions => statement,
687 :order => order_option,
687 :order => order_option,
688 :joins => joins_for_order_statement(order_option),
688 :joins => joins_for_order_statement(order_option),
689 :limit => options[:limit],
689 :limit => options[:limit],
690 :offset => options[:offset]
690 :offset => options[:offset]
691
691
692 if has_column?(:spent_hours)
692 if has_column?(:spent_hours)
693 Issue.load_visible_spent_hours(issues)
693 Issue.load_visible_spent_hours(issues)
694 end
694 end
695 if has_column?(:relations)
695 if has_column?(:relations)
696 Issue.load_visible_relations(issues)
696 Issue.load_visible_relations(issues)
697 end
697 end
698 issues
698 issues
699 rescue ::ActiveRecord::StatementInvalid => e
699 rescue ::ActiveRecord::StatementInvalid => e
700 raise StatementInvalid.new(e.message)
700 raise StatementInvalid.new(e.message)
701 end
701 end
702
702
703 # Returns the issues ids
703 # Returns the issues ids
704 def issue_ids(options={})
704 def issue_ids(options={})
705 order_option = [group_by_sort_order, options[:order]].reject {|s| s.blank?}.join(',')
705 order_option = [group_by_sort_order, options[:order]].reject {|s| s.blank?}.join(',')
706 order_option = nil if order_option.blank?
706 order_option = nil if order_option.blank?
707
707
708 Issue.visible.scoped(:conditions => options[:conditions]).scoped(:include => ([:status, :project] + (options[:include] || [])).uniq,
708 Issue.visible.scoped(:conditions => options[:conditions]).scoped(:include => ([:status, :project] + (options[:include] || [])).uniq,
709 :conditions => statement,
709 :conditions => statement,
710 :order => order_option,
710 :order => order_option,
711 :joins => joins_for_order_statement(order_option),
711 :joins => joins_for_order_statement(order_option),
712 :limit => options[:limit],
712 :limit => options[:limit],
713 :offset => options[:offset]).find_ids
713 :offset => options[:offset]).find_ids
714 rescue ::ActiveRecord::StatementInvalid => e
714 rescue ::ActiveRecord::StatementInvalid => e
715 raise StatementInvalid.new(e.message)
715 raise StatementInvalid.new(e.message)
716 end
716 end
717
717
718 # Returns the journals
718 # Returns the journals
719 # Valid options are :order, :offset, :limit
719 # Valid options are :order, :offset, :limit
720 def journals(options={})
720 def journals(options={})
721 Journal.visible.find :all, :include => [:details, :user, {:issue => [:project, :author, :tracker, :status]}],
721 Journal.visible.find :all, :include => [:details, :user, {:issue => [:project, :author, :tracker, :status]}],
722 :conditions => statement,
722 :conditions => statement,
723 :order => options[:order],
723 :order => options[:order],
724 :limit => options[:limit],
724 :limit => options[:limit],
725 :offset => options[:offset]
725 :offset => options[:offset]
726 rescue ::ActiveRecord::StatementInvalid => e
726 rescue ::ActiveRecord::StatementInvalid => e
727 raise StatementInvalid.new(e.message)
727 raise StatementInvalid.new(e.message)
728 end
728 end
729
729
730 # Returns the versions
730 # Returns the versions
731 # Valid options are :conditions
731 # Valid options are :conditions
732 def versions(options={})
732 def versions(options={})
733 Version.visible.scoped(:conditions => options[:conditions]).find :all, :include => :project, :conditions => project_statement
733 Version.visible.scoped(:conditions => options[:conditions]).find :all, :include => :project, :conditions => project_statement
734 rescue ::ActiveRecord::StatementInvalid => e
734 rescue ::ActiveRecord::StatementInvalid => e
735 raise StatementInvalid.new(e.message)
735 raise StatementInvalid.new(e.message)
736 end
736 end
737
737
738 def sql_for_watcher_id_field(field, operator, value)
738 def sql_for_watcher_id_field(field, operator, value)
739 db_table = Watcher.table_name
739 db_table = Watcher.table_name
740 "#{Issue.table_name}.id #{ operator == '=' ? 'IN' : 'NOT IN' } (SELECT #{db_table}.watchable_id FROM #{db_table} WHERE #{db_table}.watchable_type='Issue' AND " +
740 "#{Issue.table_name}.id #{ operator == '=' ? 'IN' : 'NOT IN' } (SELECT #{db_table}.watchable_id FROM #{db_table} WHERE #{db_table}.watchable_type='Issue' AND " +
741 sql_for_field(field, '=', value, db_table, 'user_id') + ')'
741 sql_for_field(field, '=', value, db_table, 'user_id') + ')'
742 end
742 end
743
743
744 def sql_for_member_of_group_field(field, operator, value)
744 def sql_for_member_of_group_field(field, operator, value)
745 if operator == '*' # Any group
745 if operator == '*' # Any group
746 groups = Group.all
746 groups = Group.all
747 operator = '=' # Override the operator since we want to find by assigned_to
747 operator = '=' # Override the operator since we want to find by assigned_to
748 elsif operator == "!*"
748 elsif operator == "!*"
749 groups = Group.all
749 groups = Group.all
750 operator = '!' # Override the operator since we want to find by assigned_to
750 operator = '!' # Override the operator since we want to find by assigned_to
751 else
751 else
752 groups = Group.find_all_by_id(value)
752 groups = Group.find_all_by_id(value)
753 end
753 end
754 groups ||= []
754 groups ||= []
755
755
756 members_of_groups = groups.inject([]) {|user_ids, group|
756 members_of_groups = groups.inject([]) {|user_ids, group|
757 if group && group.user_ids.present?
757 if group && group.user_ids.present?
758 user_ids << group.user_ids
758 user_ids << group.user_ids
759 end
759 end
760 user_ids.flatten.uniq.compact
760 user_ids.flatten.uniq.compact
761 }.sort.collect(&:to_s)
761 }.sort.collect(&:to_s)
762
762
763 '(' + sql_for_field("assigned_to_id", operator, members_of_groups, Issue.table_name, "assigned_to_id", false) + ')'
763 '(' + sql_for_field("assigned_to_id", operator, members_of_groups, Issue.table_name, "assigned_to_id", false) + ')'
764 end
764 end
765
765
766 def sql_for_assigned_to_role_field(field, operator, value)
766 def sql_for_assigned_to_role_field(field, operator, value)
767 case operator
767 case operator
768 when "*", "!*" # Member / Not member
768 when "*", "!*" # Member / Not member
769 sw = operator == "!*" ? 'NOT' : ''
769 sw = operator == "!*" ? 'NOT' : ''
770 nl = operator == "!*" ? "#{Issue.table_name}.assigned_to_id IS NULL OR" : ''
770 nl = operator == "!*" ? "#{Issue.table_name}.assigned_to_id IS NULL OR" : ''
771 "(#{nl} #{Issue.table_name}.assigned_to_id #{sw} IN (SELECT DISTINCT #{Member.table_name}.user_id FROM #{Member.table_name}" +
771 "(#{nl} #{Issue.table_name}.assigned_to_id #{sw} IN (SELECT DISTINCT #{Member.table_name}.user_id FROM #{Member.table_name}" +
772 " WHERE #{Member.table_name}.project_id = #{Issue.table_name}.project_id))"
772 " WHERE #{Member.table_name}.project_id = #{Issue.table_name}.project_id))"
773 when "=", "!"
773 when "=", "!"
774 role_cond = value.any? ?
774 role_cond = value.any? ?
775 "#{MemberRole.table_name}.role_id IN (" + value.collect{|val| "'#{connection.quote_string(val)}'"}.join(",") + ")" :
775 "#{MemberRole.table_name}.role_id IN (" + value.collect{|val| "'#{connection.quote_string(val)}'"}.join(",") + ")" :
776 "1=0"
776 "1=0"
777
777
778 sw = operator == "!" ? 'NOT' : ''
778 sw = operator == "!" ? 'NOT' : ''
779 nl = operator == "!" ? "#{Issue.table_name}.assigned_to_id IS NULL OR" : ''
779 nl = operator == "!" ? "#{Issue.table_name}.assigned_to_id IS NULL OR" : ''
780 "(#{nl} #{Issue.table_name}.assigned_to_id #{sw} IN (SELECT DISTINCT #{Member.table_name}.user_id FROM #{Member.table_name}, #{MemberRole.table_name}" +
780 "(#{nl} #{Issue.table_name}.assigned_to_id #{sw} IN (SELECT DISTINCT #{Member.table_name}.user_id FROM #{Member.table_name}, #{MemberRole.table_name}" +
781 " WHERE #{Member.table_name}.project_id = #{Issue.table_name}.project_id AND #{Member.table_name}.id = #{MemberRole.table_name}.member_id AND #{role_cond}))"
781 " WHERE #{Member.table_name}.project_id = #{Issue.table_name}.project_id AND #{Member.table_name}.id = #{MemberRole.table_name}.member_id AND #{role_cond}))"
782 end
782 end
783 end
783 end
784
784
785 def sql_for_is_private_field(field, operator, value)
785 def sql_for_is_private_field(field, operator, value)
786 op = (operator == "=" ? 'IN' : 'NOT IN')
786 op = (operator == "=" ? 'IN' : 'NOT IN')
787 va = value.map {|v| v == '0' ? connection.quoted_false : connection.quoted_true}.uniq.join(',')
787 va = value.map {|v| v == '0' ? connection.quoted_false : connection.quoted_true}.uniq.join(',')
788
788
789 "#{Issue.table_name}.is_private #{op} (#{va})"
789 "#{Issue.table_name}.is_private #{op} (#{va})"
790 end
790 end
791
791
792 def sql_for_relations(field, operator, value, options={})
792 def sql_for_relations(field, operator, value, options={})
793 relation_options = IssueRelation::TYPES[field]
793 relation_options = IssueRelation::TYPES[field]
794 return relation_options unless relation_options
794 return relation_options unless relation_options
795
795
796 relation_type = field
796 relation_type = field
797 join_column, target_join_column = "issue_from_id", "issue_to_id"
797 join_column, target_join_column = "issue_from_id", "issue_to_id"
798 if relation_options[:reverse] || options[:reverse]
798 if relation_options[:reverse] || options[:reverse]
799 relation_type = relation_options[:reverse] || relation_type
799 relation_type = relation_options[:reverse] || relation_type
800 join_column, target_join_column = target_join_column, join_column
800 join_column, target_join_column = target_join_column, join_column
801 end
801 end
802
802
803 sql = case operator
803 sql = case operator
804 when "*", "!*"
804 when "*", "!*"
805 op = (operator == "*" ? 'IN' : 'NOT IN')
805 op = (operator == "*" ? 'IN' : 'NOT IN')
806 "#{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)}')"
806 "#{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)}')"
807 when "=", "!"
807 when "=", "!"
808 op = (operator == "=" ? 'IN' : 'NOT IN')
808 op = (operator == "=" ? 'IN' : 'NOT IN')
809 "#{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})"
809 "#{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})"
810 when "=p", "=!p"
810 when "=p", "=!p"
811 op = (operator == "=p" ? '=' : '<>')
811 op = (operator == "=p" ? '=' : '<>')
812 "#{Issue.table_name}.id IN (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 #{op} #{value.first.to_i})"
812 "#{Issue.table_name}.id IN (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 #{op} #{value.first.to_i})"
813 end
813 end
814
814
815 if relation_options[:sym] == field && !options[:reverse]
815 if relation_options[:sym] == field && !options[:reverse]
816 sqls = [sql, sql_for_relations(field, operator, value, :reverse => true)]
816 sqls = [sql, sql_for_relations(field, operator, value, :reverse => true)]
817 sqls.join(["!", "!*"].include?(operator) ? " AND " : " OR ")
817 sqls.join(["!", "!*"].include?(operator) ? " AND " : " OR ")
818 else
818 else
819 sql
819 sql
820 end
820 end
821 end
821 end
822
822
823 IssueRelation::TYPES.keys.each do |relation_type|
823 IssueRelation::TYPES.keys.each do |relation_type|
824 alias_method "sql_for_#{relation_type}_field".to_sym, :sql_for_relations
824 alias_method "sql_for_#{relation_type}_field".to_sym, :sql_for_relations
825 end
825 end
826
826
827 private
827 private
828
828
829 def sql_for_custom_field(field, operator, value, custom_field_id)
829 def sql_for_custom_field(field, operator, value, custom_field_id)
830 db_table = CustomValue.table_name
830 db_table = CustomValue.table_name
831 db_field = 'value'
831 db_field = 'value'
832 filter = @available_filters[field]
832 filter = @available_filters[field]
833 return nil unless filter
833 return nil unless filter
834 if filter[:format] == 'user'
834 if filter[:format] == 'user'
835 if value.delete('me')
835 if value.delete('me')
836 value.push User.current.id.to_s
836 value.push User.current.id.to_s
837 end
837 end
838 end
838 end
839 not_in = nil
839 not_in = nil
840 if operator == '!'
840 if operator == '!'
841 # Makes ! operator work for custom fields with multiple values
841 # Makes ! operator work for custom fields with multiple values
842 operator = '='
842 operator = '='
843 not_in = 'NOT'
843 not_in = 'NOT'
844 end
844 end
845 customized_key = "id"
845 customized_key = "id"
846 customized_class = Issue
846 customized_class = Issue
847 if field =~ /^(.+)\.cf_/
847 if field =~ /^(.+)\.cf_/
848 assoc = $1
848 assoc = $1
849 customized_key = "#{assoc}_id"
849 customized_key = "#{assoc}_id"
850 customized_class = Issue.reflect_on_association(assoc.to_sym).klass.base_class rescue nil
850 customized_class = Issue.reflect_on_association(assoc.to_sym).klass.base_class rescue nil
851 raise "Unknown Issue association #{assoc}" unless customized_class
851 raise "Unknown Issue association #{assoc}" unless customized_class
852 end
852 end
853 "#{Issue.table_name}.#{customized_key} #{not_in} IN (SELECT #{customized_class.table_name}.id FROM #{customized_class.table_name} LEFT OUTER JOIN #{db_table} ON #{db_table}.customized_type='#{customized_class}' AND #{db_table}.customized_id=#{customized_class.table_name}.id AND #{db_table}.custom_field_id=#{custom_field_id} WHERE " +
853 "#{Issue.table_name}.#{customized_key} #{not_in} IN (SELECT #{customized_class.table_name}.id FROM #{customized_class.table_name} LEFT OUTER JOIN #{db_table} ON #{db_table}.customized_type='#{customized_class}' AND #{db_table}.customized_id=#{customized_class.table_name}.id AND #{db_table}.custom_field_id=#{custom_field_id} WHERE " +
854 sql_for_field(field, operator, value, db_table, db_field, true) + ')'
854 sql_for_field(field, operator, value, db_table, db_field, true) + ')'
855 end
855 end
856
856
857 # Helper method to generate the WHERE sql for a +field+, +operator+ and a +value+
857 # Helper method to generate the WHERE sql for a +field+, +operator+ and a +value+
858 def sql_for_field(field, operator, value, db_table, db_field, is_custom_filter=false)
858 def sql_for_field(field, operator, value, db_table, db_field, is_custom_filter=false)
859 sql = ''
859 sql = ''
860 case operator
860 case operator
861 when "="
861 when "="
862 if value.any?
862 if value.any?
863 case type_for(field)
863 case type_for(field)
864 when :date, :date_past
864 when :date, :date_past
865 sql = date_clause(db_table, db_field, (Date.parse(value.first) rescue nil), (Date.parse(value.first) rescue nil))
865 sql = date_clause(db_table, db_field, (Date.parse(value.first) rescue nil), (Date.parse(value.first) rescue nil))
866 when :integer
866 when :integer
867 if is_custom_filter
867 if is_custom_filter
868 sql = "(#{db_table}.#{db_field} <> '' AND CAST(#{db_table}.#{db_field} AS decimal(60,3)) = #{value.first.to_i})"
868 sql = "(#{db_table}.#{db_field} <> '' AND CAST(#{db_table}.#{db_field} AS decimal(60,3)) = #{value.first.to_i})"
869 else
869 else
870 sql = "#{db_table}.#{db_field} = #{value.first.to_i}"
870 sql = "#{db_table}.#{db_field} = #{value.first.to_i}"
871 end
871 end
872 when :float
872 when :float
873 if is_custom_filter
873 if is_custom_filter
874 sql = "(#{db_table}.#{db_field} <> '' AND CAST(#{db_table}.#{db_field} AS decimal(60,3)) BETWEEN #{value.first.to_f - 1e-5} AND #{value.first.to_f + 1e-5})"
874 sql = "(#{db_table}.#{db_field} <> '' AND CAST(#{db_table}.#{db_field} AS decimal(60,3)) BETWEEN #{value.first.to_f - 1e-5} AND #{value.first.to_f + 1e-5})"
875 else
875 else
876 sql = "#{db_table}.#{db_field} BETWEEN #{value.first.to_f - 1e-5} AND #{value.first.to_f + 1e-5}"
876 sql = "#{db_table}.#{db_field} BETWEEN #{value.first.to_f - 1e-5} AND #{value.first.to_f + 1e-5}"
877 end
877 end
878 else
878 else
879 sql = "#{db_table}.#{db_field} IN (" + value.collect{|val| "'#{connection.quote_string(val)}'"}.join(",") + ")"
879 sql = "#{db_table}.#{db_field} IN (" + value.collect{|val| "'#{connection.quote_string(val)}'"}.join(",") + ")"
880 end
880 end
881 else
881 else
882 # IN an empty set
882 # IN an empty set
883 sql = "1=0"
883 sql = "1=0"
884 end
884 end
885 when "!"
885 when "!"
886 if value.any?
886 if value.any?
887 sql = "(#{db_table}.#{db_field} IS NULL OR #{db_table}.#{db_field} NOT IN (" + value.collect{|val| "'#{connection.quote_string(val)}'"}.join(",") + "))"
887 sql = "(#{db_table}.#{db_field} IS NULL OR #{db_table}.#{db_field} NOT IN (" + value.collect{|val| "'#{connection.quote_string(val)}'"}.join(",") + "))"
888 else
888 else
889 # NOT IN an empty set
889 # NOT IN an empty set
890 sql = "1=1"
890 sql = "1=1"
891 end
891 end
892 when "!*"
892 when "!*"
893 sql = "#{db_table}.#{db_field} IS NULL"
893 sql = "#{db_table}.#{db_field} IS NULL"
894 sql << " OR #{db_table}.#{db_field} = ''" if is_custom_filter
894 sql << " OR #{db_table}.#{db_field} = ''" if is_custom_filter
895 when "*"
895 when "*"
896 sql = "#{db_table}.#{db_field} IS NOT NULL"
896 sql = "#{db_table}.#{db_field} IS NOT NULL"
897 sql << " AND #{db_table}.#{db_field} <> ''" if is_custom_filter
897 sql << " AND #{db_table}.#{db_field} <> ''" if is_custom_filter
898 when ">="
898 when ">="
899 if [:date, :date_past].include?(type_for(field))
899 if [:date, :date_past].include?(type_for(field))
900 sql = date_clause(db_table, db_field, (Date.parse(value.first) rescue nil), nil)
900 sql = date_clause(db_table, db_field, (Date.parse(value.first) rescue nil), nil)
901 else
901 else
902 if is_custom_filter
902 if is_custom_filter
903 sql = "(#{db_table}.#{db_field} <> '' AND CAST(#{db_table}.#{db_field} AS decimal(60,3)) >= #{value.first.to_f})"
903 sql = "(#{db_table}.#{db_field} <> '' AND CAST(#{db_table}.#{db_field} AS decimal(60,3)) >= #{value.first.to_f})"
904 else
904 else
905 sql = "#{db_table}.#{db_field} >= #{value.first.to_f}"
905 sql = "#{db_table}.#{db_field} >= #{value.first.to_f}"
906 end
906 end
907 end
907 end
908 when "<="
908 when "<="
909 if [:date, :date_past].include?(type_for(field))
909 if [:date, :date_past].include?(type_for(field))
910 sql = date_clause(db_table, db_field, nil, (Date.parse(value.first) rescue nil))
910 sql = date_clause(db_table, db_field, nil, (Date.parse(value.first) rescue nil))
911 else
911 else
912 if is_custom_filter
912 if is_custom_filter
913 sql = "(#{db_table}.#{db_field} <> '' AND CAST(#{db_table}.#{db_field} AS decimal(60,3)) <= #{value.first.to_f})"
913 sql = "(#{db_table}.#{db_field} <> '' AND CAST(#{db_table}.#{db_field} AS decimal(60,3)) <= #{value.first.to_f})"
914 else
914 else
915 sql = "#{db_table}.#{db_field} <= #{value.first.to_f}"
915 sql = "#{db_table}.#{db_field} <= #{value.first.to_f}"
916 end
916 end
917 end
917 end
918 when "><"
918 when "><"
919 if [:date, :date_past].include?(type_for(field))
919 if [:date, :date_past].include?(type_for(field))
920 sql = date_clause(db_table, db_field, (Date.parse(value[0]) rescue nil), (Date.parse(value[1]) rescue nil))
920 sql = date_clause(db_table, db_field, (Date.parse(value[0]) rescue nil), (Date.parse(value[1]) rescue nil))
921 else
921 else
922 if is_custom_filter
922 if is_custom_filter
923 sql = "(#{db_table}.#{db_field} <> '' AND CAST(#{db_table}.#{db_field} AS decimal(60,3)) BETWEEN #{value[0].to_f} AND #{value[1].to_f})"
923 sql = "(#{db_table}.#{db_field} <> '' AND CAST(#{db_table}.#{db_field} AS decimal(60,3)) BETWEEN #{value[0].to_f} AND #{value[1].to_f})"
924 else
924 else
925 sql = "#{db_table}.#{db_field} BETWEEN #{value[0].to_f} AND #{value[1].to_f}"
925 sql = "#{db_table}.#{db_field} BETWEEN #{value[0].to_f} AND #{value[1].to_f}"
926 end
926 end
927 end
927 end
928 when "o"
928 when "o"
929 sql = "#{Issue.table_name}.status_id IN (SELECT id FROM #{IssueStatus.table_name} WHERE is_closed=#{connection.quoted_false})" if field == "status_id"
929 sql = "#{Issue.table_name}.status_id IN (SELECT id FROM #{IssueStatus.table_name} WHERE is_closed=#{connection.quoted_false})" if field == "status_id"
930 when "c"
930 when "c"
931 sql = "#{Issue.table_name}.status_id IN (SELECT id FROM #{IssueStatus.table_name} WHERE is_closed=#{connection.quoted_true})" if field == "status_id"
931 sql = "#{Issue.table_name}.status_id IN (SELECT id FROM #{IssueStatus.table_name} WHERE is_closed=#{connection.quoted_true})" if field == "status_id"
932 when ">t-"
932 when ">t-"
933 sql = relative_date_clause(db_table, db_field, - value.first.to_i, 0)
933 sql = relative_date_clause(db_table, db_field, - value.first.to_i, 0)
934 when "<t-"
934 when "<t-"
935 sql = relative_date_clause(db_table, db_field, nil, - value.first.to_i)
935 sql = relative_date_clause(db_table, db_field, nil, - value.first.to_i)
936 when "t-"
936 when "t-"
937 sql = relative_date_clause(db_table, db_field, - value.first.to_i, - value.first.to_i)
937 sql = relative_date_clause(db_table, db_field, - value.first.to_i, - value.first.to_i)
938 when ">t+"
938 when ">t+"
939 sql = relative_date_clause(db_table, db_field, value.first.to_i, nil)
939 sql = relative_date_clause(db_table, db_field, value.first.to_i, nil)
940 when "<t+"
940 when "<t+"
941 sql = relative_date_clause(db_table, db_field, 0, value.first.to_i)
941 sql = relative_date_clause(db_table, db_field, 0, value.first.to_i)
942 when "t+"
942 when "t+"
943 sql = relative_date_clause(db_table, db_field, value.first.to_i, value.first.to_i)
943 sql = relative_date_clause(db_table, db_field, value.first.to_i, value.first.to_i)
944 when "t"
944 when "t"
945 sql = relative_date_clause(db_table, db_field, 0, 0)
945 sql = relative_date_clause(db_table, db_field, 0, 0)
946 when "w"
946 when "w"
947 first_day_of_week = l(:general_first_day_of_week).to_i
947 first_day_of_week = l(:general_first_day_of_week).to_i
948 day_of_week = Date.today.cwday
948 day_of_week = Date.today.cwday
949 days_ago = (day_of_week >= first_day_of_week ? day_of_week - first_day_of_week : day_of_week + 7 - first_day_of_week)
949 days_ago = (day_of_week >= first_day_of_week ? day_of_week - first_day_of_week : day_of_week + 7 - first_day_of_week)
950 sql = relative_date_clause(db_table, db_field, - days_ago, - days_ago + 6)
950 sql = relative_date_clause(db_table, db_field, - days_ago, - days_ago + 6)
951 when "~"
951 when "~"
952 sql = "LOWER(#{db_table}.#{db_field}) LIKE '%#{connection.quote_string(value.first.to_s.downcase)}%'"
952 sql = "LOWER(#{db_table}.#{db_field}) LIKE '%#{connection.quote_string(value.first.to_s.downcase)}%'"
953 when "!~"
953 when "!~"
954 sql = "LOWER(#{db_table}.#{db_field}) NOT LIKE '%#{connection.quote_string(value.first.to_s.downcase)}%'"
954 sql = "LOWER(#{db_table}.#{db_field}) NOT LIKE '%#{connection.quote_string(value.first.to_s.downcase)}%'"
955 else
955 else
956 raise "Unknown query operator #{operator}"
956 raise "Unknown query operator #{operator}"
957 end
957 end
958
958
959 return sql
959 return sql
960 end
960 end
961
961
962 def add_custom_fields_filters(custom_fields, assoc=nil)
962 def add_custom_fields_filters(custom_fields, assoc=nil)
963 return unless custom_fields.present?
963 return unless custom_fields.present?
964 @available_filters ||= {}
964 @available_filters ||= {}
965
965
966 custom_fields.select(&:is_filter?).each do |field|
966 custom_fields.select(&:is_filter?).each do |field|
967 case field.field_format
967 case field.field_format
968 when "text"
968 when "text"
969 options = { :type => :text, :order => 20 }
969 options = { :type => :text, :order => 20 }
970 when "list"
970 when "list"
971 options = { :type => :list_optional, :values => field.possible_values, :order => 20}
971 options = { :type => :list_optional, :values => field.possible_values, :order => 20}
972 when "date"
972 when "date"
973 options = { :type => :date, :order => 20 }
973 options = { :type => :date, :order => 20 }
974 when "bool"
974 when "bool"
975 options = { :type => :list, :values => [[l(:general_text_yes), "1"], [l(:general_text_no), "0"]], :order => 20 }
975 options = { :type => :list, :values => [[l(:general_text_yes), "1"], [l(:general_text_no), "0"]], :order => 20 }
976 when "int"
976 when "int"
977 options = { :type => :integer, :order => 20 }
977 options = { :type => :integer, :order => 20 }
978 when "float"
978 when "float"
979 options = { :type => :float, :order => 20 }
979 options = { :type => :float, :order => 20 }
980 when "user", "version"
980 when "user", "version"
981 next unless project
981 next unless project
982 values = field.possible_values_options(project)
982 values = field.possible_values_options(project)
983 if User.current.logged? && field.field_format == 'user'
983 if User.current.logged? && field.field_format == 'user'
984 values.unshift ["<< #{l(:label_me)} >>", "me"]
984 values.unshift ["<< #{l(:label_me)} >>", "me"]
985 end
985 end
986 options = { :type => :list_optional, :values => values, :order => 20}
986 options = { :type => :list_optional, :values => values, :order => 20}
987 else
987 else
988 options = { :type => :string, :order => 20 }
988 options = { :type => :string, :order => 20 }
989 end
989 end
990 filter_id = "cf_#{field.id}"
990 filter_id = "cf_#{field.id}"
991 filter_name = field.name
991 filter_name = field.name
992 if assoc.present?
992 if assoc.present?
993 filter_id = "#{assoc}.#{filter_id}"
993 filter_id = "#{assoc}.#{filter_id}"
994 filter_name = l("label_attribute_of_#{assoc}", :name => filter_name)
994 filter_name = l("label_attribute_of_#{assoc}", :name => filter_name)
995 end
995 end
996 @available_filters[filter_id] = options.merge({ :name => filter_name, :format => field.field_format })
996 @available_filters[filter_id] = options.merge({ :name => filter_name, :format => field.field_format })
997 end
997 end
998 end
998 end
999
999
1000 def add_associations_custom_fields_filters(*associations)
1000 def add_associations_custom_fields_filters(*associations)
1001 fields_by_class = CustomField.where(:is_filter => true).group_by(&:class)
1001 fields_by_class = CustomField.where(:is_filter => true).group_by(&:class)
1002 associations.each do |assoc|
1002 associations.each do |assoc|
1003 association_klass = Issue.reflect_on_association(assoc).klass
1003 association_klass = Issue.reflect_on_association(assoc).klass
1004 fields_by_class.each do |field_class, fields|
1004 fields_by_class.each do |field_class, fields|
1005 if field_class.customized_class <= association_klass
1005 if field_class.customized_class <= association_klass
1006 add_custom_fields_filters(fields, assoc)
1006 add_custom_fields_filters(fields, assoc)
1007 end
1007 end
1008 end
1008 end
1009 end
1009 end
1010 end
1010 end
1011
1011
1012 # Returns a SQL clause for a date or datetime field.
1012 # Returns a SQL clause for a date or datetime field.
1013 def date_clause(table, field, from, to)
1013 def date_clause(table, field, from, to)
1014 s = []
1014 s = []
1015 if from
1015 if from
1016 from_yesterday = from - 1
1016 from_yesterday = from - 1
1017 from_yesterday_time = Time.local(from_yesterday.year, from_yesterday.month, from_yesterday.day)
1017 from_yesterday_time = Time.local(from_yesterday.year, from_yesterday.month, from_yesterday.day)
1018 if self.class.default_timezone == :utc
1018 if self.class.default_timezone == :utc
1019 from_yesterday_time = from_yesterday_time.utc
1019 from_yesterday_time = from_yesterday_time.utc
1020 end
1020 end
1021 s << ("#{table}.#{field} > '%s'" % [connection.quoted_date(from_yesterday_time.end_of_day)])
1021 s << ("#{table}.#{field} > '%s'" % [connection.quoted_date(from_yesterday_time.end_of_day)])
1022 end
1022 end
1023 if to
1023 if to
1024 to_time = Time.local(to.year, to.month, to.day)
1024 to_time = Time.local(to.year, to.month, to.day)
1025 if self.class.default_timezone == :utc
1025 if self.class.default_timezone == :utc
1026 to_time = to_time.utc
1026 to_time = to_time.utc
1027 end
1027 end
1028 s << ("#{table}.#{field} <= '%s'" % [connection.quoted_date(to_time.end_of_day)])
1028 s << ("#{table}.#{field} <= '%s'" % [connection.quoted_date(to_time.end_of_day)])
1029 end
1029 end
1030 s.join(' AND ')
1030 s.join(' AND ')
1031 end
1031 end
1032
1032
1033 # Returns a SQL clause for a date or datetime field using relative dates.
1033 # Returns a SQL clause for a date or datetime field using relative dates.
1034 def relative_date_clause(table, field, days_from, days_to)
1034 def relative_date_clause(table, field, days_from, days_to)
1035 date_clause(table, field, (days_from ? Date.today + days_from : nil), (days_to ? Date.today + days_to : nil))
1035 date_clause(table, field, (days_from ? Date.today + days_from : nil), (days_to ? Date.today + days_to : nil))
1036 end
1036 end
1037
1037
1038 # Additional joins required for the given sort options
1038 # Additional joins required for the given sort options
1039 def joins_for_order_statement(order_options)
1039 def joins_for_order_statement(order_options)
1040 joins = []
1040 joins = []
1041
1041
1042 if order_options
1042 if order_options
1043 if order_options.include?('authors')
1043 if order_options.include?('authors')
1044 joins << "LEFT OUTER JOIN #{User.table_name} authors ON authors.id = #{Issue.table_name}.author_id"
1044 joins << "LEFT OUTER JOIN #{User.table_name} authors ON authors.id = #{Issue.table_name}.author_id"
1045 end
1045 end
1046 order_options.scan(/cf_\d+/).uniq.each do |name|
1046 order_options.scan(/cf_\d+/).uniq.each do |name|
1047 column = available_columns.detect {|c| c.name.to_s == name}
1047 column = available_columns.detect {|c| c.name.to_s == name}
1048 join = column && column.custom_field.join_for_order_statement
1048 join = column && column.custom_field.join_for_order_statement
1049 if join
1049 if join
1050 joins << join
1050 joins << join
1051 end
1051 end
1052 end
1052 end
1053 end
1053 end
1054
1054
1055 joins.any? ? joins.join(' ') : nil
1055 joins.any? ? joins.join(' ') : nil
1056 end
1056 end
1057 end
1057 end
@@ -1,43 +1,45
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2012 Jean-Philippe Lang
2 # Copyright (C) 2006-2012 Jean-Philippe Lang
3 #
3 #
4 # This program is free software; you can redistribute it and/or
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
7 # of the License, or (at your option) any later version.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU General Public License
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
17
18 require File.expand_path('../../../test_helper', __FILE__)
18 require File.expand_path('../../../test_helper', __FILE__)
19
19
20 class QueriesHelperTest < ActionView::TestCase
20 class QueriesHelperTest < ActionView::TestCase
21 include QueriesHelper
21 include QueriesHelper
22
22
23 fixtures :projects, :enabled_modules, :users, :members,
23 fixtures :projects, :enabled_modules, :users, :members,
24 :member_roles, :roles, :trackers, :issue_statuses,
24 :member_roles, :roles, :trackers, :issue_statuses,
25 :issue_categories, :enumerations, :issues,
25 :issue_categories, :enumerations, :issues,
26 :watchers, :custom_fields, :custom_values, :versions,
26 :watchers, :custom_fields, :custom_values, :versions,
27 :queries,
27 :queries,
28 :projects_trackers,
28 :projects_trackers,
29 :custom_fields_trackers
29 :custom_fields_trackers
30
30
31 def test_order
31 def test_order
32 User.current = User.find_by_login('admin')
32 User.current = User.find_by_login('admin')
33 query = Query.new(:project => nil, :name => '_')
33 query = Query.new(:project => nil, :name => '_')
34 assert_equal 30, query.available_filters.size
34 assert_equal 30, query.available_filters.size
35 fo = filters_options(query)
35 fo = filters_options(query)
36 assert_equal 31, fo.size
36 assert_equal 31, fo.size
37 assert_equal [], fo[0]
37 assert_equal [], fo[0]
38 assert_equal "status_id", fo[1][1]
38 assert_equal "status_id", fo[1][1]
39 assert_equal "project_id", fo[2][1]
39 assert_equal "project_id", fo[2][1]
40 assert_equal "tracker_id", fo[3][1]
40 assert_equal "tracker_id", fo[3][1]
41 assert_equal "priority_id", fo[4][1]
41 assert_equal "priority_id", fo[4][1]
42 assert_equal "watcher_id", fo[17][1]
43 assert_equal "is_private", fo[18][1]
42 end
44 end
43 end
45 end
General Comments 0
You need to be logged in to leave comments. Login now