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