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