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