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

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