Class: IssueQuery

Inherits:
Query
  • Object
show all
Defined in:
app/models/issue_query.rb

Overview

Redmine - project management software Copyright (C) 2006-2014 Jean-Philippe Lang

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

Constant Summary

Constants inherited from Query

Query::VISIBILITY_PRIVATE, Query::VISIBILITY_PUBLIC, Query::VISIBILITY_ROLES

Instance Method Summary collapse

Methods inherited from Query

add_available_column, #add_available_filter, #add_filter, #add_filter_error, #add_filters, #add_short_filter, #all_projects, #all_projects_values, #available_block_columns, #available_filters, #available_filters_as_json, #available_inline_columns, #block_columns, build_from_params, #column_names=, #columns, #delete_available_filter, #editable_by?, #group_by_column, #group_by_sort_order, #group_by_statement, #groupable_columns, #grouped?, #has_column?, #has_custom_field_column?, #has_default_columns?, #has_filter?, #inline_columns, #label_for, #operator_for, operators_labels, #project_statement, #queried_table_name, #sort_criteria, #sort_criteria=, #sort_criteria_key, #sort_criteria_order, #sort_criteria_order_for, #sortable_columns, #statement, #trackers, #type_for, #validate_query_filters, #value_for, #values_for

Constructor Details

#initialize(attributes = nil, *args) ⇒ IssueQuery

Returns a new instance of IssueQuery.


70
71
72
73
# File 'app/models/issue_query.rb', line 70

def initialize(attributes=nil, *args)
  super attributes
  self.filters ||= { 'status_id' => {:operator => "o", :values => [""]} }
end

Instance Method Details

#available_columnsObject


250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'app/models/issue_query.rb', line 250

def available_columns
  return @available_columns if @available_columns
  @available_columns = self.class.available_columns.dup
  @available_columns += (project ?
                          project.all_issue_custom_fields :
                          IssueCustomField
                         ).visible.collect {|cf| QueryCustomFieldColumn.new(cf) }

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

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

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

  @available_columns
end

#build_from_params(params) ⇒ Object


119
120
121
122
123
124
# File 'app/models/issue_query.rb', line 119

def build_from_params(params)
  super
  self.draw_relations = params[:draw_relations] || (params[:query] && params[:query][:draw_relations])
  self.draw_progress_line = params[:draw_progress_line] || (params[:query] && params[:query][:draw_progress_line])
  self
end

#default_columns_namesObject


283
284
285
286
287
288
289
# File 'app/models/issue_query.rb', line 283

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

    project.present? ? default_columns : [:project] | default_columns
  end
end

#draw_progress_lineObject


110
111
112
113
# File 'app/models/issue_query.rb', line 110

def draw_progress_line
  r = options[:draw_progress_line]
  r == '1'
end

#draw_progress_line=(arg) ⇒ Object


115
116
117
# File 'app/models/issue_query.rb', line 115

def draw_progress_line=(arg)
  options[:draw_progress_line] = (arg == '1' ? '1' : nil)
end

#draw_relationsObject


101
102
103
104
# File 'app/models/issue_query.rb', line 101

def draw_relations
  r = options[:draw_relations]
  r.nil? || r == '1'
end

#draw_relations=(arg) ⇒ Object


106
107
108
# File 'app/models/issue_query.rb', line 106

def draw_relations=(arg)
  options[:draw_relations] = (arg == '0' ? '0' : nil)
end

#initialize_available_filtersObject


126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'app/models/issue_query.rb', line 126

