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