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