Project

General

Profile

Feature #152 ยป projects_controller.rb

put in /redmine/app/controllers/ - Patrick Talbot, 09/17/2010 06:44 AM

 
1
# Redmine - project management software
2
# Copyright (C) 2006-2009  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

    
18
class ProjectsController < ApplicationController
19
  menu_item :overview
20
  menu_item :activity, :only => :activity
21
  menu_item :roadmap, :only => :roadmap
22
  menu_item :files, :only => [:list_files, :add_file]
23
  menu_item :settings, :only => :settings
24
  
25
  before_filter :find_project, :except => [ :index, :list, :add, :copy, :activity ]
26
  before_filter :find_optional_project, :only => :activity
27
  before_filter :authorize, :except => [ :index, :list, :add, :copy, :archive, :unarchive, :destroy, :activity ]
28
  before_filter :authorize_global, :only => :add
29
  before_filter :require_admin, :only => [ :copy, :archive, :unarchive, :destroy ]
30
  accept_key_auth :activity
31
  
32
  after_filter :only => [:add, :edit, :archive, :unarchive, :destroy] do |controller|
33
    if controller.request.post?
34
      controller.send :expire_action, :controller => 'welcome', :action => 'robots.txt'
35
    end
36
  end
37
  
38
  helper :sort
39
  include SortHelper
40
  helper :custom_fields
41
  include CustomFieldsHelper   
42
  helper :issues
43
  helper IssuesHelper
44
  helper :queries
45
  include QueriesHelper
46
  helper :repositories
47
  include RepositoriesHelper
48
  include ProjectsHelper
49
  
50
  # Lists visible projects
51
  def index
52
    respond_to do |format|
53
      format.html { 
54
        @projects = Project.visible.find(:all, :order => 'lft') 
55
      }
56
      format.atom {
57
        projects = Project.visible.find(:all, :order => 'created_on DESC',
58
                                              :limit => Setting.feeds_limit.to_i)
59
        render_feed(projects, :title => "#{Setting.app_title}: #{l(:label_project_latest)}")
60
      }
61
    end
62
  end
63
  
64
  # Add a new project
65
  def add
66
    @issue_custom_fields = IssueCustomField.find(:all, :order => "#{CustomField.table_name}.position")
67
    @trackers = Tracker.all
68
    @project = Project.new(params[:project])
69
    if request.get?
70
      @project.identifier = Project.next_identifier if Setting.sequential_project_identifiers?
71
      @project.trackers = Tracker.all
72
      @project.is_public = Setting.default_projects_public?
73
      @project.enabled_module_names = Setting.default_projects_modules
74
    else
75
      @project.enabled_module_names = params[:enabled_modules]
76
      if validate_parent_id && @project.save
77
        @project.set_allowed_parent!(params[:project]['parent_id']) if params[:project].has_key?('parent_id')
78
        # Add current user as a project member if he is not admin
79
        unless User.current.admin?
80
          r = Role.givable.find_by_id(Setting.new_project_user_role_id.to_i) || Role.givable.first
81
          m = Member.new(:user => User.current, :roles => [r])
82
          @project.members << m
83
        end
84
        flash[:notice] = l(:notice_successful_create)
85
        redirect_to :controller => 'projects', :action => 'settings', :id => @project
86
      end
87
    end	
88
  end
89
  
90
  def copy
91
    @issue_custom_fields = IssueCustomField.find(:all, :order => "#{CustomField.table_name}.position")
92
    @trackers = Tracker.all
93
    @root_projects = Project.find(:all,
94
                                  :conditions => "parent_id IS NULL AND status = #{Project::STATUS_ACTIVE}",
95
                                  :order => 'name')
96
    @source_project = Project.find(params[:id])
97
    if request.get?
98
      @project = Project.copy_from(@source_project)
99
      if @project
100
        @project.identifier = Project.next_identifier if Setting.sequential_project_identifiers?
101
      else
102
        redirect_to :controller => 'admin', :action => 'projects'
103
      end  
104
    else
105
      Mailer.with_deliveries(params[:notifications] == '1') do
106
        @project = Project.new(params[:project])
107
        @project.enabled_module_names = params[:enabled_modules]
