##// END OF EJS Templates
Changes misleading scopes on Enumeration....
Jean-Philippe Lang -
r2969:d8c5549168f3
parent child
Show More
@@ -1,190 +1,190
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 module TimelogHelper
19 19 include ApplicationHelper
20 20
21 21 def render_timelog_breadcrumb
22 22 links = []
23 23 links << link_to(l(:label_project_all), {:project_id => nil, :issue_id => nil})
24 24 links << link_to(h(@project), {:project_id => @project, :issue_id => nil}) if @project
25 25 if @issue
26 26 if @issue.visible?
27 27 links << link_to_issue(@issue, :subject => false)
28 28 else
29 29 links << "##{@issue.id}"
30 30 end
31 31 end
32 32 breadcrumb links
33 33 end
34 34
35 35 # Returns a collection of activities for a select field. time_entry
36 36 # is optional and will be used to check if the selected TimeEntryActivity
37 37 # is active.
38 38 def activity_collection_for_select_options(time_entry=nil, project=nil)
39 39 project ||= @project
40 40 if project.nil?
41 activities = TimeEntryActivity.active
41 activities = TimeEntryActivity.shared.active
42 42 else
43 43 activities = project.activities
44 44 end
45 45
46 46 collection = []
47 47 if time_entry && time_entry.activity && !time_entry.activity.active?
48 48 collection << [ "--- #{l(:actionview_instancetag_blank_option)} ---", '' ]
49 49 else
50 50 collection << [ "--- #{l(:actionview_instancetag_blank_option)} ---", '' ] unless activities.detect(&:is_default)
51 51 end
52 52 activities.each { |a| collection << [a.name, a.id] }
53 53 collection
54 54 end
55 55
56 56 def select_hours(data, criteria, value)
57 57 if value.to_s.empty?
58 58 data.select {|row| row[criteria].blank? }
59 59 else
60 60 data.select {|row| row[criteria] == value}
61 61 end
62 62 end
63 63
64 64 def sum_hours(data)
65 65 sum = 0
66 66 data.each do |row|
67 67 sum += row['hours'].to_f
68 68 end
69 69 sum
70 70 end
71 71
72 72 def options_for_period_select(value)
73 73 options_for_select([[l(:label_all_time), 'all'],
74 74 [l(:label_today), 'today'],
75 75 [l(:label_yesterday), 'yesterday'],
76 76 [l(:label_this_week), 'current_week'],
77 77 [l(:label_last_week), 'last_week'],
78 78 [l(:label_last_n_days, 7), '7_days'],
79 79 [l(:label_this_month), 'current_month'],
80 80 [l(:label_last_month), 'last_month'],
81 81 [l(:label_last_n_days, 30), '30_days'],
82 82 [l(:label_this_year), 'current_year']],
83 83 value)
84 84 end
85 85
86 86 def entries_to_csv(entries)
87 87 ic = Iconv.new(l(:general_csv_encoding), 'UTF-8')
88 88 decimal_separator = l(:general_csv_decimal_separator)
89 89 custom_fields = TimeEntryCustomField.find(:all)
90 90 export = FCSV.generate(:col_sep => l(:general_csv_separator)) do |csv|
91 91 # csv header fields
92 92 headers = [l(:field_spent_on),
93 93 l(:field_user),
94 94 l(:field_activity),
95 95 l(:field_project),
96 96 l(:field_issue),
97 97 l(:field_tracker),
98 98 l(:field_subject),
99 99 l(:field_hours),
100 100 l(:field_comments)
101 101 ]
102 102 # Export custom fields
103 103 headers += custom_fields.collect(&:name)
104 104
105 105 csv << headers.collect {|c| begin; ic.iconv(c.to_s); rescue; c.to_s; end }
106 106 # csv lines
107 107 entries.each do |entry|
108 108 fields = [format_date(entry.spent_on),
109 109 entry.user,
110 110 entry.activity,
111 111 entry.project,
112 112 (entry.issue ? entry.issue.id : nil),
113 113 (entry.issue ? entry.issue.tracker : nil),
114 114 (entry.issue ? entry.issue.subject : nil),
115 115 entry.hours.to_s.gsub('.', decimal_separator),
116 116 entry.comments
117 117 ]
118 118 fields += custom_fields.collect {|f| show_value(entry.custom_value_for(f)) }
119 119
120 120 csv << fields.collect {|c| begin; ic.iconv(c.to_s); rescue; c.to_s; end }
121 121 end
122 122 end
123 123 export
124 124 end
125 125
126 126 def format_criteria_value(criteria, value)
127 127 if value.blank?
128 128 l(:label_none)
129 129 elsif k = @available_criterias[criteria][:klass]
130 130 obj = k.find_by_id(value.to_i)
131 131 if obj.is_a?(Issue)
132 132 obj.visible? ? "#{obj.tracker} ##{obj.id}: #{obj.subject}" : "##{obj.id}"
133 133 else
134 134 obj
135 135 end
136 136 else
137 137 format_value(value, @available_criterias[criteria][:format])
138 138 end
139 139 end
140 140
141 141 def report_to_csv(criterias, periods, hours)
142 142 export = FCSV.generate(:col_sep => l(:general_csv_separator)) do |csv|
143 143 # Column headers
144 144 headers = criterias.collect {|criteria| l(@available_criterias[criteria][:label]) }
145 145 headers += periods
146 146 headers << l(:label_total)
147 147 csv << headers.collect {|c| to_utf8(c) }
148 148 # Content
149 149 report_criteria_to_csv(csv, criterias, periods, hours)
150 150 # Total row
151 151 row = [ l(:label_total) ] + [''] * (criterias.size - 1)
152 152 total = 0
153 153 periods.each do |period|
154 154 sum = sum_hours(select_hours(hours, @columns, period.to_s))
155 155 total += sum
156 156 row << (sum > 0 ? "%.2f" % sum : '')
157 157 end
158 158 row << "%.2f" %total
159 159 csv << row
160 160 end
161 161 export
162 162 end
163 163
164 164 def report_criteria_to_csv(csv, criterias, periods, hours, level=0)
165 165 hours.collect {|h| h[criterias[level]].to_s}.uniq.each do |value|
166 166 hours_for_value = select_hours(hours, criterias[level], value)
167 167 next if hours_for_value.empty?
168 168 row = [''] * level
169 169 row << to_utf8(format_criteria_value(criterias[level], value))
170 170 row += [''] * (criterias.length - level - 1)
171 171 total = 0
172 172 periods.each do |period|
173 173 sum = sum_hours(select_hours(hours_for_value, @columns, period.to_s))
174 174 total += sum
175 175 row << (sum > 0 ? "%.2f" % sum : '')
176 176 end
177 177 row << "%.2f" %total
178 178 csv << row
179 179
180 180 if criterias.length > level + 1
181 181 report_criteria_to_csv(csv, criterias, periods, hours_for_value, level + 1)
182 182 end
183 183 end
184 184 end
185 185
186 186 def to_utf8(s)
187 187 @ic ||= Iconv.new(l(:general_csv_encoding), 'UTF-8')
188 188 begin; @ic.iconv(s.to_s); rescue; s.to_s; end
189 189 end
190 190 end
@@ -1,174 +1,170
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 Enumeration < ActiveRecord::Base
19 default_scope :order => "#{Enumeration.table_name}.position ASC"
20
19 21 belongs_to :project
20 22
21 23 acts_as_list :scope => 'type = \'#{type}\''
22 24 acts_as_customizable
23 25 acts_as_tree :order => 'position ASC'
24 26
25 27 before_destroy :check_integrity
26 28
27 29 validates_presence_of :name
28 30 validates_uniqueness_of :name, :scope => [:type, :project_id]
29 31 validates_length_of :name, :maximum => 30
30 32
31 33 # Backwards compatiblity named_scopes.
32 34 # Can be removed post-0.9
33 35 named_scope :priorities, :conditions => { :type => "IssuePriority" }, :order => 'position' do
34 36 ActiveSupport::Deprecation.warn("Enumeration#priorities is deprecated, use the IssuePriority class. (#{Redmine::Info.issue(3007)})")
35 37 def default
36 38 find(:first, :conditions => { :is_default => true })
37 39 end
38 40 end
39 41
40 42 named_scope :document_categories, :conditions => { :type => "DocumentCategory" }, :order => 'position' do
41 43 ActiveSupport::Deprecation.warn("Enumeration#document_categories is deprecated, use the DocumentCategories class. (#{Redmine::Info.issue(3007)})")
42 44 def default
43 45 find(:first, :conditions => { :is_default => true })
44 46 end
45 47 end
46 48
47 49 named_scope :activities, :conditions => { :type => "TimeEntryActivity" }, :order => 'position' do
48 50 ActiveSupport::Deprecation.warn("Enumeration#activities is deprecated, use the TimeEntryActivity class. (#{Redmine::Info.issue(3007)})")
49 51 def default
50 52 find(:first, :conditions => { :is_default => true })
51 53 end
52 54 end
53 55
54 56 named_scope :values, lambda {|type| { :conditions => { :type => type }, :order => 'position' } } do
55 57 def default
56 58 find(:first, :conditions => { :is_default => true })
57 59 end
58 60 end
59 61 # End backwards compatiblity named_scopes
60 62
61 named_scope :all, :order => 'position', :conditions => { :project_id => nil }
62
63 named_scope :active, lambda {
64 {
65 :conditions => {:active => true, :project_id => nil},
66 :order => 'position'
67 }
68 }
63 named_scope :shared, :conditions => { :project_id => nil }
64 named_scope :active, :conditions => { :active => true }
69 65
70 66 def self.default
71 67 # Creates a fake default scope so Enumeration.default will check
72 68 # it's type. STI subclasses will automatically add their own
73 69 # types to the finder.
74 70 if self.descends_from_active_record?
75 71 find(:first, :conditions => { :is_default => true, :type => 'Enumeration' })
76 72 else
77 73 # STI classes are
78 74 find(:first, :conditions => { :is_default => true })
79 75 end
80 76 end
81 77
82 78 # Overloaded on concrete classes
83 79 def option_name
84 80 nil
85 81 end
86 82
87 83 # Backwards compatiblity. Can be removed post-0.9
88 84 def opt
89 85 ActiveSupport::Deprecation.warn("Enumeration#opt is deprecated, use the STI classes now. (#{Redmine::Info.issue(3007)})")
90 86 return OptName
91 87 end
92 88
93 89 def before_save
94 90 if is_default? && is_default_changed?
95 91 Enumeration.update_all("is_default = #{connection.quoted_false}", {:type => type})
96 92 end
97 93 end
98 94
99 95 # Overloaded on concrete classes
100 96 def objects_count
101 97 0
102 98 end
103 99
104 100 def in_use?
105 101 self.objects_count != 0
106 102 end
107 103
108 104 # Is this enumeration overiding a system level enumeration?
109 105 def is_override?
110 106 !self.parent.nil?
111 107 end
112 108
113 109 alias :destroy_without_reassign :destroy
114 110
115 111 # Destroy the enumeration
116 112 # If a enumeration is specified, objects are reassigned
117 113 def destroy(reassign_to = nil)
118 114 if reassign_to && reassign_to.is_a?(Enumeration)
119 115 self.transfer_relations(reassign_to)
120 116 end
121 117 destroy_without_reassign
122 118 end
123 119
124 120 def <=>(enumeration)
125 121 position <=> enumeration.position
126 122 end
127 123
128 124 def to_s; name end
129 125
130 126 # Returns the Subclasses of Enumeration. Each Subclass needs to be
131 127 # required in development mode.
132 128 #
133 129 # Note: subclasses is protected in ActiveRecord
134 130 def self.get_subclasses
135 131 @@subclasses[Enumeration]
136 132 end
137 133
138 134 # Does the +new+ Hash override the previous Enumeration?
139 135 def self.overridding_change?(new, previous)
140 136 if (same_active_state?(new['active'], previous.active)) && same_custom_values?(new,previous)
141 137 return false
142 138 else
143 139 return true
144 140 end
145 141 end
146 142
147 143 # Does the +new+ Hash have the same custom values as the previous Enumeration?
148 144 def self.same_custom_values?(new, previous)
149 145 previous.custom_field_values.each do |custom_value|
150 146 if custom_value.value != new["custom_field_values"][custom_value.custom_field_id.to_s]
151 147 return false
152 148 end
153 149 end
154 150
155 151 return true
156 152 end
157 153
158 154 # Are the new and previous fields equal?
159 155 def self.same_active_state?(new, previous)
160 156 new = (new == "1" ? true : false)
161 157 return new == previous
162 158 end
163 159
164 160 private
165 161 def check_integrity
166 162 raise "Can't delete enumeration" if self.in_use?
167 163 end
168 164
169 165 end
170 166
171 167 # Force load the subclasses in development mode
172 168 require_dependency 'time_entry_activity'
173 169 require_dependency 'document_category'
174 170 require_dependency 'issue_priority'
@@ -1,607 +1,603
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 has_many :time_entry_activities do
25 def active
26 find(:all, :conditions => {:active => true})
27 end
28 end
24 has_many :time_entry_activities
29 25 has_many :members, :include => [:user, :roles], :conditions => "#{User.table_name}.type='User' AND #{User.table_name}.status=#{User::STATUS_ACTIVE}"
30 26 has_many :member_principals, :class_name => 'Member',
31 27 :include => :principal,
32 28 :conditions => "#{Principal.table_name}.type='Group' OR (#{Principal.table_name}.type='User' AND #{Principal.table_name}.status=#{User::STATUS_ACTIVE})"
33 29 has_many :users, :through => :members
34 30 has_many :principals, :through => :member_principals, :source => :principal
35 31
36 32 has_many :enabled_modules, :dependent => :delete_all
37 33 has_and_belongs_to_many :trackers, :order => "#{Tracker.table_name}.position"
38 34 has_many :issues, :dependent => :destroy, :order => "#{Issue.table_name}.created_on DESC", :include => [:status, :tracker]
39 35 has_many :issue_changes, :through => :issues, :source => :journals
40 36 has_many :versions, :dependent => :destroy, :order => "#{Version.table_name}.effective_date DESC, #{Version.table_name}.name DESC"
41 37 has_many :time_entries, :dependent => :delete_all
42 38 has_many :queries, :dependent => :delete_all
43 39 has_many :documents, :dependent => :destroy
44 40 has_many :news, :dependent => :delete_all, :include => :author
45 41 has_many :issue_categories, :dependent => :delete_all, :order => "#{IssueCategory.table_name}.name"
46 42 has_many :boards, :dependent => :destroy, :order => "position ASC"
47 43 has_one :repository, :dependent => :destroy
48 44 has_many :changesets, :through => :repository
49 45 has_one :wiki, :dependent => :destroy
50 46 # Custom field for the project issues
51 47 has_and_belongs_to_many :issue_custom_fields,
52 48 :class_name => 'IssueCustomField',
53 49 :order => "#{CustomField.table_name}.position",
54 50 :join_table => "#{table_name_prefix}custom_fields_projects#{table_name_suffix}",
55 51 :association_foreign_key => 'custom_field_id'
56 52
57 53 acts_as_nested_set :order => 'name', :dependent => :destroy
58 54 acts_as_attachable :view_permission => :view_files,
59 55 :delete_permission => :manage_files
60 56
61 57 acts_as_customizable
62 58 acts_as_searchable :columns => ['name', 'description'], :project_key => 'id', :permission => nil
63 59 acts_as_event :title => Proc.new {|o| "#{l(:label_project)}: #{o.name}"},
64 60 :url => Proc.new {|o| {:controller => 'projects', :action => 'show', :id => o.id}},
65 61 :author => nil
66 62
67 63 attr_protected :status, :enabled_module_names
68 64
69 65 validates_presence_of :name, :identifier
70 66 validates_uniqueness_of :name, :identifier
71 67 validates_associated :repository, :wiki
72 68 validates_length_of :name, :maximum => 30
73 69 validates_length_of :homepage, :maximum => 255
74 70 validates_length_of :identifier, :in => 1..20
75 71 # donwcase letters, digits, dashes but not digits only
76 72 validates_format_of :identifier, :with => /^(?!\d+$)[a-z0-9\-]*$/, :if => Proc.new { |p| p.identifier_changed? }
77 73 # reserved words
78 74 validates_exclusion_of :identifier, :in => %w( new )
79 75
80 76 before_destroy :delete_all_members
81 77
82 78 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 79 named_scope :active, { :conditions => "#{Project.table_name}.status = #{STATUS_ACTIVE}"}
84 80 named_scope :all_public, { :conditions => { :is_public => true } }
85 81 named_scope :visible, lambda { { :conditions => Project.visible_by(User.current) } }
86 82
87 83 def identifier=(identifier)
88 84 super unless identifier_frozen?
89 85 end
90 86
91 87 def identifier_frozen?
92 88 errors[:identifier].nil? && !(new_record? || identifier.blank?)
93 89 end
94 90
95 91 # returns latest created projects
96 92 # non public projects will be returned only if user is a member of those
97 93 def self.latest(user=nil, count=5)
98 94 find(:all, :limit => count, :conditions => visible_by(user), :order => "created_on DESC")
99 95 end
100 96
101 97 # Returns a SQL :conditions string used to find all active projects for the specified user.
102 98 #
103 99 # Examples:
104 100 # Projects.visible_by(admin) => "projects.status = 1"
105 101 # Projects.visible_by(normal_user) => "projects.status = 1 AND projects.is_public = 1"
106 102 def self.visible_by(user=nil)
107 103 user ||= User.current
108 104 if user && user.admin?
109 105 return "#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"
110 106 elsif user && user.memberships.any?
111 107 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(',')}))"
112 108 else
113 109 return "#{Project.table_name}.status=#{Project::STATUS_ACTIVE} AND #{Project.table_name}.is_public = #{connection.quoted_true}"
114 110 end
115 111 end
116 112
117 113 def self.allowed_to_condition(user, permission, options={})
118 114 statements = []
119 115 base_statement = "#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"
120 116 if perm = Redmine::AccessControl.permission(permission)
121 117 unless perm.project_module.nil?
122 118 # If the permission belongs to a project module, make sure the module is enabled
123 119 base_statement << " AND #{Project.table_name}.id IN (SELECT em.project_id FROM #{EnabledModule.table_name} em WHERE em.name='#{perm.project_module}')"
124 120 end
125 121 end
126 122 if options[:project]
127 123 project_statement = "#{Project.table_name}.id = #{options[:project].id}"
128 124 project_statement << " OR (#{Project.table_name}.lft > #{options[:project].lft} AND #{Project.table_name}.rgt < #{options[:project].rgt})" if options[:with_subprojects]
129 125 base_statement = "(#{project_statement}) AND (#{base_statement})"
130 126 end
131 127 if user.admin?
132 128 # no restriction
133 129 else
134 130 statements << "1=0"
135 131 if user.logged?
136 132 if Role.non_member.allowed_to?(permission) && !options[:member]
137 133 statements << "#{Project.table_name}.is_public = #{connection.quoted_true}"
138 134 end
139 135 allowed_project_ids = user.memberships.select {|m| m.roles.detect {|role| role.allowed_to?(permission)}}.collect {|m| m.project_id}
140 136 statements << "#{Project.table_name}.id IN (#{allowed_project_ids.join(',')})" if allowed_project_ids.any?
141 137 else
142 138 if Role.anonymous.allowed_to?(permission) && !options[:member]
143 139 # anonymous user allowed on public project
144 140 statements << "#{Project.table_name}.is_public = #{connection.quoted_true}"
145 141 end
146 142 end
147 143 end
148 144 statements.empty? ? base_statement : "((#{base_statement}) AND (#{statements.join(' OR ')}))"
149 145 end
150 146
151 147 # Returns the Systemwide and project specific activities
152 148 def activities(include_inactive=false)
153 149 if include_inactive
154 150 return all_activities
155 151 else
156 152 return active_activities
157 153 end
158 154 end
159 155
160 156 # Will create a new Project specific Activity or update an existing one
161 157 #
162 158 # This will raise a ActiveRecord::Rollback if the TimeEntryActivity
163 159 # does not successfully save.
164 160 def update_or_create_time_entry_activity(id, activity_hash)
165 161 if activity_hash.respond_to?(:has_key?) && activity_hash.has_key?('parent_id')
166 162 self.create_time_entry_activity_if_needed(activity_hash)
167 163 else
168 164 activity = project.time_entry_activities.find_by_id(id.to_i)
169 165 activity.update_attributes(activity_hash) if activity
170 166 end
171 167 end
172 168
173 169 # Create a new TimeEntryActivity if it overrides a system TimeEntryActivity
174 170 #
175 171 # This will raise a ActiveRecord::Rollback if the TimeEntryActivity
176 172 # does not successfully save.
177 173 def create_time_entry_activity_if_needed(activity)
178 174 if activity['parent_id']
179 175
180 176 parent_activity = TimeEntryActivity.find(activity['parent_id'])
181 177 activity['name'] = parent_activity.name
182 178 activity['position'] = parent_activity.position
183 179
184 180 if Enumeration.overridding_change?(activity, parent_activity)
185 181 project_activity = self.time_entry_activities.create(activity)
186 182
187 183 if project_activity.new_record?
188 184 raise ActiveRecord::Rollback, "Overridding TimeEntryActivity was not successfully saved"
189 185 else
190 186 self.time_entries.update_all("activity_id = #{project_activity.id}", ["activity_id = ?", parent_activity.id])
191 187 end
192 188 end
193 189 end
194 190 end
195 191
196 192 # Returns a :conditions SQL string that can be used to find the issues associated with this project.
197 193 #
198 194 # Examples:
199 195 # project.project_condition(true) => "(projects.id = 1 OR (projects.lft > 1 AND projects.rgt < 10))"
200 196 # project.project_condition(false) => "projects.id = 1"
201 197 def project_condition(with_subprojects)
202 198 cond = "#{Project.table_name}.id = #{id}"
203 199 cond = "(#{cond} OR (#{Project.table_name}.lft > #{lft} AND #{Project.table_name}.rgt < #{rgt}))" if with_subprojects
204 200 cond
205 201 end
206 202
207 203 def self.find(*args)
208 204 if args.first && args.first.is_a?(String) && !args.first.match(/^\d*$/)
209 205 project = find_by_identifier(*args)
210 206 raise ActiveRecord::RecordNotFound, "Couldn't find Project with identifier=#{args.first}" if project.nil?
211 207 project
212 208 else
213 209 super
214 210 end
215 211 end
216 212
217 213 def to_param
218 214 # id is used for projects with a numeric identifier (compatibility)
219 215 @to_param ||= (identifier.to_s =~ %r{^\d*$} ? id : identifier)
220 216 end
221 217
222 218 def active?
223 219 self.status == STATUS_ACTIVE
224 220 end
225 221
226 222 # Archives the project and its descendants recursively
227 223 def archive
228 224 # Archive subprojects if any
229 225 children.each do |subproject|
230 226 subproject.archive
231 227 end
232 228 update_attribute :status, STATUS_ARCHIVED
233 229 end
234 230
235 231 # Unarchives the project
236 232 # All its ancestors must be active
237 233 def unarchive
238 234 return false if ancestors.detect {|a| !a.active?}
239 235 update_attribute :status, STATUS_ACTIVE
240 236 end
241 237
242 238 # Returns an array of projects the project can be moved to
243 239 # by the current user
244 240 def allowed_parents
245 241 return @allowed_parents if @allowed_parents
246 242 @allowed_parents = (Project.find(:all, :conditions => Project.allowed_to_condition(User.current, :add_project, :member => true)) - self_and_descendants)
247 243 unless parent.nil? || @allowed_parents.empty? || @allowed_parents.include?(parent)
248 244 @allowed_parents << parent
249 245 end
250 246 @allowed_parents
251 247 end
252 248
253 249 # Sets the parent of the project with authorization check
254 250 def set_allowed_parent!(p)
255 251 unless p.nil? || p.is_a?(Project)
256 252 if p.to_s.blank?
257 253 p = nil
258 254 else
259 255 p = Project.find_by_id(p)
260 256 return false unless p
261 257 end
262 258 end
263 259 if p.nil?
264 260 if !new_record? && allowed_parents.empty?
265 261 return false
266 262 end
267 263 elsif !allowed_parents.include?(p)
268 264 return false
269 265 end
270 266 set_parent!(p)
271 267 end
272 268
273 269 # Sets the parent of the project
274 270 # Argument can be either a Project, a String, a Fixnum or nil
275 271 def set_parent!(p)
276 272 unless p.nil? || p.is_a?(Project)
277 273 if p.to_s.blank?
278 274 p = nil
279 275 else
280 276 p = Project.find_by_id(p)
281 277 return false unless p
282 278 end
283 279 end
284 280 if p == parent && !p.nil?
285 281 # Nothing to do
286 282 true
287 283 elsif p.nil? || (p.active? && move_possible?(p))
288 284 # Insert the project so that target's children or root projects stay alphabetically sorted
289 285 sibs = (p.nil? ? self.class.roots : p.children)
290 286 to_be_inserted_before = sibs.detect {|c| c.name.to_s.downcase > name.to_s.downcase }
291 287 if to_be_inserted_before
292 288 move_to_left_of(to_be_inserted_before)
293 289 elsif p.nil?
294 290 if sibs.empty?
295 291 # move_to_root adds the project in first (ie. left) position
296 292 move_to_root
297 293 else
298 294 move_to_right_of(sibs.last) unless self == sibs.last
299 295 end
300 296 else
301 297 # move_to_child_of adds the project in last (ie.right) position
302 298 move_to_child_of(p)
303 299 end
304 300 true
305 301 else
306 302 # Can not move to the given target
307 303 false
308 304 end
309 305 end
310 306
311 307 # Returns an array of the trackers used by the project and its active sub projects
312 308 def rolled_up_trackers
313 309 @rolled_up_trackers ||=
314 310 Tracker.find(:all, :include => :projects,
315 311 :select => "DISTINCT #{Tracker.table_name}.*",
316 312 :conditions => ["#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status = #{STATUS_ACTIVE}", lft, rgt],
317 313 :order => "#{Tracker.table_name}.position")
318 314 end
319 315
320 316 # Closes open and locked project versions that are completed
321 317 def close_completed_versions
322 318 Version.transaction do
323 319 versions.find(:all, :conditions => {:status => %w(open locked)}).each do |version|
324 320 if version.completed?
325 321 version.update_attribute(:status, 'closed')
326 322 end
327 323 end
328 324 end
329 325 end
330 326
331 327 # Returns a hash of project users grouped by role
332 328 def users_by_role
333 329 members.find(:all, :include => [:user, :roles]).inject({}) do |h, m|
334 330 m.roles.each do |r|
335 331 h[r] ||= []
336 332 h[r] << m.user
337 333 end
338 334 h
339 335 end
340 336 end
341 337
342 338 # Deletes all project's members
343 339 def delete_all_members
344 340 me, mr = Member.table_name, MemberRole.table_name
345 341 connection.delete("DELETE FROM #{mr} WHERE #{mr}.member_id IN (SELECT #{me}.id FROM #{me} WHERE #{me}.project_id = #{id})")
346 342 Member.delete_all(['project_id = ?', id])
347 343 end
348 344
349 345 # Users issues can be assigned to
350 346 def assignable_users
351 347 members.select {|m| m.roles.detect {|role| role.assignable?}}.collect {|m| m.user}.sort
352 348 end
353 349
354 350 # Returns the mail adresses of users that should be always notified on project events
355 351 def recipients
356 352 members.select {|m| m.mail_notification? || m.user.mail_notification?}.collect {|m| m.user.mail}
357 353 end
358 354
359 355 # Returns an array of all custom fields enabled for project issues
360 356 # (explictly associated custom fields and custom fields enabled for all projects)
361 357 def all_issue_custom_fields
362 358 @all_issue_custom_fields ||= (IssueCustomField.for_all + issue_custom_fields).uniq.sort
363 359 end
364 360
365 361 def project
366 362 self
367 363 end
368 364
369 365 def <=>(project)
370 366 name.downcase <=> project.name.downcase
371 367 end
372 368
373 369 def to_s
374 370 name
375 371 end
376 372
377 373 # Returns a short description of the projects (first lines)
378 374 def short_description(length = 255)
379 375 description.gsub(/^(.{#{length}}[^\n\r]*).*$/m, '\1...').strip if description
380 376 end
381 377
382 378 # Return true if this project is allowed to do the specified action.
383 379 # action can be:
384 380 # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
385 381 # * a permission Symbol (eg. :edit_project)
386 382 def allows_to?(action)
387 383 if action.is_a? Hash
388 384 allowed_actions.include? "#{action[:controller]}/#{action[:action]}"
389 385 else
390 386 allowed_permissions.include? action
391 387 end
392 388 end
393 389
394 390 def module_enabled?(module_name)
395 391 module_name = module_name.to_s
396 392 enabled_modules.detect {|m| m.name == module_name}
397 393 end
398 394
399 395 def enabled_module_names=(module_names)
400 396 if module_names && module_names.is_a?(Array)
401 397 module_names = module_names.collect(&:to_s)
402 398 # remove disabled modules
403 399 enabled_modules.each {|mod| mod.destroy unless module_names.include?(mod.name)}
404 400 # add new modules
405 401 module_names.reject {|name| module_enabled?(name)}.each {|name| enabled_modules << EnabledModule.new(:name => name)}
406 402 else
407 403 enabled_modules.clear
408 404 end
409 405 end
410 406
411 407 # Returns an auto-generated project identifier based on the last identifier used
412 408 def self.next_identifier
413 409 p = Project.find(:first, :order => 'created_on DESC')
414 410 p.nil? ? nil : p.identifier.to_s.succ
415 411 end
416 412
417 413 # Copies and saves the Project instance based on the +project+.
418 414 # Duplicates the source project's:
419 415 # * Wiki
420 416 # * Versions
421 417 # * Categories
422 418 # * Issues
423 419 # * Members
424 420 # * Queries
425 421 #
426 422 # Accepts an +options+ argument to specify what to copy
427 423 #
428 424 # Examples:
429 425 # project.copy(1) # => copies everything
430 426 # project.copy(1, :only => 'members') # => copies members only
431 427 # project.copy(1, :only => ['members', 'versions']) # => copies members and versions
432 428 def copy(project, options={})
433 429 project = project.is_a?(Project) ? project : Project.find(project)
434 430
435 431 to_be_copied = %w(wiki versions issue_categories issues members queries boards)
436 432 to_be_copied = to_be_copied & options[:only].to_a unless options[:only].nil?
437 433
438 434 Project.transaction do
439 435 if save
440 436 reload
441 437 to_be_copied.each do |name|
442 438 send "copy_#{name}", project
443 439 end
444 440 Redmine::Hook.call_hook(:model_project_copy_before_save, :source_project => project, :destination_project => self)
445 441 save
446 442 end
447 443 end
448 444 end
449 445
450 446
451 447 # Copies +project+ and returns the new instance. This will not save
452 448 # the copy
453 449 def self.copy_from(project)
454 450 begin
455 451 project = project.is_a?(Project) ? project : Project.find(project)
456 452 if project
457 453 # clear unique attributes
458 454 attributes = project.attributes.dup.except('id', 'name', 'identifier', 'status', 'parent_id', 'lft', 'rgt')
459 455 copy = Project.new(attributes)
460 456 copy.enabled_modules = project.enabled_modules
461 457 copy.trackers = project.trackers
462 458 copy.custom_values = project.custom_values.collect {|v| v.clone}
463 459 copy.issue_custom_fields = project.issue_custom_fields
464 460 return copy
465 461 else
466 462 return nil
467 463 end
468 464 rescue ActiveRecord::RecordNotFound
469 465 return nil
470 466 end
471 467 end
472 468
473 469 private
474 470
475 471 # Copies wiki from +project+
476 472 def copy_wiki(project)
477 473 # Check that the source project has a wiki first
478 474 unless project.wiki.nil?
479 475 self.wiki ||= Wiki.new
480 476 wiki.attributes = project.wiki.attributes.dup.except("id", "project_id")
481 477 project.wiki.pages.each do |page|
482 478 new_wiki_content = WikiContent.new(page.content.attributes.dup.except("id", "page_id", "updated_on"))
483 479 new_wiki_page = WikiPage.new(page.attributes.dup.except("id", "wiki_id", "created_on", "parent_id"))
484 480 new_wiki_page.content = new_wiki_content
485 481 wiki.pages << new_wiki_page
486 482 end
487 483 end
488 484 end
489 485
490 486 # Copies versions from +project+
491 487 def copy_versions(project)
492 488 project.versions.each do |version|
493 489 new_version = Version.new
494 490 new_version.attributes = version.attributes.dup.except("id", "project_id", "created_on", "updated_on")
495 491 self.versions << new_version
496 492 end
497 493 end
498 494
499 495 # Copies issue categories from +project+
500 496 def copy_issue_categories(project)
501 497 project.issue_categories.each do |issue_category|
502 498 new_issue_category = IssueCategory.new
503 499 new_issue_category.attributes = issue_category.attributes.dup.except("id", "project_id")
504 500 self.issue_categories << new_issue_category
505 501 end
506 502 end
507 503
508 504 # Copies issues from +project+
509 505 def copy_issues(project)
510 506 project.issues.each do |issue|
511 507 new_issue = Issue.new
512 508 new_issue.copy_from(issue)
513 509 # Reassign fixed_versions by name, since names are unique per
514 510 # project and the versions for self are not yet saved
515 511 if issue.fixed_version
516 512 new_issue.fixed_version = self.versions.select {|v| v.name == issue.fixed_version.name}.first
517 513 end
518 514 # Reassign the category by name, since names are unique per
519 515 # project and the categories for self are not yet saved
520 516 if issue.category
521 517 new_issue.category = self.issue_categories.select {|c| c.name == issue.category.name}.first
522 518 end
523 519 self.issues << new_issue
524 520 end
525 521 end
526 522
527 523 # Copies members from +project+
528 524 def copy_members(project)
529 525 project.members.each do |member|
530 526 new_member = Member.new
531 527 new_member.attributes = member.attributes.dup.except("id", "project_id", "created_on")
532 528 new_member.role_ids = member.role_ids.dup
533 529 new_member.project = self
534 530 self.members << new_member
535 531 end
536 532 end
537 533
538 534 # Copies queries from +project+
539 535 def copy_queries(project)
540 536 project.queries.each do |query|
541 537 new_query = Query.new
542 538 new_query.attributes = query.attributes.dup.except("id", "project_id", "sort_criteria")
543 539 new_query.sort_criteria = query.sort_criteria if query.sort_criteria
544 540 new_query.project = self
545 541 self.queries << new_query
546 542 end
547 543 end
548 544
549 545 # Copies boards from +project+
550 546 def copy_boards(project)
551 547 project.boards.each do |board|
552 548 new_board = Board.new
553 549 new_board.attributes = board.attributes.dup.except("id", "project_id", "topics_count", "messages_count", "last_message_id")
554 550 new_board.project = self
555 551 self.boards << new_board
556 552 end
557 553 end
558 554
559 555 def allowed_permissions
560 556 @allowed_permissions ||= begin
561 557 module_names = enabled_modules.collect {|m| m.name}
562 558 Redmine::AccessControl.modules_permissions(module_names).collect {|p| p.name}
563 559 end
564 560 end
565 561
566 562 def allowed_actions
567 563 @actions_allowed ||= allowed_permissions.inject([]) { |actions, permission| actions += Redmine::AccessControl.allowed_actions(permission) }.flatten
568 564 end
569 565
570 566 # Returns all the active Systemwide and project specific activities
571 567 def active_activities
572 568 overridden_activity_ids = self.time_entry_activities.active.collect(&:parent_id)
573 569
574 570 if overridden_activity_ids.empty?
575 return TimeEntryActivity.active
571 return TimeEntryActivity.shared.active
576 572 else
577 573 return system_activities_and_project_overrides
578 574 end
579 575 end
580 576
581 577 # Returns all the Systemwide and project specific activities
582 578 # (inactive and active)
583 579 def all_activities
584 580 overridden_activity_ids = self.time_entry_activities.collect(&:parent_id)
585 581
586 582 if overridden_activity_ids.empty?
587 return TimeEntryActivity.all
583 return TimeEntryActivity.shared
588 584 else
589 585 return system_activities_and_project_overrides(true)
590 586 end
591 587 end
592 588
593 589 # Returns the systemwide active activities merged with the project specific overrides
594 590 def system_activities_and_project_overrides(include_inactive=false)
595 591 if include_inactive
596 return TimeEntryActivity.all.
592 return TimeEntryActivity.shared.
597 593 find(:all,
598 594 :conditions => ["id NOT IN (?)", self.time_entry_activities.collect(&:parent_id)]) +
599 595 self.time_entry_activities
600 596 else
601 return TimeEntryActivity.active.
597 return TimeEntryActivity.shared.active.
602 598 find(:all,
603 599 :conditions => ["id NOT IN (?)", self.time_entry_activities.active.collect(&:parent_id)]) +
604 600 self.time_entry_activities.active
605 601 end
606 602 end
607 603 end
@@ -1,37 +1,37
1 1 <h2><%=l(:label_enumerations)%></h2>
2 2
3 3 <% Enumeration.get_subclasses.each do |klass| %>
4 4 <h3><%= l(klass::OptionName) %></h3>
5 5
6 <% enumerations = klass.all %>
6 <% enumerations = klass.shared %>
7 7 <% if enumerations.any? %>
8 8 <table class="list">
9 9 <tr>
10 10 <th><%= l(:field_name) %></th>
11 11 <th style="width:15%;"><%= l(:field_is_default) %></th>
12 12 <th style="width:15%;"><%= l(:field_active) %></th>
13 13 <th style="width:15%;"></th>
14 14 <th align="center" style="width:10%;"> </th>
15 15 </tr>
16 16 <% enumerations.each do |enumeration| %>
17 17 <tr class="<%= cycle('odd', 'even') %>">
18 18 <td><%= link_to h(enumeration), :action => 'edit', :id => enumeration %></td>
19 19 <td class="center" style="width:15%;"><%= image_tag('true.png') if enumeration.is_default? %></td>
20 20 <td class="center" style="width:15%;"><%= image_tag('true.png') if enumeration.active? %></td>
21 21 <td style="width:15%;"><%= reorder_links('enumeration', {:action => 'update', :id => enumeration}) %></td>
22 22 <td class="buttons">
23 23 <%= link_to l(:button_delete), { :action => 'destroy', :id => enumeration },
24 24 :method => :post,
25 25 :confirm => l(:text_are_you_sure),
26 26 :class => 'icon icon-del' %>
27 27 </td>
28 28 </tr>
29 29 <% end %>
30 30 </table>
31 31 <% reset_cycle %>
32 32 <% end %>
33 33
34 34 <p><%= link_to l(:label_enumeration_new), { :action => 'new', :type => klass.name } %></p>
35 35 <% end %>
36 36
37 37 <% html_title(l(:label_enumerations)) -%>
General Comments 0
You need to be logged in to leave comments. Login now