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 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. # frozen_string_literal: true
  2. # Redmine - project management software
  3. # Copyright (C) 2006-2019 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 << content_tag('label', check_box_tag('c[]', column.name.to_s, query.has_column?(column), :id => nil) + " #{column.caption}", :class => 'inline')
  87. end
  88. tags
  89. end
  90. def available_totalable_columns_tags(query, options={})
  91. tag_name = (options[:name] || 't') + '[]'
  92. tags = ''.html_safe
  93. query.available_totalable_columns.each do |column|
  94. tags << content_tag('label', check_box_tag(tag_name, column.name.to_s, query.totalable_columns.include?(column), :id => nil) + " #{column.caption}", :class => 'inline')
  95. end
  96. tags << hidden_field_tag(tag_name, '')
  97. tags
  98. end
  99. def query_available_inline_columns_options(query)
  100. (query.available_inline_columns - query.columns).reject(&:frozen?).collect {|column| [column.caption, column.name]}
  101. end
  102. def query_selected_inline_columns_options(query)
  103. (query.inline_columns & query.available_inline_columns).reject(&:frozen?).collect {|column| [column.caption, column.name]}
  104. end
  105. def render_query_columns_selection(query, options={})
  106. tag_name = (options[:name] || 'c') + '[]'
  107. render :partial => 'queries/columns', :locals => {:query => query, :tag_name => tag_name}
  108. end
  109. def available_display_types_tags(query)
  110. available_display_types = []
  111. query.available_display_types.each do |t|
  112. available_display_types << [l(:"label_display_type_#{t}"), t]
  113. end
  114. select_tag('display_type', options_for_select(available_display_types, @query.display_type), :id => 'display_type')
  115. end
  116. def grouped_query_results(items, query, &block)
  117. result_count_by_group = query.result_count_by_group
  118. previous_group, first = false, true
  119. totals_by_group = query.totalable_columns.inject({}) do |h, column|
  120. h[column] = query.total_by_group_for(column)
  121. h
  122. end
  123. items.each do |item|
  124. group_name = group_count = nil
  125. if query.grouped?
  126. group = query.group_by_column.group_value(item)
  127. if first || group != previous_group
  128. if group.blank? && group != false
  129. group_name = "(#{l(:label_blank_value)})"
  130. else
  131. group_name = format_object(group)
  132. end
  133. group_name ||= ""
  134. group_count = result_count_by_group ? result_count_by_group[group] : nil
  135. group_totals = totals_by_group.map {|column, t| total_tag(column, t[group] || 0)}.join(" ").html_safe
  136. end
  137. end
  138. yield item, group_name, group_count, group_totals
  139. previous_group, first = group, false
  140. end
  141. end
  142. def render_query_totals(query)
  143. return unless query.totalable_columns.present?
  144. totals = query.totalable_columns.map do |column|
  145. total_tag(column, query.total_for(column))
  146. end
  147. content_tag('p', totals.join(" ").html_safe, :class => "query-totals")
  148. end
  149. def total_tag(column, value)
  150. label = content_tag('span', "#{column.caption}:")
  151. value =
  152. if [:hours, :spent_hours, :total_spent_hours, :estimated_hours].include? column.name
  153. format_hours(value)
  154. else
  155. format_object(value)
  156. end
  157. value = content_tag('span', value, :class => 'value')
  158. content_tag('span', label + " " + value, :class => "total-for-#{column.name.to_s.dasherize}")
  159. end
  160. def column_header(query, column, options={})
  161. if column.sortable?
  162. css, order = nil, column.default_order
  163. if column.name.to_s == query.sort_criteria.first_key
  164. if query.sort_criteria.first_asc?
  165. css = 'sort asc icon icon-sorted-desc'
  166. order = 'desc'
  167. else
  168. css = 'sort desc icon icon-sorted-asc'
  169. order = 'asc'
  170. end
  171. end
  172. param_key = options[:sort_param] || :sort
  173. sort_param = {param_key => query.sort_criteria.add(column.name, order).to_param}
  174. sort_param = {$1 => {$2 => sort_param.values.first}} while sort_param.keys.first.to_s =~ /^(.+)\[(.+)\]$/
  175. link_options = {
  176. :title => l(:label_sort_by, "\"#{column.caption}\""),
  177. :class => css
  178. }
  179. if options[:sort_link_options]
  180. link_options.merge! options[:sort_link_options]
  181. end
  182. content = link_to(column.caption,
  183. {:params => request.query_parameters.deep_merge(sort_param)},
  184. link_options
  185. )
  186. else
  187. content = column.caption
  188. end
  189. content_tag('th', content, :class => column.css_classes)
  190. end
  191. def column_content(column, item)
  192. value = column.value_object(item)
  193. if value.is_a?(Array)
  194. values = value.collect {|v| column_value(column, item, v)}.compact
  195. safe_join(values, ', ')
  196. else
  197. column_value(column, item, value)
  198. end
  199. end
  200. def column_value(column, item, value)
  201. case column.name
  202. when :id
  203. link_to value, issue_path(item)
  204. when :subject
  205. link_to value, issue_path(item)
  206. when :parent
  207. value ? (value.visible? ? link_to_issue(value, :subject => false) : "##{value.id}") : ''
  208. when :description
  209. item.description? ? content_tag('div', textilizable(item, :description), :class => "wiki") : ''
  210. when :last_notes
  211. item.last_notes.present? ? content_tag('div', textilizable(item, :last_notes), :class => "wiki") : ''
  212. when :done_ratio
  213. progress_bar(value)
  214. when :relations
  215. content_tag('span',
  216. value.to_s(item) {|other| link_to_issue(other, :subject => false, :tracker => false)}.html_safe,
  217. :class => value.css_classes_for(item))
  218. when :hours, :estimated_hours
  219. format_hours(value)
  220. when :spent_hours
  221. link_to_if(value > 0, format_hours(value), project_time_entries_path(item.project, :issue_id => "#{item.id}"))
  222. when :total_spent_hours
  223. link_to_if(value > 0, format_hours(value), project_time_entries_path(item.project, :issue_id => "~#{item.id}"))
  224. when :attachments
  225. value.to_a.map {|a| format_object(a)}.join(" ").html_safe
  226. else
  227. format_object(value)
  228. end
  229. end
  230. def csv_content(column, item)
  231. value = column.value_object(item)
  232. if value.is_a?(Array)
  233. value.collect {|v| csv_value(column, item, v)}.compact.join(', ')
  234. else
  235. csv_value(column, item, value)
  236. end
  237. end
  238. def csv_value(column, object, value)
  239. case column.name
  240. when :attachments
  241. value.to_a.map {|a| a.filename}.join("\n")
  242. else
  243. format_object(value, false) do |value|
  244. case value.class.name
  245. when 'Float'
  246. sprintf("%.2f", value).gsub('.', l(:general_csv_decimal_separator))
  247. when 'IssueRelation'
  248. value.to_s(object)
  249. when 'Issue'
  250. if object.is_a?(TimeEntry)
  251. "#{value.tracker} ##{value.id}: #{value.subject}"
  252. else
  253. value.id
  254. end
  255. else
  256. value
  257. end
  258. end
  259. end
  260. end
  261. def query_to_csv(items, query, options={})
  262. columns = query.columns
  263. Redmine::Export::CSV.generate(:encoding => params[:encoding]) do |csv|
  264. # csv header fields
  265. csv << columns.map {|c| c.caption.to_s}
  266. # csv lines
  267. items.each do |item|
  268. csv << columns.map {|c| csv_content(c, item)}
  269. end
  270. end
  271. end
  272. # Retrieve query from session or build a new query
  273. def retrieve_query(klass=IssueQuery, use_session=true, options={})
  274. session_key = klass.name.underscore.to_sym
  275. if params[:query_id].present?
  276. scope = klass.where(:project_id => nil)
  277. scope = scope.or(klass.where(:project_id => @project)) if @project
  278. @query = scope.find(params[:query_id])
  279. raise ::Unauthorized unless @query.visible?
  280. @query.project = @project
  281. session[session_key] = {:id => @query.id, :project_id => @query.project_id} if use_session
  282. elsif api_request? || params[:set_filter] || !use_session || session[session_key].nil? || session[session_key][:project_id] != (@project ? @project.id : nil)
  283. # Give it a name, required to be valid
  284. @query = klass.new(:name => "_", :project => @project)
  285. @query.build_from_params(params, options[:defaults])
  286. session[session_key] = {:project_id => @query.project_id, :filters => @query.filters, :group_by => @query.group_by, :column_names => @query.column_names, :totalable_names => @query.totalable_names, :sort => @query.sort_criteria.to_a} if use_session
  287. else
  288. # retrieve from session
  289. @query = nil
  290. @query = klass.find_by_id(session[session_key][:id]) if session[session_key][:id]
  291. @query ||= klass.new(:name => "_", :filters => session[session_key][:filters], :group_by => session[session_key][:group_by], :column_names => session[session_key][:column_names], :totalable_names => session[session_key][:totalable_names], :sort_criteria => session[session_key][:sort])
  292. @query.project = @project
  293. end
  294. if params[:sort].present?
  295. @query.sort_criteria = params[:sort]
  296. if use_session
  297. session[session_key] ||= {}
  298. session[session_key][:sort] = @query.sort_criteria.to_a
  299. end
  300. end
  301. @query
  302. end
  303. def retrieve_query_from_session(klass=IssueQuery)
  304. session_key = klass.name.underscore.to_sym
  305. session_data = session[session_key]
  306. if session_data
  307. if session_data[:id]
  308. @query = IssueQuery.find_by_id(session_data[:id])
  309. return unless @query
  310. else
  311. @query = IssueQuery.new(:name => "_", :filters => session_data[:filters], :group_by => session_data[:group_by], :column_names => session_data[:column_names], :totalable_names => session_data[:totalable_names], :sort_criteria => session[session_key][:sort])
  312. end
  313. if session_data.has_key?(:project_id)
  314. @query.project_id = session_data[:project_id]
  315. else
  316. @query.project = @project
  317. end
  318. @query
  319. end
  320. end
  321. # Returns the query definition as hidden field tags
  322. def query_as_hidden_field_tags(query)
  323. tags = hidden_field_tag("set_filter", "1", :id => nil)
  324. if query.filters.present?
  325. query.filters.each do |field, filter|
  326. tags << hidden_field_tag("f[]", field, :id => nil)
  327. tags << hidden_field_tag("op[#{field}]", filter[:operator], :id => nil)
  328. filter[:values].each do |value|
  329. tags << hidden_field_tag("v[#{field}][]", value, :id => nil)
  330. end
  331. end
  332. else
  333. tags << hidden_field_tag("f[]", "", :id => nil)
  334. end
  335. query.columns.each do |column|
  336. tags << hidden_field_tag("c[]", column.name, :id => nil)
  337. end
  338. if query.totalable_names.present?
  339. query.totalable_names.each do |name|
  340. tags << hidden_field_tag("t[]", name, :id => nil)
  341. end
  342. end
  343. if query.group_by.present?
  344. tags << hidden_field_tag("group_by", query.group_by, :id => nil)
  345. end
  346. if query.sort_criteria.present?
  347. tags << hidden_field_tag("sort", query.sort_criteria.to_param, :id => nil)
  348. end
  349. tags
  350. end
  351. def query_hidden_sort_tag(query)
  352. hidden_field_tag("sort", query.sort_criteria.to_param, :id => nil)
  353. end
  354. # Returns the queries that are rendered in the sidebar
  355. def sidebar_queries(klass, project)
  356. klass.visible.global_or_on_project(@project).sorted.to_a
  357. end
  358. # Renders a group of queries
  359. def query_links(title, queries)
  360. return '' if queries.empty?
  361. # links to #index on issues/show
  362. url_params = controller_name == 'issues' ? {:controller => 'issues', :action => 'index', :project_id => @project} : {}
  363. content_tag('h3', title) + "\n" +
  364. content_tag('ul',
  365. queries.collect {|query|
  366. css = +'query'
  367. clear_link = +''
  368. if query == @query
  369. css << ' selected'
  370. clear_link += link_to_clear_query
  371. end
  372. content_tag('li', link_to(query.name, url_params.merge(:query_id => query), :class => css) + clear_link.html_safe)
  373. }.join("\n").html_safe,
  374. :class => 'queries'
  375. ) + "\n"
  376. end
  377. def link_to_clear_query
  378. link_to l(:button_clear), { :set_filter => 1, :sort => '', :project_id => @project }, :class => 'icon-only icon-clear-query', :title => l(:button_clear)
  379. end
  380. # Renders the list of queries for the sidebar
  381. def render_sidebar_queries(klass, project)
  382. queries = sidebar_queries(klass, project)
  383. out = ''.html_safe
  384. out << query_links(l(:label_my_queries), queries.select(&:is_private?))
  385. out << query_links(l(:label_query_plural), queries.reject(&:is_private?))
  386. out
  387. end
  388. end