annotate .svn/pristine/05/05f81f90a3570490e6ea8a94e643c12e2ec9cbe3.svn-base @ 1471:d65e60e20a50 bug_531

Close obsolete branch bug_531
author Chris Cannam
date Fri, 23 Nov 2012 18:10:33 +0000
parents cbb26bc654de
children
rev   line source
Chris@909 1 # Redmine - project management software
Chris@909 2 # Copyright (C) 2006-2011 Jean-Philippe Lang
Chris@909 3 #
Chris@909 4 # This program is free software; you can redistribute it and/or
Chris@909 5 # modify it under the terms of the GNU General Public License
Chris@909 6 # as published by the Free Software Foundation; either version 2
Chris@909 7 # of the License, or (at your option) any later version.
Chris@909 8 #
Chris@909 9 # This program is distributed in the hope that it will be useful,
Chris@909 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
Chris@909 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Chris@909 12 # GNU General Public License for more details.
Chris@909 13 #
Chris@909 14 # You should have received a copy of the GNU General Public License
Chris@909 15 # along with this program; if not, write to the Free Software
Chris@909 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Chris@909 17
Chris@909 18 class Project < ActiveRecord::Base
Chris@909 19 include Redmine::SafeAttributes
Chris@909 20
Chris@909 21 # Project statuses
Chris@909 22 STATUS_ACTIVE = 1
Chris@909 23 STATUS_ARCHIVED = 9
Chris@909 24
Chris@909 25 # Maximum length for project identifiers
Chris@909 26 IDENTIFIER_MAX_LENGTH = 100
Chris@909 27
Chris@909 28 # Specific overidden Activities
Chris@909 29 has_many :time_entry_activities
Chris@909 30 has_many :members, :include => [:user, :roles], :conditions => "#{User.table_name}.type='User' AND #{User.table_name}.status=#{User::STATUS_ACTIVE}"
Chris@909 31 has_many :memberships, :class_name => 'Member'
Chris@909 32 has_many :member_principals, :class_name => 'Member',
Chris@909 33 :include => :principal,
Chris@909 34 :conditions => "#{Principal.table_name}.type='Group' OR (#{Principal.table_name}.type='User' AND #{Principal.table_name}.status=#{User::STATUS_ACTIVE})"
Chris@909 35 has_many :users, :through => :members
Chris@909 36 has_many :principals, :through => :member_principals, :source => :principal
Chris@909 37
Chris@909 38 has_many :enabled_modules, :dependent => :delete_all
Chris@909 39 has_and_belongs_to_many :trackers, :order => "#{Tracker.table_name}.position"
Chris@909 40 has_many :issues, :dependent => :destroy, :order => "#{Issue.table_name}.created_on DESC", :include => [:status, :tracker]
Chris@909 41 has_many :issue_changes, :through => :issues, :source => :journals
Chris@909 42 has_many :versions, :dependent => :destroy, :order => "#{Version.table_name}.effective_date DESC, #{Version.table_name}.name DESC"
Chris@909 43 has_many :time_entries, :dependent => :delete_all
Chris@909 44 has_many :queries, :dependent => :delete_all
Chris@909 45 has_many :documents, :dependent => :destroy
Chris@909 46 has_many :news, :dependent => :destroy, :include => :author
Chris@909 47 has_many :issue_categories, :dependent => :delete_all, :order => "#{IssueCategory.table_name}.name"
Chris@909 48 has_many :boards, :dependent => :destroy, :order => "position ASC"
Chris@909 49 has_one :repository, :dependent => :destroy
Chris@909 50 has_many :changesets, :through => :repository
Chris@909 51 has_one :wiki, :dependent => :destroy
Chris@909 52 # Custom field for the project issues
Chris@909 53 has_and_belongs_to_many :issue_custom_fields,
Chris@909 54 :class_name => 'IssueCustomField',
Chris@909 55 :order => "#{CustomField.table_name}.position",
Chris@909 56 :join_table => "#{table_name_prefix}custom_fields_projects#{table_name_suffix}",
Chris@909 57 :association_foreign_key => 'custom_field_id'
Chris@909 58
Chris@909 59 acts_as_nested_set :order => 'name', :dependent => :destroy
Chris@909 60 acts_as_attachable :view_permission => :view_files,
Chris@909 61 :delete_permission => :manage_files
Chris@909 62
Chris@909 63 acts_as_customizable
Chris@909 64 acts_as_searchable :columns => ['name', 'identifier', 'description'], :project_key => 'id', :permission => nil
Chris@909 65 acts_as_event :title => Proc.new {|o| "#{l(:label_project)}: #{o.name}"},
Chris@909 66 :url => Proc.new {|o| {:controller => 'projects', :action => 'show', :id => o}},
Chris@909 67 :author => nil
Chris@909 68
Chris@909 69 attr_protected :status
Chris@909 70
Chris@909 71 validates_presence_of :name, :identifier
Chris@909 72 validates_uniqueness_of :identifier
Chris@909 73 validates_associated :repository, :wiki
Chris@909 74 validates_length_of :name, :maximum => 255
Chris@909 75 validates_length_of :homepage, :maximum => 255
Chris@909 76 validates_length_of :identifier, :in => 1..IDENTIFIER_MAX_LENGTH
Chris@909 77 # donwcase letters, digits, dashes but not digits only
Chris@909 78 validates_format_of :identifier, :with => /^(?!\d+$)[a-z0-9\-]*$/, :if => Proc.new { |p| p.identifier_changed? }
Chris@909 79 # reserved words
Chris@909 80 validates_exclusion_of :identifier, :in => %w( new )
Chris@909 81
Chris@909 82 before_destroy :delete_all_members
Chris@909 83
Chris@909 84 named_scope :has_module, lambda { |mod| { :conditions => ["#{Project.table_name}.id IN (SELECT em.project_id FROM #{EnabledModule.table_name} em WHERE em.name=?)", mod.to_s] } }
Chris@909 85 named_scope :active, { :conditions => "#{Project.table_name}.status = #{STATUS_ACTIVE}"}
Chris@909 86 named_scope :all_public, { :conditions => { :is_public => true } }
Chris@909 87 named_scope :visible, lambda {|*args| {:conditions => Project.visible_condition(args.shift || User.current, *args) }}
Chris@909 88
Chris@909 89 def initialize(attributes = nil)
Chris@909 90 super
Chris@909 91
Chris@909 92 initialized = (attributes || {}).stringify_keys
Chris@909 93 if !initialized.key?('identifier') && Setting.sequential_project_identifiers?
Chris@909 94 self.identifier = Project.next_identifier
Chris@909 95 end
Chris@909 96 if !initialized.key?('is_public')
Chris@909 97 self.is_public = Setting.default_projects_public?
Chris@909 98 end
Chris@909 99 if !initialized.key?('enabled_module_names')
Chris@909 100 self.enabled_module_names = Setting.default_projects_modules
Chris@909 101 end
Chris@909 102 if !initialized.key?('trackers') && !initialized.key?('tracker_ids')
Chris@909 103 self.trackers = Tracker.all
Chris@909 104 end
Chris@909 105 end
Chris@909 106
Chris@909 107 def identifier=(identifier)
Chris@909 108 super unless identifier_frozen?
Chris@909 109 end
Chris@909 110
Chris@909 111 def identifier_frozen?
Chris@909 112 errors[:identifier].nil? && !(new_record? || identifier.blank?)
Chris@909 113 end
Chris@909 114
Chris@909 115 # returns latest created projects
Chris@909 116 # non public projects will be returned only if user is a member of those
Chris@909 117 def self.latest(user=nil, count=5)
Chris@909 118 visible(user).find(:all, :limit => count, :order => "created_on DESC")
Chris@909 119 end
Chris@909 120
Chris@909 121 # Returns true if the project is visible to +user+ or to the current user.
Chris@909 122 def visible?(user=User.current)
Chris@909 123 user.allowed_to?(:view_project, self)
Chris@909 124 end
Chris@909 125
Chris@909 126 # Returns a SQL conditions string used to find all projects visible by the specified user.
Chris@909 127 #
Chris@909 128 # Examples:
Chris@909 129 # Project.visible_condition(admin) => "projects.status = 1"
Chris@909 130 # Project.visible_condition(normal_user) => "((projects.status = 1) AND (projects.is_public = 1 OR projects.id IN (1,3,4)))"
Chris@909 131 # Project.visible_condition(anonymous) => "((projects.status = 1) AND (projects.is_public = 1))"
Chris@909 132 def self.visible_condition(user, options={})
Chris@909 133 allowed_to_condition(user, :view_project, options)
Chris@909 134 end
Chris@909 135
Chris@909 136 # Returns a SQL conditions string used to find all projects for which +user+ has the given +permission+
Chris@909 137 #
Chris@909 138 # Valid options:
Chris@909 139 # * :project => limit the condition to project
Chris@909 140 # * :with_subprojects => limit the condition to project and its subprojects
Chris@909 141 # * :member => limit the condition to the user projects
Chris@909 142 def self.allowed_to_condition(user, permission, options={})
Chris@909 143 base_statement = "#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"
Chris@909 144 if perm = Redmine::AccessControl.permission(permission)
Chris@909 145 unless perm.project_module.nil?
Chris@909 146 # If the permission belongs to a project module, make sure the module is enabled
Chris@909 147 base_statement << " AND #{Project.table_name}.id IN (SELECT em.project_id FROM #{EnabledModule.table_name} em WHERE em.name='#{perm.project_module}')"
Chris@909 148 end
Chris@909 149 end
Chris@909 150 if options[:project]
Chris@909 151 project_statement = "#{Project.table_name}.id = #{options[:project].id}"
Chris@909 152 project_statement << " OR (#{Project.table_name}.lft > #{options[:project].lft} AND #{Project.table_name}.rgt < #{options[:project].rgt})" if options[:with_subprojects]
Chris@909 153 base_statement = "(#{project_statement}) AND (#{base_statement})"
Chris@909 154 end
Chris@909 155
Chris@909 156 if user.admin?
Chris@909 157 base_statement
Chris@909 158 else
Chris@909 159 statement_by_role = {}
Chris@909 160 unless options[:member]
Chris@909 161 role = user.logged? ? Role.non_member : Role.anonymous
Chris@909 162 if role.allowed_to?(permission)
Chris@909 163 statement_by_role[role] = "#{Project.table_name}.is_public = #{connection.quoted_true}"
Chris@909 164 end
Chris@909 165 end
Chris@909 166 if user.logged?
Chris@909 167 user.projects_by_role.each do |role, projects|
Chris@909 168 if role.allowed_to?(permission)
Chris@909 169 statement_by_role[role] = "#{Project.table_name}.id IN (#{projects.collect(&:id).join(',')})"
Chris@909 170 end
Chris@909 171 end
Chris@909 172 end
Chris@909 173 if statement_by_role.empty?
Chris@909 174 "1=0"
Chris@909 175 else
Chris@909 176 if block_given?
Chris@909 177 statement_by_role.each do |role, statement|
Chris@909 178 if s = yield(role, user)
Chris@909 179 statement_by_role[role] = "(#{statement} AND (#{s}))"
Chris@909 180 end
Chris@909 181 end
Chris@909 182 end
Chris@909 183 "((#{base_statement}) AND (#{statement_by_role.values.join(' OR ')}))"
Chris@909 184 end
Chris@909 185 end
Chris@909 186 end
Chris@909 187
Chris@909 188 # Returns the Systemwide and project specific activities
Chris@909 189 def activities(include_inactive=false)
Chris@909 190 if include_inactive
Chris@909 191 return all_activities
Chris@909 192 else
Chris@909 193 return active_activities
Chris@909 194 end
Chris@909 195 end
Chris@909 196
Chris@909 197 # Will create a new Project specific Activity or update an existing one
Chris@909 198 #
Chris@909 199 # This will raise a ActiveRecord::Rollback if the TimeEntryActivity
Chris@909 200 # does not successfully save.
Chris@909 201 def update_or_create_time_entry_activity(id, activity_hash)
Chris@909 202 if activity_hash.respond_to?(:has_key?) && activity_hash.has_key?('parent_id')
Chris@909 203 self.create_time_entry_activity_if_needed(activity_hash)
Chris@909 204 else
Chris@909 205 activity = project.time_entry_activities.find_by_id(id.to_i)
Chris@909 206 activity.update_attributes(activity_hash) if activity
Chris@909 207 end
Chris@909 208 end
Chris@909 209
Chris@909 210 # Create a new TimeEntryActivity if it overrides a system TimeEntryActivity
Chris@909 211 #
Chris@909 212 # This will raise a ActiveRecord::Rollback if the TimeEntryActivity
Chris@909 213 # does not successfully save.
Chris@909 214 def create_time_entry_activity_if_needed(activity)
Chris@909 215 if activity['parent_id']
Chris@909 216
Chris@909 217 parent_activity = TimeEntryActivity.find(activity['parent_id'])
Chris@909 218 activity['name'] = parent_activity.name
Chris@909 219 activity['position'] = parent_activity.position
Chris@909 220
Chris@909 221 if Enumeration.overridding_change?(activity, parent_activity)
Chris@909 222 project_activity = self.time_entry_activities.create(activity)
Chris@909 223
Chris@909 224 if project_activity.new_record?
Chris@909 225 raise ActiveRecord::Rollback, "Overridding TimeEntryActivity was not successfully saved"
Chris@909 226 else
Chris@909 227 self.time_entries.update_all("activity_id = #{project_activity.id}", ["activity_id = ?", parent_activity.id])
Chris@909 228 end
Chris@909 229 end
Chris@909 230 end
Chris@909 231 end
Chris@909 232
Chris@909 233 # Returns a :conditions SQL string that can be used to find the issues associated with this project.
Chris@909 234 #
Chris@909 235 # Examples:
Chris@909 236 # project.project_condition(true) => "(projects.id = 1 OR (projects.lft > 1 AND projects.rgt < 10))"
Chris@909 237 # project.project_condition(false) => "projects.id = 1"
Chris@909 238 def project_condition(with_subprojects)
Chris@909 239 cond = "#{Project.table_name}.id = #{id}"
Chris@909 240 cond = "(#{cond} OR (#{Project.table_name}.lft > #{lft} AND #{Project.table_name}.rgt < #{rgt}))" if with_subprojects
Chris@909 241 cond
Chris@909 242 end
Chris@909 243
Chris@909 244 def self.find(*args)
Chris@909 245 if args.first && args.first.is_a?(String) && !args.first.match(/^\d*$/)
Chris@909 246 project = find_by_identifier(*args)
Chris@909 247 raise ActiveRecord::RecordNotFound, "Couldn't find Project with identifier=#{args.first}" if project.nil?
Chris@909 248 project
Chris@909 249 else
Chris@909 250 super
Chris@909 251 end
Chris@909 252 end
Chris@909 253
Chris@909 254 def to_param
Chris@909 255 # id is used for projects with a numeric identifier (compatibility)
Chris@909 256 @to_param ||= (identifier.to_s =~ %r{^\d*$} ? id : identifier)
Chris@909 257 end
Chris@909 258
Chris@909 259 def active?
Chris@909 260 self.status == STATUS_ACTIVE
Chris@909 261 end
Chris@909 262
Chris@909 263 def archived?
Chris@909 264 self.status == STATUS_ARCHIVED
Chris@909 265 end
Chris@909 266
Chris@909 267 # Archives the project and its descendants
Chris@909 268 def archive
Chris@909 269 # Check that there is no issue of a non descendant project that is assigned
Chris@909 270 # to one of the project or descendant versions
Chris@909 271 v_ids = self_and_descendants.collect {|p| p.version_ids}.flatten
Chris@909 272 if v_ids.any? && Issue.find(:first, :include => :project,
Chris@909 273 :conditions => ["(#{Project.table_name}.lft < ? OR #{Project.table_name}.rgt > ?)" +
Chris@909 274 " AND #{Issue.table_name}.fixed_version_id IN (?)", lft, rgt, v_ids])
Chris@909 275 return false
Chris@909 276 end
Chris@909 277 Project.transaction do
Chris@909 278 archive!
Chris@909 279 end
Chris@909 280 true
Chris@909 281 end
Chris@909 282
Chris@909 283 # Unarchives the project
Chris@909 284 # All its ancestors must be active
Chris@909 285 def unarchive
Chris@909 286 return false if ancestors.detect {|a| !a.active?}
Chris@909 287 update_attribute :status, STATUS_ACTIVE
Chris@909 288 end
Chris@909 289
Chris@909 290 # Returns an array of projects the project can be moved to
Chris@909 291 # by the current user
Chris@909 292 def allowed_parents
Chris@909 293 return @allowed_parents if @allowed_parents
Chris@909 294 @allowed_parents = Project.find(:all, :conditions => Project.allowed_to_condition(User.current, :add_subprojects))
Chris@909 295 @allowed_parents = @allowed_parents - self_and_descendants
Chris@909 296 if User.current.allowed_to?(:add_project, nil, :global => true) || (!new_record? && parent.nil?)
Chris@909 297 @allowed_parents << nil
Chris@909 298 end
Chris@909 299 unless parent.nil? || @allowed_parents.empty? || @allowed_parents.include?(parent)
Chris@909 300 @allowed_parents << parent
Chris@909 301 end
Chris@909 302 @allowed_parents
Chris@909 303 end
Chris@909 304
Chris@909 305 # Sets the parent of the project with authorization check
Chris@909 306 def set_allowed_parent!(p)
Chris@909 307 unless p.nil? || p.is_a?(Project)
Chris@909 308 if p.to_s.blank?
Chris@909 309 p = nil
Chris@909 310 else
Chris@909 311 p = Project.find_by_id(p)
Chris@909 312 return false unless p
Chris@909 313 end
Chris@909 314 end
Chris@909 315 if p.nil?
Chris@909 316 if !new_record? && allowed_parents.empty?
Chris@909 317 return false
Chris@909 318 end
Chris@909 319 elsif !allowed_parents.include?(p)
Chris@909 320 return false
Chris@909 321 end
Chris@909 322 set_parent!(p)
Chris@909 323 end
Chris@909 324
Chris@909 325 # Sets the parent of the project
Chris@909 326 # Argument can be either a Project, a String, a Fixnum or nil
Chris@909 327 def set_parent!(p)
Chris@909 328 unless p.nil? || p.is_a?(Project)
Chris@909 329 if p.to_s.blank?
Chris@909 330 p = nil
Chris@909 331 else
Chris@909 332 p = Project.find_by_id(p)
Chris@909 333 return false unless p
Chris@909 334 end
Chris@909 335 end
Chris@909 336 if p == parent && !p.nil?
Chris@909 337 # Nothing to do
Chris@909 338 true
Chris@909 339 elsif p.nil? || (p.active? && move_possible?(p))
Chris@909 340 # Insert the project so that target's children or root projects stay alphabetically sorted
Chris@909 341 sibs = (p.nil? ? self.class.roots : p.children)
Chris@909 342 to_be_inserted_before = sibs.detect {|c| c.name.to_s.downcase > name.to_s.downcase }
Chris@909 343 if to_be_inserted_before
Chris@909 344 move_to_left_of(to_be_inserted_before)
Chris@909 345 elsif p.nil?
Chris@909 346 if sibs.empty?
Chris@909 347 # move_to_root adds the project in first (ie. left) position
Chris@909 348 move_to_root
Chris@909 349 else
Chris@909 350 move_to_right_of(sibs.last) unless self == sibs.last
Chris@909 351 end
Chris@909 352 else
Chris@909 353 # move_to_child_of adds the project in last (ie.right) position
Chris@909 354 move_to_child_of(p)
Chris@909 355 end
Chris@909 356 Issue.update_versions_from_hierarchy_change(self)
Chris@909 357 true
Chris@909 358 else
Chris@909 359 # Can not move to the given target
Chris@909 360 false
Chris@909 361 end
Chris@909 362 end
Chris@909 363
Chris@909 364 # Returns an array of the trackers used by the project and its active sub projects
Chris@909 365 def rolled_up_trackers
Chris@909 366 @rolled_up_trackers ||=
Chris@909 367 Tracker.find(:all, :joins => :projects,
Chris@909 368 :select => "DISTINCT #{Tracker.table_name}.*",
Chris@909 369 :conditions => ["#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status = #{STATUS_ACTIVE}", lft, rgt],
Chris@909 370 :order => "#{Tracker.table_name}.position")
Chris@909 371 end
Chris@909 372
Chris@909 373 # Closes open and locked project versions that are completed
Chris@909 374 def close_completed_versions
Chris@909 375 Version.transaction do
Chris@909 376 versions.find(:all, :conditions => {:status => %w(open locked)}).each do |version|
Chris@909 377 if version.completed?
Chris@909 378 version.update_attribute(:status, 'closed')
Chris@909 379 end
Chris@909 380 end
Chris@909 381 end
Chris@909 382 end
Chris@909 383
Chris@909 384 # Returns a scope of the Versions on subprojects
Chris@909 385 def rolled_up_versions
Chris@909 386 @rolled_up_versions ||=
Chris@909 387 Version.scoped(:include => :project,
Chris@909 388 :conditions => ["#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status = #{STATUS_ACTIVE}", lft, rgt])
Chris@909 389 end
Chris@909 390
Chris@909 391 # Returns a scope of the Versions used by the project
Chris@909 392 def shared_versions
Chris@909 393 @shared_versions ||= begin
Chris@909 394 r = root? ? self : root
Chris@909 395 Version.scoped(:include => :project,
Chris@909 396 :conditions => "#{Project.table_name}.id = #{id}" +
Chris@909 397 " OR (#{Project.table_name}.status = #{Project::STATUS_ACTIVE} AND (" +
Chris@909 398 " #{Version.table_name}.sharing = 'system'" +
Chris@909 399 " OR (#{Project.table_name}.lft >= #{r.lft} AND #{Project.table_name}.rgt <= #{r.rgt} AND #{Version.table_name}.sharing = 'tree')" +
Chris@909 400 " OR (#{Project.table_name}.lft < #{lft} AND #{Project.table_name}.rgt > #{rgt} AND #{Version.table_name}.sharing IN ('hierarchy', 'descendants'))" +
Chris@909 401 " OR (#{Project.table_name}.lft > #{lft} AND #{Project.table_name}.rgt < #{rgt} AND #{Version.table_name}.sharing = 'hierarchy')" +
Chris@909 402 "))")
Chris@909 403 end
Chris@909 404 end
Chris@909 405
Chris@909 406 # Returns a hash of project users grouped by role
Chris@909 407 def users_by_role
Chris@909 408 members.find(:all, :include => [:user, :roles]).inject({}) do |h, m|
Chris@909 409 m.roles.each do |r|
Chris@909 410 h[r] ||= []
Chris@909 411 h[r] << m.user
Chris@909 412 end
Chris@909 413 h
Chris@909 414 end
Chris@909 415 end
Chris@909 416
Chris@909 417 # Deletes all project's members
Chris@909 418 def delete_all_members
Chris@909 419 me, mr = Member.table_name, MemberRole.table_name
Chris@909 420 connection.delete("DELETE FROM #{mr} WHERE #{mr}.member_id IN (SELECT #{me}.id FROM #{me} WHERE #{me}.project_id = #{id})")
Chris@909 421 Member.delete_all(['project_id = ?', id])
Chris@909 422 end
Chris@909 423
Chris@909 424 # Users/groups issues can be assigned to
Chris@909 425 def assignable_users
Chris@909 426 assignable = Setting.issue_group_assignment? ? member_principals : members
Chris@909 427 assignable.select {|m| m.roles.detect {|role| role.assignable?}}.collect {|m| m.principal}.sort
Chris@909 428 end
Chris@909 429
Chris@909 430 # Returns the mail adresses of users that should be always notified on project events
Chris@909 431 def recipients
Chris@909 432 notified_users.collect {|user| user.mail}
Chris@909 433 end
Chris@909 434
Chris@909 435 # Returns the users that should be notified on project events
Chris@909 436 def notified_users
Chris@909 437 # TODO: User part should be extracted to User#notify_about?
Chris@909 438 members.select {|m| m.mail_notification? || m.user.mail_notification == 'all'}.collect {|m| m.user}
Chris@909 439 end
Chris@909 440
Chris@909 441 # Returns an array of all custom fields enabled for project issues
Chris@909 442 # (explictly associated custom fields and custom fields enabled for all projects)
Chris@909 443 def all_issue_custom_fields
Chris@909 444 @all_issue_custom_fields ||= (IssueCustomField.for_all + issue_custom_fields).uniq.sort
Chris@909 445 end
Chris@909 446
Chris@909 447 # Returns an array of all custom fields enabled for project time entries
Chris@909 448 # (explictly associated custom fields and custom fields enabled for all projects)
Chris@909 449 def all_time_entry_custom_fields
Chris@909 450 @all_time_entry_custom_fields ||= (TimeEntryCustomField.for_all + time_entry_custom_fields).uniq.sort
Chris@909 451 end
Chris@909 452
Chris@909 453 def project
Chris@909 454 self
Chris@909 455 end
Chris@909 456
Chris@909 457 def <=>(project)
Chris@909 458 name.downcase <=> project.name.downcase
Chris@909 459 end
Chris@909 460
Chris@909 461 def to_s
Chris@909 462 name
Chris@909 463 end
Chris@909 464
Chris@909 465 # Returns a short description of the projects (first lines)
Chris@909 466 def short_description(length = 255)
Chris@909 467 description.gsub(/^(.{#{length}}[^\n\r]*).*$/m, '\1...').strip if description
Chris@909 468 end
Chris@909 469
Chris@909 470 def css_classes
Chris@909 471 s = 'project'
Chris@909 472 s << ' root' if root?
Chris@909 473 s << ' child' if child?
Chris@909 474 s << (leaf? ? ' leaf' : ' parent')
Chris@909 475 s
Chris@909 476 end
Chris@909 477
Chris@909 478 # The earliest start date of a project, based on it's issues and versions
Chris@909 479 def start_date
Chris@909 480 [
Chris@909 481 issues.minimum('start_date'),
Chris@909 482 shared_versions.collect(&:effective_date),
Chris@909 483 shared_versions.collect(&:start_date)
Chris@909 484 ].flatten.compact.min
Chris@909 485 end
Chris@909 486
Chris@909 487 # The latest due date of an issue or version
Chris@909 488 def due_date
Chris@909 489 [
Chris@909 490 issues.maximum('due_date'),
Chris@909 491 shared_versions.collect(&:effective_date),
Chris@909 492 shared_versions.collect {|v| v.fixed_issues.maximum('due_date')}
Chris@909 493 ].flatten.compact.max
Chris@909 494 end
Chris@909 495
Chris@909 496 def overdue?
Chris@909 497 active? && !due_date.nil? && (due_date < Date.today)
Chris@909 498 end
Chris@909 499
Chris@909 500 # Returns the percent completed for this project, based on the
Chris@909 501 # progress on it's versions.
Chris@909 502 def completed_percent(options={:include_subprojects => false})
Chris@909 503 if options.delete(:include_subprojects)
Chris@909 504 total = self_and_descendants.collect(&:completed_percent).sum
Chris@909 505
Chris@909 506 total / self_and_descendants.count
Chris@909 507 else
Chris@909 508 if versions.count > 0
Chris@909 509 total = versions.collect(&:completed_pourcent).sum
Chris@909 510
Chris@909 511 total / versions.count
Chris@909 512 else
Chris@909 513 100
Chris@909 514 end
Chris@909 515 end
Chris@909 516 end
Chris@909 517
Chris@909 518 # Return true if this project is allowed to do the specified action.
Chris@909 519 # action can be:
Chris@909 520 # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
Chris@909 521 # * a permission Symbol (eg. :edit_project)
Chris@909 522 def allows_to?(action)
Chris@909 523 if action.is_a? Hash
Chris@909 524 allowed_actions.include? "#{action[:controller]}/#{action[:action]}"
Chris@909 525 else
Chris@909 526 allowed_permissions.include? action
Chris@909 527 end
Chris@909 528 end
Chris@909 529
Chris@909 530 def module_enabled?(module_name)
Chris@909 531 module_name = module_name.to_s
Chris@909 532 enabled_modules.detect {|m| m.name == module_name}
Chris@909 533 end
Chris@909 534
Chris@909 535 def enabled_module_names=(module_names)
Chris@909 536 if module_names && module_names.is_a?(Array)
Chris@909 537 module_names = module_names.collect(&:to_s).reject(&:blank?)
Chris@909 538 self.enabled_modules = module_names.collect {|name| enabled_modules.detect {|mod| mod.name == name} || EnabledModule.new(:name => name)}
Chris@909 539 else
Chris@909 540 enabled_modules.clear
Chris@909 541 end
Chris@909 542 end
Chris@909 543
Chris@909 544 # Returns an array of the enabled modules names
Chris@909 545 def enabled_module_names
Chris@909 546 enabled_modules.collect(&:name)
Chris@909 547 end
Chris@909 548
Chris@909 549 # Enable a specific module
Chris@909 550 #
Chris@909 551 # Examples:
Chris@909 552 # project.enable_module!(:issue_tracking)
Chris@909 553 # project.enable_module!("issue_tracking")
Chris@909 554 def enable_module!(name)
Chris@909 555 enabled_modules << EnabledModule.new(:name => name.to_s) unless module_enabled?(name)
Chris@909 556 end
Chris@909 557
Chris@909 558 # Disable a module if it exists
Chris@909 559 #
Chris@909 560 # Examples:
Chris@909 561 # project.disable_module!(:issue_tracking)
Chris@909 562 # project.disable_module!("issue_tracking")
Chris@909 563 # project.disable_module!(project.enabled_modules.first)
Chris@909 564 def disable_module!(target)
Chris@909 565 target = enabled_modules.detect{|mod| target.to_s == mod.name} unless enabled_modules.include?(target)
Chris@909 566 target.destroy unless target.blank?
Chris@909 567 end
Chris@909 568
Chris@909 569 safe_attributes 'name',
Chris@909 570 'description',
Chris@909 571 'homepage',
Chris@909 572 'is_public',
Chris@909 573 'identifier',
Chris@909 574 'custom_field_values',
Chris@909 575 'custom_fields',
Chris@909 576 'tracker_ids',
Chris@909 577 'issue_custom_field_ids'
Chris@909 578
Chris@909 579 safe_attributes 'enabled_module_names',
Chris@909 580 :if => lambda {|project, user| project.new_record? || user.allowed_to?(:select_project_modules, project) }
Chris@909 581
Chris@909 582 # Returns an array of projects that are in this project's hierarchy
Chris@909 583 #
Chris@909 584 # Example: parents, children, siblings
Chris@909 585 def hierarchy
Chris@909 586 parents = project.self_and_ancestors || []
Chris@909 587 descendants = project.descendants || []
Chris@909 588 project_hierarchy = parents | descendants # Set union
Chris@909 589 end
Chris@909 590
Chris@909 591 # Returns an auto-generated project identifier based on the last identifier used
Chris@909 592 def self.next_identifier
Chris@909 593 p = Project.find(:first, :order => 'created_on DESC')
Chris@909 594 p.nil? ? nil : p.identifier.to_s.succ
Chris@909 595 end
Chris@909 596
Chris@909 597 # Copies and saves the Project instance based on the +project+.
Chris@909 598 # Duplicates the source project's:
Chris@909 599 # * Wiki
Chris@909 600 # * Versions
Chris@909 601 # * Categories
Chris@909 602 # * Issues
Chris@909 603 # * Members
Chris@909 604 # * Queries
Chris@909 605 #
Chris@909 606 # Accepts an +options+ argument to specify what to copy
Chris@909 607 #
Chris@909 608 # Examples:
Chris@909 609 # project.copy(1) # => copies everything
Chris@909 610 # project.copy(1, :only => 'members') # => copies members only
Chris@909 611 # project.copy(1, :only => ['members', 'versions']) # => copies members and versions
Chris@909 612 def copy(project, options={})
Chris@909 613 project = project.is_a?(Project) ? project : Project.find(project)
Chris@909 614
Chris@909 615 to_be_copied = %w(wiki versions issue_categories issues members queries boards)
Chris@909 616 to_be_copied = to_be_copied & options[:only].to_a unless options[:only].nil?
Chris@909 617
Chris@909 618 Project.transaction do
Chris@909 619 if save
Chris@909 620 reload
Chris@909 621 to_be_copied.each do |name|
Chris@909 622 send "copy_#{name}", project
Chris@909 623 end
Chris@909 624 Redmine::Hook.call_hook(:model_project_copy_before_save, :source_project => project, :destination_project => self)
Chris@909 625 save
Chris@909 626 end
Chris@909 627 end
Chris@909 628 end
Chris@909 629
Chris@909 630
Chris@909 631 # Copies +project+ and returns the new instance. This will not save
Chris@909 632 # the copy
Chris@909 633 def self.copy_from(project)
Chris@909 634 begin
Chris@909 635 project = project.is_a?(Project) ? project : Project.find(project)
Chris@909 636 if project
Chris@909 637 # clear unique attributes
Chris@909 638 attributes = project.attributes.dup.except('id', 'name', 'identifier', 'status', 'parent_id', 'lft', 'rgt')
Chris@909 639 copy = Project.new(attributes)
Chris@909 640 copy.enabled_modules = project.enabled_modules
Chris@909 641 copy.trackers = project.trackers
Chris@909 642 copy.custom_values = project.custom_values.collect {|v| v.clone}
Chris@909 643 copy.issue_custom_fields = project.issue_custom_fields
Chris@909 644 return copy
Chris@909 645 else
Chris@909 646 return nil
Chris@909 647 end
Chris@909 648 rescue ActiveRecord::RecordNotFound
Chris@909 649 return nil
Chris@909 650 end
Chris@909 651 end
Chris@909 652
Chris@909 653 # Yields the given block for each project with its level in the tree
Chris@909 654 def self.project_tree(projects, &block)
Chris@909 655 ancestors = []
Chris@909 656 projects.sort_by(&:lft).each do |project|
Chris@909 657 while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
Chris@909 658 ancestors.pop
Chris@909 659 end
Chris@909 660 yield project, ancestors.size
Chris@909 661 ancestors << project
Chris@909 662 end
Chris@909 663 end
Chris@909 664
Chris@909 665 private
Chris@909 666
Chris@909 667 # Copies wiki from +project+
Chris@909 668 def copy_wiki(project)
Chris@909 669 # Check that the source project has a wiki first
Chris@909 670 unless project.wiki.nil?
Chris@909 671 self.wiki ||= Wiki.new
Chris@909 672 wiki.attributes = project.wiki.attributes.dup.except("id", "project_id")
Chris@909 673 wiki_pages_map = {}
Chris@909 674 project.wiki.pages.each do |page|
Chris@909 675 # Skip pages without content
Chris@909 676 next if page.content.nil?
Chris@909 677 new_wiki_content = WikiContent.new(page.content.attributes.dup.except("id", "page_id", "updated_on"))
Chris@909 678 new_wiki_page = WikiPage.new(page.attributes.dup.except("id", "wiki_id", "created_on", "parent_id"))
Chris@909 679 new_wiki_page.content = new_wiki_content
Chris@909 680 wiki.pages << new_wiki_page
Chris@909 681 wiki_pages_map[page.id] = new_wiki_page
Chris@909 682 end
Chris@909 683 wiki.save
Chris@909 684 # Reproduce page hierarchy
Chris@909 685 project.wiki.pages.each do |page|
Chris@909 686 if page.parent_id && wiki_pages_map[page.id]
Chris@909 687 wiki_pages_map[page.id].parent = wiki_pages_map[page.parent_id]
Chris@909 688 wiki_pages_map[page.id].save
Chris@909 689 end
Chris@909 690 end
Chris@909 691 end
Chris@909 692 end
Chris@909 693
Chris@909 694 # Copies versions from +project+
Chris@909 695 def copy_versions(project)
Chris@909 696 project.versions.each do |version|
Chris@909 697 new_version = Version.new
Chris@909 698 new_version.attributes = version.attributes.dup.except("id", "project_id", "created_on", "updated_on")
Chris@909 699 self.versions << new_version
Chris@909 700 end
Chris@909 701 end
Chris@909 702
Chris@909 703 # Copies issue categories from +project+
Chris@909 704 def copy_issue_categories(project)
Chris@909 705 project.issue_categories.each do |issue_category|
Chris@909 706 new_issue_category = IssueCategory.new
Chris@909 707 new_issue_category.attributes = issue_category.attributes.dup.except("id", "project_id")
Chris@909 708 self.issue_categories << new_issue_category
Chris@909 709 end
Chris@909 710 end
Chris@909 711
Chris@909 712 # Copies issues from +project+
Chris@909 713 # Note: issues assigned to a closed version won't be copied due to validation rules
Chris@909 714 def copy_issues(project)
Chris@909 715 # Stores the source issue id as a key and the copied issues as the
Chris@909 716 # value. Used to map the two togeather for issue relations.
Chris@909 717 issues_map = {}
Chris@909 718
Chris@909 719 # Get issues sorted by root_id, lft so that parent issues
Chris@909 720 # get copied before their children
Chris@909 721 project.issues.find(:all, :order => 'root_id, lft').each do |issue|
Chris@909 722 new_issue = Issue.new
Chris@909 723 new_issue.copy_from(issue)
Chris@909 724 new_issue.project = self
Chris@909 725 # Reassign fixed_versions by name, since names are unique per
Chris@909 726 # project and the versions for self are not yet saved
Chris@909 727 if issue.fixed_version
Chris@909 728 new_issue.fixed_version = self.versions.select {|v| v.name == issue.fixed_version.name}.first
Chris@909 729 end
Chris@909 730 # Reassign the category by name, since names are unique per
Chris@909 731 # project and the categories for self are not yet saved
Chris@909 732 if issue.category
Chris@909 733 new_issue.category = self.issue_categories.select {|c| c.name == issue.category.name}.first
Chris@909 734 end
Chris@909 735 # Parent issue
Chris@909 736 if issue.parent_id
Chris@909 737 if copied_parent = issues_map[issue.parent_id]
Chris@909 738 new_issue.parent_issue_id = copied_parent.id
Chris@909 739 end
Chris@909 740 end
Chris@909 741
Chris@909 742 self.issues << new_issue
Chris@909 743 if new_issue.new_record?
Chris@909 744 logger.info "Project#copy_issues: issue ##{issue.id} could not be copied: #{new_issue.errors.full_messages}" if logger && logger.info
Chris@909 745 else
Chris@909 746 issues_map[issue.id] = new_issue unless new_issue.new_record?
Chris@909 747 end
Chris@909 748 end
Chris@909 749
Chris@909 750 # Relations after in case issues related each other
Chris@909 751 project.issues.each do |issue|
Chris@909 752 new_issue = issues_map[issue.id]
Chris@909 753 unless new_issue
Chris@909 754 # Issue was not copied
Chris@909 755 next
Chris@909 756 end
Chris@909 757
Chris@909 758 # Relations
Chris@909 759 issue.relations_from.each do |source_relation|
Chris@909 760 new_issue_relation = IssueRelation.new
Chris@909 761 new_issue_relation.attributes = source_relation.attributes.dup.except("id", "issue_from_id", "issue_to_id")
Chris@909 762 new_issue_relation.issue_to = issues_map[source_relation.issue_to_id]
Chris@909 763 if new_issue_relation.issue_to.nil? && Setting.cross_project_issue_relations?
Chris@909 764 new_issue_relation.issue_to = source_relation.issue_to
Chris@909 765 end
Chris@909 766 new_issue.relations_from << new_issue_relation
Chris@909 767 end
Chris@909 768
Chris@909 769 issue.relations_to.each do |source_relation|
Chris@909 770 new_issue_relation = IssueRelation.new
Chris@909 771 new_issue_relation.attributes = source_relation.attributes.dup.except("id", "issue_from_id", "issue_to_id")
Chris@909 772 new_issue_relation.issue_from = issues_map[source_relation.issue_from_id]
Chris@909 773 if new_issue_relation.issue_from.nil? && Setting.cross_project_issue_relations?
Chris@909 774 new_issue_relation.issue_from = source_relation.issue_from
Chris@909 775 end
Chris@909 776 new_issue.relations_to << new_issue_relation
Chris@909 777 end
Chris@909 778 end
Chris@909 779 end
Chris@909 780
Chris@909 781 # Copies members from +project+
Chris@909 782 def copy_members(project)
Chris@909 783 # Copy users first, then groups to handle members with inherited and given roles
Chris@909 784 members_to_copy = []
Chris@909 785 members_to_copy += project.memberships.select {|m| m.principal.is_a?(User)}
Chris@909 786 members_to_copy += project.memberships.select {|m| !m.principal.is_a?(User)}
Chris@909 787
Chris@909 788 members_to_copy.each do |member|
Chris@909 789 new_member = Member.new
Chris@909 790 new_member.attributes = member.attributes.dup.except("id", "project_id", "created_on")
Chris@909 791 # only copy non inherited roles
Chris@909 792 # inherited roles will be added when copying the group membership
Chris@909 793 role_ids = member.member_roles.reject(&:inherited?).collect(&:role_id)
Chris@909 794 next if role_ids.empty?
Chris@909 795 new_member.role_ids = role_ids
Chris@909 796 new_member.project = self
Chris@909 797 self.members << new_member
Chris@909 798 end
Chris@909 799 end
Chris@909 800
Chris@909 801 # Copies queries from +project+
Chris@909 802 def copy_queries(project)
Chris@909 803 project.queries.each do |query|
Chris@909 804 new_query = Query.new
Chris@909 805 new_query.attributes = query.attributes.dup.except("id", "project_id", "sort_criteria")
Chris@909 806 new_query.sort_criteria = query.sort_criteria if query.sort_criteria
Chris@909 807 new_query.project = self
Chris@909 808 new_query.user_id = query.user_id
Chris@909 809 self.queries << new_query
Chris@909 810 end
Chris@909 811 end
Chris@909 812
Chris@909 813 # Copies boards from +project+
Chris@909 814 def copy_boards(project)
Chris@909 815 project.boards.each do |board|
Chris@909 816 new_board = Board.new
Chris@909 817 new_board.attributes = board.attributes.dup.except("id", "project_id", "topics_count", "messages_count", "last_message_id")
Chris@909 818 new_board.project = self
Chris@909 819 self.boards << new_board
Chris@909 820 end
Chris@909 821 end
Chris@909 822
Chris@909 823 def allowed_permissions
Chris@909 824 @allowed_permissions ||= begin
Chris@909 825 module_names = enabled_modules.all(:select => :name).collect {|m| m.name}
Chris@909 826 Redmine::AccessControl.modules_permissions(module_names).collect {|p| p.name}
Chris@909 827 end
Chris@909 828 end
Chris@909 829
Chris@909 830 def allowed_actions
Chris@909 831 @actions_allowed ||= allowed_permissions.inject([]) { |actions, permission| actions += Redmine::AccessControl.allowed_actions(permission) }.flatten
Chris@909 832 end
Chris@909 833
Chris@909 834 # Returns all the active Systemwide and project specific activities
Chris@909 835 def active_activities
Chris@909 836 overridden_activity_ids = self.time_entry_activities.collect(&:parent_id)
Chris@909 837
Chris@909 838 if overridden_activity_ids.empty?
Chris@909 839 return TimeEntryActivity.shared.active
Chris@909 840 else
Chris@909 841 return system_activities_and_project_overrides
Chris@909 842 end
Chris@909 843 end
Chris@909 844
Chris@909 845 # Returns all the Systemwide and project specific activities
Chris@909 846 # (inactive and active)
Chris@909 847 def all_activities
Chris@909 848 overridden_activity_ids = self.time_entry_activities.collect(&:parent_id)
Chris@909 849
Chris@909 850 if overridden_activity_ids.empty?
Chris@909 851 return TimeEntryActivity.shared
Chris@909 852 else
Chris@909 853 return system_activities_and_project_overrides(true)
Chris@909 854 end
Chris@909 855 end
Chris@909 856
Chris@909 857 # Returns the systemwide active activities merged with the project specific overrides
Chris@909 858 def system_activities_and_project_overrides(include_inactive=false)
Chris@909 859 if include_inactive
Chris@909 860 return TimeEntryActivity.shared.
Chris@909 861 find(:all,
Chris@909 862 :conditions => ["id NOT IN (?)", self.time_entry_activities.collect(&:parent_id)]) +
Chris@909 863 self.time_entry_activities
Chris@909 864 else
Chris@909 865 return TimeEntryActivity.shared.active.
Chris@909 866 find(:all,
Chris@909 867 :conditions => ["id NOT IN (?)", self.time_entry_activities.collect(&:parent_id)]) +
Chris@909 868 self.time_entry_activities.active
Chris@909 869 end
Chris@909 870 end
Chris@909 871
Chris@909 872 # Archives subprojects recursively
Chris@909 873 def archive!
Chris@909 874 children.each do |subproject|
Chris@909 875 subproject.send :archive!
Chris@909 876 end
Chris@909 877 update_attribute :status, STATUS_ARCHIVED
Chris@909 878 end
Chris@909 879 end