To check out this repository please hg clone the following URL, or open the URL using EasyMercurial or your preferred Mercurial client.

Statistics Download as Zip
| Branch: | Tag: | Revision:

root / app / models / query.rb @ 1297:0a574315af3e

History | View | Annotate | Download (41.8 KB)

1
# Redmine - project management software
2
# Copyright (C) 2006-2012  Jean-Philippe Lang
3
#
4
# This program is free software; you can redistribute it and/or
5
# modify it under the terms of the GNU General Public License
6
# as published by the Free Software Foundation; either version 2
7
# of the License, or (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
#
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
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17

    
18
class QueryColumn
19
  attr_accessor :name, :sortable, :groupable, :default_order
20
  include Redmine::I18n
21

    
22
  def initialize(name, options={})
23
    self.name = name
24
    self.sortable = options[:sortable]
25
    self.groupable = options[:groupable] || false
26
    if groupable == true
27
      self.groupable = name.to_s
28
    end
29
    self.default_order = options[:default_order]
30
    @inline = options.key?(:inline) ? options[:inline] : true
31
    @caption_key = options[:caption] || "field_#{name}"
32
  end
33

    
34
  def caption
35
    l(@caption_key)
36
  end
37

    
38
  # Returns true if the column is sortable, otherwise false
39
  def sortable?
40
    !@sortable.nil?
41
  end
42

    
43
  def sortable
44
    @sortable.is_a?(Proc) ? @sortable.call : @sortable
45
  end
46

    
47
  def inline?
48
    @inline
49
  end
50

    
51
  def value(issue)
52
    issue.send name
53
  end
54

    
55
  def css_classes
56
    name
57
  end
58
end
59

    
60
class QueryCustomFieldColumn < QueryColumn
61

    
62
  def initialize(custom_field)
63
    self.name = "cf_#{custom_field.id}".to_sym
64
    self.sortable = custom_field.order_statement || false
65
    self.groupable = custom_field.group_statement || false
66
    @inline = true
67
    @cf = custom_field
68
  end
69

    
70
  def caption
71
    @cf.name
72
  end
73

    
74
  def custom_field
75
    @cf
76
  end
77

    
78
  def value(issue)
79
    cv = issue.custom_values.select {|v| v.custom_field_id == @cf.id}.collect {|v| @cf.cast_value(v.value)}
80
    cv.size > 1 ? cv.sort {|a,b| a.to_s <=> b.to_s} : cv.first
81
  end
82

    
83
  def css_classes
84
    @css_classes ||= "#{name} #{@cf.field_format}"
85
  end
86
end
87

    
88
class Query < ActiveRecord::Base
89
  class StatementInvalid < ::ActiveRecord::StatementInvalid
90
  end
91

    
92
  belongs_to :project
93
  belongs_to :user
94
  serialize :filters
95
  serialize :column_names
96
  serialize :sort_criteria, Array
97

    
98
  attr_protected :project_id, :user_id
99

    
100
  validates_presence_of :name
101
  validates_length_of :name, :maximum => 255
102
  validate :validate_query_filters
103

    
104
  @@operators = { "="   => :label_equals,
105
                  "!"   => :label_not_equals,
106
                  "o"   => :label_open_issues,
107
                  "c"   => :label_closed_issues,
108
                  "!*"  => :label_none,
109
                  "*"   => :label_any,
110
                  ">="  => :label_greater_or_equal,
111
                  "<="  => :label_less_or_equal,
112
                  "><"  => :label_between,
113
                  "<t+" => :label_in_less_than,
114
                  ">t+" => :label_in_more_than,
115
                  "><t+"=> :label_in_the_next_days,
116
                  "t+"  => :label_in,
117
                  "t"   => :label_today,
118
                  "w"   => :label_this_week,
119
                  ">t-" => :label_less_than_ago,
120
                  "<t-" => :label_more_than_ago,
121
                  "><t-"=> :label_in_the_past_days,
122
                  "t-"  => :label_ago,
123
                  "~"   => :label_contains,
124
                  "!~"  => :label_not_contains,
125
                  "=p"  => :label_any_issues_in_project,
126
                  "=!p" => :label_any_issues_not_in_project,
127
                  "!p"  => :label_no_issues_in_project}
128

    
129
  cattr_reader :operators
130

    
131
  @@operators_by_filter_type = { :list => [ "=", "!" ],
132
                                 :list_status => [ "o", "=", "!", "c", "*" ],
133
                                 :list_optional => [ "=", "!", "!*", "*" ],
134
                                 :list_subprojects => [ "*", "!*", "=" ],
135
                                 :date => [ "=", ">=", "<=", "><", "<t+", ">t+", "><t+", "t+", "t", "w", ">t-", "<t-", "><t-", "t-", "!*", "*" ],
136
                                 :date_past => [ "=", ">=", "<=", "><", ">t-", "<t-", "><t-", "t-", "t", "w", "!*", "*" ],
137
                                 :string => [ "=", "~", "!", "!~", "!*", "*" ],
138
                                 :text => [  "~", "!~", "!*", "*" ],
139
                                 :integer => [ "=", ">=", "<=", "><", "!*", "*" ],
140
                                 :float => [ "=", ">=", "<=", "><", "!*", "*" ],
141
                                 :relation => ["=", "=p", "=!p", "!p", "!*", "*"]}
142

    
143
  cattr_reader :operators_by_filter_type