108
        if validate_parent_id && @project.copy(@source_project, :only => params[:only])
109
          @project.set_allowed_parent!(params[:project]['parent_id']) if params[:project].has_key?('parent_id')
110
          flash[:notice] = l(:notice_successful_create)
111
          redirect_to :controller => 'admin', :action => 'projects'
112
        elsif !@project.new_record?
113
          # Project was created
114
          # But some objects were not copied due to validation failures
115
          # (eg. issues from disabled trackers)
116
          # TODO: inform about that
117
          redirect_to :controller => 'admin', :action => 'projects'
118
        end
119
      end
120
    end
121
  rescue ActiveRecord::RecordNotFound
122
    redirect_to :controller => 'admin', :action => 'projects'
123
  end
124
	
125
  # Show @project
126
  def show
127
    if params[:jump]
128
      # try to redirect to the requested menu item
129
      redirect_to_project_menu_item(@project, params[:jump]) && return
130
    end
131
    
132
    @users_by_role = @project.users_by_role
133
    @subprojects = @project.children.visible
134
    @news = @project.news.find(:all, :limit => 5, :include => [ :author, :project ], :order => "#{News.table_name}.created_on DESC")
135
    @trackers = @project.rolled_up_trackers
136
    
137
    cond = @project.project_condition(Setting.display_subprojects_issues?)
138
    
139
    @open_issues_by_tracker = Issue.visible.count(:group => :tracker,
140
                                            :include => [:project, :status, :tracker],
141
                                            :conditions => ["(#{cond}) AND #{IssueStatus.table_name}.is_closed=?", false])
142
    @total_issues_by_tracker = Issue.visible.count(:group => :tracker,
143
                                            :include => [:project, :status, :tracker],
144
                                            :conditions => cond)
145
    
146
    TimeEntry.visible_by(User.current) do
147
      @total_hours = TimeEntry.sum(:hours, 
148
                                   :include => :project,
149
                                   :conditions => cond).to_f
150
    end
151
    @key = User.current.rss_key
152
  end
153

    
154
  def settings
155
    @issue_custom_fields = IssueCustomField.find(:all, :order => "#{CustomField.table_name}.position")
156
    @issue_category ||= IssueCategory.new
157
    @member ||= @project.members.new
158
    @trackers = Tracker.all
159
    @repository ||= @project.repository
160
    @wiki ||= @project.wiki
161
  end
162
  
163
  # Edit @project
164
  def edit
165
    if request.post?
166
      @project.attributes = params[:project]
167
      if validate_parent_id && @project.save
168
        @project.set_allowed_parent!(params[:project]['parent_id']) if params[:project].has_key?('parent_id')
169
        flash[:notice] = l(:notice_successful_update)
170
        redirect_to :action => 'settings', :id => @project
171
      else
172
        settings
173
        render :action => 'settings'
174
      end
175
    end
176
  end
177
  
178
  def modules
179
    @project.enabled_module_names = params[:enabled_modules]
180
    redirect_to :action => 'settings', :id => @project, :tab => 'modules'
181
  end
182

    
183
  def archive
184
    if request.post?
185
      unless @project.archive
186
        flash[:error] = l(:error_can_not_archive_project)
187
      end
188
    end
189
    redirect_to(url_for(:controller => 'admin', :action => 'projects', :status => params[:status]))
190
  end
191
  
192
  def unarchive
193
    @project.unarchive if request.post? && !@project.active?
194
    redirect_to(url_for(:controller => 'admin', :action => 'projects', :status => params[:status]))
195
  end
196
  
197
  # Delete @project
198
  def destroy
199
    @project_to_destroy = @project
200
    if request.post? and params[:confirm]
201
      @project_to_destroy.destroy
202
      redirect_to :controller => 'admin', :action => 'projects'
203
    end
204
    # hide project in layout
205
    @project = nil
206
  end
207
	
208
  # Add a new issue category to @project
209
  def add_issue_category
210
    @category = @project.issue_categories.build(params[:category])
211
    if request.post?
212
      if @category.save
213
    	  respond_to do |format|
214
          format.html do
215
            flash[:notice] = l(:notice_successful_create)
