PageRenderTime 58ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/app/controllers/issues_controller.rb

https://github.com/kdmny/redmine
Ruby | 488 lines | 405 code | 40 blank | 43 comment | 99 complexity | 2dc715291f87ba4e3e4ca384fc201fa0 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1
  1. # Redmine - project management software
  2. # Copyright (C) 2006-2008 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. class IssuesController < ApplicationController
  18. menu_item :new_issue, :only => :new
  19. before_filter :find_issue, :only => [:show, :edit, :reply]
  20. before_filter :find_issues, :only => [:bulk_edit, :move, :destroy]
  21. before_filter :find_project, :only => [:new, :update_form, :preview]
  22. before_filter :authorize, :except => [:index, :changes, :gantt, :calendar, :preview, :update_form, :context_menu]
  23. before_filter :find_optional_project, :only => [:index, :changes, :gantt, :calendar]
  24. accept_key_auth :index, :changes
  25. helper :journals
  26. helper :projects
  27. include ProjectsHelper
  28. helper :custom_fields
  29. include CustomFieldsHelper
  30. helper :issue_relations
  31. include IssueRelationsHelper
  32. helper :watchers
  33. include WatchersHelper
  34. helper :attachments
  35. include AttachmentsHelper
  36. helper :queries
  37. helper :sort
  38. include SortHelper
  39. include IssuesHelper
  40. helper :timelog
  41. include Redmine::Export::PDF
  42. def index
  43. retrieve_query
  44. sort_init 'id', 'desc'
  45. sort_update({'id' => "#{Issue.table_name}.id"}.merge(@query.columns.inject({}) {|h, c| h[c.name.to_s] = c.sortable; h}))
  46. if @query.valid?
  47. limit = per_page_option
  48. respond_to do |format|
  49. format.html { }
  50. format.atom { }
  51. format.csv { limit = Setting.issues_export_limit.to_i }
  52. format.pdf { limit = Setting.issues_export_limit.to_i }
  53. end
  54. @issue_count = Issue.count(:include => [:status, :project], :conditions => @query.statement)
  55. @issue_pages = Paginator.new self, @issue_count, limit, params['page']
  56. @issues = Issue.find :all, :order => sort_clause,
  57. :include => [ :assigned_to, :status, :tracker, :project, :priority, :category, :fixed_version ],
  58. :conditions => @query.statement,
  59. :limit => limit,
  60. :offset => @issue_pages.current.offset
  61. respond_to do |format|
  62. format.html { render :template => 'issues/index.rhtml', :layout => !request.xhr? }
  63. format.atom { render_feed(@issues, :title => "#{@project || Setting.app_title}: #{l(:label_issue_plural)}") }
  64. format.csv { send_data(issues_to_csv(@issues, @project).read, :type => 'text/csv; header=present', :filename => 'export.csv') }
  65. format.pdf { send_data(issues_to_pdf(@issues, @project), :type => 'application/pdf', :filename => 'export.pdf') }
  66. end
  67. else
  68. # Send html if the query is not valid
  69. render(:template => 'issues/index.rhtml', :layout => !request.xhr?)
  70. end
  71. rescue ActiveRecord::RecordNotFound
  72. render_404
  73. end
  74. def changes
  75. retrieve_query
  76. sort_init 'id', 'desc'
  77. sort_update({'id' => "#{Issue.table_name}.id"}.merge(@query.columns.inject({}) {|h, c| h[c.name.to_s] = c.sortable; h}))
  78. if @query.valid?
  79. @journals = Journal.find :all, :include => [ :details, :user, {:issue => [:project, :author, :tracker, :status]} ],
  80. :conditions => @query.statement,
  81. :limit => 25,
  82. :order => "#{Journal.table_name}.created_on DESC"
  83. end
  84. @title = (@project ? @project.name : Setting.app_title) + ": " + (@query.new_record? ? l(:label_changes_details) : @query.name)
  85. render :layout => false, :content_type => 'application/atom+xml'
  86. rescue ActiveRecord::RecordNotFound
  87. render_404
  88. end
  89. def show
  90. @journals = @issue.journals.find(:all, :include => [:user, :details], :order => "#{Journal.table_name}.created_on ASC")
  91. @journals.each_with_index {|j,i| j.indice = i+1}
  92. @journals.reverse! if User.current.wants_comments_in_reverse_order?
  93. @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
  94. @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
  95. @priorities = Enumeration::get_values('IPRI')
  96. @time_entry = TimeEntry.new
  97. respond_to do |format|
  98. format.html { render :template => 'issues/show.rhtml' }
  99. format.atom { render :action => 'changes', :layout => false, :content_type => 'application/atom+xml' }
  100. format.pdf { send_data(issue_to_pdf(@issue), :type => 'application/pdf', :filename => "#{@project.identifier}-#{@issue.id}.pdf") }
  101. end
  102. end
  103. # Add a new issue
  104. # The new issue will be created from an existing one if copy_from parameter is given
  105. def new
  106. @issue = Issue.new
  107. @issue.copy_from(params[:copy_from]) if params[:copy_from]
  108. @issue.project = @project
  109. # Tracker must be set before custom field values
  110. @issue.tracker ||= @project.trackers.find((params[:issue] && params[:issue][:tracker_id]) || params[:tracker_id] || :first)
  111. if @issue.tracker.nil?
  112. flash.now[:error] = 'No tracker is associated to this project. Please check the Project settings.'
  113. render :nothing => true, :layout => true
  114. return
  115. end
  116. if params[:issue].is_a?(Hash)
  117. @issue.attributes = params[:issue]
  118. @issue.watcher_user_ids = params[:issue]['watcher_user_ids'] if User.current.allowed_to?(:add_issue_watchers, @project)
  119. end
  120. @issue.author = User.current
  121. default_status = IssueStatus.default
  122. unless default_status
  123. flash.now[:error] = 'No default issue status is defined. Please check your configuration (Go to "Administration -> Issue statuses").'
  124. render :nothing => true, :layout => true
  125. return
  126. end
  127. @issue.status = default_status
  128. @allowed_statuses = ([default_status] + default_status.find_new_statuses_allowed_to(User.current.role_for_project(@project), @issue.tracker)).uniq
  129. if request.get? || request.xhr?
  130. @issue.start_date ||= Date.today
  131. else
  132. requested_status = IssueStatus.find_by_id(params[:issue][:status_id])
  133. # Check that the user is allowed to apply the requested status
  134. @issue.status = (@allowed_statuses.include? requested_status) ? requested_status : default_status
  135. if @issue.save
  136. attach_files(@issue, params[:attachments])
  137. flash[:notice] = l(:notice_successful_create)
  138. Mailer.deliver_issue_add(@issue) if Setting.notified_events.include?('issue_added')
  139. call_hook(:controller_issues_new_after_save, { :params => params, :issue => @issue})
  140. redirect_to :controller => 'issues', :action => 'show', :id => @issue
  141. return
  142. end
  143. end
  144. @priorities = Enumeration::get_values('IPRI')
  145. render :layout => !request.xhr?
  146. end
  147. # Attributes that can be updated on workflow transition (without :edit permission)
  148. # TODO: make it configurable (at least per role)
  149. UPDATABLE_ATTRS_ON_TRANSITION = %w(status_id assigned_to_id fixed_version_id done_ratio) unless const_defined?(:UPDATABLE_ATTRS_ON_TRANSITION)
  150. def edit
  151. @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
  152. @priorities = Enumeration::get_values('IPRI')
  153. @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
  154. @time_entry = TimeEntry.new
  155. @notes = params[:notes]
  156. journal = @issue.init_journal(User.current, @notes)
  157. # User can change issue attributes only if he has :edit permission or if a workflow transition is allowed
  158. if (@edit_allowed || !@allowed_statuses.empty?) && params[:issue]
  159. attrs = params[:issue].dup
  160. attrs.delete_if {|k,v| !UPDATABLE_ATTRS_ON_TRANSITION.include?(k) } unless @edit_allowed
  161. attrs.delete(:status_id) unless @allowed_statuses.detect {|s| s.id.to_s == attrs[:status_id].to_s}
  162. @issue.attributes = attrs
  163. end
  164. if request.post?
  165. @time_entry = TimeEntry.new(:project => @project, :issue => @issue, :user => User.current, :spent_on => Date.today)
  166. @time_entry.attributes = params[:time_entry]
  167. attachments = attach_files(@issue, params[:attachments])
  168. attachments.each {|a| journal.details << JournalDetail.new(:property => 'attachment', :prop_key => a.id, :value => a.filename)}
  169. call_hook(:controller_issues_edit_before_save, { :params => params, :issue => @issue, :time_entry => @time_entry, :journal => journal})
  170. if (@time_entry.hours.nil? || @time_entry.valid?) && @issue.save
  171. # Log spend time
  172. if current_role.allowed_to?(:log_time)
  173. @time_entry.save
  174. end
  175. if !journal.new_record?
  176. # Only send notification if something was actually changed
  177. flash[:notice] = l(:notice_successful_update)
  178. Mailer.deliver_issue_edit(journal) if Setting.notified_events.include?('issue_updated')
  179. end
  180. call_hook(:controller_issues_edit_after_save, { :params => params, :issue => @issue, :time_entry => @time_entry, :journal => journal})
  181. redirect_to(params[:back_to] || {:action => 'show', :id => @issue})
  182. end
  183. end
  184. rescue ActiveRecord::StaleObjectError
  185. # Optimistic locking exception
  186. flash.now[:error] = l(:notice_locking_conflict)
  187. end
  188. def reply
  189. journal = Journal.find(params[:journal_id]) if params[:journal_id]
  190. if journal
  191. user = journal.user
  192. text = journal.notes
  193. else
  194. user = @issue.author
  195. text = @issue.description
  196. end
  197. content = "#{ll(Setting.default_language, :text_user_wrote, user)}\\n> "
  198. content << text.to_s.strip.gsub(%r{<pre>((.|\s)*?)</pre>}m, '[...]').gsub('"', '\"').gsub(/(\r?\n|\r\n?)/, "\\n> ") + "\\n\\n"
  199. render(:update) { |page|
  200. page.<< "$('notes').value = \"#{content}\";"
  201. page.show 'update'
  202. page << "Form.Element.focus('notes');"
  203. page << "Element.scrollTo('update');"
  204. page << "$('notes').scrollTop = $('notes').scrollHeight - $('notes').clientHeight;"
  205. }
  206. end
  207. # Bulk edit a set of issues
  208. def bulk_edit
  209. if request.post?
  210. status = params[:status_id].blank? ? nil : IssueStatus.find_by_id(params[:status_id])
  211. priority = params[:priority_id].blank? ? nil : Enumeration.find_by_id(params[:priority_id])
  212. assigned_to = (params[:assigned_to_id].blank? || params[:assigned_to_id] == 'none') ? nil : User.find_by_id(params[:assigned_to_id])
  213. category = (params[:category_id].blank? || params[:category_id] == 'none') ? nil : @project.issue_categories.find_by_id(params[:category_id])
  214. fixed_version = (params[:fixed_version_id].blank? || params[:fixed_version_id] == 'none') ? nil : @project.versions.find_by_id(params[:fixed_version_id])
  215. unsaved_issue_ids = []
  216. @issues.each do |issue|
  217. journal = issue.init_journal(User.current, params[:notes])
  218. issue.priority = priority if priority
  219. issue.assigned_to = assigned_to if assigned_to || params[:assigned_to_id] == 'none'
  220. issue.category = category if category || params[:category_id] == 'none'
  221. issue.fixed_version = fixed_version if fixed_version || params[:fixed_version_id] == 'none'
  222. issue.start_date = params[:start_date] unless params[:start_date].blank?
  223. issue.due_date = params[:due_date] unless params[:due_date].blank?
  224. issue.done_ratio = params[:done_ratio] unless params[:done_ratio].blank?
  225. call_hook(:controller_issues_bulk_edit_before_save, { :params => params, :issue => issue })
  226. # Don't save any change to the issue if the user is not authorized to apply the requested status
  227. if (status.nil? || (issue.status.new_status_allowed_to?(status, current_role, issue.tracker) && issue.status = status)) && issue.save
  228. # Send notification for each issue (if changed)
  229. Mailer.deliver_issue_edit(journal) if journal.details.any? && Setting.notified_events.include?('issue_updated')
  230. else
  231. # Keep unsaved issue ids to display them in flash error
  232. unsaved_issue_ids << issue.id
  233. end
  234. end
  235. if unsaved_issue_ids.empty?
  236. flash[:notice] = l(:notice_successful_update) unless @issues.empty?
  237. else
  238. flash[:error] = l(:notice_failed_to_save_issues, unsaved_issue_ids.size, @issues.size, '#' + unsaved_issue_ids.join(', #'))
  239. end
  240. redirect_to(params[:back_to] || {:controller => 'issues', :action => 'index', :project_id => @project})
  241. return
  242. end
  243. # Find potential statuses the user could be allowed to switch issues to
  244. @available_statuses = Workflow.find(:all, :include => :new_status,
  245. :conditions => {:role_id => current_role.id}).collect(&:new_status).compact.uniq.sort
  246. end
  247. def move
  248. @allowed_projects = []
  249. # find projects to which the user is allowed to move the issue
  250. if User.current.admin?
  251. # admin is allowed to move issues to any active (visible) project
  252. @allowed_projects = Project.find(:all, :conditions => Project.visible_by(User.current), :order => 'name')
  253. else
  254. User.current.memberships.each {|m| @allowed_projects << m.project if m.role.allowed_to?(:move_issues)}
  255. end
  256. @target_project = @allowed_projects.detect {|p| p.id.to_s == params[:new_project_id]} if params[:new_project_id]
  257. @target_project ||= @project
  258. @trackers = @target_project.trackers
  259. if request.post?
  260. new_tracker = params[:new_tracker_id].blank? ? nil : @target_project.trackers.find_by_id(params[:new_tracker_id])
  261. unsaved_issue_ids = []
  262. @issues.each do |issue|
  263. issue.init_journal(User.current)
  264. unsaved_issue_ids << issue.id unless issue.move_to(@target_project, new_tracker)
  265. end
  266. if unsaved_issue_ids.empty?
  267. flash[:notice] = l(:notice_successful_update) unless @issues.empty?
  268. else
  269. flash[:error] = l(:notice_failed_to_save_issues, unsaved_issue_ids.size, @issues.size, '#' + unsaved_issue_ids.join(', #'))
  270. end
  271. redirect_to :controller => 'issues', :action => 'index', :project_id => @project
  272. return
  273. end
  274. render :layout => false if request.xhr?
  275. end
  276. def destroy
  277. @hours = TimeEntry.sum(:hours, :conditions => ['issue_id IN (?)', @issues]).to_f
  278. if @hours > 0
  279. case params[:todo]
  280. when 'destroy'
  281. # nothing to do
  282. when 'nullify'
  283. TimeEntry.update_all('issue_id = NULL', ['issue_id IN (?)', @issues])
  284. when 'reassign'
  285. reassign_to = @project.issues.find_by_id(params[:reassign_to_id])
  286. if reassign_to.nil?
  287. flash.now[:error] = l(:error_issue_not_found_in_project)
  288. return
  289. else
  290. TimeEntry.update_all("issue_id = #{reassign_to.id}", ['issue_id IN (?)', @issues])
  291. end
  292. else
  293. # display the destroy form
  294. return
  295. end
  296. end
  297. @issues.each(&:destroy)
  298. redirect_to :action => 'index', :project_id => @project
  299. end
  300. def gantt
  301. @gantt = Redmine::Helpers::Gantt.new(params)
  302. retrieve_query
  303. if @query.valid?
  304. events = []
  305. # Issues that have start and due dates
  306. events += Issue.find(:all,
  307. :order => "start_date, due_date",
  308. :include => [:tracker, :status, :assigned_to, :priority, :project],
  309. :conditions => ["(#{@query.statement}) AND (((start_date>=? and start_date<=?) or (due_date>=? and due_date<=?) or (start_date<? and due_date>?)) and start_date is not null and due_date is not null)", @gantt.date_from, @gantt.date_to, @gantt.date_from, @gantt.date_to, @gantt.date_from, @gantt.date_to]
  310. )
  311. # Issues that don't have a due date but that are assigned to a version with a date
  312. events += Issue.find(:all,
  313. :order => "start_date, effective_date",
  314. :include => [:tracker, :status, :assigned_to, :priority, :project, :fixed_version],
  315. :conditions => ["(#{@query.statement}) AND (((start_date>=? and start_date<=?) or (effective_date>=? and effective_date<=?) or (start_date<? and effective_date>?)) and start_date is not null and due_date is null and effective_date is not null)", @gantt.date_from, @gantt.date_to, @gantt.date_from, @gantt.date_to, @gantt.date_from, @gantt.date_to]
  316. )
  317. # Versions
  318. events += Version.find(:all, :include => :project,
  319. :conditions => ["(#{@query.project_statement}) AND effective_date BETWEEN ? AND ?", @gantt.date_from, @gantt.date_to])
  320. @gantt.events = events
  321. end
  322. respond_to do |format|
  323. format.html { render :template => "issues/gantt.rhtml", :layout => !request.xhr? }
  324. format.png { send_data(@gantt.to_image, :disposition => 'inline', :type => 'image/png', :filename => "#{@project.identifier}-gantt.png") } if @gantt.respond_to?('to_image')
  325. format.pdf { send_data(gantt_to_pdf(@gantt, @project), :type => 'application/pdf', :filename => "#{@project.nil? ? '' : "#{@project.identifier}-" }gantt.pdf") }
  326. end
  327. end
  328. def calendar
  329. if params[:year] and params[:year].to_i > 1900
  330. @year = params[:year].to_i
  331. if params[:month] and params[:month].to_i > 0 and params[:month].to_i < 13
  332. @month = params[:month].to_i
  333. end
  334. end
  335. @year ||= Date.today.year
  336. @month ||= Date.today.month
  337. @calendar = Redmine::Helpers::Calendar.new(Date.civil(@year, @month, 1), current_language, :month)
  338. retrieve_query
  339. if @query.valid?
  340. events = []
  341. events += Issue.find(:all,
  342. :include => [:tracker, :status, :assigned_to, :priority, :project],
  343. :conditions => ["(#{@query.statement}) AND ((start_date BETWEEN ? AND ?) OR (due_date BETWEEN ? AND ?))", @calendar.startdt, @calendar.enddt, @calendar.startdt, @calendar.enddt]
  344. )
  345. events += Version.find(:all, :include => :project,
  346. :conditions => ["(#{@query.project_statement}) AND effective_date BETWEEN ? AND ?", @calendar.startdt, @calendar.enddt])
  347. @calendar.events = events
  348. end
  349. render :layout => false if request.xhr?
  350. end
  351. def context_menu
  352. @issues = Issue.find_all_by_id(params[:ids], :include => :project)
  353. if (@issues.size == 1)
  354. @issue = @issues.first
  355. @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
  356. end
  357. projects = @issues.collect(&:project).compact.uniq
  358. @project = projects.first if projects.size == 1
  359. @can = {:edit => (@project && User.current.allowed_to?(:edit_issues, @project)),
  360. :log_time => (@project && User.current.allowed_to?(:log_time, @project)),
  361. :update => (@project && (User.current.allowed_to?(:edit_issues, @project) || (User.current.allowed_to?(:change_status, @project) && @allowed_statuses && !@allowed_statuses.empty?))),
  362. :move => (@project && User.current.allowed_to?(:move_issues, @project)),
  363. :copy => (@issue && @project.trackers.include?(@issue.tracker) && User.current.allowed_to?(:add_issues, @project)),
  364. :delete => (@project && User.current.allowed_to?(:delete_issues, @project))
  365. }
  366. if @project
  367. @assignables = @project.assignable_users
  368. @assignables << @issue.assigned_to if @issue && @issue.assigned_to && !@assignables.include?(@issue.assigned_to)
  369. end
  370. @priorities = Enumeration.get_values('IPRI').reverse
  371. @statuses = IssueStatus.find(:all, :order => 'position')
  372. @back = request.env['HTTP_REFERER']
  373. render :layout => false
  374. end
  375. def update_form
  376. @issue = Issue.new(params[:issue])
  377. render :action => :new, :layout => false
  378. end
  379. def preview
  380. @issue = @project.issues.find_by_id(params[:id]) unless params[:id].blank?
  381. @attachements = @issue.attachments if @issue
  382. @text = params[:notes] || (params[:issue] ? params[:issue][:description] : nil)
  383. render :partial => 'common/preview'
  384. end
  385. private
  386. def find_issue
  387. @issue = Issue.find(params[:id], :include => [:project, :tracker, :status, :author, :priority, :category])
  388. @project = @issue.project
  389. rescue ActiveRecord::RecordNotFound
  390. render_404
  391. end
  392. # Filter for bulk operations
  393. def find_issues
  394. @issues = Issue.find_all_by_id(params[:id] || params[:ids])
  395. raise ActiveRecord::RecordNotFound if @issues.empty?
  396. projects = @issues.collect(&:project).compact.uniq
  397. if projects.size == 1
  398. @project = projects.first
  399. else
  400. # TODO: let users bulk edit/move/destroy issues from different projects
  401. render_error 'Can not bulk edit/move/destroy issues from different projects' and return false
  402. end
  403. rescue ActiveRecord::RecordNotFound
  404. render_404
  405. end
  406. def find_project
  407. @project = Project.find(params[:project_id])
  408. rescue ActiveRecord::RecordNotFound
  409. render_404
  410. end
  411. def find_optional_project
  412. @project = Project.find(params[:project_id]) unless params[:project_id].blank?
  413. allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
  414. allowed ? true : deny_access
  415. rescue ActiveRecord::RecordNotFound
  416. render_404
  417. end
  418. # Retrieve query from session or build a new query
  419. def retrieve_query
  420. if !params[:query_id].blank?
  421. cond = "project_id IS NULL"
  422. cond << " OR project_id = #{@project.id}" if @project
  423. @query = Query.find(params[:query_id], :conditions => cond)
  424. @query.project = @project
  425. session[:query] = {:id => @query.id, :project_id => @query.project_id}
  426. else
  427. if params[:set_filter] || session[:query].nil? || session[:query][:project_id] != (@project ? @project.id : nil)
  428. # Give it a name, required to be valid
  429. @query = Query.new(:name => "_")
  430. @query.project = @project
  431. if params[:fields] and params[:fields].is_a? Array
  432. params[:fields].each do |field|
  433. @query.add_filter(field, params[:operators][field], params[:values][field])
  434. end
  435. else
  436. @query.available_filters.keys.each do |field|
  437. @query.add_short_filter(field, params[field]) if params[field]
  438. end
  439. end
  440. session[:query] = {:project_id => @query.project_id, :filters => @query.filters}
  441. else
  442. @query = Query.find_by_id(session[:query][:id]) if session[:query][:id]
  443. @query ||= Query.new(:name => "_", :project => @project, :filters => session[:query][:filters])
  444. @query.project = @project
  445. end
  446. end
  447. end
  448. end