##// END OF EJS Templates
Use #reduce instead of #inject for getting the intersection of arrays....
Jean-Philippe Lang -
r8707:8c38510ee504
parent child
Show More
@@ -1,66 +1,66
1 1 class ContextMenusController < ApplicationController
2 2 helper :watchers
3 3 helper :issues
4 4
5 5 def issues
6 6 @issues = Issue.visible.all(:conditions => {:id => params[:ids]}, :include => :project)
7 7 if (@issues.size == 1)
8 8 @issue = @issues.first
9 9 end
10 10
11 @allowed_statuses = @issues.map(&:new_statuses_allowed_to).inject{|memo,a| memo & a}
11 @allowed_statuses = @issues.map(&:new_statuses_allowed_to).reduce(:&)
12 12 @projects = @issues.collect(&:project).compact.uniq
13 13 @project = @projects.first if @projects.size == 1
14 14
15 15 @can = {:edit => User.current.allowed_to?(:edit_issues, @projects),
16 16 :log_time => (@project && User.current.allowed_to?(:log_time, @project)),
17 17 :update => (User.current.allowed_to?(:edit_issues, @projects) || (User.current.allowed_to?(:change_status, @projects) && !@allowed_statuses.blank?)),
18 18 :move => (@project && User.current.allowed_to?(:move_issues, @project)),
19 19 :copy => (@issue && @project.trackers.include?(@issue.tracker) && User.current.allowed_to?(:add_issues, @project)),
20 20 :delete => User.current.allowed_to?(:delete_issues, @projects)
21 21 }
22 22 if @project
23 23 if @issue
24 24 @assignables = @issue.assignable_users
25 25 else
26 26 @assignables = @project.assignable_users
27 27 end
28 28 @trackers = @project.trackers
29 29 else
30 30 #when multiple projects, we only keep the intersection of each set
31 @assignables = @projects.map(&:assignable_users).inject{|memo,a| memo & a}
32 @trackers = @projects.map(&:trackers).inject{|memo,t| memo & t}
31 @assignables = @projects.map(&:assignable_users).reduce(:&)
32 @trackers = @projects.map(&:trackers).reduce(:&)
33 33 end
34 34
35 35 @priorities = IssuePriority.active.reverse
36 36 @back = back_url
37 37
38 38 @options_by_custom_field = {}
39 39 if @can[:edit]
40 custom_fields = @issues.map(&:available_custom_fields).inject {|memo, f| memo & f}.select do |f|
40 custom_fields = @issues.map(&:available_custom_fields).reduce(:&).select do |f|
41 41 %w(bool list user version).include?(f.field_format) && !f.multiple?
42 42 end
43 43 custom_fields.each do |field|
44 44 values = field.possible_values_options(@projects)
45 45 if values.any?
46 46 @options_by_custom_field[field] = values
47 47 end
48 48 end
49 49 end
50 50
51 51 render :layout => false
52 52 end
53 53
54 54 def time_entries
55 55 @time_entries = TimeEntry.all(
56 56 :conditions => {:id => params[:ids]}, :include => :project)
57 57 @projects = @time_entries.collect(&:project).compact.uniq
58 58 @project = @projects.first if @projects.size == 1
59 59 @activities = TimeEntryActivity.shared.active
60 60 @can = {:edit => User.current.allowed_to?(:edit_time_entries, @projects),
61 61 :delete => User.current.allowed_to?(:edit_time_entries, @projects)
62 62 }
63 63 @back = back_url
64 64 render :layout => false
65 65 end
66 66 end
@@ -1,428 +1,428
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 IssuesController < ApplicationController
19 19 menu_item :new_issue, :only => [:new, :create]
20 20 default_search_scope :issues
21 21
22 22 before_filter :find_issue, :only => [:show, :edit, :update]
23 23 before_filter :find_issues, :only => [:bulk_edit, :bulk_update, :move, :perform_move, :destroy]
24 24 before_filter :check_project_uniqueness, :only => [:move, :perform_move]
25 25 before_filter :find_project, :only => [:new, :create]
26 26 before_filter :authorize, :except => [:index]
27 27 before_filter :find_optional_project, :only => [:index]
28 28 before_filter :check_for_default_issue_status, :only => [:new, :create]
29 29 before_filter :build_new_issue_from_params, :only => [:new, :create]
30 30 accept_rss_auth :index, :show
31 31 accept_api_auth :index, :show, :create, :update, :destroy
32 32
33 33 rescue_from Query::StatementInvalid, :with => :query_statement_invalid
34 34
35 35 helper :journals
36 36 helper :projects
37 37 include ProjectsHelper
38 38 helper :custom_fields
39 39 include CustomFieldsHelper
40 40 helper :issue_relations
41 41 include IssueRelationsHelper
42 42 helper :watchers
43 43 include WatchersHelper
44 44 helper :attachments
45 45 include AttachmentsHelper
46 46 helper :queries
47 47 include QueriesHelper
48 48 helper :repositories
49 49 include RepositoriesHelper
50 50 helper :sort
51 51 include SortHelper
52 52 include IssuesHelper
53 53 helper :timelog
54 54 helper :gantt
55 55 include Redmine::Export::PDF
56 56
57 57 verify :method => :post, :only => :create, :render => {:nothing => true, :status => :method_not_allowed }
58 58 verify :method => :post, :only => :bulk_update, :render => {:nothing => true, :status => :method_not_allowed }
59 59 verify :method => :put, :only => :update, :render => {:nothing => true, :status => :method_not_allowed }
60 60
61 61 def index
62 62 retrieve_query
63 63 sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
64 64 sort_update(@query.sortable_columns)
65 65
66 66 if @query.valid?
67 67 case params[:format]
68 68 when 'csv', 'pdf'
69 69 @limit = Setting.issues_export_limit.to_i
70 70 when 'atom'
71 71 @limit = Setting.feeds_limit.to_i
72 72 when 'xml', 'json'
73 73 @offset, @limit = api_offset_and_limit
74 74 else
75 75 @limit = per_page_option
76 76 end
77 77
78 78 @issue_count = @query.issue_count
79 79 @issue_pages = Paginator.new self, @issue_count, @limit, params['page']
80 80 @offset ||= @issue_pages.current.offset
81 81 @issues = @query.issues(:include => [:assigned_to, :tracker, :priority, :category, :fixed_version],
82 82 :order => sort_clause,
83 83 :offset => @offset,
84 84 :limit => @limit)
85 85 @issue_count_by_group = @query.issue_count_by_group
86 86
87 87 respond_to do |format|
88 88 format.html { render :template => 'issues/index', :layout => !request.xhr? }
89 89 format.api {
90 90 Issue.load_relations(@issues) if include_in_api_response?('relations')
91 91 }
92 92 format.atom { render_feed(@issues, :title => "#{@project || Setting.app_title}: #{l(:label_issue_plural)}") }
93 93 format.csv { send_data(issues_to_csv(@issues, @project, @query, params), :type => 'text/csv; header=present', :filename => 'export.csv') }
94 94 format.pdf { send_data(issues_to_pdf(@issues, @project, @query), :type => 'application/pdf', :filename => 'export.pdf') }
95 95 end
96 96 else
97 97 respond_to do |format|
98 98 format.html { render(:template => 'issues/index', :layout => !request.xhr?) }
99 99 format.any(:atom, :csv, :pdf) { render(:nothing => true) }
100 100 format.api { render_validation_errors(@query) }
101 101 end
102 102 end
103 103 rescue ActiveRecord::RecordNotFound
104 104 render_404
105 105 end
106 106
107 107 def show
108 108 @journals = @issue.journals.find(:all, :include => [:user, :details], :order => "#{Journal.table_name}.created_on ASC")
109 109 @journals.each_with_index {|j,i| j.indice = i+1}
110 110 @journals.reverse! if User.current.wants_comments_in_reverse_order?
111 111
112 112 @changesets = @issue.changesets.visible.all
113 113 @changesets.reverse! if User.current.wants_comments_in_reverse_order?
114 114
115 115 @relations = @issue.relations.select {|r| r.other_issue(@issue) && r.other_issue(@issue).visible? }
116 116 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
117 117 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
118 118 @priorities = IssuePriority.active
119 119 @time_entry = TimeEntry.new(:issue => @issue, :project => @issue.project)
120 120 respond_to do |format|
121 121 format.html {
122 122 retrieve_previous_and_next_issue_ids
123 123 render :template => 'issues/show'
124 124 }
125 125 format.api
126 126 format.atom { render :template => 'journals/index', :layout => false, :content_type => 'application/atom+xml' }
127 127 format.pdf { send_data(issue_to_pdf(@issue), :type => 'application/pdf', :filename => "#{@project.identifier}-#{@issue.id}.pdf") }
128 128 end
129 129 end
130 130
131 131 # Add a new issue
132 132 # The new issue will be created from an existing one if copy_from parameter is given
133 133 def new
134 134 respond_to do |format|
135 135 format.html { render :action => 'new', :layout => !request.xhr? }
136 136 format.js {
137 137 render(:update) { |page|
138 138 if params[:project_change]
139 139 page.replace_html 'all_attributes', :partial => 'form'
140 140 else
141 141 page.replace_html 'attributes', :partial => 'attributes'
142 142 end
143 143 m = User.current.allowed_to?(:log_time, @issue.project) ? 'show' : 'hide'
144 144 page << "if ($('log_time')) {Element.#{m}('log_time');}"
145 145 }
146 146 }
147 147 end
148 148 end
149 149
150 150 def create
151 151 call_hook(:controller_issues_new_before_save, { :params => params, :issue => @issue })
152 152 if @issue.save
153 153 attachments = Attachment.attach_files(@issue, params[:attachments])
154 154 call_hook(:controller_issues_new_after_save, { :params => params, :issue => @issue})
155 155 respond_to do |format|
156 156 format.html {
157 157 render_attachment_warning_if_needed(@issue)
158 158 flash[:notice] = l(:notice_issue_successful_create, :id => "<a href='#{issue_path(@issue)}'>##{@issue.id}</a>")
159 159 redirect_to(params[:continue] ? { :action => 'new', :project_id => @issue.project, :issue => {:tracker_id => @issue.tracker, :parent_issue_id => @issue.parent_issue_id}.reject {|k,v| v.nil?} } :
160 160 { :action => 'show', :id => @issue })
161 161 }
162 162 format.api { render :action => 'show', :status => :created, :location => issue_url(@issue) }
163 163 end
164 164 return
165 165 else
166 166 respond_to do |format|
167 167 format.html { render :action => 'new' }
168 168 format.api { render_validation_errors(@issue) }
169 169 end
170 170 end
171 171 end
172 172
173 173 def edit
174 174 return unless update_issue_from_params
175 175
176 176 respond_to do |format|
177 177 format.html { }
178 178 format.xml { }
179 179 end
180 180 end
181 181
182 182 def update
183 183 return unless update_issue_from_params
184 184 saved = false
185 185 begin
186 186 saved = @issue.save_issue_with_child_records(params, @time_entry)
187 187 rescue ActiveRecord::StaleObjectError
188 188 @conflict = true
189 189 if params[:last_journal_id]
190 190 if params[:last_journal_id].present?
191 191 last_journal_id = params[:last_journal_id].to_i
192 192 @conflict_journals = @issue.journals.all(:conditions => ["#{Journal.table_name}.id > ?", last_journal_id])
193 193 else
194 194 @conflict_journals = @issue.journals.all
195 195 end
196 196 end
197 197 end
198 198
199 199 if saved
200 200 render_attachment_warning_if_needed(@issue)
201 201 flash[:notice] = l(:notice_successful_update) unless @issue.current_journal.new_record?
202 202
203 203 respond_to do |format|
204 204 format.html { redirect_back_or_default({:action => 'show', :id => @issue}) }
205 205 format.api { head :ok }
206 206 end
207 207 else
208 208 respond_to do |format|
209 209 format.html { render :action => 'edit' }
210 210 format.api { render_validation_errors(@issue) }
211 211 end
212 212 end
213 213 end
214 214
215 215 # Bulk edit/copy a set of issues
216 216 def bulk_edit
217 217 @issues.sort!
218 218 @copy = params[:copy].present?
219 219 @notes = params[:notes]
220 220
221 221 if User.current.allowed_to?(:move_issues, @projects)
222 222 @allowed_projects = Issue.allowed_target_projects_on_move
223 223 if params[:issue]
224 224 @target_project = @allowed_projects.detect {|p| p.id.to_s == params[:issue][:project_id]}
225 225 if @target_project
226 226 target_projects = [@target_project]
227 227 end
228 228 end
229 229 end
230 230 target_projects ||= @projects
231 231
232 @available_statuses = target_projects.map{|p|Workflow.available_statuses(p)}.inject{|memo,w|memo & w}
233 @custom_fields = target_projects.map{|p|p.all_issue_custom_fields}.inject{|memo,c|memo & c}
234 @assignables = target_projects.map(&:assignable_users).inject{|memo,a| memo & a}
235 @trackers = target_projects.map(&:trackers).inject{|memo,t| memo & t}
232 @available_statuses = target_projects.map{|p|Workflow.available_statuses(p)}.reduce(:&)
233 @custom_fields = target_projects.map{|p|p.all_issue_custom_fields}.reduce(:&)
234 @assignables = target_projects.map(&:assignable_users).reduce(:&)
235 @trackers = target_projects.map(&:trackers).reduce(:&)
236 236
237 @safe_attributes = @issues.map(&:safe_attribute_names).inject {|memo,attrs| memo & attrs}
237 @safe_attributes = @issues.map(&:safe_attribute_names).reduce(:&)
238 238 render :layout => false if request.xhr?
239 239 end
240 240
241 241 def bulk_update
242 242 @issues.sort!
243 243 @copy = params[:copy].present?
244 244 attributes = parse_params_for_bulk_issue_attributes(params)
245 245
246 246 unsaved_issue_ids = []
247 247 moved_issues = []
248 248 @issues.each do |issue|
249 249 issue.reload
250 250 if @copy
251 251 issue = issue.copy
252 252 end
253 253 journal = issue.init_journal(User.current, params[:notes])
254 254 issue.safe_attributes = attributes
255 255 call_hook(:controller_issues_bulk_edit_before_save, { :params => params, :issue => issue })
256 256 if issue.save
257 257 moved_issues << issue
258 258 else
259 259 # Keep unsaved issue ids to display them in flash error
260 260 unsaved_issue_ids << issue.id
261 261 end
262 262 end
263 263 set_flash_from_bulk_issue_save(@issues, unsaved_issue_ids)
264 264
265 265 if params[:follow]
266 266 if @issues.size == 1 && moved_issues.size == 1
267 267 redirect_to :controller => 'issues', :action => 'show', :id => moved_issues.first
268 268 elsif moved_issues.map(&:project).uniq.size == 1
269 269 redirect_to :controller => 'issues', :action => 'index', :project_id => moved_issues.map(&:project).first
270 270 end
271 271 else
272 272 redirect_back_or_default({:controller => 'issues', :action => 'index', :project_id => @project})
273 273 end
274 274 end
275 275
276 276 verify :method => :delete, :only => :destroy, :render => { :nothing => true, :status => :method_not_allowed }
277 277 def destroy
278 278 @hours = TimeEntry.sum(:hours, :conditions => ['issue_id IN (?)', @issues]).to_f
279 279 if @hours > 0
280 280 case params[:todo]
281 281 when 'destroy'
282 282 # nothing to do
283 283 when 'nullify'
284 284 TimeEntry.update_all('issue_id = NULL', ['issue_id IN (?)', @issues])
285 285 when 'reassign'
286 286 reassign_to = @project.issues.find_by_id(params[:reassign_to_id])
287 287 if reassign_to.nil?
288 288 flash.now[:error] = l(:error_issue_not_found_in_project)
289 289 return
290 290 else
291 291 TimeEntry.update_all("issue_id = #{reassign_to.id}", ['issue_id IN (?)', @issues])
292 292 end
293 293 else
294 294 # display the destroy form if it's a user request
295 295 return unless api_request?
296 296 end
297 297 end
298 298 @issues.each do |issue|
299 299 begin
300 300 issue.reload.destroy
301 301 rescue ::ActiveRecord::RecordNotFound # raised by #reload if issue no longer exists
302 302 # nothing to do, issue was already deleted (eg. by a parent)
303 303 end
304 304 end
305 305 respond_to do |format|
306 306 format.html { redirect_back_or_default(:action => 'index', :project_id => @project) }
307 307 format.api { head :ok }
308 308 end
309 309 end
310 310
311 311 private
312 312 def find_issue
313 313 # Issue.visible.find(...) can not be used to redirect user to the login form
314 314 # if the issue actually exists but requires authentication
315 315 @issue = Issue.find(params[:id], :include => [:project, :tracker, :status, :author, :priority, :category])
316 316 unless @issue.visible?
317 317 deny_access
318 318 return
319 319 end
320 320 @project = @issue.project
321 321 rescue ActiveRecord::RecordNotFound
322 322 render_404
323 323 end
324 324
325 325 def find_project
326 326 project_id = params[:project_id] || (params[:issue] && params[:issue][:project_id])
327 327 @project = Project.find(project_id)
328 328 rescue ActiveRecord::RecordNotFound
329 329 render_404
330 330 end
331 331
332 332 def retrieve_previous_and_next_issue_ids
333 333 retrieve_query_from_session
334 334 if @query
335 335 sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
336 336 sort_update(@query.sortable_columns, 'issues_index_sort')
337 337 limit = 500
338 338 issue_ids = @query.issue_ids(:order => sort_clause, :limit => (limit + 1), :include => [:assigned_to, :tracker, :priority, :category, :fixed_version])
339 339 if (idx = issue_ids.index(@issue.id)) && idx < limit
340 340 if issue_ids.size < 500
341 341 @issue_position = idx + 1
342 342 @issue_count = issue_ids.size
343 343 end
344 344 @prev_issue_id = issue_ids[idx - 1] if idx > 0
345 345 @next_issue_id = issue_ids[idx + 1] if idx < (issue_ids.size - 1)
346 346 end
347 347 end
348 348 end
349 349
350 350 # Used by #edit and #update to set some common instance variables
351 351 # from the params
352 352 # TODO: Refactor, not everything in here is needed by #edit
353 353 def update_issue_from_params
354 354 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
355 355 @priorities = IssuePriority.active
356 356 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
357 357 @time_entry = TimeEntry.new(:issue => @issue, :project => @issue.project)
358 358 @time_entry.attributes = params[:time_entry]
359 359
360 360 @notes = params[:notes] || (params[:issue].present? ? params[:issue][:notes] : nil)
361 361 @issue.init_journal(User.current, @notes)
362 362
363 363 issue_attributes = params[:issue]
364 364 if issue_attributes && params[:conflict_resolution]
365 365 case params[:conflict_resolution]
366 366 when 'overwrite'
367 367 issue_attributes = issue_attributes.dup
368 368 issue_attributes.delete(:lock_version)
369 369 when 'add_notes'
370 370 issue_attributes = {}
371 371 when 'cancel'
372 372 redirect_to issue_path(@issue)
373 373 return false
374 374 end
375 375 end
376 376 @issue.safe_attributes = issue_attributes
377 377 true
378 378 end
379 379
380 380 # TODO: Refactor, lots of extra code in here
381 381 # TODO: Changing tracker on an existing issue should not trigger this
382 382 def build_new_issue_from_params
383 383 if params[:id].blank?
384 384 @issue = Issue.new
385 385 if params[:copy_from]
386 386 begin
387 387 @copy_from = Issue.visible.find(params[:copy_from])
388 388 @copy_attachments = params[:copy_attachments].present? || request.get?
389 389 @issue.copy_from(@copy_from, :attachments => @copy_attachments)
390 390 rescue ActiveRecord::RecordNotFound
391 391 render_404
392 392 return
393 393 end
394 394 end
395 395 @issue.project = @project
396 396 else
397 397 @issue = @project.issues.visible.find(params[:id])
398 398 end
399 399
400 400 @issue.project = @project
401 401 @issue.author = User.current
402 402 # Tracker must be set before custom field values
403 403 @issue.tracker ||= @project.trackers.find((params[:issue] && params[:issue][:tracker_id]) || params[:tracker_id] || :first)
404 404 if @issue.tracker.nil?
405 405 render_error l(:error_no_tracker_in_project)
406 406 return false
407 407 end
408 408 @issue.start_date ||= Date.today if Setting.default_issue_start_date_to_creation_date?
409 409 @issue.safe_attributes = params[:issue]
410 410
411 411 @priorities = IssuePriority.active
412 412 @allowed_statuses = @issue.new_statuses_allowed_to(User.current, true)
413 413 end
414 414
415 415 def check_for_default_issue_status
416 416 if IssueStatus.default.nil?
417 417 render_error l(:error_no_default_issue_status)
418 418 return false
419 419 end
420 420 end
421 421
422 422 def parse_params_for_bulk_issue_attributes(params)
423 423 attributes = (params[:issue] || {}).reject {|k,v| v.blank?}
424 424 attributes.keys.each {|k| attributes[k] = '' if attributes[k] == 'none'}
425 425 attributes[:custom_field_values].reject! {|k,v| v.blank?} if attributes[:custom_field_values]
426 426 attributes
427 427 end
428 428 end
@@ -1,221 +1,221
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2012 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_custom_field
31 31 before_validation :set_searchable
32 32
33 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 # make sure only these fields can have multiple values
42 42 self.multiple = false unless %w(list user version).include?(field_format)
43 43 true
44 44 end
45 45
46 46 def validate_custom_field
47 47 if self.field_format == "list"
48 48 errors.add(:possible_values, :blank) if self.possible_values.nil? || self.possible_values.empty?
49 49 errors.add(:possible_values, :invalid) unless self.possible_values.is_a? Array
50 50 end
51 51
52 52 if regexp.present?
53 53 begin
54 54 Regexp.new(regexp)
55 55 rescue
56 56 errors.add(:regexp, :invalid)
57 57 end
58 58 end
59 59
60 60 if default_value.present? && !valid_field_value?(default_value)
61 61 errors.add(:default_value, :invalid)
62 62 end
63 63 end
64 64
65 65 def possible_values_options(obj=nil)
66 66 case field_format
67 67 when 'user', 'version'
68 68 if obj.respond_to?(:project) && obj.project
69 69 case field_format
70 70 when 'user'
71 71 obj.project.users.sort.collect {|u| [u.to_s, u.id.to_s]}
72 72 when 'version'
73 73 obj.project.shared_versions.sort.collect {|u| [u.to_s, u.id.to_s]}
74 74 end
75 75 elsif obj.is_a?(Array)
76 obj.collect {|o| possible_values_options(o)}.inject {|memo, v| memo & v}
76 obj.collect {|o| possible_values_options(o)}.reduce(:&)
77 77 else
78 78 []
79 79 end
80 80 when 'bool'
81 81 [[l(:general_text_Yes), '1'], [l(:general_text_No), '0']]
82 82 else
83 83 read_attribute(:possible_values) || []
84 84 end
85 85 end
86 86
87 87 def possible_values(obj=nil)
88 88 case field_format
89 89 when 'user', 'version'
90 90 possible_values_options(obj).collect(&:last)
91 91 when 'bool'
92 92 ['1', '0']
93 93 else
94 94 read_attribute :possible_values
95 95 end
96 96 end
97 97
98 98 # Makes possible_values accept a multiline string
99 99 def possible_values=(arg)
100 100 if arg.is_a?(Array)
101 101 write_attribute(:possible_values, arg.compact.collect(&:strip).select {|v| !v.blank?})
102 102 else
103 103 self.possible_values = arg.to_s.split(/[\n\r]+/)
104 104 end
105 105 end
106 106
107 107 def cast_value(value)
108 108 casted = nil
109 109 unless value.blank?
110 110 case field_format
111 111 when 'string', 'text', 'list'
112 112 casted = value
113 113 when 'date'
114 114 casted = begin; value.to_date; rescue; nil end
115 115 when 'bool'
116 116 casted = (value == '1' ? true : false)
117 117 when 'int'
118 118 casted = value.to_i
119 119 when 'float'
120 120 casted = value.to_f
121 121 when 'user', 'version'
122 122 casted = (value.blank? ? nil : field_format.classify.constantize.find_by_id(value.to_i))
123 123 end
124 124 end
125 125 casted
126 126 end
127 127
128 128 # Returns a ORDER BY clause that can used to sort customized
129 129 # objects by their value of the custom field.
130 130 # Returns false, if the custom field can not be used for sorting.
131 131 def order_statement
132 132 return nil if multiple?
133 133 case field_format
134 134 when 'string', 'text', 'list', 'date', 'bool'
135 135 # COALESCE is here to make sure that blank and NULL values are sorted equally
136 136 "COALESCE((SELECT cv_sort.value FROM #{CustomValue.table_name} cv_sort" +
137 137 " WHERE cv_sort.customized_type='#{self.class.customized_class.name}'" +
138 138 " AND cv_sort.customized_id=#{self.class.customized_class.table_name}.id" +
139 139 " AND cv_sort.custom_field_id=#{id} LIMIT 1), '')"
140 140 when 'int', 'float'
141 141 # Make the database cast values into numeric
142 142 # Postgresql will raise an error if a value can not be casted!
143 143 # CustomValue validations should ensure that it doesn't occur
144 144 "(SELECT CAST(cv_sort.value AS decimal(60,3)) FROM #{CustomValue.table_name} cv_sort" +
145 145 " WHERE cv_sort.customized_type='#{self.class.customized_class.name}'" +
146 146 " AND cv_sort.customized_id=#{self.class.customized_class.table_name}.id" +
147 147 " AND cv_sort.custom_field_id=#{id} AND cv_sort.value <> '' AND cv_sort.value IS NOT NULL LIMIT 1)"
148 148 else
149 149 nil
150 150 end
151 151 end
152 152
153 153 def <=>(field)
154 154 position <=> field.position
155 155 end
156 156
157 157 def self.customized_class
158 158 self.name =~ /^(.+)CustomField$/
159 159 begin; $1.constantize; rescue nil; end
160 160 end
161 161
162 162 # to move in project_custom_field
163 163 def self.for_all
164 164 find(:all, :conditions => ["is_for_all=?", true], :order => 'position')
165 165 end
166 166
167 167 def type_name
168 168 nil
169 169 end
170 170
171 171 # Returns the error messages for the given value
172 172 # or an empty array if value is a valid value for the custom field
173 173 def validate_field_value(value)
174 174 errs = []
175 175 if value.is_a?(Array)
176 176 if !multiple?
177 177 errs << ::I18n.t('activerecord.errors.messages.invalid')
178 178 end
179 179 if is_required? && value.detect(&:present?).nil?
180 180 errs << ::I18n.t('activerecord.errors.messages.blank')
181 181 end
182 182 value.each {|v| errs += validate_field_value_format(v)}
183 183 else
184 184 if is_required? && value.blank?
185 185 errs << ::I18n.t('activerecord.errors.messages.blank')
186 186 end
187 187 errs += validate_field_value_format(value)
188 188 end
189 189 errs
190 190 end
191 191
192 192 # Returns true if value is a valid value for the custom field
193 193 def valid_field_value?(value)
194 194 validate_field_value(value).empty?
195 195 end
196 196
197 197 protected
198 198
199 199 # Returns the error message for the given value regarding its format
200 200 def validate_field_value_format(value)
201 201 errs = []
202 202 if value.present?
203 203 errs << ::I18n.t('activerecord.errors.messages.invalid') unless regexp.blank? or value =~ Regexp.new(regexp)
204 204 errs << ::I18n.t('activerecord.errors.messages.too_short', :count => min_length) if min_length > 0 and value.length < min_length
205 205 errs << ::I18n.t('activerecord.errors.messages.too_long', :count => max_length) if max_length > 0 and value.length > max_length
206 206
207 207 # Format specific validations
208 208 case field_format
209 209 when 'int'
210 210 errs << ::I18n.t('activerecord.errors.messages.not_a_number') unless value =~ /^[+-]?\d+$/
211 211 when 'float'
212 212 begin; Kernel.Float(value); rescue; errs << ::I18n.t('activerecord.errors.messages.invalid') end
213 213 when 'date'
214 214 errs << ::I18n.t('activerecord.errors.messages.not_a_date') unless value =~ /^\d{4}-\d{2}-\d{2}$/ && begin; value.to_date; rescue; false end
215 215 when 'list'
216 216 errs << ::I18n.t('activerecord.errors.messages.inclusion') unless possible_values.include?(value)
217 217 end
218 218 end
219 219 errs
220 220 end
221 221 end
General Comments 0
You need to be logged in to leave comments. Login now