To check out this repository please hg clone the following URL, or open the URL using EasyMercurial or your preferred Mercurial client.

Statistics Download as Zip
| Branch: | Tag: | Revision:

root / app / models / project.rb @ 1298:4f746d8966dd

History | View | Annotate | Download (37.3 KB)

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