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