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