144

    
145
  @@available_columns = [
146
    QueryColumn.new(:project, :sortable => "#{Project.table_name}.name", :groupable => true),
147
    QueryColumn.new(:tracker, :sortable => "#{Tracker.table_name}.position", :groupable => true),
148
    QueryColumn.new(:parent, :sortable => ["#{Issue.table_name}.root_id", "#{Issue.table_name}.lft ASC"], :default_order => 'desc', :caption => :field_parent_issue),
149
    QueryColumn.new(:status, :sortable => "#{IssueStatus.table_name}.position", :groupable => true),
150
    QueryColumn.new(:priority, :sortable => "#{IssuePriority.table_name}.position", :default_order => 'desc', :groupable => true),
151
    QueryColumn.new(:subject, :sortable => "#{Issue.table_name}.subject"),
152
    QueryColumn.new(:author, :sortable => lambda {User.fields_for_order_statement("authors")}, :groupable => true),
153
    QueryColumn.new(:assigned_to, :sortable => lambda {User.fields_for_order_statement}, :groupable => true),
154
    QueryColumn.new(:updated_on, :sortable => "#{Issue.table_name}.updated_on", :default_order => 'desc'),
155
    QueryColumn.new(:category, :sortable => "#{IssueCategory.table_name}.name", :groupable => true),
156
    QueryColumn.new(:fixed_version, :sortable => lambda {Version.fields_for_order_statement}, :groupable => true),
157
    QueryColumn.new(:start_date, :sortable => "#{Issue.table_name}.start_date"),
158
    QueryColumn.new(:due_date, :sortable => "#{Issue.table_name}.due_date"),
159
    QueryColumn.new(:estimated_hours, :sortable => "#{Issue.table_name}.estimated_hours"),
160
    QueryColumn.new(:done_ratio, :sortable => "#{Issue.table_name}.done_ratio", :groupable => true),
161
    QueryColumn.new(:created_on, :sortable => "#{Issue.table_name}.created_on", :default_order => 'desc'),
162
    QueryColumn.new(:relations, :caption => :label_related_issues),
163
    QueryColumn.new(:description, :inline => false)
164
  ]
165
  cattr_reader :available_columns
166

    
167
  scope :visible, lambda {|*args|
168
    user = args.shift || User.current
169
    base = Project.allowed_to_condition(user, :view_issues, *args)
170
    user_id = user.logged? ? user.id : 0
171
    {
172
      :conditions => ["(#{table_name}.project_id IS NULL OR (#{base})) AND (#{table_name}.is_public = ? OR #{table_name}.user_id = ?)", true, user_id],
173
      :include => :project
174
    }
175
  }
176

    
177
  def initialize(attributes=nil, *args)
178
    super attributes
179
    self.filters ||= { 'status_id' => {:operator => "o", :values => [""]} }
180
    @is_for_all = project.nil?
181
  end
182

    
183
  def validate_query_filters
184
    filters.each_key do |field|
185
      if values_for(field)
186
        case type_for(field)
187
        when :integer
188
          add_filter_error(field, :invalid) if values_for(field).detect {|v| v.present? && !v.match(/^[+-]?\d+$/) }
189
        when :float
190
          add_filter_error(field, :invalid) if values_for(field).detect {|v| v.present? && !v.match(/^[+-]?\d+(\.\d*)?$/) }
191
        when :date, :date_past
192
          case operator_for(field)
193
          when "=", ">=", "<=", "><"
194
            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?) }
195
          when ">t-", "<t-", "t-", ">t+", "<t+", "t+", "><t+", "><t-"
196
            add_filter_error(field, :invalid) if values_for(field).detect {|v| v.present? && !v.match(/^\d+$/) }
197
          end
198
        end
199
      end
200

    
201
      add_filter_error(field, :blank) unless
202
          # filter requires one or more values
203
          (values_for(field) and !values_for(field).first.blank?) or
204
          # filter doesn't require any value
205
          ["o", "c", "!*", "*", "t", "w"].include? operator_for(field)
206
    end if filters
207
  end
208

    
209
  def add_filter_error(field, message)
210
    m = label_for(field) + " " + l(message, :scope => 'activerecord.errors.messages')
211
    errors.add(:base, m)
212
  end
213

    
214
  # Returns true if the query is visible to +user+ or the current user.
215
  def visible?(user=User.current)
216
    (project.nil? || user.allowed_to?(:view_issues, project)) && (self.is_public? || self.user_id == user.id)
217
  end
218

    
219
  def editable_by?(user)
220
    return false unless user
221
    # Admin can edit them all and regular users can edit their private queries
222
    return true if user.admin? || (!is_public && self.user_id == user.id)
223
    # Members can not edit public queries that are for all project (only admin is allowed to)
224
    is_public && !@is_for_all && user.allowed_to?(:manage_public_queries, project)
225
  end
226

    
227
  def trackers
228
    @trackers ||= project.nil? ? Tracker.find(:all, :order => 'position') : project.rolled_up_trackers
229
  end
230

    
231
  # Returns a hash of localized labels for all filter operators
232
  def self.operators_labels
233
    operators.inject({}) {|h, operator| h[operator.first] = l(operator.last); h}
234
  end
235

    
236
  def available_filters
237
    return @available_filters if @available_filters
238
    @available_filters = {
239
      "status_id" => {
240
        :type => :list_status, :order => 0,
241
        :values => IssueStatus.find(:all, :order => 'position').collect{|s| [s.name, s.id.to_s] }
242
       },
243
      "tracker_id" => {
244
        :type => :list, :order => 2, :values => trackers.collect{|s| [s.name, s.id.to_s] }
245
       },
246
      "priority_id" => {
247
        :type => :list, :order => 3, :values => IssuePriority.all.collect{|s| [s.name, s.id.to_s] }
248
       },
249
      "subject" => { :type => :text, :order => 8 },
250
      "created_on" => { :type => :date_past, :order => 9 },
251
      "updated_on" => { :type => :date_past, :order => 10 },
252
      "start_date" => { :type => :date, :order => 11 },
253
      "due_date" => { :type => :date, :order => 12 },
254
      "estimated_hours" => { :type => :float, :order => 13 },
255
      "done_ratio" =>  { :type => :integer, :order => 14 }
256
    }
257
    IssueRelation::TYPES.each do |relation_type, options|
258
      @available_filters[relation_type] = {
259
        :type => :relation, :order => @available_filters.size + 100,
260
        :label => options[:name]
261
      }