def initialize_available_filters
  principals = []
  subprojects = []
  versions = []
  categories = []
  issue_custom_fields = []

  if project
    principals += project.principals.visible
    unless project.leaf?
      subprojects = project.descendants.visible.to_a
      principals += Principal.member_of(subprojects).visible
    end
    versions = project.shared_versions.to_a
    categories = project.issue_categories.to_a
    issue_custom_fields = project.all_issue_custom_fields
  else
    if all_projects.any?
      principals += Principal.member_of(all_projects).visible
    end
    versions = Version.visible.where(:sharing => 'system').to_a
    issue_custom_fields = IssueCustomField.where(:is_for_all => true)
  end
  principals.uniq!
  principals.sort!
  principals.reject! {|p| p.is_a?(GroupBuiltin)}
  users = principals.select {|p| p.is_a?(User)}

  add_available_filter "status_id",
    :type => :list_status, :values => IssueStatus.sorted.collect{|s| [s.name, s.id.to_s] }

  if project.nil?
    project_values = []
    if User.current.logged? && User.current.memberships.any?
      project_values << ["<< #{l(:label_my_projects).downcase} >>", "mine"]
    end
    project_values += all_projects_values
    add_available_filter("project_id",
      :type => :list, :values => project_values
    ) unless project_values.empty?
  end

  add_available_filter "tracker_id",
    :type => :list, :values => trackers.collect{|s| [s.name, s.id.to_s] }
  add_available_filter "priority_id",
    :type => :list, :values => IssuePriority.all.collect{|s| [s.name, s.id.to_s] }

  author_values = []
  author_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged?
  author_values += users.collect{|s| [s.name, s.id.to_s] }
  add_available_filter("author_id",
    :type => :list, :values => author_values
  ) unless author_values.empty?

  assigned_to_values = []
  assigned_to_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged?
  assigned_to_values += (Setting.issue_group_assignment? ?
                            principals : users).collect{|s| [s.name, s.id.to_s] }
  add_available_filter("assigned_to_id",
    :type => :list_optional, :values => assigned_to_values
  ) unless assigned_to_values.empty?

  group_values = Group.givable.visible.collect {|g| [g.name, g.id.to_s] }
  add_available_filter("member_of_group",
    :type => :list_optional, :values => group_values
  ) unless group_values.empty?

  role_values = Role.givable.collect {|r| [r.name, r.id.to_s] }
  add_available_filter("assigned_to_role",
    :type => :list_optional, :values => role_values
  ) unless role_values.empty?

  if versions.any?
    add_available_filter "fixed_version_id",
      :type => :list_optional,
      :values => versions.sort.collect{|s| ["#{s.project.name} - #{s.name}", s.id.to_s] }
  end

  if categories.any?
    add_available_filter "category_id",
      :type => :list_optional,
      :values => categories.collect{|s| [s.name, s.id.to_s] }
  end

  add_available_filter "subject", :type => :text
  add_available_filter "created_on", :type => :date_past
  add_available_filter "updated_on", :type => :date_past
  add_available_filter "closed_on", :type => :date_past
  add_available_filter "start_date", :type => :date
  add_available_filter "due_date", :type => :date
  add_available_filter "estimated_hours", :type => :float
  add_available_filter "done_ratio", :type => :integer

  if User.current.allowed_to?(:set_issues_private, nil, :global => true) ||
    User.current.allowed_to?(:set_own_issues_private, nil, :global => true)
    add_available_filter "is_private",
      :type => :list,
      :values => [[l(:general_text_yes), "1"], [l(:general_text_no), "0"]]
  end

  if User.current.logged?
    add_available_filter "watcher_id",
      :type => :list, :values => [["<< #{l(:label_me)} >>", "me"]]
  end

  if subprojects.any?
    add_available_filter "subproject_id",
      :type => :list_subprojects,
      :values => subprojects.collect{|s| [s.name, s.id.to_s] }
  end

  add_custom_fields_filters(issue_custom_fields)

  add_associations_custom_fields_filters :project, :author, :assigned_to, :fixed_version

  IssueRelation::TYPES.each do |relation_type, options|
    add_available_filter relation_type, :type => :relation, :label => options[:name]
  end

  Tracker.disabled_core_fields(trackers).each {|field|
    delete_available_filter field
  }
end

#is_private?Boolean

Returns:

  • (Boolean)

93
94
95
# File 'app/models/issue_query.rb', line 93

def is_private?
  visibility == VISIBILITY_PRIVATE
end

#is_public?Boolean

Returns:

  • (Boolean)

97
98
99
# File 'app/models/issue_query.rb', line 97

def is_public?
  !is_private?
end

#issue_countObject

Returns the issue count


292
293
294
295
296
# File 'app/models/issue_query.rb', line 292

def issue_count
  Issue.visible.joins(:status, :project).where(statement).count
