annotate .svn/pristine/bd/bd20515ba5f4454bba8c775f551e735dca61a27d.svn-base @ 1519:afce8026aaeb redmine-2.4-integration

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