262
    end
263
    principals = []
264
    if project
265
      principals += project.principals.sort
266
      unless project.leaf?
267
        subprojects = project.descendants.visible.all
268
        if subprojects.any?
269
          @available_filters["subproject_id"] = {
270
            :type => :list_subprojects, :order => 13,
271
            :values => subprojects.collect{|s| [s.name, s.id.to_s] }
272
          }
273
          principals += Principal.member_of(subprojects)
274
        end
275
      end
276
    else
277
      if all_projects.any?
278
        # members of visible projects
279
        principals += Principal.member_of(all_projects)
280
        # project filter
281
        project_values = []
282
        if User.current.logged? && User.current.memberships.any?
283
          project_values << ["<< #{l(:label_my_projects).downcase} >>", "mine"]
284
        end
285
        project_values += all_projects_values
286
        @available_filters["project_id"] = {
287
          :type => :list, :order => 1, :values => project_values
288
        } unless project_values.empty?
289
      end
290
    end
291
    principals.uniq!
292
    principals.sort!
293
    users = principals.select {|p| p.is_a?(User)}
294

    
295
    assigned_to_values = []
296
    assigned_to_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged?
297
    assigned_to_values += (Setting.issue_group_assignment? ?
298
                              principals : users).collect{|s| [s.name, s.id.to_s] }
299
    @available_filters["assigned_to_id"] = {
300
      :type => :list_optional, :order => 4, :values => assigned_to_values
301
    } unless assigned_to_values.empty?
302

    
303
    author_values = []
304
    author_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged?
305
    author_values += users.collect{|s| [s.name, s.id.to_s] }
306
    @available_filters["author_id"] = {
307
      :type => :list, :order => 5, :values => author_values
308
    } unless author_values.empty?
309

    
310
    group_values = Group.all.collect {|g| [g.name, g.id.to_s] }
311
    @available_filters["member_of_group"] = {
312
      :type => :list_optional, :order => 6, :values => group_values
313
    } unless group_values.empty?
314

    
315
    role_values = Role.givable.collect {|r| [r.name, r.id.to_s] }
316
    @available_filters["assigned_to_role"] = {
317
      :type => :list_optional, :order => 7, :values => role_values
318
    } unless role_values.empty?
319

    
320
    if User.current.logged?
321
      @available_filters["watcher_id"] = {
322
        :type => :list, :order => 15, :values => [["<< #{l(:label_me)} >>", "me"]]
323
      }
324
    end
325

    
326
    if project
327
      # project specific filters
328
      categories = project.issue_categories.all
329
      unless categories.empty?
330
        @available_filters["category_id"] = {
331
          :type => :list_optional, :order => 6,
332
          :values => categories.collect{|s| [s.name, s.id.to_s] }
333
        }
334
      end
335
      versions = project.shared_versions.all
336
      unless versions.empty?
337
        @available_filters["fixed_version_id"] = {
338
          :type => :list_optional, :order => 7,
339
          :values => versions.sort.collect{|s| ["#{s.project.name} - #{s.name}", s.id.to_s] }
340
        }
341
      end
342
      add_custom_fields_filters(project.all_issue_custom_fields)
343
    else
344
      # global filters for cross project issue list
345
      system_shared_versions = Version.visible.find_all_by_sharing('system')
346
      unless system_shared_versions.empty?
347
        @available_filters["fixed_version_id"] = {
348
          :type => :list_optional, :order => 7,
349
          :values => system_shared_versions.sort.collect{|s|
350
                                       ["#{s.project.name} - #{s.name}", s.id.to_s]
351
                                     }
352
        }
353
      end
354
      add_custom_fields_filters(
355
                   IssueCustomField.find(:all,
356
                                         :conditions => {
357
                                            :is_filter => true,
358
                                            :is_for_all => true
359
                                         }))
360
    end
361
    add_associations_custom_fields_filters :project, :author, :assigned_to, :fixed_version
362
    if User.current.allowed_to?(:set_issues_private, nil, :global => true) ||
363
      User.current.allowed_to?(:set_own_issues_private, nil, :global => true)
364
      @available_filters["is_private"] = {
365
        :type => :list, :order => 16,
366
        :values => [[l(:general_text_yes), "1"], [l(:general_text_no), "0"]]
367
      }
368
    end
369
    Tracker.disabled_core_fields(trackers).each {|field|
370
      @available_filters.delete field
371
    }
372
    @available_filters.each do |field, options|
373
      options[:name] ||= l(options[:label] || "field_#{field}".gsub(/_id$/, ''))
374
    end
375
    @available_filters
376
  end
377

    
378
  # Returns a representation of the available filters for JSON serialization
379
  def available_filters_as_json
380
    json = {}
381
    available_filters.each do |field, options|
382
      json[field] = options.slice(:type, :name, :values).stringify_keys
383
    end
384
    json
385
  end
386

    
387
  def all_projects
388
    @all_projects ||= Project.visible.all
389
  end
390

    
391
  def all_projects_values
392
    return @all_projects_values if @all_projects_values
393

    
394
    values = []
395
    Project.project_tree(all_projects) do |p, level|
396
      prefix = (level > 0 ? ('--' * level + ' ') : '')
397
      values << ["#{prefix}#{p.name}", p.id.to_s]
398
    end
399
    @all_projects_values = values
400
  end
401

    
402
  def add_filter(field, operator, values)
403
    # values must be an array
404
    return unless values.nil? || values.is_a?(Array)
405
    # check if field is defined as an available filter
406
    if available_filters.has_key? field
407
      filter_options = available_filters[field]
408
      # check if operator is allowed for that filter
409
      #if @@operators_by_filter_type[filter_options[:type]].include? operator
410
      #  allowed_values = values & ([""] + (filter_options[:values] || []).collect {|val| val[1]})
411
      #  filters[field] = {:operator => operator, :values => allowed_values } if (allowed_values.first and !allowed_values.first.empty?) or ["o", "c", "!*", "*", "t"].include? operator
