annotate app/models/project.rb @ 861:b8105f717bf7 bug_182

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