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