412
      #end
413
      filters[field] = {:operator => operator, :values => (values || [''])}
414
    end
415
  end
416

    
417
  def add_short_filter(field, expression)
418
    return unless expression && available_filters.has_key?(field)
419
    field_type = available_filters[field][:type]
420
    @@operators_by_filter_type[field_type].sort.reverse.detect do |operator|
421
      next unless expression =~ /^#{Regexp.escape(operator)}(.*)$/
422
      add_filter field, operator, $1.present? ? $1.split('|') : ['']
423
    end || add_filter(field, '=', expression.split('|'))
424
  end
425

    
426
  # Add multiple filters using +add_filter+
427
  def add_filters(fields, operators, values)
428
    if fields.is_a?(Array) && operators.is_a?(Hash) && (values.nil? || values.is_a?(Hash))
429
      fields.each do |field|
430
        add_filter(field, operators[field], values && values[field])
431
      end
432
    end
433
  end
434

    
435
  def has_filter?(field)
436
    filters and filters[field]
437
  end
438

    
439
  def type_for(field)
440
    available_filters[field][:type] if available_filters.has_key?(field)
441
  end
442

    
443
  def operator_for(field)
444
    has_filter?(field) ? filters[field][:operator] : nil
445
  end
446

    
447
  def values_for(field)
448
    has_filter?(field) ? filters[field][:values] : nil
449
  end
450

    
451
  def value_for(field, index=0)
452
    (values_for(field) || [])[index]
453
  end
454

    
455
  def label_for(field)
456
    label = available_filters[field][:name] if available_filters.has_key?(field)
457
    label ||= l("field_#{field.to_s.gsub(/_id$/, '')}", :default => field)
458
  end
459

    
460
  def available_columns
461
    return @available_columns if @available_columns
462
    @available_columns = ::Query.available_columns.dup
463
    @available_columns += (project ?
464
                            project.all_issue_custom_fields :
465
                            IssueCustomField.find(:all)
466
                           ).collect {|cf| QueryCustomFieldColumn.new(cf) }
467

    
468
    if User.current.allowed_to?(:view_time_entries, project, :global => true)
469
      index = nil
470
      @available_columns.each_with_index {|column, i| index = i if column.name == :estimated_hours}
471
      index = (index ? index + 1 : -1)
472
      # insert the column after estimated_hours or at the end
473
      @available_columns.insert index, QueryColumn.new(:spent_hours,
474
        :sortable => "(SELECT COALESCE(SUM(hours), 0) FROM #{TimeEntry.table_name} WHERE #{TimeEntry.table_name}.issue_id = #{Issue.table_name}.id)",
475
        :default_order => 'desc',
476
        :caption => :label_spent_time
477
      )
478
    end
479

    
480
    if User.current.allowed_to?(:set_issues_private, nil, :global => true) ||
481
      User.current.allowed_to?(:set_own_issues_private, nil, :global => true)
482
      @available_columns << QueryColumn.new(:is_private, :sortable => "#{Issue.table_name}.is_private")
483
    end
484

    
485
    disabled_fields = Tracker.disabled_core_fields(trackers).map {|field| field.sub(/_id$/, '')}
486
    @available_columns.reject! {|column|
487
      disabled_fields.include?(column.name.to_s)
488
    }
489

    
490
    @available_columns
491
  end
492

    
493
  def self.available_columns=(v)
494
    self.available_columns = (v)
495
  end
496

    
497
  def self.add_available_column(column)
498
    self.available_columns << (column) if column.is_a?(QueryColumn)
499
  end
500

    
501
  # Returns an array of columns that can be used to group the results
502
  def groupable_columns
503
    available_columns.select {|c| c.groupable}
504
  end
505

    
506
  # Returns a Hash of columns and the key for sorting
507
  def sortable_columns
508
    {'id' => "#{Issue.table_name}.id"}.merge(available_columns.inject({}) {|h, column|
509
                                               h[column.name.to_s] = column.sortable
510
                                               h
511
                                             })
512
  end
513

    
514
  def columns
515
    # preserve the column_names order
516
    (has_default_columns? ? default_columns_names : column_names).collect do |name|
517
       available_columns.find { |col| col.name == name }
518
    end.compact
519
  end
520

    
521
  def inline_columns
522
    columns.select(&:inline?)
523
  end
524

    
525
  def block_columns
526
    columns.reject(&:inline?)
527
  end
528

    
529
  def available_inline_columns
530
    available_columns.select(&:inline?)
531
  end
532

    
533
  def available_block_columns
534
    available_columns.reject(&:inline?)
535
  end
536

    
537
  def default_columns_names
538
    @default_columns_names ||= begin
539
      default_columns = Setting.issue_list_default_columns.map(&:to_sym)
540

    
541
      project.present? ? default_columns : [:project] | default_columns
542
    end
543
  end
544

    
545
  def column_names=(names)
546
    if names
547
      names = names.select {|n| n.is_a?(Symbol) || !n.blank? }
548
      names = names.collect {|n| n.is_a?(Symbol) ? n : n.to_sym }
549
      # Set column_names to nil if default columns
550
      if names == default_columns_names
551
        names = nil
552
      end
553
    end
554
    write_attribute(:column_names, names)
555
  end
556

    
557
  def has_column?(column)
558
    column_names && column_names.include?(column.is_a?(QueryColumn) ? column.name : column)
559
  end
560

    
561
  def has_default_columns?
562
    column_names.nil? || column_names.empty?
563
  end
564

    
565
  def sort_criteria=(arg)
566
    c = []
567
    if arg.is_a?(Hash)
568
      arg = arg.keys.sort.collect {|k| arg[k]}
569
    end
570
    c = arg.select {|k,o| !k.to_s.blank?}.slice(0,3).collect {|k,o| [k.to_s, (o == 'desc' || o == false) ? 'desc' : 'asc']}
571
    write_attribute(:sort_criteria, c)
