##// END OF EJS Templates
use :order_column option instead of :order for acts_as_nested_set...
Toshi MARUYAMA -
r12405:1c0c22de170e
parent child
Show More
@@ -1,1043 +1,1043
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 acts_as_nested_set :order => 'name', :dependent => :destroy
59 acts_as_nested_set :order_column => '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 424 end
425 425 end
426 426
427 427 # Returns an array of the trackers used by the project and its active sub projects
428 428 def rolled_up_trackers
429 429 @rolled_up_trackers ||=
430 430 Tracker.
431 431 joins(:projects).
432 432 joins("JOIN #{EnabledModule.table_name} ON #{EnabledModule.table_name}.project_id = #{Project.table_name}.id AND #{EnabledModule.table_name}.name = 'issue_tracking'").
433 433 select("DISTINCT #{Tracker.table_name}.*").
434 434 where("#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status <> #{STATUS_ARCHIVED}", lft, rgt).
435 435 sorted.
436 436 all
437 437 end
438 438
439 439 # Closes open and locked project versions that are completed
440 440 def close_completed_versions
441 441 Version.transaction do
442 442 versions.where(:status => %w(open locked)).all.each do |version|
443 443 if version.completed?
444 444 version.update_attribute(:status, 'closed')
445 445 end
446 446 end
447 447 end
448 448 end
449 449
450 450 # Returns a scope of the Versions on subprojects
451 451 def rolled_up_versions
452 452 @rolled_up_versions ||=
453 453 Version.
454 454 includes(:project).
455 455 where("#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status <> ?", lft, rgt, STATUS_ARCHIVED)
456 456 end
457 457
458 458 # Returns a scope of the Versions used by the project
459 459 def shared_versions
460 460 if new_record?
461 461 Version.
462 462 includes(:project).
463 463 where("#{Project.table_name}.status <> ? AND #{Version.table_name}.sharing = 'system'", STATUS_ARCHIVED)
464 464 else
465 465 @shared_versions ||= begin
466 466 r = root? ? self : root
467 467 Version.
468 468 includes(:project).
469 469 where("#{Project.table_name}.id = #{id}" +
470 470 " OR (#{Project.table_name}.status <> #{Project::STATUS_ARCHIVED} AND (" +
471 471 " #{Version.table_name}.sharing = 'system'" +
472 472 " OR (#{Project.table_name}.lft >= #{r.lft} AND #{Project.table_name}.rgt <= #{r.rgt} AND #{Version.table_name}.sharing = 'tree')" +
473 473 " OR (#{Project.table_name}.lft < #{lft} AND #{Project.table_name}.rgt > #{rgt} AND #{Version.table_name}.sharing IN ('hierarchy', 'descendants'))" +
474 474 " OR (#{Project.table_name}.lft > #{lft} AND #{Project.table_name}.rgt < #{rgt} AND #{Version.table_name}.sharing = 'hierarchy')" +
475 475 "))")
476 476 end
477 477 end
478 478 end
479 479
480 480 # Returns a hash of project users grouped by role
481 481 def users_by_role
482 482 members.includes(:user, :roles).all.inject({}) do |h, m|
483 483 m.roles.each do |r|
484 484 h[r] ||= []
485 485 h[r] << m.user
486 486 end
487 487 h
488 488 end
489 489 end
490 490
491 491 # Deletes all project's members
492 492 def delete_all_members
493 493 me, mr = Member.table_name, MemberRole.table_name
494 494 connection.delete("DELETE FROM #{mr} WHERE #{mr}.member_id IN (SELECT #{me}.id FROM #{me} WHERE #{me}.project_id = #{id})")
495 495 Member.delete_all(['project_id = ?', id])
496 496 end
497 497
498 498 # Users/groups issues can be assigned to
499 499 def assignable_users
500 500 assignable = Setting.issue_group_assignment? ? member_principals : members
501 501 assignable.select {|m| m.roles.detect {|role| role.assignable?}}.collect {|m| m.principal}.sort
502 502 end
503 503
504 504 # Returns the mail adresses of users that should be always notified on project events
505 505 def recipients
506 506 notified_users.collect {|user| user.mail}
507 507 end
508 508
509 509 # Returns the users that should be notified on project events
510 510 def notified_users
511 511 # TODO: User part should be extracted to User#notify_about?
512 512 members.select {|m| m.principal.present? && (m.mail_notification? || m.principal.mail_notification == 'all')}.collect {|m| m.principal}
513 513 end
514 514
515 515 # Returns a scope of all custom fields enabled for project issues
516 516 # (explictly associated custom fields and custom fields enabled for all projects)
517 517 def all_issue_custom_fields
518 518 @all_issue_custom_fields ||= IssueCustomField.
519 519 sorted.
520 520 where("is_for_all = ? OR id IN (SELECT DISTINCT cfp.custom_field_id" +
521 521 " FROM #{table_name_prefix}custom_fields_projects#{table_name_suffix} cfp" +
522 522 " WHERE cfp.project_id = ?)", true, id)
523 523 end
524 524
525 525 # Returns an array of all custom fields enabled for project time entries
526 526 # (explictly associated custom fields and custom fields enabled for all projects)
527 527 def all_time_entry_custom_fields
528 528 @all_time_entry_custom_fields ||= (TimeEntryCustomField.for_all + time_entry_custom_fields).uniq.sort
529 529 end
530 530
531 531 def project
532 532 self
533 533 end
534 534
535 535 def <=>(project)
536 536 name.downcase <=> project.name.downcase
537 537 end
538 538
539 539 def to_s
540 540 name
541 541 end
542 542
543 543 # Returns a short description of the projects (first lines)
544 544 def short_description(length = 255)
545 545 description.gsub(/^(.{#{length}}[^\n\r]*).*$/m, '\1...').strip if description
546 546 end
547 547
548 548 def css_classes
549 549 s = 'project'
550 550 s << ' root' if root?
551 551 s << ' child' if child?
552 552 s << (leaf? ? ' leaf' : ' parent')
553 553 unless active?
554 554 if archived?
555 555 s << ' archived'
556 556 else
557 557 s << ' closed'
558 558 end
559 559 end
560 560 s
561 561 end
562 562
563 563 # The earliest start date of a project, based on it's issues and versions
564 564 def start_date
565 565 @start_date ||= [
566 566 issues.minimum('start_date'),
567 567 shared_versions.minimum('effective_date'),
568 568 Issue.fixed_version(shared_versions).minimum('start_date')
569 569 ].compact.min
570 570 end
571 571
572 572 # The latest due date of an issue or version
573 573 def due_date
574 574 @due_date ||= [
575 575 issues.maximum('due_date'),
576 576 shared_versions.maximum('effective_date'),
577 577 Issue.fixed_version(shared_versions).maximum('due_date')
578 578 ].compact.max
579 579 end
580 580
581 581 def overdue?
582 582 active? && !due_date.nil? && (due_date < Date.today)
583 583 end
584 584
585 585 # Returns the percent completed for this project, based on the
586 586 # progress on it's versions.
587 587 def completed_percent(options={:include_subprojects => false})
588 588 if options.delete(:include_subprojects)
589 589 total = self_and_descendants.collect(&:completed_percent).sum
590 590
591 591 total / self_and_descendants.count
592 592 else
593 593 if versions.count > 0
594 594 total = versions.collect(&:completed_percent).sum
595 595
596 596 total / versions.count
597 597 else
598 598 100
599 599 end
600 600 end
601 601 end
602 602
603 603 # Return true if this project allows to do the specified action.
604 604 # action can be:
605 605 # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
606 606 # * a permission Symbol (eg. :edit_project)
607 607 def allows_to?(action)
608 608 if archived?
609 609 # No action allowed on archived projects
610 610 return false
611 611 end
612 612 unless active? || Redmine::AccessControl.read_action?(action)
613 613 # No write action allowed on closed projects
614 614 return false
615 615 end
616 616 # No action allowed on disabled modules
617 617 if action.is_a? Hash
618 618 allowed_actions.include? "#{action[:controller]}/#{action[:action]}"
619 619 else
620 620 allowed_permissions.include? action
621 621 end
622 622 end
623 623
624 624 def module_enabled?(module_name)
625 625 module_name = module_name.to_s
626 626 enabled_modules.detect {|m| m.name == module_name}
627 627 end
628 628
629 629 def enabled_module_names=(module_names)
630 630 if module_names && module_names.is_a?(Array)
631 631 module_names = module_names.collect(&:to_s).reject(&:blank?)
632 632 self.enabled_modules = module_names.collect {|name| enabled_modules.detect {|mod| mod.name == name} || EnabledModule.new(:name => name)}
633 633 else
634 634 enabled_modules.clear
635 635 end
636 636 end
637 637
638 638 # Returns an array of the enabled modules names
639 639 def enabled_module_names
640 640 enabled_modules.collect(&:name)
641 641 end
642 642
643 643 # Enable a specific module
644 644 #
645 645 # Examples:
646 646 # project.enable_module!(:issue_tracking)
647 647 # project.enable_module!("issue_tracking")
648 648 def enable_module!(name)
649 649 enabled_modules << EnabledModule.new(:name => name.to_s) unless module_enabled?(name)
650 650 end
651 651
652 652 # Disable a module if it exists
653 653 #
654 654 # Examples:
655 655 # project.disable_module!(:issue_tracking)
656 656 # project.disable_module!("issue_tracking")
657 657 # project.disable_module!(project.enabled_modules.first)
658 658 def disable_module!(target)
659 659 target = enabled_modules.detect{|mod| target.to_s == mod.name} unless enabled_modules.include?(target)
660 660 target.destroy unless target.blank?
661 661 end
662 662
663 663 safe_attributes 'name',
664 664 'description',
665 665 'homepage',
666 666 'is_public',
667 667 'identifier',
668 668 'custom_field_values',
669 669 'custom_fields',
670 670 'tracker_ids',
671 671 'issue_custom_field_ids'
672 672
673 673 safe_attributes 'enabled_module_names',
674 674 :if => lambda {|project, user| project.new_record? || user.allowed_to?(:select_project_modules, project) }
675 675
676 676 safe_attributes 'inherit_members',
677 677 :if => lambda {|project, user| project.parent.nil? || project.parent.visible?(user)}
678 678
679 679 # Returns an array of projects that are in this project's hierarchy
680 680 #
681 681 # Example: parents, children, siblings
682 682 def hierarchy
683 683 parents = project.self_and_ancestors || []
684 684 descendants = project.descendants || []
685 685 project_hierarchy = parents | descendants # Set union
686 686 end
687 687
688 688 # Returns an auto-generated project identifier based on the last identifier used
689 689 def self.next_identifier
690 690 p = Project.order('id DESC').first
691 691 p.nil? ? nil : p.identifier.to_s.succ
692 692 end
693 693
694 694 # Copies and saves the Project instance based on the +project+.
695 695 # Duplicates the source project's:
696 696 # * Wiki
697 697 # * Versions
698 698 # * Categories
699 699 # * Issues
700 700 # * Members
701 701 # * Queries
702 702 #
703 703 # Accepts an +options+ argument to specify what to copy
704 704 #
705 705 # Examples:
706 706 # project.copy(1) # => copies everything
707 707 # project.copy(1, :only => 'members') # => copies members only
708 708 # project.copy(1, :only => ['members', 'versions']) # => copies members and versions
709 709 def copy(project, options={})
710 710 project = project.is_a?(Project) ? project : Project.find(project)
711 711
712 712 to_be_copied = %w(wiki versions issue_categories issues members queries boards)
713 713 to_be_copied = to_be_copied & options[:only].to_a unless options[:only].nil?
714 714
715 715 Project.transaction do
716 716 if save
717 717 reload
718 718 to_be_copied.each do |name|
719 719 send "copy_#{name}", project
720 720 end
721 721 Redmine::Hook.call_hook(:model_project_copy_before_save, :source_project => project, :destination_project => self)
722 722 save
723 723 end
724 724 end
725 725 end
726 726
727 727 # Returns a new unsaved Project instance with attributes copied from +project+
728 728 def self.copy_from(project)
729 729 project = project.is_a?(Project) ? project : Project.find(project)
730 730 # clear unique attributes
731 731 attributes = project.attributes.dup.except('id', 'name', 'identifier', 'status', 'parent_id', 'lft', 'rgt')
732 732 copy = Project.new(attributes)
733 733 copy.enabled_modules = project.enabled_modules
734 734 copy.trackers = project.trackers
735 735 copy.custom_values = project.custom_values.collect {|v| v.clone}
736 736 copy.issue_custom_fields = project.issue_custom_fields
737 737 copy
738 738 end
739 739
740 740 # Yields the given block for each project with its level in the tree
741 741 def self.project_tree(projects, &block)
742 742 ancestors = []
743 743 projects.sort_by(&:lft).each do |project|
744 744 while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
745 745 ancestors.pop
746 746 end
747 747 yield project, ancestors.size
748 748 ancestors << project
749 749 end
750 750 end
751 751
752 752 private
753 753
754 754 def after_parent_changed(parent_was)
755 755 remove_inherited_member_roles
756 756 add_inherited_member_roles
757 757 end
758 758
759 759 def update_inherited_members
760 760 if parent
761 761 if inherit_members? && !inherit_members_was
762 762 remove_inherited_member_roles
763 763 add_inherited_member_roles
764 764 elsif !inherit_members? && inherit_members_was
765 765 remove_inherited_member_roles
766 766 end
767 767 end
768 768 end
769 769
770 770 def remove_inherited_member_roles
771 771 member_roles = memberships.map(&:member_roles).flatten
772 772 member_role_ids = member_roles.map(&:id)
773 773 member_roles.each do |member_role|
774 774 if member_role.inherited_from && !member_role_ids.include?(member_role.inherited_from)
775 775 member_role.destroy
776 776 end
777 777 end
778 778 end
779 779
780 780 def add_inherited_member_roles
781 781 if inherit_members? && parent
782 782 parent.memberships.each do |parent_member|
783 783 member = Member.find_or_new(self.id, parent_member.user_id)
784 784 parent_member.member_roles.each do |parent_member_role|
785 785 member.member_roles << MemberRole.new(:role => parent_member_role.role, :inherited_from => parent_member_role.id)
786 786 end
787 787 member.save!
788 788 end
789 789 end
790 790 end
791 791
792 792 # Copies wiki from +project+
793 793 def copy_wiki(project)
794 794 # Check that the source project has a wiki first
795 795 unless project.wiki.nil?
796 796 wiki = self.wiki || Wiki.new
797 797 wiki.attributes = project.wiki.attributes.dup.except("id", "project_id")
798 798 wiki_pages_map = {}
799 799 project.wiki.pages.each do |page|
800 800 # Skip pages without content
801 801 next if page.content.nil?
802 802 new_wiki_content = WikiContent.new(page.content.attributes.dup.except("id", "page_id", "updated_on"))
803 803 new_wiki_page = WikiPage.new(page.attributes.dup.except("id", "wiki_id", "created_on", "parent_id"))
804 804 new_wiki_page.content = new_wiki_content
805 805 wiki.pages << new_wiki_page
806 806 wiki_pages_map[page.id] = new_wiki_page
807 807 end
808 808
809 809 self.wiki = wiki
810 810 wiki.save
811 811 # Reproduce page hierarchy
812 812 project.wiki.pages.each do |page|
813 813 if page.parent_id && wiki_pages_map[page.id]
814 814 wiki_pages_map[page.id].parent = wiki_pages_map[page.parent_id]
815 815 wiki_pages_map[page.id].save
816 816 end
817 817 end
818 818 end
819 819 end
820 820
821 821 # Copies versions from +project+
822 822 def copy_versions(project)
823 823 project.versions.each do |version|
824 824 new_version = Version.new
825 825 new_version.attributes = version.attributes.dup.except("id", "project_id", "created_on", "updated_on")
826 826 self.versions << new_version
827 827 end
828 828 end
829 829
830 830 # Copies issue categories from +project+
831 831 def copy_issue_categories(project)
832 832 project.issue_categories.each do |issue_category|
833 833 new_issue_category = IssueCategory.new
834 834 new_issue_category.attributes = issue_category.attributes.dup.except("id", "project_id")
835 835 self.issue_categories << new_issue_category
836 836 end
837 837 end
838 838
839 839 # Copies issues from +project+
840 840 def copy_issues(project)
841 841 # Stores the source issue id as a key and the copied issues as the
842 842 # value. Used to map the two togeather for issue relations.
843 843 issues_map = {}
844 844
845 845 # Store status and reopen locked/closed versions
846 846 version_statuses = versions.reject(&:open?).map {|version| [version, version.status]}
847 847 version_statuses.each do |version, status|
848 848 version.update_attribute :status, 'open'
849 849 end
850 850
851 851 # Get issues sorted by root_id, lft so that parent issues
852 852 # get copied before their children
853 853 project.issues.reorder('root_id, lft').each do |issue|
854 854 new_issue = Issue.new
855 855 new_issue.copy_from(issue, :subtasks => false, :link => false)
856 856 new_issue.project = self
857 857 # Changing project resets the custom field values
858 858 # TODO: handle this in Issue#project=
859 859 new_issue.custom_field_values = issue.custom_field_values.inject({}) {|h,v| h[v.custom_field_id] = v.value; h}
860 860 # Reassign fixed_versions by name, since names are unique per project
861 861 if issue.fixed_version && issue.fixed_version.project == project
862 862 new_issue.fixed_version = self.versions.detect {|v| v.name == issue.fixed_version.name}
863 863 end
864 864 # Reassign the category by name, since names are unique per project
865 865 if issue.category
866 866 new_issue.category = self.issue_categories.detect {|c| c.name == issue.category.name}
867 867 end
868 868 # Parent issue
869 869 if issue.parent_id
870 870 if copied_parent = issues_map[issue.parent_id]
871 871 new_issue.parent_issue_id = copied_parent.id
872 872 end
873 873 end
874 874
875 875 self.issues << new_issue
876 876 if new_issue.new_record?
877 877 logger.info "Project#copy_issues: issue ##{issue.id} could not be copied: #{new_issue.errors.full_messages}" if logger && logger.info
878 878 else
879 879 issues_map[issue.id] = new_issue unless new_issue.new_record?
880 880 end
881 881 end
882 882
883 883 # Restore locked/closed version statuses
884 884 version_statuses.each do |version, status|
885 885 version.update_attribute :status, status
886 886 end
887 887
888 888 # Relations after in case issues related each other
889 889 project.issues.each do |issue|
890 890 new_issue = issues_map[issue.id]
891 891 unless new_issue
892 892 # Issue was not copied
893 893 next
894 894 end
895 895
896 896 # Relations
897 897 issue.relations_from.each do |source_relation|
898 898 new_issue_relation = IssueRelation.new
899 899 new_issue_relation.attributes = source_relation.attributes.dup.except("id", "issue_from_id", "issue_to_id")
900 900 new_issue_relation.issue_to = issues_map[source_relation.issue_to_id]
901 901 if new_issue_relation.issue_to.nil? && Setting.cross_project_issue_relations?
902 902 new_issue_relation.issue_to = source_relation.issue_to
903 903 end
904 904 new_issue.relations_from << new_issue_relation
905 905 end
906 906
907 907 issue.relations_to.each do |source_relation|
908 908 new_issue_relation = IssueRelation.new
909 909 new_issue_relation.attributes = source_relation.attributes.dup.except("id", "issue_from_id", "issue_to_id")
910 910 new_issue_relation.issue_from = issues_map[source_relation.issue_from_id]
911 911 if new_issue_relation.issue_from.nil? && Setting.cross_project_issue_relations?
912 912 new_issue_relation.issue_from = source_relation.issue_from
913 913 end
914 914 new_issue.relations_to << new_issue_relation
915 915 end
916 916 end
917 917 end
918 918
919 919 # Copies members from +project+
920 920 def copy_members(project)
921 921 # Copy users first, then groups to handle members with inherited and given roles
922 922 members_to_copy = []
923 923 members_to_copy += project.memberships.select {|m| m.principal.is_a?(User)}
924 924 members_to_copy += project.memberships.select {|m| !m.principal.is_a?(User)}
925 925
926 926 members_to_copy.each do |member|
927 927 new_member = Member.new
928 928 new_member.attributes = member.attributes.dup.except("id", "project_id", "created_on")
929 929 # only copy non inherited roles
930 930 # inherited roles will be added when copying the group membership
931 931 role_ids = member.member_roles.reject(&:inherited?).collect(&:role_id)
932 932 next if role_ids.empty?
933 933 new_member.role_ids = role_ids
934 934 new_member.project = self
935 935 self.members << new_member
936 936 end
937 937 end
938 938
939 939 # Copies queries from +project+
940 940 def copy_queries(project)
941 941 project.queries.each do |query|
942 942 new_query = IssueQuery.new
943 943 new_query.attributes = query.attributes.dup.except("id", "project_id", "sort_criteria")
944 944 new_query.sort_criteria = query.sort_criteria if query.sort_criteria
945 945 new_query.project = self
946 946 new_query.user_id = query.user_id
947 947 self.queries << new_query
948 948 end
949 949 end
950 950
951 951 # Copies boards from +project+
952 952 def copy_boards(project)
953 953 project.boards.each do |board|
954 954 new_board = Board.new
955 955 new_board.attributes = board.attributes.dup.except("id", "project_id", "topics_count", "messages_count", "last_message_id")
956 956 new_board.project = self
957 957 self.boards << new_board
958 958 end
959 959 end
960 960
961 961 def allowed_permissions
962 962 @allowed_permissions ||= begin
963 963 module_names = enabled_modules.loaded? ? enabled_modules.map(&:name) : enabled_modules.pluck(:name)
964 964 Redmine::AccessControl.modules_permissions(module_names).collect {|p| p.name}
965 965 end
966 966 end
967 967
968 968 def allowed_actions
969 969 @actions_allowed ||= allowed_permissions.inject([]) { |actions, permission| actions += Redmine::AccessControl.allowed_actions(permission) }.flatten
970 970 end
971 971
972 972 # Returns all the active Systemwide and project specific activities
973 973 def active_activities
974 974 overridden_activity_ids = self.time_entry_activities.collect(&:parent_id)
975 975
976 976 if overridden_activity_ids.empty?
977 977 return TimeEntryActivity.shared.active
978 978 else
979 979 return system_activities_and_project_overrides
980 980 end
981 981 end
982 982
983 983 # Returns all the Systemwide and project specific activities
984 984 # (inactive and active)
985 985 def all_activities
986 986 overridden_activity_ids = self.time_entry_activities.collect(&:parent_id)
987 987
988 988 if overridden_activity_ids.empty?
989 989 return TimeEntryActivity.shared
990 990 else
991 991 return system_activities_and_project_overrides(true)
992 992 end
993 993 end
994 994
995 995 # Returns the systemwide active activities merged with the project specific overrides
996 996 def system_activities_and_project_overrides(include_inactive=false)
997 997 if include_inactive
998 998 return TimeEntryActivity.shared.
999 999 where("id NOT IN (?)", self.time_entry_activities.collect(&:parent_id)).all +
1000 1000 self.time_entry_activities
1001 1001 else
1002 1002 return TimeEntryActivity.shared.active.
1003 1003 where("id NOT IN (?)", self.time_entry_activities.collect(&:parent_id)).all +
1004 1004 self.time_entry_activities.active
1005 1005 end
1006 1006 end
1007 1007
1008 1008 # Archives subprojects recursively
1009 1009 def archive!
1010 1010 children.each do |subproject|
1011 1011 subproject.send :archive!
1012 1012 end
1013 1013 update_attribute :status, STATUS_ARCHIVED
1014 1014 end
1015 1015
1016 1016 def update_position_under_parent
1017 1017 set_or_update_position_under(parent)
1018 1018 end
1019 1019
1020 1020 # Inserts/moves the project so that target's children or root projects stay alphabetically sorted
1021 1021 def set_or_update_position_under(target_parent)
1022 1022 parent_was = parent
1023 1023 sibs = (target_parent.nil? ? self.class.roots : target_parent.children)
1024 1024 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 1025
1026 1026 if to_be_inserted_before
1027 1027 move_to_left_of(to_be_inserted_before)
1028 1028 elsif target_parent.nil?
1029 1029 if sibs.empty?
1030 1030 # move_to_root adds the project in first (ie. left) position
1031 1031 move_to_root
1032 1032 else
1033 1033 move_to_right_of(sibs.last) unless self == sibs.last
1034 1034 end
1035 1035 else
1036 1036 # move_to_child_of adds the project in last (ie.right) position
1037 1037 move_to_child_of(target_parent)
1038 1038 end
1039 1039 if parent_was != target_parent
1040 1040 after_parent_changed(parent_was)
1041 1041 end
1042 1042 end
1043 1043 end
@@ -1,748 +1,747
1 1 module CollectiveIdea #:nodoc:
2 2 module Acts #:nodoc:
3 3 module NestedSet #:nodoc:
4 4
5 5 # This acts provides Nested Set functionality. Nested Set is a smart way to implement
6 6 # an _ordered_ tree, with the added feature that you can select the children and all of their
7 7 # descendants with a single query. The drawback is that insertion or move need some complex
8 8 # sql queries. But everything is done here by this module!
9 9 #
10 10 # Nested sets are appropriate each time you want either an orderd tree (menus,
11 11 # commercial categories) or an efficient way of querying big trees (threaded posts).
12 12 #
13 13 # == API
14 14 #
15 15 # Methods names are aligned with acts_as_tree as much as possible to make replacment from one
16 16 # by another easier.
17 17 #
18 18 # item.children.create(:name => "child1")
19 19 #
20 20
21 21 # Configuration options are:
22 22 #
23 23 # * +:parent_column+ - specifies the column name to use for keeping the position integer (default: parent_id)
24 24 # * +:left_column+ - column name for left boundry data, default "lft"
25 25 # * +:right_column+ - column name for right boundry data, default "rgt"
26 26 # * +:depth_column+ - column name for the depth data, default "depth"
27 27 # * +:scope+ - restricts what is to be considered a list. Given a symbol, it'll attach "_id"
28 28 # (if it hasn't been already) and use that as the foreign key restriction. You
29 29 # can also pass an array to scope by multiple attributes.
30 30 # Example: <tt>acts_as_nested_set :scope => [:notable_id, :notable_type]</tt>
31 31 # * +:dependent+ - behavior for cascading destroy. If set to :destroy, all the
32 32 # child objects are destroyed alongside this object by calling their destroy
33 33 # method. If set to :delete_all (default), all the child objects are deleted
34 34 # without calling their destroy method.
35 35 # * +:counter_cache+ adds a counter cache for the number of children.
36 36 # defaults to false.
37 37 # Example: <tt>acts_as_nested_set :counter_cache => :children_count</tt>
38 38 # * +:order_column+ on which column to do sorting, by default it is the left_column_name
39 39 # Example: <tt>acts_as_nested_set :order_column => :position</tt>
40 40 #
41 41 # See CollectiveIdea::Acts::NestedSet::Model::ClassMethods for a list of class methods and
42 42 # CollectiveIdea::Acts::NestedSet::Model for a list of instance methods added
43 43 # to acts_as_nested_set models
44 44 def acts_as_nested_set(options = {})
45 45 options = {
46 46 :parent_column => 'parent_id',
47 47 :left_column => 'lft',
48 48 :right_column => 'rgt',
49 49 :depth_column => 'depth',
50 50 :dependent => :delete_all, # or :destroy
51 51 :polymorphic => false,
52 52 :counter_cache => false
53 53 }.merge(options)
54 54
55 55 if options[:scope].is_a?(Symbol) && options[:scope].to_s !~ /_id$/
56 56 options[:scope] = "#{options[:scope]}_id".intern
57 57 end
58 58
59 59 class_attribute :acts_as_nested_set_options
60 60 self.acts_as_nested_set_options = options
61 61
62 62 include CollectiveIdea::Acts::NestedSet::Model
63 63 include Columns
64 64 extend Columns
65 65
66 66 belongs_to :parent, :class_name => self.base_class.to_s,
67 67 :foreign_key => parent_column_name,
68 68 :counter_cache => options[:counter_cache],
69 69 :inverse_of => (:children unless options[:polymorphic]),
70 70 :polymorphic => options[:polymorphic]
71 71
72 72 has_many_children_options = {
73 73 :class_name => self.base_class.to_s,
74 74 :foreign_key => parent_column_name,
75 75 :order => order_column,
76 76 :inverse_of => (:parent unless options[:polymorphic]),
77 77 }
78 78
79 79 # Add callbacks, if they were supplied.. otherwise, we don't want them.
80 80 [:before_add, :after_add, :before_remove, :after_remove].each do |ar_callback|
81 81 has_many_children_options.update(ar_callback => options[ar_callback]) if options[ar_callback]
82 82 end
83 83
84 84 has_many :children, has_many_children_options
85 85
86 86 attr_accessor :skip_before_destroy
87 87
88 88 before_create :set_default_left_and_right
89 89 before_save :store_new_parent
90 90 after_save :move_to_new_parent, :set_depth!
91 91 before_destroy :destroy_descendants
92 92
93 93 # no assignment to structure fields
94 94 [left_column_name, right_column_name, depth_column_name].each do |column|
95 95 module_eval <<-"end_eval", __FILE__, __LINE__
96 96 def #{column}=(x)
97 97 raise ActiveRecord::ActiveRecordError, "Unauthorized assignment to #{column}: it's an internal field handled by acts_as_nested_set code, use move_to_* methods instead."
98 98 end
99 99 end_eval
100 100 end
101 101
102 102 define_model_callbacks :move
103 103 end
104 104
105 105 module Model
106 106 extend ActiveSupport::Concern
107 107
108 108 included do
109 109 delegate :quoted_table_name, :to => self
110 110 end
111 111
112 112 module ClassMethods
113 113 # Returns the first root
114 114 def root
115 115 roots.first
116 116 end
117 117
118 118 def roots
119 119 where(parent_column_name => nil).order(quoted_left_column_full_name)
120 120 end
121 121
122 122 def leaves
123 123 where("#{quoted_right_column_full_name} - #{quoted_left_column_full_name} = 1").order(quoted_left_column_full_name)
124 124 end
125 125
126 126 def valid?
127 127 left_and_rights_valid? && no_duplicates_for_columns? && all_roots_valid?
128 128 end
129 129
130 130 def left_and_rights_valid?
131 131 ## AS clause not supported in Oracle in FROM clause for aliasing table name
132 132 joins("LEFT OUTER JOIN #{quoted_table_name}" +
133 133 (connection.adapter_name.match(/Oracle/).nil? ? " AS " : " ") +
134 134 "parent ON " +
135 135 "#{quoted_parent_column_full_name} = parent.#{primary_key}").
136 136 where(
137 137 "#{quoted_left_column_full_name} IS NULL OR " +
138 138 "#{quoted_right_column_full_name} IS NULL OR " +
139 139 "#{quoted_left_column_full_name} >= " +
140 140 "#{quoted_right_column_full_name} OR " +
141 141 "(#{quoted_parent_column_full_name} IS NOT NULL AND " +
142 142 "(#{quoted_left_column_full_name} <= parent.#{quoted_left_column_name} OR " +
143 143 "#{quoted_right_column_full_name} >= parent.#{quoted_right_column_name}))"
144 144 ).count == 0
145 145 end
146 146
147 147 def no_duplicates_for_columns?
148 148 scope_string = Array(acts_as_nested_set_options[:scope]).map do |c|
149 149 connection.quote_column_name(c)
150 150 end.push(nil).join(", ")
151 151 [quoted_left_column_full_name, quoted_right_column_full_name].all? do |column|
152 152 # No duplicates
153 153 select("#{scope_string}#{column}, COUNT(#{column})").
154 154 group("#{scope_string}#{column}").
155 155 having("COUNT(#{column}) > 1").
156 156 first.nil?
157 157 end
158 158 end
159 159
160 160 # Wrapper for each_root_valid? that can deal with scope.
161 161 def all_roots_valid?
162 162 if acts_as_nested_set_options[:scope]
163 163 roots.group_by {|record| scope_column_names.collect {|col| record.send(col.to_sym) } }.all? do |scope, grouped_roots|
164 164 each_root_valid?(grouped_roots)
165 165 end
166 166 else
167 167 each_root_valid?(roots)
168 168 end
169 169 end
170 170
171 171 def each_root_valid?(roots_to_validate)
172 172 left = right = 0
173 173 roots_to_validate.all? do |root|
174 174 (root.left > left && root.right > right).tap do
175 175 left = root.left
176 176 right = root.right
177 177 end
178 178 end
179 179 end
180 180
181 181 # Rebuilds the left & rights if unset or invalid.
182 182 # Also very useful for converting from acts_as_tree.
183 183 def rebuild!(validate_nodes = true)
184 184 # Don't rebuild a valid tree.
185 185 return true if valid?
186 186
187 187 scope = lambda{|node|}
188 188 if acts_as_nested_set_options[:scope]
189 189 scope = lambda{|node|
190 190 scope_column_names.inject(""){|str, column_name|
191 191 str << "AND #{connection.quote_column_name(column_name)} = #{connection.quote(node.send(column_name.to_sym))} "
192 192 }
193 193 }
194 194 end
195 195 indices = {}
196 196
197 197 set_left_and_rights = lambda do |node|
198 198 # set left
199 199 node[left_column_name] = indices[scope.call(node)] += 1
200 200 # find
201 where(["#{quoted_parent_column_name} = ? #{scope.call(node)}", node]).
202 order(acts_as_nested_set_options[:order]).
203 each{|n| set_left_and_rights.call(n) }
201 where(["#{quoted_parent_column_full_name} = ? #{scope.call(node)}", node]).order("#{quoted_left_column_full_name}, #{quoted_right_column_full_name}, id").each{|n| set_left_and_rights.call(n) }
204 202 # set right
205 203 node[right_column_name] = indices[scope.call(node)] += 1
206 204 node.save!(:validate => validate_nodes)
207 205 end
208 206
209 207 # Find root node(s)
210 root_nodes = where("#{quoted_parent_column_name} IS NULL").
211 order(acts_as_nested_set_options[:order]).each do |root_node|
208 root_nodes = where("#{quoted_parent_column_full_name} IS NULL").
209 order(acts_as_nested_set_options[:order_column]).
210 each do |root_node|
212 211 # setup index for this scope
213 212 indices[scope.call(root_node)] ||= 0
214 213 set_left_and_rights.call(root_node)
215 214 end
216 215 end
217 216
218 217 # Iterates over tree elements and determines the current level in the tree.
219 218 # Only accepts default ordering, odering by an other column than lft
220 219 # does not work. This method is much more efficent than calling level
221 220 # because it doesn't require any additional database queries.
222 221 #
223 222 # Example:
224 223 # Category.each_with_level(Category.root.self_and_descendants) do |o, level|
225 224 #
226 225 def each_with_level(objects)
227 226 path = [nil]
228 227 objects.each do |o|
229 228 if o.parent_id != path.last
230 229 # we are on a new level, did we descend or ascend?
231 230 if path.include?(o.parent_id)
232 231 # remove wrong wrong tailing paths elements
233 232 path.pop while path.last != o.parent_id
234 233 else
235 234 path << o.parent_id
236 235 end
237 236 end
238 237 yield(o, path.length - 1)
239 238 end
240 239 end
241 240
242 241 # Same as each_with_level - Accepts a string as a second argument to sort the list
243 242 # Example:
244 243 # Category.each_with_level(Category.root.self_and_descendants, :sort_by_this_column) do |o, level|
245 244 def sorted_each_with_level(objects, order)
246 245 path = [nil]
247 246 children = []
248 247 objects.each do |o|
249 248 children << o if o.leaf?
250 249 if o.parent_id != path.last
251 250 if !children.empty? && !o.leaf?
252 251 children.sort_by! &order
253 252 children.each { |c| yield(c, path.length-1) }
254 253 children = []
255 254 end
256 255 # we are on a new level, did we decent or ascent?
257 256 if path.include?(o.parent_id)
258 257 # remove wrong wrong tailing paths elements
259 258 path.pop while path.last != o.parent_id
260 259 else
261 260 path << o.parent_id
262 261 end
263 262 end
264 263 yield(o,path.length-1) if !o.leaf?
265 264 end
266 265 if !children.empty?
267 266 children.sort_by! &order
268 267 children.each { |c| yield(c, path.length-1) }
269 268 end
270 269 end
271 270
272 271 def associate_parents(objects)
273 272 if objects.all?{|o| o.respond_to?(:association)}
274 273 id_indexed = objects.index_by(&:id)
275 274 objects.each do |object|
276 275 if !(association = object.association(:parent)).loaded? && (parent = id_indexed[object.parent_id])
277 276 association.target = parent
278 277 association.set_inverse_instance(parent)
279 278 end
280 279 end
281 280 else
282 281 objects
283 282 end
284 283 end
285 284 end
286 285
287 286 # Any instance method that returns a collection makes use of Rails 2.1's named_scope (which is bundled for Rails 2.0), so it can be treated as a finder.
288 287 #
289 288 # category.self_and_descendants.count
290 289 # category.ancestors.find(:all, :conditions => "name like '%foo%'")
291 290 # Value of the parent column
292 291 def parent_id
293 292 self[parent_column_name]
294 293 end
295 294
296 295 # Value of the left column
297 296 def left
298 297 self[left_column_name]
299 298 end
300 299
301 300 # Value of the right column
302 301 def right
303 302 self[right_column_name]
304 303 end
305 304
306 305 # Returns true if this is a root node.
307 306 def root?
308 307 parent_id.nil?
309 308 end
310 309
311 310 # Returns true if this is the end of a branch.
312 311 def leaf?
313 312 new_record? || (persisted? && right.to_i - left.to_i == 1)
314 313 end
315 314
316 315 # Returns true is this is a child node
317 316 def child?
318 317 !root?
319 318 end
320 319
321 320 # Returns root
322 321 def root
323 322 if persisted?
324 323 self_and_ancestors.where(parent_column_name => nil).first
325 324 else
326 325 if parent_id && current_parent = nested_set_scope.find(parent_id)
327 326 current_parent.root
328 327 else
329 328 self
330 329 end
331 330 end
332 331 end
333 332
334 333 # Returns the array of all parents and self
335 334 def self_and_ancestors
336 335 nested_set_scope.where([
337 336 "#{quoted_left_column_full_name} <= ? AND #{quoted_right_column_full_name} >= ?", left, right
338 337 ])
339 338 end
340 339
341 340 # Returns an array of all parents
342 341 def ancestors
343 342 without_self self_and_ancestors
344 343 end
345 344
346 345 # Returns the array of all children of the parent, including self
347 346 def self_and_siblings
348 347 nested_set_scope.where(parent_column_name => parent_id)
349 348 end
350 349
351 350 # Returns the array of all children of the parent, except self
352 351 def siblings
353 352 without_self self_and_siblings
354 353 end
355 354
356 355 # Returns a set of all of its nested children which do not have children
357 356 def leaves
358 357 descendants.where("#{quoted_right_column_full_name} - #{quoted_left_column_full_name} = 1")
359 358 end
360 359
361 360 # Returns the level of this object in the tree
362 361 # root level is 0
363 362 def level
364 363 parent_id.nil? ? 0 : compute_level
365 364 end
366 365
367 366 # Returns a set of itself and all of its nested children
368 367 def self_and_descendants
369 368 nested_set_scope.where([
370 369 "#{quoted_left_column_full_name} >= ? AND #{quoted_left_column_full_name} < ?", left, right
371 370 # using _left_ for both sides here lets us benefit from an index on that column if one exists
372 371 ])
373 372 end
374 373
375 374 # Returns a set of all of its children and nested children
376 375 def descendants
377 376 without_self self_and_descendants
378 377 end
379 378
380 379 def is_descendant_of?(other)
381 380 other.left < self.left && self.left < other.right && same_scope?(other)
382 381 end
383 382
384 383 def is_or_is_descendant_of?(other)
385 384 other.left <= self.left && self.left < other.right && same_scope?(other)
386 385 end
387 386
388 387 def is_ancestor_of?(other)
389 388 self.left < other.left && other.left < self.right && same_scope?(other)
390 389 end
391 390
392 391 def is_or_is_ancestor_of?(other)
393 392 self.left <= other.left && other.left < self.right && same_scope?(other)
394 393 end
395 394
396 395 # Check if other model is in the same scope
397 396 def same_scope?(other)
398 397 Array(acts_as_nested_set_options[:scope]).all? do |attr|
399 398 self.send(attr) == other.send(attr)
400 399 end
401 400 end
402 401
403 402 # Find the first sibling to the left
404 403 def left_sibling
405 404 siblings.where(["#{quoted_left_column_full_name} < ?", left]).
406 405 order("#{quoted_left_column_full_name} DESC").last
407 406 end
408 407
409 408 # Find the first sibling to the right
410 409 def right_sibling
411 410 siblings.where(["#{quoted_left_column_full_name} > ?", left]).first
412 411 end
413 412
414 413 # Shorthand method for finding the left sibling and moving to the left of it.
415 414 def move_left
416 415 move_to_left_of left_sibling
417 416 end
418 417
419 418 # Shorthand method for finding the right sibling and moving to the right of it.
420 419 def move_right
421 420 move_to_right_of right_sibling
422 421 end
423 422
424 423 # Move the node to the left of another node (you can pass id only)
425 424 def move_to_left_of(node)
426 425 move_to node, :left
427 426 end
428 427
429 428 # Move the node to the left of another node (you can pass id only)
430 429 def move_to_right_of(node)
431 430 move_to node, :right
432 431 end
433 432
434 433 # Move the node to the child of another node (you can pass id only)
435 434 def move_to_child_of(node)
436 435 move_to node, :child
437 436 end
438 437
439 438 # Move the node to the child of another node with specify index (you can pass id only)
440 439 def move_to_child_with_index(node, index)
441 440 if node.children.empty?
442 441 move_to_child_of(node)
443 442 elsif node.children.count == index
444 443 move_to_right_of(node.children.last)
445 444 else
446 445 move_to_left_of(node.children[index])
447 446 end
448 447 end
449 448
450 449 # Move the node to root nodes
451 450 def move_to_root
452 451 move_to nil, :root
453 452 end
454 453
455 454 # Order children in a nested set by an attribute
456 455 # Can order by any attribute class that uses the Comparable mixin, for example a string or integer
457 456 # Usage example when sorting categories alphabetically: @new_category.move_to_ordered_child_of(@root, "name")
458 457 def move_to_ordered_child_of(parent, order_attribute, ascending = true)
459 458 self.move_to_root and return unless parent
460 459 left = nil # This is needed, at least for the tests.
461 460 parent.children.each do |n| # Find the node immediately to the left of this node.
462 461 if ascending
463 462 left = n if n.send(order_attribute) < self.send(order_attribute)
464 463 else
465 464 left = n if n.send(order_attribute) > self.send(order_attribute)
466 465 end
467 466 end
468 467 self.move_to_child_of(parent)
469 468 return unless parent.children.count > 1 # Only need to order if there are multiple children.
470 469 if left # Self has a left neighbor.
471 470 self.move_to_right_of(left)
472 471 else # Self is the left most node.
473 472 self.move_to_left_of(parent.children[0])
474 473 end
475 474 end
476 475
477 476 def move_possible?(target)
478 477 self != target && # Can't target self
479 478 same_scope?(target) && # can't be in different scopes
480 479 # !(left..right).include?(target.left..target.right) # this needs tested more
481 480 # detect impossible move
482 481 !((left <= target.left && right >= target.left) or (left <= target.right && right >= target.right))
483 482 end
484 483
485 484 def to_text
486 485 self_and_descendants.map do |node|
487 486 "#{'*'*(node.level+1)} #{node.id} #{node.to_s} (#{node.parent_id}, #{node.left}, #{node.right})"
488 487 end.join("\n")
489 488 end
490 489
491 490 protected
492 491 def compute_level
493 492 node, nesting = self, 0
494 493 while (association = node.association(:parent)).loaded? && association.target
495 494 nesting += 1
496 495 node = node.parent
497 496 end if node.respond_to? :association
498 497 node == self ? ancestors.count : node.level + nesting
499 498 end
500 499
501 500 def without_self(scope)
502 501 scope.where(["#{self.class.quoted_table_name}.#{self.class.primary_key} != ?", self])
503 502 end
504 503
505 504 # All nested set queries should use this nested_set_scope, which performs finds on
506 505 # the base ActiveRecord class, using the :scope declared in the acts_as_nested_set
507 506 # declaration.
508 507 def nested_set_scope(options = {})
509 508 options = {:order => quoted_left_column_full_name}.merge(options)
510 509 scopes = Array(acts_as_nested_set_options[:scope])
511 510 options[:conditions] = scopes.inject({}) do |conditions,attr|
512 511 conditions.merge attr => self[attr]
513 512 end unless scopes.empty?
514 513 self.class.base_class.unscoped.scoped options
515 514 end
516 515
517 516 def store_new_parent
518 517 @move_to_new_parent_id = send("#{parent_column_name}_changed?") ? parent_id : false
519 518 true # force callback to return true
520 519 end
521 520
522 521 def move_to_new_parent
523 522 if @move_to_new_parent_id.nil?
524 523 move_to_root
525 524 elsif @move_to_new_parent_id
526 525 move_to_child_of(@move_to_new_parent_id)
527 526 end
528 527 end
529 528
530 529 def set_depth!
531 530 if nested_set_scope.column_names.map(&:to_s).include?(depth_column_name.to_s)
532 531 in_tenacious_transaction do
533 532 reload
534 533
535 534 nested_set_scope.where(:id => id).update_all(["#{quoted_depth_column_name} = ?", level])
536 535 end
537 536 self[depth_column_name.to_sym] = self.level
538 537 end
539 538 end
540 539
541 540 # on creation, set automatically lft and rgt to the end of the tree
542 541 def set_default_left_and_right
543 542 highest_right_row = nested_set_scope(:order => "#{quoted_right_column_full_name} desc").limit(1).lock(true).first
544 543 maxright = highest_right_row ? (highest_right_row[right_column_name] || 0) : 0
545 544 # adds the new node to the right of all existing nodes
546 545 self[left_column_name] = maxright + 1
547 546 self[right_column_name] = maxright + 2
548 547 end
549 548
550 549 def in_tenacious_transaction(&block)
551 550 retry_count = 0
552 551 begin
553 552 transaction(&block)
554 553 rescue ActiveRecord::StatementInvalid => error
555 554 raise unless connection.open_transactions.zero?
556 555 raise unless error.message =~ /Deadlock found when trying to get lock|Lock wait timeout exceeded/
557 556 raise unless retry_count < 10
558 557 retry_count += 1
559 558 logger.info "Deadlock detected on retry #{retry_count}, restarting transaction"
560 559 sleep(rand(retry_count)*0.1) # Aloha protocol
561 560 retry
562 561 end
563 562 end
564 563
565 564 # Prunes a branch off of the tree, shifting all of the elements on the right
566 565 # back to the left so the counts still work.
567 566 def destroy_descendants
568 567 return if right.nil? || left.nil? || skip_before_destroy
569 568
570 569 in_tenacious_transaction do
571 570 reload_nested_set
572 571 # select the rows in the model that extend past the deletion point and apply a lock
573 572 nested_set_scope.where(["#{quoted_left_column_full_name} >= ?", left]).
574 573 select(id).lock(true)
575 574
576 575 if acts_as_nested_set_options[:dependent] == :destroy
577 576 descendants.each do |model|
578 577 model.skip_before_destroy = true
579 578 model.destroy
580 579 end
581 580 else
582 581 nested_set_scope.where(["#{quoted_left_column_name} > ? AND #{quoted_right_column_name} < ?", left, right]).
583 582 delete_all
584 583 end
585 584
586 585 # update lefts and rights for remaining nodes
587 586 diff = right - left + 1
588 587 nested_set_scope.where(["#{quoted_left_column_full_name} > ?", right]).update_all(
589 588 ["#{quoted_left_column_name} = (#{quoted_left_column_name} - ?)", diff]
590 589 )
591 590
592 591 nested_set_scope.where(["#{quoted_right_column_full_name} > ?", right]).update_all(
593 592 ["#{quoted_right_column_name} = (#{quoted_right_column_name} - ?)", diff]
594 593 )
595 594
596 595 reload
597 596 # Don't allow multiple calls to destroy to corrupt the set
598 597 self.skip_before_destroy = true
599 598 end
600 599 end
601 600
602 601 # reload left, right, and parent
603 602 def reload_nested_set
604 603 reload(
605 604 :select => "#{quoted_left_column_full_name}, #{quoted_right_column_full_name}, #{quoted_parent_column_full_name}",
606 605 :lock => true
607 606 )
608 607 end
609 608
610 609 def move_to(target, position)
611 610 raise ActiveRecord::ActiveRecordError, "You cannot move a new node" if self.new_record?
612 611 run_callbacks :move do
613 612 in_tenacious_transaction do
614 613 if target.is_a? self.class.base_class
615 614 target.reload_nested_set
616 615 elsif position != :root
617 616 # load object if node is not an object
618 617 target = nested_set_scope.find(target)
619 618 end
620 619 self.reload_nested_set
621 620
622 621 unless position == :root || move_possible?(target)
623 622 raise ActiveRecord::ActiveRecordError, "Impossible move, target node cannot be inside moved tree."
624 623 end
625 624
626 625 bound = case position
627 626 when :child; target[right_column_name]
628 627 when :left; target[left_column_name]
629 628 when :right; target[right_column_name] + 1
630 629 when :root; 1
631 630 else raise ActiveRecord::ActiveRecordError, "Position should be :child, :left, :right or :root ('#{position}' received)."
632 631 end
633 632
634 633 if bound > self[right_column_name]
635 634 bound = bound - 1
636 635 other_bound = self[right_column_name] + 1
637 636 else
638 637 other_bound = self[left_column_name] - 1
639 638 end
640 639
641 640 # there would be no change
642 641 return if bound == self[right_column_name] || bound == self[left_column_name]
643 642
644 643 # we have defined the boundaries of two non-overlapping intervals,
645 644 # so sorting puts both the intervals and their boundaries in order
646 645 a, b, c, d = [self[left_column_name], self[right_column_name], bound, other_bound].sort
647 646
648 647 # select the rows in the model between a and d, and apply a lock
649 648 self.class.base_class.select('id').lock(true).where(
650 649 ["#{quoted_left_column_full_name} >= :a and #{quoted_right_column_full_name} <= :d", {:a => a, :d => d}]
651 650 )
652 651
653 652 new_parent = case position
654 653 when :child; target.id
655 654 when :root; nil
656 655 else target[parent_column_name]
657 656 end
658 657
659 658 self.nested_set_scope.update_all([
660 659 "#{quoted_left_column_name} = CASE " +
661 660 "WHEN #{quoted_left_column_name} BETWEEN :a AND :b " +
662 661 "THEN #{quoted_left_column_name} + :d - :b " +
663 662 "WHEN #{quoted_left_column_name} BETWEEN :c AND :d " +
664 663 "THEN #{quoted_left_column_name} + :a - :c " +
665 664 "ELSE #{quoted_left_column_name} END, " +
666 665 "#{quoted_right_column_name} = CASE " +
667 666 "WHEN #{quoted_right_column_name} BETWEEN :a AND :b " +
668 667 "THEN #{quoted_right_column_name} + :d - :b " +
669 668 "WHEN #{quoted_right_column_name} BETWEEN :c AND :d " +
670 669 "THEN #{quoted_right_column_name} + :a - :c " +
671 670 "ELSE #{quoted_right_column_name} END, " +
672 671 "#{quoted_parent_column_name} = CASE " +
673 672 "WHEN #{self.class.base_class.primary_key} = :id THEN :new_parent " +
674 673 "ELSE #{quoted_parent_column_name} END",
675 674 {:a => a, :b => b, :c => c, :d => d, :id => self.id, :new_parent => new_parent}
676 675 ])
677 676 end
678 677 target.reload_nested_set if target
679 678 self.set_depth!
680 679 self.descendants.each(&:save)
681 680 self.reload_nested_set
682 681 end
683 682 end
684 683
685 684 end
686 685
687 686 # Mixed into both classes and instances to provide easy access to the column names
688 687 module Columns
689 688 def left_column_name
690 689 acts_as_nested_set_options[:left_column]
691 690 end
692 691
693 692 def right_column_name
694 693 acts_as_nested_set_options[:right_column]
695 694 end
696 695
697 696 def depth_column_name
698 697 acts_as_nested_set_options[:depth_column]
699 698 end
700 699
701 700 def parent_column_name
702 701 acts_as_nested_set_options[:parent_column]
703 702 end
704 703
705 704 def order_column
706 705 acts_as_nested_set_options[:order_column] || left_column_name
707 706 end
708 707
709 708 def scope_column_names
710 709 Array(acts_as_nested_set_options[:scope])
711 710 end
712 711
713 712 def quoted_left_column_name
714 713 connection.quote_column_name(left_column_name)
715 714 end
716 715
717 716 def quoted_right_column_name
718 717 connection.quote_column_name(right_column_name)
719 718 end
720 719
721 720 def quoted_depth_column_name
722 721 connection.quote_column_name(depth_column_name)
723 722 end
724 723
725 724 def quoted_parent_column_name
726 725 connection.quote_column_name(parent_column_name)
727 726 end
728 727
729 728 def quoted_scope_column_names
730 729 scope_column_names.collect {|column_name| connection.quote_column_name(column_name) }
731 730 end
732 731
733 732 def quoted_left_column_full_name
734 733 "#{quoted_table_name}.#{quoted_left_column_name}"
735 734 end
736 735
737 736 def quoted_right_column_full_name
738 737 "#{quoted_table_name}.#{quoted_right_column_name}"
739 738 end
740 739
741 740 def quoted_parent_column_full_name
742 741 "#{quoted_table_name}.#{quoted_parent_column_name}"
743 742 end
744 743 end
745 744
746 745 end
747 746 end
748 747 end
General Comments 0
You need to be logged in to leave comments. Login now