##// END OF EJS Templates
Do not try to copy relations for issues that could not be copied....
Jean-Philippe Lang -
r4370:cd71c1cc0ad7
parent child
Show More
@@ -1,813 +1,821
1 1 # redMine - project management software
2 2 # Copyright (C) 2006 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 # Project statuses
20 20 STATUS_ACTIVE = 1
21 21 STATUS_ARCHIVED = 9
22 22
23 23 # Maximum length for project identifiers
24 24 IDENTIFIER_MAX_LENGTH = 100
25 25
26 26 # Specific overidden Activities
27 27 has_many :time_entry_activities
28 28 has_many :members, :include => [:user, :roles], :conditions => "#{User.table_name}.type='User' AND #{User.table_name}.status=#{User::STATUS_ACTIVE}"
29 29 has_many :memberships, :class_name => 'Member'
30 30 has_many :member_principals, :class_name => 'Member',
31 31 :include => :principal,
32 32 :conditions => "#{Principal.table_name}.type='Group' OR (#{Principal.table_name}.type='User' AND #{Principal.table_name}.status=#{User::STATUS_ACTIVE})"
33 33 has_many :users, :through => :members
34 34 has_many :principals, :through => :member_principals, :source => :principal
35 35
36 36 has_many :enabled_modules, :dependent => :delete_all
37 37 has_and_belongs_to_many :trackers, :order => "#{Tracker.table_name}.position"
38 38 has_many :issues, :dependent => :destroy, :order => "#{Issue.table_name}.created_on DESC", :include => [:status, :tracker]
39 39 has_many :issue_changes, :through => :issues, :source => :journals
40 40 has_many :versions, :dependent => :destroy, :order => "#{Version.table_name}.effective_date DESC, #{Version.table_name}.name DESC"
41 41 has_many :time_entries, :dependent => :delete_all
42 42 has_many :queries, :dependent => :delete_all
43 43 has_many :documents, :dependent => :destroy
44 44 has_many :news, :dependent => :delete_all, :include => :author
45 45 has_many :issue_categories, :dependent => :delete_all, :order => "#{IssueCategory.table_name}.name"
46 46 has_many :boards, :dependent => :destroy, :order => "position ASC"
47 47 has_one :repository, :dependent => :destroy
48 48 has_many :changesets, :through => :repository
49 49 has_one :wiki, :dependent => :destroy
50 50 # Custom field for the project issues
51 51 has_and_belongs_to_many :issue_custom_fields,
52 52 :class_name => 'IssueCustomField',
53 53 :order => "#{CustomField.table_name}.position",
54 54 :join_table => "#{table_name_prefix}custom_fields_projects#{table_name_suffix}",
55 55 :association_foreign_key => 'custom_field_id'
56 56
57 57 acts_as_nested_set :order => 'name'
58 58 acts_as_attachable :view_permission => :view_files,
59 59 :delete_permission => :manage_files
60 60
61 61 acts_as_customizable
62 62 acts_as_searchable :columns => ['name', 'identifier', 'description'], :project_key => 'id', :permission => nil
63 63 acts_as_event :title => Proc.new {|o| "#{l(:label_project)}: #{o.name}"},
64 64 :url => Proc.new {|o| {:controller => 'projects', :action => 'show', :id => o}},
65 65 :author => nil
66 66
67 67 attr_protected :status, :enabled_module_names
68 68
69 69 validates_presence_of :name, :identifier
70 70 validates_uniqueness_of :identifier
71 71 validates_associated :repository, :wiki
72 72 validates_length_of :name, :maximum => 255
73 73 validates_length_of :homepage, :maximum => 255
74 74 validates_length_of :identifier, :in => 1..IDENTIFIER_MAX_LENGTH
75 75 # donwcase letters, digits, dashes but not digits only
76 76 validates_format_of :identifier, :with => /^(?!\d+$)[a-z0-9\-]*$/, :if => Proc.new { |p| p.identifier_changed? }
77 77 # reserved words
78 78 validates_exclusion_of :identifier, :in => %w( new )
79 79
80 80 before_destroy :delete_all_members, :destroy_children
81 81
82 82 named_scope :has_module, lambda { |mod| { :conditions => ["#{Project.table_name}.id IN (SELECT em.project_id FROM #{EnabledModule.table_name} em WHERE em.name=?)", mod.to_s] } }
83 83 named_scope :active, { :conditions => "#{Project.table_name}.status = #{STATUS_ACTIVE}"}
84 84 named_scope :all_public, { :conditions => { :is_public => true } }
85 85 named_scope :visible, lambda { { :conditions => Project.visible_by(User.current) } }
86 86
87 87 def initialize(attributes = nil)
88 88 super
89 89
90 90 initialized = (attributes || {}).stringify_keys
91 91 if !initialized.key?('identifier') && Setting.sequential_project_identifiers?
92 92 self.identifier = Project.next_identifier
93 93 end
94 94 if !initialized.key?('is_public')
95 95 self.is_public = Setting.default_projects_public?
96 96 end
97 97 if !initialized.key?('enabled_module_names')
98 98 self.enabled_module_names = Setting.default_projects_modules
99 99 end
100 100 if !initialized.key?('trackers') && !initialized.key?('tracker_ids')
101 101 self.trackers = Tracker.all
102 102 end
103 103 end
104 104
105 105 def identifier=(identifier)
106 106 super unless identifier_frozen?
107 107 end
108 108
109 109 def identifier_frozen?
110 110 errors[:identifier].nil? && !(new_record? || identifier.blank?)
111 111 end
112 112
113 113 # returns latest created projects
114 114 # non public projects will be returned only if user is a member of those
115 115 def self.latest(user=nil, count=5)
116 116 find(:all, :limit => count, :conditions => visible_by(user), :order => "created_on DESC")
117 117 end
118 118
119 119 # Returns a SQL :conditions string used to find all active projects for the specified user.
120 120 #
121 121 # Examples:
122 122 # Projects.visible_by(admin) => "projects.status = 1"
123 123 # Projects.visible_by(normal_user) => "projects.status = 1 AND projects.is_public = 1"
124 124 def self.visible_by(user=nil)
125 125 user ||= User.current
126 126 if user && user.admin?
127 127 return "#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"
128 128 elsif user && user.memberships.any?
129 129 return "#{Project.table_name}.status=#{Project::STATUS_ACTIVE} AND (#{Project.table_name}.is_public = #{connection.quoted_true} or #{Project.table_name}.id IN (#{user.memberships.collect{|m| m.project_id}.join(',')}))"
130 130 else
131 131 return "#{Project.table_name}.status=#{Project::STATUS_ACTIVE} AND #{Project.table_name}.is_public = #{connection.quoted_true}"
132 132 end
133 133 end
134 134
135 135 def self.allowed_to_condition(user, permission, options={})
136 136 statements = []
137 137 base_statement = "#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"
138 138 if perm = Redmine::AccessControl.permission(permission)
139 139 unless perm.project_module.nil?
140 140 # If the permission belongs to a project module, make sure the module is enabled
141 141 base_statement << " AND #{Project.table_name}.id IN (SELECT em.project_id FROM #{EnabledModule.table_name} em WHERE em.name='#{perm.project_module}')"
142 142 end
143 143 end
144 144 if options[:project]
145 145 project_statement = "#{Project.table_name}.id = #{options[:project].id}"
146 146 project_statement << " OR (#{Project.table_name}.lft > #{options[:project].lft} AND #{Project.table_name}.rgt < #{options[:project].rgt})" if options[:with_subprojects]
147 147 base_statement = "(#{project_statement}) AND (#{base_statement})"
148 148 end
149 149 if user.admin?
150 150 # no restriction
151 151 else
152 152 statements << "1=0"
153 153 if user.logged?
154 154 if Role.non_member.allowed_to?(permission) && !options[:member]
155 155 statements << "#{Project.table_name}.is_public = #{connection.quoted_true}"
156 156 end
157 157 allowed_project_ids = user.memberships.select {|m| m.roles.detect {|role| role.allowed_to?(permission)}}.collect {|m| m.project_id}
158 158 statements << "#{Project.table_name}.id IN (#{allowed_project_ids.join(',')})" if allowed_project_ids.any?
159 159 else
160 160 if Role.anonymous.allowed_to?(permission) && !options[:member]
161 161 # anonymous user allowed on public project
162 162 statements << "#{Project.table_name}.is_public = #{connection.quoted_true}"
163 163 end
164 164 end
165 165 end
166 166 statements.empty? ? base_statement : "((#{base_statement}) AND (#{statements.join(' OR ')}))"
167 167 end
168 168
169 169 # Returns the Systemwide and project specific activities
170 170 def activities(include_inactive=false)
171 171 if include_inactive
172 172 return all_activities
173 173 else
174 174 return active_activities
175 175 end
176 176 end
177 177
178 178 # Will create a new Project specific Activity or update an existing one
179 179 #
180 180 # This will raise a ActiveRecord::Rollback if the TimeEntryActivity
181 181 # does not successfully save.
182 182 def update_or_create_time_entry_activity(id, activity_hash)
183 183 if activity_hash.respond_to?(:has_key?) && activity_hash.has_key?('parent_id')
184 184 self.create_time_entry_activity_if_needed(activity_hash)
185 185 else
186 186 activity = project.time_entry_activities.find_by_id(id.to_i)
187 187 activity.update_attributes(activity_hash) if activity
188 188 end
189 189 end
190 190
191 191 # Create a new TimeEntryActivity if it overrides a system TimeEntryActivity
192 192 #
193 193 # This will raise a ActiveRecord::Rollback if the TimeEntryActivity
194 194 # does not successfully save.
195 195 def create_time_entry_activity_if_needed(activity)
196 196 if activity['parent_id']
197 197
198 198 parent_activity = TimeEntryActivity.find(activity['parent_id'])
199 199 activity['name'] = parent_activity.name
200 200 activity['position'] = parent_activity.position
201 201
202 202 if Enumeration.overridding_change?(activity, parent_activity)
203 203 project_activity = self.time_entry_activities.create(activity)
204 204
205 205 if project_activity.new_record?
206 206 raise ActiveRecord::Rollback, "Overridding TimeEntryActivity was not successfully saved"
207 207 else
208 208 self.time_entries.update_all("activity_id = #{project_activity.id}", ["activity_id = ?", parent_activity.id])
209 209 end
210 210 end
211 211 end
212 212 end
213 213
214 214 # Returns a :conditions SQL string that can be used to find the issues associated with this project.
215 215 #
216 216 # Examples:
217 217 # project.project_condition(true) => "(projects.id = 1 OR (projects.lft > 1 AND projects.rgt < 10))"
218 218 # project.project_condition(false) => "projects.id = 1"
219 219 def project_condition(with_subprojects)
220 220 cond = "#{Project.table_name}.id = #{id}"
221 221 cond = "(#{cond} OR (#{Project.table_name}.lft > #{lft} AND #{Project.table_name}.rgt < #{rgt}))" if with_subprojects
222 222 cond
223 223 end
224 224
225 225 def self.find(*args)
226 226 if args.first && args.first.is_a?(String) && !args.first.match(/^\d*$/)
227 227 project = find_by_identifier(*args)
228 228 raise ActiveRecord::RecordNotFound, "Couldn't find Project with identifier=#{args.first}" if project.nil?
229 229 project
230 230 else
231 231 super
232 232 end
233 233 end
234 234
235 235 def to_param
236 236 # id is used for projects with a numeric identifier (compatibility)
237 237 @to_param ||= (identifier.to_s =~ %r{^\d*$} ? id : identifier)
238 238 end
239 239
240 240 def active?
241 241 self.status == STATUS_ACTIVE
242 242 end
243 243
244 244 def archived?
245 245 self.status == STATUS_ARCHIVED
246 246 end
247 247
248 248 # Archives the project and its descendants
249 249 def archive
250 250 # Check that there is no issue of a non descendant project that is assigned
251 251 # to one of the project or descendant versions
252 252 v_ids = self_and_descendants.collect {|p| p.version_ids}.flatten
253 253 if v_ids.any? && Issue.find(:first, :include => :project,
254 254 :conditions => ["(#{Project.table_name}.lft < ? OR #{Project.table_name}.rgt > ?)" +
255 255 " AND #{Issue.table_name}.fixed_version_id IN (?)", lft, rgt, v_ids])
256 256 return false
257 257 end
258 258 Project.transaction do
259 259 archive!
260 260 end
261 261 true
262 262 end
263 263
264 264 # Unarchives the project
265 265 # All its ancestors must be active
266 266 def unarchive
267 267 return false if ancestors.detect {|a| !a.active?}
268 268 update_attribute :status, STATUS_ACTIVE
269 269 end
270 270
271 271 # Returns an array of projects the project can be moved to
272 272 # by the current user
273 273 def allowed_parents
274 274 return @allowed_parents if @allowed_parents
275 275 @allowed_parents = Project.find(:all, :conditions => Project.allowed_to_condition(User.current, :add_subprojects))
276 276 @allowed_parents = @allowed_parents - self_and_descendants
277 277 if User.current.allowed_to?(:add_project, nil, :global => true) || (!new_record? && parent.nil?)
278 278 @allowed_parents << nil
279 279 end
280 280 unless parent.nil? || @allowed_parents.empty? || @allowed_parents.include?(parent)
281 281 @allowed_parents << parent
282 282 end
283 283 @allowed_parents
284 284 end
285 285
286 286 # Sets the parent of the project with authorization check
287 287 def set_allowed_parent!(p)
288 288 unless p.nil? || p.is_a?(Project)
289 289 if p.to_s.blank?
290 290 p = nil
291 291 else
292 292 p = Project.find_by_id(p)
293 293 return false unless p
294 294 end
295 295 end
296 296 if p.nil?
297 297 if !new_record? && allowed_parents.empty?
298 298 return false
299 299 end
300 300 elsif !allowed_parents.include?(p)
301 301 return false
302 302 end
303 303 set_parent!(p)
304 304 end
305 305
306 306 # Sets the parent of the project
307 307 # Argument can be either a Project, a String, a Fixnum or nil
308 308 def set_parent!(p)
309 309 unless p.nil? || p.is_a?(Project)
310 310 if p.to_s.blank?
311 311 p = nil
312 312 else
313 313 p = Project.find_by_id(p)
314 314 return false unless p
315 315 end
316 316 end
317 317 if p == parent && !p.nil?
318 318 # Nothing to do
319 319 true
320 320 elsif p.nil? || (p.active? && move_possible?(p))
321 321 # Insert the project so that target's children or root projects stay alphabetically sorted
322 322 sibs = (p.nil? ? self.class.roots : p.children)
323 323 to_be_inserted_before = sibs.detect {|c| c.name.to_s.downcase > name.to_s.downcase }
324 324 if to_be_inserted_before
325 325 move_to_left_of(to_be_inserted_before)
326 326 elsif p.nil?
327 327 if sibs.empty?
328 328 # move_to_root adds the project in first (ie. left) position
329 329 move_to_root
330 330 else
331 331 move_to_right_of(sibs.last) unless self == sibs.last
332 332 end
333 333 else
334 334 # move_to_child_of adds the project in last (ie.right) position
335 335 move_to_child_of(p)
336 336 end
337 337 Issue.update_versions_from_hierarchy_change(self)
338 338 true
339 339 else
340 340 # Can not move to the given target
341 341 false
342 342 end
343 343 end
344 344
345 345 # Returns an array of the trackers used by the project and its active sub projects
346 346 def rolled_up_trackers
347 347 @rolled_up_trackers ||=
348 348 Tracker.find(:all, :include => :projects,
349 349 :select => "DISTINCT #{Tracker.table_name}.*",
350 350 :conditions => ["#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status = #{STATUS_ACTIVE}", lft, rgt],
351 351 :order => "#{Tracker.table_name}.position")
352 352 end
353 353
354 354 # Closes open and locked project versions that are completed
355 355 def close_completed_versions
356 356 Version.transaction do
357 357 versions.find(:all, :conditions => {:status => %w(open locked)}).each do |version|
358 358 if version.completed?
359 359 version.update_attribute(:status, 'closed')
360 360 end
361 361 end
362 362 end
363 363 end
364 364
365 365 # Returns a scope of the Versions on subprojects
366 366 def rolled_up_versions
367 367 @rolled_up_versions ||=
368 368 Version.scoped(:include => :project,
369 369 :conditions => ["#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status = #{STATUS_ACTIVE}", lft, rgt])
370 370 end
371 371
372 372 # Returns a scope of the Versions used by the project
373 373 def shared_versions
374 374 @shared_versions ||=
375 375 Version.scoped(:include => :project,
376 376 :conditions => "#{Project.table_name}.id = #{id}" +
377 377 " OR (#{Project.table_name}.status = #{Project::STATUS_ACTIVE} AND (" +
378 378 " #{Version.table_name}.sharing = 'system'" +
379 379 " OR (#{Project.table_name}.lft >= #{root.lft} AND #{Project.table_name}.rgt <= #{root.rgt} AND #{Version.table_name}.sharing = 'tree')" +
380 380 " OR (#{Project.table_name}.lft < #{lft} AND #{Project.table_name}.rgt > #{rgt} AND #{Version.table_name}.sharing IN ('hierarchy', 'descendants'))" +
381 381 " OR (#{Project.table_name}.lft > #{lft} AND #{Project.table_name}.rgt < #{rgt} AND #{Version.table_name}.sharing = 'hierarchy')" +
382 382 "))")
383 383 end
384 384
385 385 # Returns a hash of project users grouped by role
386 386 def users_by_role
387 387 members.find(:all, :include => [:user, :roles]).inject({}) do |h, m|
388 388 m.roles.each do |r|
389 389 h[r] ||= []
390 390 h[r] << m.user
391 391 end
392 392 h
393 393 end
394 394 end
395 395
396 396 # Deletes all project's members
397 397 def delete_all_members
398 398 me, mr = Member.table_name, MemberRole.table_name
399 399 connection.delete("DELETE FROM #{mr} WHERE #{mr}.member_id IN (SELECT #{me}.id FROM #{me} WHERE #{me}.project_id = #{id})")
400 400 Member.delete_all(['project_id = ?', id])
401 401 end
402 402
403 403 # Users issues can be assigned to
404 404 def assignable_users
405 405 members.select {|m| m.roles.detect {|role| role.assignable?}}.collect {|m| m.user}.sort
406 406 end
407 407
408 408 # Returns the mail adresses of users that should be always notified on project events
409 409 def recipients
410 410 notified_users.collect {|user| user.mail}
411 411 end
412 412
413 413 # Returns the users that should be notified on project events
414 414 def notified_users
415 415 # TODO: User part should be extracted to User#notify_about?
416 416 members.select {|m| m.mail_notification? || m.user.mail_notification == 'all'}.collect {|m| m.user}
417 417 end
418 418
419 419 # Returns an array of all custom fields enabled for project issues
420 420 # (explictly associated custom fields and custom fields enabled for all projects)
421 421 def all_issue_custom_fields
422 422 @all_issue_custom_fields ||= (IssueCustomField.for_all + issue_custom_fields).uniq.sort
423 423 end
424 424
425 425 def project
426 426 self
427 427 end
428 428
429 429 def <=>(project)
430 430 name.downcase <=> project.name.downcase
431 431 end
432 432
433 433 def to_s
434 434 name
435 435 end
436 436
437 437 # Returns a short description of the projects (first lines)
438 438 def short_description(length = 255)
439 439 description.gsub(/^(.{#{length}}[^\n\r]*).*$/m, '\1...').strip if description
440 440 end
441 441
442 442 def css_classes
443 443 s = 'project'
444 444 s << ' root' if root?
445 445 s << ' child' if child?
446 446 s << (leaf? ? ' leaf' : ' parent')
447 447 s
448 448 end
449 449
450 450 # The earliest start date of a project, based on it's issues and versions
451 451 def start_date
452 452 [
453 453 issues.minimum('start_date'),
454 454 shared_versions.collect(&:effective_date),
455 455 shared_versions.collect {|v| v.fixed_issues.minimum('start_date')}
456 456 ].flatten.compact.min
457 457 end
458 458
459 459 # The latest due date of an issue or version
460 460 def due_date
461 461 [
462 462 issues.maximum('due_date'),
463 463 shared_versions.collect(&:effective_date),
464 464 shared_versions.collect {|v| v.fixed_issues.maximum('due_date')}
465 465 ].flatten.compact.max
466 466 end
467 467
468 468 def overdue?
469 469 active? && !due_date.nil? && (due_date < Date.today)
470 470 end
471 471
472 472 # Returns the percent completed for this project, based on the
473 473 # progress on it's versions.
474 474 def completed_percent(options={:include_subprojects => false})
475 475 if options.delete(:include_subprojects)
476 476 total = self_and_descendants.collect(&:completed_percent).sum
477 477
478 478 total / self_and_descendants.count
479 479 else
480 480 if versions.count > 0
481 481 total = versions.collect(&:completed_pourcent).sum
482 482
483 483 total / versions.count
484 484 else
485 485 100
486 486 end
487 487 end
488 488 end
489 489
490 490 # Return true if this project is allowed to do the specified action.
491 491 # action can be:
492 492 # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
493 493 # * a permission Symbol (eg. :edit_project)
494 494 def allows_to?(action)
495 495 if action.is_a? Hash
496 496 allowed_actions.include? "#{action[:controller]}/#{action[:action]}"
497 497 else
498 498 allowed_permissions.include? action
499 499 end
500 500 end
501 501
502 502 def module_enabled?(module_name)
503 503 module_name = module_name.to_s
504 504 enabled_modules.detect {|m| m.name == module_name}
505 505 end
506 506
507 507 def enabled_module_names=(module_names)
508 508 if module_names && module_names.is_a?(Array)
509 509 module_names = module_names.collect(&:to_s).reject(&:blank?)
510 510 # remove disabled modules
511 511 enabled_modules.each {|mod| mod.destroy unless module_names.include?(mod.name)}
512 512 # add new modules
513 513 module_names.reject {|name| module_enabled?(name)}.each {|name| enabled_modules << EnabledModule.new(:name => name)}
514 514 else
515 515 enabled_modules.clear
516 516 end
517 517 end
518 518
519 519 # Returns an array of the enabled modules names
520 520 def enabled_module_names
521 521 enabled_modules.collect(&:name)
522 522 end
523 523
524 524 # Returns an array of projects that are in this project's hierarchy
525 525 #
526 526 # Example: parents, children, siblings
527 527 def hierarchy
528 528 parents = project.self_and_ancestors || []
529 529 descendants = project.descendants || []
530 530 project_hierarchy = parents | descendants # Set union
531 531 end
532 532
533 533 # Returns an auto-generated project identifier based on the last identifier used
534 534 def self.next_identifier
535 535 p = Project.find(:first, :order => 'created_on DESC')
536 536 p.nil? ? nil : p.identifier.to_s.succ
537 537 end
538 538
539 539 # Copies and saves the Project instance based on the +project+.
540 540 # Duplicates the source project's:
541 541 # * Wiki
542 542 # * Versions
543 543 # * Categories
544 544 # * Issues
545 545 # * Members
546 546 # * Queries
547 547 #
548 548 # Accepts an +options+ argument to specify what to copy
549 549 #
550 550 # Examples:
551 551 # project.copy(1) # => copies everything
552 552 # project.copy(1, :only => 'members') # => copies members only
553 553 # project.copy(1, :only => ['members', 'versions']) # => copies members and versions
554 554 def copy(project, options={})
555 555 project = project.is_a?(Project) ? project : Project.find(project)
556 556
557 557 to_be_copied = %w(wiki versions issue_categories issues members queries boards)
558 558 to_be_copied = to_be_copied & options[:only].to_a unless options[:only].nil?
559 559
560 560 Project.transaction do
561 561 if save
562 562 reload
563 563 to_be_copied.each do |name|
564 564 send "copy_#{name}", project
565 565 end
566 566 Redmine::Hook.call_hook(:model_project_copy_before_save, :source_project => project, :destination_project => self)
567 567 save
568 568 end
569 569 end
570 570 end
571 571
572 572
573 573 # Copies +project+ and returns the new instance. This will not save
574 574 # the copy
575 575 def self.copy_from(project)
576 576 begin
577 577 project = project.is_a?(Project) ? project : Project.find(project)
578 578 if project
579 579 # clear unique attributes
580 580 attributes = project.attributes.dup.except('id', 'name', 'identifier', 'status', 'parent_id', 'lft', 'rgt')
581 581 copy = Project.new(attributes)
582 582 copy.enabled_modules = project.enabled_modules
583 583 copy.trackers = project.trackers
584 584 copy.custom_values = project.custom_values.collect {|v| v.clone}
585 585 copy.issue_custom_fields = project.issue_custom_fields
586 586 return copy
587 587 else
588 588 return nil
589 589 end
590 590 rescue ActiveRecord::RecordNotFound
591 591 return nil
592 592 end
593 593 end
594 594
595 595 # Yields the given block for each project with its level in the tree
596 596 def self.project_tree(projects, &block)
597 597 ancestors = []
598 598 projects.sort_by(&:lft).each do |project|
599 599 while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
600 600 ancestors.pop
601 601 end
602 602 yield project, ancestors.size
603 603 ancestors << project
604 604 end
605 605 end
606 606
607 607 private
608 608
609 609 # Destroys children before destroying self
610 610 def destroy_children
611 611 children.each do |child|
612 612 child.destroy
613 613 end
614 614 end
615 615
616 616 # Copies wiki from +project+
617 617 def copy_wiki(project)
618 618 # Check that the source project has a wiki first
619 619 unless project.wiki.nil?
620 620 self.wiki ||= Wiki.new
621 621 wiki.attributes = project.wiki.attributes.dup.except("id", "project_id")
622 622 wiki_pages_map = {}
623 623 project.wiki.pages.each do |page|
624 624 # Skip pages without content
625 625 next if page.content.nil?
626 626 new_wiki_content = WikiContent.new(page.content.attributes.dup.except("id", "page_id", "updated_on"))
627 627 new_wiki_page = WikiPage.new(page.attributes.dup.except("id", "wiki_id", "created_on", "parent_id"))
628 628 new_wiki_page.content = new_wiki_content
629 629 wiki.pages << new_wiki_page
630 630 wiki_pages_map[page.id] = new_wiki_page
631 631 end
632 632 wiki.save
633 633 # Reproduce page hierarchy
634 634 project.wiki.pages.each do |page|
635 635 if page.parent_id && wiki_pages_map[page.id]
636 636 wiki_pages_map[page.id].parent = wiki_pages_map[page.parent_id]
637 637 wiki_pages_map[page.id].save
638 638 end
639 639 end
640 640 end
641 641 end
642 642
643 643 # Copies versions from +project+
644 644 def copy_versions(project)
645 645 project.versions.each do |version|
646 646 new_version = Version.new
647 647 new_version.attributes = version.attributes.dup.except("id", "project_id", "created_on", "updated_on")
648 648 self.versions << new_version
649 649 end
650 650 end
651 651
652 652 # Copies issue categories from +project+
653 653 def copy_issue_categories(project)
654 654 project.issue_categories.each do |issue_category|
655 655 new_issue_category = IssueCategory.new
656 656 new_issue_category.attributes = issue_category.attributes.dup.except("id", "project_id")
657 657 self.issue_categories << new_issue_category
658 658 end
659 659 end
660 660
661 661 # Copies issues from +project+
662 662 def copy_issues(project)
663 663 # Stores the source issue id as a key and the copied issues as the
664 664 # value. Used to map the two togeather for issue relations.
665 665 issues_map = {}
666 666
667 667 # Get issues sorted by root_id, lft so that parent issues
668 668 # get copied before their children
669 669 project.issues.find(:all, :order => 'root_id, lft').each do |issue|
670 670 new_issue = Issue.new
671 671 new_issue.copy_from(issue)
672 672 new_issue.project = self
673 673 # Reassign fixed_versions by name, since names are unique per
674 674 # project and the versions for self are not yet saved
675 675 if issue.fixed_version
676 676 new_issue.fixed_version = self.versions.select {|v| v.name == issue.fixed_version.name}.first
677 677 end
678 678 # Reassign the category by name, since names are unique per
679 679 # project and the categories for self are not yet saved
680 680 if issue.category
681 681 new_issue.category = self.issue_categories.select {|c| c.name == issue.category.name}.first
682 682 end
683 683 # Parent issue
684 684 if issue.parent_id
685 685 if copied_parent = issues_map[issue.parent_id]
686 686 new_issue.parent_issue_id = copied_parent.id
687 687 end
688 688 end
689 689
690 690 self.issues << new_issue
691 issues_map[issue.id] = new_issue
691 if new_issue.new_record?
692 logger.info "Project#copy_issues: issue ##{issue.id} could not be copied: #{new_issue.errors.full_messages}" if logger && logger.info
693 else
694 issues_map[issue.id] = new_issue unless new_issue.new_record?
695 end
692 696 end
693 697
694 698 # Relations after in case issues related each other
695 699 project.issues.each do |issue|
696 700 new_issue = issues_map[issue.id]
701 unless new_issue
702 # Issue was not copied
703 next
704 end
697 705
698 706 # Relations
699 707 issue.relations_from.each do |source_relation|
700 708 new_issue_relation = IssueRelation.new
701 709 new_issue_relation.attributes = source_relation.attributes.dup.except("id", "issue_from_id", "issue_to_id")
702 710 new_issue_relation.issue_to = issues_map[source_relation.issue_to_id]
703 711 if new_issue_relation.issue_to.nil? && Setting.cross_project_issue_relations?
704 712 new_issue_relation.issue_to = source_relation.issue_to
705 713 end
706 714 new_issue.relations_from << new_issue_relation
707 715 end
708 716
709 717 issue.relations_to.each do |source_relation|
710 718 new_issue_relation = IssueRelation.new
711 719 new_issue_relation.attributes = source_relation.attributes.dup.except("id", "issue_from_id", "issue_to_id")
712 720 new_issue_relation.issue_from = issues_map[source_relation.issue_from_id]
713 721 if new_issue_relation.issue_from.nil? && Setting.cross_project_issue_relations?
714 722 new_issue_relation.issue_from = source_relation.issue_from
715 723 end
716 724 new_issue.relations_to << new_issue_relation
717 725 end
718 726 end
719 727 end
720 728
721 729 # Copies members from +project+
722 730 def copy_members(project)
723 731 project.memberships.each do |member|
724 732 new_member = Member.new
725 733 new_member.attributes = member.attributes.dup.except("id", "project_id", "created_on")
726 734 # only copy non inherited roles
727 735 # inherited roles will be added when copying the group membership
728 736 role_ids = member.member_roles.reject(&:inherited?).collect(&:role_id)
729 737 next if role_ids.empty?
730 738 new_member.role_ids = role_ids
731 739 new_member.project = self
732 740 self.members << new_member
733 741 end
734 742 end
735 743
736 744 # Copies queries from +project+
737 745 def copy_queries(project)
738 746 project.queries.each do |query|
739 747 new_query = Query.new
740 748 new_query.attributes = query.attributes.dup.except("id", "project_id", "sort_criteria")
741 749 new_query.sort_criteria = query.sort_criteria if query.sort_criteria
742 750 new_query.project = self
743 751 self.queries << new_query
744 752 end
745 753 end
746 754
747 755 # Copies boards from +project+
748 756 def copy_boards(project)
749 757 project.boards.each do |board|
750 758 new_board = Board.new
751 759 new_board.attributes = board.attributes.dup.except("id", "project_id", "topics_count", "messages_count", "last_message_id")
752 760 new_board.project = self
753 761 self.boards << new_board
754 762 end
755 763 end
756 764
757 765 def allowed_permissions
758 766 @allowed_permissions ||= begin
759 767 module_names = enabled_modules.all(:select => :name).collect {|m| m.name}
760 768 Redmine::AccessControl.modules_permissions(module_names).collect {|p| p.name}
761 769 end
762 770 end
763 771
764 772 def allowed_actions
765 773 @actions_allowed ||= allowed_permissions.inject([]) { |actions, permission| actions += Redmine::AccessControl.allowed_actions(permission) }.flatten
766 774 end
767 775
768 776 # Returns all the active Systemwide and project specific activities
769 777 def active_activities
770 778 overridden_activity_ids = self.time_entry_activities.collect(&:parent_id)
771 779
772 780 if overridden_activity_ids.empty?
773 781 return TimeEntryActivity.shared.active
774 782 else
775 783 return system_activities_and_project_overrides
776 784 end
777 785 end
778 786
779 787 # Returns all the Systemwide and project specific activities
780 788 # (inactive and active)
781 789 def all_activities
782 790 overridden_activity_ids = self.time_entry_activities.collect(&:parent_id)
783 791
784 792 if overridden_activity_ids.empty?
785 793 return TimeEntryActivity.shared
786 794 else
787 795 return system_activities_and_project_overrides(true)
788 796 end
789 797 end
790 798
791 799 # Returns the systemwide active activities merged with the project specific overrides
792 800 def system_activities_and_project_overrides(include_inactive=false)
793 801 if include_inactive
794 802 return TimeEntryActivity.shared.
795 803 find(:all,
796 804 :conditions => ["id NOT IN (?)", self.time_entry_activities.collect(&:parent_id)]) +
797 805 self.time_entry_activities
798 806 else
799 807 return TimeEntryActivity.shared.active.
800 808 find(:all,
801 809 :conditions => ["id NOT IN (?)", self.time_entry_activities.collect(&:parent_id)]) +
802 810 self.time_entry_activities.active
803 811 end
804 812 end
805 813
806 814 # Archives subprojects recursively
807 815 def archive!
808 816 children.each do |subproject|
809 817 subproject.send :archive!
810 818 end
811 819 update_attribute :status, STATUS_ARCHIVED
812 820 end
813 821 end
General Comments 0
You need to be logged in to leave comments. Login now