572
  end
573

    
574
  def sort_criteria
575
    read_attribute(:sort_criteria) || []
576
  end
577

    
578
  def sort_criteria_key(arg)
579
    sort_criteria && sort_criteria[arg] && sort_criteria[arg].first
580
  end
581

    
582
  def sort_criteria_order(arg)
583
    sort_criteria && sort_criteria[arg] && sort_criteria[arg].last
584
  end
585

    
586
  def sort_criteria_order_for(key)
587
    sort_criteria.detect {|k, order| key.to_s == k}.try(:last)
588
  end
589

    
590
  # Returns the SQL sort order that should be prepended for grouping
591
  def group_by_sort_order
592
    if grouped? && (column = group_by_column)
593
      order = sort_criteria_order_for(column.name) || column.default_order
594
      column.sortable.is_a?(Array) ?
595
        column.sortable.collect {|s| "#{s} #{order}"}.join(',') :
596
        "#{column.sortable} #{order}"
597
    end
598
  end
599

    
600
  # Returns true if the query is a grouped query
601
  def grouped?
602
    !group_by_column.nil?
603
  end
604

    
605
  def group_by_column
606
    groupable_columns.detect {|c| c.groupable && c.name.to_s == group_by}
607
  end
608

    
609
  def group_by_statement
610
    group_by_column.try(:groupable)
611
  end
612

    
613
  def project_statement
614
    project_clauses = []
615
    if project && !project.descendants.active.empty?
616
      ids = [project.id]
617
      if has_filter?("subproject_id")
618
        case operator_for("subproject_id")
619
        when '='
620
          # include the selected subprojects
621
          ids += values_for("subproject_id").each(&:to_i)
622
        when '!*'
623
          # main project only
624
        else
625
          # all subprojects
626
          ids += project.descendants.collect(&:id)
627
        end
628
      elsif Setting.display_subprojects_issues?
629
        ids += project.descendants.collect(&:id)
630
      end
631
      project_clauses << "#{Project.table_name}.id IN (%s)" % ids.join(',')
632
    elsif project
633
      project_clauses << "#{Project.table_name}.id = %d" % project.id
634
    end
635
    project_clauses.any? ? project_clauses.join(' AND ') : nil
636
  end
637

    
638
  def statement
639
    # filters clauses
640
    filters_clauses = []
641
    filters.each_key do |field|
642
      next if field == "subproject_id"
643
      v = values_for(field).clone
644
      next unless v and !v.empty?
645
      operator = operator_for(field)
646

    
647
      # "me" value subsitution
648
      if %w(assigned_to_id author_id watcher_id).include?(field)
649
        if v.delete("me")
650
          if User.current.logged?
651
            v.push(User.current.id.to_s)
652
            v += User.current.group_ids.map(&:to_s) if field == 'assigned_to_id'
653
          else
654
            v.push("0")
655
          end
656
        end
657
      end
658

    
659
      if field == 'project_id'
660
        if v.delete('mine')
661
          v += User.current.memberships.map(&:project_id).map(&:to_s)
662
        end
663
      end
664

    
665
      if field =~ /cf_(\d+)$/
666
        # custom field
667
        filters_clauses << sql_for_custom_field(field, operator, v, $1)
668
      elsif respond_to?("sql_for_#{field}_field")
669
        # specific statement
670
        filters_clauses << send("sql_for_#{field}_field", field, operator, v)
671
      else
672
        # regular field
673
        filters_clauses << '(' + sql_for_field(field, operator, v, Issue.table_name, field) + ')'
674
      end
675
    end if filters and valid?
676

    
677
    filters_clauses << project_statement
678
    filters_clauses.reject!(&:blank?)
679

    
680
    filters_clauses.any? ? filters_clauses.join(' AND ') : nil
681
  end
682

    
683
  # Returns the issue count
684
  def issue_count
685
    Issue.visible.count(:include => [:status, :project], :conditions => statement)
686
  rescue ::ActiveRecord::StatementInvalid => e
687
    raise StatementInvalid.new(e.message)
688
  end
689

    
690
  # Returns the issue count by group or nil if query is not grouped
691
  def issue_count_by_group
692
    r = nil
693
    if grouped?
694
      begin
695
        # Rails3 will raise an (unexpected) RecordNotFound if there's only a nil group value
696
        r = Issue.visible.count(:group => group_by_statement, :include => [:status, :project], :conditions => statement)
697
      rescue ActiveRecord::RecordNotFound
698
        r = {nil => issue_count}
699
      end
700
      c = group_by_column
701
      if c.is_a?(QueryCustomFieldColumn)
702
        r = r.keys.inject({}) {|h, k| h[c.custom_field.cast_value(k)] = r[k]; h}
703
      end
704
    end
705
    r
706
  rescue ::ActiveRecord::StatementInvalid => e
707
    raise StatementInvalid.new(e.message)
708
  end
709

    
710
  # Returns the issues
711
  # Valid options are :order, :offset, :limit, :include, :conditions
712
  def issues(options={})
713
    order_option = [group_by_sort_order, options[:order]].reject {|s| s.blank?}.join(',')
714
    order_option = nil if order_option.blank?
715

    
716
    issues = Issue.visible.scoped(:conditions => options[:conditions]).find :all, :include => ([:status, :project] + (options[:include] || [])).uniq,
717
                     :conditions => statement,
718
                     :order => order_option,
719
                     :joins => joins_for_order_statement(order_option),
720
                     :limit  => options[:limit],
721
                     :offset => options[:offset]
722

    
723
    if has_column?(:spent_hours)
724
      Issue.load_visible_spent_hours(issues)
725
    end
726
    if has_column?(:relations)
727
      Issue.load_visible_relations(issues)
728
    end
729
    issues
730
  rescue ::ActiveRecord::StatementInvalid => e
731
    raise StatementInvalid.new(e.message)
732
  end
733

    
734
  # Returns the issues ids