rescue ::ActiveRecord::StatementInvalid => e
  raise StatementInvalid.new(e.message)
end

#issue_count_by_groupObject

Returns the issue count by group or nil if query is not grouped


299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'app/models/issue_query.rb', line 299

def issue_count_by_group
  r = nil
  if grouped?
    begin
      # Rails3 will raise an (unexpected) RecordNotFound if there's only a nil group value
      r = Issue.visible.
        joins(:status, :project).
        where(statement).
        joins(joins_for_order_statement(group_by_statement)).
        group(group_by_statement).
        count
    rescue ActiveRecord::RecordNotFound
      r = {nil => issue_count}
    end
    c = group_by_column
    if c.is_a?(QueryCustomFieldColumn)
      r = r.keys.inject({}) {|h, k| h[c.custom_field.cast_value(k)] = r[k]; h}
    end
  end
  r
rescue ::ActiveRecord::StatementInvalid => e
  raise StatementInvalid.new(e.message)
end

#issue_ids(options = {}) ⇒ Object

Returns the issues ids


357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
# File 'app/models/issue_query.rb', line 357

def issue_ids(options={})
  order_option = [group_by_sort_order, options[:order]].flatten.reject(&:blank?)

  Issue.visible.
    joins(:status, :project).
    where(statement).
    includes(([:status, :project] + (options[:include] || [])).uniq).
    references(([:status, :project] + (options[:include] || [])).uniq).
    where(options[:conditions]).
    order(order_option).
    joins(joins_for_order_statement(order_option.join(','))).
    limit(options[:limit]).
    offset(options[:offset]).
    pluck(:id)
rescue ::ActiveRecord::StatementInvalid => e
  raise StatementInvalid.new(e.message)
end

#issues(options = {}) ⇒ Object

Returns the issues Valid options are :order, :offset, :limit, :include, :conditions


325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# File 'app/models/issue_query.rb', line 325

def issues(options={})
  order_option = [group_by_sort_order, options[:order]].flatten.reject(&:blank?)

  scope = Issue.visible.
    joins(:status, :project).
    where(statement).
    includes(([:status, :project] + (options[:include] || [])).uniq).
    where(options[:conditions]).
    order(order_option).
    joins(joins_for_order_statement(order_option.join(','))).
    limit(options[:limit]).
    offset(options[:offset])

  scope = scope.preload(:custom_values)
  if has_column?(:author)
    scope = scope.preload(:author)
  end

  issues = scope.to_a

  if has_column?(:spent_hours)
    Issue.load_visible_spent_hours(issues)
  end
  if has_column?(:relations)
    Issue.load_visible_relations(issues)
  end
  issues
rescue ::ActiveRecord::StatementInvalid => e
  raise StatementInvalid.new(e.message)
end

#journals(options = {}) ⇒ Object

Returns the journals Valid options are :order, :offset, :limit


377
378
379
380
381
382
383
384
385
386
387
388
# File 'app/models/issue_query.rb', line 377

def journals(options={})
  Journal.visible.
    joins(:issue => [:project, :status]).
    where(statement).
    order(options[:order]).
    limit(options[:limit]).
    offset(options[:offset]).
    preload(:details, :user, {:issue => [:project, :author, :tracker, :status]}).
    to_a
rescue ::ActiveRecord::StatementInvalid => e
  raise StatementInvalid.new(e.message)
end

#sql_for_assigned_to_role_field(field, operator, value) ⇒ Object


428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
# File 'app/models/issue_query.rb', line 428

def sql_for_assigned_to_role_field(field, operator, value)
  case operator
  when "*", "!*" # Member / Not member
    sw = operator == "!*" ? 'NOT' : ''
    nl = operator == "!*" ? "#{Issue.table_name}.assigned_to_id IS NULL OR" : ''
    "(#{nl} #{Issue.table_name}.assigned_to_id #{sw} IN (SELECT DISTINCT #{Member.table_name}.user_id FROM #{Member.table_name}" +
      " WHERE #{Member.table_name}.project_id = #{Issue.table_name}.project_id))"
  when "=", "!"
    role_cond = value.any? ?
      "#{MemberRole.table_name}.role_id IN (" + value.collect{|val| "'#{self.class.connection.quote_string(val)}'"}.join(",") + ")" :
      "1=0"

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

