##// END OF EJS Templates
code layout cleanup Query available_filters method...
Toshi MARUYAMA -
r10334:1d4c8abe9687
parent child
Show More
@@ -1,1019 +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
228 @available_filters = {
229 @available_filters = { "status_id" => { :type => :list_status, :order => 1, :values => IssueStatus.find(:all, :order => 'position').collect{|s| [s.name, s.id.to_s] } },
229 "status_id" => {
230 "tracker_id" => { :type => :list, :order => 2, :values => trackers.collect{|s| [s.name, s.id.to_s] } },
230 :type => :list_status, :order => 1,
231 "priority_id" => { :type => :list, :order => 3, :values => IssuePriority.all.collect{|s| [s.name, s.id.to_s] } },
231 :values => IssueStatus.find(:all, :order => 'position').collect{|s| [s.name, s.id.to_s] }
232 "subject" => { :type => :text, :order => 8 },
232 },
233 "created_on" => { :type => :date_past, :order => 9 },
233 "tracker_id" => {
234 "updated_on" => { :type => :date_past, :order => 10 },
234 :type => :list, :order => 2, :values => trackers.collect{|s| [s.name, s.id.to_s] }
235 "start_date" => { :type => :date, :order => 11 },
235 },
236 "due_date" => { :type => :date, :order => 12 },
236 "priority_id" => {
237 "estimated_hours" => { :type => :float, :order => 13 },
237 :type => :list, :order => 3, :values => IssuePriority.all.collect{|s| [s.name, s.id.to_s] }
238 "done_ratio" => { :type => :integer, :order => 14 }}
238 },
239
239 "subject" => { :type => :text, :order => 8 },
240 "created_on" => { :type => :date_past, :order => 9 },
241 "updated_on" => { :type => :date_past, :order => 10 },
242 "start_date" => { :type => :date, :order => 11 },
243 "due_date" => { :type => :date, :order => 12 },
244 "estimated_hours" => { :type => :float, :order => 13 },
245 "done_ratio" => { :type => :integer, :order => 14 }
246 }
240 IssueRelation::TYPES.each do |relation_type, options|
247 IssueRelation::TYPES.each do |relation_type, options|
241 @available_filters[relation_type] = {:type => :relation, :order => @available_filters.size + 100, :label => options[:name]}
248 @available_filters[relation_type] = {
249 :type => :relation, :order => @available_filters.size + 100,
250 :label => options[:name]
251 }
242 end
252 end
243
244 principals = []
253 principals = []
245 if project
254 if project
246 principals += project.principals.sort
255 principals += project.principals.sort
247 unless project.leaf?
256 unless project.leaf?
248 subprojects = project.descendants.visible.all
257 subprojects = project.descendants.visible.all
249 if subprojects.any?
258 if subprojects.any?
250 @available_filters["subproject_id"] = { :type => :list_subprojects, :order => 13, :values => subprojects.collect{|s| [s.name, s.id.to_s] } }
259 @available_filters["subproject_id"] = {
260 :type => :list_subprojects, :order => 13,
261 :values => subprojects.collect{|s| [s.name, s.id.to_s] }
262 }
251 principals += Principal.member_of(subprojects)
263 principals += Principal.member_of(subprojects)
252 end
264 end
253 end
265 end
254 else
266 else
255 if all_projects.any?
267 if all_projects.any?
256 # members of visible projects
268 # members of visible projects
257 principals += Principal.member_of(all_projects)
269 principals += Principal.member_of(all_projects)
258
259 # project filter
270 # project filter
260 project_values = []
271 project_values = []
261 if User.current.logged? && User.current.memberships.any?
272 if User.current.logged? && User.current.memberships.any?
262 project_values << ["<< #{l(:label_my_projects).downcase} >>", "mine"]
273 project_values << ["<< #{l(:label_my_projects).downcase} >>", "mine"]
263 end
274 end
264 project_values += all_projects_values
275 project_values += all_projects_values
265 @available_filters["project_id"] = { :type => :list, :order => 1, :values => project_values} unless project_values.empty?
276 @available_filters["project_id"] = {
277 :type => :list, :order => 1, :values => project_values
278 } unless project_values.empty?
266 end
279 end
267 end
280 end
268 principals.uniq!
281 principals.uniq!
269 principals.sort!
282 principals.sort!
270 users = principals.select {|p| p.is_a?(User)}
283 users = principals.select {|p| p.is_a?(User)}
271
284
272 assigned_to_values = []
285 assigned_to_values = []
273 assigned_to_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged?
286 assigned_to_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged?
274 assigned_to_values += (Setting.issue_group_assignment? ? principals : users).collect{|s| [s.name, s.id.to_s] }
287 assigned_to_values += (Setting.issue_group_assignment? ?
275 @available_filters["assigned_to_id"] = { :type => :list_optional, :order => 4, :values => assigned_to_values } unless assigned_to_values.empty?
288 principals : users).collect{|s| [s.name, s.id.to_s] }
289 @available_filters["assigned_to_id"] = {
290 :type => :list_optional, :order => 4, :values => assigned_to_values
291 } unless assigned_to_values.empty?
276
292
277 author_values = []
293 author_values = []
278 author_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged?
294 author_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged?
279 author_values += users.collect{|s| [s.name, s.id.to_s] }
295 author_values += users.collect{|s| [s.name, s.id.to_s] }
280 @available_filters["author_id"] = { :type => :list, :order => 5, :values => author_values } unless author_values.empty?
296 @available_filters["author_id"] = {
297 :type => :list, :order => 5, :values => author_values
298 } unless author_values.empty?
281
299
282 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] }
283 @available_filters["member_of_group"] = { :type => :list_optional, :order => 6, :values => group_values } unless group_values.empty?
301 @available_filters["member_of_group"] = {
302 :type => :list_optional, :order => 6, :values => group_values
303 } unless group_values.empty?
284
304
285 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] }
286 @available_filters["assigned_to_role"] = { :type => :list_optional, :order => 7, :values => role_values } unless role_values.empty?
306 @available_filters["assigned_to_role"] = {
307 :type => :list_optional, :order => 7, :values => role_values
308 } unless role_values.empty?
287
309
288 if User.current.logged?
310 if User.current.logged?
289 @available_filters["watcher_id"] = { :type => :list, :order => 15, :values => [["<< #{l(:label_me)} >>", "me"]] }
311 @available_filters["watcher_id"] = {
312 :type => :list, :order => 15, :values => [["<< #{l(:label_me)} >>", "me"]]
313 }
290 end
314 end
291
315
292 if project
316 if project
293 # project specific filters
317 # project specific filters
294 categories = project.issue_categories.all
318 categories = project.issue_categories.all
295 unless categories.empty?
319 unless categories.empty?
296 @available_filters["category_id"] = { :type => :list_optional, :order => 6, :values => categories.collect{|s| [s.name, s.id.to_s] } }
320 @available_filters["category_id"] = {
321 :type => :list_optional, :order => 6,
322 :values => categories.collect{|s| [s.name, s.id.to_s] }
323 }
297 end
324 end
298 versions = project.shared_versions.all
325 versions = project.shared_versions.all
299 unless versions.empty?
326 unless versions.empty?
300 @available_filters["fixed_version_id"] = { :type => :list_optional, :order => 7, :values => versions.sort.collect{|s| ["#{s.project.name} - #{s.name}", s.id.to_s] } }
327 @available_filters["fixed_version_id"] = {
328 :type => :list_optional, :order => 7,
329 :values => versions.sort.collect{|s| ["#{s.project.name} - #{s.name}", s.id.to_s] }
330 }
301 end
331 end
302 add_custom_fields_filters(project.all_issue_custom_fields)
332 add_custom_fields_filters(project.all_issue_custom_fields)
303 else
333 else
304 # global filters for cross project issue list
334 # global filters for cross project issue list
305 system_shared_versions = Version.visible.find_all_by_sharing('system')
335 system_shared_versions = Version.visible.find_all_by_sharing('system')
306 unless system_shared_versions.empty?
336 unless system_shared_versions.empty?
307 @available_filters["fixed_version_id"] = { :type => :list_optional, :order => 7, :values => system_shared_versions.sort.collect{|s| ["#{s.project.name} - #{s.name}", s.id.to_s] } }
337 @available_filters["fixed_version_id"] = {
338 :type => :list_optional, :order => 7,
339 :values => system_shared_versions.sort.collect{|s|
340 ["#{s.project.name} - #{s.name}", s.id.to_s]
341 }
342 }
308 end
343 end
309 add_custom_fields_filters(IssueCustomField.find(:all, :conditions => {:is_filter => true, :is_for_all => true}))
344 add_custom_fields_filters(
345 IssueCustomField.find(:all,
346 :conditions => {
347 :is_filter => true,
348 :is_for_all => true
349 }))
310 end
350 end
311
312 add_associations_custom_fields_filters :project, :author, :assigned_to, :fixed_version
351 add_associations_custom_fields_filters :project, :author, :assigned_to, :fixed_version
313
314 if User.current.allowed_to?(:set_issues_private, nil, :global => true) ||
352 if User.current.allowed_to?(:set_issues_private, nil, :global => true) ||
315 User.current.allowed_to?(:set_own_issues_private, nil, :global => true)
353 User.current.allowed_to?(:set_own_issues_private, nil, :global => true)
316 @available_filters["is_private"] = { :type => :list, :order => 15, :values => [[l(:general_text_yes), "1"], [l(:general_text_no), "0"]] }
354 @available_filters["is_private"] = {
355 :type => :list, :order => 15,
356 :values => [[l(:general_text_yes), "1"], [l(:general_text_no), "0"]]
357 }
317 end
358 end
318
319 Tracker.disabled_core_fields(trackers).each {|field|
359 Tracker.disabled_core_fields(trackers).each {|field|
320 @available_filters.delete field
360 @available_filters.delete field
321 }
361 }
322
323 @available_filters.each do |field, options|
362 @available_filters.each do |field, options|
324 options[:name] ||= l(options[:label] || "field_#{field}".gsub(/_id$/, ''))
363 options[:name] ||= l(options[:label] || "field_#{field}".gsub(/_id$/, ''))
325 end
364 end
326
327 @available_filters
365 @available_filters
328 end
366 end
329
367
330 # Returns a representation of the available filters for JSON serialization
368 # Returns a representation of the available filters for JSON serialization
331 def available_filters_as_json
369 def available_filters_as_json
332 json = {}
370 json = {}
333 available_filters.each do |field, options|
371 available_filters.each do |field, options|
334 json[field] = options.slice(:type, :name, :values).stringify_keys
372 json[field] = options.slice(:type, :name, :values).stringify_keys
335 end
373 end
336 json
374 json
337 end
375 end
338
376
339 def all_projects
377 def all_projects
340 @all_projects ||= Project.visible.all
378 @all_projects ||= Project.visible.all
341 end
379 end
342
380
343 def all_projects_values
381 def all_projects_values
344 return @all_projects_values if @all_projects_values
382 return @all_projects_values if @all_projects_values
345
383
346 values = []
384 values = []
347 Project.project_tree(all_projects) do |p, level|
385 Project.project_tree(all_projects) do |p, level|
348 prefix = (level > 0 ? ('--' * level + ' ') : '')
386 prefix = (level > 0 ? ('--' * level + ' ') : '')
349 values << ["#{prefix}#{p.name}", p.id.to_s]
387 values << ["#{prefix}#{p.name}", p.id.to_s]
350 end
388 end
351 @all_projects_values = values
389 @all_projects_values = values
352 end
390 end
353
391
354 def add_filter(field, operator, values)
392 def add_filter(field, operator, values)
355 # values must be an array
393 # values must be an array
356 return unless values.nil? || values.is_a?(Array)
394 return unless values.nil? || values.is_a?(Array)
357 # check if field is defined as an available filter
395 # check if field is defined as an available filter
358 if available_filters.has_key? field
396 if available_filters.has_key? field
359 filter_options = available_filters[field]
397 filter_options = available_filters[field]
360 # check if operator is allowed for that filter
398 # check if operator is allowed for that filter
361 #if @@operators_by_filter_type[filter_options[:type]].include? operator
399 #if @@operators_by_filter_type[filter_options[:type]].include? operator
362 # allowed_values = values & ([""] + (filter_options[:values] || []).collect {|val| val[1]})
400 # allowed_values = values & ([""] + (filter_options[:values] || []).collect {|val| val[1]})
363 # 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
364 #end
402 #end
365 filters[field] = {:operator => operator, :values => (values || [''])}
403 filters[field] = {:operator => operator, :values => (values || [''])}
366 end
404 end
367 end
405 end
368
406
369 def add_short_filter(field, expression)
407 def add_short_filter(field, expression)
370 return unless expression && available_filters.has_key?(field)
408 return unless expression && available_filters.has_key?(field)
371 field_type = available_filters[field][:type]
409 field_type = available_filters[field][:type]
372 @@operators_by_filter_type[field_type].sort.reverse.detect do |operator|
410 @@operators_by_filter_type[field_type].sort.reverse.detect do |operator|
373 next unless expression =~ /^#{Regexp.escape(operator)}(.*)$/
411 next unless expression =~ /^#{Regexp.escape(operator)}(.*)$/
374 add_filter field, operator, $1.present? ? $1.split('|') : ['']
412 add_filter field, operator, $1.present? ? $1.split('|') : ['']
375 end || add_filter(field, '=', expression.split('|'))
413 end || add_filter(field, '=', expression.split('|'))
376 end
414 end
377
415
378 # Add multiple filters using +add_filter+
416 # Add multiple filters using +add_filter+
379 def add_filters(fields, operators, values)
417 def add_filters(fields, operators, values)
380 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))
381 fields.each do |field|
419 fields.each do |field|
382 add_filter(field, operators[field], values && values[field])
420 add_filter(field, operators[field], values && values[field])
383 end
421 end
384 end
422 end
385 end
423 end
386
424
387 def has_filter?(field)
425 def has_filter?(field)
388 filters and filters[field]
426 filters and filters[field]
389 end
427 end
390
428
391 def type_for(field)
429 def type_for(field)
392 available_filters[field][:type] if available_filters.has_key?(field)
430 available_filters[field][:type] if available_filters.has_key?(field)
393 end
431 end
394
432
395 def operator_for(field)
433 def operator_for(field)
396 has_filter?(field) ? filters[field][:operator] : nil
434 has_filter?(field) ? filters[field][:operator] : nil
397 end
435 end
398
436
399 def values_for(field)
437 def values_for(field)
400 has_filter?(field) ? filters[field][:values] : nil
438 has_filter?(field) ? filters[field][:values] : nil
401 end
439 end
402
440
403 def value_for(field, index=0)
441 def value_for(field, index=0)
404 (values_for(field) || [])[index]
442 (values_for(field) || [])[index]
405 end
443 end
406
444
407 def label_for(field)
445 def label_for(field)
408 label = available_filters[field][:name] if available_filters.has_key?(field)
446 label = available_filters[field][:name] if available_filters.has_key?(field)
409 label ||= l("field_#{field.to_s.gsub(/_id$/, '')}", :default => field)
447 label ||= l("field_#{field.to_s.gsub(/_id$/, '')}", :default => field)
410 end
448 end
411
449
412 def available_columns
450 def available_columns
413 return @available_columns if @available_columns
451 return @available_columns if @available_columns
414 @available_columns = ::Query.available_columns.dup
452 @available_columns = ::Query.available_columns.dup
415 @available_columns += (project ?
453 @available_columns += (project ?
416 project.all_issue_custom_fields :
454 project.all_issue_custom_fields :
417 IssueCustomField.find(:all)
455 IssueCustomField.find(:all)
418 ).collect {|cf| QueryCustomFieldColumn.new(cf) }
456 ).collect {|cf| QueryCustomFieldColumn.new(cf) }
419
457
420 if User.current.allowed_to?(:view_time_entries, project, :global => true)
458 if User.current.allowed_to?(:view_time_entries, project, :global => true)
421 index = nil
459 index = nil
422 @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}
423 index = (index ? index + 1 : -1)
461 index = (index ? index + 1 : -1)
424 # insert the column after estimated_hours or at the end
462 # insert the column after estimated_hours or at the end
425 @available_columns.insert index, QueryColumn.new(:spent_hours,
463 @available_columns.insert index, QueryColumn.new(:spent_hours,
426 :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)",
427 :default_order => 'desc',
465 :default_order => 'desc',
428 :caption => :label_spent_time
466 :caption => :label_spent_time
429 )
467 )
430 end
468 end
431
469
432 if User.current.allowed_to?(:set_issues_private, nil, :global => true) ||
470 if User.current.allowed_to?(:set_issues_private, nil, :global => true) ||
433 User.current.allowed_to?(:set_own_issues_private, nil, :global => true)
471 User.current.allowed_to?(:set_own_issues_private, nil, :global => true)
434 @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")
435 end
473 end
436
474
437 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$/, '')}
438 @available_columns.reject! {|column|
476 @available_columns.reject! {|column|
439 disabled_fields.include?(column.name.to_s)
477 disabled_fields.include?(column.name.to_s)
440 }
478 }
441
479
442 @available_columns
480 @available_columns
443 end
481 end
444
482
445 def self.available_columns=(v)
483 def self.available_columns=(v)
446 self.available_columns = (v)
484 self.available_columns = (v)
447 end
485 end
448
486
449 def self.add_available_column(column)
487 def self.add_available_column(column)
450 self.available_columns << (column) if column.is_a?(QueryColumn)
488 self.available_columns << (column) if column.is_a?(QueryColumn)
451 end
489 end
452
490
453 # 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
454 def groupable_columns
492 def groupable_columns
455 available_columns.select {|c| c.groupable}
493 available_columns.select {|c| c.groupable}
456 end
494 end
457
495
458 # Returns a Hash of columns and the key for sorting
496 # Returns a Hash of columns and the key for sorting
459 def sortable_columns
497 def sortable_columns
460 {'id' => "#{Issue.table_name}.id"}.merge(available_columns.inject({}) {|h, column|
498 {'id' => "#{Issue.table_name}.id"}.merge(available_columns.inject({}) {|h, column|
461 h[column.name.to_s] = column.sortable
499 h[column.name.to_s] = column.sortable
462 h
500 h
463 })
501 })
464 end
502 end
465
503
466 def columns
504 def columns
467 # preserve the column_names order
505 # preserve the column_names order
468 (has_default_columns? ? default_columns_names : column_names).collect do |name|
506 (has_default_columns? ? default_columns_names : column_names).collect do |name|
469 available_columns.find { |col| col.name == name }
507 available_columns.find { |col| col.name == name }
470 end.compact
508 end.compact
471 end
509 end
472
510
473 def default_columns_names
511 def default_columns_names
474 @default_columns_names ||= begin
512 @default_columns_names ||= begin
475 default_columns = Setting.issue_list_default_columns.map(&:to_sym)
513 default_columns = Setting.issue_list_default_columns.map(&:to_sym)
476
514
477 project.present? ? default_columns : [:project] | default_columns
515 project.present? ? default_columns : [:project] | default_columns
478 end
516 end
479 end
517 end
480
518
481 def column_names=(names)
519 def column_names=(names)
482 if names
520 if names
483 names = names.select {|n| n.is_a?(Symbol) || !n.blank? }
521 names = names.select {|n| n.is_a?(Symbol) || !n.blank? }
484 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 }
485 # Set column_names to nil if default columns
523 # Set column_names to nil if default columns
486 if names == default_columns_names
524 if names == default_columns_names
487 names = nil
525 names = nil
488 end
526 end
489 end
527 end
490 write_attribute(:column_names, names)
528 write_attribute(:column_names, names)
491 end
529 end
492
530
493 def has_column?(column)
531 def has_column?(column)
494 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)
495 end
533 end
496
534
497 def has_default_columns?
535 def has_default_columns?
498 column_names.nil? || column_names.empty?
536 column_names.nil? || column_names.empty?
499 end
537 end
500
538
501 def sort_criteria=(arg)
539 def sort_criteria=(arg)
502 c = []
540 c = []
503 if arg.is_a?(Hash)
541 if arg.is_a?(Hash)
504 arg = arg.keys.sort.collect {|k| arg[k]}
542 arg = arg.keys.sort.collect {|k| arg[k]}
505 end
543 end
506 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']}
507 write_attribute(:sort_criteria, c)
545 write_attribute(:sort_criteria, c)
508 end
546 end
509
547
510 def sort_criteria
548 def sort_criteria
511 read_attribute(:sort_criteria) || []
549 read_attribute(:sort_criteria) || []
512 end
550 end
513
551
514 def sort_criteria_key(arg)
552 def sort_criteria_key(arg)
515 sort_criteria && sort_criteria[arg] && sort_criteria[arg].first
553 sort_criteria && sort_criteria[arg] && sort_criteria[arg].first
516 end
554 end
517
555
518 def sort_criteria_order(arg)
556 def sort_criteria_order(arg)
519 sort_criteria && sort_criteria[arg] && sort_criteria[arg].last
557 sort_criteria && sort_criteria[arg] && sort_criteria[arg].last
520 end
558 end
521
559
522 # Returns the SQL sort order that should be prepended for grouping
560 # Returns the SQL sort order that should be prepended for grouping
523 def group_by_sort_order
561 def group_by_sort_order
524 if grouped? && (column = group_by_column)
562 if grouped? && (column = group_by_column)
525 column.sortable.is_a?(Array) ?
563 column.sortable.is_a?(Array) ?
526 column.sortable.collect {|s| "#{s} #{column.default_order}"}.join(',') :
564 column.sortable.collect {|s| "#{s} #{column.default_order}"}.join(',') :
527 "#{column.sortable} #{column.default_order}"
565 "#{column.sortable} #{column.default_order}"
528 end
566 end
529 end
567 end
530
568
531 # Returns true if the query is a grouped query
569 # Returns true if the query is a grouped query
532 def grouped?
570 def grouped?
533 !group_by_column.nil?
571 !group_by_column.nil?
534 end
572 end
535
573
536 def group_by_column
574 def group_by_column
537 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}
538 end
576 end
539
577
540 def group_by_statement
578 def group_by_statement
541 group_by_column.try(:groupable)
579 group_by_column.try(:groupable)
542 end
580 end
543
581
544 def project_statement
582 def project_statement
545 project_clauses = []
583 project_clauses = []
546 if project && !project.descendants.active.empty?
584 if project && !project.descendants.active.empty?
547 ids = [project.id]
585 ids = [project.id]
548 if has_filter?("subproject_id")
586 if has_filter?("subproject_id")
549 case operator_for("subproject_id")
587 case operator_for("subproject_id")
550 when '='
588 when '='
551 # include the selected subprojects
589 # include the selected subprojects
552 ids += values_for("subproject_id").each(&:to_i)
590 ids += values_for("subproject_id").each(&:to_i)
553 when '!*'
591 when '!*'
554 # main project only
592 # main project only
555 else
593 else
556 # all subprojects
594 # all subprojects
557 ids += project.descendants.collect(&:id)
595 ids += project.descendants.collect(&:id)
558 end
596 end
559 elsif Setting.display_subprojects_issues?
597 elsif Setting.display_subprojects_issues?
560 ids += project.descendants.collect(&:id)
598 ids += project.descendants.collect(&:id)
561 end
599 end
562 project_clauses << "#{Project.table_name}.id IN (%s)" % ids.join(',')
600 project_clauses << "#{Project.table_name}.id IN (%s)" % ids.join(',')
563 elsif project
601 elsif project
564 project_clauses << "#{Project.table_name}.id = %d" % project.id
602 project_clauses << "#{Project.table_name}.id = %d" % project.id
565 end
603 end
566 project_clauses.any? ? project_clauses.join(' AND ') : nil
604 project_clauses.any? ? project_clauses.join(' AND ') : nil
567 end
605 end
568
606
569 def statement
607 def statement
570 # filters clauses
608 # filters clauses
571 filters_clauses = []
609 filters_clauses = []
572 filters.each_key do |field|
610 filters.each_key do |field|
573 next if field == "subproject_id"
611 next if field == "subproject_id"
574 v = values_for(field).clone
612 v = values_for(field).clone
575 next unless v and !v.empty?
613 next unless v and !v.empty?
576 operator = operator_for(field)
614 operator = operator_for(field)
577
615
578 # "me" value subsitution
616 # "me" value subsitution
579 if %w(assigned_to_id author_id watcher_id).include?(field)
617 if %w(assigned_to_id author_id watcher_id).include?(field)
580 if v.delete("me")
618 if v.delete("me")
581 if User.current.logged?
619 if User.current.logged?
582 v.push(User.current.id.to_s)
620 v.push(User.current.id.to_s)
583 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'
584 else
622 else
585 v.push("0")
623 v.push("0")
586 end
624 end
587 end
625 end
588 end
626 end
589
627
590 if field == 'project_id'
628 if field == 'project_id'
591 if v.delete('mine')
629 if v.delete('mine')
592 v += User.current.memberships.map(&:project_id).map(&:to_s)
630 v += User.current.memberships.map(&:project_id).map(&:to_s)
593 end
631 end
594 end
632 end
595
633
596 if field =~ /cf_(\d+)$/
634 if field =~ /cf_(\d+)$/
597 # custom field
635 # custom field
598 filters_clauses << sql_for_custom_field(field, operator, v, $1)
636 filters_clauses << sql_for_custom_field(field, operator, v, $1)
599 elsif respond_to?("sql_for_#{field}_field")
637 elsif respond_to?("sql_for_#{field}_field")
600 # specific statement
638 # specific statement
601 filters_clauses << send("sql_for_#{field}_field", field, operator, v)
639 filters_clauses << send("sql_for_#{field}_field", field, operator, v)
602 else
640 else
603 # regular field
641 # regular field
604 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) + ')'
605 end
643 end
606 end if filters and valid?
644 end if filters and valid?
607
645
608 filters_clauses << project_statement
646 filters_clauses << project_statement
609 filters_clauses.reject!(&:blank?)
647 filters_clauses.reject!(&:blank?)
610
648
611 filters_clauses.any? ? filters_clauses.join(' AND ') : nil
649 filters_clauses.any? ? filters_clauses.join(' AND ') : nil
612 end
650 end
613
651
614 # Returns the issue count
652 # Returns the issue count
615 def issue_count
653 def issue_count
616 Issue.visible.count(:include => [:status, :project], :conditions => statement)
654 Issue.visible.count(:include => [:status, :project], :conditions => statement)
617 rescue ::ActiveRecord::StatementInvalid => e
655 rescue ::ActiveRecord::StatementInvalid => e
618 raise StatementInvalid.new(e.message)
656 raise StatementInvalid.new(e.message)
619 end
657 end
620
658
621 # 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
622 def issue_count_by_group
660 def issue_count_by_group
623 r = nil
661 r = nil
624 if grouped?
662 if grouped?
625 begin
663 begin
626 # 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
627 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)
628 rescue ActiveRecord::RecordNotFound
666 rescue ActiveRecord::RecordNotFound
629 r = {nil => issue_count}
667 r = {nil => issue_count}
630 end
668 end
631 c = group_by_column
669 c = group_by_column
632 if c.is_a?(QueryCustomFieldColumn)
670 if c.is_a?(QueryCustomFieldColumn)
633 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}
634 end
672 end
635 end
673 end
636 r
674 r
637 rescue ::ActiveRecord::StatementInvalid => e
675 rescue ::ActiveRecord::StatementInvalid => e
638 raise StatementInvalid.new(e.message)
676 raise StatementInvalid.new(e.message)
639 end
677 end
640
678
641 # Returns the issues
679 # Returns the issues
642 # Valid options are :order, :offset, :limit, :include, :conditions
680 # Valid options are :order, :offset, :limit, :include, :conditions
643 def issues(options={})
681 def issues(options={})
644 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(',')
645 order_option = nil if order_option.blank?
683 order_option = nil if order_option.blank?
646
684
647 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,
648 :conditions => statement,
686 :conditions => statement,
649 :order => order_option,
687 :order => order_option,
650 :joins => joins_for_order_statement(order_option),
688 :joins => joins_for_order_statement(order_option),
651 :limit => options[:limit],
689 :limit => options[:limit],
652 :offset => options[:offset]
690 :offset => options[:offset]
653
691
654 if has_column?(:spent_hours)
692 if has_column?(:spent_hours)
655 Issue.load_visible_spent_hours(issues)
693 Issue.load_visible_spent_hours(issues)
656 end
694 end
657 if has_column?(:relations)
695 if has_column?(:relations)
658 Issue.load_visible_relations(issues)
696 Issue.load_visible_relations(issues)
659 end
697 end
660 issues
698 issues
661 rescue ::ActiveRecord::StatementInvalid => e
699 rescue ::ActiveRecord::StatementInvalid => e
662 raise StatementInvalid.new(e.message)
700 raise StatementInvalid.new(e.message)
663 end
701 end
664
702
665 # Returns the issues ids
703 # Returns the issues ids
666 def issue_ids(options={})
704 def issue_ids(options={})
667 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(',')
668 order_option = nil if order_option.blank?
706 order_option = nil if order_option.blank?
669
707
670 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,
671 :conditions => statement,
709 :conditions => statement,
672 :order => order_option,
710 :order => order_option,
673 :joins => joins_for_order_statement(order_option),
711 :joins => joins_for_order_statement(order_option),
674 :limit => options[:limit],
712 :limit => options[:limit],
675 :offset => options[:offset]).find_ids
713 :offset => options[:offset]).find_ids
676 rescue ::ActiveRecord::StatementInvalid => e
714 rescue ::ActiveRecord::StatementInvalid => e
677 raise StatementInvalid.new(e.message)
715 raise StatementInvalid.new(e.message)
678 end
716 end
679
717
680 # Returns the journals
718 # Returns the journals
681 # Valid options are :order, :offset, :limit
719 # Valid options are :order, :offset, :limit
682 def journals(options={})
720 def journals(options={})
683 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]}],
684 :conditions => statement,
722 :conditions => statement,
685 :order => options[:order],
723 :order => options[:order],
686 :limit => options[:limit],
724 :limit => options[:limit],
687 :offset => options[:offset]
725 :offset => options[:offset]
688 rescue ::ActiveRecord::StatementInvalid => e
726 rescue ::ActiveRecord::StatementInvalid => e
689 raise StatementInvalid.new(e.message)
727 raise StatementInvalid.new(e.message)
690 end
728 end
691
729
692 # Returns the versions
730 # Returns the versions
693 # Valid options are :conditions
731 # Valid options are :conditions
694 def versions(options={})
732 def versions(options={})
695 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
696 rescue ::ActiveRecord::StatementInvalid => e
734 rescue ::ActiveRecord::StatementInvalid => e
697 raise StatementInvalid.new(e.message)
735 raise StatementInvalid.new(e.message)
698 end
736 end
699
737
700 def sql_for_watcher_id_field(field, operator, value)
738 def sql_for_watcher_id_field(field, operator, value)
701 db_table = Watcher.table_name
739 db_table = Watcher.table_name
702 "#{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 " +
703 sql_for_field(field, '=', value, db_table, 'user_id') + ')'
741 sql_for_field(field, '=', value, db_table, 'user_id') + ')'
704 end
742 end
705
743
706 def sql_for_member_of_group_field(field, operator, value)
744 def sql_for_member_of_group_field(field, operator, value)
707 if operator == '*' # Any group
745 if operator == '*' # Any group
708 groups = Group.all
746 groups = Group.all
709 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
710 elsif operator == "!*"
748 elsif operator == "!*"
711 groups = Group.all
749 groups = Group.all
712 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
713 else
751 else
714 groups = Group.find_all_by_id(value)
752 groups = Group.find_all_by_id(value)
715 end
753 end
716 groups ||= []
754 groups ||= []
717
755
718 members_of_groups = groups.inject([]) {|user_ids, group|
756 members_of_groups = groups.inject([]) {|user_ids, group|
719 if group && group.user_ids.present?
757 if group && group.user_ids.present?
720 user_ids << group.user_ids
758 user_ids << group.user_ids
721 end
759 end
722 user_ids.flatten.uniq.compact
760 user_ids.flatten.uniq.compact
723 }.sort.collect(&:to_s)
761 }.sort.collect(&:to_s)
724
762
725 '(' + 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) + ')'
726 end
764 end
727
765
728 def sql_for_assigned_to_role_field(field, operator, value)
766 def sql_for_assigned_to_role_field(field, operator, value)
729 case operator
767 case operator
730 when "*", "!*" # Member / Not member
768 when "*", "!*" # Member / Not member
731 sw = operator == "!*" ? 'NOT' : ''
769 sw = operator == "!*" ? 'NOT' : ''
732 nl = operator == "!*" ? "#{Issue.table_name}.assigned_to_id IS NULL OR" : ''
770 nl = operator == "!*" ? "#{Issue.table_name}.assigned_to_id IS NULL OR" : ''
733 "(#{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}" +
734 " WHERE #{Member.table_name}.project_id = #{Issue.table_name}.project_id))"
772 " WHERE #{Member.table_name}.project_id = #{Issue.table_name}.project_id))"
735 when "=", "!"
773 when "=", "!"
736 role_cond = value.any? ?
774 role_cond = value.any? ?
737 "#{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(",") + ")" :
738 "1=0"
776 "1=0"
739
777
740 sw = operator == "!" ? 'NOT' : ''
778 sw = operator == "!" ? 'NOT' : ''
741 nl = operator == "!" ? "#{Issue.table_name}.assigned_to_id IS NULL OR" : ''
779 nl = operator == "!" ? "#{Issue.table_name}.assigned_to_id IS NULL OR" : ''
742 "(#{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}" +
743 " 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}))"
744 end
782 end
745 end
783 end
746
784
747 def sql_for_is_private_field(field, operator, value)
785 def sql_for_is_private_field(field, operator, value)
748 op = (operator == "=" ? 'IN' : 'NOT IN')
786 op = (operator == "=" ? 'IN' : 'NOT IN')
749 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(',')
750
788
751 "#{Issue.table_name}.is_private #{op} (#{va})"
789 "#{Issue.table_name}.is_private #{op} (#{va})"
752 end
790 end
753
791
754 def sql_for_relations(field, operator, value, options={})
792 def sql_for_relations(field, operator, value, options={})
755 relation_options = IssueRelation::TYPES[field]
793 relation_options = IssueRelation::TYPES[field]
756 return relation_options unless relation_options
794 return relation_options unless relation_options
757
795
758 relation_type = field
796 relation_type = field
759 join_column, target_join_column = "issue_from_id", "issue_to_id"
797 join_column, target_join_column = "issue_from_id", "issue_to_id"
760 if relation_options[:reverse] || options[:reverse]
798 if relation_options[:reverse] || options[:reverse]
761 relation_type = relation_options[:reverse] || relation_type
799 relation_type = relation_options[:reverse] || relation_type
762 join_column, target_join_column = target_join_column, join_column
800 join_column, target_join_column = target_join_column, join_column
763 end
801 end
764
802
765 sql = case operator
803 sql = case operator
766 when "*", "!*"
804 when "*", "!*"
767 op = (operator == "*" ? 'IN' : 'NOT IN')
805 op = (operator == "*" ? 'IN' : 'NOT IN')
768 "#{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)}')"
769 when "=", "!"
807 when "=", "!"
770 op = (operator == "=" ? 'IN' : 'NOT IN')
808 op = (operator == "=" ? 'IN' : 'NOT IN')
771 "#{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})"
772 when "=p", "=!p"
810 when "=p", "=!p"
773 op = (operator == "=p" ? '=' : '<>')
811 op = (operator == "=p" ? '=' : '<>')
774 "#{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})"
775 end
813 end
776
814
777 if relation_options[:sym] == field && !options[:reverse]
815 if relation_options[:sym] == field && !options[:reverse]
778 sqls = [sql, sql_for_relations(field, operator, value, :reverse => true)]
816 sqls = [sql, sql_for_relations(field, operator, value, :reverse => true)]
779 sqls.join(["!", "!*"].include?(operator) ? " AND " : " OR ")
817 sqls.join(["!", "!*"].include?(operator) ? " AND " : " OR ")
780 else
818 else
781 sql
819 sql
782 end
820 end
783 end
821 end
784
822
785 IssueRelation::TYPES.keys.each do |relation_type|
823 IssueRelation::TYPES.keys.each do |relation_type|
786 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
787 end
825 end
788
826
789 private
827 private
790
828
791 def sql_for_custom_field(field, operator, value, custom_field_id)
829 def sql_for_custom_field(field, operator, value, custom_field_id)
792 db_table = CustomValue.table_name
830 db_table = CustomValue.table_name
793 db_field = 'value'
831 db_field = 'value'
794 filter = @available_filters[field]
832 filter = @available_filters[field]
795 return nil unless filter
833 return nil unless filter
796 if filter[:format] == 'user'
834 if filter[:format] == 'user'
797 if value.delete('me')
835 if value.delete('me')
798 value.push User.current.id.to_s
836 value.push User.current.id.to_s
799 end
837 end
800 end
838 end
801 not_in = nil
839 not_in = nil
802 if operator == '!'
840 if operator == '!'
803 # Makes ! operator work for custom fields with multiple values
841 # Makes ! operator work for custom fields with multiple values
804 operator = '='
842 operator = '='
805 not_in = 'NOT'
843 not_in = 'NOT'
806 end
844 end
807 customized_key = "id"
845 customized_key = "id"
808 customized_class = Issue
846 customized_class = Issue
809 if field =~ /^(.+)\.cf_/
847 if field =~ /^(.+)\.cf_/
810 assoc = $1
848 assoc = $1
811 customized_key = "#{assoc}_id"
849 customized_key = "#{assoc}_id"
812 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
813 raise "Unknown Issue association #{assoc}" unless customized_class
851 raise "Unknown Issue association #{assoc}" unless customized_class
814 end
852 end
815 "#{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 " +
816 sql_for_field(field, operator, value, db_table, db_field, true) + ')'
854 sql_for_field(field, operator, value, db_table, db_field, true) + ')'
817 end
855 end
818
856
819 # 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+
820 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)
821 sql = ''
859 sql = ''
822 case operator
860 case operator
823 when "="
861 when "="
824 if value.any?
862 if value.any?
825 case type_for(field)
863 case type_for(field)
826 when :date, :date_past
864 when :date, :date_past
827 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))
828 when :integer
866 when :integer
829 if is_custom_filter
867 if is_custom_filter
830 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})"
831 else
869 else
832 sql = "#{db_table}.#{db_field} = #{value.first.to_i}"
870 sql = "#{db_table}.#{db_field} = #{value.first.to_i}"
833 end
871 end
834 when :float
872 when :float
835 if is_custom_filter
873 if is_custom_filter
836 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})"
837 else
875 else
838 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}"
839 end
877 end
840 else
878 else
841 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(",") + ")"
842 end
880 end
843 else
881 else
844 # IN an empty set
882 # IN an empty set
845 sql = "1=0"
883 sql = "1=0"
846 end
884 end
847 when "!"
885 when "!"
848 if value.any?
886 if value.any?
849 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(",") + "))"
850 else
888 else
851 # NOT IN an empty set
889 # NOT IN an empty set
852 sql = "1=1"
890 sql = "1=1"
853 end
891 end
854 when "!*"
892 when "!*"
855 sql = "#{db_table}.#{db_field} IS NULL"
893 sql = "#{db_table}.#{db_field} IS NULL"
856 sql << " OR #{db_table}.#{db_field} = ''" if is_custom_filter
894 sql << " OR #{db_table}.#{db_field} = ''" if is_custom_filter
857 when "*"
895 when "*"
858 sql = "#{db_table}.#{db_field} IS NOT NULL"
896 sql = "#{db_table}.#{db_field} IS NOT NULL"
859 sql << " AND #{db_table}.#{db_field} <> ''" if is_custom_filter
897 sql << " AND #{db_table}.#{db_field} <> ''" if is_custom_filter
860 when ">="
898 when ">="
861 if [:date, :date_past].include?(type_for(field))
899 if [:date, :date_past].include?(type_for(field))
862 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)
863 else
901 else
864 if is_custom_filter
902 if is_custom_filter
865 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})"
866 else
904 else
867 sql = "#{db_table}.#{db_field} >= #{value.first.to_f}"
905 sql = "#{db_table}.#{db_field} >= #{value.first.to_f}"
868 end
906 end
869 end
907 end
870 when "<="
908 when "<="
871 if [:date, :date_past].include?(type_for(field))
909 if [:date, :date_past].include?(type_for(field))
872 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))
873 else
911 else
874 if is_custom_filter
912 if is_custom_filter
875 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})"
876 else
914 else
877 sql = "#{db_table}.#{db_field} <= #{value.first.to_f}"
915 sql = "#{db_table}.#{db_field} <= #{value.first.to_f}"
878 end
916 end
879 end
917 end
880 when "><"
918 when "><"
881 if [:date, :date_past].include?(type_for(field))
919 if [:date, :date_past].include?(type_for(field))
882 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))
883 else
921 else
884 if is_custom_filter
922 if is_custom_filter
885 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})"
886 else
924 else
887 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}"
888 end
926 end
889 end
927 end
890 when "o"
928 when "o"
891 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"
892 when "c"
930 when "c"
893 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"
894 when ">t-"
932 when ">t-"
895 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)
896 when "<t-"
934 when "<t-"
897 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)
898 when "t-"
936 when "t-"
899 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)
900 when ">t+"
938 when ">t+"
901 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)
902 when "<t+"
940 when "<t+"
903 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)
904 when "t+"
942 when "t+"
905 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)
906 when "t"
944 when "t"
907 sql = relative_date_clause(db_table, db_field, 0, 0)
945 sql = relative_date_clause(db_table, db_field, 0, 0)
908 when "w"
946 when "w"
909 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
910 day_of_week = Date.today.cwday
948 day_of_week = Date.today.cwday
911 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)
912 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)
913 when "~"
951 when "~"
914 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)}%'"
915 when "!~"
953 when "!~"
916 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)}%'"
917 else
955 else
918 raise "Unknown query operator #{operator}"
956 raise "Unknown query operator #{operator}"
919 end
957 end
920
958
921 return sql
959 return sql
922 end
960 end
923
961
924 def add_custom_fields_filters(custom_fields, assoc=nil)
962 def add_custom_fields_filters(custom_fields, assoc=nil)
925 return unless custom_fields.present?
963 return unless custom_fields.present?
926 @available_filters ||= {}
964 @available_filters ||= {}
927
965
928 custom_fields.select(&:is_filter?).each do |field|
966 custom_fields.select(&:is_filter?).each do |field|
929 case field.field_format
967 case field.field_format
930 when "text"
968 when "text"
931 options = { :type => :text, :order => 20 }
969 options = { :type => :text, :order => 20 }
932 when "list"
970 when "list"
933 options = { :type => :list_optional, :values => field.possible_values, :order => 20}
971 options = { :type => :list_optional, :values => field.possible_values, :order => 20}
934 when "date"
972 when "date"
935 options = { :type => :date, :order => 20 }
973 options = { :type => :date, :order => 20 }
936 when "bool"
974 when "bool"
937 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 }
938 when "int"
976 when "int"
939 options = { :type => :integer, :order => 20 }
977 options = { :type => :integer, :order => 20 }
940 when "float"
978 when "float"
941 options = { :type => :float, :order => 20 }
979 options = { :type => :float, :order => 20 }
942 when "user", "version"
980 when "user", "version"
943 next unless project
981 next unless project
944 values = field.possible_values_options(project)
982 values = field.possible_values_options(project)
945 if User.current.logged? && field.field_format == 'user'
983 if User.current.logged? && field.field_format == 'user'
946 values.unshift ["<< #{l(:label_me)} >>", "me"]
984 values.unshift ["<< #{l(:label_me)} >>", "me"]
947 end
985 end
948 options = { :type => :list_optional, :values => values, :order => 20}
986 options = { :type => :list_optional, :values => values, :order => 20}
949 else
987 else
950 options = { :type => :string, :order => 20 }
988 options = { :type => :string, :order => 20 }
951 end
989 end
952 filter_id = "cf_#{field.id}"
990 filter_id = "cf_#{field.id}"
953 filter_name = field.name
991 filter_name = field.name
954 if assoc.present?
992 if assoc.present?
955 filter_id = "#{assoc}.#{filter_id}"
993 filter_id = "#{assoc}.#{filter_id}"
956 filter_name = l("label_attribute_of_#{assoc}", :name => filter_name)
994 filter_name = l("label_attribute_of_#{assoc}", :name => filter_name)
957 end
995 end
958 @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 })
959 end
997 end
960 end
998 end
961
999
962 def add_associations_custom_fields_filters(*associations)
1000 def add_associations_custom_fields_filters(*associations)
963 fields_by_class = CustomField.where(:is_filter => true).group_by(&:class)
1001 fields_by_class = CustomField.where(:is_filter => true).group_by(&:class)
964 associations.each do |assoc|
1002 associations.each do |assoc|
965 association_klass = Issue.reflect_on_association(assoc).klass
1003 association_klass = Issue.reflect_on_association(assoc).klass
966 fields_by_class.each do |field_class, fields|
1004 fields_by_class.each do |field_class, fields|
967 if field_class.customized_class <= association_klass
1005 if field_class.customized_class <= association_klass
968 add_custom_fields_filters(fields, assoc)
1006 add_custom_fields_filters(fields, assoc)
969 end
1007 end
970 end
1008 end
971 end
1009 end
972 end
1010 end
973
1011
974 # Returns a SQL clause for a date or datetime field.
1012 # Returns a SQL clause for a date or datetime field.
975 def date_clause(table, field, from, to)
1013 def date_clause(table, field, from, to)
976 s = []
1014 s = []
977 if from
1015 if from
978 from_yesterday = from - 1
1016 from_yesterday = from - 1
979 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)
980 if self.class.default_timezone == :utc
1018 if self.class.default_timezone == :utc
981 from_yesterday_time = from_yesterday_time.utc
1019 from_yesterday_time = from_yesterday_time.utc
982 end
1020 end
983 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)])
984 end
1022 end
985 if to
1023 if to
986 to_time = Time.local(to.year, to.month, to.day)
1024 to_time = Time.local(to.year, to.month, to.day)
987 if self.class.default_timezone == :utc
1025 if self.class.default_timezone == :utc
988 to_time = to_time.utc
1026 to_time = to_time.utc
989 end
1027 end
990 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)])
991 end
1029 end
992 s.join(' AND ')
1030 s.join(' AND ')
993 end
1031 end
994
1032
995 # 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.
996 def relative_date_clause(table, field, days_from, days_to)
1034 def relative_date_clause(table, field, days_from, days_to)
997 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))
998 end
1036 end
999
1037
1000 # Additional joins required for the given sort options
1038 # Additional joins required for the given sort options
1001 def joins_for_order_statement(order_options)
1039 def joins_for_order_statement(order_options)
1002 joins = []
1040 joins = []
1003
1041
1004 if order_options
1042 if order_options
1005 if order_options.include?('authors')
1043 if order_options.include?('authors')
1006 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"
1007 end
1045 end
1008 order_options.scan(/cf_\d+/).uniq.each do |name|
1046 order_options.scan(/cf_\d+/).uniq.each do |name|
1009 column = available_columns.detect {|c| c.name.to_s == name}
1047 column = available_columns.detect {|c| c.name.to_s == name}
1010 join = column && column.custom_field.join_for_order_statement
1048 join = column && column.custom_field.join_for_order_statement
1011 if join
1049 if join
1012 joins << join
1050 joins << join
1013 end
1051 end
1014 end
1052 end
1015 end
1053 end
1016
1054
1017 joins.any? ? joins.join(' ') : nil
1055 joins.any? ? joins.join(' ') : nil
1018 end
1056 end
1019 end
1057 end
General Comments 0
You need to be logged in to leave comments. Login now