735
  def issue_ids(options={})
736
    order_option = [group_by_sort_order, options[:order]].reject {|s| s.blank?}.join(',')
737
    order_option = nil if order_option.blank?
738

    
739
    Issue.visible.scoped(:conditions => options[:conditions]).scoped(:include => ([:status, :project] + (options[:include] || [])).uniq,
740
                     :conditions => statement,
741
                     :order => order_option,
742
                     :joins => joins_for_order_statement(order_option),
743
                     :limit  => options[:limit],
744
                     :offset => options[:offset]).find_ids
745
  rescue ::ActiveRecord::StatementInvalid => e
746
    raise StatementInvalid.new(e.message)
747
  end
748

    
749
  # Returns the journals
750
  # Valid options are :order, :offset, :limit
751
  def journals(options={})
752
    Journal.visible.find :all, :include => [:details, :user, {:issue => [:project, :author, :tracker, :status]}],
753
                       :conditions => statement,
754
                       :order => options[:order],
755
                       :limit => options[:limit],
756
                       :offset => options[:offset]
757
  rescue ::ActiveRecord::StatementInvalid => e
758
    raise StatementInvalid.new(e.message)
759
  end
760

    
761
  # Returns the versions
762
  # Valid options are :conditions
763
  def versions(options={})
764
    Version.visible.scoped(:conditions => options[:conditions]).find :all, :include => :project, :conditions => project_statement
765
  rescue ::ActiveRecord::StatementInvalid => e
766
    raise StatementInvalid.new(e.message)
767
  end
768

    
769
  def sql_for_watcher_id_field(field, operator, value)
770
    db_table = Watcher.table_name
771
    "#{Issue.table_name}.id #{ operator == '=' ? 'IN' : 'NOT IN' } (SELECT #{db_table}.watchable_id FROM #{db_table} WHERE #{db_table}.watchable_type='Issue' AND " +
772
      sql_for_field(field, '=', value, db_table, 'user_id') + ')'
773
  end
774

    
775
  def sql_for_member_of_group_field(field, operator, value)
776
    if operator == '*' # Any group
777
      groups = Group.all
778
      operator = '=' # Override the operator since we want to find by assigned_to
779
    elsif operator == "!*"
780
      groups = Group.all
781
      operator = '!' # Override the operator since we want to find by assigned_to
782
    else
783
      groups = Group.find_all_by_id(value)
784
    end
785
    groups ||= []
786

    
787
    members_of_groups = groups.inject([]) {|user_ids, group|
788
      if group && group.user_ids.present?
789
        user_ids << group.user_ids
790
      end
791
      user_ids.flatten.uniq.compact
792
    }.sort.collect(&:to_s)
793

    
794
    '(' + sql_for_field("assigned_to_id", operator, members_of_groups, Issue.table_name, "assigned_to_id", false) + ')'
795
  end
796

    
797
  def sql_for_assigned_to_role_field(field, operator, value)
798
    case operator
799
    when "*", "!*" # Member / Not member
800
      sw = operator == "!*" ? 'NOT' : ''
801
      nl = operator == "!*" ? "#{Issue.table_name}.assigned_to_id IS NULL OR" : ''
802
      "(#{nl} #{Issue.table_name}.assigned_to_id #{sw} IN (SELECT DISTINCT #{Member.table_name}.user_id FROM #{Member.table_name}" +
803
        " WHERE #{Member.table_name}.project_id = #{Issue.table_name}.project_id))"
804
    when "=", "!"
805
      role_cond = value.any? ?
806
        "#{MemberRole.table_name}.role_id IN (" + value.collect{|val| "'#{connection.quote_string(val)}'"}.join(",") + ")" :
807
        "1=0"
808

    
809
      sw = operator == "!" ? 'NOT' : ''
810
      nl = operator == "!" ? "#{Issue.table_name}.assigned_to_id IS NULL OR" : ''
811
      "(#{nl} #{Issue.table_name}.assigned_to_id #{sw} IN (SELECT DISTINCT #{Member.table_name}.user_id FROM #{Member.table_name}, #{MemberRole.table_name}" +
812
        " WHERE #{Member.table_name}.project_id = #{Issue.table_name}.project_id AND #{Member.table_name}.id = #{MemberRole.table_name}.member_id AND #{role_cond}))"
813
    end
814
  end
815

    
816
  def sql_for_is_private_field(field, operator, value)
817
    op = (operator == "=" ? 'IN' : 'NOT IN')
818
    va = value.map {|v| v == '0' ? connection.quoted_false : connection.quoted_true}.uniq.join(',')
819

    
820
    "#{Issue.table_name}.is_private #{op} (#{va})"
821
  end
822

    
823
  def sql_for_relations(field, operator, value, options={})
824
    relation_options = IssueRelation::TYPES[field]
825
    return relation_options unless relation_options
826

    
827
    relation_type = field
828
    join_column, target_join_column = "issue_from_id", "issue_to_id"
829
    if relation_options[:reverse] || options[:reverse]
830
      relation_type = relation_options[:reverse] || relation_type
831
      join_column, target_join_column = target_join_column, join_column
832
    end
833

    
834
    sql = case operator
835
      when "*", "!*"
836
        op = (operator == "*" ? 'IN' : 'NOT IN')
837
        "#{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)}')"
838
      when "=", "!"
839
        op = (operator == "=" ? 'IN' : 'NOT IN')
840
        "#{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})"
841
      when "=p", "=!p", "!p"
842
        op = (operator == "!p" ? 'NOT IN' : 'IN')
843
        comp = (operator == "=!p" ? '<>' : '=')
844
        "#{Issue.table_name}.id #{op} (SELECT DISTINCT #{IssueRelation.table_name}.#{join_column} FROM #{IssueRelation.table_name}, #{Issue.table_name} relissues WHERE #{IssueRelation.table_name}.relation_type = '#{connection.quote_string(relation_type)}' AND #{IssueRelation.table_name}.#{target_join_column} = relissues.id AND relissues.project_id #{comp} #{value.first.to_i})"
