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