##// END OF EJS Templates
Reset timestamps and wiki page hierarchy on project copy....
Jean-Philippe Lang -
r2858:4e73685af7fa
parent child
Show More
@@ -1,322 +1,322
1 1 # redMine - project management software
2 2 # Copyright (C) 2006-2007 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 Issue < ActiveRecord::Base
19 19 belongs_to :project
20 20 belongs_to :tracker
21 21 belongs_to :status, :class_name => 'IssueStatus', :foreign_key => 'status_id'
22 22 belongs_to :author, :class_name => 'User', :foreign_key => 'author_id'
23 23 belongs_to :assigned_to, :class_name => 'User', :foreign_key => 'assigned_to_id'
24 24 belongs_to :fixed_version, :class_name => 'Version', :foreign_key => 'fixed_version_id'
25 25 belongs_to :priority, :class_name => 'IssuePriority', :foreign_key => 'priority_id'
26 26 belongs_to :category, :class_name => 'IssueCategory', :foreign_key => 'category_id'
27 27
28 28 has_many :journals, :as => :journalized, :dependent => :destroy
29 29 has_many :time_entries, :dependent => :delete_all
30 30 has_and_belongs_to_many :changesets, :order => "#{Changeset.table_name}.committed_on ASC, #{Changeset.table_name}.id ASC"
31 31
32 32 has_many :relations_from, :class_name => 'IssueRelation', :foreign_key => 'issue_from_id', :dependent => :delete_all
33 33 has_many :relations_to, :class_name => 'IssueRelation', :foreign_key => 'issue_to_id', :dependent => :delete_all
34 34
35 35 acts_as_attachable :after_remove => :attachment_removed
36 36 acts_as_customizable
37 37 acts_as_watchable
38 38 acts_as_searchable :columns => ['subject', "#{table_name}.description", "#{Journal.table_name}.notes"],
39 39 :include => [:project, :journals],
40 40 # sort by id so that limited eager loading doesn't break with postgresql
41 41 :order_column => "#{table_name}.id"
42 42 acts_as_event :title => Proc.new {|o| "#{o.tracker.name} ##{o.id} (#{o.status}): #{o.subject}"},
43 43 :url => Proc.new {|o| {:controller => 'issues', :action => 'show', :id => o.id}},
44 44 :type => Proc.new {|o| 'issue' + (o.closed? ? ' closed' : '') }
45 45
46 46 acts_as_activity_provider :find_options => {:include => [:project, :author, :tracker]},
47 47 :author_key => :author_id
48 48
49 49 validates_presence_of :subject, :priority, :project, :tracker, :author, :status
50 50 validates_length_of :subject, :maximum => 255
51 51 validates_inclusion_of :done_ratio, :in => 0..100
52 52 validates_numericality_of :estimated_hours, :allow_nil => true
53 53
54 54 named_scope :visible, lambda {|*args| { :include => :project,
55 55 :conditions => Project.allowed_to_condition(args.first || User.current, :view_issues) } }
56 56
57 57 named_scope :open, :conditions => ["#{IssueStatus.table_name}.is_closed = ?", false], :include => :status
58 58
59 59 after_save :create_journal
60 60
61 61 # Returns true if usr or current user is allowed to view the issue
62 62 def visible?(usr=nil)
63 63 (usr || User.current).allowed_to?(:view_issues, self.project)
64 64 end
65 65
66 66 def after_initialize
67 67 if new_record?
68 68 # set default values for new records only
69 69 self.status ||= IssueStatus.default
70 70 self.priority ||= IssuePriority.default
71 71 end
72 72 end
73 73
74 74 # Overrides Redmine::Acts::Customizable::InstanceMethods#available_custom_fields
75 75 def available_custom_fields
76 76 (project && tracker) ? project.all_issue_custom_fields.select {|c| tracker.custom_fields.include? c } : []
77 77 end
78 78
79 79 def copy_from(arg)
80 80 issue = arg.is_a?(Issue) ? arg : Issue.find(arg)
81 self.attributes = issue.attributes.dup
81 self.attributes = issue.attributes.dup.except("id", "created_on", "updated_on")
82 82 self.custom_values = issue.custom_values.collect {|v| v.clone}
83 83 self
84 84 end
85 85
86 86 # Moves/copies an issue to a new project and tracker
87 87 # Returns the moved/copied issue on success, false on failure
88 88 def move_to(new_project, new_tracker = nil, options = {})
89 89 options ||= {}
90 90 issue = options[:copy] ? self.clone : self
91 91 transaction do
92 92 if new_project && issue.project_id != new_project.id
93 93 # delete issue relations
94 94 unless Setting.cross_project_issue_relations?
95 95 issue.relations_from.clear
96 96 issue.relations_to.clear
97 97 end
98 98 # issue is moved to another project
99 99 # reassign to the category with same name if any
100 100 new_category = issue.category.nil? ? nil : new_project.issue_categories.find_by_name(issue.category.name)
101 101 issue.category = new_category
102 102 issue.fixed_version = nil
103 103 issue.project = new_project
104 104 end
105 105 if new_tracker
106 106 issue.tracker = new_tracker
107 107 end
108 108 if options[:copy]
109 109 issue.custom_field_values = self.custom_field_values.inject({}) {|h,v| h[v.custom_field_id] = v.value; h}
110 110 issue.status = self.status
111 111 end
112 112 if issue.save
113 113 unless options[:copy]
114 114 # Manually update project_id on related time entries
115 115 TimeEntry.update_all("project_id = #{new_project.id}", {:issue_id => id})
116 116 end
117 117 else
118 118 Issue.connection.rollback_db_transaction
119 119 return false
120 120 end
121 121 end
122 122 return issue
123 123 end
124 124
125 125 def priority_id=(pid)
126 126 self.priority = nil
127 127 write_attribute(:priority_id, pid)
128 128 end
129 129
130 130 def estimated_hours=(h)
131 131 write_attribute :estimated_hours, (h.is_a?(String) ? h.to_hours : h)
132 132 end
133 133
134 134 def validate
135 135 if self.due_date.nil? && @attributes['due_date'] && !@attributes['due_date'].empty?
136 136 errors.add :due_date, :not_a_date
137 137 end
138 138
139 139 if self.due_date and self.start_date and self.due_date < self.start_date
140 140 errors.add :due_date, :greater_than_start_date
141 141 end
142 142
143 143 if start_date && soonest_start && start_date < soonest_start
144 144 errors.add :start_date, :invalid
145 145 end
146 146 end
147 147
148 148 def validate_on_create
149 149 errors.add :tracker_id, :invalid unless project.trackers.include?(tracker)
150 150 end
151 151
152 152 def before_create
153 153 # default assignment based on category
154 154 if assigned_to.nil? && category && category.assigned_to
155 155 self.assigned_to = category.assigned_to
156 156 end
157 157 end
158 158
159 159 def after_save
160 160 # Reload is needed in order to get the right status
161 161 reload
162 162
163 163 # Update start/due dates of following issues
164 164 relations_from.each(&:set_issue_to_dates)
165 165
166 166 # Close duplicates if the issue was closed
167 167 if @issue_before_change && !@issue_before_change.closed? && self.closed?
168 168 duplicates.each do |duplicate|
169 169 # Reload is need in case the duplicate was updated by a previous duplicate
170 170 duplicate.reload
171 171 # Don't re-close it if it's already closed
172 172 next if duplicate.closed?
173 173 # Same user and notes
174 174 duplicate.init_journal(@current_journal.user, @current_journal.notes)
175 175 duplicate.update_attribute :status, self.status
176 176 end
177 177 end
178 178 end
179 179
180 180 def init_journal(user, notes = "")
181 181 @current_journal ||= Journal.new(:journalized => self, :user => user, :notes => notes)
182 182 @issue_before_change = self.clone
183 183 @issue_before_change.status = self.status
184 184 @custom_values_before_change = {}
185 185 self.custom_values.each {|c| @custom_values_before_change.store c.custom_field_id, c.value }
186 186 # Make sure updated_on is updated when adding a note.
187 187 updated_on_will_change!
188 188 @current_journal
189 189 end
190 190
191 191 # Return true if the issue is closed, otherwise false
192 192 def closed?
193 193 self.status.is_closed?
194 194 end
195 195
196 196 # Returns true if the issue is overdue
197 197 def overdue?
198 198 !due_date.nil? && (due_date < Date.today) && !status.is_closed?
199 199 end
200 200
201 201 # Users the issue can be assigned to
202 202 def assignable_users
203 203 project.assignable_users
204 204 end
205 205
206 206 # Returns true if this issue is blocked by another issue that is still open
207 207 def blocked?
208 208 !relations_to.detect {|ir| ir.relation_type == 'blocks' && !ir.issue_from.closed?}.nil?
209 209 end
210 210
211 211 # Returns an array of status that user is able to apply
212 212 def new_statuses_allowed_to(user)
213 213 statuses = status.find_new_statuses_allowed_to(user.roles_for_project(project), tracker)
214 214 statuses << status unless statuses.empty?
215 215 statuses = statuses.uniq.sort
216 216 blocked? ? statuses.reject {|s| s.is_closed?} : statuses
217 217 end
218 218
219 219 # Returns the mail adresses of users that should be notified for the issue
220 220 def recipients
221 221 recipients = project.recipients
222 222 # Author and assignee are always notified unless they have been locked
223 223 recipients << author.mail if author && author.active?
224 224 recipients << assigned_to.mail if assigned_to && assigned_to.active?
225 225 recipients.compact.uniq
226 226 end
227 227
228 228 # Returns the total number of hours spent on this issue.
229 229 #
230 230 # Example:
231 231 # spent_hours => 0
232 232 # spent_hours => 50
233 233 def spent_hours
234 234 @spent_hours ||= time_entries.sum(:hours) || 0
235 235 end
236 236
237 237 def relations
238 238 (relations_from + relations_to).sort
239 239 end
240 240
241 241 def all_dependent_issues
242 242 dependencies = []
243 243 relations_from.each do |relation|
244 244 dependencies << relation.issue_to
245 245 dependencies += relation.issue_to.all_dependent_issues
246 246 end
247 247 dependencies
248 248 end
249 249
250 250 # Returns an array of issues that duplicate this one
251 251 def duplicates
252 252 relations_to.select {|r| r.relation_type == IssueRelation::TYPE_DUPLICATES}.collect {|r| r.issue_from}
253 253 end
254 254
255 255 # Returns the due date or the target due date if any
256 256 # Used on gantt chart
257 257 def due_before
258 258 due_date || (fixed_version ? fixed_version.effective_date : nil)
259 259 end
260 260
261 261 # Returns the time scheduled for this issue.
262 262 #
263 263 # Example:
264 264 # Start Date: 2/26/09, End Date: 3/04/09
265 265 # duration => 6
266 266 def duration
267 267 (start_date && due_date) ? due_date - start_date : 0
268 268 end
269 269
270 270 def soonest_start
271 271 @soonest_start ||= relations_to.collect{|relation| relation.successor_soonest_start}.compact.min
272 272 end
273 273
274 274 def to_s
275 275 "#{tracker} ##{id}: #{subject}"
276 276 end
277 277
278 278 # Returns a string of css classes that apply to the issue
279 279 def css_classes
280 280 s = "issue status-#{status.position} priority-#{priority.position}"
281 281 s << ' closed' if closed?
282 282 s << ' overdue' if overdue?
283 283 s << ' created-by-me' if User.current.logged? && author_id == User.current.id
284 284 s << ' assigned-to-me' if User.current.logged? && assigned_to_id == User.current.id
285 285 s
286 286 end
287 287
288 288 private
289 289
290 290 # Callback on attachment deletion
291 291 def attachment_removed(obj)
292 292 journal = init_journal(User.current)
293 293 journal.details << JournalDetail.new(:property => 'attachment',
294 294 :prop_key => obj.id,
295 295 :old_value => obj.filename)
296 296 journal.save
297 297 end
298 298
299 299 # Saves the changes in a Journal
300 300 # Called after_save
301 301 def create_journal
302 302 if @current_journal
303 303 # attributes changes
304 304 (Issue.column_names - %w(id description lock_version created_on updated_on)).each {|c|
305 305 @current_journal.details << JournalDetail.new(:property => 'attr',
306 306 :prop_key => c,
307 307 :old_value => @issue_before_change.send(c),
308 308 :value => send(c)) unless send(c)==@issue_before_change.send(c)
309 309 }
310 310 # custom fields changes
311 311 custom_values.each {|c|
312 312 next if (@custom_values_before_change[c.custom_field_id]==c.value ||
313 313 (@custom_values_before_change[c.custom_field_id].blank? && c.value.blank?))
314 314 @current_journal.details << JournalDetail.new(:property => 'cf',
315 315 :prop_key => c.custom_field_id,
316 316 :old_value => @custom_values_before_change[c.custom_field_id],
317 317 :value => c.value)
318 318 }
319 319 @current_journal.save
320 320 end
321 321 end
322 322 end
@@ -1,573 +1,573
1 1 # redMine - project management software
2 2 # Copyright (C) 2006 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 class Project < ActiveRecord::Base
19 19 # Project statuses
20 20 STATUS_ACTIVE = 1
21 21 STATUS_ARCHIVED = 9
22 22
23 23 # Specific overidden Activities
24 24 has_many :time_entry_activities do
25 25 def active
26 26 find(:all, :conditions => {:active => true})
27 27 end
28 28 end
29 29 has_many :members, :include => :user, :conditions => "#{User.table_name}.type='User' AND #{User.table_name}.status=#{User::STATUS_ACTIVE}"
30 30 has_many :member_principals, :class_name => 'Member',
31 31 :include => :principal,
32 32 :conditions => "#{Principal.table_name}.type='Group' OR (#{Principal.table_name}.type='User' AND #{Principal.table_name}.status=#{User::STATUS_ACTIVE})"
33 33 has_many :users, :through => :members
34 34 has_many :principals, :through => :member_principals, :source => :principal
35 35
36 36 has_many :enabled_modules, :dependent => :delete_all
37 37 has_and_belongs_to_many :trackers, :order => "#{Tracker.table_name}.position"
38 38 has_many :issues, :dependent => :destroy, :order => "#{Issue.table_name}.created_on DESC", :include => [:status, :tracker]
39 39 has_many :issue_changes, :through => :issues, :source => :journals
40 40 has_many :versions, :dependent => :destroy, :order => "#{Version.table_name}.effective_date DESC, #{Version.table_name}.name DESC"
41 41 has_many :time_entries, :dependent => :delete_all
42 42 has_many :queries, :dependent => :delete_all
43 43 has_many :documents, :dependent => :destroy
44 44 has_many :news, :dependent => :delete_all, :include => :author
45 45 has_many :issue_categories, :dependent => :delete_all, :order => "#{IssueCategory.table_name}.name"
46 46 has_many :boards, :dependent => :destroy, :order => "position ASC"
47 47 has_one :repository, :dependent => :destroy
48 48 has_many :changesets, :through => :repository
49 49 has_one :wiki, :dependent => :destroy
50 50 # Custom field for the project issues
51 51 has_and_belongs_to_many :issue_custom_fields,
52 52 :class_name => 'IssueCustomField',
53 53 :order => "#{CustomField.table_name}.position",
54 54 :join_table => "#{table_name_prefix}custom_fields_projects#{table_name_suffix}",
55 55 :association_foreign_key => 'custom_field_id'
56 56
57 57 acts_as_nested_set :order => 'name', :dependent => :destroy
58 58 acts_as_attachable :view_permission => :view_files,
59 59 :delete_permission => :manage_files
60 60
61 61 acts_as_customizable
62 62 acts_as_searchable :columns => ['name', 'description'], :project_key => 'id', :permission => nil
63 63 acts_as_event :title => Proc.new {|o| "#{l(:label_project)}: #{o.name}"},
64 64 :url => Proc.new {|o| {:controller => 'projects', :action => 'show', :id => o.id}},
65 65 :author => nil
66 66
67 67 attr_protected :status, :enabled_module_names
68 68
69 69 validates_presence_of :name, :identifier
70 70 validates_uniqueness_of :name, :identifier
71 71 validates_associated :repository, :wiki
72 72 validates_length_of :name, :maximum => 30
73 73 validates_length_of :homepage, :maximum => 255
74 74 validates_length_of :identifier, :in => 1..20
75 75 # donwcase letters, digits, dashes but not digits only
76 76 validates_format_of :identifier, :with => /^(?!\d+$)[a-z0-9\-]*$/, :if => Proc.new { |p| p.identifier_changed? }
77 77 # reserved words
78 78 validates_exclusion_of :identifier, :in => %w( new )
79 79
80 80 before_destroy :delete_all_members
81 81
82 82 named_scope :has_module, lambda { |mod| { :conditions => ["#{Project.table_name}.id IN (SELECT em.project_id FROM #{EnabledModule.table_name} em WHERE em.name=?)", mod.to_s] } }
83 83 named_scope :active, { :conditions => "#{Project.table_name}.status = #{STATUS_ACTIVE}"}
84 84 named_scope :all_public, { :conditions => { :is_public => true } }
85 85 named_scope :visible, lambda { { :conditions => Project.visible_by(User.current) } }
86 86
87 87 def identifier=(identifier)
88 88 super unless identifier_frozen?
89 89 end
90 90
91 91 def identifier_frozen?
92 92 errors[:identifier].nil? && !(new_record? || identifier.blank?)
93 93 end
94 94
95 95 def issues_with_subprojects(include_subprojects=false)
96 96 conditions = nil
97 97 if include_subprojects
98 98 ids = [id] + descendants.collect(&:id)
99 99 conditions = ["#{Project.table_name}.id IN (#{ids.join(',')}) AND #{Project.visible_by}"]
100 100 end
101 101 conditions ||= ["#{Project.table_name}.id = ?", id]
102 102 # Quick and dirty fix for Rails 2 compatibility
103 103 Issue.send(:with_scope, :find => { :conditions => conditions }) do
104 104 Version.send(:with_scope, :find => { :conditions => conditions }) do
105 105 yield
106 106 end
107 107 end
108 108 end
109 109
110 110 # returns latest created projects
111 111 # non public projects will be returned only if user is a member of those
112 112 def self.latest(user=nil, count=5)
113 113 find(:all, :limit => count, :conditions => visible_by(user), :order => "created_on DESC")
114 114 end
115 115
116 116 # Returns a SQL :conditions string used to find all active projects for the specified user.
117 117 #
118 118 # Examples:
119 119 # Projects.visible_by(admin) => "projects.status = 1"
120 120 # Projects.visible_by(normal_user) => "projects.status = 1 AND projects.is_public = 1"
121 121 def self.visible_by(user=nil)
122 122 user ||= User.current
123 123 if user && user.admin?
124 124 return "#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"
125 125 elsif user && user.memberships.any?
126 126 return "#{Project.table_name}.status=#{Project::STATUS_ACTIVE} AND (#{Project.table_name}.is_public = #{connection.quoted_true} or #{Project.table_name}.id IN (#{user.memberships.collect{|m| m.project_id}.join(',')}))"
127 127 else
128 128 return "#{Project.table_name}.status=#{Project::STATUS_ACTIVE} AND #{Project.table_name}.is_public = #{connection.quoted_true}"
129 129 end
130 130 end
131 131
132 132 def self.allowed_to_condition(user, permission, options={})
133 133 statements = []
134 134 base_statement = "#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"
135 135 if perm = Redmine::AccessControl.permission(permission)
136 136 unless perm.project_module.nil?
137 137 # If the permission belongs to a project module, make sure the module is enabled
138 138 base_statement << " AND #{Project.table_name}.id IN (SELECT em.project_id FROM #{EnabledModule.table_name} em WHERE em.name='#{perm.project_module}')"
139 139 end
140 140 end
141 141 if options[:project]
142 142 project_statement = "#{Project.table_name}.id = #{options[:project].id}"
143 143 project_statement << " OR (#{Project.table_name}.lft > #{options[:project].lft} AND #{Project.table_name}.rgt < #{options[:project].rgt})" if options[:with_subprojects]
144 144 base_statement = "(#{project_statement}) AND (#{base_statement})"
145 145 end
146 146 if user.admin?
147 147 # no restriction
148 148 else
149 149 statements << "1=0"
150 150 if user.logged?
151 151 statements << "#{Project.table_name}.is_public = #{connection.quoted_true}" if Role.non_member.allowed_to?(permission)
152 152 allowed_project_ids = user.memberships.select {|m| m.roles.detect {|role| role.allowed_to?(permission)}}.collect {|m| m.project_id}
153 153 statements << "#{Project.table_name}.id IN (#{allowed_project_ids.join(',')})" if allowed_project_ids.any?
154 154 elsif Role.anonymous.allowed_to?(permission)
155 155 # anonymous user allowed on public project
156 156 statements << "#{Project.table_name}.is_public = #{connection.quoted_true}"
157 157 else
158 158 # anonymous user is not authorized
159 159 end
160 160 end
161 161 statements.empty? ? base_statement : "((#{base_statement}) AND (#{statements.join(' OR ')}))"
162 162 end
163 163
164 164 # Returns the Systemwide and project specific activities
165 165 def activities(include_inactive=false)
166 166 if include_inactive
167 167 return all_activities
168 168 else
169 169 return active_activities
170 170 end
171 171 end
172 172
173 173 # Will create a new Project specific Activity or update an existing one
174 174 #
175 175 # This will raise a ActiveRecord::Rollback if the TimeEntryActivity
176 176 # does not successfully save.
177 177 def update_or_create_time_entry_activity(id, activity_hash)
178 178 if activity_hash.respond_to?(:has_key?) && activity_hash.has_key?('parent_id')
179 179 self.create_time_entry_activity_if_needed(activity_hash)
180 180 else
181 181 activity = project.time_entry_activities.find_by_id(id.to_i)
182 182 activity.update_attributes(activity_hash) if activity
183 183 end
184 184 end
185 185
186 186 # Create a new TimeEntryActivity if it overrides a system TimeEntryActivity
187 187 #
188 188 # This will raise a ActiveRecord::Rollback if the TimeEntryActivity
189 189 # does not successfully save.
190 190 def create_time_entry_activity_if_needed(activity)
191 191 if activity['parent_id']
192 192
193 193 parent_activity = TimeEntryActivity.find(activity['parent_id'])
194 194 activity['name'] = parent_activity.name
195 195 activity['position'] = parent_activity.position
196 196
197 197 if Enumeration.overridding_change?(activity, parent_activity)
198 198 project_activity = self.time_entry_activities.create(activity)
199 199
200 200 if project_activity.new_record?
201 201 raise ActiveRecord::Rollback, "Overridding TimeEntryActivity was not successfully saved"
202 202 else
203 203 self.time_entries.update_all("activity_id = #{project_activity.id}", ["activity_id = ?", parent_activity.id])
204 204 end
205 205 end
206 206 end
207 207 end
208 208
209 209 # Returns a :conditions SQL string that can be used to find the issues associated with this project.
210 210 #
211 211 # Examples:
212 212 # project.project_condition(true) => "(projects.id = 1 OR (projects.lft > 1 AND projects.rgt < 10))"
213 213 # project.project_condition(false) => "projects.id = 1"
214 214 def project_condition(with_subprojects)
215 215 cond = "#{Project.table_name}.id = #{id}"
216 216 cond = "(#{cond} OR (#{Project.table_name}.lft > #{lft} AND #{Project.table_name}.rgt < #{rgt}))" if with_subprojects
217 217 cond
218 218 end
219 219
220 220 def self.find(*args)
221 221 if args.first && args.first.is_a?(String) && !args.first.match(/^\d*$/)
222 222 project = find_by_identifier(*args)
223 223 raise ActiveRecord::RecordNotFound, "Couldn't find Project with identifier=#{args.first}" if project.nil?
224 224 project
225 225 else
226 226 super
227 227 end
228 228 end
229 229
230 230 def to_param
231 231 # id is used for projects with a numeric identifier (compatibility)
232 232 @to_param ||= (identifier.to_s =~ %r{^\d*$} ? id : identifier)
233 233 end
234 234
235 235 def active?
236 236 self.status == STATUS_ACTIVE
237 237 end
238 238
239 239 # Archives the project and its descendants recursively
240 240 def archive
241 241 # Archive subprojects if any
242 242 children.each do |subproject|
243 243 subproject.archive
244 244 end
245 245 update_attribute :status, STATUS_ARCHIVED
246 246 end
247 247
248 248 # Unarchives the project
249 249 # All its ancestors must be active
250 250 def unarchive
251 251 return false if ancestors.detect {|a| !a.active?}
252 252 update_attribute :status, STATUS_ACTIVE
253 253 end
254 254
255 255 # Returns an array of projects the project can be moved to
256 256 def possible_parents
257 257 @possible_parents ||= (Project.active.find(:all) - self_and_descendants)
258 258 end
259 259
260 260 # Sets the parent of the project
261 261 # Argument can be either a Project, a String, a Fixnum or nil
262 262 def set_parent!(p)
263 263 unless p.nil? || p.is_a?(Project)
264 264 if p.to_s.blank?
265 265 p = nil
266 266 else
267 267 p = Project.find_by_id(p)
268 268 return false unless p
269 269 end
270 270 end
271 271 if p == parent && !p.nil?
272 272 # Nothing to do
273 273 true
274 274 elsif p.nil? || (p.active? && move_possible?(p))
275 275 # Insert the project so that target's children or root projects stay alphabetically sorted
276 276 sibs = (p.nil? ? self.class.roots : p.children)
277 277 to_be_inserted_before = sibs.detect {|c| c.name.to_s.downcase > name.to_s.downcase }
278 278 if to_be_inserted_before
279 279 move_to_left_of(to_be_inserted_before)
280 280 elsif p.nil?
281 281 if sibs.empty?
282 282 # move_to_root adds the project in first (ie. left) position
283 283 move_to_root
284 284 else
285 285 move_to_right_of(sibs.last) unless self == sibs.last
286 286 end
287 287 else
288 288 # move_to_child_of adds the project in last (ie.right) position
289 289 move_to_child_of(p)
290 290 end
291 291 true
292 292 else
293 293 # Can not move to the given target
294 294 false
295 295 end
296 296 end
297 297
298 298 # Returns an array of the trackers used by the project and its active sub projects
299 299 def rolled_up_trackers
300 300 @rolled_up_trackers ||=
301 301 Tracker.find(:all, :include => :projects,
302 302 :select => "DISTINCT #{Tracker.table_name}.*",
303 303 :conditions => ["#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status = #{STATUS_ACTIVE}", lft, rgt],
304 304 :order => "#{Tracker.table_name}.position")
305 305 end
306 306
307 307 # Returns a hash of project users grouped by role
308 308 def users_by_role
309 309 members.find(:all, :include => [:user, :roles]).inject({}) do |h, m|
310 310 m.roles.each do |r|
311 311 h[r] ||= []
312 312 h[r] << m.user
313 313 end
314 314 h
315 315 end
316 316 end
317 317
318 318 # Deletes all project's members
319 319 def delete_all_members
320 320 me, mr = Member.table_name, MemberRole.table_name
321 321 connection.delete("DELETE FROM #{mr} WHERE #{mr}.member_id IN (SELECT #{me}.id FROM #{me} WHERE #{me}.project_id = #{id})")
322 322 Member.delete_all(['project_id = ?', id])
323 323 end
324 324
325 325 # Users issues can be assigned to
326 326 def assignable_users
327 327 members.select {|m| m.roles.detect {|role| role.assignable?}}.collect {|m| m.user}.sort
328 328 end
329 329
330 330 # Returns the mail adresses of users that should be always notified on project events
331 331 def recipients
332 332 members.select {|m| m.mail_notification? || m.user.mail_notification?}.collect {|m| m.user.mail}
333 333 end
334 334
335 335 # Returns an array of all custom fields enabled for project issues
336 336 # (explictly associated custom fields and custom fields enabled for all projects)
337 337 def all_issue_custom_fields
338 338 @all_issue_custom_fields ||= (IssueCustomField.for_all + issue_custom_fields).uniq.sort
339 339 end
340 340
341 341 def project
342 342 self
343 343 end
344 344
345 345 def <=>(project)
346 346 name.downcase <=> project.name.downcase
347 347 end
348 348
349 349 def to_s
350 350 name
351 351 end
352 352
353 353 # Returns a short description of the projects (first lines)
354 354 def short_description(length = 255)
355 355 description.gsub(/^(.{#{length}}[^\n\r]*).*$/m, '\1...').strip if description
356 356 end
357 357
358 358 # Return true if this project is allowed to do the specified action.
359 359 # action can be:
360 360 # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
361 361 # * a permission Symbol (eg. :edit_project)
362 362 def allows_to?(action)
363 363 if action.is_a? Hash
364 364 allowed_actions.include? "#{action[:controller]}/#{action[:action]}"
365 365 else
366 366 allowed_permissions.include? action
367 367 end
368 368 end
369 369
370 370 def module_enabled?(module_name)
371 371 module_name = module_name.to_s
372 372 enabled_modules.detect {|m| m.name == module_name}
373 373 end
374 374
375 375 def enabled_module_names=(module_names)
376 376 if module_names && module_names.is_a?(Array)
377 377 module_names = module_names.collect(&:to_s)
378 378 # remove disabled modules
379 379 enabled_modules.each {|mod| mod.destroy unless module_names.include?(mod.name)}
380 380 # add new modules
381 381 module_names.each {|name| enabled_modules << EnabledModule.new(:name => name)}
382 382 else
383 383 enabled_modules.clear
384 384 end
385 385 end
386 386
387 387 # Returns an auto-generated project identifier based on the last identifier used
388 388 def self.next_identifier
389 389 p = Project.find(:first, :order => 'created_on DESC')
390 390 p.nil? ? nil : p.identifier.to_s.succ
391 391 end
392 392
393 393 # Copies and saves the Project instance based on the +project+.
394 394 # Duplicates the source project's:
395 395 # * Wiki
396 396 # * Versions
397 397 # * Categories
398 398 # * Issues
399 399 # * Members
400 400 # * Queries
401 401 #
402 402 # Accepts an +options+ argument to specify what to copy
403 403 #
404 404 # Examples:
405 405 # project.copy(1) # => copies everything
406 406 # project.copy(1, :only => 'members') # => copies members only
407 407 # project.copy(1, :only => ['members', 'versions']) # => copies members and versions
408 408 def copy(project, options={})
409 409 project = project.is_a?(Project) ? project : Project.find(project)
410 410
411 411 to_be_copied = %w(wiki versions issue_categories issues members queries)
412 412 to_be_copied = to_be_copied & options[:only].to_a unless options[:only].nil?
413 413
414 414 Project.transaction do
415 415 if save
416 416 reload
417 417 to_be_copied.each do |name|
418 418 send "copy_#{name}", project
419 419 end
420 420 Redmine::Hook.call_hook(:model_project_copy_before_save, :source_project => project, :destination_project => self)
421 421 save
422 422 end
423 423 end
424 424 end
425 425
426 426
427 427 # Copies +project+ and returns the new instance. This will not save
428 428 # the copy
429 429 def self.copy_from(project)
430 430 begin
431 431 project = project.is_a?(Project) ? project : Project.find(project)
432 432 if project
433 433 # clear unique attributes
434 434 attributes = project.attributes.dup.except('name', 'identifier', 'id', 'status')
435 435 copy = Project.new(attributes)
436 436 copy.enabled_modules = project.enabled_modules
437 437 copy.trackers = project.trackers
438 438 copy.custom_values = project.custom_values.collect {|v| v.clone}
439 439 copy.issue_custom_fields = project.issue_custom_fields
440 440 return copy
441 441 else
442 442 return nil
443 443 end
444 444 rescue ActiveRecord::RecordNotFound
445 445 return nil
446 446 end
447 447 end
448 448
449 449 private
450 450
451 451 # Copies wiki from +project+
452 452 def copy_wiki(project)
453 453 # Check that the source project has a wiki first
454 454 unless project.wiki.nil?
455 455 self.wiki ||= Wiki.new
456 456 wiki.attributes = project.wiki.attributes.dup.except("id", "project_id")
457 457 project.wiki.pages.each do |page|
458 new_wiki_content = WikiContent.new(page.content.attributes.dup.except("id", "page_id"))
459 new_wiki_page = WikiPage.new(page.attributes.dup.except("id", "wiki_id"))
458 new_wiki_content = WikiContent.new(page.content.attributes.dup.except("id", "page_id", "updated_on"))
459 new_wiki_page = WikiPage.new(page.attributes.dup.except("id", "wiki_id", "created_on", "parent_id"))
460 460 new_wiki_page.content = new_wiki_content
461 461 wiki.pages << new_wiki_page
462 462 end
463 463 end
464 464 end
465 465
466 466 # Copies versions from +project+
467 467 def copy_versions(project)
468 468 project.versions.each do |version|
469 469 new_version = Version.new
470 new_version.attributes = version.attributes.dup.except("id", "project_id")
470 new_version.attributes = version.attributes.dup.except("id", "project_id", "created_on", "updated_on")
471 471 self.versions << new_version
472 472 end
473 473 end
474 474
475 475 # Copies issue categories from +project+
476 476 def copy_issue_categories(project)
477 477 project.issue_categories.each do |issue_category|
478 478 new_issue_category = IssueCategory.new
479 479 new_issue_category.attributes = issue_category.attributes.dup.except("id", "project_id")
480 480 self.issue_categories << new_issue_category
481 481 end
482 482 end
483 483
484 484 # Copies issues from +project+
485 485 def copy_issues(project)
486 486 project.issues.each do |issue|
487 487 new_issue = Issue.new
488 488 new_issue.copy_from(issue)
489 489 # Reassign fixed_versions by name, since names are unique per
490 490 # project and the versions for self are not yet saved
491 491 if issue.fixed_version
492 492 new_issue.fixed_version = self.versions.select {|v| v.name == issue.fixed_version.name}.first
493 493 end
494 494 # Reassign the category by name, since names are unique per
495 495 # project and the categories for self are not yet saved
496 496 if issue.category
497 497 new_issue.category = self.issue_categories.select {|c| c.name == issue.category.name}.first
498 498 end
499 499 self.issues << new_issue
500 500 end
501 501 end
502 502
503 503 # Copies members from +project+
504 504 def copy_members(project)
505 505 project.members.each do |member|
506 506 new_member = Member.new
507 new_member.attributes = member.attributes.dup.except("id", "project_id")
507 new_member.attributes = member.attributes.dup.except("id", "project_id", "created_on")
508 508 new_member.role_ids = member.role_ids.dup
509 509 new_member.project = self
510 510 self.members << new_member
511 511 end
512 512 end
513 513
514 514 # Copies queries from +project+
515 515 def copy_queries(project)
516 516 project.queries.each do |query|
517 517 new_query = Query.new
518 518 new_query.attributes = query.attributes.dup.except("id", "project_id", "sort_criteria")
519 519 new_query.sort_criteria = query.sort_criteria if query.sort_criteria
520 520 new_query.project = self
521 521 self.queries << new_query
522 522 end
523 523 end
524 524
525 525 def allowed_permissions
526 526 @allowed_permissions ||= begin
527 527 module_names = enabled_modules.collect {|m| m.name}
528 528 Redmine::AccessControl.modules_permissions(module_names).collect {|p| p.name}
529 529 end
530 530 end
531 531
532 532 def allowed_actions
533 533 @actions_allowed ||= allowed_permissions.inject([]) { |actions, permission| actions += Redmine::AccessControl.allowed_actions(permission) }.flatten
534 534 end
535 535
536 536 # Returns all the active Systemwide and project specific activities
537 537 def active_activities
538 538 overridden_activity_ids = self.time_entry_activities.active.collect(&:parent_id)
539 539
540 540 if overridden_activity_ids.empty?
541 541 return TimeEntryActivity.active
542 542 else
543 543 return system_activities_and_project_overrides
544 544 end
545 545 end
546 546
547 547 # Returns all the Systemwide and project specific activities
548 548 # (inactive and active)
549 549 def all_activities
550 550 overridden_activity_ids = self.time_entry_activities.collect(&:parent_id)
551 551
552 552 if overridden_activity_ids.empty?
553 553 return TimeEntryActivity.all
554 554 else
555 555 return system_activities_and_project_overrides(true)
556 556 end
557 557 end
558 558
559 559 # Returns the systemwide active activities merged with the project specific overrides
560 560 def system_activities_and_project_overrides(include_inactive=false)
561 561 if include_inactive
562 562 return TimeEntryActivity.all.
563 563 find(:all,
564 564 :conditions => ["id NOT IN (?)", self.time_entry_activities.collect(&:parent_id)]) +
565 565 self.time_entry_activities
566 566 else
567 567 return TimeEntryActivity.active.
568 568 find(:all,
569 569 :conditions => ["id NOT IN (?)", self.time_entry_activities.active.collect(&:parent_id)]) +
570 570 self.time_entry_activities.active
571 571 end
572 572 end
573 573 end
General Comments 0
You need to be logged in to leave comments. Login now