845
      end
846

    
847
    if relation_options[:sym] == field && !options[:reverse]
848
      sqls = [sql, sql_for_relations(field, operator, value, :reverse => true)]
849
      sqls.join(["!", "!*", "!p"].include?(operator) ? " AND " : " OR ")
850
    else
851
      sql
852
    end
853
  end
854

    
855
  IssueRelation::TYPES.keys.each do |relation_type|
856
    alias_method "sql_for_#{relation_type}_field".to_sym, :sql_for_relations
857
  end
858

    
859
  private
860

    
861
  def sql_for_custom_field(field, operator, value, custom_field_id)
862
    db_table = CustomValue.table_name
863
    db_field = 'value'
864
    filter = @available_filters[field]
865
    return nil unless filter
866
    if filter[:format] == 'user'
867
      if value.delete('me')
868
        value.push User.current.id.to_s
869
      end
870
    end
871
    not_in = nil
872
    if operator == '!'
873
      # Makes ! operator work for custom fields with multiple values
874
      operator = '='
875
      not_in = 'NOT'
876
    end
877
    customized_key = "id"
878
    customized_class = Issue
879
    if field =~ /^(.+)\.cf_/
880
      assoc = $1
881
      customized_key = "#{assoc}_id"
882
      customized_class = Issue.reflect_on_association(assoc.to_sym).klass.base_class rescue nil
883
      raise "Unknown Issue association #{assoc}" unless customized_class
884
    end
885
    "#{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 " +
886
      sql_for_field(field, operator, value, db_table, db_field, true) + ')'
887
  end
888

    
889
  # Helper method to generate the WHERE sql for a +field+, +operator+ and a +value+
890
  def sql_for_field(field, operator, value, db_table, db_field, is_custom_filter=false)
891
    sql = ''
892
    case operator
893
    when "="
894
      if value.any?
895
        case type_for(field)
896
        when :date, :date_past
897
          sql = date_clause(db_table, db_field, (Date.parse(value.first) rescue nil), (Date.parse(value.first) rescue nil))
898
        when :integer
899
          if is_custom_filter
900
            sql = "(#{db_table}.#{db_field} <> '' AND CAST(#{db_table}.#{db_field} AS decimal(60,3)) = #{value.first.to_i})"
901
          else
902
            sql = "#{db_table}.#{db_field} = #{value.first.to_i}"
903
          end
904
        when :float
905
          if is_custom_filter
906
            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})"
907
          else
908
            sql = "#{db_table}.#{db_field} BETWEEN #{value.first.to_f - 1e-5} AND #{value.first.to_f + 1e-5}"
909
          end
910
        else
911
          sql = "#{db_table}.#{db_field} IN (" + value.collect{|val| "'#{connection.quote_string(val)}'"}.join(",") + ")"
912
        end
913
      else
914
        # IN an empty set
915
        sql = "1=0"
916
      end
917
    when "!"
918
      if value.any?
919
        sql = "(#{db_table}.#{db_field} IS NULL OR #{db_table}.#{db_field} NOT IN (" + value.collect{|val| "'#{connection.quote_string(val)}'"}.join(",") + "))"
920
      else
921
        # NOT IN an empty set
922
        sql = "1=1"
923
      end
924
    when "!*"
925
      sql = "#{db_table}.#{db_field} IS NULL"
926
      sql << " OR #{db_table}.#{db_field} = ''" if is_custom_filter
927
    when "*"
928
      sql = "#{db_table}.#{db_field} IS NOT NULL"
929
      sql << " AND #{db_table}.#{db_field} <> ''" if is_custom_filter
930
    when ">="
931
      if [:date, :date_past].include?(type_for(field))
932
        sql = date_clause(db_table, db_field, (Date.parse(value.first) rescue nil), nil)
933
      else
934
        if is_custom_filter
935
          sql = "(#{db_table}.#{db_field} <> '' AND CAST(#{db_table}.#{db_field} AS decimal(60,3)) >= #{value.first.to_f})"
936
        else
937
          sql = "#{db_table}.#{db_field} >= #{value.first.to_f}"
938
        end
939
      end
940
    when "<="
941
      if [:date, :date_past].include?(type_for(field))
942
        sql = date_clause(db_table, db_field, nil, (Date.parse(value.first) rescue nil))
943
      else
944
        if is_custom_filter
945
          sql = "(#{db_table}.#{db_field} <> '' AND CAST(#{db_table}.#{db_field} AS decimal(60,3)) <= #{value.first.to_f})"
946
        else
947
          sql = "#{db_table}.#{db_field} <= #{value.first.to_f}"
948
        end
949
      end
950
    when "><"
951
      if [:date, :date_past].include?(type_for(field))
952
        sql = date_clause(db_table, db_field, (Date.parse(value[0]) rescue nil), (Date.parse(value[1]) rescue nil))
953
      else
954
        if is_custom_filter
955
          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})"
956
        else
957
          sql = "#{db_table}.#{db_field} BETWEEN #{value[0].to_f} AND #{value[1].to_f}"
958
        end
959
      end
960
    when "o"
961
      sql = "#{Issue.table_name}.status_id IN (SELECT id FROM #{IssueStatus.table_name} WHERE is_closed=#{connection.quoted_false})" if field == "status_id"
962
    when "c"
963
      sql = "#{Issue.table_name}.status_id IN (SELECT id FROM #{IssueStatus.table_name} WHERE is_closed=#{connection.quoted_true})" if field == "status_id"
964
    when "><t-"
965
      # between today - n days and today
966
      sql = relative_date_clause(db_table, db_field, - value.first.to_i, 0)
967
    when ">t-"
968
      # >= today - n days
969
      sql = relative_date_clause(db_table, db_field, - value.first.to_i, nil)
970
    when "<t-"
971
      # <= today - n days
