annotate app/models/.svn/text-base/query.rb.svn-base @ 507:0c939c159af4 redmine-1.2

Update to Redmine 1.2.1 on 1.2-stable branch (Redmine SVN rev 6270)
author Chris Cannam
date Thu, 14 Jul 2011 10:32:19 +0100
parents cbce1fd3b1b7
children
rev   line source
Chris@0 1 # Redmine - project management software
Chris@441 2 # Copyright (C) 2006-2011 Jean-Philippe Lang
Chris@0 3 #
Chris@0 4 # This program is free software; you can redistribute it and/or
Chris@0 5 # modify it under the terms of the GNU General Public License
Chris@0 6 # as published by the Free Software Foundation; either version 2
Chris@0 7 # of the License, or (at your option) any later version.
Chris@441 8 #
Chris@0 9 # This program is distributed in the hope that it will be useful,
Chris@0 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
Chris@0 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Chris@0 12 # GNU General Public License for more details.
Chris@441 13 #
Chris@0 14 # You should have received a copy of the GNU General Public License
Chris@0 15 # along with this program; if not, write to the Free Software
Chris@0 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Chris@0 17
Chris@441 18 class QueryColumn
Chris@0 19 attr_accessor :name, :sortable, :groupable, :default_order
Chris@0 20 include Redmine::I18n
Chris@441 21
Chris@0 22 def initialize(name, options={})
Chris@0 23 self.name = name
Chris@0 24 self.sortable = options[:sortable]
Chris@0 25 self.groupable = options[:groupable] || false
Chris@0 26 if groupable == true
Chris@0 27 self.groupable = name.to_s
Chris@0 28 end
Chris@0 29 self.default_order = options[:default_order]
Chris@0 30 @caption_key = options[:caption] || "field_#{name}"
Chris@0 31 end
Chris@441 32
Chris@0 33 def caption
Chris@0 34 l(@caption_key)
Chris@0 35 end
Chris@441 36
Chris@0 37 # Returns true if the column is sortable, otherwise false
Chris@0 38 def sortable?
Chris@0 39 !sortable.nil?
Chris@0 40 end
Chris@441 41
Chris@0 42 def value(issue)
Chris@0 43 issue.send name
Chris@0 44 end
Chris@441 45
Chris@441 46 def css_classes
Chris@441 47 name
Chris@441 48 end
Chris@0 49 end
Chris@0 50
Chris@0 51 class QueryCustomFieldColumn < QueryColumn
Chris@0 52
Chris@0 53 def initialize(custom_field)
Chris@0 54 self.name = "cf_#{custom_field.id}".to_sym
Chris@0 55 self.sortable = custom_field.order_statement || false
Chris@0 56 if %w(list date bool int).include?(custom_field.field_format)
Chris@0 57 self.groupable = custom_field.order_statement
Chris@0 58 end
Chris@0 59 self.groupable ||= false
Chris@0 60 @cf = custom_field
Chris@0 61 end
Chris@441 62
Chris@0 63 def caption
Chris@0 64 @cf.name
Chris@0 65 end
Chris@441 66
Chris@0 67 def custom_field
Chris@0 68 @cf
Chris@0 69 end
Chris@441 70
Chris@0 71 def value(issue)
Chris@0 72 cv = issue.custom_values.detect {|v| v.custom_field_id == @cf.id}
Chris@0 73 cv && @cf.cast_value(cv.value)
Chris@0 74 end
Chris@441 75
Chris@441 76 def css_classes
Chris@441 77 @css_classes ||= "#{name} #{@cf.field_format}"
Chris@441 78 end
Chris@0 79 end
Chris@0 80
Chris@0 81 class Query < ActiveRecord::Base
Chris@0 82 class StatementInvalid < ::ActiveRecord::StatementInvalid
Chris@0 83 end
Chris@441 84
Chris@0 85 belongs_to :project
Chris@0 86 belongs_to :user
Chris@0 87 serialize :filters
Chris@0 88 serialize :column_names
Chris@0 89 serialize :sort_criteria, Array
Chris@441 90
Chris@0 91 attr_protected :project_id, :user_id
Chris@441 92
Chris@0 93 validates_presence_of :name, :on => :save
Chris@0 94 validates_length_of :name, :maximum => 255
Chris@441 95
Chris@441 96 @@operators = { "=" => :label_equals,
Chris@0 97 "!" => :label_not_equals,
Chris@0 98 "o" => :label_open_issues,
Chris@0 99 "c" => :label_closed_issues,
Chris@0 100 "!*" => :label_none,
Chris@0 101 "*" => :label_all,
Chris@0 102 ">=" => :label_greater_or_equal,
Chris@0 103 "<=" => :label_less_or_equal,
Chris@0 104 "<t+" => :label_in_less_than,
Chris@0 105 ">t+" => :label_in_more_than,
Chris@0 106 "t+" => :label_in,
Chris@0 107 "t" => :label_today,
Chris@0 108 "w" => :label_this_week,
Chris@0 109 ">t-" => :label_less_than_ago,
Chris@0 110 "<t-" => :label_more_than_ago,
Chris@0 111 "t-" => :label_ago,
Chris@0 112 "~" => :label_contains,
Chris@0 113 "!~" => :label_not_contains }
Chris@0 114
Chris@0 115 cattr_reader :operators
Chris@441 116
Chris@0 117 @@operators_by_filter_type = { :list => [ "=", "!" ],
Chris@0 118 :list_status => [ "o", "=", "!", "c", "*" ],
Chris@0 119 :list_optional => [ "=", "!", "!*", "*" ],
Chris@0 120 :list_subprojects => [ "*", "!*", "=" ],
Chris@0 121 :date => [ "<t+", ">t+", "t+", "t", "w", ">t-", "<t-", "t-" ],
Chris@0 122 :date_past => [ ">t-", "<t-", "t-", "t", "w" ],
Chris@0 123 :string => [ "=", "~", "!", "!~" ],
Chris@0 124 :text => [ "~", "!~" ],
Chris@0 125 :integer => [ "=", ">=", "<=", "!*", "*" ] }
Chris@0 126
Chris@0 127 cattr_reader :operators_by_filter_type
Chris@0 128
Chris@0 129 @@available_columns = [
Chris@0 130 QueryColumn.new(:project, :sortable => "#{Project.table_name}.name", :groupable => true),
Chris@0 131 QueryColumn.new(:tracker, :sortable => "#{Tracker.table_name}.position", :groupable => true),
Chris@0 132 QueryColumn.new(:parent, :sortable => ["#{Issue.table_name}.root_id", "#{Issue.table_name}.lft ASC"], :default_order => 'desc', :caption => :field_parent_issue),
Chris@0 133 QueryColumn.new(:status, :sortable => "#{IssueStatus.table_name}.position", :groupable => true),
Chris@0 134 QueryColumn.new(:priority, :sortable => "#{IssuePriority.table_name}.position", :default_order => 'desc', :groupable => true),
Chris@0 135 QueryColumn.new(:subject, :sortable => "#{Issue.table_name}.subject"),
Chris@0 136 QueryColumn.new(:author),
Chris@0 137 QueryColumn.new(:assigned_to, :sortable => ["#{User.table_name}.lastname", "#{User.table_name}.firstname", "#{User.table_name}.id"], :groupable => true),
Chris@0 138 QueryColumn.new(:updated_on, :sortable => "#{Issue.table_name}.updated_on", :default_order => 'desc'),
Chris@0 139 QueryColumn.new(:category, :sortable => "#{IssueCategory.table_name}.name", :groupable => true),
Chris@0 140 QueryColumn.new(:fixed_version, :sortable => ["#{Version.table_name}.effective_date", "#{Version.table_name}.name"], :default_order => 'desc', :groupable => true),
Chris@0 141 QueryColumn.new(:start_date, :sortable => "#{Issue.table_name}.start_date"),
Chris@0 142 QueryColumn.new(:due_date, :sortable => "#{Issue.table_name}.due_date"),
Chris@0 143 QueryColumn.new(:estimated_hours, :sortable => "#{Issue.table_name}.estimated_hours"),
Chris@0 144 QueryColumn.new(:done_ratio, :sortable => "#{Issue.table_name}.done_ratio", :groupable => true),
Chris@0 145 QueryColumn.new(:created_on, :sortable => "#{Issue.table_name}.created_on", :default_order => 'desc'),
Chris@0 146 ]
Chris@0 147 cattr_reader :available_columns
Chris@441 148
Chris@0 149 def initialize(attributes = nil)
Chris@0 150 super attributes
Chris@0 151 self.filters ||= { 'status_id' => {:operator => "o", :values => [""]} }
Chris@0 152 end
Chris@441 153
Chris@0 154 def after_initialize
Chris@0 155 # Store the fact that project is nil (used in #editable_by?)
Chris@0 156 @is_for_all = project.nil?
Chris@0 157 end
Chris@441 158
Chris@0 159 def validate
Chris@0 160 filters.each_key do |field|
Chris@441 161 errors.add label_for(field), :blank unless
Chris@0 162 # filter requires one or more values
Chris@441 163 (values_for(field) and !values_for(field).first.blank?) or
Chris@0 164 # filter doesn't require any value
Chris@0 165 ["o", "c", "!*", "*", "t", "w"].include? operator_for(field)
Chris@0 166 end if filters
Chris@0 167 end
Chris@507 168
Chris@507 169 # Returns true if the query is visible to +user+ or the current user.
Chris@507 170 def visible?(user=User.current)
Chris@507 171 self.is_public? || self.user_id == user.id
Chris@507 172 end
Chris@441 173
Chris@0 174 def editable_by?(user)
Chris@0 175 return false unless user
Chris@0 176 # Admin can edit them all and regular users can edit their private queries
Chris@0 177 return true if user.admin? || (!is_public && self.user_id == user.id)
Chris@0 178 # Members can not edit public queries that are for all project (only admin is allowed to)
Chris@0 179 is_public && !@is_for_all && user.allowed_to?(:manage_public_queries, project)
Chris@0 180 end
Chris@441 181
Chris@0 182 def available_filters
Chris@0 183 return @available_filters if @available_filters
Chris@441 184
Chris@0 185 trackers = project.nil? ? Tracker.find(:all, :order => 'position') : project.rolled_up_trackers
Chris@441 186
Chris@441 187 @available_filters = { "status_id" => { :type => :list_status, :order => 1, :values => IssueStatus.find(:all, :order => 'position').collect{|s| [s.name, s.id.to_s] } },
Chris@441 188 "tracker_id" => { :type => :list, :order => 2, :values => trackers.collect{|s| [s.name, s.id.to_s] } },
Chris@0 189 "priority_id" => { :type => :list, :order => 3, :values => IssuePriority.all.collect{|s| [s.name, s.id.to_s] } },
Chris@441 190 "subject" => { :type => :text, :order => 8 },
Chris@441 191 "created_on" => { :type => :date_past, :order => 9 },
Chris@0 192 "updated_on" => { :type => :date_past, :order => 10 },
Chris@0 193 "start_date" => { :type => :date, :order => 11 },
Chris@0 194 "due_date" => { :type => :date, :order => 12 },
Chris@0 195 "estimated_hours" => { :type => :integer, :order => 13 },
Chris@0 196 "done_ratio" => { :type => :integer, :order => 14 }}
Chris@441 197
Chris@0 198 user_values = []
Chris@0 199 user_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged?
Chris@0 200 if project
Chris@0 201 user_values += project.users.sort.collect{|s| [s.name, s.id.to_s] }
Chris@0 202 else
Chris@119 203 all_projects = Project.visible.all
Chris@119 204 if all_projects.any?
Chris@119 205 # members of visible projects
Chris@119 206 user_values += User.active.find(:all, :conditions => ["#{User.table_name}.id IN (SELECT DISTINCT user_id FROM members WHERE project_id IN (?))", all_projects.collect(&:id)]).sort.collect{|s| [s.name, s.id.to_s] }
Chris@441 207
Chris@119 208 # project filter
Chris@119 209 project_values = []
Chris@119 210 Project.project_tree(all_projects) do |p, level|
Chris@119 211 prefix = (level > 0 ? ('--' * level + ' ') : '')
Chris@119 212 project_values << ["#{prefix}#{p.name}", p.id.to_s]
Chris@119 213 end
Chris@119 214 @available_filters["project_id"] = { :type => :list, :order => 1, :values => project_values} unless project_values.empty?
Chris@0 215 end
Chris@0 216 end
Chris@0 217 @available_filters["assigned_to_id"] = { :type => :list_optional, :order => 4, :values => user_values } unless user_values.empty?
Chris@0 218 @available_filters["author_id"] = { :type => :list, :order => 5, :values => user_values } unless user_values.empty?
chris@22 219
chris@37 220 group_values = Group.all.collect {|g| [g.name, g.id.to_s] }
chris@22 221 @available_filters["member_of_group"] = { :type => :list_optional, :order => 6, :values => group_values } unless group_values.empty?
chris@22 222
chris@37 223 role_values = Role.givable.collect {|r| [r.name, r.id.to_s] }
chris@22 224 @available_filters["assigned_to_role"] = { :type => :list_optional, :order => 7, :values => role_values } unless role_values.empty?
Chris@441 225
Chris@0 226 if User.current.logged?
Chris@0 227 @available_filters["watcher_id"] = { :type => :list, :order => 15, :values => [["<< #{l(:label_me)} >>", "me"]] }
Chris@0 228 end
Chris@441 229
Chris@0 230 if project
Chris@0 231 # project specific filters
Chris@441 232 categories = @project.issue_categories.all
Chris@441 233 unless categories.empty?
Chris@441 234 @available_filters["category_id"] = { :type => :list_optional, :order => 6, :values => categories.collect{|s| [s.name, s.id.to_s] } }
Chris@0 235 end
Chris@441 236 versions = @project.shared_versions.all
Chris@441 237 unless versions.empty?
Chris@441 238 @available_filters["fixed_version_id"] = { :type => :list_optional, :order => 7, :values => versions.sort.collect{|s| ["#{s.project.name} - #{s.name}", s.id.to_s] } }
Chris@0 239 end
Chris@441 240 unless @project.leaf?
Chris@441 241 subprojects = @project.descendants.visible.all
Chris@441 242 unless subprojects.empty?
Chris@441 243 @available_filters["subproject_id"] = { :type => :list_subprojects, :order => 13, :values => subprojects.collect{|s| [s.name, s.id.to_s] } }
Chris@441 244 end
Chris@0 245 end
Chris@0 246 add_custom_fields_filters(@project.all_issue_custom_fields)
Chris@0 247 else
Chris@0 248 # global filters for cross project issue list
Chris@0 249 system_shared_versions = Version.visible.find_all_by_sharing('system')
Chris@0 250 unless system_shared_versions.empty?
Chris@0 251 @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] } }
Chris@0 252 end
Chris@0 253 add_custom_fields_filters(IssueCustomField.find(:all, :conditions => {:is_filter => true, :is_for_all => true}))
Chris@0 254 end
Chris@0 255 @available_filters
Chris@0 256 end
Chris@441 257
Chris@0 258 def add_filter(field, operator, values)
Chris@0 259 # values must be an array
Chris@0 260 return unless values and values.is_a? Array # and !values.first.empty?
Chris@0 261 # check if field is defined as an available filter
Chris@0 262 if available_filters.has_key? field
Chris@0 263 filter_options = available_filters[field]
Chris@0 264 # check if operator is allowed for that filter
Chris@0 265 #if @@operators_by_filter_type[filter_options[:type]].include? operator
Chris@0 266 # allowed_values = values & ([""] + (filter_options[:values] || []).collect {|val| val[1]})
Chris@0 267 # filters[field] = {:operator => operator, :values => allowed_values } if (allowed_values.first and !allowed_values.first.empty?) or ["o", "c", "!*", "*", "t"].include? operator
Chris@0 268 #end
Chris@0 269 filters[field] = {:operator => operator, :values => values }
Chris@0 270 end
Chris@0 271 end
Chris@441 272
Chris@0 273 def add_short_filter(field, expression)
Chris@0 274 return unless expression
Chris@0 275 parms = expression.scan(/^(o|c|!\*|!|\*)?(.*)$/).first
Chris@0 276 add_filter field, (parms[0] || "="), [parms[1] || ""]
Chris@0 277 end
Chris@0 278
Chris@0 279 # Add multiple filters using +add_filter+
Chris@0 280 def add_filters(fields, operators, values)
chris@37 281 if fields.is_a?(Array) && operators.is_a?(Hash) && values.is_a?(Hash)
chris@37 282 fields.each do |field|
chris@37 283 add_filter(field, operators[field], values[field])
chris@37 284 end
Chris@0 285 end
Chris@0 286 end
Chris@441 287
Chris@0 288 def has_filter?(field)
Chris@0 289 filters and filters[field]
Chris@0 290 end
Chris@441 291
Chris@0 292 def operator_for(field)
Chris@0 293 has_filter?(field) ? filters[field][:operator] : nil
Chris@0 294 end
Chris@441 295
Chris@0 296 def values_for(field)
Chris@0 297 has_filter?(field) ? filters[field][:values] : nil
Chris@0 298 end
Chris@441 299
Chris@0 300 def label_for(field)
Chris@0 301 label = available_filters[field][:name] if available_filters.has_key?(field)
Chris@0 302 label ||= field.gsub(/\_id$/, "")
Chris@0 303 end
Chris@0 304
Chris@0 305 def available_columns
Chris@0 306 return @available_columns if @available_columns
Chris@0 307 @available_columns = Query.available_columns
Chris@0 308 @available_columns += (project ?
Chris@0 309 project.all_issue_custom_fields :
Chris@0 310 IssueCustomField.find(:all)
Chris@441 311 ).collect {|cf| QueryCustomFieldColumn.new(cf) }
Chris@0 312 end
Chris@0 313
Chris@0 314 def self.available_columns=(v)
Chris@0 315 self.available_columns = (v)
Chris@0 316 end
Chris@441 317
Chris@0 318 def self.add_available_column(column)
Chris@0 319 self.available_columns << (column) if column.is_a?(QueryColumn)
Chris@0 320 end
Chris@441 321
Chris@0 322 # Returns an array of columns that can be used to group the results
Chris@0 323 def groupable_columns
Chris@0 324 available_columns.select {|c| c.groupable}
Chris@0 325 end
Chris@0 326
Chris@0 327 # Returns a Hash of columns and the key for sorting
Chris@0 328 def sortable_columns
Chris@0 329 {'id' => "#{Issue.table_name}.id"}.merge(available_columns.inject({}) {|h, column|
Chris@0 330 h[column.name.to_s] = column.sortable
Chris@0 331 h
Chris@0 332 })
Chris@0 333 end
Chris@441 334
Chris@0 335 def columns
Chris@0 336 if has_default_columns?
Chris@0 337 available_columns.select do |c|
Chris@0 338 # Adds the project column by default for cross-project lists
Chris@0 339 Setting.issue_list_default_columns.include?(c.name.to_s) || (c.name == :project && project.nil?)
Chris@0 340 end
Chris@0 341 else
Chris@0 342 # preserve the column_names order
Chris@0 343 column_names.collect {|name| available_columns.find {|col| col.name == name}}.compact
Chris@0 344 end
Chris@0 345 end
Chris@441 346
Chris@0 347 def column_names=(names)
Chris@0 348 if names
Chris@0 349 names = names.select {|n| n.is_a?(Symbol) || !n.blank? }
Chris@0 350 names = names.collect {|n| n.is_a?(Symbol) ? n : n.to_sym }
Chris@0 351 # Set column_names to nil if default columns
Chris@0 352 if names.map(&:to_s) == Setting.issue_list_default_columns
Chris@0 353 names = nil
Chris@0 354 end
Chris@0 355 end
Chris@0 356 write_attribute(:column_names, names)
Chris@0 357 end
Chris@441 358
Chris@0 359 def has_column?(column)
Chris@0 360 column_names && column_names.include?(column.name)
Chris@0 361 end
Chris@441 362
Chris@0 363 def has_default_columns?
Chris@0 364 column_names.nil? || column_names.empty?
Chris@0 365 end
Chris@441 366
Chris@0 367 def sort_criteria=(arg)
Chris@0 368 c = []
Chris@0 369 if arg.is_a?(Hash)
Chris@0 370 arg = arg.keys.sort.collect {|k| arg[k]}
Chris@0 371 end
Chris@0 372 c = arg.select {|k,o| !k.to_s.blank?}.slice(0,3).collect {|k,o| [k.to_s, o == 'desc' ? o : 'asc']}
Chris@0 373 write_attribute(:sort_criteria, c)
Chris@0 374 end
Chris@441 375
Chris@0 376 def sort_criteria
Chris@0 377 read_attribute(:sort_criteria) || []
Chris@0 378 end
Chris@441 379
Chris@0 380 def sort_criteria_key(arg)
Chris@0 381 sort_criteria && sort_criteria[arg] && sort_criteria[arg].first
Chris@0 382 end
Chris@441 383
Chris@0 384 def sort_criteria_order(arg)
Chris@0 385 sort_criteria && sort_criteria[arg] && sort_criteria[arg].last
Chris@0 386 end
Chris@441 387
Chris@0 388 # Returns the SQL sort order that should be prepended for grouping
Chris@0 389 def group_by_sort_order
Chris@0 390 if grouped? && (column = group_by_column)
Chris@0 391 column.sortable.is_a?(Array) ?
Chris@0 392 column.sortable.collect {|s| "#{s} #{column.default_order}"}.join(',') :
Chris@0 393 "#{column.sortable} #{column.default_order}"
Chris@0 394 end
Chris@0 395 end
Chris@441 396
Chris@0 397 # Returns true if the query is a grouped query
Chris@0 398 def grouped?
Chris@119 399 !group_by_column.nil?
Chris@0 400 end
Chris@441 401
Chris@0 402 def group_by_column
Chris@119 403 groupable_columns.detect {|c| c.groupable && c.name.to_s == group_by}
Chris@0 404 end
Chris@441 405
Chris@0 406 def group_by_statement
Chris@119 407 group_by_column.try(:groupable)
Chris@0 408 end
Chris@441 409
Chris@0 410 def project_statement
Chris@0 411 project_clauses = []
Chris@0 412 if project && !@project.descendants.active.empty?
Chris@0 413 ids = [project.id]
Chris@0 414 if has_filter?("subproject_id")
Chris@0 415 case operator_for("subproject_id")
Chris@0 416 when '='
Chris@0 417 # include the selected subprojects
Chris@0 418 ids += values_for("subproject_id").each(&:to_i)
Chris@0 419 when '!*'
Chris@0 420 # main project only
Chris@0 421 else
Chris@0 422 # all subprojects
Chris@0 423 ids += project.descendants.collect(&:id)
Chris@0 424 end
Chris@0 425 elsif Setting.display_subprojects_issues?
Chris@0 426 ids += project.descendants.collect(&:id)
Chris@0 427 end
Chris@0 428 project_clauses << "#{Project.table_name}.id IN (%s)" % ids.join(',')
Chris@0 429 elsif project
Chris@0 430 project_clauses << "#{Project.table_name}.id = %d" % project.id
Chris@0 431 end
Chris@441 432 project_clauses.any? ? project_clauses.join(' AND ') : nil
Chris@0 433 end
Chris@0 434
Chris@0 435 def statement
Chris@0 436 # filters clauses
Chris@0 437 filters_clauses = []
Chris@0 438 filters.each_key do |field|
Chris@0 439 next if field == "subproject_id"
Chris@0 440 v = values_for(field).clone
Chris@0 441 next unless v and !v.empty?
Chris@0 442 operator = operator_for(field)
Chris@441 443
Chris@0 444 # "me" value subsitution
Chris@0 445 if %w(assigned_to_id author_id watcher_id).include?(field)
Chris@0 446 v.push(User.current.logged? ? User.current.id.to_s : "0") if v.delete("me")
Chris@0 447 end
Chris@441 448
Chris@0 449 sql = ''
Chris@0 450 if field =~ /^cf_(\d+)$/
Chris@0 451 # custom field
Chris@0 452 db_table = CustomValue.table_name
Chris@0 453 db_field = 'value'
Chris@0 454 is_custom_filter = true
Chris@0 455 sql << "#{Issue.table_name}.id IN (SELECT #{Issue.table_name}.id FROM #{Issue.table_name} LEFT OUTER JOIN #{db_table} ON #{db_table}.customized_type='Issue' AND #{db_table}.customized_id=#{Issue.table_name}.id AND #{db_table}.custom_field_id=#{$1} WHERE "
Chris@0 456 sql << sql_for_field(field, operator, v, db_table, db_field, true) + ')'
Chris@0 457 elsif field == 'watcher_id'
Chris@0 458 db_table = Watcher.table_name
Chris@0 459 db_field = 'user_id'
Chris@0 460 sql << "#{Issue.table_name}.id #{ operator == '=' ? 'IN' : 'NOT IN' } (SELECT #{db_table}.watchable_id FROM #{db_table} WHERE #{db_table}.watchable_type='Issue' AND "
Chris@0 461 sql << sql_for_field(field, '=', v, db_table, db_field) + ')'
chris@22 462 elsif field == "member_of_group" # named field
chris@22 463 if operator == '*' # Any group
chris@22 464 groups = Group.all
chris@22 465 operator = '=' # Override the operator since we want to find by assigned_to
chris@22 466 elsif operator == "!*"
chris@22 467 groups = Group.all
chris@22 468 operator = '!' # Override the operator since we want to find by assigned_to
chris@22 469 else
chris@22 470 groups = Group.find_all_by_id(v)
chris@22 471 end
chris@22 472 groups ||= []
chris@22 473
chris@22 474 members_of_groups = groups.inject([]) {|user_ids, group|
chris@22 475 if group && group.user_ids.present?
chris@22 476 user_ids << group.user_ids
chris@22 477 end
chris@22 478 user_ids.flatten.uniq.compact
chris@22 479 }.sort.collect(&:to_s)
Chris@441 480
chris@22 481 sql << '(' + sql_for_field("assigned_to_id", operator, members_of_groups, Issue.table_name, "assigned_to_id", false) + ')'
chris@22 482
chris@22 483 elsif field == "assigned_to_role" # named field
chris@22 484 if operator == "*" # Any Role
chris@22 485 roles = Role.givable
chris@22 486 operator = '=' # Override the operator since we want to find by assigned_to
chris@22 487 elsif operator == "!*" # No role
chris@22 488 roles = Role.givable
chris@22 489 operator = '!' # Override the operator since we want to find by assigned_to
chris@22 490 else
chris@22 491 roles = Role.givable.find_all_by_id(v)
chris@22 492 end
chris@22 493 roles ||= []
Chris@441 494
chris@22 495 members_of_roles = roles.inject([]) {|user_ids, role|
chris@22 496 if role && role.members
chris@22 497 user_ids << role.members.collect(&:user_id)
chris@22 498 end
chris@22 499 user_ids.flatten.uniq.compact
chris@22 500 }.sort.collect(&:to_s)
Chris@441 501
chris@22 502 sql << '(' + sql_for_field("assigned_to_id", operator, members_of_roles, Issue.table_name, "assigned_to_id", false) + ')'
Chris@0 503 else
Chris@0 504 # regular field
Chris@0 505 db_table = Issue.table_name
Chris@0 506 db_field = field
Chris@0 507 sql << '(' + sql_for_field(field, operator, v, db_table, db_field) + ')'
Chris@0 508 end
Chris@0 509 filters_clauses << sql
Chris@441 510
Chris@0 511 end if filters and valid?
Chris@441 512
Chris@441 513 filters_clauses << project_statement
Chris@441 514 filters_clauses.reject!(&:blank?)
Chris@441 515
Chris@441 516 filters_clauses.any? ? filters_clauses.join(' AND ') : nil
Chris@0 517 end
Chris@441 518
Chris@0 519 # Returns the issue count
Chris@0 520 def issue_count
Chris@0 521 Issue.count(:include => [:status, :project], :conditions => statement)
Chris@0 522 rescue ::ActiveRecord::StatementInvalid => e
Chris@0 523 raise StatementInvalid.new(e.message)
Chris@0 524 end
Chris@441 525
Chris@0 526 # Returns the issue count by group or nil if query is not grouped
Chris@0 527 def issue_count_by_group
Chris@0 528 r = nil
Chris@0 529 if grouped?
Chris@0 530 begin
Chris@0 531 # Rails will raise an (unexpected) RecordNotFound if there's only a nil group value
Chris@441 532 r = Issue.visible.count(:group => group_by_statement, :include => [:status, :project], :conditions => statement)
Chris@0 533 rescue ActiveRecord::RecordNotFound
Chris@0 534 r = {nil => issue_count}
Chris@0 535 end
Chris@0 536 c = group_by_column
Chris@0 537 if c.is_a?(QueryCustomFieldColumn)
Chris@0 538 r = r.keys.inject({}) {|h, k| h[c.custom_field.cast_value(k)] = r[k]; h}
Chris@0 539 end
Chris@0 540 end
Chris@0 541 r
Chris@0 542 rescue ::ActiveRecord::StatementInvalid => e
Chris@0 543 raise StatementInvalid.new(e.message)
Chris@0 544 end
Chris@441 545
Chris@0 546 # Returns the issues
Chris@0 547 # Valid options are :order, :offset, :limit, :include, :conditions
Chris@0 548 def issues(options={})
Chris@0 549 order_option = [group_by_sort_order, options[:order]].reject {|s| s.blank?}.join(',')
Chris@0 550 order_option = nil if order_option.blank?
Chris@441 551
Chris@441 552 Issue.visible.find :all, :include => ([:status, :project] + (options[:include] || [])).uniq,
Chris@0 553 :conditions => Query.merge_conditions(statement, options[:conditions]),
Chris@0 554 :order => order_option,
Chris@0 555 :limit => options[:limit],
Chris@0 556 :offset => options[:offset]
Chris@0 557 rescue ::ActiveRecord::StatementInvalid => e
Chris@0 558 raise StatementInvalid.new(e.message)
Chris@0 559 end
Chris@0 560
Chris@0 561 # Returns the journals
Chris@0 562 # Valid options are :order, :offset, :limit
Chris@0 563 def journals(options={})
Chris@441 564 Journal.visible.find :all, :include => [:details, :user, {:issue => [:project, :author, :tracker, :status]}],
Chris@0 565 :conditions => statement,
Chris@0 566 :order => options[:order],
Chris@0 567 :limit => options[:limit],
Chris@0 568 :offset => options[:offset]
Chris@0 569 rescue ::ActiveRecord::StatementInvalid => e
Chris@0 570 raise StatementInvalid.new(e.message)
Chris@0 571 end
Chris@441 572
Chris@0 573 # Returns the versions
Chris@0 574 # Valid options are :conditions
Chris@0 575 def versions(options={})
Chris@441 576 Version.visible.find :all, :include => :project,
Chris@0 577 :conditions => Query.merge_conditions(project_statement, options[:conditions])
Chris@0 578 rescue ::ActiveRecord::StatementInvalid => e
Chris@0 579 raise StatementInvalid.new(e.message)
Chris@0 580 end
Chris@441 581
Chris@0 582 private
Chris@441 583
Chris@0 584 # Helper method to generate the WHERE sql for a +field+, +operator+ and a +value+
Chris@0 585 def sql_for_field(field, operator, value, db_table, db_field, is_custom_filter=false)
Chris@0 586 sql = ''
Chris@0 587 case operator
Chris@0 588 when "="
Chris@245 589 if value.any?
Chris@245 590 sql = "#{db_table}.#{db_field} IN (" + value.collect{|val| "'#{connection.quote_string(val)}'"}.join(",") + ")"
Chris@245 591 else
Chris@245 592 # IN an empty set
Chris@245 593 sql = "1=0"
Chris@245 594 end
Chris@0 595 when "!"
Chris@245 596 if value.any?
Chris@245 597 sql = "(#{db_table}.#{db_field} IS NULL OR #{db_table}.#{db_field} NOT IN (" + value.collect{|val| "'#{connection.quote_string(val)}'"}.join(",") + "))"
Chris@245 598 else
Chris@245 599 # NOT IN an empty set
Chris@245 600 sql = "1=1"
Chris@245 601 end
Chris@0 602 when "!*"
Chris@0 603 sql = "#{db_table}.#{db_field} IS NULL"
Chris@0 604 sql << " OR #{db_table}.#{db_field} = ''" if is_custom_filter
Chris@0 605 when "*"
Chris@0 606 sql = "#{db_table}.#{db_field} IS NOT NULL"
Chris@0 607 sql << " AND #{db_table}.#{db_field} <> ''" if is_custom_filter
Chris@0 608 when ">="
Chris@0 609 sql = "#{db_table}.#{db_field} >= #{value.first.to_i}"
Chris@0 610 when "<="
Chris@0 611 sql = "#{db_table}.#{db_field} <= #{value.first.to_i}"
Chris@0 612 when "o"
Chris@0 613 sql = "#{IssueStatus.table_name}.is_closed=#{connection.quoted_false}" if field == "status_id"
Chris@0 614 when "c"
Chris@0 615 sql = "#{IssueStatus.table_name}.is_closed=#{connection.quoted_true}" if field == "status_id"
Chris@0 616 when ">t-"
Chris@0 617 sql = date_range_clause(db_table, db_field, - value.first.to_i, 0)
Chris@0 618 when "<t-"
Chris@0 619 sql = date_range_clause(db_table, db_field, nil, - value.first.to_i)
Chris@0 620 when "t-"
Chris@0 621 sql = date_range_clause(db_table, db_field, - value.first.to_i, - value.first.to_i)
Chris@0 622 when ">t+"
Chris@0 623 sql = date_range_clause(db_table, db_field, value.first.to_i, nil)
Chris@0 624 when "<t+"
Chris@0 625 sql = date_range_clause(db_table, db_field, 0, value.first.to_i)
Chris@0 626 when "t+"
Chris@0 627 sql = date_range_clause(db_table, db_field, value.first.to_i, value.first.to_i)
Chris@0 628 when "t"
Chris@0 629 sql = date_range_clause(db_table, db_field, 0, 0)
Chris@0 630 when "w"
Chris@441 631 first_day_of_week = l(:general_first_day_of_week).to_i
Chris@441 632 day_of_week = Date.today.cwday
Chris@441 633 days_ago = (day_of_week >= first_day_of_week ? day_of_week - first_day_of_week : day_of_week + 7 - first_day_of_week)
Chris@441 634 sql = date_range_clause(db_table, db_field, - days_ago, - days_ago + 6)
Chris@0 635 when "~"
Chris@0 636 sql = "LOWER(#{db_table}.#{db_field}) LIKE '%#{connection.quote_string(value.first.to_s.downcase)}%'"
Chris@0 637 when "!~"
Chris@0 638 sql = "LOWER(#{db_table}.#{db_field}) NOT LIKE '%#{connection.quote_string(value.first.to_s.downcase)}%'"
Chris@0 639 end
Chris@441 640
Chris@0 641 return sql
Chris@0 642 end
Chris@441 643
Chris@0 644 def add_custom_fields_filters(custom_fields)
Chris@0 645 @available_filters ||= {}
Chris@441 646
Chris@0 647 custom_fields.select(&:is_filter?).each do |field|
Chris@0 648 case field.field_format
Chris@0 649 when "text"
Chris@0 650 options = { :type => :text, :order => 20 }
Chris@0 651 when "list"
Chris@0 652 options = { :type => :list_optional, :values => field.possible_values, :order => 20}
Chris@0 653 when "date"
Chris@0 654 options = { :type => :date, :order => 20 }
Chris@0 655 when "bool"
Chris@0 656 options = { :type => :list, :values => [[l(:general_text_yes), "1"], [l(:general_text_no), "0"]], :order => 20 }
Chris@441 657 when "user", "version"
Chris@441 658 next unless project
Chris@441 659 options = { :type => :list_optional, :values => field.possible_values_options(project), :order => 20}
Chris@0 660 else
Chris@0 661 options = { :type => :string, :order => 20 }
Chris@0 662 end
Chris@0 663 @available_filters["cf_#{field.id}"] = options.merge({ :name => field.name })
Chris@0 664 end
Chris@0 665 end
Chris@441 666
Chris@0 667 # Returns a SQL clause for a date or datetime field.
Chris@0 668 def date_range_clause(table, field, from, to)
Chris@0 669 s = []
Chris@0 670 if from
Chris@0 671 s << ("#{table}.#{field} > '%s'" % [connection.quoted_date((Date.yesterday + from).to_time.end_of_day)])
Chris@0 672 end
Chris@0 673 if to
Chris@0 674 s << ("#{table}.#{field} <= '%s'" % [connection.quoted_date((Date.today + to).to_time.end_of_day)])
Chris@0 675 end
Chris@0 676 s.join(' AND ')
Chris@0 677 end
Chris@0 678 end