216
            redirect_to :action => 'settings', :tab => 'categories', :id => @project
217
          end
218
          format.js do
219
            # IE doesn't support the replace_html rjs method for select box options
220
            render(:update) {|page| page.replace "issue_category_id",
221
              content_tag('select', '<option></option>' + options_from_collection_for_select(@project.issue_categories, 'id', 'name', @category.id), :id => 'issue_category_id', :name => 'issue[category_id]')
222
            }
223
          end
224
        end
225
      else
226
        respond_to do |format|
227
          format.html
228
          format.js do
229
            render(:update) {|page| page.alert(@category.errors.full_messages.join('\n')) }
230
          end
231
        end
232
      end
233
    end
234
  end
235
	
236
  # Add a new version to @project
237
  def add_version
238
    @version = @project.versions.build
239
    if params[:version]
240
      attributes = params[:version].dup
241
      attributes.delete('sharing') unless attributes.nil? || @version.allowed_sharings.include?(attributes['sharing'])
242
      @version.attributes = attributes
243
    end
244
  	if request.post?
245
  	  if @version.save
246
        respond_to do |format|
247
          format.html do
248
            flash[:notice] = l(:notice_successful_create)
249
            redirect_to :action => 'settings', :tab => 'versions', :id => @project
250
          end
251
          format.js do
252
            # IE doesn't support the replace_html rjs method for select box options
253
            render(:update) {|page| page.replace "issue_fixed_version_id",
254
              content_tag('select', '<option></option>' + version_options_for_select(@project.shared_versions.open, @version), :id => 'issue_fixed_version_id', :name => 'issue[fixed_version_id]')
255
            }
256
          end
257
        end
258
      else
259
        respond_to do |format|
260
          format.html
261
          format.js do
262
            render(:update) {|page| page.alert(@version.errors.full_messages.join('\n')) }
263
          end
264
        end
265
  	  end
266
  	end
267
  end
268

    
269
  def add_file
270
    if request.post?
271
      container = (params[:version_id].blank? ? @project : @project.versions.find_by_id(params[:version_id]))
272
      attachments = attach_files(container, params[:attachments])
273
      if !attachments.empty? && Setting.notified_events.include?('file_added')
274
        Mailer.deliver_attachments_added(attachments)
275
      end
276
      redirect_to :controller => 'projects', :action => 'list_files', :id => @project
277
      return
278
    end
279
    @versions = @project.versions.sort
280
  end
281

    
282
  def save_activities
283
    if request.post? && params[:enumerations]
284
      Project.transaction do
285
        params[:enumerations].each do |id, activity|
286
          @project.update_or_create_time_entry_activity(id, activity)
287
        end
288
      end
289
    end
290
    
291
    redirect_to :controller => 'projects', :action => 'settings', :tab => 'activities', :id => @project
292
  end
293

    
294
  def reset_activities
295
    @project.time_entry_activities.each do |time_entry_activity|
296
      time_entry_activity.destroy(time_entry_activity.parent)
297
    end
298
    redirect_to :controller => 'projects', :action => 'settings', :tab => 'activities', :id => @project
299
  end
300
  
301
  def list_files
302
    sort_init 'created_on', 'desc'
303
    sort_update 'filename' => "#{Attachment.table_name}.filename",
304
    		'description' => "#{Attachment.table_name}.description",
305
                'created_on' => "#{Attachment.table_name}.created_on",
306
                'size' => "#{Attachment.table_name}.filesize",
307
                'downloads' => "#{Attachment.table_name}.downloads"
308
                
309
    @containers = [ Project.find(@project.id, :include => :attachments, :order => sort_clause)]
310
    @containers += @project.versions.find(:all, :include => :attachments, :order => sort_clause).sort.reverse
311
    render :layout => !request.xhr?
312
  end
313

    
314
  def roadmap
315
    @trackers = @project.trackers.find(:all, :order => 'position')
316
    retrieve_selected_tracker_ids(@trackers, @trackers.select {|t| t.is_in_roadmap?})
317
    @with_subprojects = params[:with_subprojects].nil? ? Setting.display_subprojects_issues? : (params[:with_subprojects] == '1')
