You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

queries_helper.rb 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. # frozen_string_literal: true
  2. # Redmine - project management software
  3. # Copyright (C) 2006-2021 Jean-Philippe Lang
  4. #
  5. # This program is free software; you can redistribute it and/or
  6. # modify it under the terms of the GNU General Public License
  7. # as published by the Free Software Foundation; either version 2
  8. # of the License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. require 'redmine/export/csv'
  19. module QueriesHelper
  20. include ApplicationHelper
  21. def filters_options_for_select(query)
  22. ungrouped = []
  23. grouped = {}
  24. query.available_filters.map do |field, field_options|
  25. if field_options[:type] == :relation
  26. group = :label_relations
  27. elsif field_options[:type] == :tree
  28. group = query.is_a?(IssueQuery) ? :label_relations : nil
  29. elsif /^cf_\d+\./.match?(field)
  30. group = (field_options[:through] || field_options[:field]).try(:name)
  31. elsif field =~ /^(.+)\./
  32. # association filters
  33. group = "field_#{$1}".to_sym
  34. elsif %w(member_of_group assigned_to_role).include?(field)
  35. group = :field_assigned_to
  36. elsif field_options[:type] == :date_past || field_options[:type] == :date
  37. group = :label_date
  38. elsif %w(estimated_hours spent_time).include?(field)
  39. group = :label_time_tracking
  40. end
  41. if group
  42. (grouped[group] ||= []) << [field_options[:name], field]
  43. else
  44. ungrouped << [field_options[:name], field]
  45. end
  46. end
  47. # Don't group dates if there's only one (eg. time entries filters)
  48. if grouped[:label_date].try(:size) == 1
  49. ungrouped << grouped.delete(:label_date).first
  50. end
  51. s = options_for_select([[]] + ungrouped)
  52. if grouped.present?
  53. localized_grouped = grouped.map {|k, v| [k.is_a?(Symbol) ? l(k) : k.to_s, v]}
  54. s << grouped_options_for_select(localized_grouped)
  55. end
  56. s
  57. end
  58. def query_filters_hidden_tags(query)
  59. tags = ''.html_safe
  60. query.filters.each do |field, options|
  61. tags << hidden_field_tag("f[]", field, :id => nil)
  62. tags << hidden_field_tag("op[#{field}]", options[:operator], :id => nil)
  63. options[:values].each do |value|
  64. tags << hidden_field_tag("v[#{field}][]", value, :id => nil)
  65. end
  66. end
  67. tags
  68. end
  69. def query_columns_hidden_tags(query)
  70. tags = ''.html_safe
  71. query.columns.each do |column|
  72. tags << hidden_field_tag("c[]", column.name, :id => nil)
  73. end
  74. tags
  75. end
  76. def query_hidden_tags(query)
  77. query_filters_hidden_tags(query) + query_columns_hidden_tags(query)
  78. end
  79. def group_by_column_select_tag(query)
  80. options = [[]] + query.groupable_columns.collect {|c| [c.caption, c.name.to_s]}
  81. select_tag('group_by', options_for_select(options, @query.group_by))
  82. end
  83. def available_block_columns_tags(query)
  84. tags = ''.html_safe
  85. query.available_block_columns.each do |column|
  86. tags <<
  87. content_tag(
  88. 'label',
  89. check_box_tag(
  90. 'c[]', column.name.to_s,
  91. query.has_column?(column), :id => nil
  92. ) + " #{column.caption}", :class => 'inline'
  93. )
  94. end
  95. tags
  96. end
  97. def available_totalable_columns_tags(query, options={})
  98. tag_name = (options[:name] || 't') + '[]'
  99. tags = ''.html_safe
  100. query.available_totalable_columns.each do |column|
  101. tags <<
  102. content_tag(
  103. 'label',
  104. check_box_tag(
  105. tag_name, column.name.to_s,
  106. query.totalable_columns.include?(column), :id => nil
  107. ) + " #{column.caption}", :class => 'inline'
  108. )
  109. end
  110. tags << hidden_field_tag(tag_name, '')
  111. tags
  112. end
  113. def query_available_inline_columns_options(query)
  114. (query.available_inline_columns - query.columns).
  115. reject(&:frozen?).collect {|column| [column.caption, column.name]}
  116. end
  117. def query_selected_inline_columns_options(query)
  118. (query.inline_columns & query.available_inline_columns).
  119. reject(&:frozen?).collect {|column| [column.caption, column.name]}
  120. end
  121. def render_query_columns_selection(query, options={})
  122. tag_name = (options[:name] || 'c') + '[]'
  123. render :partial => 'queries/columns', :locals => {:query => query, :tag_name => tag_name}
  124. end
  125. def available_display_types_tags(query)
  126. tags = ''.html_safe
  127. query.available_display_types.each do |t|
  128. tags << radio_button_tag('display_type', t, @query.display_type == t, :id => "display_type_#{t}") +
  129. content_tag('label', l(:"label_display_type_#{t}"), :for => "display_type_#{t}", :class => "inline")
  130. end
  131. tags
  132. end
  133. def grouped_query_results(items, query, &block)
  134. result_count_by_group = query.result_count_by_group
  135. previous_group, first = false, true
  136. totals_by_group = query.totalable_columns.inject({}) do |h, column|
  137. h[column] = query.total_by_group_for(column)
  138. h
  139. end
  140. items.each do |item|
  141. group_name = group_count = nil
  142. if query.grouped?
  143. group = query.group_by_column.group_value(item)
  144. if first || group != previous_group
  145. if group.blank? && group != false
  146. group_name = "(#{l(:label_blank_value)})"
  147. else
  148. group_name = format_object(group)
  149. end
  150. group_name ||= ""
  151. group_count = result_count_by_group ? result_count_by_group[group] : nil
  152. group_totals = totals_by_group.map {|column, t| total_tag(column, t[group] || 0)}.join(" ").html_safe
  153. end
  154. end
  155. yield item, group_name, group_count, group_totals
  156. previous_group, first = group, false
  157. end
  158. end
  159. def render_query_totals(query)
  160. return unless query.totalable_columns.present?
  161. totals = query.totalable_columns.map do |column|
  162. total_tag(column, query.total_for(column))
  163. end
  164. content_tag('p', totals.join(" ").html_safe, :class => "query-totals")
  165. end
  166. def total_tag(column, value)
  167. label = content_tag('span', "#{column.caption}:")
  168. value =
  169. if [:hours, :spent_hours, :total_spent_hours, :estimated_hours, :total_estimated_hours].include? column.name
  170. format_hours(value)
  171. else
  172. format_object(value)
  173. end
  174. value = content_tag('span', value, :class => 'value')
  175. content_tag('span', label + " " + value, :class => "total-for-#{column.name.to_s.dasherize}")
  176. end
  177. def column_header(query, column, options={})
  178. if column.sortable?
  179. css, order = nil, column.default_order
  180. if column.name.to_s == query.sort_criteria.first_key
  181. if query.sort_criteria.first_asc?
  182. css = 'sort asc icon icon-sorted-desc'
  183. order = 'desc'
  184. else
  185. css = 'sort desc icon icon-sorted-asc'
  186. order = 'asc'
  187. end
  188. end
  189. param_key = options[:sort_param] || :sort
  190. sort_param = {param_key => query.sort_criteria.add(column.name, order).to_param}
  191. sort_param = {$1 => {$2 => sort_param.values.first}} while sort_param.keys.first.to_s =~ /^(.+)\[(.+)\]$/
  192. link_options = {
  193. :title => l(:label_sort_by, "\"#{column.caption}\""),
  194. :class => css
  195. }
  196. if options[:sort_link_options]
  197. link_options.merge! options[:sort_link_options]
  198. end
  199. content =
  200. link_to(
  201. column.caption,
  202. {:params => request.query_parameters.deep_merge(sort_param)},
  203. link_options
  204. )
  205. else
  206. content = column.caption
  207. end
  208. content_tag('th', content, :class => column.css_classes)
  209. end
  210. def column_content(column, item)
  211. value = column.value_object(item)
  212. if value.is_a?(Array)
  213. values = value.collect {|v| column_value(column, item, v)}.compact
  214. safe_join(values, ', ')
  215. else
  216. column_value(column, item, value)
  217. end
  218. end
  219. def column_value(column, item, value)
  220. case column.name
  221. when :id
  222. link_to value, issue_path(item)
  223. when :subject
  224. link_to value, issue_path(item)
  225. when :parent
  226. value ? (value.visible? ? link_to_issue(value, :subject => false) : "##{value.id}") : ''
  227. when :description
  228. item.description? ? content_tag('div', textilizable(item, :description), :class => "wiki") : ''
  229. when :last_notes
  230. item.last_notes.present? ? content_tag('div', textilizable(item, :last_notes), :class => "wiki") : ''
  231. when :done_ratio
  232. progress_bar(value)
  233. when :relations
  234. content_tag(
  235. 'span',
  236. value.to_s(item) {|other| link_to_issue(other, :subject => false, :tracker => false)}.html_safe,
  237. :class => value.css_classes_for(item))
  238. when :hours, :estimated_hours, :total_estimated_hours
  239. format_hours(value)
  240. when :spent_hours
  241. link_to_if(value > 0, format_hours(value), project_time_entries_path(item.project, :issue_id => "#{item.id}"))
  242. when :total_spent_hours
  243. link_to_if(value > 0, format_hours(value), project_time_entries_path(item.project, :issue_id => "~#{item.id}"))
  244. when :attachments
  245. value.to_a.map {|a| format_object(a)}.join(" ").html_safe
  246. else
  247. format_object(value)
  248. end
  249. end
  250. def csv_content(column, item)
  251. value = column.value_object(item)
  252. if value.is_a?(Array)
  253. value.collect {|v| csv_value(column, item, v)}.compact.join(', ')
  254. else
  255. csv_value(column, item, value)
  256. end
  257. end
  258. def csv_value(column, object, value)
  259. case column.name
  260. when :attachments
  261. value.to_a.map {|a| a.filename}.join("\n")
  262. else
  263. format_object(value, false) do |value|
  264. case value.class.name
  265. when 'Float'
  266. sprintf("%.2f", value).gsub('.', l(:general_csv_decimal_separator))
  267. when 'IssueRelation'
  268. value.to_s(object)
  269. when 'Issue'
  270. if object.is_a?(TimeEntry)
  271. value.visible? ? "#{value.tracker} ##{value.id}: #{value.subject}" : "##{value.id}"
  272. else
  273. value.id
  274. end
  275. else
  276. value
  277. end
  278. end
  279. end
  280. end
  281. def query_to_csv(items, query, options={})
  282. columns = query.columns
  283. Redmine::Export::CSV.generate(:encoding => params[:encoding]) do |csv|
  284. # csv header fields
  285. csv << columns.map {|c| c.caption.to_s}
  286. # csv lines
  287. items.each do |item|
  288. csv << columns.map {|c| csv_content(c, item)}
  289. end
  290. end
  291. end
  292. # Retrieve query from session or build a new query
  293. def retrieve_query(klass=IssueQuery, use_session=true, options={})
  294. session_key = klass.name.underscore.to_sym
  295. if params[:query_id].present?
  296. scope = klass.where(:project_id => nil)
  297. scope = scope.or(klass.where(:project_id => @project)) if @project
  298. @query = scope.find(params[:query_id])
  299. raise ::Unauthorized unless @query.visible?
  300. @query.project = @project
  301. session[session_key] = {:id => @query.id, :project_id => @query.project_id} if use_session
  302. elsif api_request? || params[:set_filter] || !use_session ||
  303. session[session_key].nil? ||
  304. session[session_key][:project_id] != (@project ? @project.id : nil)
  305. # Give it a name, required to be valid
  306. @query = klass.new(:name => "_", :project => @project)
  307. @query.build_from_params(params, options[:defaults])
  308. if use_session
  309. session[session_key] = {
  310. :project_id => @query.project_id,
  311. :filters => @query.filters,
  312. :group_by => @query.group_by,
  313. :column_names => @query.column_names,
  314. :totalable_names => @query.totalable_names,
  315. :sort => @query.sort_criteria.to_a
  316. }
  317. end
  318. else
  319. # retrieve from session
  320. @query = nil
  321. @query = klass.find_by_id(session[session_key][:id]) if session[session_key][:id]
  322. @query ||=
  323. klass.new(
  324. :name => "_",
  325. :filters => session[session_key][:filters],
  326. :group_by => session[session_key][:group_by],
  327. :column_names => session[session_key][:column_names],
  328. :totalable_names => session[session_key][:totalable_names],
  329. :sort_criteria => session[session_key][:sort]
  330. )
  331. @query.project = @project
  332. end
  333. if params[:sort].present?
  334. @query.sort_criteria = params[:sort]
  335. if use_session
  336. session[session_key] ||= {}
  337. session[session_key][:sort] = @query.sort_criteria.to_a
  338. end
  339. end
  340. @query
  341. end
  342. def retrieve_query_from_session(klass=IssueQuery)
  343. session_key = klass.name.underscore.to_sym
  344. session_data = session[session_key]
  345. if session_data
  346. if session_data[:id]
  347. @query = IssueQuery.find_by_id(session_data[:id])
  348. return unless @query
  349. else
  350. @query =
  351. IssueQuery.new(
  352. :name => "_",
  353. :filters => session_data[:filters],
  354. :group_by => session_data[:group_by],
  355. :column_names => session_data[:column_names],
  356. :totalable_names => session_data[:totalable_names],
  357. :sort_criteria => session[session_key][:sort]
  358. )
  359. end
  360. if session_data.has_key?(:project_id)
  361. @query.project_id = session_data[:project_id]
  362. else
  363. @query.project = @project
  364. end
  365. @query
  366. end
  367. end
  368. # Returns the query definition as hidden field tags
  369. def query_as_hidden_field_tags(query)
  370. tags = hidden_field_tag("set_filter", "1", :id => nil)
  371. if query.filters.present?
  372. query.filters.each do |field, filter|
  373. tags << hidden_field_tag("f[]", field, :id => nil)
  374. tags << hidden_field_tag("op[#{field}]", filter[:operator], :id => nil)
  375. filter[:values].each do |value|
  376. tags << hidden_field_tag("v[#{field}][]", value, :id => nil)
  377. end
  378. end
  379. else
  380. tags << hidden_field_tag("f[]", "", :id => nil)
  381. end
  382. query.columns.each do |column|
  383. tags << hidden_field_tag("c[]", column.name, :id => nil)
  384. end
  385. if query.totalable_names.present?
  386. query.totalable_names.each do |name|
  387. tags << hidden_field_tag("t[]", name, :id => nil)
  388. end
  389. end
  390. if query.group_by.present?
  391. tags << hidden_field_tag("group_by", query.group_by, :id => nil)
  392. end
  393. if query.sort_criteria.present?
  394. tags << hidden_field_tag("sort", query.sort_criteria.to_param, :id => nil)
  395. end
  396. tags
  397. end
  398. def query_hidden_sort_tag(query)
  399. hidden_field_tag("sort", query.sort_criteria.to_param, :id => nil)
  400. end
  401. # Returns the queries that are rendered in the sidebar
  402. def sidebar_queries(klass, project)
  403. klass.visible.global_or_on_project(@project).sorted.to_a
  404. end
  405. # Renders a group of queries
  406. def query_links(title, queries)
  407. return '' if queries.empty?
  408. # links to #index on issues/show
  409. url_params =
  410. if controller_name == 'issues'
  411. {:controller => 'issues', :action => 'index', :project_id => @project}
  412. else
  413. {}
  414. end
  415. content_tag('h3', title) + "\n" +
  416. content_tag(
  417. 'ul',
  418. queries.collect do |query|
  419. css = +'query'
  420. clear_link = +''
  421. if query == @query
  422. css << ' selected'
  423. clear_link += link_to_clear_query
  424. end
  425. content_tag('li',
  426. link_to(query.name,
  427. url_params.merge(:query_id => query),
  428. :class => css) +
  429. clear_link.html_safe)
  430. end.join("\n").html_safe,
  431. :class => 'queries'
  432. ) + "\n"
  433. end
  434. def link_to_clear_query
  435. link_to(
  436. l(:button_clear),
  437. {:set_filter => 1, :sort => '', :project_id => @project},
  438. :class => 'icon-only icon-clear-query',
  439. :title => l(:button_clear)
  440. )
  441. end
  442. # Renders the list of queries for the sidebar
  443. def render_sidebar_queries(klass, project)
  444. queries = sidebar_queries(klass, project)
  445. out = ''.html_safe
  446. out << query_links(l(:label_my_queries), queries.select(&:is_private?))
  447. out << query_links(l(:label_query_plural), queries.reject(&:is_private?))
  448. out
  449. end
  450. end