##// END OF EJS Templates
Makes models #initialize accept additional arguments....
Jean-Philippe Lang -
r8167:062fbeae8047
parent child
Show More
@@ -1,164 +1,164
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2011 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 class CustomField < ActiveRecord::Base
19 19 include Redmine::SubclassFactory
20 20
21 21 has_many :custom_values, :dependent => :delete_all
22 22 acts_as_list :scope => 'type = \'#{self.class}\''
23 23 serialize :possible_values
24 24
25 25 validates_presence_of :name, :field_format
26 26 validates_uniqueness_of :name, :scope => :type
27 27 validates_length_of :name, :maximum => 30
28 28 validates_inclusion_of :field_format, :in => Redmine::CustomFieldFormat.available_formats
29 29
30 30 validate :validate_values
31 31 before_validation :set_searchable
32 32
33 def initialize(attributes = nil)
33 def initialize(attributes=nil, *args)
34 34 super
35 35 self.possible_values ||= []
36 36 end
37 37
38 38 def set_searchable
39 39 # make sure these fields are not searchable
40 40 self.searchable = false if %w(int float date bool).include?(field_format)
41 41 true
42 42 end
43 43
44 44 def validate_values
45 45 if self.field_format == "list"
46 46 errors.add(:possible_values, :blank) if self.possible_values.nil? || self.possible_values.empty?
47 47 errors.add(:possible_values, :invalid) unless self.possible_values.is_a? Array
48 48 end
49 49
50 50 if regexp.present?
51 51 begin
52 52 Regexp.new(regexp)
53 53 rescue
54 54 errors.add(:regexp, :invalid)
55 55 end
56 56 end
57 57
58 58 # validate default value
59 59 v = CustomValue.new(:custom_field => self.clone, :value => default_value, :customized => nil)
60 60 v.custom_field.is_required = false
61 61 errors.add(:default_value, :invalid) unless v.valid?
62 62 end
63 63
64 64 def possible_values_options(obj=nil)
65 65 case field_format
66 66 when 'user', 'version'
67 67 if obj.respond_to?(:project) && obj.project
68 68 case field_format
69 69 when 'user'
70 70 obj.project.users.sort.collect {|u| [u.to_s, u.id.to_s]}
71 71 when 'version'
72 72 obj.project.shared_versions.sort.collect {|u| [u.to_s, u.id.to_s]}
73 73 end
74 74 elsif obj.is_a?(Array)
75 75 obj.collect {|o| possible_values_options(o)}.inject {|memo, v| memo & v}
76 76 else
77 77 []
78 78 end
79 79 else
80 80 read_attribute :possible_values
81 81 end
82 82 end
83 83
84 84 def possible_values(obj=nil)
85 85 case field_format
86 86 when 'user', 'version'
87 87 possible_values_options(obj).collect(&:last)
88 88 else
89 89 read_attribute :possible_values
90 90 end
91 91 end
92 92
93 93 # Makes possible_values accept a multiline string
94 94 def possible_values=(arg)
95 95 if arg.is_a?(Array)
96 96 write_attribute(:possible_values, arg.compact.collect(&:strip).select {|v| !v.blank?})
97 97 else
98 98 self.possible_values = arg.to_s.split(/[\n\r]+/)
99 99 end
100 100 end
101 101
102 102 def cast_value(value)
103 103 casted = nil
104 104 unless value.blank?
105 105 case field_format
106 106 when 'string', 'text', 'list'
107 107 casted = value
108 108 when 'date'
109 109 casted = begin; value.to_date; rescue; nil end
110 110 when 'bool'
111 111 casted = (value == '1' ? true : false)
112 112 when 'int'
113 113 casted = value.to_i
114 114 when 'float'
115 115 casted = value.to_f
116 116 when 'user', 'version'
117 117 casted = (value.blank? ? nil : field_format.classify.constantize.find_by_id(value.to_i))
118 118 end
119 119 end
120 120 casted
121 121 end
122 122
123 123 # Returns a ORDER BY clause that can used to sort customized
124 124 # objects by their value of the custom field.
125 125 # Returns false, if the custom field can not be used for sorting.
126 126 def order_statement
127 127 case field_format
128 128 when 'string', 'text', 'list', 'date', 'bool'
129 129 # COALESCE is here to make sure that blank and NULL values are sorted equally
130 130 "COALESCE((SELECT cv_sort.value FROM #{CustomValue.table_name} cv_sort" +
131 131 " WHERE cv_sort.customized_type='#{self.class.customized_class.name}'" +
132 132 " AND cv_sort.customized_id=#{self.class.customized_class.table_name}.id" +
133 133 " AND cv_sort.custom_field_id=#{id} LIMIT 1), '')"
134 134 when 'int', 'float'
135 135 # Make the database cast values into numeric
136 136 # Postgresql will raise an error if a value can not be casted!
137 137 # CustomValue validations should ensure that it doesn't occur
138 138 "(SELECT CAST(cv_sort.value AS decimal(60,3)) FROM #{CustomValue.table_name} cv_sort" +
139 139 " WHERE cv_sort.customized_type='#{self.class.customized_class.name}'" +
140 140 " AND cv_sort.customized_id=#{self.class.customized_class.table_name}.id" +
141 141 " AND cv_sort.custom_field_id=#{id} AND cv_sort.value <> '' AND cv_sort.value IS NOT NULL LIMIT 1)"
142 142 else
143 143 nil
144 144 end
145 145 end
146 146
147 147 def <=>(field)
148 148 position <=> field.position
149 149 end
150 150
151 151 def self.customized_class
152 152 self.name =~ /^(.+)CustomField$/
153 153 begin; $1.constantize; rescue nil; end
154 154 end
155 155
156 156 # to move in project_custom_field
157 157 def self.for_all
158 158 find(:all, :conditions => ["is_for_all=?", true], :order => 'position')
159 159 end
160 160
161 161 def type_name
162 162 nil
163 163 end
164 164 end
@@ -1,888 +1,888
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2011 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 class Project < ActiveRecord::Base
19 19 include Redmine::SafeAttributes
20 20
21 21 # Project statuses
22 22 STATUS_ACTIVE = 1
23 23 STATUS_ARCHIVED = 9
24 24
25 25 # Maximum length for project identifiers
26 26 IDENTIFIER_MAX_LENGTH = 100
27 27
28 28 # Specific overidden Activities
29 29 has_many :time_entry_activities
30 30 has_many :members, :include => [:user, :roles], :conditions => "#{User.table_name}.type='User' AND #{User.table_name}.status=#{User::STATUS_ACTIVE}"
31 31 has_many :memberships, :class_name => 'Member'
32 32 has_many :member_principals, :class_name => 'Member',
33 33 :include => :principal,
34 34 :conditions => "#{Principal.table_name}.type='Group' OR (#{Principal.table_name}.type='User' AND #{Principal.table_name}.status=#{User::STATUS_ACTIVE})"
35 35 has_many :users, :through => :members
36 36 has_many :principals, :through => :member_principals, :source => :principal
37 37
38 38 has_many :enabled_modules, :dependent => :delete_all
39 39 has_and_belongs_to_many :trackers, :order => "#{Tracker.table_name}.position"
40 40 has_many :issues, :dependent => :destroy, :order => "#{Issue.table_name}.created_on DESC", :include => [:status, :tracker]
41 41 has_many :issue_changes, :through => :issues, :source => :journals
42 42 has_many :versions, :dependent => :destroy, :order => "#{Version.table_name}.effective_date DESC, #{Version.table_name}.name DESC"
43 43 has_many :time_entries, :dependent => :delete_all
44 44 has_many :queries, :dependent => :delete_all
45 45 has_many :documents, :dependent => :destroy
46 46 has_many :news, :dependent => :destroy, :include => :author
47 47 has_many :issue_categories, :dependent => :delete_all, :order => "#{IssueCategory.table_name}.name"
48 48 has_many :boards, :dependent => :destroy, :order => "position ASC"
49 49 has_one :repository, :dependent => :destroy
50 50 has_many :changesets, :through => :repository
51 51 has_one :wiki, :dependent => :destroy
52 52 # Custom field for the project issues
53 53 has_and_belongs_to_many :issue_custom_fields,
54 54 :class_name => 'IssueCustomField',
55 55 :order => "#{CustomField.table_name}.position",
56 56 :join_table => "#{table_name_prefix}custom_fields_projects#{table_name_suffix}",
57 57 :association_foreign_key => 'custom_field_id'
58 58
59 59 acts_as_nested_set :order => 'name', :dependent => :destroy
60 60 acts_as_attachable :view_permission => :view_files,
61 61 :delete_permission => :manage_files
62 62
63 63 acts_as_customizable
64 64 acts_as_searchable :columns => ['name', 'identifier', 'description'], :project_key => 'id', :permission => nil
65 65 acts_as_event :title => Proc.new {|o| "#{l(:label_project)}: #{o.name}"},
66 66 :url => Proc.new {|o| {:controller => 'projects', :action => 'show', :id => o}},
67 67 :author => nil
68 68
69 69 attr_protected :status
70 70
71 71 validates_presence_of :name, :identifier
72 72 validates_uniqueness_of :identifier
73 73 validates_associated :repository, :wiki
74 74 validates_length_of :name, :maximum => 255
75 75 validates_length_of :homepage, :maximum => 255
76 76 validates_length_of :identifier, :in => 1..IDENTIFIER_MAX_LENGTH
77 77 # donwcase letters, digits, dashes but not digits only
78 78 validates_format_of :identifier, :with => /^(?!\d+$)[a-z0-9\-]*$/, :if => Proc.new { |p| p.identifier_changed? }
79 79 # reserved words
80 80 validates_exclusion_of :identifier, :in => %w( new )
81 81
82 82 before_destroy :delete_all_members
83 83
84 84 named_scope :has_module, lambda { |mod| { :conditions => ["#{Project.table_name}.id IN (SELECT em.project_id FROM #{EnabledModule.table_name} em WHERE em.name=?)", mod.to_s] } }
85 85 named_scope :active, { :conditions => "#{Project.table_name}.status = #{STATUS_ACTIVE}"}
86 86 named_scope :status, lambda {|arg| arg.blank? ? {} : {:conditions => {:status => arg.to_i}} }
87 87 named_scope :all_public, { :conditions => { :is_public => true } }
88 88 named_scope :visible, lambda {|*args| {:conditions => Project.visible_condition(args.shift || User.current, *args) }}
89 89 named_scope :like, lambda {|arg|
90 90 if arg.blank?
91 91 {}
92 92 else
93 93 pattern = "%#{arg.to_s.strip.downcase}%"
94 94 {:conditions => ["LOWER(identifier) LIKE :p OR LOWER(name) LIKE :p", {:p => pattern}]}
95 95 end
96 96 }
97 97
98 def initialize(attributes = nil)
98 def initialize(attributes=nil, *args)
99 99 super
100 100
101 101 initialized = (attributes || {}).stringify_keys
102 102 if !initialized.key?('identifier') && Setting.sequential_project_identifiers?
103 103 self.identifier = Project.next_identifier
104 104 end
105 105 if !initialized.key?('is_public')
106 106 self.is_public = Setting.default_projects_public?
107 107 end
108 108 if !initialized.key?('enabled_module_names')
109 109 self.enabled_module_names = Setting.default_projects_modules
110 110 end
111 111 if !initialized.key?('trackers') && !initialized.key?('tracker_ids')
112 112 self.trackers = Tracker.all
113 113 end
114 114 end
115 115
116 116 def identifier=(identifier)
117 117 super unless identifier_frozen?
118 118 end
119 119
120 120 def identifier_frozen?
121 121 errors[:identifier].nil? && !(new_record? || identifier.blank?)
122 122 end
123 123
124 124 # returns latest created projects
125 125 # non public projects will be returned only if user is a member of those
126 126 def self.latest(user=nil, count=5)
127 127 visible(user).find(:all, :limit => count, :order => "created_on DESC")
128 128 end
129 129
130 130 # Returns true if the project is visible to +user+ or to the current user.
131 131 def visible?(user=User.current)
132 132 user.allowed_to?(:view_project, self)
133 133 end
134 134
135 135 # Returns a SQL conditions string used to find all projects visible by the specified user.
136 136 #
137 137 # Examples:
138 138 # Project.visible_condition(admin) => "projects.status = 1"
139 139 # Project.visible_condition(normal_user) => "((projects.status = 1) AND (projects.is_public = 1 OR projects.id IN (1,3,4)))"
140 140 # Project.visible_condition(anonymous) => "((projects.status = 1) AND (projects.is_public = 1))"
141 141 def self.visible_condition(user, options={})
142 142 allowed_to_condition(user, :view_project, options)
143 143 end
144 144
145 145 # Returns a SQL conditions string used to find all projects for which +user+ has the given +permission+
146 146 #
147 147 # Valid options:
148 148 # * :project => limit the condition to project
149 149 # * :with_subprojects => limit the condition to project and its subprojects
150 150 # * :member => limit the condition to the user projects
151 151 def self.allowed_to_condition(user, permission, options={})
152 152 base_statement = "#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"
153 153 if perm = Redmine::AccessControl.permission(permission)
154 154 unless perm.project_module.nil?
155 155 # If the permission belongs to a project module, make sure the module is enabled
156 156 base_statement << " AND #{Project.table_name}.id IN (SELECT em.project_id FROM #{EnabledModule.table_name} em WHERE em.name='#{perm.project_module}')"
157 157 end
158 158 end
159 159 if options[:project]
160 160 project_statement = "#{Project.table_name}.id = #{options[:project].id}"
161 161 project_statement << " OR (#{Project.table_name}.lft > #{options[:project].lft} AND #{Project.table_name}.rgt < #{options[:project].rgt})" if options[:with_subprojects]
162 162 base_statement = "(#{project_statement}) AND (#{base_statement})"
163 163 end
164 164
165 165 if user.admin?
166 166 base_statement
167 167 else
168 168 statement_by_role = {}
169 169 unless options[:member]
170 170 role = user.logged? ? Role.non_member : Role.anonymous
171 171 if role.allowed_to?(permission)
172 172 statement_by_role[role] = "#{Project.table_name}.is_public = #{connection.quoted_true}"
173 173 end
174 174 end
175 175 if user.logged?
176 176 user.projects_by_role.each do |role, projects|
177 177 if role.allowed_to?(permission)
178 178 statement_by_role[role] = "#{Project.table_name}.id IN (#{projects.collect(&:id).join(',')})"
179 179 end
180 180 end
181 181 end
182 182 if statement_by_role.empty?
183 183 "1=0"
184 184 else
185 185 if block_given?
186 186 statement_by_role.each do |role, statement|
187 187 if s = yield(role, user)
188 188 statement_by_role[role] = "(#{statement} AND (#{s}))"
189 189 end
190 190 end
191 191 end
192 192 "((#{base_statement}) AND (#{statement_by_role.values.join(' OR ')}))"
193 193 end
194 194 end
195 195 end
196 196
197 197 # Returns the Systemwide and project specific activities
198 198 def activities(include_inactive=false)
199 199 if include_inactive
200 200 return all_activities
201 201 else
202 202 return active_activities
203 203 end
204 204 end
205 205
206 206 # Will create a new Project specific Activity or update an existing one
207 207 #
208 208 # This will raise a ActiveRecord::Rollback if the TimeEntryActivity
209 209 # does not successfully save.
210 210 def update_or_create_time_entry_activity(id, activity_hash)
211 211 if activity_hash.respond_to?(:has_key?) && activity_hash.has_key?('parent_id')
212 212 self.create_time_entry_activity_if_needed(activity_hash)
213 213 else
214 214 activity = project.time_entry_activities.find_by_id(id.to_i)
215 215 activity.update_attributes(activity_hash) if activity
216 216 end
217 217 end
218 218
219 219 # Create a new TimeEntryActivity if it overrides a system TimeEntryActivity
220 220 #
221 221 # This will raise a ActiveRecord::Rollback if the TimeEntryActivity
222 222 # does not successfully save.
223 223 def create_time_entry_activity_if_needed(activity)
224 224 if activity['parent_id']
225 225
226 226 parent_activity = TimeEntryActivity.find(activity['parent_id'])
227 227 activity['name'] = parent_activity.name
228 228 activity['position'] = parent_activity.position
229 229
230 230 if Enumeration.overridding_change?(activity, parent_activity)
231 231 project_activity = self.time_entry_activities.create(activity)
232 232
233 233 if project_activity.new_record?
234 234 raise ActiveRecord::Rollback, "Overridding TimeEntryActivity was not successfully saved"
235 235 else
236 236 self.time_entries.update_all("activity_id = #{project_activity.id}", ["activity_id = ?", parent_activity.id])
237 237 end
238 238 end
239 239 end
240 240 end
241 241
242 242 # Returns a :conditions SQL string that can be used to find the issues associated with this project.
243 243 #
244 244 # Examples:
245 245 # project.project_condition(true) => "(projects.id = 1 OR (projects.lft > 1 AND projects.rgt < 10))"
246 246 # project.project_condition(false) => "projects.id = 1"
247 247 def project_condition(with_subprojects)
248 248 cond = "#{Project.table_name}.id = #{id}"
249 249 cond = "(#{cond} OR (#{Project.table_name}.lft > #{lft} AND #{Project.table_name}.rgt < #{rgt}))" if with_subprojects
250 250 cond
251 251 end
252 252
253 253 def self.find(*args)
254 254 if args.first && args.first.is_a?(String) && !args.first.match(/^\d*$/)
255 255 project = find_by_identifier(*args)
256 256 raise ActiveRecord::RecordNotFound, "Couldn't find Project with identifier=#{args.first}" if project.nil?
257 257 project
258 258 else
259 259 super
260 260 end
261 261 end
262 262
263 263 def to_param
264 264 # id is used for projects with a numeric identifier (compatibility)
265 265 @to_param ||= (identifier.to_s =~ %r{^\d*$} ? id : identifier)
266 266 end
267 267
268 268 def active?
269 269 self.status == STATUS_ACTIVE
270 270 end
271 271
272 272 def archived?
273 273 self.status == STATUS_ARCHIVED
274 274 end
275 275
276 276 # Archives the project and its descendants
277 277 def archive
278 278 # Check that there is no issue of a non descendant project that is assigned
279 279 # to one of the project or descendant versions
280 280 v_ids = self_and_descendants.collect {|p| p.version_ids}.flatten
281 281 if v_ids.any? && Issue.find(:first, :include => :project,
282 282 :conditions => ["(#{Project.table_name}.lft < ? OR #{Project.table_name}.rgt > ?)" +
283 283 " AND #{Issue.table_name}.fixed_version_id IN (?)", lft, rgt, v_ids])
284 284 return false
285 285 end
286 286 Project.transaction do
287 287 archive!
288 288 end
289 289 true
290 290 end
291 291
292 292 # Unarchives the project
293 293 # All its ancestors must be active
294 294 def unarchive
295 295 return false if ancestors.detect {|a| !a.active?}
296 296 update_attribute :status, STATUS_ACTIVE
297 297 end
298 298
299 299 # Returns an array of projects the project can be moved to
300 300 # by the current user
301 301 def allowed_parents
302 302 return @allowed_parents if @allowed_parents
303 303 @allowed_parents = Project.find(:all, :conditions => Project.allowed_to_condition(User.current, :add_subprojects))
304 304 @allowed_parents = @allowed_parents - self_and_descendants
305 305 if User.current.allowed_to?(:add_project, nil, :global => true) || (!new_record? && parent.nil?)
306 306 @allowed_parents << nil
307 307 end
308 308 unless parent.nil? || @allowed_parents.empty? || @allowed_parents.include?(parent)
309 309 @allowed_parents << parent
310 310 end
311 311 @allowed_parents
312 312 end
313 313
314 314 # Sets the parent of the project with authorization check
315 315 def set_allowed_parent!(p)
316 316 unless p.nil? || p.is_a?(Project)
317 317 if p.to_s.blank?
318 318 p = nil
319 319 else
320 320 p = Project.find_by_id(p)
321 321 return false unless p
322 322 end
323 323 end
324 324 if p.nil?
325 325 if !new_record? && allowed_parents.empty?
326 326 return false
327 327 end
328 328 elsif !allowed_parents.include?(p)
329 329 return false
330 330 end
331 331 set_parent!(p)
332 332 end
333 333
334 334 # Sets the parent of the project
335 335 # Argument can be either a Project, a String, a Fixnum or nil
336 336 def set_parent!(p)
337 337 unless p.nil? || p.is_a?(Project)
338 338 if p.to_s.blank?
339 339 p = nil
340 340 else
341 341 p = Project.find_by_id(p)
342 342 return false unless p
343 343 end
344 344 end
345 345 if p == parent && !p.nil?
346 346 # Nothing to do
347 347 true
348 348 elsif p.nil? || (p.active? && move_possible?(p))
349 349 # Insert the project so that target's children or root projects stay alphabetically sorted
350 350 sibs = (p.nil? ? self.class.roots : p.children)
351 351 to_be_inserted_before = sibs.detect {|c| c.name.to_s.downcase > name.to_s.downcase }
352 352 if to_be_inserted_before
353 353 move_to_left_of(to_be_inserted_before)
354 354 elsif p.nil?
355 355 if sibs.empty?
356 356 # move_to_root adds the project in first (ie. left) position
357 357 move_to_root
358 358 else
359 359 move_to_right_of(sibs.last) unless self == sibs.last
360 360 end
361 361 else
362 362 # move_to_child_of adds the project in last (ie.right) position
363 363 move_to_child_of(p)
364 364 end
365 365 Issue.update_versions_from_hierarchy_change(self)
366 366 true
367 367 else
368 368 # Can not move to the given target
369 369 false
370 370 end
371 371 end
372 372
373 373 # Returns an array of the trackers used by the project and its active sub projects
374 374 def rolled_up_trackers
375 375 @rolled_up_trackers ||=
376 376 Tracker.find(:all, :joins => :projects,
377 377 :select => "DISTINCT #{Tracker.table_name}.*",
378 378 :conditions => ["#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status = #{STATUS_ACTIVE}", lft, rgt],
379 379 :order => "#{Tracker.table_name}.position")
380 380 end
381 381
382 382 # Closes open and locked project versions that are completed
383 383 def close_completed_versions
384 384 Version.transaction do
385 385 versions.find(:all, :conditions => {:status => %w(open locked)}).each do |version|
386 386 if version.completed?
387 387 version.update_attribute(:status, 'closed')
388 388 end
389 389 end
390 390 end
391 391 end
392 392
393 393 # Returns a scope of the Versions on subprojects
394 394 def rolled_up_versions
395 395 @rolled_up_versions ||=
396 396 Version.scoped(:include => :project,
397 397 :conditions => ["#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status = #{STATUS_ACTIVE}", lft, rgt])
398 398 end
399 399
400 400 # Returns a scope of the Versions used by the project
401 401 def shared_versions
402 402 @shared_versions ||= begin
403 403 r = root? ? self : root
404 404 Version.scoped(:include => :project,
405 405 :conditions => "#{Project.table_name}.id = #{id}" +
406 406 " OR (#{Project.table_name}.status = #{Project::STATUS_ACTIVE} AND (" +
407 407 " #{Version.table_name}.sharing = 'system'" +
408 408 " OR (#{Project.table_name}.lft >= #{r.lft} AND #{Project.table_name}.rgt <= #{r.rgt} AND #{Version.table_name}.sharing = 'tree')" +
409 409 " OR (#{Project.table_name}.lft < #{lft} AND #{Project.table_name}.rgt > #{rgt} AND #{Version.table_name}.sharing IN ('hierarchy', 'descendants'))" +
410 410 " OR (#{Project.table_name}.lft > #{lft} AND #{Project.table_name}.rgt < #{rgt} AND #{Version.table_name}.sharing = 'hierarchy')" +
411 411 "))")
412 412 end
413 413 end
414 414
415 415 # Returns a hash of project users grouped by role
416 416 def users_by_role
417 417 members.find(:all, :include => [:user, :roles]).inject({}) do |h, m|
418 418 m.roles.each do |r|
419 419 h[r] ||= []
420 420 h[r] << m.user
421 421 end
422 422 h
423 423 end
424 424 end
425 425
426 426 # Deletes all project's members
427 427 def delete_all_members
428 428 me, mr = Member.table_name, MemberRole.table_name
429 429 connection.delete("DELETE FROM #{mr} WHERE #{mr}.member_id IN (SELECT #{me}.id FROM #{me} WHERE #{me}.project_id = #{id})")
430 430 Member.delete_all(['project_id = ?', id])
431 431 end
432 432
433 433 # Users/groups issues can be assigned to
434 434 def assignable_users
435 435 assignable = Setting.issue_group_assignment? ? member_principals : members
436 436 assignable.select {|m| m.roles.detect {|role| role.assignable?}}.collect {|m| m.principal}.sort
437 437 end
438 438
439 439 # Returns the mail adresses of users that should be always notified on project events
440 440 def recipients
441 441 notified_users.collect {|user| user.mail}
442 442 end
443 443
444 444 # Returns the users that should be notified on project events
445 445 def notified_users
446 446 # TODO: User part should be extracted to User#notify_about?
447 447 members.select {|m| m.mail_notification? || m.user.mail_notification == 'all'}.collect {|m| m.user}
448 448 end
449 449
450 450 # Returns an array of all custom fields enabled for project issues
451 451 # (explictly associated custom fields and custom fields enabled for all projects)
452 452 def all_issue_custom_fields
453 453 @all_issue_custom_fields ||= (IssueCustomField.for_all + issue_custom_fields).uniq.sort
454 454 end
455 455
456 456 # Returns an array of all custom fields enabled for project time entries
457 457 # (explictly associated custom fields and custom fields enabled for all projects)
458 458 def all_time_entry_custom_fields
459 459 @all_time_entry_custom_fields ||= (TimeEntryCustomField.for_all + time_entry_custom_fields).uniq.sort
460 460 end
461 461
462 462 def project
463 463 self
464 464 end
465 465
466 466 def <=>(project)
467 467 name.downcase <=> project.name.downcase
468 468 end
469 469
470 470 def to_s
471 471 name
472 472 end
473 473
474 474 # Returns a short description of the projects (first lines)
475 475 def short_description(length = 255)
476 476 description.gsub(/^(.{#{length}}[^\n\r]*).*$/m, '\1...').strip if description
477 477 end
478 478
479 479 def css_classes
480 480 s = 'project'
481 481 s << ' root' if root?
482 482 s << ' child' if child?
483 483 s << (leaf? ? ' leaf' : ' parent')
484 484 s
485 485 end
486 486
487 487 # The earliest start date of a project, based on it's issues and versions
488 488 def start_date
489 489 [
490 490 issues.minimum('start_date'),
491 491 shared_versions.collect(&:effective_date),
492 492 shared_versions.collect(&:start_date)
493 493 ].flatten.compact.min
494 494 end
495 495
496 496 # The latest due date of an issue or version
497 497 def due_date
498 498 [
499 499 issues.maximum('due_date'),
500 500 shared_versions.collect(&:effective_date),
501 501 shared_versions.collect {|v| v.fixed_issues.maximum('due_date')}
502 502 ].flatten.compact.max
503 503 end
504 504
505 505 def overdue?
506 506 active? && !due_date.nil? && (due_date < Date.today)
507 507 end
508 508
509 509 # Returns the percent completed for this project, based on the
510 510 # progress on it's versions.
511 511 def completed_percent(options={:include_subprojects => false})
512 512 if options.delete(:include_subprojects)
513 513 total = self_and_descendants.collect(&:completed_percent).sum
514 514
515 515 total / self_and_descendants.count
516 516 else
517 517 if versions.count > 0
518 518 total = versions.collect(&:completed_pourcent).sum
519 519
520 520 total / versions.count
521 521 else
522 522 100
523 523 end
524 524 end
525 525 end
526 526
527 527 # Return true if this project is allowed to do the specified action.
528 528 # action can be:
529 529 # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
530 530 # * a permission Symbol (eg. :edit_project)
531 531 def allows_to?(action)
532 532 if action.is_a? Hash
533 533 allowed_actions.include? "#{action[:controller]}/#{action[:action]}"
534 534 else
535 535 allowed_permissions.include? action
536 536 end
537 537 end
538 538
539 539 def module_enabled?(module_name)
540 540 module_name = module_name.to_s
541 541 enabled_modules.detect {|m| m.name == module_name}
542 542 end
543 543
544 544 def enabled_module_names=(module_names)
545 545 if module_names && module_names.is_a?(Array)
546 546 module_names = module_names.collect(&:to_s).reject(&:blank?)
547 547 self.enabled_modules = module_names.collect {|name| enabled_modules.detect {|mod| mod.name == name} || EnabledModule.new(:name => name)}
548 548 else
549 549 enabled_modules.clear
550 550 end
551 551 end
552 552
553 553 # Returns an array of the enabled modules names
554 554 def enabled_module_names
555 555 enabled_modules.collect(&:name)
556 556 end
557 557
558 558 # Enable a specific module
559 559 #
560 560 # Examples:
561 561 # project.enable_module!(:issue_tracking)
562 562 # project.enable_module!("issue_tracking")
563 563 def enable_module!(name)
564 564 enabled_modules << EnabledModule.new(:name => name.to_s) unless module_enabled?(name)
565 565 end
566 566
567 567 # Disable a module if it exists
568 568 #
569 569 # Examples:
570 570 # project.disable_module!(:issue_tracking)
571 571 # project.disable_module!("issue_tracking")
572 572 # project.disable_module!(project.enabled_modules.first)
573 573 def disable_module!(target)
574 574 target = enabled_modules.detect{|mod| target.to_s == mod.name} unless enabled_modules.include?(target)
575 575 target.destroy unless target.blank?
576 576 end
577 577
578 578 safe_attributes 'name',
579 579 'description',
580 580 'homepage',
581 581 'is_public',
582 582 'identifier',
583 583 'custom_field_values',
584 584 'custom_fields',
585 585 'tracker_ids',
586 586 'issue_custom_field_ids'
587 587
588 588 safe_attributes 'enabled_module_names',
589 589 :if => lambda {|project, user| project.new_record? || user.allowed_to?(:select_project_modules, project) }
590 590
591 591 # Returns an array of projects that are in this project's hierarchy
592 592 #
593 593 # Example: parents, children, siblings
594 594 def hierarchy
595 595 parents = project.self_and_ancestors || []
596 596 descendants = project.descendants || []
597 597 project_hierarchy = parents | descendants # Set union
598 598 end
599 599
600 600 # Returns an auto-generated project identifier based on the last identifier used
601 601 def self.next_identifier
602 602 p = Project.find(:first, :order => 'created_on DESC')
603 603 p.nil? ? nil : p.identifier.to_s.succ
604 604 end
605 605
606 606 # Copies and saves the Project instance based on the +project+.
607 607 # Duplicates the source project's:
608 608 # * Wiki
609 609 # * Versions
610 610 # * Categories
611 611 # * Issues
612 612 # * Members
613 613 # * Queries
614 614 #
615 615 # Accepts an +options+ argument to specify what to copy
616 616 #
617 617 # Examples:
618 618 # project.copy(1) # => copies everything
619 619 # project.copy(1, :only => 'members') # => copies members only
620 620 # project.copy(1, :only => ['members', 'versions']) # => copies members and versions
621 621 def copy(project, options={})
622 622 project = project.is_a?(Project) ? project : Project.find(project)
623 623
624 624 to_be_copied = %w(wiki versions issue_categories issues members queries boards)
625 625 to_be_copied = to_be_copied & options[:only].to_a unless options[:only].nil?
626 626
627 627 Project.transaction do
628 628 if save
629 629 reload
630 630 to_be_copied.each do |name|
631 631 send "copy_#{name}", project
632 632 end
633 633 Redmine::Hook.call_hook(:model_project_copy_before_save, :source_project => project, :destination_project => self)
634 634 save
635 635 end
636 636 end
637 637 end
638 638
639 639
640 640 # Copies +project+ and returns the new instance. This will not save
641 641 # the copy
642 642 def self.copy_from(project)
643 643 begin
644 644 project = project.is_a?(Project) ? project : Project.find(project)
645 645 if project
646 646 # clear unique attributes
647 647 attributes = project.attributes.dup.except('id', 'name', 'identifier', 'status', 'parent_id', 'lft', 'rgt')
648 648 copy = Project.new(attributes)
649 649 copy.enabled_modules = project.enabled_modules
650 650 copy.trackers = project.trackers
651 651 copy.custom_values = project.custom_values.collect {|v| v.clone}
652 652 copy.issue_custom_fields = project.issue_custom_fields
653 653 return copy
654 654 else
655 655 return nil
656 656 end
657 657 rescue ActiveRecord::RecordNotFound
658 658 return nil
659 659 end
660 660 end
661 661
662 662 # Yields the given block for each project with its level in the tree
663 663 def self.project_tree(projects, &block)
664 664 ancestors = []
665 665 projects.sort_by(&:lft).each do |project|
666 666 while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
667 667 ancestors.pop
668 668 end
669 669 yield project, ancestors.size
670 670 ancestors << project
671 671 end
672 672 end
673 673
674 674 private
675 675
676 676 # Copies wiki from +project+
677 677 def copy_wiki(project)
678 678 # Check that the source project has a wiki first
679 679 unless project.wiki.nil?
680 680 self.wiki ||= Wiki.new
681 681 wiki.attributes = project.wiki.attributes.dup.except("id", "project_id")
682 682 wiki_pages_map = {}
683 683 project.wiki.pages.each do |page|
684 684 # Skip pages without content
685 685 next if page.content.nil?
686 686 new_wiki_content = WikiContent.new(page.content.attributes.dup.except("id", "page_id", "updated_on"))
687 687 new_wiki_page = WikiPage.new(page.attributes.dup.except("id", "wiki_id", "created_on", "parent_id"))
688 688 new_wiki_page.content = new_wiki_content
689 689 wiki.pages << new_wiki_page
690 690 wiki_pages_map[page.id] = new_wiki_page
691 691 end
692 692 wiki.save
693 693 # Reproduce page hierarchy
694 694 project.wiki.pages.each do |page|
695 695 if page.parent_id && wiki_pages_map[page.id]
696 696 wiki_pages_map[page.id].parent = wiki_pages_map[page.parent_id]
697 697 wiki_pages_map[page.id].save
698 698 end
699 699 end
700 700 end
701 701 end
702 702
703 703 # Copies versions from +project+
704 704 def copy_versions(project)
705 705 project.versions.each do |version|
706 706 new_version = Version.new
707 707 new_version.attributes = version.attributes.dup.except("id", "project_id", "created_on", "updated_on")
708 708 self.versions << new_version
709 709 end
710 710 end
711 711
712 712 # Copies issue categories from +project+
713 713 def copy_issue_categories(project)
714 714 project.issue_categories.each do |issue_category|
715 715 new_issue_category = IssueCategory.new
716 716 new_issue_category.attributes = issue_category.attributes.dup.except("id", "project_id")
717 717 self.issue_categories << new_issue_category
718 718 end
719 719 end
720 720
721 721 # Copies issues from +project+
722 722 # Note: issues assigned to a closed version won't be copied due to validation rules
723 723 def copy_issues(project)
724 724 # Stores the source issue id as a key and the copied issues as the
725 725 # value. Used to map the two togeather for issue relations.
726 726 issues_map = {}
727 727
728 728 # Get issues sorted by root_id, lft so that parent issues
729 729 # get copied before their children
730 730 project.issues.find(:all, :order => 'root_id, lft').each do |issue|
731 731 new_issue = Issue.new
732 732 new_issue.copy_from(issue)
733 733 new_issue.project = self
734 734 # Reassign fixed_versions by name, since names are unique per
735 735 # project and the versions for self are not yet saved
736 736 if issue.fixed_version
737 737 new_issue.fixed_version = self.versions.select {|v| v.name == issue.fixed_version.name}.first
738 738 end
739 739 # Reassign the category by name, since names are unique per
740 740 # project and the categories for self are not yet saved
741 741 if issue.category
742 742 new_issue.category = self.issue_categories.select {|c| c.name == issue.category.name}.first
743 743 end
744 744 # Parent issue
745 745 if issue.parent_id
746 746 if copied_parent = issues_map[issue.parent_id]
747 747 new_issue.parent_issue_id = copied_parent.id
748 748 end
749 749 end
750 750
751 751 self.issues << new_issue
752 752 if new_issue.new_record?
753 753 logger.info "Project#copy_issues: issue ##{issue.id} could not be copied: #{new_issue.errors.full_messages}" if logger && logger.info
754 754 else
755 755 issues_map[issue.id] = new_issue unless new_issue.new_record?
756 756 end
757 757 end
758 758
759 759 # Relations after in case issues related each other
760 760 project.issues.each do |issue|
761 761 new_issue = issues_map[issue.id]
762 762 unless new_issue
763 763 # Issue was not copied
764 764 next
765 765 end
766 766
767 767 # Relations
768 768 issue.relations_from.each do |source_relation|
769 769 new_issue_relation = IssueRelation.new
770 770 new_issue_relation.attributes = source_relation.attributes.dup.except("id", "issue_from_id", "issue_to_id")
771 771 new_issue_relation.issue_to = issues_map[source_relation.issue_to_id]
772 772 if new_issue_relation.issue_to.nil? && Setting.cross_project_issue_relations?
773 773 new_issue_relation.issue_to = source_relation.issue_to
774 774 end
775 775 new_issue.relations_from << new_issue_relation
776 776 end
777 777
778 778 issue.relations_to.each do |source_relation|
779 779 new_issue_relation = IssueRelation.new
780 780 new_issue_relation.attributes = source_relation.attributes.dup.except("id", "issue_from_id", "issue_to_id")
781 781 new_issue_relation.issue_from = issues_map[source_relation.issue_from_id]
782 782 if new_issue_relation.issue_from.nil? && Setting.cross_project_issue_relations?
783 783 new_issue_relation.issue_from = source_relation.issue_from
784 784 end
785 785 new_issue.relations_to << new_issue_relation
786 786 end
787 787 end
788 788 end
789 789
790 790 # Copies members from +project+
791 791 def copy_members(project)
792 792 # Copy users first, then groups to handle members with inherited and given roles
793 793 members_to_copy = []
794 794 members_to_copy += project.memberships.select {|m| m.principal.is_a?(User)}
795 795 members_to_copy += project.memberships.select {|m| !m.principal.is_a?(User)}
796 796
797 797 members_to_copy.each do |member|
798 798 new_member = Member.new
799 799 new_member.attributes = member.attributes.dup.except("id", "project_id", "created_on")
800 800 # only copy non inherited roles
801 801 # inherited roles will be added when copying the group membership
802 802 role_ids = member.member_roles.reject(&:inherited?).collect(&:role_id)
803 803 next if role_ids.empty?
804 804 new_member.role_ids = role_ids
805 805 new_member.project = self
806 806 self.members << new_member
807 807 end
808 808 end
809 809
810 810 # Copies queries from +project+
811 811 def copy_queries(project)
812 812 project.queries.each do |query|
813 813 new_query = Query.new
814 814 new_query.attributes = query.attributes.dup.except("id", "project_id", "sort_criteria")
815 815 new_query.sort_criteria = query.sort_criteria if query.sort_criteria
816 816 new_query.project = self
817 817 new_query.user_id = query.user_id
818 818 self.queries << new_query
819 819 end
820 820 end
821 821
822 822 # Copies boards from +project+
823 823 def copy_boards(project)
824 824 project.boards.each do |board|
825 825 new_board = Board.new
826 826 new_board.attributes = board.attributes.dup.except("id", "project_id", "topics_count", "messages_count", "last_message_id")
827 827 new_board.project = self
828 828 self.boards << new_board
829 829 end
830 830 end
831 831
832 832 def allowed_permissions
833 833 @allowed_permissions ||= begin
834 834 module_names = enabled_modules.all(:select => :name).collect {|m| m.name}
835 835 Redmine::AccessControl.modules_permissions(module_names).collect {|p| p.name}
836 836 end
837 837 end
838 838
839 839 def allowed_actions
840 840 @actions_allowed ||= allowed_permissions.inject([]) { |actions, permission| actions += Redmine::AccessControl.allowed_actions(permission) }.flatten
841 841 end
842 842
843 843 # Returns all the active Systemwide and project specific activities
844 844 def active_activities
845 845 overridden_activity_ids = self.time_entry_activities.collect(&:parent_id)
846 846
847 847 if overridden_activity_ids.empty?
848 848 return TimeEntryActivity.shared.active
849 849 else
850 850 return system_activities_and_project_overrides
851 851 end
852 852 end
853 853
854 854 # Returns all the Systemwide and project specific activities
855 855 # (inactive and active)
856 856 def all_activities
857 857 overridden_activity_ids = self.time_entry_activities.collect(&:parent_id)
858 858
859 859 if overridden_activity_ids.empty?
860 860 return TimeEntryActivity.shared
861 861 else
862 862 return system_activities_and_project_overrides(true)
863 863 end
864 864 end
865 865
866 866 # Returns the systemwide active activities merged with the project specific overrides
867 867 def system_activities_and_project_overrides(include_inactive=false)
868 868 if include_inactive
869 869 return TimeEntryActivity.shared.
870 870 find(:all,
871 871 :conditions => ["id NOT IN (?)", self.time_entry_activities.collect(&:parent_id)]) +
872 872 self.time_entry_activities
873 873 else
874 874 return TimeEntryActivity.shared.active.
875 875 find(:all,
876 876 :conditions => ["id NOT IN (?)", self.time_entry_activities.collect(&:parent_id)]) +
877 877 self.time_entry_activities.active
878 878 end
879 879 end
880 880
881 881 # Archives subprojects recursively
882 882 def archive!
883 883 children.each do |subproject|
884 884 subproject.send :archive!
885 885 end
886 886 update_attribute :status, STATUS_ARCHIVED
887 887 end
888 888 end
@@ -1,819 +1,819
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2011 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 class QueryColumn
19 19 attr_accessor :name, :sortable, :groupable, :default_order
20 20 include Redmine::I18n
21 21
22 22 def initialize(name, options={})
23 23 self.name = name
24 24 self.sortable = options[:sortable]
25 25 self.groupable = options[:groupable] || false
26 26 if groupable == true
27 27 self.groupable = name.to_s
28 28 end
29 29 self.default_order = options[:default_order]
30 30 @caption_key = options[:caption] || "field_#{name}"
31 31 end
32 32
33 33 def caption
34 34 l(@caption_key)
35 35 end
36 36
37 37 # Returns true if the column is sortable, otherwise false
38 38 def sortable?
39 39 !@sortable.nil?
40 40 end
41 41
42 42 def sortable
43 43 @sortable.is_a?(Proc) ? @sortable.call : @sortable
44 44 end
45 45
46 46 def value(issue)
47 47 issue.send name
48 48 end
49 49
50 50 def css_classes
51 51 name
52 52 end
53 53 end
54 54
55 55 class QueryCustomFieldColumn < QueryColumn
56 56
57 57 def initialize(custom_field)
58 58 self.name = "cf_#{custom_field.id}".to_sym
59 59 self.sortable = custom_field.order_statement || false
60 60 if %w(list date bool int).include?(custom_field.field_format)
61 61 self.groupable = custom_field.order_statement
62 62 end
63 63 self.groupable ||= false
64 64 @cf = custom_field
65 65 end
66 66
67 67 def caption
68 68 @cf.name
69 69 end
70 70
71 71 def custom_field
72 72 @cf
73 73 end
74 74
75 75 def value(issue)
76 76 cv = issue.custom_values.detect {|v| v.custom_field_id == @cf.id}
77 77 cv && @cf.cast_value(cv.value)
78 78 end
79 79
80 80 def css_classes
81 81 @css_classes ||= "#{name} #{@cf.field_format}"
82 82 end
83 83 end
84 84
85 85 class Query < ActiveRecord::Base
86 86 class StatementInvalid < ::ActiveRecord::StatementInvalid
87 87 end
88 88
89 89 belongs_to :project
90 90 belongs_to :user
91 91 serialize :filters
92 92 serialize :column_names
93 93 serialize :sort_criteria, Array
94 94
95 95 attr_protected :project_id, :user_id
96 96
97 97 validates_presence_of :name, :on => :save
98 98 validates_length_of :name, :maximum => 255
99 99 validate :validate_query_filters
100 100
101 101 @@operators = { "=" => :label_equals,
102 102 "!" => :label_not_equals,
103 103 "o" => :label_open_issues,
104 104 "c" => :label_closed_issues,
105 105 "!*" => :label_none,
106 106 "*" => :label_all,
107 107 ">=" => :label_greater_or_equal,
108 108 "<=" => :label_less_or_equal,
109 109 "><" => :label_between,
110 110 "<t+" => :label_in_less_than,
111 111 ">t+" => :label_in_more_than,
112 112 "t+" => :label_in,
113 113 "t" => :label_today,
114 114 "w" => :label_this_week,
115 115 ">t-" => :label_less_than_ago,
116 116 "<t-" => :label_more_than_ago,
117 117 "t-" => :label_ago,
118 118 "~" => :label_contains,
119 119 "!~" => :label_not_contains }
120 120
121 121 cattr_reader :operators
122 122
123 123 @@operators_by_filter_type = { :list => [ "=", "!" ],
124 124 :list_status => [ "o", "=", "!", "c", "*" ],
125 125 :list_optional => [ "=", "!", "!*", "*" ],
126 126 :list_subprojects => [ "*", "!*", "=" ],
127 127 :date => [ "=", ">=", "<=", "><", "<t+", ">t+", "t+", "t", "w", ">t-", "<t-", "t-", "!*", "*" ],
128 128 :date_past => [ "=", ">=", "<=", "><", ">t-", "<t-", "t-", "t", "w", "!*", "*" ],
129 129 :string => [ "=", "~", "!", "!~" ],
130 130 :text => [ "~", "!~" ],
131 131 :integer => [ "=", ">=", "<=", "><", "!*", "*" ],
132 132 :float => [ "=", ">=", "<=", "><", "!*", "*" ] }
133 133
134 134 cattr_reader :operators_by_filter_type
135 135
136 136 @@available_columns = [
137 137 QueryColumn.new(:project, :sortable => "#{Project.table_name}.name", :groupable => true),
138 138 QueryColumn.new(:tracker, :sortable => "#{Tracker.table_name}.position", :groupable => true),
139 139 QueryColumn.new(:parent, :sortable => ["#{Issue.table_name}.root_id", "#{Issue.table_name}.lft ASC"], :default_order => 'desc', :caption => :field_parent_issue),
140 140 QueryColumn.new(:status, :sortable => "#{IssueStatus.table_name}.position", :groupable => true),
141 141 QueryColumn.new(:priority, :sortable => "#{IssuePriority.table_name}.position", :default_order => 'desc', :groupable => true),
142 142 QueryColumn.new(:subject, :sortable => "#{Issue.table_name}.subject"),
143 143 QueryColumn.new(:author, :sortable => lambda {User.fields_for_order_statement("authors")}, :groupable => true),
144 144 QueryColumn.new(:assigned_to, :sortable => lambda {User.fields_for_order_statement}, :groupable => true),
145 145 QueryColumn.new(:updated_on, :sortable => "#{Issue.table_name}.updated_on", :default_order => 'desc'),
146 146 QueryColumn.new(:category, :sortable => "#{IssueCategory.table_name}.name", :groupable => true),
147 147 QueryColumn.new(:fixed_version, :sortable => ["#{Version.table_name}.effective_date", "#{Version.table_name}.name"], :default_order => 'desc', :groupable => true),
148 148 QueryColumn.new(:start_date, :sortable => "#{Issue.table_name}.start_date"),
149 149 QueryColumn.new(:due_date, :sortable => "#{Issue.table_name}.due_date"),
150 150 QueryColumn.new(:estimated_hours, :sortable => "#{Issue.table_name}.estimated_hours"),
151 151 QueryColumn.new(:done_ratio, :sortable => "#{Issue.table_name}.done_ratio", :groupable => true),
152 152 QueryColumn.new(:created_on, :sortable => "#{Issue.table_name}.created_on", :default_order => 'desc'),
153 153 ]
154 154 cattr_reader :available_columns
155 155
156 156 named_scope :visible, lambda {|*args|
157 157 user = args.shift || User.current
158 158 base = Project.allowed_to_condition(user, :view_issues, *args)
159 159 user_id = user.logged? ? user.id : 0
160 160 {
161 161 :conditions => ["(#{table_name}.project_id IS NULL OR (#{base})) AND (#{table_name}.is_public = ? OR #{table_name}.user_id = ?)", true, user_id],
162 162 :include => :project
163 163 }
164 164 }
165 165
166 def initialize(attributes = nil)
166 def initialize(attributes=nil, *args)
167 167 super attributes
168 168 self.filters ||= { 'status_id' => {:operator => "o", :values => [""]} }
169 169 end
170 170
171 171 def after_initialize
172 172 # Store the fact that project is nil (used in #editable_by?)
173 173 @is_for_all = project.nil?
174 174 end
175 175
176 176 def validate_query_filters
177 177 filters.each_key do |field|
178 178 if values_for(field)
179 179 case type_for(field)
180 180 when :integer
181 181 errors.add(label_for(field), :invalid) if values_for(field).detect {|v| v.present? && !v.match(/^\d+$/) }
182 182 when :float
183 183 errors.add(label_for(field), :invalid) if values_for(field).detect {|v| v.present? && !v.match(/^\d+(\.\d*)?$/) }
184 184 when :date, :date_past
185 185 case operator_for(field)
186 186 when "=", ">=", "<=", "><"
187 187 errors.add(label_for(field), :invalid) if values_for(field).detect {|v| v.present? && (!v.match(/^\d{4}-\d{2}-\d{2}$/) || (Date.parse(v) rescue nil).nil?) }
188 188 when ">t-", "<t-", "t-"
189 189 errors.add(label_for(field), :invalid) if values_for(field).detect {|v| v.present? && !v.match(/^\d+$/) }
190 190 end
191 191 end
192 192 end
193 193
194 194 errors.add label_for(field), :blank unless
195 195 # filter requires one or more values
196 196 (values_for(field) and !values_for(field).first.blank?) or
197 197 # filter doesn't require any value
198 198 ["o", "c", "!*", "*", "t", "w"].include? operator_for(field)
199 199 end if filters
200 200 end
201 201
202 202 # Returns true if the query is visible to +user+ or the current user.
203 203 def visible?(user=User.current)
204 204 (project.nil? || user.allowed_to?(:view_issues, project)) && (self.is_public? || self.user_id == user.id)
205 205 end
206 206
207 207 def editable_by?(user)
208 208 return false unless user
209 209 # Admin can edit them all and regular users can edit their private queries
210 210 return true if user.admin? || (!is_public && self.user_id == user.id)
211 211 # Members can not edit public queries that are for all project (only admin is allowed to)
212 212 is_public && !@is_for_all && user.allowed_to?(:manage_public_queries, project)
213 213 end
214 214
215 215 def available_filters
216 216 return @available_filters if @available_filters
217 217
218 218 trackers = project.nil? ? Tracker.find(:all, :order => 'position') : project.rolled_up_trackers
219 219
220 220 @available_filters = { "status_id" => { :type => :list_status, :order => 1, :values => IssueStatus.find(:all, :order => 'position').collect{|s| [s.name, s.id.to_s] } },
221 221 "tracker_id" => { :type => :list, :order => 2, :values => trackers.collect{|s| [s.name, s.id.to_s] } },
222 222 "priority_id" => { :type => :list, :order => 3, :values => IssuePriority.all.collect{|s| [s.name, s.id.to_s] } },
223 223 "subject" => { :type => :text, :order => 8 },
224 224 "created_on" => { :type => :date_past, :order => 9 },
225 225 "updated_on" => { :type => :date_past, :order => 10 },
226 226 "start_date" => { :type => :date, :order => 11 },
227 227 "due_date" => { :type => :date, :order => 12 },
228 228 "estimated_hours" => { :type => :float, :order => 13 },
229 229 "done_ratio" => { :type => :integer, :order => 14 }}
230 230
231 231 principals = []
232 232 if project
233 233 principals += project.principals.sort
234 234 else
235 235 all_projects = Project.visible.all
236 236 if all_projects.any?
237 237 # members of visible projects
238 238 principals += Principal.active.find(:all, :conditions => ["#{User.table_name}.id IN (SELECT DISTINCT user_id FROM members WHERE project_id IN (?))", all_projects.collect(&:id)]).sort
239 239
240 240 # project filter
241 241 project_values = []
242 242 Project.project_tree(all_projects) do |p, level|
243 243 prefix = (level > 0 ? ('--' * level + ' ') : '')
244 244 project_values << ["#{prefix}#{p.name}", p.id.to_s]
245 245 end
246 246 @available_filters["project_id"] = { :type => :list, :order => 1, :values => project_values} unless project_values.empty?
247 247 end
248 248 end
249 249 users = principals.select {|p| p.is_a?(User)}
250 250
251 251 assigned_to_values = []
252 252 assigned_to_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged?
253 253 assigned_to_values += (Setting.issue_group_assignment? ? principals : users).collect{|s| [s.name, s.id.to_s] }
254 254 @available_filters["assigned_to_id"] = { :type => :list_optional, :order => 4, :values => assigned_to_values } unless assigned_to_values.empty?
255 255
256 256 author_values = []
257 257 author_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged?
258 258 author_values += users.collect{|s| [s.name, s.id.to_s] }
259 259 @available_filters["author_id"] = { :type => :list, :order => 5, :values => author_values } unless author_values.empty?
260 260
261 261 group_values = Group.all.collect {|g| [g.name, g.id.to_s] }
262 262 @available_filters["member_of_group"] = { :type => :list_optional, :order => 6, :values => group_values } unless group_values.empty?
263 263
264 264 role_values = Role.givable.collect {|r| [r.name, r.id.to_s] }
265 265 @available_filters["assigned_to_role"] = { :type => :list_optional, :order => 7, :values => role_values } unless role_values.empty?
266 266
267 267 if User.current.logged?
268 268 @available_filters["watcher_id"] = { :type => :list, :order => 15, :values => [["<< #{l(:label_me)} >>", "me"]] }
269 269 end
270 270
271 271 if project
272 272 # project specific filters
273 273 categories = project.issue_categories.all
274 274 unless categories.empty?
275 275 @available_filters["category_id"] = { :type => :list_optional, :order => 6, :values => categories.collect{|s| [s.name, s.id.to_s] } }
276 276 end
277 277 versions = project.shared_versions.all
278 278 unless versions.empty?
279 279 @available_filters["fixed_version_id"] = { :type => :list_optional, :order => 7, :values => versions.sort.collect{|s| ["#{s.project.name} - #{s.name}", s.id.to_s] } }
280 280 end
281 281 unless project.leaf?
282 282 subprojects = project.descendants.visible.all
283 283 unless subprojects.empty?
284 284 @available_filters["subproject_id"] = { :type => :list_subprojects, :order => 13, :values => subprojects.collect{|s| [s.name, s.id.to_s] } }
285 285 end
286 286 end
287 287 add_custom_fields_filters(project.all_issue_custom_fields)
288 288 else
289 289 # global filters for cross project issue list
290 290 system_shared_versions = Version.visible.find_all_by_sharing('system')
291 291 unless system_shared_versions.empty?
292 292 @available_filters["fixed_version_id"] = { :type => :list_optional, :order => 7, :values => system_shared_versions.sort.collect{|s| ["#{s.project.name} - #{s.name}", s.id.to_s] } }
293 293 end
294 294 add_custom_fields_filters(IssueCustomField.find(:all, :conditions => {:is_filter => true, :is_for_all => true}))
295 295 end
296 296 @available_filters
297 297 end
298 298
299 299 def add_filter(field, operator, values)
300 300 # values must be an array
301 301 return unless values.nil? || values.is_a?(Array)
302 302 # check if field is defined as an available filter
303 303 if available_filters.has_key? field
304 304 filter_options = available_filters[field]
305 305 # check if operator is allowed for that filter
306 306 #if @@operators_by_filter_type[filter_options[:type]].include? operator
307 307 # allowed_values = values & ([""] + (filter_options[:values] || []).collect {|val| val[1]})
308 308 # filters[field] = {:operator => operator, :values => allowed_values } if (allowed_values.first and !allowed_values.first.empty?) or ["o", "c", "!*", "*", "t"].include? operator
309 309 #end
310 310 filters[field] = {:operator => operator, :values => (values || [''])}
311 311 end
312 312 end
313 313
314 314 def add_short_filter(field, expression)
315 315 return unless expression && available_filters.has_key?(field)
316 316 field_type = available_filters[field][:type]
317 317 @@operators_by_filter_type[field_type].sort.reverse.detect do |operator|
318 318 next unless expression =~ /^#{Regexp.escape(operator)}(.*)$/
319 319 add_filter field, operator, $1.present? ? $1.split('|') : ['']
320 320 end || add_filter(field, '=', expression.split('|'))
321 321 end
322 322
323 323 # Add multiple filters using +add_filter+
324 324 def add_filters(fields, operators, values)
325 325 if fields.is_a?(Array) && operators.is_a?(Hash) && (values.nil? || values.is_a?(Hash))
326 326 fields.each do |field|
327 327 add_filter(field, operators[field], values && values[field])
328 328 end
329 329 end
330 330 end
331 331
332 332 def has_filter?(field)
333 333 filters and filters[field]
334 334 end
335 335
336 336 def type_for(field)
337 337 available_filters[field][:type] if available_filters.has_key?(field)
338 338 end
339 339
340 340 def operator_for(field)
341 341 has_filter?(field) ? filters[field][:operator] : nil
342 342 end
343 343
344 344 def values_for(field)
345 345 has_filter?(field) ? filters[field][:values] : nil
346 346 end
347 347
348 348 def value_for(field, index=0)
349 349 (values_for(field) || [])[index]
350 350 end
351 351
352 352 def label_for(field)
353 353 label = available_filters[field][:name] if available_filters.has_key?(field)
354 354 label ||= field.gsub(/\_id$/, "")
355 355 end
356 356
357 357 def available_columns
358 358 return @available_columns if @available_columns
359 359 @available_columns = ::Query.available_columns.dup
360 360 @available_columns += (project ?
361 361 project.all_issue_custom_fields :
362 362 IssueCustomField.find(:all)
363 363 ).collect {|cf| QueryCustomFieldColumn.new(cf) }
364 364
365 365 if User.current.allowed_to?(:view_time_entries, project, :global => true)
366 366 index = nil
367 367 @available_columns.each_with_index {|column, i| index = i if column.name == :estimated_hours}
368 368 index = (index ? index + 1 : -1)
369 369 # insert the column after estimated_hours or at the end
370 370 @available_columns.insert index, QueryColumn.new(:spent_hours,
371 371 :sortable => "(SELECT COALESCE(SUM(hours), 0) FROM #{TimeEntry.table_name} WHERE #{TimeEntry.table_name}.issue_id = #{Issue.table_name}.id)",
372 372 :default_order => 'desc',
373 373 :caption => :label_spent_time
374 374 )
375 375 end
376 376 @available_columns
377 377 end
378 378
379 379 def self.available_columns=(v)
380 380 self.available_columns = (v)
381 381 end
382 382
383 383 def self.add_available_column(column)
384 384 self.available_columns << (column) if column.is_a?(QueryColumn)
385 385 end
386 386
387 387 # Returns an array of columns that can be used to group the results
388 388 def groupable_columns
389 389 available_columns.select {|c| c.groupable}
390 390 end
391 391
392 392 # Returns a Hash of columns and the key for sorting
393 393 def sortable_columns
394 394 {'id' => "#{Issue.table_name}.id"}.merge(available_columns.inject({}) {|h, column|
395 395 h[column.name.to_s] = column.sortable
396 396 h
397 397 })
398 398 end
399 399
400 400 def columns
401 401 # preserve the column_names order
402 402 (has_default_columns? ? default_columns_names : column_names).collect do |name|
403 403 available_columns.find { |col| col.name == name }
404 404 end.compact
405 405 end
406 406
407 407 def default_columns_names
408 408 @default_columns_names ||= begin
409 409 default_columns = Setting.issue_list_default_columns.map(&:to_sym)
410 410
411 411 project.present? ? default_columns : [:project] | default_columns
412 412 end
413 413 end
414 414
415 415 def column_names=(names)
416 416 if names
417 417 names = names.select {|n| n.is_a?(Symbol) || !n.blank? }
418 418 names = names.collect {|n| n.is_a?(Symbol) ? n : n.to_sym }
419 419 # Set column_names to nil if default columns
420 420 if names == default_columns_names
421 421 names = nil
422 422 end
423 423 end
424 424 write_attribute(:column_names, names)
425 425 end
426 426
427 427 def has_column?(column)
428 428 column_names && column_names.include?(column.is_a?(QueryColumn) ? column.name : column)
429 429 end
430 430
431 431 def has_default_columns?
432 432 column_names.nil? || column_names.empty?
433 433 end
434 434
435 435 def sort_criteria=(arg)
436 436 c = []
437 437 if arg.is_a?(Hash)
438 438 arg = arg.keys.sort.collect {|k| arg[k]}
439 439 end
440 440 c = arg.select {|k,o| !k.to_s.blank?}.slice(0,3).collect {|k,o| [k.to_s, o == 'desc' ? o : 'asc']}
441 441 write_attribute(:sort_criteria, c)
442 442 end
443 443
444 444 def sort_criteria
445 445 read_attribute(:sort_criteria) || []
446 446 end
447 447
448 448 def sort_criteria_key(arg)
449 449 sort_criteria && sort_criteria[arg] && sort_criteria[arg].first
450 450 end
451 451
452 452 def sort_criteria_order(arg)
453 453 sort_criteria && sort_criteria[arg] && sort_criteria[arg].last
454 454 end
455 455
456 456 # Returns the SQL sort order that should be prepended for grouping
457 457 def group_by_sort_order
458 458 if grouped? && (column = group_by_column)
459 459 column.sortable.is_a?(Array) ?
460 460 column.sortable.collect {|s| "#{s} #{column.default_order}"}.join(',') :
461 461 "#{column.sortable} #{column.default_order}"
462 462 end
463 463 end
464 464
465 465 # Returns true if the query is a grouped query
466 466 def grouped?
467 467 !group_by_column.nil?
468 468 end
469 469
470 470 def group_by_column
471 471 groupable_columns.detect {|c| c.groupable && c.name.to_s == group_by}
472 472 end
473 473
474 474 def group_by_statement
475 475 group_by_column.try(:groupable)
476 476 end
477 477
478 478 def project_statement
479 479 project_clauses = []
480 480 if project && !project.descendants.active.empty?
481 481 ids = [project.id]
482 482 if has_filter?("subproject_id")
483 483 case operator_for("subproject_id")
484 484 when '='
485 485 # include the selected subprojects
486 486 ids += values_for("subproject_id").each(&:to_i)
487 487 when '!*'
488 488 # main project only
489 489 else
490 490 # all subprojects
491 491 ids += project.descendants.collect(&:id)
492 492 end
493 493 elsif Setting.display_subprojects_issues?
494 494 ids += project.descendants.collect(&:id)
495 495 end
496 496 project_clauses << "#{Project.table_name}.id IN (%s)" % ids.join(',')
497 497 elsif project
498 498 project_clauses << "#{Project.table_name}.id = %d" % project.id
499 499 end
500 500 project_clauses.any? ? project_clauses.join(' AND ') : nil
501 501 end
502 502
503 503 def statement
504 504 # filters clauses
505 505 filters_clauses = []
506 506 filters.each_key do |field|
507 507 next if field == "subproject_id"
508 508 v = values_for(field).clone
509 509 next unless v and !v.empty?
510 510 operator = operator_for(field)
511 511
512 512 # "me" value subsitution
513 513 if %w(assigned_to_id author_id watcher_id).include?(field)
514 514 if v.delete("me")
515 515 if User.current.logged?
516 516 v.push(User.current.id.to_s)
517 517 v += User.current.group_ids.map(&:to_s) if field == 'assigned_to_id'
518 518 else
519 519 v.push("0")
520 520 end
521 521 end
522 522 end
523 523
524 524 if field =~ /^cf_(\d+)$/
525 525 # custom field
526 526 filters_clauses << sql_for_custom_field(field, operator, v, $1)
527 527 elsif respond_to?("sql_for_#{field}_field")
528 528 # specific statement
529 529 filters_clauses << send("sql_for_#{field}_field", field, operator, v)
530 530 else
531 531 # regular field
532 532 filters_clauses << '(' + sql_for_field(field, operator, v, Issue.table_name, field) + ')'
533 533 end
534 534 end if filters and valid?
535 535
536 536 filters_clauses << project_statement
537 537 filters_clauses.reject!(&:blank?)
538 538
539 539 filters_clauses.any? ? filters_clauses.join(' AND ') : nil
540 540 end
541 541
542 542 # Returns the issue count
543 543 def issue_count
544 544 Issue.visible.count(:include => [:status, :project], :conditions => statement)
545 545 rescue ::ActiveRecord::StatementInvalid => e
546 546 raise StatementInvalid.new(e.message)
547 547 end
548 548
549 549 # Returns the issue count by group or nil if query is not grouped
550 550 def issue_count_by_group
551 551 r = nil
552 552 if grouped?
553 553 begin
554 554 # Rails will raise an (unexpected) RecordNotFound if there's only a nil group value
555 555 r = Issue.visible.count(:group => group_by_statement, :include => [:status, :project], :conditions => statement)
556 556 rescue ActiveRecord::RecordNotFound
557 557 r = {nil => issue_count}
558 558 end
559 559 c = group_by_column
560 560 if c.is_a?(QueryCustomFieldColumn)
561 561 r = r.keys.inject({}) {|h, k| h[c.custom_field.cast_value(k)] = r[k]; h}
562 562 end
563 563 end
564 564 r
565 565 rescue ::ActiveRecord::StatementInvalid => e
566 566 raise StatementInvalid.new(e.message)
567 567 end
568 568
569 569 # Returns the issues
570 570 # Valid options are :order, :offset, :limit, :include, :conditions
571 571 def issues(options={})
572 572 order_option = [group_by_sort_order, options[:order]].reject {|s| s.blank?}.join(',')
573 573 order_option = nil if order_option.blank?
574 574
575 575 joins = (order_option && order_option.include?('authors')) ? "LEFT OUTER JOIN users authors ON authors.id = #{Issue.table_name}.author_id" : nil
576 576
577 577 issues = Issue.visible.scoped(:conditions => options[:conditions]).find :all, :include => ([:status, :project] + (options[:include] || [])).uniq,
578 578 :conditions => statement,
579 579 :order => order_option,
580 580 :joins => joins,
581 581 :limit => options[:limit],
582 582 :offset => options[:offset]
583 583
584 584 if has_column?(:spent_hours)
585 585 Issue.load_visible_spent_hours(issues)
586 586 end
587 587 issues
588 588 rescue ::ActiveRecord::StatementInvalid => e
589 589 raise StatementInvalid.new(e.message)
590 590 end
591 591
592 592 # Returns the journals
593 593 # Valid options are :order, :offset, :limit
594 594 def journals(options={})
595 595 Journal.visible.find :all, :include => [:details, :user, {:issue => [:project, :author, :tracker, :status]}],
596 596 :conditions => statement,
597 597 :order => options[:order],
598 598 :limit => options[:limit],
599 599 :offset => options[:offset]
600 600 rescue ::ActiveRecord::StatementInvalid => e
601 601 raise StatementInvalid.new(e.message)
602 602 end
603 603
604 604 # Returns the versions
605 605 # Valid options are :conditions
606 606 def versions(options={})
607 607 Version.visible.scoped(:conditions => options[:conditions]).find :all, :include => :project, :conditions => project_statement
608 608 rescue ::ActiveRecord::StatementInvalid => e
609 609 raise StatementInvalid.new(e.message)
610 610 end
611 611
612 612 def sql_for_watcher_id_field(field, operator, value)
613 613 db_table = Watcher.table_name
614 614 "#{Issue.table_name}.id #{ operator == '=' ? 'IN' : 'NOT IN' } (SELECT #{db_table}.watchable_id FROM #{db_table} WHERE #{db_table}.watchable_type='Issue' AND " +
615 615 sql_for_field(field, '=', value, db_table, 'user_id') + ')'
616 616 end
617 617
618 618 def sql_for_member_of_group_field(field, operator, value)
619 619 if operator == '*' # Any group
620 620 groups = Group.all
621 621 operator = '=' # Override the operator since we want to find by assigned_to
622 622 elsif operator == "!*"
623 623 groups = Group.all
624 624 operator = '!' # Override the operator since we want to find by assigned_to
625 625 else
626 626 groups = Group.find_all_by_id(value)
627 627 end
628 628 groups ||= []
629 629
630 630 members_of_groups = groups.inject([]) {|user_ids, group|
631 631 if group && group.user_ids.present?
632 632 user_ids << group.user_ids
633 633 end
634 634 user_ids.flatten.uniq.compact
635 635 }.sort.collect(&:to_s)
636 636
637 637 '(' + sql_for_field("assigned_to_id", operator, members_of_groups, Issue.table_name, "assigned_to_id", false) + ')'
638 638 end
639 639
640 640 def sql_for_assigned_to_role_field(field, operator, value)
641 641 case operator
642 642 when "*", "!*" # Member / Not member
643 643 sw = operator == "!*" ? 'NOT' : ''
644 644 nl = operator == "!*" ? "#{Issue.table_name}.assigned_to_id IS NULL OR" : ''
645 645 "(#{nl} #{Issue.table_name}.assigned_to_id #{sw} IN (SELECT DISTINCT #{Member.table_name}.user_id FROM #{Member.table_name}" +
646 646 " WHERE #{Member.table_name}.project_id = #{Issue.table_name}.project_id))"
647 647 when "=", "!"
648 648 role_cond = value.any? ?
649 649 "#{MemberRole.table_name}.role_id IN (" + value.collect{|val| "'#{connection.quote_string(val)}'"}.join(",") + ")" :
650 650 "1=0"
651 651
652 652 sw = operator == "!" ? 'NOT' : ''
653 653 nl = operator == "!" ? "#{Issue.table_name}.assigned_to_id IS NULL OR" : ''
654 654 "(#{nl} #{Issue.table_name}.assigned_to_id #{sw} IN (SELECT DISTINCT #{Member.table_name}.user_id FROM #{Member.table_name}, #{MemberRole.table_name}" +
655 655 " WHERE #{Member.table_name}.project_id = #{Issue.table_name}.project_id AND #{Member.table_name}.id = #{MemberRole.table_name}.member_id AND #{role_cond}))"
656 656 end
657 657 end
658 658
659 659 private
660 660
661 661 def sql_for_custom_field(field, operator, value, custom_field_id)
662 662 db_table = CustomValue.table_name
663 663 db_field = 'value'
664 664 "#{Issue.table_name}.id IN (SELECT #{Issue.table_name}.id FROM #{Issue.table_name} LEFT OUTER JOIN #{db_table} ON #{db_table}.customized_type='Issue' AND #{db_table}.customized_id=#{Issue.table_name}.id AND #{db_table}.custom_field_id=#{custom_field_id} WHERE " +
665 665 sql_for_field(field, operator, value, db_table, db_field, true) + ')'
666 666 end
667 667
668 668 # Helper method to generate the WHERE sql for a +field+, +operator+ and a +value+
669 669 def sql_for_field(field, operator, value, db_table, db_field, is_custom_filter=false)
670 670 sql = ''
671 671 case operator
672 672 when "="
673 673 if value.any?
674 674 case type_for(field)
675 675 when :date, :date_past
676 676 sql = date_clause(db_table, db_field, (Date.parse(value.first) rescue nil), (Date.parse(value.first) rescue nil))
677 677 when :integer
678 678 if is_custom_filter
679 679 sql = "(#{db_table}.#{db_field} <> '' AND CAST(#{db_table}.#{db_field} AS decimal(60,3)) = #{value.first.to_i})"
680 680 else
681 681 sql = "#{db_table}.#{db_field} = #{value.first.to_i}"
682 682 end
683 683 when :float
684 684 if is_custom_filter
685 685 sql = "(#{db_table}.#{db_field} <> '' AND CAST(#{db_table}.#{db_field} AS decimal(60,3)) BETWEEN #{value.first.to_f - 1e-5} AND #{value.first.to_f + 1e-5})"
686 686 else
687 687 sql = "#{db_table}.#{db_field} BETWEEN #{value.first.to_f - 1e-5} AND #{value.first.to_f + 1e-5}"
688 688 end
689 689 else
690 690 sql = "#{db_table}.#{db_field} IN (" + value.collect{|val| "'#{connection.quote_string(val)}'"}.join(",") + ")"
691 691 end
692 692 else
693 693 # IN an empty set
694 694 sql = "1=0"
695 695 end
696 696 when "!"
697 697 if value.any?
698 698 sql = "(#{db_table}.#{db_field} IS NULL OR #{db_table}.#{db_field} NOT IN (" + value.collect{|val| "'#{connection.quote_string(val)}'"}.join(",") + "))"
699 699 else
700 700 # NOT IN an empty set
701 701 sql = "1=1"
702 702 end
703 703 when "!*"
704 704 sql = "#{db_table}.#{db_field} IS NULL"
705 705 sql << " OR #{db_table}.#{db_field} = ''" if is_custom_filter
706 706 when "*"
707 707 sql = "#{db_table}.#{db_field} IS NOT NULL"
708 708 sql << " AND #{db_table}.#{db_field} <> ''" if is_custom_filter
709 709 when ">="
710 710 if [:date, :date_past].include?(type_for(field))
711 711 sql = date_clause(db_table, db_field, (Date.parse(value.first) rescue nil), nil)
712 712 else
713 713 if is_custom_filter
714 714 sql = "(#{db_table}.#{db_field} <> '' AND CAST(#{db_table}.#{db_field} AS decimal(60,3)) >= #{value.first.to_f})"
715 715 else
716 716 sql = "#{db_table}.#{db_field} >= #{value.first.to_f}"
717 717 end
718 718 end
719 719 when "<="
720 720 if [:date, :date_past].include?(type_for(field))
721 721 sql = date_clause(db_table, db_field, nil, (Date.parse(value.first) rescue nil))
722 722 else
723 723 if is_custom_filter
724 724 sql = "(#{db_table}.#{db_field} <> '' AND CAST(#{db_table}.#{db_field} AS decimal(60,3)) <= #{value.first.to_f})"
725 725 else
726 726 sql = "#{db_table}.#{db_field} <= #{value.first.to_f}"
727 727 end
728 728 end
729 729 when "><"
730 730 if [:date, :date_past].include?(type_for(field))
731 731 sql = date_clause(db_table, db_field, (Date.parse(value[0]) rescue nil), (Date.parse(value[1]) rescue nil))
732 732 else
733 733 if is_custom_filter
734 734 sql = "(#{db_table}.#{db_field} <> '' AND CAST(#{db_table}.#{db_field} AS decimal(60,3)) BETWEEN #{value[0].to_f} AND #{value[1].to_f})"
735 735 else
736 736 sql = "#{db_table}.#{db_field} BETWEEN #{value[0].to_f} AND #{value[1].to_f}"
737 737 end
738 738 end
739 739 when "o"
740 740 sql = "#{IssueStatus.table_name}.is_closed=#{connection.quoted_false}" if field == "status_id"
741 741 when "c"
742 742 sql = "#{IssueStatus.table_name}.is_closed=#{connection.quoted_true}" if field == "status_id"
743 743 when ">t-"
744 744 sql = relative_date_clause(db_table, db_field, - value.first.to_i, 0)
745 745 when "<t-"
746 746 sql = relative_date_clause(db_table, db_field, nil, - value.first.to_i)
747 747 when "t-"
748 748 sql = relative_date_clause(db_table, db_field, - value.first.to_i, - value.first.to_i)
749 749 when ">t+"
750 750 sql = relative_date_clause(db_table, db_field, value.first.to_i, nil)
751 751 when "<t+"
752 752 sql = relative_date_clause(db_table, db_field, 0, value.first.to_i)
753 753 when "t+"
754 754 sql = relative_date_clause(db_table, db_field, value.first.to_i, value.first.to_i)
755 755 when "t"
756 756 sql = relative_date_clause(db_table, db_field, 0, 0)
757 757 when "w"
758 758 first_day_of_week = l(:general_first_day_of_week).to_i
759 759 day_of_week = Date.today.cwday
760 760 days_ago = (day_of_week >= first_day_of_week ? day_of_week - first_day_of_week : day_of_week + 7 - first_day_of_week)
761 761 sql = relative_date_clause(db_table, db_field, - days_ago, - days_ago + 6)
762 762 when "~"
763 763 sql = "LOWER(#{db_table}.#{db_field}) LIKE '%#{connection.quote_string(value.first.to_s.downcase)}%'"
764 764 when "!~"
765 765 sql = "LOWER(#{db_table}.#{db_field}) NOT LIKE '%#{connection.quote_string(value.first.to_s.downcase)}%'"
766 766 else
767 767 raise "Unknown query operator #{operator}"
768 768 end
769 769
770 770 return sql
771 771 end
772 772
773 773 def add_custom_fields_filters(custom_fields)
774 774 @available_filters ||= {}
775 775
776 776 custom_fields.select(&:is_filter?).each do |field|
777 777 case field.field_format
778 778 when "text"
779 779 options = { :type => :text, :order => 20 }
780 780 when "list"
781 781 options = { :type => :list_optional, :values => field.possible_values, :order => 20}
782 782 when "date"
783 783 options = { :type => :date, :order => 20 }
784 784 when "bool"
785 785 options = { :type => :list, :values => [[l(:general_text_yes), "1"], [l(:general_text_no), "0"]], :order => 20 }
786 786 when "int"
787 787 options = { :type => :integer, :order => 20 }
788 788 when "float"
789 789 options = { :type => :float, :order => 20 }
790 790 when "user", "version"
791 791 next unless project
792 792 options = { :type => :list_optional, :values => field.possible_values_options(project), :order => 20}
793 793 else
794 794 options = { :type => :string, :order => 20 }
795 795 end
796 796 @available_filters["cf_#{field.id}"] = options.merge({ :name => field.name })
797 797 end
798 798 end
799 799
800 800 # Returns a SQL clause for a date or datetime field.
801 801 def date_clause(table, field, from, to)
802 802 s = []
803 803 if from
804 804 from_yesterday = from - 1
805 805 from_yesterday_utc = Time.gm(from_yesterday.year, from_yesterday.month, from_yesterday.day)
806 806 s << ("#{table}.#{field} > '%s'" % [connection.quoted_date(from_yesterday_utc.end_of_day)])
807 807 end
808 808 if to
809 809 to_utc = Time.gm(to.year, to.month, to.day)
810 810 s << ("#{table}.#{field} <= '%s'" % [connection.quoted_date(to_utc.end_of_day)])
811 811 end
812 812 s.join(' AND ')
813 813 end
814 814
815 815 # Returns a SQL clause for a date or datetime field using relative dates.
816 816 def relative_date_clause(table, field, days_from, days_to)
817 817 date_clause(table, field, (days_from ? Date.today + days_from : nil), (days_to ? Date.today + days_to : nil))
818 818 end
819 819 end
@@ -1,59 +1,59
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2011 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 class UserPreference < ActiveRecord::Base
19 19 belongs_to :user
20 20 serialize :others
21 21
22 22 attr_protected :others
23 23
24 24 before_save :set_others_hash
25 25
26 def initialize(attributes = nil)
26 def initialize(attributes=nil, *args)
27 27 super
28 28 self.others ||= {}
29 29 end
30 30
31 31 def set_others_hash
32 32 self.others ||= {}
33 33 end
34 34
35 35 def [](attr_name)
36 36 if attribute_present? attr_name
37 37 super
38 38 else
39 39 others ? others[attr_name] : nil
40 40 end
41 41 end
42 42
43 43 def []=(attr_name, value)
44 44 if attribute_present? attr_name
45 45 super
46 46 else
47 47 h = read_attribute(:others).dup || {}
48 48 h.update(attr_name => value)
49 49 write_attribute(:others, h)
50 50 value
51 51 end
52 52 end
53 53
54 54 def comments_sorting; self[:comments_sorting] end
55 55 def comments_sorting=(order); self[:comments_sorting]=order end
56 56
57 57 def warn_on_leaving_unsaved; self[:warn_on_leaving_unsaved] || '1'; end
58 58 def warn_on_leaving_unsaved=(value); self[:warn_on_leaving_unsaved]=value; end
59 59 end
General Comments 0
You need to be logged in to leave comments. Login now