318
    project_ids = @with_subprojects ? @project.self_and_descendants.collect(&:id) : [@project.id]
319
    
320
    @versions = @project.shared_versions.sort
321
    @versions.reject! {|version| version.closed? || version.completed? } unless params[:completed]
322
    
323
    @issues_by_version = {}
324
    unless @selected_tracker_ids.empty?
325
      @versions.each do |version|
326
        issues = version.fixed_issues.visible.find(:all,
327
                                                   :include => [:project, :status, :tracker, :priority],
328
                                                   :conditions => {:tracker_id => @selected_tracker_ids, :project_id => project_ids},
329
                                                   :order => "#{Project.table_name}.lft, #{Tracker.table_name}.position, #{Issue.table_name}.id")
330
        @issues_by_version[version] = issues
331
      end
332
    end
333
    @versions.reject! {|version| !project_ids.include?(version.project_id) && @issues_by_version[version].empty?}
334
  end
335
  
336
  def activity
337
    @days = Setting.activity_days_default.to_i
338
    
339
    if params[:from]
340
      begin; @date_to = params[:from].to_date + 1; rescue; end
341
    end
342

    
343
    @date_to ||= Date.today + 1
344
    @date_from = @date_to - @days
345
    @with_subprojects = params[:with_subprojects].nil? ? Setting.display_subprojects_issues? : (params[:with_subprojects] == '1')
346
    @author = (params[:user_id].blank? ? nil : User.active.find(params[:user_id]))
347
    
348
    @activity = Redmine::Activity::Fetcher.new(User.current, :project => @project, 
349
                                                             :with_subprojects => @with_subprojects,
350
                                                             :author => @author)
351
    @activity.scope_select {|t| !params["show_#{t}"].nil?}
352
    @activity.scope = (@author.nil? ? :default : :all) if @activity.scope.empty?
353

    
354
    events = @activity.events(@date_from, @date_to)
355
    
356
    if events.empty? || stale?(:etag => [events.first, User.current])
357
      respond_to do |format|
358
        format.html { 
359
          @events_by_day = events.group_by(&:event_date)
360
          render :layout => false if request.xhr?
361
        }
362
        format.atom {
363
          title = l(:label_activity)
364
          if @author
365
            title = @author.name
366
          elsif @activity.scope.size == 1
367
            title = l("label_#{@activity.scope.first.singularize}_plural")
368
          end
369
          render_feed(events, :title => "#{@project || Setting.app_title}: #{title}")
370
        }
371
      end
372
    end
373
    
374
  rescue ActiveRecord::RecordNotFound
375
    render_404
376
  end
377
  
378
private
379
  # Find project of id params[:id]
380
  # if not found, redirect to project list
381
  # Used as a before_filter
382
  def find_project
383
    @project = Project.find(params[:id])
384
  rescue ActiveRecord::RecordNotFound
385
    render_404
386
  end
387
  
388
  def find_optional_project
389
    return true unless params[:id]
390
    @project = Project.find(params[:id])
391
    authorize
392
  rescue ActiveRecord::RecordNotFound
393
    render_404
394
  end
395

    
396
  def retrieve_selected_tracker_ids(selectable_trackers, default_trackers=nil)
397
    if ids = params[:tracker_ids]
398
      @selected_tracker_ids = (ids.is_a? Array) ? ids.collect { |id| id.to_i.to_s } : ids.split('/').collect { |id| id.to_i.to_s }
399
    else
400
      @selected_tracker_ids = (default_trackers || selectable_trackers).collect {|t| t.id.to_s }
401
    end
402
  end
403
  
404
  # Validates parent_id param according to user's permissions
405
  # TODO: move it to Project model in a validation that depends on User.current
406
  def validate_parent_id
407
    return true if User.current.admin?
408
    parent_id = params[:project] && params[:project][:parent_id]
409
    if parent_id || @project.new_record?
410
      parent = parent_id.blank? ? nil : Project.find_by_id(parent_id.to_i)
411
      unless @project.allowed_parents.include?(parent)
412
        @project.errors.add :parent_id, :invalid
413
        return false
414
      end
415
    end
416
    true
417
  end
418
end
    (1-1/1)