#sql_for_is_private_field(field, operator, value) ⇒ Object


447
448
449
450
451
452
# File 'app/models/issue_query.rb', line 447

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

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

#sql_for_member_of_group_field(field, operator, value) ⇒ Object


409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
# File 'app/models/issue_query.rb', line 409

def sql_for_member_of_group_field(field, operator, value)
  if operator == '*' # Any group
    groups = Group.givable
    operator = '=' # Override the operator since we want to find by assigned_to
  elsif operator == "!*"
    groups = Group.givable
    operator = '!' # Override the operator since we want to find by assigned_to
  else
    groups = Group.where(:id => value).to_a
  end
  groups ||= []

  members_of_groups = groups.inject([]) {|user_ids, group|
    user_ids + group.user_ids + [group.id]
  }.uniq.compact.sort.collect(&:to_s)

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

#sql_for_relations(field, operator, value, options = {}) ⇒ Object


454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
# File 'app/models/issue_query.rb', line 454

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

  relation_type = field
  join_column, target_join_column = "issue_from_id", "issue_to_id"
  if relation_options[:reverse] || options[:reverse]
    relation_type = relation_options[:reverse] || relation_type
    join_column, target_join_column = target_join_column, join_column
  end

  sql = case operator
    when "*", "!*"
      op = (operator == "*" ? 'IN' : 'NOT IN')
      "#{Issue.table_name}.id #{op} (SELECT DISTINCT #{IssueRelation.table_name}.#{join_column} FROM #{IssueRelation.table_name} WHERE #{IssueRelation.table_name}.relation_type = '#{self.class.connection.quote_string(relation_type)}')"
    when "=", "!"
      op = (operator == "=" ? 'IN' : 'NOT IN')
      "#{Issue.table_name}.id #{op} (SELECT DISTINCT #{IssueRelation.table_name}.#{join_column} FROM #{IssueRelation.table_name} WHERE #{IssueRelation.table_name}.relation_type = '#{self.class.connection.quote_string(relation_type)}' AND #{IssueRelation.table_name}.#{target_join_column} = #{value.first.to_i})"
    when "=p", "=!p", "!p"
      op = (operator == "!p" ? 'NOT IN' : 'IN')
      comp = (operator == "=!p" ? '<>' : '=')
      "#{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 = '#{self.class.connection.quote_string(relation_type)}' AND #{IssueRelation.table_name}.#{target_join_column} = relissues.id AND relissues.project_id #{comp} #{value.first.to_i})"
    end

  if relation_options[:sym] == field && !options[:reverse]
    sqls = [sql, sql_for_relations(field, operator, value, :reverse => true)]
    sql = sqls.join(["!", "!*", "!p"].include?(operator) ? " AND " : " OR ")
  end
  "(#{sql})"
end

#sql_for_watcher_id_field(field, operator, value) ⇒ Object


403
404
405
406
407
# File 'app/models/issue_query.rb', line 403

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

#versions(options = {}) ⇒ Object

Returns the versions Valid options are :conditions


392
393
394
395
396
397
398
399
400
401
# File 'app/models/issue_query.rb', line 392

def versions(options={})
  Version.visible.
    where(project_statement).
    where(options[:conditions]).
    includes(:project).
    references(:project).
    to_a
rescue ::ActiveRecord::StatementInvalid => e
  raise StatementInvalid.new(e.message)
end

#visible?(user = User.current) ⇒ Boolean

Returns true if the query is visible to user or the current user.

Returns:

  • (Boolean)

76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'app/models/issue_query.rb', line 76

def visible?(user=User.current)
  return true if user.admin?
  return false unless project.nil? || user.allowed_to?(:view_issues, project)
  case visibility
  when VISIBILITY_PUBLIC
    true
  when VISIBILITY_ROLES
    if project
      (user.roles_for_project(project) & roles).any?
    else
      Member.where(:user_id => user.id).joins(:roles).where(:member_roles => {:role_id => roles.map(&:id)}).any?
    end
  else
    user == self.user
  end
end