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