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