972
      sql = relative_date_clause(db_table, db_field, nil, - value.first.to_i)
973
    when "t-"
974
      # = n days in past
975
      sql = relative_date_clause(db_table, db_field, - value.first.to_i, - value.first.to_i)
976
    when "><t+"
977
      # between today and today + n days
978
      sql = relative_date_clause(db_table, db_field, 0, value.first.to_i)
979
    when ">t+"
980
      # >= today + n days
981
      sql = relative_date_clause(db_table, db_field, value.first.to_i, nil)
982
    when "<t+"
983
      # <= today + n days
984
      sql = relative_date_clause(db_table, db_field, nil, value.first.to_i)
985
    when "t+"
986
      # = today + n days
987
      sql = relative_date_clause(db_table, db_field, value.first.to_i, value.first.to_i)
988
    when "t"
989
      # = today
990
      sql = relative_date_clause(db_table, db_field, 0, 0)
991
    when "w"
992
      # = this week
993
      first_day_of_week = l(:general_first_day_of_week).to_i
994
      day_of_week = Date.today.cwday
995
      days_ago = (day_of_week >= first_day_of_week ? day_of_week - first_day_of_week : day_of_week + 7 - first_day_of_week)
996
      sql = relative_date_clause(db_table, db_field, - days_ago, - days_ago + 6)
997
    when "~"
998
      sql = "LOWER(#{db_table}.#{db_field}) LIKE '%#{connection.quote_string(value.first.to_s.downcase)}%'"
999
    when "!~"
1000
      sql = "LOWER(#{db_table}.#{db_field}) NOT LIKE '%#{connection.quote_string(value.first.to_s.downcase)}%'"
1001
    else
1002
      raise "Unknown query operator #{operator}"
1003
    end
1004

    
1005
    return sql
1006
  end
1007

    
1008
  def add_custom_fields_filters(custom_fields, assoc=nil)
1009
    return unless custom_fields.present?
1010
    @available_filters ||= {}
1011

    
1012
    custom_fields.select(&:is_filter?).each do |field|
1013
      case field.field_format
1014
      when "text"
1015
        options = { :type => :text, :order => 20 }
1016
      when "list"
1017
        options = { :type => :list_optional, :values => field.possible_values, :order => 20}
1018
      when "date"
1019
        options = { :type => :date, :order => 20 }
1020
      when "bool"
1021
        options = { :type => :list, :values => [[l(:general_text_yes), "1"], [l(:general_text_no), "0"]], :order => 20 }
1022
      when "int"
1023
        options = { :type => :integer, :order => 20 }
1024
      when "float"
1025
        options = { :type => :float, :order => 20 }
1026
      when "user", "version"
1027
        next unless project
1028
        values = field.possible_values_options(project)
1029
        if User.current.logged? && field.field_format == 'user'
1030
          values.unshift ["<< #{l(:label_me)} >>", "me"]
1031
        end
1032
        options = { :type => :list_optional, :values => values, :order => 20}
1033
      else
1034
        options = { :type => :string, :order => 20 }
1035
      end
1036
      filter_id = "cf_#{field.id}"
1037
      filter_name = field.name
1038
      if assoc.present?
1039
        filter_id = "#{assoc}.#{filter_id}"
1040
        filter_name = l("label_attribute_of_#{assoc}", :name => filter_name)
1041
      end
1042
      @available_filters[filter_id] = options.merge({
1043
               :name => filter_name,
1044
               :format => field.field_format,
1045
               :field => field
1046
             })
1047
    end
1048
  end
1049

    
1050
  def add_associations_custom_fields_filters(*associations)
1051
    fields_by_class = CustomField.where(:is_filter => true).group_by(&:class)
1052
    associations.each do |assoc|
1053
      association_klass = Issue.reflect_on_association(assoc).klass
1054
      fields_by_class.each do |field_class, fields|
1055
        if field_class.customized_class <= association_klass
1056
          add_custom_fields_filters(fields, assoc)
1057
        end
1058
      end
1059
    end
1060
  end
1061

    
1062
  # Returns a SQL clause for a date or datetime field.
1063
  def date_clause(table, field, from, to)
1064
    s = []
1065
    if from
1066
      from_yesterday = from - 1
1067
      from_yesterday_time = Time.local(from_yesterday.year, from_yesterday.month, from_yesterday.day)
1068
      if self.class.default_timezone == :utc
1069
        from_yesterday_time = from_yesterday_time.utc
1070
      end
1071
      s << ("#{table}.#{field} > '%s'" % [connection.quoted_date(from_yesterday_time.end_of_day)])
1072
    end
1073
    if to
1074
      to_time = Time.local(to.year, to.month, to.day)
1075
      if self.class.default_timezone == :utc
1076
        to_time = to_time.utc
1077
      end
1078
      s << ("#{table}.#{field} <= '%s'" % [connection.quoted_date(to_time.end_of_day)])
1079
    end
1080
    s.join(' AND ')
1081
  end
1082

    
1083
  # Returns a SQL clause for a date or datetime field using relative dates.
1084
  def relative_date_clause(table, field, days_from, days_to)
1085
    date_clause(table, field, (days_from ? Date.today + days_from : nil), (days_to ? Date.today + days_to : nil))
1086
  end
1087

    
1088
  # Additional joins required for the given sort options
1089
  def joins_for_order_statement(order_options)
1090
    joins = []
1091

    
1092
    if order_options
1093
      if order_options.include?('authors')
1094
        joins << "LEFT OUTER JOIN #{User.table_name} authors ON authors.id = #{Issue.table_name}.author_id"
1095
      end
1096
      order_options.scan(/cf_\d+/).uniq.each do |name|
1097
        column = available_columns.detect {|c| c.name.to_s == name}
1098
        join = column && column.custom_field.join_for_order_statement
1099
        if join
1100
          joins << join
1101
        end
1102
      end
1103
    end
1104

    
1105
    joins.any? ? joins.join(' ') : nil
1106
  end
1107
end